--- a/server/python/django/renkanmanager/static/renkanmanager/lib/FileSaver.js Fri Apr 24 13:05:09 2015 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,253 +0,0 @@
-/*! FileSaver.js
- * A saveAs() FileSaver implementation.
- * 2014-01-24
- *
- * By Eli Grey, http://eligrey.com
- * License: X11/MIT
- * See LICENSE.md
- */
-
-/*global self */
-/*jslint bitwise: true, indent: 4, laxbreak: true, laxcomma: true, smarttabs: true, plusplus: true */
-
-/*! @source http://purl.eligrey.com/github/FileSaver.js/blob/master/FileSaver.js */
-
-var saveAs = saveAs
- // IE 10+ (native saveAs)
- || (typeof navigator !== "undefined" &&
- navigator.msSaveOrOpenBlob && navigator.msSaveOrOpenBlob.bind(navigator))
- // Everyone else
- || (function(view) {
- "use strict";
- // IE <10 is explicitly unsupported
- if (typeof navigator !== "undefined" &&
- /MSIE [1-9]\./.test(navigator.userAgent)) {
- return;
- }
- var
- doc = view.document
- // only get URL when necessary in case BlobBuilder.js hasn't overridden it yet
- , get_URL = function() {
- return view.URL || view.webkitURL || view;
- }
- , URL = view.URL || view.webkitURL || view
- , save_link = doc.createElementNS("http://www.w3.org/1999/xhtml", "a")
- , can_use_save_link = !view.externalHost && "download" in save_link
- , click = function(node) {
- var event = doc.createEvent("MouseEvents");
- event.initMouseEvent(
- "click", true, false, view, 0, 0, 0, 0, 0
- , false, false, false, false, 0, null
- );
- node.dispatchEvent(event);
- }
- , webkit_req_fs = view.webkitRequestFileSystem
- , req_fs = view.requestFileSystem || webkit_req_fs || view.mozRequestFileSystem
- , throw_outside = function(ex) {
- (view.setImmediate || view.setTimeout)(function() {
- throw ex;
- }, 0);
- }
- , force_saveable_type = "application/octet-stream"
- , fs_min_size = 0
- , deletion_queue = []
- , process_deletion_queue = function() {
- var i = deletion_queue.length;
- while (i--) {
- var file = deletion_queue[i];
- if (typeof file === "string") { // file is an object URL
- URL.revokeObjectURL(file);
- } else { // file is a File
- file.remove();
- }
- }
- deletion_queue.length = 0; // clear queue
- }
- , dispatch = function(filesaver, event_types, event) {
- event_types = [].concat(event_types);
- var i = event_types.length;
- while (i--) {
- var listener = filesaver["on" + event_types[i]];
- if (typeof listener === "function") {
- try {
- listener.call(filesaver, event || filesaver);
- } catch (ex) {
- throw_outside(ex);
- }
- }
- }
- }
- , FileSaver = function(blob, name) {
- // First try a.download, then web filesystem, then object URLs
- var
- filesaver = this
- , type = blob.type
- , blob_changed = false
- , object_url
- , target_view
- , get_object_url = function() {
- var object_url = get_URL().createObjectURL(blob);
- deletion_queue.push(object_url);
- return object_url;
- }
- , dispatch_all = function() {
- dispatch(filesaver, "writestart progress write writeend".split(" "));
- }
- // on any filesys errors revert to saving with object URLs
- , fs_error = function() {
- // don't create more object URLs than needed
- if (blob_changed || !object_url) {
- object_url = get_object_url(blob);
- }
- if (target_view) {
- target_view.location.href = object_url;
- } else {
- window.open(object_url, "_blank");
- }
- filesaver.readyState = filesaver.DONE;
- dispatch_all();
- }
- , abortable = function(func) {
- return function() {
- if (filesaver.readyState !== filesaver.DONE) {
- return func.apply(this, arguments);
- }
- };
- }
- , create_if_not_found = {create: true, exclusive: false}
- , slice
- ;
- filesaver.readyState = filesaver.INIT;
- if (!name) {
- name = "download";
- }
- if (can_use_save_link) {
- object_url = get_object_url(blob);
- // FF for Android has a nasty garbage collection mechanism
- // that turns all objects that are not pure javascript into 'deadObject'
- // this means `doc` and `save_link` are unusable and need to be recreated
- // `view` is usable though:
- doc = view.document;
- save_link = doc.createElementNS("http://www.w3.org/1999/xhtml", "a");
- save_link.href = object_url;
- save_link.download = name;
- var event = doc.createEvent("MouseEvents");
- event.initMouseEvent(
- "click", true, false, view, 0, 0, 0, 0, 0
- , false, false, false, false, 0, null
- );
- save_link.dispatchEvent(event);
- filesaver.readyState = filesaver.DONE;
- dispatch_all();
- return;
- }
- // Object and web filesystem URLs have a problem saving in Google Chrome when
- // viewed in a tab, so I force save with application/octet-stream
- // http://code.google.com/p/chromium/issues/detail?id=91158
- if (view.chrome && type && type !== force_saveable_type) {
- slice = blob.slice || blob.webkitSlice;
- blob = slice.call(blob, 0, blob.size, force_saveable_type);
- blob_changed = true;
- }
- // Since I can't be sure that the guessed media type will trigger a download
- // in WebKit, I append .download to the filename.
- // https://bugs.webkit.org/show_bug.cgi?id=65440
- if (webkit_req_fs && name !== "download") {
- name += ".download";
- }
- if (type === force_saveable_type || webkit_req_fs) {
- target_view = view;
- }
- if (!req_fs) {
- fs_error();
- return;
- }
- fs_min_size += blob.size;
- req_fs(view.TEMPORARY, fs_min_size, abortable(function(fs) {
- fs.root.getDirectory("saved", create_if_not_found, abortable(function(dir) {
- var save = function() {
- dir.getFile(name, create_if_not_found, abortable(function(file) {
- file.createWriter(abortable(function(writer) {
- writer.onwriteend = function(event) {
- target_view.location.href = file.toURL();
- deletion_queue.push(file);
- filesaver.readyState = filesaver.DONE;
- dispatch(filesaver, "writeend", event);
- };
- writer.onerror = function() {
- var error = writer.error;
- if (error.code !== error.ABORT_ERR) {
- fs_error();
- }
- };
- "writestart progress write abort".split(" ").forEach(function(event) {
- writer["on" + event] = filesaver["on" + event];
- });
- writer.write(blob);
- filesaver.abort = function() {
- writer.abort();
- filesaver.readyState = filesaver.DONE;
- };
- filesaver.readyState = filesaver.WRITING;
- }), fs_error);
- }), fs_error);
- };
- dir.getFile(name, {create: false}, abortable(function(file) {
- // delete file if it already exists
- file.remove();
- save();
- }), abortable(function(ex) {
- if (ex.code === ex.NOT_FOUND_ERR) {
- save();
- } else {
- fs_error();
- }
- }));
- }), fs_error);
- }), fs_error);
- }
- , FS_proto = FileSaver.prototype
- , saveAs = function(blob, name) {
- return new FileSaver(blob, name);
- }
- ;
- FS_proto.abort = function() {
- var filesaver = this;
- filesaver.readyState = filesaver.DONE;
- dispatch(filesaver, "abort");
- };
- FS_proto.readyState = FS_proto.INIT = 0;
- FS_proto.WRITING = 1;
- FS_proto.DONE = 2;
-
- FS_proto.error =
- FS_proto.onwritestart =
- FS_proto.onprogress =
- FS_proto.onwrite =
- FS_proto.onabort =
- FS_proto.onerror =
- FS_proto.onwriteend =
- null;
-
- view.addEventListener("unload", process_deletion_queue, false);
- saveAs.unload = function() {
- process_deletion_queue();
- view.removeEventListener("unload", process_deletion_queue, false);
- };
- return saveAs;
-}(
- typeof self !== "undefined" && self
- || typeof window !== "undefined" && window
- || this.content
-));
-// `self` is undefined in Firefox for Android content script context
-// while `this` is nsIContentFrameMessageManager
-// with an attribute `content` that corresponds to the window
-
-if (typeof module !== "undefined" && module !== null) {
- module.exports = saveAs;
-} else if ((typeof define !== "undefined" && define !== null) && (define.amd != null)) {
- define([], function() {
- return saveAs;
- });
-}
--- a/server/python/django/renkanmanager/static/renkanmanager/lib/backbone-relational.js Fri Apr 24 13:05:09 2015 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,1860 +0,0 @@
-/* vim: set tabstop=4 softtabstop=4 shiftwidth=4 noexpandtab: */
-/**
- * Backbone-relational.js 0.8.5
- * (c) 2011-2013 Paul Uithol and contributors (https://github.com/PaulUithol/Backbone-relational/graphs/contributors)
- *
- * Backbone-relational may be freely distributed under the MIT license; see the accompanying LICENSE.txt.
- * For details and documentation: https://github.com/PaulUithol/Backbone-relational.
- * Depends on Backbone (and thus on Underscore as well): https://github.com/documentcloud/backbone.
- */
-( function( undefined ) {
- "use strict";
-
- /**
- * CommonJS shim
- **/
- var _, Backbone, exports;
- if ( typeof window === 'undefined' ) {
- _ = require( 'underscore' );
- Backbone = require( 'backbone' );
- exports = module.exports = Backbone;
- }
- else {
- _ = window._;
- Backbone = window.Backbone;
- exports = window;
- }
-
- Backbone.Relational = {
- showWarnings: true
- };
-
- /**
- * Semaphore mixin; can be used as both binary and counting.
- **/
- Backbone.Semaphore = {
- _permitsAvailable: null,
- _permitsUsed: 0,
-
- acquire: function() {
- if ( this._permitsAvailable && this._permitsUsed >= this._permitsAvailable ) {
- throw new Error( 'Max permits acquired' );
- }
- else {
- this._permitsUsed++;
- }
- },
-
- release: function() {
- if ( this._permitsUsed === 0 ) {
- throw new Error( 'All permits released' );
- }
- else {
- this._permitsUsed--;
- }
- },
-
- isLocked: function() {
- return this._permitsUsed > 0;
- },
-
- setAvailablePermits: function( amount ) {
- if ( this._permitsUsed > amount ) {
- throw new Error( 'Available permits cannot be less than used permits' );
- }
- this._permitsAvailable = amount;
- }
- };
-
- /**
- * A BlockingQueue that accumulates items while blocked (via 'block'),
- * and processes them when unblocked (via 'unblock').
- * Process can also be called manually (via 'process').
- */
- Backbone.BlockingQueue = function() {
- this._queue = [];
- };
- _.extend( Backbone.BlockingQueue.prototype, Backbone.Semaphore, {
- _queue: null,
-
- add: function( func ) {
- if ( this.isBlocked() ) {
- this._queue.push( func );
- }
- else {
- func();
- }
- },
-
- process: function() {
- while ( this._queue && this._queue.length ) {
- this._queue.shift()();
- }
- },
-
- block: function() {
- this.acquire();
- },
-
- unblock: function() {
- this.release();
- if ( !this.isBlocked() ) {
- this.process();
- }
- },
-
- isBlocked: function() {
- return this.isLocked();
- }
- });
- /**
- * Global event queue. Accumulates external events ('add:<key>', 'remove:<key>' and 'change:<key>')
- * until the top-level object is fully initialized (see 'Backbone.RelationalModel').
- */
- Backbone.Relational.eventQueue = new Backbone.BlockingQueue();
-
- /**
- * Backbone.Store keeps track of all created (and destruction of) Backbone.RelationalModel.
- * Handles lookup for relations.
- */
- Backbone.Store = function() {
- this._collections = [];
- this._reverseRelations = [];
- this._orphanRelations = [];
- this._subModels = [];
- this._modelScopes = [ exports ];
- };
- _.extend( Backbone.Store.prototype, Backbone.Events, {
- /**
- * Create a new `Relation`.
- * @param {Backbone.RelationalModel} [model]
- * @param {Object} relation
- * @param {Object} [options]
- */
- initializeRelation: function( model, relation, options ) {
- var type = !_.isString( relation.type ) ? relation.type : Backbone[ relation.type ] || this.getObjectByName( relation.type );
- if ( type && type.prototype instanceof Backbone.Relation ) {
- new type( model, relation, options ); // Also pushes the new Relation into `model._relations`
- }
- else {
- Backbone.Relational.showWarnings && typeof console !== 'undefined' && console.warn( 'Relation=%o; missing or invalid relation type!', relation );
- }
- },
-
- /**
- * Add a scope for `getObjectByName` to look for model types by name.
- * @param {Object} scope
- */
- addModelScope: function( scope ) {
- this._modelScopes.push( scope );
- },
-
- /**
- * Remove a scope.
- * @param {Object} scope
- */
- removeModelScope: function( scope ) {
- this._modelScopes = _.without( this._modelScopes, scope );
- },
-
- /**
- * Add a set of subModelTypes to the store, that can be used to resolve the '_superModel'
- * for a model later in 'setupSuperModel'.
- *
- * @param {Backbone.RelationalModel} subModelTypes
- * @param {Backbone.RelationalModel} superModelType
- */
- addSubModels: function( subModelTypes, superModelType ) {
- this._subModels.push({
- 'superModelType': superModelType,
- 'subModels': subModelTypes
- });
- },
-
- /**
- * Check if the given modelType is registered as another model's subModel. If so, add it to the super model's
- * '_subModels', and set the modelType's '_superModel', '_subModelTypeName', and '_subModelTypeAttribute'.
- *
- * @param {Backbone.RelationalModel} modelType
- */
- setupSuperModel: function( modelType ) {
- _.find( this._subModels, function( subModelDef ) {
- return _.find( subModelDef.subModels || [], function( subModelTypeName, typeValue ) {
- var subModelType = this.getObjectByName( subModelTypeName );
-
- if ( modelType === subModelType ) {
- // Set 'modelType' as a child of the found superModel
- subModelDef.superModelType._subModels[ typeValue ] = modelType;
-
- // Set '_superModel', '_subModelTypeValue', and '_subModelTypeAttribute' on 'modelType'.
- modelType._superModel = subModelDef.superModelType;
- modelType._subModelTypeValue = typeValue;
- modelType._subModelTypeAttribute = subModelDef.superModelType.prototype.subModelTypeAttribute;
- return true;
- }
- }, this );
- }, this );
- },
-
- /**
- * Add a reverse relation. Is added to the 'relations' property on model's prototype, and to
- * existing instances of 'model' in the store as well.
- * @param {Object} relation
- * @param {Backbone.RelationalModel} relation.model
- * @param {String} relation.type
- * @param {String} relation.key
- * @param {String|Object} relation.relatedModel
- */
- addReverseRelation: function( relation ) {
- var exists = _.any( this._reverseRelations, function( rel ) {
- return _.all( relation || [], function( val, key ) {
- return val === rel[ key ];
- });
- });
-
- if ( !exists && relation.model && relation.type ) {
- this._reverseRelations.push( relation );
- this._addRelation( relation.model, relation );
- this.retroFitRelation( relation );
- }
- },
-
- /**
- * Deposit a `relation` for which the `relatedModel` can't be resolved at the moment.
- *
- * @param {Object} relation
- */
- addOrphanRelation: function( relation ) {
- var exists = _.any( this._orphanRelations, function( rel ) {
- return _.all( relation || [], function( val, key ) {
- return val === rel[ key ];
- });
- });
-
- if ( !exists && relation.model && relation.type ) {
- this._orphanRelations.push( relation );
- }
- },
-
- /**
- * Try to initialize any `_orphanRelation`s
- */
- processOrphanRelations: function() {
- // Make sure to operate on a copy since we're removing while iterating
- _.each( this._orphanRelations.slice( 0 ), function( rel ) {
- var relatedModel = Backbone.Relational.store.getObjectByName( rel.relatedModel );
- if ( relatedModel ) {
- this.initializeRelation( null, rel );
- this._orphanRelations = _.without( this._orphanRelations, rel );
- }
- }, this );
- },
-
- /**
- *
- * @param {Backbone.RelationalModel.constructor} type
- * @param {Object} relation
- * @private
- */
- _addRelation: function( type, relation ) {
- if ( !type.prototype.relations ) {
- type.prototype.relations = [];
- }
- type.prototype.relations.push( relation );
-
- _.each( type._subModels || [], function( subModel ) {
- this._addRelation( subModel, relation );
- }, this );
- },
-
- /**
- * Add a 'relation' to all existing instances of 'relation.model' in the store
- * @param {Object} relation
- */
- retroFitRelation: function( relation ) {
- var coll = this.getCollection( relation.model, false );
- coll && coll.each( function( model ) {
- if ( !( model instanceof relation.model ) ) {
- return;
- }
-
- new relation.type( model, relation );
- }, this );
- },
-
- /**
- * Find the Store's collection for a certain type of model.
- * @param {Backbone.RelationalModel} type
- * @param {Boolean} [create=true] Should a collection be created if none is found?
- * @return {Backbone.Collection} A collection if found (or applicable for 'model'), or null
- */
- getCollection: function( type, create ) {
- if ( type instanceof Backbone.RelationalModel ) {
- type = type.constructor;
- }
-
- var rootModel = type;
- while ( rootModel._superModel ) {
- rootModel = rootModel._superModel;
- }
-
- var coll = _.findWhere( this._collections, { model: rootModel } );
-
- if ( !coll && create !== false ) {
- coll = this._createCollection( rootModel );
- }
-
- return coll;
- },
-
- /**
- * Find a model type on one of the modelScopes by name. Names are split on dots.
- * @param {String} name
- * @return {Object}
- */
- getObjectByName: function( name ) {
- var parts = name.split( '.' ),
- type = null;
-
- _.find( this._modelScopes, function( scope ) {
- type = _.reduce( parts || [], function( memo, val ) {
- return memo ? memo[ val ] : undefined;
- }, scope );
-
- if ( type && type !== scope ) {
- return true;
- }
- }, this );
-
- return type;
- },
-
- _createCollection: function( type ) {
- var coll;
-
- // If 'type' is an instance, take its constructor
- if ( type instanceof Backbone.RelationalModel ) {
- type = type.constructor;
- }
-
- // Type should inherit from Backbone.RelationalModel.
- if ( type.prototype instanceof Backbone.RelationalModel ) {
- coll = new Backbone.Collection();
- coll.model = type;
-
- this._collections.push( coll );
- }
-
- return coll;
- },
-
- /**
- * Find the attribute that is to be used as the `id` on a given object
- * @param type
- * @param {String|Number|Object|Backbone.RelationalModel} item
- * @return {String|Number}
- */
- resolveIdForItem: function( type, item ) {
- var id = _.isString( item ) || _.isNumber( item ) ? item : null;
-
- if ( id === null ) {
- if ( item instanceof Backbone.RelationalModel ) {
- id = item.id;
- }
- else if ( _.isObject( item ) ) {
- id = item[ type.prototype.idAttribute ];
- }
- }
-
- // Make all falsy values `null` (except for 0, which could be an id.. see '/issues/179')
- if ( !id && id !== 0 ) {
- id = null;
- }
-
- return id;
- },
-
- /**
- * Find a specific model of a certain `type` in the store
- * @param type
- * @param {String|Number|Object|Backbone.RelationalModel} item
- */
- find: function( type, item ) {
- var id = this.resolveIdForItem( type, item );
- var coll = this.getCollection( type );
-
- // Because the found object could be of any of the type's superModel
- // types, only return it if it's actually of the type asked for.
- if ( coll ) {
- var obj = coll.get( id );
-
- if ( obj instanceof type ) {
- return obj;
- }
- }
-
- return null;
- },
-
- /**
- * Add a 'model' to its appropriate collection. Retain the original contents of 'model.collection'.
- * @param {Backbone.RelationalModel} model
- */
- register: function( model ) {
- var coll = this.getCollection( model );
-
- if ( coll ) {
- var modelColl = model.collection;
- coll.add( model );
- this.listenTo( model, 'destroy', this.unregister, this );
- model.collection = modelColl;
- }
- },
-
- /**
- * Check if the given model may use the given `id`
- * @param model
- * @param [id]
- */
- checkId: function( model, id ) {
- var coll = this.getCollection( model ),
- duplicate = coll && coll.get( id );
-
- if ( duplicate && model !== duplicate ) {
- if ( Backbone.Relational.showWarnings && typeof console !== 'undefined' ) {
- console.warn( 'Duplicate id! Old RelationalModel=%o, new RelationalModel=%o', duplicate, model );
- }
-
- throw new Error( "Cannot instantiate more than one Backbone.RelationalModel with the same id per type!" );
- }
- },
-
- /**
- * Explicitly update a model's id in its store collection
- * @param {Backbone.RelationalModel} model
- */
- update: function( model ) {
- var coll = this.getCollection( model );
- // This triggers updating the lookup indices kept in a collection
- coll._onModelEvent( 'change:' + model.idAttribute, model, coll );
-
- // Trigger an event on model so related models (having the model's new id in their keyContents) can add it.
- model.trigger( 'relational:change:id', model, coll );
- },
-
- /**
- * Remove a 'model' from the store.
- * @param {Backbone.RelationalModel} model
- */
- unregister: function( model ) {
- this.stopListening( model, 'destroy', this.unregister );
- var coll = this.getCollection( model );
- coll && coll.remove( model );
- },
-
- /**
- * Reset the `store` to it's original state. The `reverseRelations` are kept though, since attempting to
- * re-initialize these on models would lead to a large amount of warnings.
- */
- reset: function() {
- this.stopListening();
- this._collections = [];
- this._subModels = [];
- this._modelScopes = [ exports ];
- }
- });
- Backbone.Relational.store = new Backbone.Store();
-
- /**
- * The main Relation class, from which 'HasOne' and 'HasMany' inherit. Internally, 'relational:<key>' events
- * are used to regulate addition and removal of models from relations.
- *
- * @param {Backbone.RelationalModel} [instance] Model that this relation is created for. If no model is supplied,
- * Relation just tries to instantiate it's `reverseRelation` if specified, and bails out after that.
- * @param {Object} options
- * @param {string} options.key
- * @param {Backbone.RelationalModel.constructor} options.relatedModel
- * @param {Boolean|String} [options.includeInJSON=true] Serialize the given attribute for related model(s)' in toJSON, or just their ids.
- * @param {Boolean} [options.createModels=true] Create objects from the contents of keys if the object is not found in Backbone.store.
- * @param {Object} [options.reverseRelation] Specify a bi-directional relation. If provided, Relation will reciprocate
- * the relation to the 'relatedModel'. Required and optional properties match 'options', except that it also needs
- * {Backbone.Relation|String} type ('HasOne' or 'HasMany').
- * @param {Object} opts
- */
- Backbone.Relation = function( instance, options, opts ) {
- this.instance = instance;
- // Make sure 'options' is sane, and fill with defaults from subclasses and this object's prototype
- options = _.isObject( options ) ? options : {};
- this.reverseRelation = _.defaults( options.reverseRelation || {}, this.options.reverseRelation );
- this.options = _.defaults( options, this.options, Backbone.Relation.prototype.options );
-
- this.reverseRelation.type = !_.isString( this.reverseRelation.type ) ? this.reverseRelation.type :
- Backbone[ this.reverseRelation.type ] || Backbone.Relational.store.getObjectByName( this.reverseRelation.type );
-
- this.key = this.options.key;
- this.keySource = this.options.keySource || this.key;
- this.keyDestination = this.options.keyDestination || this.keySource || this.key;
-
- this.model = this.options.model || this.instance.constructor;
- this.relatedModel = this.options.relatedModel;
- if ( _.isString( this.relatedModel ) ) {
- this.relatedModel = Backbone.Relational.store.getObjectByName( this.relatedModel );
- }
-
- if ( !this.checkPreconditions() ) {
- return;
- }
-
- // Add the reverse relation on 'relatedModel' to the store's reverseRelations
- if ( !this.options.isAutoRelation && this.reverseRelation.type && this.reverseRelation.key ) {
- Backbone.Relational.store.addReverseRelation( _.defaults( {
- isAutoRelation: true,
- model: this.relatedModel,
- relatedModel: this.model,
- reverseRelation: this.options // current relation is the 'reverseRelation' for its own reverseRelation
- },
- this.reverseRelation // Take further properties from this.reverseRelation (type, key, etc.)
- ) );
- }
-
- if ( instance ) {
- var contentKey = this.keySource;
- if ( contentKey !== this.key && typeof this.instance.get( this.key ) === 'object' ) {
- contentKey = this.key;
- }
-
- this.setKeyContents( this.instance.get( contentKey ) );
- this.relatedCollection = Backbone.Relational.store.getCollection( this.relatedModel );
-
- // Explicitly clear 'keySource', to prevent a leaky abstraction if 'keySource' differs from 'key'.
- if ( this.keySource !== this.key ) {
- this.instance.unset( this.keySource, { silent: true } );
- }
-
- // Add this Relation to instance._relations
- this.instance._relations[ this.key ] = this;
-
- this.initialize( opts );
-
- if ( this.options.autoFetch ) {
- this.instance.fetchRelated( this.key, _.isObject( this.options.autoFetch ) ? this.options.autoFetch : {} );
- }
-
- // When 'relatedModel' are created or destroyed, check if it affects this relation.
- this.listenTo( this.instance, 'destroy', this.destroy )
- .listenTo( this.relatedCollection, 'relational:add relational:change:id', this.tryAddRelated )
- .listenTo( this.relatedCollection, 'relational:remove', this.removeRelated )
- }
- };
- // Fix inheritance :\
- Backbone.Relation.extend = Backbone.Model.extend;
- // Set up all inheritable **Backbone.Relation** properties and methods.
- _.extend( Backbone.Relation.prototype, Backbone.Events, Backbone.Semaphore, {
- options: {
- createModels: true,
- includeInJSON: true,
- isAutoRelation: false,
- autoFetch: false,
- parse: false
- },
-
- instance: null,
- key: null,
- keyContents: null,
- relatedModel: null,
- relatedCollection: null,
- reverseRelation: null,
- related: null,
-
- /**
- * Check several pre-conditions.
- * @return {Boolean} True if pre-conditions are satisfied, false if they're not.
- */
- checkPreconditions: function() {
- var i = this.instance,
- k = this.key,
- m = this.model,
- rm = this.relatedModel,
- warn = Backbone.Relational.showWarnings && typeof console !== 'undefined';
-
- if ( !m || !k || !rm ) {
- warn && console.warn( 'Relation=%o: missing model, key or relatedModel (%o, %o, %o).', this, m, k, rm );
- return false;
- }
- // Check if the type in 'model' inherits from Backbone.RelationalModel
- if ( !( m.prototype instanceof Backbone.RelationalModel ) ) {
- warn && console.warn( 'Relation=%o: model does not inherit from Backbone.RelationalModel (%o).', this, i );
- return false;
- }
- // Check if the type in 'relatedModel' inherits from Backbone.RelationalModel
- if ( !( rm.prototype instanceof Backbone.RelationalModel ) ) {
- warn && console.warn( 'Relation=%o: relatedModel does not inherit from Backbone.RelationalModel (%o).', this, rm );
- return false;
- }
- // Check if this is not a HasMany, and the reverse relation is HasMany as well
- if ( this instanceof Backbone.HasMany && this.reverseRelation.type === Backbone.HasMany ) {
- warn && console.warn( 'Relation=%o: relation is a HasMany, and the reverseRelation is HasMany as well.', this );
- return false;
- }
- // Check if we're not attempting to create a relationship on a `key` that's already used.
- if ( i && _.keys( i._relations ).length ) {
- var existing = _.find( i._relations, function( rel ) {
- return rel.key === k;
- }, this );
-
- if ( existing ) {
- warn && console.warn( 'Cannot create relation=%o on %o for model=%o: already taken by relation=%o.',
- this, k, i, existing );
- return false;
- }
- }
-
- return true;
- },
-
- /**
- * Set the related model(s) for this relation
- * @param {Backbone.Model|Backbone.Collection} related
- */
- setRelated: function( related ) {
- this.related = related;
-
- this.instance.acquire();
- this.instance.attributes[ this.key ] = related;
- this.instance.release();
- },
-
- /**
- * Determine if a relation (on a different RelationalModel) is the reverse
- * relation of the current one.
- * @param {Backbone.Relation} relation
- * @return {Boolean}
- */
- _isReverseRelation: function( relation ) {
- return relation.instance instanceof this.relatedModel && this.reverseRelation.key === relation.key &&
- this.key === relation.reverseRelation.key;
- },
-
- /**
- * Get the reverse relations (pointing back to 'this.key' on 'this.instance') for the currently related model(s).
- * @param {Backbone.RelationalModel} [model] Get the reverse relations for a specific model.
- * If not specified, 'this.related' is used.
- * @return {Backbone.Relation[]}
- */
- getReverseRelations: function( model ) {
- var reverseRelations = [];
- // Iterate over 'model', 'this.related.models' (if this.related is a Backbone.Collection), or wrap 'this.related' in an array.
- var models = !_.isUndefined( model ) ? [ model ] : this.related && ( this.related.models || [ this.related ] );
- _.each( models || [], function( related ) {
- _.each( related.getRelations() || [], function( relation ) {
- if ( this._isReverseRelation( relation ) ) {
- reverseRelations.push( relation );
- }
- }, this );
- }, this );
-
- return reverseRelations;
- },
-
- /**
- * When `this.instance` is destroyed, cleanup our relations.
- * Get reverse relation, call removeRelated on each.
- */
- destroy: function() {
- this.stopListening();
-
- if ( this instanceof Backbone.HasOne ) {
- this.setRelated( null );
- }
- else if ( this instanceof Backbone.HasMany ) {
- this.setRelated( this._prepareCollection() );
- }
-
- _.each( this.getReverseRelations(), function( relation ) {
- relation.removeRelated( this.instance );
- }, this );
- }
- });
-
- Backbone.HasOne = Backbone.Relation.extend({
- options: {
- reverseRelation: { type: 'HasMany' }
- },
-
- initialize: function( opts ) {
- this.listenTo( this.instance, 'relational:change:' + this.key, this.onChange );
-
- var related = this.findRelated( opts );
- this.setRelated( related );
-
- // Notify new 'related' object of the new relation.
- _.each( this.getReverseRelations(), function( relation ) {
- relation.addRelated( this.instance, opts );
- }, this );
- },
-
- /**
- * Find related Models.
- * @param {Object} [options]
- * @return {Backbone.Model}
- */
- findRelated: function( options ) {
- var related = null;
-
- options = _.defaults( { parse: this.options.parse }, options );
-
- if ( this.keyContents instanceof this.relatedModel ) {
- related = this.keyContents;
- }
- else if ( this.keyContents || this.keyContents === 0 ) { // since 0 can be a valid `id` as well
- var opts = _.defaults( { create: this.options.createModels }, options );
- related = this.relatedModel.findOrCreate( this.keyContents, opts );
- }
-
- // Nullify `keyId` if we have a related model; in case it was already part of the relation
- if ( this.related ) {
- this.keyId = null;
- }
-
- return related;
- },
-
- /**
- * Normalize and reduce `keyContents` to an `id`, for easier comparison
- * @param {String|Number|Backbone.Model} keyContents
- */
- setKeyContents: function( keyContents ) {
- this.keyContents = keyContents;
- this.keyId = Backbone.Relational.store.resolveIdForItem( this.relatedModel, this.keyContents );
- },
-
- /**
- * Event handler for `change:<key>`.
- * If the key is changed, notify old & new reverse relations and initialize the new relation.
- */
- onChange: function( model, attr, options ) {
- // Don't accept recursive calls to onChange (like onChange->findRelated->findOrCreate->initializeRelations->addRelated->onChange)
- if ( this.isLocked() ) {
- return;
- }
- this.acquire();
- options = options ? _.clone( options ) : {};
-
- // 'options.__related' is set by 'addRelated'/'removeRelated'. If it is set, the change
- // is the result of a call from a relation. If it's not, the change is the result of
- // a 'set' call on this.instance.
- var changed = _.isUndefined( options.__related ),
- oldRelated = changed ? this.related : options.__related;
-
- if ( changed ) {
- this.setKeyContents( attr );
- var related = this.findRelated( options );
- this.setRelated( related );
- }
-
- // Notify old 'related' object of the terminated relation
- if ( oldRelated && this.related !== oldRelated ) {
- _.each( this.getReverseRelations( oldRelated ), function( relation ) {
- relation.removeRelated( this.instance, null, options );
- }, this );
- }
-
- // Notify new 'related' object of the new relation. Note we do re-apply even if this.related is oldRelated;
- // that can be necessary for bi-directional relations if 'this.instance' was created after 'this.related'.
- // In that case, 'this.instance' will already know 'this.related', but the reverse might not exist yet.
- _.each( this.getReverseRelations(), function( relation ) {
- relation.addRelated( this.instance, options );
- }, this );
-
- // Fire the 'change:<key>' event if 'related' was updated
- if ( !options.silent && this.related !== oldRelated ) {
- var dit = this;
- this.changed = true;
- Backbone.Relational.eventQueue.add( function() {
- dit.instance.trigger( 'change:' + dit.key, dit.instance, dit.related, options, true );
- dit.changed = false;
- });
- }
- this.release();
- },
-
- /**
- * If a new 'this.relatedModel' appears in the 'store', try to match it to the last set 'keyContents'
- */
- tryAddRelated: function( model, coll, options ) {
- if ( ( this.keyId || this.keyId === 0 ) && model.id === this.keyId ) { // since 0 can be a valid `id` as well
- this.addRelated( model, options );
- this.keyId = null;
- }
- },
-
- addRelated: function( model, options ) {
- // Allow 'model' to set up its relations before proceeding.
- // (which can result in a call to 'addRelated' from a relation of 'model')
- var dit = this;
- model.queue( function() {
- if ( model !== dit.related ) {
- var oldRelated = dit.related || null;
- dit.setRelated( model );
- dit.onChange( dit.instance, model, _.defaults( { __related: oldRelated }, options ) );
- }
- });
- },
-
- removeRelated: function( model, coll, options ) {
- if ( !this.related ) {
- return;
- }
-
- if ( model === this.related ) {
- var oldRelated = this.related || null;
- this.setRelated( null );
- this.onChange( this.instance, model, _.defaults( { __related: oldRelated }, options ) );
- }
- }
- });
-
- Backbone.HasMany = Backbone.Relation.extend({
- collectionType: null,
-
- options: {
- reverseRelation: { type: 'HasOne' },
- collectionType: Backbone.Collection,
- collectionKey: true,
- collectionOptions: {}
- },
-
- initialize: function( opts ) {
- this.listenTo( this.instance, 'relational:change:' + this.key, this.onChange );
-
- // Handle a custom 'collectionType'
- this.collectionType = this.options.collectionType;
- if ( _.isString( this.collectionType ) ) {
- this.collectionType = Backbone.Relational.store.getObjectByName( this.collectionType );
- }
- if ( this.collectionType !== Backbone.Collection && !( this.collectionType.prototype instanceof Backbone.Collection ) ) {
- throw new Error( '`collectionType` must inherit from Backbone.Collection' );
- }
-
- var related = this.findRelated( opts );
- this.setRelated( related );
- },
-
- /**
- * Bind events and setup collectionKeys for a collection that is to be used as the backing store for a HasMany.
- * If no 'collection' is supplied, a new collection will be created of the specified 'collectionType' option.
- * @param {Backbone.Collection} [collection]
- * @return {Backbone.Collection}
- */
- _prepareCollection: function( collection ) {
- if ( this.related ) {
- this.stopListening( this.related );
- }
-
- if ( !collection || !( collection instanceof Backbone.Collection ) ) {
- var options = _.isFunction( this.options.collectionOptions ) ?
- this.options.collectionOptions( this.instance ) : this.options.collectionOptions;
-
- collection = new this.collectionType( null, options );
- }
-
- collection.model = this.relatedModel;
-
- if ( this.options.collectionKey ) {
- var key = this.options.collectionKey === true ? this.options.reverseRelation.key : this.options.collectionKey;
-
- if ( collection[ key ] && collection[ key ] !== this.instance ) {
- if ( Backbone.Relational.showWarnings && typeof console !== 'undefined' ) {
- console.warn( 'Relation=%o; collectionKey=%s already exists on collection=%o', this, key, this.options.collectionKey );
- }
- }
- else if ( key ) {
- collection[ key ] = this.instance;
- }
- }
-
- this.listenTo( collection, 'relational:add', this.handleAddition )
- .listenTo( collection, 'relational:remove', this.handleRemoval )
- .listenTo( collection, 'relational:reset', this.handleReset );
-
- return collection;
- },
-
- /**
- * Find related Models.
- * @param {Object} [options]
- * @return {Backbone.Collection}
- */
- findRelated: function( options ) {
- var related = null;
-
- options = _.defaults( { parse: this.options.parse }, options );
-
- // Replace 'this.related' by 'this.keyContents' if it is a Backbone.Collection
- if ( this.keyContents instanceof Backbone.Collection ) {
- this._prepareCollection( this.keyContents );
- related = this.keyContents;
- }
- // Otherwise, 'this.keyContents' should be an array of related object ids.
- // Re-use the current 'this.related' if it is a Backbone.Collection; otherwise, create a new collection.
- else {
- var toAdd = [];
-
- _.each( this.keyContents, function( attributes ) {
- if ( attributes instanceof this.relatedModel ) {
- var model = attributes;
- }
- else {
- // If `merge` is true, update models here, instead of during update.
- model = this.relatedModel.findOrCreate( attributes,
- _.extend( { merge: true }, options, { create: this.options.createModels } )
- );
- }
-
- model && toAdd.push( model );
- }, this );
-
- if ( this.related instanceof Backbone.Collection ) {
- related = this.related;
- }
- else {
- related = this._prepareCollection();
- }
-
- // By now, both `merge` and `parse` will already have been executed for models if they were specified.
- // Disable them to prevent additional calls.
- related.set( toAdd, _.defaults( { merge: false, parse: false }, options ) );
- }
-
- // Remove entries from `keyIds` that were already part of the relation (and are thus 'unchanged')
- this.keyIds = _.difference( this.keyIds, _.pluck( related.models, 'id' ) );
-
- return related;
- },
-
- /**
- * Normalize and reduce `keyContents` to a list of `ids`, for easier comparison
- * @param {String|Number|String[]|Number[]|Backbone.Collection} keyContents
- */
- setKeyContents: function( keyContents ) {
- this.keyContents = keyContents instanceof Backbone.Collection ? keyContents : null;
- this.keyIds = [];
-
- if ( !this.keyContents && ( keyContents || keyContents === 0 ) ) { // since 0 can be a valid `id` as well
- // Handle cases the an API/user supplies just an Object/id instead of an Array
- this.keyContents = _.isArray( keyContents ) ? keyContents : [ keyContents ];
-
- _.each( this.keyContents, function( item ) {
- var itemId = Backbone.Relational.store.resolveIdForItem( this.relatedModel, item );
- if ( itemId || itemId === 0 ) {
- this.keyIds.push( itemId );
- }
- }, this );
- }
- },
-
- /**
- * Event handler for `change:<key>`.
- * If the contents of the key are changed, notify old & new reverse relations and initialize the new relation.
- */
- onChange: function( model, attr, options ) {
- options = options ? _.clone( options ) : {};
- this.setKeyContents( attr );
- this.changed = false;
-
- var related = this.findRelated( options );
- this.setRelated( related );
-
- if ( !options.silent ) {
- var dit = this;
- Backbone.Relational.eventQueue.add( function() {
- // The `changed` flag can be set in `handleAddition` or `handleRemoval`
- if ( dit.changed ) {
- dit.instance.trigger( 'change:' + dit.key, dit.instance, dit.related, options, true );
- dit.changed = false;
- }
- });
- }
- },
-
- /**
- * When a model is added to a 'HasMany', trigger 'add' on 'this.instance' and notify reverse relations.
- * (should be 'HasOne', must set 'this.instance' as their related).
- */
- handleAddition: function( model, coll, options ) {
- //console.debug('handleAddition called; args=%o', arguments);
- options = options ? _.clone( options ) : {};
- this.changed = true;
-
- _.each( this.getReverseRelations( model ), function( relation ) {
- relation.addRelated( this.instance, options );
- }, this );
-
- // Only trigger 'add' once the newly added model is initialized (so, has its relations set up)
- var dit = this;
- !options.silent && Backbone.Relational.eventQueue.add( function() {
- dit.instance.trigger( 'add:' + dit.key, model, dit.related, options );
- });
- },
-
- /**
- * When a model is removed from a 'HasMany', trigger 'remove' on 'this.instance' and notify reverse relations.
- * (should be 'HasOne', which should be nullified)
- */
- handleRemoval: function( model, coll, options ) {
- //console.debug('handleRemoval called; args=%o', arguments);
- options = options ? _.clone( options ) : {};
- this.changed = true;
-
- _.each( this.getReverseRelations( model ), function( relation ) {
- relation.removeRelated( this.instance, null, options );
- }, this );
-
- var dit = this;
- !options.silent && Backbone.Relational.eventQueue.add( function() {
- dit.instance.trigger( 'remove:' + dit.key, model, dit.related, options );
- });
- },
-
- handleReset: function( coll, options ) {
- var dit = this;
- options = options ? _.clone( options ) : {};
- !options.silent && Backbone.Relational.eventQueue.add( function() {
- dit.instance.trigger( 'reset:' + dit.key, dit.related, options );
- });
- },
-
- tryAddRelated: function( model, coll, options ) {
- var item = _.contains( this.keyIds, model.id );
-
- if ( item ) {
- this.addRelated( model, options );
- this.keyIds = _.without( this.keyIds, model.id );
- }
- },
-
- addRelated: function( model, options ) {
- // Allow 'model' to set up its relations before proceeding.
- // (which can result in a call to 'addRelated' from a relation of 'model')
- var dit = this;
- model.queue( function() {
- if ( dit.related && !dit.related.get( model ) ) {
- dit.related.add( model, _.defaults( { parse: false }, options ) );
- }
- });
- },
-
- removeRelated: function( model, coll, options ) {
- if ( this.related.get( model ) ) {
- this.related.remove( model, options );
- }
- }
- });
-
- /**
- * A type of Backbone.Model that also maintains relations to other models and collections.
- * New events when compared to the original:
- * - 'add:<key>' (model, related collection, options)
- * - 'remove:<key>' (model, related collection, options)
- * - 'change:<key>' (model, related model or collection, options)
- */
- Backbone.RelationalModel = Backbone.Model.extend({
- relations: null, // Relation descriptions on the prototype
- _relations: null, // Relation instances
- _isInitialized: false,
- _deferProcessing: false,
- _queue: null,
-
- subModelTypeAttribute: 'type',
- subModelTypes: null,
-
- constructor: function( attributes, options ) {
- // Nasty hack, for cases like 'model.get( <HasMany key> ).add( item )'.
- // Defer 'processQueue', so that when 'Relation.createModels' is used we trigger 'HasMany'
- // collection events only after the model is really fully set up.
- // Example: event for "p.on( 'add:jobs' )" -> "p.get('jobs').add( { company: c.id, person: p.id } )".
- if ( options && options.collection ) {
- var dit = this,
- collection = this.collection = options.collection;
-
- // Prevent `collection` from cascading down to nested models; they shouldn't go into this `if` clause.
- delete options.collection;
-
- this._deferProcessing = true;
-
- var processQueue = function( model ) {
- if ( model === dit ) {
- dit._deferProcessing = false;
- dit.processQueue();
- collection.off( 'relational:add', processQueue );
- }
- };
- collection.on( 'relational:add', processQueue );
-
- // So we do process the queue eventually, regardless of whether this model actually gets added to 'options.collection'.
- _.defer( function() {
- processQueue( dit );
- });
- }
-
- Backbone.Relational.store.processOrphanRelations();
-
- this._queue = new Backbone.BlockingQueue();
- this._queue.block();
- Backbone.Relational.eventQueue.block();
-
- try {
- Backbone.Model.apply( this, arguments );
- }
- finally {
- // Try to run the global queue holding external events
- Backbone.Relational.eventQueue.unblock();
- }
- },
-
- /**
- * Override 'trigger' to queue 'change' and 'change:*' events
- */
- trigger: function( eventName ) {
- if ( eventName.length > 5 && eventName.indexOf( 'change' ) === 0 ) {
- var dit = this,
- args = arguments;
-
- Backbone.Relational.eventQueue.add( function() {
- if ( !dit._isInitialized ) {
- return;
- }
-
- // Determine if the `change` event is still valid, now that all relations are populated
- var changed = true;
- if ( eventName === 'change' ) {
- changed = dit.hasChanged();
- }
- else {
- var attr = eventName.slice( 7 ),
- rel = dit.getRelation( attr );
-
- if ( rel ) {
- // If `attr` is a relation, `change:attr` get triggered from `Relation.onChange`.
- // These take precedence over `change:attr` events triggered by `Model.set`.
- // The relation set a fourth attribute to `true`. If this attribute is present,
- // continue triggering this event; otherwise, it's from `Model.set` and should be stopped.
- changed = ( args[ 4 ] === true );
-
- // If this event was triggered by a relation, set the right value in `this.changed`
- // (a Collection or Model instead of raw data).
- if ( changed ) {
- dit.changed[ attr ] = args[ 2 ];
- }
- // Otherwise, this event is from `Model.set`. If the relation doesn't report a change,
- // remove attr from `dit.changed` so `hasChanged` doesn't take it into account.
- else if ( !rel.changed ) {
- delete dit.changed[ attr ];
- }
- }
- }
-
- changed && Backbone.Model.prototype.trigger.apply( dit, args );
- });
- }
- else {
- Backbone.Model.prototype.trigger.apply( this, arguments );
- }
-
- return this;
- },
-
- /**
- * Initialize Relations present in this.relations; determine the type (HasOne/HasMany), then creates a new instance.
- * Invoked in the first call so 'set' (which is made from the Backbone.Model constructor).
- */
- initializeRelations: function( options ) {
- this.acquire(); // Setting up relations often also involve calls to 'set', and we only want to enter this function once
- this._relations = {};
-
- _.each( this.relations || [], function( rel ) {
- Backbone.Relational.store.initializeRelation( this, rel, options );
- }, this );
-
- this._isInitialized = true;
- this.release();
- this.processQueue();
- },
-
- /**
- * When new values are set, notify this model's relations (also if options.silent is set).
- * (Relation.setRelated locks this model before calling 'set' on it to prevent loops)
- */
- updateRelations: function( options ) {
- if ( this._isInitialized && !this.isLocked() ) {
- _.each( this._relations, function( rel ) {
- // Update from data in `rel.keySource` if set, or `rel.key` otherwise
- var val = this.attributes[ rel.keySource ] || this.attributes[ rel.key ];
- if ( rel.related !== val ) {
- this.trigger( 'relational:change:' + rel.key, this, val, options || {} );
- }
- }, this );
- }
- },
-
- /**
- * Either add to the queue (if we're not initialized yet), or execute right away.
- */
- queue: function( func ) {
- this._queue.add( func );
- },
-
- /**
- * Process _queue
- */
- processQueue: function() {
- if ( this._isInitialized && !this._deferProcessing && this._queue.isBlocked() ) {
- this._queue.unblock();
- }
- },
-
- /**
- * Get a specific relation.
- * @param key {string} The relation key to look for.
- * @return {Backbone.Relation} An instance of 'Backbone.Relation', if a relation was found for 'key', or null.
- */
- getRelation: function( key ) {
- return this._relations[ key ];
- },
-
- /**
- * Get all of the created relations.
- * @return {Backbone.Relation[]}
- */
- getRelations: function() {
- return _.values( this._relations );
- },
-
- /**
- * Retrieve related objects.
- * @param key {string} The relation key to fetch models for.
- * @param [options] {Object} Options for 'Backbone.Model.fetch' and 'Backbone.sync'.
- * @param [refresh=false] {boolean} Fetch existing models from the server as well (in order to update them).
- * @return {jQuery.when[]} An array of request objects
- */
- fetchRelated: function( key, options, refresh ) {
- // Set default `options` for fetch
- options = _.extend( { update: true, remove: false }, options );
-
- var setUrl,
- requests = [],
- rel = this.getRelation( key ),
- idsToFetch = rel && ( rel.keyIds || ( ( rel.keyId || rel.keyId === 0 ) ? [ rel.keyId ] : [] ) );
-
- // On `refresh`, add the ids for current models in the relation to `idsToFetch`
- if ( refresh ) {
- var models = rel.related instanceof Backbone.Collection ? rel.related.models : [ rel.related ];
- _.each( models, function( model ) {
- if ( model.id || model.id === 0 ) {
- idsToFetch.push( model.id );
- }
- });
- }
-
- if ( idsToFetch && idsToFetch.length ) {
- // Find (or create) a model for each one that is to be fetched
- var created = [],
- models = _.map( idsToFetch, function( id ) {
- var model = Backbone.Relational.store.find( rel.relatedModel, id );
-
- if ( !model ) {
- var attrs = {};
- attrs[ rel.relatedModel.prototype.idAttribute ] = id;
- model = rel.relatedModel.findOrCreate( attrs, options );
- created.push( model );
- }
-
- return model;
- }, this );
-
- // Try if the 'collection' can provide a url to fetch a set of models in one request.
- if ( rel.related instanceof Backbone.Collection && _.isFunction( rel.related.url ) ) {
- setUrl = rel.related.url( models );
- }
-
- // An assumption is that when 'Backbone.Collection.url' is a function, it can handle building of set urls.
- // To make sure it can, test if the url we got by supplying a list of models to fetch is different from
- // the one supplied for the default fetch action (without args to 'url').
- if ( setUrl && setUrl !== rel.related.url() ) {
- var opts = _.defaults(
- {
- error: function() {
- var args = arguments;
- _.each( created, function( model ) {
- model.trigger( 'destroy', model, model.collection, options );
- options.error && options.error.apply( model, args );
- });
- },
- url: setUrl
- },
- options
- );
-
- requests = [ rel.related.fetch( opts ) ];
- }
- else {
- requests = _.map( models, function( model ) {
- var opts = _.defaults(
- {
- error: function() {
- if ( _.contains( created, model ) ) {
- model.trigger( 'destroy', model, model.collection, options );
- options.error && options.error.apply( model, arguments );
- }
- }
- },
- options
- );
- return model.fetch( opts );
- }, this );
- }
- }
-
- return requests;
- },
-
- get: function( attr ) {
- var originalResult = Backbone.Model.prototype.get.call( this, attr );
-
- // Use `originalResult` get if dotNotation not enabled or not required because no dot is in `attr`
- if ( !this.dotNotation || attr.indexOf( '.' ) === -1 ) {
- return originalResult;
- }
-
- // Go through all splits and return the final result
- var splits = attr.split( '.' );
- var result = _.reduce(splits, function( model, split ) {
- if ( !( model instanceof Backbone.Model ) ) {
- throw new Error( 'Attribute must be an instanceof Backbone.Model. Is: ' + model + ', currentSplit: ' + split );
- }
-
- return Backbone.Model.prototype.get.call( model, split );
- }, this );
-
- if ( originalResult !== undefined && result !== undefined ) {
- throw new Error( "Ambiguous result for '" + attr + "'. direct result: " + originalResult + ", dotNotation: " + result );
- }
-
- return originalResult || result;
- },
-
- set: function( key, value, options ) {
- Backbone.Relational.eventQueue.block();
-
- // Duplicate backbone's behavior to allow separate key/value parameters, instead of a single 'attributes' object
- var attributes;
- if ( _.isObject( key ) || key == null ) {
- attributes = key;
- options = value;
- }
- else {
- attributes = {};
- attributes[ key ] = value;
- }
-
- try {
- var id = this.id,
- newId = attributes && this.idAttribute in attributes && attributes[ this.idAttribute ];
-
- // Check if we're not setting a duplicate id before actually calling `set`.
- Backbone.Relational.store.checkId( this, newId );
-
- var result = Backbone.Model.prototype.set.apply( this, arguments );
-
- // Ideal place to set up relations, if this is the first time we're here for this model
- if ( !this._isInitialized && !this.isLocked() ) {
- this.constructor.initializeModelHierarchy();
- Backbone.Relational.store.register( this );
- this.initializeRelations( options );
- }
- // The store should know about an `id` update asap
- else if ( newId && newId !== id ) {
- Backbone.Relational.store.update( this );
- }
-
- if ( attributes ) {
- this.updateRelations( options );
- }
- }
- finally {
- // Try to run the global queue holding external events
- Backbone.Relational.eventQueue.unblock();
- }
-
- return result;
- },
-
- unset: function( attribute, options ) {
- Backbone.Relational.eventQueue.block();
-
- var result = Backbone.Model.prototype.unset.apply( this, arguments );
- this.updateRelations( options );
-
- // Try to run the global queue holding external events
- Backbone.Relational.eventQueue.unblock();
-
- return result;
- },
-
- clear: function( options ) {
- Backbone.Relational.eventQueue.block();
-
- var result = Backbone.Model.prototype.clear.apply( this, arguments );
- this.updateRelations( options );
-
- // Try to run the global queue holding external events
- Backbone.Relational.eventQueue.unblock();
-
- return result;
- },
-
- clone: function() {
- var attributes = _.clone( this.attributes );
- if ( !_.isUndefined( attributes[ this.idAttribute ] ) ) {
- attributes[ this.idAttribute ] = null;
- }
-
- _.each( this.getRelations(), function( rel ) {
- delete attributes[ rel.key ];
- });
-
- return new this.constructor( attributes );
- },
-
- /**
- * Convert relations to JSON, omits them when required
- */
- toJSON: function( options ) {
- // If this Model has already been fully serialized in this branch once, return to avoid loops
- if ( this.isLocked() ) {
- return this.id;
- }
-
- this.acquire();
- var json = Backbone.Model.prototype.toJSON.call( this, options );
-
- if ( this.constructor._superModel && !( this.constructor._subModelTypeAttribute in json ) ) {
- json[ this.constructor._subModelTypeAttribute ] = this.constructor._subModelTypeValue;
- }
-
- _.each( this._relations, function( rel ) {
- var related = json[ rel.key ],
- includeInJSON = rel.options.includeInJSON,
- value = null;
-
- if ( includeInJSON === true ) {
- if ( related && _.isFunction( related.toJSON ) ) {
- value = related.toJSON( options );
- }
- }
- else if ( _.isString( includeInJSON ) ) {
- if ( related instanceof Backbone.Collection ) {
- value = related.pluck( includeInJSON );
- }
- else if ( related instanceof Backbone.Model ) {
- value = related.get( includeInJSON );
- }
-
- // Add ids for 'unfound' models if includeInJSON is equal to (only) the relatedModel's `idAttribute`
- if ( includeInJSON === rel.relatedModel.prototype.idAttribute ) {
- if ( rel instanceof Backbone.HasMany ) {
- value = value.concat( rel.keyIds );
- }
- else if ( rel instanceof Backbone.HasOne ) {
- value = value || rel.keyId;
- }
- }
- }
- else if ( _.isArray( includeInJSON ) ) {
- if ( related instanceof Backbone.Collection ) {
- value = [];
- related.each( function( model ) {
- var curJson = {};
- _.each( includeInJSON, function( key ) {
- curJson[ key ] = model.get( key );
- });
- value.push( curJson );
- });
- }
- else if ( related instanceof Backbone.Model ) {
- value = {};
- _.each( includeInJSON, function( key ) {
- value[ key ] = related.get( key );
- });
- }
- }
- else {
- delete json[ rel.key ];
- }
-
- if ( includeInJSON ) {
- json[ rel.keyDestination ] = value;
- }
-
- if ( rel.keyDestination !== rel.key ) {
- delete json[ rel.key ];
- }
- });
-
- this.release();
- return json;
- }
- },
- {
- /**
- *
- * @param superModel
- * @returns {Backbone.RelationalModel.constructor}
- */
- setup: function( superModel ) {
- // We don't want to share a relations array with a parent, as this will cause problems with
- // reverse relations.
- this.prototype.relations = ( this.prototype.relations || [] ).slice( 0 );
-
- this._subModels = {};
- this._superModel = null;
-
- // If this model has 'subModelTypes' itself, remember them in the store
- if ( this.prototype.hasOwnProperty( 'subModelTypes' ) ) {
- Backbone.Relational.store.addSubModels( this.prototype.subModelTypes, this );
- }
- // The 'subModelTypes' property should not be inherited, so reset it.
- else {
- this.prototype.subModelTypes = null;
- }
-
- // Initialize all reverseRelations that belong to this new model.
- _.each( this.prototype.relations || [], function( rel ) {
- if ( !rel.model ) {
- rel.model = this;
- }
-
- if ( rel.reverseRelation && rel.model === this ) {
- var preInitialize = true;
- if ( _.isString( rel.relatedModel ) ) {
- /**
- * The related model might not be defined for two reasons
- * 1. it is related to itself
- * 2. it never gets defined, e.g. a typo
- * 3. the model hasn't been defined yet, but will be later
- * In neither of these cases do we need to pre-initialize reverse relations.
- * However, for 3. (which is, to us, indistinguishable from 2.), we do need to attempt
- * setting up this relation again later, in case the related model is defined later.
- */
- var relatedModel = Backbone.Relational.store.getObjectByName( rel.relatedModel );
- preInitialize = relatedModel && ( relatedModel.prototype instanceof Backbone.RelationalModel );
- }
-
- if ( preInitialize ) {
- Backbone.Relational.store.initializeRelation( null, rel );
- }
- else if ( _.isString( rel.relatedModel ) ) {
- Backbone.Relational.store.addOrphanRelation( rel );
- }
- }
- }, this );
-
- return this;
- },
-
- /**
- * Create a 'Backbone.Model' instance based on 'attributes'.
- * @param {Object} attributes
- * @param {Object} [options]
- * @return {Backbone.Model}
- */
- build: function( attributes, options ) {
- var model = this;
-
- // 'build' is a possible entrypoint; it's possible no model hierarchy has been determined yet.
- this.initializeModelHierarchy();
-
- // Determine what type of (sub)model should be built if applicable.
- // Lookup the proper subModelType in 'this._subModels'.
- if ( this._subModels && this.prototype.subModelTypeAttribute in attributes ) {
- var subModelTypeAttribute = attributes[ this.prototype.subModelTypeAttribute ];
- var subModelType = this._subModels[ subModelTypeAttribute ];
- if ( subModelType ) {
- model = subModelType;
- }
- }
-
- return new model( attributes, options );
- },
-
- /**
- *
- */
- initializeModelHierarchy: function() {
- // If we're here for the first time, try to determine if this modelType has a 'superModel'.
- if ( _.isUndefined( this._superModel ) || _.isNull( this._superModel ) ) {
- Backbone.Relational.store.setupSuperModel( this );
-
- // If a superModel has been found, copy relations from the _superModel if they haven't been
- // inherited automatically (due to a redefinition of 'relations').
- // Otherwise, make sure we don't get here again for this type by making '_superModel' false so we fail
- // the isUndefined/isNull check next time.
- if ( this._superModel && this._superModel.prototype.relations ) {
- // Find relations that exist on the `_superModel`, but not yet on this model.
- var inheritedRelations = _.select( this._superModel.prototype.relations || [], function( superRel ) {
- return !_.any( this.prototype.relations || [], function( rel ) {
- return superRel.relatedModel === rel.relatedModel && superRel.key === rel.key;
- }, this );
- }, this );
-
- this.prototype.relations = inheritedRelations.concat( this.prototype.relations );
- }
- else {
- this._superModel = false;
- }
- }
-
- // If we came here through 'build' for a model that has 'subModelTypes', and not all of them have been resolved yet, try to resolve each.
- if ( this.prototype.subModelTypes && _.keys( this.prototype.subModelTypes ).length !== _.keys( this._subModels ).length ) {
- _.each( this.prototype.subModelTypes || [], function( subModelTypeName ) {
- var subModelType = Backbone.Relational.store.getObjectByName( subModelTypeName );
- subModelType && subModelType.initializeModelHierarchy();
- });
- }
- },
-
- /**
- * Find an instance of `this` type in 'Backbone.Relational.store'.
- * - If `attributes` is a string or a number, `findOrCreate` will just query the `store` and return a model if found.
- * - If `attributes` is an object and is found in the store, the model will be updated with `attributes` unless `options.update` is `false`.
- * Otherwise, a new model is created with `attributes` (unless `options.create` is explicitly set to `false`).
- * @param {Object|String|Number} attributes Either a model's id, or the attributes used to create or update a model.
- * @param {Object} [options]
- * @param {Boolean} [options.create=true]
- * @param {Boolean} [options.merge=true]
- * @param {Boolean} [options.parse=false]
- * @return {Backbone.RelationalModel}
- */
- findOrCreate: function( attributes, options ) {
- options || ( options = {} );
- var parsedAttributes = ( _.isObject( attributes ) && options.parse && this.prototype.parse ) ?
- this.prototype.parse( attributes ) : attributes;
-
- // Try to find an instance of 'this' model type in the store
- var model = Backbone.Relational.store.find( this, parsedAttributes );
-
- // If we found an instance, update it with the data in 'item' (unless 'options.merge' is false).
- // If not, create an instance (unless 'options.create' is false).
- if ( _.isObject( attributes ) ) {
- if ( model && options.merge !== false ) {
- // Make sure `options.collection` doesn't cascade to nested models
- delete options.collection;
-
- model.set( parsedAttributes, options );
- }
- else if ( !model && options.create !== false ) {
- model = this.build( attributes, options );
- }
- }
-
- return model;
- }
- });
- _.extend( Backbone.RelationalModel.prototype, Backbone.Semaphore );
-
- /**
- * Override Backbone.Collection._prepareModel, so objects will be built using the correct type
- * if the collection.model has subModels.
- * Attempts to find a model for `attrs` in Backbone.store through `findOrCreate`
- * (which sets the new properties on it if found), or instantiates a new model.
- */
- Backbone.Collection.prototype.__prepareModel = Backbone.Collection.prototype._prepareModel;
- Backbone.Collection.prototype._prepareModel = function ( attrs, options ) {
- var model;
-
- if ( attrs instanceof Backbone.Model ) {
- if ( !attrs.collection ) {
- attrs.collection = this;
- }
- model = attrs;
- }
- else {
- options || ( options = {} );
- options.collection = this;
-
- if ( typeof this.model.findOrCreate !== 'undefined' ) {
- model = this.model.findOrCreate( attrs, options );
- }
- else {
- model = new this.model( attrs, options );
- }
-
- if ( model && model.isNew() && !model._validate( attrs, options ) ) {
- this.trigger( 'invalid', this, attrs, options );
- model = false;
- }
- }
-
- return model;
- };
-
-
- /**
- * Override Backbone.Collection.set, so we'll create objects from attributes where required,
- * and update the existing models. Also, trigger 'relational:add'.
- */
- var set = Backbone.Collection.prototype.__set = Backbone.Collection.prototype.set;
- Backbone.Collection.prototype.set = function( models, options ) {
- // Short-circuit if this Collection doesn't hold RelationalModels
- if ( !( this.model.prototype instanceof Backbone.RelationalModel ) ) {
- return set.apply( this, arguments );
- }
-
- if ( options && options.parse ) {
- models = this.parse( models, options );
- }
-
- if ( !_.isArray( models ) ) {
- models = models ? [ models ] : [];
- }
-
- var newModels = [],
- toAdd = [];
-
- //console.debug( 'calling add on coll=%o; model=%o, options=%o', this, models, options );
- _.each( models, function( model ) {
- if ( !( model instanceof Backbone.Model ) ) {
- model = Backbone.Collection.prototype._prepareModel.call( this, model, options );
- }
-
- if ( model ) {
- toAdd.push( model );
-
- if ( !( this.get( model ) || this.get( model.cid ) ) ) {
- newModels.push( model );
- }
- // If we arrive in `add` while performing a `set` (after a create, so the model gains an `id`),
- // we may get here before `_onModelEvent` has had the chance to update `_byId`.
- else if ( model.id != null ) {
- this._byId[ model.id ] = model;
- }
- }
- }, this );
-
- // Add 'models' in a single batch, so the original add will only be called once (and thus 'sort', etc).
- // If `parse` was specified, the collection and contained models have been parsed now.
- set.call( this, toAdd, _.defaults( { parse: false }, options ) );
-
- _.each( newModels, function( model ) {
- // Fire a `relational:add` event for any model in `newModels` that has actually been added to the collection.
- if ( this.get( model ) || this.get( model.cid ) ) {
- this.trigger( 'relational:add', model, this, options );
- }
- }, this );
-
- return this;
- };
-
- /**
- * Override 'Backbone.Collection.remove' to trigger 'relational:remove'.
- */
- var remove = Backbone.Collection.prototype.__remove = Backbone.Collection.prototype.remove;
- Backbone.Collection.prototype.remove = function( models, options ) {
- // Short-circuit if this Collection doesn't hold RelationalModels
- if ( !( this.model.prototype instanceof Backbone.RelationalModel ) ) {
- return remove.apply( this, arguments );
- }
-
- models = _.isArray( models ) ? models.slice() : [ models ];
- options || ( options = {} );
-
- var toRemove = [];
-
- //console.debug('calling remove on coll=%o; models=%o, options=%o', this, models, options );
- _.each( models, function( model ) {
- model = this.get( model ) || this.get( model.cid );
- model && toRemove.push( model );
- }, this );
-
- if ( toRemove.length ) {
- remove.call( this, toRemove, options );
-
- _.each( toRemove, function( model ) {
- this.trigger('relational:remove', model, this, options);
- }, this );
- }
-
- return this;
- };
-
- /**
- * Override 'Backbone.Collection.reset' to trigger 'relational:reset'.
- */
- var reset = Backbone.Collection.prototype.__reset = Backbone.Collection.prototype.reset;
- Backbone.Collection.prototype.reset = function( models, options ) {
- options = _.extend( { merge: true }, options );
- reset.call( this, models, options );
-
- if ( this.model.prototype instanceof Backbone.RelationalModel ) {
- this.trigger( 'relational:reset', this, options );
- }
-
- return this;
- };
-
- /**
- * Override 'Backbone.Collection.sort' to trigger 'relational:reset'.
- */
- var sort = Backbone.Collection.prototype.__sort = Backbone.Collection.prototype.sort;
- Backbone.Collection.prototype.sort = function( options ) {
- sort.call( this, options );
-
- if ( this.model.prototype instanceof Backbone.RelationalModel ) {
- this.trigger( 'relational:reset', this, options );
- }
-
- return this;
- };
-
- /**
- * Override 'Backbone.Collection.trigger' so 'add', 'remove' and 'reset' events are queued until relations
- * are ready.
- */
- var trigger = Backbone.Collection.prototype.__trigger = Backbone.Collection.prototype.trigger;
- Backbone.Collection.prototype.trigger = function( eventName ) {
- // Short-circuit if this Collection doesn't hold RelationalModels
- if ( !( this.model.prototype instanceof Backbone.RelationalModel ) ) {
- return trigger.apply( this, arguments );
- }
-
- if ( eventName === 'add' || eventName === 'remove' || eventName === 'reset' ) {
- var dit = this,
- args = arguments;
-
- if ( _.isObject( args[ 3 ] ) ) {
- args = _.toArray( args );
- // the fourth argument is the option object.
- // we need to clone it, as it could be modified while we wait on the eventQueue to be unblocked
- args[ 3 ] = _.clone( args[ 3 ] );
- }
-
- Backbone.Relational.eventQueue.add( function() {
- trigger.apply( dit, args );
- });
- }
- else {
- trigger.apply( this, arguments );
- }
-
- return this;
- };
-
- // Override .extend() to automatically call .setup()
- Backbone.RelationalModel.extend = function( protoProps, classProps ) {
- var child = Backbone.Model.extend.apply( this, arguments );
-
- child.setup( this );
-
- return child;
- };
-})();
--- a/server/python/django/renkanmanager/static/renkanmanager/lib/backbone.js Fri Apr 24 13:05:09 2015 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,4 +0,0 @@
-(function(){var t=this;var e=t.Backbone;var i=[];var r=i.push;var s=i.slice;var n=i.splice;var a;if(typeof exports!=="undefined"){a=exports}else{a=t.Backbone={}}a.VERSION="1.0.0";var h=t._;if(!h&&typeof require!=="undefined")h=require("underscore");a.$=t.jQuery||t.Zepto||t.ender||t.$;a.noConflict=function(){t.Backbone=e;return this};a.emulateHTTP=false;a.emulateJSON=false;var o=a.Events={on:function(t,e,i){if(!l(this,"on",t,[e,i])||!e)return this;this._events||(this._events={});var r=this._events[t]||(this._events[t]=[]);r.push({callback:e,context:i,ctx:i||this});return this},once:function(t,e,i){if(!l(this,"once",t,[e,i])||!e)return this;var r=this;var s=h.once(function(){r.off(t,s);e.apply(this,arguments)});s._callback=e;return this.on(t,s,i)},off:function(t,e,i){var r,s,n,a,o,u,c,f;if(!this._events||!l(this,"off",t,[e,i]))return this;if(!t&&!e&&!i){this._events={};return this}a=t?[t]:h.keys(this._events);for(o=0,u=a.length;o<u;o++){t=a[o];if(n=this._events[t]){this._events[t]=r=[];if(e||i){for(c=0,f=n.length;c<f;c++){s=n[c];if(e&&e!==s.callback&&e!==s.callback._callback||i&&i!==s.context){r.push(s)}}}if(!r.length)delete this._events[t]}}return this},trigger:function(t){if(!this._events)return this;var e=s.call(arguments,1);if(!l(this,"trigger",t,e))return this;var i=this._events[t];var r=this._events.all;if(i)c(i,e);if(r)c(r,arguments);return this},stopListening:function(t,e,i){var r=this._listeners;if(!r)return this;var s=!e&&!i;if(typeof e==="object")i=this;if(t)(r={})[t._listenerId]=t;for(var n in r){r[n].off(e,i,this);if(s)delete this._listeners[n]}return this}};var u=/\s+/;var l=function(t,e,i,r){if(!i)return true;if(typeof i==="object"){for(var s in i){t[e].apply(t,[s,i[s]].concat(r))}return false}if(u.test(i)){var n=i.split(u);for(var a=0,h=n.length;a<h;a++){t[e].apply(t,[n[a]].concat(r))}return false}return true};var c=function(t,e){var i,r=-1,s=t.length,n=e[0],a=e[1],h=e[2];switch(e.length){case 0:while(++r<s)(i=t[r]).callback.call(i.ctx);return;case 1:while(++r<s)(i=t[r]).callback.call(i.ctx,n);return;case 2:while(++r<s)(i=t[r]).callback.call(i.ctx,n,a);return;case 3:while(++r<s)(i=t[r]).callback.call(i.ctx,n,a,h);return;default:while(++r<s)(i=t[r]).callback.apply(i.ctx,e)}};var f={listenTo:"on",listenToOnce:"once"};h.each(f,function(t,e){o[e]=function(e,i,r){var s=this._listeners||(this._listeners={});var n=e._listenerId||(e._listenerId=h.uniqueId("l"));s[n]=e;if(typeof i==="object")r=this;e[t](i,r,this);return this}});o.bind=o.on;o.unbind=o.off;h.extend(a,o);var d=a.Model=function(t,e){var i;var r=t||{};e||(e={});this.cid=h.uniqueId("c");this.attributes={};h.extend(this,h.pick(e,p));if(e.parse)r=this.parse(r,e)||{};if(i=h.result(this,"defaults")){r=h.defaults({},r,i)}this.set(r,e);this.changed={};this.initialize.apply(this,arguments)};var p=["url","urlRoot","collection"];h.extend(d.prototype,o,{changed:null,validationError:null,idAttribute:"id",initialize:function(){},toJSON:function(t){return h.clone(this.attributes)},sync:function(){return a.sync.apply(this,arguments)},get:function(t){return this.attributes[t]},escape:function(t){return h.escape(this.get(t))},has:function(t){return this.get(t)!=null},set:function(t,e,i){var r,s,n,a,o,u,l,c;if(t==null)return this;if(typeof t==="object"){s=t;i=e}else{(s={})[t]=e}i||(i={});if(!this._validate(s,i))return false;n=i.unset;o=i.silent;a=[];u=this._changing;this._changing=true;if(!u){this._previousAttributes=h.clone(this.attributes);this.changed={}}c=this.attributes,l=this._previousAttributes;if(this.idAttribute in s)this.id=s[this.idAttribute];for(r in s){e=s[r];if(!h.isEqual(c[r],e))a.push(r);if(!h.isEqual(l[r],e)){this.changed[r]=e}else{delete this.changed[r]}n?delete c[r]:c[r]=e}if(!o){if(a.length)this._pending=true;for(var f=0,d=a.length;f<d;f++){this.trigger("change:"+a[f],this,c[a[f]],i)}}if(u)return this;if(!o){while(this._pending){this._pending=false;this.trigger("change",this,i)}}this._pending=false;this._changing=false;return this},unset:function(t,e){return this.set(t,void 0,h.extend({},e,{unset:true}))},clear:function(t){var e={};for(var i in this.attributes)e[i]=void 0;return this.set(e,h.extend({},t,{unset:true}))},hasChanged:function(t){if(t==null)return!h.isEmpty(this.changed);return h.has(this.changed,t)},changedAttributes:function(t){if(!t)return this.hasChanged()?h.clone(this.changed):false;var e,i=false;var r=this._changing?this._previousAttributes:this.attributes;for(var s in t){if(h.isEqual(r[s],e=t[s]))continue;(i||(i={}))[s]=e}return i},previous:function(t){if(t==null||!this._previousAttributes)return null;return this._previousAttributes[t]},previousAttributes:function(){return h.clone(this._previousAttributes)},fetch:function(t){t=t?h.clone(t):{};if(t.parse===void 0)t.parse=true;var e=this;var i=t.success;t.success=function(r){if(!e.set(e.parse(r,t),t))return false;if(i)i(e,r,t);e.trigger("sync",e,r,t)};R(this,t);return this.sync("read",this,t)},save:function(t,e,i){var r,s,n,a=this.attributes;if(t==null||typeof t==="object"){r=t;i=e}else{(r={})[t]=e}if(r&&(!i||!i.wait)&&!this.set(r,i))return false;i=h.extend({validate:true},i);if(!this._validate(r,i))return false;if(r&&i.wait){this.attributes=h.extend({},a,r)}if(i.parse===void 0)i.parse=true;var o=this;var u=i.success;i.success=function(t){o.attributes=a;var e=o.parse(t,i);if(i.wait)e=h.extend(r||{},e);if(h.isObject(e)&&!o.set(e,i)){return false}if(u)u(o,t,i);o.trigger("sync",o,t,i)};R(this,i);s=this.isNew()?"create":i.patch?"patch":"update";if(s==="patch")i.attrs=r;n=this.sync(s,this,i);if(r&&i.wait)this.attributes=a;return n},destroy:function(t){t=t?h.clone(t):{};var e=this;var i=t.success;var r=function(){e.trigger("destroy",e,e.collection,t)};t.success=function(s){if(t.wait||e.isNew())r();if(i)i(e,s,t);if(!e.isNew())e.trigger("sync",e,s,t)};if(this.isNew()){t.success();return false}R(this,t);var s=this.sync("delete",this,t);if(!t.wait)r();return s},url:function(){var t=h.result(this,"urlRoot")||h.result(this.collection,"url")||U();if(this.isNew())return t;return t+(t.charAt(t.length-1)==="/"?"":"/")+encodeURIComponent(this.id)},parse:function(t,e){return t},clone:function(){return new this.constructor(this.attributes)},isNew:function(){return this.id==null},isValid:function(t){return this._validate({},h.extend(t||{},{validate:true}))},_validate:function(t,e){if(!e.validate||!this.validate)return true;t=h.extend({},this.attributes,t);var i=this.validationError=this.validate(t,e)||null;if(!i)return true;this.trigger("invalid",this,i,h.extend(e||{},{validationError:i}));return false}});var v=["keys","values","pairs","invert","pick","omit"];h.each(v,function(t){d.prototype[t]=function(){var e=s.call(arguments);e.unshift(this.attributes);return h[t].apply(h,e)}});var g=a.Collection=function(t,e){e||(e={});if(e.url)this.url=e.url;if(e.model)this.model=e.model;if(e.comparator!==void 0)this.comparator=e.comparator;this._reset();this.initialize.apply(this,arguments);if(t)this.reset(t,h.extend({silent:true},e))};var m={add:true,remove:true,merge:true};var y={add:true,merge:false,remove:false};h.extend(g.prototype,o,{model:d,initialize:function(){},toJSON:function(t){return this.map(function(e){return e.toJSON(t)})},sync:function(){return a.sync.apply(this,arguments)},add:function(t,e){return this.set(t,h.defaults(e||{},y))},remove:function(t,e){t=h.isArray(t)?t.slice():[t];e||(e={});var i,r,s,n;for(i=0,r=t.length;i<r;i++){n=this.get(t[i]);if(!n)continue;delete this._byId[n.id];delete this._byId[n.cid];s=this.indexOf(n);this.models.splice(s,1);this.length--;if(!e.silent){e.index=s;n.trigger("remove",n,this,e)}this._removeReference(n)}return this},set:function(t,e){e=h.defaults(e||{},m);if(e.parse)t=this.parse(t,e);if(!h.isArray(t))t=t?[t]:[];var i,s,a,o,u,l;var c=e.at;var f=this.comparator&&c==null&&e.sort!==false;var d=h.isString(this.comparator)?this.comparator:null;var p=[],v=[],g={};for(i=0,s=t.length;i<s;i++){if(!(a=this._prepareModel(t[i],e)))continue;if(u=this.get(a)){if(e.remove)g[u.cid]=true;if(e.merge){u.set(a.attributes,e);if(f&&!l&&u.hasChanged(d))l=true}}else if(e.add){p.push(a);a.on("all",this._onModelEvent,this);this._byId[a.cid]=a;if(a.id!=null)this._byId[a.id]=a}}if(e.remove){for(i=0,s=this.length;i<s;++i){if(!g[(a=this.models[i]).cid])v.push(a)}if(v.length)this.remove(v,e)}if(p.length){if(f)l=true;this.length+=p.length;if(c!=null){n.apply(this.models,[c,0].concat(p))}else{r.apply(this.models,p)}}if(l)this.sort({silent:true});if(e.silent)return this;for(i=0,s=p.length;i<s;i++){(a=p[i]).trigger("add",a,this,e)}if(l)this.trigger("sort",this,e);return this},reset:function(t,e){e||(e={});for(var i=0,r=this.models.length;i<r;i++){this._removeReference(this.models[i])}e.previousModels=this.models;this._reset();this.add(t,h.extend({silent:true},e));if(!e.silent)this.trigger("reset",this,e);return this},push:function(t,e){t=this._prepareModel(t,e);this.add(t,h.extend({at:this.length},e));return t},pop:function(t){var e=this.at(this.length-1);this.remove(e,t);return e},unshift:function(t,e){t=this._prepareModel(t,e);this.add(t,h.extend({at:0},e));return t},shift:function(t){var e=this.at(0);this.remove(e,t);return e},slice:function(t,e){return this.models.slice(t,e)},get:function(t){if(t==null)return void 0;return this._byId[t.id!=null?t.id:t.cid||t]},at:function(t){return this.models[t]},where:function(t,e){if(h.isEmpty(t))return e?void 0:[];return this[e?"find":"filter"](function(e){for(var i in t){if(t[i]!==e.get(i))return false}return true})},findWhere:function(t){return this.where(t,true)},sort:function(t){if(!this.comparator)throw new Error("Cannot sort a set without a comparator");t||(t={});if(h.isString(this.comparator)||this.comparator.length===1){this.models=this.sortBy(this.comparator,this)}else{this.models.sort(h.bind(this.comparator,this))}if(!t.silent)this.trigger("sort",this,t);return this},sortedIndex:function(t,e,i){e||(e=this.comparator);var r=h.isFunction(e)?e:function(t){return t.get(e)};return h.sortedIndex(this.models,t,r,i)},pluck:function(t){return h.invoke(this.models,"get",t)},fetch:function(t){t=t?h.clone(t):{};if(t.parse===void 0)t.parse=true;var e=t.success;var i=this;t.success=function(r){var s=t.reset?"reset":"set";i[s](r,t);if(e)e(i,r,t);i.trigger("sync",i,r,t)};R(this,t);return this.sync("read",this,t)},create:function(t,e){e=e?h.clone(e):{};if(!(t=this._prepareModel(t,e)))return false;if(!e.wait)this.add(t,e);var i=this;var r=e.success;e.success=function(s){if(e.wait)i.add(t,e);if(r)r(t,s,e)};t.save(null,e);return t},parse:function(t,e){return t},clone:function(){return new this.constructor(this.models)},_reset:function(){this.length=0;this.models=[];this._byId={}},_prepareModel:function(t,e){if(t instanceof d){if(!t.collection)t.collection=this;return t}e||(e={});e.collection=this;var i=new this.model(t,e);if(!i._validate(t,e)){this.trigger("invalid",this,t,e);return false}return i},_removeReference:function(t){if(this===t.collection)delete t.collection;t.off("all",this._onModelEvent,this)},_onModelEvent:function(t,e,i,r){if((t==="add"||t==="remove")&&i!==this)return;if(t==="destroy")this.remove(e,r);if(e&&t==="change:"+e.idAttribute){delete this._byId[e.previous(e.idAttribute)];if(e.id!=null)this._byId[e.id]=e}this.trigger.apply(this,arguments)}});var _=["forEach","each","map","collect","reduce","foldl","inject","reduceRight","foldr","find","detect","filter","select","reject","every","all","some","any","include","contains","invoke","max","min","toArray","size","first","head","take","initial","rest","tail","drop","last","without","indexOf","shuffle","lastIndexOf","isEmpty","chain"];h.each(_,function(t){g.prototype[t]=function(){var e=s.call(arguments);e.unshift(this.models);return h[t].apply(h,e)}});var w=["groupBy","countBy","sortBy"];h.each(w,function(t){g.prototype[t]=function(e,i){var r=h.isFunction(e)?e:function(t){return t.get(e)};return h[t](this.models,r,i)}});var b=a.View=function(t){this.cid=h.uniqueId("view");this._configure(t||{});this._ensureElement();this.initialize.apply(this,arguments);this.delegateEvents()};var x=/^(\S+)\s*(.*)$/;var E=["model","collection","el","id","attributes","className","tagName","events"];h.extend(b.prototype,o,{tagName:"div",$:function(t){return this.$el.find(t)},initialize:function(){},render:function(){return this},remove:function(){this.$el.remove();this.stopListening();return this},setElement:function(t,e){if(this.$el)this.undelegateEvents();this.$el=t instanceof a.$?t:a.$(t);this.el=this.$el[0];if(e!==false)this.delegateEvents();return this},delegateEvents:function(t){if(!(t||(t=h.result(this,"events"))))return this;this.undelegateEvents();for(var e in t){var i=t[e];if(!h.isFunction(i))i=this[t[e]];if(!i)continue;var r=e.match(x);var s=r[1],n=r[2];i=h.bind(i,this);s+=".delegateEvents"+this.cid;if(n===""){this.$el.on(s,i)}else{this.$el.on(s,n,i)}}return this},undelegateEvents:function(){this.$el.off(".delegateEvents"+this.cid);return this},_configure:function(t){if(this.options)t=h.extend({},h.result(this,"options"),t);h.extend(this,h.pick(t,E));this.options=t},_ensureElement:function(){if(!this.el){var t=h.extend({},h.result(this,"attributes"));if(this.id)t.id=h.result(this,"id");if(this.className)t["class"]=h.result(this,"className");var e=a.$("<"+h.result(this,"tagName")+">").attr(t);this.setElement(e,false)}else{this.setElement(h.result(this,"el"),false)}}});a.sync=function(t,e,i){var r=k[t];h.defaults(i||(i={}),{emulateHTTP:a.emulateHTTP,emulateJSON:a.emulateJSON});var s={type:r,dataType:"json"};if(!i.url){s.url=h.result(e,"url")||U()}if(i.data==null&&e&&(t==="create"||t==="update"||t==="patch")){s.contentType="application/json";s.data=JSON.stringify(i.attrs||e.toJSON(i))}if(i.emulateJSON){s.contentType="application/x-www-form-urlencoded";s.data=s.data?{model:s.data}:{}}if(i.emulateHTTP&&(r==="PUT"||r==="DELETE"||r==="PATCH")){s.type="POST";if(i.emulateJSON)s.data._method=r;var n=i.beforeSend;i.beforeSend=function(t){t.setRequestHeader("X-HTTP-Method-Override",r);if(n)return n.apply(this,arguments)}}if(s.type!=="GET"&&!i.emulateJSON){s.processData=false}if(s.type==="PATCH"&&window.ActiveXObject&&!(window.external&&window.external.msActiveXFilteringEnabled)){s.xhr=function(){return new ActiveXObject("Microsoft.XMLHTTP")}}var o=i.xhr=a.ajax(h.extend(s,i));e.trigger("request",e,o,i);return o};var k={create:"POST",update:"PUT",patch:"PATCH","delete":"DELETE",read:"GET"};a.ajax=function(){return a.$.ajax.apply(a.$,arguments)};var S=a.Router=function(t){t||(t={});if(t.routes)this.routes=t.routes;this._bindRoutes();this.initialize.apply(this,arguments)};var $=/\((.*?)\)/g;var T=/(\(\?)?:\w+/g;var H=/\*\w+/g;var A=/[\-{}\[\]+?.,\\\^$|#\s]/g;h.extend(S.prototype,o,{initialize:function(){},route:function(t,e,i){if(!h.isRegExp(t))t=this._routeToRegExp(t);if(h.isFunction(e)){i=e;e=""}if(!i)i=this[e];var r=this;a.history.route(t,function(s){var n=r._extractParameters(t,s);i&&i.apply(r,n);r.trigger.apply(r,["route:"+e].concat(n));r.trigger("route",e,n);a.history.trigger("route",r,e,n)});return this},navigate:function(t,e){a.history.navigate(t,e);return this},_bindRoutes:function(){if(!this.routes)return;this.routes=h.result(this,"routes");var t,e=h.keys(this.routes);while((t=e.pop())!=null){this.route(t,this.routes[t])}},_routeToRegExp:function(t){t=t.replace(A,"\\$&").replace($,"(?:$1)?").replace(T,function(t,e){return e?t:"([^/]+)"}).replace(H,"(.*?)");return new RegExp("^"+t+"$")},_extractParameters:function(t,e){var i=t.exec(e).slice(1);return h.map(i,function(t){return t?decodeURIComponent(t):null})}});var I=a.History=function(){this.handlers=[];h.bindAll(this,"checkUrl");if(typeof window!=="undefined"){this.location=window.location;this.history=window.history}};var N=/^[#\/]|\s+$/g;var P=/^\/+|\/+$/g;var O=/msie [\w.]+/;var C=/\/$/;I.started=false;h.extend(I.prototype,o,{interval:50,getHash:function(t){var e=(t||this).location.href.match(/#(.*)$/);return e?e[1]:""},getFragment:function(t,e){if(t==null){if(this._hasPushState||!this._wantsHashChange||e){t=this.location.pathname;var i=this.root.replace(C,"");if(!t.indexOf(i))t=t.substr(i.length)}else{t=this.getHash()}}return t.replace(N,"")},start:function(t){if(I.started)throw new Error("Backbone.history has already been started");I.started=true;this.options=h.extend({},{root:"/"},this.options,t);this.root=this.options.root;this._wantsHashChange=this.options.hashChange!==false;this._wantsPushState=!!this.options.pushState;this._hasPushState=!!(this.options.pushState&&this.history&&this.history.pushState);var e=this.getFragment();var i=document.documentMode;var r=O.exec(navigator.userAgent.toLowerCase())&&(!i||i<=7);this.root=("/"+this.root+"/").replace(P,"/");if(r&&this._wantsHashChange){this.iframe=a.$('<iframe src="javascript:0" tabindex="-1" />').hide().appendTo("body")[0].contentWindow;this.navigate(e)}if(this._hasPushState){a.$(window).on("popstate",this.checkUrl)}else if(this._wantsHashChange&&"onhashchange"in window&&!r){a.$(window).on("hashchange",this.checkUrl)}else if(this._wantsHashChange){this._checkUrlInterval=setInterval(this.checkUrl,this.interval)}this.fragment=e;var s=this.location;var n=s.pathname.replace(/[^\/]$/,"$&/")===this.root;if(this._wantsHashChange&&this._wantsPushState&&!this._hasPushState&&!n){this.fragment=this.getFragment(null,true);this.location.replace(this.root+this.location.search+"#"+this.fragment);return true}else if(this._wantsPushState&&this._hasPushState&&n&&s.hash){this.fragment=this.getHash().replace(N,"");this.history.replaceState({},document.title,this.root+this.fragment+s.search)}if(!this.options.silent)return this.loadUrl()},stop:function(){a.$(window).off("popstate",this.checkUrl).off("hashchange",this.checkUrl);clearInterval(this._checkUrlInterval);I.started=false},route:function(t,e){this.handlers.unshift({route:t,callback:e})},checkUrl:function(t){var e=this.getFragment();if(e===this.fragment&&this.iframe){e=this.getFragment(this.getHash(this.iframe))}if(e===this.fragment)return false;if(this.iframe)this.navigate(e);this.loadUrl()||this.loadUrl(this.getHash())},loadUrl:function(t){var e=this.fragment=this.getFragment(t);var i=h.any(this.handlers,function(t){if(t.route.test(e)){t.callback(e);return true}});return i},navigate:function(t,e){if(!I.started)return false;if(!e||e===true)e={trigger:e};t=this.getFragment(t||"");if(this.fragment===t)return;this.fragment=t;var i=this.root+t;if(this._hasPushState){this.history[e.replace?"replaceState":"pushState"]({},document.title,i)}else if(this._wantsHashChange){this._updateHash(this.location,t,e.replace);if(this.iframe&&t!==this.getFragment(this.getHash(this.iframe))){if(!e.replace)this.iframe.document.open().close();this._updateHash(this.iframe.location,t,e.replace)}}else{return this.location.assign(i)}if(e.trigger)this.loadUrl(t)},_updateHash:function(t,e,i){if(i){var r=t.href.replace(/(javascript:|#).*$/,"");t.replace(r+"#"+e)}else{t.hash="#"+e}}});a.history=new I;var j=function(t,e){var i=this;var r;if(t&&h.has(t,"constructor")){r=t.constructor}else{r=function(){return i.apply(this,arguments)}}h.extend(r,i,e);var s=function(){this.constructor=r};s.prototype=i.prototype;r.prototype=new s;if(t)h.extend(r.prototype,t);r.__super__=i.prototype;return r};d.extend=g.extend=S.extend=b.extend=I.extend=j;var U=function(){throw new Error('A "url" property or function must be specified')};var R=function(t,e){var i=e.error;e.error=function(r){if(i)i(t,r,e);t.trigger("error",t,r,e)}}}).call(this);
-/*
-//@ sourceMappingURL=backbone-min.map
-*/
\ No newline at end of file
--- a/server/python/django/renkanmanager/static/renkanmanager/lib/jquery-ui.js Fri Apr 24 13:05:09 2015 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,15008 +0,0 @@
-/*! jQuery UI - v1.10.4 - 2014-02-09
-* http://jqueryui.com
-* Includes: jquery.ui.core.js, jquery.ui.widget.js, jquery.ui.mouse.js, jquery.ui.position.js, jquery.ui.draggable.js, jquery.ui.droppable.js, jquery.ui.resizable.js, jquery.ui.selectable.js, jquery.ui.sortable.js, jquery.ui.accordion.js, jquery.ui.autocomplete.js, jquery.ui.button.js, jquery.ui.datepicker.js, jquery.ui.dialog.js, jquery.ui.menu.js, jquery.ui.progressbar.js, jquery.ui.slider.js, jquery.ui.spinner.js, jquery.ui.tabs.js, jquery.ui.tooltip.js, jquery.ui.effect.js, jquery.ui.effect-blind.js, jquery.ui.effect-bounce.js, jquery.ui.effect-clip.js, jquery.ui.effect-drop.js, jquery.ui.effect-explode.js, jquery.ui.effect-fade.js, jquery.ui.effect-fold.js, jquery.ui.effect-highlight.js, jquery.ui.effect-pulsate.js, jquery.ui.effect-scale.js, jquery.ui.effect-shake.js, jquery.ui.effect-slide.js, jquery.ui.effect-transfer.js
-* Copyright 2014 jQuery Foundation and other contributors; Licensed MIT */
-
-(function( $, undefined ) {
-
-var uuid = 0,
- runiqueId = /^ui-id-\d+$/;
-
-// $.ui might exist from components with no dependencies, e.g., $.ui.position
-$.ui = $.ui || {};
-
-$.extend( $.ui, {
- version: "1.10.4",
-
- keyCode: {
- BACKSPACE: 8,
- COMMA: 188,
- DELETE: 46,
- DOWN: 40,
- END: 35,
- ENTER: 13,
- ESCAPE: 27,
- HOME: 36,
- LEFT: 37,
- NUMPAD_ADD: 107,
- NUMPAD_DECIMAL: 110,
- NUMPAD_DIVIDE: 111,
- NUMPAD_ENTER: 108,
- NUMPAD_MULTIPLY: 106,
- NUMPAD_SUBTRACT: 109,
- PAGE_DOWN: 34,
- PAGE_UP: 33,
- PERIOD: 190,
- RIGHT: 39,
- SPACE: 32,
- TAB: 9,
- UP: 38
- }
-});
-
-// plugins
-$.fn.extend({
- focus: (function( orig ) {
- return function( delay, fn ) {
- return typeof delay === "number" ?
- this.each(function() {
- var elem = this;
- setTimeout(function() {
- $( elem ).focus();
- if ( fn ) {
- fn.call( elem );
- }
- }, delay );
- }) :
- orig.apply( this, arguments );
- };
- })( $.fn.focus ),
-
- scrollParent: function() {
- var scrollParent;
- if (($.ui.ie && (/(static|relative)/).test(this.css("position"))) || (/absolute/).test(this.css("position"))) {
- scrollParent = this.parents().filter(function() {
- return (/(relative|absolute|fixed)/).test($.css(this,"position")) && (/(auto|scroll)/).test($.css(this,"overflow")+$.css(this,"overflow-y")+$.css(this,"overflow-x"));
- }).eq(0);
- } else {
- scrollParent = this.parents().filter(function() {
- return (/(auto|scroll)/).test($.css(this,"overflow")+$.css(this,"overflow-y")+$.css(this,"overflow-x"));
- }).eq(0);
- }
-
- return (/fixed/).test(this.css("position")) || !scrollParent.length ? $(document) : scrollParent;
- },
-
- zIndex: function( zIndex ) {
- if ( zIndex !== undefined ) {
- return this.css( "zIndex", zIndex );
- }
-
- if ( this.length ) {
- var elem = $( this[ 0 ] ), position, value;
- while ( elem.length && elem[ 0 ] !== document ) {
- // Ignore z-index if position is set to a value where z-index is ignored by the browser
- // This makes behavior of this function consistent across browsers
- // WebKit always returns auto if the element is positioned
- position = elem.css( "position" );
- if ( position === "absolute" || position === "relative" || position === "fixed" ) {
- // IE returns 0 when zIndex is not specified
- // other browsers return a string
- // we ignore the case of nested elements with an explicit value of 0
- // <div style="z-index: -10;"><div style="z-index: 0;"></div></div>
- value = parseInt( elem.css( "zIndex" ), 10 );
- if ( !isNaN( value ) && value !== 0 ) {
- return value;
- }
- }
- elem = elem.parent();
- }
- }
-
- return 0;
- },
-
- uniqueId: function() {
- return this.each(function() {
- if ( !this.id ) {
- this.id = "ui-id-" + (++uuid);
- }
- });
- },
-
- removeUniqueId: function() {
- return this.each(function() {
- if ( runiqueId.test( this.id ) ) {
- $( this ).removeAttr( "id" );
- }
- });
- }
-});
-
-// selectors
-function focusable( element, isTabIndexNotNaN ) {
- var map, mapName, img,
- nodeName = element.nodeName.toLowerCase();
- if ( "area" === nodeName ) {
- map = element.parentNode;
- mapName = map.name;
- if ( !element.href || !mapName || map.nodeName.toLowerCase() !== "map" ) {
- return false;
- }
- img = $( "img[usemap=#" + mapName + "]" )[0];
- return !!img && visible( img );
- }
- return ( /input|select|textarea|button|object/.test( nodeName ) ?
- !element.disabled :
- "a" === nodeName ?
- element.href || isTabIndexNotNaN :
- isTabIndexNotNaN) &&
- // the element and all of its ancestors must be visible
- visible( element );
-}
-
-function visible( element ) {
- return $.expr.filters.visible( element ) &&
- !$( element ).parents().addBack().filter(function() {
- return $.css( this, "visibility" ) === "hidden";
- }).length;
-}
-
-$.extend( $.expr[ ":" ], {
- data: $.expr.createPseudo ?
- $.expr.createPseudo(function( dataName ) {
- return function( elem ) {
- return !!$.data( elem, dataName );
- };
- }) :
- // support: jQuery <1.8
- function( elem, i, match ) {
- return !!$.data( elem, match[ 3 ] );
- },
-
- focusable: function( element ) {
- return focusable( element, !isNaN( $.attr( element, "tabindex" ) ) );
- },
-
- tabbable: function( element ) {
- var tabIndex = $.attr( element, "tabindex" ),
- isTabIndexNaN = isNaN( tabIndex );
- return ( isTabIndexNaN || tabIndex >= 0 ) && focusable( element, !isTabIndexNaN );
- }
-});
-
-// support: jQuery <1.8
-if ( !$( "<a>" ).outerWidth( 1 ).jquery ) {
- $.each( [ "Width", "Height" ], function( i, name ) {
- var side = name === "Width" ? [ "Left", "Right" ] : [ "Top", "Bottom" ],
- type = name.toLowerCase(),
- orig = {
- innerWidth: $.fn.innerWidth,
- innerHeight: $.fn.innerHeight,
- outerWidth: $.fn.outerWidth,
- outerHeight: $.fn.outerHeight
- };
-
- function reduce( elem, size, border, margin ) {
- $.each( side, function() {
- size -= parseFloat( $.css( elem, "padding" + this ) ) || 0;
- if ( border ) {
- size -= parseFloat( $.css( elem, "border" + this + "Width" ) ) || 0;
- }
- if ( margin ) {
- size -= parseFloat( $.css( elem, "margin" + this ) ) || 0;
- }
- });
- return size;
- }
-
- $.fn[ "inner" + name ] = function( size ) {
- if ( size === undefined ) {
- return orig[ "inner" + name ].call( this );
- }
-
- return this.each(function() {
- $( this ).css( type, reduce( this, size ) + "px" );
- });
- };
-
- $.fn[ "outer" + name] = function( size, margin ) {
- if ( typeof size !== "number" ) {
- return orig[ "outer" + name ].call( this, size );
- }
-
- return this.each(function() {
- $( this).css( type, reduce( this, size, true, margin ) + "px" );
- });
- };
- });
-}
-
-// support: jQuery <1.8
-if ( !$.fn.addBack ) {
- $.fn.addBack = function( selector ) {
- return this.add( selector == null ?
- this.prevObject : this.prevObject.filter( selector )
- );
- };
-}
-
-// support: jQuery 1.6.1, 1.6.2 (http://bugs.jquery.com/ticket/9413)
-if ( $( "<a>" ).data( "a-b", "a" ).removeData( "a-b" ).data( "a-b" ) ) {
- $.fn.removeData = (function( removeData ) {
- return function( key ) {
- if ( arguments.length ) {
- return removeData.call( this, $.camelCase( key ) );
- } else {
- return removeData.call( this );
- }
- };
- })( $.fn.removeData );
-}
-
-
-
-
-
-// deprecated
-$.ui.ie = !!/msie [\w.]+/.exec( navigator.userAgent.toLowerCase() );
-
-$.support.selectstart = "onselectstart" in document.createElement( "div" );
-$.fn.extend({
- disableSelection: function() {
- return this.bind( ( $.support.selectstart ? "selectstart" : "mousedown" ) +
- ".ui-disableSelection", function( event ) {
- event.preventDefault();
- });
- },
-
- enableSelection: function() {
- return this.unbind( ".ui-disableSelection" );
- }
-});
-
-$.extend( $.ui, {
- // $.ui.plugin is deprecated. Use $.widget() extensions instead.
- plugin: {
- add: function( module, option, set ) {
- var i,
- proto = $.ui[ module ].prototype;
- for ( i in set ) {
- proto.plugins[ i ] = proto.plugins[ i ] || [];
- proto.plugins[ i ].push( [ option, set[ i ] ] );
- }
- },
- call: function( instance, name, args ) {
- var i,
- set = instance.plugins[ name ];
- if ( !set || !instance.element[ 0 ].parentNode || instance.element[ 0 ].parentNode.nodeType === 11 ) {
- return;
- }
-
- for ( i = 0; i < set.length; i++ ) {
- if ( instance.options[ set[ i ][ 0 ] ] ) {
- set[ i ][ 1 ].apply( instance.element, args );
- }
- }
- }
- },
-
- // only used by resizable
- hasScroll: function( el, a ) {
-
- //If overflow is hidden, the element might have extra content, but the user wants to hide it
- if ( $( el ).css( "overflow" ) === "hidden") {
- return false;
- }
-
- var scroll = ( a && a === "left" ) ? "scrollLeft" : "scrollTop",
- has = false;
-
- if ( el[ scroll ] > 0 ) {
- return true;
- }
-
- // TODO: determine which cases actually cause this to happen
- // if the element doesn't have the scroll set, see if it's possible to
- // set the scroll
- el[ scroll ] = 1;
- has = ( el[ scroll ] > 0 );
- el[ scroll ] = 0;
- return has;
- }
-});
-
-})( jQuery );
-(function( $, undefined ) {
-
-var uuid = 0,
- slice = Array.prototype.slice,
- _cleanData = $.cleanData;
-$.cleanData = function( elems ) {
- for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
- try {
- $( elem ).triggerHandler( "remove" );
- // http://bugs.jquery.com/ticket/8235
- } catch( e ) {}
- }
- _cleanData( elems );
-};
-
-$.widget = function( name, base, prototype ) {
- var fullName, existingConstructor, constructor, basePrototype,
- // proxiedPrototype allows the provided prototype to remain unmodified
- // so that it can be used as a mixin for multiple widgets (#8876)
- proxiedPrototype = {},
- namespace = name.split( "." )[ 0 ];
-
- name = name.split( "." )[ 1 ];
- fullName = namespace + "-" + name;
-
- if ( !prototype ) {
- prototype = base;
- base = $.Widget;
- }
-
- // create selector for plugin
- $.expr[ ":" ][ fullName.toLowerCase() ] = function( elem ) {
- return !!$.data( elem, fullName );
- };
-
- $[ namespace ] = $[ namespace ] || {};
- existingConstructor = $[ namespace ][ name ];
- constructor = $[ namespace ][ name ] = function( options, element ) {
- // allow instantiation without "new" keyword
- if ( !this._createWidget ) {
- return new constructor( options, element );
- }
-
- // allow instantiation without initializing for simple inheritance
- // must use "new" keyword (the code above always passes args)
- if ( arguments.length ) {
- this._createWidget( options, element );
- }
- };
- // extend with the existing constructor to carry over any static properties
- $.extend( constructor, existingConstructor, {
- version: prototype.version,
- // copy the object used to create the prototype in case we need to
- // redefine the widget later
- _proto: $.extend( {}, prototype ),
- // track widgets that inherit from this widget in case this widget is
- // redefined after a widget inherits from it
- _childConstructors: []
- });
-
- basePrototype = new base();
- // we need to make the options hash a property directly on the new instance
- // otherwise we'll modify the options hash on the prototype that we're
- // inheriting from
- basePrototype.options = $.widget.extend( {}, basePrototype.options );
- $.each( prototype, function( prop, value ) {
- if ( !$.isFunction( value ) ) {
- proxiedPrototype[ prop ] = value;
- return;
- }
- proxiedPrototype[ prop ] = (function() {
- var _super = function() {
- return base.prototype[ prop ].apply( this, arguments );
- },
- _superApply = function( args ) {
- return base.prototype[ prop ].apply( this, args );
- };
- return function() {
- var __super = this._super,
- __superApply = this._superApply,
- returnValue;
-
- this._super = _super;
- this._superApply = _superApply;
-
- returnValue = value.apply( this, arguments );
-
- this._super = __super;
- this._superApply = __superApply;
-
- return returnValue;
- };
- })();
- });
- constructor.prototype = $.widget.extend( basePrototype, {
- // TODO: remove support for widgetEventPrefix
- // always use the name + a colon as the prefix, e.g., draggable:start
- // don't prefix for widgets that aren't DOM-based
- widgetEventPrefix: existingConstructor ? (basePrototype.widgetEventPrefix || name) : name
- }, proxiedPrototype, {
- constructor: constructor,
- namespace: namespace,
- widgetName: name,
- widgetFullName: fullName
- });
-
- // If this widget is being redefined then we need to find all widgets that
- // are inheriting from it and redefine all of them so that they inherit from
- // the new version of this widget. We're essentially trying to replace one
- // level in the prototype chain.
- if ( existingConstructor ) {
- $.each( existingConstructor._childConstructors, function( i, child ) {
- var childPrototype = child.prototype;
-
- // redefine the child widget using the same prototype that was
- // originally used, but inherit from the new version of the base
- $.widget( childPrototype.namespace + "." + childPrototype.widgetName, constructor, child._proto );
- });
- // remove the list of existing child constructors from the old constructor
- // so the old child constructors can be garbage collected
- delete existingConstructor._childConstructors;
- } else {
- base._childConstructors.push( constructor );
- }
-
- $.widget.bridge( name, constructor );
-};
-
-$.widget.extend = function( target ) {
- var input = slice.call( arguments, 1 ),
- inputIndex = 0,
- inputLength = input.length,
- key,
- value;
- for ( ; inputIndex < inputLength; inputIndex++ ) {
- for ( key in input[ inputIndex ] ) {
- value = input[ inputIndex ][ key ];
- if ( input[ inputIndex ].hasOwnProperty( key ) && value !== undefined ) {
- // Clone objects
- if ( $.isPlainObject( value ) ) {
- target[ key ] = $.isPlainObject( target[ key ] ) ?
- $.widget.extend( {}, target[ key ], value ) :
- // Don't extend strings, arrays, etc. with objects
- $.widget.extend( {}, value );
- // Copy everything else by reference
- } else {
- target[ key ] = value;
- }
- }
- }
- }
- return target;
-};
-
-$.widget.bridge = function( name, object ) {
- var fullName = object.prototype.widgetFullName || name;
- $.fn[ name ] = function( options ) {
- var isMethodCall = typeof options === "string",
- args = slice.call( arguments, 1 ),
- returnValue = this;
-
- // allow multiple hashes to be passed on init
- options = !isMethodCall && args.length ?
- $.widget.extend.apply( null, [ options ].concat(args) ) :
- options;
-
- if ( isMethodCall ) {
- this.each(function() {
- var methodValue,
- instance = $.data( this, fullName );
- if ( !instance ) {
- return $.error( "cannot call methods on " + name + " prior to initialization; " +
- "attempted to call method '" + options + "'" );
- }
- if ( !$.isFunction( instance[options] ) || options.charAt( 0 ) === "_" ) {
- return $.error( "no such method '" + options + "' for " + name + " widget instance" );
- }
- methodValue = instance[ options ].apply( instance, args );
- if ( methodValue !== instance && methodValue !== undefined ) {
- returnValue = methodValue && methodValue.jquery ?
- returnValue.pushStack( methodValue.get() ) :
- methodValue;
- return false;
- }
- });
- } else {
- this.each(function() {
- var instance = $.data( this, fullName );
- if ( instance ) {
- instance.option( options || {} )._init();
- } else {
- $.data( this, fullName, new object( options, this ) );
- }
- });
- }
-
- return returnValue;
- };
-};
-
-$.Widget = function( /* options, element */ ) {};
-$.Widget._childConstructors = [];
-
-$.Widget.prototype = {
- widgetName: "widget",
- widgetEventPrefix: "",
- defaultElement: "<div>",
- options: {
- disabled: false,
-
- // callbacks
- create: null
- },
- _createWidget: function( options, element ) {
- element = $( element || this.defaultElement || this )[ 0 ];
- this.element = $( element );
- this.uuid = uuid++;
- this.eventNamespace = "." + this.widgetName + this.uuid;
- this.options = $.widget.extend( {},
- this.options,
- this._getCreateOptions(),
- options );
-
- this.bindings = $();
- this.hoverable = $();
- this.focusable = $();
-
- if ( element !== this ) {
- $.data( element, this.widgetFullName, this );
- this._on( true, this.element, {
- remove: function( event ) {
- if ( event.target === element ) {
- this.destroy();
- }
- }
- });
- this.document = $( element.style ?
- // element within the document
- element.ownerDocument :
- // element is window or document
- element.document || element );
- this.window = $( this.document[0].defaultView || this.document[0].parentWindow );
- }
-
- this._create();
- this._trigger( "create", null, this._getCreateEventData() );
- this._init();
- },
- _getCreateOptions: $.noop,
- _getCreateEventData: $.noop,
- _create: $.noop,
- _init: $.noop,
-
- destroy: function() {
- this._destroy();
- // we can probably remove the unbind calls in 2.0
- // all event bindings should go through this._on()
- this.element
- .unbind( this.eventNamespace )
- // 1.9 BC for #7810
- // TODO remove dual storage
- .removeData( this.widgetName )
- .removeData( this.widgetFullName )
- // support: jquery <1.6.3
- // http://bugs.jquery.com/ticket/9413
- .removeData( $.camelCase( this.widgetFullName ) );
- this.widget()
- .unbind( this.eventNamespace )
- .removeAttr( "aria-disabled" )
- .removeClass(
- this.widgetFullName + "-disabled " +
- "ui-state-disabled" );
-
- // clean up events and states
- this.bindings.unbind( this.eventNamespace );
- this.hoverable.removeClass( "ui-state-hover" );
- this.focusable.removeClass( "ui-state-focus" );
- },
- _destroy: $.noop,
-
- widget: function() {
- return this.element;
- },
-
- option: function( key, value ) {
- var options = key,
- parts,
- curOption,
- i;
-
- if ( arguments.length === 0 ) {
- // don't return a reference to the internal hash
- return $.widget.extend( {}, this.options );
- }
-
- if ( typeof key === "string" ) {
- // handle nested keys, e.g., "foo.bar" => { foo: { bar: ___ } }
- options = {};
- parts = key.split( "." );
- key = parts.shift();
- if ( parts.length ) {
- curOption = options[ key ] = $.widget.extend( {}, this.options[ key ] );
- for ( i = 0; i < parts.length - 1; i++ ) {
- curOption[ parts[ i ] ] = curOption[ parts[ i ] ] || {};
- curOption = curOption[ parts[ i ] ];
- }
- key = parts.pop();
- if ( arguments.length === 1 ) {
- return curOption[ key ] === undefined ? null : curOption[ key ];
- }
- curOption[ key ] = value;
- } else {
- if ( arguments.length === 1 ) {
- return this.options[ key ] === undefined ? null : this.options[ key ];
- }
- options[ key ] = value;
- }
- }
-
- this._setOptions( options );
-
- return this;
- },
- _setOptions: function( options ) {
- var key;
-
- for ( key in options ) {
- this._setOption( key, options[ key ] );
- }
-
- return this;
- },
- _setOption: function( key, value ) {
- this.options[ key ] = value;
-
- if ( key === "disabled" ) {
- this.widget()
- .toggleClass( this.widgetFullName + "-disabled ui-state-disabled", !!value )
- .attr( "aria-disabled", value );
- this.hoverable.removeClass( "ui-state-hover" );
- this.focusable.removeClass( "ui-state-focus" );
- }
-
- return this;
- },
-
- enable: function() {
- return this._setOption( "disabled", false );
- },
- disable: function() {
- return this._setOption( "disabled", true );
- },
-
- _on: function( suppressDisabledCheck, element, handlers ) {
- var delegateElement,
- instance = this;
-
- // no suppressDisabledCheck flag, shuffle arguments
- if ( typeof suppressDisabledCheck !== "boolean" ) {
- handlers = element;
- element = suppressDisabledCheck;
- suppressDisabledCheck = false;
- }
-
- // no element argument, shuffle and use this.element
- if ( !handlers ) {
- handlers = element;
- element = this.element;
- delegateElement = this.widget();
- } else {
- // accept selectors, DOM elements
- element = delegateElement = $( element );
- this.bindings = this.bindings.add( element );
- }
-
- $.each( handlers, function( event, handler ) {
- function handlerProxy() {
- // allow widgets to customize the disabled handling
- // - disabled as an array instead of boolean
- // - disabled class as method for disabling individual parts
- if ( !suppressDisabledCheck &&
- ( instance.options.disabled === true ||
- $( this ).hasClass( "ui-state-disabled" ) ) ) {
- return;
- }
- return ( typeof handler === "string" ? instance[ handler ] : handler )
- .apply( instance, arguments );
- }
-
- // copy the guid so direct unbinding works
- if ( typeof handler !== "string" ) {
- handlerProxy.guid = handler.guid =
- handler.guid || handlerProxy.guid || $.guid++;
- }
-
- var match = event.match( /^(\w+)\s*(.*)$/ ),
- eventName = match[1] + instance.eventNamespace,
- selector = match[2];
- if ( selector ) {
- delegateElement.delegate( selector, eventName, handlerProxy );
- } else {
- element.bind( eventName, handlerProxy );
- }
- });
- },
-
- _off: function( element, eventName ) {
- eventName = (eventName || "").split( " " ).join( this.eventNamespace + " " ) + this.eventNamespace;
- element.unbind( eventName ).undelegate( eventName );
- },
-
- _delay: function( handler, delay ) {
- function handlerProxy() {
- return ( typeof handler === "string" ? instance[ handler ] : handler )
- .apply( instance, arguments );
- }
- var instance = this;
- return setTimeout( handlerProxy, delay || 0 );
- },
-
- _hoverable: function( element ) {
- this.hoverable = this.hoverable.add( element );
- this._on( element, {
- mouseenter: function( event ) {
- $( event.currentTarget ).addClass( "ui-state-hover" );
- },
- mouseleave: function( event ) {
- $( event.currentTarget ).removeClass( "ui-state-hover" );
- }
- });
- },
-
- _focusable: function( element ) {
- this.focusable = this.focusable.add( element );
- this._on( element, {
- focusin: function( event ) {
- $( event.currentTarget ).addClass( "ui-state-focus" );
- },
- focusout: function( event ) {
- $( event.currentTarget ).removeClass( "ui-state-focus" );
- }
- });
- },
-
- _trigger: function( type, event, data ) {
- var prop, orig,
- callback = this.options[ type ];
-
- data = data || {};
- event = $.Event( event );
- event.type = ( type === this.widgetEventPrefix ?
- type :
- this.widgetEventPrefix + type ).toLowerCase();
- // the original event may come from any element
- // so we need to reset the target on the new event
- event.target = this.element[ 0 ];
-
- // copy original event properties over to the new event
- orig = event.originalEvent;
- if ( orig ) {
- for ( prop in orig ) {
- if ( !( prop in event ) ) {
- event[ prop ] = orig[ prop ];
- }
- }
- }
-
- this.element.trigger( event, data );
- return !( $.isFunction( callback ) &&
- callback.apply( this.element[0], [ event ].concat( data ) ) === false ||
- event.isDefaultPrevented() );
- }
-};
-
-$.each( { show: "fadeIn", hide: "fadeOut" }, function( method, defaultEffect ) {
- $.Widget.prototype[ "_" + method ] = function( element, options, callback ) {
- if ( typeof options === "string" ) {
- options = { effect: options };
- }
- var hasOptions,
- effectName = !options ?
- method :
- options === true || typeof options === "number" ?
- defaultEffect :
- options.effect || defaultEffect;
- options = options || {};
- if ( typeof options === "number" ) {
- options = { duration: options };
- }
- hasOptions = !$.isEmptyObject( options );
- options.complete = callback;
- if ( options.delay ) {
- element.delay( options.delay );
- }
- if ( hasOptions && $.effects && $.effects.effect[ effectName ] ) {
- element[ method ]( options );
- } else if ( effectName !== method && element[ effectName ] ) {
- element[ effectName ]( options.duration, options.easing, callback );
- } else {
- element.queue(function( next ) {
- $( this )[ method ]();
- if ( callback ) {
- callback.call( element[ 0 ] );
- }
- next();
- });
- }
- };
-});
-
-})( jQuery );
-(function( $, undefined ) {
-
-var mouseHandled = false;
-$( document ).mouseup( function() {
- mouseHandled = false;
-});
-
-$.widget("ui.mouse", {
- version: "1.10.4",
- options: {
- cancel: "input,textarea,button,select,option",
- distance: 1,
- delay: 0
- },
- _mouseInit: function() {
- var that = this;
-
- this.element
- .bind("mousedown."+this.widgetName, function(event) {
- return that._mouseDown(event);
- })
- .bind("click."+this.widgetName, function(event) {
- if (true === $.data(event.target, that.widgetName + ".preventClickEvent")) {
- $.removeData(event.target, that.widgetName + ".preventClickEvent");
- event.stopImmediatePropagation();
- return false;
- }
- });
-
- this.started = false;
- },
-
- // TODO: make sure destroying one instance of mouse doesn't mess with
- // other instances of mouse
- _mouseDestroy: function() {
- this.element.unbind("."+this.widgetName);
- if ( this._mouseMoveDelegate ) {
- $(document)
- .unbind("mousemove."+this.widgetName, this._mouseMoveDelegate)
- .unbind("mouseup."+this.widgetName, this._mouseUpDelegate);
- }
- },
-
- _mouseDown: function(event) {
- // don't let more than one widget handle mouseStart
- if( mouseHandled ) { return; }
-
- // we may have missed mouseup (out of window)
- (this._mouseStarted && this._mouseUp(event));
-
- this._mouseDownEvent = event;
-
- var that = this,
- btnIsLeft = (event.which === 1),
- // event.target.nodeName works around a bug in IE 8 with
- // disabled inputs (#7620)
- elIsCancel = (typeof this.options.cancel === "string" && event.target.nodeName ? $(event.target).closest(this.options.cancel).length : false);
- if (!btnIsLeft || elIsCancel || !this._mouseCapture(event)) {
- return true;
- }
-
- this.mouseDelayMet = !this.options.delay;
- if (!this.mouseDelayMet) {
- this._mouseDelayTimer = setTimeout(function() {
- that.mouseDelayMet = true;
- }, this.options.delay);
- }
-
- if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) {
- this._mouseStarted = (this._mouseStart(event) !== false);
- if (!this._mouseStarted) {
- event.preventDefault();
- return true;
- }
- }
-
- // Click event may never have fired (Gecko & Opera)
- if (true === $.data(event.target, this.widgetName + ".preventClickEvent")) {
- $.removeData(event.target, this.widgetName + ".preventClickEvent");
- }
-
- // these delegates are required to keep context
- this._mouseMoveDelegate = function(event) {
- return that._mouseMove(event);
- };
- this._mouseUpDelegate = function(event) {
- return that._mouseUp(event);
- };
- $(document)
- .bind("mousemove."+this.widgetName, this._mouseMoveDelegate)
- .bind("mouseup."+this.widgetName, this._mouseUpDelegate);
-
- event.preventDefault();
-
- mouseHandled = true;
- return true;
- },
-
- _mouseMove: function(event) {
- // IE mouseup check - mouseup happened when mouse was out of window
- if ($.ui.ie && ( !document.documentMode || document.documentMode < 9 ) && !event.button) {
- return this._mouseUp(event);
- }
-
- if (this._mouseStarted) {
- this._mouseDrag(event);
- return event.preventDefault();
- }
-
- if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) {
- this._mouseStarted =
- (this._mouseStart(this._mouseDownEvent, event) !== false);
- (this._mouseStarted ? this._mouseDrag(event) : this._mouseUp(event));
- }
-
- return !this._mouseStarted;
- },
-
- _mouseUp: function(event) {
- $(document)
- .unbind("mousemove."+this.widgetName, this._mouseMoveDelegate)
- .unbind("mouseup."+this.widgetName, this._mouseUpDelegate);
-
- if (this._mouseStarted) {
- this._mouseStarted = false;
-
- if (event.target === this._mouseDownEvent.target) {
- $.data(event.target, this.widgetName + ".preventClickEvent", true);
- }
-
- this._mouseStop(event);
- }
-
- return false;
- },
-
- _mouseDistanceMet: function(event) {
- return (Math.max(
- Math.abs(this._mouseDownEvent.pageX - event.pageX),
- Math.abs(this._mouseDownEvent.pageY - event.pageY)
- ) >= this.options.distance
- );
- },
-
- _mouseDelayMet: function(/* event */) {
- return this.mouseDelayMet;
- },
-
- // These are placeholder methods, to be overriden by extending plugin
- _mouseStart: function(/* event */) {},
- _mouseDrag: function(/* event */) {},
- _mouseStop: function(/* event */) {},
- _mouseCapture: function(/* event */) { return true; }
-});
-
-})(jQuery);
-(function( $, undefined ) {
-
-$.ui = $.ui || {};
-
-var cachedScrollbarWidth,
- max = Math.max,
- abs = Math.abs,
- round = Math.round,
- rhorizontal = /left|center|right/,
- rvertical = /top|center|bottom/,
- roffset = /[\+\-]\d+(\.[\d]+)?%?/,
- rposition = /^\w+/,
- rpercent = /%$/,
- _position = $.fn.position;
-
-function getOffsets( offsets, width, height ) {
- return [
- parseFloat( offsets[ 0 ] ) * ( rpercent.test( offsets[ 0 ] ) ? width / 100 : 1 ),
- parseFloat( offsets[ 1 ] ) * ( rpercent.test( offsets[ 1 ] ) ? height / 100 : 1 )
- ];
-}
-
-function parseCss( element, property ) {
- return parseInt( $.css( element, property ), 10 ) || 0;
-}
-
-function getDimensions( elem ) {
- var raw = elem[0];
- if ( raw.nodeType === 9 ) {
- return {
- width: elem.width(),
- height: elem.height(),
- offset: { top: 0, left: 0 }
- };
- }
- if ( $.isWindow( raw ) ) {
- return {
- width: elem.width(),
- height: elem.height(),
- offset: { top: elem.scrollTop(), left: elem.scrollLeft() }
- };
- }
- if ( raw.preventDefault ) {
- return {
- width: 0,
- height: 0,
- offset: { top: raw.pageY, left: raw.pageX }
- };
- }
- return {
- width: elem.outerWidth(),
- height: elem.outerHeight(),
- offset: elem.offset()
- };
-}
-
-$.position = {
- scrollbarWidth: function() {
- if ( cachedScrollbarWidth !== undefined ) {
- return cachedScrollbarWidth;
- }
- var w1, w2,
- div = $( "<div style='display:block;position:absolute;width:50px;height:50px;overflow:hidden;'><div style='height:100px;width:auto;'></div></div>" ),
- innerDiv = div.children()[0];
-
- $( "body" ).append( div );
- w1 = innerDiv.offsetWidth;
- div.css( "overflow", "scroll" );
-
- w2 = innerDiv.offsetWidth;
-
- if ( w1 === w2 ) {
- w2 = div[0].clientWidth;
- }
-
- div.remove();
-
- return (cachedScrollbarWidth = w1 - w2);
- },
- getScrollInfo: function( within ) {
- var overflowX = within.isWindow || within.isDocument ? "" :
- within.element.css( "overflow-x" ),
- overflowY = within.isWindow || within.isDocument ? "" :
- within.element.css( "overflow-y" ),
- hasOverflowX = overflowX === "scroll" ||
- ( overflowX === "auto" && within.width < within.element[0].scrollWidth ),
- hasOverflowY = overflowY === "scroll" ||
- ( overflowY === "auto" && within.height < within.element[0].scrollHeight );
- return {
- width: hasOverflowY ? $.position.scrollbarWidth() : 0,
- height: hasOverflowX ? $.position.scrollbarWidth() : 0
- };
- },
- getWithinInfo: function( element ) {
- var withinElement = $( element || window ),
- isWindow = $.isWindow( withinElement[0] ),
- isDocument = !!withinElement[ 0 ] && withinElement[ 0 ].nodeType === 9;
- return {
- element: withinElement,
- isWindow: isWindow,
- isDocument: isDocument,
- offset: withinElement.offset() || { left: 0, top: 0 },
- scrollLeft: withinElement.scrollLeft(),
- scrollTop: withinElement.scrollTop(),
- width: isWindow ? withinElement.width() : withinElement.outerWidth(),
- height: isWindow ? withinElement.height() : withinElement.outerHeight()
- };
- }
-};
-
-$.fn.position = function( options ) {
- if ( !options || !options.of ) {
- return _position.apply( this, arguments );
- }
-
- // make a copy, we don't want to modify arguments
- options = $.extend( {}, options );
-
- var atOffset, targetWidth, targetHeight, targetOffset, basePosition, dimensions,
- target = $( options.of ),
- within = $.position.getWithinInfo( options.within ),
- scrollInfo = $.position.getScrollInfo( within ),
- collision = ( options.collision || "flip" ).split( " " ),
- offsets = {};
-
- dimensions = getDimensions( target );
- if ( target[0].preventDefault ) {
- // force left top to allow flipping
- options.at = "left top";
- }
- targetWidth = dimensions.width;
- targetHeight = dimensions.height;
- targetOffset = dimensions.offset;
- // clone to reuse original targetOffset later
- basePosition = $.extend( {}, targetOffset );
-
- // force my and at to have valid horizontal and vertical positions
- // if a value is missing or invalid, it will be converted to center
- $.each( [ "my", "at" ], function() {
- var pos = ( options[ this ] || "" ).split( " " ),
- horizontalOffset,
- verticalOffset;
-
- if ( pos.length === 1) {
- pos = rhorizontal.test( pos[ 0 ] ) ?
- pos.concat( [ "center" ] ) :
- rvertical.test( pos[ 0 ] ) ?
- [ "center" ].concat( pos ) :
- [ "center", "center" ];
- }
- pos[ 0 ] = rhorizontal.test( pos[ 0 ] ) ? pos[ 0 ] : "center";
- pos[ 1 ] = rvertical.test( pos[ 1 ] ) ? pos[ 1 ] : "center";
-
- // calculate offsets
- horizontalOffset = roffset.exec( pos[ 0 ] );
- verticalOffset = roffset.exec( pos[ 1 ] );
- offsets[ this ] = [
- horizontalOffset ? horizontalOffset[ 0 ] : 0,
- verticalOffset ? verticalOffset[ 0 ] : 0
- ];
-
- // reduce to just the positions without the offsets
- options[ this ] = [
- rposition.exec( pos[ 0 ] )[ 0 ],
- rposition.exec( pos[ 1 ] )[ 0 ]
- ];
- });
-
- // normalize collision option
- if ( collision.length === 1 ) {
- collision[ 1 ] = collision[ 0 ];
- }
-
- if ( options.at[ 0 ] === "right" ) {
- basePosition.left += targetWidth;
- } else if ( options.at[ 0 ] === "center" ) {
- basePosition.left += targetWidth / 2;
- }
-
- if ( options.at[ 1 ] === "bottom" ) {
- basePosition.top += targetHeight;
- } else if ( options.at[ 1 ] === "center" ) {
- basePosition.top += targetHeight / 2;
- }
-
- atOffset = getOffsets( offsets.at, targetWidth, targetHeight );
- basePosition.left += atOffset[ 0 ];
- basePosition.top += atOffset[ 1 ];
-
- return this.each(function() {
- var collisionPosition, using,
- elem = $( this ),
- elemWidth = elem.outerWidth(),
- elemHeight = elem.outerHeight(),
- marginLeft = parseCss( this, "marginLeft" ),
- marginTop = parseCss( this, "marginTop" ),
- collisionWidth = elemWidth + marginLeft + parseCss( this, "marginRight" ) + scrollInfo.width,
- collisionHeight = elemHeight + marginTop + parseCss( this, "marginBottom" ) + scrollInfo.height,
- position = $.extend( {}, basePosition ),
- myOffset = getOffsets( offsets.my, elem.outerWidth(), elem.outerHeight() );
-
- if ( options.my[ 0 ] === "right" ) {
- position.left -= elemWidth;
- } else if ( options.my[ 0 ] === "center" ) {
- position.left -= elemWidth / 2;
- }
-
- if ( options.my[ 1 ] === "bottom" ) {
- position.top -= elemHeight;
- } else if ( options.my[ 1 ] === "center" ) {
- position.top -= elemHeight / 2;
- }
-
- position.left += myOffset[ 0 ];
- position.top += myOffset[ 1 ];
-
- // if the browser doesn't support fractions, then round for consistent results
- if ( !$.support.offsetFractions ) {
- position.left = round( position.left );
- position.top = round( position.top );
- }
-
- collisionPosition = {
- marginLeft: marginLeft,
- marginTop: marginTop
- };
-
- $.each( [ "left", "top" ], function( i, dir ) {
- if ( $.ui.position[ collision[ i ] ] ) {
- $.ui.position[ collision[ i ] ][ dir ]( position, {
- targetWidth: targetWidth,
- targetHeight: targetHeight,
- elemWidth: elemWidth,
- elemHeight: elemHeight,
- collisionPosition: collisionPosition,
- collisionWidth: collisionWidth,
- collisionHeight: collisionHeight,
- offset: [ atOffset[ 0 ] + myOffset[ 0 ], atOffset [ 1 ] + myOffset[ 1 ] ],
- my: options.my,
- at: options.at,
- within: within,
- elem : elem
- });
- }
- });
-
- if ( options.using ) {
- // adds feedback as second argument to using callback, if present
- using = function( props ) {
- var left = targetOffset.left - position.left,
- right = left + targetWidth - elemWidth,
- top = targetOffset.top - position.top,
- bottom = top + targetHeight - elemHeight,
- feedback = {
- target: {
- element: target,
- left: targetOffset.left,
- top: targetOffset.top,
- width: targetWidth,
- height: targetHeight
- },
- element: {
- element: elem,
- left: position.left,
- top: position.top,
- width: elemWidth,
- height: elemHeight
- },
- horizontal: right < 0 ? "left" : left > 0 ? "right" : "center",
- vertical: bottom < 0 ? "top" : top > 0 ? "bottom" : "middle"
- };
- if ( targetWidth < elemWidth && abs( left + right ) < targetWidth ) {
- feedback.horizontal = "center";
- }
- if ( targetHeight < elemHeight && abs( top + bottom ) < targetHeight ) {
- feedback.vertical = "middle";
- }
- if ( max( abs( left ), abs( right ) ) > max( abs( top ), abs( bottom ) ) ) {
- feedback.important = "horizontal";
- } else {
- feedback.important = "vertical";
- }
- options.using.call( this, props, feedback );
- };
- }
-
- elem.offset( $.extend( position, { using: using } ) );
- });
-};
-
-$.ui.position = {
- fit: {
- left: function( position, data ) {
- var within = data.within,
- withinOffset = within.isWindow ? within.scrollLeft : within.offset.left,
- outerWidth = within.width,
- collisionPosLeft = position.left - data.collisionPosition.marginLeft,
- overLeft = withinOffset - collisionPosLeft,
- overRight = collisionPosLeft + data.collisionWidth - outerWidth - withinOffset,
- newOverRight;
-
- // element is wider than within
- if ( data.collisionWidth > outerWidth ) {
- // element is initially over the left side of within
- if ( overLeft > 0 && overRight <= 0 ) {
- newOverRight = position.left + overLeft + data.collisionWidth - outerWidth - withinOffset;
- position.left += overLeft - newOverRight;
- // element is initially over right side of within
- } else if ( overRight > 0 && overLeft <= 0 ) {
- position.left = withinOffset;
- // element is initially over both left and right sides of within
- } else {
- if ( overLeft > overRight ) {
- position.left = withinOffset + outerWidth - data.collisionWidth;
- } else {
- position.left = withinOffset;
- }
- }
- // too far left -> align with left edge
- } else if ( overLeft > 0 ) {
- position.left += overLeft;
- // too far right -> align with right edge
- } else if ( overRight > 0 ) {
- position.left -= overRight;
- // adjust based on position and margin
- } else {
- position.left = max( position.left - collisionPosLeft, position.left );
- }
- },
- top: function( position, data ) {
- var within = data.within,
- withinOffset = within.isWindow ? within.scrollTop : within.offset.top,
- outerHeight = data.within.height,
- collisionPosTop = position.top - data.collisionPosition.marginTop,
- overTop = withinOffset - collisionPosTop,
- overBottom = collisionPosTop + data.collisionHeight - outerHeight - withinOffset,
- newOverBottom;
-
- // element is taller than within
- if ( data.collisionHeight > outerHeight ) {
- // element is initially over the top of within
- if ( overTop > 0 && overBottom <= 0 ) {
- newOverBottom = position.top + overTop + data.collisionHeight - outerHeight - withinOffset;
- position.top += overTop - newOverBottom;
- // element is initially over bottom of within
- } else if ( overBottom > 0 && overTop <= 0 ) {
- position.top = withinOffset;
- // element is initially over both top and bottom of within
- } else {
- if ( overTop > overBottom ) {
- position.top = withinOffset + outerHeight - data.collisionHeight;
- } else {
- position.top = withinOffset;
- }
- }
- // too far up -> align with top
- } else if ( overTop > 0 ) {
- position.top += overTop;
- // too far down -> align with bottom edge
- } else if ( overBottom > 0 ) {
- position.top -= overBottom;
- // adjust based on position and margin
- } else {
- position.top = max( position.top - collisionPosTop, position.top );
- }
- }
- },
- flip: {
- left: function( position, data ) {
- var within = data.within,
- withinOffset = within.offset.left + within.scrollLeft,
- outerWidth = within.width,
- offsetLeft = within.isWindow ? within.scrollLeft : within.offset.left,
- collisionPosLeft = position.left - data.collisionPosition.marginLeft,
- overLeft = collisionPosLeft - offsetLeft,
- overRight = collisionPosLeft + data.collisionWidth - outerWidth - offsetLeft,
- myOffset = data.my[ 0 ] === "left" ?
- -data.elemWidth :
- data.my[ 0 ] === "right" ?
- data.elemWidth :
- 0,
- atOffset = data.at[ 0 ] === "left" ?
- data.targetWidth :
- data.at[ 0 ] === "right" ?
- -data.targetWidth :
- 0,
- offset = -2 * data.offset[ 0 ],
- newOverRight,
- newOverLeft;
-
- if ( overLeft < 0 ) {
- newOverRight = position.left + myOffset + atOffset + offset + data.collisionWidth - outerWidth - withinOffset;
- if ( newOverRight < 0 || newOverRight < abs( overLeft ) ) {
- position.left += myOffset + atOffset + offset;
- }
- }
- else if ( overRight > 0 ) {
- newOverLeft = position.left - data.collisionPosition.marginLeft + myOffset + atOffset + offset - offsetLeft;
- if ( newOverLeft > 0 || abs( newOverLeft ) < overRight ) {
- position.left += myOffset + atOffset + offset;
- }
- }
- },
- top: function( position, data ) {
- var within = data.within,
- withinOffset = within.offset.top + within.scrollTop,
- outerHeight = within.height,
- offsetTop = within.isWindow ? within.scrollTop : within.offset.top,
- collisionPosTop = position.top - data.collisionPosition.marginTop,
- overTop = collisionPosTop - offsetTop,
- overBottom = collisionPosTop + data.collisionHeight - outerHeight - offsetTop,
- top = data.my[ 1 ] === "top",
- myOffset = top ?
- -data.elemHeight :
- data.my[ 1 ] === "bottom" ?
- data.elemHeight :
- 0,
- atOffset = data.at[ 1 ] === "top" ?
- data.targetHeight :
- data.at[ 1 ] === "bottom" ?
- -data.targetHeight :
- 0,
- offset = -2 * data.offset[ 1 ],
- newOverTop,
- newOverBottom;
- if ( overTop < 0 ) {
- newOverBottom = position.top + myOffset + atOffset + offset + data.collisionHeight - outerHeight - withinOffset;
- if ( ( position.top + myOffset + atOffset + offset) > overTop && ( newOverBottom < 0 || newOverBottom < abs( overTop ) ) ) {
- position.top += myOffset + atOffset + offset;
- }
- }
- else if ( overBottom > 0 ) {
- newOverTop = position.top - data.collisionPosition.marginTop + myOffset + atOffset + offset - offsetTop;
- if ( ( position.top + myOffset + atOffset + offset) > overBottom && ( newOverTop > 0 || abs( newOverTop ) < overBottom ) ) {
- position.top += myOffset + atOffset + offset;
- }
- }
- }
- },
- flipfit: {
- left: function() {
- $.ui.position.flip.left.apply( this, arguments );
- $.ui.position.fit.left.apply( this, arguments );
- },
- top: function() {
- $.ui.position.flip.top.apply( this, arguments );
- $.ui.position.fit.top.apply( this, arguments );
- }
- }
-};
-
-// fraction support test
-(function () {
- var testElement, testElementParent, testElementStyle, offsetLeft, i,
- body = document.getElementsByTagName( "body" )[ 0 ],
- div = document.createElement( "div" );
-
- //Create a "fake body" for testing based on method used in jQuery.support
- testElement = document.createElement( body ? "div" : "body" );
- testElementStyle = {
- visibility: "hidden",
- width: 0,
- height: 0,
- border: 0,
- margin: 0,
- background: "none"
- };
- if ( body ) {
- $.extend( testElementStyle, {
- position: "absolute",
- left: "-1000px",
- top: "-1000px"
- });
- }
- for ( i in testElementStyle ) {
- testElement.style[ i ] = testElementStyle[ i ];
- }
- testElement.appendChild( div );
- testElementParent = body || document.documentElement;
- testElementParent.insertBefore( testElement, testElementParent.firstChild );
-
- div.style.cssText = "position: absolute; left: 10.7432222px;";
-
- offsetLeft = $( div ).offset().left;
- $.support.offsetFractions = offsetLeft > 10 && offsetLeft < 11;
-
- testElement.innerHTML = "";
- testElementParent.removeChild( testElement );
-})();
-
-}( jQuery ) );
-(function( $, undefined ) {
-
-$.widget("ui.draggable", $.ui.mouse, {
- version: "1.10.4",
- widgetEventPrefix: "drag",
- options: {
- addClasses: true,
- appendTo: "parent",
- axis: false,
- connectToSortable: false,
- containment: false,
- cursor: "auto",
- cursorAt: false,
- grid: false,
- handle: false,
- helper: "original",
- iframeFix: false,
- opacity: false,
- refreshPositions: false,
- revert: false,
- revertDuration: 500,
- scope: "default",
- scroll: true,
- scrollSensitivity: 20,
- scrollSpeed: 20,
- snap: false,
- snapMode: "both",
- snapTolerance: 20,
- stack: false,
- zIndex: false,
-
- // callbacks
- drag: null,
- start: null,
- stop: null
- },
- _create: function() {
-
- if (this.options.helper === "original" && !(/^(?:r|a|f)/).test(this.element.css("position"))) {
- this.element[0].style.position = "relative";
- }
- if (this.options.addClasses){
- this.element.addClass("ui-draggable");
- }
- if (this.options.disabled){
- this.element.addClass("ui-draggable-disabled");
- }
-
- this._mouseInit();
-
- },
-
- _destroy: function() {
- this.element.removeClass( "ui-draggable ui-draggable-dragging ui-draggable-disabled" );
- this._mouseDestroy();
- },
-
- _mouseCapture: function(event) {
-
- var o = this.options;
-
- // among others, prevent a drag on a resizable-handle
- if (this.helper || o.disabled || $(event.target).closest(".ui-resizable-handle").length > 0) {
- return false;
- }
-
- //Quit if we're not on a valid handle
- this.handle = this._getHandle(event);
- if (!this.handle) {
- return false;
- }
-
- $(o.iframeFix === true ? "iframe" : o.iframeFix).each(function() {
- $("<div class='ui-draggable-iframeFix' style='background: #fff;'></div>")
- .css({
- width: this.offsetWidth+"px", height: this.offsetHeight+"px",
- position: "absolute", opacity: "0.001", zIndex: 1000
- })
- .css($(this).offset())
- .appendTo("body");
- });
-
- return true;
-
- },
-
- _mouseStart: function(event) {
-
- var o = this.options;
-
- //Create and append the visible helper
- this.helper = this._createHelper(event);
-
- this.helper.addClass("ui-draggable-dragging");
-
- //Cache the helper size
- this._cacheHelperProportions();
-
- //If ddmanager is used for droppables, set the global draggable
- if($.ui.ddmanager) {
- $.ui.ddmanager.current = this;
- }
-
- /*
- * - Position generation -
- * This block generates everything position related - it's the core of draggables.
- */
-
- //Cache the margins of the original element
- this._cacheMargins();
-
- //Store the helper's css position
- this.cssPosition = this.helper.css( "position" );
- this.scrollParent = this.helper.scrollParent();
- this.offsetParent = this.helper.offsetParent();
- this.offsetParentCssPosition = this.offsetParent.css( "position" );
-
- //The element's absolute position on the page minus margins
- this.offset = this.positionAbs = this.element.offset();
- this.offset = {
- top: this.offset.top - this.margins.top,
- left: this.offset.left - this.margins.left
- };
-
- //Reset scroll cache
- this.offset.scroll = false;
-
- $.extend(this.offset, {
- click: { //Where the click happened, relative to the element
- left: event.pageX - this.offset.left,
- top: event.pageY - this.offset.top
- },
- parent: this._getParentOffset(),
- relative: this._getRelativeOffset() //This is a relative to absolute position minus the actual position calculation - only used for relative positioned helper
- });
-
- //Generate the original position
- this.originalPosition = this.position = this._generatePosition(event);
- this.originalPageX = event.pageX;
- this.originalPageY = event.pageY;
-
- //Adjust the mouse offset relative to the helper if "cursorAt" is supplied
- (o.cursorAt && this._adjustOffsetFromHelper(o.cursorAt));
-
- //Set a containment if given in the options
- this._setContainment();
-
- //Trigger event + callbacks
- if(this._trigger("start", event) === false) {
- this._clear();
- return false;
- }
-
- //Recache the helper size
- this._cacheHelperProportions();
-
- //Prepare the droppable offsets
- if ($.ui.ddmanager && !o.dropBehaviour) {
- $.ui.ddmanager.prepareOffsets(this, event);
- }
-
-
- this._mouseDrag(event, true); //Execute the drag once - this causes the helper not to be visible before getting its correct position
-
- //If the ddmanager is used for droppables, inform the manager that dragging has started (see #5003)
- if ( $.ui.ddmanager ) {
- $.ui.ddmanager.dragStart(this, event);
- }
-
- return true;
- },
-
- _mouseDrag: function(event, noPropagation) {
- // reset any necessary cached properties (see #5009)
- if ( this.offsetParentCssPosition === "fixed" ) {
- this.offset.parent = this._getParentOffset();
- }
-
- //Compute the helpers position
- this.position = this._generatePosition(event);
- this.positionAbs = this._convertPositionTo("absolute");
-
- //Call plugins and callbacks and use the resulting position if something is returned
- if (!noPropagation) {
- var ui = this._uiHash();
- if(this._trigger("drag", event, ui) === false) {
- this._mouseUp({});
- return false;
- }
- this.position = ui.position;
- }
-
- if(!this.options.axis || this.options.axis !== "y") {
- this.helper[0].style.left = this.position.left+"px";
- }
- if(!this.options.axis || this.options.axis !== "x") {
- this.helper[0].style.top = this.position.top+"px";
- }
- if($.ui.ddmanager) {
- $.ui.ddmanager.drag(this, event);
- }
-
- return false;
- },
-
- _mouseStop: function(event) {
-
- //If we are using droppables, inform the manager about the drop
- var that = this,
- dropped = false;
- if ($.ui.ddmanager && !this.options.dropBehaviour) {
- dropped = $.ui.ddmanager.drop(this, event);
- }
-
- //if a drop comes from outside (a sortable)
- if(this.dropped) {
- dropped = this.dropped;
- this.dropped = false;
- }
-
- //if the original element is no longer in the DOM don't bother to continue (see #8269)
- if ( this.options.helper === "original" && !$.contains( this.element[ 0 ].ownerDocument, this.element[ 0 ] ) ) {
- return false;
- }
-
- if((this.options.revert === "invalid" && !dropped) || (this.options.revert === "valid" && dropped) || this.options.revert === true || ($.isFunction(this.options.revert) && this.options.revert.call(this.element, dropped))) {
- $(this.helper).animate(this.originalPosition, parseInt(this.options.revertDuration, 10), function() {
- if(that._trigger("stop", event) !== false) {
- that._clear();
- }
- });
- } else {
- if(this._trigger("stop", event) !== false) {
- this._clear();
- }
- }
-
- return false;
- },
-
- _mouseUp: function(event) {
- //Remove frame helpers
- $("div.ui-draggable-iframeFix").each(function() {
- this.parentNode.removeChild(this);
- });
-
- //If the ddmanager is used for droppables, inform the manager that dragging has stopped (see #5003)
- if( $.ui.ddmanager ) {
- $.ui.ddmanager.dragStop(this, event);
- }
-
- return $.ui.mouse.prototype._mouseUp.call(this, event);
- },
-
- cancel: function() {
-
- if(this.helper.is(".ui-draggable-dragging")) {
- this._mouseUp({});
- } else {
- this._clear();
- }
-
- return this;
-
- },
-
- _getHandle: function(event) {
- return this.options.handle ?
- !!$( event.target ).closest( this.element.find( this.options.handle ) ).length :
- true;
- },
-
- _createHelper: function(event) {
-
- var o = this.options,
- helper = $.isFunction(o.helper) ? $(o.helper.apply(this.element[0], [event])) : (o.helper === "clone" ? this.element.clone().removeAttr("id") : this.element);
-
- if(!helper.parents("body").length) {
- helper.appendTo((o.appendTo === "parent" ? this.element[0].parentNode : o.appendTo));
- }
-
- if(helper[0] !== this.element[0] && !(/(fixed|absolute)/).test(helper.css("position"))) {
- helper.css("position", "absolute");
- }
-
- return helper;
-
- },
-
- _adjustOffsetFromHelper: function(obj) {
- if (typeof obj === "string") {
- obj = obj.split(" ");
- }
- if ($.isArray(obj)) {
- obj = {left: +obj[0], top: +obj[1] || 0};
- }
- if ("left" in obj) {
- this.offset.click.left = obj.left + this.margins.left;
- }
- if ("right" in obj) {
- this.offset.click.left = this.helperProportions.width - obj.right + this.margins.left;
- }
- if ("top" in obj) {
- this.offset.click.top = obj.top + this.margins.top;
- }
- if ("bottom" in obj) {
- this.offset.click.top = this.helperProportions.height - obj.bottom + this.margins.top;
- }
- },
-
- _getParentOffset: function() {
-
- //Get the offsetParent and cache its position
- var po = this.offsetParent.offset();
-
- // This is a special case where we need to modify a offset calculated on start, since the following happened:
- // 1. The position of the helper is absolute, so it's position is calculated based on the next positioned parent
- // 2. The actual offset parent is a child of the scroll parent, and the scroll parent isn't the document, which means that
- // the scroll is included in the initial calculation of the offset of the parent, and never recalculated upon drag
- if(this.cssPosition === "absolute" && this.scrollParent[0] !== document && $.contains(this.scrollParent[0], this.offsetParent[0])) {
- po.left += this.scrollParent.scrollLeft();
- po.top += this.scrollParent.scrollTop();
- }
-
- //This needs to be actually done for all browsers, since pageX/pageY includes this information
- //Ugly IE fix
- if((this.offsetParent[0] === document.body) ||
- (this.offsetParent[0].tagName && this.offsetParent[0].tagName.toLowerCase() === "html" && $.ui.ie)) {
- po = { top: 0, left: 0 };
- }
-
- return {
- top: po.top + (parseInt(this.offsetParent.css("borderTopWidth"),10) || 0),
- left: po.left + (parseInt(this.offsetParent.css("borderLeftWidth"),10) || 0)
- };
-
- },
-
- _getRelativeOffset: function() {
-
- if(this.cssPosition === "relative") {
- var p = this.element.position();
- return {
- top: p.top - (parseInt(this.helper.css("top"),10) || 0) + this.scrollParent.scrollTop(),
- left: p.left - (parseInt(this.helper.css("left"),10) || 0) + this.scrollParent.scrollLeft()
- };
- } else {
- return { top: 0, left: 0 };
- }
-
- },
-
- _cacheMargins: function() {
- this.margins = {
- left: (parseInt(this.element.css("marginLeft"),10) || 0),
- top: (parseInt(this.element.css("marginTop"),10) || 0),
- right: (parseInt(this.element.css("marginRight"),10) || 0),
- bottom: (parseInt(this.element.css("marginBottom"),10) || 0)
- };
- },
-
- _cacheHelperProportions: function() {
- this.helperProportions = {
- width: this.helper.outerWidth(),
- height: this.helper.outerHeight()
- };
- },
-
- _setContainment: function() {
-
- var over, c, ce,
- o = this.options;
-
- if ( !o.containment ) {
- this.containment = null;
- return;
- }
-
- if ( o.containment === "window" ) {
- this.containment = [
- $( window ).scrollLeft() - this.offset.relative.left - this.offset.parent.left,
- $( window ).scrollTop() - this.offset.relative.top - this.offset.parent.top,
- $( window ).scrollLeft() + $( window ).width() - this.helperProportions.width - this.margins.left,
- $( window ).scrollTop() + ( $( window ).height() || document.body.parentNode.scrollHeight ) - this.helperProportions.height - this.margins.top
- ];
- return;
- }
-
- if ( o.containment === "document") {
- this.containment = [
- 0,
- 0,
- $( document ).width() - this.helperProportions.width - this.margins.left,
- ( $( document ).height() || document.body.parentNode.scrollHeight ) - this.helperProportions.height - this.margins.top
- ];
- return;
- }
-
- if ( o.containment.constructor === Array ) {
- this.containment = o.containment;
- return;
- }
-
- if ( o.containment === "parent" ) {
- o.containment = this.helper[ 0 ].parentNode;
- }
-
- c = $( o.containment );
- ce = c[ 0 ];
-
- if( !ce ) {
- return;
- }
-
- over = c.css( "overflow" ) !== "hidden";
-
- this.containment = [
- ( parseInt( c.css( "borderLeftWidth" ), 10 ) || 0 ) + ( parseInt( c.css( "paddingLeft" ), 10 ) || 0 ),
- ( parseInt( c.css( "borderTopWidth" ), 10 ) || 0 ) + ( parseInt( c.css( "paddingTop" ), 10 ) || 0 ) ,
- ( over ? Math.max( ce.scrollWidth, ce.offsetWidth ) : ce.offsetWidth ) - ( parseInt( c.css( "borderRightWidth" ), 10 ) || 0 ) - ( parseInt( c.css( "paddingRight" ), 10 ) || 0 ) - this.helperProportions.width - this.margins.left - this.margins.right,
- ( over ? Math.max( ce.scrollHeight, ce.offsetHeight ) : ce.offsetHeight ) - ( parseInt( c.css( "borderBottomWidth" ), 10 ) || 0 ) - ( parseInt( c.css( "paddingBottom" ), 10 ) || 0 ) - this.helperProportions.height - this.margins.top - this.margins.bottom
- ];
- this.relative_container = c;
- },
-
- _convertPositionTo: function(d, pos) {
-
- if(!pos) {
- pos = this.position;
- }
-
- var mod = d === "absolute" ? 1 : -1,
- scroll = this.cssPosition === "absolute" && !( this.scrollParent[ 0 ] !== document && $.contains( this.scrollParent[ 0 ], this.offsetParent[ 0 ] ) ) ? this.offsetParent : this.scrollParent;
-
- //Cache the scroll
- if (!this.offset.scroll) {
- this.offset.scroll = {top : scroll.scrollTop(), left : scroll.scrollLeft()};
- }
-
- return {
- top: (
- pos.top + // The absolute mouse position
- this.offset.relative.top * mod + // Only for relative positioned nodes: Relative offset from element to offset parent
- this.offset.parent.top * mod - // The offsetParent's offset without borders (offset + border)
- ( ( this.cssPosition === "fixed" ? -this.scrollParent.scrollTop() : this.offset.scroll.top ) * mod )
- ),
- left: (
- pos.left + // The absolute mouse position
- this.offset.relative.left * mod + // Only for relative positioned nodes: Relative offset from element to offset parent
- this.offset.parent.left * mod - // The offsetParent's offset without borders (offset + border)
- ( ( this.cssPosition === "fixed" ? -this.scrollParent.scrollLeft() : this.offset.scroll.left ) * mod )
- )
- };
-
- },
-
- _generatePosition: function(event) {
-
- var containment, co, top, left,
- o = this.options,
- scroll = this.cssPosition === "absolute" && !( this.scrollParent[ 0 ] !== document && $.contains( this.scrollParent[ 0 ], this.offsetParent[ 0 ] ) ) ? this.offsetParent : this.scrollParent,
- pageX = event.pageX,
- pageY = event.pageY;
-
- //Cache the scroll
- if (!this.offset.scroll) {
- this.offset.scroll = {top : scroll.scrollTop(), left : scroll.scrollLeft()};
- }
-
- /*
- * - Position constraining -
- * Constrain the position to a mix of grid, containment.
- */
-
- // If we are not dragging yet, we won't check for options
- if ( this.originalPosition ) {
- if ( this.containment ) {
- if ( this.relative_container ){
- co = this.relative_container.offset();
- containment = [
- this.containment[ 0 ] + co.left,
- this.containment[ 1 ] + co.top,
- this.containment[ 2 ] + co.left,
- this.containment[ 3 ] + co.top
- ];
- }
- else {
- containment = this.containment;
- }
-
- if(event.pageX - this.offset.click.left < containment[0]) {
- pageX = containment[0] + this.offset.click.left;
- }
- if(event.pageY - this.offset.click.top < containment[1]) {
- pageY = containment[1] + this.offset.click.top;
- }
- if(event.pageX - this.offset.click.left > containment[2]) {
- pageX = containment[2] + this.offset.click.left;
- }
- if(event.pageY - this.offset.click.top > containment[3]) {
- pageY = containment[3] + this.offset.click.top;
- }
- }
-
- if(o.grid) {
- //Check for grid elements set to 0 to prevent divide by 0 error causing invalid argument errors in IE (see ticket #6950)
- top = o.grid[1] ? this.originalPageY + Math.round((pageY - this.originalPageY) / o.grid[1]) * o.grid[1] : this.originalPageY;
- pageY = containment ? ((top - this.offset.click.top >= containment[1] || top - this.offset.click.top > containment[3]) ? top : ((top - this.offset.click.top >= containment[1]) ? top - o.grid[1] : top + o.grid[1])) : top;
-
- left = o.grid[0] ? this.originalPageX + Math.round((pageX - this.originalPageX) / o.grid[0]) * o.grid[0] : this.originalPageX;
- pageX = containment ? ((left - this.offset.click.left >= containment[0] || left - this.offset.click.left > containment[2]) ? left : ((left - this.offset.click.left >= containment[0]) ? left - o.grid[0] : left + o.grid[0])) : left;
- }
-
- }
-
- return {
- top: (
- pageY - // The absolute mouse position
- this.offset.click.top - // Click offset (relative to the element)
- this.offset.relative.top - // Only for relative positioned nodes: Relative offset from element to offset parent
- this.offset.parent.top + // The offsetParent's offset without borders (offset + border)
- ( this.cssPosition === "fixed" ? -this.scrollParent.scrollTop() : this.offset.scroll.top )
- ),
- left: (
- pageX - // The absolute mouse position
- this.offset.click.left - // Click offset (relative to the element)
- this.offset.relative.left - // Only for relative positioned nodes: Relative offset from element to offset parent
- this.offset.parent.left + // The offsetParent's offset without borders (offset + border)
- ( this.cssPosition === "fixed" ? -this.scrollParent.scrollLeft() : this.offset.scroll.left )
- )
- };
-
- },
-
- _clear: function() {
- this.helper.removeClass("ui-draggable-dragging");
- if(this.helper[0] !== this.element[0] && !this.cancelHelperRemoval) {
- this.helper.remove();
- }
- this.helper = null;
- this.cancelHelperRemoval = false;
- },
-
- // From now on bulk stuff - mainly helpers
-
- _trigger: function(type, event, ui) {
- ui = ui || this._uiHash();
- $.ui.plugin.call(this, type, [event, ui]);
- //The absolute position has to be recalculated after plugins
- if(type === "drag") {
- this.positionAbs = this._convertPositionTo("absolute");
- }
- return $.Widget.prototype._trigger.call(this, type, event, ui);
- },
-
- plugins: {},
-
- _uiHash: function() {
- return {
- helper: this.helper,
- position: this.position,
- originalPosition: this.originalPosition,
- offset: this.positionAbs
- };
- }
-
-});
-
-$.ui.plugin.add("draggable", "connectToSortable", {
- start: function(event, ui) {
-
- var inst = $(this).data("ui-draggable"), o = inst.options,
- uiSortable = $.extend({}, ui, { item: inst.element });
- inst.sortables = [];
- $(o.connectToSortable).each(function() {
- var sortable = $.data(this, "ui-sortable");
- if (sortable && !sortable.options.disabled) {
- inst.sortables.push({
- instance: sortable,
- shouldRevert: sortable.options.revert
- });
- sortable.refreshPositions(); // Call the sortable's refreshPositions at drag start to refresh the containerCache since the sortable container cache is used in drag and needs to be up to date (this will ensure it's initialised as well as being kept in step with any changes that might have happened on the page).
- sortable._trigger("activate", event, uiSortable);
- }
- });
-
- },
- stop: function(event, ui) {
-
- //If we are still over the sortable, we fake the stop event of the sortable, but also remove helper
- var inst = $(this).data("ui-draggable"),
- uiSortable = $.extend({}, ui, { item: inst.element });
-
- $.each(inst.sortables, function() {
- if(this.instance.isOver) {
-
- this.instance.isOver = 0;
-
- inst.cancelHelperRemoval = true; //Don't remove the helper in the draggable instance
- this.instance.cancelHelperRemoval = false; //Remove it in the sortable instance (so sortable plugins like revert still work)
-
- //The sortable revert is supported, and we have to set a temporary dropped variable on the draggable to support revert: "valid/invalid"
- if(this.shouldRevert) {
- this.instance.options.revert = this.shouldRevert;
- }
-
- //Trigger the stop of the sortable
- this.instance._mouseStop(event);
-
- this.instance.options.helper = this.instance.options._helper;
-
- //If the helper has been the original item, restore properties in the sortable
- if(inst.options.helper === "original") {
- this.instance.currentItem.css({ top: "auto", left: "auto" });
- }
-
- } else {
- this.instance.cancelHelperRemoval = false; //Remove the helper in the sortable instance
- this.instance._trigger("deactivate", event, uiSortable);
- }
-
- });
-
- },
- drag: function(event, ui) {
-
- var inst = $(this).data("ui-draggable"), that = this;
-
- $.each(inst.sortables, function() {
-
- var innermostIntersecting = false,
- thisSortable = this;
-
- //Copy over some variables to allow calling the sortable's native _intersectsWith
- this.instance.positionAbs = inst.positionAbs;
- this.instance.helperProportions = inst.helperProportions;
- this.instance.offset.click = inst.offset.click;
-
- if(this.instance._intersectsWith(this.instance.containerCache)) {
- innermostIntersecting = true;
- $.each(inst.sortables, function () {
- this.instance.positionAbs = inst.positionAbs;
- this.instance.helperProportions = inst.helperProportions;
- this.instance.offset.click = inst.offset.click;
- if (this !== thisSortable &&
- this.instance._intersectsWith(this.instance.containerCache) &&
- $.contains(thisSortable.instance.element[0], this.instance.element[0])
- ) {
- innermostIntersecting = false;
- }
- return innermostIntersecting;
- });
- }
-
-
- if(innermostIntersecting) {
- //If it intersects, we use a little isOver variable and set it once, so our move-in stuff gets fired only once
- if(!this.instance.isOver) {
-
- this.instance.isOver = 1;
- //Now we fake the start of dragging for the sortable instance,
- //by cloning the list group item, appending it to the sortable and using it as inst.currentItem
- //We can then fire the start event of the sortable with our passed browser event, and our own helper (so it doesn't create a new one)
- this.instance.currentItem = $(that).clone().removeAttr("id").appendTo(this.instance.element).data("ui-sortable-item", true);
- this.instance.options._helper = this.instance.options.helper; //Store helper option to later restore it
- this.instance.options.helper = function() { return ui.helper[0]; };
-
- event.target = this.instance.currentItem[0];
- this.instance._mouseCapture(event, true);
- this.instance._mouseStart(event, true, true);
-
- //Because the browser event is way off the new appended portlet, we modify a couple of variables to reflect the changes
- this.instance.offset.click.top = inst.offset.click.top;
- this.instance.offset.click.left = inst.offset.click.left;
- this.instance.offset.parent.left -= inst.offset.parent.left - this.instance.offset.parent.left;
- this.instance.offset.parent.top -= inst.offset.parent.top - this.instance.offset.parent.top;
-
- inst._trigger("toSortable", event);
- inst.dropped = this.instance.element; //draggable revert needs that
- //hack so receive/update callbacks work (mostly)
- inst.currentItem = inst.element;
- this.instance.fromOutside = inst;
-
- }
-
- //Provided we did all the previous steps, we can fire the drag event of the sortable on every draggable drag, when it intersects with the sortable
- if(this.instance.currentItem) {
- this.instance._mouseDrag(event);
- }
-
- } else {
-
- //If it doesn't intersect with the sortable, and it intersected before,
- //we fake the drag stop of the sortable, but make sure it doesn't remove the helper by using cancelHelperRemoval
- if(this.instance.isOver) {
-
- this.instance.isOver = 0;
- this.instance.cancelHelperRemoval = true;
-
- //Prevent reverting on this forced stop
- this.instance.options.revert = false;
-
- // The out event needs to be triggered independently
- this.instance._trigger("out", event, this.instance._uiHash(this.instance));
-
- this.instance._mouseStop(event, true);
- this.instance.options.helper = this.instance.options._helper;
-
- //Now we remove our currentItem, the list group clone again, and the placeholder, and animate the helper back to it's original size
- this.instance.currentItem.remove();
- if(this.instance.placeholder) {
- this.instance.placeholder.remove();
- }
-
- inst._trigger("fromSortable", event);
- inst.dropped = false; //draggable revert needs that
- }
-
- }
-
- });
-
- }
-});
-
-$.ui.plugin.add("draggable", "cursor", {
- start: function() {
- var t = $("body"), o = $(this).data("ui-draggable").options;
- if (t.css("cursor")) {
- o._cursor = t.css("cursor");
- }
- t.css("cursor", o.cursor);
- },
- stop: function() {
- var o = $(this).data("ui-draggable").options;
- if (o._cursor) {
- $("body").css("cursor", o._cursor);
- }
- }
-});
-
-$.ui.plugin.add("draggable", "opacity", {
- start: function(event, ui) {
- var t = $(ui.helper), o = $(this).data("ui-draggable").options;
- if(t.css("opacity")) {
- o._opacity = t.css("opacity");
- }
- t.css("opacity", o.opacity);
- },
- stop: function(event, ui) {
- var o = $(this).data("ui-draggable").options;
- if(o._opacity) {
- $(ui.helper).css("opacity", o._opacity);
- }
- }
-});
-
-$.ui.plugin.add("draggable", "scroll", {
- start: function() {
- var i = $(this).data("ui-draggable");
- if(i.scrollParent[0] !== document && i.scrollParent[0].tagName !== "HTML") {
- i.overflowOffset = i.scrollParent.offset();
- }
- },
- drag: function( event ) {
-
- var i = $(this).data("ui-draggable"), o = i.options, scrolled = false;
-
- if(i.scrollParent[0] !== document && i.scrollParent[0].tagName !== "HTML") {
-
- if(!o.axis || o.axis !== "x") {
- if((i.overflowOffset.top + i.scrollParent[0].offsetHeight) - event.pageY < o.scrollSensitivity) {
- i.scrollParent[0].scrollTop = scrolled = i.scrollParent[0].scrollTop + o.scrollSpeed;
- } else if(event.pageY - i.overflowOffset.top < o.scrollSensitivity) {
- i.scrollParent[0].scrollTop = scrolled = i.scrollParent[0].scrollTop - o.scrollSpeed;
- }
- }
-
- if(!o.axis || o.axis !== "y") {
- if((i.overflowOffset.left + i.scrollParent[0].offsetWidth) - event.pageX < o.scrollSensitivity) {
- i.scrollParent[0].scrollLeft = scrolled = i.scrollParent[0].scrollLeft + o.scrollSpeed;
- } else if(event.pageX - i.overflowOffset.left < o.scrollSensitivity) {
- i.scrollParent[0].scrollLeft = scrolled = i.scrollParent[0].scrollLeft - o.scrollSpeed;
- }
- }
-
- } else {
-
- if(!o.axis || o.axis !== "x") {
- if(event.pageY - $(document).scrollTop() < o.scrollSensitivity) {
- scrolled = $(document).scrollTop($(document).scrollTop() - o.scrollSpeed);
- } else if($(window).height() - (event.pageY - $(document).scrollTop()) < o.scrollSensitivity) {
- scrolled = $(document).scrollTop($(document).scrollTop() + o.scrollSpeed);
- }
- }
-
- if(!o.axis || o.axis !== "y") {
- if(event.pageX - $(document).scrollLeft() < o.scrollSensitivity) {
- scrolled = $(document).scrollLeft($(document).scrollLeft() - o.scrollSpeed);
- } else if($(window).width() - (event.pageX - $(document).scrollLeft()) < o.scrollSensitivity) {
- scrolled = $(document).scrollLeft($(document).scrollLeft() + o.scrollSpeed);
- }
- }
-
- }
-
- if(scrolled !== false && $.ui.ddmanager && !o.dropBehaviour) {
- $.ui.ddmanager.prepareOffsets(i, event);
- }
-
- }
-});
-
-$.ui.plugin.add("draggable", "snap", {
- start: function() {
-
- var i = $(this).data("ui-draggable"),
- o = i.options;
-
- i.snapElements = [];
-
- $(o.snap.constructor !== String ? ( o.snap.items || ":data(ui-draggable)" ) : o.snap).each(function() {
- var $t = $(this),
- $o = $t.offset();
- if(this !== i.element[0]) {
- i.snapElements.push({
- item: this,
- width: $t.outerWidth(), height: $t.outerHeight(),
- top: $o.top, left: $o.left
- });
- }
- });
-
- },
- drag: function(event, ui) {
-
- var ts, bs, ls, rs, l, r, t, b, i, first,
- inst = $(this).data("ui-draggable"),
- o = inst.options,
- d = o.snapTolerance,
- x1 = ui.offset.left, x2 = x1 + inst.helperProportions.width,
- y1 = ui.offset.top, y2 = y1 + inst.helperProportions.height;
-
- for (i = inst.snapElements.length - 1; i >= 0; i--){
-
- l = inst.snapElements[i].left;
- r = l + inst.snapElements[i].width;
- t = inst.snapElements[i].top;
- b = t + inst.snapElements[i].height;
-
- if ( x2 < l - d || x1 > r + d || y2 < t - d || y1 > b + d || !$.contains( inst.snapElements[ i ].item.ownerDocument, inst.snapElements[ i ].item ) ) {
- if(inst.snapElements[i].snapping) {
- (inst.options.snap.release && inst.options.snap.release.call(inst.element, event, $.extend(inst._uiHash(), { snapItem: inst.snapElements[i].item })));
- }
- inst.snapElements[i].snapping = false;
- continue;
- }
-
- if(o.snapMode !== "inner") {
- ts = Math.abs(t - y2) <= d;
- bs = Math.abs(b - y1) <= d;
- ls = Math.abs(l - x2) <= d;
- rs = Math.abs(r - x1) <= d;
- if(ts) {
- ui.position.top = inst._convertPositionTo("relative", { top: t - inst.helperProportions.height, left: 0 }).top - inst.margins.top;
- }
- if(bs) {
- ui.position.top = inst._convertPositionTo("relative", { top: b, left: 0 }).top - inst.margins.top;
- }
- if(ls) {
- ui.position.left = inst._convertPositionTo("relative", { top: 0, left: l - inst.helperProportions.width }).left - inst.margins.left;
- }
- if(rs) {
- ui.position.left = inst._convertPositionTo("relative", { top: 0, left: r }).left - inst.margins.left;
- }
- }
-
- first = (ts || bs || ls || rs);
-
- if(o.snapMode !== "outer") {
- ts = Math.abs(t - y1) <= d;
- bs = Math.abs(b - y2) <= d;
- ls = Math.abs(l - x1) <= d;
- rs = Math.abs(r - x2) <= d;
- if(ts) {
- ui.position.top = inst._convertPositionTo("relative", { top: t, left: 0 }).top - inst.margins.top;
- }
- if(bs) {
- ui.position.top = inst._convertPositionTo("relative", { top: b - inst.helperProportions.height, left: 0 }).top - inst.margins.top;
- }
- if(ls) {
- ui.position.left = inst._convertPositionTo("relative", { top: 0, left: l }).left - inst.margins.left;
- }
- if(rs) {
- ui.position.left = inst._convertPositionTo("relative", { top: 0, left: r - inst.helperProportions.width }).left - inst.margins.left;
- }
- }
-
- if(!inst.snapElements[i].snapping && (ts || bs || ls || rs || first)) {
- (inst.options.snap.snap && inst.options.snap.snap.call(inst.element, event, $.extend(inst._uiHash(), { snapItem: inst.snapElements[i].item })));
- }
- inst.snapElements[i].snapping = (ts || bs || ls || rs || first);
-
- }
-
- }
-});
-
-$.ui.plugin.add("draggable", "stack", {
- start: function() {
- var min,
- o = this.data("ui-draggable").options,
- group = $.makeArray($(o.stack)).sort(function(a,b) {
- return (parseInt($(a).css("zIndex"),10) || 0) - (parseInt($(b).css("zIndex"),10) || 0);
- });
-
- if (!group.length) { return; }
-
- min = parseInt($(group[0]).css("zIndex"), 10) || 0;
- $(group).each(function(i) {
- $(this).css("zIndex", min + i);
- });
- this.css("zIndex", (min + group.length));
- }
-});
-
-$.ui.plugin.add("draggable", "zIndex", {
- start: function(event, ui) {
- var t = $(ui.helper), o = $(this).data("ui-draggable").options;
- if(t.css("zIndex")) {
- o._zIndex = t.css("zIndex");
- }
- t.css("zIndex", o.zIndex);
- },
- stop: function(event, ui) {
- var o = $(this).data("ui-draggable").options;
- if(o._zIndex) {
- $(ui.helper).css("zIndex", o._zIndex);
- }
- }
-});
-
-})(jQuery);
-(function( $, undefined ) {
-
-function isOverAxis( x, reference, size ) {
- return ( x > reference ) && ( x < ( reference + size ) );
-}
-
-$.widget("ui.droppable", {
- version: "1.10.4",
- widgetEventPrefix: "drop",
- options: {
- accept: "*",
- activeClass: false,
- addClasses: true,
- greedy: false,
- hoverClass: false,
- scope: "default",
- tolerance: "intersect",
-
- // callbacks
- activate: null,
- deactivate: null,
- drop: null,
- out: null,
- over: null
- },
- _create: function() {
-
- var proportions,
- o = this.options,
- accept = o.accept;
-
- this.isover = false;
- this.isout = true;
-
- this.accept = $.isFunction(accept) ? accept : function(d) {
- return d.is(accept);
- };
-
- this.proportions = function( /* valueToWrite */ ) {
- if ( arguments.length ) {
- // Store the droppable's proportions
- proportions = arguments[ 0 ];
- } else {
- // Retrieve or derive the droppable's proportions
- return proportions ?
- proportions :
- proportions = {
- width: this.element[ 0 ].offsetWidth,
- height: this.element[ 0 ].offsetHeight
- };
- }
- };
-
- // Add the reference and positions to the manager
- $.ui.ddmanager.droppables[o.scope] = $.ui.ddmanager.droppables[o.scope] || [];
- $.ui.ddmanager.droppables[o.scope].push(this);
-
- (o.addClasses && this.element.addClass("ui-droppable"));
-
- },
-
- _destroy: function() {
- var i = 0,
- drop = $.ui.ddmanager.droppables[this.options.scope];
-
- for ( ; i < drop.length; i++ ) {
- if ( drop[i] === this ) {
- drop.splice(i, 1);
- }
- }
-
- this.element.removeClass("ui-droppable ui-droppable-disabled");
- },
-
- _setOption: function(key, value) {
-
- if(key === "accept") {
- this.accept = $.isFunction(value) ? value : function(d) {
- return d.is(value);
- };
- }
- $.Widget.prototype._setOption.apply(this, arguments);
- },
-
- _activate: function(event) {
- var draggable = $.ui.ddmanager.current;
- if(this.options.activeClass) {
- this.element.addClass(this.options.activeClass);
- }
- if(draggable){
- this._trigger("activate", event, this.ui(draggable));
- }
- },
-
- _deactivate: function(event) {
- var draggable = $.ui.ddmanager.current;
- if(this.options.activeClass) {
- this.element.removeClass(this.options.activeClass);
- }
- if(draggable){
- this._trigger("deactivate", event, this.ui(draggable));
- }
- },
-
- _over: function(event) {
-
- var draggable = $.ui.ddmanager.current;
-
- // Bail if draggable and droppable are same element
- if (!draggable || (draggable.currentItem || draggable.element)[0] === this.element[0]) {
- return;
- }
-
- if (this.accept.call(this.element[0],(draggable.currentItem || draggable.element))) {
- if(this.options.hoverClass) {
- this.element.addClass(this.options.hoverClass);
- }
- this._trigger("over", event, this.ui(draggable));
- }
-
- },
-
- _out: function(event) {
-
- var draggable = $.ui.ddmanager.current;
-
- // Bail if draggable and droppable are same element
- if (!draggable || (draggable.currentItem || draggable.element)[0] === this.element[0]) {
- return;
- }
-
- if (this.accept.call(this.element[0],(draggable.currentItem || draggable.element))) {
- if(this.options.hoverClass) {
- this.element.removeClass(this.options.hoverClass);
- }
- this._trigger("out", event, this.ui(draggable));
- }
-
- },
-
- _drop: function(event,custom) {
-
- var draggable = custom || $.ui.ddmanager.current,
- childrenIntersection = false;
-
- // Bail if draggable and droppable are same element
- if (!draggable || (draggable.currentItem || draggable.element)[0] === this.element[0]) {
- return false;
- }
-
- this.element.find(":data(ui-droppable)").not(".ui-draggable-dragging").each(function() {
- var inst = $.data(this, "ui-droppable");
- if(
- inst.options.greedy &&
- !inst.options.disabled &&
- inst.options.scope === draggable.options.scope &&
- inst.accept.call(inst.element[0], (draggable.currentItem || draggable.element)) &&
- $.ui.intersect(draggable, $.extend(inst, { offset: inst.element.offset() }), inst.options.tolerance)
- ) { childrenIntersection = true; return false; }
- });
- if(childrenIntersection) {
- return false;
- }
-
- if(this.accept.call(this.element[0],(draggable.currentItem || draggable.element))) {
- if(this.options.activeClass) {
- this.element.removeClass(this.options.activeClass);
- }
- if(this.options.hoverClass) {
- this.element.removeClass(this.options.hoverClass);
- }
- this._trigger("drop", event, this.ui(draggable));
- return this.element;
- }
-
- return false;
-
- },
-
- ui: function(c) {
- return {
- draggable: (c.currentItem || c.element),
- helper: c.helper,
- position: c.position,
- offset: c.positionAbs
- };
- }
-
-});
-
-$.ui.intersect = function(draggable, droppable, toleranceMode) {
-
- if (!droppable.offset) {
- return false;
- }
-
- var draggableLeft, draggableTop,
- x1 = (draggable.positionAbs || draggable.position.absolute).left,
- y1 = (draggable.positionAbs || draggable.position.absolute).top,
- x2 = x1 + draggable.helperProportions.width,
- y2 = y1 + draggable.helperProportions.height,
- l = droppable.offset.left,
- t = droppable.offset.top,
- r = l + droppable.proportions().width,
- b = t + droppable.proportions().height;
-
- switch (toleranceMode) {
- case "fit":
- return (l <= x1 && x2 <= r && t <= y1 && y2 <= b);
- case "intersect":
- return (l < x1 + (draggable.helperProportions.width / 2) && // Right Half
- x2 - (draggable.helperProportions.width / 2) < r && // Left Half
- t < y1 + (draggable.helperProportions.height / 2) && // Bottom Half
- y2 - (draggable.helperProportions.height / 2) < b ); // Top Half
- case "pointer":
- draggableLeft = ((draggable.positionAbs || draggable.position.absolute).left + (draggable.clickOffset || draggable.offset.click).left);
- draggableTop = ((draggable.positionAbs || draggable.position.absolute).top + (draggable.clickOffset || draggable.offset.click).top);
- return isOverAxis( draggableTop, t, droppable.proportions().height ) && isOverAxis( draggableLeft, l, droppable.proportions().width );
- case "touch":
- return (
- (y1 >= t && y1 <= b) || // Top edge touching
- (y2 >= t && y2 <= b) || // Bottom edge touching
- (y1 < t && y2 > b) // Surrounded vertically
- ) && (
- (x1 >= l && x1 <= r) || // Left edge touching
- (x2 >= l && x2 <= r) || // Right edge touching
- (x1 < l && x2 > r) // Surrounded horizontally
- );
- default:
- return false;
- }
-
-};
-
-/*
- This manager tracks offsets of draggables and droppables
-*/
-$.ui.ddmanager = {
- current: null,
- droppables: { "default": [] },
- prepareOffsets: function(t, event) {
-
- var i, j,
- m = $.ui.ddmanager.droppables[t.options.scope] || [],
- type = event ? event.type : null, // workaround for #2317
- list = (t.currentItem || t.element).find(":data(ui-droppable)").addBack();
-
- droppablesLoop: for (i = 0; i < m.length; i++) {
-
- //No disabled and non-accepted
- if(m[i].options.disabled || (t && !m[i].accept.call(m[i].element[0],(t.currentItem || t.element)))) {
- continue;
- }
-
- // Filter out elements in the current dragged item
- for (j=0; j < list.length; j++) {
- if(list[j] === m[i].element[0]) {
- m[i].proportions().height = 0;
- continue droppablesLoop;
- }
- }
-
- m[i].visible = m[i].element.css("display") !== "none";
- if(!m[i].visible) {
- continue;
- }
-
- //Activate the droppable if used directly from draggables
- if(type === "mousedown") {
- m[i]._activate.call(m[i], event);
- }
-
- m[ i ].offset = m[ i ].element.offset();
- m[ i ].proportions({ width: m[ i ].element[ 0 ].offsetWidth, height: m[ i ].element[ 0 ].offsetHeight });
-
- }
-
- },
- drop: function(draggable, event) {
-
- var dropped = false;
- // Create a copy of the droppables in case the list changes during the drop (#9116)
- $.each(($.ui.ddmanager.droppables[draggable.options.scope] || []).slice(), function() {
-
- if(!this.options) {
- return;
- }
- if (!this.options.disabled && this.visible && $.ui.intersect(draggable, this, this.options.tolerance)) {
- dropped = this._drop.call(this, event) || dropped;
- }
-
- if (!this.options.disabled && this.visible && this.accept.call(this.element[0],(draggable.currentItem || draggable.element))) {
- this.isout = true;
- this.isover = false;
- this._deactivate.call(this, event);
- }
-
- });
- return dropped;
-
- },
- dragStart: function( draggable, event ) {
- //Listen for scrolling so that if the dragging causes scrolling the position of the droppables can be recalculated (see #5003)
- draggable.element.parentsUntil( "body" ).bind( "scroll.droppable", function() {
- if( !draggable.options.refreshPositions ) {
- $.ui.ddmanager.prepareOffsets( draggable, event );
- }
- });
- },
- drag: function(draggable, event) {
-
- //If you have a highly dynamic page, you might try this option. It renders positions every time you move the mouse.
- if(draggable.options.refreshPositions) {
- $.ui.ddmanager.prepareOffsets(draggable, event);
- }
-
- //Run through all droppables and check their positions based on specific tolerance options
- $.each($.ui.ddmanager.droppables[draggable.options.scope] || [], function() {
-
- if(this.options.disabled || this.greedyChild || !this.visible) {
- return;
- }
-
- var parentInstance, scope, parent,
- intersects = $.ui.intersect(draggable, this, this.options.tolerance),
- c = !intersects && this.isover ? "isout" : (intersects && !this.isover ? "isover" : null);
- if(!c) {
- return;
- }
-
- if (this.options.greedy) {
- // find droppable parents with same scope
- scope = this.options.scope;
- parent = this.element.parents(":data(ui-droppable)").filter(function () {
- return $.data(this, "ui-droppable").options.scope === scope;
- });
-
- if (parent.length) {
- parentInstance = $.data(parent[0], "ui-droppable");
- parentInstance.greedyChild = (c === "isover");
- }
- }
-
- // we just moved into a greedy child
- if (parentInstance && c === "isover") {
- parentInstance.isover = false;
- parentInstance.isout = true;
- parentInstance._out.call(parentInstance, event);
- }
-
- this[c] = true;
- this[c === "isout" ? "isover" : "isout"] = false;
- this[c === "isover" ? "_over" : "_out"].call(this, event);
-
- // we just moved out of a greedy child
- if (parentInstance && c === "isout") {
- parentInstance.isout = false;
- parentInstance.isover = true;
- parentInstance._over.call(parentInstance, event);
- }
- });
-
- },
- dragStop: function( draggable, event ) {
- draggable.element.parentsUntil( "body" ).unbind( "scroll.droppable" );
- //Call prepareOffsets one final time since IE does not fire return scroll events when overflow was caused by drag (see #5003)
- if( !draggable.options.refreshPositions ) {
- $.ui.ddmanager.prepareOffsets( draggable, event );
- }
- }
-};
-
-})(jQuery);
-(function( $, undefined ) {
-
-function num(v) {
- return parseInt(v, 10) || 0;
-}
-
-function isNumber(value) {
- return !isNaN(parseInt(value, 10));
-}
-
-$.widget("ui.resizable", $.ui.mouse, {
- version: "1.10.4",
- widgetEventPrefix: "resize",
- options: {
- alsoResize: false,
- animate: false,
- animateDuration: "slow",
- animateEasing: "swing",
- aspectRatio: false,
- autoHide: false,
- containment: false,
- ghost: false,
- grid: false,
- handles: "e,s,se",
- helper: false,
- maxHeight: null,
- maxWidth: null,
- minHeight: 10,
- minWidth: 10,
- // See #7960
- zIndex: 90,
-
- // callbacks
- resize: null,
- start: null,
- stop: null
- },
- _create: function() {
-
- var n, i, handle, axis, hname,
- that = this,
- o = this.options;
- this.element.addClass("ui-resizable");
-
- $.extend(this, {
- _aspectRatio: !!(o.aspectRatio),
- aspectRatio: o.aspectRatio,
- originalElement: this.element,
- _proportionallyResizeElements: [],
- _helper: o.helper || o.ghost || o.animate ? o.helper || "ui-resizable-helper" : null
- });
-
- //Wrap the element if it cannot hold child nodes
- if(this.element[0].nodeName.match(/canvas|textarea|input|select|button|img/i)) {
-
- //Create a wrapper element and set the wrapper to the new current internal element
- this.element.wrap(
- $("<div class='ui-wrapper' style='overflow: hidden;'></div>").css({
- position: this.element.css("position"),
- width: this.element.outerWidth(),
- height: this.element.outerHeight(),
- top: this.element.css("top"),
- left: this.element.css("left")
- })
- );
-
- //Overwrite the original this.element
- this.element = this.element.parent().data(
- "ui-resizable", this.element.data("ui-resizable")
- );
-
- this.elementIsWrapper = true;
-
- //Move margins to the wrapper
- this.element.css({ marginLeft: this.originalElement.css("marginLeft"), marginTop: this.originalElement.css("marginTop"), marginRight: this.originalElement.css("marginRight"), marginBottom: this.originalElement.css("marginBottom") });
- this.originalElement.css({ marginLeft: 0, marginTop: 0, marginRight: 0, marginBottom: 0});
-
- //Prevent Safari textarea resize
- this.originalResizeStyle = this.originalElement.css("resize");
- this.originalElement.css("resize", "none");
-
- //Push the actual element to our proportionallyResize internal array
- this._proportionallyResizeElements.push(this.originalElement.css({ position: "static", zoom: 1, display: "block" }));
-
- // avoid IE jump (hard set the margin)
- this.originalElement.css({ margin: this.originalElement.css("margin") });
-
- // fix handlers offset
- this._proportionallyResize();
-
- }
-
- this.handles = o.handles || (!$(".ui-resizable-handle", this.element).length ? "e,s,se" : { n: ".ui-resizable-n", e: ".ui-resizable-e", s: ".ui-resizable-s", w: ".ui-resizable-w", se: ".ui-resizable-se", sw: ".ui-resizable-sw", ne: ".ui-resizable-ne", nw: ".ui-resizable-nw" });
- if(this.handles.constructor === String) {
-
- if ( this.handles === "all") {
- this.handles = "n,e,s,w,se,sw,ne,nw";
- }
-
- n = this.handles.split(",");
- this.handles = {};
-
- for(i = 0; i < n.length; i++) {
-
- handle = $.trim(n[i]);
- hname = "ui-resizable-"+handle;
- axis = $("<div class='ui-resizable-handle " + hname + "'></div>");
-
- // Apply zIndex to all handles - see #7960
- axis.css({ zIndex: o.zIndex });
-
- //TODO : What's going on here?
- if ("se" === handle) {
- axis.addClass("ui-icon ui-icon-gripsmall-diagonal-se");
- }
-
- //Insert into internal handles object and append to element
- this.handles[handle] = ".ui-resizable-"+handle;
- this.element.append(axis);
- }
-
- }
-
- this._renderAxis = function(target) {
-
- var i, axis, padPos, padWrapper;
-
- target = target || this.element;
-
- for(i in this.handles) {
-
- if(this.handles[i].constructor === String) {
- this.handles[i] = $(this.handles[i], this.element).show();
- }
-
- //Apply pad to wrapper element, needed to fix axis position (textarea, inputs, scrolls)
- if (this.elementIsWrapper && this.originalElement[0].nodeName.match(/textarea|input|select|button/i)) {
-
- axis = $(this.handles[i], this.element);
-
- //Checking the correct pad and border
- padWrapper = /sw|ne|nw|se|n|s/.test(i) ? axis.outerHeight() : axis.outerWidth();
-
- //The padding type i have to apply...
- padPos = [ "padding",
- /ne|nw|n/.test(i) ? "Top" :
- /se|sw|s/.test(i) ? "Bottom" :
- /^e$/.test(i) ? "Right" : "Left" ].join("");
-
- target.css(padPos, padWrapper);
-
- this._proportionallyResize();
-
- }
-
- //TODO: What's that good for? There's not anything to be executed left
- if(!$(this.handles[i]).length) {
- continue;
- }
- }
- };
-
- //TODO: make renderAxis a prototype function
- this._renderAxis(this.element);
-
- this._handles = $(".ui-resizable-handle", this.element)
- .disableSelection();
-
- //Matching axis name
- this._handles.mouseover(function() {
- if (!that.resizing) {
- if (this.className) {
- axis = this.className.match(/ui-resizable-(se|sw|ne|nw|n|e|s|w)/i);
- }
- //Axis, default = se
- that.axis = axis && axis[1] ? axis[1] : "se";
- }
- });
-
- //If we want to auto hide the elements
- if (o.autoHide) {
- this._handles.hide();
- $(this.element)
- .addClass("ui-resizable-autohide")
- .mouseenter(function() {
- if (o.disabled) {
- return;
- }
- $(this).removeClass("ui-resizable-autohide");
- that._handles.show();
- })
- .mouseleave(function(){
- if (o.disabled) {
- return;
- }
- if (!that.resizing) {
- $(this).addClass("ui-resizable-autohide");
- that._handles.hide();
- }
- });
- }
-
- //Initialize the mouse interaction
- this._mouseInit();
-
- },
-
- _destroy: function() {
-
- this._mouseDestroy();
-
- var wrapper,
- _destroy = function(exp) {
- $(exp).removeClass("ui-resizable ui-resizable-disabled ui-resizable-resizing")
- .removeData("resizable").removeData("ui-resizable").unbind(".resizable").find(".ui-resizable-handle").remove();
- };
-
- //TODO: Unwrap at same DOM position
- if (this.elementIsWrapper) {
- _destroy(this.element);
- wrapper = this.element;
- this.originalElement.css({
- position: wrapper.css("position"),
- width: wrapper.outerWidth(),
- height: wrapper.outerHeight(),
- top: wrapper.css("top"),
- left: wrapper.css("left")
- }).insertAfter( wrapper );
- wrapper.remove();
- }
-
- this.originalElement.css("resize", this.originalResizeStyle);
- _destroy(this.originalElement);
-
- return this;
- },
-
- _mouseCapture: function(event) {
- var i, handle,
- capture = false;
-
- for (i in this.handles) {
- handle = $(this.handles[i])[0];
- if (handle === event.target || $.contains(handle, event.target)) {
- capture = true;
- }
- }
-
- return !this.options.disabled && capture;
- },
-
- _mouseStart: function(event) {
-
- var curleft, curtop, cursor,
- o = this.options,
- iniPos = this.element.position(),
- el = this.element;
-
- this.resizing = true;
-
- // bugfix for http://dev.jquery.com/ticket/1749
- if ( (/absolute/).test( el.css("position") ) ) {
- el.css({ position: "absolute", top: el.css("top"), left: el.css("left") });
- } else if (el.is(".ui-draggable")) {
- el.css({ position: "absolute", top: iniPos.top, left: iniPos.left });
- }
-
- this._renderProxy();
-
- curleft = num(this.helper.css("left"));
- curtop = num(this.helper.css("top"));
-
- if (o.containment) {
- curleft += $(o.containment).scrollLeft() || 0;
- curtop += $(o.containment).scrollTop() || 0;
- }
-
- //Store needed variables
- this.offset = this.helper.offset();
- this.position = { left: curleft, top: curtop };
- this.size = this._helper ? { width: this.helper.width(), height: this.helper.height() } : { width: el.width(), height: el.height() };
- this.originalSize = this._helper ? { width: el.outerWidth(), height: el.outerHeight() } : { width: el.width(), height: el.height() };
- this.originalPosition = { left: curleft, top: curtop };
- this.sizeDiff = { width: el.outerWidth() - el.width(), height: el.outerHeight() - el.height() };
- this.originalMousePosition = { left: event.pageX, top: event.pageY };
-
- //Aspect Ratio
- this.aspectRatio = (typeof o.aspectRatio === "number") ? o.aspectRatio : ((this.originalSize.width / this.originalSize.height) || 1);
-
- cursor = $(".ui-resizable-" + this.axis).css("cursor");
- $("body").css("cursor", cursor === "auto" ? this.axis + "-resize" : cursor);
-
- el.addClass("ui-resizable-resizing");
- this._propagate("start", event);
- return true;
- },
-
- _mouseDrag: function(event) {
-
- //Increase performance, avoid regex
- var data,
- el = this.helper, props = {},
- smp = this.originalMousePosition,
- a = this.axis,
- prevTop = this.position.top,
- prevLeft = this.position.left,
- prevWidth = this.size.width,
- prevHeight = this.size.height,
- dx = (event.pageX-smp.left)||0,
- dy = (event.pageY-smp.top)||0,
- trigger = this._change[a];
-
- if (!trigger) {
- return false;
- }
-
- // Calculate the attrs that will be change
- data = trigger.apply(this, [event, dx, dy]);
-
- // Put this in the mouseDrag handler since the user can start pressing shift while resizing
- this._updateVirtualBoundaries(event.shiftKey);
- if (this._aspectRatio || event.shiftKey) {
- data = this._updateRatio(data, event);
- }
-
- data = this._respectSize(data, event);
-
- this._updateCache(data);
-
- // plugins callbacks need to be called first
- this._propagate("resize", event);
-
- if (this.position.top !== prevTop) {
- props.top = this.position.top + "px";
- }
- if (this.position.left !== prevLeft) {
- props.left = this.position.left + "px";
- }
- if (this.size.width !== prevWidth) {
- props.width = this.size.width + "px";
- }
- if (this.size.height !== prevHeight) {
- props.height = this.size.height + "px";
- }
- el.css(props);
-
- if (!this._helper && this._proportionallyResizeElements.length) {
- this._proportionallyResize();
- }
-
- // Call the user callback if the element was resized
- if ( ! $.isEmptyObject(props) ) {
- this._trigger("resize", event, this.ui());
- }
-
- return false;
- },
-
- _mouseStop: function(event) {
-
- this.resizing = false;
- var pr, ista, soffseth, soffsetw, s, left, top,
- o = this.options, that = this;
-
- if(this._helper) {
-
- pr = this._proportionallyResizeElements;
- ista = pr.length && (/textarea/i).test(pr[0].nodeName);
- soffseth = ista && $.ui.hasScroll(pr[0], "left") /* TODO - jump height */ ? 0 : that.sizeDiff.height;
- soffsetw = ista ? 0 : that.sizeDiff.width;
-
- s = { width: (that.helper.width() - soffsetw), height: (that.helper.height() - soffseth) };
- left = (parseInt(that.element.css("left"), 10) + (that.position.left - that.originalPosition.left)) || null;
- top = (parseInt(that.element.css("top"), 10) + (that.position.top - that.originalPosition.top)) || null;
-
- if (!o.animate) {
- this.element.css($.extend(s, { top: top, left: left }));
- }
-
- that.helper.height(that.size.height);
- that.helper.width(that.size.width);
-
- if (this._helper && !o.animate) {
- this._proportionallyResize();
- }
- }
-
- $("body").css("cursor", "auto");
-
- this.element.removeClass("ui-resizable-resizing");
-
- this._propagate("stop", event);
-
- if (this._helper) {
- this.helper.remove();
- }
-
- return false;
-
- },
-
- _updateVirtualBoundaries: function(forceAspectRatio) {
- var pMinWidth, pMaxWidth, pMinHeight, pMaxHeight, b,
- o = this.options;
-
- b = {
- minWidth: isNumber(o.minWidth) ? o.minWidth : 0,
- maxWidth: isNumber(o.maxWidth) ? o.maxWidth : Infinity,
- minHeight: isNumber(o.minHeight) ? o.minHeight : 0,
- maxHeight: isNumber(o.maxHeight) ? o.maxHeight : Infinity
- };
-
- if(this._aspectRatio || forceAspectRatio) {
- // We want to create an enclosing box whose aspect ration is the requested one
- // First, compute the "projected" size for each dimension based on the aspect ratio and other dimension
- pMinWidth = b.minHeight * this.aspectRatio;
- pMinHeight = b.minWidth / this.aspectRatio;
- pMaxWidth = b.maxHeight * this.aspectRatio;
- pMaxHeight = b.maxWidth / this.aspectRatio;
-
- if(pMinWidth > b.minWidth) {
- b.minWidth = pMinWidth;
- }
- if(pMinHeight > b.minHeight) {
- b.minHeight = pMinHeight;
- }
- if(pMaxWidth < b.maxWidth) {
- b.maxWidth = pMaxWidth;
- }
- if(pMaxHeight < b.maxHeight) {
- b.maxHeight = pMaxHeight;
- }
- }
- this._vBoundaries = b;
- },
-
- _updateCache: function(data) {
- this.offset = this.helper.offset();
- if (isNumber(data.left)) {
- this.position.left = data.left;
- }
- if (isNumber(data.top)) {
- this.position.top = data.top;
- }
- if (isNumber(data.height)) {
- this.size.height = data.height;
- }
- if (isNumber(data.width)) {
- this.size.width = data.width;
- }
- },
-
- _updateRatio: function( data ) {
-
- var cpos = this.position,
- csize = this.size,
- a = this.axis;
-
- if (isNumber(data.height)) {
- data.width = (data.height * this.aspectRatio);
- } else if (isNumber(data.width)) {
- data.height = (data.width / this.aspectRatio);
- }
-
- if (a === "sw") {
- data.left = cpos.left + (csize.width - data.width);
- data.top = null;
- }
- if (a === "nw") {
- data.top = cpos.top + (csize.height - data.height);
- data.left = cpos.left + (csize.width - data.width);
- }
-
- return data;
- },
-
- _respectSize: function( data ) {
-
- var o = this._vBoundaries,
- a = this.axis,
- ismaxw = isNumber(data.width) && o.maxWidth && (o.maxWidth < data.width), ismaxh = isNumber(data.height) && o.maxHeight && (o.maxHeight < data.height),
- isminw = isNumber(data.width) && o.minWidth && (o.minWidth > data.width), isminh = isNumber(data.height) && o.minHeight && (o.minHeight > data.height),
- dw = this.originalPosition.left + this.originalSize.width,
- dh = this.position.top + this.size.height,
- cw = /sw|nw|w/.test(a), ch = /nw|ne|n/.test(a);
- if (isminw) {
- data.width = o.minWidth;
- }
- if (isminh) {
- data.height = o.minHeight;
- }
- if (ismaxw) {
- data.width = o.maxWidth;
- }
- if (ismaxh) {
- data.height = o.maxHeight;
- }
-
- if (isminw && cw) {
- data.left = dw - o.minWidth;
- }
- if (ismaxw && cw) {
- data.left = dw - o.maxWidth;
- }
- if (isminh && ch) {
- data.top = dh - o.minHeight;
- }
- if (ismaxh && ch) {
- data.top = dh - o.maxHeight;
- }
-
- // fixing jump error on top/left - bug #2330
- if (!data.width && !data.height && !data.left && data.top) {
- data.top = null;
- } else if (!data.width && !data.height && !data.top && data.left) {
- data.left = null;
- }
-
- return data;
- },
-
- _proportionallyResize: function() {
-
- if (!this._proportionallyResizeElements.length) {
- return;
- }
-
- var i, j, borders, paddings, prel,
- element = this.helper || this.element;
-
- for ( i=0; i < this._proportionallyResizeElements.length; i++) {
-
- prel = this._proportionallyResizeElements[i];
-
- if (!this.borderDif) {
- this.borderDif = [];
- borders = [prel.css("borderTopWidth"), prel.css("borderRightWidth"), prel.css("borderBottomWidth"), prel.css("borderLeftWidth")];
- paddings = [prel.css("paddingTop"), prel.css("paddingRight"), prel.css("paddingBottom"), prel.css("paddingLeft")];
-
- for ( j = 0; j < borders.length; j++ ) {
- this.borderDif[ j ] = ( parseInt( borders[ j ], 10 ) || 0 ) + ( parseInt( paddings[ j ], 10 ) || 0 );
- }
- }
-
- prel.css({
- height: (element.height() - this.borderDif[0] - this.borderDif[2]) || 0,
- width: (element.width() - this.borderDif[1] - this.borderDif[3]) || 0
- });
-
- }
-
- },
-
- _renderProxy: function() {
-
- var el = this.element, o = this.options;
- this.elementOffset = el.offset();
-
- if(this._helper) {
-
- this.helper = this.helper || $("<div style='overflow:hidden;'></div>");
-
- this.helper.addClass(this._helper).css({
- width: this.element.outerWidth() - 1,
- height: this.element.outerHeight() - 1,
- position: "absolute",
- left: this.elementOffset.left +"px",
- top: this.elementOffset.top +"px",
- zIndex: ++o.zIndex //TODO: Don't modify option
- });
-
- this.helper
- .appendTo("body")
- .disableSelection();
-
- } else {
- this.helper = this.element;
- }
-
- },
-
- _change: {
- e: function(event, dx) {
- return { width: this.originalSize.width + dx };
- },
- w: function(event, dx) {
- var cs = this.originalSize, sp = this.originalPosition;
- return { left: sp.left + dx, width: cs.width - dx };
- },
- n: function(event, dx, dy) {
- var cs = this.originalSize, sp = this.originalPosition;
- return { top: sp.top + dy, height: cs.height - dy };
- },
- s: function(event, dx, dy) {
- return { height: this.originalSize.height + dy };
- },
- se: function(event, dx, dy) {
- return $.extend(this._change.s.apply(this, arguments), this._change.e.apply(this, [event, dx, dy]));
- },
- sw: function(event, dx, dy) {
- return $.extend(this._change.s.apply(this, arguments), this._change.w.apply(this, [event, dx, dy]));
- },
- ne: function(event, dx, dy) {
- return $.extend(this._change.n.apply(this, arguments), this._change.e.apply(this, [event, dx, dy]));
- },
- nw: function(event, dx, dy) {
- return $.extend(this._change.n.apply(this, arguments), this._change.w.apply(this, [event, dx, dy]));
- }
- },
-
- _propagate: function(n, event) {
- $.ui.plugin.call(this, n, [event, this.ui()]);
- (n !== "resize" && this._trigger(n, event, this.ui()));
- },
-
- plugins: {},
-
- ui: function() {
- return {
- originalElement: this.originalElement,
- element: this.element,
- helper: this.helper,
- position: this.position,
- size: this.size,
- originalSize: this.originalSize,
- originalPosition: this.originalPosition
- };
- }
-
-});
-
-/*
- * Resizable Extensions
- */
-
-$.ui.plugin.add("resizable", "animate", {
-
- stop: function( event ) {
- var that = $(this).data("ui-resizable"),
- o = that.options,
- pr = that._proportionallyResizeElements,
- ista = pr.length && (/textarea/i).test(pr[0].nodeName),
- soffseth = ista && $.ui.hasScroll(pr[0], "left") /* TODO - jump height */ ? 0 : that.sizeDiff.height,
- soffsetw = ista ? 0 : that.sizeDiff.width,
- style = { width: (that.size.width - soffsetw), height: (that.size.height - soffseth) },
- left = (parseInt(that.element.css("left"), 10) + (that.position.left - that.originalPosition.left)) || null,
- top = (parseInt(that.element.css("top"), 10) + (that.position.top - that.originalPosition.top)) || null;
-
- that.element.animate(
- $.extend(style, top && left ? { top: top, left: left } : {}), {
- duration: o.animateDuration,
- easing: o.animateEasing,
- step: function() {
-
- var data = {
- width: parseInt(that.element.css("width"), 10),
- height: parseInt(that.element.css("height"), 10),
- top: parseInt(that.element.css("top"), 10),
- left: parseInt(that.element.css("left"), 10)
- };
-
- if (pr && pr.length) {
- $(pr[0]).css({ width: data.width, height: data.height });
- }
-
- // propagating resize, and updating values for each animation step
- that._updateCache(data);
- that._propagate("resize", event);
-
- }
- }
- );
- }
-
-});
-
-$.ui.plugin.add("resizable", "containment", {
-
- start: function() {
- var element, p, co, ch, cw, width, height,
- that = $(this).data("ui-resizable"),
- o = that.options,
- el = that.element,
- oc = o.containment,
- ce = (oc instanceof $) ? oc.get(0) : (/parent/.test(oc)) ? el.parent().get(0) : oc;
-
- if (!ce) {
- return;
- }
-
- that.containerElement = $(ce);
-
- if (/document/.test(oc) || oc === document) {
- that.containerOffset = { left: 0, top: 0 };
- that.containerPosition = { left: 0, top: 0 };
-
- that.parentData = {
- element: $(document), left: 0, top: 0,
- width: $(document).width(), height: $(document).height() || document.body.parentNode.scrollHeight
- };
- }
-
- // i'm a node, so compute top, left, right, bottom
- else {
- element = $(ce);
- p = [];
- $([ "Top", "Right", "Left", "Bottom" ]).each(function(i, name) { p[i] = num(element.css("padding" + name)); });
-
- that.containerOffset = element.offset();
- that.containerPosition = element.position();
- that.containerSize = { height: (element.innerHeight() - p[3]), width: (element.innerWidth() - p[1]) };
-
- co = that.containerOffset;
- ch = that.containerSize.height;
- cw = that.containerSize.width;
- width = ($.ui.hasScroll(ce, "left") ? ce.scrollWidth : cw );
- height = ($.ui.hasScroll(ce) ? ce.scrollHeight : ch);
-
- that.parentData = {
- element: ce, left: co.left, top: co.top, width: width, height: height
- };
- }
- },
-
- resize: function( event ) {
- var woset, hoset, isParent, isOffsetRelative,
- that = $(this).data("ui-resizable"),
- o = that.options,
- co = that.containerOffset, cp = that.position,
- pRatio = that._aspectRatio || event.shiftKey,
- cop = { top:0, left:0 }, ce = that.containerElement;
-
- if (ce[0] !== document && (/static/).test(ce.css("position"))) {
- cop = co;
- }
-
- if (cp.left < (that._helper ? co.left : 0)) {
- that.size.width = that.size.width + (that._helper ? (that.position.left - co.left) : (that.position.left - cop.left));
- if (pRatio) {
- that.size.height = that.size.width / that.aspectRatio;
- }
- that.position.left = o.helper ? co.left : 0;
- }
-
- if (cp.top < (that._helper ? co.top : 0)) {
- that.size.height = that.size.height + (that._helper ? (that.position.top - co.top) : that.position.top);
- if (pRatio) {
- that.size.width = that.size.height * that.aspectRatio;
- }
- that.position.top = that._helper ? co.top : 0;
- }
-
- that.offset.left = that.parentData.left+that.position.left;
- that.offset.top = that.parentData.top+that.position.top;
-
- woset = Math.abs( (that._helper ? that.offset.left - cop.left : (that.offset.left - cop.left)) + that.sizeDiff.width );
- hoset = Math.abs( (that._helper ? that.offset.top - cop.top : (that.offset.top - co.top)) + that.sizeDiff.height );
-
- isParent = that.containerElement.get(0) === that.element.parent().get(0);
- isOffsetRelative = /relative|absolute/.test(that.containerElement.css("position"));
-
- if ( isParent && isOffsetRelative ) {
- woset -= Math.abs( that.parentData.left );
- }
-
- if (woset + that.size.width >= that.parentData.width) {
- that.size.width = that.parentData.width - woset;
- if (pRatio) {
- that.size.height = that.size.width / that.aspectRatio;
- }
- }
-
- if (hoset + that.size.height >= that.parentData.height) {
- that.size.height = that.parentData.height - hoset;
- if (pRatio) {
- that.size.width = that.size.height * that.aspectRatio;
- }
- }
- },
-
- stop: function(){
- var that = $(this).data("ui-resizable"),
- o = that.options,
- co = that.containerOffset,
- cop = that.containerPosition,
- ce = that.containerElement,
- helper = $(that.helper),
- ho = helper.offset(),
- w = helper.outerWidth() - that.sizeDiff.width,
- h = helper.outerHeight() - that.sizeDiff.height;
-
- if (that._helper && !o.animate && (/relative/).test(ce.css("position"))) {
- $(this).css({ left: ho.left - cop.left - co.left, width: w, height: h });
- }
-
- if (that._helper && !o.animate && (/static/).test(ce.css("position"))) {
- $(this).css({ left: ho.left - cop.left - co.left, width: w, height: h });
- }
-
- }
-});
-
-$.ui.plugin.add("resizable", "alsoResize", {
-
- start: function () {
- var that = $(this).data("ui-resizable"),
- o = that.options,
- _store = function (exp) {
- $(exp).each(function() {
- var el = $(this);
- el.data("ui-resizable-alsoresize", {
- width: parseInt(el.width(), 10), height: parseInt(el.height(), 10),
- left: parseInt(el.css("left"), 10), top: parseInt(el.css("top"), 10)
- });
- });
- };
-
- if (typeof(o.alsoResize) === "object" && !o.alsoResize.parentNode) {
- if (o.alsoResize.length) { o.alsoResize = o.alsoResize[0]; _store(o.alsoResize); }
- else { $.each(o.alsoResize, function (exp) { _store(exp); }); }
- }else{
- _store(o.alsoResize);
- }
- },
-
- resize: function (event, ui) {
- var that = $(this).data("ui-resizable"),
- o = that.options,
- os = that.originalSize,
- op = that.originalPosition,
- delta = {
- height: (that.size.height - os.height) || 0, width: (that.size.width - os.width) || 0,
- top: (that.position.top - op.top) || 0, left: (that.position.left - op.left) || 0
- },
-
- _alsoResize = function (exp, c) {
- $(exp).each(function() {
- var el = $(this), start = $(this).data("ui-resizable-alsoresize"), style = {},
- css = c && c.length ? c : el.parents(ui.originalElement[0]).length ? ["width", "height"] : ["width", "height", "top", "left"];
-
- $.each(css, function (i, prop) {
- var sum = (start[prop]||0) + (delta[prop]||0);
- if (sum && sum >= 0) {
- style[prop] = sum || null;
- }
- });
-
- el.css(style);
- });
- };
-
- if (typeof(o.alsoResize) === "object" && !o.alsoResize.nodeType) {
- $.each(o.alsoResize, function (exp, c) { _alsoResize(exp, c); });
- }else{
- _alsoResize(o.alsoResize);
- }
- },
-
- stop: function () {
- $(this).removeData("resizable-alsoresize");
- }
-});
-
-$.ui.plugin.add("resizable", "ghost", {
-
- start: function() {
-
- var that = $(this).data("ui-resizable"), o = that.options, cs = that.size;
-
- that.ghost = that.originalElement.clone();
- that.ghost
- .css({ opacity: 0.25, display: "block", position: "relative", height: cs.height, width: cs.width, margin: 0, left: 0, top: 0 })
- .addClass("ui-resizable-ghost")
- .addClass(typeof o.ghost === "string" ? o.ghost : "");
-
- that.ghost.appendTo(that.helper);
-
- },
-
- resize: function(){
- var that = $(this).data("ui-resizable");
- if (that.ghost) {
- that.ghost.css({ position: "relative", height: that.size.height, width: that.size.width });
- }
- },
-
- stop: function() {
- var that = $(this).data("ui-resizable");
- if (that.ghost && that.helper) {
- that.helper.get(0).removeChild(that.ghost.get(0));
- }
- }
-
-});
-
-$.ui.plugin.add("resizable", "grid", {
-
- resize: function() {
- var that = $(this).data("ui-resizable"),
- o = that.options,
- cs = that.size,
- os = that.originalSize,
- op = that.originalPosition,
- a = that.axis,
- grid = typeof o.grid === "number" ? [o.grid, o.grid] : o.grid,
- gridX = (grid[0]||1),
- gridY = (grid[1]||1),
- ox = Math.round((cs.width - os.width) / gridX) * gridX,
- oy = Math.round((cs.height - os.height) / gridY) * gridY,
- newWidth = os.width + ox,
- newHeight = os.height + oy,
- isMaxWidth = o.maxWidth && (o.maxWidth < newWidth),
- isMaxHeight = o.maxHeight && (o.maxHeight < newHeight),
- isMinWidth = o.minWidth && (o.minWidth > newWidth),
- isMinHeight = o.minHeight && (o.minHeight > newHeight);
-
- o.grid = grid;
-
- if (isMinWidth) {
- newWidth = newWidth + gridX;
- }
- if (isMinHeight) {
- newHeight = newHeight + gridY;
- }
- if (isMaxWidth) {
- newWidth = newWidth - gridX;
- }
- if (isMaxHeight) {
- newHeight = newHeight - gridY;
- }
-
- if (/^(se|s|e)$/.test(a)) {
- that.size.width = newWidth;
- that.size.height = newHeight;
- } else if (/^(ne)$/.test(a)) {
- that.size.width = newWidth;
- that.size.height = newHeight;
- that.position.top = op.top - oy;
- } else if (/^(sw)$/.test(a)) {
- that.size.width = newWidth;
- that.size.height = newHeight;
- that.position.left = op.left - ox;
- } else {
- if ( newHeight - gridY > 0 ) {
- that.size.height = newHeight;
- that.position.top = op.top - oy;
- } else {
- that.size.height = gridY;
- that.position.top = op.top + os.height - gridY;
- }
- if ( newWidth - gridX > 0 ) {
- that.size.width = newWidth;
- that.position.left = op.left - ox;
- } else {
- that.size.width = gridX;
- that.position.left = op.left + os.width - gridX;
- }
- }
- }
-
-});
-
-})(jQuery);
-(function( $, undefined ) {
-
-$.widget("ui.selectable", $.ui.mouse, {
- version: "1.10.4",
- options: {
- appendTo: "body",
- autoRefresh: true,
- distance: 0,
- filter: "*",
- tolerance: "touch",
-
- // callbacks
- selected: null,
- selecting: null,
- start: null,
- stop: null,
- unselected: null,
- unselecting: null
- },
- _create: function() {
- var selectees,
- that = this;
-
- this.element.addClass("ui-selectable");
-
- this.dragged = false;
-
- // cache selectee children based on filter
- this.refresh = function() {
- selectees = $(that.options.filter, that.element[0]);
- selectees.addClass("ui-selectee");
- selectees.each(function() {
- var $this = $(this),
- pos = $this.offset();
- $.data(this, "selectable-item", {
- element: this,
- $element: $this,
- left: pos.left,
- top: pos.top,
- right: pos.left + $this.outerWidth(),
- bottom: pos.top + $this.outerHeight(),
- startselected: false,
- selected: $this.hasClass("ui-selected"),
- selecting: $this.hasClass("ui-selecting"),
- unselecting: $this.hasClass("ui-unselecting")
- });
- });
- };
- this.refresh();
-
- this.selectees = selectees.addClass("ui-selectee");
-
- this._mouseInit();
-
- this.helper = $("<div class='ui-selectable-helper'></div>");
- },
-
- _destroy: function() {
- this.selectees
- .removeClass("ui-selectee")
- .removeData("selectable-item");
- this.element
- .removeClass("ui-selectable ui-selectable-disabled");
- this._mouseDestroy();
- },
-
- _mouseStart: function(event) {
- var that = this,
- options = this.options;
-
- this.opos = [event.pageX, event.pageY];
-
- if (this.options.disabled) {
- return;
- }
-
- this.selectees = $(options.filter, this.element[0]);
-
- this._trigger("start", event);
-
- $(options.appendTo).append(this.helper);
- // position helper (lasso)
- this.helper.css({
- "left": event.pageX,
- "top": event.pageY,
- "width": 0,
- "height": 0
- });
-
- if (options.autoRefresh) {
- this.refresh();
- }
-
- this.selectees.filter(".ui-selected").each(function() {
- var selectee = $.data(this, "selectable-item");
- selectee.startselected = true;
- if (!event.metaKey && !event.ctrlKey) {
- selectee.$element.removeClass("ui-selected");
- selectee.selected = false;
- selectee.$element.addClass("ui-unselecting");
- selectee.unselecting = true;
- // selectable UNSELECTING callback
- that._trigger("unselecting", event, {
- unselecting: selectee.element
- });
- }
- });
-
- $(event.target).parents().addBack().each(function() {
- var doSelect,
- selectee = $.data(this, "selectable-item");
- if (selectee) {
- doSelect = (!event.metaKey && !event.ctrlKey) || !selectee.$element.hasClass("ui-selected");
- selectee.$element
- .removeClass(doSelect ? "ui-unselecting" : "ui-selected")
- .addClass(doSelect ? "ui-selecting" : "ui-unselecting");
- selectee.unselecting = !doSelect;
- selectee.selecting = doSelect;
- selectee.selected = doSelect;
- // selectable (UN)SELECTING callback
- if (doSelect) {
- that._trigger("selecting", event, {
- selecting: selectee.element
- });
- } else {
- that._trigger("unselecting", event, {
- unselecting: selectee.element
- });
- }
- return false;
- }
- });
-
- },
-
- _mouseDrag: function(event) {
-
- this.dragged = true;
-
- if (this.options.disabled) {
- return;
- }
-
- var tmp,
- that = this,
- options = this.options,
- x1 = this.opos[0],
- y1 = this.opos[1],
- x2 = event.pageX,
- y2 = event.pageY;
-
- if (x1 > x2) { tmp = x2; x2 = x1; x1 = tmp; }
- if (y1 > y2) { tmp = y2; y2 = y1; y1 = tmp; }
- this.helper.css({left: x1, top: y1, width: x2-x1, height: y2-y1});
-
- this.selectees.each(function() {
- var selectee = $.data(this, "selectable-item"),
- hit = false;
-
- //prevent helper from being selected if appendTo: selectable
- if (!selectee || selectee.element === that.element[0]) {
- return;
- }
-
- if (options.tolerance === "touch") {
- hit = ( !(selectee.left > x2 || selectee.right < x1 || selectee.top > y2 || selectee.bottom < y1) );
- } else if (options.tolerance === "fit") {
- hit = (selectee.left > x1 && selectee.right < x2 && selectee.top > y1 && selectee.bottom < y2);
- }
-
- if (hit) {
- // SELECT
- if (selectee.selected) {
- selectee.$element.removeClass("ui-selected");
- selectee.selected = false;
- }
- if (selectee.unselecting) {
- selectee.$element.removeClass("ui-unselecting");
- selectee.unselecting = false;
- }
- if (!selectee.selecting) {
- selectee.$element.addClass("ui-selecting");
- selectee.selecting = true;
- // selectable SELECTING callback
- that._trigger("selecting", event, {
- selecting: selectee.element
- });
- }
- } else {
- // UNSELECT
- if (selectee.selecting) {
- if ((event.metaKey || event.ctrlKey) && selectee.startselected) {
- selectee.$element.removeClass("ui-selecting");
- selectee.selecting = false;
- selectee.$element.addClass("ui-selected");
- selectee.selected = true;
- } else {
- selectee.$element.removeClass("ui-selecting");
- selectee.selecting = false;
- if (selectee.startselected) {
- selectee.$element.addClass("ui-unselecting");
- selectee.unselecting = true;
- }
- // selectable UNSELECTING callback
- that._trigger("unselecting", event, {
- unselecting: selectee.element
- });
- }
- }
- if (selectee.selected) {
- if (!event.metaKey && !event.ctrlKey && !selectee.startselected) {
- selectee.$element.removeClass("ui-selected");
- selectee.selected = false;
-
- selectee.$element.addClass("ui-unselecting");
- selectee.unselecting = true;
- // selectable UNSELECTING callback
- that._trigger("unselecting", event, {
- unselecting: selectee.element
- });
- }
- }
- }
- });
-
- return false;
- },
-
- _mouseStop: function(event) {
- var that = this;
-
- this.dragged = false;
-
- $(".ui-unselecting", this.element[0]).each(function() {
- var selectee = $.data(this, "selectable-item");
- selectee.$element.removeClass("ui-unselecting");
- selectee.unselecting = false;
- selectee.startselected = false;
- that._trigger("unselected", event, {
- unselected: selectee.element
- });
- });
- $(".ui-selecting", this.element[0]).each(function() {
- var selectee = $.data(this, "selectable-item");
- selectee.$element.removeClass("ui-selecting").addClass("ui-selected");
- selectee.selecting = false;
- selectee.selected = true;
- selectee.startselected = true;
- that._trigger("selected", event, {
- selected: selectee.element
- });
- });
- this._trigger("stop", event);
-
- this.helper.remove();
-
- return false;
- }
-
-});
-
-})(jQuery);
-(function( $, undefined ) {
-
-function isOverAxis( x, reference, size ) {
- return ( x > reference ) && ( x < ( reference + size ) );
-}
-
-function isFloating(item) {
- return (/left|right/).test(item.css("float")) || (/inline|table-cell/).test(item.css("display"));
-}
-
-$.widget("ui.sortable", $.ui.mouse, {
- version: "1.10.4",
- widgetEventPrefix: "sort",
- ready: false,
- options: {
- appendTo: "parent",
- axis: false,
- connectWith: false,
- containment: false,
- cursor: "auto",
- cursorAt: false,
- dropOnEmpty: true,
- forcePlaceholderSize: false,
- forceHelperSize: false,
- grid: false,
- handle: false,
- helper: "original",
- items: "> *",
- opacity: false,
- placeholder: false,
- revert: false,
- scroll: true,
- scrollSensitivity: 20,
- scrollSpeed: 20,
- scope: "default",
- tolerance: "intersect",
- zIndex: 1000,
-
- // callbacks
- activate: null,
- beforeStop: null,
- change: null,
- deactivate: null,
- out: null,
- over: null,
- receive: null,
- remove: null,
- sort: null,
- start: null,
- stop: null,
- update: null
- },
- _create: function() {
-
- var o = this.options;
- this.containerCache = {};
- this.element.addClass("ui-sortable");
-
- //Get the items
- this.refresh();
-
- //Let's determine if the items are being displayed horizontally
- this.floating = this.items.length ? o.axis === "x" || isFloating(this.items[0].item) : false;
-
- //Let's determine the parent's offset
- this.offset = this.element.offset();
-
- //Initialize mouse events for interaction
- this._mouseInit();
-
- //We're ready to go
- this.ready = true;
-
- },
-
- _destroy: function() {
- this.element
- .removeClass("ui-sortable ui-sortable-disabled");
- this._mouseDestroy();
-
- for ( var i = this.items.length - 1; i >= 0; i-- ) {
- this.items[i].item.removeData(this.widgetName + "-item");
- }
-
- return this;
- },
-
- _setOption: function(key, value){
- if ( key === "disabled" ) {
- this.options[ key ] = value;
-
- this.widget().toggleClass( "ui-sortable-disabled", !!value );
- } else {
- // Don't call widget base _setOption for disable as it adds ui-state-disabled class
- $.Widget.prototype._setOption.apply(this, arguments);
- }
- },
-
- _mouseCapture: function(event, overrideHandle) {
- var currentItem = null,
- validHandle = false,
- that = this;
-
- if (this.reverting) {
- return false;
- }
-
- if(this.options.disabled || this.options.type === "static") {
- return false;
- }
-
- //We have to refresh the items data once first
- this._refreshItems(event);
-
- //Find out if the clicked node (or one of its parents) is a actual item in this.items
- $(event.target).parents().each(function() {
- if($.data(this, that.widgetName + "-item") === that) {
- currentItem = $(this);
- return false;
- }
- });
- if($.data(event.target, that.widgetName + "-item") === that) {
- currentItem = $(event.target);
- }
-
- if(!currentItem) {
- return false;
- }
- if(this.options.handle && !overrideHandle) {
- $(this.options.handle, currentItem).find("*").addBack().each(function() {
- if(this === event.target) {
- validHandle = true;
- }
- });
- if(!validHandle) {
- return false;
- }
- }
-
- this.currentItem = currentItem;
- this._removeCurrentsFromItems();
- return true;
-
- },
-
- _mouseStart: function(event, overrideHandle, noActivation) {
-
- var i, body,
- o = this.options;
-
- this.currentContainer = this;
-
- //We only need to call refreshPositions, because the refreshItems call has been moved to mouseCapture
- this.refreshPositions();
-
- //Create and append the visible helper
- this.helper = this._createHelper(event);
-
- //Cache the helper size
- this._cacheHelperProportions();
-
- /*
- * - Position generation -
- * This block generates everything position related - it's the core of draggables.
- */
-
- //Cache the margins of the original element
- this._cacheMargins();
-
- //Get the next scrolling parent
- this.scrollParent = this.helper.scrollParent();
-
- //The element's absolute position on the page minus margins
- this.offset = this.currentItem.offset();
- this.offset = {
- top: this.offset.top - this.margins.top,
- left: this.offset.left - this.margins.left
- };
-
- $.extend(this.offset, {
- click: { //Where the click happened, relative to the element
- left: event.pageX - this.offset.left,
- top: event.pageY - this.offset.top
- },
- parent: this._getParentOffset(),
- relative: this._getRelativeOffset() //This is a relative to absolute position minus the actual position calculation - only used for relative positioned helper
- });
-
- // Only after we got the offset, we can change the helper's position to absolute
- // TODO: Still need to figure out a way to make relative sorting possible
- this.helper.css("position", "absolute");
- this.cssPosition = this.helper.css("position");
-
- //Generate the original position
- this.originalPosition = this._generatePosition(event);
- this.originalPageX = event.pageX;
- this.originalPageY = event.pageY;
-
- //Adjust the mouse offset relative to the helper if "cursorAt" is supplied
- (o.cursorAt && this._adjustOffsetFromHelper(o.cursorAt));
-
- //Cache the former DOM position
- this.domPosition = { prev: this.currentItem.prev()[0], parent: this.currentItem.parent()[0] };
-
- //If the helper is not the original, hide the original so it's not playing any role during the drag, won't cause anything bad this way
- if(this.helper[0] !== this.currentItem[0]) {
- this.currentItem.hide();
- }
-
- //Create the placeholder
- this._createPlaceholder();
-
- //Set a containment if given in the options
- if(o.containment) {
- this._setContainment();
- }
-
- if( o.cursor && o.cursor !== "auto" ) { // cursor option
- body = this.document.find( "body" );
-
- // support: IE
- this.storedCursor = body.css( "cursor" );
- body.css( "cursor", o.cursor );
-
- this.storedStylesheet = $( "<style>*{ cursor: "+o.cursor+" !important; }</style>" ).appendTo( body );
- }
-
- if(o.opacity) { // opacity option
- if (this.helper.css("opacity")) {
- this._storedOpacity = this.helper.css("opacity");
- }
- this.helper.css("opacity", o.opacity);
- }
-
- if(o.zIndex) { // zIndex option
- if (this.helper.css("zIndex")) {
- this._storedZIndex = this.helper.css("zIndex");
- }
- this.helper.css("zIndex", o.zIndex);
- }
-
- //Prepare scrolling
- if(this.scrollParent[0] !== document && this.scrollParent[0].tagName !== "HTML") {
- this.overflowOffset = this.scrollParent.offset();
- }
-
- //Call callbacks
- this._trigger("start", event, this._uiHash());
-
- //Recache the helper size
- if(!this._preserveHelperProportions) {
- this._cacheHelperProportions();
- }
-
-
- //Post "activate" events to possible containers
- if( !noActivation ) {
- for ( i = this.containers.length - 1; i >= 0; i-- ) {
- this.containers[ i ]._trigger( "activate", event, this._uiHash( this ) );
- }
- }
-
- //Prepare possible droppables
- if($.ui.ddmanager) {
- $.ui.ddmanager.current = this;
- }
-
- if ($.ui.ddmanager && !o.dropBehaviour) {
- $.ui.ddmanager.prepareOffsets(this, event);
- }
-
- this.dragging = true;
-
- this.helper.addClass("ui-sortable-helper");
- this._mouseDrag(event); //Execute the drag once - this causes the helper not to be visible before getting its correct position
- return true;
-
- },
-
- _mouseDrag: function(event) {
- var i, item, itemElement, intersection,
- o = this.options,
- scrolled = false;
-
- //Compute the helpers position
- this.position = this._generatePosition(event);
- this.positionAbs = this._convertPositionTo("absolute");
-
- if (!this.lastPositionAbs) {
- this.lastPositionAbs = this.positionAbs;
- }
-
- //Do scrolling
- if(this.options.scroll) {
- if(this.scrollParent[0] !== document && this.scrollParent[0].tagName !== "HTML") {
-
- if((this.overflowOffset.top + this.scrollParent[0].offsetHeight) - event.pageY < o.scrollSensitivity) {
- this.scrollParent[0].scrollTop = scrolled = this.scrollParent[0].scrollTop + o.scrollSpeed;
- } else if(event.pageY - this.overflowOffset.top < o.scrollSensitivity) {
- this.scrollParent[0].scrollTop = scrolled = this.scrollParent[0].scrollTop - o.scrollSpeed;
- }
-
- if((this.overflowOffset.left + this.scrollParent[0].offsetWidth) - event.pageX < o.scrollSensitivity) {
- this.scrollParent[0].scrollLeft = scrolled = this.scrollParent[0].scrollLeft + o.scrollSpeed;
- } else if(event.pageX - this.overflowOffset.left < o.scrollSensitivity) {
- this.scrollParent[0].scrollLeft = scrolled = this.scrollParent[0].scrollLeft - o.scrollSpeed;
- }
-
- } else {
-
- if(event.pageY - $(document).scrollTop() < o.scrollSensitivity) {
- scrolled = $(document).scrollTop($(document).scrollTop() - o.scrollSpeed);
- } else if($(window).height() - (event.pageY - $(document).scrollTop()) < o.scrollSensitivity) {
- scrolled = $(document).scrollTop($(document).scrollTop() + o.scrollSpeed);
- }
-
- if(event.pageX - $(document).scrollLeft() < o.scrollSensitivity) {
- scrolled = $(document).scrollLeft($(document).scrollLeft() - o.scrollSpeed);
- } else if($(window).width() - (event.pageX - $(document).scrollLeft()) < o.scrollSensitivity) {
- scrolled = $(document).scrollLeft($(document).scrollLeft() + o.scrollSpeed);
- }
-
- }
-
- if(scrolled !== false && $.ui.ddmanager && !o.dropBehaviour) {
- $.ui.ddmanager.prepareOffsets(this, event);
- }
- }
-
- //Regenerate the absolute position used for position checks
- this.positionAbs = this._convertPositionTo("absolute");
-
- //Set the helper position
- if(!this.options.axis || this.options.axis !== "y") {
- this.helper[0].style.left = this.position.left+"px";
- }
- if(!this.options.axis || this.options.axis !== "x") {
- this.helper[0].style.top = this.position.top+"px";
- }
-
- //Rearrange
- for (i = this.items.length - 1; i >= 0; i--) {
-
- //Cache variables and intersection, continue if no intersection
- item = this.items[i];
- itemElement = item.item[0];
- intersection = this._intersectsWithPointer(item);
- if (!intersection) {
- continue;
- }
-
- // Only put the placeholder inside the current Container, skip all
- // items from other containers. This works because when moving
- // an item from one container to another the
- // currentContainer is switched before the placeholder is moved.
- //
- // Without this, moving items in "sub-sortables" can cause
- // the placeholder to jitter beetween the outer and inner container.
- if (item.instance !== this.currentContainer) {
- continue;
- }
-
- // cannot intersect with itself
- // no useless actions that have been done before
- // no action if the item moved is the parent of the item checked
- if (itemElement !== this.currentItem[0] &&
- this.placeholder[intersection === 1 ? "next" : "prev"]()[0] !== itemElement &&
- !$.contains(this.placeholder[0], itemElement) &&
- (this.options.type === "semi-dynamic" ? !$.contains(this.element[0], itemElement) : true)
- ) {
-
- this.direction = intersection === 1 ? "down" : "up";
-
- if (this.options.tolerance === "pointer" || this._intersectsWithSides(item)) {
- this._rearrange(event, item);
- } else {
- break;
- }
-
- this._trigger("change", event, this._uiHash());
- break;
- }
- }
-
- //Post events to containers
- this._contactContainers(event);
-
- //Interconnect with droppables
- if($.ui.ddmanager) {
- $.ui.ddmanager.drag(this, event);
- }
-
- //Call callbacks
- this._trigger("sort", event, this._uiHash());
-
- this.lastPositionAbs = this.positionAbs;
- return false;
-
- },
-
- _mouseStop: function(event, noPropagation) {
-
- if(!event) {
- return;
- }
-
- //If we are using droppables, inform the manager about the drop
- if ($.ui.ddmanager && !this.options.dropBehaviour) {
- $.ui.ddmanager.drop(this, event);
- }
-
- if(this.options.revert) {
- var that = this,
- cur = this.placeholder.offset(),
- axis = this.options.axis,
- animation = {};
-
- if ( !axis || axis === "x" ) {
- animation.left = cur.left - this.offset.parent.left - this.margins.left + (this.offsetParent[0] === document.body ? 0 : this.offsetParent[0].scrollLeft);
- }
- if ( !axis || axis === "y" ) {
- animation.top = cur.top - this.offset.parent.top - this.margins.top + (this.offsetParent[0] === document.body ? 0 : this.offsetParent[0].scrollTop);
- }
- this.reverting = true;
- $(this.helper).animate( animation, parseInt(this.options.revert, 10) || 500, function() {
- that._clear(event);
- });
- } else {
- this._clear(event, noPropagation);
- }
-
- return false;
-
- },
-
- cancel: function() {
-
- if(this.dragging) {
-
- this._mouseUp({ target: null });
-
- if(this.options.helper === "original") {
- this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper");
- } else {
- this.currentItem.show();
- }
-
- //Post deactivating events to containers
- for (var i = this.containers.length - 1; i >= 0; i--){
- this.containers[i]._trigger("deactivate", null, this._uiHash(this));
- if(this.containers[i].containerCache.over) {
- this.containers[i]._trigger("out", null, this._uiHash(this));
- this.containers[i].containerCache.over = 0;
- }
- }
-
- }
-
- if (this.placeholder) {
- //$(this.placeholder[0]).remove(); would have been the jQuery way - unfortunately, it unbinds ALL events from the original node!
- if(this.placeholder[0].parentNode) {
- this.placeholder[0].parentNode.removeChild(this.placeholder[0]);
- }
- if(this.options.helper !== "original" && this.helper && this.helper[0].parentNode) {
- this.helper.remove();
- }
-
- $.extend(this, {
- helper: null,
- dragging: false,
- reverting: false,
- _noFinalSort: null
- });
-
- if(this.domPosition.prev) {
- $(this.domPosition.prev).after(this.currentItem);
- } else {
- $(this.domPosition.parent).prepend(this.currentItem);
- }
- }
-
- return this;
-
- },
-
- serialize: function(o) {
-
- var items = this._getItemsAsjQuery(o && o.connected),
- str = [];
- o = o || {};
-
- $(items).each(function() {
- var res = ($(o.item || this).attr(o.attribute || "id") || "").match(o.expression || (/(.+)[\-=_](.+)/));
- if (res) {
- str.push((o.key || res[1]+"[]")+"="+(o.key && o.expression ? res[1] : res[2]));
- }
- });
-
- if(!str.length && o.key) {
- str.push(o.key + "=");
- }
-
- return str.join("&");
-
- },
-
- toArray: function(o) {
-
- var items = this._getItemsAsjQuery(o && o.connected),
- ret = [];
-
- o = o || {};
-
- items.each(function() { ret.push($(o.item || this).attr(o.attribute || "id") || ""); });
- return ret;
-
- },
-
- /* Be careful with the following core functions */
- _intersectsWith: function(item) {
-
- var x1 = this.positionAbs.left,
- x2 = x1 + this.helperProportions.width,
- y1 = this.positionAbs.top,
- y2 = y1 + this.helperProportions.height,
- l = item.left,
- r = l + item.width,
- t = item.top,
- b = t + item.height,
- dyClick = this.offset.click.top,
- dxClick = this.offset.click.left,
- isOverElementHeight = ( this.options.axis === "x" ) || ( ( y1 + dyClick ) > t && ( y1 + dyClick ) < b ),
- isOverElementWidth = ( this.options.axis === "y" ) || ( ( x1 + dxClick ) > l && ( x1 + dxClick ) < r ),
- isOverElement = isOverElementHeight && isOverElementWidth;
-
- if ( this.options.tolerance === "pointer" ||
- this.options.forcePointerForContainers ||
- (this.options.tolerance !== "pointer" && this.helperProportions[this.floating ? "width" : "height"] > item[this.floating ? "width" : "height"])
- ) {
- return isOverElement;
- } else {
-
- return (l < x1 + (this.helperProportions.width / 2) && // Right Half
- x2 - (this.helperProportions.width / 2) < r && // Left Half
- t < y1 + (this.helperProportions.height / 2) && // Bottom Half
- y2 - (this.helperProportions.height / 2) < b ); // Top Half
-
- }
- },
-
- _intersectsWithPointer: function(item) {
-
- var isOverElementHeight = (this.options.axis === "x") || isOverAxis(this.positionAbs.top + this.offset.click.top, item.top, item.height),
- isOverElementWidth = (this.options.axis === "y") || isOverAxis(this.positionAbs.left + this.offset.click.left, item.left, item.width),
- isOverElement = isOverElementHeight && isOverElementWidth,
- verticalDirection = this._getDragVerticalDirection(),
- horizontalDirection = this._getDragHorizontalDirection();
-
- if (!isOverElement) {
- return false;
- }
-
- return this.floating ?
- ( ((horizontalDirection && horizontalDirection === "right") || verticalDirection === "down") ? 2 : 1 )
- : ( verticalDirection && (verticalDirection === "down" ? 2 : 1) );
-
- },
-
- _intersectsWithSides: function(item) {
-
- var isOverBottomHalf = isOverAxis(this.positionAbs.top + this.offset.click.top, item.top + (item.height/2), item.height),
- isOverRightHalf = isOverAxis(this.positionAbs.left + this.offset.click.left, item.left + (item.width/2), item.width),
- verticalDirection = this._getDragVerticalDirection(),
- horizontalDirection = this._getDragHorizontalDirection();
-
- if (this.floating && horizontalDirection) {
- return ((horizontalDirection === "right" && isOverRightHalf) || (horizontalDirection === "left" && !isOverRightHalf));
- } else {
- return verticalDirection && ((verticalDirection === "down" && isOverBottomHalf) || (verticalDirection === "up" && !isOverBottomHalf));
- }
-
- },
-
- _getDragVerticalDirection: function() {
- var delta = this.positionAbs.top - this.lastPositionAbs.top;
- return delta !== 0 && (delta > 0 ? "down" : "up");
- },
-
- _getDragHorizontalDirection: function() {
- var delta = this.positionAbs.left - this.lastPositionAbs.left;
- return delta !== 0 && (delta > 0 ? "right" : "left");
- },
-
- refresh: function(event) {
- this._refreshItems(event);
- this.refreshPositions();
- return this;
- },
-
- _connectWith: function() {
- var options = this.options;
- return options.connectWith.constructor === String ? [options.connectWith] : options.connectWith;
- },
-
- _getItemsAsjQuery: function(connected) {
-
- var i, j, cur, inst,
- items = [],
- queries = [],
- connectWith = this._connectWith();
-
- if(connectWith && connected) {
- for (i = connectWith.length - 1; i >= 0; i--){
- cur = $(connectWith[i]);
- for ( j = cur.length - 1; j >= 0; j--){
- inst = $.data(cur[j], this.widgetFullName);
- if(inst && inst !== this && !inst.options.disabled) {
- queries.push([$.isFunction(inst.options.items) ? inst.options.items.call(inst.element) : $(inst.options.items, inst.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"), inst]);
- }
- }
- }
- }
-
- queries.push([$.isFunction(this.options.items) ? this.options.items.call(this.element, null, { options: this.options, item: this.currentItem }) : $(this.options.items, this.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"), this]);
-
- function addItems() {
- items.push( this );
- }
- for (i = queries.length - 1; i >= 0; i--){
- queries[i][0].each( addItems );
- }
-
- return $(items);
-
- },
-
- _removeCurrentsFromItems: function() {
-
- var list = this.currentItem.find(":data(" + this.widgetName + "-item)");
-
- this.items = $.grep(this.items, function (item) {
- for (var j=0; j < list.length; j++) {
- if(list[j] === item.item[0]) {
- return false;
- }
- }
- return true;
- });
-
- },
-
- _refreshItems: function(event) {
-
- this.items = [];
- this.containers = [this];
-
- var i, j, cur, inst, targetData, _queries, item, queriesLength,
- items = this.items,
- queries = [[$.isFunction(this.options.items) ? this.options.items.call(this.element[0], event, { item: this.currentItem }) : $(this.options.items, this.element), this]],
- connectWith = this._connectWith();
-
- if(connectWith && this.ready) { //Shouldn't be run the first time through due to massive slow-down
- for (i = connectWith.length - 1; i >= 0; i--){
- cur = $(connectWith[i]);
- for (j = cur.length - 1; j >= 0; j--){
- inst = $.data(cur[j], this.widgetFullName);
- if(inst && inst !== this && !inst.options.disabled) {
- queries.push([$.isFunction(inst.options.items) ? inst.options.items.call(inst.element[0], event, { item: this.currentItem }) : $(inst.options.items, inst.element), inst]);
- this.containers.push(inst);
- }
- }
- }
- }
-
- for (i = queries.length - 1; i >= 0; i--) {
- targetData = queries[i][1];
- _queries = queries[i][0];
-
- for (j=0, queriesLength = _queries.length; j < queriesLength; j++) {
- item = $(_queries[j]);
-
- item.data(this.widgetName + "-item", targetData); // Data for target checking (mouse manager)
-
- items.push({
- item: item,
- instance: targetData,
- width: 0, height: 0,
- left: 0, top: 0
- });
- }
- }
-
- },
-
- refreshPositions: function(fast) {
-
- //This has to be redone because due to the item being moved out/into the offsetParent, the offsetParent's position will change
- if(this.offsetParent && this.helper) {
- this.offset.parent = this._getParentOffset();
- }
-
- var i, item, t, p;
-
- for (i = this.items.length - 1; i >= 0; i--){
- item = this.items[i];
-
- //We ignore calculating positions of all connected containers when we're not over them
- if(item.instance !== this.currentContainer && this.currentContainer && item.item[0] !== this.currentItem[0]) {
- continue;
- }
-
- t = this.options.toleranceElement ? $(this.options.toleranceElement, item.item) : item.item;
-
- if (!fast) {
- item.width = t.outerWidth();
- item.height = t.outerHeight();
- }
-
- p = t.offset();
- item.left = p.left;
- item.top = p.top;
- }
-
- if(this.options.custom && this.options.custom.refreshContainers) {
- this.options.custom.refreshContainers.call(this);
- } else {
- for (i = this.containers.length - 1; i >= 0; i--){
- p = this.containers[i].element.offset();
- this.containers[i].containerCache.left = p.left;
- this.containers[i].containerCache.top = p.top;
- this.containers[i].containerCache.width = this.containers[i].element.outerWidth();
- this.containers[i].containerCache.height = this.containers[i].element.outerHeight();
- }
- }
-
- return this;
- },
-
- _createPlaceholder: function(that) {
- that = that || this;
- var className,
- o = that.options;
-
- if(!o.placeholder || o.placeholder.constructor === String) {
- className = o.placeholder;
- o.placeholder = {
- element: function() {
-
- var nodeName = that.currentItem[0].nodeName.toLowerCase(),
- element = $( "<" + nodeName + ">", that.document[0] )
- .addClass(className || that.currentItem[0].className+" ui-sortable-placeholder")
- .removeClass("ui-sortable-helper");
-
- if ( nodeName === "tr" ) {
- that.currentItem.children().each(function() {
- $( "<td> </td>", that.document[0] )
- .attr( "colspan", $( this ).attr( "colspan" ) || 1 )
- .appendTo( element );
- });
- } else if ( nodeName === "img" ) {
- element.attr( "src", that.currentItem.attr( "src" ) );
- }
-
- if ( !className ) {
- element.css( "visibility", "hidden" );
- }
-
- return element;
- },
- update: function(container, p) {
-
- // 1. If a className is set as 'placeholder option, we don't force sizes - the class is responsible for that
- // 2. The option 'forcePlaceholderSize can be enabled to force it even if a class name is specified
- if(className && !o.forcePlaceholderSize) {
- return;
- }
-
- //If the element doesn't have a actual height by itself (without styles coming from a stylesheet), it receives the inline height from the dragged item
- if(!p.height()) { p.height(that.currentItem.innerHeight() - parseInt(that.currentItem.css("paddingTop")||0, 10) - parseInt(that.currentItem.css("paddingBottom")||0, 10)); }
- if(!p.width()) { p.width(that.currentItem.innerWidth() - parseInt(that.currentItem.css("paddingLeft")||0, 10) - parseInt(that.currentItem.css("paddingRight")||0, 10)); }
- }
- };
- }
-
- //Create the placeholder
- that.placeholder = $(o.placeholder.element.call(that.element, that.currentItem));
-
- //Append it after the actual current item
- that.currentItem.after(that.placeholder);
-
- //Update the size of the placeholder (TODO: Logic to fuzzy, see line 316/317)
- o.placeholder.update(that, that.placeholder);
-
- },
-
- _contactContainers: function(event) {
- var i, j, dist, itemWithLeastDistance, posProperty, sizeProperty, base, cur, nearBottom, floating,
- innermostContainer = null,
- innermostIndex = null;
-
- // get innermost container that intersects with item
- for (i = this.containers.length - 1; i >= 0; i--) {
-
- // never consider a container that's located within the item itself
- if($.contains(this.currentItem[0], this.containers[i].element[0])) {
- continue;
- }
-
- if(this._intersectsWith(this.containers[i].containerCache)) {
-
- // if we've already found a container and it's more "inner" than this, then continue
- if(innermostContainer && $.contains(this.containers[i].element[0], innermostContainer.element[0])) {
- continue;
- }
-
- innermostContainer = this.containers[i];
- innermostIndex = i;
-
- } else {
- // container doesn't intersect. trigger "out" event if necessary
- if(this.containers[i].containerCache.over) {
- this.containers[i]._trigger("out", event, this._uiHash(this));
- this.containers[i].containerCache.over = 0;
- }
- }
-
- }
-
- // if no intersecting containers found, return
- if(!innermostContainer) {
- return;
- }
-
- // move the item into the container if it's not there already
- if(this.containers.length === 1) {
- if (!this.containers[innermostIndex].containerCache.over) {
- this.containers[innermostIndex]._trigger("over", event, this._uiHash(this));
- this.containers[innermostIndex].containerCache.over = 1;
- }
- } else {
-
- //When entering a new container, we will find the item with the least distance and append our item near it
- dist = 10000;
- itemWithLeastDistance = null;
- floating = innermostContainer.floating || isFloating(this.currentItem);
- posProperty = floating ? "left" : "top";
- sizeProperty = floating ? "width" : "height";
- base = this.positionAbs[posProperty] + this.offset.click[posProperty];
- for (j = this.items.length - 1; j >= 0; j--) {
- if(!$.contains(this.containers[innermostIndex].element[0], this.items[j].item[0])) {
- continue;
- }
- if(this.items[j].item[0] === this.currentItem[0]) {
- continue;
- }
- if (floating && !isOverAxis(this.positionAbs.top + this.offset.click.top, this.items[j].top, this.items[j].height)) {
- continue;
- }
- cur = this.items[j].item.offset()[posProperty];
- nearBottom = false;
- if(Math.abs(cur - base) > Math.abs(cur + this.items[j][sizeProperty] - base)){
- nearBottom = true;
- cur += this.items[j][sizeProperty];
- }
-
- if(Math.abs(cur - base) < dist) {
- dist = Math.abs(cur - base); itemWithLeastDistance = this.items[j];
- this.direction = nearBottom ? "up": "down";
- }
- }
-
- //Check if dropOnEmpty is enabled
- if(!itemWithLeastDistance && !this.options.dropOnEmpty) {
- return;
- }
-
- if(this.currentContainer === this.containers[innermostIndex]) {
- return;
- }
-
- itemWithLeastDistance ? this._rearrange(event, itemWithLeastDistance, null, true) : this._rearrange(event, null, this.containers[innermostIndex].element, true);
- this._trigger("change", event, this._uiHash());
- this.containers[innermostIndex]._trigger("change", event, this._uiHash(this));
- this.currentContainer = this.containers[innermostIndex];
-
- //Update the placeholder
- this.options.placeholder.update(this.currentContainer, this.placeholder);
-
- this.containers[innermostIndex]._trigger("over", event, this._uiHash(this));
- this.containers[innermostIndex].containerCache.over = 1;
- }
-
-
- },
-
- _createHelper: function(event) {
-
- var o = this.options,
- helper = $.isFunction(o.helper) ? $(o.helper.apply(this.element[0], [event, this.currentItem])) : (o.helper === "clone" ? this.currentItem.clone() : this.currentItem);
-
- //Add the helper to the DOM if that didn't happen already
- if(!helper.parents("body").length) {
- $(o.appendTo !== "parent" ? o.appendTo : this.currentItem[0].parentNode)[0].appendChild(helper[0]);
- }
-
- if(helper[0] === this.currentItem[0]) {
- this._storedCSS = { width: this.currentItem[0].style.width, height: this.currentItem[0].style.height, position: this.currentItem.css("position"), top: this.currentItem.css("top"), left: this.currentItem.css("left") };
- }
-
- if(!helper[0].style.width || o.forceHelperSize) {
- helper.width(this.currentItem.width());
- }
- if(!helper[0].style.height || o.forceHelperSize) {
- helper.height(this.currentItem.height());
- }
-
- return helper;
-
- },
-
- _adjustOffsetFromHelper: function(obj) {
- if (typeof obj === "string") {
- obj = obj.split(" ");
- }
- if ($.isArray(obj)) {
- obj = {left: +obj[0], top: +obj[1] || 0};
- }
- if ("left" in obj) {
- this.offset.click.left = obj.left + this.margins.left;
- }
- if ("right" in obj) {
- this.offset.click.left = this.helperProportions.width - obj.right + this.margins.left;
- }
- if ("top" in obj) {
- this.offset.click.top = obj.top + this.margins.top;
- }
- if ("bottom" in obj) {
- this.offset.click.top = this.helperProportions.height - obj.bottom + this.margins.top;
- }
- },
-
- _getParentOffset: function() {
-
-
- //Get the offsetParent and cache its position
- this.offsetParent = this.helper.offsetParent();
- var po = this.offsetParent.offset();
-
- // This is a special case where we need to modify a offset calculated on start, since the following happened:
- // 1. The position of the helper is absolute, so it's position is calculated based on the next positioned parent
- // 2. The actual offset parent is a child of the scroll parent, and the scroll parent isn't the document, which means that
- // the scroll is included in the initial calculation of the offset of the parent, and never recalculated upon drag
- if(this.cssPosition === "absolute" && this.scrollParent[0] !== document && $.contains(this.scrollParent[0], this.offsetParent[0])) {
- po.left += this.scrollParent.scrollLeft();
- po.top += this.scrollParent.scrollTop();
- }
-
- // This needs to be actually done for all browsers, since pageX/pageY includes this information
- // with an ugly IE fix
- if( this.offsetParent[0] === document.body || (this.offsetParent[0].tagName && this.offsetParent[0].tagName.toLowerCase() === "html" && $.ui.ie)) {
- po = { top: 0, left: 0 };
- }
-
- return {
- top: po.top + (parseInt(this.offsetParent.css("borderTopWidth"),10) || 0),
- left: po.left + (parseInt(this.offsetParent.css("borderLeftWidth"),10) || 0)
- };
-
- },
-
- _getRelativeOffset: function() {
-
- if(this.cssPosition === "relative") {
- var p = this.currentItem.position();
- return {
- top: p.top - (parseInt(this.helper.css("top"),10) || 0) + this.scrollParent.scrollTop(),
- left: p.left - (parseInt(this.helper.css("left"),10) || 0) + this.scrollParent.scrollLeft()
- };
- } else {
- return { top: 0, left: 0 };
- }
-
- },
-
- _cacheMargins: function() {
- this.margins = {
- left: (parseInt(this.currentItem.css("marginLeft"),10) || 0),
- top: (parseInt(this.currentItem.css("marginTop"),10) || 0)
- };
- },
-
- _cacheHelperProportions: function() {
- this.helperProportions = {
- width: this.helper.outerWidth(),
- height: this.helper.outerHeight()
- };
- },
-
- _setContainment: function() {
-
- var ce, co, over,
- o = this.options;
- if(o.containment === "parent") {
- o.containment = this.helper[0].parentNode;
- }
- if(o.containment === "document" || o.containment === "window") {
- this.containment = [
- 0 - this.offset.relative.left - this.offset.parent.left,
- 0 - this.offset.relative.top - this.offset.parent.top,
- $(o.containment === "document" ? document : window).width() - this.helperProportions.width - this.margins.left,
- ($(o.containment === "document" ? document : window).height() || document.body.parentNode.scrollHeight) - this.helperProportions.height - this.margins.top
- ];
- }
-
- if(!(/^(document|window|parent)$/).test(o.containment)) {
- ce = $(o.containment)[0];
- co = $(o.containment).offset();
- over = ($(ce).css("overflow") !== "hidden");
-
- this.containment = [
- co.left + (parseInt($(ce).css("borderLeftWidth"),10) || 0) + (parseInt($(ce).css("paddingLeft"),10) || 0) - this.margins.left,
- co.top + (parseInt($(ce).css("borderTopWidth"),10) || 0) + (parseInt($(ce).css("paddingTop"),10) || 0) - this.margins.top,
- co.left+(over ? Math.max(ce.scrollWidth,ce.offsetWidth) : ce.offsetWidth) - (parseInt($(ce).css("borderLeftWidth"),10) || 0) - (parseInt($(ce).css("paddingRight"),10) || 0) - this.helperProportions.width - this.margins.left,
- co.top+(over ? Math.max(ce.scrollHeight,ce.offsetHeight) : ce.offsetHeight) - (parseInt($(ce).css("borderTopWidth"),10) || 0) - (parseInt($(ce).css("paddingBottom"),10) || 0) - this.helperProportions.height - this.margins.top
- ];
- }
-
- },
-
- _convertPositionTo: function(d, pos) {
-
- if(!pos) {
- pos = this.position;
- }
- var mod = d === "absolute" ? 1 : -1,
- scroll = this.cssPosition === "absolute" && !(this.scrollParent[0] !== document && $.contains(this.scrollParent[0], this.offsetParent[0])) ? this.offsetParent : this.scrollParent,
- scrollIsRootNode = (/(html|body)/i).test(scroll[0].tagName);
-
- return {
- top: (
- pos.top + // The absolute mouse position
- this.offset.relative.top * mod + // Only for relative positioned nodes: Relative offset from element to offset parent
- this.offset.parent.top * mod - // The offsetParent's offset without borders (offset + border)
- ( ( this.cssPosition === "fixed" ? -this.scrollParent.scrollTop() : ( scrollIsRootNode ? 0 : scroll.scrollTop() ) ) * mod)
- ),
- left: (
- pos.left + // The absolute mouse position
- this.offset.relative.left * mod + // Only for relative positioned nodes: Relative offset from element to offset parent
- this.offset.parent.left * mod - // The offsetParent's offset without borders (offset + border)
- ( ( this.cssPosition === "fixed" ? -this.scrollParent.scrollLeft() : scrollIsRootNode ? 0 : scroll.scrollLeft() ) * mod)
- )
- };
-
- },
-
- _generatePosition: function(event) {
-
- var top, left,
- o = this.options,
- pageX = event.pageX,
- pageY = event.pageY,
- scroll = this.cssPosition === "absolute" && !(this.scrollParent[0] !== document && $.contains(this.scrollParent[0], this.offsetParent[0])) ? this.offsetParent : this.scrollParent, scrollIsRootNode = (/(html|body)/i).test(scroll[0].tagName);
-
- // This is another very weird special case that only happens for relative elements:
- // 1. If the css position is relative
- // 2. and the scroll parent is the document or similar to the offset parent
- // we have to refresh the relative offset during the scroll so there are no jumps
- if(this.cssPosition === "relative" && !(this.scrollParent[0] !== document && this.scrollParent[0] !== this.offsetParent[0])) {
- this.offset.relative = this._getRelativeOffset();
- }
-
- /*
- * - Position constraining -
- * Constrain the position to a mix of grid, containment.
- */
-
- if(this.originalPosition) { //If we are not dragging yet, we won't check for options
-
- if(this.containment) {
- if(event.pageX - this.offset.click.left < this.containment[0]) {
- pageX = this.containment[0] + this.offset.click.left;
- }
- if(event.pageY - this.offset.click.top < this.containment[1]) {
- pageY = this.containment[1] + this.offset.click.top;
- }
- if(event.pageX - this.offset.click.left > this.containment[2]) {
- pageX = this.containment[2] + this.offset.click.left;
- }
- if(event.pageY - this.offset.click.top > this.containment[3]) {
- pageY = this.containment[3] + this.offset.click.top;
- }
- }
-
- if(o.grid) {
- top = this.originalPageY + Math.round((pageY - this.originalPageY) / o.grid[1]) * o.grid[1];
- pageY = this.containment ? ( (top - this.offset.click.top >= this.containment[1] && top - this.offset.click.top <= this.containment[3]) ? top : ((top - this.offset.click.top >= this.containment[1]) ? top - o.grid[1] : top + o.grid[1])) : top;
-
- left = this.originalPageX + Math.round((pageX - this.originalPageX) / o.grid[0]) * o.grid[0];
- pageX = this.containment ? ( (left - this.offset.click.left >= this.containment[0] && left - this.offset.click.left <= this.containment[2]) ? left : ((left - this.offset.click.left >= this.containment[0]) ? left - o.grid[0] : left + o.grid[0])) : left;
- }
-
- }
-
- return {
- top: (
- pageY - // The absolute mouse position
- this.offset.click.top - // Click offset (relative to the element)
- this.offset.relative.top - // Only for relative positioned nodes: Relative offset from element to offset parent
- this.offset.parent.top + // The offsetParent's offset without borders (offset + border)
- ( ( this.cssPosition === "fixed" ? -this.scrollParent.scrollTop() : ( scrollIsRootNode ? 0 : scroll.scrollTop() ) ))
- ),
- left: (
- pageX - // The absolute mouse position
- this.offset.click.left - // Click offset (relative to the element)
- this.offset.relative.left - // Only for relative positioned nodes: Relative offset from element to offset parent
- this.offset.parent.left + // The offsetParent's offset without borders (offset + border)
- ( ( this.cssPosition === "fixed" ? -this.scrollParent.scrollLeft() : scrollIsRootNode ? 0 : scroll.scrollLeft() ))
- )
- };
-
- },
-
- _rearrange: function(event, i, a, hardRefresh) {
-
- a ? a[0].appendChild(this.placeholder[0]) : i.item[0].parentNode.insertBefore(this.placeholder[0], (this.direction === "down" ? i.item[0] : i.item[0].nextSibling));
-
- //Various things done here to improve the performance:
- // 1. we create a setTimeout, that calls refreshPositions
- // 2. on the instance, we have a counter variable, that get's higher after every append
- // 3. on the local scope, we copy the counter variable, and check in the timeout, if it's still the same
- // 4. this lets only the last addition to the timeout stack through
- this.counter = this.counter ? ++this.counter : 1;
- var counter = this.counter;
-
- this._delay(function() {
- if(counter === this.counter) {
- this.refreshPositions(!hardRefresh); //Precompute after each DOM insertion, NOT on mousemove
- }
- });
-
- },
-
- _clear: function(event, noPropagation) {
-
- this.reverting = false;
- // We delay all events that have to be triggered to after the point where the placeholder has been removed and
- // everything else normalized again
- var i,
- delayedTriggers = [];
-
- // We first have to update the dom position of the actual currentItem
- // Note: don't do it if the current item is already removed (by a user), or it gets reappended (see #4088)
- if(!this._noFinalSort && this.currentItem.parent().length) {
- this.placeholder.before(this.currentItem);
- }
- this._noFinalSort = null;
-
- if(this.helper[0] === this.currentItem[0]) {
- for(i in this._storedCSS) {
- if(this._storedCSS[i] === "auto" || this._storedCSS[i] === "static") {
- this._storedCSS[i] = "";
- }
- }
- this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper");
- } else {
- this.currentItem.show();
- }
-
- if(this.fromOutside && !noPropagation) {
- delayedTriggers.push(function(event) { this._trigger("receive", event, this._uiHash(this.fromOutside)); });
- }
- if((this.fromOutside || this.domPosition.prev !== this.currentItem.prev().not(".ui-sortable-helper")[0] || this.domPosition.parent !== this.currentItem.parent()[0]) && !noPropagation) {
- delayedTriggers.push(function(event) { this._trigger("update", event, this._uiHash()); }); //Trigger update callback if the DOM position has changed
- }
-
- // Check if the items Container has Changed and trigger appropriate
- // events.
- if (this !== this.currentContainer) {
- if(!noPropagation) {
- delayedTriggers.push(function(event) { this._trigger("remove", event, this._uiHash()); });
- delayedTriggers.push((function(c) { return function(event) { c._trigger("receive", event, this._uiHash(this)); }; }).call(this, this.currentContainer));
- delayedTriggers.push((function(c) { return function(event) { c._trigger("update", event, this._uiHash(this)); }; }).call(this, this.currentContainer));
- }
- }
-
-
- //Post events to containers
- function delayEvent( type, instance, container ) {
- return function( event ) {
- container._trigger( type, event, instance._uiHash( instance ) );
- };
- }
- for (i = this.containers.length - 1; i >= 0; i--){
- if (!noPropagation) {
- delayedTriggers.push( delayEvent( "deactivate", this, this.containers[ i ] ) );
- }
- if(this.containers[i].containerCache.over) {
- delayedTriggers.push( delayEvent( "out", this, this.containers[ i ] ) );
- this.containers[i].containerCache.over = 0;
- }
- }
-
- //Do what was originally in plugins
- if ( this.storedCursor ) {
- this.document.find( "body" ).css( "cursor", this.storedCursor );
- this.storedStylesheet.remove();
- }
- if(this._storedOpacity) {
- this.helper.css("opacity", this._storedOpacity);
- }
- if(this._storedZIndex) {
- this.helper.css("zIndex", this._storedZIndex === "auto" ? "" : this._storedZIndex);
- }
-
- this.dragging = false;
- if(this.cancelHelperRemoval) {
- if(!noPropagation) {
- this._trigger("beforeStop", event, this._uiHash());
- for (i=0; i < delayedTriggers.length; i++) {
- delayedTriggers[i].call(this, event);
- } //Trigger all delayed events
- this._trigger("stop", event, this._uiHash());
- }
-
- this.fromOutside = false;
- return false;
- }
-
- if(!noPropagation) {
- this._trigger("beforeStop", event, this._uiHash());
- }
-
- //$(this.placeholder[0]).remove(); would have been the jQuery way - unfortunately, it unbinds ALL events from the original node!
- this.placeholder[0].parentNode.removeChild(this.placeholder[0]);
-
- if(this.helper[0] !== this.currentItem[0]) {
- this.helper.remove();
- }
- this.helper = null;
-
- if(!noPropagation) {
- for (i=0; i < delayedTriggers.length; i++) {
- delayedTriggers[i].call(this, event);
- } //Trigger all delayed events
- this._trigger("stop", event, this._uiHash());
- }
-
- this.fromOutside = false;
- return true;
-
- },
-
- _trigger: function() {
- if ($.Widget.prototype._trigger.apply(this, arguments) === false) {
- this.cancel();
- }
- },
-
- _uiHash: function(_inst) {
- var inst = _inst || this;
- return {
- helper: inst.helper,
- placeholder: inst.placeholder || $([]),
- position: inst.position,
- originalPosition: inst.originalPosition,
- offset: inst.positionAbs,
- item: inst.currentItem,
- sender: _inst ? _inst.element : null
- };
- }
-
-});
-
-})(jQuery);
-(function( $, undefined ) {
-
-var uid = 0,
- hideProps = {},
- showProps = {};
-
-hideProps.height = hideProps.paddingTop = hideProps.paddingBottom =
- hideProps.borderTopWidth = hideProps.borderBottomWidth = "hide";
-showProps.height = showProps.paddingTop = showProps.paddingBottom =
- showProps.borderTopWidth = showProps.borderBottomWidth = "show";
-
-$.widget( "ui.accordion", {
- version: "1.10.4",
- options: {
- active: 0,
- animate: {},
- collapsible: false,
- event: "click",
- header: "> li > :first-child,> :not(li):even",
- heightStyle: "auto",
- icons: {
- activeHeader: "ui-icon-triangle-1-s",
- header: "ui-icon-triangle-1-e"
- },
-
- // callbacks
- activate: null,
- beforeActivate: null
- },
-
- _create: function() {
- var options = this.options;
- this.prevShow = this.prevHide = $();
- this.element.addClass( "ui-accordion ui-widget ui-helper-reset" )
- // ARIA
- .attr( "role", "tablist" );
-
- // don't allow collapsible: false and active: false / null
- if ( !options.collapsible && (options.active === false || options.active == null) ) {
- options.active = 0;
- }
-
- this._processPanels();
- // handle negative values
- if ( options.active < 0 ) {
- options.active += this.headers.length;
- }
- this._refresh();
- },
-
- _getCreateEventData: function() {
- return {
- header: this.active,
- panel: !this.active.length ? $() : this.active.next(),
- content: !this.active.length ? $() : this.active.next()
- };
- },
-
- _createIcons: function() {
- var icons = this.options.icons;
- if ( icons ) {
- $( "<span>" )
- .addClass( "ui-accordion-header-icon ui-icon " + icons.header )
- .prependTo( this.headers );
- this.active.children( ".ui-accordion-header-icon" )
- .removeClass( icons.header )
- .addClass( icons.activeHeader );
- this.headers.addClass( "ui-accordion-icons" );
- }
- },
-
- _destroyIcons: function() {
- this.headers
- .removeClass( "ui-accordion-icons" )
- .children( ".ui-accordion-header-icon" )
- .remove();
- },
-
- _destroy: function() {
- var contents;
-
- // clean up main element
- this.element
- .removeClass( "ui-accordion ui-widget ui-helper-reset" )
- .removeAttr( "role" );
-
- // clean up headers
- this.headers
- .removeClass( "ui-accordion-header ui-accordion-header-active ui-helper-reset ui-state-default ui-corner-all ui-state-active ui-state-disabled ui-corner-top" )
- .removeAttr( "role" )
- .removeAttr( "aria-expanded" )
- .removeAttr( "aria-selected" )
- .removeAttr( "aria-controls" )
- .removeAttr( "tabIndex" )
- .each(function() {
- if ( /^ui-accordion/.test( this.id ) ) {
- this.removeAttribute( "id" );
- }
- });
- this._destroyIcons();
-
- // clean up content panels
- contents = this.headers.next()
- .css( "display", "" )
- .removeAttr( "role" )
- .removeAttr( "aria-hidden" )
- .removeAttr( "aria-labelledby" )
- .removeClass( "ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content ui-accordion-content-active ui-state-disabled" )
- .each(function() {
- if ( /^ui-accordion/.test( this.id ) ) {
- this.removeAttribute( "id" );
- }
- });
- if ( this.options.heightStyle !== "content" ) {
- contents.css( "height", "" );
- }
- },
-
- _setOption: function( key, value ) {
- if ( key === "active" ) {
- // _activate() will handle invalid values and update this.options
- this._activate( value );
- return;
- }
-
- if ( key === "event" ) {
- if ( this.options.event ) {
- this._off( this.headers, this.options.event );
- }
- this._setupEvents( value );
- }
-
- this._super( key, value );
-
- // setting collapsible: false while collapsed; open first panel
- if ( key === "collapsible" && !value && this.options.active === false ) {
- this._activate( 0 );
- }
-
- if ( key === "icons" ) {
- this._destroyIcons();
- if ( value ) {
- this._createIcons();
- }
- }
-
- // #5332 - opacity doesn't cascade to positioned elements in IE
- // so we need to add the disabled class to the headers and panels
- if ( key === "disabled" ) {
- this.headers.add( this.headers.next() )
- .toggleClass( "ui-state-disabled", !!value );
- }
- },
-
- _keydown: function( event ) {
- if ( event.altKey || event.ctrlKey ) {
- return;
- }
-
- var keyCode = $.ui.keyCode,
- length = this.headers.length,
- currentIndex = this.headers.index( event.target ),
- toFocus = false;
-
- switch ( event.keyCode ) {
- case keyCode.RIGHT:
- case keyCode.DOWN:
- toFocus = this.headers[ ( currentIndex + 1 ) % length ];
- break;
- case keyCode.LEFT:
- case keyCode.UP:
- toFocus = this.headers[ ( currentIndex - 1 + length ) % length ];
- break;
- case keyCode.SPACE:
- case keyCode.ENTER:
- this._eventHandler( event );
- break;
- case keyCode.HOME:
- toFocus = this.headers[ 0 ];
- break;
- case keyCode.END:
- toFocus = this.headers[ length - 1 ];
- break;
- }
-
- if ( toFocus ) {
- $( event.target ).attr( "tabIndex", -1 );
- $( toFocus ).attr( "tabIndex", 0 );
- toFocus.focus();
- event.preventDefault();
- }
- },
-
- _panelKeyDown : function( event ) {
- if ( event.keyCode === $.ui.keyCode.UP && event.ctrlKey ) {
- $( event.currentTarget ).prev().focus();
- }
- },
-
- refresh: function() {
- var options = this.options;
- this._processPanels();
-
- // was collapsed or no panel
- if ( ( options.active === false && options.collapsible === true ) || !this.headers.length ) {
- options.active = false;
- this.active = $();
- // active false only when collapsible is true
- } else if ( options.active === false ) {
- this._activate( 0 );
- // was active, but active panel is gone
- } else if ( this.active.length && !$.contains( this.element[ 0 ], this.active[ 0 ] ) ) {
- // all remaining panel are disabled
- if ( this.headers.length === this.headers.find(".ui-state-disabled").length ) {
- options.active = false;
- this.active = $();
- // activate previous panel
- } else {
- this._activate( Math.max( 0, options.active - 1 ) );
- }
- // was active, active panel still exists
- } else {
- // make sure active index is correct
- options.active = this.headers.index( this.active );
- }
-
- this._destroyIcons();
-
- this._refresh();
- },
-
- _processPanels: function() {
- this.headers = this.element.find( this.options.header )
- .addClass( "ui-accordion-header ui-helper-reset ui-state-default ui-corner-all" );
-
- this.headers.next()
- .addClass( "ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom" )
- .filter(":not(.ui-accordion-content-active)")
- .hide();
- },
-
- _refresh: function() {
- var maxHeight,
- options = this.options,
- heightStyle = options.heightStyle,
- parent = this.element.parent(),
- accordionId = this.accordionId = "ui-accordion-" +
- (this.element.attr( "id" ) || ++uid);
-
- this.active = this._findActive( options.active )
- .addClass( "ui-accordion-header-active ui-state-active ui-corner-top" )
- .removeClass( "ui-corner-all" );
- this.active.next()
- .addClass( "ui-accordion-content-active" )
- .show();
-
- this.headers
- .attr( "role", "tab" )
- .each(function( i ) {
- var header = $( this ),
- headerId = header.attr( "id" ),
- panel = header.next(),
- panelId = panel.attr( "id" );
- if ( !headerId ) {
- headerId = accordionId + "-header-" + i;
- header.attr( "id", headerId );
- }
- if ( !panelId ) {
- panelId = accordionId + "-panel-" + i;
- panel.attr( "id", panelId );
- }
- header.attr( "aria-controls", panelId );
- panel.attr( "aria-labelledby", headerId );
- })
- .next()
- .attr( "role", "tabpanel" );
-
- this.headers
- .not( this.active )
- .attr({
- "aria-selected": "false",
- "aria-expanded": "false",
- tabIndex: -1
- })
- .next()
- .attr({
- "aria-hidden": "true"
- })
- .hide();
-
- // make sure at least one header is in the tab order
- if ( !this.active.length ) {
- this.headers.eq( 0 ).attr( "tabIndex", 0 );
- } else {
- this.active.attr({
- "aria-selected": "true",
- "aria-expanded": "true",
- tabIndex: 0
- })
- .next()
- .attr({
- "aria-hidden": "false"
- });
- }
-
- this._createIcons();
-
- this._setupEvents( options.event );
-
- if ( heightStyle === "fill" ) {
- maxHeight = parent.height();
- this.element.siblings( ":visible" ).each(function() {
- var elem = $( this ),
- position = elem.css( "position" );
-
- if ( position === "absolute" || position === "fixed" ) {
- return;
- }
- maxHeight -= elem.outerHeight( true );
- });
-
- this.headers.each(function() {
- maxHeight -= $( this ).outerHeight( true );
- });
-
- this.headers.next()
- .each(function() {
- $( this ).height( Math.max( 0, maxHeight -
- $( this ).innerHeight() + $( this ).height() ) );
- })
- .css( "overflow", "auto" );
- } else if ( heightStyle === "auto" ) {
- maxHeight = 0;
- this.headers.next()
- .each(function() {
- maxHeight = Math.max( maxHeight, $( this ).css( "height", "" ).height() );
- })
- .height( maxHeight );
- }
- },
-
- _activate: function( index ) {
- var active = this._findActive( index )[ 0 ];
-
- // trying to activate the already active panel
- if ( active === this.active[ 0 ] ) {
- return;
- }
-
- // trying to collapse, simulate a click on the currently active header
- active = active || this.active[ 0 ];
-
- this._eventHandler({
- target: active,
- currentTarget: active,
- preventDefault: $.noop
- });
- },
-
- _findActive: function( selector ) {
- return typeof selector === "number" ? this.headers.eq( selector ) : $();
- },
-
- _setupEvents: function( event ) {
- var events = {
- keydown: "_keydown"
- };
- if ( event ) {
- $.each( event.split(" "), function( index, eventName ) {
- events[ eventName ] = "_eventHandler";
- });
- }
-
- this._off( this.headers.add( this.headers.next() ) );
- this._on( this.headers, events );
- this._on( this.headers.next(), { keydown: "_panelKeyDown" });
- this._hoverable( this.headers );
- this._focusable( this.headers );
- },
-
- _eventHandler: function( event ) {
- var options = this.options,
- active = this.active,
- clicked = $( event.currentTarget ),
- clickedIsActive = clicked[ 0 ] === active[ 0 ],
- collapsing = clickedIsActive && options.collapsible,
- toShow = collapsing ? $() : clicked.next(),
- toHide = active.next(),
- eventData = {
- oldHeader: active,
- oldPanel: toHide,
- newHeader: collapsing ? $() : clicked,
- newPanel: toShow
- };
-
- event.preventDefault();
-
- if (
- // click on active header, but not collapsible
- ( clickedIsActive && !options.collapsible ) ||
- // allow canceling activation
- ( this._trigger( "beforeActivate", event, eventData ) === false ) ) {
- return;
- }
-
- options.active = collapsing ? false : this.headers.index( clicked );
-
- // when the call to ._toggle() comes after the class changes
- // it causes a very odd bug in IE 8 (see #6720)
- this.active = clickedIsActive ? $() : clicked;
- this._toggle( eventData );
-
- // switch classes
- // corner classes on the previously active header stay after the animation
- active.removeClass( "ui-accordion-header-active ui-state-active" );
- if ( options.icons ) {
- active.children( ".ui-accordion-header-icon" )
- .removeClass( options.icons.activeHeader )
- .addClass( options.icons.header );
- }
-
- if ( !clickedIsActive ) {
- clicked
- .removeClass( "ui-corner-all" )
- .addClass( "ui-accordion-header-active ui-state-active ui-corner-top" );
- if ( options.icons ) {
- clicked.children( ".ui-accordion-header-icon" )
- .removeClass( options.icons.header )
- .addClass( options.icons.activeHeader );
- }
-
- clicked
- .next()
- .addClass( "ui-accordion-content-active" );
- }
- },
-
- _toggle: function( data ) {
- var toShow = data.newPanel,
- toHide = this.prevShow.length ? this.prevShow : data.oldPanel;
-
- // handle activating a panel during the animation for another activation
- this.prevShow.add( this.prevHide ).stop( true, true );
- this.prevShow = toShow;
- this.prevHide = toHide;
-
- if ( this.options.animate ) {
- this._animate( toShow, toHide, data );
- } else {
- toHide.hide();
- toShow.show();
- this._toggleComplete( data );
- }
-
- toHide.attr({
- "aria-hidden": "true"
- });
- toHide.prev().attr( "aria-selected", "false" );
- // if we're switching panels, remove the old header from the tab order
- // if we're opening from collapsed state, remove the previous header from the tab order
- // if we're collapsing, then keep the collapsing header in the tab order
- if ( toShow.length && toHide.length ) {
- toHide.prev().attr({
- "tabIndex": -1,
- "aria-expanded": "false"
- });
- } else if ( toShow.length ) {
- this.headers.filter(function() {
- return $( this ).attr( "tabIndex" ) === 0;
- })
- .attr( "tabIndex", -1 );
- }
-
- toShow
- .attr( "aria-hidden", "false" )
- .prev()
- .attr({
- "aria-selected": "true",
- tabIndex: 0,
- "aria-expanded": "true"
- });
- },
-
- _animate: function( toShow, toHide, data ) {
- var total, easing, duration,
- that = this,
- adjust = 0,
- down = toShow.length &&
- ( !toHide.length || ( toShow.index() < toHide.index() ) ),
- animate = this.options.animate || {},
- options = down && animate.down || animate,
- complete = function() {
- that._toggleComplete( data );
- };
-
- if ( typeof options === "number" ) {
- duration = options;
- }
- if ( typeof options === "string" ) {
- easing = options;
- }
- // fall back from options to animation in case of partial down settings
- easing = easing || options.easing || animate.easing;
- duration = duration || options.duration || animate.duration;
-
- if ( !toHide.length ) {
- return toShow.animate( showProps, duration, easing, complete );
- }
- if ( !toShow.length ) {
- return toHide.animate( hideProps, duration, easing, complete );
- }
-
- total = toShow.show().outerHeight();
- toHide.animate( hideProps, {
- duration: duration,
- easing: easing,
- step: function( now, fx ) {
- fx.now = Math.round( now );
- }
- });
- toShow
- .hide()
- .animate( showProps, {
- duration: duration,
- easing: easing,
- complete: complete,
- step: function( now, fx ) {
- fx.now = Math.round( now );
- if ( fx.prop !== "height" ) {
- adjust += fx.now;
- } else if ( that.options.heightStyle !== "content" ) {
- fx.now = Math.round( total - toHide.outerHeight() - adjust );
- adjust = 0;
- }
- }
- });
- },
-
- _toggleComplete: function( data ) {
- var toHide = data.oldPanel;
-
- toHide
- .removeClass( "ui-accordion-content-active" )
- .prev()
- .removeClass( "ui-corner-top" )
- .addClass( "ui-corner-all" );
-
- // Work around for rendering bug in IE (#5421)
- if ( toHide.length ) {
- toHide.parent()[0].className = toHide.parent()[0].className;
- }
- this._trigger( "activate", null, data );
- }
-});
-
-})( jQuery );
-(function( $, undefined ) {
-
-$.widget( "ui.autocomplete", {
- version: "1.10.4",
- defaultElement: "<input>",
- options: {
- appendTo: null,
- autoFocus: false,
- delay: 300,
- minLength: 1,
- position: {
- my: "left top",
- at: "left bottom",
- collision: "none"
- },
- source: null,
-
- // callbacks
- change: null,
- close: null,
- focus: null,
- open: null,
- response: null,
- search: null,
- select: null
- },
-
- requestIndex: 0,
- pending: 0,
-
- _create: function() {
- // Some browsers only repeat keydown events, not keypress events,
- // so we use the suppressKeyPress flag to determine if we've already
- // handled the keydown event. #7269
- // Unfortunately the code for & in keypress is the same as the up arrow,
- // so we use the suppressKeyPressRepeat flag to avoid handling keypress
- // events when we know the keydown event was used to modify the
- // search term. #7799
- var suppressKeyPress, suppressKeyPressRepeat, suppressInput,
- nodeName = this.element[0].nodeName.toLowerCase(),
- isTextarea = nodeName === "textarea",
- isInput = nodeName === "input";
-
- this.isMultiLine =
- // Textareas are always multi-line
- isTextarea ? true :
- // Inputs are always single-line, even if inside a contentEditable element
- // IE also treats inputs as contentEditable
- isInput ? false :
- // All other element types are determined by whether or not they're contentEditable
- this.element.prop( "isContentEditable" );
-
- this.valueMethod = this.element[ isTextarea || isInput ? "val" : "text" ];
- this.isNewMenu = true;
-
- this.element
- .addClass( "ui-autocomplete-input" )
- .attr( "autocomplete", "off" );
-
- this._on( this.element, {
- keydown: function( event ) {
- if ( this.element.prop( "readOnly" ) ) {
- suppressKeyPress = true;
- suppressInput = true;
- suppressKeyPressRepeat = true;
- return;
- }
-
- suppressKeyPress = false;
- suppressInput = false;
- suppressKeyPressRepeat = false;
- var keyCode = $.ui.keyCode;
- switch( event.keyCode ) {
- case keyCode.PAGE_UP:
- suppressKeyPress = true;
- this._move( "previousPage", event );
- break;
- case keyCode.PAGE_DOWN:
- suppressKeyPress = true;
- this._move( "nextPage", event );
- break;
- case keyCode.UP:
- suppressKeyPress = true;
- this._keyEvent( "previous", event );
- break;
- case keyCode.DOWN:
- suppressKeyPress = true;
- this._keyEvent( "next", event );
- break;
- case keyCode.ENTER:
- case keyCode.NUMPAD_ENTER:
- // when menu is open and has focus
- if ( this.menu.active ) {
- // #6055 - Opera still allows the keypress to occur
- // which causes forms to submit
- suppressKeyPress = true;
- event.preventDefault();
- this.menu.select( event );
- }
- break;
- case keyCode.TAB:
- if ( this.menu.active ) {
- this.menu.select( event );
- }
- break;
- case keyCode.ESCAPE:
- if ( this.menu.element.is( ":visible" ) ) {
- this._value( this.term );
- this.close( event );
- // Different browsers have different default behavior for escape
- // Single press can mean undo or clear
- // Double press in IE means clear the whole form
- event.preventDefault();
- }
- break;
- default:
- suppressKeyPressRepeat = true;
- // search timeout should be triggered before the input value is changed
- this._searchTimeout( event );
- break;
- }
- },
- keypress: function( event ) {
- if ( suppressKeyPress ) {
- suppressKeyPress = false;
- if ( !this.isMultiLine || this.menu.element.is( ":visible" ) ) {
- event.preventDefault();
- }
- return;
- }
- if ( suppressKeyPressRepeat ) {
- return;
- }
-
- // replicate some key handlers to allow them to repeat in Firefox and Opera
- var keyCode = $.ui.keyCode;
- switch( event.keyCode ) {
- case keyCode.PAGE_UP:
- this._move( "previousPage", event );
- break;
- case keyCode.PAGE_DOWN:
- this._move( "nextPage", event );
- break;
- case keyCode.UP:
- this._keyEvent( "previous", event );
- break;
- case keyCode.DOWN:
- this._keyEvent( "next", event );
- break;
- }
- },
- input: function( event ) {
- if ( suppressInput ) {
- suppressInput = false;
- event.preventDefault();
- return;
- }
- this._searchTimeout( event );
- },
- focus: function() {
- this.selectedItem = null;
- this.previous = this._value();
- },
- blur: function( event ) {
- if ( this.cancelBlur ) {
- delete this.cancelBlur;
- return;
- }
-
- clearTimeout( this.searching );
- this.close( event );
- this._change( event );
- }
- });
-
- this._initSource();
- this.menu = $( "<ul>" )
- .addClass( "ui-autocomplete ui-front" )
- .appendTo( this._appendTo() )
- .menu({
- // disable ARIA support, the live region takes care of that
- role: null
- })
- .hide()
- .data( "ui-menu" );
-
- this._on( this.menu.element, {
- mousedown: function( event ) {
- // prevent moving focus out of the text field
- event.preventDefault();
-
- // IE doesn't prevent moving focus even with event.preventDefault()
- // so we set a flag to know when we should ignore the blur event
- this.cancelBlur = true;
- this._delay(function() {
- delete this.cancelBlur;
- });
-
- // clicking on the scrollbar causes focus to shift to the body
- // but we can't detect a mouseup or a click immediately afterward
- // so we have to track the next mousedown and close the menu if
- // the user clicks somewhere outside of the autocomplete
- var menuElement = this.menu.element[ 0 ];
- if ( !$( event.target ).closest( ".ui-menu-item" ).length ) {
- this._delay(function() {
- var that = this;
- this.document.one( "mousedown", function( event ) {
- if ( event.target !== that.element[ 0 ] &&
- event.target !== menuElement &&
- !$.contains( menuElement, event.target ) ) {
- that.close();
- }
- });
- });
- }
- },
- menufocus: function( event, ui ) {
- // support: Firefox
- // Prevent accidental activation of menu items in Firefox (#7024 #9118)
- if ( this.isNewMenu ) {
- this.isNewMenu = false;
- if ( event.originalEvent && /^mouse/.test( event.originalEvent.type ) ) {
- this.menu.blur();
-
- this.document.one( "mousemove", function() {
- $( event.target ).trigger( event.originalEvent );
- });
-
- return;
- }
- }
-
- var item = ui.item.data( "ui-autocomplete-item" );
- if ( false !== this._trigger( "focus", event, { item: item } ) ) {
- // use value to match what will end up in the input, if it was a key event
- if ( event.originalEvent && /^key/.test( event.originalEvent.type ) ) {
- this._value( item.value );
- }
- } else {
- // Normally the input is populated with the item's value as the
- // menu is navigated, causing screen readers to notice a change and
- // announce the item. Since the focus event was canceled, this doesn't
- // happen, so we update the live region so that screen readers can
- // still notice the change and announce it.
- this.liveRegion.text( item.value );
- }
- },
- menuselect: function( event, ui ) {
- var item = ui.item.data( "ui-autocomplete-item" ),
- previous = this.previous;
-
- // only trigger when focus was lost (click on menu)
- if ( this.element[0] !== this.document[0].activeElement ) {
- this.element.focus();
- this.previous = previous;
- // #6109 - IE triggers two focus events and the second
- // is asynchronous, so we need to reset the previous
- // term synchronously and asynchronously :-(
- this._delay(function() {
- this.previous = previous;
- this.selectedItem = item;
- });
- }
-
- if ( false !== this._trigger( "select", event, { item: item } ) ) {
- this._value( item.value );
- }
- // reset the term after the select event
- // this allows custom select handling to work properly
- this.term = this._value();
-
- this.close( event );
- this.selectedItem = item;
- }
- });
-
- this.liveRegion = $( "<span>", {
- role: "status",
- "aria-live": "polite"
- })
- .addClass( "ui-helper-hidden-accessible" )
- .insertBefore( this.element );
-
- // turning off autocomplete prevents the browser from remembering the
- // value when navigating through history, so we re-enable autocomplete
- // if the page is unloaded before the widget is destroyed. #7790
- this._on( this.window, {
- beforeunload: function() {
- this.element.removeAttr( "autocomplete" );
- }
- });
- },
-
- _destroy: function() {
- clearTimeout( this.searching );
- this.element
- .removeClass( "ui-autocomplete-input" )
- .removeAttr( "autocomplete" );
- this.menu.element.remove();
- this.liveRegion.remove();
- },
-
- _setOption: function( key, value ) {
- this._super( key, value );
- if ( key === "source" ) {
- this._initSource();
- }
- if ( key === "appendTo" ) {
- this.menu.element.appendTo( this._appendTo() );
- }
- if ( key === "disabled" && value && this.xhr ) {
- this.xhr.abort();
- }
- },
-
- _appendTo: function() {
- var element = this.options.appendTo;
-
- if ( element ) {
- element = element.jquery || element.nodeType ?
- $( element ) :
- this.document.find( element ).eq( 0 );
- }
-
- if ( !element ) {
- element = this.element.closest( ".ui-front" );
- }
-
- if ( !element.length ) {
- element = this.document[0].body;
- }
-
- return element;
- },
-
- _initSource: function() {
- var array, url,
- that = this;
- if ( $.isArray(this.options.source) ) {
- array = this.options.source;
- this.source = function( request, response ) {
- response( $.ui.autocomplete.filter( array, request.term ) );
- };
- } else if ( typeof this.options.source === "string" ) {
- url = this.options.source;
- this.source = function( request, response ) {
- if ( that.xhr ) {
- that.xhr.abort();
- }
- that.xhr = $.ajax({
- url: url,
- data: request,
- dataType: "json",
- success: function( data ) {
- response( data );
- },
- error: function() {
- response( [] );
- }
- });
- };
- } else {
- this.source = this.options.source;
- }
- },
-
- _searchTimeout: function( event ) {
- clearTimeout( this.searching );
- this.searching = this._delay(function() {
- // only search if the value has changed
- if ( this.term !== this._value() ) {
- this.selectedItem = null;
- this.search( null, event );
- }
- }, this.options.delay );
- },
-
- search: function( value, event ) {
- value = value != null ? value : this._value();
-
- // always save the actual value, not the one passed as an argument
- this.term = this._value();
-
- if ( value.length < this.options.minLength ) {
- return this.close( event );
- }
-
- if ( this._trigger( "search", event ) === false ) {
- return;
- }
-
- return this._search( value );
- },
-
- _search: function( value ) {
- this.pending++;
- this.element.addClass( "ui-autocomplete-loading" );
- this.cancelSearch = false;
-
- this.source( { term: value }, this._response() );
- },
-
- _response: function() {
- var index = ++this.requestIndex;
-
- return $.proxy(function( content ) {
- if ( index === this.requestIndex ) {
- this.__response( content );
- }
-
- this.pending--;
- if ( !this.pending ) {
- this.element.removeClass( "ui-autocomplete-loading" );
- }
- }, this );
- },
-
- __response: function( content ) {
- if ( content ) {
- content = this._normalize( content );
- }
- this._trigger( "response", null, { content: content } );
- if ( !this.options.disabled && content && content.length && !this.cancelSearch ) {
- this._suggest( content );
- this._trigger( "open" );
- } else {
- // use ._close() instead of .close() so we don't cancel future searches
- this._close();
- }
- },
-
- close: function( event ) {
- this.cancelSearch = true;
- this._close( event );
- },
-
- _close: function( event ) {
- if ( this.menu.element.is( ":visible" ) ) {
- this.menu.element.hide();
- this.menu.blur();
- this.isNewMenu = true;
- this._trigger( "close", event );
- }
- },
-
- _change: function( event ) {
- if ( this.previous !== this._value() ) {
- this._trigger( "change", event, { item: this.selectedItem } );
- }
- },
-
- _normalize: function( items ) {
- // assume all items have the right format when the first item is complete
- if ( items.length && items[0].label && items[0].value ) {
- return items;
- }
- return $.map( items, function( item ) {
- if ( typeof item === "string" ) {
- return {
- label: item,
- value: item
- };
- }
- return $.extend({
- label: item.label || item.value,
- value: item.value || item.label
- }, item );
- });
- },
-
- _suggest: function( items ) {
- var ul = this.menu.element.empty();
- this._renderMenu( ul, items );
- this.isNewMenu = true;
- this.menu.refresh();
-
- // size and position menu
- ul.show();
- this._resizeMenu();
- ul.position( $.extend({
- of: this.element
- }, this.options.position ));
-
- if ( this.options.autoFocus ) {
- this.menu.next();
- }
- },
-
- _resizeMenu: function() {
- var ul = this.menu.element;
- ul.outerWidth( Math.max(
- // Firefox wraps long text (possibly a rounding bug)
- // so we add 1px to avoid the wrapping (#7513)
- ul.width( "" ).outerWidth() + 1,
- this.element.outerWidth()
- ) );
- },
-
- _renderMenu: function( ul, items ) {
- var that = this;
- $.each( items, function( index, item ) {
- that._renderItemData( ul, item );
- });
- },
-
- _renderItemData: function( ul, item ) {
- return this._renderItem( ul, item ).data( "ui-autocomplete-item", item );
- },
-
- _renderItem: function( ul, item ) {
- return $( "<li>" )
- .append( $( "<a>" ).text( item.label ) )
- .appendTo( ul );
- },
-
- _move: function( direction, event ) {
- if ( !this.menu.element.is( ":visible" ) ) {
- this.search( null, event );
- return;
- }
- if ( this.menu.isFirstItem() && /^previous/.test( direction ) ||
- this.menu.isLastItem() && /^next/.test( direction ) ) {
- this._value( this.term );
- this.menu.blur();
- return;
- }
- this.menu[ direction ]( event );
- },
-
- widget: function() {
- return this.menu.element;
- },
-
- _value: function() {
- return this.valueMethod.apply( this.element, arguments );
- },
-
- _keyEvent: function( keyEvent, event ) {
- if ( !this.isMultiLine || this.menu.element.is( ":visible" ) ) {
- this._move( keyEvent, event );
-
- // prevents moving cursor to beginning/end of the text field in some browsers
- event.preventDefault();
- }
- }
-});
-
-$.extend( $.ui.autocomplete, {
- escapeRegex: function( value ) {
- return value.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&");
- },
- filter: function(array, term) {
- var matcher = new RegExp( $.ui.autocomplete.escapeRegex(term), "i" );
- return $.grep( array, function(value) {
- return matcher.test( value.label || value.value || value );
- });
- }
-});
-
-
-// live region extension, adding a `messages` option
-// NOTE: This is an experimental API. We are still investigating
-// a full solution for string manipulation and internationalization.
-$.widget( "ui.autocomplete", $.ui.autocomplete, {
- options: {
- messages: {
- noResults: "No search results.",
- results: function( amount ) {
- return amount + ( amount > 1 ? " results are" : " result is" ) +
- " available, use up and down arrow keys to navigate.";
- }
- }
- },
-
- __response: function( content ) {
- var message;
- this._superApply( arguments );
- if ( this.options.disabled || this.cancelSearch ) {
- return;
- }
- if ( content && content.length ) {
- message = this.options.messages.results( content.length );
- } else {
- message = this.options.messages.noResults;
- }
- this.liveRegion.text( message );
- }
-});
-
-}( jQuery ));
-(function( $, undefined ) {
-
-var lastActive,
- baseClasses = "ui-button ui-widget ui-state-default ui-corner-all",
- typeClasses = "ui-button-icons-only ui-button-icon-only ui-button-text-icons ui-button-text-icon-primary ui-button-text-icon-secondary ui-button-text-only",
- formResetHandler = function() {
- var form = $( this );
- setTimeout(function() {
- form.find( ":ui-button" ).button( "refresh" );
- }, 1 );
- },
- radioGroup = function( radio ) {
- var name = radio.name,
- form = radio.form,
- radios = $( [] );
- if ( name ) {
- name = name.replace( /'/g, "\\'" );
- if ( form ) {
- radios = $( form ).find( "[name='" + name + "']" );
- } else {
- radios = $( "[name='" + name + "']", radio.ownerDocument )
- .filter(function() {
- return !this.form;
- });
- }
- }
- return radios;
- };
-
-$.widget( "ui.button", {
- version: "1.10.4",
- defaultElement: "<button>",
- options: {
- disabled: null,
- text: true,
- label: null,
- icons: {
- primary: null,
- secondary: null
- }
- },
- _create: function() {
- this.element.closest( "form" )
- .unbind( "reset" + this.eventNamespace )
- .bind( "reset" + this.eventNamespace, formResetHandler );
-
- if ( typeof this.options.disabled !== "boolean" ) {
- this.options.disabled = !!this.element.prop( "disabled" );
- } else {
- this.element.prop( "disabled", this.options.disabled );
- }
-
- this._determineButtonType();
- this.hasTitle = !!this.buttonElement.attr( "title" );
-
- var that = this,
- options = this.options,
- toggleButton = this.type === "checkbox" || this.type === "radio",
- activeClass = !toggleButton ? "ui-state-active" : "";
-
- if ( options.label === null ) {
- options.label = (this.type === "input" ? this.buttonElement.val() : this.buttonElement.html());
- }
-
- this._hoverable( this.buttonElement );
-
- this.buttonElement
- .addClass( baseClasses )
- .attr( "role", "button" )
- .bind( "mouseenter" + this.eventNamespace, function() {
- if ( options.disabled ) {
- return;
- }
- if ( this === lastActive ) {
- $( this ).addClass( "ui-state-active" );
- }
- })
- .bind( "mouseleave" + this.eventNamespace, function() {
- if ( options.disabled ) {
- return;
- }
- $( this ).removeClass( activeClass );
- })
- .bind( "click" + this.eventNamespace, function( event ) {
- if ( options.disabled ) {
- event.preventDefault();
- event.stopImmediatePropagation();
- }
- });
-
- // Can't use _focusable() because the element that receives focus
- // and the element that gets the ui-state-focus class are different
- this._on({
- focus: function() {
- this.buttonElement.addClass( "ui-state-focus" );
- },
- blur: function() {
- this.buttonElement.removeClass( "ui-state-focus" );
- }
- });
-
- if ( toggleButton ) {
- this.element.bind( "change" + this.eventNamespace, function() {
- that.refresh();
- });
- }
-
- if ( this.type === "checkbox" ) {
- this.buttonElement.bind( "click" + this.eventNamespace, function() {
- if ( options.disabled ) {
- return false;
- }
- });
- } else if ( this.type === "radio" ) {
- this.buttonElement.bind( "click" + this.eventNamespace, function() {
- if ( options.disabled ) {
- return false;
- }
- $( this ).addClass( "ui-state-active" );
- that.buttonElement.attr( "aria-pressed", "true" );
-
- var radio = that.element[ 0 ];
- radioGroup( radio )
- .not( radio )
- .map(function() {
- return $( this ).button( "widget" )[ 0 ];
- })
- .removeClass( "ui-state-active" )
- .attr( "aria-pressed", "false" );
- });
- } else {
- this.buttonElement
- .bind( "mousedown" + this.eventNamespace, function() {
- if ( options.disabled ) {
- return false;
- }
- $( this ).addClass( "ui-state-active" );
- lastActive = this;
- that.document.one( "mouseup", function() {
- lastActive = null;
- });
- })
- .bind( "mouseup" + this.eventNamespace, function() {
- if ( options.disabled ) {
- return false;
- }
- $( this ).removeClass( "ui-state-active" );
- })
- .bind( "keydown" + this.eventNamespace, function(event) {
- if ( options.disabled ) {
- return false;
- }
- if ( event.keyCode === $.ui.keyCode.SPACE || event.keyCode === $.ui.keyCode.ENTER ) {
- $( this ).addClass( "ui-state-active" );
- }
- })
- // see #8559, we bind to blur here in case the button element loses
- // focus between keydown and keyup, it would be left in an "active" state
- .bind( "keyup" + this.eventNamespace + " blur" + this.eventNamespace, function() {
- $( this ).removeClass( "ui-state-active" );
- });
-
- if ( this.buttonElement.is("a") ) {
- this.buttonElement.keyup(function(event) {
- if ( event.keyCode === $.ui.keyCode.SPACE ) {
- // TODO pass through original event correctly (just as 2nd argument doesn't work)
- $( this ).click();
- }
- });
- }
- }
-
- // TODO: pull out $.Widget's handling for the disabled option into
- // $.Widget.prototype._setOptionDisabled so it's easy to proxy and can
- // be overridden by individual plugins
- this._setOption( "disabled", options.disabled );
- this._resetButton();
- },
-
- _determineButtonType: function() {
- var ancestor, labelSelector, checked;
-
- if ( this.element.is("[type=checkbox]") ) {
- this.type = "checkbox";
- } else if ( this.element.is("[type=radio]") ) {
- this.type = "radio";
- } else if ( this.element.is("input") ) {
- this.type = "input";
- } else {
- this.type = "button";
- }
-
- if ( this.type === "checkbox" || this.type === "radio" ) {
- // we don't search against the document in case the element
- // is disconnected from the DOM
- ancestor = this.element.parents().last();
- labelSelector = "label[for='" + this.element.attr("id") + "']";
- this.buttonElement = ancestor.find( labelSelector );
- if ( !this.buttonElement.length ) {
- ancestor = ancestor.length ? ancestor.siblings() : this.element.siblings();
- this.buttonElement = ancestor.filter( labelSelector );
- if ( !this.buttonElement.length ) {
- this.buttonElement = ancestor.find( labelSelector );
- }
- }
- this.element.addClass( "ui-helper-hidden-accessible" );
-
- checked = this.element.is( ":checked" );
- if ( checked ) {
- this.buttonElement.addClass( "ui-state-active" );
- }
- this.buttonElement.prop( "aria-pressed", checked );
- } else {
- this.buttonElement = this.element;
- }
- },
-
- widget: function() {
- return this.buttonElement;
- },
-
- _destroy: function() {
- this.element
- .removeClass( "ui-helper-hidden-accessible" );
- this.buttonElement
- .removeClass( baseClasses + " ui-state-active " + typeClasses )
- .removeAttr( "role" )
- .removeAttr( "aria-pressed" )
- .html( this.buttonElement.find(".ui-button-text").html() );
-
- if ( !this.hasTitle ) {
- this.buttonElement.removeAttr( "title" );
- }
- },
-
- _setOption: function( key, value ) {
- this._super( key, value );
- if ( key === "disabled" ) {
- this.element.prop( "disabled", !!value );
- if ( value ) {
- this.buttonElement.removeClass( "ui-state-focus" );
- }
- return;
- }
- this._resetButton();
- },
-
- refresh: function() {
- //See #8237 & #8828
- var isDisabled = this.element.is( "input, button" ) ? this.element.is( ":disabled" ) : this.element.hasClass( "ui-button-disabled" );
-
- if ( isDisabled !== this.options.disabled ) {
- this._setOption( "disabled", isDisabled );
- }
- if ( this.type === "radio" ) {
- radioGroup( this.element[0] ).each(function() {
- if ( $( this ).is( ":checked" ) ) {
- $( this ).button( "widget" )
- .addClass( "ui-state-active" )
- .attr( "aria-pressed", "true" );
- } else {
- $( this ).button( "widget" )
- .removeClass( "ui-state-active" )
- .attr( "aria-pressed", "false" );
- }
- });
- } else if ( this.type === "checkbox" ) {
- if ( this.element.is( ":checked" ) ) {
- this.buttonElement
- .addClass( "ui-state-active" )
- .attr( "aria-pressed", "true" );
- } else {
- this.buttonElement
- .removeClass( "ui-state-active" )
- .attr( "aria-pressed", "false" );
- }
- }
- },
-
- _resetButton: function() {
- if ( this.type === "input" ) {
- if ( this.options.label ) {
- this.element.val( this.options.label );
- }
- return;
- }
- var buttonElement = this.buttonElement.removeClass( typeClasses ),
- buttonText = $( "<span></span>", this.document[0] )
- .addClass( "ui-button-text" )
- .html( this.options.label )
- .appendTo( buttonElement.empty() )
- .text(),
- icons = this.options.icons,
- multipleIcons = icons.primary && icons.secondary,
- buttonClasses = [];
-
- if ( icons.primary || icons.secondary ) {
- if ( this.options.text ) {
- buttonClasses.push( "ui-button-text-icon" + ( multipleIcons ? "s" : ( icons.primary ? "-primary" : "-secondary" ) ) );
- }
-
- if ( icons.primary ) {
- buttonElement.prepend( "<span class='ui-button-icon-primary ui-icon " + icons.primary + "'></span>" );
- }
-
- if ( icons.secondary ) {
- buttonElement.append( "<span class='ui-button-icon-secondary ui-icon " + icons.secondary + "'></span>" );
- }
-
- if ( !this.options.text ) {
- buttonClasses.push( multipleIcons ? "ui-button-icons-only" : "ui-button-icon-only" );
-
- if ( !this.hasTitle ) {
- buttonElement.attr( "title", $.trim( buttonText ) );
- }
- }
- } else {
- buttonClasses.push( "ui-button-text-only" );
- }
- buttonElement.addClass( buttonClasses.join( " " ) );
- }
-});
-
-$.widget( "ui.buttonset", {
- version: "1.10.4",
- options: {
- items: "button, input[type=button], input[type=submit], input[type=reset], input[type=checkbox], input[type=radio], a, :data(ui-button)"
- },
-
- _create: function() {
- this.element.addClass( "ui-buttonset" );
- },
-
- _init: function() {
- this.refresh();
- },
-
- _setOption: function( key, value ) {
- if ( key === "disabled" ) {
- this.buttons.button( "option", key, value );
- }
-
- this._super( key, value );
- },
-
- refresh: function() {
- var rtl = this.element.css( "direction" ) === "rtl";
-
- this.buttons = this.element.find( this.options.items )
- .filter( ":ui-button" )
- .button( "refresh" )
- .end()
- .not( ":ui-button" )
- .button()
- .end()
- .map(function() {
- return $( this ).button( "widget" )[ 0 ];
- })
- .removeClass( "ui-corner-all ui-corner-left ui-corner-right" )
- .filter( ":first" )
- .addClass( rtl ? "ui-corner-right" : "ui-corner-left" )
- .end()
- .filter( ":last" )
- .addClass( rtl ? "ui-corner-left" : "ui-corner-right" )
- .end()
- .end();
- },
-
- _destroy: function() {
- this.element.removeClass( "ui-buttonset" );
- this.buttons
- .map(function() {
- return $( this ).button( "widget" )[ 0 ];
- })
- .removeClass( "ui-corner-left ui-corner-right" )
- .end()
- .button( "destroy" );
- }
-});
-
-}( jQuery ) );
-(function( $, undefined ) {
-
-$.extend($.ui, { datepicker: { version: "1.10.4" } });
-
-var PROP_NAME = "datepicker",
- instActive;
-
-/* Date picker manager.
- Use the singleton instance of this class, $.datepicker, to interact with the date picker.
- Settings for (groups of) date pickers are maintained in an instance object,
- allowing multiple different settings on the same page. */
-
-function Datepicker() {
- this._curInst = null; // The current instance in use
- this._keyEvent = false; // If the last event was a key event
- this._disabledInputs = []; // List of date picker inputs that have been disabled
- this._datepickerShowing = false; // True if the popup picker is showing , false if not
- this._inDialog = false; // True if showing within a "dialog", false if not
- this._mainDivId = "ui-datepicker-div"; // The ID of the main datepicker division
- this._inlineClass = "ui-datepicker-inline"; // The name of the inline marker class
- this._appendClass = "ui-datepicker-append"; // The name of the append marker class
- this._triggerClass = "ui-datepicker-trigger"; // The name of the trigger marker class
- this._dialogClass = "ui-datepicker-dialog"; // The name of the dialog marker class
- this._disableClass = "ui-datepicker-disabled"; // The name of the disabled covering marker class
- this._unselectableClass = "ui-datepicker-unselectable"; // The name of the unselectable cell marker class
- this._currentClass = "ui-datepicker-current-day"; // The name of the current day marker class
- this._dayOverClass = "ui-datepicker-days-cell-over"; // The name of the day hover marker class
- this.regional = []; // Available regional settings, indexed by language code
- this.regional[""] = { // Default regional settings
- closeText: "Done", // Display text for close link
- prevText: "Prev", // Display text for previous month link
- nextText: "Next", // Display text for next month link
- currentText: "Today", // Display text for current month link
- monthNames: ["January","February","March","April","May","June",
- "July","August","September","October","November","December"], // Names of months for drop-down and formatting
- monthNamesShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], // For formatting
- dayNames: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"], // For formatting
- dayNamesShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"], // For formatting
- dayNamesMin: ["Su","Mo","Tu","We","Th","Fr","Sa"], // Column headings for days starting at Sunday
- weekHeader: "Wk", // Column header for week of the year
- dateFormat: "mm/dd/yy", // See format options on parseDate
- firstDay: 0, // The first day of the week, Sun = 0, Mon = 1, ...
- isRTL: false, // True if right-to-left language, false if left-to-right
- showMonthAfterYear: false, // True if the year select precedes month, false for month then year
- yearSuffix: "" // Additional text to append to the year in the month headers
- };
- this._defaults = { // Global defaults for all the date picker instances
- showOn: "focus", // "focus" for popup on focus,
- // "button" for trigger button, or "both" for either
- showAnim: "fadeIn", // Name of jQuery animation for popup
- showOptions: {}, // Options for enhanced animations
- defaultDate: null, // Used when field is blank: actual date,
- // +/-number for offset from today, null for today
- appendText: "", // Display text following the input box, e.g. showing the format
- buttonText: "...", // Text for trigger button
- buttonImage: "", // URL for trigger button image
- buttonImageOnly: false, // True if the image appears alone, false if it appears on a button
- hideIfNoPrevNext: false, // True to hide next/previous month links
- // if not applicable, false to just disable them
- navigationAsDateFormat: false, // True if date formatting applied to prev/today/next links
- gotoCurrent: false, // True if today link goes back to current selection instead
- changeMonth: false, // True if month can be selected directly, false if only prev/next
- changeYear: false, // True if year can be selected directly, false if only prev/next
- yearRange: "c-10:c+10", // Range of years to display in drop-down,
- // either relative to today's year (-nn:+nn), relative to currently displayed year
- // (c-nn:c+nn), absolute (nnnn:nnnn), or a combination of the above (nnnn:-n)
- showOtherMonths: false, // True to show dates in other months, false to leave blank
- selectOtherMonths: false, // True to allow selection of dates in other months, false for unselectable
- showWeek: false, // True to show week of the year, false to not show it
- calculateWeek: this.iso8601Week, // How to calculate the week of the year,
- // takes a Date and returns the number of the week for it
- shortYearCutoff: "+10", // Short year values < this are in the current century,
- // > this are in the previous century,
- // string value starting with "+" for current year + value
- minDate: null, // The earliest selectable date, or null for no limit
- maxDate: null, // The latest selectable date, or null for no limit
- duration: "fast", // Duration of display/closure
- beforeShowDay: null, // Function that takes a date and returns an array with
- // [0] = true if selectable, false if not, [1] = custom CSS class name(s) or "",
- // [2] = cell title (optional), e.g. $.datepicker.noWeekends
- beforeShow: null, // Function that takes an input field and
- // returns a set of custom settings for the date picker
- onSelect: null, // Define a callback function when a date is selected
- onChangeMonthYear: null, // Define a callback function when the month or year is changed
- onClose: null, // Define a callback function when the datepicker is closed
- numberOfMonths: 1, // Number of months to show at a time
- showCurrentAtPos: 0, // The position in multipe months at which to show the current month (starting at 0)
- stepMonths: 1, // Number of months to step back/forward
- stepBigMonths: 12, // Number of months to step back/forward for the big links
- altField: "", // Selector for an alternate field to store selected dates into
- altFormat: "", // The date format to use for the alternate field
- constrainInput: true, // The input is constrained by the current date format
- showButtonPanel: false, // True to show button panel, false to not show it
- autoSize: false, // True to size the input for the date format, false to leave as is
- disabled: false // The initial disabled state
- };
- $.extend(this._defaults, this.regional[""]);
- this.dpDiv = bindHover($("<div id='" + this._mainDivId + "' class='ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all'></div>"));
-}
-
-$.extend(Datepicker.prototype, {
- /* Class name added to elements to indicate already configured with a date picker. */
- markerClassName: "hasDatepicker",
-
- //Keep track of the maximum number of rows displayed (see #7043)
- maxRows: 4,
-
- // TODO rename to "widget" when switching to widget factory
- _widgetDatepicker: function() {
- return this.dpDiv;
- },
-
- /* Override the default settings for all instances of the date picker.
- * @param settings object - the new settings to use as defaults (anonymous object)
- * @return the manager object
- */
- setDefaults: function(settings) {
- extendRemove(this._defaults, settings || {});
- return this;
- },
-
- /* Attach the date picker to a jQuery selection.
- * @param target element - the target input field or division or span
- * @param settings object - the new settings to use for this date picker instance (anonymous)
- */
- _attachDatepicker: function(target, settings) {
- var nodeName, inline, inst;
- nodeName = target.nodeName.toLowerCase();
- inline = (nodeName === "div" || nodeName === "span");
- if (!target.id) {
- this.uuid += 1;
- target.id = "dp" + this.uuid;
- }
- inst = this._newInst($(target), inline);
- inst.settings = $.extend({}, settings || {});
- if (nodeName === "input") {
- this._connectDatepicker(target, inst);
- } else if (inline) {
- this._inlineDatepicker(target, inst);
- }
- },
-
- /* Create a new instance object. */
- _newInst: function(target, inline) {
- var id = target[0].id.replace(/([^A-Za-z0-9_\-])/g, "\\\\$1"); // escape jQuery meta chars
- return {id: id, input: target, // associated target
- selectedDay: 0, selectedMonth: 0, selectedYear: 0, // current selection
- drawMonth: 0, drawYear: 0, // month being drawn
- inline: inline, // is datepicker inline or not
- dpDiv: (!inline ? this.dpDiv : // presentation div
- bindHover($("<div class='" + this._inlineClass + " ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all'></div>")))};
- },
-
- /* Attach the date picker to an input field. */
- _connectDatepicker: function(target, inst) {
- var input = $(target);
- inst.append = $([]);
- inst.trigger = $([]);
- if (input.hasClass(this.markerClassName)) {
- return;
- }
- this._attachments(input, inst);
- input.addClass(this.markerClassName).keydown(this._doKeyDown).
- keypress(this._doKeyPress).keyup(this._doKeyUp);
- this._autoSize(inst);
- $.data(target, PROP_NAME, inst);
- //If disabled option is true, disable the datepicker once it has been attached to the input (see ticket #5665)
- if( inst.settings.disabled ) {
- this._disableDatepicker( target );
- }
- },
-
- /* Make attachments based on settings. */
- _attachments: function(input, inst) {
- var showOn, buttonText, buttonImage,
- appendText = this._get(inst, "appendText"),
- isRTL = this._get(inst, "isRTL");
-
- if (inst.append) {
- inst.append.remove();
- }
- if (appendText) {
- inst.append = $("<span class='" + this._appendClass + "'>" + appendText + "</span>");
- input[isRTL ? "before" : "after"](inst.append);
- }
-
- input.unbind("focus", this._showDatepicker);
-
- if (inst.trigger) {
- inst.trigger.remove();
- }
-
- showOn = this._get(inst, "showOn");
- if (showOn === "focus" || showOn === "both") { // pop-up date picker when in the marked field
- input.focus(this._showDatepicker);
- }
- if (showOn === "button" || showOn === "both") { // pop-up date picker when button clicked
- buttonText = this._get(inst, "buttonText");
- buttonImage = this._get(inst, "buttonImage");
- inst.trigger = $(this._get(inst, "buttonImageOnly") ?
- $("<img/>").addClass(this._triggerClass).
- attr({ src: buttonImage, alt: buttonText, title: buttonText }) :
- $("<button type='button'></button>").addClass(this._triggerClass).
- html(!buttonImage ? buttonText : $("<img/>").attr(
- { src:buttonImage, alt:buttonText, title:buttonText })));
- input[isRTL ? "before" : "after"](inst.trigger);
- inst.trigger.click(function() {
- if ($.datepicker._datepickerShowing && $.datepicker._lastInput === input[0]) {
- $.datepicker._hideDatepicker();
- } else if ($.datepicker._datepickerShowing && $.datepicker._lastInput !== input[0]) {
- $.datepicker._hideDatepicker();
- $.datepicker._showDatepicker(input[0]);
- } else {
- $.datepicker._showDatepicker(input[0]);
- }
- return false;
- });
- }
- },
-
- /* Apply the maximum length for the date format. */
- _autoSize: function(inst) {
- if (this._get(inst, "autoSize") && !inst.inline) {
- var findMax, max, maxI, i,
- date = new Date(2009, 12 - 1, 20), // Ensure double digits
- dateFormat = this._get(inst, "dateFormat");
-
- if (dateFormat.match(/[DM]/)) {
- findMax = function(names) {
- max = 0;
- maxI = 0;
- for (i = 0; i < names.length; i++) {
- if (names[i].length > max) {
- max = names[i].length;
- maxI = i;
- }
- }
- return maxI;
- };
- date.setMonth(findMax(this._get(inst, (dateFormat.match(/MM/) ?
- "monthNames" : "monthNamesShort"))));
- date.setDate(findMax(this._get(inst, (dateFormat.match(/DD/) ?
- "dayNames" : "dayNamesShort"))) + 20 - date.getDay());
- }
- inst.input.attr("size", this._formatDate(inst, date).length);
- }
- },
-
- /* Attach an inline date picker to a div. */
- _inlineDatepicker: function(target, inst) {
- var divSpan = $(target);
- if (divSpan.hasClass(this.markerClassName)) {
- return;
- }
- divSpan.addClass(this.markerClassName).append(inst.dpDiv);
- $.data(target, PROP_NAME, inst);
- this._setDate(inst, this._getDefaultDate(inst), true);
- this._updateDatepicker(inst);
- this._updateAlternate(inst);
- //If disabled option is true, disable the datepicker before showing it (see ticket #5665)
- if( inst.settings.disabled ) {
- this._disableDatepicker( target );
- }
- // Set display:block in place of inst.dpDiv.show() which won't work on disconnected elements
- // http://bugs.jqueryui.com/ticket/7552 - A Datepicker created on a detached div has zero height
- inst.dpDiv.css( "display", "block" );
- },
-
- /* Pop-up the date picker in a "dialog" box.
- * @param input element - ignored
- * @param date string or Date - the initial date to display
- * @param onSelect function - the function to call when a date is selected
- * @param settings object - update the dialog date picker instance's settings (anonymous object)
- * @param pos int[2] - coordinates for the dialog's position within the screen or
- * event - with x/y coordinates or
- * leave empty for default (screen centre)
- * @return the manager object
- */
- _dialogDatepicker: function(input, date, onSelect, settings, pos) {
- var id, browserWidth, browserHeight, scrollX, scrollY,
- inst = this._dialogInst; // internal instance
-
- if (!inst) {
- this.uuid += 1;
- id = "dp" + this.uuid;
- this._dialogInput = $("<input type='text' id='" + id +
- "' style='position: absolute; top: -100px; width: 0px;'/>");
- this._dialogInput.keydown(this._doKeyDown);
- $("body").append(this._dialogInput);
- inst = this._dialogInst = this._newInst(this._dialogInput, false);
- inst.settings = {};
- $.data(this._dialogInput[0], PROP_NAME, inst);
- }
- extendRemove(inst.settings, settings || {});
- date = (date && date.constructor === Date ? this._formatDate(inst, date) : date);
- this._dialogInput.val(date);
-
- this._pos = (pos ? (pos.length ? pos : [pos.pageX, pos.pageY]) : null);
- if (!this._pos) {
- browserWidth = document.documentElement.clientWidth;
- browserHeight = document.documentElement.clientHeight;
- scrollX = document.documentElement.scrollLeft || document.body.scrollLeft;
- scrollY = document.documentElement.scrollTop || document.body.scrollTop;
- this._pos = // should use actual width/height below
- [(browserWidth / 2) - 100 + scrollX, (browserHeight / 2) - 150 + scrollY];
- }
-
- // move input on screen for focus, but hidden behind dialog
- this._dialogInput.css("left", (this._pos[0] + 20) + "px").css("top", this._pos[1] + "px");
- inst.settings.onSelect = onSelect;
- this._inDialog = true;
- this.dpDiv.addClass(this._dialogClass);
- this._showDatepicker(this._dialogInput[0]);
- if ($.blockUI) {
- $.blockUI(this.dpDiv);
- }
- $.data(this._dialogInput[0], PROP_NAME, inst);
- return this;
- },
-
- /* Detach a datepicker from its control.
- * @param target element - the target input field or division or span
- */
- _destroyDatepicker: function(target) {
- var nodeName,
- $target = $(target),
- inst = $.data(target, PROP_NAME);
-
- if (!$target.hasClass(this.markerClassName)) {
- return;
- }
-
- nodeName = target.nodeName.toLowerCase();
- $.removeData(target, PROP_NAME);
- if (nodeName === "input") {
- inst.append.remove();
- inst.trigger.remove();
- $target.removeClass(this.markerClassName).
- unbind("focus", this._showDatepicker).
- unbind("keydown", this._doKeyDown).
- unbind("keypress", this._doKeyPress).
- unbind("keyup", this._doKeyUp);
- } else if (nodeName === "div" || nodeName === "span") {
- $target.removeClass(this.markerClassName).empty();
- }
- },
-
- /* Enable the date picker to a jQuery selection.
- * @param target element - the target input field or division or span
- */
- _enableDatepicker: function(target) {
- var nodeName, inline,
- $target = $(target),
- inst = $.data(target, PROP_NAME);
-
- if (!$target.hasClass(this.markerClassName)) {
- return;
- }
-
- nodeName = target.nodeName.toLowerCase();
- if (nodeName === "input") {
- target.disabled = false;
- inst.trigger.filter("button").
- each(function() { this.disabled = false; }).end().
- filter("img").css({opacity: "1.0", cursor: ""});
- } else if (nodeName === "div" || nodeName === "span") {
- inline = $target.children("." + this._inlineClass);
- inline.children().removeClass("ui-state-disabled");
- inline.find("select.ui-datepicker-month, select.ui-datepicker-year").
- prop("disabled", false);
- }
- this._disabledInputs = $.map(this._disabledInputs,
- function(value) { return (value === target ? null : value); }); // delete entry
- },
-
- /* Disable the date picker to a jQuery selection.
- * @param target element - the target input field or division or span
- */
- _disableDatepicker: function(target) {
- var nodeName, inline,
- $target = $(target),
- inst = $.data(target, PROP_NAME);
-
- if (!$target.hasClass(this.markerClassName)) {
- return;
- }
-
- nodeName = target.nodeName.toLowerCase();
- if (nodeName === "input") {
- target.disabled = true;
- inst.trigger.filter("button").
- each(function() { this.disabled = true; }).end().
- filter("img").css({opacity: "0.5", cursor: "default"});
- } else if (nodeName === "div" || nodeName === "span") {
- inline = $target.children("." + this._inlineClass);
- inline.children().addClass("ui-state-disabled");
- inline.find("select.ui-datepicker-month, select.ui-datepicker-year").
- prop("disabled", true);
- }
- this._disabledInputs = $.map(this._disabledInputs,
- function(value) { return (value === target ? null : value); }); // delete entry
- this._disabledInputs[this._disabledInputs.length] = target;
- },
-
- /* Is the first field in a jQuery collection disabled as a datepicker?
- * @param target element - the target input field or division or span
- * @return boolean - true if disabled, false if enabled
- */
- _isDisabledDatepicker: function(target) {
- if (!target) {
- return false;
- }
- for (var i = 0; i < this._disabledInputs.length; i++) {
- if (this._disabledInputs[i] === target) {
- return true;
- }
- }
- return false;
- },
-
- /* Retrieve the instance data for the target control.
- * @param target element - the target input field or division or span
- * @return object - the associated instance data
- * @throws error if a jQuery problem getting data
- */
- _getInst: function(target) {
- try {
- return $.data(target, PROP_NAME);
- }
- catch (err) {
- throw "Missing instance data for this datepicker";
- }
- },
-
- /* Update or retrieve the settings for a date picker attached to an input field or division.
- * @param target element - the target input field or division or span
- * @param name object - the new settings to update or
- * string - the name of the setting to change or retrieve,
- * when retrieving also "all" for all instance settings or
- * "defaults" for all global defaults
- * @param value any - the new value for the setting
- * (omit if above is an object or to retrieve a value)
- */
- _optionDatepicker: function(target, name, value) {
- var settings, date, minDate, maxDate,
- inst = this._getInst(target);
-
- if (arguments.length === 2 && typeof name === "string") {
- return (name === "defaults" ? $.extend({}, $.datepicker._defaults) :
- (inst ? (name === "all" ? $.extend({}, inst.settings) :
- this._get(inst, name)) : null));
- }
-
- settings = name || {};
- if (typeof name === "string") {
- settings = {};
- settings[name] = value;
- }
-
- if (inst) {
- if (this._curInst === inst) {
- this._hideDatepicker();
- }
-
- date = this._getDateDatepicker(target, true);
- minDate = this._getMinMaxDate(inst, "min");
- maxDate = this._getMinMaxDate(inst, "max");
- extendRemove(inst.settings, settings);
- // reformat the old minDate/maxDate values if dateFormat changes and a new minDate/maxDate isn't provided
- if (minDate !== null && settings.dateFormat !== undefined && settings.minDate === undefined) {
- inst.settings.minDate = this._formatDate(inst, minDate);
- }
- if (maxDate !== null && settings.dateFormat !== undefined && settings.maxDate === undefined) {
- inst.settings.maxDate = this._formatDate(inst, maxDate);
- }
- if ( "disabled" in settings ) {
- if ( settings.disabled ) {
- this._disableDatepicker(target);
- } else {
- this._enableDatepicker(target);
- }
- }
- this._attachments($(target), inst);
- this._autoSize(inst);
- this._setDate(inst, date);
- this._updateAlternate(inst);
- this._updateDatepicker(inst);
- }
- },
-
- // change method deprecated
- _changeDatepicker: function(target, name, value) {
- this._optionDatepicker(target, name, value);
- },
-
- /* Redraw the date picker attached to an input field or division.
- * @param target element - the target input field or division or span
- */
- _refreshDatepicker: function(target) {
- var inst = this._getInst(target);
- if (inst) {
- this._updateDatepicker(inst);
- }
- },
-
- /* Set the dates for a jQuery selection.
- * @param target element - the target input field or division or span
- * @param date Date - the new date
- */
- _setDateDatepicker: function(target, date) {
- var inst = this._getInst(target);
- if (inst) {
- this._setDate(inst, date);
- this._updateDatepicker(inst);
- this._updateAlternate(inst);
- }
- },
-
- /* Get the date(s) for the first entry in a jQuery selection.
- * @param target element - the target input field or division or span
- * @param noDefault boolean - true if no default date is to be used
- * @return Date - the current date
- */
- _getDateDatepicker: function(target, noDefault) {
- var inst = this._getInst(target);
- if (inst && !inst.inline) {
- this._setDateFromField(inst, noDefault);
- }
- return (inst ? this._getDate(inst) : null);
- },
-
- /* Handle keystrokes. */
- _doKeyDown: function(event) {
- var onSelect, dateStr, sel,
- inst = $.datepicker._getInst(event.target),
- handled = true,
- isRTL = inst.dpDiv.is(".ui-datepicker-rtl");
-
- inst._keyEvent = true;
- if ($.datepicker._datepickerShowing) {
- switch (event.keyCode) {
- case 9: $.datepicker._hideDatepicker();
- handled = false;
- break; // hide on tab out
- case 13: sel = $("td." + $.datepicker._dayOverClass + ":not(." +
- $.datepicker._currentClass + ")", inst.dpDiv);
- if (sel[0]) {
- $.datepicker._selectDay(event.target, inst.selectedMonth, inst.selectedYear, sel[0]);
- }
-
- onSelect = $.datepicker._get(inst, "onSelect");
- if (onSelect) {
- dateStr = $.datepicker._formatDate(inst);
-
- // trigger custom callback
- onSelect.apply((inst.input ? inst.input[0] : null), [dateStr, inst]);
- } else {
- $.datepicker._hideDatepicker();
- }
-
- return false; // don't submit the form
- case 27: $.datepicker._hideDatepicker();
- break; // hide on escape
- case 33: $.datepicker._adjustDate(event.target, (event.ctrlKey ?
- -$.datepicker._get(inst, "stepBigMonths") :
- -$.datepicker._get(inst, "stepMonths")), "M");
- break; // previous month/year on page up/+ ctrl
- case 34: $.datepicker._adjustDate(event.target, (event.ctrlKey ?
- +$.datepicker._get(inst, "stepBigMonths") :
- +$.datepicker._get(inst, "stepMonths")), "M");
- break; // next month/year on page down/+ ctrl
- case 35: if (event.ctrlKey || event.metaKey) {
- $.datepicker._clearDate(event.target);
- }
- handled = event.ctrlKey || event.metaKey;
- break; // clear on ctrl or command +end
- case 36: if (event.ctrlKey || event.metaKey) {
- $.datepicker._gotoToday(event.target);
- }
- handled = event.ctrlKey || event.metaKey;
- break; // current on ctrl or command +home
- case 37: if (event.ctrlKey || event.metaKey) {
- $.datepicker._adjustDate(event.target, (isRTL ? +1 : -1), "D");
- }
- handled = event.ctrlKey || event.metaKey;
- // -1 day on ctrl or command +left
- if (event.originalEvent.altKey) {
- $.datepicker._adjustDate(event.target, (event.ctrlKey ?
- -$.datepicker._get(inst, "stepBigMonths") :
- -$.datepicker._get(inst, "stepMonths")), "M");
- }
- // next month/year on alt +left on Mac
- break;
- case 38: if (event.ctrlKey || event.metaKey) {
- $.datepicker._adjustDate(event.target, -7, "D");
- }
- handled = event.ctrlKey || event.metaKey;
- break; // -1 week on ctrl or command +up
- case 39: if (event.ctrlKey || event.metaKey) {
- $.datepicker._adjustDate(event.target, (isRTL ? -1 : +1), "D");
- }
- handled = event.ctrlKey || event.metaKey;
- // +1 day on ctrl or command +right
- if (event.originalEvent.altKey) {
- $.datepicker._adjustDate(event.target, (event.ctrlKey ?
- +$.datepicker._get(inst, "stepBigMonths") :
- +$.datepicker._get(inst, "stepMonths")), "M");
- }
- // next month/year on alt +right
- break;
- case 40: if (event.ctrlKey || event.metaKey) {
- $.datepicker._adjustDate(event.target, +7, "D");
- }
- handled = event.ctrlKey || event.metaKey;
- break; // +1 week on ctrl or command +down
- default: handled = false;
- }
- } else if (event.keyCode === 36 && event.ctrlKey) { // display the date picker on ctrl+home
- $.datepicker._showDatepicker(this);
- } else {
- handled = false;
- }
-
- if (handled) {
- event.preventDefault();
- event.stopPropagation();
- }
- },
-
- /* Filter entered characters - based on date format. */
- _doKeyPress: function(event) {
- var chars, chr,
- inst = $.datepicker._getInst(event.target);
-
- if ($.datepicker._get(inst, "constrainInput")) {
- chars = $.datepicker._possibleChars($.datepicker._get(inst, "dateFormat"));
- chr = String.fromCharCode(event.charCode == null ? event.keyCode : event.charCode);
- return event.ctrlKey || event.metaKey || (chr < " " || !chars || chars.indexOf(chr) > -1);
- }
- },
-
- /* Synchronise manual entry and field/alternate field. */
- _doKeyUp: function(event) {
- var date,
- inst = $.datepicker._getInst(event.target);
-
- if (inst.input.val() !== inst.lastVal) {
- try {
- date = $.datepicker.parseDate($.datepicker._get(inst, "dateFormat"),
- (inst.input ? inst.input.val() : null),
- $.datepicker._getFormatConfig(inst));
-
- if (date) { // only if valid
- $.datepicker._setDateFromField(inst);
- $.datepicker._updateAlternate(inst);
- $.datepicker._updateDatepicker(inst);
- }
- }
- catch (err) {
- }
- }
- return true;
- },
-
- /* Pop-up the date picker for a given input field.
- * If false returned from beforeShow event handler do not show.
- * @param input element - the input field attached to the date picker or
- * event - if triggered by focus
- */
- _showDatepicker: function(input) {
- input = input.target || input;
- if (input.nodeName.toLowerCase() !== "input") { // find from button/image trigger
- input = $("input", input.parentNode)[0];
- }
-
- if ($.datepicker._isDisabledDatepicker(input) || $.datepicker._lastInput === input) { // already here
- return;
- }
-
- var inst, beforeShow, beforeShowSettings, isFixed,
- offset, showAnim, duration;
-
- inst = $.datepicker._getInst(input);
- if ($.datepicker._curInst && $.datepicker._curInst !== inst) {
- $.datepicker._curInst.dpDiv.stop(true, true);
- if ( inst && $.datepicker._datepickerShowing ) {
- $.datepicker._hideDatepicker( $.datepicker._curInst.input[0] );
- }
- }
-
- beforeShow = $.datepicker._get(inst, "beforeShow");
- beforeShowSettings = beforeShow ? beforeShow.apply(input, [input, inst]) : {};
- if(beforeShowSettings === false){
- return;
- }
- extendRemove(inst.settings, beforeShowSettings);
-
- inst.lastVal = null;
- $.datepicker._lastInput = input;
- $.datepicker._setDateFromField(inst);
-
- if ($.datepicker._inDialog) { // hide cursor
- input.value = "";
- }
- if (!$.datepicker._pos) { // position below input
- $.datepicker._pos = $.datepicker._findPos(input);
- $.datepicker._pos[1] += input.offsetHeight; // add the height
- }
-
- isFixed = false;
- $(input).parents().each(function() {
- isFixed |= $(this).css("position") === "fixed";
- return !isFixed;
- });
-
- offset = {left: $.datepicker._pos[0], top: $.datepicker._pos[1]};
- $.datepicker._pos = null;
- //to avoid flashes on Firefox
- inst.dpDiv.empty();
- // determine sizing offscreen
- inst.dpDiv.css({position: "absolute", display: "block", top: "-1000px"});
- $.datepicker._updateDatepicker(inst);
- // fix width for dynamic number of date pickers
- // and adjust position before showing
- offset = $.datepicker._checkOffset(inst, offset, isFixed);
- inst.dpDiv.css({position: ($.datepicker._inDialog && $.blockUI ?
- "static" : (isFixed ? "fixed" : "absolute")), display: "none",
- left: offset.left + "px", top: offset.top + "px"});
-
- if (!inst.inline) {
- showAnim = $.datepicker._get(inst, "showAnim");
- duration = $.datepicker._get(inst, "duration");
- inst.dpDiv.zIndex($(input).zIndex()+1);
- $.datepicker._datepickerShowing = true;
-
- if ( $.effects && $.effects.effect[ showAnim ] ) {
- inst.dpDiv.show(showAnim, $.datepicker._get(inst, "showOptions"), duration);
- } else {
- inst.dpDiv[showAnim || "show"](showAnim ? duration : null);
- }
-
- if ( $.datepicker._shouldFocusInput( inst ) ) {
- inst.input.focus();
- }
-
- $.datepicker._curInst = inst;
- }
- },
-
- /* Generate the date picker content. */
- _updateDatepicker: function(inst) {
- this.maxRows = 4; //Reset the max number of rows being displayed (see #7043)
- instActive = inst; // for delegate hover events
- inst.dpDiv.empty().append(this._generateHTML(inst));
- this._attachHandlers(inst);
- inst.dpDiv.find("." + this._dayOverClass + " a").mouseover();
-
- var origyearshtml,
- numMonths = this._getNumberOfMonths(inst),
- cols = numMonths[1],
- width = 17;
-
- inst.dpDiv.removeClass("ui-datepicker-multi-2 ui-datepicker-multi-3 ui-datepicker-multi-4").width("");
- if (cols > 1) {
- inst.dpDiv.addClass("ui-datepicker-multi-" + cols).css("width", (width * cols) + "em");
- }
- inst.dpDiv[(numMonths[0] !== 1 || numMonths[1] !== 1 ? "add" : "remove") +
- "Class"]("ui-datepicker-multi");
- inst.dpDiv[(this._get(inst, "isRTL") ? "add" : "remove") +
- "Class"]("ui-datepicker-rtl");
-
- if (inst === $.datepicker._curInst && $.datepicker._datepickerShowing && $.datepicker._shouldFocusInput( inst ) ) {
- inst.input.focus();
- }
-
- // deffered render of the years select (to avoid flashes on Firefox)
- if( inst.yearshtml ){
- origyearshtml = inst.yearshtml;
- setTimeout(function(){
- //assure that inst.yearshtml didn't change.
- if( origyearshtml === inst.yearshtml && inst.yearshtml ){
- inst.dpDiv.find("select.ui-datepicker-year:first").replaceWith(inst.yearshtml);
- }
- origyearshtml = inst.yearshtml = null;
- }, 0);
- }
- },
-
- // #6694 - don't focus the input if it's already focused
- // this breaks the change event in IE
- // Support: IE and jQuery <1.9
- _shouldFocusInput: function( inst ) {
- return inst.input && inst.input.is( ":visible" ) && !inst.input.is( ":disabled" ) && !inst.input.is( ":focus" );
- },
-
- /* Check positioning to remain on screen. */
- _checkOffset: function(inst, offset, isFixed) {
- var dpWidth = inst.dpDiv.outerWidth(),
- dpHeight = inst.dpDiv.outerHeight(),
- inputWidth = inst.input ? inst.input.outerWidth() : 0,
- inputHeight = inst.input ? inst.input.outerHeight() : 0,
- viewWidth = document.documentElement.clientWidth + (isFixed ? 0 : $(document).scrollLeft()),
- viewHeight = document.documentElement.clientHeight + (isFixed ? 0 : $(document).scrollTop());
-
- offset.left -= (this._get(inst, "isRTL") ? (dpWidth - inputWidth) : 0);
- offset.left -= (isFixed && offset.left === inst.input.offset().left) ? $(document).scrollLeft() : 0;
- offset.top -= (isFixed && offset.top === (inst.input.offset().top + inputHeight)) ? $(document).scrollTop() : 0;
-
- // now check if datepicker is showing outside window viewport - move to a better place if so.
- offset.left -= Math.min(offset.left, (offset.left + dpWidth > viewWidth && viewWidth > dpWidth) ?
- Math.abs(offset.left + dpWidth - viewWidth) : 0);
- offset.top -= Math.min(offset.top, (offset.top + dpHeight > viewHeight && viewHeight > dpHeight) ?
- Math.abs(dpHeight + inputHeight) : 0);
-
- return offset;
- },
-
- /* Find an object's position on the screen. */
- _findPos: function(obj) {
- var position,
- inst = this._getInst(obj),
- isRTL = this._get(inst, "isRTL");
-
- while (obj && (obj.type === "hidden" || obj.nodeType !== 1 || $.expr.filters.hidden(obj))) {
- obj = obj[isRTL ? "previousSibling" : "nextSibling"];
- }
-
- position = $(obj).offset();
- return [position.left, position.top];
- },
-
- /* Hide the date picker from view.
- * @param input element - the input field attached to the date picker
- */
- _hideDatepicker: function(input) {
- var showAnim, duration, postProcess, onClose,
- inst = this._curInst;
-
- if (!inst || (input && inst !== $.data(input, PROP_NAME))) {
- return;
- }
-
- if (this._datepickerShowing) {
- showAnim = this._get(inst, "showAnim");
- duration = this._get(inst, "duration");
- postProcess = function() {
- $.datepicker._tidyDialog(inst);
- };
-
- // DEPRECATED: after BC for 1.8.x $.effects[ showAnim ] is not needed
- if ( $.effects && ( $.effects.effect[ showAnim ] || $.effects[ showAnim ] ) ) {
- inst.dpDiv.hide(showAnim, $.datepicker._get(inst, "showOptions"), duration, postProcess);
- } else {
- inst.dpDiv[(showAnim === "slideDown" ? "slideUp" :
- (showAnim === "fadeIn" ? "fadeOut" : "hide"))]((showAnim ? duration : null), postProcess);
- }
-
- if (!showAnim) {
- postProcess();
- }
- this._datepickerShowing = false;
-
- onClose = this._get(inst, "onClose");
- if (onClose) {
- onClose.apply((inst.input ? inst.input[0] : null), [(inst.input ? inst.input.val() : ""), inst]);
- }
-
- this._lastInput = null;
- if (this._inDialog) {
- this._dialogInput.css({ position: "absolute", left: "0", top: "-100px" });
- if ($.blockUI) {
- $.unblockUI();
- $("body").append(this.dpDiv);
- }
- }
- this._inDialog = false;
- }
- },
-
- /* Tidy up after a dialog display. */
- _tidyDialog: function(inst) {
- inst.dpDiv.removeClass(this._dialogClass).unbind(".ui-datepicker-calendar");
- },
-
- /* Close date picker if clicked elsewhere. */
- _checkExternalClick: function(event) {
- if (!$.datepicker._curInst) {
- return;
- }
-
- var $target = $(event.target),
- inst = $.datepicker._getInst($target[0]);
-
- if ( ( ( $target[0].id !== $.datepicker._mainDivId &&
- $target.parents("#" + $.datepicker._mainDivId).length === 0 &&
- !$target.hasClass($.datepicker.markerClassName) &&
- !$target.closest("." + $.datepicker._triggerClass).length &&
- $.datepicker._datepickerShowing && !($.datepicker._inDialog && $.blockUI) ) ) ||
- ( $target.hasClass($.datepicker.markerClassName) && $.datepicker._curInst !== inst ) ) {
- $.datepicker._hideDatepicker();
- }
- },
-
- /* Adjust one of the date sub-fields. */
- _adjustDate: function(id, offset, period) {
- var target = $(id),
- inst = this._getInst(target[0]);
-
- if (this._isDisabledDatepicker(target[0])) {
- return;
- }
- this._adjustInstDate(inst, offset +
- (period === "M" ? this._get(inst, "showCurrentAtPos") : 0), // undo positioning
- period);
- this._updateDatepicker(inst);
- },
-
- /* Action for current link. */
- _gotoToday: function(id) {
- var date,
- target = $(id),
- inst = this._getInst(target[0]);
-
- if (this._get(inst, "gotoCurrent") && inst.currentDay) {
- inst.selectedDay = inst.currentDay;
- inst.drawMonth = inst.selectedMonth = inst.currentMonth;
- inst.drawYear = inst.selectedYear = inst.currentYear;
- } else {
- date = new Date();
- inst.selectedDay = date.getDate();
- inst.drawMonth = inst.selectedMonth = date.getMonth();
- inst.drawYear = inst.selectedYear = date.getFullYear();
- }
- this._notifyChange(inst);
- this._adjustDate(target);
- },
-
- /* Action for selecting a new month/year. */
- _selectMonthYear: function(id, select, period) {
- var target = $(id),
- inst = this._getInst(target[0]);
-
- inst["selected" + (period === "M" ? "Month" : "Year")] =
- inst["draw" + (period === "M" ? "Month" : "Year")] =
- parseInt(select.options[select.selectedIndex].value,10);
-
- this._notifyChange(inst);
- this._adjustDate(target);
- },
-
- /* Action for selecting a day. */
- _selectDay: function(id, month, year, td) {
- var inst,
- target = $(id);
-
- if ($(td).hasClass(this._unselectableClass) || this._isDisabledDatepicker(target[0])) {
- return;
- }
-
- inst = this._getInst(target[0]);
- inst.selectedDay = inst.currentDay = $("a", td).html();
- inst.selectedMonth = inst.currentMonth = month;
- inst.selectedYear = inst.currentYear = year;
- this._selectDate(id, this._formatDate(inst,
- inst.currentDay, inst.currentMonth, inst.currentYear));
- },
-
- /* Erase the input field and hide the date picker. */
- _clearDate: function(id) {
- var target = $(id);
- this._selectDate(target, "");
- },
-
- /* Update the input field with the selected date. */
- _selectDate: function(id, dateStr) {
- var onSelect,
- target = $(id),
- inst = this._getInst(target[0]);
-
- dateStr = (dateStr != null ? dateStr : this._formatDate(inst));
- if (inst.input) {
- inst.input.val(dateStr);
- }
- this._updateAlternate(inst);
-
- onSelect = this._get(inst, "onSelect");
- if (onSelect) {
- onSelect.apply((inst.input ? inst.input[0] : null), [dateStr, inst]); // trigger custom callback
- } else if (inst.input) {
- inst.input.trigger("change"); // fire the change event
- }
-
- if (inst.inline){
- this._updateDatepicker(inst);
- } else {
- this._hideDatepicker();
- this._lastInput = inst.input[0];
- if (typeof(inst.input[0]) !== "object") {
- inst.input.focus(); // restore focus
- }
- this._lastInput = null;
- }
- },
-
- /* Update any alternate field to synchronise with the main field. */
- _updateAlternate: function(inst) {
- var altFormat, date, dateStr,
- altField = this._get(inst, "altField");
-
- if (altField) { // update alternate field too
- altFormat = this._get(inst, "altFormat") || this._get(inst, "dateFormat");
- date = this._getDate(inst);
- dateStr = this.formatDate(altFormat, date, this._getFormatConfig(inst));
- $(altField).each(function() { $(this).val(dateStr); });
- }
- },
-
- /* Set as beforeShowDay function to prevent selection of weekends.
- * @param date Date - the date to customise
- * @return [boolean, string] - is this date selectable?, what is its CSS class?
- */
- noWeekends: function(date) {
- var day = date.getDay();
- return [(day > 0 && day < 6), ""];
- },
-
- /* Set as calculateWeek to determine the week of the year based on the ISO 8601 definition.
- * @param date Date - the date to get the week for
- * @return number - the number of the week within the year that contains this date
- */
- iso8601Week: function(date) {
- var time,
- checkDate = new Date(date.getTime());
-
- // Find Thursday of this week starting on Monday
- checkDate.setDate(checkDate.getDate() + 4 - (checkDate.getDay() || 7));
-
- time = checkDate.getTime();
- checkDate.setMonth(0); // Compare with Jan 1
- checkDate.setDate(1);
- return Math.floor(Math.round((time - checkDate) / 86400000) / 7) + 1;
- },
-
- /* Parse a string value into a date object.
- * See formatDate below for the possible formats.
- *
- * @param format string - the expected format of the date
- * @param value string - the date in the above format
- * @param settings Object - attributes include:
- * shortYearCutoff number - the cutoff year for determining the century (optional)
- * dayNamesShort string[7] - abbreviated names of the days from Sunday (optional)
- * dayNames string[7] - names of the days from Sunday (optional)
- * monthNamesShort string[12] - abbreviated names of the months (optional)
- * monthNames string[12] - names of the months (optional)
- * @return Date - the extracted date value or null if value is blank
- */
- parseDate: function (format, value, settings) {
- if (format == null || value == null) {
- throw "Invalid arguments";
- }
-
- value = (typeof value === "object" ? value.toString() : value + "");
- if (value === "") {
- return null;
- }
-
- var iFormat, dim, extra,
- iValue = 0,
- shortYearCutoffTemp = (settings ? settings.shortYearCutoff : null) || this._defaults.shortYearCutoff,
- shortYearCutoff = (typeof shortYearCutoffTemp !== "string" ? shortYearCutoffTemp :
- new Date().getFullYear() % 100 + parseInt(shortYearCutoffTemp, 10)),
- dayNamesShort = (settings ? settings.dayNamesShort : null) || this._defaults.dayNamesShort,
- dayNames = (settings ? settings.dayNames : null) || this._defaults.dayNames,
- monthNamesShort = (settings ? settings.monthNamesShort : null) || this._defaults.monthNamesShort,
- monthNames = (settings ? settings.monthNames : null) || this._defaults.monthNames,
- year = -1,
- month = -1,
- day = -1,
- doy = -1,
- literal = false,
- date,
- // Check whether a format character is doubled
- lookAhead = function(match) {
- var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) === match);
- if (matches) {
- iFormat++;
- }
- return matches;
- },
- // Extract a number from the string value
- getNumber = function(match) {
- var isDoubled = lookAhead(match),
- size = (match === "@" ? 14 : (match === "!" ? 20 :
- (match === "y" && isDoubled ? 4 : (match === "o" ? 3 : 2)))),
- digits = new RegExp("^\\d{1," + size + "}"),
- num = value.substring(iValue).match(digits);
- if (!num) {
- throw "Missing number at position " + iValue;
- }
- iValue += num[0].length;
- return parseInt(num[0], 10);
- },
- // Extract a name from the string value and convert to an index
- getName = function(match, shortNames, longNames) {
- var index = -1,
- names = $.map(lookAhead(match) ? longNames : shortNames, function (v, k) {
- return [ [k, v] ];
- }).sort(function (a, b) {
- return -(a[1].length - b[1].length);
- });
-
- $.each(names, function (i, pair) {
- var name = pair[1];
- if (value.substr(iValue, name.length).toLowerCase() === name.toLowerCase()) {
- index = pair[0];
- iValue += name.length;
- return false;
- }
- });
- if (index !== -1) {
- return index + 1;
- } else {
- throw "Unknown name at position " + iValue;
- }
- },
- // Confirm that a literal character matches the string value
- checkLiteral = function() {
- if (value.charAt(iValue) !== format.charAt(iFormat)) {
- throw "Unexpected literal at position " + iValue;
- }
- iValue++;
- };
-
- for (iFormat = 0; iFormat < format.length; iFormat++) {
- if (literal) {
- if (format.charAt(iFormat) === "'" && !lookAhead("'")) {
- literal = false;
- } else {
- checkLiteral();
- }
- } else {
- switch (format.charAt(iFormat)) {
- case "d":
- day = getNumber("d");
- break;
- case "D":
- getName("D", dayNamesShort, dayNames);
- break;
- case "o":
- doy = getNumber("o");
- break;
- case "m":
- month = getNumber("m");
- break;
- case "M":
- month = getName("M", monthNamesShort, monthNames);
- break;
- case "y":
- year = getNumber("y");
- break;
- case "@":
- date = new Date(getNumber("@"));
- year = date.getFullYear();
- month = date.getMonth() + 1;
- day = date.getDate();
- break;
- case "!":
- date = new Date((getNumber("!") - this._ticksTo1970) / 10000);
- year = date.getFullYear();
- month = date.getMonth() + 1;
- day = date.getDate();
- break;
- case "'":
- if (lookAhead("'")){
- checkLiteral();
- } else {
- literal = true;
- }
- break;
- default:
- checkLiteral();
- }
- }
- }
-
- if (iValue < value.length){
- extra = value.substr(iValue);
- if (!/^\s+/.test(extra)) {
- throw "Extra/unparsed characters found in date: " + extra;
- }
- }
-
- if (year === -1) {
- year = new Date().getFullYear();
- } else if (year < 100) {
- year += new Date().getFullYear() - new Date().getFullYear() % 100 +
- (year <= shortYearCutoff ? 0 : -100);
- }
-
- if (doy > -1) {
- month = 1;
- day = doy;
- do {
- dim = this._getDaysInMonth(year, month - 1);
- if (day <= dim) {
- break;
- }
- month++;
- day -= dim;
- } while (true);
- }
-
- date = this._daylightSavingAdjust(new Date(year, month - 1, day));
- if (date.getFullYear() !== year || date.getMonth() + 1 !== month || date.getDate() !== day) {
- throw "Invalid date"; // E.g. 31/02/00
- }
- return date;
- },
-
- /* Standard date formats. */
- ATOM: "yy-mm-dd", // RFC 3339 (ISO 8601)
- COOKIE: "D, dd M yy",
- ISO_8601: "yy-mm-dd",
- RFC_822: "D, d M y",
- RFC_850: "DD, dd-M-y",
- RFC_1036: "D, d M y",
- RFC_1123: "D, d M yy",
- RFC_2822: "D, d M yy",
- RSS: "D, d M y", // RFC 822
- TICKS: "!",
- TIMESTAMP: "@",
- W3C: "yy-mm-dd", // ISO 8601
-
- _ticksTo1970: (((1970 - 1) * 365 + Math.floor(1970 / 4) - Math.floor(1970 / 100) +
- Math.floor(1970 / 400)) * 24 * 60 * 60 * 10000000),
-
- /* Format a date object into a string value.
- * The format can be combinations of the following:
- * d - day of month (no leading zero)
- * dd - day of month (two digit)
- * o - day of year (no leading zeros)
- * oo - day of year (three digit)
- * D - day name short
- * DD - day name long
- * m - month of year (no leading zero)
- * mm - month of year (two digit)
- * M - month name short
- * MM - month name long
- * y - year (two digit)
- * yy - year (four digit)
- * @ - Unix timestamp (ms since 01/01/1970)
- * ! - Windows ticks (100ns since 01/01/0001)
- * "..." - literal text
- * '' - single quote
- *
- * @param format string - the desired format of the date
- * @param date Date - the date value to format
- * @param settings Object - attributes include:
- * dayNamesShort string[7] - abbreviated names of the days from Sunday (optional)
- * dayNames string[7] - names of the days from Sunday (optional)
- * monthNamesShort string[12] - abbreviated names of the months (optional)
- * monthNames string[12] - names of the months (optional)
- * @return string - the date in the above format
- */
- formatDate: function (format, date, settings) {
- if (!date) {
- return "";
- }
-
- var iFormat,
- dayNamesShort = (settings ? settings.dayNamesShort : null) || this._defaults.dayNamesShort,
- dayNames = (settings ? settings.dayNames : null) || this._defaults.dayNames,
- monthNamesShort = (settings ? settings.monthNamesShort : null) || this._defaults.monthNamesShort,
- monthNames = (settings ? settings.monthNames : null) || this._defaults.monthNames,
- // Check whether a format character is doubled
- lookAhead = function(match) {
- var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) === match);
- if (matches) {
- iFormat++;
- }
- return matches;
- },
- // Format a number, with leading zero if necessary
- formatNumber = function(match, value, len) {
- var num = "" + value;
- if (lookAhead(match)) {
- while (num.length < len) {
- num = "0" + num;
- }
- }
- return num;
- },
- // Format a name, short or long as requested
- formatName = function(match, value, shortNames, longNames) {
- return (lookAhead(match) ? longNames[value] : shortNames[value]);
- },
- output = "",
- literal = false;
-
- if (date) {
- for (iFormat = 0; iFormat < format.length; iFormat++) {
- if (literal) {
- if (format.charAt(iFormat) === "'" && !lookAhead("'")) {
- literal = false;
- } else {
- output += format.charAt(iFormat);
- }
- } else {
- switch (format.charAt(iFormat)) {
- case "d":
- output += formatNumber("d", date.getDate(), 2);
- break;
- case "D":
- output += formatName("D", date.getDay(), dayNamesShort, dayNames);
- break;
- case "o":
- output += formatNumber("o",
- Math.round((new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime() - new Date(date.getFullYear(), 0, 0).getTime()) / 86400000), 3);
- break;
- case "m":
- output += formatNumber("m", date.getMonth() + 1, 2);
- break;
- case "M":
- output += formatName("M", date.getMonth(), monthNamesShort, monthNames);
- break;
- case "y":
- output += (lookAhead("y") ? date.getFullYear() :
- (date.getYear() % 100 < 10 ? "0" : "") + date.getYear() % 100);
- break;
- case "@":
- output += date.getTime();
- break;
- case "!":
- output += date.getTime() * 10000 + this._ticksTo1970;
- break;
- case "'":
- if (lookAhead("'")) {
- output += "'";
- } else {
- literal = true;
- }
- break;
- default:
- output += format.charAt(iFormat);
- }
- }
- }
- }
- return output;
- },
-
- /* Extract all possible characters from the date format. */
- _possibleChars: function (format) {
- var iFormat,
- chars = "",
- literal = false,
- // Check whether a format character is doubled
- lookAhead = function(match) {
- var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) === match);
- if (matches) {
- iFormat++;
- }
- return matches;
- };
-
- for (iFormat = 0; iFormat < format.length; iFormat++) {
- if (literal) {
- if (format.charAt(iFormat) === "'" && !lookAhead("'")) {
- literal = false;
- } else {
- chars += format.charAt(iFormat);
- }
- } else {
- switch (format.charAt(iFormat)) {
- case "d": case "m": case "y": case "@":
- chars += "0123456789";
- break;
- case "D": case "M":
- return null; // Accept anything
- case "'":
- if (lookAhead("'")) {
- chars += "'";
- } else {
- literal = true;
- }
- break;
- default:
- chars += format.charAt(iFormat);
- }
- }
- }
- return chars;
- },
-
- /* Get a setting value, defaulting if necessary. */
- _get: function(inst, name) {
- return inst.settings[name] !== undefined ?
- inst.settings[name] : this._defaults[name];
- },
-
- /* Parse existing date and initialise date picker. */
- _setDateFromField: function(inst, noDefault) {
- if (inst.input.val() === inst.lastVal) {
- return;
- }
-
- var dateFormat = this._get(inst, "dateFormat"),
- dates = inst.lastVal = inst.input ? inst.input.val() : null,
- defaultDate = this._getDefaultDate(inst),
- date = defaultDate,
- settings = this._getFormatConfig(inst);
-
- try {
- date = this.parseDate(dateFormat, dates, settings) || defaultDate;
- } catch (event) {
- dates = (noDefault ? "" : dates);
- }
- inst.selectedDay = date.getDate();
- inst.drawMonth = inst.selectedMonth = date.getMonth();
- inst.drawYear = inst.selectedYear = date.getFullYear();
- inst.currentDay = (dates ? date.getDate() : 0);
- inst.currentMonth = (dates ? date.getMonth() : 0);
- inst.currentYear = (dates ? date.getFullYear() : 0);
- this._adjustInstDate(inst);
- },
-
- /* Retrieve the default date shown on opening. */
- _getDefaultDate: function(inst) {
- return this._restrictMinMax(inst,
- this._determineDate(inst, this._get(inst, "defaultDate"), new Date()));
- },
-
- /* A date may be specified as an exact value or a relative one. */
- _determineDate: function(inst, date, defaultDate) {
- var offsetNumeric = function(offset) {
- var date = new Date();
- date.setDate(date.getDate() + offset);
- return date;
- },
- offsetString = function(offset) {
- try {
- return $.datepicker.parseDate($.datepicker._get(inst, "dateFormat"),
- offset, $.datepicker._getFormatConfig(inst));
- }
- catch (e) {
- // Ignore
- }
-
- var date = (offset.toLowerCase().match(/^c/) ?
- $.datepicker._getDate(inst) : null) || new Date(),
- year = date.getFullYear(),
- month = date.getMonth(),
- day = date.getDate(),
- pattern = /([+\-]?[0-9]+)\s*(d|D|w|W|m|M|y|Y)?/g,
- matches = pattern.exec(offset);
-
- while (matches) {
- switch (matches[2] || "d") {
- case "d" : case "D" :
- day += parseInt(matches[1],10); break;
- case "w" : case "W" :
- day += parseInt(matches[1],10) * 7; break;
- case "m" : case "M" :
- month += parseInt(matches[1],10);
- day = Math.min(day, $.datepicker._getDaysInMonth(year, month));
- break;
- case "y": case "Y" :
- year += parseInt(matches[1],10);
- day = Math.min(day, $.datepicker._getDaysInMonth(year, month));
- break;
- }
- matches = pattern.exec(offset);
- }
- return new Date(year, month, day);
- },
- newDate = (date == null || date === "" ? defaultDate : (typeof date === "string" ? offsetString(date) :
- (typeof date === "number" ? (isNaN(date) ? defaultDate : offsetNumeric(date)) : new Date(date.getTime()))));
-
- newDate = (newDate && newDate.toString() === "Invalid Date" ? defaultDate : newDate);
- if (newDate) {
- newDate.setHours(0);
- newDate.setMinutes(0);
- newDate.setSeconds(0);
- newDate.setMilliseconds(0);
- }
- return this._daylightSavingAdjust(newDate);
- },
-
- /* Handle switch to/from daylight saving.
- * Hours may be non-zero on daylight saving cut-over:
- * > 12 when midnight changeover, but then cannot generate
- * midnight datetime, so jump to 1AM, otherwise reset.
- * @param date (Date) the date to check
- * @return (Date) the corrected date
- */
- _daylightSavingAdjust: function(date) {
- if (!date) {
- return null;
- }
- date.setHours(date.getHours() > 12 ? date.getHours() + 2 : 0);
- return date;
- },
-
- /* Set the date(s) directly. */
- _setDate: function(inst, date, noChange) {
- var clear = !date,
- origMonth = inst.selectedMonth,
- origYear = inst.selectedYear,
- newDate = this._restrictMinMax(inst, this._determineDate(inst, date, new Date()));
-
- inst.selectedDay = inst.currentDay = newDate.getDate();
- inst.drawMonth = inst.selectedMonth = inst.currentMonth = newDate.getMonth();
- inst.drawYear = inst.selectedYear = inst.currentYear = newDate.getFullYear();
- if ((origMonth !== inst.selectedMonth || origYear !== inst.selectedYear) && !noChange) {
- this._notifyChange(inst);
- }
- this._adjustInstDate(inst);
- if (inst.input) {
- inst.input.val(clear ? "" : this._formatDate(inst));
- }
- },
-
- /* Retrieve the date(s) directly. */
- _getDate: function(inst) {
- var startDate = (!inst.currentYear || (inst.input && inst.input.val() === "") ? null :
- this._daylightSavingAdjust(new Date(
- inst.currentYear, inst.currentMonth, inst.currentDay)));
- return startDate;
- },
-
- /* Attach the onxxx handlers. These are declared statically so
- * they work with static code transformers like Caja.
- */
- _attachHandlers: function(inst) {
- var stepMonths = this._get(inst, "stepMonths"),
- id = "#" + inst.id.replace( /\\\\/g, "\\" );
- inst.dpDiv.find("[data-handler]").map(function () {
- var handler = {
- prev: function () {
- $.datepicker._adjustDate(id, -stepMonths, "M");
- },
- next: function () {
- $.datepicker._adjustDate(id, +stepMonths, "M");
- },
- hide: function () {
- $.datepicker._hideDatepicker();
- },
- today: function () {
- $.datepicker._gotoToday(id);
- },
- selectDay: function () {
- $.datepicker._selectDay(id, +this.getAttribute("data-month"), +this.getAttribute("data-year"), this);
- return false;
- },
- selectMonth: function () {
- $.datepicker._selectMonthYear(id, this, "M");
- return false;
- },
- selectYear: function () {
- $.datepicker._selectMonthYear(id, this, "Y");
- return false;
- }
- };
- $(this).bind(this.getAttribute("data-event"), handler[this.getAttribute("data-handler")]);
- });
- },
-
- /* Generate the HTML for the current state of the date picker. */
- _generateHTML: function(inst) {
- var maxDraw, prevText, prev, nextText, next, currentText, gotoDate,
- controls, buttonPanel, firstDay, showWeek, dayNames, dayNamesMin,
- monthNames, monthNamesShort, beforeShowDay, showOtherMonths,
- selectOtherMonths, defaultDate, html, dow, row, group, col, selectedDate,
- cornerClass, calender, thead, day, daysInMonth, leadDays, curRows, numRows,
- printDate, dRow, tbody, daySettings, otherMonth, unselectable,
- tempDate = new Date(),
- today = this._daylightSavingAdjust(
- new Date(tempDate.getFullYear(), tempDate.getMonth(), tempDate.getDate())), // clear time
- isRTL = this._get(inst, "isRTL"),
- showButtonPanel = this._get(inst, "showButtonPanel"),
- hideIfNoPrevNext = this._get(inst, "hideIfNoPrevNext"),
- navigationAsDateFormat = this._get(inst, "navigationAsDateFormat"),
- numMonths = this._getNumberOfMonths(inst),
- showCurrentAtPos = this._get(inst, "showCurrentAtPos"),
- stepMonths = this._get(inst, "stepMonths"),
- isMultiMonth = (numMonths[0] !== 1 || numMonths[1] !== 1),
- currentDate = this._daylightSavingAdjust((!inst.currentDay ? new Date(9999, 9, 9) :
- new Date(inst.currentYear, inst.currentMonth, inst.currentDay))),
- minDate = this._getMinMaxDate(inst, "min"),
- maxDate = this._getMinMaxDate(inst, "max"),
- drawMonth = inst.drawMonth - showCurrentAtPos,
- drawYear = inst.drawYear;
-
- if (drawMonth < 0) {
- drawMonth += 12;
- drawYear--;
- }
- if (maxDate) {
- maxDraw = this._daylightSavingAdjust(new Date(maxDate.getFullYear(),
- maxDate.getMonth() - (numMonths[0] * numMonths[1]) + 1, maxDate.getDate()));
- maxDraw = (minDate && maxDraw < minDate ? minDate : maxDraw);
- while (this._daylightSavingAdjust(new Date(drawYear, drawMonth, 1)) > maxDraw) {
- drawMonth--;
- if (drawMonth < 0) {
- drawMonth = 11;
- drawYear--;
- }
- }
- }
- inst.drawMonth = drawMonth;
- inst.drawYear = drawYear;
-
- prevText = this._get(inst, "prevText");
- prevText = (!navigationAsDateFormat ? prevText : this.formatDate(prevText,
- this._daylightSavingAdjust(new Date(drawYear, drawMonth - stepMonths, 1)),
- this._getFormatConfig(inst)));
-
- prev = (this._canAdjustMonth(inst, -1, drawYear, drawMonth) ?
- "<a class='ui-datepicker-prev ui-corner-all' data-handler='prev' data-event='click'" +
- " title='" + prevText + "'><span class='ui-icon ui-icon-circle-triangle-" + ( isRTL ? "e" : "w") + "'>" + prevText + "</span></a>" :
- (hideIfNoPrevNext ? "" : "<a class='ui-datepicker-prev ui-corner-all ui-state-disabled' title='"+ prevText +"'><span class='ui-icon ui-icon-circle-triangle-" + ( isRTL ? "e" : "w") + "'>" + prevText + "</span></a>"));
-
- nextText = this._get(inst, "nextText");
- nextText = (!navigationAsDateFormat ? nextText : this.formatDate(nextText,
- this._daylightSavingAdjust(new Date(drawYear, drawMonth + stepMonths, 1)),
- this._getFormatConfig(inst)));
-
- next = (this._canAdjustMonth(inst, +1, drawYear, drawMonth) ?
- "<a class='ui-datepicker-next ui-corner-all' data-handler='next' data-event='click'" +
- " title='" + nextText + "'><span class='ui-icon ui-icon-circle-triangle-" + ( isRTL ? "w" : "e") + "'>" + nextText + "</span></a>" :
- (hideIfNoPrevNext ? "" : "<a class='ui-datepicker-next ui-corner-all ui-state-disabled' title='"+ nextText + "'><span class='ui-icon ui-icon-circle-triangle-" + ( isRTL ? "w" : "e") + "'>" + nextText + "</span></a>"));
-
- currentText = this._get(inst, "currentText");
- gotoDate = (this._get(inst, "gotoCurrent") && inst.currentDay ? currentDate : today);
- currentText = (!navigationAsDateFormat ? currentText :
- this.formatDate(currentText, gotoDate, this._getFormatConfig(inst)));
-
- controls = (!inst.inline ? "<button type='button' class='ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all' data-handler='hide' data-event='click'>" +
- this._get(inst, "closeText") + "</button>" : "");
-
- buttonPanel = (showButtonPanel) ? "<div class='ui-datepicker-buttonpane ui-widget-content'>" + (isRTL ? controls : "") +
- (this._isInRange(inst, gotoDate) ? "<button type='button' class='ui-datepicker-current ui-state-default ui-priority-secondary ui-corner-all' data-handler='today' data-event='click'" +
- ">" + currentText + "</button>" : "") + (isRTL ? "" : controls) + "</div>" : "";
-
- firstDay = parseInt(this._get(inst, "firstDay"),10);
- firstDay = (isNaN(firstDay) ? 0 : firstDay);
-
- showWeek = this._get(inst, "showWeek");
- dayNames = this._get(inst, "dayNames");
- dayNamesMin = this._get(inst, "dayNamesMin");
- monthNames = this._get(inst, "monthNames");
- monthNamesShort = this._get(inst, "monthNamesShort");
- beforeShowDay = this._get(inst, "beforeShowDay");
- showOtherMonths = this._get(inst, "showOtherMonths");
- selectOtherMonths = this._get(inst, "selectOtherMonths");
- defaultDate = this._getDefaultDate(inst);
- html = "";
- dow;
- for (row = 0; row < numMonths[0]; row++) {
- group = "";
- this.maxRows = 4;
- for (col = 0; col < numMonths[1]; col++) {
- selectedDate = this._daylightSavingAdjust(new Date(drawYear, drawMonth, inst.selectedDay));
- cornerClass = " ui-corner-all";
- calender = "";
- if (isMultiMonth) {
- calender += "<div class='ui-datepicker-group";
- if (numMonths[1] > 1) {
- switch (col) {
- case 0: calender += " ui-datepicker-group-first";
- cornerClass = " ui-corner-" + (isRTL ? "right" : "left"); break;
- case numMonths[1]-1: calender += " ui-datepicker-group-last";
- cornerClass = " ui-corner-" + (isRTL ? "left" : "right"); break;
- default: calender += " ui-datepicker-group-middle"; cornerClass = ""; break;
- }
- }
- calender += "'>";
- }
- calender += "<div class='ui-datepicker-header ui-widget-header ui-helper-clearfix" + cornerClass + "'>" +
- (/all|left/.test(cornerClass) && row === 0 ? (isRTL ? next : prev) : "") +
- (/all|right/.test(cornerClass) && row === 0 ? (isRTL ? prev : next) : "") +
- this._generateMonthYearHeader(inst, drawMonth, drawYear, minDate, maxDate,
- row > 0 || col > 0, monthNames, monthNamesShort) + // draw month headers
- "</div><table class='ui-datepicker-calendar'><thead>" +
- "<tr>";
- thead = (showWeek ? "<th class='ui-datepicker-week-col'>" + this._get(inst, "weekHeader") + "</th>" : "");
- for (dow = 0; dow < 7; dow++) { // days of the week
- day = (dow + firstDay) % 7;
- thead += "<th" + ((dow + firstDay + 6) % 7 >= 5 ? " class='ui-datepicker-week-end'" : "") + ">" +
- "<span title='" + dayNames[day] + "'>" + dayNamesMin[day] + "</span></th>";
- }
- calender += thead + "</tr></thead><tbody>";
- daysInMonth = this._getDaysInMonth(drawYear, drawMonth);
- if (drawYear === inst.selectedYear && drawMonth === inst.selectedMonth) {
- inst.selectedDay = Math.min(inst.selectedDay, daysInMonth);
- }
- leadDays = (this._getFirstDayOfMonth(drawYear, drawMonth) - firstDay + 7) % 7;
- curRows = Math.ceil((leadDays + daysInMonth) / 7); // calculate the number of rows to generate
- numRows = (isMultiMonth ? this.maxRows > curRows ? this.maxRows : curRows : curRows); //If multiple months, use the higher number of rows (see #7043)
- this.maxRows = numRows;
- printDate = this._daylightSavingAdjust(new Date(drawYear, drawMonth, 1 - leadDays));
- for (dRow = 0; dRow < numRows; dRow++) { // create date picker rows
- calender += "<tr>";
- tbody = (!showWeek ? "" : "<td class='ui-datepicker-week-col'>" +
- this._get(inst, "calculateWeek")(printDate) + "</td>");
- for (dow = 0; dow < 7; dow++) { // create date picker days
- daySettings = (beforeShowDay ?
- beforeShowDay.apply((inst.input ? inst.input[0] : null), [printDate]) : [true, ""]);
- otherMonth = (printDate.getMonth() !== drawMonth);
- unselectable = (otherMonth && !selectOtherMonths) || !daySettings[0] ||
- (minDate && printDate < minDate) || (maxDate && printDate > maxDate);
- tbody += "<td class='" +
- ((dow + firstDay + 6) % 7 >= 5 ? " ui-datepicker-week-end" : "") + // highlight weekends
- (otherMonth ? " ui-datepicker-other-month" : "") + // highlight days from other months
- ((printDate.getTime() === selectedDate.getTime() && drawMonth === inst.selectedMonth && inst._keyEvent) || // user pressed key
- (defaultDate.getTime() === printDate.getTime() && defaultDate.getTime() === selectedDate.getTime()) ?
- // or defaultDate is current printedDate and defaultDate is selectedDate
- " " + this._dayOverClass : "") + // highlight selected day
- (unselectable ? " " + this._unselectableClass + " ui-state-disabled": "") + // highlight unselectable days
- (otherMonth && !showOtherMonths ? "" : " " + daySettings[1] + // highlight custom dates
- (printDate.getTime() === currentDate.getTime() ? " " + this._currentClass : "") + // highlight selected day
- (printDate.getTime() === today.getTime() ? " ui-datepicker-today" : "")) + "'" + // highlight today (if different)
- ((!otherMonth || showOtherMonths) && daySettings[2] ? " title='" + daySettings[2].replace(/'/g, "'") + "'" : "") + // cell title
- (unselectable ? "" : " data-handler='selectDay' data-event='click' data-month='" + printDate.getMonth() + "' data-year='" + printDate.getFullYear() + "'") + ">" + // actions
- (otherMonth && !showOtherMonths ? " " : // display for other months
- (unselectable ? "<span class='ui-state-default'>" + printDate.getDate() + "</span>" : "<a class='ui-state-default" +
- (printDate.getTime() === today.getTime() ? " ui-state-highlight" : "") +
- (printDate.getTime() === currentDate.getTime() ? " ui-state-active" : "") + // highlight selected day
- (otherMonth ? " ui-priority-secondary" : "") + // distinguish dates from other months
- "' href='#'>" + printDate.getDate() + "</a>")) + "</td>"; // display selectable date
- printDate.setDate(printDate.getDate() + 1);
- printDate = this._daylightSavingAdjust(printDate);
- }
- calender += tbody + "</tr>";
- }
- drawMonth++;
- if (drawMonth > 11) {
- drawMonth = 0;
- drawYear++;
- }
- calender += "</tbody></table>" + (isMultiMonth ? "</div>" +
- ((numMonths[0] > 0 && col === numMonths[1]-1) ? "<div class='ui-datepicker-row-break'></div>" : "") : "");
- group += calender;
- }
- html += group;
- }
- html += buttonPanel;
- inst._keyEvent = false;
- return html;
- },
-
- /* Generate the month and year header. */
- _generateMonthYearHeader: function(inst, drawMonth, drawYear, minDate, maxDate,
- secondary, monthNames, monthNamesShort) {
-
- var inMinYear, inMaxYear, month, years, thisYear, determineYear, year, endYear,
- changeMonth = this._get(inst, "changeMonth"),
- changeYear = this._get(inst, "changeYear"),
- showMonthAfterYear = this._get(inst, "showMonthAfterYear"),
- html = "<div class='ui-datepicker-title'>",
- monthHtml = "";
-
- // month selection
- if (secondary || !changeMonth) {
- monthHtml += "<span class='ui-datepicker-month'>" + monthNames[drawMonth] + "</span>";
- } else {
- inMinYear = (minDate && minDate.getFullYear() === drawYear);
- inMaxYear = (maxDate && maxDate.getFullYear() === drawYear);
- monthHtml += "<select class='ui-datepicker-month' data-handler='selectMonth' data-event='change'>";
- for ( month = 0; month < 12; month++) {
- if ((!inMinYear || month >= minDate.getMonth()) && (!inMaxYear || month <= maxDate.getMonth())) {
- monthHtml += "<option value='" + month + "'" +
- (month === drawMonth ? " selected='selected'" : "") +
- ">" + monthNamesShort[month] + "</option>";
- }
- }
- monthHtml += "</select>";
- }
-
- if (!showMonthAfterYear) {
- html += monthHtml + (secondary || !(changeMonth && changeYear) ? " " : "");
- }
-
- // year selection
- if ( !inst.yearshtml ) {
- inst.yearshtml = "";
- if (secondary || !changeYear) {
- html += "<span class='ui-datepicker-year'>" + drawYear + "</span>";
- } else {
- // determine range of years to display
- years = this._get(inst, "yearRange").split(":");
- thisYear = new Date().getFullYear();
- determineYear = function(value) {
- var year = (value.match(/c[+\-].*/) ? drawYear + parseInt(value.substring(1), 10) :
- (value.match(/[+\-].*/) ? thisYear + parseInt(value, 10) :
- parseInt(value, 10)));
- return (isNaN(year) ? thisYear : year);
- };
- year = determineYear(years[0]);
- endYear = Math.max(year, determineYear(years[1] || ""));
- year = (minDate ? Math.max(year, minDate.getFullYear()) : year);
- endYear = (maxDate ? Math.min(endYear, maxDate.getFullYear()) : endYear);
- inst.yearshtml += "<select class='ui-datepicker-year' data-handler='selectYear' data-event='change'>";
- for (; year <= endYear; year++) {
- inst.yearshtml += "<option value='" + year + "'" +
- (year === drawYear ? " selected='selected'" : "") +
- ">" + year + "</option>";
- }
- inst.yearshtml += "</select>";
-
- html += inst.yearshtml;
- inst.yearshtml = null;
- }
- }
-
- html += this._get(inst, "yearSuffix");
- if (showMonthAfterYear) {
- html += (secondary || !(changeMonth && changeYear) ? " " : "") + monthHtml;
- }
- html += "</div>"; // Close datepicker_header
- return html;
- },
-
- /* Adjust one of the date sub-fields. */
- _adjustInstDate: function(inst, offset, period) {
- var year = inst.drawYear + (period === "Y" ? offset : 0),
- month = inst.drawMonth + (period === "M" ? offset : 0),
- day = Math.min(inst.selectedDay, this._getDaysInMonth(year, month)) + (period === "D" ? offset : 0),
- date = this._restrictMinMax(inst, this._daylightSavingAdjust(new Date(year, month, day)));
-
- inst.selectedDay = date.getDate();
- inst.drawMonth = inst.selectedMonth = date.getMonth();
- inst.drawYear = inst.selectedYear = date.getFullYear();
- if (period === "M" || period === "Y") {
- this._notifyChange(inst);
- }
- },
-
- /* Ensure a date is within any min/max bounds. */
- _restrictMinMax: function(inst, date) {
- var minDate = this._getMinMaxDate(inst, "min"),
- maxDate = this._getMinMaxDate(inst, "max"),
- newDate = (minDate && date < minDate ? minDate : date);
- return (maxDate && newDate > maxDate ? maxDate : newDate);
- },
-
- /* Notify change of month/year. */
- _notifyChange: function(inst) {
- var onChange = this._get(inst, "onChangeMonthYear");
- if (onChange) {
- onChange.apply((inst.input ? inst.input[0] : null),
- [inst.selectedYear, inst.selectedMonth + 1, inst]);
- }
- },
-
- /* Determine the number of months to show. */
- _getNumberOfMonths: function(inst) {
- var numMonths = this._get(inst, "numberOfMonths");
- return (numMonths == null ? [1, 1] : (typeof numMonths === "number" ? [1, numMonths] : numMonths));
- },
-
- /* Determine the current maximum date - ensure no time components are set. */
- _getMinMaxDate: function(inst, minMax) {
- return this._determineDate(inst, this._get(inst, minMax + "Date"), null);
- },
-
- /* Find the number of days in a given month. */
- _getDaysInMonth: function(year, month) {
- return 32 - this._daylightSavingAdjust(new Date(year, month, 32)).getDate();
- },
-
- /* Find the day of the week of the first of a month. */
- _getFirstDayOfMonth: function(year, month) {
- return new Date(year, month, 1).getDay();
- },
-
- /* Determines if we should allow a "next/prev" month display change. */
- _canAdjustMonth: function(inst, offset, curYear, curMonth) {
- var numMonths = this._getNumberOfMonths(inst),
- date = this._daylightSavingAdjust(new Date(curYear,
- curMonth + (offset < 0 ? offset : numMonths[0] * numMonths[1]), 1));
-
- if (offset < 0) {
- date.setDate(this._getDaysInMonth(date.getFullYear(), date.getMonth()));
- }
- return this._isInRange(inst, date);
- },
-
- /* Is the given date in the accepted range? */
- _isInRange: function(inst, date) {
- var yearSplit, currentYear,
- minDate = this._getMinMaxDate(inst, "min"),
- maxDate = this._getMinMaxDate(inst, "max"),
- minYear = null,
- maxYear = null,
- years = this._get(inst, "yearRange");
- if (years){
- yearSplit = years.split(":");
- currentYear = new Date().getFullYear();
- minYear = parseInt(yearSplit[0], 10);
- maxYear = parseInt(yearSplit[1], 10);
- if ( yearSplit[0].match(/[+\-].*/) ) {
- minYear += currentYear;
- }
- if ( yearSplit[1].match(/[+\-].*/) ) {
- maxYear += currentYear;
- }
- }
-
- return ((!minDate || date.getTime() >= minDate.getTime()) &&
- (!maxDate || date.getTime() <= maxDate.getTime()) &&
- (!minYear || date.getFullYear() >= minYear) &&
- (!maxYear || date.getFullYear() <= maxYear));
- },
-
- /* Provide the configuration settings for formatting/parsing. */
- _getFormatConfig: function(inst) {
- var shortYearCutoff = this._get(inst, "shortYearCutoff");
- shortYearCutoff = (typeof shortYearCutoff !== "string" ? shortYearCutoff :
- new Date().getFullYear() % 100 + parseInt(shortYearCutoff, 10));
- return {shortYearCutoff: shortYearCutoff,
- dayNamesShort: this._get(inst, "dayNamesShort"), dayNames: this._get(inst, "dayNames"),
- monthNamesShort: this._get(inst, "monthNamesShort"), monthNames: this._get(inst, "monthNames")};
- },
-
- /* Format the given date for display. */
- _formatDate: function(inst, day, month, year) {
- if (!day) {
- inst.currentDay = inst.selectedDay;
- inst.currentMonth = inst.selectedMonth;
- inst.currentYear = inst.selectedYear;
- }
- var date = (day ? (typeof day === "object" ? day :
- this._daylightSavingAdjust(new Date(year, month, day))) :
- this._daylightSavingAdjust(new Date(inst.currentYear, inst.currentMonth, inst.currentDay)));
- return this.formatDate(this._get(inst, "dateFormat"), date, this._getFormatConfig(inst));
- }
-});
-
-/*
- * Bind hover events for datepicker elements.
- * Done via delegate so the binding only occurs once in the lifetime of the parent div.
- * Global instActive, set by _updateDatepicker allows the handlers to find their way back to the active picker.
- */
-function bindHover(dpDiv) {
- var selector = "button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a";
- return dpDiv.delegate(selector, "mouseout", function() {
- $(this).removeClass("ui-state-hover");
- if (this.className.indexOf("ui-datepicker-prev") !== -1) {
- $(this).removeClass("ui-datepicker-prev-hover");
- }
- if (this.className.indexOf("ui-datepicker-next") !== -1) {
- $(this).removeClass("ui-datepicker-next-hover");
- }
- })
- .delegate(selector, "mouseover", function(){
- if (!$.datepicker._isDisabledDatepicker( instActive.inline ? dpDiv.parent()[0] : instActive.input[0])) {
- $(this).parents(".ui-datepicker-calendar").find("a").removeClass("ui-state-hover");
- $(this).addClass("ui-state-hover");
- if (this.className.indexOf("ui-datepicker-prev") !== -1) {
- $(this).addClass("ui-datepicker-prev-hover");
- }
- if (this.className.indexOf("ui-datepicker-next") !== -1) {
- $(this).addClass("ui-datepicker-next-hover");
- }
- }
- });
-}
-
-/* jQuery extend now ignores nulls! */
-function extendRemove(target, props) {
- $.extend(target, props);
- for (var name in props) {
- if (props[name] == null) {
- target[name] = props[name];
- }
- }
- return target;
-}
-
-/* Invoke the datepicker functionality.
- @param options string - a command, optionally followed by additional parameters or
- Object - settings for attaching new datepicker functionality
- @return jQuery object */
-$.fn.datepicker = function(options){
-
- /* Verify an empty collection wasn't passed - Fixes #6976 */
- if ( !this.length ) {
- return this;
- }
-
- /* Initialise the date picker. */
- if (!$.datepicker.initialized) {
- $(document).mousedown($.datepicker._checkExternalClick);
- $.datepicker.initialized = true;
- }
-
- /* Append datepicker main container to body if not exist. */
- if ($("#"+$.datepicker._mainDivId).length === 0) {
- $("body").append($.datepicker.dpDiv);
- }
-
- var otherArgs = Array.prototype.slice.call(arguments, 1);
- if (typeof options === "string" && (options === "isDisabled" || options === "getDate" || options === "widget")) {
- return $.datepicker["_" + options + "Datepicker"].
- apply($.datepicker, [this[0]].concat(otherArgs));
- }
- if (options === "option" && arguments.length === 2 && typeof arguments[1] === "string") {
- return $.datepicker["_" + options + "Datepicker"].
- apply($.datepicker, [this[0]].concat(otherArgs));
- }
- return this.each(function() {
- typeof options === "string" ?
- $.datepicker["_" + options + "Datepicker"].
- apply($.datepicker, [this].concat(otherArgs)) :
- $.datepicker._attachDatepicker(this, options);
- });
-};
-
-$.datepicker = new Datepicker(); // singleton instance
-$.datepicker.initialized = false;
-$.datepicker.uuid = new Date().getTime();
-$.datepicker.version = "1.10.4";
-
-})(jQuery);
-(function( $, undefined ) {
-
-var sizeRelatedOptions = {
- buttons: true,
- height: true,
- maxHeight: true,
- maxWidth: true,
- minHeight: true,
- minWidth: true,
- width: true
- },
- resizableRelatedOptions = {
- maxHeight: true,
- maxWidth: true,
- minHeight: true,
- minWidth: true
- };
-
-$.widget( "ui.dialog", {
- version: "1.10.4",
- options: {
- appendTo: "body",
- autoOpen: true,
- buttons: [],
- closeOnEscape: true,
- closeText: "close",
- dialogClass: "",
- draggable: true,
- hide: null,
- height: "auto",
- maxHeight: null,
- maxWidth: null,
- minHeight: 150,
- minWidth: 150,
- modal: false,
- position: {
- my: "center",
- at: "center",
- of: window,
- collision: "fit",
- // Ensure the titlebar is always visible
- using: function( pos ) {
- var topOffset = $( this ).css( pos ).offset().top;
- if ( topOffset < 0 ) {
- $( this ).css( "top", pos.top - topOffset );
- }
- }
- },
- resizable: true,
- show: null,
- title: null,
- width: 300,
-
- // callbacks
- beforeClose: null,
- close: null,
- drag: null,
- dragStart: null,
- dragStop: null,
- focus: null,
- open: null,
- resize: null,
- resizeStart: null,
- resizeStop: null
- },
-
- _create: function() {
- this.originalCss = {
- display: this.element[0].style.display,
- width: this.element[0].style.width,
- minHeight: this.element[0].style.minHeight,
- maxHeight: this.element[0].style.maxHeight,
- height: this.element[0].style.height
- };
- this.originalPosition = {
- parent: this.element.parent(),
- index: this.element.parent().children().index( this.element )
- };
- this.originalTitle = this.element.attr("title");
- this.options.title = this.options.title || this.originalTitle;
-
- this._createWrapper();
-
- this.element
- .show()
- .removeAttr("title")
- .addClass("ui-dialog-content ui-widget-content")
- .appendTo( this.uiDialog );
-
- this._createTitlebar();
- this._createButtonPane();
-
- if ( this.options.draggable && $.fn.draggable ) {
- this._makeDraggable();
- }
- if ( this.options.resizable && $.fn.resizable ) {
- this._makeResizable();
- }
-
- this._isOpen = false;
- },
-
- _init: function() {
- if ( this.options.autoOpen ) {
- this.open();
- }
- },
-
- _appendTo: function() {
- var element = this.options.appendTo;
- if ( element && (element.jquery || element.nodeType) ) {
- return $( element );
- }
- return this.document.find( element || "body" ).eq( 0 );
- },
-
- _destroy: function() {
- var next,
- originalPosition = this.originalPosition;
-
- this._destroyOverlay();
-
- this.element
- .removeUniqueId()
- .removeClass("ui-dialog-content ui-widget-content")
- .css( this.originalCss )
- // Without detaching first, the following becomes really slow
- .detach();
-
- this.uiDialog.stop( true, true ).remove();
-
- if ( this.originalTitle ) {
- this.element.attr( "title", this.originalTitle );
- }
-
- next = originalPosition.parent.children().eq( originalPosition.index );
- // Don't try to place the dialog next to itself (#8613)
- if ( next.length && next[0] !== this.element[0] ) {
- next.before( this.element );
- } else {
- originalPosition.parent.append( this.element );
- }
- },
-
- widget: function() {
- return this.uiDialog;
- },
-
- disable: $.noop,
- enable: $.noop,
-
- close: function( event ) {
- var activeElement,
- that = this;
-
- if ( !this._isOpen || this._trigger( "beforeClose", event ) === false ) {
- return;
- }
-
- this._isOpen = false;
- this._destroyOverlay();
-
- if ( !this.opener.filter(":focusable").focus().length ) {
-
- // support: IE9
- // IE9 throws an "Unspecified error" accessing document.activeElement from an <iframe>
- try {
- activeElement = this.document[ 0 ].activeElement;
-
- // Support: IE9, IE10
- // If the <body> is blurred, IE will switch windows, see #4520
- if ( activeElement && activeElement.nodeName.toLowerCase() !== "body" ) {
-
- // Hiding a focused element doesn't trigger blur in WebKit
- // so in case we have nothing to focus on, explicitly blur the active element
- // https://bugs.webkit.org/show_bug.cgi?id=47182
- $( activeElement ).blur();
- }
- } catch ( error ) {}
- }
-
- this._hide( this.uiDialog, this.options.hide, function() {
- that._trigger( "close", event );
- });
- },
-
- isOpen: function() {
- return this._isOpen;
- },
-
- moveToTop: function() {
- this._moveToTop();
- },
-
- _moveToTop: function( event, silent ) {
- var moved = !!this.uiDialog.nextAll(":visible").insertBefore( this.uiDialog ).length;
- if ( moved && !silent ) {
- this._trigger( "focus", event );
- }
- return moved;
- },
-
- open: function() {
- var that = this;
- if ( this._isOpen ) {
- if ( this._moveToTop() ) {
- this._focusTabbable();
- }
- return;
- }
-
- this._isOpen = true;
- this.opener = $( this.document[0].activeElement );
-
- this._size();
- this._position();
- this._createOverlay();
- this._moveToTop( null, true );
- this._show( this.uiDialog, this.options.show, function() {
- that._focusTabbable();
- that._trigger("focus");
- });
-
- this._trigger("open");
- },
-
- _focusTabbable: function() {
- // Set focus to the first match:
- // 1. First element inside the dialog matching [autofocus]
- // 2. Tabbable element inside the content element
- // 3. Tabbable element inside the buttonpane
- // 4. The close button
- // 5. The dialog itself
- var hasFocus = this.element.find("[autofocus]");
- if ( !hasFocus.length ) {
- hasFocus = this.element.find(":tabbable");
- }
- if ( !hasFocus.length ) {
- hasFocus = this.uiDialogButtonPane.find(":tabbable");
- }
- if ( !hasFocus.length ) {
- hasFocus = this.uiDialogTitlebarClose.filter(":tabbable");
- }
- if ( !hasFocus.length ) {
- hasFocus = this.uiDialog;
- }
- hasFocus.eq( 0 ).focus();
- },
-
- _keepFocus: function( event ) {
- function checkFocus() {
- var activeElement = this.document[0].activeElement,
- isActive = this.uiDialog[0] === activeElement ||
- $.contains( this.uiDialog[0], activeElement );
- if ( !isActive ) {
- this._focusTabbable();
- }
- }
- event.preventDefault();
- checkFocus.call( this );
- // support: IE
- // IE <= 8 doesn't prevent moving focus even with event.preventDefault()
- // so we check again later
- this._delay( checkFocus );
- },
-
- _createWrapper: function() {
- this.uiDialog = $("<div>")
- .addClass( "ui-dialog ui-widget ui-widget-content ui-corner-all ui-front " +
- this.options.dialogClass )
- .hide()
- .attr({
- // Setting tabIndex makes the div focusable
- tabIndex: -1,
- role: "dialog"
- })
- .appendTo( this._appendTo() );
-
- this._on( this.uiDialog, {
- keydown: function( event ) {
- if ( this.options.closeOnEscape && !event.isDefaultPrevented() && event.keyCode &&
- event.keyCode === $.ui.keyCode.ESCAPE ) {
- event.preventDefault();
- this.close( event );
- return;
- }
-
- // prevent tabbing out of dialogs
- if ( event.keyCode !== $.ui.keyCode.TAB ) {
- return;
- }
- var tabbables = this.uiDialog.find(":tabbable"),
- first = tabbables.filter(":first"),
- last = tabbables.filter(":last");
-
- if ( ( event.target === last[0] || event.target === this.uiDialog[0] ) && !event.shiftKey ) {
- first.focus( 1 );
- event.preventDefault();
- } else if ( ( event.target === first[0] || event.target === this.uiDialog[0] ) && event.shiftKey ) {
- last.focus( 1 );
- event.preventDefault();
- }
- },
- mousedown: function( event ) {
- if ( this._moveToTop( event ) ) {
- this._focusTabbable();
- }
- }
- });
-
- // We assume that any existing aria-describedby attribute means
- // that the dialog content is marked up properly
- // otherwise we brute force the content as the description
- if ( !this.element.find("[aria-describedby]").length ) {
- this.uiDialog.attr({
- "aria-describedby": this.element.uniqueId().attr("id")
- });
- }
- },
-
- _createTitlebar: function() {
- var uiDialogTitle;
-
- this.uiDialogTitlebar = $("<div>")
- .addClass("ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix")
- .prependTo( this.uiDialog );
- this._on( this.uiDialogTitlebar, {
- mousedown: function( event ) {
- // Don't prevent click on close button (#8838)
- // Focusing a dialog that is partially scrolled out of view
- // causes the browser to scroll it into view, preventing the click event
- if ( !$( event.target ).closest(".ui-dialog-titlebar-close") ) {
- // Dialog isn't getting focus when dragging (#8063)
- this.uiDialog.focus();
- }
- }
- });
-
- // support: IE
- // Use type="button" to prevent enter keypresses in textboxes from closing the
- // dialog in IE (#9312)
- this.uiDialogTitlebarClose = $( "<button type='button'></button>" )
- .button({
- label: this.options.closeText,
- icons: {
- primary: "ui-icon-closethick"
- },
- text: false
- })
- .addClass("ui-dialog-titlebar-close")
- .appendTo( this.uiDialogTitlebar );
- this._on( this.uiDialogTitlebarClose, {
- click: function( event ) {
- event.preventDefault();
- this.close( event );
- }
- });
-
- uiDialogTitle = $("<span>")
- .uniqueId()
- .addClass("ui-dialog-title")
- .prependTo( this.uiDialogTitlebar );
- this._title( uiDialogTitle );
-
- this.uiDialog.attr({
- "aria-labelledby": uiDialogTitle.attr("id")
- });
- },
-
- _title: function( title ) {
- if ( !this.options.title ) {
- title.html(" ");
- }
- title.text( this.options.title );
- },
-
- _createButtonPane: function() {
- this.uiDialogButtonPane = $("<div>")
- .addClass("ui-dialog-buttonpane ui-widget-content ui-helper-clearfix");
-
- this.uiButtonSet = $("<div>")
- .addClass("ui-dialog-buttonset")
- .appendTo( this.uiDialogButtonPane );
-
- this._createButtons();
- },
-
- _createButtons: function() {
- var that = this,
- buttons = this.options.buttons;
-
- // if we already have a button pane, remove it
- this.uiDialogButtonPane.remove();
- this.uiButtonSet.empty();
-
- if ( $.isEmptyObject( buttons ) || ($.isArray( buttons ) && !buttons.length) ) {
- this.uiDialog.removeClass("ui-dialog-buttons");
- return;
- }
-
- $.each( buttons, function( name, props ) {
- var click, buttonOptions;
- props = $.isFunction( props ) ?
- { click: props, text: name } :
- props;
- // Default to a non-submitting button
- props = $.extend( { type: "button" }, props );
- // Change the context for the click callback to be the main element
- click = props.click;
- props.click = function() {
- click.apply( that.element[0], arguments );
- };
- buttonOptions = {
- icons: props.icons,
- text: props.showText
- };
- delete props.icons;
- delete props.showText;
- $( "<button></button>", props )
- .button( buttonOptions )
- .appendTo( that.uiButtonSet );
- });
- this.uiDialog.addClass("ui-dialog-buttons");
- this.uiDialogButtonPane.appendTo( this.uiDialog );
- },
-
- _makeDraggable: function() {
- var that = this,
- options = this.options;
-
- function filteredUi( ui ) {
- return {
- position: ui.position,
- offset: ui.offset
- };
- }
-
- this.uiDialog.draggable({
- cancel: ".ui-dialog-content, .ui-dialog-titlebar-close",
- handle: ".ui-dialog-titlebar",
- containment: "document",
- start: function( event, ui ) {
- $( this ).addClass("ui-dialog-dragging");
- that._blockFrames();
- that._trigger( "dragStart", event, filteredUi( ui ) );
- },
- drag: function( event, ui ) {
- that._trigger( "drag", event, filteredUi( ui ) );
- },
- stop: function( event, ui ) {
- options.position = [
- ui.position.left - that.document.scrollLeft(),
- ui.position.top - that.document.scrollTop()
- ];
- $( this ).removeClass("ui-dialog-dragging");
- that._unblockFrames();
- that._trigger( "dragStop", event, filteredUi( ui ) );
- }
- });
- },
-
- _makeResizable: function() {
- var that = this,
- options = this.options,
- handles = options.resizable,
- // .ui-resizable has position: relative defined in the stylesheet
- // but dialogs have to use absolute or fixed positioning
- position = this.uiDialog.css("position"),
- resizeHandles = typeof handles === "string" ?
- handles :
- "n,e,s,w,se,sw,ne,nw";
-
- function filteredUi( ui ) {
- return {
- originalPosition: ui.originalPosition,
- originalSize: ui.originalSize,
- position: ui.position,
- size: ui.size
- };
- }
-
- this.uiDialog.resizable({
- cancel: ".ui-dialog-content",
- containment: "document",
- alsoResize: this.element,
- maxWidth: options.maxWidth,
- maxHeight: options.maxHeight,
- minWidth: options.minWidth,
- minHeight: this._minHeight(),
- handles: resizeHandles,
- start: function( event, ui ) {
- $( this ).addClass("ui-dialog-resizing");
- that._blockFrames();
- that._trigger( "resizeStart", event, filteredUi( ui ) );
- },
- resize: function( event, ui ) {
- that._trigger( "resize", event, filteredUi( ui ) );
- },
- stop: function( event, ui ) {
- options.height = $( this ).height();
- options.width = $( this ).width();
- $( this ).removeClass("ui-dialog-resizing");
- that._unblockFrames();
- that._trigger( "resizeStop", event, filteredUi( ui ) );
- }
- })
- .css( "position", position );
- },
-
- _minHeight: function() {
- var options = this.options;
-
- return options.height === "auto" ?
- options.minHeight :
- Math.min( options.minHeight, options.height );
- },
-
- _position: function() {
- // Need to show the dialog to get the actual offset in the position plugin
- var isVisible = this.uiDialog.is(":visible");
- if ( !isVisible ) {
- this.uiDialog.show();
- }
- this.uiDialog.position( this.options.position );
- if ( !isVisible ) {
- this.uiDialog.hide();
- }
- },
-
- _setOptions: function( options ) {
- var that = this,
- resize = false,
- resizableOptions = {};
-
- $.each( options, function( key, value ) {
- that._setOption( key, value );
-
- if ( key in sizeRelatedOptions ) {
- resize = true;
- }
- if ( key in resizableRelatedOptions ) {
- resizableOptions[ key ] = value;
- }
- });
-
- if ( resize ) {
- this._size();
- this._position();
- }
- if ( this.uiDialog.is(":data(ui-resizable)") ) {
- this.uiDialog.resizable( "option", resizableOptions );
- }
- },
-
- _setOption: function( key, value ) {
- var isDraggable, isResizable,
- uiDialog = this.uiDialog;
-
- if ( key === "dialogClass" ) {
- uiDialog
- .removeClass( this.options.dialogClass )
- .addClass( value );
- }
-
- if ( key === "disabled" ) {
- return;
- }
-
- this._super( key, value );
-
- if ( key === "appendTo" ) {
- this.uiDialog.appendTo( this._appendTo() );
- }
-
- if ( key === "buttons" ) {
- this._createButtons();
- }
-
- if ( key === "closeText" ) {
- this.uiDialogTitlebarClose.button({
- // Ensure that we always pass a string
- label: "" + value
- });
- }
-
- if ( key === "draggable" ) {
- isDraggable = uiDialog.is(":data(ui-draggable)");
- if ( isDraggable && !value ) {
- uiDialog.draggable("destroy");
- }
-
- if ( !isDraggable && value ) {
- this._makeDraggable();
- }
- }
-
- if ( key === "position" ) {
- this._position();
- }
-
- if ( key === "resizable" ) {
- // currently resizable, becoming non-resizable
- isResizable = uiDialog.is(":data(ui-resizable)");
- if ( isResizable && !value ) {
- uiDialog.resizable("destroy");
- }
-
- // currently resizable, changing handles
- if ( isResizable && typeof value === "string" ) {
- uiDialog.resizable( "option", "handles", value );
- }
-
- // currently non-resizable, becoming resizable
- if ( !isResizable && value !== false ) {
- this._makeResizable();
- }
- }
-
- if ( key === "title" ) {
- this._title( this.uiDialogTitlebar.find(".ui-dialog-title") );
- }
- },
-
- _size: function() {
- // If the user has resized the dialog, the .ui-dialog and .ui-dialog-content
- // divs will both have width and height set, so we need to reset them
- var nonContentHeight, minContentHeight, maxContentHeight,
- options = this.options;
-
- // Reset content sizing
- this.element.show().css({
- width: "auto",
- minHeight: 0,
- maxHeight: "none",
- height: 0
- });
-
- if ( options.minWidth > options.width ) {
- options.width = options.minWidth;
- }
-
- // reset wrapper sizing
- // determine the height of all the non-content elements
- nonContentHeight = this.uiDialog.css({
- height: "auto",
- width: options.width
- })
- .outerHeight();
- minContentHeight = Math.max( 0, options.minHeight - nonContentHeight );
- maxContentHeight = typeof options.maxHeight === "number" ?
- Math.max( 0, options.maxHeight - nonContentHeight ) :
- "none";
-
- if ( options.height === "auto" ) {
- this.element.css({
- minHeight: minContentHeight,
- maxHeight: maxContentHeight,
- height: "auto"
- });
- } else {
- this.element.height( Math.max( 0, options.height - nonContentHeight ) );
- }
-
- if (this.uiDialog.is(":data(ui-resizable)") ) {
- this.uiDialog.resizable( "option", "minHeight", this._minHeight() );
- }
- },
-
- _blockFrames: function() {
- this.iframeBlocks = this.document.find( "iframe" ).map(function() {
- var iframe = $( this );
-
- return $( "<div>" )
- .css({
- position: "absolute",
- width: iframe.outerWidth(),
- height: iframe.outerHeight()
- })
- .appendTo( iframe.parent() )
- .offset( iframe.offset() )[0];
- });
- },
-
- _unblockFrames: function() {
- if ( this.iframeBlocks ) {
- this.iframeBlocks.remove();
- delete this.iframeBlocks;
- }
- },
-
- _allowInteraction: function( event ) {
- if ( $( event.target ).closest(".ui-dialog").length ) {
- return true;
- }
-
- // TODO: Remove hack when datepicker implements
- // the .ui-front logic (#8989)
- return !!$( event.target ).closest(".ui-datepicker").length;
- },
-
- _createOverlay: function() {
- if ( !this.options.modal ) {
- return;
- }
-
- var that = this,
- widgetFullName = this.widgetFullName;
- if ( !$.ui.dialog.overlayInstances ) {
- // Prevent use of anchors and inputs.
- // We use a delay in case the overlay is created from an
- // event that we're going to be cancelling. (#2804)
- this._delay(function() {
- // Handle .dialog().dialog("close") (#4065)
- if ( $.ui.dialog.overlayInstances ) {
- this.document.bind( "focusin.dialog", function( event ) {
- if ( !that._allowInteraction( event ) ) {
- event.preventDefault();
- $(".ui-dialog:visible:last .ui-dialog-content")
- .data( widgetFullName )._focusTabbable();
- }
- });
- }
- });
- }
-
- this.overlay = $("<div>")
- .addClass("ui-widget-overlay ui-front")
- .appendTo( this._appendTo() );
- this._on( this.overlay, {
- mousedown: "_keepFocus"
- });
- $.ui.dialog.overlayInstances++;
- },
-
- _destroyOverlay: function() {
- if ( !this.options.modal ) {
- return;
- }
-
- if ( this.overlay ) {
- $.ui.dialog.overlayInstances--;
-
- if ( !$.ui.dialog.overlayInstances ) {
- this.document.unbind( "focusin.dialog" );
- }
- this.overlay.remove();
- this.overlay = null;
- }
- }
-});
-
-$.ui.dialog.overlayInstances = 0;
-
-// DEPRECATED
-if ( $.uiBackCompat !== false ) {
- // position option with array notation
- // just override with old implementation
- $.widget( "ui.dialog", $.ui.dialog, {
- _position: function() {
- var position = this.options.position,
- myAt = [],
- offset = [ 0, 0 ],
- isVisible;
-
- if ( position ) {
- if ( typeof position === "string" || (typeof position === "object" && "0" in position ) ) {
- myAt = position.split ? position.split(" ") : [ position[0], position[1] ];
- if ( myAt.length === 1 ) {
- myAt[1] = myAt[0];
- }
-
- $.each( [ "left", "top" ], function( i, offsetPosition ) {
- if ( +myAt[ i ] === myAt[ i ] ) {
- offset[ i ] = myAt[ i ];
- myAt[ i ] = offsetPosition;
- }
- });
-
- position = {
- my: myAt[0] + (offset[0] < 0 ? offset[0] : "+" + offset[0]) + " " +
- myAt[1] + (offset[1] < 0 ? offset[1] : "+" + offset[1]),
- at: myAt.join(" ")
- };
- }
-
- position = $.extend( {}, $.ui.dialog.prototype.options.position, position );
- } else {
- position = $.ui.dialog.prototype.options.position;
- }
-
- // need to show the dialog to get the actual offset in the position plugin
- isVisible = this.uiDialog.is(":visible");
- if ( !isVisible ) {
- this.uiDialog.show();
- }
- this.uiDialog.position( position );
- if ( !isVisible ) {
- this.uiDialog.hide();
- }
- }
- });
-}
-
-}( jQuery ) );
-(function( $, undefined ) {
-
-$.widget( "ui.menu", {
- version: "1.10.4",
- defaultElement: "<ul>",
- delay: 300,
- options: {
- icons: {
- submenu: "ui-icon-carat-1-e"
- },
- menus: "ul",
- position: {
- my: "left top",
- at: "right top"
- },
- role: "menu",
-
- // callbacks
- blur: null,
- focus: null,
- select: null
- },
-
- _create: function() {
- this.activeMenu = this.element;
- // flag used to prevent firing of the click handler
- // as the event bubbles up through nested menus
- this.mouseHandled = false;
- this.element
- .uniqueId()
- .addClass( "ui-menu ui-widget ui-widget-content ui-corner-all" )
- .toggleClass( "ui-menu-icons", !!this.element.find( ".ui-icon" ).length )
- .attr({
- role: this.options.role,
- tabIndex: 0
- })
- // need to catch all clicks on disabled menu
- // not possible through _on
- .bind( "click" + this.eventNamespace, $.proxy(function( event ) {
- if ( this.options.disabled ) {
- event.preventDefault();
- }
- }, this ));
-
- if ( this.options.disabled ) {
- this.element
- .addClass( "ui-state-disabled" )
- .attr( "aria-disabled", "true" );
- }
-
- this._on({
- // Prevent focus from sticking to links inside menu after clicking
- // them (focus should always stay on UL during navigation).
- "mousedown .ui-menu-item > a": function( event ) {
- event.preventDefault();
- },
- "click .ui-state-disabled > a": function( event ) {
- event.preventDefault();
- },
- "click .ui-menu-item:has(a)": function( event ) {
- var target = $( event.target ).closest( ".ui-menu-item" );
- if ( !this.mouseHandled && target.not( ".ui-state-disabled" ).length ) {
- this.select( event );
-
- // Only set the mouseHandled flag if the event will bubble, see #9469.
- if ( !event.isPropagationStopped() ) {
- this.mouseHandled = true;
- }
-
- // Open submenu on click
- if ( target.has( ".ui-menu" ).length ) {
- this.expand( event );
- } else if ( !this.element.is( ":focus" ) && $( this.document[ 0 ].activeElement ).closest( ".ui-menu" ).length ) {
-
- // Redirect focus to the menu
- this.element.trigger( "focus", [ true ] );
-
- // If the active item is on the top level, let it stay active.
- // Otherwise, blur the active item since it is no longer visible.
- if ( this.active && this.active.parents( ".ui-menu" ).length === 1 ) {
- clearTimeout( this.timer );
- }
- }
- }
- },
- "mouseenter .ui-menu-item": function( event ) {
- var target = $( event.currentTarget );
- // Remove ui-state-active class from siblings of the newly focused menu item
- // to avoid a jump caused by adjacent elements both having a class with a border
- target.siblings().children( ".ui-state-active" ).removeClass( "ui-state-active" );
- this.focus( event, target );
- },
- mouseleave: "collapseAll",
- "mouseleave .ui-menu": "collapseAll",
- focus: function( event, keepActiveItem ) {
- // If there's already an active item, keep it active
- // If not, activate the first item
- var item = this.active || this.element.children( ".ui-menu-item" ).eq( 0 );
-
- if ( !keepActiveItem ) {
- this.focus( event, item );
- }
- },
- blur: function( event ) {
- this._delay(function() {
- if ( !$.contains( this.element[0], this.document[0].activeElement ) ) {
- this.collapseAll( event );
- }
- });
- },
- keydown: "_keydown"
- });
-
- this.refresh();
-
- // Clicks outside of a menu collapse any open menus
- this._on( this.document, {
- click: function( event ) {
- if ( !$( event.target ).closest( ".ui-menu" ).length ) {
- this.collapseAll( event );
- }
-
- // Reset the mouseHandled flag
- this.mouseHandled = false;
- }
- });
- },
-
- _destroy: function() {
- // Destroy (sub)menus
- this.element
- .removeAttr( "aria-activedescendant" )
- .find( ".ui-menu" ).addBack()
- .removeClass( "ui-menu ui-widget ui-widget-content ui-corner-all ui-menu-icons" )
- .removeAttr( "role" )
- .removeAttr( "tabIndex" )
- .removeAttr( "aria-labelledby" )
- .removeAttr( "aria-expanded" )
- .removeAttr( "aria-hidden" )
- .removeAttr( "aria-disabled" )
- .removeUniqueId()
- .show();
-
- // Destroy menu items
- this.element.find( ".ui-menu-item" )
- .removeClass( "ui-menu-item" )
- .removeAttr( "role" )
- .removeAttr( "aria-disabled" )
- .children( "a" )
- .removeUniqueId()
- .removeClass( "ui-corner-all ui-state-hover" )
- .removeAttr( "tabIndex" )
- .removeAttr( "role" )
- .removeAttr( "aria-haspopup" )
- .children().each( function() {
- var elem = $( this );
- if ( elem.data( "ui-menu-submenu-carat" ) ) {
- elem.remove();
- }
- });
-
- // Destroy menu dividers
- this.element.find( ".ui-menu-divider" ).removeClass( "ui-menu-divider ui-widget-content" );
- },
-
- _keydown: function( event ) {
- var match, prev, character, skip, regex,
- preventDefault = true;
-
- function escape( value ) {
- return value.replace( /[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&" );
- }
-
- switch ( event.keyCode ) {
- case $.ui.keyCode.PAGE_UP:
- this.previousPage( event );
- break;
- case $.ui.keyCode.PAGE_DOWN:
- this.nextPage( event );
- break;
- case $.ui.keyCode.HOME:
- this._move( "first", "first", event );
- break;
- case $.ui.keyCode.END:
- this._move( "last", "last", event );
- break;
- case $.ui.keyCode.UP:
- this.previous( event );
- break;
- case $.ui.keyCode.DOWN:
- this.next( event );
- break;
- case $.ui.keyCode.LEFT:
- this.collapse( event );
- break;
- case $.ui.keyCode.RIGHT:
- if ( this.active && !this.active.is( ".ui-state-disabled" ) ) {
- this.expand( event );
- }
- break;
- case $.ui.keyCode.ENTER:
- case $.ui.keyCode.SPACE:
- this._activate( event );
- break;
- case $.ui.keyCode.ESCAPE:
- this.collapse( event );
- break;
- default:
- preventDefault = false;
- prev = this.previousFilter || "";
- character = String.fromCharCode( event.keyCode );
- skip = false;
-
- clearTimeout( this.filterTimer );
-
- if ( character === prev ) {
- skip = true;
- } else {
- character = prev + character;
- }
-
- regex = new RegExp( "^" + escape( character ), "i" );
- match = this.activeMenu.children( ".ui-menu-item" ).filter(function() {
- return regex.test( $( this ).children( "a" ).text() );
- });
- match = skip && match.index( this.active.next() ) !== -1 ?
- this.active.nextAll( ".ui-menu-item" ) :
- match;
-
- // If no matches on the current filter, reset to the last character pressed
- // to move down the menu to the first item that starts with that character
- if ( !match.length ) {
- character = String.fromCharCode( event.keyCode );
- regex = new RegExp( "^" + escape( character ), "i" );
- match = this.activeMenu.children( ".ui-menu-item" ).filter(function() {
- return regex.test( $( this ).children( "a" ).text() );
- });
- }
-
- if ( match.length ) {
- this.focus( event, match );
- if ( match.length > 1 ) {
- this.previousFilter = character;
- this.filterTimer = this._delay(function() {
- delete this.previousFilter;
- }, 1000 );
- } else {
- delete this.previousFilter;
- }
- } else {
- delete this.previousFilter;
- }
- }
-
- if ( preventDefault ) {
- event.preventDefault();
- }
- },
-
- _activate: function( event ) {
- if ( !this.active.is( ".ui-state-disabled" ) ) {
- if ( this.active.children( "a[aria-haspopup='true']" ).length ) {
- this.expand( event );
- } else {
- this.select( event );
- }
- }
- },
-
- refresh: function() {
- var menus,
- icon = this.options.icons.submenu,
- submenus = this.element.find( this.options.menus );
-
- this.element.toggleClass( "ui-menu-icons", !!this.element.find( ".ui-icon" ).length );
-
- // Initialize nested menus
- submenus.filter( ":not(.ui-menu)" )
- .addClass( "ui-menu ui-widget ui-widget-content ui-corner-all" )
- .hide()
- .attr({
- role: this.options.role,
- "aria-hidden": "true",
- "aria-expanded": "false"
- })
- .each(function() {
- var menu = $( this ),
- item = menu.prev( "a" ),
- submenuCarat = $( "<span>" )
- .addClass( "ui-menu-icon ui-icon " + icon )
- .data( "ui-menu-submenu-carat", true );
-
- item
- .attr( "aria-haspopup", "true" )
- .prepend( submenuCarat );
- menu.attr( "aria-labelledby", item.attr( "id" ) );
- });
-
- menus = submenus.add( this.element );
-
- // Don't refresh list items that are already adapted
- menus.children( ":not(.ui-menu-item):has(a)" )
- .addClass( "ui-menu-item" )
- .attr( "role", "presentation" )
- .children( "a" )
- .uniqueId()
- .addClass( "ui-corner-all" )
- .attr({
- tabIndex: -1,
- role: this._itemRole()
- });
-
- // Initialize unlinked menu-items containing spaces and/or dashes only as dividers
- menus.children( ":not(.ui-menu-item)" ).each(function() {
- var item = $( this );
- // hyphen, em dash, en dash
- if ( !/[^\-\u2014\u2013\s]/.test( item.text() ) ) {
- item.addClass( "ui-widget-content ui-menu-divider" );
- }
- });
-
- // Add aria-disabled attribute to any disabled menu item
- menus.children( ".ui-state-disabled" ).attr( "aria-disabled", "true" );
-
- // If the active item has been removed, blur the menu
- if ( this.active && !$.contains( this.element[ 0 ], this.active[ 0 ] ) ) {
- this.blur();
- }
- },
-
- _itemRole: function() {
- return {
- menu: "menuitem",
- listbox: "option"
- }[ this.options.role ];
- },
-
- _setOption: function( key, value ) {
- if ( key === "icons" ) {
- this.element.find( ".ui-menu-icon" )
- .removeClass( this.options.icons.submenu )
- .addClass( value.submenu );
- }
- this._super( key, value );
- },
-
- focus: function( event, item ) {
- var nested, focused;
- this.blur( event, event && event.type === "focus" );
-
- this._scrollIntoView( item );
-
- this.active = item.first();
- focused = this.active.children( "a" ).addClass( "ui-state-focus" );
- // Only update aria-activedescendant if there's a role
- // otherwise we assume focus is managed elsewhere
- if ( this.options.role ) {
- this.element.attr( "aria-activedescendant", focused.attr( "id" ) );
- }
-
- // Highlight active parent menu item, if any
- this.active
- .parent()
- .closest( ".ui-menu-item" )
- .children( "a:first" )
- .addClass( "ui-state-active" );
-
- if ( event && event.type === "keydown" ) {
- this._close();
- } else {
- this.timer = this._delay(function() {
- this._close();
- }, this.delay );
- }
-
- nested = item.children( ".ui-menu" );
- if ( nested.length && event && ( /^mouse/.test( event.type ) ) ) {
- this._startOpening(nested);
- }
- this.activeMenu = item.parent();
-
- this._trigger( "focus", event, { item: item } );
- },
-
- _scrollIntoView: function( item ) {
- var borderTop, paddingTop, offset, scroll, elementHeight, itemHeight;
- if ( this._hasScroll() ) {
- borderTop = parseFloat( $.css( this.activeMenu[0], "borderTopWidth" ) ) || 0;
- paddingTop = parseFloat( $.css( this.activeMenu[0], "paddingTop" ) ) || 0;
- offset = item.offset().top - this.activeMenu.offset().top - borderTop - paddingTop;
- scroll = this.activeMenu.scrollTop();
- elementHeight = this.activeMenu.height();
- itemHeight = item.height();
-
- if ( offset < 0 ) {
- this.activeMenu.scrollTop( scroll + offset );
- } else if ( offset + itemHeight > elementHeight ) {
- this.activeMenu.scrollTop( scroll + offset - elementHeight + itemHeight );
- }
- }
- },
-
- blur: function( event, fromFocus ) {
- if ( !fromFocus ) {
- clearTimeout( this.timer );
- }
-
- if ( !this.active ) {
- return;
- }
-
- this.active.children( "a" ).removeClass( "ui-state-focus" );
- this.active = null;
-
- this._trigger( "blur", event, { item: this.active } );
- },
-
- _startOpening: function( submenu ) {
- clearTimeout( this.timer );
-
- // Don't open if already open fixes a Firefox bug that caused a .5 pixel
- // shift in the submenu position when mousing over the carat icon
- if ( submenu.attr( "aria-hidden" ) !== "true" ) {
- return;
- }
-
- this.timer = this._delay(function() {
- this._close();
- this._open( submenu );
- }, this.delay );
- },
-
- _open: function( submenu ) {
- var position = $.extend({
- of: this.active
- }, this.options.position );
-
- clearTimeout( this.timer );
- this.element.find( ".ui-menu" ).not( submenu.parents( ".ui-menu" ) )
- .hide()
- .attr( "aria-hidden", "true" );
-
- submenu
- .show()
- .removeAttr( "aria-hidden" )
- .attr( "aria-expanded", "true" )
- .position( position );
- },
-
- collapseAll: function( event, all ) {
- clearTimeout( this.timer );
- this.timer = this._delay(function() {
- // If we were passed an event, look for the submenu that contains the event
- var currentMenu = all ? this.element :
- $( event && event.target ).closest( this.element.find( ".ui-menu" ) );
-
- // If we found no valid submenu ancestor, use the main menu to close all sub menus anyway
- if ( !currentMenu.length ) {
- currentMenu = this.element;
- }
-
- this._close( currentMenu );
-
- this.blur( event );
- this.activeMenu = currentMenu;
- }, this.delay );
- },
-
- // With no arguments, closes the currently active menu - if nothing is active
- // it closes all menus. If passed an argument, it will search for menus BELOW
- _close: function( startMenu ) {
- if ( !startMenu ) {
- startMenu = this.active ? this.active.parent() : this.element;
- }
-
- startMenu
- .find( ".ui-menu" )
- .hide()
- .attr( "aria-hidden", "true" )
- .attr( "aria-expanded", "false" )
- .end()
- .find( "a.ui-state-active" )
- .removeClass( "ui-state-active" );
- },
-
- collapse: function( event ) {
- var newItem = this.active &&
- this.active.parent().closest( ".ui-menu-item", this.element );
- if ( newItem && newItem.length ) {
- this._close();
- this.focus( event, newItem );
- }
- },
-
- expand: function( event ) {
- var newItem = this.active &&
- this.active
- .children( ".ui-menu " )
- .children( ".ui-menu-item" )
- .first();
-
- if ( newItem && newItem.length ) {
- this._open( newItem.parent() );
-
- // Delay so Firefox will not hide activedescendant change in expanding submenu from AT
- this._delay(function() {
- this.focus( event, newItem );
- });
- }
- },
-
- next: function( event ) {
- this._move( "next", "first", event );
- },
-
- previous: function( event ) {
- this._move( "prev", "last", event );
- },
-
- isFirstItem: function() {
- return this.active && !this.active.prevAll( ".ui-menu-item" ).length;
- },
-
- isLastItem: function() {
- return this.active && !this.active.nextAll( ".ui-menu-item" ).length;
- },
-
- _move: function( direction, filter, event ) {
- var next;
- if ( this.active ) {
- if ( direction === "first" || direction === "last" ) {
- next = this.active
- [ direction === "first" ? "prevAll" : "nextAll" ]( ".ui-menu-item" )
- .eq( -1 );
- } else {
- next = this.active
- [ direction + "All" ]( ".ui-menu-item" )
- .eq( 0 );
- }
- }
- if ( !next || !next.length || !this.active ) {
- next = this.activeMenu.children( ".ui-menu-item" )[ filter ]();
- }
-
- this.focus( event, next );
- },
-
- nextPage: function( event ) {
- var item, base, height;
-
- if ( !this.active ) {
- this.next( event );
- return;
- }
- if ( this.isLastItem() ) {
- return;
- }
- if ( this._hasScroll() ) {
- base = this.active.offset().top;
- height = this.element.height();
- this.active.nextAll( ".ui-menu-item" ).each(function() {
- item = $( this );
- return item.offset().top - base - height < 0;
- });
-
- this.focus( event, item );
- } else {
- this.focus( event, this.activeMenu.children( ".ui-menu-item" )
- [ !this.active ? "first" : "last" ]() );
- }
- },
-
- previousPage: function( event ) {
- var item, base, height;
- if ( !this.active ) {
- this.next( event );
- return;
- }
- if ( this.isFirstItem() ) {
- return;
- }
- if ( this._hasScroll() ) {
- base = this.active.offset().top;
- height = this.element.height();
- this.active.prevAll( ".ui-menu-item" ).each(function() {
- item = $( this );
- return item.offset().top - base + height > 0;
- });
-
- this.focus( event, item );
- } else {
- this.focus( event, this.activeMenu.children( ".ui-menu-item" ).first() );
- }
- },
-
- _hasScroll: function() {
- return this.element.outerHeight() < this.element.prop( "scrollHeight" );
- },
-
- select: function( event ) {
- // TODO: It should never be possible to not have an active item at this
- // point, but the tests don't trigger mouseenter before click.
- this.active = this.active || $( event.target ).closest( ".ui-menu-item" );
- var ui = { item: this.active };
- if ( !this.active.has( ".ui-menu" ).length ) {
- this.collapseAll( event, true );
- }
- this._trigger( "select", event, ui );
- }
-});
-
-}( jQuery ));
-(function( $, undefined ) {
-
-$.widget( "ui.progressbar", {
- version: "1.10.4",
- options: {
- max: 100,
- value: 0,
-
- change: null,
- complete: null
- },
-
- min: 0,
-
- _create: function() {
- // Constrain initial value
- this.oldValue = this.options.value = this._constrainedValue();
-
- this.element
- .addClass( "ui-progressbar ui-widget ui-widget-content ui-corner-all" )
- .attr({
- // Only set static values, aria-valuenow and aria-valuemax are
- // set inside _refreshValue()
- role: "progressbar",
- "aria-valuemin": this.min
- });
-
- this.valueDiv = $( "<div class='ui-progressbar-value ui-widget-header ui-corner-left'></div>" )
- .appendTo( this.element );
-
- this._refreshValue();
- },
-
- _destroy: function() {
- this.element
- .removeClass( "ui-progressbar ui-widget ui-widget-content ui-corner-all" )
- .removeAttr( "role" )
- .removeAttr( "aria-valuemin" )
- .removeAttr( "aria-valuemax" )
- .removeAttr( "aria-valuenow" );
-
- this.valueDiv.remove();
- },
-
- value: function( newValue ) {
- if ( newValue === undefined ) {
- return this.options.value;
- }
-
- this.options.value = this._constrainedValue( newValue );
- this._refreshValue();
- },
-
- _constrainedValue: function( newValue ) {
- if ( newValue === undefined ) {
- newValue = this.options.value;
- }
-
- this.indeterminate = newValue === false;
-
- // sanitize value
- if ( typeof newValue !== "number" ) {
- newValue = 0;
- }
-
- return this.indeterminate ? false :
- Math.min( this.options.max, Math.max( this.min, newValue ) );
- },
-
- _setOptions: function( options ) {
- // Ensure "value" option is set after other values (like max)
- var value = options.value;
- delete options.value;
-
- this._super( options );
-
- this.options.value = this._constrainedValue( value );
- this._refreshValue();
- },
-
- _setOption: function( key, value ) {
- if ( key === "max" ) {
- // Don't allow a max less than min
- value = Math.max( this.min, value );
- }
-
- this._super( key, value );
- },
-
- _percentage: function() {
- return this.indeterminate ? 100 : 100 * ( this.options.value - this.min ) / ( this.options.max - this.min );
- },
-
- _refreshValue: function() {
- var value = this.options.value,
- percentage = this._percentage();
-
- this.valueDiv
- .toggle( this.indeterminate || value > this.min )
- .toggleClass( "ui-corner-right", value === this.options.max )
- .width( percentage.toFixed(0) + "%" );
-
- this.element.toggleClass( "ui-progressbar-indeterminate", this.indeterminate );
-
- if ( this.indeterminate ) {
- this.element.removeAttr( "aria-valuenow" );
- if ( !this.overlayDiv ) {
- this.overlayDiv = $( "<div class='ui-progressbar-overlay'></div>" ).appendTo( this.valueDiv );
- }
- } else {
- this.element.attr({
- "aria-valuemax": this.options.max,
- "aria-valuenow": value
- });
- if ( this.overlayDiv ) {
- this.overlayDiv.remove();
- this.overlayDiv = null;
- }
- }
-
- if ( this.oldValue !== value ) {
- this.oldValue = value;
- this._trigger( "change" );
- }
- if ( value === this.options.max ) {
- this._trigger( "complete" );
- }
- }
-});
-
-})( jQuery );
-(function( $, undefined ) {
-
-// number of pages in a slider
-// (how many times can you page up/down to go through the whole range)
-var numPages = 5;
-
-$.widget( "ui.slider", $.ui.mouse, {
- version: "1.10.4",
- widgetEventPrefix: "slide",
-
- options: {
- animate: false,
- distance: 0,
- max: 100,
- min: 0,
- orientation: "horizontal",
- range: false,
- step: 1,
- value: 0,
- values: null,
-
- // callbacks
- change: null,
- slide: null,
- start: null,
- stop: null
- },
-
- _create: function() {
- this._keySliding = false;
- this._mouseSliding = false;
- this._animateOff = true;
- this._handleIndex = null;
- this._detectOrientation();
- this._mouseInit();
-
- this.element
- .addClass( "ui-slider" +
- " ui-slider-" + this.orientation +
- " ui-widget" +
- " ui-widget-content" +
- " ui-corner-all");
-
- this._refresh();
- this._setOption( "disabled", this.options.disabled );
-
- this._animateOff = false;
- },
-
- _refresh: function() {
- this._createRange();
- this._createHandles();
- this._setupEvents();
- this._refreshValue();
- },
-
- _createHandles: function() {
- var i, handleCount,
- options = this.options,
- existingHandles = this.element.find( ".ui-slider-handle" ).addClass( "ui-state-default ui-corner-all" ),
- handle = "<a class='ui-slider-handle ui-state-default ui-corner-all' href='#'></a>",
- handles = [];
-
- handleCount = ( options.values && options.values.length ) || 1;
-
- if ( existingHandles.length > handleCount ) {
- existingHandles.slice( handleCount ).remove();
- existingHandles = existingHandles.slice( 0, handleCount );
- }
-
- for ( i = existingHandles.length; i < handleCount; i++ ) {
- handles.push( handle );
- }
-
- this.handles = existingHandles.add( $( handles.join( "" ) ).appendTo( this.element ) );
-
- this.handle = this.handles.eq( 0 );
-
- this.handles.each(function( i ) {
- $( this ).data( "ui-slider-handle-index", i );
- });
- },
-
- _createRange: function() {
- var options = this.options,
- classes = "";
-
- if ( options.range ) {
- if ( options.range === true ) {
- if ( !options.values ) {
- options.values = [ this._valueMin(), this._valueMin() ];
- } else if ( options.values.length && options.values.length !== 2 ) {
- options.values = [ options.values[0], options.values[0] ];
- } else if ( $.isArray( options.values ) ) {
- options.values = options.values.slice(0);
- }
- }
-
- if ( !this.range || !this.range.length ) {
- this.range = $( "<div></div>" )
- .appendTo( this.element );
-
- classes = "ui-slider-range" +
- // note: this isn't the most fittingly semantic framework class for this element,
- // but worked best visually with a variety of themes
- " ui-widget-header ui-corner-all";
- } else {
- this.range.removeClass( "ui-slider-range-min ui-slider-range-max" )
- // Handle range switching from true to min/max
- .css({
- "left": "",
- "bottom": ""
- });
- }
-
- this.range.addClass( classes +
- ( ( options.range === "min" || options.range === "max" ) ? " ui-slider-range-" + options.range : "" ) );
- } else {
- if ( this.range ) {
- this.range.remove();
- }
- this.range = null;
- }
- },
-
- _setupEvents: function() {
- var elements = this.handles.add( this.range ).filter( "a" );
- this._off( elements );
- this._on( elements, this._handleEvents );
- this._hoverable( elements );
- this._focusable( elements );
- },
-
- _destroy: function() {
- this.handles.remove();
- if ( this.range ) {
- this.range.remove();
- }
-
- this.element
- .removeClass( "ui-slider" +
- " ui-slider-horizontal" +
- " ui-slider-vertical" +
- " ui-widget" +
- " ui-widget-content" +
- " ui-corner-all" );
-
- this._mouseDestroy();
- },
-
- _mouseCapture: function( event ) {
- var position, normValue, distance, closestHandle, index, allowed, offset, mouseOverHandle,
- that = this,
- o = this.options;
-
- if ( o.disabled ) {
- return false;
- }
-
- this.elementSize = {
- width: this.element.outerWidth(),
- height: this.element.outerHeight()
- };
- this.elementOffset = this.element.offset();
-
- position = { x: event.pageX, y: event.pageY };
- normValue = this._normValueFromMouse( position );
- distance = this._valueMax() - this._valueMin() + 1;
- this.handles.each(function( i ) {
- var thisDistance = Math.abs( normValue - that.values(i) );
- if (( distance > thisDistance ) ||
- ( distance === thisDistance &&
- (i === that._lastChangedValue || that.values(i) === o.min ))) {
- distance = thisDistance;
- closestHandle = $( this );
- index = i;
- }
- });
-
- allowed = this._start( event, index );
- if ( allowed === false ) {
- return false;
- }
- this._mouseSliding = true;
-
- this._handleIndex = index;
-
- closestHandle
- .addClass( "ui-state-active" )
- .focus();
-
- offset = closestHandle.offset();
- mouseOverHandle = !$( event.target ).parents().addBack().is( ".ui-slider-handle" );
- this._clickOffset = mouseOverHandle ? { left: 0, top: 0 } : {
- left: event.pageX - offset.left - ( closestHandle.width() / 2 ),
- top: event.pageY - offset.top -
- ( closestHandle.height() / 2 ) -
- ( parseInt( closestHandle.css("borderTopWidth"), 10 ) || 0 ) -
- ( parseInt( closestHandle.css("borderBottomWidth"), 10 ) || 0) +
- ( parseInt( closestHandle.css("marginTop"), 10 ) || 0)
- };
-
- if ( !this.handles.hasClass( "ui-state-hover" ) ) {
- this._slide( event, index, normValue );
- }
- this._animateOff = true;
- return true;
- },
-
- _mouseStart: function() {
- return true;
- },
-
- _mouseDrag: function( event ) {
- var position = { x: event.pageX, y: event.pageY },
- normValue = this._normValueFromMouse( position );
-
- this._slide( event, this._handleIndex, normValue );
-
- return false;
- },
-
- _mouseStop: function( event ) {
- this.handles.removeClass( "ui-state-active" );
- this._mouseSliding = false;
-
- this._stop( event, this._handleIndex );
- this._change( event, this._handleIndex );
-
- this._handleIndex = null;
- this._clickOffset = null;
- this._animateOff = false;
-
- return false;
- },
-
- _detectOrientation: function() {
- this.orientation = ( this.options.orientation === "vertical" ) ? "vertical" : "horizontal";
- },
-
- _normValueFromMouse: function( position ) {
- var pixelTotal,
- pixelMouse,
- percentMouse,
- valueTotal,
- valueMouse;
-
- if ( this.orientation === "horizontal" ) {
- pixelTotal = this.elementSize.width;
- pixelMouse = position.x - this.elementOffset.left - ( this._clickOffset ? this._clickOffset.left : 0 );
- } else {
- pixelTotal = this.elementSize.height;
- pixelMouse = position.y - this.elementOffset.top - ( this._clickOffset ? this._clickOffset.top : 0 );
- }
-
- percentMouse = ( pixelMouse / pixelTotal );
- if ( percentMouse > 1 ) {
- percentMouse = 1;
- }
- if ( percentMouse < 0 ) {
- percentMouse = 0;
- }
- if ( this.orientation === "vertical" ) {
- percentMouse = 1 - percentMouse;
- }
-
- valueTotal = this._valueMax() - this._valueMin();
- valueMouse = this._valueMin() + percentMouse * valueTotal;
-
- return this._trimAlignValue( valueMouse );
- },
-
- _start: function( event, index ) {
- var uiHash = {
- handle: this.handles[ index ],
- value: this.value()
- };
- if ( this.options.values && this.options.values.length ) {
- uiHash.value = this.values( index );
- uiHash.values = this.values();
- }
- return this._trigger( "start", event, uiHash );
- },
-
- _slide: function( event, index, newVal ) {
- var otherVal,
- newValues,
- allowed;
-
- if ( this.options.values && this.options.values.length ) {
- otherVal = this.values( index ? 0 : 1 );
-
- if ( ( this.options.values.length === 2 && this.options.range === true ) &&
- ( ( index === 0 && newVal > otherVal) || ( index === 1 && newVal < otherVal ) )
- ) {
- newVal = otherVal;
- }
-
- if ( newVal !== this.values( index ) ) {
- newValues = this.values();
- newValues[ index ] = newVal;
- // A slide can be canceled by returning false from the slide callback
- allowed = this._trigger( "slide", event, {
- handle: this.handles[ index ],
- value: newVal,
- values: newValues
- } );
- otherVal = this.values( index ? 0 : 1 );
- if ( allowed !== false ) {
- this.values( index, newVal );
- }
- }
- } else {
- if ( newVal !== this.value() ) {
- // A slide can be canceled by returning false from the slide callback
- allowed = this._trigger( "slide", event, {
- handle: this.handles[ index ],
- value: newVal
- } );
- if ( allowed !== false ) {
- this.value( newVal );
- }
- }
- }
- },
-
- _stop: function( event, index ) {
- var uiHash = {
- handle: this.handles[ index ],
- value: this.value()
- };
- if ( this.options.values && this.options.values.length ) {
- uiHash.value = this.values( index );
- uiHash.values = this.values();
- }
-
- this._trigger( "stop", event, uiHash );
- },
-
- _change: function( event, index ) {
- if ( !this._keySliding && !this._mouseSliding ) {
- var uiHash = {
- handle: this.handles[ index ],
- value: this.value()
- };
- if ( this.options.values && this.options.values.length ) {
- uiHash.value = this.values( index );
- uiHash.values = this.values();
- }
-
- //store the last changed value index for reference when handles overlap
- this._lastChangedValue = index;
-
- this._trigger( "change", event, uiHash );
- }
- },
-
- value: function( newValue ) {
- if ( arguments.length ) {
- this.options.value = this._trimAlignValue( newValue );
- this._refreshValue();
- this._change( null, 0 );
- return;
- }
-
- return this._value();
- },
-
- values: function( index, newValue ) {
- var vals,
- newValues,
- i;
-
- if ( arguments.length > 1 ) {
- this.options.values[ index ] = this._trimAlignValue( newValue );
- this._refreshValue();
- this._change( null, index );
- return;
- }
-
- if ( arguments.length ) {
- if ( $.isArray( arguments[ 0 ] ) ) {
- vals = this.options.values;
- newValues = arguments[ 0 ];
- for ( i = 0; i < vals.length; i += 1 ) {
- vals[ i ] = this._trimAlignValue( newValues[ i ] );
- this._change( null, i );
- }
- this._refreshValue();
- } else {
- if ( this.options.values && this.options.values.length ) {
- return this._values( index );
- } else {
- return this.value();
- }
- }
- } else {
- return this._values();
- }
- },
-
- _setOption: function( key, value ) {
- var i,
- valsLength = 0;
-
- if ( key === "range" && this.options.range === true ) {
- if ( value === "min" ) {
- this.options.value = this._values( 0 );
- this.options.values = null;
- } else if ( value === "max" ) {
- this.options.value = this._values( this.options.values.length-1 );
- this.options.values = null;
- }
- }
-
- if ( $.isArray( this.options.values ) ) {
- valsLength = this.options.values.length;
- }
-
- $.Widget.prototype._setOption.apply( this, arguments );
-
- switch ( key ) {
- case "orientation":
- this._detectOrientation();
- this.element
- .removeClass( "ui-slider-horizontal ui-slider-vertical" )
- .addClass( "ui-slider-" + this.orientation );
- this._refreshValue();
- break;
- case "value":
- this._animateOff = true;
- this._refreshValue();
- this._change( null, 0 );
- this._animateOff = false;
- break;
- case "values":
- this._animateOff = true;
- this._refreshValue();
- for ( i = 0; i < valsLength; i += 1 ) {
- this._change( null, i );
- }
- this._animateOff = false;
- break;
- case "min":
- case "max":
- this._animateOff = true;
- this._refreshValue();
- this._animateOff = false;
- break;
- case "range":
- this._animateOff = true;
- this._refresh();
- this._animateOff = false;
- break;
- }
- },
-
- //internal value getter
- // _value() returns value trimmed by min and max, aligned by step
- _value: function() {
- var val = this.options.value;
- val = this._trimAlignValue( val );
-
- return val;
- },
-
- //internal values getter
- // _values() returns array of values trimmed by min and max, aligned by step
- // _values( index ) returns single value trimmed by min and max, aligned by step
- _values: function( index ) {
- var val,
- vals,
- i;
-
- if ( arguments.length ) {
- val = this.options.values[ index ];
- val = this._trimAlignValue( val );
-
- return val;
- } else if ( this.options.values && this.options.values.length ) {
- // .slice() creates a copy of the array
- // this copy gets trimmed by min and max and then returned
- vals = this.options.values.slice();
- for ( i = 0; i < vals.length; i+= 1) {
- vals[ i ] = this._trimAlignValue( vals[ i ] );
- }
-
- return vals;
- } else {
- return [];
- }
- },
-
- // returns the step-aligned value that val is closest to, between (inclusive) min and max
- _trimAlignValue: function( val ) {
- if ( val <= this._valueMin() ) {
- return this._valueMin();
- }
- if ( val >= this._valueMax() ) {
- return this._valueMax();
- }
- var step = ( this.options.step > 0 ) ? this.options.step : 1,
- valModStep = (val - this._valueMin()) % step,
- alignValue = val - valModStep;
-
- if ( Math.abs(valModStep) * 2 >= step ) {
- alignValue += ( valModStep > 0 ) ? step : ( -step );
- }
-
- // Since JavaScript has problems with large floats, round
- // the final value to 5 digits after the decimal point (see #4124)
- return parseFloat( alignValue.toFixed(5) );
- },
-
- _valueMin: function() {
- return this.options.min;
- },
-
- _valueMax: function() {
- return this.options.max;
- },
-
- _refreshValue: function() {
- var lastValPercent, valPercent, value, valueMin, valueMax,
- oRange = this.options.range,
- o = this.options,
- that = this,
- animate = ( !this._animateOff ) ? o.animate : false,
- _set = {};
-
- if ( this.options.values && this.options.values.length ) {
- this.handles.each(function( i ) {
- valPercent = ( that.values(i) - that._valueMin() ) / ( that._valueMax() - that._valueMin() ) * 100;
- _set[ that.orientation === "horizontal" ? "left" : "bottom" ] = valPercent + "%";
- $( this ).stop( 1, 1 )[ animate ? "animate" : "css" ]( _set, o.animate );
- if ( that.options.range === true ) {
- if ( that.orientation === "horizontal" ) {
- if ( i === 0 ) {
- that.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { left: valPercent + "%" }, o.animate );
- }
- if ( i === 1 ) {
- that.range[ animate ? "animate" : "css" ]( { width: ( valPercent - lastValPercent ) + "%" }, { queue: false, duration: o.animate } );
- }
- } else {
- if ( i === 0 ) {
- that.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { bottom: ( valPercent ) + "%" }, o.animate );
- }
- if ( i === 1 ) {
- that.range[ animate ? "animate" : "css" ]( { height: ( valPercent - lastValPercent ) + "%" }, { queue: false, duration: o.animate } );
- }
- }
- }
- lastValPercent = valPercent;
- });
- } else {
- value = this.value();
- valueMin = this._valueMin();
- valueMax = this._valueMax();
- valPercent = ( valueMax !== valueMin ) ?
- ( value - valueMin ) / ( valueMax - valueMin ) * 100 :
- 0;
- _set[ this.orientation === "horizontal" ? "left" : "bottom" ] = valPercent + "%";
- this.handle.stop( 1, 1 )[ animate ? "animate" : "css" ]( _set, o.animate );
-
- if ( oRange === "min" && this.orientation === "horizontal" ) {
- this.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { width: valPercent + "%" }, o.animate );
- }
- if ( oRange === "max" && this.orientation === "horizontal" ) {
- this.range[ animate ? "animate" : "css" ]( { width: ( 100 - valPercent ) + "%" }, { queue: false, duration: o.animate } );
- }
- if ( oRange === "min" && this.orientation === "vertical" ) {
- this.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { height: valPercent + "%" }, o.animate );
- }
- if ( oRange === "max" && this.orientation === "vertical" ) {
- this.range[ animate ? "animate" : "css" ]( { height: ( 100 - valPercent ) + "%" }, { queue: false, duration: o.animate } );
- }
- }
- },
-
- _handleEvents: {
- keydown: function( event ) {
- var allowed, curVal, newVal, step,
- index = $( event.target ).data( "ui-slider-handle-index" );
-
- switch ( event.keyCode ) {
- case $.ui.keyCode.HOME:
- case $.ui.keyCode.END:
- case $.ui.keyCode.PAGE_UP:
- case $.ui.keyCode.PAGE_DOWN:
- case $.ui.keyCode.UP:
- case $.ui.keyCode.RIGHT:
- case $.ui.keyCode.DOWN:
- case $.ui.keyCode.LEFT:
- event.preventDefault();
- if ( !this._keySliding ) {
- this._keySliding = true;
- $( event.target ).addClass( "ui-state-active" );
- allowed = this._start( event, index );
- if ( allowed === false ) {
- return;
- }
- }
- break;
- }
-
- step = this.options.step;
- if ( this.options.values && this.options.values.length ) {
- curVal = newVal = this.values( index );
- } else {
- curVal = newVal = this.value();
- }
-
- switch ( event.keyCode ) {
- case $.ui.keyCode.HOME:
- newVal = this._valueMin();
- break;
- case $.ui.keyCode.END:
- newVal = this._valueMax();
- break;
- case $.ui.keyCode.PAGE_UP:
- newVal = this._trimAlignValue( curVal + ( (this._valueMax() - this._valueMin()) / numPages ) );
- break;
- case $.ui.keyCode.PAGE_DOWN:
- newVal = this._trimAlignValue( curVal - ( (this._valueMax() - this._valueMin()) / numPages ) );
- break;
- case $.ui.keyCode.UP:
- case $.ui.keyCode.RIGHT:
- if ( curVal === this._valueMax() ) {
- return;
- }
- newVal = this._trimAlignValue( curVal + step );
- break;
- case $.ui.keyCode.DOWN:
- case $.ui.keyCode.LEFT:
- if ( curVal === this._valueMin() ) {
- return;
- }
- newVal = this._trimAlignValue( curVal - step );
- break;
- }
-
- this._slide( event, index, newVal );
- },
- click: function( event ) {
- event.preventDefault();
- },
- keyup: function( event ) {
- var index = $( event.target ).data( "ui-slider-handle-index" );
-
- if ( this._keySliding ) {
- this._keySliding = false;
- this._stop( event, index );
- this._change( event, index );
- $( event.target ).removeClass( "ui-state-active" );
- }
- }
- }
-
-});
-
-}(jQuery));
-(function( $ ) {
-
-function modifier( fn ) {
- return function() {
- var previous = this.element.val();
- fn.apply( this, arguments );
- this._refresh();
- if ( previous !== this.element.val() ) {
- this._trigger( "change" );
- }
- };
-}
-
-$.widget( "ui.spinner", {
- version: "1.10.4",
- defaultElement: "<input>",
- widgetEventPrefix: "spin",
- options: {
- culture: null,
- icons: {
- down: "ui-icon-triangle-1-s",
- up: "ui-icon-triangle-1-n"
- },
- incremental: true,
- max: null,
- min: null,
- numberFormat: null,
- page: 10,
- step: 1,
-
- change: null,
- spin: null,
- start: null,
- stop: null
- },
-
- _create: function() {
- // handle string values that need to be parsed
- this._setOption( "max", this.options.max );
- this._setOption( "min", this.options.min );
- this._setOption( "step", this.options.step );
-
- // Only format if there is a value, prevents the field from being marked
- // as invalid in Firefox, see #9573.
- if ( this.value() !== "" ) {
- // Format the value, but don't constrain.
- this._value( this.element.val(), true );
- }
-
- this._draw();
- this._on( this._events );
- this._refresh();
-
- // turning off autocomplete prevents the browser from remembering the
- // value when navigating through history, so we re-enable autocomplete
- // if the page is unloaded before the widget is destroyed. #7790
- this._on( this.window, {
- beforeunload: function() {
- this.element.removeAttr( "autocomplete" );
- }
- });
- },
-
- _getCreateOptions: function() {
- var options = {},
- element = this.element;
-
- $.each( [ "min", "max", "step" ], function( i, option ) {
- var value = element.attr( option );
- if ( value !== undefined && value.length ) {
- options[ option ] = value;
- }
- });
-
- return options;
- },
-
- _events: {
- keydown: function( event ) {
- if ( this._start( event ) && this._keydown( event ) ) {
- event.preventDefault();
- }
- },
- keyup: "_stop",
- focus: function() {
- this.previous = this.element.val();
- },
- blur: function( event ) {
- if ( this.cancelBlur ) {
- delete this.cancelBlur;
- return;
- }
-
- this._stop();
- this._refresh();
- if ( this.previous !== this.element.val() ) {
- this._trigger( "change", event );
- }
- },
- mousewheel: function( event, delta ) {
- if ( !delta ) {
- return;
- }
- if ( !this.spinning && !this._start( event ) ) {
- return false;
- }
-
- this._spin( (delta > 0 ? 1 : -1) * this.options.step, event );
- clearTimeout( this.mousewheelTimer );
- this.mousewheelTimer = this._delay(function() {
- if ( this.spinning ) {
- this._stop( event );
- }
- }, 100 );
- event.preventDefault();
- },
- "mousedown .ui-spinner-button": function( event ) {
- var previous;
-
- // We never want the buttons to have focus; whenever the user is
- // interacting with the spinner, the focus should be on the input.
- // If the input is focused then this.previous is properly set from
- // when the input first received focus. If the input is not focused
- // then we need to set this.previous based on the value before spinning.
- previous = this.element[0] === this.document[0].activeElement ?
- this.previous : this.element.val();
- function checkFocus() {
- var isActive = this.element[0] === this.document[0].activeElement;
- if ( !isActive ) {
- this.element.focus();
- this.previous = previous;
- // support: IE
- // IE sets focus asynchronously, so we need to check if focus
- // moved off of the input because the user clicked on the button.
- this._delay(function() {
- this.previous = previous;
- });
- }
- }
-
- // ensure focus is on (or stays on) the text field
- event.preventDefault();
- checkFocus.call( this );
-
- // support: IE
- // IE doesn't prevent moving focus even with event.preventDefault()
- // so we set a flag to know when we should ignore the blur event
- // and check (again) if focus moved off of the input.
- this.cancelBlur = true;
- this._delay(function() {
- delete this.cancelBlur;
- checkFocus.call( this );
- });
-
- if ( this._start( event ) === false ) {
- return;
- }
-
- this._repeat( null, $( event.currentTarget ).hasClass( "ui-spinner-up" ) ? 1 : -1, event );
- },
- "mouseup .ui-spinner-button": "_stop",
- "mouseenter .ui-spinner-button": function( event ) {
- // button will add ui-state-active if mouse was down while mouseleave and kept down
- if ( !$( event.currentTarget ).hasClass( "ui-state-active" ) ) {
- return;
- }
-
- if ( this._start( event ) === false ) {
- return false;
- }
- this._repeat( null, $( event.currentTarget ).hasClass( "ui-spinner-up" ) ? 1 : -1, event );
- },
- // TODO: do we really want to consider this a stop?
- // shouldn't we just stop the repeater and wait until mouseup before
- // we trigger the stop event?
- "mouseleave .ui-spinner-button": "_stop"
- },
-
- _draw: function() {
- var uiSpinner = this.uiSpinner = this.element
- .addClass( "ui-spinner-input" )
- .attr( "autocomplete", "off" )
- .wrap( this._uiSpinnerHtml() )
- .parent()
- // add buttons
- .append( this._buttonHtml() );
-
- this.element.attr( "role", "spinbutton" );
-
- // button bindings
- this.buttons = uiSpinner.find( ".ui-spinner-button" )
- .attr( "tabIndex", -1 )
- .button()
- .removeClass( "ui-corner-all" );
-
- // IE 6 doesn't understand height: 50% for the buttons
- // unless the wrapper has an explicit height
- if ( this.buttons.height() > Math.ceil( uiSpinner.height() * 0.5 ) &&
- uiSpinner.height() > 0 ) {
- uiSpinner.height( uiSpinner.height() );
- }
-
- // disable spinner if element was already disabled
- if ( this.options.disabled ) {
- this.disable();
- }
- },
-
- _keydown: function( event ) {
- var options = this.options,
- keyCode = $.ui.keyCode;
-
- switch ( event.keyCode ) {
- case keyCode.UP:
- this._repeat( null, 1, event );
- return true;
- case keyCode.DOWN:
- this._repeat( null, -1, event );
- return true;
- case keyCode.PAGE_UP:
- this._repeat( null, options.page, event );
- return true;
- case keyCode.PAGE_DOWN:
- this._repeat( null, -options.page, event );
- return true;
- }
-
- return false;
- },
-
- _uiSpinnerHtml: function() {
- return "<span class='ui-spinner ui-widget ui-widget-content ui-corner-all'></span>";
- },
-
- _buttonHtml: function() {
- return "" +
- "<a class='ui-spinner-button ui-spinner-up ui-corner-tr'>" +
- "<span class='ui-icon " + this.options.icons.up + "'>▲</span>" +
- "</a>" +
- "<a class='ui-spinner-button ui-spinner-down ui-corner-br'>" +
- "<span class='ui-icon " + this.options.icons.down + "'>▼</span>" +
- "</a>";
- },
-
- _start: function( event ) {
- if ( !this.spinning && this._trigger( "start", event ) === false ) {
- return false;
- }
-
- if ( !this.counter ) {
- this.counter = 1;
- }
- this.spinning = true;
- return true;
- },
-
- _repeat: function( i, steps, event ) {
- i = i || 500;
-
- clearTimeout( this.timer );
- this.timer = this._delay(function() {
- this._repeat( 40, steps, event );
- }, i );
-
- this._spin( steps * this.options.step, event );
- },
-
- _spin: function( step, event ) {
- var value = this.value() || 0;
-
- if ( !this.counter ) {
- this.counter = 1;
- }
-
- value = this._adjustValue( value + step * this._increment( this.counter ) );
-
- if ( !this.spinning || this._trigger( "spin", event, { value: value } ) !== false) {
- this._value( value );
- this.counter++;
- }
- },
-
- _increment: function( i ) {
- var incremental = this.options.incremental;
-
- if ( incremental ) {
- return $.isFunction( incremental ) ?
- incremental( i ) :
- Math.floor( i*i*i/50000 - i*i/500 + 17*i/200 + 1 );
- }
-
- return 1;
- },
-
- _precision: function() {
- var precision = this._precisionOf( this.options.step );
- if ( this.options.min !== null ) {
- precision = Math.max( precision, this._precisionOf( this.options.min ) );
- }
- return precision;
- },
-
- _precisionOf: function( num ) {
- var str = num.toString(),
- decimal = str.indexOf( "." );
- return decimal === -1 ? 0 : str.length - decimal - 1;
- },
-
- _adjustValue: function( value ) {
- var base, aboveMin,
- options = this.options;
-
- // make sure we're at a valid step
- // - find out where we are relative to the base (min or 0)
- base = options.min !== null ? options.min : 0;
- aboveMin = value - base;
- // - round to the nearest step
- aboveMin = Math.round(aboveMin / options.step) * options.step;
- // - rounding is based on 0, so adjust back to our base
- value = base + aboveMin;
-
- // fix precision from bad JS floating point math
- value = parseFloat( value.toFixed( this._precision() ) );
-
- // clamp the value
- if ( options.max !== null && value > options.max) {
- return options.max;
- }
- if ( options.min !== null && value < options.min ) {
- return options.min;
- }
-
- return value;
- },
-
- _stop: function( event ) {
- if ( !this.spinning ) {
- return;
- }
-
- clearTimeout( this.timer );
- clearTimeout( this.mousewheelTimer );
- this.counter = 0;
- this.spinning = false;
- this._trigger( "stop", event );
- },
-
- _setOption: function( key, value ) {
- if ( key === "culture" || key === "numberFormat" ) {
- var prevValue = this._parse( this.element.val() );
- this.options[ key ] = value;
- this.element.val( this._format( prevValue ) );
- return;
- }
-
- if ( key === "max" || key === "min" || key === "step" ) {
- if ( typeof value === "string" ) {
- value = this._parse( value );
- }
- }
- if ( key === "icons" ) {
- this.buttons.first().find( ".ui-icon" )
- .removeClass( this.options.icons.up )
- .addClass( value.up );
- this.buttons.last().find( ".ui-icon" )
- .removeClass( this.options.icons.down )
- .addClass( value.down );
- }
-
- this._super( key, value );
-
- if ( key === "disabled" ) {
- if ( value ) {
- this.element.prop( "disabled", true );
- this.buttons.button( "disable" );
- } else {
- this.element.prop( "disabled", false );
- this.buttons.button( "enable" );
- }
- }
- },
-
- _setOptions: modifier(function( options ) {
- this._super( options );
- this._value( this.element.val() );
- }),
-
- _parse: function( val ) {
- if ( typeof val === "string" && val !== "" ) {
- val = window.Globalize && this.options.numberFormat ?
- Globalize.parseFloat( val, 10, this.options.culture ) : +val;
- }
- return val === "" || isNaN( val ) ? null : val;
- },
-
- _format: function( value ) {
- if ( value === "" ) {
- return "";
- }
- return window.Globalize && this.options.numberFormat ?
- Globalize.format( value, this.options.numberFormat, this.options.culture ) :
- value;
- },
-
- _refresh: function() {
- this.element.attr({
- "aria-valuemin": this.options.min,
- "aria-valuemax": this.options.max,
- // TODO: what should we do with values that can't be parsed?
- "aria-valuenow": this._parse( this.element.val() )
- });
- },
-
- // update the value without triggering change
- _value: function( value, allowAny ) {
- var parsed;
- if ( value !== "" ) {
- parsed = this._parse( value );
- if ( parsed !== null ) {
- if ( !allowAny ) {
- parsed = this._adjustValue( parsed );
- }
- value = this._format( parsed );
- }
- }
- this.element.val( value );
- this._refresh();
- },
-
- _destroy: function() {
- this.element
- .removeClass( "ui-spinner-input" )
- .prop( "disabled", false )
- .removeAttr( "autocomplete" )
- .removeAttr( "role" )
- .removeAttr( "aria-valuemin" )
- .removeAttr( "aria-valuemax" )
- .removeAttr( "aria-valuenow" );
- this.uiSpinner.replaceWith( this.element );
- },
-
- stepUp: modifier(function( steps ) {
- this._stepUp( steps );
- }),
- _stepUp: function( steps ) {
- if ( this._start() ) {
- this._spin( (steps || 1) * this.options.step );
- this._stop();
- }
- },
-
- stepDown: modifier(function( steps ) {
- this._stepDown( steps );
- }),
- _stepDown: function( steps ) {
- if ( this._start() ) {
- this._spin( (steps || 1) * -this.options.step );
- this._stop();
- }
- },
-
- pageUp: modifier(function( pages ) {
- this._stepUp( (pages || 1) * this.options.page );
- }),
-
- pageDown: modifier(function( pages ) {
- this._stepDown( (pages || 1) * this.options.page );
- }),
-
- value: function( newVal ) {
- if ( !arguments.length ) {
- return this._parse( this.element.val() );
- }
- modifier( this._value ).call( this, newVal );
- },
-
- widget: function() {
- return this.uiSpinner;
- }
-});
-
-}( jQuery ) );
-(function( $, undefined ) {
-
-var tabId = 0,
- rhash = /#.*$/;
-
-function getNextTabId() {
- return ++tabId;
-}
-
-function isLocal( anchor ) {
- // support: IE7
- // IE7 doesn't normalize the href property when set via script (#9317)
- anchor = anchor.cloneNode( false );
-
- return anchor.hash.length > 1 &&
- decodeURIComponent( anchor.href.replace( rhash, "" ) ) ===
- decodeURIComponent( location.href.replace( rhash, "" ) );
-}
-
-$.widget( "ui.tabs", {
- version: "1.10.4",
- delay: 300,
- options: {
- active: null,
- collapsible: false,
- event: "click",
- heightStyle: "content",
- hide: null,
- show: null,
-
- // callbacks
- activate: null,
- beforeActivate: null,
- beforeLoad: null,
- load: null
- },
-
- _create: function() {
- var that = this,
- options = this.options;
-
- this.running = false;
-
- this.element
- .addClass( "ui-tabs ui-widget ui-widget-content ui-corner-all" )
- .toggleClass( "ui-tabs-collapsible", options.collapsible )
- // Prevent users from focusing disabled tabs via click
- .delegate( ".ui-tabs-nav > li", "mousedown" + this.eventNamespace, function( event ) {
- if ( $( this ).is( ".ui-state-disabled" ) ) {
- event.preventDefault();
- }
- })
- // support: IE <9
- // Preventing the default action in mousedown doesn't prevent IE
- // from focusing the element, so if the anchor gets focused, blur.
- // We don't have to worry about focusing the previously focused
- // element since clicking on a non-focusable element should focus
- // the body anyway.
- .delegate( ".ui-tabs-anchor", "focus" + this.eventNamespace, function() {
- if ( $( this ).closest( "li" ).is( ".ui-state-disabled" ) ) {
- this.blur();
- }
- });
-
- this._processTabs();
- options.active = this._initialActive();
-
- // Take disabling tabs via class attribute from HTML
- // into account and update option properly.
- if ( $.isArray( options.disabled ) ) {
- options.disabled = $.unique( options.disabled.concat(
- $.map( this.tabs.filter( ".ui-state-disabled" ), function( li ) {
- return that.tabs.index( li );
- })
- ) ).sort();
- }
-
- // check for length avoids error when initializing empty list
- if ( this.options.active !== false && this.anchors.length ) {
- this.active = this._findActive( options.active );
- } else {
- this.active = $();
- }
-
- this._refresh();
-
- if ( this.active.length ) {
- this.load( options.active );
- }
- },
-
- _initialActive: function() {
- var active = this.options.active,
- collapsible = this.options.collapsible,
- locationHash = location.hash.substring( 1 );
-
- if ( active === null ) {
- // check the fragment identifier in the URL
- if ( locationHash ) {
- this.tabs.each(function( i, tab ) {
- if ( $( tab ).attr( "aria-controls" ) === locationHash ) {
- active = i;
- return false;
- }
- });
- }
-
- // check for a tab marked active via a class
- if ( active === null ) {
- active = this.tabs.index( this.tabs.filter( ".ui-tabs-active" ) );
- }
-
- // no active tab, set to false
- if ( active === null || active === -1 ) {
- active = this.tabs.length ? 0 : false;
- }
- }
-
- // handle numbers: negative, out of range
- if ( active !== false ) {
- active = this.tabs.index( this.tabs.eq( active ) );
- if ( active === -1 ) {
- active = collapsible ? false : 0;
- }
- }
-
- // don't allow collapsible: false and active: false
- if ( !collapsible && active === false && this.anchors.length ) {
- active = 0;
- }
-
- return active;
- },
-
- _getCreateEventData: function() {
- return {
- tab: this.active,
- panel: !this.active.length ? $() : this._getPanelForTab( this.active )
- };
- },
-
- _tabKeydown: function( event ) {
- var focusedTab = $( this.document[0].activeElement ).closest( "li" ),
- selectedIndex = this.tabs.index( focusedTab ),
- goingForward = true;
-
- if ( this._handlePageNav( event ) ) {
- return;
- }
-
- switch ( event.keyCode ) {
- case $.ui.keyCode.RIGHT:
- case $.ui.keyCode.DOWN:
- selectedIndex++;
- break;
- case $.ui.keyCode.UP:
- case $.ui.keyCode.LEFT:
- goingForward = false;
- selectedIndex--;
- break;
- case $.ui.keyCode.END:
- selectedIndex = this.anchors.length - 1;
- break;
- case $.ui.keyCode.HOME:
- selectedIndex = 0;
- break;
- case $.ui.keyCode.SPACE:
- // Activate only, no collapsing
- event.preventDefault();
- clearTimeout( this.activating );
- this._activate( selectedIndex );
- return;
- case $.ui.keyCode.ENTER:
- // Toggle (cancel delayed activation, allow collapsing)
- event.preventDefault();
- clearTimeout( this.activating );
- // Determine if we should collapse or activate
- this._activate( selectedIndex === this.options.active ? false : selectedIndex );
- return;
- default:
- return;
- }
-
- // Focus the appropriate tab, based on which key was pressed
- event.preventDefault();
- clearTimeout( this.activating );
- selectedIndex = this._focusNextTab( selectedIndex, goingForward );
-
- // Navigating with control key will prevent automatic activation
- if ( !event.ctrlKey ) {
- // Update aria-selected immediately so that AT think the tab is already selected.
- // Otherwise AT may confuse the user by stating that they need to activate the tab,
- // but the tab will already be activated by the time the announcement finishes.
- focusedTab.attr( "aria-selected", "false" );
- this.tabs.eq( selectedIndex ).attr( "aria-selected", "true" );
-
- this.activating = this._delay(function() {
- this.option( "active", selectedIndex );
- }, this.delay );
- }
- },
-
- _panelKeydown: function( event ) {
- if ( this._handlePageNav( event ) ) {
- return;
- }
-
- // Ctrl+up moves focus to the current tab
- if ( event.ctrlKey && event.keyCode === $.ui.keyCode.UP ) {
- event.preventDefault();
- this.active.focus();
- }
- },
-
- // Alt+page up/down moves focus to the previous/next tab (and activates)
- _handlePageNav: function( event ) {
- if ( event.altKey && event.keyCode === $.ui.keyCode.PAGE_UP ) {
- this._activate( this._focusNextTab( this.options.active - 1, false ) );
- return true;
- }
- if ( event.altKey && event.keyCode === $.ui.keyCode.PAGE_DOWN ) {
- this._activate( this._focusNextTab( this.options.active + 1, true ) );
- return true;
- }
- },
-
- _findNextTab: function( index, goingForward ) {
- var lastTabIndex = this.tabs.length - 1;
-
- function constrain() {
- if ( index > lastTabIndex ) {
- index = 0;
- }
- if ( index < 0 ) {
- index = lastTabIndex;
- }
- return index;
- }
-
- while ( $.inArray( constrain(), this.options.disabled ) !== -1 ) {
- index = goingForward ? index + 1 : index - 1;
- }
-
- return index;
- },
-
- _focusNextTab: function( index, goingForward ) {
- index = this._findNextTab( index, goingForward );
- this.tabs.eq( index ).focus();
- return index;
- },
-
- _setOption: function( key, value ) {
- if ( key === "active" ) {
- // _activate() will handle invalid values and update this.options
- this._activate( value );
- return;
- }
-
- if ( key === "disabled" ) {
- // don't use the widget factory's disabled handling
- this._setupDisabled( value );
- return;
- }
-
- this._super( key, value);
-
- if ( key === "collapsible" ) {
- this.element.toggleClass( "ui-tabs-collapsible", value );
- // Setting collapsible: false while collapsed; open first panel
- if ( !value && this.options.active === false ) {
- this._activate( 0 );
- }
- }
-
- if ( key === "event" ) {
- this._setupEvents( value );
- }
-
- if ( key === "heightStyle" ) {
- this._setupHeightStyle( value );
- }
- },
-
- _tabId: function( tab ) {
- return tab.attr( "aria-controls" ) || "ui-tabs-" + getNextTabId();
- },
-
- _sanitizeSelector: function( hash ) {
- return hash ? hash.replace( /[!"$%&'()*+,.\/:;<=>?@\[\]\^`{|}~]/g, "\\$&" ) : "";
- },
-
- refresh: function() {
- var options = this.options,
- lis = this.tablist.children( ":has(a[href])" );
-
- // get disabled tabs from class attribute from HTML
- // this will get converted to a boolean if needed in _refresh()
- options.disabled = $.map( lis.filter( ".ui-state-disabled" ), function( tab ) {
- return lis.index( tab );
- });
-
- this._processTabs();
-
- // was collapsed or no tabs
- if ( options.active === false || !this.anchors.length ) {
- options.active = false;
- this.active = $();
- // was active, but active tab is gone
- } else if ( this.active.length && !$.contains( this.tablist[ 0 ], this.active[ 0 ] ) ) {
- // all remaining tabs are disabled
- if ( this.tabs.length === options.disabled.length ) {
- options.active = false;
- this.active = $();
- // activate previous tab
- } else {
- this._activate( this._findNextTab( Math.max( 0, options.active - 1 ), false ) );
- }
- // was active, active tab still exists
- } else {
- // make sure active index is correct
- options.active = this.tabs.index( this.active );
- }
-
- this._refresh();
- },
-
- _refresh: function() {
- this._setupDisabled( this.options.disabled );
- this._setupEvents( this.options.event );
- this._setupHeightStyle( this.options.heightStyle );
-
- this.tabs.not( this.active ).attr({
- "aria-selected": "false",
- tabIndex: -1
- });
- this.panels.not( this._getPanelForTab( this.active ) )
- .hide()
- .attr({
- "aria-expanded": "false",
- "aria-hidden": "true"
- });
-
- // Make sure one tab is in the tab order
- if ( !this.active.length ) {
- this.tabs.eq( 0 ).attr( "tabIndex", 0 );
- } else {
- this.active
- .addClass( "ui-tabs-active ui-state-active" )
- .attr({
- "aria-selected": "true",
- tabIndex: 0
- });
- this._getPanelForTab( this.active )
- .show()
- .attr({
- "aria-expanded": "true",
- "aria-hidden": "false"
- });
- }
- },
-
- _processTabs: function() {
- var that = this;
-
- this.tablist = this._getList()
- .addClass( "ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all" )
- .attr( "role", "tablist" );
-
- this.tabs = this.tablist.find( "> li:has(a[href])" )
- .addClass( "ui-state-default ui-corner-top" )
- .attr({
- role: "tab",
- tabIndex: -1
- });
-
- this.anchors = this.tabs.map(function() {
- return $( "a", this )[ 0 ];
- })
- .addClass( "ui-tabs-anchor" )
- .attr({
- role: "presentation",
- tabIndex: -1
- });
-
- this.panels = $();
-
- this.anchors.each(function( i, anchor ) {
- var selector, panel, panelId,
- anchorId = $( anchor ).uniqueId().attr( "id" ),
- tab = $( anchor ).closest( "li" ),
- originalAriaControls = tab.attr( "aria-controls" );
-
- // inline tab
- if ( isLocal( anchor ) ) {
- selector = anchor.hash;
- panel = that.element.find( that._sanitizeSelector( selector ) );
- // remote tab
- } else {
- panelId = that._tabId( tab );
- selector = "#" + panelId;
- panel = that.element.find( selector );
- if ( !panel.length ) {
- panel = that._createPanel( panelId );
- panel.insertAfter( that.panels[ i - 1 ] || that.tablist );
- }
- panel.attr( "aria-live", "polite" );
- }
-
- if ( panel.length) {
- that.panels = that.panels.add( panel );
- }
- if ( originalAriaControls ) {
- tab.data( "ui-tabs-aria-controls", originalAriaControls );
- }
- tab.attr({
- "aria-controls": selector.substring( 1 ),
- "aria-labelledby": anchorId
- });
- panel.attr( "aria-labelledby", anchorId );
- });
-
- this.panels
- .addClass( "ui-tabs-panel ui-widget-content ui-corner-bottom" )
- .attr( "role", "tabpanel" );
- },
-
- // allow overriding how to find the list for rare usage scenarios (#7715)
- _getList: function() {
- return this.tablist || this.element.find( "ol,ul" ).eq( 0 );
- },
-
- _createPanel: function( id ) {
- return $( "<div>" )
- .attr( "id", id )
- .addClass( "ui-tabs-panel ui-widget-content ui-corner-bottom" )
- .data( "ui-tabs-destroy", true );
- },
-
- _setupDisabled: function( disabled ) {
- if ( $.isArray( disabled ) ) {
- if ( !disabled.length ) {
- disabled = false;
- } else if ( disabled.length === this.anchors.length ) {
- disabled = true;
- }
- }
-
- // disable tabs
- for ( var i = 0, li; ( li = this.tabs[ i ] ); i++ ) {
- if ( disabled === true || $.inArray( i, disabled ) !== -1 ) {
- $( li )
- .addClass( "ui-state-disabled" )
- .attr( "aria-disabled", "true" );
- } else {
- $( li )
- .removeClass( "ui-state-disabled" )
- .removeAttr( "aria-disabled" );
- }
- }
-
- this.options.disabled = disabled;
- },
-
- _setupEvents: function( event ) {
- var events = {
- click: function( event ) {
- event.preventDefault();
- }
- };
- if ( event ) {
- $.each( event.split(" "), function( index, eventName ) {
- events[ eventName ] = "_eventHandler";
- });
- }
-
- this._off( this.anchors.add( this.tabs ).add( this.panels ) );
- this._on( this.anchors, events );
- this._on( this.tabs, { keydown: "_tabKeydown" } );
- this._on( this.panels, { keydown: "_panelKeydown" } );
-
- this._focusable( this.tabs );
- this._hoverable( this.tabs );
- },
-
- _setupHeightStyle: function( heightStyle ) {
- var maxHeight,
- parent = this.element.parent();
-
- if ( heightStyle === "fill" ) {
- maxHeight = parent.height();
- maxHeight -= this.element.outerHeight() - this.element.height();
-
- this.element.siblings( ":visible" ).each(function() {
- var elem = $( this ),
- position = elem.css( "position" );
-
- if ( position === "absolute" || position === "fixed" ) {
- return;
- }
- maxHeight -= elem.outerHeight( true );
- });
-
- this.element.children().not( this.panels ).each(function() {
- maxHeight -= $( this ).outerHeight( true );
- });
-
- this.panels.each(function() {
- $( this ).height( Math.max( 0, maxHeight -
- $( this ).innerHeight() + $( this ).height() ) );
- })
- .css( "overflow", "auto" );
- } else if ( heightStyle === "auto" ) {
- maxHeight = 0;
- this.panels.each(function() {
- maxHeight = Math.max( maxHeight, $( this ).height( "" ).height() );
- }).height( maxHeight );
- }
- },
-
- _eventHandler: function( event ) {
- var options = this.options,
- active = this.active,
- anchor = $( event.currentTarget ),
- tab = anchor.closest( "li" ),
- clickedIsActive = tab[ 0 ] === active[ 0 ],
- collapsing = clickedIsActive && options.collapsible,
- toShow = collapsing ? $() : this._getPanelForTab( tab ),
- toHide = !active.length ? $() : this._getPanelForTab( active ),
- eventData = {
- oldTab: active,
- oldPanel: toHide,
- newTab: collapsing ? $() : tab,
- newPanel: toShow
- };
-
- event.preventDefault();
-
- if ( tab.hasClass( "ui-state-disabled" ) ||
- // tab is already loading
- tab.hasClass( "ui-tabs-loading" ) ||
- // can't switch durning an animation
- this.running ||
- // click on active header, but not collapsible
- ( clickedIsActive && !options.collapsible ) ||
- // allow canceling activation
- ( this._trigger( "beforeActivate", event, eventData ) === false ) ) {
- return;
- }
-
- options.active = collapsing ? false : this.tabs.index( tab );
-
- this.active = clickedIsActive ? $() : tab;
- if ( this.xhr ) {
- this.xhr.abort();
- }
-
- if ( !toHide.length && !toShow.length ) {
- $.error( "jQuery UI Tabs: Mismatching fragment identifier." );
- }
-
- if ( toShow.length ) {
- this.load( this.tabs.index( tab ), event );
- }
- this._toggle( event, eventData );
- },
-
- // handles show/hide for selecting tabs
- _toggle: function( event, eventData ) {
- var that = this,
- toShow = eventData.newPanel,
- toHide = eventData.oldPanel;
-
- this.running = true;
-
- function complete() {
- that.running = false;
- that._trigger( "activate", event, eventData );
- }
-
- function show() {
- eventData.newTab.closest( "li" ).addClass( "ui-tabs-active ui-state-active" );
-
- if ( toShow.length && that.options.show ) {
- that._show( toShow, that.options.show, complete );
- } else {
- toShow.show();
- complete();
- }
- }
-
- // start out by hiding, then showing, then completing
- if ( toHide.length && this.options.hide ) {
- this._hide( toHide, this.options.hide, function() {
- eventData.oldTab.closest( "li" ).removeClass( "ui-tabs-active ui-state-active" );
- show();
- });
- } else {
- eventData.oldTab.closest( "li" ).removeClass( "ui-tabs-active ui-state-active" );
- toHide.hide();
- show();
- }
-
- toHide.attr({
- "aria-expanded": "false",
- "aria-hidden": "true"
- });
- eventData.oldTab.attr( "aria-selected", "false" );
- // If we're switching tabs, remove the old tab from the tab order.
- // If we're opening from collapsed state, remove the previous tab from the tab order.
- // If we're collapsing, then keep the collapsing tab in the tab order.
- if ( toShow.length && toHide.length ) {
- eventData.oldTab.attr( "tabIndex", -1 );
- } else if ( toShow.length ) {
- this.tabs.filter(function() {
- return $( this ).attr( "tabIndex" ) === 0;
- })
- .attr( "tabIndex", -1 );
- }
-
- toShow.attr({
- "aria-expanded": "true",
- "aria-hidden": "false"
- });
- eventData.newTab.attr({
- "aria-selected": "true",
- tabIndex: 0
- });
- },
-
- _activate: function( index ) {
- var anchor,
- active = this._findActive( index );
-
- // trying to activate the already active panel
- if ( active[ 0 ] === this.active[ 0 ] ) {
- return;
- }
-
- // trying to collapse, simulate a click on the current active header
- if ( !active.length ) {
- active = this.active;
- }
-
- anchor = active.find( ".ui-tabs-anchor" )[ 0 ];
- this._eventHandler({
- target: anchor,
- currentTarget: anchor,
- preventDefault: $.noop
- });
- },
-
- _findActive: function( index ) {
- return index === false ? $() : this.tabs.eq( index );
- },
-
- _getIndex: function( index ) {
- // meta-function to give users option to provide a href string instead of a numerical index.
- if ( typeof index === "string" ) {
- index = this.anchors.index( this.anchors.filter( "[href$='" + index + "']" ) );
- }
-
- return index;
- },
-
- _destroy: function() {
- if ( this.xhr ) {
- this.xhr.abort();
- }
-
- this.element.removeClass( "ui-tabs ui-widget ui-widget-content ui-corner-all ui-tabs-collapsible" );
-
- this.tablist
- .removeClass( "ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all" )
- .removeAttr( "role" );
-
- this.anchors
- .removeClass( "ui-tabs-anchor" )
- .removeAttr( "role" )
- .removeAttr( "tabIndex" )
- .removeUniqueId();
-
- this.tabs.add( this.panels ).each(function() {
- if ( $.data( this, "ui-tabs-destroy" ) ) {
- $( this ).remove();
- } else {
- $( this )
- .removeClass( "ui-state-default ui-state-active ui-state-disabled " +
- "ui-corner-top ui-corner-bottom ui-widget-content ui-tabs-active ui-tabs-panel" )
- .removeAttr( "tabIndex" )
- .removeAttr( "aria-live" )
- .removeAttr( "aria-busy" )
- .removeAttr( "aria-selected" )
- .removeAttr( "aria-labelledby" )
- .removeAttr( "aria-hidden" )
- .removeAttr( "aria-expanded" )
- .removeAttr( "role" );
- }
- });
-
- this.tabs.each(function() {
- var li = $( this ),
- prev = li.data( "ui-tabs-aria-controls" );
- if ( prev ) {
- li
- .attr( "aria-controls", prev )
- .removeData( "ui-tabs-aria-controls" );
- } else {
- li.removeAttr( "aria-controls" );
- }
- });
-
- this.panels.show();
-
- if ( this.options.heightStyle !== "content" ) {
- this.panels.css( "height", "" );
- }
- },
-
- enable: function( index ) {
- var disabled = this.options.disabled;
- if ( disabled === false ) {
- return;
- }
-
- if ( index === undefined ) {
- disabled = false;
- } else {
- index = this._getIndex( index );
- if ( $.isArray( disabled ) ) {
- disabled = $.map( disabled, function( num ) {
- return num !== index ? num : null;
- });
- } else {
- disabled = $.map( this.tabs, function( li, num ) {
- return num !== index ? num : null;
- });
- }
- }
- this._setupDisabled( disabled );
- },
-
- disable: function( index ) {
- var disabled = this.options.disabled;
- if ( disabled === true ) {
- return;
- }
-
- if ( index === undefined ) {
- disabled = true;
- } else {
- index = this._getIndex( index );
- if ( $.inArray( index, disabled ) !== -1 ) {
- return;
- }
- if ( $.isArray( disabled ) ) {
- disabled = $.merge( [ index ], disabled ).sort();
- } else {
- disabled = [ index ];
- }
- }
- this._setupDisabled( disabled );
- },
-
- load: function( index, event ) {
- index = this._getIndex( index );
- var that = this,
- tab = this.tabs.eq( index ),
- anchor = tab.find( ".ui-tabs-anchor" ),
- panel = this._getPanelForTab( tab ),
- eventData = {
- tab: tab,
- panel: panel
- };
-
- // not remote
- if ( isLocal( anchor[ 0 ] ) ) {
- return;
- }
-
- this.xhr = $.ajax( this._ajaxSettings( anchor, event, eventData ) );
-
- // support: jQuery <1.8
- // jQuery <1.8 returns false if the request is canceled in beforeSend,
- // but as of 1.8, $.ajax() always returns a jqXHR object.
- if ( this.xhr && this.xhr.statusText !== "canceled" ) {
- tab.addClass( "ui-tabs-loading" );
- panel.attr( "aria-busy", "true" );
-
- this.xhr
- .success(function( response ) {
- // support: jQuery <1.8
- // http://bugs.jquery.com/ticket/11778
- setTimeout(function() {
- panel.html( response );
- that._trigger( "load", event, eventData );
- }, 1 );
- })
- .complete(function( jqXHR, status ) {
- // support: jQuery <1.8
- // http://bugs.jquery.com/ticket/11778
- setTimeout(function() {
- if ( status === "abort" ) {
- that.panels.stop( false, true );
- }
-
- tab.removeClass( "ui-tabs-loading" );
- panel.removeAttr( "aria-busy" );
-
- if ( jqXHR === that.xhr ) {
- delete that.xhr;
- }
- }, 1 );
- });
- }
- },
-
- _ajaxSettings: function( anchor, event, eventData ) {
- var that = this;
- return {
- url: anchor.attr( "href" ),
- beforeSend: function( jqXHR, settings ) {
- return that._trigger( "beforeLoad", event,
- $.extend( { jqXHR : jqXHR, ajaxSettings: settings }, eventData ) );
- }
- };
- },
-
- _getPanelForTab: function( tab ) {
- var id = $( tab ).attr( "aria-controls" );
- return this.element.find( this._sanitizeSelector( "#" + id ) );
- }
-});
-
-})( jQuery );
-(function( $ ) {
-
-var increments = 0;
-
-function addDescribedBy( elem, id ) {
- var describedby = (elem.attr( "aria-describedby" ) || "").split( /\s+/ );
- describedby.push( id );
- elem
- .data( "ui-tooltip-id", id )
- .attr( "aria-describedby", $.trim( describedby.join( " " ) ) );
-}
-
-function removeDescribedBy( elem ) {
- var id = elem.data( "ui-tooltip-id" ),
- describedby = (elem.attr( "aria-describedby" ) || "").split( /\s+/ ),
- index = $.inArray( id, describedby );
- if ( index !== -1 ) {
- describedby.splice( index, 1 );
- }
-
- elem.removeData( "ui-tooltip-id" );
- describedby = $.trim( describedby.join( " " ) );
- if ( describedby ) {
- elem.attr( "aria-describedby", describedby );
- } else {
- elem.removeAttr( "aria-describedby" );
- }
-}
-
-$.widget( "ui.tooltip", {
- version: "1.10.4",
- options: {
- content: function() {
- // support: IE<9, Opera in jQuery <1.7
- // .text() can't accept undefined, so coerce to a string
- var title = $( this ).attr( "title" ) || "";
- // Escape title, since we're going from an attribute to raw HTML
- return $( "<a>" ).text( title ).html();
- },
- hide: true,
- // Disabled elements have inconsistent behavior across browsers (#8661)
- items: "[title]:not([disabled])",
- position: {
- my: "left top+15",
- at: "left bottom",
- collision: "flipfit flip"
- },
- show: true,
- tooltipClass: null,
- track: false,
-
- // callbacks
- close: null,
- open: null
- },
-
- _create: function() {
- this._on({
- mouseover: "open",
- focusin: "open"
- });
-
- // IDs of generated tooltips, needed for destroy
- this.tooltips = {};
- // IDs of parent tooltips where we removed the title attribute
- this.parents = {};
-
- if ( this.options.disabled ) {
- this._disable();
- }
- },
-
- _setOption: function( key, value ) {
- var that = this;
-
- if ( key === "disabled" ) {
- this[ value ? "_disable" : "_enable" ]();
- this.options[ key ] = value;
- // disable element style changes
- return;
- }
-
- this._super( key, value );
-
- if ( key === "content" ) {
- $.each( this.tooltips, function( id, element ) {
- that._updateContent( element );
- });
- }
- },
-
- _disable: function() {
- var that = this;
-
- // close open tooltips
- $.each( this.tooltips, function( id, element ) {
- var event = $.Event( "blur" );
- event.target = event.currentTarget = element[0];
- that.close( event, true );
- });
-
- // remove title attributes to prevent native tooltips
- this.element.find( this.options.items ).addBack().each(function() {
- var element = $( this );
- if ( element.is( "[title]" ) ) {
- element
- .data( "ui-tooltip-title", element.attr( "title" ) )
- .attr( "title", "" );
- }
- });
- },
-
- _enable: function() {
- // restore title attributes
- this.element.find( this.options.items ).addBack().each(function() {
- var element = $( this );
- if ( element.data( "ui-tooltip-title" ) ) {
- element.attr( "title", element.data( "ui-tooltip-title" ) );
- }
- });
- },
-
- open: function( event ) {
- var that = this,
- target = $( event ? event.target : this.element )
- // we need closest here due to mouseover bubbling,
- // but always pointing at the same event target
- .closest( this.options.items );
-
- // No element to show a tooltip for or the tooltip is already open
- if ( !target.length || target.data( "ui-tooltip-id" ) ) {
- return;
- }
-
- if ( target.attr( "title" ) ) {
- target.data( "ui-tooltip-title", target.attr( "title" ) );
- }
-
- target.data( "ui-tooltip-open", true );
-
- // kill parent tooltips, custom or native, for hover
- if ( event && event.type === "mouseover" ) {
- target.parents().each(function() {
- var parent = $( this ),
- blurEvent;
- if ( parent.data( "ui-tooltip-open" ) ) {
- blurEvent = $.Event( "blur" );
- blurEvent.target = blurEvent.currentTarget = this;
- that.close( blurEvent, true );
- }
- if ( parent.attr( "title" ) ) {
- parent.uniqueId();
- that.parents[ this.id ] = {
- element: this,
- title: parent.attr( "title" )
- };
- parent.attr( "title", "" );
- }
- });
- }
-
- this._updateContent( target, event );
- },
-
- _updateContent: function( target, event ) {
- var content,
- contentOption = this.options.content,
- that = this,
- eventType = event ? event.type : null;
-
- if ( typeof contentOption === "string" ) {
- return this._open( event, target, contentOption );
- }
-
- content = contentOption.call( target[0], function( response ) {
- // ignore async response if tooltip was closed already
- if ( !target.data( "ui-tooltip-open" ) ) {
- return;
- }
- // IE may instantly serve a cached response for ajax requests
- // delay this call to _open so the other call to _open runs first
- that._delay(function() {
- // jQuery creates a special event for focusin when it doesn't
- // exist natively. To improve performance, the native event
- // object is reused and the type is changed. Therefore, we can't
- // rely on the type being correct after the event finished
- // bubbling, so we set it back to the previous value. (#8740)
- if ( event ) {
- event.type = eventType;
- }
- this._open( event, target, response );
- });
- });
- if ( content ) {
- this._open( event, target, content );
- }
- },
-
- _open: function( event, target, content ) {
- var tooltip, events, delayedShow,
- positionOption = $.extend( {}, this.options.position );
-
- if ( !content ) {
- return;
- }
-
- // Content can be updated multiple times. If the tooltip already
- // exists, then just update the content and bail.
- tooltip = this._find( target );
- if ( tooltip.length ) {
- tooltip.find( ".ui-tooltip-content" ).html( content );
- return;
- }
-
- // if we have a title, clear it to prevent the native tooltip
- // we have to check first to avoid defining a title if none exists
- // (we don't want to cause an element to start matching [title])
- //
- // We use removeAttr only for key events, to allow IE to export the correct
- // accessible attributes. For mouse events, set to empty string to avoid
- // native tooltip showing up (happens only when removing inside mouseover).
- if ( target.is( "[title]" ) ) {
- if ( event && event.type === "mouseover" ) {
- target.attr( "title", "" );
- } else {
- target.removeAttr( "title" );
- }
- }
-
- tooltip = this._tooltip( target );
- addDescribedBy( target, tooltip.attr( "id" ) );
- tooltip.find( ".ui-tooltip-content" ).html( content );
-
- function position( event ) {
- positionOption.of = event;
- if ( tooltip.is( ":hidden" ) ) {
- return;
- }
- tooltip.position( positionOption );
- }
- if ( this.options.track && event && /^mouse/.test( event.type ) ) {
- this._on( this.document, {
- mousemove: position
- });
- // trigger once to override element-relative positioning
- position( event );
- } else {
- tooltip.position( $.extend({
- of: target
- }, this.options.position ) );
- }
-
- tooltip.hide();
-
- this._show( tooltip, this.options.show );
- // Handle tracking tooltips that are shown with a delay (#8644). As soon
- // as the tooltip is visible, position the tooltip using the most recent
- // event.
- if ( this.options.show && this.options.show.delay ) {
- delayedShow = this.delayedShow = setInterval(function() {
- if ( tooltip.is( ":visible" ) ) {
- position( positionOption.of );
- clearInterval( delayedShow );
- }
- }, $.fx.interval );
- }
-
- this._trigger( "open", event, { tooltip: tooltip } );
-
- events = {
- keyup: function( event ) {
- if ( event.keyCode === $.ui.keyCode.ESCAPE ) {
- var fakeEvent = $.Event(event);
- fakeEvent.currentTarget = target[0];
- this.close( fakeEvent, true );
- }
- },
- remove: function() {
- this._removeTooltip( tooltip );
- }
- };
- if ( !event || event.type === "mouseover" ) {
- events.mouseleave = "close";
- }
- if ( !event || event.type === "focusin" ) {
- events.focusout = "close";
- }
- this._on( true, target, events );
- },
-
- close: function( event ) {
- var that = this,
- target = $( event ? event.currentTarget : this.element ),
- tooltip = this._find( target );
-
- // disabling closes the tooltip, so we need to track when we're closing
- // to avoid an infinite loop in case the tooltip becomes disabled on close
- if ( this.closing ) {
- return;
- }
-
- // Clear the interval for delayed tracking tooltips
- clearInterval( this.delayedShow );
-
- // only set title if we had one before (see comment in _open())
- if ( target.data( "ui-tooltip-title" ) ) {
- target.attr( "title", target.data( "ui-tooltip-title" ) );
- }
-
- removeDescribedBy( target );
-
- tooltip.stop( true );
- this._hide( tooltip, this.options.hide, function() {
- that._removeTooltip( $( this ) );
- });
-
- target.removeData( "ui-tooltip-open" );
- this._off( target, "mouseleave focusout keyup" );
- // Remove 'remove' binding only on delegated targets
- if ( target[0] !== this.element[0] ) {
- this._off( target, "remove" );
- }
- this._off( this.document, "mousemove" );
-
- if ( event && event.type === "mouseleave" ) {
- $.each( this.parents, function( id, parent ) {
- $( parent.element ).attr( "title", parent.title );
- delete that.parents[ id ];
- });
- }
-
- this.closing = true;
- this._trigger( "close", event, { tooltip: tooltip } );
- this.closing = false;
- },
-
- _tooltip: function( element ) {
- var id = "ui-tooltip-" + increments++,
- tooltip = $( "<div>" )
- .attr({
- id: id,
- role: "tooltip"
- })
- .addClass( "ui-tooltip ui-widget ui-corner-all ui-widget-content " +
- ( this.options.tooltipClass || "" ) );
- $( "<div>" )
- .addClass( "ui-tooltip-content" )
- .appendTo( tooltip );
- tooltip.appendTo( this.document[0].body );
- this.tooltips[ id ] = element;
- return tooltip;
- },
-
- _find: function( target ) {
- var id = target.data( "ui-tooltip-id" );
- return id ? $( "#" + id ) : $();
- },
-
- _removeTooltip: function( tooltip ) {
- tooltip.remove();
- delete this.tooltips[ tooltip.attr( "id" ) ];
- },
-
- _destroy: function() {
- var that = this;
-
- // close open tooltips
- $.each( this.tooltips, function( id, element ) {
- // Delegate to close method to handle common cleanup
- var event = $.Event( "blur" );
- event.target = event.currentTarget = element[0];
- that.close( event, true );
-
- // Remove immediately; destroying an open tooltip doesn't use the
- // hide animation
- $( "#" + id ).remove();
-
- // Restore the title
- if ( element.data( "ui-tooltip-title" ) ) {
- element.attr( "title", element.data( "ui-tooltip-title" ) );
- element.removeData( "ui-tooltip-title" );
- }
- });
- }
-});
-
-}( jQuery ) );
-(function($, undefined) {
-
-var dataSpace = "ui-effects-";
-
-$.effects = {
- effect: {}
-};
-
-/*!
- * jQuery Color Animations v2.1.2
- * https://github.com/jquery/jquery-color
- *
- * Copyright 2013 jQuery Foundation and other contributors
- * Released under the MIT license.
- * http://jquery.org/license
- *
- * Date: Wed Jan 16 08:47:09 2013 -0600
- */
-(function( jQuery, undefined ) {
-
- var stepHooks = "backgroundColor borderBottomColor borderLeftColor borderRightColor borderTopColor color columnRuleColor outlineColor textDecorationColor textEmphasisColor",
-
- // plusequals test for += 100 -= 100
- rplusequals = /^([\-+])=\s*(\d+\.?\d*)/,
- // a set of RE's that can match strings and generate color tuples.
- stringParsers = [{
- re: /rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,
- parse: function( execResult ) {
- return [
- execResult[ 1 ],
- execResult[ 2 ],
- execResult[ 3 ],
- execResult[ 4 ]
- ];
- }
- }, {
- re: /rgba?\(\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,
- parse: function( execResult ) {
- return [
- execResult[ 1 ] * 2.55,
- execResult[ 2 ] * 2.55,
- execResult[ 3 ] * 2.55,
- execResult[ 4 ]
- ];
- }
- }, {
- // this regex ignores A-F because it's compared against an already lowercased string
- re: /#([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})/,
- parse: function( execResult ) {
- return [
- parseInt( execResult[ 1 ], 16 ),
- parseInt( execResult[ 2 ], 16 ),
- parseInt( execResult[ 3 ], 16 )
- ];
- }
- }, {
- // this regex ignores A-F because it's compared against an already lowercased string
- re: /#([a-f0-9])([a-f0-9])([a-f0-9])/,
- parse: function( execResult ) {
- return [
- parseInt( execResult[ 1 ] + execResult[ 1 ], 16 ),
- parseInt( execResult[ 2 ] + execResult[ 2 ], 16 ),
- parseInt( execResult[ 3 ] + execResult[ 3 ], 16 )
- ];
- }
- }, {
- re: /hsla?\(\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,
- space: "hsla",
- parse: function( execResult ) {
- return [
- execResult[ 1 ],
- execResult[ 2 ] / 100,
- execResult[ 3 ] / 100,
- execResult[ 4 ]
- ];
- }
- }],
-
- // jQuery.Color( )
- color = jQuery.Color = function( color, green, blue, alpha ) {
- return new jQuery.Color.fn.parse( color, green, blue, alpha );
- },
- spaces = {
- rgba: {
- props: {
- red: {
- idx: 0,
- type: "byte"
- },
- green: {
- idx: 1,
- type: "byte"
- },
- blue: {
- idx: 2,
- type: "byte"
- }
- }
- },
-
- hsla: {
- props: {
- hue: {
- idx: 0,
- type: "degrees"
- },
- saturation: {
- idx: 1,
- type: "percent"
- },
- lightness: {
- idx: 2,
- type: "percent"
- }
- }
- }
- },
- propTypes = {
- "byte": {
- floor: true,
- max: 255
- },
- "percent": {
- max: 1
- },
- "degrees": {
- mod: 360,
- floor: true
- }
- },
- support = color.support = {},
-
- // element for support tests
- supportElem = jQuery( "<p>" )[ 0 ],
-
- // colors = jQuery.Color.names
- colors,
-
- // local aliases of functions called often
- each = jQuery.each;
-
-// determine rgba support immediately
-supportElem.style.cssText = "background-color:rgba(1,1,1,.5)";
-support.rgba = supportElem.style.backgroundColor.indexOf( "rgba" ) > -1;
-
-// define cache name and alpha properties
-// for rgba and hsla spaces
-each( spaces, function( spaceName, space ) {
- space.cache = "_" + spaceName;
- space.props.alpha = {
- idx: 3,
- type: "percent",
- def: 1
- };
-});
-
-function clamp( value, prop, allowEmpty ) {
- var type = propTypes[ prop.type ] || {};
-
- if ( value == null ) {
- return (allowEmpty || !prop.def) ? null : prop.def;
- }
-
- // ~~ is an short way of doing floor for positive numbers
- value = type.floor ? ~~value : parseFloat( value );
-
- // IE will pass in empty strings as value for alpha,
- // which will hit this case
- if ( isNaN( value ) ) {
- return prop.def;
- }
-
- if ( type.mod ) {
- // we add mod before modding to make sure that negatives values
- // get converted properly: -10 -> 350
- return (value + type.mod) % type.mod;
- }
-
- // for now all property types without mod have min and max
- return 0 > value ? 0 : type.max < value ? type.max : value;
-}
-
-function stringParse( string ) {
- var inst = color(),
- rgba = inst._rgba = [];
-
- string = string.toLowerCase();
-
- each( stringParsers, function( i, parser ) {
- var parsed,
- match = parser.re.exec( string ),
- values = match && parser.parse( match ),
- spaceName = parser.space || "rgba";
-
- if ( values ) {
- parsed = inst[ spaceName ]( values );
-
- // if this was an rgba parse the assignment might happen twice
- // oh well....
- inst[ spaces[ spaceName ].cache ] = parsed[ spaces[ spaceName ].cache ];
- rgba = inst._rgba = parsed._rgba;
-
- // exit each( stringParsers ) here because we matched
- return false;
- }
- });
-
- // Found a stringParser that handled it
- if ( rgba.length ) {
-
- // if this came from a parsed string, force "transparent" when alpha is 0
- // chrome, (and maybe others) return "transparent" as rgba(0,0,0,0)
- if ( rgba.join() === "0,0,0,0" ) {
- jQuery.extend( rgba, colors.transparent );
- }
- return inst;
- }
-
- // named colors
- return colors[ string ];
-}
-
-color.fn = jQuery.extend( color.prototype, {
- parse: function( red, green, blue, alpha ) {
- if ( red === undefined ) {
- this._rgba = [ null, null, null, null ];
- return this;
- }
- if ( red.jquery || red.nodeType ) {
- red = jQuery( red ).css( green );
- green = undefined;
- }
-
- var inst = this,
- type = jQuery.type( red ),
- rgba = this._rgba = [];
-
- // more than 1 argument specified - assume ( red, green, blue, alpha )
- if ( green !== undefined ) {
- red = [ red, green, blue, alpha ];
- type = "array";
- }
-
- if ( type === "string" ) {
- return this.parse( stringParse( red ) || colors._default );
- }
-
- if ( type === "array" ) {
- each( spaces.rgba.props, function( key, prop ) {
- rgba[ prop.idx ] = clamp( red[ prop.idx ], prop );
- });
- return this;
- }
-
- if ( type === "object" ) {
- if ( red instanceof color ) {
- each( spaces, function( spaceName, space ) {
- if ( red[ space.cache ] ) {
- inst[ space.cache ] = red[ space.cache ].slice();
- }
- });
- } else {
- each( spaces, function( spaceName, space ) {
- var cache = space.cache;
- each( space.props, function( key, prop ) {
-
- // if the cache doesn't exist, and we know how to convert
- if ( !inst[ cache ] && space.to ) {
-
- // if the value was null, we don't need to copy it
- // if the key was alpha, we don't need to copy it either
- if ( key === "alpha" || red[ key ] == null ) {
- return;
- }
- inst[ cache ] = space.to( inst._rgba );
- }
-
- // this is the only case where we allow nulls for ALL properties.
- // call clamp with alwaysAllowEmpty
- inst[ cache ][ prop.idx ] = clamp( red[ key ], prop, true );
- });
-
- // everything defined but alpha?
- if ( inst[ cache ] && jQuery.inArray( null, inst[ cache ].slice( 0, 3 ) ) < 0 ) {
- // use the default of 1
- inst[ cache ][ 3 ] = 1;
- if ( space.from ) {
- inst._rgba = space.from( inst[ cache ] );
- }
- }
- });
- }
- return this;
- }
- },
- is: function( compare ) {
- var is = color( compare ),
- same = true,
- inst = this;
-
- each( spaces, function( _, space ) {
- var localCache,
- isCache = is[ space.cache ];
- if (isCache) {
- localCache = inst[ space.cache ] || space.to && space.to( inst._rgba ) || [];
- each( space.props, function( _, prop ) {
- if ( isCache[ prop.idx ] != null ) {
- same = ( isCache[ prop.idx ] === localCache[ prop.idx ] );
- return same;
- }
- });
- }
- return same;
- });
- return same;
- },
- _space: function() {
- var used = [],
- inst = this;
- each( spaces, function( spaceName, space ) {
- if ( inst[ space.cache ] ) {
- used.push( spaceName );
- }
- });
- return used.pop();
- },
- transition: function( other, distance ) {
- var end = color( other ),
- spaceName = end._space(),
- space = spaces[ spaceName ],
- startColor = this.alpha() === 0 ? color( "transparent" ) : this,
- start = startColor[ space.cache ] || space.to( startColor._rgba ),
- result = start.slice();
-
- end = end[ space.cache ];
- each( space.props, function( key, prop ) {
- var index = prop.idx,
- startValue = start[ index ],
- endValue = end[ index ],
- type = propTypes[ prop.type ] || {};
-
- // if null, don't override start value
- if ( endValue === null ) {
- return;
- }
- // if null - use end
- if ( startValue === null ) {
- result[ index ] = endValue;
- } else {
- if ( type.mod ) {
- if ( endValue - startValue > type.mod / 2 ) {
- startValue += type.mod;
- } else if ( startValue - endValue > type.mod / 2 ) {
- startValue -= type.mod;
- }
- }
- result[ index ] = clamp( ( endValue - startValue ) * distance + startValue, prop );
- }
- });
- return this[ spaceName ]( result );
- },
- blend: function( opaque ) {
- // if we are already opaque - return ourself
- if ( this._rgba[ 3 ] === 1 ) {
- return this;
- }
-
- var rgb = this._rgba.slice(),
- a = rgb.pop(),
- blend = color( opaque )._rgba;
-
- return color( jQuery.map( rgb, function( v, i ) {
- return ( 1 - a ) * blend[ i ] + a * v;
- }));
- },
- toRgbaString: function() {
- var prefix = "rgba(",
- rgba = jQuery.map( this._rgba, function( v, i ) {
- return v == null ? ( i > 2 ? 1 : 0 ) : v;
- });
-
- if ( rgba[ 3 ] === 1 ) {
- rgba.pop();
- prefix = "rgb(";
- }
-
- return prefix + rgba.join() + ")";
- },
- toHslaString: function() {
- var prefix = "hsla(",
- hsla = jQuery.map( this.hsla(), function( v, i ) {
- if ( v == null ) {
- v = i > 2 ? 1 : 0;
- }
-
- // catch 1 and 2
- if ( i && i < 3 ) {
- v = Math.round( v * 100 ) + "%";
- }
- return v;
- });
-
- if ( hsla[ 3 ] === 1 ) {
- hsla.pop();
- prefix = "hsl(";
- }
- return prefix + hsla.join() + ")";
- },
- toHexString: function( includeAlpha ) {
- var rgba = this._rgba.slice(),
- alpha = rgba.pop();
-
- if ( includeAlpha ) {
- rgba.push( ~~( alpha * 255 ) );
- }
-
- return "#" + jQuery.map( rgba, function( v ) {
-
- // default to 0 when nulls exist
- v = ( v || 0 ).toString( 16 );
- return v.length === 1 ? "0" + v : v;
- }).join("");
- },
- toString: function() {
- return this._rgba[ 3 ] === 0 ? "transparent" : this.toRgbaString();
- }
-});
-color.fn.parse.prototype = color.fn;
-
-// hsla conversions adapted from:
-// https://code.google.com/p/maashaack/source/browse/packages/graphics/trunk/src/graphics/colors/HUE2RGB.as?r=5021
-
-function hue2rgb( p, q, h ) {
- h = ( h + 1 ) % 1;
- if ( h * 6 < 1 ) {
- return p + (q - p) * h * 6;
- }
- if ( h * 2 < 1) {
- return q;
- }
- if ( h * 3 < 2 ) {
- return p + (q - p) * ((2/3) - h) * 6;
- }
- return p;
-}
-
-spaces.hsla.to = function ( rgba ) {
- if ( rgba[ 0 ] == null || rgba[ 1 ] == null || rgba[ 2 ] == null ) {
- return [ null, null, null, rgba[ 3 ] ];
- }
- var r = rgba[ 0 ] / 255,
- g = rgba[ 1 ] / 255,
- b = rgba[ 2 ] / 255,
- a = rgba[ 3 ],
- max = Math.max( r, g, b ),
- min = Math.min( r, g, b ),
- diff = max - min,
- add = max + min,
- l = add * 0.5,
- h, s;
-
- if ( min === max ) {
- h = 0;
- } else if ( r === max ) {
- h = ( 60 * ( g - b ) / diff ) + 360;
- } else if ( g === max ) {
- h = ( 60 * ( b - r ) / diff ) + 120;
- } else {
- h = ( 60 * ( r - g ) / diff ) + 240;
- }
-
- // chroma (diff) == 0 means greyscale which, by definition, saturation = 0%
- // otherwise, saturation is based on the ratio of chroma (diff) to lightness (add)
- if ( diff === 0 ) {
- s = 0;
- } else if ( l <= 0.5 ) {
- s = diff / add;
- } else {
- s = diff / ( 2 - add );
- }
- return [ Math.round(h) % 360, s, l, a == null ? 1 : a ];
-};
-
-spaces.hsla.from = function ( hsla ) {
- if ( hsla[ 0 ] == null || hsla[ 1 ] == null || hsla[ 2 ] == null ) {
- return [ null, null, null, hsla[ 3 ] ];
- }
- var h = hsla[ 0 ] / 360,
- s = hsla[ 1 ],
- l = hsla[ 2 ],
- a = hsla[ 3 ],
- q = l <= 0.5 ? l * ( 1 + s ) : l + s - l * s,
- p = 2 * l - q;
-
- return [
- Math.round( hue2rgb( p, q, h + ( 1 / 3 ) ) * 255 ),
- Math.round( hue2rgb( p, q, h ) * 255 ),
- Math.round( hue2rgb( p, q, h - ( 1 / 3 ) ) * 255 ),
- a
- ];
-};
-
-
-each( spaces, function( spaceName, space ) {
- var props = space.props,
- cache = space.cache,
- to = space.to,
- from = space.from;
-
- // makes rgba() and hsla()
- color.fn[ spaceName ] = function( value ) {
-
- // generate a cache for this space if it doesn't exist
- if ( to && !this[ cache ] ) {
- this[ cache ] = to( this._rgba );
- }
- if ( value === undefined ) {
- return this[ cache ].slice();
- }
-
- var ret,
- type = jQuery.type( value ),
- arr = ( type === "array" || type === "object" ) ? value : arguments,
- local = this[ cache ].slice();
-
- each( props, function( key, prop ) {
- var val = arr[ type === "object" ? key : prop.idx ];
- if ( val == null ) {
- val = local[ prop.idx ];
- }
- local[ prop.idx ] = clamp( val, prop );
- });
-
- if ( from ) {
- ret = color( from( local ) );
- ret[ cache ] = local;
- return ret;
- } else {
- return color( local );
- }
- };
-
- // makes red() green() blue() alpha() hue() saturation() lightness()
- each( props, function( key, prop ) {
- // alpha is included in more than one space
- if ( color.fn[ key ] ) {
- return;
- }
- color.fn[ key ] = function( value ) {
- var vtype = jQuery.type( value ),
- fn = ( key === "alpha" ? ( this._hsla ? "hsla" : "rgba" ) : spaceName ),
- local = this[ fn ](),
- cur = local[ prop.idx ],
- match;
-
- if ( vtype === "undefined" ) {
- return cur;
- }
-
- if ( vtype === "function" ) {
- value = value.call( this, cur );
- vtype = jQuery.type( value );
- }
- if ( value == null && prop.empty ) {
- return this;
- }
- if ( vtype === "string" ) {
- match = rplusequals.exec( value );
- if ( match ) {
- value = cur + parseFloat( match[ 2 ] ) * ( match[ 1 ] === "+" ? 1 : -1 );
- }
- }
- local[ prop.idx ] = value;
- return this[ fn ]( local );
- };
- });
-});
-
-// add cssHook and .fx.step function for each named hook.
-// accept a space separated string of properties
-color.hook = function( hook ) {
- var hooks = hook.split( " " );
- each( hooks, function( i, hook ) {
- jQuery.cssHooks[ hook ] = {
- set: function( elem, value ) {
- var parsed, curElem,
- backgroundColor = "";
-
- if ( value !== "transparent" && ( jQuery.type( value ) !== "string" || ( parsed = stringParse( value ) ) ) ) {
- value = color( parsed || value );
- if ( !support.rgba && value._rgba[ 3 ] !== 1 ) {
- curElem = hook === "backgroundColor" ? elem.parentNode : elem;
- while (
- (backgroundColor === "" || backgroundColor === "transparent") &&
- curElem && curElem.style
- ) {
- try {
- backgroundColor = jQuery.css( curElem, "backgroundColor" );
- curElem = curElem.parentNode;
- } catch ( e ) {
- }
- }
-
- value = value.blend( backgroundColor && backgroundColor !== "transparent" ?
- backgroundColor :
- "_default" );
- }
-
- value = value.toRgbaString();
- }
- try {
- elem.style[ hook ] = value;
- } catch( e ) {
- // wrapped to prevent IE from throwing errors on "invalid" values like 'auto' or 'inherit'
- }
- }
- };
- jQuery.fx.step[ hook ] = function( fx ) {
- if ( !fx.colorInit ) {
- fx.start = color( fx.elem, hook );
- fx.end = color( fx.end );
- fx.colorInit = true;
- }
- jQuery.cssHooks[ hook ].set( fx.elem, fx.start.transition( fx.end, fx.pos ) );
- };
- });
-
-};
-
-color.hook( stepHooks );
-
-jQuery.cssHooks.borderColor = {
- expand: function( value ) {
- var expanded = {};
-
- each( [ "Top", "Right", "Bottom", "Left" ], function( i, part ) {
- expanded[ "border" + part + "Color" ] = value;
- });
- return expanded;
- }
-};
-
-// Basic color names only.
-// Usage of any of the other color names requires adding yourself or including
-// jquery.color.svg-names.js.
-colors = jQuery.Color.names = {
- // 4.1. Basic color keywords
- aqua: "#00ffff",
- black: "#000000",
- blue: "#0000ff",
- fuchsia: "#ff00ff",
- gray: "#808080",
- green: "#008000",
- lime: "#00ff00",
- maroon: "#800000",
- navy: "#000080",
- olive: "#808000",
- purple: "#800080",
- red: "#ff0000",
- silver: "#c0c0c0",
- teal: "#008080",
- white: "#ffffff",
- yellow: "#ffff00",
-
- // 4.2.3. "transparent" color keyword
- transparent: [ null, null, null, 0 ],
-
- _default: "#ffffff"
-};
-
-})( jQuery );
-
-
-/******************************************************************************/
-/****************************** CLASS ANIMATIONS ******************************/
-/******************************************************************************/
-(function() {
-
-var classAnimationActions = [ "add", "remove", "toggle" ],
- shorthandStyles = {
- border: 1,
- borderBottom: 1,
- borderColor: 1,
- borderLeft: 1,
- borderRight: 1,
- borderTop: 1,
- borderWidth: 1,
- margin: 1,
- padding: 1
- };
-
-$.each([ "borderLeftStyle", "borderRightStyle", "borderBottomStyle", "borderTopStyle" ], function( _, prop ) {
- $.fx.step[ prop ] = function( fx ) {
- if ( fx.end !== "none" && !fx.setAttr || fx.pos === 1 && !fx.setAttr ) {
- jQuery.style( fx.elem, prop, fx.end );
- fx.setAttr = true;
- }
- };
-});
-
-function getElementStyles( elem ) {
- var key, len,
- style = elem.ownerDocument.defaultView ?
- elem.ownerDocument.defaultView.getComputedStyle( elem, null ) :
- elem.currentStyle,
- styles = {};
-
- if ( style && style.length && style[ 0 ] && style[ style[ 0 ] ] ) {
- len = style.length;
- while ( len-- ) {
- key = style[ len ];
- if ( typeof style[ key ] === "string" ) {
- styles[ $.camelCase( key ) ] = style[ key ];
- }
- }
- // support: Opera, IE <9
- } else {
- for ( key in style ) {
- if ( typeof style[ key ] === "string" ) {
- styles[ key ] = style[ key ];
- }
- }
- }
-
- return styles;
-}
-
-
-function styleDifference( oldStyle, newStyle ) {
- var diff = {},
- name, value;
-
- for ( name in newStyle ) {
- value = newStyle[ name ];
- if ( oldStyle[ name ] !== value ) {
- if ( !shorthandStyles[ name ] ) {
- if ( $.fx.step[ name ] || !isNaN( parseFloat( value ) ) ) {
- diff[ name ] = value;
- }
- }
- }
- }
-
- return diff;
-}
-
-// support: jQuery <1.8
-if ( !$.fn.addBack ) {
- $.fn.addBack = function( selector ) {
- return this.add( selector == null ?
- this.prevObject : this.prevObject.filter( selector )
- );
- };
-}
-
-$.effects.animateClass = function( value, duration, easing, callback ) {
- var o = $.speed( duration, easing, callback );
-
- return this.queue( function() {
- var animated = $( this ),
- baseClass = animated.attr( "class" ) || "",
- applyClassChange,
- allAnimations = o.children ? animated.find( "*" ).addBack() : animated;
-
- // map the animated objects to store the original styles.
- allAnimations = allAnimations.map(function() {
- var el = $( this );
- return {
- el: el,
- start: getElementStyles( this )
- };
- });
-
- // apply class change
- applyClassChange = function() {
- $.each( classAnimationActions, function(i, action) {
- if ( value[ action ] ) {
- animated[ action + "Class" ]( value[ action ] );
- }
- });
- };
- applyClassChange();
-
- // map all animated objects again - calculate new styles and diff
- allAnimations = allAnimations.map(function() {
- this.end = getElementStyles( this.el[ 0 ] );
- this.diff = styleDifference( this.start, this.end );
- return this;
- });
-
- // apply original class
- animated.attr( "class", baseClass );
-
- // map all animated objects again - this time collecting a promise
- allAnimations = allAnimations.map(function() {
- var styleInfo = this,
- dfd = $.Deferred(),
- opts = $.extend({}, o, {
- queue: false,
- complete: function() {
- dfd.resolve( styleInfo );
- }
- });
-
- this.el.animate( this.diff, opts );
- return dfd.promise();
- });
-
- // once all animations have completed:
- $.when.apply( $, allAnimations.get() ).done(function() {
-
- // set the final class
- applyClassChange();
-
- // for each animated element,
- // clear all css properties that were animated
- $.each( arguments, function() {
- var el = this.el;
- $.each( this.diff, function(key) {
- el.css( key, "" );
- });
- });
-
- // this is guarnteed to be there if you use jQuery.speed()
- // it also handles dequeuing the next anim...
- o.complete.call( animated[ 0 ] );
- });
- });
-};
-
-$.fn.extend({
- addClass: (function( orig ) {
- return function( classNames, speed, easing, callback ) {
- return speed ?
- $.effects.animateClass.call( this,
- { add: classNames }, speed, easing, callback ) :
- orig.apply( this, arguments );
- };
- })( $.fn.addClass ),
-
- removeClass: (function( orig ) {
- return function( classNames, speed, easing, callback ) {
- return arguments.length > 1 ?
- $.effects.animateClass.call( this,
- { remove: classNames }, speed, easing, callback ) :
- orig.apply( this, arguments );
- };
- })( $.fn.removeClass ),
-
- toggleClass: (function( orig ) {
- return function( classNames, force, speed, easing, callback ) {
- if ( typeof force === "boolean" || force === undefined ) {
- if ( !speed ) {
- // without speed parameter
- return orig.apply( this, arguments );
- } else {
- return $.effects.animateClass.call( this,
- (force ? { add: classNames } : { remove: classNames }),
- speed, easing, callback );
- }
- } else {
- // without force parameter
- return $.effects.animateClass.call( this,
- { toggle: classNames }, force, speed, easing );
- }
- };
- })( $.fn.toggleClass ),
-
- switchClass: function( remove, add, speed, easing, callback) {
- return $.effects.animateClass.call( this, {
- add: add,
- remove: remove
- }, speed, easing, callback );
- }
-});
-
-})();
-
-/******************************************************************************/
-/*********************************** EFFECTS **********************************/
-/******************************************************************************/
-
-(function() {
-
-$.extend( $.effects, {
- version: "1.10.4",
-
- // Saves a set of properties in a data storage
- save: function( element, set ) {
- for( var i=0; i < set.length; i++ ) {
- if ( set[ i ] !== null ) {
- element.data( dataSpace + set[ i ], element[ 0 ].style[ set[ i ] ] );
- }
- }
- },
-
- // Restores a set of previously saved properties from a data storage
- restore: function( element, set ) {
- var val, i;
- for( i=0; i < set.length; i++ ) {
- if ( set[ i ] !== null ) {
- val = element.data( dataSpace + set[ i ] );
- // support: jQuery 1.6.2
- // http://bugs.jquery.com/ticket/9917
- // jQuery 1.6.2 incorrectly returns undefined for any falsy value.
- // We can't differentiate between "" and 0 here, so we just assume
- // empty string since it's likely to be a more common value...
- if ( val === undefined ) {
- val = "";
- }
- element.css( set[ i ], val );
- }
- }
- },
-
- setMode: function( el, mode ) {
- if (mode === "toggle") {
- mode = el.is( ":hidden" ) ? "show" : "hide";
- }
- return mode;
- },
-
- // Translates a [top,left] array into a baseline value
- // this should be a little more flexible in the future to handle a string & hash
- getBaseline: function( origin, original ) {
- var y, x;
- switch ( origin[ 0 ] ) {
- case "top": y = 0; break;
- case "middle": y = 0.5; break;
- case "bottom": y = 1; break;
- default: y = origin[ 0 ] / original.height;
- }
- switch ( origin[ 1 ] ) {
- case "left": x = 0; break;
- case "center": x = 0.5; break;
- case "right": x = 1; break;
- default: x = origin[ 1 ] / original.width;
- }
- return {
- x: x,
- y: y
- };
- },
-
- // Wraps the element around a wrapper that copies position properties
- createWrapper: function( element ) {
-
- // if the element is already wrapped, return it
- if ( element.parent().is( ".ui-effects-wrapper" )) {
- return element.parent();
- }
-
- // wrap the element
- var props = {
- width: element.outerWidth(true),
- height: element.outerHeight(true),
- "float": element.css( "float" )
- },
- wrapper = $( "<div></div>" )
- .addClass( "ui-effects-wrapper" )
- .css({
- fontSize: "100%",
- background: "transparent",
- border: "none",
- margin: 0,
- padding: 0
- }),
- // Store the size in case width/height are defined in % - Fixes #5245
- size = {
- width: element.width(),
- height: element.height()
- },
- active = document.activeElement;
-
- // support: Firefox
- // Firefox incorrectly exposes anonymous content
- // https://bugzilla.mozilla.org/show_bug.cgi?id=561664
- try {
- active.id;
- } catch( e ) {
- active = document.body;
- }
-
- element.wrap( wrapper );
-
- // Fixes #7595 - Elements lose focus when wrapped.
- if ( element[ 0 ] === active || $.contains( element[ 0 ], active ) ) {
- $( active ).focus();
- }
-
- wrapper = element.parent(); //Hotfix for jQuery 1.4 since some change in wrap() seems to actually lose the reference to the wrapped element
-
- // transfer positioning properties to the wrapper
- if ( element.css( "position" ) === "static" ) {
- wrapper.css({ position: "relative" });
- element.css({ position: "relative" });
- } else {
- $.extend( props, {
- position: element.css( "position" ),
- zIndex: element.css( "z-index" )
- });
- $.each([ "top", "left", "bottom", "right" ], function(i, pos) {
- props[ pos ] = element.css( pos );
- if ( isNaN( parseInt( props[ pos ], 10 ) ) ) {
- props[ pos ] = "auto";
- }
- });
- element.css({
- position: "relative",
- top: 0,
- left: 0,
- right: "auto",
- bottom: "auto"
- });
- }
- element.css(size);
-
- return wrapper.css( props ).show();
- },
-
- removeWrapper: function( element ) {
- var active = document.activeElement;
-
- if ( element.parent().is( ".ui-effects-wrapper" ) ) {
- element.parent().replaceWith( element );
-
- // Fixes #7595 - Elements lose focus when wrapped.
- if ( element[ 0 ] === active || $.contains( element[ 0 ], active ) ) {
- $( active ).focus();
- }
- }
-
-
- return element;
- },
-
- setTransition: function( element, list, factor, value ) {
- value = value || {};
- $.each( list, function( i, x ) {
- var unit = element.cssUnit( x );
- if ( unit[ 0 ] > 0 ) {
- value[ x ] = unit[ 0 ] * factor + unit[ 1 ];
- }
- });
- return value;
- }
-});
-
-// return an effect options object for the given parameters:
-function _normalizeArguments( effect, options, speed, callback ) {
-
- // allow passing all options as the first parameter
- if ( $.isPlainObject( effect ) ) {
- options = effect;
- effect = effect.effect;
- }
-
- // convert to an object
- effect = { effect: effect };
-
- // catch (effect, null, ...)
- if ( options == null ) {
- options = {};
- }
-
- // catch (effect, callback)
- if ( $.isFunction( options ) ) {
- callback = options;
- speed = null;
- options = {};
- }
-
- // catch (effect, speed, ?)
- if ( typeof options === "number" || $.fx.speeds[ options ] ) {
- callback = speed;
- speed = options;
- options = {};
- }
-
- // catch (effect, options, callback)
- if ( $.isFunction( speed ) ) {
- callback = speed;
- speed = null;
- }
-
- // add options to effect
- if ( options ) {
- $.extend( effect, options );
- }
-
- speed = speed || options.duration;
- effect.duration = $.fx.off ? 0 :
- typeof speed === "number" ? speed :
- speed in $.fx.speeds ? $.fx.speeds[ speed ] :
- $.fx.speeds._default;
-
- effect.complete = callback || options.complete;
-
- return effect;
-}
-
-function standardAnimationOption( option ) {
- // Valid standard speeds (nothing, number, named speed)
- if ( !option || typeof option === "number" || $.fx.speeds[ option ] ) {
- return true;
- }
-
- // Invalid strings - treat as "normal" speed
- if ( typeof option === "string" && !$.effects.effect[ option ] ) {
- return true;
- }
-
- // Complete callback
- if ( $.isFunction( option ) ) {
- return true;
- }
-
- // Options hash (but not naming an effect)
- if ( typeof option === "object" && !option.effect ) {
- return true;
- }
-
- // Didn't match any standard API
- return false;
-}
-
-$.fn.extend({
- effect: function( /* effect, options, speed, callback */ ) {
- var args = _normalizeArguments.apply( this, arguments ),
- mode = args.mode,
- queue = args.queue,
- effectMethod = $.effects.effect[ args.effect ];
-
- if ( $.fx.off || !effectMethod ) {
- // delegate to the original method (e.g., .show()) if possible
- if ( mode ) {
- return this[ mode ]( args.duration, args.complete );
- } else {
- return this.each( function() {
- if ( args.complete ) {
- args.complete.call( this );
- }
- });
- }
- }
-
- function run( next ) {
- var elem = $( this ),
- complete = args.complete,
- mode = args.mode;
-
- function done() {
- if ( $.isFunction( complete ) ) {
- complete.call( elem[0] );
- }
- if ( $.isFunction( next ) ) {
- next();
- }
- }
-
- // If the element already has the correct final state, delegate to
- // the core methods so the internal tracking of "olddisplay" works.
- if ( elem.is( ":hidden" ) ? mode === "hide" : mode === "show" ) {
- elem[ mode ]();
- done();
- } else {
- effectMethod.call( elem[0], args, done );
- }
- }
-
- return queue === false ? this.each( run ) : this.queue( queue || "fx", run );
- },
-
- show: (function( orig ) {
- return function( option ) {
- if ( standardAnimationOption( option ) ) {
- return orig.apply( this, arguments );
- } else {
- var args = _normalizeArguments.apply( this, arguments );
- args.mode = "show";
- return this.effect.call( this, args );
- }
- };
- })( $.fn.show ),
-
- hide: (function( orig ) {
- return function( option ) {
- if ( standardAnimationOption( option ) ) {
- return orig.apply( this, arguments );
- } else {
- var args = _normalizeArguments.apply( this, arguments );
- args.mode = "hide";
- return this.effect.call( this, args );
- }
- };
- })( $.fn.hide ),
-
- toggle: (function( orig ) {
- return function( option ) {
- if ( standardAnimationOption( option ) || typeof option === "boolean" ) {
- return orig.apply( this, arguments );
- } else {
- var args = _normalizeArguments.apply( this, arguments );
- args.mode = "toggle";
- return this.effect.call( this, args );
- }
- };
- })( $.fn.toggle ),
-
- // helper functions
- cssUnit: function(key) {
- var style = this.css( key ),
- val = [];
-
- $.each( [ "em", "px", "%", "pt" ], function( i, unit ) {
- if ( style.indexOf( unit ) > 0 ) {
- val = [ parseFloat( style ), unit ];
- }
- });
- return val;
- }
-});
-
-})();
-
-/******************************************************************************/
-/*********************************** EASING ***********************************/
-/******************************************************************************/
-
-(function() {
-
-// based on easing equations from Robert Penner (http://www.robertpenner.com/easing)
-
-var baseEasings = {};
-
-$.each( [ "Quad", "Cubic", "Quart", "Quint", "Expo" ], function( i, name ) {
- baseEasings[ name ] = function( p ) {
- return Math.pow( p, i + 2 );
- };
-});
-
-$.extend( baseEasings, {
- Sine: function ( p ) {
- return 1 - Math.cos( p * Math.PI / 2 );
- },
- Circ: function ( p ) {
- return 1 - Math.sqrt( 1 - p * p );
- },
- Elastic: function( p ) {
- return p === 0 || p === 1 ? p :
- -Math.pow( 2, 8 * (p - 1) ) * Math.sin( ( (p - 1) * 80 - 7.5 ) * Math.PI / 15 );
- },
- Back: function( p ) {
- return p * p * ( 3 * p - 2 );
- },
- Bounce: function ( p ) {
- var pow2,
- bounce = 4;
-
- while ( p < ( ( pow2 = Math.pow( 2, --bounce ) ) - 1 ) / 11 ) {}
- return 1 / Math.pow( 4, 3 - bounce ) - 7.5625 * Math.pow( ( pow2 * 3 - 2 ) / 22 - p, 2 );
- }
-});
-
-$.each( baseEasings, function( name, easeIn ) {
- $.easing[ "easeIn" + name ] = easeIn;
- $.easing[ "easeOut" + name ] = function( p ) {
- return 1 - easeIn( 1 - p );
- };
- $.easing[ "easeInOut" + name ] = function( p ) {
- return p < 0.5 ?
- easeIn( p * 2 ) / 2 :
- 1 - easeIn( p * -2 + 2 ) / 2;
- };
-});
-
-})();
-
-})(jQuery);
-(function( $, undefined ) {
-
-var rvertical = /up|down|vertical/,
- rpositivemotion = /up|left|vertical|horizontal/;
-
-$.effects.effect.blind = function( o, done ) {
- // Create element
- var el = $( this ),
- props = [ "position", "top", "bottom", "left", "right", "height", "width" ],
- mode = $.effects.setMode( el, o.mode || "hide" ),
- direction = o.direction || "up",
- vertical = rvertical.test( direction ),
- ref = vertical ? "height" : "width",
- ref2 = vertical ? "top" : "left",
- motion = rpositivemotion.test( direction ),
- animation = {},
- show = mode === "show",
- wrapper, distance, margin;
-
- // if already wrapped, the wrapper's properties are my property. #6245
- if ( el.parent().is( ".ui-effects-wrapper" ) ) {
- $.effects.save( el.parent(), props );
- } else {
- $.effects.save( el, props );
- }
- el.show();
- wrapper = $.effects.createWrapper( el ).css({
- overflow: "hidden"
- });
-
- distance = wrapper[ ref ]();
- margin = parseFloat( wrapper.css( ref2 ) ) || 0;
-
- animation[ ref ] = show ? distance : 0;
- if ( !motion ) {
- el
- .css( vertical ? "bottom" : "right", 0 )
- .css( vertical ? "top" : "left", "auto" )
- .css({ position: "absolute" });
-
- animation[ ref2 ] = show ? margin : distance + margin;
- }
-
- // start at 0 if we are showing
- if ( show ) {
- wrapper.css( ref, 0 );
- if ( ! motion ) {
- wrapper.css( ref2, margin + distance );
- }
- }
-
- // Animate
- wrapper.animate( animation, {
- duration: o.duration,
- easing: o.easing,
- queue: false,
- complete: function() {
- if ( mode === "hide" ) {
- el.hide();
- }
- $.effects.restore( el, props );
- $.effects.removeWrapper( el );
- done();
- }
- });
-
-};
-
-})(jQuery);
-(function( $, undefined ) {
-
-$.effects.effect.bounce = function( o, done ) {
- var el = $( this ),
- props = [ "position", "top", "bottom", "left", "right", "height", "width" ],
-
- // defaults:
- mode = $.effects.setMode( el, o.mode || "effect" ),
- hide = mode === "hide",
- show = mode === "show",
- direction = o.direction || "up",
- distance = o.distance,
- times = o.times || 5,
-
- // number of internal animations
- anims = times * 2 + ( show || hide ? 1 : 0 ),
- speed = o.duration / anims,
- easing = o.easing,
-
- // utility:
- ref = ( direction === "up" || direction === "down" ) ? "top" : "left",
- motion = ( direction === "up" || direction === "left" ),
- i,
- upAnim,
- downAnim,
-
- // we will need to re-assemble the queue to stack our animations in place
- queue = el.queue(),
- queuelen = queue.length;
-
- // Avoid touching opacity to prevent clearType and PNG issues in IE
- if ( show || hide ) {
- props.push( "opacity" );
- }
-
- $.effects.save( el, props );
- el.show();
- $.effects.createWrapper( el ); // Create Wrapper
-
- // default distance for the BIGGEST bounce is the outer Distance / 3
- if ( !distance ) {
- distance = el[ ref === "top" ? "outerHeight" : "outerWidth" ]() / 3;
- }
-
- if ( show ) {
- downAnim = { opacity: 1 };
- downAnim[ ref ] = 0;
-
- // if we are showing, force opacity 0 and set the initial position
- // then do the "first" animation
- el.css( "opacity", 0 )
- .css( ref, motion ? -distance * 2 : distance * 2 )
- .animate( downAnim, speed, easing );
- }
-
- // start at the smallest distance if we are hiding
- if ( hide ) {
- distance = distance / Math.pow( 2, times - 1 );
- }
-
- downAnim = {};
- downAnim[ ref ] = 0;
- // Bounces up/down/left/right then back to 0 -- times * 2 animations happen here
- for ( i = 0; i < times; i++ ) {
- upAnim = {};
- upAnim[ ref ] = ( motion ? "-=" : "+=" ) + distance;
-
- el.animate( upAnim, speed, easing )
- .animate( downAnim, speed, easing );
-
- distance = hide ? distance * 2 : distance / 2;
- }
-
- // Last Bounce when Hiding
- if ( hide ) {
- upAnim = { opacity: 0 };
- upAnim[ ref ] = ( motion ? "-=" : "+=" ) + distance;
-
- el.animate( upAnim, speed, easing );
- }
-
- el.queue(function() {
- if ( hide ) {
- el.hide();
- }
- $.effects.restore( el, props );
- $.effects.removeWrapper( el );
- done();
- });
-
- // inject all the animations we just queued to be first in line (after "inprogress")
- if ( queuelen > 1) {
- queue.splice.apply( queue,
- [ 1, 0 ].concat( queue.splice( queuelen, anims + 1 ) ) );
- }
- el.dequeue();
-
-};
-
-})(jQuery);
-(function( $, undefined ) {
-
-$.effects.effect.clip = function( o, done ) {
- // Create element
- var el = $( this ),
- props = [ "position", "top", "bottom", "left", "right", "height", "width" ],
- mode = $.effects.setMode( el, o.mode || "hide" ),
- show = mode === "show",
- direction = o.direction || "vertical",
- vert = direction === "vertical",
- size = vert ? "height" : "width",
- position = vert ? "top" : "left",
- animation = {},
- wrapper, animate, distance;
-
- // Save & Show
- $.effects.save( el, props );
- el.show();
-
- // Create Wrapper
- wrapper = $.effects.createWrapper( el ).css({
- overflow: "hidden"
- });
- animate = ( el[0].tagName === "IMG" ) ? wrapper : el;
- distance = animate[ size ]();
-
- // Shift
- if ( show ) {
- animate.css( size, 0 );
- animate.css( position, distance / 2 );
- }
-
- // Create Animation Object:
- animation[ size ] = show ? distance : 0;
- animation[ position ] = show ? 0 : distance / 2;
-
- // Animate
- animate.animate( animation, {
- queue: false,
- duration: o.duration,
- easing: o.easing,
- complete: function() {
- if ( !show ) {
- el.hide();
- }
- $.effects.restore( el, props );
- $.effects.removeWrapper( el );
- done();
- }
- });
-
-};
-
-})(jQuery);
-(function( $, undefined ) {
-
-$.effects.effect.drop = function( o, done ) {
-
- var el = $( this ),
- props = [ "position", "top", "bottom", "left", "right", "opacity", "height", "width" ],
- mode = $.effects.setMode( el, o.mode || "hide" ),
- show = mode === "show",
- direction = o.direction || "left",
- ref = ( direction === "up" || direction === "down" ) ? "top" : "left",
- motion = ( direction === "up" || direction === "left" ) ? "pos" : "neg",
- animation = {
- opacity: show ? 1 : 0
- },
- distance;
-
- // Adjust
- $.effects.save( el, props );
- el.show();
- $.effects.createWrapper( el );
-
- distance = o.distance || el[ ref === "top" ? "outerHeight": "outerWidth" ]( true ) / 2;
-
- if ( show ) {
- el
- .css( "opacity", 0 )
- .css( ref, motion === "pos" ? -distance : distance );
- }
-
- // Animation
- animation[ ref ] = ( show ?
- ( motion === "pos" ? "+=" : "-=" ) :
- ( motion === "pos" ? "-=" : "+=" ) ) +
- distance;
-
- // Animate
- el.animate( animation, {
- queue: false,
- duration: o.duration,
- easing: o.easing,
- complete: function() {
- if ( mode === "hide" ) {
- el.hide();
- }
- $.effects.restore( el, props );
- $.effects.removeWrapper( el );
- done();
- }
- });
-};
-
-})(jQuery);
-(function( $, undefined ) {
-
-$.effects.effect.explode = function( o, done ) {
-
- var rows = o.pieces ? Math.round( Math.sqrt( o.pieces ) ) : 3,
- cells = rows,
- el = $( this ),
- mode = $.effects.setMode( el, o.mode || "hide" ),
- show = mode === "show",
-
- // show and then visibility:hidden the element before calculating offset
- offset = el.show().css( "visibility", "hidden" ).offset(),
-
- // width and height of a piece
- width = Math.ceil( el.outerWidth() / cells ),
- height = Math.ceil( el.outerHeight() / rows ),
- pieces = [],
-
- // loop
- i, j, left, top, mx, my;
-
- // children animate complete:
- function childComplete() {
- pieces.push( this );
- if ( pieces.length === rows * cells ) {
- animComplete();
- }
- }
-
- // clone the element for each row and cell.
- for( i = 0; i < rows ; i++ ) { // ===>
- top = offset.top + i * height;
- my = i - ( rows - 1 ) / 2 ;
-
- for( j = 0; j < cells ; j++ ) { // |||
- left = offset.left + j * width;
- mx = j - ( cells - 1 ) / 2 ;
-
- // Create a clone of the now hidden main element that will be absolute positioned
- // within a wrapper div off the -left and -top equal to size of our pieces
- el
- .clone()
- .appendTo( "body" )
- .wrap( "<div></div>" )
- .css({
- position: "absolute",
- visibility: "visible",
- left: -j * width,
- top: -i * height
- })
-
- // select the wrapper - make it overflow: hidden and absolute positioned based on
- // where the original was located +left and +top equal to the size of pieces
- .parent()
- .addClass( "ui-effects-explode" )
- .css({
- position: "absolute",
- overflow: "hidden",
- width: width,
- height: height,
- left: left + ( show ? mx * width : 0 ),
- top: top + ( show ? my * height : 0 ),
- opacity: show ? 0 : 1
- }).animate({
- left: left + ( show ? 0 : mx * width ),
- top: top + ( show ? 0 : my * height ),
- opacity: show ? 1 : 0
- }, o.duration || 500, o.easing, childComplete );
- }
- }
-
- function animComplete() {
- el.css({
- visibility: "visible"
- });
- $( pieces ).remove();
- if ( !show ) {
- el.hide();
- }
- done();
- }
-};
-
-})(jQuery);
-(function( $, undefined ) {
-
-$.effects.effect.fade = function( o, done ) {
- var el = $( this ),
- mode = $.effects.setMode( el, o.mode || "toggle" );
-
- el.animate({
- opacity: mode
- }, {
- queue: false,
- duration: o.duration,
- easing: o.easing,
- complete: done
- });
-};
-
-})( jQuery );
-(function( $, undefined ) {
-
-$.effects.effect.fold = function( o, done ) {
-
- // Create element
- var el = $( this ),
- props = [ "position", "top", "bottom", "left", "right", "height", "width" ],
- mode = $.effects.setMode( el, o.mode || "hide" ),
- show = mode === "show",
- hide = mode === "hide",
- size = o.size || 15,
- percent = /([0-9]+)%/.exec( size ),
- horizFirst = !!o.horizFirst,
- widthFirst = show !== horizFirst,
- ref = widthFirst ? [ "width", "height" ] : [ "height", "width" ],
- duration = o.duration / 2,
- wrapper, distance,
- animation1 = {},
- animation2 = {};
-
- $.effects.save( el, props );
- el.show();
-
- // Create Wrapper
- wrapper = $.effects.createWrapper( el ).css({
- overflow: "hidden"
- });
- distance = widthFirst ?
- [ wrapper.width(), wrapper.height() ] :
- [ wrapper.height(), wrapper.width() ];
-
- if ( percent ) {
- size = parseInt( percent[ 1 ], 10 ) / 100 * distance[ hide ? 0 : 1 ];
- }
- if ( show ) {
- wrapper.css( horizFirst ? {
- height: 0,
- width: size
- } : {
- height: size,
- width: 0
- });
- }
-
- // Animation
- animation1[ ref[ 0 ] ] = show ? distance[ 0 ] : size;
- animation2[ ref[ 1 ] ] = show ? distance[ 1 ] : 0;
-
- // Animate
- wrapper
- .animate( animation1, duration, o.easing )
- .animate( animation2, duration, o.easing, function() {
- if ( hide ) {
- el.hide();
- }
- $.effects.restore( el, props );
- $.effects.removeWrapper( el );
- done();
- });
-
-};
-
-})(jQuery);
-(function( $, undefined ) {
-
-$.effects.effect.highlight = function( o, done ) {
- var elem = $( this ),
- props = [ "backgroundImage", "backgroundColor", "opacity" ],
- mode = $.effects.setMode( elem, o.mode || "show" ),
- animation = {
- backgroundColor: elem.css( "backgroundColor" )
- };
-
- if (mode === "hide") {
- animation.opacity = 0;
- }
-
- $.effects.save( elem, props );
-
- elem
- .show()
- .css({
- backgroundImage: "none",
- backgroundColor: o.color || "#ffff99"
- })
- .animate( animation, {
- queue: false,
- duration: o.duration,
- easing: o.easing,
- complete: function() {
- if ( mode === "hide" ) {
- elem.hide();
- }
- $.effects.restore( elem, props );
- done();
- }
- });
-};
-
-})(jQuery);
-(function( $, undefined ) {
-
-$.effects.effect.pulsate = function( o, done ) {
- var elem = $( this ),
- mode = $.effects.setMode( elem, o.mode || "show" ),
- show = mode === "show",
- hide = mode === "hide",
- showhide = ( show || mode === "hide" ),
-
- // showing or hiding leaves of the "last" animation
- anims = ( ( o.times || 5 ) * 2 ) + ( showhide ? 1 : 0 ),
- duration = o.duration / anims,
- animateTo = 0,
- queue = elem.queue(),
- queuelen = queue.length,
- i;
-
- if ( show || !elem.is(":visible")) {
- elem.css( "opacity", 0 ).show();
- animateTo = 1;
- }
-
- // anims - 1 opacity "toggles"
- for ( i = 1; i < anims; i++ ) {
- elem.animate({
- opacity: animateTo
- }, duration, o.easing );
- animateTo = 1 - animateTo;
- }
-
- elem.animate({
- opacity: animateTo
- }, duration, o.easing);
-
- elem.queue(function() {
- if ( hide ) {
- elem.hide();
- }
- done();
- });
-
- // We just queued up "anims" animations, we need to put them next in the queue
- if ( queuelen > 1 ) {
- queue.splice.apply( queue,
- [ 1, 0 ].concat( queue.splice( queuelen, anims + 1 ) ) );
- }
- elem.dequeue();
-};
-
-})(jQuery);
-(function( $, undefined ) {
-
-$.effects.effect.puff = function( o, done ) {
- var elem = $( this ),
- mode = $.effects.setMode( elem, o.mode || "hide" ),
- hide = mode === "hide",
- percent = parseInt( o.percent, 10 ) || 150,
- factor = percent / 100,
- original = {
- height: elem.height(),
- width: elem.width(),
- outerHeight: elem.outerHeight(),
- outerWidth: elem.outerWidth()
- };
-
- $.extend( o, {
- effect: "scale",
- queue: false,
- fade: true,
- mode: mode,
- complete: done,
- percent: hide ? percent : 100,
- from: hide ?
- original :
- {
- height: original.height * factor,
- width: original.width * factor,
- outerHeight: original.outerHeight * factor,
- outerWidth: original.outerWidth * factor
- }
- });
-
- elem.effect( o );
-};
-
-$.effects.effect.scale = function( o, done ) {
-
- // Create element
- var el = $( this ),
- options = $.extend( true, {}, o ),
- mode = $.effects.setMode( el, o.mode || "effect" ),
- percent = parseInt( o.percent, 10 ) ||
- ( parseInt( o.percent, 10 ) === 0 ? 0 : ( mode === "hide" ? 0 : 100 ) ),
- direction = o.direction || "both",
- origin = o.origin,
- original = {
- height: el.height(),
- width: el.width(),
- outerHeight: el.outerHeight(),
- outerWidth: el.outerWidth()
- },
- factor = {
- y: direction !== "horizontal" ? (percent / 100) : 1,
- x: direction !== "vertical" ? (percent / 100) : 1
- };
-
- // We are going to pass this effect to the size effect:
- options.effect = "size";
- options.queue = false;
- options.complete = done;
-
- // Set default origin and restore for show/hide
- if ( mode !== "effect" ) {
- options.origin = origin || ["middle","center"];
- options.restore = true;
- }
-
- options.from = o.from || ( mode === "show" ? {
- height: 0,
- width: 0,
- outerHeight: 0,
- outerWidth: 0
- } : original );
- options.to = {
- height: original.height * factor.y,
- width: original.width * factor.x,
- outerHeight: original.outerHeight * factor.y,
- outerWidth: original.outerWidth * factor.x
- };
-
- // Fade option to support puff
- if ( options.fade ) {
- if ( mode === "show" ) {
- options.from.opacity = 0;
- options.to.opacity = 1;
- }
- if ( mode === "hide" ) {
- options.from.opacity = 1;
- options.to.opacity = 0;
- }
- }
-
- // Animate
- el.effect( options );
-
-};
-
-$.effects.effect.size = function( o, done ) {
-
- // Create element
- var original, baseline, factor,
- el = $( this ),
- props0 = [ "position", "top", "bottom", "left", "right", "width", "height", "overflow", "opacity" ],
-
- // Always restore
- props1 = [ "position", "top", "bottom", "left", "right", "overflow", "opacity" ],
-
- // Copy for children
- props2 = [ "width", "height", "overflow" ],
- cProps = [ "fontSize" ],
- vProps = [ "borderTopWidth", "borderBottomWidth", "paddingTop", "paddingBottom" ],
- hProps = [ "borderLeftWidth", "borderRightWidth", "paddingLeft", "paddingRight" ],
-
- // Set options
- mode = $.effects.setMode( el, o.mode || "effect" ),
- restore = o.restore || mode !== "effect",
- scale = o.scale || "both",
- origin = o.origin || [ "middle", "center" ],
- position = el.css( "position" ),
- props = restore ? props0 : props1,
- zero = {
- height: 0,
- width: 0,
- outerHeight: 0,
- outerWidth: 0
- };
-
- if ( mode === "show" ) {
- el.show();
- }
- original = {
- height: el.height(),
- width: el.width(),
- outerHeight: el.outerHeight(),
- outerWidth: el.outerWidth()
- };
-
- if ( o.mode === "toggle" && mode === "show" ) {
- el.from = o.to || zero;
- el.to = o.from || original;
- } else {
- el.from = o.from || ( mode === "show" ? zero : original );
- el.to = o.to || ( mode === "hide" ? zero : original );
- }
-
- // Set scaling factor
- factor = {
- from: {
- y: el.from.height / original.height,
- x: el.from.width / original.width
- },
- to: {
- y: el.to.height / original.height,
- x: el.to.width / original.width
- }
- };
-
- // Scale the css box
- if ( scale === "box" || scale === "both" ) {
-
- // Vertical props scaling
- if ( factor.from.y !== factor.to.y ) {
- props = props.concat( vProps );
- el.from = $.effects.setTransition( el, vProps, factor.from.y, el.from );
- el.to = $.effects.setTransition( el, vProps, factor.to.y, el.to );
- }
-
- // Horizontal props scaling
- if ( factor.from.x !== factor.to.x ) {
- props = props.concat( hProps );
- el.from = $.effects.setTransition( el, hProps, factor.from.x, el.from );
- el.to = $.effects.setTransition( el, hProps, factor.to.x, el.to );
- }
- }
-
- // Scale the content
- if ( scale === "content" || scale === "both" ) {
-
- // Vertical props scaling
- if ( factor.from.y !== factor.to.y ) {
- props = props.concat( cProps ).concat( props2 );
- el.from = $.effects.setTransition( el, cProps, factor.from.y, el.from );
- el.to = $.effects.setTransition( el, cProps, factor.to.y, el.to );
- }
- }
-
- $.effects.save( el, props );
- el.show();
- $.effects.createWrapper( el );
- el.css( "overflow", "hidden" ).css( el.from );
-
- // Adjust
- if (origin) { // Calculate baseline shifts
- baseline = $.effects.getBaseline( origin, original );
- el.from.top = ( original.outerHeight - el.outerHeight() ) * baseline.y;
- el.from.left = ( original.outerWidth - el.outerWidth() ) * baseline.x;
- el.to.top = ( original.outerHeight - el.to.outerHeight ) * baseline.y;
- el.to.left = ( original.outerWidth - el.to.outerWidth ) * baseline.x;
- }
- el.css( el.from ); // set top & left
-
- // Animate
- if ( scale === "content" || scale === "both" ) { // Scale the children
-
- // Add margins/font-size
- vProps = vProps.concat([ "marginTop", "marginBottom" ]).concat(cProps);
- hProps = hProps.concat([ "marginLeft", "marginRight" ]);
- props2 = props0.concat(vProps).concat(hProps);
-
- el.find( "*[width]" ).each( function(){
- var child = $( this ),
- c_original = {
- height: child.height(),
- width: child.width(),
- outerHeight: child.outerHeight(),
- outerWidth: child.outerWidth()
- };
- if (restore) {
- $.effects.save(child, props2);
- }
-
- child.from = {
- height: c_original.height * factor.from.y,
- width: c_original.width * factor.from.x,
- outerHeight: c_original.outerHeight * factor.from.y,
- outerWidth: c_original.outerWidth * factor.from.x
- };
- child.to = {
- height: c_original.height * factor.to.y,
- width: c_original.width * factor.to.x,
- outerHeight: c_original.height * factor.to.y,
- outerWidth: c_original.width * factor.to.x
- };
-
- // Vertical props scaling
- if ( factor.from.y !== factor.to.y ) {
- child.from = $.effects.setTransition( child, vProps, factor.from.y, child.from );
- child.to = $.effects.setTransition( child, vProps, factor.to.y, child.to );
- }
-
- // Horizontal props scaling
- if ( factor.from.x !== factor.to.x ) {
- child.from = $.effects.setTransition( child, hProps, factor.from.x, child.from );
- child.to = $.effects.setTransition( child, hProps, factor.to.x, child.to );
- }
-
- // Animate children
- child.css( child.from );
- child.animate( child.to, o.duration, o.easing, function() {
-
- // Restore children
- if ( restore ) {
- $.effects.restore( child, props2 );
- }
- });
- });
- }
-
- // Animate
- el.animate( el.to, {
- queue: false,
- duration: o.duration,
- easing: o.easing,
- complete: function() {
- if ( el.to.opacity === 0 ) {
- el.css( "opacity", el.from.opacity );
- }
- if( mode === "hide" ) {
- el.hide();
- }
- $.effects.restore( el, props );
- if ( !restore ) {
-
- // we need to calculate our new positioning based on the scaling
- if ( position === "static" ) {
- el.css({
- position: "relative",
- top: el.to.top,
- left: el.to.left
- });
- } else {
- $.each([ "top", "left" ], function( idx, pos ) {
- el.css( pos, function( _, str ) {
- var val = parseInt( str, 10 ),
- toRef = idx ? el.to.left : el.to.top;
-
- // if original was "auto", recalculate the new value from wrapper
- if ( str === "auto" ) {
- return toRef + "px";
- }
-
- return val + toRef + "px";
- });
- });
- }
- }
-
- $.effects.removeWrapper( el );
- done();
- }
- });
-
-};
-
-})(jQuery);
-(function( $, undefined ) {
-
-$.effects.effect.shake = function( o, done ) {
-
- var el = $( this ),
- props = [ "position", "top", "bottom", "left", "right", "height", "width" ],
- mode = $.effects.setMode( el, o.mode || "effect" ),
- direction = o.direction || "left",
- distance = o.distance || 20,
- times = o.times || 3,
- anims = times * 2 + 1,
- speed = Math.round(o.duration/anims),
- ref = (direction === "up" || direction === "down") ? "top" : "left",
- positiveMotion = (direction === "up" || direction === "left"),
- animation = {},
- animation1 = {},
- animation2 = {},
- i,
-
- // we will need to re-assemble the queue to stack our animations in place
- queue = el.queue(),
- queuelen = queue.length;
-
- $.effects.save( el, props );
- el.show();
- $.effects.createWrapper( el );
-
- // Animation
- animation[ ref ] = ( positiveMotion ? "-=" : "+=" ) + distance;
- animation1[ ref ] = ( positiveMotion ? "+=" : "-=" ) + distance * 2;
- animation2[ ref ] = ( positiveMotion ? "-=" : "+=" ) + distance * 2;
-
- // Animate
- el.animate( animation, speed, o.easing );
-
- // Shakes
- for ( i = 1; i < times; i++ ) {
- el.animate( animation1, speed, o.easing ).animate( animation2, speed, o.easing );
- }
- el
- .animate( animation1, speed, o.easing )
- .animate( animation, speed / 2, o.easing )
- .queue(function() {
- if ( mode === "hide" ) {
- el.hide();
- }
- $.effects.restore( el, props );
- $.effects.removeWrapper( el );
- done();
- });
-
- // inject all the animations we just queued to be first in line (after "inprogress")
- if ( queuelen > 1) {
- queue.splice.apply( queue,
- [ 1, 0 ].concat( queue.splice( queuelen, anims + 1 ) ) );
- }
- el.dequeue();
-
-};
-
-})(jQuery);
-(function( $, undefined ) {
-
-$.effects.effect.slide = function( o, done ) {
-
- // Create element
- var el = $( this ),
- props = [ "position", "top", "bottom", "left", "right", "width", "height" ],
- mode = $.effects.setMode( el, o.mode || "show" ),
- show = mode === "show",
- direction = o.direction || "left",
- ref = (direction === "up" || direction === "down") ? "top" : "left",
- positiveMotion = (direction === "up" || direction === "left"),
- distance,
- animation = {};
-
- // Adjust
- $.effects.save( el, props );
- el.show();
- distance = o.distance || el[ ref === "top" ? "outerHeight" : "outerWidth" ]( true );
-
- $.effects.createWrapper( el ).css({
- overflow: "hidden"
- });
-
- if ( show ) {
- el.css( ref, positiveMotion ? (isNaN(distance) ? "-" + distance : -distance) : distance );
- }
-
- // Animation
- animation[ ref ] = ( show ?
- ( positiveMotion ? "+=" : "-=") :
- ( positiveMotion ? "-=" : "+=")) +
- distance;
-
- // Animate
- el.animate( animation, {
- queue: false,
- duration: o.duration,
- easing: o.easing,
- complete: function() {
- if ( mode === "hide" ) {
- el.hide();
- }
- $.effects.restore( el, props );
- $.effects.removeWrapper( el );
- done();
- }
- });
-};
-
-})(jQuery);
-(function( $, undefined ) {
-
-$.effects.effect.transfer = function( o, done ) {
- var elem = $( this ),
- target = $( o.to ),
- targetFixed = target.css( "position" ) === "fixed",
- body = $("body"),
- fixTop = targetFixed ? body.scrollTop() : 0,
- fixLeft = targetFixed ? body.scrollLeft() : 0,
- endPosition = target.offset(),
- animation = {
- top: endPosition.top - fixTop ,
- left: endPosition.left - fixLeft ,
- height: target.innerHeight(),
- width: target.innerWidth()
- },
- startPosition = elem.offset(),
- transfer = $( "<div class='ui-effects-transfer'></div>" )
- .appendTo( document.body )
- .addClass( o.className )
- .css({
- top: startPosition.top - fixTop ,
- left: startPosition.left - fixLeft ,
- height: elem.innerHeight(),
- width: elem.innerWidth(),
- position: targetFixed ? "fixed" : "absolute"
- })
- .animate( animation, o.duration, o.easing, function() {
- transfer.remove();
- done();
- });
-};
-
-})(jQuery);
--- a/server/python/django/renkanmanager/static/renkanmanager/lib/jquery-ui.min.js Fri Apr 24 13:05:09 2015 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,7 +0,0 @@
-/*! jQuery UI - v1.10.4 - 2014-02-09
-* http://jqueryui.com
-* Includes: jquery.ui.core.js, jquery.ui.widget.js, jquery.ui.mouse.js, jquery.ui.position.js, jquery.ui.draggable.js, jquery.ui.droppable.js, jquery.ui.resizable.js, jquery.ui.selectable.js, jquery.ui.sortable.js, jquery.ui.accordion.js, jquery.ui.autocomplete.js, jquery.ui.button.js, jquery.ui.datepicker.js, jquery.ui.dialog.js, jquery.ui.menu.js, jquery.ui.progressbar.js, jquery.ui.slider.js, jquery.ui.spinner.js, jquery.ui.tabs.js, jquery.ui.tooltip.js, jquery.ui.effect.js, jquery.ui.effect-blind.js, jquery.ui.effect-bounce.js, jquery.ui.effect-clip.js, jquery.ui.effect-drop.js, jquery.ui.effect-explode.js, jquery.ui.effect-fade.js, jquery.ui.effect-fold.js, jquery.ui.effect-highlight.js, jquery.ui.effect-pulsate.js, jquery.ui.effect-scale.js, jquery.ui.effect-shake.js, jquery.ui.effect-slide.js, jquery.ui.effect-transfer.js
-* Copyright 2014 jQuery Foundation and other contributors; Licensed MIT */
-
-(function(e,t){function i(t,i){var s,a,o,r=t.nodeName.toLowerCase();return"area"===r?(s=t.parentNode,a=s.name,t.href&&a&&"map"===s.nodeName.toLowerCase()?(o=e("img[usemap=#"+a+"]")[0],!!o&&n(o)):!1):(/input|select|textarea|button|object/.test(r)?!t.disabled:"a"===r?t.href||i:i)&&n(t)}function n(t){return e.expr.filters.visible(t)&&!e(t).parents().addBack().filter(function(){return"hidden"===e.css(this,"visibility")}).length}var s=0,a=/^ui-id-\d+$/;e.ui=e.ui||{},e.extend(e.ui,{version:"1.10.4",keyCode:{BACKSPACE:8,COMMA:188,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,HOME:36,LEFT:37,NUMPAD_ADD:107,NUMPAD_DECIMAL:110,NUMPAD_DIVIDE:111,NUMPAD_ENTER:108,NUMPAD_MULTIPLY:106,NUMPAD_SUBTRACT:109,PAGE_DOWN:34,PAGE_UP:33,PERIOD:190,RIGHT:39,SPACE:32,TAB:9,UP:38}}),e.fn.extend({focus:function(t){return function(i,n){return"number"==typeof i?this.each(function(){var t=this;setTimeout(function(){e(t).focus(),n&&n.call(t)},i)}):t.apply(this,arguments)}}(e.fn.focus),scrollParent:function(){var t;return t=e.ui.ie&&/(static|relative)/.test(this.css("position"))||/absolute/.test(this.css("position"))?this.parents().filter(function(){return/(relative|absolute|fixed)/.test(e.css(this,"position"))&&/(auto|scroll)/.test(e.css(this,"overflow")+e.css(this,"overflow-y")+e.css(this,"overflow-x"))}).eq(0):this.parents().filter(function(){return/(auto|scroll)/.test(e.css(this,"overflow")+e.css(this,"overflow-y")+e.css(this,"overflow-x"))}).eq(0),/fixed/.test(this.css("position"))||!t.length?e(document):t},zIndex:function(i){if(i!==t)return this.css("zIndex",i);if(this.length)for(var n,s,a=e(this[0]);a.length&&a[0]!==document;){if(n=a.css("position"),("absolute"===n||"relative"===n||"fixed"===n)&&(s=parseInt(a.css("zIndex"),10),!isNaN(s)&&0!==s))return s;a=a.parent()}return 0},uniqueId:function(){return this.each(function(){this.id||(this.id="ui-id-"+ ++s)})},removeUniqueId:function(){return this.each(function(){a.test(this.id)&&e(this).removeAttr("id")})}}),e.extend(e.expr[":"],{data:e.expr.createPseudo?e.expr.createPseudo(function(t){return function(i){return!!e.data(i,t)}}):function(t,i,n){return!!e.data(t,n[3])},focusable:function(t){return i(t,!isNaN(e.attr(t,"tabindex")))},tabbable:function(t){var n=e.attr(t,"tabindex"),s=isNaN(n);return(s||n>=0)&&i(t,!s)}}),e("<a>").outerWidth(1).jquery||e.each(["Width","Height"],function(i,n){function s(t,i,n,s){return e.each(a,function(){i-=parseFloat(e.css(t,"padding"+this))||0,n&&(i-=parseFloat(e.css(t,"border"+this+"Width"))||0),s&&(i-=parseFloat(e.css(t,"margin"+this))||0)}),i}var a="Width"===n?["Left","Right"]:["Top","Bottom"],o=n.toLowerCase(),r={innerWidth:e.fn.innerWidth,innerHeight:e.fn.innerHeight,outerWidth:e.fn.outerWidth,outerHeight:e.fn.outerHeight};e.fn["inner"+n]=function(i){return i===t?r["inner"+n].call(this):this.each(function(){e(this).css(o,s(this,i)+"px")})},e.fn["outer"+n]=function(t,i){return"number"!=typeof t?r["outer"+n].call(this,t):this.each(function(){e(this).css(o,s(this,t,!0,i)+"px")})}}),e.fn.addBack||(e.fn.addBack=function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}),e("<a>").data("a-b","a").removeData("a-b").data("a-b")&&(e.fn.removeData=function(t){return function(i){return arguments.length?t.call(this,e.camelCase(i)):t.call(this)}}(e.fn.removeData)),e.ui.ie=!!/msie [\w.]+/.exec(navigator.userAgent.toLowerCase()),e.support.selectstart="onselectstart"in document.createElement("div"),e.fn.extend({disableSelection:function(){return this.bind((e.support.selectstart?"selectstart":"mousedown")+".ui-disableSelection",function(e){e.preventDefault()})},enableSelection:function(){return this.unbind(".ui-disableSelection")}}),e.extend(e.ui,{plugin:{add:function(t,i,n){var s,a=e.ui[t].prototype;for(s in n)a.plugins[s]=a.plugins[s]||[],a.plugins[s].push([i,n[s]])},call:function(e,t,i){var n,s=e.plugins[t];if(s&&e.element[0].parentNode&&11!==e.element[0].parentNode.nodeType)for(n=0;s.length>n;n++)e.options[s[n][0]]&&s[n][1].apply(e.element,i)}},hasScroll:function(t,i){if("hidden"===e(t).css("overflow"))return!1;var n=i&&"left"===i?"scrollLeft":"scrollTop",s=!1;return t[n]>0?!0:(t[n]=1,s=t[n]>0,t[n]=0,s)}})})(jQuery);(function(t,e){var i=0,s=Array.prototype.slice,n=t.cleanData;t.cleanData=function(e){for(var i,s=0;null!=(i=e[s]);s++)try{t(i).triggerHandler("remove")}catch(o){}n(e)},t.widget=function(i,s,n){var o,a,r,h,l={},c=i.split(".")[0];i=i.split(".")[1],o=c+"-"+i,n||(n=s,s=t.Widget),t.expr[":"][o.toLowerCase()]=function(e){return!!t.data(e,o)},t[c]=t[c]||{},a=t[c][i],r=t[c][i]=function(t,i){return this._createWidget?(arguments.length&&this._createWidget(t,i),e):new r(t,i)},t.extend(r,a,{version:n.version,_proto:t.extend({},n),_childConstructors:[]}),h=new s,h.options=t.widget.extend({},h.options),t.each(n,function(i,n){return t.isFunction(n)?(l[i]=function(){var t=function(){return s.prototype[i].apply(this,arguments)},e=function(t){return s.prototype[i].apply(this,t)};return function(){var i,s=this._super,o=this._superApply;return this._super=t,this._superApply=e,i=n.apply(this,arguments),this._super=s,this._superApply=o,i}}(),e):(l[i]=n,e)}),r.prototype=t.widget.extend(h,{widgetEventPrefix:a?h.widgetEventPrefix||i:i},l,{constructor:r,namespace:c,widgetName:i,widgetFullName:o}),a?(t.each(a._childConstructors,function(e,i){var s=i.prototype;t.widget(s.namespace+"."+s.widgetName,r,i._proto)}),delete a._childConstructors):s._childConstructors.push(r),t.widget.bridge(i,r)},t.widget.extend=function(i){for(var n,o,a=s.call(arguments,1),r=0,h=a.length;h>r;r++)for(n in a[r])o=a[r][n],a[r].hasOwnProperty(n)&&o!==e&&(i[n]=t.isPlainObject(o)?t.isPlainObject(i[n])?t.widget.extend({},i[n],o):t.widget.extend({},o):o);return i},t.widget.bridge=function(i,n){var o=n.prototype.widgetFullName||i;t.fn[i]=function(a){var r="string"==typeof a,h=s.call(arguments,1),l=this;return a=!r&&h.length?t.widget.extend.apply(null,[a].concat(h)):a,r?this.each(function(){var s,n=t.data(this,o);return n?t.isFunction(n[a])&&"_"!==a.charAt(0)?(s=n[a].apply(n,h),s!==n&&s!==e?(l=s&&s.jquery?l.pushStack(s.get()):s,!1):e):t.error("no such method '"+a+"' for "+i+" widget instance"):t.error("cannot call methods on "+i+" prior to initialization; "+"attempted to call method '"+a+"'")}):this.each(function(){var e=t.data(this,o);e?e.option(a||{})._init():t.data(this,o,new n(a,this))}),l}},t.Widget=function(){},t.Widget._childConstructors=[],t.Widget.prototype={widgetName:"widget",widgetEventPrefix:"",defaultElement:"<div>",options:{disabled:!1,create:null},_createWidget:function(e,s){s=t(s||this.defaultElement||this)[0],this.element=t(s),this.uuid=i++,this.eventNamespace="."+this.widgetName+this.uuid,this.options=t.widget.extend({},this.options,this._getCreateOptions(),e),this.bindings=t(),this.hoverable=t(),this.focusable=t(),s!==this&&(t.data(s,this.widgetFullName,this),this._on(!0,this.element,{remove:function(t){t.target===s&&this.destroy()}}),this.document=t(s.style?s.ownerDocument:s.document||s),this.window=t(this.document[0].defaultView||this.document[0].parentWindow)),this._create(),this._trigger("create",null,this._getCreateEventData()),this._init()},_getCreateOptions:t.noop,_getCreateEventData:t.noop,_create:t.noop,_init:t.noop,destroy:function(){this._destroy(),this.element.unbind(this.eventNamespace).removeData(this.widgetName).removeData(this.widgetFullName).removeData(t.camelCase(this.widgetFullName)),this.widget().unbind(this.eventNamespace).removeAttr("aria-disabled").removeClass(this.widgetFullName+"-disabled "+"ui-state-disabled"),this.bindings.unbind(this.eventNamespace),this.hoverable.removeClass("ui-state-hover"),this.focusable.removeClass("ui-state-focus")},_destroy:t.noop,widget:function(){return this.element},option:function(i,s){var n,o,a,r=i;if(0===arguments.length)return t.widget.extend({},this.options);if("string"==typeof i)if(r={},n=i.split("."),i=n.shift(),n.length){for(o=r[i]=t.widget.extend({},this.options[i]),a=0;n.length-1>a;a++)o[n[a]]=o[n[a]]||{},o=o[n[a]];if(i=n.pop(),1===arguments.length)return o[i]===e?null:o[i];o[i]=s}else{if(1===arguments.length)return this.options[i]===e?null:this.options[i];r[i]=s}return this._setOptions(r),this},_setOptions:function(t){var e;for(e in t)this._setOption(e,t[e]);return this},_setOption:function(t,e){return this.options[t]=e,"disabled"===t&&(this.widget().toggleClass(this.widgetFullName+"-disabled ui-state-disabled",!!e).attr("aria-disabled",e),this.hoverable.removeClass("ui-state-hover"),this.focusable.removeClass("ui-state-focus")),this},enable:function(){return this._setOption("disabled",!1)},disable:function(){return this._setOption("disabled",!0)},_on:function(i,s,n){var o,a=this;"boolean"!=typeof i&&(n=s,s=i,i=!1),n?(s=o=t(s),this.bindings=this.bindings.add(s)):(n=s,s=this.element,o=this.widget()),t.each(n,function(n,r){function h(){return i||a.options.disabled!==!0&&!t(this).hasClass("ui-state-disabled")?("string"==typeof r?a[r]:r).apply(a,arguments):e}"string"!=typeof r&&(h.guid=r.guid=r.guid||h.guid||t.guid++);var l=n.match(/^(\w+)\s*(.*)$/),c=l[1]+a.eventNamespace,u=l[2];u?o.delegate(u,c,h):s.bind(c,h)})},_off:function(t,e){e=(e||"").split(" ").join(this.eventNamespace+" ")+this.eventNamespace,t.unbind(e).undelegate(e)},_delay:function(t,e){function i(){return("string"==typeof t?s[t]:t).apply(s,arguments)}var s=this;return setTimeout(i,e||0)},_hoverable:function(e){this.hoverable=this.hoverable.add(e),this._on(e,{mouseenter:function(e){t(e.currentTarget).addClass("ui-state-hover")},mouseleave:function(e){t(e.currentTarget).removeClass("ui-state-hover")}})},_focusable:function(e){this.focusable=this.focusable.add(e),this._on(e,{focusin:function(e){t(e.currentTarget).addClass("ui-state-focus")},focusout:function(e){t(e.currentTarget).removeClass("ui-state-focus")}})},_trigger:function(e,i,s){var n,o,a=this.options[e];if(s=s||{},i=t.Event(i),i.type=(e===this.widgetEventPrefix?e:this.widgetEventPrefix+e).toLowerCase(),i.target=this.element[0],o=i.originalEvent)for(n in o)n in i||(i[n]=o[n]);return this.element.trigger(i,s),!(t.isFunction(a)&&a.apply(this.element[0],[i].concat(s))===!1||i.isDefaultPrevented())}},t.each({show:"fadeIn",hide:"fadeOut"},function(e,i){t.Widget.prototype["_"+e]=function(s,n,o){"string"==typeof n&&(n={effect:n});var a,r=n?n===!0||"number"==typeof n?i:n.effect||i:e;n=n||{},"number"==typeof n&&(n={duration:n}),a=!t.isEmptyObject(n),n.complete=o,n.delay&&s.delay(n.delay),a&&t.effects&&t.effects.effect[r]?s[e](n):r!==e&&s[r]?s[r](n.duration,n.easing,o):s.queue(function(i){t(this)[e](),o&&o.call(s[0]),i()})}})})(jQuery);(function(t){var e=!1;t(document).mouseup(function(){e=!1}),t.widget("ui.mouse",{version:"1.10.4",options:{cancel:"input,textarea,button,select,option",distance:1,delay:0},_mouseInit:function(){var e=this;this.element.bind("mousedown."+this.widgetName,function(t){return e._mouseDown(t)}).bind("click."+this.widgetName,function(i){return!0===t.data(i.target,e.widgetName+".preventClickEvent")?(t.removeData(i.target,e.widgetName+".preventClickEvent"),i.stopImmediatePropagation(),!1):undefined}),this.started=!1},_mouseDestroy:function(){this.element.unbind("."+this.widgetName),this._mouseMoveDelegate&&t(document).unbind("mousemove."+this.widgetName,this._mouseMoveDelegate).unbind("mouseup."+this.widgetName,this._mouseUpDelegate)},_mouseDown:function(i){if(!e){this._mouseStarted&&this._mouseUp(i),this._mouseDownEvent=i;var s=this,n=1===i.which,a="string"==typeof this.options.cancel&&i.target.nodeName?t(i.target).closest(this.options.cancel).length:!1;return n&&!a&&this._mouseCapture(i)?(this.mouseDelayMet=!this.options.delay,this.mouseDelayMet||(this._mouseDelayTimer=setTimeout(function(){s.mouseDelayMet=!0},this.options.delay)),this._mouseDistanceMet(i)&&this._mouseDelayMet(i)&&(this._mouseStarted=this._mouseStart(i)!==!1,!this._mouseStarted)?(i.preventDefault(),!0):(!0===t.data(i.target,this.widgetName+".preventClickEvent")&&t.removeData(i.target,this.widgetName+".preventClickEvent"),this._mouseMoveDelegate=function(t){return s._mouseMove(t)},this._mouseUpDelegate=function(t){return s._mouseUp(t)},t(document).bind("mousemove."+this.widgetName,this._mouseMoveDelegate).bind("mouseup."+this.widgetName,this._mouseUpDelegate),i.preventDefault(),e=!0,!0)):!0}},_mouseMove:function(e){return t.ui.ie&&(!document.documentMode||9>document.documentMode)&&!e.button?this._mouseUp(e):this._mouseStarted?(this._mouseDrag(e),e.preventDefault()):(this._mouseDistanceMet(e)&&this._mouseDelayMet(e)&&(this._mouseStarted=this._mouseStart(this._mouseDownEvent,e)!==!1,this._mouseStarted?this._mouseDrag(e):this._mouseUp(e)),!this._mouseStarted)},_mouseUp:function(e){return t(document).unbind("mousemove."+this.widgetName,this._mouseMoveDelegate).unbind("mouseup."+this.widgetName,this._mouseUpDelegate),this._mouseStarted&&(this._mouseStarted=!1,e.target===this._mouseDownEvent.target&&t.data(e.target,this.widgetName+".preventClickEvent",!0),this._mouseStop(e)),!1},_mouseDistanceMet:function(t){return Math.max(Math.abs(this._mouseDownEvent.pageX-t.pageX),Math.abs(this._mouseDownEvent.pageY-t.pageY))>=this.options.distance},_mouseDelayMet:function(){return this.mouseDelayMet},_mouseStart:function(){},_mouseDrag:function(){},_mouseStop:function(){},_mouseCapture:function(){return!0}})})(jQuery);(function(t,e){function i(t,e,i){return[parseFloat(t[0])*(p.test(t[0])?e/100:1),parseFloat(t[1])*(p.test(t[1])?i/100:1)]}function s(e,i){return parseInt(t.css(e,i),10)||0}function n(e){var i=e[0];return 9===i.nodeType?{width:e.width(),height:e.height(),offset:{top:0,left:0}}:t.isWindow(i)?{width:e.width(),height:e.height(),offset:{top:e.scrollTop(),left:e.scrollLeft()}}:i.preventDefault?{width:0,height:0,offset:{top:i.pageY,left:i.pageX}}:{width:e.outerWidth(),height:e.outerHeight(),offset:e.offset()}}t.ui=t.ui||{};var a,o=Math.max,r=Math.abs,l=Math.round,h=/left|center|right/,c=/top|center|bottom/,u=/[\+\-]\d+(\.[\d]+)?%?/,d=/^\w+/,p=/%$/,f=t.fn.position;t.position={scrollbarWidth:function(){if(a!==e)return a;var i,s,n=t("<div style='display:block;position:absolute;width:50px;height:50px;overflow:hidden;'><div style='height:100px;width:auto;'></div></div>"),o=n.children()[0];return t("body").append(n),i=o.offsetWidth,n.css("overflow","scroll"),s=o.offsetWidth,i===s&&(s=n[0].clientWidth),n.remove(),a=i-s},getScrollInfo:function(e){var i=e.isWindow||e.isDocument?"":e.element.css("overflow-x"),s=e.isWindow||e.isDocument?"":e.element.css("overflow-y"),n="scroll"===i||"auto"===i&&e.width<e.element[0].scrollWidth,a="scroll"===s||"auto"===s&&e.height<e.element[0].scrollHeight;return{width:a?t.position.scrollbarWidth():0,height:n?t.position.scrollbarWidth():0}},getWithinInfo:function(e){var i=t(e||window),s=t.isWindow(i[0]),n=!!i[0]&&9===i[0].nodeType;return{element:i,isWindow:s,isDocument:n,offset:i.offset()||{left:0,top:0},scrollLeft:i.scrollLeft(),scrollTop:i.scrollTop(),width:s?i.width():i.outerWidth(),height:s?i.height():i.outerHeight()}}},t.fn.position=function(e){if(!e||!e.of)return f.apply(this,arguments);e=t.extend({},e);var a,p,g,m,v,_,b=t(e.of),y=t.position.getWithinInfo(e.within),k=t.position.getScrollInfo(y),w=(e.collision||"flip").split(" "),D={};return _=n(b),b[0].preventDefault&&(e.at="left top"),p=_.width,g=_.height,m=_.offset,v=t.extend({},m),t.each(["my","at"],function(){var t,i,s=(e[this]||"").split(" ");1===s.length&&(s=h.test(s[0])?s.concat(["center"]):c.test(s[0])?["center"].concat(s):["center","center"]),s[0]=h.test(s[0])?s[0]:"center",s[1]=c.test(s[1])?s[1]:"center",t=u.exec(s[0]),i=u.exec(s[1]),D[this]=[t?t[0]:0,i?i[0]:0],e[this]=[d.exec(s[0])[0],d.exec(s[1])[0]]}),1===w.length&&(w[1]=w[0]),"right"===e.at[0]?v.left+=p:"center"===e.at[0]&&(v.left+=p/2),"bottom"===e.at[1]?v.top+=g:"center"===e.at[1]&&(v.top+=g/2),a=i(D.at,p,g),v.left+=a[0],v.top+=a[1],this.each(function(){var n,h,c=t(this),u=c.outerWidth(),d=c.outerHeight(),f=s(this,"marginLeft"),_=s(this,"marginTop"),x=u+f+s(this,"marginRight")+k.width,C=d+_+s(this,"marginBottom")+k.height,M=t.extend({},v),T=i(D.my,c.outerWidth(),c.outerHeight());"right"===e.my[0]?M.left-=u:"center"===e.my[0]&&(M.left-=u/2),"bottom"===e.my[1]?M.top-=d:"center"===e.my[1]&&(M.top-=d/2),M.left+=T[0],M.top+=T[1],t.support.offsetFractions||(M.left=l(M.left),M.top=l(M.top)),n={marginLeft:f,marginTop:_},t.each(["left","top"],function(i,s){t.ui.position[w[i]]&&t.ui.position[w[i]][s](M,{targetWidth:p,targetHeight:g,elemWidth:u,elemHeight:d,collisionPosition:n,collisionWidth:x,collisionHeight:C,offset:[a[0]+T[0],a[1]+T[1]],my:e.my,at:e.at,within:y,elem:c})}),e.using&&(h=function(t){var i=m.left-M.left,s=i+p-u,n=m.top-M.top,a=n+g-d,l={target:{element:b,left:m.left,top:m.top,width:p,height:g},element:{element:c,left:M.left,top:M.top,width:u,height:d},horizontal:0>s?"left":i>0?"right":"center",vertical:0>a?"top":n>0?"bottom":"middle"};u>p&&p>r(i+s)&&(l.horizontal="center"),d>g&&g>r(n+a)&&(l.vertical="middle"),l.important=o(r(i),r(s))>o(r(n),r(a))?"horizontal":"vertical",e.using.call(this,t,l)}),c.offset(t.extend(M,{using:h}))})},t.ui.position={fit:{left:function(t,e){var i,s=e.within,n=s.isWindow?s.scrollLeft:s.offset.left,a=s.width,r=t.left-e.collisionPosition.marginLeft,l=n-r,h=r+e.collisionWidth-a-n;e.collisionWidth>a?l>0&&0>=h?(i=t.left+l+e.collisionWidth-a-n,t.left+=l-i):t.left=h>0&&0>=l?n:l>h?n+a-e.collisionWidth:n:l>0?t.left+=l:h>0?t.left-=h:t.left=o(t.left-r,t.left)},top:function(t,e){var i,s=e.within,n=s.isWindow?s.scrollTop:s.offset.top,a=e.within.height,r=t.top-e.collisionPosition.marginTop,l=n-r,h=r+e.collisionHeight-a-n;e.collisionHeight>a?l>0&&0>=h?(i=t.top+l+e.collisionHeight-a-n,t.top+=l-i):t.top=h>0&&0>=l?n:l>h?n+a-e.collisionHeight:n:l>0?t.top+=l:h>0?t.top-=h:t.top=o(t.top-r,t.top)}},flip:{left:function(t,e){var i,s,n=e.within,a=n.offset.left+n.scrollLeft,o=n.width,l=n.isWindow?n.scrollLeft:n.offset.left,h=t.left-e.collisionPosition.marginLeft,c=h-l,u=h+e.collisionWidth-o-l,d="left"===e.my[0]?-e.elemWidth:"right"===e.my[0]?e.elemWidth:0,p="left"===e.at[0]?e.targetWidth:"right"===e.at[0]?-e.targetWidth:0,f=-2*e.offset[0];0>c?(i=t.left+d+p+f+e.collisionWidth-o-a,(0>i||r(c)>i)&&(t.left+=d+p+f)):u>0&&(s=t.left-e.collisionPosition.marginLeft+d+p+f-l,(s>0||u>r(s))&&(t.left+=d+p+f))},top:function(t,e){var i,s,n=e.within,a=n.offset.top+n.scrollTop,o=n.height,l=n.isWindow?n.scrollTop:n.offset.top,h=t.top-e.collisionPosition.marginTop,c=h-l,u=h+e.collisionHeight-o-l,d="top"===e.my[1],p=d?-e.elemHeight:"bottom"===e.my[1]?e.elemHeight:0,f="top"===e.at[1]?e.targetHeight:"bottom"===e.at[1]?-e.targetHeight:0,g=-2*e.offset[1];0>c?(s=t.top+p+f+g+e.collisionHeight-o-a,t.top+p+f+g>c&&(0>s||r(c)>s)&&(t.top+=p+f+g)):u>0&&(i=t.top-e.collisionPosition.marginTop+p+f+g-l,t.top+p+f+g>u&&(i>0||u>r(i))&&(t.top+=p+f+g))}},flipfit:{left:function(){t.ui.position.flip.left.apply(this,arguments),t.ui.position.fit.left.apply(this,arguments)},top:function(){t.ui.position.flip.top.apply(this,arguments),t.ui.position.fit.top.apply(this,arguments)}}},function(){var e,i,s,n,a,o=document.getElementsByTagName("body")[0],r=document.createElement("div");e=document.createElement(o?"div":"body"),s={visibility:"hidden",width:0,height:0,border:0,margin:0,background:"none"},o&&t.extend(s,{position:"absolute",left:"-1000px",top:"-1000px"});for(a in s)e.style[a]=s[a];e.appendChild(r),i=o||document.documentElement,i.insertBefore(e,i.firstChild),r.style.cssText="position: absolute; left: 10.7432222px;",n=t(r).offset().left,t.support.offsetFractions=n>10&&11>n,e.innerHTML="",i.removeChild(e)}()})(jQuery);(function(t){t.widget("ui.draggable",t.ui.mouse,{version:"1.10.4",widgetEventPrefix:"drag",options:{addClasses:!0,appendTo:"parent",axis:!1,connectToSortable:!1,containment:!1,cursor:"auto",cursorAt:!1,grid:!1,handle:!1,helper:"original",iframeFix:!1,opacity:!1,refreshPositions:!1,revert:!1,revertDuration:500,scope:"default",scroll:!0,scrollSensitivity:20,scrollSpeed:20,snap:!1,snapMode:"both",snapTolerance:20,stack:!1,zIndex:!1,drag:null,start:null,stop:null},_create:function(){"original"!==this.options.helper||/^(?:r|a|f)/.test(this.element.css("position"))||(this.element[0].style.position="relative"),this.options.addClasses&&this.element.addClass("ui-draggable"),this.options.disabled&&this.element.addClass("ui-draggable-disabled"),this._mouseInit()},_destroy:function(){this.element.removeClass("ui-draggable ui-draggable-dragging ui-draggable-disabled"),this._mouseDestroy()},_mouseCapture:function(e){var i=this.options;return this.helper||i.disabled||t(e.target).closest(".ui-resizable-handle").length>0?!1:(this.handle=this._getHandle(e),this.handle?(t(i.iframeFix===!0?"iframe":i.iframeFix).each(function(){t("<div class='ui-draggable-iframeFix' style='background: #fff;'></div>").css({width:this.offsetWidth+"px",height:this.offsetHeight+"px",position:"absolute",opacity:"0.001",zIndex:1e3}).css(t(this).offset()).appendTo("body")}),!0):!1)},_mouseStart:function(e){var i=this.options;return this.helper=this._createHelper(e),this.helper.addClass("ui-draggable-dragging"),this._cacheHelperProportions(),t.ui.ddmanager&&(t.ui.ddmanager.current=this),this._cacheMargins(),this.cssPosition=this.helper.css("position"),this.scrollParent=this.helper.scrollParent(),this.offsetParent=this.helper.offsetParent(),this.offsetParentCssPosition=this.offsetParent.css("position"),this.offset=this.positionAbs=this.element.offset(),this.offset={top:this.offset.top-this.margins.top,left:this.offset.left-this.margins.left},this.offset.scroll=!1,t.extend(this.offset,{click:{left:e.pageX-this.offset.left,top:e.pageY-this.offset.top},parent:this._getParentOffset(),relative:this._getRelativeOffset()}),this.originalPosition=this.position=this._generatePosition(e),this.originalPageX=e.pageX,this.originalPageY=e.pageY,i.cursorAt&&this._adjustOffsetFromHelper(i.cursorAt),this._setContainment(),this._trigger("start",e)===!1?(this._clear(),!1):(this._cacheHelperProportions(),t.ui.ddmanager&&!i.dropBehaviour&&t.ui.ddmanager.prepareOffsets(this,e),this._mouseDrag(e,!0),t.ui.ddmanager&&t.ui.ddmanager.dragStart(this,e),!0)},_mouseDrag:function(e,i){if("fixed"===this.offsetParentCssPosition&&(this.offset.parent=this._getParentOffset()),this.position=this._generatePosition(e),this.positionAbs=this._convertPositionTo("absolute"),!i){var s=this._uiHash();if(this._trigger("drag",e,s)===!1)return this._mouseUp({}),!1;this.position=s.position}return this.options.axis&&"y"===this.options.axis||(this.helper[0].style.left=this.position.left+"px"),this.options.axis&&"x"===this.options.axis||(this.helper[0].style.top=this.position.top+"px"),t.ui.ddmanager&&t.ui.ddmanager.drag(this,e),!1},_mouseStop:function(e){var i=this,s=!1;return t.ui.ddmanager&&!this.options.dropBehaviour&&(s=t.ui.ddmanager.drop(this,e)),this.dropped&&(s=this.dropped,this.dropped=!1),"original"!==this.options.helper||t.contains(this.element[0].ownerDocument,this.element[0])?("invalid"===this.options.revert&&!s||"valid"===this.options.revert&&s||this.options.revert===!0||t.isFunction(this.options.revert)&&this.options.revert.call(this.element,s)?t(this.helper).animate(this.originalPosition,parseInt(this.options.revertDuration,10),function(){i._trigger("stop",e)!==!1&&i._clear()}):this._trigger("stop",e)!==!1&&this._clear(),!1):!1},_mouseUp:function(e){return t("div.ui-draggable-iframeFix").each(function(){this.parentNode.removeChild(this)}),t.ui.ddmanager&&t.ui.ddmanager.dragStop(this,e),t.ui.mouse.prototype._mouseUp.call(this,e)},cancel:function(){return this.helper.is(".ui-draggable-dragging")?this._mouseUp({}):this._clear(),this},_getHandle:function(e){return this.options.handle?!!t(e.target).closest(this.element.find(this.options.handle)).length:!0},_createHelper:function(e){var i=this.options,s=t.isFunction(i.helper)?t(i.helper.apply(this.element[0],[e])):"clone"===i.helper?this.element.clone().removeAttr("id"):this.element;return s.parents("body").length||s.appendTo("parent"===i.appendTo?this.element[0].parentNode:i.appendTo),s[0]===this.element[0]||/(fixed|absolute)/.test(s.css("position"))||s.css("position","absolute"),s},_adjustOffsetFromHelper:function(e){"string"==typeof e&&(e=e.split(" ")),t.isArray(e)&&(e={left:+e[0],top:+e[1]||0}),"left"in e&&(this.offset.click.left=e.left+this.margins.left),"right"in e&&(this.offset.click.left=this.helperProportions.width-e.right+this.margins.left),"top"in e&&(this.offset.click.top=e.top+this.margins.top),"bottom"in e&&(this.offset.click.top=this.helperProportions.height-e.bottom+this.margins.top)},_getParentOffset:function(){var e=this.offsetParent.offset();return"absolute"===this.cssPosition&&this.scrollParent[0]!==document&&t.contains(this.scrollParent[0],this.offsetParent[0])&&(e.left+=this.scrollParent.scrollLeft(),e.top+=this.scrollParent.scrollTop()),(this.offsetParent[0]===document.body||this.offsetParent[0].tagName&&"html"===this.offsetParent[0].tagName.toLowerCase()&&t.ui.ie)&&(e={top:0,left:0}),{top:e.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:e.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)}},_getRelativeOffset:function(){if("relative"===this.cssPosition){var t=this.element.position();return{top:t.top-(parseInt(this.helper.css("top"),10)||0)+this.scrollParent.scrollTop(),left:t.left-(parseInt(this.helper.css("left"),10)||0)+this.scrollParent.scrollLeft()}}return{top:0,left:0}},_cacheMargins:function(){this.margins={left:parseInt(this.element.css("marginLeft"),10)||0,top:parseInt(this.element.css("marginTop"),10)||0,right:parseInt(this.element.css("marginRight"),10)||0,bottom:parseInt(this.element.css("marginBottom"),10)||0}},_cacheHelperProportions:function(){this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()}},_setContainment:function(){var e,i,s,n=this.options;return n.containment?"window"===n.containment?(this.containment=[t(window).scrollLeft()-this.offset.relative.left-this.offset.parent.left,t(window).scrollTop()-this.offset.relative.top-this.offset.parent.top,t(window).scrollLeft()+t(window).width()-this.helperProportions.width-this.margins.left,t(window).scrollTop()+(t(window).height()||document.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top],undefined):"document"===n.containment?(this.containment=[0,0,t(document).width()-this.helperProportions.width-this.margins.left,(t(document).height()||document.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top],undefined):n.containment.constructor===Array?(this.containment=n.containment,undefined):("parent"===n.containment&&(n.containment=this.helper[0].parentNode),i=t(n.containment),s=i[0],s&&(e="hidden"!==i.css("overflow"),this.containment=[(parseInt(i.css("borderLeftWidth"),10)||0)+(parseInt(i.css("paddingLeft"),10)||0),(parseInt(i.css("borderTopWidth"),10)||0)+(parseInt(i.css("paddingTop"),10)||0),(e?Math.max(s.scrollWidth,s.offsetWidth):s.offsetWidth)-(parseInt(i.css("borderRightWidth"),10)||0)-(parseInt(i.css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left-this.margins.right,(e?Math.max(s.scrollHeight,s.offsetHeight):s.offsetHeight)-(parseInt(i.css("borderBottomWidth"),10)||0)-(parseInt(i.css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top-this.margins.bottom],this.relative_container=i),undefined):(this.containment=null,undefined)},_convertPositionTo:function(e,i){i||(i=this.position);var s="absolute"===e?1:-1,n="absolute"!==this.cssPosition||this.scrollParent[0]!==document&&t.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent;return this.offset.scroll||(this.offset.scroll={top:n.scrollTop(),left:n.scrollLeft()}),{top:i.top+this.offset.relative.top*s+this.offset.parent.top*s-("fixed"===this.cssPosition?-this.scrollParent.scrollTop():this.offset.scroll.top)*s,left:i.left+this.offset.relative.left*s+this.offset.parent.left*s-("fixed"===this.cssPosition?-this.scrollParent.scrollLeft():this.offset.scroll.left)*s}},_generatePosition:function(e){var i,s,n,a,o=this.options,r="absolute"!==this.cssPosition||this.scrollParent[0]!==document&&t.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent,l=e.pageX,h=e.pageY;return this.offset.scroll||(this.offset.scroll={top:r.scrollTop(),left:r.scrollLeft()}),this.originalPosition&&(this.containment&&(this.relative_container?(s=this.relative_container.offset(),i=[this.containment[0]+s.left,this.containment[1]+s.top,this.containment[2]+s.left,this.containment[3]+s.top]):i=this.containment,e.pageX-this.offset.click.left<i[0]&&(l=i[0]+this.offset.click.left),e.pageY-this.offset.click.top<i[1]&&(h=i[1]+this.offset.click.top),e.pageX-this.offset.click.left>i[2]&&(l=i[2]+this.offset.click.left),e.pageY-this.offset.click.top>i[3]&&(h=i[3]+this.offset.click.top)),o.grid&&(n=o.grid[1]?this.originalPageY+Math.round((h-this.originalPageY)/o.grid[1])*o.grid[1]:this.originalPageY,h=i?n-this.offset.click.top>=i[1]||n-this.offset.click.top>i[3]?n:n-this.offset.click.top>=i[1]?n-o.grid[1]:n+o.grid[1]:n,a=o.grid[0]?this.originalPageX+Math.round((l-this.originalPageX)/o.grid[0])*o.grid[0]:this.originalPageX,l=i?a-this.offset.click.left>=i[0]||a-this.offset.click.left>i[2]?a:a-this.offset.click.left>=i[0]?a-o.grid[0]:a+o.grid[0]:a)),{top:h-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+("fixed"===this.cssPosition?-this.scrollParent.scrollTop():this.offset.scroll.top),left:l-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+("fixed"===this.cssPosition?-this.scrollParent.scrollLeft():this.offset.scroll.left)}},_clear:function(){this.helper.removeClass("ui-draggable-dragging"),this.helper[0]===this.element[0]||this.cancelHelperRemoval||this.helper.remove(),this.helper=null,this.cancelHelperRemoval=!1},_trigger:function(e,i,s){return s=s||this._uiHash(),t.ui.plugin.call(this,e,[i,s]),"drag"===e&&(this.positionAbs=this._convertPositionTo("absolute")),t.Widget.prototype._trigger.call(this,e,i,s)},plugins:{},_uiHash:function(){return{helper:this.helper,position:this.position,originalPosition:this.originalPosition,offset:this.positionAbs}}}),t.ui.plugin.add("draggable","connectToSortable",{start:function(e,i){var s=t(this).data("ui-draggable"),n=s.options,a=t.extend({},i,{item:s.element});s.sortables=[],t(n.connectToSortable).each(function(){var i=t.data(this,"ui-sortable");i&&!i.options.disabled&&(s.sortables.push({instance:i,shouldRevert:i.options.revert}),i.refreshPositions(),i._trigger("activate",e,a))})},stop:function(e,i){var s=t(this).data("ui-draggable"),n=t.extend({},i,{item:s.element});t.each(s.sortables,function(){this.instance.isOver?(this.instance.isOver=0,s.cancelHelperRemoval=!0,this.instance.cancelHelperRemoval=!1,this.shouldRevert&&(this.instance.options.revert=this.shouldRevert),this.instance._mouseStop(e),this.instance.options.helper=this.instance.options._helper,"original"===s.options.helper&&this.instance.currentItem.css({top:"auto",left:"auto"})):(this.instance.cancelHelperRemoval=!1,this.instance._trigger("deactivate",e,n))})},drag:function(e,i){var s=t(this).data("ui-draggable"),n=this;t.each(s.sortables,function(){var a=!1,o=this;this.instance.positionAbs=s.positionAbs,this.instance.helperProportions=s.helperProportions,this.instance.offset.click=s.offset.click,this.instance._intersectsWith(this.instance.containerCache)&&(a=!0,t.each(s.sortables,function(){return this.instance.positionAbs=s.positionAbs,this.instance.helperProportions=s.helperProportions,this.instance.offset.click=s.offset.click,this!==o&&this.instance._intersectsWith(this.instance.containerCache)&&t.contains(o.instance.element[0],this.instance.element[0])&&(a=!1),a})),a?(this.instance.isOver||(this.instance.isOver=1,this.instance.currentItem=t(n).clone().removeAttr("id").appendTo(this.instance.element).data("ui-sortable-item",!0),this.instance.options._helper=this.instance.options.helper,this.instance.options.helper=function(){return i.helper[0]},e.target=this.instance.currentItem[0],this.instance._mouseCapture(e,!0),this.instance._mouseStart(e,!0,!0),this.instance.offset.click.top=s.offset.click.top,this.instance.offset.click.left=s.offset.click.left,this.instance.offset.parent.left-=s.offset.parent.left-this.instance.offset.parent.left,this.instance.offset.parent.top-=s.offset.parent.top-this.instance.offset.parent.top,s._trigger("toSortable",e),s.dropped=this.instance.element,s.currentItem=s.element,this.instance.fromOutside=s),this.instance.currentItem&&this.instance._mouseDrag(e)):this.instance.isOver&&(this.instance.isOver=0,this.instance.cancelHelperRemoval=!0,this.instance.options.revert=!1,this.instance._trigger("out",e,this.instance._uiHash(this.instance)),this.instance._mouseStop(e,!0),this.instance.options.helper=this.instance.options._helper,this.instance.currentItem.remove(),this.instance.placeholder&&this.instance.placeholder.remove(),s._trigger("fromSortable",e),s.dropped=!1)})}}),t.ui.plugin.add("draggable","cursor",{start:function(){var e=t("body"),i=t(this).data("ui-draggable").options;e.css("cursor")&&(i._cursor=e.css("cursor")),e.css("cursor",i.cursor)},stop:function(){var e=t(this).data("ui-draggable").options;e._cursor&&t("body").css("cursor",e._cursor)}}),t.ui.plugin.add("draggable","opacity",{start:function(e,i){var s=t(i.helper),n=t(this).data("ui-draggable").options;s.css("opacity")&&(n._opacity=s.css("opacity")),s.css("opacity",n.opacity)},stop:function(e,i){var s=t(this).data("ui-draggable").options;s._opacity&&t(i.helper).css("opacity",s._opacity)}}),t.ui.plugin.add("draggable","scroll",{start:function(){var e=t(this).data("ui-draggable");e.scrollParent[0]!==document&&"HTML"!==e.scrollParent[0].tagName&&(e.overflowOffset=e.scrollParent.offset())},drag:function(e){var i=t(this).data("ui-draggable"),s=i.options,n=!1;i.scrollParent[0]!==document&&"HTML"!==i.scrollParent[0].tagName?(s.axis&&"x"===s.axis||(i.overflowOffset.top+i.scrollParent[0].offsetHeight-e.pageY<s.scrollSensitivity?i.scrollParent[0].scrollTop=n=i.scrollParent[0].scrollTop+s.scrollSpeed:e.pageY-i.overflowOffset.top<s.scrollSensitivity&&(i.scrollParent[0].scrollTop=n=i.scrollParent[0].scrollTop-s.scrollSpeed)),s.axis&&"y"===s.axis||(i.overflowOffset.left+i.scrollParent[0].offsetWidth-e.pageX<s.scrollSensitivity?i.scrollParent[0].scrollLeft=n=i.scrollParent[0].scrollLeft+s.scrollSpeed:e.pageX-i.overflowOffset.left<s.scrollSensitivity&&(i.scrollParent[0].scrollLeft=n=i.scrollParent[0].scrollLeft-s.scrollSpeed))):(s.axis&&"x"===s.axis||(e.pageY-t(document).scrollTop()<s.scrollSensitivity?n=t(document).scrollTop(t(document).scrollTop()-s.scrollSpeed):t(window).height()-(e.pageY-t(document).scrollTop())<s.scrollSensitivity&&(n=t(document).scrollTop(t(document).scrollTop()+s.scrollSpeed))),s.axis&&"y"===s.axis||(e.pageX-t(document).scrollLeft()<s.scrollSensitivity?n=t(document).scrollLeft(t(document).scrollLeft()-s.scrollSpeed):t(window).width()-(e.pageX-t(document).scrollLeft())<s.scrollSensitivity&&(n=t(document).scrollLeft(t(document).scrollLeft()+s.scrollSpeed)))),n!==!1&&t.ui.ddmanager&&!s.dropBehaviour&&t.ui.ddmanager.prepareOffsets(i,e)}}),t.ui.plugin.add("draggable","snap",{start:function(){var e=t(this).data("ui-draggable"),i=e.options;e.snapElements=[],t(i.snap.constructor!==String?i.snap.items||":data(ui-draggable)":i.snap).each(function(){var i=t(this),s=i.offset();this!==e.element[0]&&e.snapElements.push({item:this,width:i.outerWidth(),height:i.outerHeight(),top:s.top,left:s.left})})},drag:function(e,i){var s,n,a,o,r,l,h,c,u,d,p=t(this).data("ui-draggable"),g=p.options,f=g.snapTolerance,m=i.offset.left,_=m+p.helperProportions.width,v=i.offset.top,b=v+p.helperProportions.height;for(u=p.snapElements.length-1;u>=0;u--)r=p.snapElements[u].left,l=r+p.snapElements[u].width,h=p.snapElements[u].top,c=h+p.snapElements[u].height,r-f>_||m>l+f||h-f>b||v>c+f||!t.contains(p.snapElements[u].item.ownerDocument,p.snapElements[u].item)?(p.snapElements[u].snapping&&p.options.snap.release&&p.options.snap.release.call(p.element,e,t.extend(p._uiHash(),{snapItem:p.snapElements[u].item})),p.snapElements[u].snapping=!1):("inner"!==g.snapMode&&(s=f>=Math.abs(h-b),n=f>=Math.abs(c-v),a=f>=Math.abs(r-_),o=f>=Math.abs(l-m),s&&(i.position.top=p._convertPositionTo("relative",{top:h-p.helperProportions.height,left:0}).top-p.margins.top),n&&(i.position.top=p._convertPositionTo("relative",{top:c,left:0}).top-p.margins.top),a&&(i.position.left=p._convertPositionTo("relative",{top:0,left:r-p.helperProportions.width}).left-p.margins.left),o&&(i.position.left=p._convertPositionTo("relative",{top:0,left:l}).left-p.margins.left)),d=s||n||a||o,"outer"!==g.snapMode&&(s=f>=Math.abs(h-v),n=f>=Math.abs(c-b),a=f>=Math.abs(r-m),o=f>=Math.abs(l-_),s&&(i.position.top=p._convertPositionTo("relative",{top:h,left:0}).top-p.margins.top),n&&(i.position.top=p._convertPositionTo("relative",{top:c-p.helperProportions.height,left:0}).top-p.margins.top),a&&(i.position.left=p._convertPositionTo("relative",{top:0,left:r}).left-p.margins.left),o&&(i.position.left=p._convertPositionTo("relative",{top:0,left:l-p.helperProportions.width}).left-p.margins.left)),!p.snapElements[u].snapping&&(s||n||a||o||d)&&p.options.snap.snap&&p.options.snap.snap.call(p.element,e,t.extend(p._uiHash(),{snapItem:p.snapElements[u].item})),p.snapElements[u].snapping=s||n||a||o||d)}}),t.ui.plugin.add("draggable","stack",{start:function(){var e,i=this.data("ui-draggable").options,s=t.makeArray(t(i.stack)).sort(function(e,i){return(parseInt(t(e).css("zIndex"),10)||0)-(parseInt(t(i).css("zIndex"),10)||0)});s.length&&(e=parseInt(t(s[0]).css("zIndex"),10)||0,t(s).each(function(i){t(this).css("zIndex",e+i)}),this.css("zIndex",e+s.length))}}),t.ui.plugin.add("draggable","zIndex",{start:function(e,i){var s=t(i.helper),n=t(this).data("ui-draggable").options;s.css("zIndex")&&(n._zIndex=s.css("zIndex")),s.css("zIndex",n.zIndex)},stop:function(e,i){var s=t(this).data("ui-draggable").options;s._zIndex&&t(i.helper).css("zIndex",s._zIndex)}})})(jQuery);(function(t){function e(t,e,i){return t>e&&e+i>t}t.widget("ui.droppable",{version:"1.10.4",widgetEventPrefix:"drop",options:{accept:"*",activeClass:!1,addClasses:!0,greedy:!1,hoverClass:!1,scope:"default",tolerance:"intersect",activate:null,deactivate:null,drop:null,out:null,over:null},_create:function(){var e,i=this.options,s=i.accept;this.isover=!1,this.isout=!0,this.accept=t.isFunction(s)?s:function(t){return t.is(s)},this.proportions=function(){return arguments.length?(e=arguments[0],undefined):e?e:e={width:this.element[0].offsetWidth,height:this.element[0].offsetHeight}},t.ui.ddmanager.droppables[i.scope]=t.ui.ddmanager.droppables[i.scope]||[],t.ui.ddmanager.droppables[i.scope].push(this),i.addClasses&&this.element.addClass("ui-droppable")},_destroy:function(){for(var e=0,i=t.ui.ddmanager.droppables[this.options.scope];i.length>e;e++)i[e]===this&&i.splice(e,1);this.element.removeClass("ui-droppable ui-droppable-disabled")},_setOption:function(e,i){"accept"===e&&(this.accept=t.isFunction(i)?i:function(t){return t.is(i)}),t.Widget.prototype._setOption.apply(this,arguments)},_activate:function(e){var i=t.ui.ddmanager.current;this.options.activeClass&&this.element.addClass(this.options.activeClass),i&&this._trigger("activate",e,this.ui(i))},_deactivate:function(e){var i=t.ui.ddmanager.current;this.options.activeClass&&this.element.removeClass(this.options.activeClass),i&&this._trigger("deactivate",e,this.ui(i))},_over:function(e){var i=t.ui.ddmanager.current;i&&(i.currentItem||i.element)[0]!==this.element[0]&&this.accept.call(this.element[0],i.currentItem||i.element)&&(this.options.hoverClass&&this.element.addClass(this.options.hoverClass),this._trigger("over",e,this.ui(i)))},_out:function(e){var i=t.ui.ddmanager.current;i&&(i.currentItem||i.element)[0]!==this.element[0]&&this.accept.call(this.element[0],i.currentItem||i.element)&&(this.options.hoverClass&&this.element.removeClass(this.options.hoverClass),this._trigger("out",e,this.ui(i)))},_drop:function(e,i){var s=i||t.ui.ddmanager.current,n=!1;return s&&(s.currentItem||s.element)[0]!==this.element[0]?(this.element.find(":data(ui-droppable)").not(".ui-draggable-dragging").each(function(){var e=t.data(this,"ui-droppable");return e.options.greedy&&!e.options.disabled&&e.options.scope===s.options.scope&&e.accept.call(e.element[0],s.currentItem||s.element)&&t.ui.intersect(s,t.extend(e,{offset:e.element.offset()}),e.options.tolerance)?(n=!0,!1):undefined}),n?!1:this.accept.call(this.element[0],s.currentItem||s.element)?(this.options.activeClass&&this.element.removeClass(this.options.activeClass),this.options.hoverClass&&this.element.removeClass(this.options.hoverClass),this._trigger("drop",e,this.ui(s)),this.element):!1):!1},ui:function(t){return{draggable:t.currentItem||t.element,helper:t.helper,position:t.position,offset:t.positionAbs}}}),t.ui.intersect=function(t,i,s){if(!i.offset)return!1;var n,a,o=(t.positionAbs||t.position.absolute).left,r=(t.positionAbs||t.position.absolute).top,l=o+t.helperProportions.width,h=r+t.helperProportions.height,c=i.offset.left,u=i.offset.top,d=c+i.proportions().width,p=u+i.proportions().height;switch(s){case"fit":return o>=c&&d>=l&&r>=u&&p>=h;case"intersect":return o+t.helperProportions.width/2>c&&d>l-t.helperProportions.width/2&&r+t.helperProportions.height/2>u&&p>h-t.helperProportions.height/2;case"pointer":return n=(t.positionAbs||t.position.absolute).left+(t.clickOffset||t.offset.click).left,a=(t.positionAbs||t.position.absolute).top+(t.clickOffset||t.offset.click).top,e(a,u,i.proportions().height)&&e(n,c,i.proportions().width);case"touch":return(r>=u&&p>=r||h>=u&&p>=h||u>r&&h>p)&&(o>=c&&d>=o||l>=c&&d>=l||c>o&&l>d);default:return!1}},t.ui.ddmanager={current:null,droppables:{"default":[]},prepareOffsets:function(e,i){var s,n,a=t.ui.ddmanager.droppables[e.options.scope]||[],o=i?i.type:null,r=(e.currentItem||e.element).find(":data(ui-droppable)").addBack();t:for(s=0;a.length>s;s++)if(!(a[s].options.disabled||e&&!a[s].accept.call(a[s].element[0],e.currentItem||e.element))){for(n=0;r.length>n;n++)if(r[n]===a[s].element[0]){a[s].proportions().height=0;continue t}a[s].visible="none"!==a[s].element.css("display"),a[s].visible&&("mousedown"===o&&a[s]._activate.call(a[s],i),a[s].offset=a[s].element.offset(),a[s].proportions({width:a[s].element[0].offsetWidth,height:a[s].element[0].offsetHeight}))}},drop:function(e,i){var s=!1;return t.each((t.ui.ddmanager.droppables[e.options.scope]||[]).slice(),function(){this.options&&(!this.options.disabled&&this.visible&&t.ui.intersect(e,this,this.options.tolerance)&&(s=this._drop.call(this,i)||s),!this.options.disabled&&this.visible&&this.accept.call(this.element[0],e.currentItem||e.element)&&(this.isout=!0,this.isover=!1,this._deactivate.call(this,i)))}),s},dragStart:function(e,i){e.element.parentsUntil("body").bind("scroll.droppable",function(){e.options.refreshPositions||t.ui.ddmanager.prepareOffsets(e,i)})},drag:function(e,i){e.options.refreshPositions&&t.ui.ddmanager.prepareOffsets(e,i),t.each(t.ui.ddmanager.droppables[e.options.scope]||[],function(){if(!this.options.disabled&&!this.greedyChild&&this.visible){var s,n,a,o=t.ui.intersect(e,this,this.options.tolerance),r=!o&&this.isover?"isout":o&&!this.isover?"isover":null;r&&(this.options.greedy&&(n=this.options.scope,a=this.element.parents(":data(ui-droppable)").filter(function(){return t.data(this,"ui-droppable").options.scope===n}),a.length&&(s=t.data(a[0],"ui-droppable"),s.greedyChild="isover"===r)),s&&"isover"===r&&(s.isover=!1,s.isout=!0,s._out.call(s,i)),this[r]=!0,this["isout"===r?"isover":"isout"]=!1,this["isover"===r?"_over":"_out"].call(this,i),s&&"isout"===r&&(s.isout=!1,s.isover=!0,s._over.call(s,i)))}})},dragStop:function(e,i){e.element.parentsUntil("body").unbind("scroll.droppable"),e.options.refreshPositions||t.ui.ddmanager.prepareOffsets(e,i)}}})(jQuery);(function(t){function e(t){return parseInt(t,10)||0}function i(t){return!isNaN(parseInt(t,10))}t.widget("ui.resizable",t.ui.mouse,{version:"1.10.4",widgetEventPrefix:"resize",options:{alsoResize:!1,animate:!1,animateDuration:"slow",animateEasing:"swing",aspectRatio:!1,autoHide:!1,containment:!1,ghost:!1,grid:!1,handles:"e,s,se",helper:!1,maxHeight:null,maxWidth:null,minHeight:10,minWidth:10,zIndex:90,resize:null,start:null,stop:null},_create:function(){var e,i,s,n,a,o=this,r=this.options;if(this.element.addClass("ui-resizable"),t.extend(this,{_aspectRatio:!!r.aspectRatio,aspectRatio:r.aspectRatio,originalElement:this.element,_proportionallyResizeElements:[],_helper:r.helper||r.ghost||r.animate?r.helper||"ui-resizable-helper":null}),this.element[0].nodeName.match(/canvas|textarea|input|select|button|img/i)&&(this.element.wrap(t("<div class='ui-wrapper' style='overflow: hidden;'></div>").css({position:this.element.css("position"),width:this.element.outerWidth(),height:this.element.outerHeight(),top:this.element.css("top"),left:this.element.css("left")})),this.element=this.element.parent().data("ui-resizable",this.element.data("ui-resizable")),this.elementIsWrapper=!0,this.element.css({marginLeft:this.originalElement.css("marginLeft"),marginTop:this.originalElement.css("marginTop"),marginRight:this.originalElement.css("marginRight"),marginBottom:this.originalElement.css("marginBottom")}),this.originalElement.css({marginLeft:0,marginTop:0,marginRight:0,marginBottom:0}),this.originalResizeStyle=this.originalElement.css("resize"),this.originalElement.css("resize","none"),this._proportionallyResizeElements.push(this.originalElement.css({position:"static",zoom:1,display:"block"})),this.originalElement.css({margin:this.originalElement.css("margin")}),this._proportionallyResize()),this.handles=r.handles||(t(".ui-resizable-handle",this.element).length?{n:".ui-resizable-n",e:".ui-resizable-e",s:".ui-resizable-s",w:".ui-resizable-w",se:".ui-resizable-se",sw:".ui-resizable-sw",ne:".ui-resizable-ne",nw:".ui-resizable-nw"}:"e,s,se"),this.handles.constructor===String)for("all"===this.handles&&(this.handles="n,e,s,w,se,sw,ne,nw"),e=this.handles.split(","),this.handles={},i=0;e.length>i;i++)s=t.trim(e[i]),a="ui-resizable-"+s,n=t("<div class='ui-resizable-handle "+a+"'></div>"),n.css({zIndex:r.zIndex}),"se"===s&&n.addClass("ui-icon ui-icon-gripsmall-diagonal-se"),this.handles[s]=".ui-resizable-"+s,this.element.append(n);this._renderAxis=function(e){var i,s,n,a;e=e||this.element;for(i in this.handles)this.handles[i].constructor===String&&(this.handles[i]=t(this.handles[i],this.element).show()),this.elementIsWrapper&&this.originalElement[0].nodeName.match(/textarea|input|select|button/i)&&(s=t(this.handles[i],this.element),a=/sw|ne|nw|se|n|s/.test(i)?s.outerHeight():s.outerWidth(),n=["padding",/ne|nw|n/.test(i)?"Top":/se|sw|s/.test(i)?"Bottom":/^e$/.test(i)?"Right":"Left"].join(""),e.css(n,a),this._proportionallyResize()),t(this.handles[i]).length},this._renderAxis(this.element),this._handles=t(".ui-resizable-handle",this.element).disableSelection(),this._handles.mouseover(function(){o.resizing||(this.className&&(n=this.className.match(/ui-resizable-(se|sw|ne|nw|n|e|s|w)/i)),o.axis=n&&n[1]?n[1]:"se")}),r.autoHide&&(this._handles.hide(),t(this.element).addClass("ui-resizable-autohide").mouseenter(function(){r.disabled||(t(this).removeClass("ui-resizable-autohide"),o._handles.show())}).mouseleave(function(){r.disabled||o.resizing||(t(this).addClass("ui-resizable-autohide"),o._handles.hide())})),this._mouseInit()},_destroy:function(){this._mouseDestroy();var e,i=function(e){t(e).removeClass("ui-resizable ui-resizable-disabled ui-resizable-resizing").removeData("resizable").removeData("ui-resizable").unbind(".resizable").find(".ui-resizable-handle").remove()};return this.elementIsWrapper&&(i(this.element),e=this.element,this.originalElement.css({position:e.css("position"),width:e.outerWidth(),height:e.outerHeight(),top:e.css("top"),left:e.css("left")}).insertAfter(e),e.remove()),this.originalElement.css("resize",this.originalResizeStyle),i(this.originalElement),this},_mouseCapture:function(e){var i,s,n=!1;for(i in this.handles)s=t(this.handles[i])[0],(s===e.target||t.contains(s,e.target))&&(n=!0);return!this.options.disabled&&n},_mouseStart:function(i){var s,n,a,o=this.options,r=this.element.position(),h=this.element;return this.resizing=!0,/absolute/.test(h.css("position"))?h.css({position:"absolute",top:h.css("top"),left:h.css("left")}):h.is(".ui-draggable")&&h.css({position:"absolute",top:r.top,left:r.left}),this._renderProxy(),s=e(this.helper.css("left")),n=e(this.helper.css("top")),o.containment&&(s+=t(o.containment).scrollLeft()||0,n+=t(o.containment).scrollTop()||0),this.offset=this.helper.offset(),this.position={left:s,top:n},this.size=this._helper?{width:this.helper.width(),height:this.helper.height()}:{width:h.width(),height:h.height()},this.originalSize=this._helper?{width:h.outerWidth(),height:h.outerHeight()}:{width:h.width(),height:h.height()},this.originalPosition={left:s,top:n},this.sizeDiff={width:h.outerWidth()-h.width(),height:h.outerHeight()-h.height()},this.originalMousePosition={left:i.pageX,top:i.pageY},this.aspectRatio="number"==typeof o.aspectRatio?o.aspectRatio:this.originalSize.width/this.originalSize.height||1,a=t(".ui-resizable-"+this.axis).css("cursor"),t("body").css("cursor","auto"===a?this.axis+"-resize":a),h.addClass("ui-resizable-resizing"),this._propagate("start",i),!0},_mouseDrag:function(e){var i,s=this.helper,n={},a=this.originalMousePosition,o=this.axis,r=this.position.top,h=this.position.left,l=this.size.width,c=this.size.height,u=e.pageX-a.left||0,d=e.pageY-a.top||0,p=this._change[o];return p?(i=p.apply(this,[e,u,d]),this._updateVirtualBoundaries(e.shiftKey),(this._aspectRatio||e.shiftKey)&&(i=this._updateRatio(i,e)),i=this._respectSize(i,e),this._updateCache(i),this._propagate("resize",e),this.position.top!==r&&(n.top=this.position.top+"px"),this.position.left!==h&&(n.left=this.position.left+"px"),this.size.width!==l&&(n.width=this.size.width+"px"),this.size.height!==c&&(n.height=this.size.height+"px"),s.css(n),!this._helper&&this._proportionallyResizeElements.length&&this._proportionallyResize(),t.isEmptyObject(n)||this._trigger("resize",e,this.ui()),!1):!1},_mouseStop:function(e){this.resizing=!1;var i,s,n,a,o,r,h,l=this.options,c=this;return this._helper&&(i=this._proportionallyResizeElements,s=i.length&&/textarea/i.test(i[0].nodeName),n=s&&t.ui.hasScroll(i[0],"left")?0:c.sizeDiff.height,a=s?0:c.sizeDiff.width,o={width:c.helper.width()-a,height:c.helper.height()-n},r=parseInt(c.element.css("left"),10)+(c.position.left-c.originalPosition.left)||null,h=parseInt(c.element.css("top"),10)+(c.position.top-c.originalPosition.top)||null,l.animate||this.element.css(t.extend(o,{top:h,left:r})),c.helper.height(c.size.height),c.helper.width(c.size.width),this._helper&&!l.animate&&this._proportionallyResize()),t("body").css("cursor","auto"),this.element.removeClass("ui-resizable-resizing"),this._propagate("stop",e),this._helper&&this.helper.remove(),!1},_updateVirtualBoundaries:function(t){var e,s,n,a,o,r=this.options;o={minWidth:i(r.minWidth)?r.minWidth:0,maxWidth:i(r.maxWidth)?r.maxWidth:1/0,minHeight:i(r.minHeight)?r.minHeight:0,maxHeight:i(r.maxHeight)?r.maxHeight:1/0},(this._aspectRatio||t)&&(e=o.minHeight*this.aspectRatio,n=o.minWidth/this.aspectRatio,s=o.maxHeight*this.aspectRatio,a=o.maxWidth/this.aspectRatio,e>o.minWidth&&(o.minWidth=e),n>o.minHeight&&(o.minHeight=n),o.maxWidth>s&&(o.maxWidth=s),o.maxHeight>a&&(o.maxHeight=a)),this._vBoundaries=o},_updateCache:function(t){this.offset=this.helper.offset(),i(t.left)&&(this.position.left=t.left),i(t.top)&&(this.position.top=t.top),i(t.height)&&(this.size.height=t.height),i(t.width)&&(this.size.width=t.width)},_updateRatio:function(t){var e=this.position,s=this.size,n=this.axis;return i(t.height)?t.width=t.height*this.aspectRatio:i(t.width)&&(t.height=t.width/this.aspectRatio),"sw"===n&&(t.left=e.left+(s.width-t.width),t.top=null),"nw"===n&&(t.top=e.top+(s.height-t.height),t.left=e.left+(s.width-t.width)),t},_respectSize:function(t){var e=this._vBoundaries,s=this.axis,n=i(t.width)&&e.maxWidth&&e.maxWidth<t.width,a=i(t.height)&&e.maxHeight&&e.maxHeight<t.height,o=i(t.width)&&e.minWidth&&e.minWidth>t.width,r=i(t.height)&&e.minHeight&&e.minHeight>t.height,h=this.originalPosition.left+this.originalSize.width,l=this.position.top+this.size.height,c=/sw|nw|w/.test(s),u=/nw|ne|n/.test(s);return o&&(t.width=e.minWidth),r&&(t.height=e.minHeight),n&&(t.width=e.maxWidth),a&&(t.height=e.maxHeight),o&&c&&(t.left=h-e.minWidth),n&&c&&(t.left=h-e.maxWidth),r&&u&&(t.top=l-e.minHeight),a&&u&&(t.top=l-e.maxHeight),t.width||t.height||t.left||!t.top?t.width||t.height||t.top||!t.left||(t.left=null):t.top=null,t},_proportionallyResize:function(){if(this._proportionallyResizeElements.length){var t,e,i,s,n,a=this.helper||this.element;for(t=0;this._proportionallyResizeElements.length>t;t++){if(n=this._proportionallyResizeElements[t],!this.borderDif)for(this.borderDif=[],i=[n.css("borderTopWidth"),n.css("borderRightWidth"),n.css("borderBottomWidth"),n.css("borderLeftWidth")],s=[n.css("paddingTop"),n.css("paddingRight"),n.css("paddingBottom"),n.css("paddingLeft")],e=0;i.length>e;e++)this.borderDif[e]=(parseInt(i[e],10)||0)+(parseInt(s[e],10)||0);n.css({height:a.height()-this.borderDif[0]-this.borderDif[2]||0,width:a.width()-this.borderDif[1]-this.borderDif[3]||0})}}},_renderProxy:function(){var e=this.element,i=this.options;this.elementOffset=e.offset(),this._helper?(this.helper=this.helper||t("<div style='overflow:hidden;'></div>"),this.helper.addClass(this._helper).css({width:this.element.outerWidth()-1,height:this.element.outerHeight()-1,position:"absolute",left:this.elementOffset.left+"px",top:this.elementOffset.top+"px",zIndex:++i.zIndex}),this.helper.appendTo("body").disableSelection()):this.helper=this.element},_change:{e:function(t,e){return{width:this.originalSize.width+e}},w:function(t,e){var i=this.originalSize,s=this.originalPosition;return{left:s.left+e,width:i.width-e}},n:function(t,e,i){var s=this.originalSize,n=this.originalPosition;return{top:n.top+i,height:s.height-i}},s:function(t,e,i){return{height:this.originalSize.height+i}},se:function(e,i,s){return t.extend(this._change.s.apply(this,arguments),this._change.e.apply(this,[e,i,s]))},sw:function(e,i,s){return t.extend(this._change.s.apply(this,arguments),this._change.w.apply(this,[e,i,s]))},ne:function(e,i,s){return t.extend(this._change.n.apply(this,arguments),this._change.e.apply(this,[e,i,s]))},nw:function(e,i,s){return t.extend(this._change.n.apply(this,arguments),this._change.w.apply(this,[e,i,s]))}},_propagate:function(e,i){t.ui.plugin.call(this,e,[i,this.ui()]),"resize"!==e&&this._trigger(e,i,this.ui())},plugins:{},ui:function(){return{originalElement:this.originalElement,element:this.element,helper:this.helper,position:this.position,size:this.size,originalSize:this.originalSize,originalPosition:this.originalPosition}}}),t.ui.plugin.add("resizable","animate",{stop:function(e){var i=t(this).data("ui-resizable"),s=i.options,n=i._proportionallyResizeElements,a=n.length&&/textarea/i.test(n[0].nodeName),o=a&&t.ui.hasScroll(n[0],"left")?0:i.sizeDiff.height,r=a?0:i.sizeDiff.width,h={width:i.size.width-r,height:i.size.height-o},l=parseInt(i.element.css("left"),10)+(i.position.left-i.originalPosition.left)||null,c=parseInt(i.element.css("top"),10)+(i.position.top-i.originalPosition.top)||null;i.element.animate(t.extend(h,c&&l?{top:c,left:l}:{}),{duration:s.animateDuration,easing:s.animateEasing,step:function(){var s={width:parseInt(i.element.css("width"),10),height:parseInt(i.element.css("height"),10),top:parseInt(i.element.css("top"),10),left:parseInt(i.element.css("left"),10)};n&&n.length&&t(n[0]).css({width:s.width,height:s.height}),i._updateCache(s),i._propagate("resize",e)}})}}),t.ui.plugin.add("resizable","containment",{start:function(){var i,s,n,a,o,r,h,l=t(this).data("ui-resizable"),c=l.options,u=l.element,d=c.containment,p=d instanceof t?d.get(0):/parent/.test(d)?u.parent().get(0):d;p&&(l.containerElement=t(p),/document/.test(d)||d===document?(l.containerOffset={left:0,top:0},l.containerPosition={left:0,top:0},l.parentData={element:t(document),left:0,top:0,width:t(document).width(),height:t(document).height()||document.body.parentNode.scrollHeight}):(i=t(p),s=[],t(["Top","Right","Left","Bottom"]).each(function(t,n){s[t]=e(i.css("padding"+n))}),l.containerOffset=i.offset(),l.containerPosition=i.position(),l.containerSize={height:i.innerHeight()-s[3],width:i.innerWidth()-s[1]},n=l.containerOffset,a=l.containerSize.height,o=l.containerSize.width,r=t.ui.hasScroll(p,"left")?p.scrollWidth:o,h=t.ui.hasScroll(p)?p.scrollHeight:a,l.parentData={element:p,left:n.left,top:n.top,width:r,height:h}))},resize:function(e){var i,s,n,a,o=t(this).data("ui-resizable"),r=o.options,h=o.containerOffset,l=o.position,c=o._aspectRatio||e.shiftKey,u={top:0,left:0},d=o.containerElement;d[0]!==document&&/static/.test(d.css("position"))&&(u=h),l.left<(o._helper?h.left:0)&&(o.size.width=o.size.width+(o._helper?o.position.left-h.left:o.position.left-u.left),c&&(o.size.height=o.size.width/o.aspectRatio),o.position.left=r.helper?h.left:0),l.top<(o._helper?h.top:0)&&(o.size.height=o.size.height+(o._helper?o.position.top-h.top:o.position.top),c&&(o.size.width=o.size.height*o.aspectRatio),o.position.top=o._helper?h.top:0),o.offset.left=o.parentData.left+o.position.left,o.offset.top=o.parentData.top+o.position.top,i=Math.abs((o._helper?o.offset.left-u.left:o.offset.left-u.left)+o.sizeDiff.width),s=Math.abs((o._helper?o.offset.top-u.top:o.offset.top-h.top)+o.sizeDiff.height),n=o.containerElement.get(0)===o.element.parent().get(0),a=/relative|absolute/.test(o.containerElement.css("position")),n&&a&&(i-=Math.abs(o.parentData.left)),i+o.size.width>=o.parentData.width&&(o.size.width=o.parentData.width-i,c&&(o.size.height=o.size.width/o.aspectRatio)),s+o.size.height>=o.parentData.height&&(o.size.height=o.parentData.height-s,c&&(o.size.width=o.size.height*o.aspectRatio))},stop:function(){var e=t(this).data("ui-resizable"),i=e.options,s=e.containerOffset,n=e.containerPosition,a=e.containerElement,o=t(e.helper),r=o.offset(),h=o.outerWidth()-e.sizeDiff.width,l=o.outerHeight()-e.sizeDiff.height;e._helper&&!i.animate&&/relative/.test(a.css("position"))&&t(this).css({left:r.left-n.left-s.left,width:h,height:l}),e._helper&&!i.animate&&/static/.test(a.css("position"))&&t(this).css({left:r.left-n.left-s.left,width:h,height:l})}}),t.ui.plugin.add("resizable","alsoResize",{start:function(){var e=t(this).data("ui-resizable"),i=e.options,s=function(e){t(e).each(function(){var e=t(this);e.data("ui-resizable-alsoresize",{width:parseInt(e.width(),10),height:parseInt(e.height(),10),left:parseInt(e.css("left"),10),top:parseInt(e.css("top"),10)})})};"object"!=typeof i.alsoResize||i.alsoResize.parentNode?s(i.alsoResize):i.alsoResize.length?(i.alsoResize=i.alsoResize[0],s(i.alsoResize)):t.each(i.alsoResize,function(t){s(t)})},resize:function(e,i){var s=t(this).data("ui-resizable"),n=s.options,a=s.originalSize,o=s.originalPosition,r={height:s.size.height-a.height||0,width:s.size.width-a.width||0,top:s.position.top-o.top||0,left:s.position.left-o.left||0},h=function(e,s){t(e).each(function(){var e=t(this),n=t(this).data("ui-resizable-alsoresize"),a={},o=s&&s.length?s:e.parents(i.originalElement[0]).length?["width","height"]:["width","height","top","left"];t.each(o,function(t,e){var i=(n[e]||0)+(r[e]||0);i&&i>=0&&(a[e]=i||null)}),e.css(a)})};"object"!=typeof n.alsoResize||n.alsoResize.nodeType?h(n.alsoResize):t.each(n.alsoResize,function(t,e){h(t,e)})},stop:function(){t(this).removeData("resizable-alsoresize")}}),t.ui.plugin.add("resizable","ghost",{start:function(){var e=t(this).data("ui-resizable"),i=e.options,s=e.size;e.ghost=e.originalElement.clone(),e.ghost.css({opacity:.25,display:"block",position:"relative",height:s.height,width:s.width,margin:0,left:0,top:0}).addClass("ui-resizable-ghost").addClass("string"==typeof i.ghost?i.ghost:""),e.ghost.appendTo(e.helper)},resize:function(){var e=t(this).data("ui-resizable");e.ghost&&e.ghost.css({position:"relative",height:e.size.height,width:e.size.width})},stop:function(){var e=t(this).data("ui-resizable");e.ghost&&e.helper&&e.helper.get(0).removeChild(e.ghost.get(0))}}),t.ui.plugin.add("resizable","grid",{resize:function(){var e=t(this).data("ui-resizable"),i=e.options,s=e.size,n=e.originalSize,a=e.originalPosition,o=e.axis,r="number"==typeof i.grid?[i.grid,i.grid]:i.grid,h=r[0]||1,l=r[1]||1,c=Math.round((s.width-n.width)/h)*h,u=Math.round((s.height-n.height)/l)*l,d=n.width+c,p=n.height+u,f=i.maxWidth&&d>i.maxWidth,g=i.maxHeight&&p>i.maxHeight,m=i.minWidth&&i.minWidth>d,v=i.minHeight&&i.minHeight>p;i.grid=r,m&&(d+=h),v&&(p+=l),f&&(d-=h),g&&(p-=l),/^(se|s|e)$/.test(o)?(e.size.width=d,e.size.height=p):/^(ne)$/.test(o)?(e.size.width=d,e.size.height=p,e.position.top=a.top-u):/^(sw)$/.test(o)?(e.size.width=d,e.size.height=p,e.position.left=a.left-c):(p-l>0?(e.size.height=p,e.position.top=a.top-u):(e.size.height=l,e.position.top=a.top+n.height-l),d-h>0?(e.size.width=d,e.position.left=a.left-c):(e.size.width=h,e.position.left=a.left+n.width-h))}})})(jQuery);(function(t){t.widget("ui.selectable",t.ui.mouse,{version:"1.10.4",options:{appendTo:"body",autoRefresh:!0,distance:0,filter:"*",tolerance:"touch",selected:null,selecting:null,start:null,stop:null,unselected:null,unselecting:null},_create:function(){var e,i=this;this.element.addClass("ui-selectable"),this.dragged=!1,this.refresh=function(){e=t(i.options.filter,i.element[0]),e.addClass("ui-selectee"),e.each(function(){var e=t(this),i=e.offset();t.data(this,"selectable-item",{element:this,$element:e,left:i.left,top:i.top,right:i.left+e.outerWidth(),bottom:i.top+e.outerHeight(),startselected:!1,selected:e.hasClass("ui-selected"),selecting:e.hasClass("ui-selecting"),unselecting:e.hasClass("ui-unselecting")})})},this.refresh(),this.selectees=e.addClass("ui-selectee"),this._mouseInit(),this.helper=t("<div class='ui-selectable-helper'></div>")},_destroy:function(){this.selectees.removeClass("ui-selectee").removeData("selectable-item"),this.element.removeClass("ui-selectable ui-selectable-disabled"),this._mouseDestroy()},_mouseStart:function(e){var i=this,s=this.options;this.opos=[e.pageX,e.pageY],this.options.disabled||(this.selectees=t(s.filter,this.element[0]),this._trigger("start",e),t(s.appendTo).append(this.helper),this.helper.css({left:e.pageX,top:e.pageY,width:0,height:0}),s.autoRefresh&&this.refresh(),this.selectees.filter(".ui-selected").each(function(){var s=t.data(this,"selectable-item");s.startselected=!0,e.metaKey||e.ctrlKey||(s.$element.removeClass("ui-selected"),s.selected=!1,s.$element.addClass("ui-unselecting"),s.unselecting=!0,i._trigger("unselecting",e,{unselecting:s.element}))}),t(e.target).parents().addBack().each(function(){var s,n=t.data(this,"selectable-item");return n?(s=!e.metaKey&&!e.ctrlKey||!n.$element.hasClass("ui-selected"),n.$element.removeClass(s?"ui-unselecting":"ui-selected").addClass(s?"ui-selecting":"ui-unselecting"),n.unselecting=!s,n.selecting=s,n.selected=s,s?i._trigger("selecting",e,{selecting:n.element}):i._trigger("unselecting",e,{unselecting:n.element}),!1):undefined}))},_mouseDrag:function(e){if(this.dragged=!0,!this.options.disabled){var i,s=this,n=this.options,a=this.opos[0],o=this.opos[1],r=e.pageX,l=e.pageY;return a>r&&(i=r,r=a,a=i),o>l&&(i=l,l=o,o=i),this.helper.css({left:a,top:o,width:r-a,height:l-o}),this.selectees.each(function(){var i=t.data(this,"selectable-item"),h=!1;i&&i.element!==s.element[0]&&("touch"===n.tolerance?h=!(i.left>r||a>i.right||i.top>l||o>i.bottom):"fit"===n.tolerance&&(h=i.left>a&&r>i.right&&i.top>o&&l>i.bottom),h?(i.selected&&(i.$element.removeClass("ui-selected"),i.selected=!1),i.unselecting&&(i.$element.removeClass("ui-unselecting"),i.unselecting=!1),i.selecting||(i.$element.addClass("ui-selecting"),i.selecting=!0,s._trigger("selecting",e,{selecting:i.element}))):(i.selecting&&((e.metaKey||e.ctrlKey)&&i.startselected?(i.$element.removeClass("ui-selecting"),i.selecting=!1,i.$element.addClass("ui-selected"),i.selected=!0):(i.$element.removeClass("ui-selecting"),i.selecting=!1,i.startselected&&(i.$element.addClass("ui-unselecting"),i.unselecting=!0),s._trigger("unselecting",e,{unselecting:i.element}))),i.selected&&(e.metaKey||e.ctrlKey||i.startselected||(i.$element.removeClass("ui-selected"),i.selected=!1,i.$element.addClass("ui-unselecting"),i.unselecting=!0,s._trigger("unselecting",e,{unselecting:i.element})))))}),!1}},_mouseStop:function(e){var i=this;return this.dragged=!1,t(".ui-unselecting",this.element[0]).each(function(){var s=t.data(this,"selectable-item");s.$element.removeClass("ui-unselecting"),s.unselecting=!1,s.startselected=!1,i._trigger("unselected",e,{unselected:s.element})}),t(".ui-selecting",this.element[0]).each(function(){var s=t.data(this,"selectable-item");s.$element.removeClass("ui-selecting").addClass("ui-selected"),s.selecting=!1,s.selected=!0,s.startselected=!0,i._trigger("selected",e,{selected:s.element})}),this._trigger("stop",e),this.helper.remove(),!1}})})(jQuery);(function(t){function e(t,e,i){return t>e&&e+i>t}function i(t){return/left|right/.test(t.css("float"))||/inline|table-cell/.test(t.css("display"))}t.widget("ui.sortable",t.ui.mouse,{version:"1.10.4",widgetEventPrefix:"sort",ready:!1,options:{appendTo:"parent",axis:!1,connectWith:!1,containment:!1,cursor:"auto",cursorAt:!1,dropOnEmpty:!0,forcePlaceholderSize:!1,forceHelperSize:!1,grid:!1,handle:!1,helper:"original",items:"> *",opacity:!1,placeholder:!1,revert:!1,scroll:!0,scrollSensitivity:20,scrollSpeed:20,scope:"default",tolerance:"intersect",zIndex:1e3,activate:null,beforeStop:null,change:null,deactivate:null,out:null,over:null,receive:null,remove:null,sort:null,start:null,stop:null,update:null},_create:function(){var t=this.options;this.containerCache={},this.element.addClass("ui-sortable"),this.refresh(),this.floating=this.items.length?"x"===t.axis||i(this.items[0].item):!1,this.offset=this.element.offset(),this._mouseInit(),this.ready=!0},_destroy:function(){this.element.removeClass("ui-sortable ui-sortable-disabled"),this._mouseDestroy();for(var t=this.items.length-1;t>=0;t--)this.items[t].item.removeData(this.widgetName+"-item");return this},_setOption:function(e,i){"disabled"===e?(this.options[e]=i,this.widget().toggleClass("ui-sortable-disabled",!!i)):t.Widget.prototype._setOption.apply(this,arguments)},_mouseCapture:function(e,i){var s=null,n=!1,o=this;return this.reverting?!1:this.options.disabled||"static"===this.options.type?!1:(this._refreshItems(e),t(e.target).parents().each(function(){return t.data(this,o.widgetName+"-item")===o?(s=t(this),!1):undefined}),t.data(e.target,o.widgetName+"-item")===o&&(s=t(e.target)),s?!this.options.handle||i||(t(this.options.handle,s).find("*").addBack().each(function(){this===e.target&&(n=!0)}),n)?(this.currentItem=s,this._removeCurrentsFromItems(),!0):!1:!1)},_mouseStart:function(e,i,s){var n,o,a=this.options;if(this.currentContainer=this,this.refreshPositions(),this.helper=this._createHelper(e),this._cacheHelperProportions(),this._cacheMargins(),this.scrollParent=this.helper.scrollParent(),this.offset=this.currentItem.offset(),this.offset={top:this.offset.top-this.margins.top,left:this.offset.left-this.margins.left},t.extend(this.offset,{click:{left:e.pageX-this.offset.left,top:e.pageY-this.offset.top},parent:this._getParentOffset(),relative:this._getRelativeOffset()}),this.helper.css("position","absolute"),this.cssPosition=this.helper.css("position"),this.originalPosition=this._generatePosition(e),this.originalPageX=e.pageX,this.originalPageY=e.pageY,a.cursorAt&&this._adjustOffsetFromHelper(a.cursorAt),this.domPosition={prev:this.currentItem.prev()[0],parent:this.currentItem.parent()[0]},this.helper[0]!==this.currentItem[0]&&this.currentItem.hide(),this._createPlaceholder(),a.containment&&this._setContainment(),a.cursor&&"auto"!==a.cursor&&(o=this.document.find("body"),this.storedCursor=o.css("cursor"),o.css("cursor",a.cursor),this.storedStylesheet=t("<style>*{ cursor: "+a.cursor+" !important; }</style>").appendTo(o)),a.opacity&&(this.helper.css("opacity")&&(this._storedOpacity=this.helper.css("opacity")),this.helper.css("opacity",a.opacity)),a.zIndex&&(this.helper.css("zIndex")&&(this._storedZIndex=this.helper.css("zIndex")),this.helper.css("zIndex",a.zIndex)),this.scrollParent[0]!==document&&"HTML"!==this.scrollParent[0].tagName&&(this.overflowOffset=this.scrollParent.offset()),this._trigger("start",e,this._uiHash()),this._preserveHelperProportions||this._cacheHelperProportions(),!s)for(n=this.containers.length-1;n>=0;n--)this.containers[n]._trigger("activate",e,this._uiHash(this));return t.ui.ddmanager&&(t.ui.ddmanager.current=this),t.ui.ddmanager&&!a.dropBehaviour&&t.ui.ddmanager.prepareOffsets(this,e),this.dragging=!0,this.helper.addClass("ui-sortable-helper"),this._mouseDrag(e),!0},_mouseDrag:function(e){var i,s,n,o,a=this.options,r=!1;for(this.position=this._generatePosition(e),this.positionAbs=this._convertPositionTo("absolute"),this.lastPositionAbs||(this.lastPositionAbs=this.positionAbs),this.options.scroll&&(this.scrollParent[0]!==document&&"HTML"!==this.scrollParent[0].tagName?(this.overflowOffset.top+this.scrollParent[0].offsetHeight-e.pageY<a.scrollSensitivity?this.scrollParent[0].scrollTop=r=this.scrollParent[0].scrollTop+a.scrollSpeed:e.pageY-this.overflowOffset.top<a.scrollSensitivity&&(this.scrollParent[0].scrollTop=r=this.scrollParent[0].scrollTop-a.scrollSpeed),this.overflowOffset.left+this.scrollParent[0].offsetWidth-e.pageX<a.scrollSensitivity?this.scrollParent[0].scrollLeft=r=this.scrollParent[0].scrollLeft+a.scrollSpeed:e.pageX-this.overflowOffset.left<a.scrollSensitivity&&(this.scrollParent[0].scrollLeft=r=this.scrollParent[0].scrollLeft-a.scrollSpeed)):(e.pageY-t(document).scrollTop()<a.scrollSensitivity?r=t(document).scrollTop(t(document).scrollTop()-a.scrollSpeed):t(window).height()-(e.pageY-t(document).scrollTop())<a.scrollSensitivity&&(r=t(document).scrollTop(t(document).scrollTop()+a.scrollSpeed)),e.pageX-t(document).scrollLeft()<a.scrollSensitivity?r=t(document).scrollLeft(t(document).scrollLeft()-a.scrollSpeed):t(window).width()-(e.pageX-t(document).scrollLeft())<a.scrollSensitivity&&(r=t(document).scrollLeft(t(document).scrollLeft()+a.scrollSpeed))),r!==!1&&t.ui.ddmanager&&!a.dropBehaviour&&t.ui.ddmanager.prepareOffsets(this,e)),this.positionAbs=this._convertPositionTo("absolute"),this.options.axis&&"y"===this.options.axis||(this.helper[0].style.left=this.position.left+"px"),this.options.axis&&"x"===this.options.axis||(this.helper[0].style.top=this.position.top+"px"),i=this.items.length-1;i>=0;i--)if(s=this.items[i],n=s.item[0],o=this._intersectsWithPointer(s),o&&s.instance===this.currentContainer&&n!==this.currentItem[0]&&this.placeholder[1===o?"next":"prev"]()[0]!==n&&!t.contains(this.placeholder[0],n)&&("semi-dynamic"===this.options.type?!t.contains(this.element[0],n):!0)){if(this.direction=1===o?"down":"up","pointer"!==this.options.tolerance&&!this._intersectsWithSides(s))break;this._rearrange(e,s),this._trigger("change",e,this._uiHash());break}return this._contactContainers(e),t.ui.ddmanager&&t.ui.ddmanager.drag(this,e),this._trigger("sort",e,this._uiHash()),this.lastPositionAbs=this.positionAbs,!1},_mouseStop:function(e,i){if(e){if(t.ui.ddmanager&&!this.options.dropBehaviour&&t.ui.ddmanager.drop(this,e),this.options.revert){var s=this,n=this.placeholder.offset(),o=this.options.axis,a={};o&&"x"!==o||(a.left=n.left-this.offset.parent.left-this.margins.left+(this.offsetParent[0]===document.body?0:this.offsetParent[0].scrollLeft)),o&&"y"!==o||(a.top=n.top-this.offset.parent.top-this.margins.top+(this.offsetParent[0]===document.body?0:this.offsetParent[0].scrollTop)),this.reverting=!0,t(this.helper).animate(a,parseInt(this.options.revert,10)||500,function(){s._clear(e)})}else this._clear(e,i);return!1}},cancel:function(){if(this.dragging){this._mouseUp({target:null}),"original"===this.options.helper?this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper"):this.currentItem.show();for(var e=this.containers.length-1;e>=0;e--)this.containers[e]._trigger("deactivate",null,this._uiHash(this)),this.containers[e].containerCache.over&&(this.containers[e]._trigger("out",null,this._uiHash(this)),this.containers[e].containerCache.over=0)}return this.placeholder&&(this.placeholder[0].parentNode&&this.placeholder[0].parentNode.removeChild(this.placeholder[0]),"original"!==this.options.helper&&this.helper&&this.helper[0].parentNode&&this.helper.remove(),t.extend(this,{helper:null,dragging:!1,reverting:!1,_noFinalSort:null}),this.domPosition.prev?t(this.domPosition.prev).after(this.currentItem):t(this.domPosition.parent).prepend(this.currentItem)),this},serialize:function(e){var i=this._getItemsAsjQuery(e&&e.connected),s=[];return e=e||{},t(i).each(function(){var i=(t(e.item||this).attr(e.attribute||"id")||"").match(e.expression||/(.+)[\-=_](.+)/);i&&s.push((e.key||i[1]+"[]")+"="+(e.key&&e.expression?i[1]:i[2]))}),!s.length&&e.key&&s.push(e.key+"="),s.join("&")},toArray:function(e){var i=this._getItemsAsjQuery(e&&e.connected),s=[];return e=e||{},i.each(function(){s.push(t(e.item||this).attr(e.attribute||"id")||"")}),s},_intersectsWith:function(t){var e=this.positionAbs.left,i=e+this.helperProportions.width,s=this.positionAbs.top,n=s+this.helperProportions.height,o=t.left,a=o+t.width,r=t.top,h=r+t.height,l=this.offset.click.top,c=this.offset.click.left,u="x"===this.options.axis||s+l>r&&h>s+l,d="y"===this.options.axis||e+c>o&&a>e+c,p=u&&d;return"pointer"===this.options.tolerance||this.options.forcePointerForContainers||"pointer"!==this.options.tolerance&&this.helperProportions[this.floating?"width":"height"]>t[this.floating?"width":"height"]?p:e+this.helperProportions.width/2>o&&a>i-this.helperProportions.width/2&&s+this.helperProportions.height/2>r&&h>n-this.helperProportions.height/2},_intersectsWithPointer:function(t){var i="x"===this.options.axis||e(this.positionAbs.top+this.offset.click.top,t.top,t.height),s="y"===this.options.axis||e(this.positionAbs.left+this.offset.click.left,t.left,t.width),n=i&&s,o=this._getDragVerticalDirection(),a=this._getDragHorizontalDirection();return n?this.floating?a&&"right"===a||"down"===o?2:1:o&&("down"===o?2:1):!1},_intersectsWithSides:function(t){var i=e(this.positionAbs.top+this.offset.click.top,t.top+t.height/2,t.height),s=e(this.positionAbs.left+this.offset.click.left,t.left+t.width/2,t.width),n=this._getDragVerticalDirection(),o=this._getDragHorizontalDirection();return this.floating&&o?"right"===o&&s||"left"===o&&!s:n&&("down"===n&&i||"up"===n&&!i)},_getDragVerticalDirection:function(){var t=this.positionAbs.top-this.lastPositionAbs.top;return 0!==t&&(t>0?"down":"up")},_getDragHorizontalDirection:function(){var t=this.positionAbs.left-this.lastPositionAbs.left;return 0!==t&&(t>0?"right":"left")},refresh:function(t){return this._refreshItems(t),this.refreshPositions(),this},_connectWith:function(){var t=this.options;return t.connectWith.constructor===String?[t.connectWith]:t.connectWith},_getItemsAsjQuery:function(e){function i(){r.push(this)}var s,n,o,a,r=[],h=[],l=this._connectWith();if(l&&e)for(s=l.length-1;s>=0;s--)for(o=t(l[s]),n=o.length-1;n>=0;n--)a=t.data(o[n],this.widgetFullName),a&&a!==this&&!a.options.disabled&&h.push([t.isFunction(a.options.items)?a.options.items.call(a.element):t(a.options.items,a.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),a]);for(h.push([t.isFunction(this.options.items)?this.options.items.call(this.element,null,{options:this.options,item:this.currentItem}):t(this.options.items,this.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),this]),s=h.length-1;s>=0;s--)h[s][0].each(i);return t(r)},_removeCurrentsFromItems:function(){var e=this.currentItem.find(":data("+this.widgetName+"-item)");this.items=t.grep(this.items,function(t){for(var i=0;e.length>i;i++)if(e[i]===t.item[0])return!1;return!0})},_refreshItems:function(e){this.items=[],this.containers=[this];var i,s,n,o,a,r,h,l,c=this.items,u=[[t.isFunction(this.options.items)?this.options.items.call(this.element[0],e,{item:this.currentItem}):t(this.options.items,this.element),this]],d=this._connectWith();if(d&&this.ready)for(i=d.length-1;i>=0;i--)for(n=t(d[i]),s=n.length-1;s>=0;s--)o=t.data(n[s],this.widgetFullName),o&&o!==this&&!o.options.disabled&&(u.push([t.isFunction(o.options.items)?o.options.items.call(o.element[0],e,{item:this.currentItem}):t(o.options.items,o.element),o]),this.containers.push(o));for(i=u.length-1;i>=0;i--)for(a=u[i][1],r=u[i][0],s=0,l=r.length;l>s;s++)h=t(r[s]),h.data(this.widgetName+"-item",a),c.push({item:h,instance:a,width:0,height:0,left:0,top:0})},refreshPositions:function(e){this.offsetParent&&this.helper&&(this.offset.parent=this._getParentOffset());var i,s,n,o;for(i=this.items.length-1;i>=0;i--)s=this.items[i],s.instance!==this.currentContainer&&this.currentContainer&&s.item[0]!==this.currentItem[0]||(n=this.options.toleranceElement?t(this.options.toleranceElement,s.item):s.item,e||(s.width=n.outerWidth(),s.height=n.outerHeight()),o=n.offset(),s.left=o.left,s.top=o.top);if(this.options.custom&&this.options.custom.refreshContainers)this.options.custom.refreshContainers.call(this);else for(i=this.containers.length-1;i>=0;i--)o=this.containers[i].element.offset(),this.containers[i].containerCache.left=o.left,this.containers[i].containerCache.top=o.top,this.containers[i].containerCache.width=this.containers[i].element.outerWidth(),this.containers[i].containerCache.height=this.containers[i].element.outerHeight();return this},_createPlaceholder:function(e){e=e||this;var i,s=e.options;s.placeholder&&s.placeholder.constructor!==String||(i=s.placeholder,s.placeholder={element:function(){var s=e.currentItem[0].nodeName.toLowerCase(),n=t("<"+s+">",e.document[0]).addClass(i||e.currentItem[0].className+" ui-sortable-placeholder").removeClass("ui-sortable-helper");return"tr"===s?e.currentItem.children().each(function(){t("<td> </td>",e.document[0]).attr("colspan",t(this).attr("colspan")||1).appendTo(n)}):"img"===s&&n.attr("src",e.currentItem.attr("src")),i||n.css("visibility","hidden"),n},update:function(t,n){(!i||s.forcePlaceholderSize)&&(n.height()||n.height(e.currentItem.innerHeight()-parseInt(e.currentItem.css("paddingTop")||0,10)-parseInt(e.currentItem.css("paddingBottom")||0,10)),n.width()||n.width(e.currentItem.innerWidth()-parseInt(e.currentItem.css("paddingLeft")||0,10)-parseInt(e.currentItem.css("paddingRight")||0,10)))}}),e.placeholder=t(s.placeholder.element.call(e.element,e.currentItem)),e.currentItem.after(e.placeholder),s.placeholder.update(e,e.placeholder)},_contactContainers:function(s){var n,o,a,r,h,l,c,u,d,p,f=null,g=null;for(n=this.containers.length-1;n>=0;n--)if(!t.contains(this.currentItem[0],this.containers[n].element[0]))if(this._intersectsWith(this.containers[n].containerCache)){if(f&&t.contains(this.containers[n].element[0],f.element[0]))continue;f=this.containers[n],g=n}else this.containers[n].containerCache.over&&(this.containers[n]._trigger("out",s,this._uiHash(this)),this.containers[n].containerCache.over=0);if(f)if(1===this.containers.length)this.containers[g].containerCache.over||(this.containers[g]._trigger("over",s,this._uiHash(this)),this.containers[g].containerCache.over=1);else{for(a=1e4,r=null,p=f.floating||i(this.currentItem),h=p?"left":"top",l=p?"width":"height",c=this.positionAbs[h]+this.offset.click[h],o=this.items.length-1;o>=0;o--)t.contains(this.containers[g].element[0],this.items[o].item[0])&&this.items[o].item[0]!==this.currentItem[0]&&(!p||e(this.positionAbs.top+this.offset.click.top,this.items[o].top,this.items[o].height))&&(u=this.items[o].item.offset()[h],d=!1,Math.abs(u-c)>Math.abs(u+this.items[o][l]-c)&&(d=!0,u+=this.items[o][l]),a>Math.abs(u-c)&&(a=Math.abs(u-c),r=this.items[o],this.direction=d?"up":"down"));if(!r&&!this.options.dropOnEmpty)return;if(this.currentContainer===this.containers[g])return;r?this._rearrange(s,r,null,!0):this._rearrange(s,null,this.containers[g].element,!0),this._trigger("change",s,this._uiHash()),this.containers[g]._trigger("change",s,this._uiHash(this)),this.currentContainer=this.containers[g],this.options.placeholder.update(this.currentContainer,this.placeholder),this.containers[g]._trigger("over",s,this._uiHash(this)),this.containers[g].containerCache.over=1}},_createHelper:function(e){var i=this.options,s=t.isFunction(i.helper)?t(i.helper.apply(this.element[0],[e,this.currentItem])):"clone"===i.helper?this.currentItem.clone():this.currentItem;return s.parents("body").length||t("parent"!==i.appendTo?i.appendTo:this.currentItem[0].parentNode)[0].appendChild(s[0]),s[0]===this.currentItem[0]&&(this._storedCSS={width:this.currentItem[0].style.width,height:this.currentItem[0].style.height,position:this.currentItem.css("position"),top:this.currentItem.css("top"),left:this.currentItem.css("left")}),(!s[0].style.width||i.forceHelperSize)&&s.width(this.currentItem.width()),(!s[0].style.height||i.forceHelperSize)&&s.height(this.currentItem.height()),s},_adjustOffsetFromHelper:function(e){"string"==typeof e&&(e=e.split(" ")),t.isArray(e)&&(e={left:+e[0],top:+e[1]||0}),"left"in e&&(this.offset.click.left=e.left+this.margins.left),"right"in e&&(this.offset.click.left=this.helperProportions.width-e.right+this.margins.left),"top"in e&&(this.offset.click.top=e.top+this.margins.top),"bottom"in e&&(this.offset.click.top=this.helperProportions.height-e.bottom+this.margins.top)},_getParentOffset:function(){this.offsetParent=this.helper.offsetParent();var e=this.offsetParent.offset();return"absolute"===this.cssPosition&&this.scrollParent[0]!==document&&t.contains(this.scrollParent[0],this.offsetParent[0])&&(e.left+=this.scrollParent.scrollLeft(),e.top+=this.scrollParent.scrollTop()),(this.offsetParent[0]===document.body||this.offsetParent[0].tagName&&"html"===this.offsetParent[0].tagName.toLowerCase()&&t.ui.ie)&&(e={top:0,left:0}),{top:e.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:e.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)}},_getRelativeOffset:function(){if("relative"===this.cssPosition){var t=this.currentItem.position();return{top:t.top-(parseInt(this.helper.css("top"),10)||0)+this.scrollParent.scrollTop(),left:t.left-(parseInt(this.helper.css("left"),10)||0)+this.scrollParent.scrollLeft()}}return{top:0,left:0}},_cacheMargins:function(){this.margins={left:parseInt(this.currentItem.css("marginLeft"),10)||0,top:parseInt(this.currentItem.css("marginTop"),10)||0}},_cacheHelperProportions:function(){this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()}},_setContainment:function(){var e,i,s,n=this.options;"parent"===n.containment&&(n.containment=this.helper[0].parentNode),("document"===n.containment||"window"===n.containment)&&(this.containment=[0-this.offset.relative.left-this.offset.parent.left,0-this.offset.relative.top-this.offset.parent.top,t("document"===n.containment?document:window).width()-this.helperProportions.width-this.margins.left,(t("document"===n.containment?document:window).height()||document.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top]),/^(document|window|parent)$/.test(n.containment)||(e=t(n.containment)[0],i=t(n.containment).offset(),s="hidden"!==t(e).css("overflow"),this.containment=[i.left+(parseInt(t(e).css("borderLeftWidth"),10)||0)+(parseInt(t(e).css("paddingLeft"),10)||0)-this.margins.left,i.top+(parseInt(t(e).css("borderTopWidth"),10)||0)+(parseInt(t(e).css("paddingTop"),10)||0)-this.margins.top,i.left+(s?Math.max(e.scrollWidth,e.offsetWidth):e.offsetWidth)-(parseInt(t(e).css("borderLeftWidth"),10)||0)-(parseInt(t(e).css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left,i.top+(s?Math.max(e.scrollHeight,e.offsetHeight):e.offsetHeight)-(parseInt(t(e).css("borderTopWidth"),10)||0)-(parseInt(t(e).css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top])},_convertPositionTo:function(e,i){i||(i=this.position);var s="absolute"===e?1:-1,n="absolute"!==this.cssPosition||this.scrollParent[0]!==document&&t.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent,o=/(html|body)/i.test(n[0].tagName);return{top:i.top+this.offset.relative.top*s+this.offset.parent.top*s-("fixed"===this.cssPosition?-this.scrollParent.scrollTop():o?0:n.scrollTop())*s,left:i.left+this.offset.relative.left*s+this.offset.parent.left*s-("fixed"===this.cssPosition?-this.scrollParent.scrollLeft():o?0:n.scrollLeft())*s}},_generatePosition:function(e){var i,s,n=this.options,o=e.pageX,a=e.pageY,r="absolute"!==this.cssPosition||this.scrollParent[0]!==document&&t.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent,h=/(html|body)/i.test(r[0].tagName);return"relative"!==this.cssPosition||this.scrollParent[0]!==document&&this.scrollParent[0]!==this.offsetParent[0]||(this.offset.relative=this._getRelativeOffset()),this.originalPosition&&(this.containment&&(e.pageX-this.offset.click.left<this.containment[0]&&(o=this.containment[0]+this.offset.click.left),e.pageY-this.offset.click.top<this.containment[1]&&(a=this.containment[1]+this.offset.click.top),e.pageX-this.offset.click.left>this.containment[2]&&(o=this.containment[2]+this.offset.click.left),e.pageY-this.offset.click.top>this.containment[3]&&(a=this.containment[3]+this.offset.click.top)),n.grid&&(i=this.originalPageY+Math.round((a-this.originalPageY)/n.grid[1])*n.grid[1],a=this.containment?i-this.offset.click.top>=this.containment[1]&&i-this.offset.click.top<=this.containment[3]?i:i-this.offset.click.top>=this.containment[1]?i-n.grid[1]:i+n.grid[1]:i,s=this.originalPageX+Math.round((o-this.originalPageX)/n.grid[0])*n.grid[0],o=this.containment?s-this.offset.click.left>=this.containment[0]&&s-this.offset.click.left<=this.containment[2]?s:s-this.offset.click.left>=this.containment[0]?s-n.grid[0]:s+n.grid[0]:s)),{top:a-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+("fixed"===this.cssPosition?-this.scrollParent.scrollTop():h?0:r.scrollTop()),left:o-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+("fixed"===this.cssPosition?-this.scrollParent.scrollLeft():h?0:r.scrollLeft())}},_rearrange:function(t,e,i,s){i?i[0].appendChild(this.placeholder[0]):e.item[0].parentNode.insertBefore(this.placeholder[0],"down"===this.direction?e.item[0]:e.item[0].nextSibling),this.counter=this.counter?++this.counter:1;var n=this.counter;this._delay(function(){n===this.counter&&this.refreshPositions(!s)})},_clear:function(t,e){function i(t,e,i){return function(s){i._trigger(t,s,e._uiHash(e))}}this.reverting=!1;var s,n=[];if(!this._noFinalSort&&this.currentItem.parent().length&&this.placeholder.before(this.currentItem),this._noFinalSort=null,this.helper[0]===this.currentItem[0]){for(s in this._storedCSS)("auto"===this._storedCSS[s]||"static"===this._storedCSS[s])&&(this._storedCSS[s]="");this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper")}else this.currentItem.show();for(this.fromOutside&&!e&&n.push(function(t){this._trigger("receive",t,this._uiHash(this.fromOutside))}),!this.fromOutside&&this.domPosition.prev===this.currentItem.prev().not(".ui-sortable-helper")[0]&&this.domPosition.parent===this.currentItem.parent()[0]||e||n.push(function(t){this._trigger("update",t,this._uiHash())}),this!==this.currentContainer&&(e||(n.push(function(t){this._trigger("remove",t,this._uiHash())}),n.push(function(t){return function(e){t._trigger("receive",e,this._uiHash(this))}}.call(this,this.currentContainer)),n.push(function(t){return function(e){t._trigger("update",e,this._uiHash(this))}}.call(this,this.currentContainer)))),s=this.containers.length-1;s>=0;s--)e||n.push(i("deactivate",this,this.containers[s])),this.containers[s].containerCache.over&&(n.push(i("out",this,this.containers[s])),this.containers[s].containerCache.over=0);if(this.storedCursor&&(this.document.find("body").css("cursor",this.storedCursor),this.storedStylesheet.remove()),this._storedOpacity&&this.helper.css("opacity",this._storedOpacity),this._storedZIndex&&this.helper.css("zIndex","auto"===this._storedZIndex?"":this._storedZIndex),this.dragging=!1,this.cancelHelperRemoval){if(!e){for(this._trigger("beforeStop",t,this._uiHash()),s=0;n.length>s;s++)n[s].call(this,t);this._trigger("stop",t,this._uiHash())}return this.fromOutside=!1,!1}if(e||this._trigger("beforeStop",t,this._uiHash()),this.placeholder[0].parentNode.removeChild(this.placeholder[0]),this.helper[0]!==this.currentItem[0]&&this.helper.remove(),this.helper=null,!e){for(s=0;n.length>s;s++)n[s].call(this,t);this._trigger("stop",t,this._uiHash())}return this.fromOutside=!1,!0},_trigger:function(){t.Widget.prototype._trigger.apply(this,arguments)===!1&&this.cancel()},_uiHash:function(e){var i=e||this;return{helper:i.helper,placeholder:i.placeholder||t([]),position:i.position,originalPosition:i.originalPosition,offset:i.positionAbs,item:i.currentItem,sender:e?e.element:null}}})})(jQuery);(function(e){var t=0,i={},a={};i.height=i.paddingTop=i.paddingBottom=i.borderTopWidth=i.borderBottomWidth="hide",a.height=a.paddingTop=a.paddingBottom=a.borderTopWidth=a.borderBottomWidth="show",e.widget("ui.accordion",{version:"1.10.4",options:{active:0,animate:{},collapsible:!1,event:"click",header:"> li > :first-child,> :not(li):even",heightStyle:"auto",icons:{activeHeader:"ui-icon-triangle-1-s",header:"ui-icon-triangle-1-e"},activate:null,beforeActivate:null},_create:function(){var t=this.options;this.prevShow=this.prevHide=e(),this.element.addClass("ui-accordion ui-widget ui-helper-reset").attr("role","tablist"),t.collapsible||t.active!==!1&&null!=t.active||(t.active=0),this._processPanels(),0>t.active&&(t.active+=this.headers.length),this._refresh()},_getCreateEventData:function(){return{header:this.active,panel:this.active.length?this.active.next():e(),content:this.active.length?this.active.next():e()}},_createIcons:function(){var t=this.options.icons;t&&(e("<span>").addClass("ui-accordion-header-icon ui-icon "+t.header).prependTo(this.headers),this.active.children(".ui-accordion-header-icon").removeClass(t.header).addClass(t.activeHeader),this.headers.addClass("ui-accordion-icons"))},_destroyIcons:function(){this.headers.removeClass("ui-accordion-icons").children(".ui-accordion-header-icon").remove()},_destroy:function(){var e;this.element.removeClass("ui-accordion ui-widget ui-helper-reset").removeAttr("role"),this.headers.removeClass("ui-accordion-header ui-accordion-header-active ui-helper-reset ui-state-default ui-corner-all ui-state-active ui-state-disabled ui-corner-top").removeAttr("role").removeAttr("aria-expanded").removeAttr("aria-selected").removeAttr("aria-controls").removeAttr("tabIndex").each(function(){/^ui-accordion/.test(this.id)&&this.removeAttribute("id")}),this._destroyIcons(),e=this.headers.next().css("display","").removeAttr("role").removeAttr("aria-hidden").removeAttr("aria-labelledby").removeClass("ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content ui-accordion-content-active ui-state-disabled").each(function(){/^ui-accordion/.test(this.id)&&this.removeAttribute("id")}),"content"!==this.options.heightStyle&&e.css("height","")},_setOption:function(e,t){return"active"===e?(this._activate(t),undefined):("event"===e&&(this.options.event&&this._off(this.headers,this.options.event),this._setupEvents(t)),this._super(e,t),"collapsible"!==e||t||this.options.active!==!1||this._activate(0),"icons"===e&&(this._destroyIcons(),t&&this._createIcons()),"disabled"===e&&this.headers.add(this.headers.next()).toggleClass("ui-state-disabled",!!t),undefined)},_keydown:function(t){if(!t.altKey&&!t.ctrlKey){var i=e.ui.keyCode,a=this.headers.length,s=this.headers.index(t.target),n=!1;switch(t.keyCode){case i.RIGHT:case i.DOWN:n=this.headers[(s+1)%a];break;case i.LEFT:case i.UP:n=this.headers[(s-1+a)%a];break;case i.SPACE:case i.ENTER:this._eventHandler(t);break;case i.HOME:n=this.headers[0];break;case i.END:n=this.headers[a-1]}n&&(e(t.target).attr("tabIndex",-1),e(n).attr("tabIndex",0),n.focus(),t.preventDefault())}},_panelKeyDown:function(t){t.keyCode===e.ui.keyCode.UP&&t.ctrlKey&&e(t.currentTarget).prev().focus()},refresh:function(){var t=this.options;this._processPanels(),t.active===!1&&t.collapsible===!0||!this.headers.length?(t.active=!1,this.active=e()):t.active===!1?this._activate(0):this.active.length&&!e.contains(this.element[0],this.active[0])?this.headers.length===this.headers.find(".ui-state-disabled").length?(t.active=!1,this.active=e()):this._activate(Math.max(0,t.active-1)):t.active=this.headers.index(this.active),this._destroyIcons(),this._refresh()},_processPanels:function(){this.headers=this.element.find(this.options.header).addClass("ui-accordion-header ui-helper-reset ui-state-default ui-corner-all"),this.headers.next().addClass("ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom").filter(":not(.ui-accordion-content-active)").hide()},_refresh:function(){var i,a=this.options,s=a.heightStyle,n=this.element.parent(),r=this.accordionId="ui-accordion-"+(this.element.attr("id")||++t);this.active=this._findActive(a.active).addClass("ui-accordion-header-active ui-state-active ui-corner-top").removeClass("ui-corner-all"),this.active.next().addClass("ui-accordion-content-active").show(),this.headers.attr("role","tab").each(function(t){var i=e(this),a=i.attr("id"),s=i.next(),n=s.attr("id");a||(a=r+"-header-"+t,i.attr("id",a)),n||(n=r+"-panel-"+t,s.attr("id",n)),i.attr("aria-controls",n),s.attr("aria-labelledby",a)}).next().attr("role","tabpanel"),this.headers.not(this.active).attr({"aria-selected":"false","aria-expanded":"false",tabIndex:-1}).next().attr({"aria-hidden":"true"}).hide(),this.active.length?this.active.attr({"aria-selected":"true","aria-expanded":"true",tabIndex:0}).next().attr({"aria-hidden":"false"}):this.headers.eq(0).attr("tabIndex",0),this._createIcons(),this._setupEvents(a.event),"fill"===s?(i=n.height(),this.element.siblings(":visible").each(function(){var t=e(this),a=t.css("position");"absolute"!==a&&"fixed"!==a&&(i-=t.outerHeight(!0))}),this.headers.each(function(){i-=e(this).outerHeight(!0)}),this.headers.next().each(function(){e(this).height(Math.max(0,i-e(this).innerHeight()+e(this).height()))}).css("overflow","auto")):"auto"===s&&(i=0,this.headers.next().each(function(){i=Math.max(i,e(this).css("height","").height())}).height(i))},_activate:function(t){var i=this._findActive(t)[0];i!==this.active[0]&&(i=i||this.active[0],this._eventHandler({target:i,currentTarget:i,preventDefault:e.noop}))},_findActive:function(t){return"number"==typeof t?this.headers.eq(t):e()},_setupEvents:function(t){var i={keydown:"_keydown"};t&&e.each(t.split(" "),function(e,t){i[t]="_eventHandler"}),this._off(this.headers.add(this.headers.next())),this._on(this.headers,i),this._on(this.headers.next(),{keydown:"_panelKeyDown"}),this._hoverable(this.headers),this._focusable(this.headers)},_eventHandler:function(t){var i=this.options,a=this.active,s=e(t.currentTarget),n=s[0]===a[0],r=n&&i.collapsible,o=r?e():s.next(),h=a.next(),d={oldHeader:a,oldPanel:h,newHeader:r?e():s,newPanel:o};t.preventDefault(),n&&!i.collapsible||this._trigger("beforeActivate",t,d)===!1||(i.active=r?!1:this.headers.index(s),this.active=n?e():s,this._toggle(d),a.removeClass("ui-accordion-header-active ui-state-active"),i.icons&&a.children(".ui-accordion-header-icon").removeClass(i.icons.activeHeader).addClass(i.icons.header),n||(s.removeClass("ui-corner-all").addClass("ui-accordion-header-active ui-state-active ui-corner-top"),i.icons&&s.children(".ui-accordion-header-icon").removeClass(i.icons.header).addClass(i.icons.activeHeader),s.next().addClass("ui-accordion-content-active")))},_toggle:function(t){var i=t.newPanel,a=this.prevShow.length?this.prevShow:t.oldPanel;this.prevShow.add(this.prevHide).stop(!0,!0),this.prevShow=i,this.prevHide=a,this.options.animate?this._animate(i,a,t):(a.hide(),i.show(),this._toggleComplete(t)),a.attr({"aria-hidden":"true"}),a.prev().attr("aria-selected","false"),i.length&&a.length?a.prev().attr({tabIndex:-1,"aria-expanded":"false"}):i.length&&this.headers.filter(function(){return 0===e(this).attr("tabIndex")}).attr("tabIndex",-1),i.attr("aria-hidden","false").prev().attr({"aria-selected":"true",tabIndex:0,"aria-expanded":"true"})},_animate:function(e,t,s){var n,r,o,h=this,d=0,c=e.length&&(!t.length||e.index()<t.index()),l=this.options.animate||{},u=c&&l.down||l,v=function(){h._toggleComplete(s)};return"number"==typeof u&&(o=u),"string"==typeof u&&(r=u),r=r||u.easing||l.easing,o=o||u.duration||l.duration,t.length?e.length?(n=e.show().outerHeight(),t.animate(i,{duration:o,easing:r,step:function(e,t){t.now=Math.round(e)}}),e.hide().animate(a,{duration:o,easing:r,complete:v,step:function(e,i){i.now=Math.round(e),"height"!==i.prop?d+=i.now:"content"!==h.options.heightStyle&&(i.now=Math.round(n-t.outerHeight()-d),d=0)}}),undefined):t.animate(i,o,r,v):e.animate(a,o,r,v)},_toggleComplete:function(e){var t=e.oldPanel;t.removeClass("ui-accordion-content-active").prev().removeClass("ui-corner-top").addClass("ui-corner-all"),t.length&&(t.parent()[0].className=t.parent()[0].className),this._trigger("activate",null,e)}})})(jQuery);(function(e){e.widget("ui.autocomplete",{version:"1.10.4",defaultElement:"<input>",options:{appendTo:null,autoFocus:!1,delay:300,minLength:1,position:{my:"left top",at:"left bottom",collision:"none"},source:null,change:null,close:null,focus:null,open:null,response:null,search:null,select:null},requestIndex:0,pending:0,_create:function(){var t,i,s,n=this.element[0].nodeName.toLowerCase(),a="textarea"===n,o="input"===n;this.isMultiLine=a?!0:o?!1:this.element.prop("isContentEditable"),this.valueMethod=this.element[a||o?"val":"text"],this.isNewMenu=!0,this.element.addClass("ui-autocomplete-input").attr("autocomplete","off"),this._on(this.element,{keydown:function(n){if(this.element.prop("readOnly"))return t=!0,s=!0,i=!0,undefined;t=!1,s=!1,i=!1;var a=e.ui.keyCode;switch(n.keyCode){case a.PAGE_UP:t=!0,this._move("previousPage",n);break;case a.PAGE_DOWN:t=!0,this._move("nextPage",n);break;case a.UP:t=!0,this._keyEvent("previous",n);break;case a.DOWN:t=!0,this._keyEvent("next",n);break;case a.ENTER:case a.NUMPAD_ENTER:this.menu.active&&(t=!0,n.preventDefault(),this.menu.select(n));break;case a.TAB:this.menu.active&&this.menu.select(n);break;case a.ESCAPE:this.menu.element.is(":visible")&&(this._value(this.term),this.close(n),n.preventDefault());break;default:i=!0,this._searchTimeout(n)}},keypress:function(s){if(t)return t=!1,(!this.isMultiLine||this.menu.element.is(":visible"))&&s.preventDefault(),undefined;if(!i){var n=e.ui.keyCode;switch(s.keyCode){case n.PAGE_UP:this._move("previousPage",s);break;case n.PAGE_DOWN:this._move("nextPage",s);break;case n.UP:this._keyEvent("previous",s);break;case n.DOWN:this._keyEvent("next",s)}}},input:function(e){return s?(s=!1,e.preventDefault(),undefined):(this._searchTimeout(e),undefined)},focus:function(){this.selectedItem=null,this.previous=this._value()},blur:function(e){return this.cancelBlur?(delete this.cancelBlur,undefined):(clearTimeout(this.searching),this.close(e),this._change(e),undefined)}}),this._initSource(),this.menu=e("<ul>").addClass("ui-autocomplete ui-front").appendTo(this._appendTo()).menu({role:null}).hide().data("ui-menu"),this._on(this.menu.element,{mousedown:function(t){t.preventDefault(),this.cancelBlur=!0,this._delay(function(){delete this.cancelBlur});var i=this.menu.element[0];e(t.target).closest(".ui-menu-item").length||this._delay(function(){var t=this;this.document.one("mousedown",function(s){s.target===t.element[0]||s.target===i||e.contains(i,s.target)||t.close()})})},menufocus:function(t,i){if(this.isNewMenu&&(this.isNewMenu=!1,t.originalEvent&&/^mouse/.test(t.originalEvent.type)))return this.menu.blur(),this.document.one("mousemove",function(){e(t.target).trigger(t.originalEvent)}),undefined;var s=i.item.data("ui-autocomplete-item");!1!==this._trigger("focus",t,{item:s})?t.originalEvent&&/^key/.test(t.originalEvent.type)&&this._value(s.value):this.liveRegion.text(s.value)},menuselect:function(e,t){var i=t.item.data("ui-autocomplete-item"),s=this.previous;this.element[0]!==this.document[0].activeElement&&(this.element.focus(),this.previous=s,this._delay(function(){this.previous=s,this.selectedItem=i})),!1!==this._trigger("select",e,{item:i})&&this._value(i.value),this.term=this._value(),this.close(e),this.selectedItem=i}}),this.liveRegion=e("<span>",{role:"status","aria-live":"polite"}).addClass("ui-helper-hidden-accessible").insertBefore(this.element),this._on(this.window,{beforeunload:function(){this.element.removeAttr("autocomplete")}})},_destroy:function(){clearTimeout(this.searching),this.element.removeClass("ui-autocomplete-input").removeAttr("autocomplete"),this.menu.element.remove(),this.liveRegion.remove()},_setOption:function(e,t){this._super(e,t),"source"===e&&this._initSource(),"appendTo"===e&&this.menu.element.appendTo(this._appendTo()),"disabled"===e&&t&&this.xhr&&this.xhr.abort()},_appendTo:function(){var t=this.options.appendTo;return t&&(t=t.jquery||t.nodeType?e(t):this.document.find(t).eq(0)),t||(t=this.element.closest(".ui-front")),t.length||(t=this.document[0].body),t},_initSource:function(){var t,i,s=this;e.isArray(this.options.source)?(t=this.options.source,this.source=function(i,s){s(e.ui.autocomplete.filter(t,i.term))}):"string"==typeof this.options.source?(i=this.options.source,this.source=function(t,n){s.xhr&&s.xhr.abort(),s.xhr=e.ajax({url:i,data:t,dataType:"json",success:function(e){n(e)},error:function(){n([])}})}):this.source=this.options.source},_searchTimeout:function(e){clearTimeout(this.searching),this.searching=this._delay(function(){this.term!==this._value()&&(this.selectedItem=null,this.search(null,e))},this.options.delay)},search:function(e,t){return e=null!=e?e:this._value(),this.term=this._value(),e.length<this.options.minLength?this.close(t):this._trigger("search",t)!==!1?this._search(e):undefined},_search:function(e){this.pending++,this.element.addClass("ui-autocomplete-loading"),this.cancelSearch=!1,this.source({term:e},this._response())},_response:function(){var t=++this.requestIndex;return e.proxy(function(e){t===this.requestIndex&&this.__response(e),this.pending--,this.pending||this.element.removeClass("ui-autocomplete-loading")},this)},__response:function(e){e&&(e=this._normalize(e)),this._trigger("response",null,{content:e}),!this.options.disabled&&e&&e.length&&!this.cancelSearch?(this._suggest(e),this._trigger("open")):this._close()},close:function(e){this.cancelSearch=!0,this._close(e)},_close:function(e){this.menu.element.is(":visible")&&(this.menu.element.hide(),this.menu.blur(),this.isNewMenu=!0,this._trigger("close",e))},_change:function(e){this.previous!==this._value()&&this._trigger("change",e,{item:this.selectedItem})},_normalize:function(t){return t.length&&t[0].label&&t[0].value?t:e.map(t,function(t){return"string"==typeof t?{label:t,value:t}:e.extend({label:t.label||t.value,value:t.value||t.label},t)})},_suggest:function(t){var i=this.menu.element.empty();this._renderMenu(i,t),this.isNewMenu=!0,this.menu.refresh(),i.show(),this._resizeMenu(),i.position(e.extend({of:this.element},this.options.position)),this.options.autoFocus&&this.menu.next()},_resizeMenu:function(){var e=this.menu.element;e.outerWidth(Math.max(e.width("").outerWidth()+1,this.element.outerWidth()))},_renderMenu:function(t,i){var s=this;e.each(i,function(e,i){s._renderItemData(t,i)})},_renderItemData:function(e,t){return this._renderItem(e,t).data("ui-autocomplete-item",t)},_renderItem:function(t,i){return e("<li>").append(e("<a>").text(i.label)).appendTo(t)},_move:function(e,t){return this.menu.element.is(":visible")?this.menu.isFirstItem()&&/^previous/.test(e)||this.menu.isLastItem()&&/^next/.test(e)?(this._value(this.term),this.menu.blur(),undefined):(this.menu[e](t),undefined):(this.search(null,t),undefined)},widget:function(){return this.menu.element},_value:function(){return this.valueMethod.apply(this.element,arguments)},_keyEvent:function(e,t){(!this.isMultiLine||this.menu.element.is(":visible"))&&(this._move(e,t),t.preventDefault())}}),e.extend(e.ui.autocomplete,{escapeRegex:function(e){return e.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")},filter:function(t,i){var s=RegExp(e.ui.autocomplete.escapeRegex(i),"i");return e.grep(t,function(e){return s.test(e.label||e.value||e)})}}),e.widget("ui.autocomplete",e.ui.autocomplete,{options:{messages:{noResults:"No search results.",results:function(e){return e+(e>1?" results are":" result is")+" available, use up and down arrow keys to navigate."}}},__response:function(e){var t;this._superApply(arguments),this.options.disabled||this.cancelSearch||(t=e&&e.length?this.options.messages.results(e.length):this.options.messages.noResults,this.liveRegion.text(t))}})})(jQuery);(function(e){var t,i="ui-button ui-widget ui-state-default ui-corner-all",n="ui-button-icons-only ui-button-icon-only ui-button-text-icons ui-button-text-icon-primary ui-button-text-icon-secondary ui-button-text-only",s=function(){var t=e(this);setTimeout(function(){t.find(":ui-button").button("refresh")},1)},a=function(t){var i=t.name,n=t.form,s=e([]);return i&&(i=i.replace(/'/g,"\\'"),s=n?e(n).find("[name='"+i+"']"):e("[name='"+i+"']",t.ownerDocument).filter(function(){return!this.form})),s};e.widget("ui.button",{version:"1.10.4",defaultElement:"<button>",options:{disabled:null,text:!0,label:null,icons:{primary:null,secondary:null}},_create:function(){this.element.closest("form").unbind("reset"+this.eventNamespace).bind("reset"+this.eventNamespace,s),"boolean"!=typeof this.options.disabled?this.options.disabled=!!this.element.prop("disabled"):this.element.prop("disabled",this.options.disabled),this._determineButtonType(),this.hasTitle=!!this.buttonElement.attr("title");var n=this,o=this.options,r="checkbox"===this.type||"radio"===this.type,h=r?"":"ui-state-active";null===o.label&&(o.label="input"===this.type?this.buttonElement.val():this.buttonElement.html()),this._hoverable(this.buttonElement),this.buttonElement.addClass(i).attr("role","button").bind("mouseenter"+this.eventNamespace,function(){o.disabled||this===t&&e(this).addClass("ui-state-active")}).bind("mouseleave"+this.eventNamespace,function(){o.disabled||e(this).removeClass(h)}).bind("click"+this.eventNamespace,function(e){o.disabled&&(e.preventDefault(),e.stopImmediatePropagation())}),this._on({focus:function(){this.buttonElement.addClass("ui-state-focus")},blur:function(){this.buttonElement.removeClass("ui-state-focus")}}),r&&this.element.bind("change"+this.eventNamespace,function(){n.refresh()}),"checkbox"===this.type?this.buttonElement.bind("click"+this.eventNamespace,function(){return o.disabled?!1:undefined}):"radio"===this.type?this.buttonElement.bind("click"+this.eventNamespace,function(){if(o.disabled)return!1;e(this).addClass("ui-state-active"),n.buttonElement.attr("aria-pressed","true");var t=n.element[0];a(t).not(t).map(function(){return e(this).button("widget")[0]}).removeClass("ui-state-active").attr("aria-pressed","false")}):(this.buttonElement.bind("mousedown"+this.eventNamespace,function(){return o.disabled?!1:(e(this).addClass("ui-state-active"),t=this,n.document.one("mouseup",function(){t=null}),undefined)}).bind("mouseup"+this.eventNamespace,function(){return o.disabled?!1:(e(this).removeClass("ui-state-active"),undefined)}).bind("keydown"+this.eventNamespace,function(t){return o.disabled?!1:((t.keyCode===e.ui.keyCode.SPACE||t.keyCode===e.ui.keyCode.ENTER)&&e(this).addClass("ui-state-active"),undefined)}).bind("keyup"+this.eventNamespace+" blur"+this.eventNamespace,function(){e(this).removeClass("ui-state-active")}),this.buttonElement.is("a")&&this.buttonElement.keyup(function(t){t.keyCode===e.ui.keyCode.SPACE&&e(this).click()})),this._setOption("disabled",o.disabled),this._resetButton()},_determineButtonType:function(){var e,t,i;this.type=this.element.is("[type=checkbox]")?"checkbox":this.element.is("[type=radio]")?"radio":this.element.is("input")?"input":"button","checkbox"===this.type||"radio"===this.type?(e=this.element.parents().last(),t="label[for='"+this.element.attr("id")+"']",this.buttonElement=e.find(t),this.buttonElement.length||(e=e.length?e.siblings():this.element.siblings(),this.buttonElement=e.filter(t),this.buttonElement.length||(this.buttonElement=e.find(t))),this.element.addClass("ui-helper-hidden-accessible"),i=this.element.is(":checked"),i&&this.buttonElement.addClass("ui-state-active"),this.buttonElement.prop("aria-pressed",i)):this.buttonElement=this.element},widget:function(){return this.buttonElement},_destroy:function(){this.element.removeClass("ui-helper-hidden-accessible"),this.buttonElement.removeClass(i+" ui-state-active "+n).removeAttr("role").removeAttr("aria-pressed").html(this.buttonElement.find(".ui-button-text").html()),this.hasTitle||this.buttonElement.removeAttr("title")},_setOption:function(e,t){return this._super(e,t),"disabled"===e?(this.element.prop("disabled",!!t),t&&this.buttonElement.removeClass("ui-state-focus"),undefined):(this._resetButton(),undefined)},refresh:function(){var t=this.element.is("input, button")?this.element.is(":disabled"):this.element.hasClass("ui-button-disabled");t!==this.options.disabled&&this._setOption("disabled",t),"radio"===this.type?a(this.element[0]).each(function(){e(this).is(":checked")?e(this).button("widget").addClass("ui-state-active").attr("aria-pressed","true"):e(this).button("widget").removeClass("ui-state-active").attr("aria-pressed","false")}):"checkbox"===this.type&&(this.element.is(":checked")?this.buttonElement.addClass("ui-state-active").attr("aria-pressed","true"):this.buttonElement.removeClass("ui-state-active").attr("aria-pressed","false"))},_resetButton:function(){if("input"===this.type)return this.options.label&&this.element.val(this.options.label),undefined;var t=this.buttonElement.removeClass(n),i=e("<span></span>",this.document[0]).addClass("ui-button-text").html(this.options.label).appendTo(t.empty()).text(),s=this.options.icons,a=s.primary&&s.secondary,o=[];s.primary||s.secondary?(this.options.text&&o.push("ui-button-text-icon"+(a?"s":s.primary?"-primary":"-secondary")),s.primary&&t.prepend("<span class='ui-button-icon-primary ui-icon "+s.primary+"'></span>"),s.secondary&&t.append("<span class='ui-button-icon-secondary ui-icon "+s.secondary+"'></span>"),this.options.text||(o.push(a?"ui-button-icons-only":"ui-button-icon-only"),this.hasTitle||t.attr("title",e.trim(i)))):o.push("ui-button-text-only"),t.addClass(o.join(" "))}}),e.widget("ui.buttonset",{version:"1.10.4",options:{items:"button, input[type=button], input[type=submit], input[type=reset], input[type=checkbox], input[type=radio], a, :data(ui-button)"},_create:function(){this.element.addClass("ui-buttonset")},_init:function(){this.refresh()},_setOption:function(e,t){"disabled"===e&&this.buttons.button("option",e,t),this._super(e,t)},refresh:function(){var t="rtl"===this.element.css("direction");this.buttons=this.element.find(this.options.items).filter(":ui-button").button("refresh").end().not(":ui-button").button().end().map(function(){return e(this).button("widget")[0]}).removeClass("ui-corner-all ui-corner-left ui-corner-right").filter(":first").addClass(t?"ui-corner-right":"ui-corner-left").end().filter(":last").addClass(t?"ui-corner-left":"ui-corner-right").end().end()},_destroy:function(){this.element.removeClass("ui-buttonset"),this.buttons.map(function(){return e(this).button("widget")[0]}).removeClass("ui-corner-left ui-corner-right").end().button("destroy")}})})(jQuery);(function(e,t){function i(){this._curInst=null,this._keyEvent=!1,this._disabledInputs=[],this._datepickerShowing=!1,this._inDialog=!1,this._mainDivId="ui-datepicker-div",this._inlineClass="ui-datepicker-inline",this._appendClass="ui-datepicker-append",this._triggerClass="ui-datepicker-trigger",this._dialogClass="ui-datepicker-dialog",this._disableClass="ui-datepicker-disabled",this._unselectableClass="ui-datepicker-unselectable",this._currentClass="ui-datepicker-current-day",this._dayOverClass="ui-datepicker-days-cell-over",this.regional=[],this.regional[""]={closeText:"Done",prevText:"Prev",nextText:"Next",currentText:"Today",monthNames:["January","February","March","April","May","June","July","August","September","October","November","December"],monthNamesShort:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],dayNames:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],dayNamesShort:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],dayNamesMin:["Su","Mo","Tu","We","Th","Fr","Sa"],weekHeader:"Wk",dateFormat:"mm/dd/yy",firstDay:0,isRTL:!1,showMonthAfterYear:!1,yearSuffix:""},this._defaults={showOn:"focus",showAnim:"fadeIn",showOptions:{},defaultDate:null,appendText:"",buttonText:"...",buttonImage:"",buttonImageOnly:!1,hideIfNoPrevNext:!1,navigationAsDateFormat:!1,gotoCurrent:!1,changeMonth:!1,changeYear:!1,yearRange:"c-10:c+10",showOtherMonths:!1,selectOtherMonths:!1,showWeek:!1,calculateWeek:this.iso8601Week,shortYearCutoff:"+10",minDate:null,maxDate:null,duration:"fast",beforeShowDay:null,beforeShow:null,onSelect:null,onChangeMonthYear:null,onClose:null,numberOfMonths:1,showCurrentAtPos:0,stepMonths:1,stepBigMonths:12,altField:"",altFormat:"",constrainInput:!0,showButtonPanel:!1,autoSize:!1,disabled:!1},e.extend(this._defaults,this.regional[""]),this.dpDiv=a(e("<div id='"+this._mainDivId+"' class='ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all'></div>"))}function a(t){var i="button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a";return t.delegate(i,"mouseout",function(){e(this).removeClass("ui-state-hover"),-1!==this.className.indexOf("ui-datepicker-prev")&&e(this).removeClass("ui-datepicker-prev-hover"),-1!==this.className.indexOf("ui-datepicker-next")&&e(this).removeClass("ui-datepicker-next-hover")}).delegate(i,"mouseover",function(){e.datepicker._isDisabledDatepicker(n.inline?t.parent()[0]:n.input[0])||(e(this).parents(".ui-datepicker-calendar").find("a").removeClass("ui-state-hover"),e(this).addClass("ui-state-hover"),-1!==this.className.indexOf("ui-datepicker-prev")&&e(this).addClass("ui-datepicker-prev-hover"),-1!==this.className.indexOf("ui-datepicker-next")&&e(this).addClass("ui-datepicker-next-hover"))})}function s(t,i){e.extend(t,i);for(var a in i)null==i[a]&&(t[a]=i[a]);return t}e.extend(e.ui,{datepicker:{version:"1.10.4"}});var n,r="datepicker";e.extend(i.prototype,{markerClassName:"hasDatepicker",maxRows:4,_widgetDatepicker:function(){return this.dpDiv},setDefaults:function(e){return s(this._defaults,e||{}),this},_attachDatepicker:function(t,i){var a,s,n;a=t.nodeName.toLowerCase(),s="div"===a||"span"===a,t.id||(this.uuid+=1,t.id="dp"+this.uuid),n=this._newInst(e(t),s),n.settings=e.extend({},i||{}),"input"===a?this._connectDatepicker(t,n):s&&this._inlineDatepicker(t,n)},_newInst:function(t,i){var s=t[0].id.replace(/([^A-Za-z0-9_\-])/g,"\\\\$1");return{id:s,input:t,selectedDay:0,selectedMonth:0,selectedYear:0,drawMonth:0,drawYear:0,inline:i,dpDiv:i?a(e("<div class='"+this._inlineClass+" ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all'></div>")):this.dpDiv}},_connectDatepicker:function(t,i){var a=e(t);i.append=e([]),i.trigger=e([]),a.hasClass(this.markerClassName)||(this._attachments(a,i),a.addClass(this.markerClassName).keydown(this._doKeyDown).keypress(this._doKeyPress).keyup(this._doKeyUp),this._autoSize(i),e.data(t,r,i),i.settings.disabled&&this._disableDatepicker(t))},_attachments:function(t,i){var a,s,n,r=this._get(i,"appendText"),o=this._get(i,"isRTL");i.append&&i.append.remove(),r&&(i.append=e("<span class='"+this._appendClass+"'>"+r+"</span>"),t[o?"before":"after"](i.append)),t.unbind("focus",this._showDatepicker),i.trigger&&i.trigger.remove(),a=this._get(i,"showOn"),("focus"===a||"both"===a)&&t.focus(this._showDatepicker),("button"===a||"both"===a)&&(s=this._get(i,"buttonText"),n=this._get(i,"buttonImage"),i.trigger=e(this._get(i,"buttonImageOnly")?e("<img/>").addClass(this._triggerClass).attr({src:n,alt:s,title:s}):e("<button type='button'></button>").addClass(this._triggerClass).html(n?e("<img/>").attr({src:n,alt:s,title:s}):s)),t[o?"before":"after"](i.trigger),i.trigger.click(function(){return e.datepicker._datepickerShowing&&e.datepicker._lastInput===t[0]?e.datepicker._hideDatepicker():e.datepicker._datepickerShowing&&e.datepicker._lastInput!==t[0]?(e.datepicker._hideDatepicker(),e.datepicker._showDatepicker(t[0])):e.datepicker._showDatepicker(t[0]),!1}))},_autoSize:function(e){if(this._get(e,"autoSize")&&!e.inline){var t,i,a,s,n=new Date(2009,11,20),r=this._get(e,"dateFormat");r.match(/[DM]/)&&(t=function(e){for(i=0,a=0,s=0;e.length>s;s++)e[s].length>i&&(i=e[s].length,a=s);return a},n.setMonth(t(this._get(e,r.match(/MM/)?"monthNames":"monthNamesShort"))),n.setDate(t(this._get(e,r.match(/DD/)?"dayNames":"dayNamesShort"))+20-n.getDay())),e.input.attr("size",this._formatDate(e,n).length)}},_inlineDatepicker:function(t,i){var a=e(t);a.hasClass(this.markerClassName)||(a.addClass(this.markerClassName).append(i.dpDiv),e.data(t,r,i),this._setDate(i,this._getDefaultDate(i),!0),this._updateDatepicker(i),this._updateAlternate(i),i.settings.disabled&&this._disableDatepicker(t),i.dpDiv.css("display","block"))},_dialogDatepicker:function(t,i,a,n,o){var u,c,h,l,d,p=this._dialogInst;return p||(this.uuid+=1,u="dp"+this.uuid,this._dialogInput=e("<input type='text' id='"+u+"' style='position: absolute; top: -100px; width: 0px;'/>"),this._dialogInput.keydown(this._doKeyDown),e("body").append(this._dialogInput),p=this._dialogInst=this._newInst(this._dialogInput,!1),p.settings={},e.data(this._dialogInput[0],r,p)),s(p.settings,n||{}),i=i&&i.constructor===Date?this._formatDate(p,i):i,this._dialogInput.val(i),this._pos=o?o.length?o:[o.pageX,o.pageY]:null,this._pos||(c=document.documentElement.clientWidth,h=document.documentElement.clientHeight,l=document.documentElement.scrollLeft||document.body.scrollLeft,d=document.documentElement.scrollTop||document.body.scrollTop,this._pos=[c/2-100+l,h/2-150+d]),this._dialogInput.css("left",this._pos[0]+20+"px").css("top",this._pos[1]+"px"),p.settings.onSelect=a,this._inDialog=!0,this.dpDiv.addClass(this._dialogClass),this._showDatepicker(this._dialogInput[0]),e.blockUI&&e.blockUI(this.dpDiv),e.data(this._dialogInput[0],r,p),this},_destroyDatepicker:function(t){var i,a=e(t),s=e.data(t,r);a.hasClass(this.markerClassName)&&(i=t.nodeName.toLowerCase(),e.removeData(t,r),"input"===i?(s.append.remove(),s.trigger.remove(),a.removeClass(this.markerClassName).unbind("focus",this._showDatepicker).unbind("keydown",this._doKeyDown).unbind("keypress",this._doKeyPress).unbind("keyup",this._doKeyUp)):("div"===i||"span"===i)&&a.removeClass(this.markerClassName).empty())},_enableDatepicker:function(t){var i,a,s=e(t),n=e.data(t,r);s.hasClass(this.markerClassName)&&(i=t.nodeName.toLowerCase(),"input"===i?(t.disabled=!1,n.trigger.filter("button").each(function(){this.disabled=!1}).end().filter("img").css({opacity:"1.0",cursor:""})):("div"===i||"span"===i)&&(a=s.children("."+this._inlineClass),a.children().removeClass("ui-state-disabled"),a.find("select.ui-datepicker-month, select.ui-datepicker-year").prop("disabled",!1)),this._disabledInputs=e.map(this._disabledInputs,function(e){return e===t?null:e}))},_disableDatepicker:function(t){var i,a,s=e(t),n=e.data(t,r);s.hasClass(this.markerClassName)&&(i=t.nodeName.toLowerCase(),"input"===i?(t.disabled=!0,n.trigger.filter("button").each(function(){this.disabled=!0}).end().filter("img").css({opacity:"0.5",cursor:"default"})):("div"===i||"span"===i)&&(a=s.children("."+this._inlineClass),a.children().addClass("ui-state-disabled"),a.find("select.ui-datepicker-month, select.ui-datepicker-year").prop("disabled",!0)),this._disabledInputs=e.map(this._disabledInputs,function(e){return e===t?null:e}),this._disabledInputs[this._disabledInputs.length]=t)},_isDisabledDatepicker:function(e){if(!e)return!1;for(var t=0;this._disabledInputs.length>t;t++)if(this._disabledInputs[t]===e)return!0;return!1},_getInst:function(t){try{return e.data(t,r)}catch(i){throw"Missing instance data for this datepicker"}},_optionDatepicker:function(i,a,n){var r,o,u,c,h=this._getInst(i);return 2===arguments.length&&"string"==typeof a?"defaults"===a?e.extend({},e.datepicker._defaults):h?"all"===a?e.extend({},h.settings):this._get(h,a):null:(r=a||{},"string"==typeof a&&(r={},r[a]=n),h&&(this._curInst===h&&this._hideDatepicker(),o=this._getDateDatepicker(i,!0),u=this._getMinMaxDate(h,"min"),c=this._getMinMaxDate(h,"max"),s(h.settings,r),null!==u&&r.dateFormat!==t&&r.minDate===t&&(h.settings.minDate=this._formatDate(h,u)),null!==c&&r.dateFormat!==t&&r.maxDate===t&&(h.settings.maxDate=this._formatDate(h,c)),"disabled"in r&&(r.disabled?this._disableDatepicker(i):this._enableDatepicker(i)),this._attachments(e(i),h),this._autoSize(h),this._setDate(h,o),this._updateAlternate(h),this._updateDatepicker(h)),t)},_changeDatepicker:function(e,t,i){this._optionDatepicker(e,t,i)},_refreshDatepicker:function(e){var t=this._getInst(e);t&&this._updateDatepicker(t)},_setDateDatepicker:function(e,t){var i=this._getInst(e);i&&(this._setDate(i,t),this._updateDatepicker(i),this._updateAlternate(i))},_getDateDatepicker:function(e,t){var i=this._getInst(e);return i&&!i.inline&&this._setDateFromField(i,t),i?this._getDate(i):null},_doKeyDown:function(t){var i,a,s,n=e.datepicker._getInst(t.target),r=!0,o=n.dpDiv.is(".ui-datepicker-rtl");if(n._keyEvent=!0,e.datepicker._datepickerShowing)switch(t.keyCode){case 9:e.datepicker._hideDatepicker(),r=!1;break;case 13:return s=e("td."+e.datepicker._dayOverClass+":not(."+e.datepicker._currentClass+")",n.dpDiv),s[0]&&e.datepicker._selectDay(t.target,n.selectedMonth,n.selectedYear,s[0]),i=e.datepicker._get(n,"onSelect"),i?(a=e.datepicker._formatDate(n),i.apply(n.input?n.input[0]:null,[a,n])):e.datepicker._hideDatepicker(),!1;case 27:e.datepicker._hideDatepicker();break;case 33:e.datepicker._adjustDate(t.target,t.ctrlKey?-e.datepicker._get(n,"stepBigMonths"):-e.datepicker._get(n,"stepMonths"),"M");break;case 34:e.datepicker._adjustDate(t.target,t.ctrlKey?+e.datepicker._get(n,"stepBigMonths"):+e.datepicker._get(n,"stepMonths"),"M");break;case 35:(t.ctrlKey||t.metaKey)&&e.datepicker._clearDate(t.target),r=t.ctrlKey||t.metaKey;break;case 36:(t.ctrlKey||t.metaKey)&&e.datepicker._gotoToday(t.target),r=t.ctrlKey||t.metaKey;break;case 37:(t.ctrlKey||t.metaKey)&&e.datepicker._adjustDate(t.target,o?1:-1,"D"),r=t.ctrlKey||t.metaKey,t.originalEvent.altKey&&e.datepicker._adjustDate(t.target,t.ctrlKey?-e.datepicker._get(n,"stepBigMonths"):-e.datepicker._get(n,"stepMonths"),"M");break;case 38:(t.ctrlKey||t.metaKey)&&e.datepicker._adjustDate(t.target,-7,"D"),r=t.ctrlKey||t.metaKey;break;case 39:(t.ctrlKey||t.metaKey)&&e.datepicker._adjustDate(t.target,o?-1:1,"D"),r=t.ctrlKey||t.metaKey,t.originalEvent.altKey&&e.datepicker._adjustDate(t.target,t.ctrlKey?+e.datepicker._get(n,"stepBigMonths"):+e.datepicker._get(n,"stepMonths"),"M");break;case 40:(t.ctrlKey||t.metaKey)&&e.datepicker._adjustDate(t.target,7,"D"),r=t.ctrlKey||t.metaKey;break;default:r=!1}else 36===t.keyCode&&t.ctrlKey?e.datepicker._showDatepicker(this):r=!1;r&&(t.preventDefault(),t.stopPropagation())},_doKeyPress:function(i){var a,s,n=e.datepicker._getInst(i.target);return e.datepicker._get(n,"constrainInput")?(a=e.datepicker._possibleChars(e.datepicker._get(n,"dateFormat")),s=String.fromCharCode(null==i.charCode?i.keyCode:i.charCode),i.ctrlKey||i.metaKey||" ">s||!a||a.indexOf(s)>-1):t},_doKeyUp:function(t){var i,a=e.datepicker._getInst(t.target);if(a.input.val()!==a.lastVal)try{i=e.datepicker.parseDate(e.datepicker._get(a,"dateFormat"),a.input?a.input.val():null,e.datepicker._getFormatConfig(a)),i&&(e.datepicker._setDateFromField(a),e.datepicker._updateAlternate(a),e.datepicker._updateDatepicker(a))}catch(s){}return!0},_showDatepicker:function(t){if(t=t.target||t,"input"!==t.nodeName.toLowerCase()&&(t=e("input",t.parentNode)[0]),!e.datepicker._isDisabledDatepicker(t)&&e.datepicker._lastInput!==t){var i,a,n,r,o,u,c;i=e.datepicker._getInst(t),e.datepicker._curInst&&e.datepicker._curInst!==i&&(e.datepicker._curInst.dpDiv.stop(!0,!0),i&&e.datepicker._datepickerShowing&&e.datepicker._hideDatepicker(e.datepicker._curInst.input[0])),a=e.datepicker._get(i,"beforeShow"),n=a?a.apply(t,[t,i]):{},n!==!1&&(s(i.settings,n),i.lastVal=null,e.datepicker._lastInput=t,e.datepicker._setDateFromField(i),e.datepicker._inDialog&&(t.value=""),e.datepicker._pos||(e.datepicker._pos=e.datepicker._findPos(t),e.datepicker._pos[1]+=t.offsetHeight),r=!1,e(t).parents().each(function(){return r|="fixed"===e(this).css("position"),!r}),o={left:e.datepicker._pos[0],top:e.datepicker._pos[1]},e.datepicker._pos=null,i.dpDiv.empty(),i.dpDiv.css({position:"absolute",display:"block",top:"-1000px"}),e.datepicker._updateDatepicker(i),o=e.datepicker._checkOffset(i,o,r),i.dpDiv.css({position:e.datepicker._inDialog&&e.blockUI?"static":r?"fixed":"absolute",display:"none",left:o.left+"px",top:o.top+"px"}),i.inline||(u=e.datepicker._get(i,"showAnim"),c=e.datepicker._get(i,"duration"),i.dpDiv.zIndex(e(t).zIndex()+1),e.datepicker._datepickerShowing=!0,e.effects&&e.effects.effect[u]?i.dpDiv.show(u,e.datepicker._get(i,"showOptions"),c):i.dpDiv[u||"show"](u?c:null),e.datepicker._shouldFocusInput(i)&&i.input.focus(),e.datepicker._curInst=i))}},_updateDatepicker:function(t){this.maxRows=4,n=t,t.dpDiv.empty().append(this._generateHTML(t)),this._attachHandlers(t),t.dpDiv.find("."+this._dayOverClass+" a").mouseover();var i,a=this._getNumberOfMonths(t),s=a[1],r=17;t.dpDiv.removeClass("ui-datepicker-multi-2 ui-datepicker-multi-3 ui-datepicker-multi-4").width(""),s>1&&t.dpDiv.addClass("ui-datepicker-multi-"+s).css("width",r*s+"em"),t.dpDiv[(1!==a[0]||1!==a[1]?"add":"remove")+"Class"]("ui-datepicker-multi"),t.dpDiv[(this._get(t,"isRTL")?"add":"remove")+"Class"]("ui-datepicker-rtl"),t===e.datepicker._curInst&&e.datepicker._datepickerShowing&&e.datepicker._shouldFocusInput(t)&&t.input.focus(),t.yearshtml&&(i=t.yearshtml,setTimeout(function(){i===t.yearshtml&&t.yearshtml&&t.dpDiv.find("select.ui-datepicker-year:first").replaceWith(t.yearshtml),i=t.yearshtml=null},0))},_shouldFocusInput:function(e){return e.input&&e.input.is(":visible")&&!e.input.is(":disabled")&&!e.input.is(":focus")},_checkOffset:function(t,i,a){var s=t.dpDiv.outerWidth(),n=t.dpDiv.outerHeight(),r=t.input?t.input.outerWidth():0,o=t.input?t.input.outerHeight():0,u=document.documentElement.clientWidth+(a?0:e(document).scrollLeft()),c=document.documentElement.clientHeight+(a?0:e(document).scrollTop());return i.left-=this._get(t,"isRTL")?s-r:0,i.left-=a&&i.left===t.input.offset().left?e(document).scrollLeft():0,i.top-=a&&i.top===t.input.offset().top+o?e(document).scrollTop():0,i.left-=Math.min(i.left,i.left+s>u&&u>s?Math.abs(i.left+s-u):0),i.top-=Math.min(i.top,i.top+n>c&&c>n?Math.abs(n+o):0),i},_findPos:function(t){for(var i,a=this._getInst(t),s=this._get(a,"isRTL");t&&("hidden"===t.type||1!==t.nodeType||e.expr.filters.hidden(t));)t=t[s?"previousSibling":"nextSibling"];return i=e(t).offset(),[i.left,i.top]},_hideDatepicker:function(t){var i,a,s,n,o=this._curInst;!o||t&&o!==e.data(t,r)||this._datepickerShowing&&(i=this._get(o,"showAnim"),a=this._get(o,"duration"),s=function(){e.datepicker._tidyDialog(o)},e.effects&&(e.effects.effect[i]||e.effects[i])?o.dpDiv.hide(i,e.datepicker._get(o,"showOptions"),a,s):o.dpDiv["slideDown"===i?"slideUp":"fadeIn"===i?"fadeOut":"hide"](i?a:null,s),i||s(),this._datepickerShowing=!1,n=this._get(o,"onClose"),n&&n.apply(o.input?o.input[0]:null,[o.input?o.input.val():"",o]),this._lastInput=null,this._inDialog&&(this._dialogInput.css({position:"absolute",left:"0",top:"-100px"}),e.blockUI&&(e.unblockUI(),e("body").append(this.dpDiv))),this._inDialog=!1)},_tidyDialog:function(e){e.dpDiv.removeClass(this._dialogClass).unbind(".ui-datepicker-calendar")},_checkExternalClick:function(t){if(e.datepicker._curInst){var i=e(t.target),a=e.datepicker._getInst(i[0]);(i[0].id!==e.datepicker._mainDivId&&0===i.parents("#"+e.datepicker._mainDivId).length&&!i.hasClass(e.datepicker.markerClassName)&&!i.closest("."+e.datepicker._triggerClass).length&&e.datepicker._datepickerShowing&&(!e.datepicker._inDialog||!e.blockUI)||i.hasClass(e.datepicker.markerClassName)&&e.datepicker._curInst!==a)&&e.datepicker._hideDatepicker()}},_adjustDate:function(t,i,a){var s=e(t),n=this._getInst(s[0]);this._isDisabledDatepicker(s[0])||(this._adjustInstDate(n,i+("M"===a?this._get(n,"showCurrentAtPos"):0),a),this._updateDatepicker(n))},_gotoToday:function(t){var i,a=e(t),s=this._getInst(a[0]);this._get(s,"gotoCurrent")&&s.currentDay?(s.selectedDay=s.currentDay,s.drawMonth=s.selectedMonth=s.currentMonth,s.drawYear=s.selectedYear=s.currentYear):(i=new Date,s.selectedDay=i.getDate(),s.drawMonth=s.selectedMonth=i.getMonth(),s.drawYear=s.selectedYear=i.getFullYear()),this._notifyChange(s),this._adjustDate(a)},_selectMonthYear:function(t,i,a){var s=e(t),n=this._getInst(s[0]);n["selected"+("M"===a?"Month":"Year")]=n["draw"+("M"===a?"Month":"Year")]=parseInt(i.options[i.selectedIndex].value,10),this._notifyChange(n),this._adjustDate(s)},_selectDay:function(t,i,a,s){var n,r=e(t);e(s).hasClass(this._unselectableClass)||this._isDisabledDatepicker(r[0])||(n=this._getInst(r[0]),n.selectedDay=n.currentDay=e("a",s).html(),n.selectedMonth=n.currentMonth=i,n.selectedYear=n.currentYear=a,this._selectDate(t,this._formatDate(n,n.currentDay,n.currentMonth,n.currentYear)))},_clearDate:function(t){var i=e(t);this._selectDate(i,"")},_selectDate:function(t,i){var a,s=e(t),n=this._getInst(s[0]);i=null!=i?i:this._formatDate(n),n.input&&n.input.val(i),this._updateAlternate(n),a=this._get(n,"onSelect"),a?a.apply(n.input?n.input[0]:null,[i,n]):n.input&&n.input.trigger("change"),n.inline?this._updateDatepicker(n):(this._hideDatepicker(),this._lastInput=n.input[0],"object"!=typeof n.input[0]&&n.input.focus(),this._lastInput=null)},_updateAlternate:function(t){var i,a,s,n=this._get(t,"altField");n&&(i=this._get(t,"altFormat")||this._get(t,"dateFormat"),a=this._getDate(t),s=this.formatDate(i,a,this._getFormatConfig(t)),e(n).each(function(){e(this).val(s)}))},noWeekends:function(e){var t=e.getDay();return[t>0&&6>t,""]},iso8601Week:function(e){var t,i=new Date(e.getTime());return i.setDate(i.getDate()+4-(i.getDay()||7)),t=i.getTime(),i.setMonth(0),i.setDate(1),Math.floor(Math.round((t-i)/864e5)/7)+1},parseDate:function(i,a,s){if(null==i||null==a)throw"Invalid arguments";if(a="object"==typeof a?""+a:a+"",""===a)return null;var n,r,o,u,c=0,h=(s?s.shortYearCutoff:null)||this._defaults.shortYearCutoff,l="string"!=typeof h?h:(new Date).getFullYear()%100+parseInt(h,10),d=(s?s.dayNamesShort:null)||this._defaults.dayNamesShort,p=(s?s.dayNames:null)||this._defaults.dayNames,g=(s?s.monthNamesShort:null)||this._defaults.monthNamesShort,m=(s?s.monthNames:null)||this._defaults.monthNames,f=-1,_=-1,v=-1,k=-1,y=!1,b=function(e){var t=i.length>n+1&&i.charAt(n+1)===e;return t&&n++,t},D=function(e){var t=b(e),i="@"===e?14:"!"===e?20:"y"===e&&t?4:"o"===e?3:2,s=RegExp("^\\d{1,"+i+"}"),n=a.substring(c).match(s);if(!n)throw"Missing number at position "+c;return c+=n[0].length,parseInt(n[0],10)},w=function(i,s,n){var r=-1,o=e.map(b(i)?n:s,function(e,t){return[[t,e]]}).sort(function(e,t){return-(e[1].length-t[1].length)});if(e.each(o,function(e,i){var s=i[1];return a.substr(c,s.length).toLowerCase()===s.toLowerCase()?(r=i[0],c+=s.length,!1):t}),-1!==r)return r+1;throw"Unknown name at position "+c},M=function(){if(a.charAt(c)!==i.charAt(n))throw"Unexpected literal at position "+c;c++};for(n=0;i.length>n;n++)if(y)"'"!==i.charAt(n)||b("'")?M():y=!1;else switch(i.charAt(n)){case"d":v=D("d");break;case"D":w("D",d,p);break;case"o":k=D("o");break;case"m":_=D("m");break;case"M":_=w("M",g,m);break;case"y":f=D("y");break;case"@":u=new Date(D("@")),f=u.getFullYear(),_=u.getMonth()+1,v=u.getDate();break;case"!":u=new Date((D("!")-this._ticksTo1970)/1e4),f=u.getFullYear(),_=u.getMonth()+1,v=u.getDate();break;case"'":b("'")?M():y=!0;break;default:M()}if(a.length>c&&(o=a.substr(c),!/^\s+/.test(o)))throw"Extra/unparsed characters found in date: "+o;if(-1===f?f=(new Date).getFullYear():100>f&&(f+=(new Date).getFullYear()-(new Date).getFullYear()%100+(l>=f?0:-100)),k>-1)for(_=1,v=k;;){if(r=this._getDaysInMonth(f,_-1),r>=v)break;_++,v-=r}if(u=this._daylightSavingAdjust(new Date(f,_-1,v)),u.getFullYear()!==f||u.getMonth()+1!==_||u.getDate()!==v)throw"Invalid date";return u},ATOM:"yy-mm-dd",COOKIE:"D, dd M yy",ISO_8601:"yy-mm-dd",RFC_822:"D, d M y",RFC_850:"DD, dd-M-y",RFC_1036:"D, d M y",RFC_1123:"D, d M yy",RFC_2822:"D, d M yy",RSS:"D, d M y",TICKS:"!",TIMESTAMP:"@",W3C:"yy-mm-dd",_ticksTo1970:1e7*60*60*24*(718685+Math.floor(492.5)-Math.floor(19.7)+Math.floor(4.925)),formatDate:function(e,t,i){if(!t)return"";var a,s=(i?i.dayNamesShort:null)||this._defaults.dayNamesShort,n=(i?i.dayNames:null)||this._defaults.dayNames,r=(i?i.monthNamesShort:null)||this._defaults.monthNamesShort,o=(i?i.monthNames:null)||this._defaults.monthNames,u=function(t){var i=e.length>a+1&&e.charAt(a+1)===t;return i&&a++,i},c=function(e,t,i){var a=""+t;if(u(e))for(;i>a.length;)a="0"+a;return a},h=function(e,t,i,a){return u(e)?a[t]:i[t]},l="",d=!1;if(t)for(a=0;e.length>a;a++)if(d)"'"!==e.charAt(a)||u("'")?l+=e.charAt(a):d=!1;else switch(e.charAt(a)){case"d":l+=c("d",t.getDate(),2);break;case"D":l+=h("D",t.getDay(),s,n);break;case"o":l+=c("o",Math.round((new Date(t.getFullYear(),t.getMonth(),t.getDate()).getTime()-new Date(t.getFullYear(),0,0).getTime())/864e5),3);break;case"m":l+=c("m",t.getMonth()+1,2);break;case"M":l+=h("M",t.getMonth(),r,o);break;case"y":l+=u("y")?t.getFullYear():(10>t.getYear()%100?"0":"")+t.getYear()%100;break;case"@":l+=t.getTime();break;case"!":l+=1e4*t.getTime()+this._ticksTo1970;break;case"'":u("'")?l+="'":d=!0;break;default:l+=e.charAt(a)}return l},_possibleChars:function(e){var t,i="",a=!1,s=function(i){var a=e.length>t+1&&e.charAt(t+1)===i;return a&&t++,a};for(t=0;e.length>t;t++)if(a)"'"!==e.charAt(t)||s("'")?i+=e.charAt(t):a=!1;else switch(e.charAt(t)){case"d":case"m":case"y":case"@":i+="0123456789";break;case"D":case"M":return null;case"'":s("'")?i+="'":a=!0;break;default:i+=e.charAt(t)}return i},_get:function(e,i){return e.settings[i]!==t?e.settings[i]:this._defaults[i]},_setDateFromField:function(e,t){if(e.input.val()!==e.lastVal){var i=this._get(e,"dateFormat"),a=e.lastVal=e.input?e.input.val():null,s=this._getDefaultDate(e),n=s,r=this._getFormatConfig(e);try{n=this.parseDate(i,a,r)||s}catch(o){a=t?"":a}e.selectedDay=n.getDate(),e.drawMonth=e.selectedMonth=n.getMonth(),e.drawYear=e.selectedYear=n.getFullYear(),e.currentDay=a?n.getDate():0,e.currentMonth=a?n.getMonth():0,e.currentYear=a?n.getFullYear():0,this._adjustInstDate(e)}},_getDefaultDate:function(e){return this._restrictMinMax(e,this._determineDate(e,this._get(e,"defaultDate"),new Date))},_determineDate:function(t,i,a){var s=function(e){var t=new Date;return t.setDate(t.getDate()+e),t},n=function(i){try{return e.datepicker.parseDate(e.datepicker._get(t,"dateFormat"),i,e.datepicker._getFormatConfig(t))}catch(a){}for(var s=(i.toLowerCase().match(/^c/)?e.datepicker._getDate(t):null)||new Date,n=s.getFullYear(),r=s.getMonth(),o=s.getDate(),u=/([+\-]?[0-9]+)\s*(d|D|w|W|m|M|y|Y)?/g,c=u.exec(i);c;){switch(c[2]||"d"){case"d":case"D":o+=parseInt(c[1],10);break;case"w":case"W":o+=7*parseInt(c[1],10);break;case"m":case"M":r+=parseInt(c[1],10),o=Math.min(o,e.datepicker._getDaysInMonth(n,r));break;case"y":case"Y":n+=parseInt(c[1],10),o=Math.min(o,e.datepicker._getDaysInMonth(n,r))}c=u.exec(i)}return new Date(n,r,o)},r=null==i||""===i?a:"string"==typeof i?n(i):"number"==typeof i?isNaN(i)?a:s(i):new Date(i.getTime());return r=r&&"Invalid Date"==""+r?a:r,r&&(r.setHours(0),r.setMinutes(0),r.setSeconds(0),r.setMilliseconds(0)),this._daylightSavingAdjust(r)},_daylightSavingAdjust:function(e){return e?(e.setHours(e.getHours()>12?e.getHours()+2:0),e):null},_setDate:function(e,t,i){var a=!t,s=e.selectedMonth,n=e.selectedYear,r=this._restrictMinMax(e,this._determineDate(e,t,new Date));e.selectedDay=e.currentDay=r.getDate(),e.drawMonth=e.selectedMonth=e.currentMonth=r.getMonth(),e.drawYear=e.selectedYear=e.currentYear=r.getFullYear(),s===e.selectedMonth&&n===e.selectedYear||i||this._notifyChange(e),this._adjustInstDate(e),e.input&&e.input.val(a?"":this._formatDate(e))},_getDate:function(e){var t=!e.currentYear||e.input&&""===e.input.val()?null:this._daylightSavingAdjust(new Date(e.currentYear,e.currentMonth,e.currentDay));return t},_attachHandlers:function(t){var i=this._get(t,"stepMonths"),a="#"+t.id.replace(/\\\\/g,"\\");t.dpDiv.find("[data-handler]").map(function(){var t={prev:function(){e.datepicker._adjustDate(a,-i,"M")},next:function(){e.datepicker._adjustDate(a,+i,"M")},hide:function(){e.datepicker._hideDatepicker()},today:function(){e.datepicker._gotoToday(a)},selectDay:function(){return e.datepicker._selectDay(a,+this.getAttribute("data-month"),+this.getAttribute("data-year"),this),!1},selectMonth:function(){return e.datepicker._selectMonthYear(a,this,"M"),!1},selectYear:function(){return e.datepicker._selectMonthYear(a,this,"Y"),!1}};e(this).bind(this.getAttribute("data-event"),t[this.getAttribute("data-handler")])})},_generateHTML:function(e){var t,i,a,s,n,r,o,u,c,h,l,d,p,g,m,f,_,v,k,y,b,D,w,M,C,x,I,N,T,A,E,S,Y,F,P,O,j,K,R,H=new Date,W=this._daylightSavingAdjust(new Date(H.getFullYear(),H.getMonth(),H.getDate())),L=this._get(e,"isRTL"),U=this._get(e,"showButtonPanel"),B=this._get(e,"hideIfNoPrevNext"),z=this._get(e,"navigationAsDateFormat"),q=this._getNumberOfMonths(e),G=this._get(e,"showCurrentAtPos"),J=this._get(e,"stepMonths"),Q=1!==q[0]||1!==q[1],V=this._daylightSavingAdjust(e.currentDay?new Date(e.currentYear,e.currentMonth,e.currentDay):new Date(9999,9,9)),$=this._getMinMaxDate(e,"min"),X=this._getMinMaxDate(e,"max"),Z=e.drawMonth-G,et=e.drawYear;if(0>Z&&(Z+=12,et--),X)for(t=this._daylightSavingAdjust(new Date(X.getFullYear(),X.getMonth()-q[0]*q[1]+1,X.getDate())),t=$&&$>t?$:t;this._daylightSavingAdjust(new Date(et,Z,1))>t;)Z--,0>Z&&(Z=11,et--);for(e.drawMonth=Z,e.drawYear=et,i=this._get(e,"prevText"),i=z?this.formatDate(i,this._daylightSavingAdjust(new Date(et,Z-J,1)),this._getFormatConfig(e)):i,a=this._canAdjustMonth(e,-1,et,Z)?"<a class='ui-datepicker-prev ui-corner-all' data-handler='prev' data-event='click' title='"+i+"'><span class='ui-icon ui-icon-circle-triangle-"+(L?"e":"w")+"'>"+i+"</span></a>":B?"":"<a class='ui-datepicker-prev ui-corner-all ui-state-disabled' title='"+i+"'><span class='ui-icon ui-icon-circle-triangle-"+(L?"e":"w")+"'>"+i+"</span></a>",s=this._get(e,"nextText"),s=z?this.formatDate(s,this._daylightSavingAdjust(new Date(et,Z+J,1)),this._getFormatConfig(e)):s,n=this._canAdjustMonth(e,1,et,Z)?"<a class='ui-datepicker-next ui-corner-all' data-handler='next' data-event='click' title='"+s+"'><span class='ui-icon ui-icon-circle-triangle-"+(L?"w":"e")+"'>"+s+"</span></a>":B?"":"<a class='ui-datepicker-next ui-corner-all ui-state-disabled' title='"+s+"'><span class='ui-icon ui-icon-circle-triangle-"+(L?"w":"e")+"'>"+s+"</span></a>",r=this._get(e,"currentText"),o=this._get(e,"gotoCurrent")&&e.currentDay?V:W,r=z?this.formatDate(r,o,this._getFormatConfig(e)):r,u=e.inline?"":"<button type='button' class='ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all' data-handler='hide' data-event='click'>"+this._get(e,"closeText")+"</button>",c=U?"<div class='ui-datepicker-buttonpane ui-widget-content'>"+(L?u:"")+(this._isInRange(e,o)?"<button type='button' class='ui-datepicker-current ui-state-default ui-priority-secondary ui-corner-all' data-handler='today' data-event='click'>"+r+"</button>":"")+(L?"":u)+"</div>":"",h=parseInt(this._get(e,"firstDay"),10),h=isNaN(h)?0:h,l=this._get(e,"showWeek"),d=this._get(e,"dayNames"),p=this._get(e,"dayNamesMin"),g=this._get(e,"monthNames"),m=this._get(e,"monthNamesShort"),f=this._get(e,"beforeShowDay"),_=this._get(e,"showOtherMonths"),v=this._get(e,"selectOtherMonths"),k=this._getDefaultDate(e),y="",D=0;q[0]>D;D++){for(w="",this.maxRows=4,M=0;q[1]>M;M++){if(C=this._daylightSavingAdjust(new Date(et,Z,e.selectedDay)),x=" ui-corner-all",I="",Q){if(I+="<div class='ui-datepicker-group",q[1]>1)switch(M){case 0:I+=" ui-datepicker-group-first",x=" ui-corner-"+(L?"right":"left");break;case q[1]-1:I+=" ui-datepicker-group-last",x=" ui-corner-"+(L?"left":"right");break;default:I+=" ui-datepicker-group-middle",x=""}I+="'>"}for(I+="<div class='ui-datepicker-header ui-widget-header ui-helper-clearfix"+x+"'>"+(/all|left/.test(x)&&0===D?L?n:a:"")+(/all|right/.test(x)&&0===D?L?a:n:"")+this._generateMonthYearHeader(e,Z,et,$,X,D>0||M>0,g,m)+"</div><table class='ui-datepicker-calendar'><thead>"+"<tr>",N=l?"<th class='ui-datepicker-week-col'>"+this._get(e,"weekHeader")+"</th>":"",b=0;7>b;b++)T=(b+h)%7,N+="<th"+((b+h+6)%7>=5?" class='ui-datepicker-week-end'":"")+">"+"<span title='"+d[T]+"'>"+p[T]+"</span></th>";for(I+=N+"</tr></thead><tbody>",A=this._getDaysInMonth(et,Z),et===e.selectedYear&&Z===e.selectedMonth&&(e.selectedDay=Math.min(e.selectedDay,A)),E=(this._getFirstDayOfMonth(et,Z)-h+7)%7,S=Math.ceil((E+A)/7),Y=Q?this.maxRows>S?this.maxRows:S:S,this.maxRows=Y,F=this._daylightSavingAdjust(new Date(et,Z,1-E)),P=0;Y>P;P++){for(I+="<tr>",O=l?"<td class='ui-datepicker-week-col'>"+this._get(e,"calculateWeek")(F)+"</td>":"",b=0;7>b;b++)j=f?f.apply(e.input?e.input[0]:null,[F]):[!0,""],K=F.getMonth()!==Z,R=K&&!v||!j[0]||$&&$>F||X&&F>X,O+="<td class='"+((b+h+6)%7>=5?" ui-datepicker-week-end":"")+(K?" ui-datepicker-other-month":"")+(F.getTime()===C.getTime()&&Z===e.selectedMonth&&e._keyEvent||k.getTime()===F.getTime()&&k.getTime()===C.getTime()?" "+this._dayOverClass:"")+(R?" "+this._unselectableClass+" ui-state-disabled":"")+(K&&!_?"":" "+j[1]+(F.getTime()===V.getTime()?" "+this._currentClass:"")+(F.getTime()===W.getTime()?" ui-datepicker-today":""))+"'"+(K&&!_||!j[2]?"":" title='"+j[2].replace(/'/g,"'")+"'")+(R?"":" data-handler='selectDay' data-event='click' data-month='"+F.getMonth()+"' data-year='"+F.getFullYear()+"'")+">"+(K&&!_?" ":R?"<span class='ui-state-default'>"+F.getDate()+"</span>":"<a class='ui-state-default"+(F.getTime()===W.getTime()?" ui-state-highlight":"")+(F.getTime()===V.getTime()?" ui-state-active":"")+(K?" ui-priority-secondary":"")+"' href='#'>"+F.getDate()+"</a>")+"</td>",F.setDate(F.getDate()+1),F=this._daylightSavingAdjust(F);I+=O+"</tr>"}Z++,Z>11&&(Z=0,et++),I+="</tbody></table>"+(Q?"</div>"+(q[0]>0&&M===q[1]-1?"<div class='ui-datepicker-row-break'></div>":""):""),w+=I}y+=w}return y+=c,e._keyEvent=!1,y},_generateMonthYearHeader:function(e,t,i,a,s,n,r,o){var u,c,h,l,d,p,g,m,f=this._get(e,"changeMonth"),_=this._get(e,"changeYear"),v=this._get(e,"showMonthAfterYear"),k="<div class='ui-datepicker-title'>",y="";if(n||!f)y+="<span class='ui-datepicker-month'>"+r[t]+"</span>";else{for(u=a&&a.getFullYear()===i,c=s&&s.getFullYear()===i,y+="<select class='ui-datepicker-month' data-handler='selectMonth' data-event='change'>",h=0;12>h;h++)(!u||h>=a.getMonth())&&(!c||s.getMonth()>=h)&&(y+="<option value='"+h+"'"+(h===t?" selected='selected'":"")+">"+o[h]+"</option>");y+="</select>"}if(v||(k+=y+(!n&&f&&_?"":" ")),!e.yearshtml)if(e.yearshtml="",n||!_)k+="<span class='ui-datepicker-year'>"+i+"</span>";else{for(l=this._get(e,"yearRange").split(":"),d=(new Date).getFullYear(),p=function(e){var t=e.match(/c[+\-].*/)?i+parseInt(e.substring(1),10):e.match(/[+\-].*/)?d+parseInt(e,10):parseInt(e,10);
-return isNaN(t)?d:t},g=p(l[0]),m=Math.max(g,p(l[1]||"")),g=a?Math.max(g,a.getFullYear()):g,m=s?Math.min(m,s.getFullYear()):m,e.yearshtml+="<select class='ui-datepicker-year' data-handler='selectYear' data-event='change'>";m>=g;g++)e.yearshtml+="<option value='"+g+"'"+(g===i?" selected='selected'":"")+">"+g+"</option>";e.yearshtml+="</select>",k+=e.yearshtml,e.yearshtml=null}return k+=this._get(e,"yearSuffix"),v&&(k+=(!n&&f&&_?"":" ")+y),k+="</div>"},_adjustInstDate:function(e,t,i){var a=e.drawYear+("Y"===i?t:0),s=e.drawMonth+("M"===i?t:0),n=Math.min(e.selectedDay,this._getDaysInMonth(a,s))+("D"===i?t:0),r=this._restrictMinMax(e,this._daylightSavingAdjust(new Date(a,s,n)));e.selectedDay=r.getDate(),e.drawMonth=e.selectedMonth=r.getMonth(),e.drawYear=e.selectedYear=r.getFullYear(),("M"===i||"Y"===i)&&this._notifyChange(e)},_restrictMinMax:function(e,t){var i=this._getMinMaxDate(e,"min"),a=this._getMinMaxDate(e,"max"),s=i&&i>t?i:t;return a&&s>a?a:s},_notifyChange:function(e){var t=this._get(e,"onChangeMonthYear");t&&t.apply(e.input?e.input[0]:null,[e.selectedYear,e.selectedMonth+1,e])},_getNumberOfMonths:function(e){var t=this._get(e,"numberOfMonths");return null==t?[1,1]:"number"==typeof t?[1,t]:t},_getMinMaxDate:function(e,t){return this._determineDate(e,this._get(e,t+"Date"),null)},_getDaysInMonth:function(e,t){return 32-this._daylightSavingAdjust(new Date(e,t,32)).getDate()},_getFirstDayOfMonth:function(e,t){return new Date(e,t,1).getDay()},_canAdjustMonth:function(e,t,i,a){var s=this._getNumberOfMonths(e),n=this._daylightSavingAdjust(new Date(i,a+(0>t?t:s[0]*s[1]),1));return 0>t&&n.setDate(this._getDaysInMonth(n.getFullYear(),n.getMonth())),this._isInRange(e,n)},_isInRange:function(e,t){var i,a,s=this._getMinMaxDate(e,"min"),n=this._getMinMaxDate(e,"max"),r=null,o=null,u=this._get(e,"yearRange");return u&&(i=u.split(":"),a=(new Date).getFullYear(),r=parseInt(i[0],10),o=parseInt(i[1],10),i[0].match(/[+\-].*/)&&(r+=a),i[1].match(/[+\-].*/)&&(o+=a)),(!s||t.getTime()>=s.getTime())&&(!n||t.getTime()<=n.getTime())&&(!r||t.getFullYear()>=r)&&(!o||o>=t.getFullYear())},_getFormatConfig:function(e){var t=this._get(e,"shortYearCutoff");return t="string"!=typeof t?t:(new Date).getFullYear()%100+parseInt(t,10),{shortYearCutoff:t,dayNamesShort:this._get(e,"dayNamesShort"),dayNames:this._get(e,"dayNames"),monthNamesShort:this._get(e,"monthNamesShort"),monthNames:this._get(e,"monthNames")}},_formatDate:function(e,t,i,a){t||(e.currentDay=e.selectedDay,e.currentMonth=e.selectedMonth,e.currentYear=e.selectedYear);var s=t?"object"==typeof t?t:this._daylightSavingAdjust(new Date(a,i,t)):this._daylightSavingAdjust(new Date(e.currentYear,e.currentMonth,e.currentDay));return this.formatDate(this._get(e,"dateFormat"),s,this._getFormatConfig(e))}}),e.fn.datepicker=function(t){if(!this.length)return this;e.datepicker.initialized||(e(document).mousedown(e.datepicker._checkExternalClick),e.datepicker.initialized=!0),0===e("#"+e.datepicker._mainDivId).length&&e("body").append(e.datepicker.dpDiv);var i=Array.prototype.slice.call(arguments,1);return"string"!=typeof t||"isDisabled"!==t&&"getDate"!==t&&"widget"!==t?"option"===t&&2===arguments.length&&"string"==typeof arguments[1]?e.datepicker["_"+t+"Datepicker"].apply(e.datepicker,[this[0]].concat(i)):this.each(function(){"string"==typeof t?e.datepicker["_"+t+"Datepicker"].apply(e.datepicker,[this].concat(i)):e.datepicker._attachDatepicker(this,t)}):e.datepicker["_"+t+"Datepicker"].apply(e.datepicker,[this[0]].concat(i))},e.datepicker=new i,e.datepicker.initialized=!1,e.datepicker.uuid=(new Date).getTime(),e.datepicker.version="1.10.4"})(jQuery);(function(e){var t={buttons:!0,height:!0,maxHeight:!0,maxWidth:!0,minHeight:!0,minWidth:!0,width:!0},i={maxHeight:!0,maxWidth:!0,minHeight:!0,minWidth:!0};e.widget("ui.dialog",{version:"1.10.4",options:{appendTo:"body",autoOpen:!0,buttons:[],closeOnEscape:!0,closeText:"close",dialogClass:"",draggable:!0,hide:null,height:"auto",maxHeight:null,maxWidth:null,minHeight:150,minWidth:150,modal:!1,position:{my:"center",at:"center",of:window,collision:"fit",using:function(t){var i=e(this).css(t).offset().top;0>i&&e(this).css("top",t.top-i)}},resizable:!0,show:null,title:null,width:300,beforeClose:null,close:null,drag:null,dragStart:null,dragStop:null,focus:null,open:null,resize:null,resizeStart:null,resizeStop:null},_create:function(){this.originalCss={display:this.element[0].style.display,width:this.element[0].style.width,minHeight:this.element[0].style.minHeight,maxHeight:this.element[0].style.maxHeight,height:this.element[0].style.height},this.originalPosition={parent:this.element.parent(),index:this.element.parent().children().index(this.element)},this.originalTitle=this.element.attr("title"),this.options.title=this.options.title||this.originalTitle,this._createWrapper(),this.element.show().removeAttr("title").addClass("ui-dialog-content ui-widget-content").appendTo(this.uiDialog),this._createTitlebar(),this._createButtonPane(),this.options.draggable&&e.fn.draggable&&this._makeDraggable(),this.options.resizable&&e.fn.resizable&&this._makeResizable(),this._isOpen=!1},_init:function(){this.options.autoOpen&&this.open()},_appendTo:function(){var t=this.options.appendTo;return t&&(t.jquery||t.nodeType)?e(t):this.document.find(t||"body").eq(0)},_destroy:function(){var e,t=this.originalPosition;this._destroyOverlay(),this.element.removeUniqueId().removeClass("ui-dialog-content ui-widget-content").css(this.originalCss).detach(),this.uiDialog.stop(!0,!0).remove(),this.originalTitle&&this.element.attr("title",this.originalTitle),e=t.parent.children().eq(t.index),e.length&&e[0]!==this.element[0]?e.before(this.element):t.parent.append(this.element)},widget:function(){return this.uiDialog},disable:e.noop,enable:e.noop,close:function(t){var i,a=this;if(this._isOpen&&this._trigger("beforeClose",t)!==!1){if(this._isOpen=!1,this._destroyOverlay(),!this.opener.filter(":focusable").focus().length)try{i=this.document[0].activeElement,i&&"body"!==i.nodeName.toLowerCase()&&e(i).blur()}catch(s){}this._hide(this.uiDialog,this.options.hide,function(){a._trigger("close",t)})}},isOpen:function(){return this._isOpen},moveToTop:function(){this._moveToTop()},_moveToTop:function(e,t){var i=!!this.uiDialog.nextAll(":visible").insertBefore(this.uiDialog).length;return i&&!t&&this._trigger("focus",e),i},open:function(){var t=this;return this._isOpen?(this._moveToTop()&&this._focusTabbable(),undefined):(this._isOpen=!0,this.opener=e(this.document[0].activeElement),this._size(),this._position(),this._createOverlay(),this._moveToTop(null,!0),this._show(this.uiDialog,this.options.show,function(){t._focusTabbable(),t._trigger("focus")}),this._trigger("open"),undefined)},_focusTabbable:function(){var e=this.element.find("[autofocus]");e.length||(e=this.element.find(":tabbable")),e.length||(e=this.uiDialogButtonPane.find(":tabbable")),e.length||(e=this.uiDialogTitlebarClose.filter(":tabbable")),e.length||(e=this.uiDialog),e.eq(0).focus()},_keepFocus:function(t){function i(){var t=this.document[0].activeElement,i=this.uiDialog[0]===t||e.contains(this.uiDialog[0],t);i||this._focusTabbable()}t.preventDefault(),i.call(this),this._delay(i)},_createWrapper:function(){this.uiDialog=e("<div>").addClass("ui-dialog ui-widget ui-widget-content ui-corner-all ui-front "+this.options.dialogClass).hide().attr({tabIndex:-1,role:"dialog"}).appendTo(this._appendTo()),this._on(this.uiDialog,{keydown:function(t){if(this.options.closeOnEscape&&!t.isDefaultPrevented()&&t.keyCode&&t.keyCode===e.ui.keyCode.ESCAPE)return t.preventDefault(),this.close(t),undefined;if(t.keyCode===e.ui.keyCode.TAB){var i=this.uiDialog.find(":tabbable"),a=i.filter(":first"),s=i.filter(":last");t.target!==s[0]&&t.target!==this.uiDialog[0]||t.shiftKey?t.target!==a[0]&&t.target!==this.uiDialog[0]||!t.shiftKey||(s.focus(1),t.preventDefault()):(a.focus(1),t.preventDefault())}},mousedown:function(e){this._moveToTop(e)&&this._focusTabbable()}}),this.element.find("[aria-describedby]").length||this.uiDialog.attr({"aria-describedby":this.element.uniqueId().attr("id")})},_createTitlebar:function(){var t;this.uiDialogTitlebar=e("<div>").addClass("ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix").prependTo(this.uiDialog),this._on(this.uiDialogTitlebar,{mousedown:function(t){e(t.target).closest(".ui-dialog-titlebar-close")||this.uiDialog.focus()}}),this.uiDialogTitlebarClose=e("<button type='button'></button>").button({label:this.options.closeText,icons:{primary:"ui-icon-closethick"},text:!1}).addClass("ui-dialog-titlebar-close").appendTo(this.uiDialogTitlebar),this._on(this.uiDialogTitlebarClose,{click:function(e){e.preventDefault(),this.close(e)}}),t=e("<span>").uniqueId().addClass("ui-dialog-title").prependTo(this.uiDialogTitlebar),this._title(t),this.uiDialog.attr({"aria-labelledby":t.attr("id")})},_title:function(e){this.options.title||e.html(" "),e.text(this.options.title)},_createButtonPane:function(){this.uiDialogButtonPane=e("<div>").addClass("ui-dialog-buttonpane ui-widget-content ui-helper-clearfix"),this.uiButtonSet=e("<div>").addClass("ui-dialog-buttonset").appendTo(this.uiDialogButtonPane),this._createButtons()},_createButtons:function(){var t=this,i=this.options.buttons;return this.uiDialogButtonPane.remove(),this.uiButtonSet.empty(),e.isEmptyObject(i)||e.isArray(i)&&!i.length?(this.uiDialog.removeClass("ui-dialog-buttons"),undefined):(e.each(i,function(i,a){var s,n;a=e.isFunction(a)?{click:a,text:i}:a,a=e.extend({type:"button"},a),s=a.click,a.click=function(){s.apply(t.element[0],arguments)},n={icons:a.icons,text:a.showText},delete a.icons,delete a.showText,e("<button></button>",a).button(n).appendTo(t.uiButtonSet)}),this.uiDialog.addClass("ui-dialog-buttons"),this.uiDialogButtonPane.appendTo(this.uiDialog),undefined)},_makeDraggable:function(){function t(e){return{position:e.position,offset:e.offset}}var i=this,a=this.options;this.uiDialog.draggable({cancel:".ui-dialog-content, .ui-dialog-titlebar-close",handle:".ui-dialog-titlebar",containment:"document",start:function(a,s){e(this).addClass("ui-dialog-dragging"),i._blockFrames(),i._trigger("dragStart",a,t(s))},drag:function(e,a){i._trigger("drag",e,t(a))},stop:function(s,n){a.position=[n.position.left-i.document.scrollLeft(),n.position.top-i.document.scrollTop()],e(this).removeClass("ui-dialog-dragging"),i._unblockFrames(),i._trigger("dragStop",s,t(n))}})},_makeResizable:function(){function t(e){return{originalPosition:e.originalPosition,originalSize:e.originalSize,position:e.position,size:e.size}}var i=this,a=this.options,s=a.resizable,n=this.uiDialog.css("position"),r="string"==typeof s?s:"n,e,s,w,se,sw,ne,nw";this.uiDialog.resizable({cancel:".ui-dialog-content",containment:"document",alsoResize:this.element,maxWidth:a.maxWidth,maxHeight:a.maxHeight,minWidth:a.minWidth,minHeight:this._minHeight(),handles:r,start:function(a,s){e(this).addClass("ui-dialog-resizing"),i._blockFrames(),i._trigger("resizeStart",a,t(s))},resize:function(e,a){i._trigger("resize",e,t(a))},stop:function(s,n){a.height=e(this).height(),a.width=e(this).width(),e(this).removeClass("ui-dialog-resizing"),i._unblockFrames(),i._trigger("resizeStop",s,t(n))}}).css("position",n)},_minHeight:function(){var e=this.options;return"auto"===e.height?e.minHeight:Math.min(e.minHeight,e.height)},_position:function(){var e=this.uiDialog.is(":visible");e||this.uiDialog.show(),this.uiDialog.position(this.options.position),e||this.uiDialog.hide()},_setOptions:function(a){var s=this,n=!1,r={};e.each(a,function(e,a){s._setOption(e,a),e in t&&(n=!0),e in i&&(r[e]=a)}),n&&(this._size(),this._position()),this.uiDialog.is(":data(ui-resizable)")&&this.uiDialog.resizable("option",r)},_setOption:function(e,t){var i,a,s=this.uiDialog;"dialogClass"===e&&s.removeClass(this.options.dialogClass).addClass(t),"disabled"!==e&&(this._super(e,t),"appendTo"===e&&this.uiDialog.appendTo(this._appendTo()),"buttons"===e&&this._createButtons(),"closeText"===e&&this.uiDialogTitlebarClose.button({label:""+t}),"draggable"===e&&(i=s.is(":data(ui-draggable)"),i&&!t&&s.draggable("destroy"),!i&&t&&this._makeDraggable()),"position"===e&&this._position(),"resizable"===e&&(a=s.is(":data(ui-resizable)"),a&&!t&&s.resizable("destroy"),a&&"string"==typeof t&&s.resizable("option","handles",t),a||t===!1||this._makeResizable()),"title"===e&&this._title(this.uiDialogTitlebar.find(".ui-dialog-title")))},_size:function(){var e,t,i,a=this.options;this.element.show().css({width:"auto",minHeight:0,maxHeight:"none",height:0}),a.minWidth>a.width&&(a.width=a.minWidth),e=this.uiDialog.css({height:"auto",width:a.width}).outerHeight(),t=Math.max(0,a.minHeight-e),i="number"==typeof a.maxHeight?Math.max(0,a.maxHeight-e):"none","auto"===a.height?this.element.css({minHeight:t,maxHeight:i,height:"auto"}):this.element.height(Math.max(0,a.height-e)),this.uiDialog.is(":data(ui-resizable)")&&this.uiDialog.resizable("option","minHeight",this._minHeight())},_blockFrames:function(){this.iframeBlocks=this.document.find("iframe").map(function(){var t=e(this);return e("<div>").css({position:"absolute",width:t.outerWidth(),height:t.outerHeight()}).appendTo(t.parent()).offset(t.offset())[0]})},_unblockFrames:function(){this.iframeBlocks&&(this.iframeBlocks.remove(),delete this.iframeBlocks)},_allowInteraction:function(t){return e(t.target).closest(".ui-dialog").length?!0:!!e(t.target).closest(".ui-datepicker").length},_createOverlay:function(){if(this.options.modal){var t=this,i=this.widgetFullName;e.ui.dialog.overlayInstances||this._delay(function(){e.ui.dialog.overlayInstances&&this.document.bind("focusin.dialog",function(a){t._allowInteraction(a)||(a.preventDefault(),e(".ui-dialog:visible:last .ui-dialog-content").data(i)._focusTabbable())})}),this.overlay=e("<div>").addClass("ui-widget-overlay ui-front").appendTo(this._appendTo()),this._on(this.overlay,{mousedown:"_keepFocus"}),e.ui.dialog.overlayInstances++}},_destroyOverlay:function(){this.options.modal&&this.overlay&&(e.ui.dialog.overlayInstances--,e.ui.dialog.overlayInstances||this.document.unbind("focusin.dialog"),this.overlay.remove(),this.overlay=null)}}),e.ui.dialog.overlayInstances=0,e.uiBackCompat!==!1&&e.widget("ui.dialog",e.ui.dialog,{_position:function(){var t,i=this.options.position,a=[],s=[0,0];i?(("string"==typeof i||"object"==typeof i&&"0"in i)&&(a=i.split?i.split(" "):[i[0],i[1]],1===a.length&&(a[1]=a[0]),e.each(["left","top"],function(e,t){+a[e]===a[e]&&(s[e]=a[e],a[e]=t)}),i={my:a[0]+(0>s[0]?s[0]:"+"+s[0])+" "+a[1]+(0>s[1]?s[1]:"+"+s[1]),at:a.join(" ")}),i=e.extend({},e.ui.dialog.prototype.options.position,i)):i=e.ui.dialog.prototype.options.position,t=this.uiDialog.is(":visible"),t||this.uiDialog.show(),this.uiDialog.position(i),t||this.uiDialog.hide()}})})(jQuery);(function(t){t.widget("ui.menu",{version:"1.10.4",defaultElement:"<ul>",delay:300,options:{icons:{submenu:"ui-icon-carat-1-e"},menus:"ul",position:{my:"left top",at:"right top"},role:"menu",blur:null,focus:null,select:null},_create:function(){this.activeMenu=this.element,this.mouseHandled=!1,this.element.uniqueId().addClass("ui-menu ui-widget ui-widget-content ui-corner-all").toggleClass("ui-menu-icons",!!this.element.find(".ui-icon").length).attr({role:this.options.role,tabIndex:0}).bind("click"+this.eventNamespace,t.proxy(function(t){this.options.disabled&&t.preventDefault()},this)),this.options.disabled&&this.element.addClass("ui-state-disabled").attr("aria-disabled","true"),this._on({"mousedown .ui-menu-item > a":function(t){t.preventDefault()},"click .ui-state-disabled > a":function(t){t.preventDefault()},"click .ui-menu-item:has(a)":function(e){var i=t(e.target).closest(".ui-menu-item");!this.mouseHandled&&i.not(".ui-state-disabled").length&&(this.select(e),e.isPropagationStopped()||(this.mouseHandled=!0),i.has(".ui-menu").length?this.expand(e):!this.element.is(":focus")&&t(this.document[0].activeElement).closest(".ui-menu").length&&(this.element.trigger("focus",[!0]),this.active&&1===this.active.parents(".ui-menu").length&&clearTimeout(this.timer)))},"mouseenter .ui-menu-item":function(e){var i=t(e.currentTarget);i.siblings().children(".ui-state-active").removeClass("ui-state-active"),this.focus(e,i)},mouseleave:"collapseAll","mouseleave .ui-menu":"collapseAll",focus:function(t,e){var i=this.active||this.element.children(".ui-menu-item").eq(0);e||this.focus(t,i)},blur:function(e){this._delay(function(){t.contains(this.element[0],this.document[0].activeElement)||this.collapseAll(e)})},keydown:"_keydown"}),this.refresh(),this._on(this.document,{click:function(e){t(e.target).closest(".ui-menu").length||this.collapseAll(e),this.mouseHandled=!1}})},_destroy:function(){this.element.removeAttr("aria-activedescendant").find(".ui-menu").addBack().removeClass("ui-menu ui-widget ui-widget-content ui-corner-all ui-menu-icons").removeAttr("role").removeAttr("tabIndex").removeAttr("aria-labelledby").removeAttr("aria-expanded").removeAttr("aria-hidden").removeAttr("aria-disabled").removeUniqueId().show(),this.element.find(".ui-menu-item").removeClass("ui-menu-item").removeAttr("role").removeAttr("aria-disabled").children("a").removeUniqueId().removeClass("ui-corner-all ui-state-hover").removeAttr("tabIndex").removeAttr("role").removeAttr("aria-haspopup").children().each(function(){var e=t(this);e.data("ui-menu-submenu-carat")&&e.remove()}),this.element.find(".ui-menu-divider").removeClass("ui-menu-divider ui-widget-content")},_keydown:function(e){function i(t){return t.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}var s,n,a,o,r,l=!0;switch(e.keyCode){case t.ui.keyCode.PAGE_UP:this.previousPage(e);break;case t.ui.keyCode.PAGE_DOWN:this.nextPage(e);break;case t.ui.keyCode.HOME:this._move("first","first",e);break;case t.ui.keyCode.END:this._move("last","last",e);break;case t.ui.keyCode.UP:this.previous(e);break;case t.ui.keyCode.DOWN:this.next(e);break;case t.ui.keyCode.LEFT:this.collapse(e);break;case t.ui.keyCode.RIGHT:this.active&&!this.active.is(".ui-state-disabled")&&this.expand(e);break;case t.ui.keyCode.ENTER:case t.ui.keyCode.SPACE:this._activate(e);break;case t.ui.keyCode.ESCAPE:this.collapse(e);break;default:l=!1,n=this.previousFilter||"",a=String.fromCharCode(e.keyCode),o=!1,clearTimeout(this.filterTimer),a===n?o=!0:a=n+a,r=RegExp("^"+i(a),"i"),s=this.activeMenu.children(".ui-menu-item").filter(function(){return r.test(t(this).children("a").text())}),s=o&&-1!==s.index(this.active.next())?this.active.nextAll(".ui-menu-item"):s,s.length||(a=String.fromCharCode(e.keyCode),r=RegExp("^"+i(a),"i"),s=this.activeMenu.children(".ui-menu-item").filter(function(){return r.test(t(this).children("a").text())})),s.length?(this.focus(e,s),s.length>1?(this.previousFilter=a,this.filterTimer=this._delay(function(){delete this.previousFilter},1e3)):delete this.previousFilter):delete this.previousFilter}l&&e.preventDefault()},_activate:function(t){this.active.is(".ui-state-disabled")||(this.active.children("a[aria-haspopup='true']").length?this.expand(t):this.select(t))},refresh:function(){var e,i=this.options.icons.submenu,s=this.element.find(this.options.menus);this.element.toggleClass("ui-menu-icons",!!this.element.find(".ui-icon").length),s.filter(":not(.ui-menu)").addClass("ui-menu ui-widget ui-widget-content ui-corner-all").hide().attr({role:this.options.role,"aria-hidden":"true","aria-expanded":"false"}).each(function(){var e=t(this),s=e.prev("a"),n=t("<span>").addClass("ui-menu-icon ui-icon "+i).data("ui-menu-submenu-carat",!0);s.attr("aria-haspopup","true").prepend(n),e.attr("aria-labelledby",s.attr("id"))}),e=s.add(this.element),e.children(":not(.ui-menu-item):has(a)").addClass("ui-menu-item").attr("role","presentation").children("a").uniqueId().addClass("ui-corner-all").attr({tabIndex:-1,role:this._itemRole()}),e.children(":not(.ui-menu-item)").each(function(){var e=t(this);/[^\-\u2014\u2013\s]/.test(e.text())||e.addClass("ui-widget-content ui-menu-divider")}),e.children(".ui-state-disabled").attr("aria-disabled","true"),this.active&&!t.contains(this.element[0],this.active[0])&&this.blur()},_itemRole:function(){return{menu:"menuitem",listbox:"option"}[this.options.role]},_setOption:function(t,e){"icons"===t&&this.element.find(".ui-menu-icon").removeClass(this.options.icons.submenu).addClass(e.submenu),this._super(t,e)},focus:function(t,e){var i,s;this.blur(t,t&&"focus"===t.type),this._scrollIntoView(e),this.active=e.first(),s=this.active.children("a").addClass("ui-state-focus"),this.options.role&&this.element.attr("aria-activedescendant",s.attr("id")),this.active.parent().closest(".ui-menu-item").children("a:first").addClass("ui-state-active"),t&&"keydown"===t.type?this._close():this.timer=this._delay(function(){this._close()},this.delay),i=e.children(".ui-menu"),i.length&&t&&/^mouse/.test(t.type)&&this._startOpening(i),this.activeMenu=e.parent(),this._trigger("focus",t,{item:e})},_scrollIntoView:function(e){var i,s,n,a,o,r;this._hasScroll()&&(i=parseFloat(t.css(this.activeMenu[0],"borderTopWidth"))||0,s=parseFloat(t.css(this.activeMenu[0],"paddingTop"))||0,n=e.offset().top-this.activeMenu.offset().top-i-s,a=this.activeMenu.scrollTop(),o=this.activeMenu.height(),r=e.height(),0>n?this.activeMenu.scrollTop(a+n):n+r>o&&this.activeMenu.scrollTop(a+n-o+r))},blur:function(t,e){e||clearTimeout(this.timer),this.active&&(this.active.children("a").removeClass("ui-state-focus"),this.active=null,this._trigger("blur",t,{item:this.active}))},_startOpening:function(t){clearTimeout(this.timer),"true"===t.attr("aria-hidden")&&(this.timer=this._delay(function(){this._close(),this._open(t)},this.delay))},_open:function(e){var i=t.extend({of:this.active},this.options.position);clearTimeout(this.timer),this.element.find(".ui-menu").not(e.parents(".ui-menu")).hide().attr("aria-hidden","true"),e.show().removeAttr("aria-hidden").attr("aria-expanded","true").position(i)},collapseAll:function(e,i){clearTimeout(this.timer),this.timer=this._delay(function(){var s=i?this.element:t(e&&e.target).closest(this.element.find(".ui-menu"));s.length||(s=this.element),this._close(s),this.blur(e),this.activeMenu=s},this.delay)},_close:function(t){t||(t=this.active?this.active.parent():this.element),t.find(".ui-menu").hide().attr("aria-hidden","true").attr("aria-expanded","false").end().find("a.ui-state-active").removeClass("ui-state-active")},collapse:function(t){var e=this.active&&this.active.parent().closest(".ui-menu-item",this.element);e&&e.length&&(this._close(),this.focus(t,e))},expand:function(t){var e=this.active&&this.active.children(".ui-menu ").children(".ui-menu-item").first();e&&e.length&&(this._open(e.parent()),this._delay(function(){this.focus(t,e)}))},next:function(t){this._move("next","first",t)},previous:function(t){this._move("prev","last",t)},isFirstItem:function(){return this.active&&!this.active.prevAll(".ui-menu-item").length},isLastItem:function(){return this.active&&!this.active.nextAll(".ui-menu-item").length},_move:function(t,e,i){var s;this.active&&(s="first"===t||"last"===t?this.active["first"===t?"prevAll":"nextAll"](".ui-menu-item").eq(-1):this.active[t+"All"](".ui-menu-item").eq(0)),s&&s.length&&this.active||(s=this.activeMenu.children(".ui-menu-item")[e]()),this.focus(i,s)},nextPage:function(e){var i,s,n;return this.active?(this.isLastItem()||(this._hasScroll()?(s=this.active.offset().top,n=this.element.height(),this.active.nextAll(".ui-menu-item").each(function(){return i=t(this),0>i.offset().top-s-n}),this.focus(e,i)):this.focus(e,this.activeMenu.children(".ui-menu-item")[this.active?"last":"first"]())),undefined):(this.next(e),undefined)},previousPage:function(e){var i,s,n;return this.active?(this.isFirstItem()||(this._hasScroll()?(s=this.active.offset().top,n=this.element.height(),this.active.prevAll(".ui-menu-item").each(function(){return i=t(this),i.offset().top-s+n>0}),this.focus(e,i)):this.focus(e,this.activeMenu.children(".ui-menu-item").first())),undefined):(this.next(e),undefined)},_hasScroll:function(){return this.element.outerHeight()<this.element.prop("scrollHeight")},select:function(e){this.active=this.active||t(e.target).closest(".ui-menu-item");var i={item:this.active};this.active.has(".ui-menu").length||this.collapseAll(e,!0),this._trigger("select",e,i)}})})(jQuery);(function(t,e){t.widget("ui.progressbar",{version:"1.10.4",options:{max:100,value:0,change:null,complete:null},min:0,_create:function(){this.oldValue=this.options.value=this._constrainedValue(),this.element.addClass("ui-progressbar ui-widget ui-widget-content ui-corner-all").attr({role:"progressbar","aria-valuemin":this.min}),this.valueDiv=t("<div class='ui-progressbar-value ui-widget-header ui-corner-left'></div>").appendTo(this.element),this._refreshValue()},_destroy:function(){this.element.removeClass("ui-progressbar ui-widget ui-widget-content ui-corner-all").removeAttr("role").removeAttr("aria-valuemin").removeAttr("aria-valuemax").removeAttr("aria-valuenow"),this.valueDiv.remove()},value:function(t){return t===e?this.options.value:(this.options.value=this._constrainedValue(t),this._refreshValue(),e)},_constrainedValue:function(t){return t===e&&(t=this.options.value),this.indeterminate=t===!1,"number"!=typeof t&&(t=0),this.indeterminate?!1:Math.min(this.options.max,Math.max(this.min,t))},_setOptions:function(t){var e=t.value;delete t.value,this._super(t),this.options.value=this._constrainedValue(e),this._refreshValue()},_setOption:function(t,e){"max"===t&&(e=Math.max(this.min,e)),this._super(t,e)},_percentage:function(){return this.indeterminate?100:100*(this.options.value-this.min)/(this.options.max-this.min)},_refreshValue:function(){var e=this.options.value,i=this._percentage();this.valueDiv.toggle(this.indeterminate||e>this.min).toggleClass("ui-corner-right",e===this.options.max).width(i.toFixed(0)+"%"),this.element.toggleClass("ui-progressbar-indeterminate",this.indeterminate),this.indeterminate?(this.element.removeAttr("aria-valuenow"),this.overlayDiv||(this.overlayDiv=t("<div class='ui-progressbar-overlay'></div>").appendTo(this.valueDiv))):(this.element.attr({"aria-valuemax":this.options.max,"aria-valuenow":e}),this.overlayDiv&&(this.overlayDiv.remove(),this.overlayDiv=null)),this.oldValue!==e&&(this.oldValue=e,this._trigger("change")),e===this.options.max&&this._trigger("complete")}})})(jQuery);(function(t){var e=5;t.widget("ui.slider",t.ui.mouse,{version:"1.10.4",widgetEventPrefix:"slide",options:{animate:!1,distance:0,max:100,min:0,orientation:"horizontal",range:!1,step:1,value:0,values:null,change:null,slide:null,start:null,stop:null},_create:function(){this._keySliding=!1,this._mouseSliding=!1,this._animateOff=!0,this._handleIndex=null,this._detectOrientation(),this._mouseInit(),this.element.addClass("ui-slider ui-slider-"+this.orientation+" ui-widget"+" ui-widget-content"+" ui-corner-all"),this._refresh(),this._setOption("disabled",this.options.disabled),this._animateOff=!1},_refresh:function(){this._createRange(),this._createHandles(),this._setupEvents(),this._refreshValue()},_createHandles:function(){var e,i,s=this.options,n=this.element.find(".ui-slider-handle").addClass("ui-state-default ui-corner-all"),a="<a class='ui-slider-handle ui-state-default ui-corner-all' href='#'></a>",o=[];for(i=s.values&&s.values.length||1,n.length>i&&(n.slice(i).remove(),n=n.slice(0,i)),e=n.length;i>e;e++)o.push(a);this.handles=n.add(t(o.join("")).appendTo(this.element)),this.handle=this.handles.eq(0),this.handles.each(function(e){t(this).data("ui-slider-handle-index",e)})},_createRange:function(){var e=this.options,i="";e.range?(e.range===!0&&(e.values?e.values.length&&2!==e.values.length?e.values=[e.values[0],e.values[0]]:t.isArray(e.values)&&(e.values=e.values.slice(0)):e.values=[this._valueMin(),this._valueMin()]),this.range&&this.range.length?this.range.removeClass("ui-slider-range-min ui-slider-range-max").css({left:"",bottom:""}):(this.range=t("<div></div>").appendTo(this.element),i="ui-slider-range ui-widget-header ui-corner-all"),this.range.addClass(i+("min"===e.range||"max"===e.range?" ui-slider-range-"+e.range:""))):(this.range&&this.range.remove(),this.range=null)},_setupEvents:function(){var t=this.handles.add(this.range).filter("a");this._off(t),this._on(t,this._handleEvents),this._hoverable(t),this._focusable(t)},_destroy:function(){this.handles.remove(),this.range&&this.range.remove(),this.element.removeClass("ui-slider ui-slider-horizontal ui-slider-vertical ui-widget ui-widget-content ui-corner-all"),this._mouseDestroy()},_mouseCapture:function(e){var i,s,n,a,o,r,l,h,u=this,c=this.options;return c.disabled?!1:(this.elementSize={width:this.element.outerWidth(),height:this.element.outerHeight()},this.elementOffset=this.element.offset(),i={x:e.pageX,y:e.pageY},s=this._normValueFromMouse(i),n=this._valueMax()-this._valueMin()+1,this.handles.each(function(e){var i=Math.abs(s-u.values(e));(n>i||n===i&&(e===u._lastChangedValue||u.values(e)===c.min))&&(n=i,a=t(this),o=e)}),r=this._start(e,o),r===!1?!1:(this._mouseSliding=!0,this._handleIndex=o,a.addClass("ui-state-active").focus(),l=a.offset(),h=!t(e.target).parents().addBack().is(".ui-slider-handle"),this._clickOffset=h?{left:0,top:0}:{left:e.pageX-l.left-a.width()/2,top:e.pageY-l.top-a.height()/2-(parseInt(a.css("borderTopWidth"),10)||0)-(parseInt(a.css("borderBottomWidth"),10)||0)+(parseInt(a.css("marginTop"),10)||0)},this.handles.hasClass("ui-state-hover")||this._slide(e,o,s),this._animateOff=!0,!0))},_mouseStart:function(){return!0},_mouseDrag:function(t){var e={x:t.pageX,y:t.pageY},i=this._normValueFromMouse(e);return this._slide(t,this._handleIndex,i),!1},_mouseStop:function(t){return this.handles.removeClass("ui-state-active"),this._mouseSliding=!1,this._stop(t,this._handleIndex),this._change(t,this._handleIndex),this._handleIndex=null,this._clickOffset=null,this._animateOff=!1,!1},_detectOrientation:function(){this.orientation="vertical"===this.options.orientation?"vertical":"horizontal"},_normValueFromMouse:function(t){var e,i,s,n,a;return"horizontal"===this.orientation?(e=this.elementSize.width,i=t.x-this.elementOffset.left-(this._clickOffset?this._clickOffset.left:0)):(e=this.elementSize.height,i=t.y-this.elementOffset.top-(this._clickOffset?this._clickOffset.top:0)),s=i/e,s>1&&(s=1),0>s&&(s=0),"vertical"===this.orientation&&(s=1-s),n=this._valueMax()-this._valueMin(),a=this._valueMin()+s*n,this._trimAlignValue(a)},_start:function(t,e){var i={handle:this.handles[e],value:this.value()};return this.options.values&&this.options.values.length&&(i.value=this.values(e),i.values=this.values()),this._trigger("start",t,i)},_slide:function(t,e,i){var s,n,a;this.options.values&&this.options.values.length?(s=this.values(e?0:1),2===this.options.values.length&&this.options.range===!0&&(0===e&&i>s||1===e&&s>i)&&(i=s),i!==this.values(e)&&(n=this.values(),n[e]=i,a=this._trigger("slide",t,{handle:this.handles[e],value:i,values:n}),s=this.values(e?0:1),a!==!1&&this.values(e,i))):i!==this.value()&&(a=this._trigger("slide",t,{handle:this.handles[e],value:i}),a!==!1&&this.value(i))},_stop:function(t,e){var i={handle:this.handles[e],value:this.value()};this.options.values&&this.options.values.length&&(i.value=this.values(e),i.values=this.values()),this._trigger("stop",t,i)},_change:function(t,e){if(!this._keySliding&&!this._mouseSliding){var i={handle:this.handles[e],value:this.value()};this.options.values&&this.options.values.length&&(i.value=this.values(e),i.values=this.values()),this._lastChangedValue=e,this._trigger("change",t,i)}},value:function(t){return arguments.length?(this.options.value=this._trimAlignValue(t),this._refreshValue(),this._change(null,0),undefined):this._value()},values:function(e,i){var s,n,a;if(arguments.length>1)return this.options.values[e]=this._trimAlignValue(i),this._refreshValue(),this._change(null,e),undefined;if(!arguments.length)return this._values();if(!t.isArray(arguments[0]))return this.options.values&&this.options.values.length?this._values(e):this.value();for(s=this.options.values,n=arguments[0],a=0;s.length>a;a+=1)s[a]=this._trimAlignValue(n[a]),this._change(null,a);this._refreshValue()},_setOption:function(e,i){var s,n=0;switch("range"===e&&this.options.range===!0&&("min"===i?(this.options.value=this._values(0),this.options.values=null):"max"===i&&(this.options.value=this._values(this.options.values.length-1),this.options.values=null)),t.isArray(this.options.values)&&(n=this.options.values.length),t.Widget.prototype._setOption.apply(this,arguments),e){case"orientation":this._detectOrientation(),this.element.removeClass("ui-slider-horizontal ui-slider-vertical").addClass("ui-slider-"+this.orientation),this._refreshValue();break;case"value":this._animateOff=!0,this._refreshValue(),this._change(null,0),this._animateOff=!1;break;case"values":for(this._animateOff=!0,this._refreshValue(),s=0;n>s;s+=1)this._change(null,s);this._animateOff=!1;break;case"min":case"max":this._animateOff=!0,this._refreshValue(),this._animateOff=!1;break;case"range":this._animateOff=!0,this._refresh(),this._animateOff=!1}},_value:function(){var t=this.options.value;return t=this._trimAlignValue(t)},_values:function(t){var e,i,s;if(arguments.length)return e=this.options.values[t],e=this._trimAlignValue(e);if(this.options.values&&this.options.values.length){for(i=this.options.values.slice(),s=0;i.length>s;s+=1)i[s]=this._trimAlignValue(i[s]);return i}return[]},_trimAlignValue:function(t){if(this._valueMin()>=t)return this._valueMin();if(t>=this._valueMax())return this._valueMax();var e=this.options.step>0?this.options.step:1,i=(t-this._valueMin())%e,s=t-i;return 2*Math.abs(i)>=e&&(s+=i>0?e:-e),parseFloat(s.toFixed(5))},_valueMin:function(){return this.options.min},_valueMax:function(){return this.options.max},_refreshValue:function(){var e,i,s,n,a,o=this.options.range,r=this.options,l=this,h=this._animateOff?!1:r.animate,u={};this.options.values&&this.options.values.length?this.handles.each(function(s){i=100*((l.values(s)-l._valueMin())/(l._valueMax()-l._valueMin())),u["horizontal"===l.orientation?"left":"bottom"]=i+"%",t(this).stop(1,1)[h?"animate":"css"](u,r.animate),l.options.range===!0&&("horizontal"===l.orientation?(0===s&&l.range.stop(1,1)[h?"animate":"css"]({left:i+"%"},r.animate),1===s&&l.range[h?"animate":"css"]({width:i-e+"%"},{queue:!1,duration:r.animate})):(0===s&&l.range.stop(1,1)[h?"animate":"css"]({bottom:i+"%"},r.animate),1===s&&l.range[h?"animate":"css"]({height:i-e+"%"},{queue:!1,duration:r.animate}))),e=i}):(s=this.value(),n=this._valueMin(),a=this._valueMax(),i=a!==n?100*((s-n)/(a-n)):0,u["horizontal"===this.orientation?"left":"bottom"]=i+"%",this.handle.stop(1,1)[h?"animate":"css"](u,r.animate),"min"===o&&"horizontal"===this.orientation&&this.range.stop(1,1)[h?"animate":"css"]({width:i+"%"},r.animate),"max"===o&&"horizontal"===this.orientation&&this.range[h?"animate":"css"]({width:100-i+"%"},{queue:!1,duration:r.animate}),"min"===o&&"vertical"===this.orientation&&this.range.stop(1,1)[h?"animate":"css"]({height:i+"%"},r.animate),"max"===o&&"vertical"===this.orientation&&this.range[h?"animate":"css"]({height:100-i+"%"},{queue:!1,duration:r.animate}))},_handleEvents:{keydown:function(i){var s,n,a,o,r=t(i.target).data("ui-slider-handle-index");switch(i.keyCode){case t.ui.keyCode.HOME:case t.ui.keyCode.END:case t.ui.keyCode.PAGE_UP:case t.ui.keyCode.PAGE_DOWN:case t.ui.keyCode.UP:case t.ui.keyCode.RIGHT:case t.ui.keyCode.DOWN:case t.ui.keyCode.LEFT:if(i.preventDefault(),!this._keySliding&&(this._keySliding=!0,t(i.target).addClass("ui-state-active"),s=this._start(i,r),s===!1))return}switch(o=this.options.step,n=a=this.options.values&&this.options.values.length?this.values(r):this.value(),i.keyCode){case t.ui.keyCode.HOME:a=this._valueMin();break;case t.ui.keyCode.END:a=this._valueMax();break;case t.ui.keyCode.PAGE_UP:a=this._trimAlignValue(n+(this._valueMax()-this._valueMin())/e);break;case t.ui.keyCode.PAGE_DOWN:a=this._trimAlignValue(n-(this._valueMax()-this._valueMin())/e);break;case t.ui.keyCode.UP:case t.ui.keyCode.RIGHT:if(n===this._valueMax())return;a=this._trimAlignValue(n+o);break;case t.ui.keyCode.DOWN:case t.ui.keyCode.LEFT:if(n===this._valueMin())return;a=this._trimAlignValue(n-o)}this._slide(i,r,a)},click:function(t){t.preventDefault()},keyup:function(e){var i=t(e.target).data("ui-slider-handle-index");this._keySliding&&(this._keySliding=!1,this._stop(e,i),this._change(e,i),t(e.target).removeClass("ui-state-active"))}}})})(jQuery);(function(t){function e(t){return function(){var e=this.element.val();t.apply(this,arguments),this._refresh(),e!==this.element.val()&&this._trigger("change")}}t.widget("ui.spinner",{version:"1.10.4",defaultElement:"<input>",widgetEventPrefix:"spin",options:{culture:null,icons:{down:"ui-icon-triangle-1-s",up:"ui-icon-triangle-1-n"},incremental:!0,max:null,min:null,numberFormat:null,page:10,step:1,change:null,spin:null,start:null,stop:null},_create:function(){this._setOption("max",this.options.max),this._setOption("min",this.options.min),this._setOption("step",this.options.step),""!==this.value()&&this._value(this.element.val(),!0),this._draw(),this._on(this._events),this._refresh(),this._on(this.window,{beforeunload:function(){this.element.removeAttr("autocomplete")}})},_getCreateOptions:function(){var e={},i=this.element;return t.each(["min","max","step"],function(t,s){var n=i.attr(s);void 0!==n&&n.length&&(e[s]=n)}),e},_events:{keydown:function(t){this._start(t)&&this._keydown(t)&&t.preventDefault()},keyup:"_stop",focus:function(){this.previous=this.element.val()},blur:function(t){return this.cancelBlur?(delete this.cancelBlur,void 0):(this._stop(),this._refresh(),this.previous!==this.element.val()&&this._trigger("change",t),void 0)},mousewheel:function(t,e){if(e){if(!this.spinning&&!this._start(t))return!1;this._spin((e>0?1:-1)*this.options.step,t),clearTimeout(this.mousewheelTimer),this.mousewheelTimer=this._delay(function(){this.spinning&&this._stop(t)},100),t.preventDefault()}},"mousedown .ui-spinner-button":function(e){function i(){var t=this.element[0]===this.document[0].activeElement;t||(this.element.focus(),this.previous=s,this._delay(function(){this.previous=s}))}var s;s=this.element[0]===this.document[0].activeElement?this.previous:this.element.val(),e.preventDefault(),i.call(this),this.cancelBlur=!0,this._delay(function(){delete this.cancelBlur,i.call(this)}),this._start(e)!==!1&&this._repeat(null,t(e.currentTarget).hasClass("ui-spinner-up")?1:-1,e)},"mouseup .ui-spinner-button":"_stop","mouseenter .ui-spinner-button":function(e){return t(e.currentTarget).hasClass("ui-state-active")?this._start(e)===!1?!1:(this._repeat(null,t(e.currentTarget).hasClass("ui-spinner-up")?1:-1,e),void 0):void 0},"mouseleave .ui-spinner-button":"_stop"},_draw:function(){var t=this.uiSpinner=this.element.addClass("ui-spinner-input").attr("autocomplete","off").wrap(this._uiSpinnerHtml()).parent().append(this._buttonHtml());this.element.attr("role","spinbutton"),this.buttons=t.find(".ui-spinner-button").attr("tabIndex",-1).button().removeClass("ui-corner-all"),this.buttons.height()>Math.ceil(.5*t.height())&&t.height()>0&&t.height(t.height()),this.options.disabled&&this.disable()},_keydown:function(e){var i=this.options,s=t.ui.keyCode;switch(e.keyCode){case s.UP:return this._repeat(null,1,e),!0;case s.DOWN:return this._repeat(null,-1,e),!0;case s.PAGE_UP:return this._repeat(null,i.page,e),!0;case s.PAGE_DOWN:return this._repeat(null,-i.page,e),!0}return!1},_uiSpinnerHtml:function(){return"<span class='ui-spinner ui-widget ui-widget-content ui-corner-all'></span>"},_buttonHtml:function(){return"<a class='ui-spinner-button ui-spinner-up ui-corner-tr'><span class='ui-icon "+this.options.icons.up+"'>▲</span>"+"</a>"+"<a class='ui-spinner-button ui-spinner-down ui-corner-br'>"+"<span class='ui-icon "+this.options.icons.down+"'>▼</span>"+"</a>"},_start:function(t){return this.spinning||this._trigger("start",t)!==!1?(this.counter||(this.counter=1),this.spinning=!0,!0):!1},_repeat:function(t,e,i){t=t||500,clearTimeout(this.timer),this.timer=this._delay(function(){this._repeat(40,e,i)},t),this._spin(e*this.options.step,i)},_spin:function(t,e){var i=this.value()||0;this.counter||(this.counter=1),i=this._adjustValue(i+t*this._increment(this.counter)),this.spinning&&this._trigger("spin",e,{value:i})===!1||(this._value(i),this.counter++)},_increment:function(e){var i=this.options.incremental;return i?t.isFunction(i)?i(e):Math.floor(e*e*e/5e4-e*e/500+17*e/200+1):1},_precision:function(){var t=this._precisionOf(this.options.step);return null!==this.options.min&&(t=Math.max(t,this._precisionOf(this.options.min))),t},_precisionOf:function(t){var e=""+t,i=e.indexOf(".");return-1===i?0:e.length-i-1},_adjustValue:function(t){var e,i,s=this.options;return e=null!==s.min?s.min:0,i=t-e,i=Math.round(i/s.step)*s.step,t=e+i,t=parseFloat(t.toFixed(this._precision())),null!==s.max&&t>s.max?s.max:null!==s.min&&s.min>t?s.min:t},_stop:function(t){this.spinning&&(clearTimeout(this.timer),clearTimeout(this.mousewheelTimer),this.counter=0,this.spinning=!1,this._trigger("stop",t))},_setOption:function(t,e){if("culture"===t||"numberFormat"===t){var i=this._parse(this.element.val());return this.options[t]=e,this.element.val(this._format(i)),void 0}("max"===t||"min"===t||"step"===t)&&"string"==typeof e&&(e=this._parse(e)),"icons"===t&&(this.buttons.first().find(".ui-icon").removeClass(this.options.icons.up).addClass(e.up),this.buttons.last().find(".ui-icon").removeClass(this.options.icons.down).addClass(e.down)),this._super(t,e),"disabled"===t&&(e?(this.element.prop("disabled",!0),this.buttons.button("disable")):(this.element.prop("disabled",!1),this.buttons.button("enable")))},_setOptions:e(function(t){this._super(t),this._value(this.element.val())}),_parse:function(t){return"string"==typeof t&&""!==t&&(t=window.Globalize&&this.options.numberFormat?Globalize.parseFloat(t,10,this.options.culture):+t),""===t||isNaN(t)?null:t},_format:function(t){return""===t?"":window.Globalize&&this.options.numberFormat?Globalize.format(t,this.options.numberFormat,this.options.culture):t},_refresh:function(){this.element.attr({"aria-valuemin":this.options.min,"aria-valuemax":this.options.max,"aria-valuenow":this._parse(this.element.val())})},_value:function(t,e){var i;""!==t&&(i=this._parse(t),null!==i&&(e||(i=this._adjustValue(i)),t=this._format(i))),this.element.val(t),this._refresh()},_destroy:function(){this.element.removeClass("ui-spinner-input").prop("disabled",!1).removeAttr("autocomplete").removeAttr("role").removeAttr("aria-valuemin").removeAttr("aria-valuemax").removeAttr("aria-valuenow"),this.uiSpinner.replaceWith(this.element)},stepUp:e(function(t){this._stepUp(t)}),_stepUp:function(t){this._start()&&(this._spin((t||1)*this.options.step),this._stop())},stepDown:e(function(t){this._stepDown(t)}),_stepDown:function(t){this._start()&&(this._spin((t||1)*-this.options.step),this._stop())},pageUp:e(function(t){this._stepUp((t||1)*this.options.page)}),pageDown:e(function(t){this._stepDown((t||1)*this.options.page)}),value:function(t){return arguments.length?(e(this._value).call(this,t),void 0):this._parse(this.element.val())},widget:function(){return this.uiSpinner}})})(jQuery);(function(t,e){function i(){return++n}function s(t){return t=t.cloneNode(!1),t.hash.length>1&&decodeURIComponent(t.href.replace(a,""))===decodeURIComponent(location.href.replace(a,""))}var n=0,a=/#.*$/;t.widget("ui.tabs",{version:"1.10.4",delay:300,options:{active:null,collapsible:!1,event:"click",heightStyle:"content",hide:null,show:null,activate:null,beforeActivate:null,beforeLoad:null,load:null},_create:function(){var e=this,i=this.options;this.running=!1,this.element.addClass("ui-tabs ui-widget ui-widget-content ui-corner-all").toggleClass("ui-tabs-collapsible",i.collapsible).delegate(".ui-tabs-nav > li","mousedown"+this.eventNamespace,function(e){t(this).is(".ui-state-disabled")&&e.preventDefault()}).delegate(".ui-tabs-anchor","focus"+this.eventNamespace,function(){t(this).closest("li").is(".ui-state-disabled")&&this.blur()}),this._processTabs(),i.active=this._initialActive(),t.isArray(i.disabled)&&(i.disabled=t.unique(i.disabled.concat(t.map(this.tabs.filter(".ui-state-disabled"),function(t){return e.tabs.index(t)}))).sort()),this.active=this.options.active!==!1&&this.anchors.length?this._findActive(i.active):t(),this._refresh(),this.active.length&&this.load(i.active)},_initialActive:function(){var i=this.options.active,s=this.options.collapsible,n=location.hash.substring(1);return null===i&&(n&&this.tabs.each(function(s,a){return t(a).attr("aria-controls")===n?(i=s,!1):e}),null===i&&(i=this.tabs.index(this.tabs.filter(".ui-tabs-active"))),(null===i||-1===i)&&(i=this.tabs.length?0:!1)),i!==!1&&(i=this.tabs.index(this.tabs.eq(i)),-1===i&&(i=s?!1:0)),!s&&i===!1&&this.anchors.length&&(i=0),i},_getCreateEventData:function(){return{tab:this.active,panel:this.active.length?this._getPanelForTab(this.active):t()}},_tabKeydown:function(i){var s=t(this.document[0].activeElement).closest("li"),n=this.tabs.index(s),a=!0;if(!this._handlePageNav(i)){switch(i.keyCode){case t.ui.keyCode.RIGHT:case t.ui.keyCode.DOWN:n++;break;case t.ui.keyCode.UP:case t.ui.keyCode.LEFT:a=!1,n--;break;case t.ui.keyCode.END:n=this.anchors.length-1;break;case t.ui.keyCode.HOME:n=0;break;case t.ui.keyCode.SPACE:return i.preventDefault(),clearTimeout(this.activating),this._activate(n),e;case t.ui.keyCode.ENTER:return i.preventDefault(),clearTimeout(this.activating),this._activate(n===this.options.active?!1:n),e;default:return}i.preventDefault(),clearTimeout(this.activating),n=this._focusNextTab(n,a),i.ctrlKey||(s.attr("aria-selected","false"),this.tabs.eq(n).attr("aria-selected","true"),this.activating=this._delay(function(){this.option("active",n)},this.delay))}},_panelKeydown:function(e){this._handlePageNav(e)||e.ctrlKey&&e.keyCode===t.ui.keyCode.UP&&(e.preventDefault(),this.active.focus())},_handlePageNav:function(i){return i.altKey&&i.keyCode===t.ui.keyCode.PAGE_UP?(this._activate(this._focusNextTab(this.options.active-1,!1)),!0):i.altKey&&i.keyCode===t.ui.keyCode.PAGE_DOWN?(this._activate(this._focusNextTab(this.options.active+1,!0)),!0):e},_findNextTab:function(e,i){function s(){return e>n&&(e=0),0>e&&(e=n),e}for(var n=this.tabs.length-1;-1!==t.inArray(s(),this.options.disabled);)e=i?e+1:e-1;return e},_focusNextTab:function(t,e){return t=this._findNextTab(t,e),this.tabs.eq(t).focus(),t},_setOption:function(t,i){return"active"===t?(this._activate(i),e):"disabled"===t?(this._setupDisabled(i),e):(this._super(t,i),"collapsible"===t&&(this.element.toggleClass("ui-tabs-collapsible",i),i||this.options.active!==!1||this._activate(0)),"event"===t&&this._setupEvents(i),"heightStyle"===t&&this._setupHeightStyle(i),e)},_tabId:function(t){return t.attr("aria-controls")||"ui-tabs-"+i()},_sanitizeSelector:function(t){return t?t.replace(/[!"$%&'()*+,.\/:;<=>?@\[\]\^`{|}~]/g,"\\$&"):""},refresh:function(){var e=this.options,i=this.tablist.children(":has(a[href])");e.disabled=t.map(i.filter(".ui-state-disabled"),function(t){return i.index(t)}),this._processTabs(),e.active!==!1&&this.anchors.length?this.active.length&&!t.contains(this.tablist[0],this.active[0])?this.tabs.length===e.disabled.length?(e.active=!1,this.active=t()):this._activate(this._findNextTab(Math.max(0,e.active-1),!1)):e.active=this.tabs.index(this.active):(e.active=!1,this.active=t()),this._refresh()},_refresh:function(){this._setupDisabled(this.options.disabled),this._setupEvents(this.options.event),this._setupHeightStyle(this.options.heightStyle),this.tabs.not(this.active).attr({"aria-selected":"false",tabIndex:-1}),this.panels.not(this._getPanelForTab(this.active)).hide().attr({"aria-expanded":"false","aria-hidden":"true"}),this.active.length?(this.active.addClass("ui-tabs-active ui-state-active").attr({"aria-selected":"true",tabIndex:0}),this._getPanelForTab(this.active).show().attr({"aria-expanded":"true","aria-hidden":"false"})):this.tabs.eq(0).attr("tabIndex",0)},_processTabs:function(){var e=this;this.tablist=this._getList().addClass("ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all").attr("role","tablist"),this.tabs=this.tablist.find("> li:has(a[href])").addClass("ui-state-default ui-corner-top").attr({role:"tab",tabIndex:-1}),this.anchors=this.tabs.map(function(){return t("a",this)[0]}).addClass("ui-tabs-anchor").attr({role:"presentation",tabIndex:-1}),this.panels=t(),this.anchors.each(function(i,n){var a,o,r,h=t(n).uniqueId().attr("id"),l=t(n).closest("li"),c=l.attr("aria-controls");s(n)?(a=n.hash,o=e.element.find(e._sanitizeSelector(a))):(r=e._tabId(l),a="#"+r,o=e.element.find(a),o.length||(o=e._createPanel(r),o.insertAfter(e.panels[i-1]||e.tablist)),o.attr("aria-live","polite")),o.length&&(e.panels=e.panels.add(o)),c&&l.data("ui-tabs-aria-controls",c),l.attr({"aria-controls":a.substring(1),"aria-labelledby":h}),o.attr("aria-labelledby",h)}),this.panels.addClass("ui-tabs-panel ui-widget-content ui-corner-bottom").attr("role","tabpanel")},_getList:function(){return this.tablist||this.element.find("ol,ul").eq(0)},_createPanel:function(e){return t("<div>").attr("id",e).addClass("ui-tabs-panel ui-widget-content ui-corner-bottom").data("ui-tabs-destroy",!0)},_setupDisabled:function(e){t.isArray(e)&&(e.length?e.length===this.anchors.length&&(e=!0):e=!1);for(var i,s=0;i=this.tabs[s];s++)e===!0||-1!==t.inArray(s,e)?t(i).addClass("ui-state-disabled").attr("aria-disabled","true"):t(i).removeClass("ui-state-disabled").removeAttr("aria-disabled");this.options.disabled=e},_setupEvents:function(e){var i={click:function(t){t.preventDefault()}};e&&t.each(e.split(" "),function(t,e){i[e]="_eventHandler"}),this._off(this.anchors.add(this.tabs).add(this.panels)),this._on(this.anchors,i),this._on(this.tabs,{keydown:"_tabKeydown"}),this._on(this.panels,{keydown:"_panelKeydown"}),this._focusable(this.tabs),this._hoverable(this.tabs)},_setupHeightStyle:function(e){var i,s=this.element.parent();"fill"===e?(i=s.height(),i-=this.element.outerHeight()-this.element.height(),this.element.siblings(":visible").each(function(){var e=t(this),s=e.css("position");"absolute"!==s&&"fixed"!==s&&(i-=e.outerHeight(!0))}),this.element.children().not(this.panels).each(function(){i-=t(this).outerHeight(!0)}),this.panels.each(function(){t(this).height(Math.max(0,i-t(this).innerHeight()+t(this).height()))}).css("overflow","auto")):"auto"===e&&(i=0,this.panels.each(function(){i=Math.max(i,t(this).height("").height())}).height(i))},_eventHandler:function(e){var i=this.options,s=this.active,n=t(e.currentTarget),a=n.closest("li"),o=a[0]===s[0],r=o&&i.collapsible,h=r?t():this._getPanelForTab(a),l=s.length?this._getPanelForTab(s):t(),c={oldTab:s,oldPanel:l,newTab:r?t():a,newPanel:h};e.preventDefault(),a.hasClass("ui-state-disabled")||a.hasClass("ui-tabs-loading")||this.running||o&&!i.collapsible||this._trigger("beforeActivate",e,c)===!1||(i.active=r?!1:this.tabs.index(a),this.active=o?t():a,this.xhr&&this.xhr.abort(),l.length||h.length||t.error("jQuery UI Tabs: Mismatching fragment identifier."),h.length&&this.load(this.tabs.index(a),e),this._toggle(e,c))},_toggle:function(e,i){function s(){a.running=!1,a._trigger("activate",e,i)}function n(){i.newTab.closest("li").addClass("ui-tabs-active ui-state-active"),o.length&&a.options.show?a._show(o,a.options.show,s):(o.show(),s())}var a=this,o=i.newPanel,r=i.oldPanel;this.running=!0,r.length&&this.options.hide?this._hide(r,this.options.hide,function(){i.oldTab.closest("li").removeClass("ui-tabs-active ui-state-active"),n()}):(i.oldTab.closest("li").removeClass("ui-tabs-active ui-state-active"),r.hide(),n()),r.attr({"aria-expanded":"false","aria-hidden":"true"}),i.oldTab.attr("aria-selected","false"),o.length&&r.length?i.oldTab.attr("tabIndex",-1):o.length&&this.tabs.filter(function(){return 0===t(this).attr("tabIndex")}).attr("tabIndex",-1),o.attr({"aria-expanded":"true","aria-hidden":"false"}),i.newTab.attr({"aria-selected":"true",tabIndex:0})},_activate:function(e){var i,s=this._findActive(e);s[0]!==this.active[0]&&(s.length||(s=this.active),i=s.find(".ui-tabs-anchor")[0],this._eventHandler({target:i,currentTarget:i,preventDefault:t.noop}))},_findActive:function(e){return e===!1?t():this.tabs.eq(e)},_getIndex:function(t){return"string"==typeof t&&(t=this.anchors.index(this.anchors.filter("[href$='"+t+"']"))),t},_destroy:function(){this.xhr&&this.xhr.abort(),this.element.removeClass("ui-tabs ui-widget ui-widget-content ui-corner-all ui-tabs-collapsible"),this.tablist.removeClass("ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all").removeAttr("role"),this.anchors.removeClass("ui-tabs-anchor").removeAttr("role").removeAttr("tabIndex").removeUniqueId(),this.tabs.add(this.panels).each(function(){t.data(this,"ui-tabs-destroy")?t(this).remove():t(this).removeClass("ui-state-default ui-state-active ui-state-disabled ui-corner-top ui-corner-bottom ui-widget-content ui-tabs-active ui-tabs-panel").removeAttr("tabIndex").removeAttr("aria-live").removeAttr("aria-busy").removeAttr("aria-selected").removeAttr("aria-labelledby").removeAttr("aria-hidden").removeAttr("aria-expanded").removeAttr("role")}),this.tabs.each(function(){var e=t(this),i=e.data("ui-tabs-aria-controls");i?e.attr("aria-controls",i).removeData("ui-tabs-aria-controls"):e.removeAttr("aria-controls")}),this.panels.show(),"content"!==this.options.heightStyle&&this.panels.css("height","")},enable:function(i){var s=this.options.disabled;s!==!1&&(i===e?s=!1:(i=this._getIndex(i),s=t.isArray(s)?t.map(s,function(t){return t!==i?t:null}):t.map(this.tabs,function(t,e){return e!==i?e:null})),this._setupDisabled(s))},disable:function(i){var s=this.options.disabled;if(s!==!0){if(i===e)s=!0;else{if(i=this._getIndex(i),-1!==t.inArray(i,s))return;s=t.isArray(s)?t.merge([i],s).sort():[i]}this._setupDisabled(s)}},load:function(e,i){e=this._getIndex(e);var n=this,a=this.tabs.eq(e),o=a.find(".ui-tabs-anchor"),r=this._getPanelForTab(a),h={tab:a,panel:r};s(o[0])||(this.xhr=t.ajax(this._ajaxSettings(o,i,h)),this.xhr&&"canceled"!==this.xhr.statusText&&(a.addClass("ui-tabs-loading"),r.attr("aria-busy","true"),this.xhr.success(function(t){setTimeout(function(){r.html(t),n._trigger("load",i,h)},1)}).complete(function(t,e){setTimeout(function(){"abort"===e&&n.panels.stop(!1,!0),a.removeClass("ui-tabs-loading"),r.removeAttr("aria-busy"),t===n.xhr&&delete n.xhr},1)})))},_ajaxSettings:function(e,i,s){var n=this;return{url:e.attr("href"),beforeSend:function(e,a){return n._trigger("beforeLoad",i,t.extend({jqXHR:e,ajaxSettings:a},s))}}},_getPanelForTab:function(e){var i=t(e).attr("aria-controls");return this.element.find(this._sanitizeSelector("#"+i))}})})(jQuery);(function(t){function e(e,i){var s=(e.attr("aria-describedby")||"").split(/\s+/);s.push(i),e.data("ui-tooltip-id",i).attr("aria-describedby",t.trim(s.join(" ")))}function i(e){var i=e.data("ui-tooltip-id"),s=(e.attr("aria-describedby")||"").split(/\s+/),n=t.inArray(i,s);-1!==n&&s.splice(n,1),e.removeData("ui-tooltip-id"),s=t.trim(s.join(" ")),s?e.attr("aria-describedby",s):e.removeAttr("aria-describedby")}var s=0;t.widget("ui.tooltip",{version:"1.10.4",options:{content:function(){var e=t(this).attr("title")||"";return t("<a>").text(e).html()},hide:!0,items:"[title]:not([disabled])",position:{my:"left top+15",at:"left bottom",collision:"flipfit flip"},show:!0,tooltipClass:null,track:!1,close:null,open:null},_create:function(){this._on({mouseover:"open",focusin:"open"}),this.tooltips={},this.parents={},this.options.disabled&&this._disable()},_setOption:function(e,i){var s=this;return"disabled"===e?(this[i?"_disable":"_enable"](),this.options[e]=i,void 0):(this._super(e,i),"content"===e&&t.each(this.tooltips,function(t,e){s._updateContent(e)}),void 0)},_disable:function(){var e=this;t.each(this.tooltips,function(i,s){var n=t.Event("blur");n.target=n.currentTarget=s[0],e.close(n,!0)}),this.element.find(this.options.items).addBack().each(function(){var e=t(this);e.is("[title]")&&e.data("ui-tooltip-title",e.attr("title")).attr("title","")})},_enable:function(){this.element.find(this.options.items).addBack().each(function(){var e=t(this);e.data("ui-tooltip-title")&&e.attr("title",e.data("ui-tooltip-title"))})},open:function(e){var i=this,s=t(e?e.target:this.element).closest(this.options.items);s.length&&!s.data("ui-tooltip-id")&&(s.attr("title")&&s.data("ui-tooltip-title",s.attr("title")),s.data("ui-tooltip-open",!0),e&&"mouseover"===e.type&&s.parents().each(function(){var e,s=t(this);s.data("ui-tooltip-open")&&(e=t.Event("blur"),e.target=e.currentTarget=this,i.close(e,!0)),s.attr("title")&&(s.uniqueId(),i.parents[this.id]={element:this,title:s.attr("title")},s.attr("title",""))}),this._updateContent(s,e))},_updateContent:function(t,e){var i,s=this.options.content,n=this,o=e?e.type:null;return"string"==typeof s?this._open(e,t,s):(i=s.call(t[0],function(i){t.data("ui-tooltip-open")&&n._delay(function(){e&&(e.type=o),this._open(e,t,i)})}),i&&this._open(e,t,i),void 0)},_open:function(i,s,n){function o(t){l.of=t,a.is(":hidden")||a.position(l)}var a,r,h,l=t.extend({},this.options.position);if(n){if(a=this._find(s),a.length)return a.find(".ui-tooltip-content").html(n),void 0;s.is("[title]")&&(i&&"mouseover"===i.type?s.attr("title",""):s.removeAttr("title")),a=this._tooltip(s),e(s,a.attr("id")),a.find(".ui-tooltip-content").html(n),this.options.track&&i&&/^mouse/.test(i.type)?(this._on(this.document,{mousemove:o}),o(i)):a.position(t.extend({of:s},this.options.position)),a.hide(),this._show(a,this.options.show),this.options.show&&this.options.show.delay&&(h=this.delayedShow=setInterval(function(){a.is(":visible")&&(o(l.of),clearInterval(h))},t.fx.interval)),this._trigger("open",i,{tooltip:a}),r={keyup:function(e){if(e.keyCode===t.ui.keyCode.ESCAPE){var i=t.Event(e);i.currentTarget=s[0],this.close(i,!0)}},remove:function(){this._removeTooltip(a)}},i&&"mouseover"!==i.type||(r.mouseleave="close"),i&&"focusin"!==i.type||(r.focusout="close"),this._on(!0,s,r)}},close:function(e){var s=this,n=t(e?e.currentTarget:this.element),o=this._find(n);this.closing||(clearInterval(this.delayedShow),n.data("ui-tooltip-title")&&n.attr("title",n.data("ui-tooltip-title")),i(n),o.stop(!0),this._hide(o,this.options.hide,function(){s._removeTooltip(t(this))}),n.removeData("ui-tooltip-open"),this._off(n,"mouseleave focusout keyup"),n[0]!==this.element[0]&&this._off(n,"remove"),this._off(this.document,"mousemove"),e&&"mouseleave"===e.type&&t.each(this.parents,function(e,i){t(i.element).attr("title",i.title),delete s.parents[e]}),this.closing=!0,this._trigger("close",e,{tooltip:o}),this.closing=!1)},_tooltip:function(e){var i="ui-tooltip-"+s++,n=t("<div>").attr({id:i,role:"tooltip"}).addClass("ui-tooltip ui-widget ui-corner-all ui-widget-content "+(this.options.tooltipClass||""));return t("<div>").addClass("ui-tooltip-content").appendTo(n),n.appendTo(this.document[0].body),this.tooltips[i]=e,n},_find:function(e){var i=e.data("ui-tooltip-id");return i?t("#"+i):t()},_removeTooltip:function(t){t.remove(),delete this.tooltips[t.attr("id")]},_destroy:function(){var e=this;t.each(this.tooltips,function(i,s){var n=t.Event("blur");n.target=n.currentTarget=s[0],e.close(n,!0),t("#"+i).remove(),s.data("ui-tooltip-title")&&(s.attr("title",s.data("ui-tooltip-title")),s.removeData("ui-tooltip-title"))})}})})(jQuery);(function(t,e){var i="ui-effects-";t.effects={effect:{}},function(t,e){function i(t,e,i){var s=u[e.type]||{};return null==t?i||!e.def?null:e.def:(t=s.floor?~~t:parseFloat(t),isNaN(t)?e.def:s.mod?(t+s.mod)%s.mod:0>t?0:t>s.max?s.max:t)}function s(i){var s=h(),n=s._rgba=[];return i=i.toLowerCase(),f(l,function(t,a){var o,r=a.re.exec(i),l=r&&a.parse(r),h=a.space||"rgba";return l?(o=s[h](l),s[c[h].cache]=o[c[h].cache],n=s._rgba=o._rgba,!1):e}),n.length?("0,0,0,0"===n.join()&&t.extend(n,a.transparent),s):a[i]}function n(t,e,i){return i=(i+1)%1,1>6*i?t+6*(e-t)*i:1>2*i?e:2>3*i?t+6*(e-t)*(2/3-i):t}var a,o="backgroundColor borderBottomColor borderLeftColor borderRightColor borderTopColor color columnRuleColor outlineColor textDecorationColor textEmphasisColor",r=/^([\-+])=\s*(\d+\.?\d*)/,l=[{re:/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,parse:function(t){return[t[1],t[2],t[3],t[4]]}},{re:/rgba?\(\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,parse:function(t){return[2.55*t[1],2.55*t[2],2.55*t[3],t[4]]}},{re:/#([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})/,parse:function(t){return[parseInt(t[1],16),parseInt(t[2],16),parseInt(t[3],16)]}},{re:/#([a-f0-9])([a-f0-9])([a-f0-9])/,parse:function(t){return[parseInt(t[1]+t[1],16),parseInt(t[2]+t[2],16),parseInt(t[3]+t[3],16)]}},{re:/hsla?\(\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,space:"hsla",parse:function(t){return[t[1],t[2]/100,t[3]/100,t[4]]}}],h=t.Color=function(e,i,s,n){return new t.Color.fn.parse(e,i,s,n)},c={rgba:{props:{red:{idx:0,type:"byte"},green:{idx:1,type:"byte"},blue:{idx:2,type:"byte"}}},hsla:{props:{hue:{idx:0,type:"degrees"},saturation:{idx:1,type:"percent"},lightness:{idx:2,type:"percent"}}}},u={"byte":{floor:!0,max:255},percent:{max:1},degrees:{mod:360,floor:!0}},d=h.support={},p=t("<p>")[0],f=t.each;p.style.cssText="background-color:rgba(1,1,1,.5)",d.rgba=p.style.backgroundColor.indexOf("rgba")>-1,f(c,function(t,e){e.cache="_"+t,e.props.alpha={idx:3,type:"percent",def:1}}),h.fn=t.extend(h.prototype,{parse:function(n,o,r,l){if(n===e)return this._rgba=[null,null,null,null],this;(n.jquery||n.nodeType)&&(n=t(n).css(o),o=e);var u=this,d=t.type(n),p=this._rgba=[];return o!==e&&(n=[n,o,r,l],d="array"),"string"===d?this.parse(s(n)||a._default):"array"===d?(f(c.rgba.props,function(t,e){p[e.idx]=i(n[e.idx],e)}),this):"object"===d?(n instanceof h?f(c,function(t,e){n[e.cache]&&(u[e.cache]=n[e.cache].slice())}):f(c,function(e,s){var a=s.cache;f(s.props,function(t,e){if(!u[a]&&s.to){if("alpha"===t||null==n[t])return;u[a]=s.to(u._rgba)}u[a][e.idx]=i(n[t],e,!0)}),u[a]&&0>t.inArray(null,u[a].slice(0,3))&&(u[a][3]=1,s.from&&(u._rgba=s.from(u[a])))}),this):e},is:function(t){var i=h(t),s=!0,n=this;return f(c,function(t,a){var o,r=i[a.cache];return r&&(o=n[a.cache]||a.to&&a.to(n._rgba)||[],f(a.props,function(t,i){return null!=r[i.idx]?s=r[i.idx]===o[i.idx]:e})),s}),s},_space:function(){var t=[],e=this;return f(c,function(i,s){e[s.cache]&&t.push(i)}),t.pop()},transition:function(t,e){var s=h(t),n=s._space(),a=c[n],o=0===this.alpha()?h("transparent"):this,r=o[a.cache]||a.to(o._rgba),l=r.slice();return s=s[a.cache],f(a.props,function(t,n){var a=n.idx,o=r[a],h=s[a],c=u[n.type]||{};null!==h&&(null===o?l[a]=h:(c.mod&&(h-o>c.mod/2?o+=c.mod:o-h>c.mod/2&&(o-=c.mod)),l[a]=i((h-o)*e+o,n)))}),this[n](l)},blend:function(e){if(1===this._rgba[3])return this;var i=this._rgba.slice(),s=i.pop(),n=h(e)._rgba;return h(t.map(i,function(t,e){return(1-s)*n[e]+s*t}))},toRgbaString:function(){var e="rgba(",i=t.map(this._rgba,function(t,e){return null==t?e>2?1:0:t});return 1===i[3]&&(i.pop(),e="rgb("),e+i.join()+")"},toHslaString:function(){var e="hsla(",i=t.map(this.hsla(),function(t,e){return null==t&&(t=e>2?1:0),e&&3>e&&(t=Math.round(100*t)+"%"),t});return 1===i[3]&&(i.pop(),e="hsl("),e+i.join()+")"},toHexString:function(e){var i=this._rgba.slice(),s=i.pop();return e&&i.push(~~(255*s)),"#"+t.map(i,function(t){return t=(t||0).toString(16),1===t.length?"0"+t:t}).join("")},toString:function(){return 0===this._rgba[3]?"transparent":this.toRgbaString()}}),h.fn.parse.prototype=h.fn,c.hsla.to=function(t){if(null==t[0]||null==t[1]||null==t[2])return[null,null,null,t[3]];var e,i,s=t[0]/255,n=t[1]/255,a=t[2]/255,o=t[3],r=Math.max(s,n,a),l=Math.min(s,n,a),h=r-l,c=r+l,u=.5*c;return e=l===r?0:s===r?60*(n-a)/h+360:n===r?60*(a-s)/h+120:60*(s-n)/h+240,i=0===h?0:.5>=u?h/c:h/(2-c),[Math.round(e)%360,i,u,null==o?1:o]},c.hsla.from=function(t){if(null==t[0]||null==t[1]||null==t[2])return[null,null,null,t[3]];var e=t[0]/360,i=t[1],s=t[2],a=t[3],o=.5>=s?s*(1+i):s+i-s*i,r=2*s-o;return[Math.round(255*n(r,o,e+1/3)),Math.round(255*n(r,o,e)),Math.round(255*n(r,o,e-1/3)),a]},f(c,function(s,n){var a=n.props,o=n.cache,l=n.to,c=n.from;h.fn[s]=function(s){if(l&&!this[o]&&(this[o]=l(this._rgba)),s===e)return this[o].slice();var n,r=t.type(s),u="array"===r||"object"===r?s:arguments,d=this[o].slice();return f(a,function(t,e){var s=u["object"===r?t:e.idx];null==s&&(s=d[e.idx]),d[e.idx]=i(s,e)}),c?(n=h(c(d)),n[o]=d,n):h(d)},f(a,function(e,i){h.fn[e]||(h.fn[e]=function(n){var a,o=t.type(n),l="alpha"===e?this._hsla?"hsla":"rgba":s,h=this[l](),c=h[i.idx];return"undefined"===o?c:("function"===o&&(n=n.call(this,c),o=t.type(n)),null==n&&i.empty?this:("string"===o&&(a=r.exec(n),a&&(n=c+parseFloat(a[2])*("+"===a[1]?1:-1))),h[i.idx]=n,this[l](h)))})})}),h.hook=function(e){var i=e.split(" ");f(i,function(e,i){t.cssHooks[i]={set:function(e,n){var a,o,r="";if("transparent"!==n&&("string"!==t.type(n)||(a=s(n)))){if(n=h(a||n),!d.rgba&&1!==n._rgba[3]){for(o="backgroundColor"===i?e.parentNode:e;(""===r||"transparent"===r)&&o&&o.style;)try{r=t.css(o,"backgroundColor"),o=o.parentNode}catch(l){}n=n.blend(r&&"transparent"!==r?r:"_default")}n=n.toRgbaString()}try{e.style[i]=n}catch(l){}}},t.fx.step[i]=function(e){e.colorInit||(e.start=h(e.elem,i),e.end=h(e.end),e.colorInit=!0),t.cssHooks[i].set(e.elem,e.start.transition(e.end,e.pos))}})},h.hook(o),t.cssHooks.borderColor={expand:function(t){var e={};return f(["Top","Right","Bottom","Left"],function(i,s){e["border"+s+"Color"]=t}),e}},a=t.Color.names={aqua:"#00ffff",black:"#000000",blue:"#0000ff",fuchsia:"#ff00ff",gray:"#808080",green:"#008000",lime:"#00ff00",maroon:"#800000",navy:"#000080",olive:"#808000",purple:"#800080",red:"#ff0000",silver:"#c0c0c0",teal:"#008080",white:"#ffffff",yellow:"#ffff00",transparent:[null,null,null,0],_default:"#ffffff"}}(jQuery),function(){function i(e){var i,s,n=e.ownerDocument.defaultView?e.ownerDocument.defaultView.getComputedStyle(e,null):e.currentStyle,a={};if(n&&n.length&&n[0]&&n[n[0]])for(s=n.length;s--;)i=n[s],"string"==typeof n[i]&&(a[t.camelCase(i)]=n[i]);else for(i in n)"string"==typeof n[i]&&(a[i]=n[i]);return a}function s(e,i){var s,n,o={};for(s in i)n=i[s],e[s]!==n&&(a[s]||(t.fx.step[s]||!isNaN(parseFloat(n)))&&(o[s]=n));return o}var n=["add","remove","toggle"],a={border:1,borderBottom:1,borderColor:1,borderLeft:1,borderRight:1,borderTop:1,borderWidth:1,margin:1,padding:1};t.each(["borderLeftStyle","borderRightStyle","borderBottomStyle","borderTopStyle"],function(e,i){t.fx.step[i]=function(t){("none"!==t.end&&!t.setAttr||1===t.pos&&!t.setAttr)&&(jQuery.style(t.elem,i,t.end),t.setAttr=!0)}}),t.fn.addBack||(t.fn.addBack=function(t){return this.add(null==t?this.prevObject:this.prevObject.filter(t))}),t.effects.animateClass=function(e,a,o,r){var l=t.speed(a,o,r);return this.queue(function(){var a,o=t(this),r=o.attr("class")||"",h=l.children?o.find("*").addBack():o;h=h.map(function(){var e=t(this);return{el:e,start:i(this)}}),a=function(){t.each(n,function(t,i){e[i]&&o[i+"Class"](e[i])})},a(),h=h.map(function(){return this.end=i(this.el[0]),this.diff=s(this.start,this.end),this}),o.attr("class",r),h=h.map(function(){var e=this,i=t.Deferred(),s=t.extend({},l,{queue:!1,complete:function(){i.resolve(e)}});return this.el.animate(this.diff,s),i.promise()}),t.when.apply(t,h.get()).done(function(){a(),t.each(arguments,function(){var e=this.el;t.each(this.diff,function(t){e.css(t,"")})}),l.complete.call(o[0])})})},t.fn.extend({addClass:function(e){return function(i,s,n,a){return s?t.effects.animateClass.call(this,{add:i},s,n,a):e.apply(this,arguments)}}(t.fn.addClass),removeClass:function(e){return function(i,s,n,a){return arguments.length>1?t.effects.animateClass.call(this,{remove:i},s,n,a):e.apply(this,arguments)}}(t.fn.removeClass),toggleClass:function(i){return function(s,n,a,o,r){return"boolean"==typeof n||n===e?a?t.effects.animateClass.call(this,n?{add:s}:{remove:s},a,o,r):i.apply(this,arguments):t.effects.animateClass.call(this,{toggle:s},n,a,o)}}(t.fn.toggleClass),switchClass:function(e,i,s,n,a){return t.effects.animateClass.call(this,{add:i,remove:e},s,n,a)}})}(),function(){function s(e,i,s,n){return t.isPlainObject(e)&&(i=e,e=e.effect),e={effect:e},null==i&&(i={}),t.isFunction(i)&&(n=i,s=null,i={}),("number"==typeof i||t.fx.speeds[i])&&(n=s,s=i,i={}),t.isFunction(s)&&(n=s,s=null),i&&t.extend(e,i),s=s||i.duration,e.duration=t.fx.off?0:"number"==typeof s?s:s in t.fx.speeds?t.fx.speeds[s]:t.fx.speeds._default,e.complete=n||i.complete,e}function n(e){return!e||"number"==typeof e||t.fx.speeds[e]?!0:"string"!=typeof e||t.effects.effect[e]?t.isFunction(e)?!0:"object"!=typeof e||e.effect?!1:!0:!0}t.extend(t.effects,{version:"1.10.4",save:function(t,e){for(var s=0;e.length>s;s++)null!==e[s]&&t.data(i+e[s],t[0].style[e[s]])},restore:function(t,s){var n,a;for(a=0;s.length>a;a++)null!==s[a]&&(n=t.data(i+s[a]),n===e&&(n=""),t.css(s[a],n))},setMode:function(t,e){return"toggle"===e&&(e=t.is(":hidden")?"show":"hide"),e},getBaseline:function(t,e){var i,s;switch(t[0]){case"top":i=0;break;case"middle":i=.5;break;case"bottom":i=1;break;default:i=t[0]/e.height}switch(t[1]){case"left":s=0;break;case"center":s=.5;break;case"right":s=1;break;default:s=t[1]/e.width}return{x:s,y:i}},createWrapper:function(e){if(e.parent().is(".ui-effects-wrapper"))return e.parent();var i={width:e.outerWidth(!0),height:e.outerHeight(!0),"float":e.css("float")},s=t("<div></div>").addClass("ui-effects-wrapper").css({fontSize:"100%",background:"transparent",border:"none",margin:0,padding:0}),n={width:e.width(),height:e.height()},a=document.activeElement;try{a.id}catch(o){a=document.body}return e.wrap(s),(e[0]===a||t.contains(e[0],a))&&t(a).focus(),s=e.parent(),"static"===e.css("position")?(s.css({position:"relative"}),e.css({position:"relative"})):(t.extend(i,{position:e.css("position"),zIndex:e.css("z-index")}),t.each(["top","left","bottom","right"],function(t,s){i[s]=e.css(s),isNaN(parseInt(i[s],10))&&(i[s]="auto")}),e.css({position:"relative",top:0,left:0,right:"auto",bottom:"auto"})),e.css(n),s.css(i).show()},removeWrapper:function(e){var i=document.activeElement;return e.parent().is(".ui-effects-wrapper")&&(e.parent().replaceWith(e),(e[0]===i||t.contains(e[0],i))&&t(i).focus()),e},setTransition:function(e,i,s,n){return n=n||{},t.each(i,function(t,i){var a=e.cssUnit(i);a[0]>0&&(n[i]=a[0]*s+a[1])}),n}}),t.fn.extend({effect:function(){function e(e){function s(){t.isFunction(a)&&a.call(n[0]),t.isFunction(e)&&e()}var n=t(this),a=i.complete,r=i.mode;(n.is(":hidden")?"hide"===r:"show"===r)?(n[r](),s()):o.call(n[0],i,s)}var i=s.apply(this,arguments),n=i.mode,a=i.queue,o=t.effects.effect[i.effect];return t.fx.off||!o?n?this[n](i.duration,i.complete):this.each(function(){i.complete&&i.complete.call(this)}):a===!1?this.each(e):this.queue(a||"fx",e)},show:function(t){return function(e){if(n(e))return t.apply(this,arguments);var i=s.apply(this,arguments);return i.mode="show",this.effect.call(this,i)}}(t.fn.show),hide:function(t){return function(e){if(n(e))return t.apply(this,arguments);var i=s.apply(this,arguments);return i.mode="hide",this.effect.call(this,i)}}(t.fn.hide),toggle:function(t){return function(e){if(n(e)||"boolean"==typeof e)return t.apply(this,arguments);var i=s.apply(this,arguments);return i.mode="toggle",this.effect.call(this,i)}}(t.fn.toggle),cssUnit:function(e){var i=this.css(e),s=[];return t.each(["em","px","%","pt"],function(t,e){i.indexOf(e)>0&&(s=[parseFloat(i),e])}),s}})}(),function(){var e={};t.each(["Quad","Cubic","Quart","Quint","Expo"],function(t,i){e[i]=function(e){return Math.pow(e,t+2)}}),t.extend(e,{Sine:function(t){return 1-Math.cos(t*Math.PI/2)},Circ:function(t){return 1-Math.sqrt(1-t*t)},Elastic:function(t){return 0===t||1===t?t:-Math.pow(2,8*(t-1))*Math.sin((80*(t-1)-7.5)*Math.PI/15)},Back:function(t){return t*t*(3*t-2)},Bounce:function(t){for(var e,i=4;((e=Math.pow(2,--i))-1)/11>t;);return 1/Math.pow(4,3-i)-7.5625*Math.pow((3*e-2)/22-t,2)}}),t.each(e,function(e,i){t.easing["easeIn"+e]=i,t.easing["easeOut"+e]=function(t){return 1-i(1-t)},t.easing["easeInOut"+e]=function(t){return.5>t?i(2*t)/2:1-i(-2*t+2)/2}})}()})(jQuery);(function(t){var e=/up|down|vertical/,i=/up|left|vertical|horizontal/;t.effects.effect.blind=function(s,n){var a,o,r,l=t(this),h=["position","top","bottom","left","right","height","width"],c=t.effects.setMode(l,s.mode||"hide"),u=s.direction||"up",d=e.test(u),p=d?"height":"width",f=d?"top":"left",g=i.test(u),m={},v="show"===c;l.parent().is(".ui-effects-wrapper")?t.effects.save(l.parent(),h):t.effects.save(l,h),l.show(),a=t.effects.createWrapper(l).css({overflow:"hidden"}),o=a[p](),r=parseFloat(a.css(f))||0,m[p]=v?o:0,g||(l.css(d?"bottom":"right",0).css(d?"top":"left","auto").css({position:"absolute"}),m[f]=v?r:o+r),v&&(a.css(p,0),g||a.css(f,r+o)),a.animate(m,{duration:s.duration,easing:s.easing,queue:!1,complete:function(){"hide"===c&&l.hide(),t.effects.restore(l,h),t.effects.removeWrapper(l),n()}})}})(jQuery);(function(t){t.effects.effect.bounce=function(e,i){var s,n,a,o=t(this),r=["position","top","bottom","left","right","height","width"],l=t.effects.setMode(o,e.mode||"effect"),h="hide"===l,c="show"===l,u=e.direction||"up",d=e.distance,p=e.times||5,f=2*p+(c||h?1:0),g=e.duration/f,m=e.easing,v="up"===u||"down"===u?"top":"left",_="up"===u||"left"===u,b=o.queue(),y=b.length;for((c||h)&&r.push("opacity"),t.effects.save(o,r),o.show(),t.effects.createWrapper(o),d||(d=o["top"===v?"outerHeight":"outerWidth"]()/3),c&&(a={opacity:1},a[v]=0,o.css("opacity",0).css(v,_?2*-d:2*d).animate(a,g,m)),h&&(d/=Math.pow(2,p-1)),a={},a[v]=0,s=0;p>s;s++)n={},n[v]=(_?"-=":"+=")+d,o.animate(n,g,m).animate(a,g,m),d=h?2*d:d/2;h&&(n={opacity:0},n[v]=(_?"-=":"+=")+d,o.animate(n,g,m)),o.queue(function(){h&&o.hide(),t.effects.restore(o,r),t.effects.removeWrapper(o),i()}),y>1&&b.splice.apply(b,[1,0].concat(b.splice(y,f+1))),o.dequeue()}})(jQuery);(function(t){t.effects.effect.clip=function(e,i){var s,n,a,o=t(this),r=["position","top","bottom","left","right","height","width"],l=t.effects.setMode(o,e.mode||"hide"),h="show"===l,c=e.direction||"vertical",u="vertical"===c,d=u?"height":"width",p=u?"top":"left",f={};t.effects.save(o,r),o.show(),s=t.effects.createWrapper(o).css({overflow:"hidden"}),n="IMG"===o[0].tagName?s:o,a=n[d](),h&&(n.css(d,0),n.css(p,a/2)),f[d]=h?a:0,f[p]=h?0:a/2,n.animate(f,{queue:!1,duration:e.duration,easing:e.easing,complete:function(){h||o.hide(),t.effects.restore(o,r),t.effects.removeWrapper(o),i()}})}})(jQuery);(function(t){t.effects.effect.drop=function(e,i){var s,n=t(this),a=["position","top","bottom","left","right","opacity","height","width"],o=t.effects.setMode(n,e.mode||"hide"),r="show"===o,l=e.direction||"left",h="up"===l||"down"===l?"top":"left",c="up"===l||"left"===l?"pos":"neg",u={opacity:r?1:0};t.effects.save(n,a),n.show(),t.effects.createWrapper(n),s=e.distance||n["top"===h?"outerHeight":"outerWidth"](!0)/2,r&&n.css("opacity",0).css(h,"pos"===c?-s:s),u[h]=(r?"pos"===c?"+=":"-=":"pos"===c?"-=":"+=")+s,n.animate(u,{queue:!1,duration:e.duration,easing:e.easing,complete:function(){"hide"===o&&n.hide(),t.effects.restore(n,a),t.effects.removeWrapper(n),i()}})}})(jQuery);(function(t){t.effects.effect.explode=function(e,i){function s(){b.push(this),b.length===u*d&&n()}function n(){p.css({visibility:"visible"}),t(b).remove(),g||p.hide(),i()}var a,o,r,l,h,c,u=e.pieces?Math.round(Math.sqrt(e.pieces)):3,d=u,p=t(this),f=t.effects.setMode(p,e.mode||"hide"),g="show"===f,m=p.show().css("visibility","hidden").offset(),v=Math.ceil(p.outerWidth()/d),_=Math.ceil(p.outerHeight()/u),b=[];for(a=0;u>a;a++)for(l=m.top+a*_,c=a-(u-1)/2,o=0;d>o;o++)r=m.left+o*v,h=o-(d-1)/2,p.clone().appendTo("body").wrap("<div></div>").css({position:"absolute",visibility:"visible",left:-o*v,top:-a*_}).parent().addClass("ui-effects-explode").css({position:"absolute",overflow:"hidden",width:v,height:_,left:r+(g?h*v:0),top:l+(g?c*_:0),opacity:g?0:1}).animate({left:r+(g?0:h*v),top:l+(g?0:c*_),opacity:g?1:0},e.duration||500,e.easing,s)}})(jQuery);(function(t){t.effects.effect.fade=function(e,i){var s=t(this),n=t.effects.setMode(s,e.mode||"toggle");s.animate({opacity:n},{queue:!1,duration:e.duration,easing:e.easing,complete:i})}})(jQuery);(function(t){t.effects.effect.fold=function(e,i){var s,n,a=t(this),o=["position","top","bottom","left","right","height","width"],r=t.effects.setMode(a,e.mode||"hide"),l="show"===r,h="hide"===r,c=e.size||15,u=/([0-9]+)%/.exec(c),d=!!e.horizFirst,p=l!==d,f=p?["width","height"]:["height","width"],g=e.duration/2,m={},v={};t.effects.save(a,o),a.show(),s=t.effects.createWrapper(a).css({overflow:"hidden"}),n=p?[s.width(),s.height()]:[s.height(),s.width()],u&&(c=parseInt(u[1],10)/100*n[h?0:1]),l&&s.css(d?{height:0,width:c}:{height:c,width:0}),m[f[0]]=l?n[0]:c,v[f[1]]=l?n[1]:0,s.animate(m,g,e.easing).animate(v,g,e.easing,function(){h&&a.hide(),t.effects.restore(a,o),t.effects.removeWrapper(a),i()})}})(jQuery);(function(t){t.effects.effect.highlight=function(e,i){var s=t(this),n=["backgroundImage","backgroundColor","opacity"],a=t.effects.setMode(s,e.mode||"show"),o={backgroundColor:s.css("backgroundColor")};"hide"===a&&(o.opacity=0),t.effects.save(s,n),s.show().css({backgroundImage:"none",backgroundColor:e.color||"#ffff99"}).animate(o,{queue:!1,duration:e.duration,easing:e.easing,complete:function(){"hide"===a&&s.hide(),t.effects.restore(s,n),i()}})}})(jQuery);(function(t){t.effects.effect.pulsate=function(e,i){var s,n=t(this),a=t.effects.setMode(n,e.mode||"show"),o="show"===a,r="hide"===a,l=o||"hide"===a,h=2*(e.times||5)+(l?1:0),c=e.duration/h,u=0,d=n.queue(),p=d.length;for((o||!n.is(":visible"))&&(n.css("opacity",0).show(),u=1),s=1;h>s;s++)n.animate({opacity:u},c,e.easing),u=1-u;n.animate({opacity:u},c,e.easing),n.queue(function(){r&&n.hide(),i()}),p>1&&d.splice.apply(d,[1,0].concat(d.splice(p,h+1))),n.dequeue()}})(jQuery);(function(t){t.effects.effect.puff=function(e,i){var s=t(this),n=t.effects.setMode(s,e.mode||"hide"),a="hide"===n,o=parseInt(e.percent,10)||150,r=o/100,l={height:s.height(),width:s.width(),outerHeight:s.outerHeight(),outerWidth:s.outerWidth()};t.extend(e,{effect:"scale",queue:!1,fade:!0,mode:n,complete:i,percent:a?o:100,from:a?l:{height:l.height*r,width:l.width*r,outerHeight:l.outerHeight*r,outerWidth:l.outerWidth*r}}),s.effect(e)},t.effects.effect.scale=function(e,i){var s=t(this),n=t.extend(!0,{},e),a=t.effects.setMode(s,e.mode||"effect"),o=parseInt(e.percent,10)||(0===parseInt(e.percent,10)?0:"hide"===a?0:100),r=e.direction||"both",l=e.origin,h={height:s.height(),width:s.width(),outerHeight:s.outerHeight(),outerWidth:s.outerWidth()},c={y:"horizontal"!==r?o/100:1,x:"vertical"!==r?o/100:1};n.effect="size",n.queue=!1,n.complete=i,"effect"!==a&&(n.origin=l||["middle","center"],n.restore=!0),n.from=e.from||("show"===a?{height:0,width:0,outerHeight:0,outerWidth:0}:h),n.to={height:h.height*c.y,width:h.width*c.x,outerHeight:h.outerHeight*c.y,outerWidth:h.outerWidth*c.x},n.fade&&("show"===a&&(n.from.opacity=0,n.to.opacity=1),"hide"===a&&(n.from.opacity=1,n.to.opacity=0)),s.effect(n)},t.effects.effect.size=function(e,i){var s,n,a,o=t(this),r=["position","top","bottom","left","right","width","height","overflow","opacity"],l=["position","top","bottom","left","right","overflow","opacity"],h=["width","height","overflow"],c=["fontSize"],u=["borderTopWidth","borderBottomWidth","paddingTop","paddingBottom"],d=["borderLeftWidth","borderRightWidth","paddingLeft","paddingRight"],p=t.effects.setMode(o,e.mode||"effect"),f=e.restore||"effect"!==p,g=e.scale||"both",m=e.origin||["middle","center"],v=o.css("position"),_=f?r:l,b={height:0,width:0,outerHeight:0,outerWidth:0};"show"===p&&o.show(),s={height:o.height(),width:o.width(),outerHeight:o.outerHeight(),outerWidth:o.outerWidth()},"toggle"===e.mode&&"show"===p?(o.from=e.to||b,o.to=e.from||s):(o.from=e.from||("show"===p?b:s),o.to=e.to||("hide"===p?b:s)),a={from:{y:o.from.height/s.height,x:o.from.width/s.width},to:{y:o.to.height/s.height,x:o.to.width/s.width}},("box"===g||"both"===g)&&(a.from.y!==a.to.y&&(_=_.concat(u),o.from=t.effects.setTransition(o,u,a.from.y,o.from),o.to=t.effects.setTransition(o,u,a.to.y,o.to)),a.from.x!==a.to.x&&(_=_.concat(d),o.from=t.effects.setTransition(o,d,a.from.x,o.from),o.to=t.effects.setTransition(o,d,a.to.x,o.to))),("content"===g||"both"===g)&&a.from.y!==a.to.y&&(_=_.concat(c).concat(h),o.from=t.effects.setTransition(o,c,a.from.y,o.from),o.to=t.effects.setTransition(o,c,a.to.y,o.to)),t.effects.save(o,_),o.show(),t.effects.createWrapper(o),o.css("overflow","hidden").css(o.from),m&&(n=t.effects.getBaseline(m,s),o.from.top=(s.outerHeight-o.outerHeight())*n.y,o.from.left=(s.outerWidth-o.outerWidth())*n.x,o.to.top=(s.outerHeight-o.to.outerHeight)*n.y,o.to.left=(s.outerWidth-o.to.outerWidth)*n.x),o.css(o.from),("content"===g||"both"===g)&&(u=u.concat(["marginTop","marginBottom"]).concat(c),d=d.concat(["marginLeft","marginRight"]),h=r.concat(u).concat(d),o.find("*[width]").each(function(){var i=t(this),s={height:i.height(),width:i.width(),outerHeight:i.outerHeight(),outerWidth:i.outerWidth()};f&&t.effects.save(i,h),i.from={height:s.height*a.from.y,width:s.width*a.from.x,outerHeight:s.outerHeight*a.from.y,outerWidth:s.outerWidth*a.from.x},i.to={height:s.height*a.to.y,width:s.width*a.to.x,outerHeight:s.height*a.to.y,outerWidth:s.width*a.to.x},a.from.y!==a.to.y&&(i.from=t.effects.setTransition(i,u,a.from.y,i.from),i.to=t.effects.setTransition(i,u,a.to.y,i.to)),a.from.x!==a.to.x&&(i.from=t.effects.setTransition(i,d,a.from.x,i.from),i.to=t.effects.setTransition(i,d,a.to.x,i.to)),i.css(i.from),i.animate(i.to,e.duration,e.easing,function(){f&&t.effects.restore(i,h)})})),o.animate(o.to,{queue:!1,duration:e.duration,easing:e.easing,complete:function(){0===o.to.opacity&&o.css("opacity",o.from.opacity),"hide"===p&&o.hide(),t.effects.restore(o,_),f||("static"===v?o.css({position:"relative",top:o.to.top,left:o.to.left}):t.each(["top","left"],function(t,e){o.css(e,function(e,i){var s=parseInt(i,10),n=t?o.to.left:o.to.top;return"auto"===i?n+"px":s+n+"px"})})),t.effects.removeWrapper(o),i()}})}})(jQuery);(function(t){t.effects.effect.shake=function(e,i){var s,n=t(this),a=["position","top","bottom","left","right","height","width"],o=t.effects.setMode(n,e.mode||"effect"),r=e.direction||"left",l=e.distance||20,h=e.times||3,c=2*h+1,u=Math.round(e.duration/c),d="up"===r||"down"===r?"top":"left",p="up"===r||"left"===r,f={},g={},m={},v=n.queue(),_=v.length;for(t.effects.save(n,a),n.show(),t.effects.createWrapper(n),f[d]=(p?"-=":"+=")+l,g[d]=(p?"+=":"-=")+2*l,m[d]=(p?"-=":"+=")+2*l,n.animate(f,u,e.easing),s=1;h>s;s++)n.animate(g,u,e.easing).animate(m,u,e.easing);n.animate(g,u,e.easing).animate(f,u/2,e.easing).queue(function(){"hide"===o&&n.hide(),t.effects.restore(n,a),t.effects.removeWrapper(n),i()}),_>1&&v.splice.apply(v,[1,0].concat(v.splice(_,c+1))),n.dequeue()}})(jQuery);(function(t){t.effects.effect.slide=function(e,i){var s,n=t(this),a=["position","top","bottom","left","right","width","height"],o=t.effects.setMode(n,e.mode||"show"),r="show"===o,l=e.direction||"left",h="up"===l||"down"===l?"top":"left",c="up"===l||"left"===l,u={};t.effects.save(n,a),n.show(),s=e.distance||n["top"===h?"outerHeight":"outerWidth"](!0),t.effects.createWrapper(n).css({overflow:"hidden"}),r&&n.css(h,c?isNaN(s)?"-"+s:-s:s),u[h]=(r?c?"+=":"-=":c?"-=":"+=")+s,n.animate(u,{queue:!1,duration:e.duration,easing:e.easing,complete:function(){"hide"===o&&n.hide(),t.effects.restore(n,a),t.effects.removeWrapper(n),i()}})}})(jQuery);(function(t){t.effects.effect.transfer=function(e,i){var s=t(this),n=t(e.to),a="fixed"===n.css("position"),o=t("body"),r=a?o.scrollTop():0,l=a?o.scrollLeft():0,h=n.offset(),c={top:h.top-r,left:h.left-l,height:n.innerHeight(),width:n.innerWidth()},u=s.offset(),d=t("<div class='ui-effects-transfer'></div>").appendTo(document.body).addClass(e.className).css({top:u.top-r,left:u.left-l,height:s.innerHeight(),width:s.innerWidth(),position:a?"fixed":"absolute"}).animate(c,e.duration,e.easing,function(){d.remove(),i()})}})(jQuery);
\ No newline at end of file
--- a/server/python/django/renkanmanager/static/renkanmanager/lib/jquery.js Fri Apr 24 13:05:09 2015 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,9111 +0,0 @@
-/*!
- * jQuery JavaScript Library v2.1.0
- * http://jquery.com/
- *
- * Includes Sizzle.js
- * http://sizzlejs.com/
- *
- * Copyright 2005, 2014 jQuery Foundation, Inc. and other contributors
- * Released under the MIT license
- * http://jquery.org/license
- *
- * Date: 2014-01-23T21:10Z
- */
-
-(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 inherently posses a window with a document
- // (such as Node.js), expose a jQuery-making 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 ) {
-
-// Can't do this because several apps including ASP.NET trace
-// the stack via arguments.caller.callee and Firefox dies if
-// you try to trace through "use strict" call chains. (#13335)
-// Support: Firefox 18+
-//
-
-var arr = [];
-
-var slice = arr.slice;
-
-var concat = arr.concat;
-
-var push = arr.push;
-
-var indexOf = arr.indexOf;
-
-var class2type = {};
-
-var toString = class2type.toString;
-
-var hasOwn = class2type.hasOwnProperty;
-
-var trim = "".trim;
-
-var support = {};
-
-
-
-var
- // Use the correct document accordingly with window argument (sandbox)
- document = window.document,
-
- version = "2.1.0",
-
- // 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 );
- },
-
- // 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 a 'clean' array
- ( num < 0 ? this[ num + this.length ] : this[ num ] ) :
-
- // Return just the object
- 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.
- // (You can seed the arguments with an array of args, but this is
- // only used internally.)
- each: function( callback, args ) {
- return jQuery.each( this, callback, args );
- },
-
- 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(null);
- },
-
- // For internal use only.
- // Behaves like an Array's method, not like a jQuery method.
- push: push,
- sort: arr.sort,
- splice: arr.splice
-};
-
-jQuery.extend = jQuery.fn.extend = function() {
- var options, name, src, copy, copyIsArray, 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,
-
- isWindow: function( obj ) {
- 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
- return obj - parseFloat( obj ) >= 0;
- },
-
- isPlainObject: function( obj ) {
- // Not plain objects:
- // - Any object or value whose internal [[Class]] property is not "[object Object]"
- // - DOM nodes
- // - window
- if ( jQuery.type( obj ) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
- return false;
- }
-
- // Support: Firefox <20
- // The try/catch suppresses exceptions thrown when attempting to access
- // the "constructor" property of certain host objects, ie. |window.location|
- // https://bugzilla.mozilla.org/show_bug.cgi?id=814622
- try {
- if ( obj.constructor &&
- !hasOwn.call( obj.constructor.prototype, "isPrototypeOf" ) ) {
- return false;
- }
- } catch ( e ) {
- return false;
- }
-
- // If the function hasn't returned already, we're confident that
- // |obj| is a plain object, created by {} or constructed with new Object
- return true;
- },
-
- isEmptyObject: function( obj ) {
- var name;
- for ( name in obj ) {
- return false;
- }
- return true;
- },
-
- type: function( obj ) {
- if ( obj == null ) {
- return obj + "";
- }
- // Support: Android < 4.0, iOS < 6 (functionish RegExp)
- return typeof obj === "object" || typeof obj === "function" ?
- class2type[ toString.call(obj) ] || "object" :
- typeof obj;
- },
-
- // Evaluates a script in a global context
- globalEval: function( code ) {
- var script,
- indirect = eval;
-
- code = jQuery.trim( code );
-
- if ( code ) {
- // If the code includes a valid, prologue position
- // strict mode pragma, execute code by injecting a
- // script tag into the document.
- if ( code.indexOf("use strict") === 1 ) {
- script = document.createElement("script");
- script.text = code;
- document.head.appendChild( script ).parentNode.removeChild( script );
- } else {
- // Otherwise, avoid the DOM node creation, insertion
- // and removal by using an indirect global eval
- indirect( code );
- }
- }
- },
-
- // 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();
- },
-
- // args is for internal usage only
- each: function( obj, callback, args ) {
- var value,
- i = 0,
- length = obj.length,
- isArray = isArraylike( obj );
-
- if ( args ) {
- if ( isArray ) {
- for ( ; i < length; i++ ) {
- value = callback.apply( obj[ i ], args );
-
- if ( value === false ) {
- break;
- }
- }
- } else {
- for ( i in obj ) {
- value = callback.apply( obj[ i ], args );
-
- if ( value === false ) {
- break;
- }
- }
- }
-
- // A special, fast, case for the most common use of each
- } else {
- if ( isArray ) {
- for ( ; i < length; i++ ) {
- value = callback.call( obj[ i ], i, obj[ i ] );
-
- if ( value === false ) {
- break;
- }
- }
- } else {
- for ( i in obj ) {
- value = callback.call( obj[ i ], i, obj[ i ] );
-
- if ( value === false ) {
- break;
- }
- }
- }
- }
-
- return obj;
- },
-
- trim: function( text ) {
- return text == null ? "" : trim.call( text );
- },
-
- // 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 ) {
- return arr == null ? -1 : indexOf.call( arr, elem, i );
- },
-
- merge: function( first, second ) {
- var len = +second.length,
- j = 0,
- i = first.length;
-
- for ( ; j < len; j++ ) {
- 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 value,
- i = 0,
- length = elems.length,
- isArray = isArraylike( elems ),
- ret = [];
-
- // Go through the array, translating each of the items to their new values
- if ( isArray ) {
- 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 tmp, args, proxy;
-
- 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: Date.now,
-
- // jQuery.support is not used in Core but other projects attach their
- // properties to it so it needs to exist.
- support: support
-});
-
-// Populate the class2type map
-jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) {
- class2type[ "[object " + name + "]" ] = name.toLowerCase();
-});
-
-function isArraylike( obj ) {
- var length = obj.length,
- type = jQuery.type( obj );
-
- if ( type === "function" || jQuery.isWindow( obj ) ) {
- return false;
- }
-
- if ( obj.nodeType === 1 && length ) {
- return true;
- }
-
- return type === "array" || length === 0 ||
- typeof length === "number" && length > 0 && ( length - 1 ) in obj;
-}
-var Sizzle =
-/*!
- * Sizzle CSS Selector Engine v1.10.16
- * http://sizzlejs.com/
- *
- * Copyright 2013 jQuery Foundation, Inc. and other contributors
- * Released under the MIT license
- * http://jquery.org/license
- *
- * Date: 2014-01-13
- */
-(function( window ) {
-
-var i,
- support,
- Expr,
- getText,
- isXML,
- compile,
- outermostContext,
- sortInput,
- hasDuplicate,
-
- // Local document vars
- setDocument,
- document,
- docElem,
- documentIsHTML,
- rbuggyQSA,
- rbuggyMatches,
- matches,
- contains,
-
- // Instance-specific data
- expando = "sizzle" + -(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
- strundefined = typeof undefined,
- 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 if we can't use a native one
- indexOf = arr.indexOf || function( elem ) {
- var i = 0,
- len = this.length;
- for ( ; i < len; i++ ) {
- if ( this[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
-
- // Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace
- whitespace = "[\\x20\\t\\r\\n\\f]",
- // http://www.w3.org/TR/css3-syntax/#characters
- characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",
-
- // Loosely modeled on CSS identifier characters
- // An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors
- // Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier
- identifier = characterEncoding.replace( "w", "w#" ),
-
- // Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors
- attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace +
- "*(?:([*^$|!~]?=)" + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]",
-
- // Prefer arguments quoted,
- // then not containing pseudos/brackets,
- // then attribute selectors/non-parenthetical expressions,
- // then anything else
- // These preferences are here to reduce the number of selectors
- // needing tokenize in the PSEUDO preFilter
- pseudos = ":(" + characterEncoding + ")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|" + attributes.replace( 3, 8 ) + ")*)|.*)\\)|)",
-
- // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter
- 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( "^#(" + characterEncoding + ")" ),
- "CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ),
- "TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ),
- "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
- // 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 );
- };
-
-// 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 match, elem, m, nodeType,
- // QSA vars
- i, groups, old, nid, newContext, newSelector;
-
- if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) {
- setDocument( context );
- }
-
- context = context || document;
- results = results || [];
-
- if ( !selector || typeof selector !== "string" ) {
- return results;
- }
-
- if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) {
- return [];
- }
-
- if ( documentIsHTML && !seed ) {
-
- // Shortcuts
- if ( (match = rquickExpr.exec( selector )) ) {
- // Speed-up: Sizzle("#ID")
- if ( (m = match[1]) ) {
- if ( nodeType === 9 ) {
- elem = context.getElementById( m );
- // Check parentNode to catch when Blackberry 4.6 returns
- // nodes that are no longer in the document (jQuery #6963)
- if ( elem && elem.parentNode ) {
- // Handle the case where IE, Opera, and Webkit return items
- // by name instead of ID
- if ( elem.id === m ) {
- results.push( elem );
- return results;
- }
- } else {
- return results;
- }
- } else {
- // Context is not a document
- if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) &&
- contains( context, elem ) && elem.id === m ) {
- results.push( elem );
- return results;
- }
- }
-
- // Speed-up: Sizzle("TAG")
- } else if ( match[2] ) {
- push.apply( results, context.getElementsByTagName( selector ) );
- return results;
-
- // Speed-up: Sizzle(".CLASS")
- } else if ( (m = match[3]) && support.getElementsByClassName && context.getElementsByClassName ) {
- push.apply( results, context.getElementsByClassName( m ) );
- return results;
- }
- }
-
- // QSA path
- if ( support.qsa && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) {
- nid = old = expando;
- newContext = context;
- newSelector = nodeType === 9 && selector;
-
- // qSA works strangely on Element-rooted queries
- // We can work around this by specifying an extra ID on the root
- // and working up from there (Thanks to Andrew Dupont for the technique)
- // IE 8 doesn't work on object elements
- if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) {
- groups = tokenize( selector );
-
- if ( (old = context.getAttribute("id")) ) {
- nid = old.replace( rescape, "\\$&" );
- } else {
- context.setAttribute( "id", nid );
- }
- nid = "[id='" + nid + "'] ";
-
- i = groups.length;
- while ( i-- ) {
- groups[i] = nid + toSelector( groups[i] );
- }
- newContext = rsibling.test( selector ) && testContext( context.parentNode ) || context;
- newSelector = groups.join(",");
- }
-
- if ( newSelector ) {
- try {
- push.apply( results,
- newContext.querySelectorAll( newSelector )
- );
- return results;
- } catch(qsaError) {
- } finally {
- if ( !old ) {
- 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 = attrs.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 !== strundefined && 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,
- doc = node ? node.ownerDocument || node : preferredDoc,
- parent = doc.defaultView;
-
- // If no document and documentElement is available, return
- if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) {
- return document;
- }
-
- // Set our document
- document = doc;
- docElem = doc.documentElement;
-
- // Support tests
- documentIsHTML = !isXML( doc );
-
- // Support: IE>8
- // If iframe document is assigned to "document" variable and if iframe has been reloaded,
- // IE will throw "permission denied" error when accessing "document" variable, see jQuery #13936
- // IE6-8 do not support the defaultView property so parent will be undefined
- if ( parent && parent !== parent.top ) {
- // IE11 does not have attachEvent, so all must suffer
- if ( parent.addEventListener ) {
- parent.addEventListener( "unload", function() {
- setDocument();
- }, false );
- } else if ( parent.attachEvent ) {
- parent.attachEvent( "onunload", function() {
- setDocument();
- });
- }
- }
-
- /* 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( doc.createComment("") );
- return !div.getElementsByTagName("*").length;
- });
-
- // Check if getElementsByClassName can be trusted
- support.getElementsByClassName = rnative.test( doc.getElementsByClassName ) && assert(function( div ) {
- div.innerHTML = "<div class='a'></div><div class='a i'></div>";
-
- // Support: Safari<4
- // Catch class over-caching
- div.firstChild.className = "i";
- // Support: Opera<10
- // Catch gEBCN failure to find non-leading classes
- return div.getElementsByClassName("i").length === 2;
- });
-
- // 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 !doc.getElementsByName || !doc.getElementsByName( expando ).length;
- });
-
- // ID find and filter
- if ( support.getById ) {
- Expr.find["ID"] = function( id, context ) {
- if ( typeof context.getElementById !== strundefined && documentIsHTML ) {
- var m = context.getElementById( id );
- // Check parentNode to catch when Blackberry 4.6 returns
- // nodes that are no longer in the document #6963
- return m && m.parentNode ? [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 !== strundefined && elem.getAttributeNode("id");
- return node && node.value === attrId;
- };
- };
- }
-
- // Tag
- Expr.find["TAG"] = support.getElementsByTagName ?
- function( tag, context ) {
- if ( typeof context.getElementsByTagName !== strundefined ) {
- return context.getElementsByTagName( tag );
- }
- } :
- function( tag, context ) {
- var elem,
- tmp = [],
- i = 0,
- 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 !== strundefined && 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( doc.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
- div.innerHTML = "<select t=''><option selected=''></option></select>";
-
- // Support: IE8, Opera 10-12
- // Nothing should be selected when empty strings follow ^= or $= or *=
- if ( div.querySelectorAll("[t^='']").length ) {
- rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" );
- }
-
- // Support: IE8
- // Boolean attributes and "value" are not treated correctly
- if ( !div.querySelectorAll("[selected]").length ) {
- rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" );
- }
-
- // 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");
- }
- });
-
- assert(function( div ) {
- // Support: Windows 8 Native Apps
- // The type and name attributes are restricted during .innerHTML assignment
- var input = doc.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.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 does not implement inclusive descendent
- // 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 === doc || a.ownerDocument === preferredDoc && contains(preferredDoc, a) ) {
- return -1;
- }
- if ( b === doc || b.ownerDocument === preferredDoc && contains(preferredDoc, b) ) {
- return 1;
- }
-
- // Maintain original order
- return sortInput ?
- ( indexOf.call( sortInput, a ) - indexOf.call( 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 === doc ? -1 :
- b === doc ? 1 :
- aup ? -1 :
- bup ? 1 :
- sortInput ?
- ( indexOf.call( sortInput, a ) - indexOf.call( 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 doc;
-};
-
-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 &&
- ( !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[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[5] && match[2];
-
- if ( matchExpr["CHILD"].test( match[0] ) ) {
- return null;
- }
-
- // Accept quoted arguments as-is
- if ( match[3] && match[4] !== undefined ) {
- match[2] = match[4];
-
- // 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 !== strundefined && 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 + " " ).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, outerCache, node, diff, nodeIndex, start,
- dir = simple !== forward ? "nextSibling" : "previousSibling",
- parent = elem.parentNode,
- name = ofType && elem.nodeName.toLowerCase(),
- useCache = !xml && !ofType;
-
- 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
- outerCache = parent[ expando ] || (parent[ expando ] = {});
- cache = outerCache[ type ] || [];
- nodeIndex = cache[0] === dirruns && cache[1];
- diff = cache[0] === dirruns && 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 ) {
- outerCache[ type ] = [ dirruns, nodeIndex, diff ];
- break;
- }
- }
-
- // Use previously-cached element index if available
- } else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) {
- diff = cache[1];
-
- // xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...)
- } else {
- // 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 ) {
- (node[ expando ] || (node[ expando ] = {}))[ 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.call( 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 );
- return !results.pop();
- };
- }),
-
- "has": markFunction(function( selector ) {
- return function( elem ) {
- return Sizzle( selector, elem ).length > 0;
- };
- }),
-
- "contains": markFunction(function( text ) {
- 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();
-
-function tokenize( 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, outerCache,
- newCache = [ dirruns, doneName ];
-
- // We can't set arbitrary data on XML nodes, so they don't benefit from dir 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 ] = {});
- if ( (oldCache = outerCache[ 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
- outerCache[ 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 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.call( 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.call( checkContext, elem ) > -1;
- }, implicitRelative, true ),
- matchers = [ function( elem, context, xml ) {
- return ( !leadingRelative && ( xml || context !== outermostContext ) ) || (
- (checkContext = context).nodeType ?
- matchContext( elem, context, xml ) :
- matchAnyContext( elem, context, xml ) );
- } ];
-
- 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;
- }
-
- // Add elements passing elementMatchers directly to results
- // Keep `i` a string if there are no elements so `matchedCount` will be "00" below
- // Support: IE<9, Safari
- // Tolerate NodeList properties (IE: "length"; Safari: <number>) matching elements by id
- for ( ; i !== len && (elem = elems[i]) != null; i++ ) {
- if ( byElement && elem ) {
- j = 0;
- while ( (matcher = elementMatchers[j++]) ) {
- if ( matcher( elem, context, 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 );
- }
- }
- }
-
- // Apply set filters to unmatched elements
- matchedCount += i;
- 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, group /* 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 ( !group ) {
- group = tokenize( selector );
- }
- i = group.length;
- while ( i-- ) {
- cached = matcherFromTokens( group[i] );
- if ( cached[ expando ] ) {
- setMatchers.push( cached );
- } else {
- elementMatchers.push( cached );
- }
- }
-
- // Cache the compiled function
- cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) );
- }
- return cached;
-};
-
-function multipleContexts( selector, contexts, results ) {
- var i = 0,
- len = contexts.length;
- for ( ; i < len; i++ ) {
- Sizzle( selector, contexts[i], results );
- }
- return results;
-}
-
-function select( selector, context, results, seed ) {
- var i, tokens, token, type, find,
- match = tokenize( selector );
-
- if ( !seed ) {
- // Try to minimize operations if there is only one group
- if ( match.length === 1 ) {
-
- // Take a shortcut and set the context if the root 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;
- }
- 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
- // Provide `match` to avoid retokenization if we modified the selector above
- compile( selector, match )(
- seed,
- context,
- !documentIsHTML,
- results,
- 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
-// 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 = "<a href='#'></a>";
- 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 = "<input/>";
- 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.unique = Sizzle.uniqueSort;
-jQuery.text = Sizzle.getText;
-jQuery.isXMLDoc = Sizzle.isXML;
-jQuery.contains = Sizzle.contains;
-
-
-
-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 ( indexOf.call( qualifier, elem ) >= 0 ) !== 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,
- len = this.length,
- ret = [],
- self = this;
-
- 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 <tag> 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 ) {
- var match, elem;
-
- // HANDLE: $(""), $(null), $(undefined), $(false)
- if ( !selector ) {
- return this;
- }
-
- // Handle HTML strings
- if ( typeof selector === "string" ) {
- if ( selector[0] === "<" && selector[ 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 ) {
- // 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 || rootjQuery ).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 rootjQuery.ready !== "undefined" ?
- rootjQuery.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.extend({
- 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;
- },
-
- sibling: function( n, elem ) {
- var matched = [];
-
- for ( ; n; n = n.nextSibling ) {
- if ( n.nodeType === 1 && n !== elem ) {
- matched.push( n );
- }
- }
-
- return matched;
- }
-});
-
-jQuery.fn.extend({
- has: function( target ) {
- var targets = jQuery( target, this ),
- l = targets.length;
-
- return this.filter(function() {
- var i = 0;
- for ( ; i < l; 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.unique( 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 indexOf.call( jQuery( elem ), this[ 0 ] );
- }
-
- // Locate the position of the desired element
- return indexOf.call( this,
-
- // If it receives a jQuery object, the first element is used
- elem.jquery ? elem[ 0 ] : elem
- );
- },
-
- add: function( selector, context ) {
- return this.pushStack(
- jQuery.unique(
- 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 ) {
- while ( (cur = cur[dir]) && 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 jQuery.dir( elem, "parentNode" );
- },
- parentsUntil: function( elem, i, until ) {
- return jQuery.dir( elem, "parentNode", until );
- },
- next: function( elem ) {
- return sibling( elem, "nextSibling" );
- },
- prev: function( elem ) {
- return sibling( elem, "previousSibling" );
- },
- nextAll: function( elem ) {
- return jQuery.dir( elem, "nextSibling" );
- },
- prevAll: function( elem ) {
- return jQuery.dir( elem, "previousSibling" );
- },
- nextUntil: function( elem, i, until ) {
- return jQuery.dir( elem, "nextSibling", until );
- },
- prevUntil: function( elem, i, until ) {
- return jQuery.dir( elem, "previousSibling", until );
- },
- siblings: function( elem ) {
- return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem );
- },
- children: function( elem ) {
- return jQuery.sibling( elem.firstChild );
- },
- contents: function( elem ) {
- return elem.contentDocument || jQuery.merge( [], elem.childNodes );
- }
-}, function( name, fn ) {
- jQuery.fn[ name ] = function( until, selector ) {
- var matched = jQuery.map( this, fn, until );
-
- if ( name.slice( -5 ) !== "Until" ) {
- selector = until;
- }
-
- if ( selector && typeof selector === "string" ) {
- matched = jQuery.filter( selector, matched );
- }
-
- if ( this.length > 1 ) {
- // Remove duplicates
- if ( !guaranteedUnique[ name ] ) {
- jQuery.unique( matched );
- }
-
- // Reverse order for parents* and prev-derivatives
- if ( rparentsprev.test( name ) ) {
- matched.reverse();
- }
- }
-
- return this.pushStack( matched );
- };
-});
-var rnotwhite = (/\S+/g);
-
-
-
-// String to Object options format cache
-var optionsCache = {};
-
-// Convert String-formatted options into Object-formatted ones and store in cache
-function createOptions( options ) {
- var object = optionsCache[ options ] = {};
- 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" ?
- ( optionsCache[ options ] || createOptions( options ) ) :
- jQuery.extend( {}, options );
-
- var // Last fire value (for non-forgettable lists)
- memory,
- // Flag to know if list was already fired
- fired,
- // Flag to know if list is currently firing
- firing,
- // First callback to fire (used internally by add and fireWith)
- firingStart,
- // End of the loop when firing
- firingLength,
- // Index of currently firing callback (modified by remove if needed)
- firingIndex,
- // Actual callback list
- list = [],
- // Stack of fire calls for repeatable lists
- stack = !options.once && [],
- // Fire callbacks
- fire = function( data ) {
- memory = options.memory && data;
- fired = true;
- firingIndex = firingStart || 0;
- firingStart = 0;
- firingLength = list.length;
- firing = true;
- for ( ; list && firingIndex < firingLength; firingIndex++ ) {
- if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) {
- memory = false; // To prevent further calls using add
- break;
- }
- }
- firing = false;
- if ( list ) {
- if ( stack ) {
- if ( stack.length ) {
- fire( stack.shift() );
- }
- } else if ( memory ) {
- list = [];
- } else {
- self.disable();
- }
- }
- },
- // Actual Callbacks object
- self = {
- // Add a callback or a collection of callbacks to the list
- add: function() {
- if ( list ) {
- // First, we save the current length
- var start = list.length;
- (function add( args ) {
- jQuery.each( args, function( _, arg ) {
- var type = jQuery.type( arg );
- if ( type === "function" ) {
- if ( !options.unique || !self.has( arg ) ) {
- list.push( arg );
- }
- } else if ( arg && arg.length && type !== "string" ) {
- // Inspect recursively
- add( arg );
- }
- });
- })( arguments );
- // Do we need to add the callbacks to the
- // current firing batch?
- if ( firing ) {
- firingLength = list.length;
- // With memory, if we're not firing then
- // we should call right away
- } else if ( memory ) {
- firingStart = start;
- fire( memory );
- }
- }
- return this;
- },
- // Remove a callback from the list
- remove: function() {
- if ( list ) {
- jQuery.each( arguments, function( _, arg ) {
- var index;
- while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) {
- list.splice( index, 1 );
- // Handle firing indexes
- if ( firing ) {
- if ( index <= firingLength ) {
- firingLength--;
- }
- 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 && list.length );
- },
- // Remove all callbacks from the list
- empty: function() {
- list = [];
- firingLength = 0;
- return this;
- },
- // Have the list do nothing anymore
- disable: function() {
- list = stack = memory = undefined;
- return this;
- },
- // Is it disabled?
- disabled: function() {
- return !list;
- },
- // Lock the list in its current state
- lock: function() {
- stack = undefined;
- if ( !memory ) {
- self.disable();
- }
- return this;
- },
- // Is it locked?
- locked: function() {
- return !stack;
- },
- // Call all callbacks with the given context and arguments
- fireWith: function( context, args ) {
- if ( list && ( !fired || stack ) ) {
- args = args || [];
- args = [ context, args.slice ? args.slice() : args ];
- if ( firing ) {
- stack.push( args );
- } else {
- fire( args );
- }
- }
- 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()
- .done( newDefer.resolve )
- .fail( newDefer.reject )
- .progress( newDefer.notify );
- } 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()
- .done( updateFunc( i, resolveContexts, resolveValues ) )
- .fail( deferred.reject )
- .progress( updateFunc( i, progressContexts, progressValues ) );
- } 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.trigger ) {
- jQuery( document ).trigger("ready").off("ready");
- }
- }
-});
-
-/**
- * The ready event handler and self cleanup method
- */
-function completed() {
- document.removeEventListener( "DOMContentLoaded", completed, false );
- window.removeEventListener( "load", completed, false );
- 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.
- // we once tried to use readyState "interactive" here, but it caused issues like the one
- // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15
- if ( document.readyState === "complete" ) {
- // Handle it asynchronously to allow scripts the opportunity to delay ready
- setTimeout( jQuery.ready );
-
- } else {
-
- // Use the handy event callback
- document.addEventListener( "DOMContentLoaded", completed, false );
-
- // A fallback to window.onload, that will always work
- window.addEventListener( "load", completed, false );
- }
- }
- return readyList.promise( obj );
-};
-
-// Kick off the DOM ready check even if the user does not
-jQuery.ready.promise();
-
-
-
-
-// Multifunctional method to get and set values of a collection
-// The value/s can optionally be executed if it's a function
-var access = jQuery.access = function( elems, fn, key, value, chainable, emptyGet, raw ) {
- var i = 0,
- len = elems.length,
- bulk = key == null;
-
- // Sets many values
- if ( jQuery.type( key ) === "object" ) {
- chainable = true;
- for ( i in key ) {
- jQuery.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 < len; i++ ) {
- fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) );
- }
- }
- }
-
- return chainable ?
- elems :
-
- // Gets
- bulk ?
- fn.call( elems ) :
- len ? fn( elems[0], key ) : emptyGet;
-};
-
-
-/**
- * Determines whether an object can have data
- */
-jQuery.acceptData = function( owner ) {
- // Accepts only:
- // - Node
- // - Node.ELEMENT_NODE
- // - Node.DOCUMENT_NODE
- // - Object
- // - Any
- /* jshint -W018 */
- return owner.nodeType === 1 || owner.nodeType === 9 || !( +owner.nodeType );
-};
-
-
-function Data() {
- // Support: Android < 4,
- // Old WebKit does not have Object.preventExtensions/freeze method,
- // return new empty object instead with no [[set]] accessor
- Object.defineProperty( this.cache = {}, 0, {
- get: function() {
- return {};
- }
- });
-
- this.expando = jQuery.expando + Math.random();
-}
-
-Data.uid = 1;
-Data.accepts = jQuery.acceptData;
-
-Data.prototype = {
- key: function( owner ) {
- // We can accept data for non-element nodes in modern browsers,
- // but we should not, see #8335.
- // Always return the key for a frozen object.
- if ( !Data.accepts( owner ) ) {
- return 0;
- }
-
- var descriptor = {},
- // Check if the owner object already has a cache key
- unlock = owner[ this.expando ];
-
- // If not, create one
- if ( !unlock ) {
- unlock = Data.uid++;
-
- // Secure it in a non-enumerable, non-writable property
- try {
- descriptor[ this.expando ] = { value: unlock };
- Object.defineProperties( owner, descriptor );
-
- // Support: Android < 4
- // Fallback to a less secure definition
- } catch ( e ) {
- descriptor[ this.expando ] = unlock;
- jQuery.extend( owner, descriptor );
- }
- }
-
- // Ensure the cache object
- if ( !this.cache[ unlock ] ) {
- this.cache[ unlock ] = {};
- }
-
- return unlock;
- },
- set: function( owner, data, value ) {
- var prop,
- // There may be an unlock assigned to this node,
- // if there is no entry for this "owner", create one inline
- // and set the unlock as though an owner entry had always existed
- unlock = this.key( owner ),
- cache = this.cache[ unlock ];
-
- // Handle: [ owner, key, value ] args
- if ( typeof data === "string" ) {
- cache[ data ] = value;
-
- // Handle: [ owner, { properties } ] args
- } else {
- // Fresh assignments by object are shallow copied
- if ( jQuery.isEmptyObject( cache ) ) {
- jQuery.extend( this.cache[ unlock ], data );
- // Otherwise, copy the properties one-by-one to the cache object
- } else {
- for ( prop in data ) {
- cache[ prop ] = data[ prop ];
- }
- }
- }
- return cache;
- },
- get: function( owner, key ) {
- // Either a valid cache is found, or will be created.
- // New caches will be created and the unlock returned,
- // allowing direct access to the newly created
- // empty data object. A valid owner object must be provided.
- var cache = this.cache[ this.key( owner ) ];
-
- return key === undefined ?
- cache : cache[ key ];
- },
- access: function( owner, key, value ) {
- var stored;
- // In cases where either:
- //
- // 1. No key was specified
- // 2. A string key was specified, but no value provided
- //
- // Take the "read" path and allow the get method to determine
- // which value to return, respectively either:
- //
- // 1. The entire cache object
- // 2. The data stored at the key
- //
- if ( key === undefined ||
- ((key && typeof key === "string") && value === undefined) ) {
-
- stored = this.get( owner, key );
-
- return stored !== undefined ?
- stored : this.get( owner, jQuery.camelCase(key) );
- }
-
- // [*]When the key is not a string, or both a key and value
- // are specified, set or extend (existing objects) with either:
- //
- // 1. An object of properties
- // 2. A key and value
- //
- this.set( owner, key, value );
-
- // Since the "set" path can have two possible entry points
- // return the expected data based on which path was taken[*]
- return value !== undefined ? value : key;
- },
- remove: function( owner, key ) {
- var i, name, camel,
- unlock = this.key( owner ),
- cache = this.cache[ unlock ];
-
- if ( key === undefined ) {
- this.cache[ unlock ] = {};
-
- } else {
- // Support array or space separated string of keys
- if ( jQuery.isArray( key ) ) {
- // 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 = key.concat( key.map( jQuery.camelCase ) );
- } else {
- camel = jQuery.camelCase( key );
- // Try the string as a key before any manipulation
- if ( key in cache ) {
- name = [ key, camel ];
- } else {
- // If a key with the spaces exists, use it.
- // Otherwise, create an array by matching non-whitespace
- name = camel;
- name = name in cache ?
- [ name ] : ( name.match( rnotwhite ) || [] );
- }
- }
-
- i = name.length;
- while ( i-- ) {
- delete cache[ name[ i ] ];
- }
- }
- },
- hasData: function( owner ) {
- return !jQuery.isEmptyObject(
- this.cache[ owner[ this.expando ] ] || {}
- );
- },
- discard: function( owner ) {
- if ( owner[ this.expando ] ) {
- delete this.cache[ owner[ this.expando ] ];
- }
- }
-};
-var data_priv = new Data();
-
-var data_user = new Data();
-
-
-
-/*
- Implementation Summary
-
- 1. Enforce API surface and semantic compatibility with 1.9.x branch
- 2. Improve the module's maintainability by reducing the storage
- paths to a single mechanism.
- 3. Use the same single mechanism to support "private" and "user" data.
- 4. _Never_ expose "private" data to user code (TODO: Drop _data, _removeData)
- 5. Avoid exposing implementation details on user objects (eg. expando properties)
- 6. Provide a clear path for implementation upgrade to WeakMap in 2014
-*/
-var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,
- rmultiDash = /([A-Z])/g;
-
-function dataAttr( elem, key, data ) {
- var name;
-
- // If nothing was found internally, try to fetch any
- // data from the HTML5 data-* attribute
- if ( data === undefined && elem.nodeType === 1 ) {
- 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
- data_user.set( elem, key, data );
- } else {
- data = undefined;
- }
- }
- return data;
-}
-
-jQuery.extend({
- hasData: function( elem ) {
- return data_user.hasData( elem ) || data_priv.hasData( elem );
- },
-
- data: function( elem, name, data ) {
- return data_user.access( elem, name, data );
- },
-
- removeData: function( elem, name ) {
- data_user.remove( elem, name );
- },
-
- // TODO: Now that all calls to _data and _removeData have been replaced
- // with direct calls to data_priv methods, these can be deprecated.
- _data: function( elem, name, data ) {
- return data_priv.access( elem, name, data );
- },
-
- _removeData: function( elem, name ) {
- data_priv.remove( elem, name );
- }
-});
-
-jQuery.fn.extend({
- data: function( key, value ) {
- var i, name, data,
- elem = this[ 0 ],
- attrs = elem && elem.attributes;
-
- // Gets all values
- if ( key === undefined ) {
- if ( this.length ) {
- data = data_user.get( elem );
-
- if ( elem.nodeType === 1 && !data_priv.get( elem, "hasDataAttrs" ) ) {
- i = attrs.length;
- while ( i-- ) {
- name = attrs[ i ].name;
-
- if ( name.indexOf( "data-" ) === 0 ) {
- name = jQuery.camelCase( name.slice(5) );
- dataAttr( elem, name, data[ name ] );
- }
- }
- data_priv.set( elem, "hasDataAttrs", true );
- }
- }
-
- return data;
- }
-
- // Sets multiple values
- if ( typeof key === "object" ) {
- return this.each(function() {
- data_user.set( this, key );
- });
- }
-
- return access( this, function( value ) {
- var data,
- camelKey = jQuery.camelCase( key );
-
- // The calling jQuery object (element matches) is not empty
- // (and therefore has an element appears at this[ 0 ]) and the
- // `value` parameter was not undefined. An empty jQuery object
- // will result in `undefined` for elem = this[ 0 ] which will
- // throw an exception if an attempt to read a data cache is made.
- if ( elem && value === undefined ) {
- // Attempt to get data from the cache
- // with the key as-is
- data = data_user.get( elem, key );
- if ( data !== undefined ) {
- return data;
- }
-
- // Attempt to get data from the cache
- // with the key camelized
- data = data_user.get( elem, camelKey );
- if ( data !== undefined ) {
- return data;
- }
-
- // Attempt to "discover" the data in
- // HTML5 custom data-* attrs
- data = dataAttr( elem, camelKey, undefined );
- if ( data !== undefined ) {
- return data;
- }
-
- // We tried really hard, but the data doesn't exist.
- return;
- }
-
- // Set the data...
- this.each(function() {
- // First, attempt to store a copy or reference of any
- // data that might've been store with a camelCased key.
- var data = data_user.get( this, camelKey );
-
- // For HTML5 data-* attribute interop, we have to
- // store property names with dashes in a camelCase form.
- // This might not apply to all properties...*
- data_user.set( this, camelKey, value );
-
- // *... In the case of properties that might _actually_
- // have dashes, we need to also store a copy of that
- // unchanged property.
- if ( key.indexOf("-") !== -1 && data !== undefined ) {
- data_user.set( this, key, value );
- }
- });
- }, null, value, arguments.length > 1, null, true );
- },
-
- removeData: function( key ) {
- return this.each(function() {
- data_user.remove( this, key );
- });
- }
-});
-
-
-jQuery.extend({
- queue: function( elem, type, data ) {
- var queue;
-
- if ( elem ) {
- type = ( type || "fx" ) + "queue";
- queue = data_priv.get( elem, type );
-
- // Speed up dequeue by getting out quickly if this is just a lookup
- if ( data ) {
- if ( !queue || jQuery.isArray( data ) ) {
- queue = data_priv.access( 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 data_priv.get( elem, key ) || data_priv.access( elem, key, {
- empty: jQuery.Callbacks("once memory").add(function() {
- data_priv.remove( elem, [ type + "queue", 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 = data_priv.get( elements[ i ], type + "queueHooks" );
- if ( tmp && tmp.empty ) {
- count++;
- tmp.empty.add( resolve );
- }
- }
- resolve();
- return defer.promise( obj );
- }
-});
-var pnum = (/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/).source;
-
-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 );
- };
-
-var rcheckableType = (/^(?:checkbox|radio)$/i);
-
-
-
-(function() {
- var fragment = document.createDocumentFragment(),
- div = fragment.appendChild( document.createElement( "div" ) );
-
- // #11217 - WebKit loses check when the name is after the checked attribute
- div.innerHTML = "<input type='radio' checked='checked' name='t'/>";
-
- // 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;
-
- // Make sure textarea (and checkbox) defaultValue is properly cloned
- // Support: IE9-IE11+
- div.innerHTML = "<textarea>x</textarea>";
- support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue;
-})();
-var strundefined = typeof undefined;
-
-
-
-support.focusinBubbles = "onfocusin" in window;
-
-
-var
- rkeyEvent = /^key/,
- rmouseEvent = /^(?:mouse|contextmenu)|click/,
- rfocusMorph = /^(?:focusinfocus|focusoutblur)$/,
- rtypenamespace = /^([^.]*)(?:\.(.+)|)$/;
-
-function returnTrue() {
- return true;
-}
-
-function returnFalse() {
- return false;
-}
-
-function safeActiveElement() {
- try {
- return document.activeElement;
- } catch ( err ) { }
-}
-
-/*
- * 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 handleObjIn, eventHandle, tmp,
- events, t, handleObj,
- special, handlers, type, namespaces, origType,
- elemData = data_priv.get( 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 !== strundefined && jQuery.event.triggered !== e.type ?
- jQuery.event.dispatch.apply( elem, arguments ) : undefined;
- };
- }
-
- // 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 if the special events handler returns false
- if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) {
- if ( elem.addEventListener ) {
- elem.addEventListener( type, eventHandle, false );
- }
- }
- }
-
- 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;
- }
-
- },
-
- // Detach an event or set of events from an element
- remove: function( elem, types, handler, selector, mappedTypes ) {
-
- var j, origCount, tmp,
- events, t, handleObj,
- special, handlers, type, namespaces, origType,
- elemData = data_priv.hasData( elem ) && data_priv.get( 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;
- data_priv.remove( elem, "events" );
- }
- },
-
- trigger: function( event, data, elem, onlyHandlers ) {
-
- var i, cur, tmp, bubbleType, ontype, handle, special,
- 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(".") >= 0 ) {
- // 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.namespace_re = 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 = ( data_priv.get( cur, "events" ) || {} )[ event.type ] && data_priv.get( cur, "handle" );
- if ( handle ) {
- handle.apply( cur, data );
- }
-
- // Native handler
- handle = ontype && cur[ ontype ];
- if ( handle && handle.apply && jQuery.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) &&
- jQuery.acceptData( elem ) ) {
-
- // Call a native DOM method on the target with the same name name as the event.
- // Don't do default actions on window, that's where global variables be (#6170)
- if ( ontype && jQuery.isFunction( 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;
- elem[ type ]();
- 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 = ( data_priv.get( 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.namespace_re || event.namespace_re.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;
-
- // Find delegate handlers
- // Black-hole SVG <use> instance trees (#13180)
- // Avoid non-left-click bubbling in Firefox (#3861)
- if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) {
-
- for ( ; cur !== this; cur = cur.parentNode || this ) {
-
- // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764)
- if ( 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 ) >= 0 :
- 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;
- },
-
- // Includes some event props shared by KeyEvent and MouseEvent
- props: "altKey bubbles cancelable ctrlKey currentTarget 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 offsetX offsetY pageX pageY screenX screenY toElement".split(" "),
- filter: function( event, original ) {
- var eventDoc, doc, body,
- button = original.button;
-
- // 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 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;
- }
- },
-
- 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: Cordova 2.5 (WebKit) (#13255)
- // All events should have a target; Cordova deviceready doesn't
- if ( !event.target ) {
- event.target = document;
- }
-
- // Support: Safari 6.0+, Chrome < 28
- // Target should not be a text node (#504, #13143)
- if ( event.target.nodeType === 3 ) {
- event.target = event.target.parentNode;
- }
-
- return fixHook.filter ? fixHook.filter( event, originalEvent ) : 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 ) {
- this.focus();
- return false;
- }
- },
- 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 ( this.type === "checkbox" && this.click && jQuery.nodeName( this, "input" ) ) {
- 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.returnValue = event.result;
- }
- }
- }
- },
-
- simulate: function( type, elem, event, bubble ) {
- // Piggyback on a donor event to simulate a different one.
- // Fake originalEvent to avoid donor's stopPropagation, but if the
- // simulated event prevents default then we do the same on the donor.
- var e = jQuery.extend(
- new jQuery.Event(),
- event,
- {
- type: type,
- isSimulated: true,
- originalEvent: {}
- }
- );
- if ( bubble ) {
- jQuery.event.trigger( e, null, elem );
- } else {
- jQuery.event.dispatch.call( elem, e );
- }
- if ( e.isDefaultPrevented() ) {
- event.preventDefault();
- }
- }
-};
-
-jQuery.removeEvent = function( elem, type, handle ) {
- if ( elem.removeEventListener ) {
- elem.removeEventListener( type, handle, false );
- }
-};
-
-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 ||
- // Support: Android < 4.0
- src.defaultPrevented === undefined &&
- src.getPreventDefault && src.getPreventDefault() ?
- 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 = {
- isDefaultPrevented: returnFalse,
- isPropagationStopped: returnFalse,
- isImmediatePropagationStopped: returnFalse,
-
- preventDefault: function() {
- var e = this.originalEvent;
-
- this.isDefaultPrevented = returnTrue;
-
- if ( e && e.preventDefault ) {
- e.preventDefault();
- }
- },
- stopPropagation: function() {
- var e = this.originalEvent;
-
- this.isPropagationStopped = returnTrue;
-
- if ( e && e.stopPropagation ) {
- e.stopPropagation();
- }
- },
- stopImmediatePropagation: function() {
- this.isImmediatePropagationStopped = returnTrue;
- this.stopPropagation();
- }
-};
-
-// Create mouseenter/leave events using mouseover/out and event-time checks
-// Support: Chrome 15+
-jQuery.each({
- mouseenter: "mouseover",
- mouseleave: "mouseout"
-}, 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 mousenter/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;
- }
- };
-});
-
-// Create "bubbling" focus and blur events
-// Support: Firefox, Chrome, Safari
-if ( !support.focusinBubbles ) {
- 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 ), true );
- };
-
- jQuery.event.special[ fix ] = {
- setup: function() {
- var doc = this.ownerDocument || this,
- attaches = data_priv.access( doc, fix );
-
- if ( !attaches ) {
- doc.addEventListener( orig, handler, true );
- }
- data_priv.access( doc, fix, ( attaches || 0 ) + 1 );
- },
- teardown: function() {
- var doc = this.ownerDocument || this,
- attaches = data_priv.access( doc, fix ) - 1;
-
- if ( !attaches ) {
- doc.removeEventListener( orig, handler, true );
- data_priv.remove( doc, fix );
-
- } else {
- data_priv.access( doc, fix, attaches );
- }
- }
- };
- });
-}
-
-jQuery.fn.extend({
-
- on: function( types, selector, data, fn, /*INTERNAL*/ 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 ) {
- this.on( type, selector, data, types[ type ], one );
- }
- return this;
- }
-
- 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 this;
- }
-
- 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 this.each( function() {
- jQuery.event.add( this, types, fn, data, selector );
- });
- },
- one: function( types, selector, data, fn ) {
- return this.on( 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
- rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,
- rtagName = /<([\w:]+)/,
- rhtml = /<|&#?\w+;/,
- rnoInnerhtml = /<(?:script|style|link)/i,
- // checked="checked" or checked
- rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
- rscriptType = /^$|\/(?:java|ecma)script/i,
- rscriptTypeMasked = /^true\/(.*)/,
- rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,
-
- // We have to close these tags to support XHTML (#13200)
- wrapMap = {
-
- // Support: IE 9
- option: [ 1, "<select multiple='multiple'>", "</select>" ],
-
- thead: [ 1, "<table>", "</table>" ],
- col: [ 2, "<table><colgroup>", "</colgroup></table>" ],
- tr: [ 2, "<table><tbody>", "</tbody></table>" ],
- td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],
-
- _default: [ 0, "", "" ]
- };
-
-// Support: IE 9
-wrapMap.optgroup = wrapMap.option;
-
-wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
-wrapMap.th = wrapMap.td;
-
-// Support: 1.x compatibility
-// 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 = (elem.getAttribute("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;
-}
-
-// Mark scripts as having already been evaluated
-function setGlobalEval( elems, refElements ) {
- var i = 0,
- l = elems.length;
-
- for ( ; i < l; i++ ) {
- data_priv.set(
- elems[ i ], "globalEval", !refElements || data_priv.get( refElements[ i ], "globalEval" )
- );
- }
-}
-
-function cloneCopyEvent( src, dest ) {
- var i, l, type, pdataOld, pdataCur, udataOld, udataCur, events;
-
- if ( dest.nodeType !== 1 ) {
- return;
- }
-
- // 1. Copy private data: events, handlers, etc.
- if ( data_priv.hasData( src ) ) {
- pdataOld = data_priv.access( src );
- pdataCur = data_priv.set( dest, pdataOld );
- events = pdataOld.events;
-
- if ( events ) {
- delete pdataCur.handle;
- pdataCur.events = {};
-
- for ( type in events ) {
- for ( i = 0, l = events[ type ].length; i < l; i++ ) {
- jQuery.event.add( dest, type, events[ type ][ i ] );
- }
- }
- }
- }
-
- // 2. Copy user data
- if ( data_user.hasData( src ) ) {
- udataOld = data_user.access( src );
- udataCur = jQuery.extend( {}, udataOld );
-
- data_user.set( dest, udataCur );
- }
-}
-
-function getAll( context, tag ) {
- var ret = context.getElementsByTagName ? context.getElementsByTagName( tag || "*" ) :
- context.querySelectorAll ? context.querySelectorAll( tag || "*" ) :
- [];
-
- return tag === undefined || tag && jQuery.nodeName( context, tag ) ?
- jQuery.merge( [ context ], ret ) :
- ret;
-}
-
-// Support: IE >= 9
-function fixInput( src, dest ) {
- var nodeName = dest.nodeName.toLowerCase();
-
- // Fails to persist the checked state of a cloned checkbox or radio button.
- if ( nodeName === "input" && rcheckableType.test( src.type ) ) {
- dest.checked = src.checked;
-
- // Fails to return the selected option to the default selected state when cloning options
- } else if ( nodeName === "input" || nodeName === "textarea" ) {
- dest.defaultValue = src.defaultValue;
- }
-}
-
-jQuery.extend({
- clone: function( elem, dataAndEvents, deepDataAndEvents ) {
- var i, l, srcElements, destElements,
- clone = elem.cloneNode( true ),
- inPage = jQuery.contains( elem.ownerDocument, elem );
-
- // Support: IE >= 9
- // Fix Cloning issues
- if ( !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 );
-
- for ( i = 0, l = srcElements.length; i < l; i++ ) {
- fixInput( srcElements[ i ], 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, l = srcElements.length; i < l; i++ ) {
- cloneCopyEvent( srcElements[ i ], destElements[ i ] );
- }
- } else {
- cloneCopyEvent( elem, clone );
- }
- }
-
- // Preserve script evaluation history
- destElements = getAll( clone, "script" );
- if ( destElements.length > 0 ) {
- setGlobalEval( destElements, !inPage && getAll( elem, "script" ) );
- }
-
- // Return the cloned set
- return clone;
- },
-
- buildFragment: function( elems, context, scripts, selection ) {
- var elem, tmp, tag, wrap, contains, j,
- fragment = context.createDocumentFragment(),
- nodes = [],
- i = 0,
- l = elems.length;
-
- for ( ; i < l; i++ ) {
- elem = elems[ i ];
-
- if ( elem || elem === 0 ) {
-
- // Add nodes directly
- if ( jQuery.type( elem ) === "object" ) {
- // Support: QtWebKit
- // jQuery.merge because push.apply(_, arraylike) throws
- jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem );
-
- // Convert non-html into a text node
- } else if ( !rhtml.test( elem ) ) {
- nodes.push( context.createTextNode( elem ) );
-
- // Convert html into DOM nodes
- } else {
- tmp = tmp || fragment.appendChild( context.createElement("div") );
-
- // Deserialize a standard representation
- tag = ( rtagName.exec( elem ) || [ "", "" ] )[ 1 ].toLowerCase();
- wrap = wrapMap[ tag ] || wrapMap._default;
- tmp.innerHTML = wrap[ 1 ] + elem.replace( rxhtmlTag, "<$1></$2>" ) + wrap[ 2 ];
-
- // Descend through wrappers to the right content
- j = wrap[ 0 ];
- while ( j-- ) {
- tmp = tmp.lastChild;
- }
-
- // Support: QtWebKit
- // jQuery.merge because push.apply(_, arraylike) throws
- jQuery.merge( nodes, tmp.childNodes );
-
- // Remember the top-level container
- tmp = fragment.firstChild;
-
- // Fixes #12346
- // Support: Webkit, IE
- tmp.textContent = "";
- }
- }
- }
-
- // Remove wrapper from fragment
- fragment.textContent = "";
-
- i = 0;
- while ( (elem = nodes[ i++ ]) ) {
-
- // #4087 - If origin and destination elements are the same, and this is
- // that element, do not do anything
- if ( selection && jQuery.inArray( elem, selection ) !== -1 ) {
- continue;
- }
-
- contains = jQuery.contains( elem.ownerDocument, elem );
-
- // Append to fragment
- tmp = getAll( fragment.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 );
- }
- }
- }
- }
-
- return fragment;
- },
-
- cleanData: function( elems ) {
- var data, elem, events, type, key, j,
- special = jQuery.event.special,
- i = 0;
-
- for ( ; (elem = elems[ i ]) !== undefined; i++ ) {
- if ( jQuery.acceptData( elem ) ) {
- key = elem[ data_priv.expando ];
-
- if ( key && (data = data_priv.cache[ key ]) ) {
- events = Object.keys( data.events || {} );
- if ( events.length ) {
- for ( j = 0; (type = events[j]) !== undefined; j++ ) {
- 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 );
- }
- }
- }
- if ( data_priv.cache[ key ] ) {
- // Discard any remaining `private` data
- delete data_priv.cache[ key ];
- }
- }
- }
- // Discard any remaining `user` data
- delete data_user.cache[ elem[ data_user.expando ] ];
- }
- }
-});
-
-jQuery.fn.extend({
- text: function( value ) {
- return access( this, function( value ) {
- return value === undefined ?
- jQuery.text( this ) :
- this.empty().each(function() {
- if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
- this.textContent = value;
- }
- });
- }, null, value, arguments.length );
- },
-
- append: function() {
- return this.domManip( arguments, function( elem ) {
- if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
- var target = manipulationTarget( this, elem );
- target.appendChild( elem );
- }
- });
- },
-
- prepend: function() {
- return this.domManip( 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 this.domManip( arguments, function( elem ) {
- if ( this.parentNode ) {
- this.parentNode.insertBefore( elem, this );
- }
- });
- },
-
- after: function() {
- return this.domManip( arguments, function( elem ) {
- if ( this.parentNode ) {
- this.parentNode.insertBefore( elem, this.nextSibling );
- }
- });
- },
-
- remove: function( selector, keepData /* Internal Use Only */ ) {
- var elem,
- elems = selector ? jQuery.filter( selector, this ) : this,
- i = 0;
-
- for ( ; (elem = elems[i]) != null; i++ ) {
- if ( !keepData && elem.nodeType === 1 ) {
- jQuery.cleanData( getAll( elem ) );
- }
-
- if ( elem.parentNode ) {
- if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) {
- setGlobalEval( getAll( elem, "script" ) );
- }
- elem.parentNode.removeChild( elem );
- }
- }
-
- return this;
- },
-
- empty: function() {
- var elem,
- i = 0;
-
- for ( ; (elem = this[i]) != null; i++ ) {
- if ( elem.nodeType === 1 ) {
-
- // Prevent memory leaks
- jQuery.cleanData( getAll( elem, false ) );
-
- // Remove any remaining nodes
- elem.textContent = "";
- }
- }
-
- 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 && elem.nodeType === 1 ) {
- return elem.innerHTML;
- }
-
- // See if we can take a shortcut and just use innerHTML
- if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
- !wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) {
-
- value = value.replace( rxhtmlTag, "<$1></$2>" );
-
- try {
- for ( ; i < l; i++ ) {
- elem = this[ i ] || {};
-
- // Remove element nodes and prevent memory leaks
- 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 arg = arguments[ 0 ];
-
- // Make the changes, replacing each context element with the new content
- this.domManip( arguments, function( elem ) {
- arg = this.parentNode;
-
- jQuery.cleanData( getAll( this ) );
-
- if ( arg ) {
- arg.replaceChild( elem, this );
- }
- });
-
- // Force removal if there was no new content (e.g., from empty arguments)
- return arg && (arg.length || arg.nodeType) ? this : this.remove();
- },
-
- detach: function( selector ) {
- return this.remove( selector, true );
- },
-
- domManip: function( args, callback ) {
-
- // Flatten any nested arrays
- args = concat.apply( [], args );
-
- var fragment, first, scripts, hasScripts, node, doc,
- i = 0,
- l = this.length,
- set = this,
- 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 this.each(function( index ) {
- var self = set.eq( index );
- if ( isFunction ) {
- args[ 0 ] = value.call( this, index, self.html() );
- }
- self.domManip( args, callback );
- });
- }
-
- if ( l ) {
- fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, this );
- first = fragment.firstChild;
-
- if ( fragment.childNodes.length === 1 ) {
- fragment = first;
- }
-
- if ( first ) {
- 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: QtWebKit
- // jQuery.merge because push.apply(_, arraylike) throws
- jQuery.merge( scripts, getAll( node, "script" ) );
- }
- }
-
- callback.call( this[ 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 || "" ) &&
- !data_priv.access( 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.textContent.replace( rcleanScript, "" ) );
- }
- }
- }
- }
- }
- }
-
- return this;
- }
-});
-
-jQuery.each({
- appendTo: "append",
- prependTo: "prepend",
- insertBefore: "before",
- insertAfter: "after",
- replaceAll: "replaceWith"
-}, function( name, original ) {
- jQuery.fn[ name ] = function( selector ) {
- var elems,
- ret = [],
- insert = jQuery( selector ),
- last = insert.length - 1,
- i = 0;
-
- for ( ; i <= last; i++ ) {
- elems = i === last ? this : this.clone( true );
- jQuery( insert[ i ] )[ original ]( elems );
-
- // Support: QtWebKit
- // .get() because push.apply(_, arraylike) throws
- push.apply( ret, elems.get() );
- }
-
- return this.pushStack( ret );
- };
-});
-
-
-var iframe,
- elemdisplay = {};
-
-/**
- * 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 ),
-
- // getDefaultComputedStyle might be reliably used only on attached element
- display = window.getDefaultComputedStyle ?
-
- // Use of this method is a temporary fix (more like optmization) until something better comes along,
- // since it was removed from specification and supported only in FF
- window.getDefaultComputedStyle( elem[ 0 ] ).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( "<iframe frameborder='0' width='0' height='0'/>" )).appendTo( doc.documentElement );
-
- // Always write a new HTML skeleton so Webkit and Firefox don't choke on reuse
- doc = iframe[ 0 ].contentDocument;
-
- // Support: IE
- doc.write();
- doc.close();
-
- display = actualDisplay( nodeName, doc );
- iframe.detach();
- }
-
- // Store the correct default display
- elemdisplay[ nodeName ] = display;
- }
-
- return display;
-}
-var rmargin = (/^margin/);
-
-var rnumnonpx = new RegExp( "^(" + pnum + ")(?!px)[a-z%]+$", "i" );
-
-var getStyles = function( elem ) {
- return elem.ownerDocument.defaultView.getComputedStyle( elem, null );
- };
-
-
-
-function curCSS( elem, name, computed ) {
- var width, minWidth, maxWidth, ret,
- style = elem.style;
-
- computed = computed || getStyles( elem );
-
- // Support: IE9
- // getPropertyValue is only needed for .css('filter') in IE9, see #12537
- if ( computed ) {
- ret = computed.getPropertyValue( name ) || computed[ name ];
- }
-
- if ( computed ) {
-
- if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) {
- ret = jQuery.style( elem, name );
- }
-
- // Support: iOS < 6
- // A tribute to the "awesome hack by Dean Edwards"
- // iOS < 6 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels
- // this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values
- if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) {
-
- // Remember the original values
- width = style.width;
- minWidth = style.minWidth;
- maxWidth = style.maxWidth;
-
- // Put in the new values to get a computed value out
- style.minWidth = style.maxWidth = style.width = ret;
- ret = computed.width;
-
- // Revert the changed values
- style.width = width;
- style.minWidth = minWidth;
- style.maxWidth = maxWidth;
- }
- }
-
- return ret !== undefined ?
- // Support: IE
- // IE returns zIndex value as an integer.
- ret + "" :
- ret;
-}
-
-
-function addGetHookIf( conditionFn, hookFn ) {
- // Define the hook, we'll check on the first run if it's really needed.
- return {
- get: function() {
- if ( conditionFn() ) {
- // Hook not needed (or it's not possible to use it due to missing dependency),
- // remove it.
- // Since there are no other hooks for marginRight, remove the whole object.
- delete this.get;
- return;
- }
-
- // Hook needed; redefine it so that the support test is not executed again.
-
- return (this.get = hookFn).apply( this, arguments );
- }
- };
-}
-
-
-(function() {
- var pixelPositionVal, boxSizingReliableVal,
- // Support: Firefox, Android 2.3 (Prefixed box-sizing versions).
- divReset = "padding:0;margin:0;border:0;display:block;-webkit-box-sizing:content-box;" +
- "-moz-box-sizing:content-box;box-sizing:content-box",
- docElem = document.documentElement,
- container = document.createElement( "div" ),
- div = document.createElement( "div" );
-
- div.style.backgroundClip = "content-box";
- div.cloneNode( true ).style.backgroundClip = "";
- support.clearCloneStyle = div.style.backgroundClip === "content-box";
-
- container.style.cssText = "border:0;width:0;height:0;position:absolute;top:0;left:-9999px;" +
- "margin-top:1px";
- container.appendChild( div );
-
- // Executing both pixelPosition & boxSizingReliable tests require only one layout
- // so they're executed at the same time to save the second computation.
- function computePixelPositionAndBoxSizingReliable() {
- // Support: Firefox, Android 2.3 (Prefixed box-sizing versions).
- div.style.cssText = "-webkit-box-sizing:border-box;-moz-box-sizing:border-box;" +
- "box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;" +
- "position:absolute;top:1%";
- docElem.appendChild( container );
-
- var divStyle = window.getComputedStyle( div, null );
- pixelPositionVal = divStyle.top !== "1%";
- boxSizingReliableVal = divStyle.width === "4px";
-
- docElem.removeChild( container );
- }
-
- // Use window.getComputedStyle because jsdom on node.js will break without it.
- if ( window.getComputedStyle ) {
- jQuery.extend(support, {
- pixelPosition: function() {
- // This test is executed only once but we still do memoizing
- // since we can use the boxSizingReliable pre-computing.
- // No need to check if the test was already performed, though.
- computePixelPositionAndBoxSizingReliable();
- return pixelPositionVal;
- },
- boxSizingReliable: function() {
- if ( boxSizingReliableVal == null ) {
- computePixelPositionAndBoxSizingReliable();
- }
- return boxSizingReliableVal;
- },
- reliableMarginRight: function() {
- // Support: Android 2.3
- // Check if div with explicit width and no margin-right incorrectly
- // gets computed margin-right based on width of container. (#3333)
- // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
- // This support function is only executed once so no memoizing is needed.
- var ret,
- marginDiv = div.appendChild( document.createElement( "div" ) );
- marginDiv.style.cssText = div.style.cssText = divReset;
- marginDiv.style.marginRight = marginDiv.style.width = "0";
- div.style.width = "1px";
- docElem.appendChild( container );
-
- ret = !parseFloat( window.getComputedStyle( marginDiv, null ).marginRight );
-
- docElem.removeChild( container );
-
- // Clean up the div for other support tests.
- div.innerHTML = "";
-
- return ret;
- }
- });
- }
-})();
-
-
-// A method for quickly swapping in/out CSS properties to get correct calculations.
-jQuery.swap = function( elem, options, callback, args ) {
- var ret, name,
- old = {};
-
- // Remember the old values, and insert the new ones
- for ( name in options ) {
- old[ name ] = elem.style[ name ];
- elem.style[ name ] = options[ name ];
- }
-
- ret = callback.apply( elem, args || [] );
-
- // Revert the old values
- for ( name in options ) {
- elem.style[ name ] = old[ name ];
- }
-
- return ret;
-};
-
-
-var
- // swappable if display is none or starts with table except "table", "table-cell", or "table-caption"
- // see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display
- rdisplayswap = /^(none|table(?!-c[ea]).+)/,
- rnumsplit = new RegExp( "^(" + pnum + ")(.*)$", "i" ),
- rrelNum = new RegExp( "^([+-])=(" + pnum + ")", "i" ),
-
- cssShow = { position: "absolute", visibility: "hidden", display: "block" },
- cssNormalTransform = {
- letterSpacing: 0,
- fontWeight: 400
- },
-
- cssPrefixes = [ "Webkit", "O", "Moz", "ms" ];
-
-// return a css property mapped to a potentially vendor prefixed property
-function vendorPropName( style, name ) {
-
- // shortcut for names that are not vendor prefixed
- if ( name in style ) {
- return name;
- }
-
- // check for vendor prefixed names
- var capName = name[0].toUpperCase() + name.slice(1),
- origName = name,
- i = cssPrefixes.length;
-
- while ( i-- ) {
- name = cssPrefixes[ i ] + capName;
- if ( name in style ) {
- return name;
- }
- }
-
- return origName;
-}
-
-function setPositiveNumber( elem, value, subtract ) {
- var matches = rnumsplit.exec( value );
- return matches ?
- // Guard against undefined "subtract", e.g., when used as in cssHooks
- Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) :
- value;
-}
-
-function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) {
- var i = extra === ( isBorderBox ? "border" : "content" ) ?
- // If we already have the right measurement, avoid augmentation
- 4 :
- // Otherwise initialize for horizontal or vertical properties
- name === "width" ? 1 : 0,
-
- val = 0;
-
- for ( ; i < 4; i += 2 ) {
- // both box models exclude margin, so add it if we want it
- if ( extra === "margin" ) {
- val += jQuery.css( elem, extra + cssExpand[ i ], true, styles );
- }
-
- if ( isBorderBox ) {
- // border-box includes padding, so remove it if we want content
- if ( extra === "content" ) {
- val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles );
- }
-
- // at this point, extra isn't border nor margin, so remove border
- if ( extra !== "margin" ) {
- val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
- }
- } else {
- // at this point, extra isn't content, so add padding
- val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles );
-
- // at this point, extra isn't content nor padding, so add border
- if ( extra !== "padding" ) {
- val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
- }
- }
- }
-
- return val;
-}
-
-function getWidthOrHeight( elem, name, extra ) {
-
- // Start with offset property, which is equivalent to the border-box value
- var valueIsBorderBox = true,
- val = name === "width" ? elem.offsetWidth : elem.offsetHeight,
- styles = getStyles( elem ),
- isBorderBox = jQuery.css( elem, "boxSizing", false, styles ) === "border-box";
-
- // some non-html elements return undefined for offsetWidth, so check for null/undefined
- // svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285
- // MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668
- if ( val <= 0 || val == null ) {
- // Fall back to computed then uncomputed css if necessary
- val = curCSS( elem, name, styles );
- if ( val < 0 || val == null ) {
- val = elem.style[ name ];
- }
-
- // Computed unit is not pixels. Stop here and return.
- if ( rnumnonpx.test(val) ) {
- return val;
- }
-
- // we need the check for style in case a browser which returns unreliable values
- // for getComputedStyle silently falls back to the reliable elem.style
- valueIsBorderBox = isBorderBox &&
- ( support.boxSizingReliable() || val === elem.style[ name ] );
-
- // Normalize "", auto, and prepare for extra
- val = parseFloat( val ) || 0;
- }
-
- // use the active box-sizing model to add/subtract irrelevant styles
- return ( val +
- augmentWidthOrHeight(
- elem,
- name,
- extra || ( isBorderBox ? "border" : "content" ),
- valueIsBorderBox,
- styles
- )
- ) + "px";
-}
-
-function showHide( elements, show ) {
- var display, elem, hidden,
- values = [],
- index = 0,
- length = elements.length;
-
- for ( ; index < length; index++ ) {
- elem = elements[ index ];
- if ( !elem.style ) {
- continue;
- }
-
- values[ index ] = data_priv.get( elem, "olddisplay" );
- display = elem.style.display;
- if ( show ) {
- // Reset the inline display of this element to learn if it is
- // being hidden by cascaded rules or not
- if ( !values[ index ] && display === "none" ) {
- elem.style.display = "";
- }
-
- // Set elements which have been overridden with display: none
- // in a stylesheet to whatever the default browser style is
- // for such an element
- if ( elem.style.display === "" && isHidden( elem ) ) {
- values[ index ] = data_priv.access( elem, "olddisplay", defaultDisplay(elem.nodeName) );
- }
- } else {
-
- if ( !values[ index ] ) {
- hidden = isHidden( elem );
-
- if ( display && display !== "none" || !hidden ) {
- data_priv.set( elem, "olddisplay", hidden ? display : jQuery.css(elem, "display") );
- }
- }
- }
- }
-
- // Set the display of most of the elements in a second loop
- // to avoid the constant reflow
- for ( index = 0; index < length; index++ ) {
- elem = elements[ index ];
- if ( !elem.style ) {
- continue;
- }
- if ( !show || elem.style.display === "none" || elem.style.display === "" ) {
- elem.style.display = show ? values[ index ] || "" : "none";
- }
- }
-
- return elements;
-}
-
-jQuery.extend({
- // Add in style property hooks for overriding the default
- // behavior of getting and setting a style property
- cssHooks: {
- opacity: {
- get: function( elem, computed ) {
- if ( computed ) {
- // We should always get a number back from opacity
- var ret = curCSS( elem, "opacity" );
- return ret === "" ? "1" : ret;
- }
- }
- }
- },
-
- // Don't automatically add "px" to these possibly-unitless properties
- cssNumber: {
- "columnCount": true,
- "fillOpacity": true,
- "fontWeight": true,
- "lineHeight": true,
- "opacity": true,
- "order": true,
- "orphans": true,
- "widows": true,
- "zIndex": true,
- "zoom": true
- },
-
- // Add in properties whose names you wish to fix before
- // setting or getting the value
- cssProps: {
- // normalize float css property
- "float": "cssFloat"
- },
-
- // Get and set the style property on a DOM Node
- style: function( elem, name, value, extra ) {
- // Don't set styles on text and comment nodes
- if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) {
- return;
- }
-
- // Make sure that we're working with the right name
- var ret, type, hooks,
- origName = jQuery.camelCase( name ),
- style = elem.style;
-
- name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) );
-
- // gets hook for the prefixed version
- // followed by the unprefixed version
- hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
-
- // Check if we're setting a value
- if ( value !== undefined ) {
- type = typeof value;
-
- // convert relative number strings (+= or -=) to relative numbers. #7345
- if ( type === "string" && (ret = rrelNum.exec( value )) ) {
- value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) );
- // Fixes bug #9237
- type = "number";
- }
-
- // Make sure that null and NaN values aren't set. See: #7116
- if ( value == null || value !== value ) {
- return;
- }
-
- // If a number was passed in, add 'px' to the (except for certain CSS properties)
- if ( type === "number" && !jQuery.cssNumber[ origName ] ) {
- value += "px";
- }
-
- // Fixes #8908, it can be done more correctly by specifying setters in cssHooks,
- // but it would mean to define eight (for every problematic property) identical functions
- if ( !support.clearCloneStyle && value === "" && name.indexOf( "background" ) === 0 ) {
- style[ name ] = "inherit";
- }
-
- // If a hook was provided, use that value, otherwise just set the specified value
- if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) {
- // Support: Chrome, Safari
- // Setting style to blank string required to delete "style: x !important;"
- style[ name ] = "";
- style[ name ] = value;
- }
-
- } else {
- // If a hook was provided get the non-computed value from there
- if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) {
- return ret;
- }
-
- // Otherwise just get the value from the style object
- return style[ name ];
- }
- },
-
- css: function( elem, name, extra, styles ) {
- var val, num, hooks,
- origName = jQuery.camelCase( name );
-
- // Make sure that we're working with the right name
- name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) );
-
- // gets hook for the prefixed version
- // followed by the unprefixed version
- hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
-
- // If a hook was provided get the computed value from there
- if ( hooks && "get" in hooks ) {
- val = hooks.get( elem, true, extra );
- }
-
- // Otherwise, if a way to get the computed value exists, use that
- if ( val === undefined ) {
- val = curCSS( elem, name, styles );
- }
-
- //convert "normal" to computed value
- if ( val === "normal" && name in cssNormalTransform ) {
- val = cssNormalTransform[ name ];
- }
-
- // Return, converting to number if forced or a qualifier was provided and val looks numeric
- if ( extra === "" || extra ) {
- num = parseFloat( val );
- return extra === true || jQuery.isNumeric( num ) ? num || 0 : val;
- }
- return val;
- }
-});
-
-jQuery.each([ "height", "width" ], function( i, name ) {
- jQuery.cssHooks[ name ] = {
- get: function( elem, computed, extra ) {
- if ( computed ) {
- // certain elements can have dimension info if we invisibly show them
- // however, it must have a current display style that would benefit from this
- return elem.offsetWidth === 0 && rdisplayswap.test( jQuery.css( elem, "display" ) ) ?
- jQuery.swap( elem, cssShow, function() {
- return getWidthOrHeight( elem, name, extra );
- }) :
- getWidthOrHeight( elem, name, extra );
- }
- },
-
- set: function( elem, value, extra ) {
- var styles = extra && getStyles( elem );
- return setPositiveNumber( elem, value, extra ?
- augmentWidthOrHeight(
- elem,
- name,
- extra,
- jQuery.css( elem, "boxSizing", false, styles ) === "border-box",
- styles
- ) : 0
- );
- }
- };
-});
-
-// Support: Android 2.3
-jQuery.cssHooks.marginRight = addGetHookIf( support.reliableMarginRight,
- function( elem, computed ) {
- if ( computed ) {
- // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
- // Work around by temporarily setting element display to inline-block
- return jQuery.swap( elem, { "display": "inline-block" },
- curCSS, [ elem, "marginRight" ] );
- }
- }
-);
-
-// These hooks are used by animate to expand properties
-jQuery.each({
- margin: "",
- padding: "",
- border: "Width"
-}, function( prefix, suffix ) {
- jQuery.cssHooks[ prefix + suffix ] = {
- expand: function( value ) {
- var i = 0,
- expanded = {},
-
- // assumes a single number if not a string
- parts = typeof value === "string" ? value.split(" ") : [ value ];
-
- for ( ; i < 4; i++ ) {
- expanded[ prefix + cssExpand[ i ] + suffix ] =
- parts[ i ] || parts[ i - 2 ] || parts[ 0 ];
- }
-
- return expanded;
- }
- };
-
- if ( !rmargin.test( prefix ) ) {
- jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber;
- }
-});
-
-jQuery.fn.extend({
- css: function( name, value ) {
- return access( this, function( elem, name, value ) {
- var styles, len,
- map = {},
- i = 0;
-
- if ( jQuery.isArray( name ) ) {
- styles = getStyles( elem );
- len = name.length;
-
- for ( ; i < len; i++ ) {
- map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles );
- }
-
- return map;
- }
-
- return value !== undefined ?
- jQuery.style( elem, name, value ) :
- jQuery.css( elem, name );
- }, name, value, arguments.length > 1 );
- },
- show: function() {
- return showHide( this, true );
- },
- hide: function() {
- return showHide( this );
- },
- toggle: function( state ) {
- if ( typeof state === "boolean" ) {
- return state ? this.show() : this.hide();
- }
-
- return this.each(function() {
- if ( isHidden( this ) ) {
- jQuery( this ).show();
- } else {
- jQuery( this ).hide();
- }
- });
- }
-});
-
-
-function Tween( elem, options, prop, end, easing ) {
- return new Tween.prototype.init( elem, options, prop, end, easing );
-}
-jQuery.Tween = Tween;
-
-Tween.prototype = {
- constructor: Tween,
- init: function( elem, options, prop, end, easing, unit ) {
- this.elem = elem;
- this.prop = prop;
- this.easing = easing || "swing";
- this.options = options;
- this.start = this.now = this.cur();
- this.end = end;
- this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" );
- },
- cur: function() {
- var hooks = Tween.propHooks[ this.prop ];
-
- return hooks && hooks.get ?
- hooks.get( this ) :
- Tween.propHooks._default.get( this );
- },
- run: function( percent ) {
- var eased,
- hooks = Tween.propHooks[ this.prop ];
-
- if ( this.options.duration ) {
- this.pos = eased = jQuery.easing[ this.easing ](
- percent, this.options.duration * percent, 0, 1, this.options.duration
- );
- } else {
- this.pos = eased = percent;
- }
- this.now = ( this.end - this.start ) * eased + this.start;
-
- if ( this.options.step ) {
- this.options.step.call( this.elem, this.now, this );
- }
-
- if ( hooks && hooks.set ) {
- hooks.set( this );
- } else {
- Tween.propHooks._default.set( this );
- }
- return this;
- }
-};
-
-Tween.prototype.init.prototype = Tween.prototype;
-
-Tween.propHooks = {
- _default: {
- get: function( tween ) {
- var result;
-
- if ( tween.elem[ tween.prop ] != null &&
- (!tween.elem.style || tween.elem.style[ tween.prop ] == null) ) {
- return tween.elem[ tween.prop ];
- }
-
- // passing an empty string as a 3rd parameter to .css will automatically
- // attempt a parseFloat and fallback to a string if the parse fails
- // so, simple values such as "10px" are parsed to Float.
- // complex values such as "rotate(1rad)" are returned as is.
- result = jQuery.css( tween.elem, tween.prop, "" );
- // Empty strings, null, undefined and "auto" are converted to 0.
- return !result || result === "auto" ? 0 : result;
- },
- set: function( tween ) {
- // use step hook for back compat - use cssHook if its there - use .style if its
- // available and use plain properties where available
- if ( jQuery.fx.step[ tween.prop ] ) {
- jQuery.fx.step[ tween.prop ]( tween );
- } else if ( tween.elem.style && ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || jQuery.cssHooks[ tween.prop ] ) ) {
- jQuery.style( tween.elem, tween.prop, tween.now + tween.unit );
- } else {
- tween.elem[ tween.prop ] = tween.now;
- }
- }
- }
-};
-
-// Support: IE9
-// Panic based approach to setting things on disconnected nodes
-
-Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = {
- set: function( tween ) {
- if ( tween.elem.nodeType && tween.elem.parentNode ) {
- tween.elem[ tween.prop ] = tween.now;
- }
- }
-};
-
-jQuery.easing = {
- linear: function( p ) {
- return p;
- },
- swing: function( p ) {
- return 0.5 - Math.cos( p * Math.PI ) / 2;
- }
-};
-
-jQuery.fx = Tween.prototype.init;
-
-// Back Compat <1.8 extension point
-jQuery.fx.step = {};
-
-
-
-
-var
- fxNow, timerId,
- rfxtypes = /^(?:toggle|show|hide)$/,
- rfxnum = new RegExp( "^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i" ),
- rrun = /queueHooks$/,
- animationPrefilters = [ defaultPrefilter ],
- tweeners = {
- "*": [ function( prop, value ) {
- var tween = this.createTween( prop, value ),
- target = tween.cur(),
- parts = rfxnum.exec( value ),
- unit = parts && parts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ),
-
- // Starting value computation is required for potential unit mismatches
- start = ( jQuery.cssNumber[ prop ] || unit !== "px" && +target ) &&
- rfxnum.exec( jQuery.css( tween.elem, prop ) ),
- scale = 1,
- maxIterations = 20;
-
- if ( start && start[ 3 ] !== unit ) {
- // Trust units reported by jQuery.css
- unit = unit || start[ 3 ];
-
- // Make sure we update the tween properties later on
- parts = parts || [];
-
- // Iteratively approximate from a nonzero starting point
- start = +target || 1;
-
- do {
- // If previous iteration zeroed out, double until we get *something*
- // Use a string for doubling factor so we don't accidentally see scale as unchanged below
- scale = scale || ".5";
-
- // Adjust and apply
- start = start / scale;
- jQuery.style( tween.elem, prop, start + unit );
-
- // Update scale, tolerating zero or NaN from tween.cur()
- // And breaking the loop if scale is unchanged or perfect, or if we've just had enough
- } while ( scale !== (scale = tween.cur() / target) && scale !== 1 && --maxIterations );
- }
-
- // Update tween properties
- if ( parts ) {
- start = tween.start = +start || +target || 0;
- tween.unit = unit;
- // If a +=/-= token was provided, we're doing a relative animation
- tween.end = parts[ 1 ] ?
- start + ( parts[ 1 ] + 1 ) * parts[ 2 ] :
- +parts[ 2 ];
- }
-
- return tween;
- } ]
- };
-
-// Animations created synchronously will run synchronously
-function createFxNow() {
- setTimeout(function() {
- fxNow = undefined;
- });
- return ( fxNow = jQuery.now() );
-}
-
-// Generate parameters to create a standard animation
-function genFx( type, includeWidth ) {
- var which,
- i = 0,
- attrs = { height: type };
-
- // if we include width, step value is 1 to do all cssExpand values,
- // if we don't include width, step value is 2 to skip over Left and Right
- includeWidth = includeWidth ? 1 : 0;
- for ( ; i < 4 ; i += 2 - includeWidth ) {
- which = cssExpand[ i ];
- attrs[ "margin" + which ] = attrs[ "padding" + which ] = type;
- }
-
- if ( includeWidth ) {
- attrs.opacity = attrs.width = type;
- }
-
- return attrs;
-}
-
-function createTween( value, prop, animation ) {
- var tween,
- collection = ( tweeners[ prop ] || [] ).concat( tweeners[ "*" ] ),
- index = 0,
- length = collection.length;
- for ( ; index < length; index++ ) {
- if ( (tween = collection[ index ].call( animation, prop, value )) ) {
-
- // we're done with this property
- return tween;
- }
- }
-}
-
-function defaultPrefilter( elem, props, opts ) {
- /* jshint validthis: true */
- var prop, value, toggle, tween, hooks, oldfire, display,
- anim = this,
- orig = {},
- style = elem.style,
- hidden = elem.nodeType && isHidden( elem ),
- dataShow = data_priv.get( elem, "fxshow" );
-
- // handle queue: false promises
- if ( !opts.queue ) {
- hooks = jQuery._queueHooks( elem, "fx" );
- if ( hooks.unqueued == null ) {
- hooks.unqueued = 0;
- oldfire = hooks.empty.fire;
- hooks.empty.fire = function() {
- if ( !hooks.unqueued ) {
- oldfire();
- }
- };
- }
- hooks.unqueued++;
-
- anim.always(function() {
- // doing this makes sure that the complete handler will be called
- // before this completes
- anim.always(function() {
- hooks.unqueued--;
- if ( !jQuery.queue( elem, "fx" ).length ) {
- hooks.empty.fire();
- }
- });
- });
- }
-
- // height/width overflow pass
- if ( elem.nodeType === 1 && ( "height" in props || "width" in props ) ) {
- // Make sure that nothing sneaks out
- // Record all 3 overflow attributes because IE9-10 do not
- // change the overflow attribute when overflowX and
- // overflowY are set to the same value
- opts.overflow = [ style.overflow, style.overflowX, style.overflowY ];
-
- // Set display property to inline-block for height/width
- // animations on inline elements that are having width/height animated
- display = jQuery.css( elem, "display" );
- // Get default display if display is currently "none"
- if ( display === "none" ) {
- display = defaultDisplay( elem.nodeName );
- }
- if ( display === "inline" &&
- jQuery.css( elem, "float" ) === "none" ) {
-
- style.display = "inline-block";
- }
- }
-
- if ( opts.overflow ) {
- style.overflow = "hidden";
- anim.always(function() {
- style.overflow = opts.overflow[ 0 ];
- style.overflowX = opts.overflow[ 1 ];
- style.overflowY = opts.overflow[ 2 ];
- });
- }
-
- // show/hide pass
- for ( prop in props ) {
- value = props[ prop ];
- if ( rfxtypes.exec( value ) ) {
- delete props[ prop ];
- toggle = toggle || value === "toggle";
- if ( value === ( hidden ? "hide" : "show" ) ) {
-
- // If there is dataShow left over from a stopped hide or show and we are going to proceed with show, we should pretend to be hidden
- if ( value === "show" && dataShow && dataShow[ prop ] !== undefined ) {
- hidden = true;
- } else {
- continue;
- }
- }
- orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop );
- }
- }
-
- if ( !jQuery.isEmptyObject( orig ) ) {
- if ( dataShow ) {
- if ( "hidden" in dataShow ) {
- hidden = dataShow.hidden;
- }
- } else {
- dataShow = data_priv.access( elem, "fxshow", {} );
- }
-
- // store state if its toggle - enables .stop().toggle() to "reverse"
- if ( toggle ) {
- dataShow.hidden = !hidden;
- }
- if ( hidden ) {
- jQuery( elem ).show();
- } else {
- anim.done(function() {
- jQuery( elem ).hide();
- });
- }
- anim.done(function() {
- var prop;
-
- data_priv.remove( elem, "fxshow" );
- for ( prop in orig ) {
- jQuery.style( elem, prop, orig[ prop ] );
- }
- });
- for ( prop in orig ) {
- tween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim );
-
- if ( !( prop in dataShow ) ) {
- dataShow[ prop ] = tween.start;
- if ( hidden ) {
- tween.end = tween.start;
- tween.start = prop === "width" || prop === "height" ? 1 : 0;
- }
- }
- }
- }
-}
-
-function propFilter( props, specialEasing ) {
- var index, name, easing, value, hooks;
-
- // camelCase, specialEasing and expand cssHook pass
- for ( index in props ) {
- name = jQuery.camelCase( index );
- easing = specialEasing[ name ];
- value = props[ index ];
- if ( jQuery.isArray( value ) ) {
- easing = value[ 1 ];
- value = props[ index ] = value[ 0 ];
- }
-
- if ( index !== name ) {
- props[ name ] = value;
- delete props[ index ];
- }
-
- hooks = jQuery.cssHooks[ name ];
- if ( hooks && "expand" in hooks ) {
- value = hooks.expand( value );
- delete props[ name ];
-
- // not quite $.extend, this wont overwrite keys already present.
- // also - reusing 'index' from above because we have the correct "name"
- for ( index in value ) {
- if ( !( index in props ) ) {
- props[ index ] = value[ index ];
- specialEasing[ index ] = easing;
- }
- }
- } else {
- specialEasing[ name ] = easing;
- }
- }
-}
-
-function Animation( elem, properties, options ) {
- var result,
- stopped,
- index = 0,
- length = animationPrefilters.length,
- deferred = jQuery.Deferred().always( function() {
- // don't match elem in the :animated selector
- delete tick.elem;
- }),
- tick = function() {
- if ( stopped ) {
- return false;
- }
- var currentTime = fxNow || createFxNow(),
- remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ),
- // archaic crash bug won't allow us to use 1 - ( 0.5 || 0 ) (#12497)
- temp = remaining / animation.duration || 0,
- percent = 1 - temp,
- index = 0,
- length = animation.tweens.length;
-
- for ( ; index < length ; index++ ) {
- animation.tweens[ index ].run( percent );
- }
-
- deferred.notifyWith( elem, [ animation, percent, remaining ]);
-
- if ( percent < 1 && length ) {
- return remaining;
- } else {
- deferred.resolveWith( elem, [ animation ] );
- return false;
- }
- },
- animation = deferred.promise({
- elem: elem,
- props: jQuery.extend( {}, properties ),
- opts: jQuery.extend( true, { specialEasing: {} }, options ),
- originalProperties: properties,
- originalOptions: options,
- startTime: fxNow || createFxNow(),
- duration: options.duration,
- tweens: [],
- createTween: function( prop, end ) {
- var tween = jQuery.Tween( elem, animation.opts, prop, end,
- animation.opts.specialEasing[ prop ] || animation.opts.easing );
- animation.tweens.push( tween );
- return tween;
- },
- stop: function( gotoEnd ) {
- var index = 0,
- // if we are going to the end, we want to run all the tweens
- // otherwise we skip this part
- length = gotoEnd ? animation.tweens.length : 0;
- if ( stopped ) {
- return this;
- }
- stopped = true;
- for ( ; index < length ; index++ ) {
- animation.tweens[ index ].run( 1 );
- }
-
- // resolve when we played the last frame
- // otherwise, reject
- if ( gotoEnd ) {
- deferred.resolveWith( elem, [ animation, gotoEnd ] );
- } else {
- deferred.rejectWith( elem, [ animation, gotoEnd ] );
- }
- return this;
- }
- }),
- props = animation.props;
-
- propFilter( props, animation.opts.specialEasing );
-
- for ( ; index < length ; index++ ) {
- result = animationPrefilters[ index ].call( animation, elem, props, animation.opts );
- if ( result ) {
- return result;
- }
- }
-
- jQuery.map( props, createTween, animation );
-
- if ( jQuery.isFunction( animation.opts.start ) ) {
- animation.opts.start.call( elem, animation );
- }
-
- jQuery.fx.timer(
- jQuery.extend( tick, {
- elem: elem,
- anim: animation,
- queue: animation.opts.queue
- })
- );
-
- // attach callbacks from options
- return animation.progress( animation.opts.progress )
- .done( animation.opts.done, animation.opts.complete )
- .fail( animation.opts.fail )
- .always( animation.opts.always );
-}
-
-jQuery.Animation = jQuery.extend( Animation, {
-
- tweener: function( props, callback ) {
- if ( jQuery.isFunction( props ) ) {
- callback = props;
- props = [ "*" ];
- } else {
- props = props.split(" ");
- }
-
- var prop,
- index = 0,
- length = props.length;
-
- for ( ; index < length ; index++ ) {
- prop = props[ index ];
- tweeners[ prop ] = tweeners[ prop ] || [];
- tweeners[ prop ].unshift( callback );
- }
- },
-
- prefilter: function( callback, prepend ) {
- if ( prepend ) {
- animationPrefilters.unshift( callback );
- } else {
- animationPrefilters.push( callback );
- }
- }
-});
-
-jQuery.speed = function( speed, easing, fn ) {
- var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : {
- complete: fn || !fn && easing ||
- jQuery.isFunction( speed ) && speed,
- duration: speed,
- easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing
- };
-
- opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration :
- opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default;
-
- // normalize opt.queue - true/undefined/null -> "fx"
- if ( opt.queue == null || opt.queue === true ) {
- opt.queue = "fx";
- }
-
- // Queueing
- opt.old = opt.complete;
-
- opt.complete = function() {
- if ( jQuery.isFunction( opt.old ) ) {
- opt.old.call( this );
- }
-
- if ( opt.queue ) {
- jQuery.dequeue( this, opt.queue );
- }
- };
-
- return opt;
-};
-
-jQuery.fn.extend({
- fadeTo: function( speed, to, easing, callback ) {
-
- // show any hidden elements after setting opacity to 0
- return this.filter( isHidden ).css( "opacity", 0 ).show()
-
- // animate to the value specified
- .end().animate({ opacity: to }, speed, easing, callback );
- },
- animate: function( prop, speed, easing, callback ) {
- var empty = jQuery.isEmptyObject( prop ),
- optall = jQuery.speed( speed, easing, callback ),
- doAnimation = function() {
- // Operate on a copy of prop so per-property easing won't be lost
- var anim = Animation( this, jQuery.extend( {}, prop ), optall );
-
- // Empty animations, or finishing resolves immediately
- if ( empty || data_priv.get( this, "finish" ) ) {
- anim.stop( true );
- }
- };
- doAnimation.finish = doAnimation;
-
- return empty || optall.queue === false ?
- this.each( doAnimation ) :
- this.queue( optall.queue, doAnimation );
- },
- stop: function( type, clearQueue, gotoEnd ) {
- var stopQueue = function( hooks ) {
- var stop = hooks.stop;
- delete hooks.stop;
- stop( gotoEnd );
- };
-
- if ( typeof type !== "string" ) {
- gotoEnd = clearQueue;
- clearQueue = type;
- type = undefined;
- }
- if ( clearQueue && type !== false ) {
- this.queue( type || "fx", [] );
- }
-
- return this.each(function() {
- var dequeue = true,
- index = type != null && type + "queueHooks",
- timers = jQuery.timers,
- data = data_priv.get( this );
-
- if ( index ) {
- if ( data[ index ] && data[ index ].stop ) {
- stopQueue( data[ index ] );
- }
- } else {
- for ( index in data ) {
- if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) {
- stopQueue( data[ index ] );
- }
- }
- }
-
- for ( index = timers.length; index--; ) {
- if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) {
- timers[ index ].anim.stop( gotoEnd );
- dequeue = false;
- timers.splice( index, 1 );
- }
- }
-
- // start the next in the queue if the last step wasn't forced
- // timers currently will call their complete callbacks, which will dequeue
- // but only if they were gotoEnd
- if ( dequeue || !gotoEnd ) {
- jQuery.dequeue( this, type );
- }
- });
- },
- finish: function( type ) {
- if ( type !== false ) {
- type = type || "fx";
- }
- return this.each(function() {
- var index,
- data = data_priv.get( this ),
- queue = data[ type + "queue" ],
- hooks = data[ type + "queueHooks" ],
- timers = jQuery.timers,
- length = queue ? queue.length : 0;
-
- // enable finishing flag on private data
- data.finish = true;
-
- // empty the queue first
- jQuery.queue( this, type, [] );
-
- if ( hooks && hooks.stop ) {
- hooks.stop.call( this, true );
- }
-
- // look for any active animations, and finish them
- for ( index = timers.length; index--; ) {
- if ( timers[ index ].elem === this && timers[ index ].queue === type ) {
- timers[ index ].anim.stop( true );
- timers.splice( index, 1 );
- }
- }
-
- // look for any animations in the old queue and finish them
- for ( index = 0; index < length; index++ ) {
- if ( queue[ index ] && queue[ index ].finish ) {
- queue[ index ].finish.call( this );
- }
- }
-
- // turn off finishing flag
- delete data.finish;
- });
- }
-});
-
-jQuery.each([ "toggle", "show", "hide" ], function( i, name ) {
- var cssFn = jQuery.fn[ name ];
- jQuery.fn[ name ] = function( speed, easing, callback ) {
- return speed == null || typeof speed === "boolean" ?
- cssFn.apply( this, arguments ) :
- this.animate( genFx( name, true ), speed, easing, callback );
- };
-});
-
-// Generate shortcuts for custom animations
-jQuery.each({
- slideDown: genFx("show"),
- slideUp: genFx("hide"),
- slideToggle: genFx("toggle"),
- fadeIn: { opacity: "show" },
- fadeOut: { opacity: "hide" },
- fadeToggle: { opacity: "toggle" }
-}, function( name, props ) {
- jQuery.fn[ name ] = function( speed, easing, callback ) {
- return this.animate( props, speed, easing, callback );
- };
-});
-
-jQuery.timers = [];
-jQuery.fx.tick = function() {
- var timer,
- i = 0,
- timers = jQuery.timers;
-
- fxNow = jQuery.now();
-
- for ( ; i < timers.length; i++ ) {
- timer = timers[ i ];
- // Checks the timer has not already been removed
- if ( !timer() && timers[ i ] === timer ) {
- timers.splice( i--, 1 );
- }
- }
-
- if ( !timers.length ) {
- jQuery.fx.stop();
- }
- fxNow = undefined;
-};
-
-jQuery.fx.timer = function( timer ) {
- jQuery.timers.push( timer );
- if ( timer() ) {
- jQuery.fx.start();
- } else {
- jQuery.timers.pop();
- }
-};
-
-jQuery.fx.interval = 13;
-
-jQuery.fx.start = function() {
- if ( !timerId ) {
- timerId = setInterval( jQuery.fx.tick, jQuery.fx.interval );
- }
-};
-
-jQuery.fx.stop = function() {
- clearInterval( timerId );
- timerId = null;
-};
-
-jQuery.fx.speeds = {
- slow: 600,
- fast: 200,
- // Default speed
- _default: 400
-};
-
-
-// Based off of the plugin by Clint Helfers, with permission.
-// http://blindsignals.com/index.php/2009/07/jquery-delay/
-jQuery.fn.delay = function( time, type ) {
- time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time;
- type = type || "fx";
-
- return this.queue( type, function( next, hooks ) {
- var timeout = setTimeout( next, time );
- hooks.stop = function() {
- clearTimeout( timeout );
- };
- });
-};
-
-
-(function() {
- var input = document.createElement( "input" ),
- select = document.createElement( "select" ),
- opt = select.appendChild( document.createElement( "option" ) );
-
- input.type = "checkbox";
-
- // Support: iOS 5.1, Android 4.x, Android 2.3
- // Check the default checkbox/radio value ("" on old WebKit; "on" elsewhere)
- support.checkOn = input.value !== "";
-
- // Must access the parent to make an option select properly
- // Support: IE9, IE10
- support.optSelected = opt.selected;
-
- // Make sure that the options inside disabled selects aren't marked as disabled
- // (WebKit marks them as disabled)
- select.disabled = true;
- support.optDisabled = !opt.disabled;
-
- // Check if an input maintains its value after becoming a radio
- // Support: IE9, IE10
- input = document.createElement( "input" );
- input.value = "t";
- input.type = "radio";
- support.radioValue = input.value === "t";
-})();
-
-
-var nodeHook, boolHook,
- attrHandle = jQuery.expr.attrHandle;
-
-jQuery.fn.extend({
- attr: function( name, value ) {
- return access( this, jQuery.attr, name, value, arguments.length > 1 );
- },
-
- removeAttr: function( name ) {
- return this.each(function() {
- jQuery.removeAttr( this, name );
- });
- }
-});
-
-jQuery.extend({
- attr: function( elem, name, value ) {
- var hooks, ret,
- nType = elem.nodeType;
-
- // don't get/set attributes on text, comment and attribute nodes
- if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
- return;
- }
-
- // Fallback to prop when attributes are not supported
- if ( typeof elem.getAttribute === strundefined ) {
- return jQuery.prop( elem, name, value );
- }
-
- // All attributes are lowercase
- // Grab necessary hook if one is defined
- if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) {
- name = name.toLowerCase();
- hooks = jQuery.attrHooks[ name ] ||
- ( jQuery.expr.match.bool.test( name ) ? boolHook : nodeHook );
- }
-
- if ( value !== undefined ) {
-
- if ( value === null ) {
- jQuery.removeAttr( elem, name );
-
- } else if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) {
- return ret;
-
- } else {
- elem.setAttribute( name, value + "" );
- return value;
- }
-
- } else if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) {
- return ret;
-
- } else {
- ret = jQuery.find.attr( elem, name );
-
- // Non-existent attributes return null, we normalize to undefined
- return ret == null ?
- undefined :
- ret;
- }
- },
-
- removeAttr: function( elem, value ) {
- var name, propName,
- i = 0,
- attrNames = value && value.match( rnotwhite );
-
- if ( attrNames && elem.nodeType === 1 ) {
- while ( (name = attrNames[i++]) ) {
- propName = jQuery.propFix[ name ] || name;
-
- // Boolean attributes get special treatment (#10870)
- if ( jQuery.expr.match.bool.test( name ) ) {
- // Set corresponding property to false
- elem[ propName ] = false;
- }
-
- elem.removeAttribute( name );
- }
- }
- },
-
- attrHooks: {
- type: {
- set: function( elem, value ) {
- if ( !support.radioValue && value === "radio" &&
- jQuery.nodeName( elem, "input" ) ) {
- // Setting the type on a radio button after the value resets the value in IE6-9
- // Reset value to default in case type is set after value during creation
- var val = elem.value;
- elem.setAttribute( "type", value );
- if ( val ) {
- elem.value = val;
- }
- return value;
- }
- }
- }
- }
-});
-
-// Hooks for boolean attributes
-boolHook = {
- set: function( elem, value, name ) {
- if ( value === false ) {
- // Remove boolean attributes when set to false
- jQuery.removeAttr( elem, name );
- } else {
- elem.setAttribute( name, name );
- }
- return name;
- }
-};
-jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) {
- var getter = attrHandle[ name ] || jQuery.find.attr;
-
- attrHandle[ name ] = function( elem, name, isXML ) {
- var ret, handle;
- if ( !isXML ) {
- // Avoid an infinite loop by temporarily removing this function from the getter
- handle = attrHandle[ name ];
- attrHandle[ name ] = ret;
- ret = getter( elem, name, isXML ) != null ?
- name.toLowerCase() :
- null;
- attrHandle[ name ] = handle;
- }
- return ret;
- };
-});
-
-
-
-
-var rfocusable = /^(?:input|select|textarea|button)$/i;
-
-jQuery.fn.extend({
- prop: function( name, value ) {
- return access( this, jQuery.prop, name, value, arguments.length > 1 );
- },
-
- removeProp: function( name ) {
- return this.each(function() {
- delete this[ jQuery.propFix[ name ] || name ];
- });
- }
-});
-
-jQuery.extend({
- propFix: {
- "for": "htmlFor",
- "class": "className"
- },
-
- prop: function( elem, name, value ) {
- var ret, hooks, notxml,
- nType = elem.nodeType;
-
- // don't get/set properties on text, comment and attribute nodes
- if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
- return;
- }
-
- notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
-
- if ( notxml ) {
- // Fix name and attach hooks
- name = jQuery.propFix[ name ] || name;
- hooks = jQuery.propHooks[ name ];
- }
-
- if ( value !== undefined ) {
- return hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ?
- ret :
- ( elem[ name ] = value );
-
- } else {
- return hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ?
- ret :
- elem[ name ];
- }
- },
-
- propHooks: {
- tabIndex: {
- get: function( elem ) {
- return elem.hasAttribute( "tabindex" ) || rfocusable.test( elem.nodeName ) || elem.href ?
- elem.tabIndex :
- -1;
- }
- }
- }
-});
-
-// Support: IE9+
-// Selectedness for an option in an optgroup can be inaccurate
-if ( !support.optSelected ) {
- jQuery.propHooks.selected = {
- get: function( elem ) {
- var parent = elem.parentNode;
- if ( parent && parent.parentNode ) {
- parent.parentNode.selectedIndex;
- }
- return null;
- }
- };
-}
-
-jQuery.each([
- "tabIndex",
- "readOnly",
- "maxLength",
- "cellSpacing",
- "cellPadding",
- "rowSpan",
- "colSpan",
- "useMap",
- "frameBorder",
- "contentEditable"
-], function() {
- jQuery.propFix[ this.toLowerCase() ] = this;
-});
-
-
-
-
-var rclass = /[\t\r\n\f]/g;
-
-jQuery.fn.extend({
- addClass: function( value ) {
- var classes, elem, cur, clazz, j, finalValue,
- proceed = typeof value === "string" && value,
- i = 0,
- len = this.length;
-
- if ( jQuery.isFunction( value ) ) {
- return this.each(function( j ) {
- jQuery( this ).addClass( value.call( this, j, this.className ) );
- });
- }
-
- if ( proceed ) {
- // The disjunction here is for better compressibility (see removeClass)
- classes = ( value || "" ).match( rnotwhite ) || [];
-
- for ( ; i < len; i++ ) {
- elem = this[ i ];
- cur = elem.nodeType === 1 && ( elem.className ?
- ( " " + elem.className + " " ).replace( rclass, " " ) :
- " "
- );
-
- if ( cur ) {
- j = 0;
- while ( (clazz = classes[j++]) ) {
- if ( cur.indexOf( " " + clazz + " " ) < 0 ) {
- cur += clazz + " ";
- }
- }
-
- // only assign if different to avoid unneeded rendering.
- finalValue = jQuery.trim( cur );
- if ( elem.className !== finalValue ) {
- elem.className = finalValue;
- }
- }
- }
- }
-
- return this;
- },
-
- removeClass: function( value ) {
- var classes, elem, cur, clazz, j, finalValue,
- proceed = arguments.length === 0 || typeof value === "string" && value,
- i = 0,
- len = this.length;
-
- if ( jQuery.isFunction( value ) ) {
- return this.each(function( j ) {
- jQuery( this ).removeClass( value.call( this, j, this.className ) );
- });
- }
- if ( proceed ) {
- classes = ( value || "" ).match( rnotwhite ) || [];
-
- for ( ; i < len; i++ ) {
- elem = this[ i ];
- // This expression is here for better compressibility (see addClass)
- cur = elem.nodeType === 1 && ( elem.className ?
- ( " " + elem.className + " " ).replace( rclass, " " ) :
- ""
- );
-
- if ( cur ) {
- j = 0;
- while ( (clazz = classes[j++]) ) {
- // Remove *all* instances
- while ( cur.indexOf( " " + clazz + " " ) >= 0 ) {
- cur = cur.replace( " " + clazz + " ", " " );
- }
- }
-
- // only assign if different to avoid unneeded rendering.
- finalValue = value ? jQuery.trim( cur ) : "";
- if ( elem.className !== finalValue ) {
- elem.className = finalValue;
- }
- }
- }
- }
-
- return this;
- },
-
- toggleClass: function( value, stateVal ) {
- var type = typeof value;
-
- if ( typeof stateVal === "boolean" && type === "string" ) {
- return stateVal ? this.addClass( value ) : this.removeClass( value );
- }
-
- if ( jQuery.isFunction( value ) ) {
- return this.each(function( i ) {
- jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal );
- });
- }
-
- return this.each(function() {
- if ( type === "string" ) {
- // toggle individual class names
- var className,
- i = 0,
- self = jQuery( this ),
- classNames = value.match( rnotwhite ) || [];
-
- while ( (className = classNames[ i++ ]) ) {
- // check each className given, space separated list
- if ( self.hasClass( className ) ) {
- self.removeClass( className );
- } else {
- self.addClass( className );
- }
- }
-
- // Toggle whole class name
- } else if ( type === strundefined || type === "boolean" ) {
- if ( this.className ) {
- // store className if set
- data_priv.set( this, "__className__", this.className );
- }
-
- // If the element has a class name or if we're passed "false",
- // then remove the whole classname (if there was one, the above saved it).
- // Otherwise bring back whatever was previously saved (if anything),
- // falling back to the empty string if nothing was stored.
- this.className = this.className || value === false ? "" : data_priv.get( this, "__className__" ) || "";
- }
- });
- },
-
- hasClass: function( selector ) {
- var className = " " + selector + " ",
- i = 0,
- l = this.length;
- for ( ; i < l; i++ ) {
- if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) {
- return true;
- }
- }
-
- return false;
- }
-});
-
-
-
-
-var rreturn = /\r/g;
-
-jQuery.fn.extend({
- val: function( value ) {
- var hooks, ret, isFunction,
- elem = this[0];
-
- if ( !arguments.length ) {
- if ( elem ) {
- hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ];
-
- if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) {
- return ret;
- }
-
- ret = elem.value;
-
- return typeof ret === "string" ?
- // handle most common string cases
- ret.replace(rreturn, "") :
- // handle cases where value is null/undef or number
- ret == null ? "" : ret;
- }
-
- return;
- }
-
- isFunction = jQuery.isFunction( value );
-
- return this.each(function( i ) {
- var val;
-
- if ( this.nodeType !== 1 ) {
- return;
- }
-
- if ( isFunction ) {
- val = value.call( this, i, jQuery( this ).val() );
- } else {
- val = value;
- }
-
- // Treat null/undefined as ""; convert numbers to string
- if ( val == null ) {
- val = "";
-
- } else if ( typeof val === "number" ) {
- val += "";
-
- } else if ( jQuery.isArray( val ) ) {
- val = jQuery.map( val, function( value ) {
- return value == null ? "" : value + "";
- });
- }
-
- hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ];
-
- // If set returns undefined, fall back to normal setting
- if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) {
- this.value = val;
- }
- });
- }
-});
-
-jQuery.extend({
- valHooks: {
- select: {
- get: function( elem ) {
- var value, option,
- options = elem.options,
- index = elem.selectedIndex,
- one = elem.type === "select-one" || index < 0,
- values = one ? null : [],
- max = one ? index + 1 : options.length,
- i = index < 0 ?
- max :
- one ? index : 0;
-
- // Loop through all the selected options
- for ( ; i < max; i++ ) {
- option = options[ i ];
-
- // IE6-9 doesn't update selected after form reset (#2551)
- if ( ( option.selected || i === index ) &&
- // Don't return options that are disabled or in a disabled optgroup
- ( support.optDisabled ? !option.disabled : option.getAttribute( "disabled" ) === null ) &&
- ( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) {
-
- // Get the specific value for the option
- value = jQuery( option ).val();
-
- // We don't need an array for one selects
- if ( one ) {
- return value;
- }
-
- // Multi-Selects return an array
- values.push( value );
- }
- }
-
- return values;
- },
-
- set: function( elem, value ) {
- var optionSet, option,
- options = elem.options,
- values = jQuery.makeArray( value ),
- i = options.length;
-
- while ( i-- ) {
- option = options[ i ];
- if ( (option.selected = jQuery.inArray( jQuery(option).val(), values ) >= 0) ) {
- optionSet = true;
- }
- }
-
- // force browsers to behave consistently when non-matching value is set
- if ( !optionSet ) {
- elem.selectedIndex = -1;
- }
- return values;
- }
- }
- }
-});
-
-// Radios and checkboxes getter/setter
-jQuery.each([ "radio", "checkbox" ], function() {
- jQuery.valHooks[ this ] = {
- set: function( elem, value ) {
- if ( jQuery.isArray( value ) ) {
- return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 );
- }
- }
- };
- if ( !support.checkOn ) {
- jQuery.valHooks[ this ].get = function( elem ) {
- // Support: Webkit
- // "" is returned instead of "on" if a value isn't specified
- return elem.getAttribute("value") === null ? "on" : elem.value;
- };
- }
-});
-
-
-
-
-// Return jQuery for attributes-only inclusion
-
-
-jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " +
- "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
- "change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) {
-
- // Handle event binding
- jQuery.fn[ name ] = function( data, fn ) {
- return arguments.length > 0 ?
- this.on( name, null, data, fn ) :
- this.trigger( name );
- };
-});
-
-jQuery.fn.extend({
- hover: function( fnOver, fnOut ) {
- return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );
- },
-
- bind: function( types, data, fn ) {
- return this.on( types, null, data, fn );
- },
- unbind: function( types, fn ) {
- return this.off( types, null, fn );
- },
-
- delegate: function( selector, types, data, fn ) {
- return this.on( types, selector, data, fn );
- },
- undelegate: function( selector, types, fn ) {
- // ( namespace ) or ( selector, types [, fn] )
- return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn );
- }
-});
-
-
-var nonce = jQuery.now();
-
-var rquery = (/\?/);
-
-
-
-// Support: Android 2.3
-// Workaround failure to string-cast null input
-jQuery.parseJSON = function( data ) {
- return JSON.parse( data + "" );
-};
-
-
-// Cross-browser xml parsing
-jQuery.parseXML = function( data ) {
- var xml, tmp;
- if ( !data || typeof data !== "string" ) {
- return null;
- }
-
- // Support: IE9
- try {
- tmp = new DOMParser();
- xml = tmp.parseFromString( data, "text/xml" );
- } catch ( e ) {
- xml = undefined;
- }
-
- if ( !xml || xml.getElementsByTagName( "parsererror" ).length ) {
- jQuery.error( "Invalid XML: " + data );
- }
- return xml;
-};
-
-
-var
- // Document location
- ajaxLocParts,
- ajaxLocation,
-
- rhash = /#.*$/,
- rts = /([?&])_=[^&]*/,
- rheaders = /^(.*?):[ \t]*([^\r\n]*)$/mg,
- // #7653, #8125, #8152: local protocol detection
- rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/,
- rnoContent = /^(?:GET|HEAD)$/,
- rprotocol = /^\/\//,
- rurl = /^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,
-
- /* Prefilters
- * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example)
- * 2) These are called:
- * - BEFORE asking for a transport
- * - AFTER param serialization (s.data is a string if s.processData is true)
- * 3) key is the dataType
- * 4) the catchall symbol "*" can be used
- * 5) execution will start with transport dataType and THEN continue down to "*" if needed
- */
- prefilters = {},
-
- /* Transports bindings
- * 1) key is the dataType
- * 2) the catchall symbol "*" can be used
- * 3) selection will start with transport dataType and THEN go to "*" if needed
- */
- transports = {},
-
- // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression
- allTypes = "*/".concat("*");
-
-// #8138, IE may throw an exception when accessing
-// a field from window.location if document.domain has been set
-try {
- ajaxLocation = location.href;
-} catch( e ) {
- // Use the href attribute of an A element
- // since IE will modify it given document.location
- ajaxLocation = document.createElement( "a" );
- ajaxLocation.href = "";
- ajaxLocation = ajaxLocation.href;
-}
-
-// Segment location into parts
-ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || [];
-
-// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport
-function addToPrefiltersOrTransports( structure ) {
-
- // dataTypeExpression is optional and defaults to "*"
- return function( dataTypeExpression, func ) {
-
- if ( typeof dataTypeExpression !== "string" ) {
- func = dataTypeExpression;
- dataTypeExpression = "*";
- }
-
- var dataType,
- i = 0,
- dataTypes = dataTypeExpression.toLowerCase().match( rnotwhite ) || [];
-
- if ( jQuery.isFunction( func ) ) {
- // For each dataType in the dataTypeExpression
- while ( (dataType = dataTypes[i++]) ) {
- // Prepend if requested
- if ( dataType[0] === "+" ) {
- dataType = dataType.slice( 1 ) || "*";
- (structure[ dataType ] = structure[ dataType ] || []).unshift( func );
-
- // Otherwise append
- } else {
- (structure[ dataType ] = structure[ dataType ] || []).push( func );
- }
- }
- }
- };
-}
-
-// Base inspection function for prefilters and transports
-function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) {
-
- var inspected = {},
- seekingTransport = ( structure === transports );
-
- function inspect( dataType ) {
- var selected;
- inspected[ dataType ] = true;
- jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) {
- var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR );
- if ( typeof dataTypeOrTransport === "string" && !seekingTransport && !inspected[ dataTypeOrTransport ] ) {
- options.dataTypes.unshift( dataTypeOrTransport );
- inspect( dataTypeOrTransport );
- return false;
- } else if ( seekingTransport ) {
- return !( selected = dataTypeOrTransport );
- }
- });
- return selected;
- }
-
- return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" );
-}
-
-// A special extend for ajax options
-// that takes "flat" options (not to be deep extended)
-// Fixes #9887
-function ajaxExtend( target, src ) {
- var key, deep,
- flatOptions = jQuery.ajaxSettings.flatOptions || {};
-
- for ( key in src ) {
- if ( src[ key ] !== undefined ) {
- ( flatOptions[ key ] ? target : ( deep || (deep = {}) ) )[ key ] = src[ key ];
- }
- }
- if ( deep ) {
- jQuery.extend( true, target, deep );
- }
-
- return target;
-}
-
-/* Handles responses to an ajax request:
- * - finds the right dataType (mediates between content-type and expected dataType)
- * - returns the corresponding response
- */
-function ajaxHandleResponses( s, jqXHR, responses ) {
-
- var ct, type, finalDataType, firstDataType,
- contents = s.contents,
- dataTypes = s.dataTypes;
-
- // Remove auto dataType and get content-type in the process
- while ( dataTypes[ 0 ] === "*" ) {
- dataTypes.shift();
- if ( ct === undefined ) {
- ct = s.mimeType || jqXHR.getResponseHeader("Content-Type");
- }
- }
-
- // Check if we're dealing with a known content-type
- if ( ct ) {
- for ( type in contents ) {
- if ( contents[ type ] && contents[ type ].test( ct ) ) {
- dataTypes.unshift( type );
- break;
- }
- }
- }
-
- // Check to see if we have a response for the expected dataType
- if ( dataTypes[ 0 ] in responses ) {
- finalDataType = dataTypes[ 0 ];
- } else {
- // Try convertible dataTypes
- for ( type in responses ) {
- if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) {
- finalDataType = type;
- break;
- }
- if ( !firstDataType ) {
- firstDataType = type;
- }
- }
- // Or just use first one
- finalDataType = finalDataType || firstDataType;
- }
-
- // If we found a dataType
- // We add the dataType to the list if needed
- // and return the corresponding response
- if ( finalDataType ) {
- if ( finalDataType !== dataTypes[ 0 ] ) {
- dataTypes.unshift( finalDataType );
- }
- return responses[ finalDataType ];
- }
-}
-
-/* Chain conversions given the request and the original response
- * Also sets the responseXXX fields on the jqXHR instance
- */
-function ajaxConvert( s, response, jqXHR, isSuccess ) {
- var conv2, current, conv, tmp, prev,
- converters = {},
- // Work with a copy of dataTypes in case we need to modify it for conversion
- dataTypes = s.dataTypes.slice();
-
- // Create converters map with lowercased keys
- if ( dataTypes[ 1 ] ) {
- for ( conv in s.converters ) {
- converters[ conv.toLowerCase() ] = s.converters[ conv ];
- }
- }
-
- current = dataTypes.shift();
-
- // Convert to each sequential dataType
- while ( current ) {
-
- if ( s.responseFields[ current ] ) {
- jqXHR[ s.responseFields[ current ] ] = response;
- }
-
- // Apply the dataFilter if provided
- if ( !prev && isSuccess && s.dataFilter ) {
- response = s.dataFilter( response, s.dataType );
- }
-
- prev = current;
- current = dataTypes.shift();
-
- if ( current ) {
-
- // There's only work to do if current dataType is non-auto
- if ( current === "*" ) {
-
- current = prev;
-
- // Convert response if prev dataType is non-auto and differs from current
- } else if ( prev !== "*" && prev !== current ) {
-
- // Seek a direct converter
- conv = converters[ prev + " " + current ] || converters[ "* " + current ];
-
- // If none found, seek a pair
- if ( !conv ) {
- for ( conv2 in converters ) {
-
- // If conv2 outputs current
- tmp = conv2.split( " " );
- if ( tmp[ 1 ] === current ) {
-
- // If prev can be converted to accepted input
- conv = converters[ prev + " " + tmp[ 0 ] ] ||
- converters[ "* " + tmp[ 0 ] ];
- if ( conv ) {
- // Condense equivalence converters
- if ( conv === true ) {
- conv = converters[ conv2 ];
-
- // Otherwise, insert the intermediate dataType
- } else if ( converters[ conv2 ] !== true ) {
- current = tmp[ 0 ];
- dataTypes.unshift( tmp[ 1 ] );
- }
- break;
- }
- }
- }
- }
-
- // Apply converter (if not an equivalence)
- if ( conv !== true ) {
-
- // Unless errors are allowed to bubble, catch and return them
- if ( conv && s[ "throws" ] ) {
- response = conv( response );
- } else {
- try {
- response = conv( response );
- } catch ( e ) {
- return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current };
- }
- }
- }
- }
- }
- }
-
- return { state: "success", data: response };
-}
-
-jQuery.extend({
-
- // Counter for holding the number of active queries
- active: 0,
-
- // Last-Modified header cache for next request
- lastModified: {},
- etag: {},
-
- ajaxSettings: {
- url: ajaxLocation,
- type: "GET",
- isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ),
- global: true,
- processData: true,
- async: true,
- contentType: "application/x-www-form-urlencoded; charset=UTF-8",
- /*
- timeout: 0,
- data: null,
- dataType: null,
- username: null,
- password: null,
- cache: null,
- throws: false,
- traditional: false,
- headers: {},
- */
-
- accepts: {
- "*": allTypes,
- text: "text/plain",
- html: "text/html",
- xml: "application/xml, text/xml",
- json: "application/json, text/javascript"
- },
-
- contents: {
- xml: /xml/,
- html: /html/,
- json: /json/
- },
-
- responseFields: {
- xml: "responseXML",
- text: "responseText",
- json: "responseJSON"
- },
-
- // Data converters
- // Keys separate source (or catchall "*") and destination types with a single space
- converters: {
-
- // Convert anything to text
- "* text": String,
-
- // Text to html (true = no transformation)
- "text html": true,
-
- // Evaluate text as a json expression
- "text json": jQuery.parseJSON,
-
- // Parse text as xml
- "text xml": jQuery.parseXML
- },
-
- // For options that shouldn't be deep extended:
- // you can add your own custom options here if
- // and when you create one that shouldn't be
- // deep extended (see ajaxExtend)
- flatOptions: {
- url: true,
- context: true
- }
- },
-
- // Creates a full fledged settings object into target
- // with both ajaxSettings and settings fields.
- // If target is omitted, writes into ajaxSettings.
- ajaxSetup: function( target, settings ) {
- return settings ?
-
- // Building a settings object
- ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) :
-
- // Extending ajaxSettings
- ajaxExtend( jQuery.ajaxSettings, target );
- },
-
- ajaxPrefilter: addToPrefiltersOrTransports( prefilters ),
- ajaxTransport: addToPrefiltersOrTransports( transports ),
-
- // Main method
- ajax: function( url, options ) {
-
- // If url is an object, simulate pre-1.5 signature
- if ( typeof url === "object" ) {
- options = url;
- url = undefined;
- }
-
- // Force options to be an object
- options = options || {};
-
- var transport,
- // URL without anti-cache param
- cacheURL,
- // Response headers
- responseHeadersString,
- responseHeaders,
- // timeout handle
- timeoutTimer,
- // Cross-domain detection vars
- parts,
- // To know if global events are to be dispatched
- fireGlobals,
- // Loop variable
- i,
- // Create the final options object
- s = jQuery.ajaxSetup( {}, options ),
- // Callbacks context
- callbackContext = s.context || s,
- // Context for global events is callbackContext if it is a DOM node or jQuery collection
- globalEventContext = s.context && ( callbackContext.nodeType || callbackContext.jquery ) ?
- jQuery( callbackContext ) :
- jQuery.event,
- // Deferreds
- deferred = jQuery.Deferred(),
- completeDeferred = jQuery.Callbacks("once memory"),
- // Status-dependent callbacks
- statusCode = s.statusCode || {},
- // Headers (they are sent all at once)
- requestHeaders = {},
- requestHeadersNames = {},
- // The jqXHR state
- state = 0,
- // Default abort message
- strAbort = "canceled",
- // Fake xhr
- jqXHR = {
- readyState: 0,
-
- // Builds headers hashtable if needed
- getResponseHeader: function( key ) {
- var match;
- if ( state === 2 ) {
- if ( !responseHeaders ) {
- responseHeaders = {};
- while ( (match = rheaders.exec( responseHeadersString )) ) {
- responseHeaders[ match[1].toLowerCase() ] = match[ 2 ];
- }
- }
- match = responseHeaders[ key.toLowerCase() ];
- }
- return match == null ? null : match;
- },
-
- // Raw string
- getAllResponseHeaders: function() {
- return state === 2 ? responseHeadersString : null;
- },
-
- // Caches the header
- setRequestHeader: function( name, value ) {
- var lname = name.toLowerCase();
- if ( !state ) {
- name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name;
- requestHeaders[ name ] = value;
- }
- return this;
- },
-
- // Overrides response content-type header
- overrideMimeType: function( type ) {
- if ( !state ) {
- s.mimeType = type;
- }
- return this;
- },
-
- // Status-dependent callbacks
- statusCode: function( map ) {
- var code;
- if ( map ) {
- if ( state < 2 ) {
- for ( code in map ) {
- // Lazy-add the new callback in a way that preserves old ones
- statusCode[ code ] = [ statusCode[ code ], map[ code ] ];
- }
- } else {
- // Execute the appropriate callbacks
- jqXHR.always( map[ jqXHR.status ] );
- }
- }
- return this;
- },
-
- // Cancel the request
- abort: function( statusText ) {
- var finalText = statusText || strAbort;
- if ( transport ) {
- transport.abort( finalText );
- }
- done( 0, finalText );
- return this;
- }
- };
-
- // Attach deferreds
- deferred.promise( jqXHR ).complete = completeDeferred.add;
- jqXHR.success = jqXHR.done;
- jqXHR.error = jqXHR.fail;
-
- // Remove hash character (#7531: and string promotion)
- // Add protocol if not provided (prefilters might expect it)
- // Handle falsy url in the settings object (#10093: consistency with old signature)
- // We also use the url parameter if available
- s.url = ( ( url || s.url || ajaxLocation ) + "" ).replace( rhash, "" )
- .replace( rprotocol, ajaxLocParts[ 1 ] + "//" );
-
- // Alias method option to type as per ticket #12004
- s.type = options.method || options.type || s.method || s.type;
-
- // Extract dataTypes list
- s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().match( rnotwhite ) || [ "" ];
-
- // A cross-domain request is in order when we have a protocol:host:port mismatch
- if ( s.crossDomain == null ) {
- parts = rurl.exec( s.url.toLowerCase() );
- s.crossDomain = !!( parts &&
- ( parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] ||
- ( parts[ 3 ] || ( parts[ 1 ] === "http:" ? "80" : "443" ) ) !==
- ( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? "80" : "443" ) ) )
- );
- }
-
- // Convert data if not already a string
- if ( s.data && s.processData && typeof s.data !== "string" ) {
- s.data = jQuery.param( s.data, s.traditional );
- }
-
- // Apply prefilters
- inspectPrefiltersOrTransports( prefilters, s, options, jqXHR );
-
- // If request was aborted inside a prefilter, stop there
- if ( state === 2 ) {
- return jqXHR;
- }
-
- // We can fire global events as of now if asked to
- fireGlobals = s.global;
-
- // Watch for a new set of requests
- if ( fireGlobals && jQuery.active++ === 0 ) {
- jQuery.event.trigger("ajaxStart");
- }
-
- // Uppercase the type
- s.type = s.type.toUpperCase();
-
- // Determine if request has content
- s.hasContent = !rnoContent.test( s.type );
-
- // Save the URL in case we're toying with the If-Modified-Since
- // and/or If-None-Match header later on
- cacheURL = s.url;
-
- // More options handling for requests with no content
- if ( !s.hasContent ) {
-
- // If data is available, append data to url
- if ( s.data ) {
- cacheURL = ( s.url += ( rquery.test( cacheURL ) ? "&" : "?" ) + s.data );
- // #9682: remove data so that it's not used in an eventual retry
- delete s.data;
- }
-
- // Add anti-cache in url if needed
- if ( s.cache === false ) {
- s.url = rts.test( cacheURL ) ?
-
- // If there is already a '_' parameter, set its value
- cacheURL.replace( rts, "$1_=" + nonce++ ) :
-
- // Otherwise add one to the end
- cacheURL + ( rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + nonce++;
- }
- }
-
- // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
- if ( s.ifModified ) {
- if ( jQuery.lastModified[ cacheURL ] ) {
- jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] );
- }
- if ( jQuery.etag[ cacheURL ] ) {
- jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] );
- }
- }
-
- // Set the correct header, if data is being sent
- if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
- jqXHR.setRequestHeader( "Content-Type", s.contentType );
- }
-
- // Set the Accepts header for the server, depending on the dataType
- jqXHR.setRequestHeader(
- "Accept",
- s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ?
- s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) :
- s.accepts[ "*" ]
- );
-
- // Check for headers option
- for ( i in s.headers ) {
- jqXHR.setRequestHeader( i, s.headers[ i ] );
- }
-
- // Allow custom headers/mimetypes and early abort
- if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) {
- // Abort if not done already and return
- return jqXHR.abort();
- }
-
- // aborting is no longer a cancellation
- strAbort = "abort";
-
- // Install callbacks on deferreds
- for ( i in { success: 1, error: 1, complete: 1 } ) {
- jqXHR[ i ]( s[ i ] );
- }
-
- // Get transport
- transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR );
-
- // If no transport, we auto-abort
- if ( !transport ) {
- done( -1, "No Transport" );
- } else {
- jqXHR.readyState = 1;
-
- // Send global event
- if ( fireGlobals ) {
- globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] );
- }
- // Timeout
- if ( s.async && s.timeout > 0 ) {
- timeoutTimer = setTimeout(function() {
- jqXHR.abort("timeout");
- }, s.timeout );
- }
-
- try {
- state = 1;
- transport.send( requestHeaders, done );
- } catch ( e ) {
- // Propagate exception as error if not done
- if ( state < 2 ) {
- done( -1, e );
- // Simply rethrow otherwise
- } else {
- throw e;
- }
- }
- }
-
- // Callback for when everything is done
- function done( status, nativeStatusText, responses, headers ) {
- var isSuccess, success, error, response, modified,
- statusText = nativeStatusText;
-
- // Called once
- if ( state === 2 ) {
- return;
- }
-
- // State is "done" now
- state = 2;
-
- // Clear timeout if it exists
- if ( timeoutTimer ) {
- clearTimeout( timeoutTimer );
- }
-
- // Dereference transport for early garbage collection
- // (no matter how long the jqXHR object will be used)
- transport = undefined;
-
- // Cache response headers
- responseHeadersString = headers || "";
-
- // Set readyState
- jqXHR.readyState = status > 0 ? 4 : 0;
-
- // Determine if successful
- isSuccess = status >= 200 && status < 300 || status === 304;
-
- // Get response data
- if ( responses ) {
- response = ajaxHandleResponses( s, jqXHR, responses );
- }
-
- // Convert no matter what (that way responseXXX fields are always set)
- response = ajaxConvert( s, response, jqXHR, isSuccess );
-
- // If successful, handle type chaining
- if ( isSuccess ) {
-
- // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
- if ( s.ifModified ) {
- modified = jqXHR.getResponseHeader("Last-Modified");
- if ( modified ) {
- jQuery.lastModified[ cacheURL ] = modified;
- }
- modified = jqXHR.getResponseHeader("etag");
- if ( modified ) {
- jQuery.etag[ cacheURL ] = modified;
- }
- }
-
- // if no content
- if ( status === 204 || s.type === "HEAD" ) {
- statusText = "nocontent";
-
- // if not modified
- } else if ( status === 304 ) {
- statusText = "notmodified";
-
- // If we have data, let's convert it
- } else {
- statusText = response.state;
- success = response.data;
- error = response.error;
- isSuccess = !error;
- }
- } else {
- // We extract error from statusText
- // then normalize statusText and status for non-aborts
- error = statusText;
- if ( status || !statusText ) {
- statusText = "error";
- if ( status < 0 ) {
- status = 0;
- }
- }
- }
-
- // Set data for the fake xhr object
- jqXHR.status = status;
- jqXHR.statusText = ( nativeStatusText || statusText ) + "";
-
- // Success/Error
- if ( isSuccess ) {
- deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] );
- } else {
- deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] );
- }
-
- // Status-dependent callbacks
- jqXHR.statusCode( statusCode );
- statusCode = undefined;
-
- if ( fireGlobals ) {
- globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError",
- [ jqXHR, s, isSuccess ? success : error ] );
- }
-
- // Complete
- completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] );
-
- if ( fireGlobals ) {
- globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] );
- // Handle the global AJAX counter
- if ( !( --jQuery.active ) ) {
- jQuery.event.trigger("ajaxStop");
- }
- }
- }
-
- return jqXHR;
- },
-
- getJSON: function( url, data, callback ) {
- return jQuery.get( url, data, callback, "json" );
- },
-
- getScript: function( url, callback ) {
- return jQuery.get( url, undefined, callback, "script" );
- }
-});
-
-jQuery.each( [ "get", "post" ], function( i, method ) {
- jQuery[ method ] = function( url, data, callback, type ) {
- // shift arguments if data argument was omitted
- if ( jQuery.isFunction( data ) ) {
- type = type || callback;
- callback = data;
- data = undefined;
- }
-
- return jQuery.ajax({
- url: url,
- type: method,
- dataType: type,
- data: data,
- success: callback
- });
- };
-});
-
-// Attach a bunch of functions for handling common AJAX events
-jQuery.each( [ "ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend" ], function( i, type ) {
- jQuery.fn[ type ] = function( fn ) {
- return this.on( type, fn );
- };
-});
-
-
-jQuery._evalUrl = function( url ) {
- return jQuery.ajax({
- url: url,
- type: "GET",
- dataType: "script",
- async: false,
- global: false,
- "throws": true
- });
-};
-
-
-jQuery.fn.extend({
- wrapAll: function( html ) {
- var wrap;
-
- if ( jQuery.isFunction( html ) ) {
- return this.each(function( i ) {
- jQuery( this ).wrapAll( html.call(this, i) );
- });
- }
-
- if ( this[ 0 ] ) {
-
- // The elements to wrap the target around
- wrap = jQuery( html, this[ 0 ].ownerDocument ).eq( 0 ).clone( true );
-
- if ( this[ 0 ].parentNode ) {
- wrap.insertBefore( this[ 0 ] );
- }
-
- wrap.map(function() {
- var elem = this;
-
- while ( elem.firstElementChild ) {
- elem = elem.firstElementChild;
- }
-
- return elem;
- }).append( this );
- }
-
- return this;
- },
-
- wrapInner: function( html ) {
- if ( jQuery.isFunction( html ) ) {
- return this.each(function( i ) {
- jQuery( this ).wrapInner( html.call(this, i) );
- });
- }
-
- return this.each(function() {
- var self = jQuery( this ),
- contents = self.contents();
-
- if ( contents.length ) {
- contents.wrapAll( html );
-
- } else {
- self.append( html );
- }
- });
- },
-
- wrap: function( html ) {
- var isFunction = jQuery.isFunction( html );
-
- return this.each(function( i ) {
- jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html );
- });
- },
-
- unwrap: function() {
- return this.parent().each(function() {
- if ( !jQuery.nodeName( this, "body" ) ) {
- jQuery( this ).replaceWith( this.childNodes );
- }
- }).end();
- }
-});
-
-
-jQuery.expr.filters.hidden = function( elem ) {
- // Support: Opera <= 12.12
- // Opera reports offsetWidths and offsetHeights less than zero on some elements
- return elem.offsetWidth <= 0 && elem.offsetHeight <= 0;
-};
-jQuery.expr.filters.visible = function( elem ) {
- return !jQuery.expr.filters.hidden( elem );
-};
-
-
-
-
-var r20 = /%20/g,
- rbracket = /\[\]$/,
- rCRLF = /\r?\n/g,
- rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i,
- rsubmittable = /^(?:input|select|textarea|keygen)/i;
-
-function buildParams( prefix, obj, traditional, add ) {
- var name;
-
- if ( jQuery.isArray( obj ) ) {
- // Serialize array item.
- jQuery.each( obj, function( i, v ) {
- if ( traditional || rbracket.test( prefix ) ) {
- // Treat each array item as a scalar.
- add( prefix, v );
-
- } else {
- // Item is non-scalar (array or object), encode its numeric index.
- buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add );
- }
- });
-
- } else if ( !traditional && jQuery.type( obj ) === "object" ) {
- // Serialize object item.
- for ( name in obj ) {
- buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
- }
-
- } else {
- // Serialize scalar item.
- add( prefix, obj );
- }
-}
-
-// Serialize an array of form elements or a set of
-// key/values into a query string
-jQuery.param = function( a, traditional ) {
- var prefix,
- s = [],
- add = function( key, value ) {
- // If value is a function, invoke it and return its value
- value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value );
- s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
- };
-
- // Set traditional to true for jQuery <= 1.3.2 behavior.
- if ( traditional === undefined ) {
- traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional;
- }
-
- // If an array was passed in, assume that it is an array of form elements.
- if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {
- // Serialize the form elements
- jQuery.each( a, function() {
- add( this.name, this.value );
- });
-
- } else {
- // If traditional, encode the "old" way (the way 1.3.2 or older
- // did it), otherwise encode params recursively.
- for ( prefix in a ) {
- buildParams( prefix, a[ prefix ], traditional, add );
- }
- }
-
- // Return the resulting serialization
- return s.join( "&" ).replace( r20, "+" );
-};
-
-jQuery.fn.extend({
- serialize: function() {
- return jQuery.param( this.serializeArray() );
- },
- serializeArray: function() {
- return this.map(function() {
- // Can add propHook for "elements" to filter or add form elements
- var elements = jQuery.prop( this, "elements" );
- return elements ? jQuery.makeArray( elements ) : this;
- })
- .filter(function() {
- var type = this.type;
-
- // Use .is( ":disabled" ) so that fieldset[disabled] works
- return this.name && !jQuery( this ).is( ":disabled" ) &&
- rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) &&
- ( this.checked || !rcheckableType.test( type ) );
- })
- .map(function( i, elem ) {
- var val = jQuery( this ).val();
-
- return val == null ?
- null :
- jQuery.isArray( val ) ?
- jQuery.map( val, function( val ) {
- return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
- }) :
- { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
- }).get();
- }
-});
-
-
-jQuery.ajaxSettings.xhr = function() {
- try {
- return new XMLHttpRequest();
- } catch( e ) {}
-};
-
-var xhrId = 0,
- xhrCallbacks = {},
- xhrSuccessStatus = {
- // file protocol always yields status code 0, assume 200
- 0: 200,
- // Support: IE9
- // #1450: sometimes IE returns 1223 when it should be 204
- 1223: 204
- },
- xhrSupported = jQuery.ajaxSettings.xhr();
-
-// Support: IE9
-// Open requests must be manually aborted on unload (#5280)
-if ( window.ActiveXObject ) {
- jQuery( window ).on( "unload", function() {
- for ( var key in xhrCallbacks ) {
- xhrCallbacks[ key ]();
- }
- });
-}
-
-support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported );
-support.ajax = xhrSupported = !!xhrSupported;
-
-jQuery.ajaxTransport(function( options ) {
- var callback;
-
- // Cross domain only allowed if supported through XMLHttpRequest
- if ( support.cors || xhrSupported && !options.crossDomain ) {
- return {
- send: function( headers, complete ) {
- var i,
- xhr = options.xhr(),
- id = ++xhrId;
-
- xhr.open( options.type, options.url, options.async, options.username, options.password );
-
- // Apply custom fields if provided
- if ( options.xhrFields ) {
- for ( i in options.xhrFields ) {
- xhr[ i ] = options.xhrFields[ i ];
- }
- }
-
- // Override mime type if needed
- if ( options.mimeType && xhr.overrideMimeType ) {
- xhr.overrideMimeType( options.mimeType );
- }
-
- // X-Requested-With header
- // For cross-domain requests, seeing as conditions for a preflight are
- // akin to a jigsaw puzzle, we simply never set it to be sure.
- // (it can always be set on a per-request basis or even using ajaxSetup)
- // For same-domain requests, won't change header if already provided.
- if ( !options.crossDomain && !headers["X-Requested-With"] ) {
- headers["X-Requested-With"] = "XMLHttpRequest";
- }
-
- // Set headers
- for ( i in headers ) {
- xhr.setRequestHeader( i, headers[ i ] );
- }
-
- // Callback
- callback = function( type ) {
- return function() {
- if ( callback ) {
- delete xhrCallbacks[ id ];
- callback = xhr.onload = xhr.onerror = null;
-
- if ( type === "abort" ) {
- xhr.abort();
- } else if ( type === "error" ) {
- complete(
- // file: protocol always yields status 0; see #8605, #14207
- xhr.status,
- xhr.statusText
- );
- } else {
- complete(
- xhrSuccessStatus[ xhr.status ] || xhr.status,
- xhr.statusText,
- // Support: IE9
- // Accessing binary-data responseText throws an exception
- // (#11426)
- typeof xhr.responseText === "string" ? {
- text: xhr.responseText
- } : undefined,
- xhr.getAllResponseHeaders()
- );
- }
- }
- };
- };
-
- // Listen to events
- xhr.onload = callback();
- xhr.onerror = callback("error");
-
- // Create the abort callback
- callback = xhrCallbacks[ id ] = callback("abort");
-
- // Do send the request
- // This may raise an exception which is actually
- // handled in jQuery.ajax (so no try/catch here)
- xhr.send( options.hasContent && options.data || null );
- },
-
- abort: function() {
- if ( callback ) {
- callback();
- }
- }
- };
- }
-});
-
-
-
-
-// Install script dataType
-jQuery.ajaxSetup({
- accepts: {
- script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"
- },
- contents: {
- script: /(?:java|ecma)script/
- },
- converters: {
- "text script": function( text ) {
- jQuery.globalEval( text );
- return text;
- }
- }
-});
-
-// Handle cache's special case and crossDomain
-jQuery.ajaxPrefilter( "script", function( s ) {
- if ( s.cache === undefined ) {
- s.cache = false;
- }
- if ( s.crossDomain ) {
- s.type = "GET";
- }
-});
-
-// Bind script tag hack transport
-jQuery.ajaxTransport( "script", function( s ) {
- // This transport only deals with cross domain requests
- if ( s.crossDomain ) {
- var script, callback;
- return {
- send: function( _, complete ) {
- script = jQuery("<script>").prop({
- async: true,
- charset: s.scriptCharset,
- src: s.url
- }).on(
- "load error",
- callback = function( evt ) {
- script.remove();
- callback = null;
- if ( evt ) {
- complete( evt.type === "error" ? 404 : 200, evt.type );
- }
- }
- );
- document.head.appendChild( script[ 0 ] );
- },
- abort: function() {
- if ( callback ) {
- callback();
- }
- }
- };
- }
-});
-
-
-
-
-var oldCallbacks = [],
- rjsonp = /(=)\?(?=&|$)|\?\?/;
-
-// Default jsonp settings
-jQuery.ajaxSetup({
- jsonp: "callback",
- jsonpCallback: function() {
- var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( nonce++ ) );
- this[ callback ] = true;
- return callback;
- }
-});
-
-// Detect, normalize options and install callbacks for jsonp requests
-jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) {
-
- var callbackName, overwritten, responseContainer,
- jsonProp = s.jsonp !== false && ( rjsonp.test( s.url ) ?
- "url" :
- typeof s.data === "string" && !( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") && rjsonp.test( s.data ) && "data"
- );
-
- // Handle iff the expected data type is "jsonp" or we have a parameter to set
- if ( jsonProp || s.dataTypes[ 0 ] === "jsonp" ) {
-
- // Get callback name, remembering preexisting value associated with it
- callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ?
- s.jsonpCallback() :
- s.jsonpCallback;
-
- // Insert callback into url or form data
- if ( jsonProp ) {
- s[ jsonProp ] = s[ jsonProp ].replace( rjsonp, "$1" + callbackName );
- } else if ( s.jsonp !== false ) {
- s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName;
- }
-
- // Use data converter to retrieve json after script execution
- s.converters["script json"] = function() {
- if ( !responseContainer ) {
- jQuery.error( callbackName + " was not called" );
- }
- return responseContainer[ 0 ];
- };
-
- // force json dataType
- s.dataTypes[ 0 ] = "json";
-
- // Install callback
- overwritten = window[ callbackName ];
- window[ callbackName ] = function() {
- responseContainer = arguments;
- };
-
- // Clean-up function (fires after converters)
- jqXHR.always(function() {
- // Restore preexisting value
- window[ callbackName ] = overwritten;
-
- // Save back as free
- if ( s[ callbackName ] ) {
- // make sure that re-using the options doesn't screw things around
- s.jsonpCallback = originalSettings.jsonpCallback;
-
- // save the callback name for future use
- oldCallbacks.push( callbackName );
- }
-
- // Call if it was a function and we have a response
- if ( responseContainer && jQuery.isFunction( overwritten ) ) {
- overwritten( responseContainer[ 0 ] );
- }
-
- responseContainer = overwritten = undefined;
- });
-
- // Delegate to script
- return "script";
- }
-});
-
-
-
-
-// data: string of html
-// context (optional): If specified, the fragment will be created in this context, defaults to document
-// keepScripts (optional): If true, will include scripts passed in the html string
-jQuery.parseHTML = function( data, context, keepScripts ) {
- if ( !data || typeof data !== "string" ) {
- return null;
- }
- if ( typeof context === "boolean" ) {
- keepScripts = context;
- context = false;
- }
- context = context || document;
-
- var parsed = rsingleTag.exec( data ),
- scripts = !keepScripts && [];
-
- // Single tag
- if ( parsed ) {
- return [ context.createElement( parsed[1] ) ];
- }
-
- parsed = jQuery.buildFragment( [ data ], context, scripts );
-
- if ( scripts && scripts.length ) {
- jQuery( scripts ).remove();
- }
-
- return jQuery.merge( [], parsed.childNodes );
-};
-
-
-// Keep a copy of the old load method
-var _load = jQuery.fn.load;
-
-/**
- * Load a url into a page
- */
-jQuery.fn.load = function( url, params, callback ) {
- if ( typeof url !== "string" && _load ) {
- return _load.apply( this, arguments );
- }
-
- var selector, type, response,
- self = this,
- off = url.indexOf(" ");
-
- if ( off >= 0 ) {
- selector = url.slice( off );
- url = url.slice( 0, off );
- }
-
- // If it's a function
- if ( jQuery.isFunction( params ) ) {
-
- // We assume that it's the callback
- callback = params;
- params = undefined;
-
- // Otherwise, build a param string
- } else if ( params && typeof params === "object" ) {
- type = "POST";
- }
-
- // If we have elements to modify, make the request
- if ( self.length > 0 ) {
- jQuery.ajax({
- url: url,
-
- // if "type" variable is undefined, then "GET" method will be used
- type: type,
- dataType: "html",
- data: params
- }).done(function( responseText ) {
-
- // Save response for use in complete callback
- response = arguments;
-
- self.html( selector ?
-
- // If a selector was specified, locate the right elements in a dummy div
- // Exclude scripts to avoid IE 'Permission Denied' errors
- jQuery("<div>").append( jQuery.parseHTML( responseText ) ).find( selector ) :
-
- // Otherwise use the full result
- responseText );
-
- }).complete( callback && function( jqXHR, status ) {
- self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] );
- });
- }
-
- return this;
-};
-
-
-
-
-jQuery.expr.filters.animated = function( elem ) {
- return jQuery.grep(jQuery.timers, function( fn ) {
- return elem === fn.elem;
- }).length;
-};
-
-
-
-
-var docElem = window.document.documentElement;
-
-/**
- * Gets a window from an element
- */
-function getWindow( elem ) {
- return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 && elem.defaultView;
-}
-
-jQuery.offset = {
- setOffset: function( elem, options, i ) {
- var curPosition, curLeft, curCSSTop, curTop, curOffset, curCSSLeft, calculatePosition,
- position = jQuery.css( elem, "position" ),
- curElem = jQuery( elem ),
- props = {};
-
- // Set position first, in-case top/left are set even on static elem
- if ( position === "static" ) {
- elem.style.position = "relative";
- }
-
- curOffset = curElem.offset();
- curCSSTop = jQuery.css( elem, "top" );
- curCSSLeft = jQuery.css( elem, "left" );
- calculatePosition = ( position === "absolute" || position === "fixed" ) &&
- ( curCSSTop + curCSSLeft ).indexOf("auto") > -1;
-
- // Need to be able to calculate position if either top or left is auto and position is either absolute or fixed
- if ( calculatePosition ) {
- curPosition = curElem.position();
- curTop = curPosition.top;
- curLeft = curPosition.left;
-
- } else {
- curTop = parseFloat( curCSSTop ) || 0;
- curLeft = parseFloat( curCSSLeft ) || 0;
- }
-
- if ( jQuery.isFunction( options ) ) {
- options = options.call( elem, i, curOffset );
- }
-
- if ( options.top != null ) {
- props.top = ( options.top - curOffset.top ) + curTop;
- }
- if ( options.left != null ) {
- props.left = ( options.left - curOffset.left ) + curLeft;
- }
-
- if ( "using" in options ) {
- options.using.call( elem, props );
-
- } else {
- curElem.css( props );
- }
- }
-};
-
-jQuery.fn.extend({
- offset: function( options ) {
- if ( arguments.length ) {
- return options === undefined ?
- this :
- this.each(function( i ) {
- jQuery.offset.setOffset( this, options, i );
- });
- }
-
- var docElem, win,
- elem = this[ 0 ],
- box = { top: 0, left: 0 },
- doc = elem && elem.ownerDocument;
-
- if ( !doc ) {
- return;
- }
-
- docElem = doc.documentElement;
-
- // Make sure it's not a disconnected DOM node
- if ( !jQuery.contains( docElem, elem ) ) {
- return box;
- }
-
- // If we don't have gBCR, just use 0,0 rather than error
- // BlackBerry 5, iOS 3 (original iPhone)
- if ( typeof elem.getBoundingClientRect !== strundefined ) {
- box = elem.getBoundingClientRect();
- }
- win = getWindow( doc );
- return {
- top: box.top + win.pageYOffset - docElem.clientTop,
- left: box.left + win.pageXOffset - docElem.clientLeft
- };
- },
-
- position: function() {
- if ( !this[ 0 ] ) {
- return;
- }
-
- var offsetParent, offset,
- elem = this[ 0 ],
- parentOffset = { top: 0, left: 0 };
-
- // Fixed elements are offset from window (parentOffset = {top:0, left: 0}, because it is its only offset parent
- if ( jQuery.css( elem, "position" ) === "fixed" ) {
- // We assume that getBoundingClientRect is available when computed position is fixed
- offset = elem.getBoundingClientRect();
-
- } else {
- // Get *real* offsetParent
- offsetParent = this.offsetParent();
-
- // Get correct offsets
- offset = this.offset();
- if ( !jQuery.nodeName( offsetParent[ 0 ], "html" ) ) {
- parentOffset = offsetParent.offset();
- }
-
- // Add offsetParent borders
- parentOffset.top += jQuery.css( offsetParent[ 0 ], "borderTopWidth", true );
- parentOffset.left += jQuery.css( offsetParent[ 0 ], "borderLeftWidth", true );
- }
-
- // Subtract parent offsets and element margins
- return {
- top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ),
- left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true )
- };
- },
-
- offsetParent: function() {
- return this.map(function() {
- var offsetParent = this.offsetParent || docElem;
-
- while ( offsetParent && ( !jQuery.nodeName( offsetParent, "html" ) && jQuery.css( offsetParent, "position" ) === "static" ) ) {
- offsetParent = offsetParent.offsetParent;
- }
-
- return offsetParent || docElem;
- });
- }
-});
-
-// Create scrollLeft and scrollTop methods
-jQuery.each( { scrollLeft: "pageXOffset", scrollTop: "pageYOffset" }, function( method, prop ) {
- var top = "pageYOffset" === prop;
-
- jQuery.fn[ method ] = function( val ) {
- return access( this, function( elem, method, val ) {
- var win = getWindow( elem );
-
- if ( val === undefined ) {
- return win ? win[ prop ] : elem[ method ];
- }
-
- if ( win ) {
- win.scrollTo(
- !top ? val : window.pageXOffset,
- top ? val : window.pageYOffset
- );
-
- } else {
- elem[ method ] = val;
- }
- }, method, val, arguments.length, null );
- };
-});
-
-// Add the top/left cssHooks using jQuery.fn.position
-// Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084
-// getComputedStyle returns percent when specified for top/left/bottom/right
-// rather than make the css module depend on the offset module, we just check for it here
-jQuery.each( [ "top", "left" ], function( i, prop ) {
- jQuery.cssHooks[ prop ] = addGetHookIf( support.pixelPosition,
- function( elem, computed ) {
- if ( computed ) {
- computed = curCSS( elem, prop );
- // if curCSS returns percentage, fallback to offset
- return rnumnonpx.test( computed ) ?
- jQuery( elem ).position()[ prop ] + "px" :
- computed;
- }
- }
- );
-});
-
-
-// Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods
-jQuery.each( { Height: "height", Width: "width" }, function( name, type ) {
- jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name }, function( defaultExtra, funcName ) {
- // margin is only for outerHeight, outerWidth
- jQuery.fn[ funcName ] = function( margin, value ) {
- var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ),
- extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" );
-
- return access( this, function( elem, type, value ) {
- var doc;
-
- if ( jQuery.isWindow( elem ) ) {
- // As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there
- // isn't a whole lot we can do. See pull request at this URL for discussion:
- // https://github.com/jquery/jquery/pull/764
- return elem.document.documentElement[ "client" + name ];
- }
-
- // Get document width or height
- if ( elem.nodeType === 9 ) {
- doc = elem.documentElement;
-
- // Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height],
- // whichever is greatest
- return Math.max(
- elem.body[ "scroll" + name ], doc[ "scroll" + name ],
- elem.body[ "offset" + name ], doc[ "offset" + name ],
- doc[ "client" + name ]
- );
- }
-
- return value === undefined ?
- // Get width or height on the element, requesting but not forcing parseFloat
- jQuery.css( elem, type, extra ) :
-
- // Set width or height on the element
- jQuery.style( elem, type, value, extra );
- }, type, chainable ? margin : undefined, chainable, null );
- };
- });
-});
-
-
-// The number of elements contained in the matched element set
-jQuery.fn.size = function() {
- return this.length;
-};
-
-jQuery.fn.andSelf = jQuery.fn.addBack;
-
-
-
-
-// Register as a named AMD module, since jQuery can be concatenated with other
-// files that may use define, but not via a proper concatenation script that
-// understands anonymous AMD modules. A named AMD is safest and most robust
-// way to register. Lowercase jquery is used because AMD module names are
-// derived from file names, and jQuery is normally delivered in a lowercase
-// file name. Do this after creating the global so that if an AMD module wants
-// to call noConflict to hide this version of jQuery, it will work.
-if ( typeof define === "function" && define.amd ) {
- define( "jquery", [], function() {
- return jQuery;
- });
-}
-
-
-
-
-var
- // Map over jQuery in case of overwrite
- _jQuery = window.jQuery,
-
- // Map over the $ in case of overwrite
- _$ = window.$;
-
-jQuery.noConflict = function( deep ) {
- if ( window.$ === jQuery ) {
- window.$ = _$;
- }
-
- if ( deep && window.jQuery === jQuery ) {
- window.jQuery = _jQuery;
- }
-
- return jQuery;
-};
-
-// Expose jQuery and $ identifiers, even in
-// AMD (#7102#comment:10, https://github.com/jquery/jquery/pull/557)
-// and CommonJS for browser emulators (#13566)
-if ( typeof noGlobal === strundefined ) {
- window.jQuery = window.$ = jQuery;
-}
-
-
-
-
-return jQuery;
-
-}));
--- a/server/python/django/renkanmanager/static/renkanmanager/lib/jquery.min.js Fri Apr 24 13:05:09 2015 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,4 +0,0 @@
-/*! jQuery v2.1.0 | (c) 2005, 2014 jQuery Foundation, Inc. | jquery.org/license */
-!function(a,b){"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){var c=[],d=c.slice,e=c.concat,f=c.push,g=c.indexOf,h={},i=h.toString,j=h.hasOwnProperty,k="".trim,l={},m=a.document,n="2.1.0",o=function(a,b){return new o.fn.init(a,b)},p=/^-ms-/,q=/-([\da-z])/gi,r=function(a,b){return b.toUpperCase()};o.fn=o.prototype={jquery:n,constructor:o,selector:"",length:0,toArray:function(){return d.call(this)},get:function(a){return null!=a?0>a?this[a+this.length]:this[a]:d.call(this)},pushStack:function(a){var b=o.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a,b){return o.each(this,a,b)},map:function(a){return this.pushStack(o.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(d.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(0>a?b:0);return this.pushStack(c>=0&&b>c?[this[c]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:c.sort,splice:c.splice},o.extend=o.fn.extend=function(){var a,b,c,d,e,f,g=arguments[0]||{},h=1,i=arguments.length,j=!1;for("boolean"==typeof g&&(j=g,g=arguments[h]||{},h++),"object"==typeof g||o.isFunction(g)||(g={}),h===i&&(g=this,h--);i>h;h++)if(null!=(a=arguments[h]))for(b in a)c=g[b],d=a[b],g!==d&&(j&&d&&(o.isPlainObject(d)||(e=o.isArray(d)))?(e?(e=!1,f=c&&o.isArray(c)?c:[]):f=c&&o.isPlainObject(c)?c:{},g[b]=o.extend(j,f,d)):void 0!==d&&(g[b]=d));return g},o.extend({expando:"jQuery"+(n+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===o.type(a)},isArray:Array.isArray,isWindow:function(a){return null!=a&&a===a.window},isNumeric:function(a){return a-parseFloat(a)>=0},isPlainObject:function(a){if("object"!==o.type(a)||a.nodeType||o.isWindow(a))return!1;try{if(a.constructor&&!j.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(b){return!1}return!0},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?h[i.call(a)]||"object":typeof a},globalEval:function(a){var b,c=eval;a=o.trim(a),a&&(1===a.indexOf("use strict")?(b=m.createElement("script"),b.text=a,m.head.appendChild(b).parentNode.removeChild(b)):c(a))},camelCase:function(a){return a.replace(p,"ms-").replace(q,r)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b,c){var d,e=0,f=a.length,g=s(a);if(c){if(g){for(;f>e;e++)if(d=b.apply(a[e],c),d===!1)break}else for(e in a)if(d=b.apply(a[e],c),d===!1)break}else if(g){for(;f>e;e++)if(d=b.call(a[e],e,a[e]),d===!1)break}else for(e in a)if(d=b.call(a[e],e,a[e]),d===!1)break;return a},trim:function(a){return null==a?"":k.call(a)},makeArray:function(a,b){var c=b||[];return null!=a&&(s(Object(a))?o.merge(c,"string"==typeof a?[a]:a):f.call(c,a)),c},inArray:function(a,b,c){return null==b?-1:g.call(b,a,c)},merge:function(a,b){for(var c=+b.length,d=0,e=a.length;c>d;d++)a[e++]=b[d];return a.length=e,a},grep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;g>f;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e},map:function(a,b,c){var d,f=0,g=a.length,h=s(a),i=[];if(h)for(;g>f;f++)d=b(a[f],f,c),null!=d&&i.push(d);else for(f in a)d=b(a[f],f,c),null!=d&&i.push(d);return e.apply([],i)},guid:1,proxy:function(a,b){var c,e,f;return"string"==typeof b&&(c=a[b],b=a,a=c),o.isFunction(a)?(e=d.call(arguments,2),f=function(){return a.apply(b||this,e.concat(d.call(arguments)))},f.guid=a.guid=a.guid||o.guid++,f):void 0},now:Date.now,support:l}),o.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(a,b){h["[object "+b+"]"]=b.toLowerCase()});function s(a){var b=a.length,c=o.type(a);return"function"===c||o.isWindow(a)?!1:1===a.nodeType&&b?!0:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}var t=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s="sizzle"+-new Date,t=a.document,u=0,v=0,w=eb(),x=eb(),y=eb(),z=function(a,b){return a===b&&(j=!0),0},A="undefined",B=1<<31,C={}.hasOwnProperty,D=[],E=D.pop,F=D.push,G=D.push,H=D.slice,I=D.indexOf||function(a){for(var b=0,c=this.length;c>b;b++)if(this[b]===a)return b;return-1},J="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",K="[\\x20\\t\\r\\n\\f]",L="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",M=L.replace("w","w#"),N="\\["+K+"*("+L+")"+K+"*(?:([*^$|!~]?=)"+K+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+M+")|)|)"+K+"*\\]",O=":("+L+")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|"+N.replace(3,8)+")*)|.*)\\)|)",P=new RegExp("^"+K+"+|((?:^|[^\\\\])(?:\\\\.)*)"+K+"+$","g"),Q=new RegExp("^"+K+"*,"+K+"*"),R=new RegExp("^"+K+"*([>+~]|"+K+")"+K+"*"),S=new RegExp("="+K+"*([^\\]'\"]*?)"+K+"*\\]","g"),T=new RegExp(O),U=new RegExp("^"+M+"$"),V={ID:new RegExp("^#("+L+")"),CLASS:new RegExp("^\\.("+L+")"),TAG:new RegExp("^("+L.replace("w","w*")+")"),ATTR:new RegExp("^"+N),PSEUDO:new RegExp("^"+O),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+K+"*(even|odd|(([+-]|)(\\d*)n|)"+K+"*(?:([+-]|)"+K+"*(\\d+)|))"+K+"*\\)|)","i"),bool:new RegExp("^(?:"+J+")$","i"),needsContext:new RegExp("^"+K+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+K+"*((?:-\\d)?\\d*)"+K+"*\\)|)(?=[^-]|$)","i")},W=/^(?:input|select|textarea|button)$/i,X=/^h\d$/i,Y=/^[^{]+\{\s*\[native \w/,Z=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,$=/[+~]/,_=/'|\\/g,ab=new RegExp("\\\\([\\da-f]{1,6}"+K+"?|("+K+")|.)","ig"),bb=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:0>d?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)};try{G.apply(D=H.call(t.childNodes),t.childNodes),D[t.childNodes.length].nodeType}catch(cb){G={apply:D.length?function(a,b){F.apply(a,H.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function db(a,b,d,e){var f,g,h,i,j,m,p,q,u,v;if((b?b.ownerDocument||b:t)!==l&&k(b),b=b||l,d=d||[],!a||"string"!=typeof a)return d;if(1!==(i=b.nodeType)&&9!==i)return[];if(n&&!e){if(f=Z.exec(a))if(h=f[1]){if(9===i){if(g=b.getElementById(h),!g||!g.parentNode)return d;if(g.id===h)return d.push(g),d}else if(b.ownerDocument&&(g=b.ownerDocument.getElementById(h))&&r(b,g)&&g.id===h)return d.push(g),d}else{if(f[2])return G.apply(d,b.getElementsByTagName(a)),d;if((h=f[3])&&c.getElementsByClassName&&b.getElementsByClassName)return G.apply(d,b.getElementsByClassName(h)),d}if(c.qsa&&(!o||!o.test(a))){if(q=p=s,u=b,v=9===i&&a,1===i&&"object"!==b.nodeName.toLowerCase()){m=ob(a),(p=b.getAttribute("id"))?q=p.replace(_,"\\$&"):b.setAttribute("id",q),q="[id='"+q+"'] ",j=m.length;while(j--)m[j]=q+pb(m[j]);u=$.test(a)&&mb(b.parentNode)||b,v=m.join(",")}if(v)try{return G.apply(d,u.querySelectorAll(v)),d}catch(w){}finally{p||b.removeAttribute("id")}}}return xb(a.replace(P,"$1"),b,d,e)}function eb(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function fb(a){return a[s]=!0,a}function gb(a){var b=l.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function hb(a,b){var c=a.split("|"),e=a.length;while(e--)d.attrHandle[c[e]]=b}function ib(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||B)-(~a.sourceIndex||B);if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function jb(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function kb(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function lb(a){return fb(function(b){return b=+b,fb(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function mb(a){return a&&typeof a.getElementsByTagName!==A&&a}c=db.support={},f=db.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},k=db.setDocument=function(a){var b,e=a?a.ownerDocument||a:t,g=e.defaultView;return e!==l&&9===e.nodeType&&e.documentElement?(l=e,m=e.documentElement,n=!f(e),g&&g!==g.top&&(g.addEventListener?g.addEventListener("unload",function(){k()},!1):g.attachEvent&&g.attachEvent("onunload",function(){k()})),c.attributes=gb(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=gb(function(a){return a.appendChild(e.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=Y.test(e.getElementsByClassName)&&gb(function(a){return a.innerHTML="<div class='a'></div><div class='a i'></div>",a.firstChild.className="i",2===a.getElementsByClassName("i").length}),c.getById=gb(function(a){return m.appendChild(a).id=s,!e.getElementsByName||!e.getElementsByName(s).length}),c.getById?(d.find.ID=function(a,b){if(typeof b.getElementById!==A&&n){var c=b.getElementById(a);return c&&c.parentNode?[c]:[]}},d.filter.ID=function(a){var b=a.replace(ab,bb);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(ab,bb);return function(a){var c=typeof a.getAttributeNode!==A&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return typeof b.getElementsByTagName!==A?b.getElementsByTagName(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){return typeof b.getElementsByClassName!==A&&n?b.getElementsByClassName(a):void 0},p=[],o=[],(c.qsa=Y.test(e.querySelectorAll))&&(gb(function(a){a.innerHTML="<select t=''><option selected=''></option></select>",a.querySelectorAll("[t^='']").length&&o.push("[*^$]="+K+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||o.push("\\["+K+"*(?:value|"+J+")"),a.querySelectorAll(":checked").length||o.push(":checked")}),gb(function(a){var b=e.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&o.push("name"+K+"*[*^$|!~]?="),a.querySelectorAll(":enabled").length||o.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),o.push(",.*:")})),(c.matchesSelector=Y.test(q=m.webkitMatchesSelector||m.mozMatchesSelector||m.oMatchesSelector||m.msMatchesSelector))&&gb(function(a){c.disconnectedMatch=q.call(a,"div"),q.call(a,"[s!='']:x"),p.push("!=",O)}),o=o.length&&new RegExp(o.join("|")),p=p.length&&new RegExp(p.join("|")),b=Y.test(m.compareDocumentPosition),r=b||Y.test(m.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)while(b=b.parentNode)if(b===a)return!0;return!1},z=b?function(a,b){if(a===b)return j=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===e||a.ownerDocument===t&&r(t,a)?-1:b===e||b.ownerDocument===t&&r(t,b)?1:i?I.call(i,a)-I.call(i,b):0:4&d?-1:1)}:function(a,b){if(a===b)return j=!0,0;var c,d=0,f=a.parentNode,g=b.parentNode,h=[a],k=[b];if(!f||!g)return a===e?-1:b===e?1:f?-1:g?1:i?I.call(i,a)-I.call(i,b):0;if(f===g)return ib(a,b);c=a;while(c=c.parentNode)h.unshift(c);c=b;while(c=c.parentNode)k.unshift(c);while(h[d]===k[d])d++;return d?ib(h[d],k[d]):h[d]===t?-1:k[d]===t?1:0},e):l},db.matches=function(a,b){return db(a,null,null,b)},db.matchesSelector=function(a,b){if((a.ownerDocument||a)!==l&&k(a),b=b.replace(S,"='$1']"),!(!c.matchesSelector||!n||p&&p.test(b)||o&&o.test(b)))try{var d=q.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return db(b,l,null,[a]).length>0},db.contains=function(a,b){return(a.ownerDocument||a)!==l&&k(a),r(a,b)},db.attr=function(a,b){(a.ownerDocument||a)!==l&&k(a);var e=d.attrHandle[b.toLowerCase()],f=e&&C.call(d.attrHandle,b.toLowerCase())?e(a,b,!n):void 0;return void 0!==f?f:c.attributes||!n?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},db.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},db.uniqueSort=function(a){var b,d=[],e=0,f=0;if(j=!c.detectDuplicates,i=!c.sortStable&&a.slice(0),a.sort(z),j){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return i=null,a},e=db.getText=function(a){var b,c="",d=0,f=a.nodeType;if(f){if(1===f||9===f||11===f){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=e(a)}else if(3===f||4===f)return a.nodeValue}else while(b=a[d++])c+=e(b);return c},d=db.selectors={cacheLength:50,createPseudo:fb,match:V,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(ab,bb),a[3]=(a[4]||a[5]||"").replace(ab,bb),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||db.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&db.error(a[0]),a},PSEUDO:function(a){var b,c=!a[5]&&a[2];return V.CHILD.test(a[0])?null:(a[3]&&void 0!==a[4]?a[2]=a[4]:c&&T.test(c)&&(b=ob(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(ab,bb).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=w[a+" "];return b||(b=new RegExp("(^|"+K+")"+a+"("+K+"|$)"))&&w(a,function(a){return b.test("string"==typeof a.className&&a.className||typeof a.getAttribute!==A&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=db.attr(d,a);return null==e?"!="===b:b?(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e+" ").indexOf(c)>-1:"|="===b?e===c||e.slice(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),t=!i&&!h;if(q){if(f){while(p){l=b;while(l=l[p])if(h?l.nodeName.toLowerCase()===r:1===l.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&t){k=q[s]||(q[s]={}),j=k[a]||[],n=j[0]===u&&j[1],m=j[0]===u&&j[2],l=n&&q.childNodes[n];while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if(1===l.nodeType&&++m&&l===b){k[a]=[u,n,m];break}}else if(t&&(j=(b[s]||(b[s]={}))[a])&&j[0]===u)m=j[1];else while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if((h?l.nodeName.toLowerCase()===r:1===l.nodeType)&&++m&&(t&&((l[s]||(l[s]={}))[a]=[u,m]),l===b))break;return m-=e,m===d||m%d===0&&m/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||db.error("unsupported pseudo: "+a);return e[s]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?fb(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=I.call(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:fb(function(a){var b=[],c=[],d=g(a.replace(P,"$1"));return d[s]?fb(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),!c.pop()}}),has:fb(function(a){return function(b){return db(a,b).length>0}}),contains:fb(function(a){return function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:fb(function(a){return U.test(a||"")||db.error("unsupported lang: "+a),a=a.replace(ab,bb).toLowerCase(),function(b){var c;do if(c=n?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===m},focus:function(a){return a===l.activeElement&&(!l.hasFocus||l.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return X.test(a.nodeName)},input:function(a){return W.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:lb(function(){return[0]}),last:lb(function(a,b){return[b-1]}),eq:lb(function(a,b,c){return[0>c?c+b:c]}),even:lb(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:lb(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:lb(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:lb(function(a,b,c){for(var d=0>c?c+b:c;++d<b;)a.push(d);return a})}},d.pseudos.nth=d.pseudos.eq;for(b in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})d.pseudos[b]=jb(b);for(b in{submit:!0,reset:!0})d.pseudos[b]=kb(b);function nb(){}nb.prototype=d.filters=d.pseudos,d.setFilters=new nb;function ob(a,b){var c,e,f,g,h,i,j,k=x[a+" "];if(k)return b?0:k.slice(0);h=a,i=[],j=d.preFilter;while(h){(!c||(e=Q.exec(h)))&&(e&&(h=h.slice(e[0].length)||h),i.push(f=[])),c=!1,(e=R.exec(h))&&(c=e.shift(),f.push({value:c,type:e[0].replace(P," ")}),h=h.slice(c.length));for(g in d.filter)!(e=V[g].exec(h))||j[g]&&!(e=j[g](e))||(c=e.shift(),f.push({value:c,type:g,matches:e}),h=h.slice(c.length));if(!c)break}return b?h.length:h?db.error(a):x(a,i).slice(0)}function pb(a){for(var b=0,c=a.length,d="";c>b;b++)d+=a[b].value;return d}function qb(a,b,c){var d=b.dir,e=c&&"parentNode"===d,f=v++;return b.first?function(b,c,f){while(b=b[d])if(1===b.nodeType||e)return a(b,c,f)}:function(b,c,g){var h,i,j=[u,f];if(g){while(b=b[d])if((1===b.nodeType||e)&&a(b,c,g))return!0}else while(b=b[d])if(1===b.nodeType||e){if(i=b[s]||(b[s]={}),(h=i[d])&&h[0]===u&&h[1]===f)return j[2]=h[2];if(i[d]=j,j[2]=a(b,c,g))return!0}}}function rb(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function sb(a,b,c,d,e){for(var f,g=[],h=0,i=a.length,j=null!=b;i>h;h++)(f=a[h])&&(!c||c(f,d,e))&&(g.push(f),j&&b.push(h));return g}function tb(a,b,c,d,e,f){return d&&!d[s]&&(d=tb(d)),e&&!e[s]&&(e=tb(e,f)),fb(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||wb(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:sb(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=sb(r,n),d(j,[],h,i),k=j.length;while(k--)(l=j[k])&&(r[n[k]]=!(q[n[k]]=l))}if(f){if(e||a){if(e){j=[],k=r.length;while(k--)(l=r[k])&&j.push(q[k]=l);e(null,r=[],j,i)}k=r.length;while(k--)(l=r[k])&&(j=e?I.call(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=sb(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):G.apply(g,r)})}function ub(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],i=g||d.relative[" "],j=g?1:0,k=qb(function(a){return a===b},i,!0),l=qb(function(a){return I.call(b,a)>-1},i,!0),m=[function(a,c,d){return!g&&(d||c!==h)||((b=c).nodeType?k(a,c,d):l(a,c,d))}];f>j;j++)if(c=d.relative[a[j].type])m=[qb(rb(m),c)];else{if(c=d.filter[a[j].type].apply(null,a[j].matches),c[s]){for(e=++j;f>e;e++)if(d.relative[a[e].type])break;return tb(j>1&&rb(m),j>1&&pb(a.slice(0,j-1).concat({value:" "===a[j-2].type?"*":""})).replace(P,"$1"),c,e>j&&ub(a.slice(j,e)),f>e&&ub(a=a.slice(e)),f>e&&pb(a))}m.push(c)}return rb(m)}function vb(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,i,j,k){var m,n,o,p=0,q="0",r=f&&[],s=[],t=h,v=f||e&&d.find.TAG("*",k),w=u+=null==t?1:Math.random()||.1,x=v.length;for(k&&(h=g!==l&&g);q!==x&&null!=(m=v[q]);q++){if(e&&m){n=0;while(o=a[n++])if(o(m,g,i)){j.push(m);break}k&&(u=w)}c&&((m=!o&&m)&&p--,f&&r.push(m))}if(p+=q,c&&q!==p){n=0;while(o=b[n++])o(r,s,g,i);if(f){if(p>0)while(q--)r[q]||s[q]||(s[q]=E.call(j));s=sb(s)}G.apply(j,s),k&&!f&&s.length>0&&p+b.length>1&&db.uniqueSort(j)}return k&&(u=w,h=t),r};return c?fb(f):f}g=db.compile=function(a,b){var c,d=[],e=[],f=y[a+" "];if(!f){b||(b=ob(a)),c=b.length;while(c--)f=ub(b[c]),f[s]?d.push(f):e.push(f);f=y(a,vb(e,d))}return f};function wb(a,b,c){for(var d=0,e=b.length;e>d;d++)db(a,b[d],c);return c}function xb(a,b,e,f){var h,i,j,k,l,m=ob(a);if(!f&&1===m.length){if(i=m[0]=m[0].slice(0),i.length>2&&"ID"===(j=i[0]).type&&c.getById&&9===b.nodeType&&n&&d.relative[i[1].type]){if(b=(d.find.ID(j.matches[0].replace(ab,bb),b)||[])[0],!b)return e;a=a.slice(i.shift().value.length)}h=V.needsContext.test(a)?0:i.length;while(h--){if(j=i[h],d.relative[k=j.type])break;if((l=d.find[k])&&(f=l(j.matches[0].replace(ab,bb),$.test(i[0].type)&&mb(b.parentNode)||b))){if(i.splice(h,1),a=f.length&&pb(i),!a)return G.apply(e,f),e;break}}}return g(a,m)(f,b,!n,e,$.test(a)&&mb(b.parentNode)||b),e}return c.sortStable=s.split("").sort(z).join("")===s,c.detectDuplicates=!!j,k(),c.sortDetached=gb(function(a){return 1&a.compareDocumentPosition(l.createElement("div"))}),gb(function(a){return a.innerHTML="<a href='#'></a>","#"===a.firstChild.getAttribute("href")})||hb("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&gb(function(a){return a.innerHTML="<input/>",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||hb("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),gb(function(a){return null==a.getAttribute("disabled")})||hb(J,function(a,b,c){var d;return c?void 0:a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),db}(a);o.find=t,o.expr=t.selectors,o.expr[":"]=o.expr.pseudos,o.unique=t.uniqueSort,o.text=t.getText,o.isXMLDoc=t.isXML,o.contains=t.contains;var u=o.expr.match.needsContext,v=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,w=/^.[^:#\[\.,]*$/;function x(a,b,c){if(o.isFunction(b))return o.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return o.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(w.test(b))return o.filter(b,a,c);b=o.filter(b,a)}return o.grep(a,function(a){return g.call(b,a)>=0!==c})}o.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?o.find.matchesSelector(d,a)?[d]:[]:o.find.matches(a,o.grep(b,function(a){return 1===a.nodeType}))},o.fn.extend({find:function(a){var b,c=this.length,d=[],e=this;if("string"!=typeof a)return this.pushStack(o(a).filter(function(){for(b=0;c>b;b++)if(o.contains(e[b],this))return!0}));for(b=0;c>b;b++)o.find(a,e[b],d);return d=this.pushStack(c>1?o.unique(d):d),d.selector=this.selector?this.selector+" "+a:a,d},filter:function(a){return this.pushStack(x(this,a||[],!1))},not:function(a){return this.pushStack(x(this,a||[],!0))},is:function(a){return!!x(this,"string"==typeof a&&u.test(a)?o(a):a||[],!1).length}});var y,z=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,A=o.fn.init=function(a,b){var c,d;if(!a)return this;if("string"==typeof a){if(c="<"===a[0]&&">"===a[a.length-1]&&a.length>=3?[null,a,null]:z.exec(a),!c||!c[1]&&b)return!b||b.jquery?(b||y).find(a):this.constructor(b).find(a);if(c[1]){if(b=b instanceof o?b[0]:b,o.merge(this,o.parseHTML(c[1],b&&b.nodeType?b.ownerDocument||b:m,!0)),v.test(c[1])&&o.isPlainObject(b))for(c in b)o.isFunction(this[c])?this[c](b[c]):this.attr(c,b[c]);return this}return d=m.getElementById(c[2]),d&&d.parentNode&&(this.length=1,this[0]=d),this.context=m,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):o.isFunction(a)?"undefined"!=typeof y.ready?y.ready(a):a(o):(void 0!==a.selector&&(this.selector=a.selector,this.context=a.context),o.makeArray(a,this))};A.prototype=o.fn,y=o(m);var B=/^(?:parents|prev(?:Until|All))/,C={children:!0,contents:!0,next:!0,prev:!0};o.extend({dir:function(a,b,c){var d=[],e=void 0!==c;while((a=a[b])&&9!==a.nodeType)if(1===a.nodeType){if(e&&o(a).is(c))break;d.push(a)}return d},sibling:function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c}}),o.fn.extend({has:function(a){var b=o(a,this),c=b.length;return this.filter(function(){for(var a=0;c>a;a++)if(o.contains(this,b[a]))return!0})},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=u.test(a)||"string"!=typeof a?o(a,b||this.context):0;e>d;d++)for(c=this[d];c&&c!==b;c=c.parentNode)if(c.nodeType<11&&(g?g.index(c)>-1:1===c.nodeType&&o.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?o.unique(f):f)},index:function(a){return a?"string"==typeof a?g.call(o(a),this[0]):g.call(this,a.jquery?a[0]:a):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(o.unique(o.merge(this.get(),o(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function D(a,b){while((a=a[b])&&1!==a.nodeType);return a}o.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return o.dir(a,"parentNode")},parentsUntil:function(a,b,c){return o.dir(a,"parentNode",c)},next:function(a){return D(a,"nextSibling")},prev:function(a){return D(a,"previousSibling")},nextAll:function(a){return o.dir(a,"nextSibling")},prevAll:function(a){return o.dir(a,"previousSibling")},nextUntil:function(a,b,c){return o.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return o.dir(a,"previousSibling",c)},siblings:function(a){return o.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return o.sibling(a.firstChild)},contents:function(a){return a.contentDocument||o.merge([],a.childNodes)}},function(a,b){o.fn[a]=function(c,d){var e=o.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=o.filter(d,e)),this.length>1&&(C[a]||o.unique(e),B.test(a)&&e.reverse()),this.pushStack(e)}});var E=/\S+/g,F={};function G(a){var b=F[a]={};return o.each(a.match(E)||[],function(a,c){b[c]=!0}),b}o.Callbacks=function(a){a="string"==typeof a?F[a]||G(a):o.extend({},a);var b,c,d,e,f,g,h=[],i=!a.once&&[],j=function(l){for(b=a.memory&&l,c=!0,g=e||0,e=0,f=h.length,d=!0;h&&f>g;g++)if(h[g].apply(l[0],l[1])===!1&&a.stopOnFalse){b=!1;break}d=!1,h&&(i?i.length&&j(i.shift()):b?h=[]:k.disable())},k={add:function(){if(h){var c=h.length;!function g(b){o.each(b,function(b,c){var d=o.type(c);"function"===d?a.unique&&k.has(c)||h.push(c):c&&c.length&&"string"!==d&&g(c)})}(arguments),d?f=h.length:b&&(e=c,j(b))}return this},remove:function(){return h&&o.each(arguments,function(a,b){var c;while((c=o.inArray(b,h,c))>-1)h.splice(c,1),d&&(f>=c&&f--,g>=c&&g--)}),this},has:function(a){return a?o.inArray(a,h)>-1:!(!h||!h.length)},empty:function(){return h=[],f=0,this},disable:function(){return h=i=b=void 0,this},disabled:function(){return!h},lock:function(){return i=void 0,b||k.disable(),this},locked:function(){return!i},fireWith:function(a,b){return!h||c&&!i||(b=b||[],b=[a,b.slice?b.slice():b],d?i.push(b):j(b)),this},fire:function(){return k.fireWith(this,arguments),this},fired:function(){return!!c}};return k},o.extend({Deferred:function(a){var b=[["resolve","done",o.Callbacks("once memory"),"resolved"],["reject","fail",o.Callbacks("once memory"),"rejected"],["notify","progress",o.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return o.Deferred(function(c){o.each(b,function(b,f){var g=o.isFunction(a[b])&&a[b];e[f[1]](function(){var a=g&&g.apply(this,arguments);a&&o.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f[0]+"With"](this===d?c.promise():this,g?[a]:arguments)})}),a=null}).promise()},promise:function(a){return null!=a?o.extend(a,d):d}},e={};return d.pipe=d.then,o.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[1^a][2].disable,b[2][2].lock),e[f[0]]=function(){return e[f[0]+"With"](this===e?d:this,arguments),this},e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=d.call(arguments),e=c.length,f=1!==e||a&&o.isFunction(a.promise)?e:0,g=1===f?a:o.Deferred(),h=function(a,b,c){return function(e){b[a]=this,c[a]=arguments.length>1?d.call(arguments):e,c===i?g.notifyWith(b,c):--f||g.resolveWith(b,c)}},i,j,k;if(e>1)for(i=new Array(e),j=new Array(e),k=new Array(e);e>b;b++)c[b]&&o.isFunction(c[b].promise)?c[b].promise().done(h(b,k,c)).fail(g.reject).progress(h(b,j,i)):--f;return f||g.resolveWith(k,c),g.promise()}});var H;o.fn.ready=function(a){return o.ready.promise().done(a),this},o.extend({isReady:!1,readyWait:1,holdReady:function(a){a?o.readyWait++:o.ready(!0)},ready:function(a){(a===!0?--o.readyWait:o.isReady)||(o.isReady=!0,a!==!0&&--o.readyWait>0||(H.resolveWith(m,[o]),o.fn.trigger&&o(m).trigger("ready").off("ready")))}});function I(){m.removeEventListener("DOMContentLoaded",I,!1),a.removeEventListener("load",I,!1),o.ready()}o.ready.promise=function(b){return H||(H=o.Deferred(),"complete"===m.readyState?setTimeout(o.ready):(m.addEventListener("DOMContentLoaded",I,!1),a.addEventListener("load",I,!1))),H.promise(b)},o.ready.promise();var J=o.access=function(a,b,c,d,e,f,g){var h=0,i=a.length,j=null==c;if("object"===o.type(c)){e=!0;for(h in c)o.access(a,b,h,c[h],!0,f,g)}else if(void 0!==d&&(e=!0,o.isFunction(d)||(g=!0),j&&(g?(b.call(a,d),b=null):(j=b,b=function(a,b,c){return j.call(o(a),c)})),b))for(;i>h;h++)b(a[h],c,g?d:d.call(a[h],h,b(a[h],c)));return e?a:j?b.call(a):i?b(a[0],c):f};o.acceptData=function(a){return 1===a.nodeType||9===a.nodeType||!+a.nodeType};function K(){Object.defineProperty(this.cache={},0,{get:function(){return{}}}),this.expando=o.expando+Math.random()}K.uid=1,K.accepts=o.acceptData,K.prototype={key:function(a){if(!K.accepts(a))return 0;var b={},c=a[this.expando];if(!c){c=K.uid++;try{b[this.expando]={value:c},Object.defineProperties(a,b)}catch(d){b[this.expando]=c,o.extend(a,b)}}return this.cache[c]||(this.cache[c]={}),c},set:function(a,b,c){var d,e=this.key(a),f=this.cache[e];if("string"==typeof b)f[b]=c;else if(o.isEmptyObject(f))o.extend(this.cache[e],b);else for(d in b)f[d]=b[d];return f},get:function(a,b){var c=this.cache[this.key(a)];return void 0===b?c:c[b]},access:function(a,b,c){var d;return void 0===b||b&&"string"==typeof b&&void 0===c?(d=this.get(a,b),void 0!==d?d:this.get(a,o.camelCase(b))):(this.set(a,b,c),void 0!==c?c:b)},remove:function(a,b){var c,d,e,f=this.key(a),g=this.cache[f];if(void 0===b)this.cache[f]={};else{o.isArray(b)?d=b.concat(b.map(o.camelCase)):(e=o.camelCase(b),b in g?d=[b,e]:(d=e,d=d in g?[d]:d.match(E)||[])),c=d.length;while(c--)delete g[d[c]]}},hasData:function(a){return!o.isEmptyObject(this.cache[a[this.expando]]||{})},discard:function(a){a[this.expando]&&delete this.cache[a[this.expando]]}};var L=new K,M=new K,N=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,O=/([A-Z])/g;function P(a,b,c){var d;if(void 0===c&&1===a.nodeType)if(d="data-"+b.replace(O,"-$1").toLowerCase(),c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:N.test(c)?o.parseJSON(c):c}catch(e){}M.set(a,b,c)}else c=void 0;return c}o.extend({hasData:function(a){return M.hasData(a)||L.hasData(a)},data:function(a,b,c){return M.access(a,b,c)},removeData:function(a,b){M.remove(a,b)},_data:function(a,b,c){return L.access(a,b,c)},_removeData:function(a,b){L.remove(a,b)}}),o.fn.extend({data:function(a,b){var c,d,e,f=this[0],g=f&&f.attributes;if(void 0===a){if(this.length&&(e=M.get(f),1===f.nodeType&&!L.get(f,"hasDataAttrs"))){c=g.length;
-while(c--)d=g[c].name,0===d.indexOf("data-")&&(d=o.camelCase(d.slice(5)),P(f,d,e[d]));L.set(f,"hasDataAttrs",!0)}return e}return"object"==typeof a?this.each(function(){M.set(this,a)}):J(this,function(b){var c,d=o.camelCase(a);if(f&&void 0===b){if(c=M.get(f,a),void 0!==c)return c;if(c=M.get(f,d),void 0!==c)return c;if(c=P(f,d,void 0),void 0!==c)return c}else this.each(function(){var c=M.get(this,d);M.set(this,d,b),-1!==a.indexOf("-")&&void 0!==c&&M.set(this,a,b)})},null,b,arguments.length>1,null,!0)},removeData:function(a){return this.each(function(){M.remove(this,a)})}}),o.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=L.get(a,b),c&&(!d||o.isArray(c)?d=L.access(a,b,o.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=o.queue(a,b),d=c.length,e=c.shift(),f=o._queueHooks(a,b),g=function(){o.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return L.get(a,c)||L.access(a,c,{empty:o.Callbacks("once memory").add(function(){L.remove(a,[b+"queue",c])})})}}),o.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.length<c?o.queue(this[0],a):void 0===b?this:this.each(function(){var c=o.queue(this,a,b);o._queueHooks(this,a),"fx"===a&&"inprogress"!==c[0]&&o.dequeue(this,a)})},dequeue:function(a){return this.each(function(){o.dequeue(this,a)})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,b){var c,d=1,e=o.Deferred(),f=this,g=this.length,h=function(){--d||e.resolveWith(f,[f])};"string"!=typeof a&&(b=a,a=void 0),a=a||"fx";while(g--)c=L.get(f[g],a+"queueHooks"),c&&c.empty&&(d++,c.empty.add(h));return h(),e.promise(b)}});var Q=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,R=["Top","Right","Bottom","Left"],S=function(a,b){return a=b||a,"none"===o.css(a,"display")||!o.contains(a.ownerDocument,a)},T=/^(?:checkbox|radio)$/i;!function(){var a=m.createDocumentFragment(),b=a.appendChild(m.createElement("div"));b.innerHTML="<input type='radio' checked='checked' name='t'/>",l.checkClone=b.cloneNode(!0).cloneNode(!0).lastChild.checked,b.innerHTML="<textarea>x</textarea>",l.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue}();var U="undefined";l.focusinBubbles="onfocusin"in a;var V=/^key/,W=/^(?:mouse|contextmenu)|click/,X=/^(?:focusinfocus|focusoutblur)$/,Y=/^([^.]*)(?:\.(.+)|)$/;function Z(){return!0}function $(){return!1}function _(){try{return m.activeElement}catch(a){}}o.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,n,p,q,r=L.get(a);if(r){c.handler&&(f=c,c=f.handler,e=f.selector),c.guid||(c.guid=o.guid++),(i=r.events)||(i=r.events={}),(g=r.handle)||(g=r.handle=function(b){return typeof o!==U&&o.event.triggered!==b.type?o.event.dispatch.apply(a,arguments):void 0}),b=(b||"").match(E)||[""],j=b.length;while(j--)h=Y.exec(b[j])||[],n=q=h[1],p=(h[2]||"").split(".").sort(),n&&(l=o.event.special[n]||{},n=(e?l.delegateType:l.bindType)||n,l=o.event.special[n]||{},k=o.extend({type:n,origType:q,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&o.expr.match.needsContext.test(e),namespace:p.join(".")},f),(m=i[n])||(m=i[n]=[],m.delegateCount=0,l.setup&&l.setup.call(a,d,p,g)!==!1||a.addEventListener&&a.addEventListener(n,g,!1)),l.add&&(l.add.call(a,k),k.handler.guid||(k.handler.guid=c.guid)),e?m.splice(m.delegateCount++,0,k):m.push(k),o.event.global[n]=!0)}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,n,p,q,r=L.hasData(a)&&L.get(a);if(r&&(i=r.events)){b=(b||"").match(E)||[""],j=b.length;while(j--)if(h=Y.exec(b[j])||[],n=q=h[1],p=(h[2]||"").split(".").sort(),n){l=o.event.special[n]||{},n=(d?l.delegateType:l.bindType)||n,m=i[n]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),g=f=m.length;while(f--)k=m[f],!e&&q!==k.origType||c&&c.guid!==k.guid||h&&!h.test(k.namespace)||d&&d!==k.selector&&("**"!==d||!k.selector)||(m.splice(f,1),k.selector&&m.delegateCount--,l.remove&&l.remove.call(a,k));g&&!m.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||o.removeEvent(a,n,r.handle),delete i[n])}else for(n in i)o.event.remove(a,n+b[j],c,d,!0);o.isEmptyObject(i)&&(delete r.handle,L.remove(a,"events"))}},trigger:function(b,c,d,e){var f,g,h,i,k,l,n,p=[d||m],q=j.call(b,"type")?b.type:b,r=j.call(b,"namespace")?b.namespace.split("."):[];if(g=h=d=d||m,3!==d.nodeType&&8!==d.nodeType&&!X.test(q+o.event.triggered)&&(q.indexOf(".")>=0&&(r=q.split("."),q=r.shift(),r.sort()),k=q.indexOf(":")<0&&"on"+q,b=b[o.expando]?b:new o.Event(q,"object"==typeof b&&b),b.isTrigger=e?2:3,b.namespace=r.join("."),b.namespace_re=b.namespace?new RegExp("(^|\\.)"+r.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=d),c=null==c?[b]:o.makeArray(c,[b]),n=o.event.special[q]||{},e||!n.trigger||n.trigger.apply(d,c)!==!1)){if(!e&&!n.noBubble&&!o.isWindow(d)){for(i=n.delegateType||q,X.test(i+q)||(g=g.parentNode);g;g=g.parentNode)p.push(g),h=g;h===(d.ownerDocument||m)&&p.push(h.defaultView||h.parentWindow||a)}f=0;while((g=p[f++])&&!b.isPropagationStopped())b.type=f>1?i:n.bindType||q,l=(L.get(g,"events")||{})[b.type]&&L.get(g,"handle"),l&&l.apply(g,c),l=k&&g[k],l&&l.apply&&o.acceptData(g)&&(b.result=l.apply(g,c),b.result===!1&&b.preventDefault());return b.type=q,e||b.isDefaultPrevented()||n._default&&n._default.apply(p.pop(),c)!==!1||!o.acceptData(d)||k&&o.isFunction(d[q])&&!o.isWindow(d)&&(h=d[k],h&&(d[k]=null),o.event.triggered=q,d[q](),o.event.triggered=void 0,h&&(d[k]=h)),b.result}},dispatch:function(a){a=o.event.fix(a);var b,c,e,f,g,h=[],i=d.call(arguments),j=(L.get(this,"events")||{})[a.type]||[],k=o.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,a)!==!1){h=o.event.handlers.call(this,a,j),b=0;while((f=h[b++])&&!a.isPropagationStopped()){a.currentTarget=f.elem,c=0;while((g=f.handlers[c++])&&!a.isImmediatePropagationStopped())(!a.namespace_re||a.namespace_re.test(g.namespace))&&(a.handleObj=g,a.data=g.data,e=((o.event.special[g.origType]||{}).handle||g.handler).apply(f.elem,i),void 0!==e&&(a.result=e)===!1&&(a.preventDefault(),a.stopPropagation()))}return k.postDispatch&&k.postDispatch.call(this,a),a.result}},handlers:function(a,b){var c,d,e,f,g=[],h=b.delegateCount,i=a.target;if(h&&i.nodeType&&(!a.button||"click"!==a.type))for(;i!==this;i=i.parentNode||this)if(i.disabled!==!0||"click"!==a.type){for(d=[],c=0;h>c;c++)f=b[c],e=f.selector+" ",void 0===d[e]&&(d[e]=f.needsContext?o(e,this).index(i)>=0:o.find(e,this,null,[i]).length),d[e]&&d.push(f);d.length&&g.push({elem:i,handlers:d})}return h<b.length&&g.push({elem:this,handlers:b.slice(h)}),g},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(a,b){return null==a.which&&(a.which=null!=b.charCode?b.charCode:b.keyCode),a}},mouseHooks:{props:"button buttons clientX clientY offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,b){var c,d,e,f=b.button;return null==a.pageX&&null!=b.clientX&&(c=a.target.ownerDocument||m,d=c.documentElement,e=c.body,a.pageX=b.clientX+(d&&d.scrollLeft||e&&e.scrollLeft||0)-(d&&d.clientLeft||e&&e.clientLeft||0),a.pageY=b.clientY+(d&&d.scrollTop||e&&e.scrollTop||0)-(d&&d.clientTop||e&&e.clientTop||0)),a.which||void 0===f||(a.which=1&f?1:2&f?3:4&f?2:0),a}},fix:function(a){if(a[o.expando])return a;var b,c,d,e=a.type,f=a,g=this.fixHooks[e];g||(this.fixHooks[e]=g=W.test(e)?this.mouseHooks:V.test(e)?this.keyHooks:{}),d=g.props?this.props.concat(g.props):this.props,a=new o.Event(f),b=d.length;while(b--)c=d[b],a[c]=f[c];return a.target||(a.target=m),3===a.target.nodeType&&(a.target=a.target.parentNode),g.filter?g.filter(a,f):a},special:{load:{noBubble:!0},focus:{trigger:function(){return this!==_()&&this.focus?(this.focus(),!1):void 0},delegateType:"focusin"},blur:{trigger:function(){return this===_()&&this.blur?(this.blur(),!1):void 0},delegateType:"focusout"},click:{trigger:function(){return"checkbox"===this.type&&this.click&&o.nodeName(this,"input")?(this.click(),!1):void 0},_default:function(a){return o.nodeName(a.target,"a")}},beforeunload:{postDispatch:function(a){void 0!==a.result&&(a.originalEvent.returnValue=a.result)}}},simulate:function(a,b,c,d){var e=o.extend(new o.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?o.event.trigger(e,null,b):o.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},o.removeEvent=function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)},o.Event=function(a,b){return this instanceof o.Event?(a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||void 0===a.defaultPrevented&&a.getPreventDefault&&a.getPreventDefault()?Z:$):this.type=a,b&&o.extend(this,b),this.timeStamp=a&&a.timeStamp||o.now(),void(this[o.expando]=!0)):new o.Event(a,b)},o.Event.prototype={isDefaultPrevented:$,isPropagationStopped:$,isImmediatePropagationStopped:$,preventDefault:function(){var a=this.originalEvent;this.isDefaultPrevented=Z,a&&a.preventDefault&&a.preventDefault()},stopPropagation:function(){var a=this.originalEvent;this.isPropagationStopped=Z,a&&a.stopPropagation&&a.stopPropagation()},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=Z,this.stopPropagation()}},o.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){o.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c,d=this,e=a.relatedTarget,f=a.handleObj;return(!e||e!==d&&!o.contains(d,e))&&(a.type=f.origType,c=f.handler.apply(this,arguments),a.type=b),c}}}),l.focusinBubbles||o.each({focus:"focusin",blur:"focusout"},function(a,b){var c=function(a){o.event.simulate(b,a.target,o.event.fix(a),!0)};o.event.special[b]={setup:function(){var d=this.ownerDocument||this,e=L.access(d,b);e||d.addEventListener(a,c,!0),L.access(d,b,(e||0)+1)},teardown:function(){var d=this.ownerDocument||this,e=L.access(d,b)-1;e?L.access(d,b,e):(d.removeEventListener(a,c,!0),L.remove(d,b))}}}),o.fn.extend({on:function(a,b,c,d,e){var f,g;if("object"==typeof a){"string"!=typeof b&&(c=c||b,b=void 0);for(g in a)this.on(g,b,c,a[g],e);return this}if(null==c&&null==d?(d=b,c=b=void 0):null==d&&("string"==typeof b?(d=c,c=void 0):(d=c,c=b,b=void 0)),d===!1)d=$;else if(!d)return this;return 1===e&&(f=d,d=function(a){return o().off(a),f.apply(this,arguments)},d.guid=f.guid||(f.guid=o.guid++)),this.each(function(){o.event.add(this,a,d,c,b)})},one:function(a,b,c,d){return this.on(a,b,c,d,1)},off:function(a,b,c){var d,e;if(a&&a.preventDefault&&a.handleObj)return d=a.handleObj,o(a.delegateTarget).off(d.namespace?d.origType+"."+d.namespace:d.origType,d.selector,d.handler),this;if("object"==typeof a){for(e in a)this.off(e,b,a[e]);return this}return(b===!1||"function"==typeof b)&&(c=b,b=void 0),c===!1&&(c=$),this.each(function(){o.event.remove(this,a,c,b)})},trigger:function(a,b){return this.each(function(){o.event.trigger(a,b,this)})},triggerHandler:function(a,b){var c=this[0];return c?o.event.trigger(a,b,c,!0):void 0}});var ab=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,bb=/<([\w:]+)/,cb=/<|&#?\w+;/,db=/<(?:script|style|link)/i,eb=/checked\s*(?:[^=]|=\s*.checked.)/i,fb=/^$|\/(?:java|ecma)script/i,gb=/^true\/(.*)/,hb=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,ib={option:[1,"<select multiple='multiple'>","</select>"],thead:[1,"<table>","</table>"],col:[2,"<table><colgroup>","</colgroup></table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:[0,"",""]};ib.optgroup=ib.option,ib.tbody=ib.tfoot=ib.colgroup=ib.caption=ib.thead,ib.th=ib.td;function jb(a,b){return o.nodeName(a,"table")&&o.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function kb(a){return a.type=(null!==a.getAttribute("type"))+"/"+a.type,a}function lb(a){var b=gb.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function mb(a,b){for(var c=0,d=a.length;d>c;c++)L.set(a[c],"globalEval",!b||L.get(b[c],"globalEval"))}function nb(a,b){var c,d,e,f,g,h,i,j;if(1===b.nodeType){if(L.hasData(a)&&(f=L.access(a),g=L.set(b,f),j=f.events)){delete g.handle,g.events={};for(e in j)for(c=0,d=j[e].length;d>c;c++)o.event.add(b,e,j[e][c])}M.hasData(a)&&(h=M.access(a),i=o.extend({},h),M.set(b,i))}}function ob(a,b){var c=a.getElementsByTagName?a.getElementsByTagName(b||"*"):a.querySelectorAll?a.querySelectorAll(b||"*"):[];return void 0===b||b&&o.nodeName(a,b)?o.merge([a],c):c}function pb(a,b){var c=b.nodeName.toLowerCase();"input"===c&&T.test(a.type)?b.checked=a.checked:("input"===c||"textarea"===c)&&(b.defaultValue=a.defaultValue)}o.extend({clone:function(a,b,c){var d,e,f,g,h=a.cloneNode(!0),i=o.contains(a.ownerDocument,a);if(!(l.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||o.isXMLDoc(a)))for(g=ob(h),f=ob(a),d=0,e=f.length;e>d;d++)pb(f[d],g[d]);if(b)if(c)for(f=f||ob(a),g=g||ob(h),d=0,e=f.length;e>d;d++)nb(f[d],g[d]);else nb(a,h);return g=ob(h,"script"),g.length>0&&mb(g,!i&&ob(a,"script")),h},buildFragment:function(a,b,c,d){for(var e,f,g,h,i,j,k=b.createDocumentFragment(),l=[],m=0,n=a.length;n>m;m++)if(e=a[m],e||0===e)if("object"===o.type(e))o.merge(l,e.nodeType?[e]:e);else if(cb.test(e)){f=f||k.appendChild(b.createElement("div")),g=(bb.exec(e)||["",""])[1].toLowerCase(),h=ib[g]||ib._default,f.innerHTML=h[1]+e.replace(ab,"<$1></$2>")+h[2],j=h[0];while(j--)f=f.lastChild;o.merge(l,f.childNodes),f=k.firstChild,f.textContent=""}else l.push(b.createTextNode(e));k.textContent="",m=0;while(e=l[m++])if((!d||-1===o.inArray(e,d))&&(i=o.contains(e.ownerDocument,e),f=ob(k.appendChild(e),"script"),i&&mb(f),c)){j=0;while(e=f[j++])fb.test(e.type||"")&&c.push(e)}return k},cleanData:function(a){for(var b,c,d,e,f,g,h=o.event.special,i=0;void 0!==(c=a[i]);i++){if(o.acceptData(c)&&(f=c[L.expando],f&&(b=L.cache[f]))){if(d=Object.keys(b.events||{}),d.length)for(g=0;void 0!==(e=d[g]);g++)h[e]?o.event.remove(c,e):o.removeEvent(c,e,b.handle);L.cache[f]&&delete L.cache[f]}delete M.cache[c[M.expando]]}}}),o.fn.extend({text:function(a){return J(this,function(a){return void 0===a?o.text(this):this.empty().each(function(){(1===this.nodeType||11===this.nodeType||9===this.nodeType)&&(this.textContent=a)})},null,a,arguments.length)},append:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=jb(this,a);b.appendChild(a)}})},prepend:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=jb(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},remove:function(a,b){for(var c,d=a?o.filter(a,this):this,e=0;null!=(c=d[e]);e++)b||1!==c.nodeType||o.cleanData(ob(c)),c.parentNode&&(b&&o.contains(c.ownerDocument,c)&&mb(ob(c,"script")),c.parentNode.removeChild(c));return this},empty:function(){for(var a,b=0;null!=(a=this[b]);b++)1===a.nodeType&&(o.cleanData(ob(a,!1)),a.textContent="");return this},clone:function(a,b){return a=null==a?!1:a,b=null==b?a:b,this.map(function(){return o.clone(this,a,b)})},html:function(a){return J(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a&&1===b.nodeType)return b.innerHTML;if("string"==typeof a&&!db.test(a)&&!ib[(bb.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(ab,"<$1></$2>");try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(o.cleanData(ob(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=arguments[0];return this.domManip(arguments,function(b){a=this.parentNode,o.cleanData(ob(this)),a&&a.replaceChild(b,this)}),a&&(a.length||a.nodeType)?this:this.remove()},detach:function(a){return this.remove(a,!0)},domManip:function(a,b){a=e.apply([],a);var c,d,f,g,h,i,j=0,k=this.length,m=this,n=k-1,p=a[0],q=o.isFunction(p);if(q||k>1&&"string"==typeof p&&!l.checkClone&&eb.test(p))return this.each(function(c){var d=m.eq(c);q&&(a[0]=p.call(this,c,d.html())),d.domManip(a,b)});if(k&&(c=o.buildFragment(a,this[0].ownerDocument,!1,this),d=c.firstChild,1===c.childNodes.length&&(c=d),d)){for(f=o.map(ob(c,"script"),kb),g=f.length;k>j;j++)h=c,j!==n&&(h=o.clone(h,!0,!0),g&&o.merge(f,ob(h,"script"))),b.call(this[j],h,j);if(g)for(i=f[f.length-1].ownerDocument,o.map(f,lb),j=0;g>j;j++)h=f[j],fb.test(h.type||"")&&!L.access(h,"globalEval")&&o.contains(i,h)&&(h.src?o._evalUrl&&o._evalUrl(h.src):o.globalEval(h.textContent.replace(hb,"")))}return this}}),o.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){o.fn[a]=function(a){for(var c,d=[],e=o(a),g=e.length-1,h=0;g>=h;h++)c=h===g?this:this.clone(!0),o(e[h])[b](c),f.apply(d,c.get());return this.pushStack(d)}});var qb,rb={};function sb(b,c){var d=o(c.createElement(b)).appendTo(c.body),e=a.getDefaultComputedStyle?a.getDefaultComputedStyle(d[0]).display:o.css(d[0],"display");return d.detach(),e}function tb(a){var b=m,c=rb[a];return c||(c=sb(a,b),"none"!==c&&c||(qb=(qb||o("<iframe frameborder='0' width='0' height='0'/>")).appendTo(b.documentElement),b=qb[0].contentDocument,b.write(),b.close(),c=sb(a,b),qb.detach()),rb[a]=c),c}var ub=/^margin/,vb=new RegExp("^("+Q+")(?!px)[a-z%]+$","i"),wb=function(a){return a.ownerDocument.defaultView.getComputedStyle(a,null)};function xb(a,b,c){var d,e,f,g,h=a.style;return c=c||wb(a),c&&(g=c.getPropertyValue(b)||c[b]),c&&(""!==g||o.contains(a.ownerDocument,a)||(g=o.style(a,b)),vb.test(g)&&ub.test(b)&&(d=h.width,e=h.minWidth,f=h.maxWidth,h.minWidth=h.maxWidth=h.width=g,g=c.width,h.width=d,h.minWidth=e,h.maxWidth=f)),void 0!==g?g+"":g}function yb(a,b){return{get:function(){return a()?void delete this.get:(this.get=b).apply(this,arguments)}}}!function(){var b,c,d="padding:0;margin:0;border:0;display:block;-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box",e=m.documentElement,f=m.createElement("div"),g=m.createElement("div");g.style.backgroundClip="content-box",g.cloneNode(!0).style.backgroundClip="",l.clearCloneStyle="content-box"===g.style.backgroundClip,f.style.cssText="border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px",f.appendChild(g);function h(){g.style.cssText="-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%",e.appendChild(f);var d=a.getComputedStyle(g,null);b="1%"!==d.top,c="4px"===d.width,e.removeChild(f)}a.getComputedStyle&&o.extend(l,{pixelPosition:function(){return h(),b},boxSizingReliable:function(){return null==c&&h(),c},reliableMarginRight:function(){var b,c=g.appendChild(m.createElement("div"));return c.style.cssText=g.style.cssText=d,c.style.marginRight=c.style.width="0",g.style.width="1px",e.appendChild(f),b=!parseFloat(a.getComputedStyle(c,null).marginRight),e.removeChild(f),g.innerHTML="",b}})}(),o.swap=function(a,b,c,d){var e,f,g={};for(f in b)g[f]=a.style[f],a.style[f]=b[f];e=c.apply(a,d||[]);for(f in b)a.style[f]=g[f];return e};var zb=/^(none|table(?!-c[ea]).+)/,Ab=new RegExp("^("+Q+")(.*)$","i"),Bb=new RegExp("^([+-])=("+Q+")","i"),Cb={position:"absolute",visibility:"hidden",display:"block"},Db={letterSpacing:0,fontWeight:400},Eb=["Webkit","O","Moz","ms"];function Fb(a,b){if(b in a)return b;var c=b[0].toUpperCase()+b.slice(1),d=b,e=Eb.length;while(e--)if(b=Eb[e]+c,b in a)return b;return d}function Gb(a,b,c){var d=Ab.exec(b);return d?Math.max(0,d[1]-(c||0))+(d[2]||"px"):b}function Hb(a,b,c,d,e){for(var f=c===(d?"border":"content")?4:"width"===b?1:0,g=0;4>f;f+=2)"margin"===c&&(g+=o.css(a,c+R[f],!0,e)),d?("content"===c&&(g-=o.css(a,"padding"+R[f],!0,e)),"margin"!==c&&(g-=o.css(a,"border"+R[f]+"Width",!0,e))):(g+=o.css(a,"padding"+R[f],!0,e),"padding"!==c&&(g+=o.css(a,"border"+R[f]+"Width",!0,e)));return g}function Ib(a,b,c){var d=!0,e="width"===b?a.offsetWidth:a.offsetHeight,f=wb(a),g="border-box"===o.css(a,"boxSizing",!1,f);if(0>=e||null==e){if(e=xb(a,b,f),(0>e||null==e)&&(e=a.style[b]),vb.test(e))return e;d=g&&(l.boxSizingReliable()||e===a.style[b]),e=parseFloat(e)||0}return e+Hb(a,b,c||(g?"border":"content"),d,f)+"px"}function Jb(a,b){for(var c,d,e,f=[],g=0,h=a.length;h>g;g++)d=a[g],d.style&&(f[g]=L.get(d,"olddisplay"),c=d.style.display,b?(f[g]||"none"!==c||(d.style.display=""),""===d.style.display&&S(d)&&(f[g]=L.access(d,"olddisplay",tb(d.nodeName)))):f[g]||(e=S(d),(c&&"none"!==c||!e)&&L.set(d,"olddisplay",e?c:o.css(d,"display"))));for(g=0;h>g;g++)d=a[g],d.style&&(b&&"none"!==d.style.display&&""!==d.style.display||(d.style.display=b?f[g]||"":"none"));return a}o.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=xb(a,"opacity");return""===c?"1":c}}}},cssNumber:{columnCount:!0,fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":"cssFloat"},style:function(a,b,c,d){if(a&&3!==a.nodeType&&8!==a.nodeType&&a.style){var e,f,g,h=o.camelCase(b),i=a.style;return b=o.cssProps[h]||(o.cssProps[h]=Fb(i,h)),g=o.cssHooks[b]||o.cssHooks[h],void 0===c?g&&"get"in g&&void 0!==(e=g.get(a,!1,d))?e:i[b]:(f=typeof c,"string"===f&&(e=Bb.exec(c))&&(c=(e[1]+1)*e[2]+parseFloat(o.css(a,b)),f="number"),null!=c&&c===c&&("number"!==f||o.cssNumber[h]||(c+="px"),l.clearCloneStyle||""!==c||0!==b.indexOf("background")||(i[b]="inherit"),g&&"set"in g&&void 0===(c=g.set(a,c,d))||(i[b]="",i[b]=c)),void 0)}},css:function(a,b,c,d){var e,f,g,h=o.camelCase(b);return b=o.cssProps[h]||(o.cssProps[h]=Fb(a.style,h)),g=o.cssHooks[b]||o.cssHooks[h],g&&"get"in g&&(e=g.get(a,!0,c)),void 0===e&&(e=xb(a,b,d)),"normal"===e&&b in Db&&(e=Db[b]),""===c||c?(f=parseFloat(e),c===!0||o.isNumeric(f)?f||0:e):e}}),o.each(["height","width"],function(a,b){o.cssHooks[b]={get:function(a,c,d){return c?0===a.offsetWidth&&zb.test(o.css(a,"display"))?o.swap(a,Cb,function(){return Ib(a,b,d)}):Ib(a,b,d):void 0},set:function(a,c,d){var e=d&&wb(a);return Gb(a,c,d?Hb(a,b,d,"border-box"===o.css(a,"boxSizing",!1,e),e):0)}}}),o.cssHooks.marginRight=yb(l.reliableMarginRight,function(a,b){return b?o.swap(a,{display:"inline-block"},xb,[a,"marginRight"]):void 0}),o.each({margin:"",padding:"",border:"Width"},function(a,b){o.cssHooks[a+b]={expand:function(c){for(var d=0,e={},f="string"==typeof c?c.split(" "):[c];4>d;d++)e[a+R[d]+b]=f[d]||f[d-2]||f[0];return e}},ub.test(a)||(o.cssHooks[a+b].set=Gb)}),o.fn.extend({css:function(a,b){return J(this,function(a,b,c){var d,e,f={},g=0;if(o.isArray(b)){for(d=wb(a),e=b.length;e>g;g++)f[b[g]]=o.css(a,b[g],!1,d);return f}return void 0!==c?o.style(a,b,c):o.css(a,b)},a,b,arguments.length>1)},show:function(){return Jb(this,!0)},hide:function(){return Jb(this)},toggle:function(a){return"boolean"==typeof a?a?this.show():this.hide():this.each(function(){S(this)?o(this).show():o(this).hide()})}});function Kb(a,b,c,d,e){return new Kb.prototype.init(a,b,c,d,e)}o.Tween=Kb,Kb.prototype={constructor:Kb,init:function(a,b,c,d,e,f){this.elem=a,this.prop=c,this.easing=e||"swing",this.options=b,this.start=this.now=this.cur(),this.end=d,this.unit=f||(o.cssNumber[c]?"":"px")},cur:function(){var a=Kb.propHooks[this.prop];return a&&a.get?a.get(this):Kb.propHooks._default.get(this)},run:function(a){var b,c=Kb.propHooks[this.prop];return this.pos=b=this.options.duration?o.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration):a,this.now=(this.end-this.start)*b+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),c&&c.set?c.set(this):Kb.propHooks._default.set(this),this}},Kb.prototype.init.prototype=Kb.prototype,Kb.propHooks={_default:{get:function(a){var b;return null==a.elem[a.prop]||a.elem.style&&null!=a.elem.style[a.prop]?(b=o.css(a.elem,a.prop,""),b&&"auto"!==b?b:0):a.elem[a.prop]},set:function(a){o.fx.step[a.prop]?o.fx.step[a.prop](a):a.elem.style&&(null!=a.elem.style[o.cssProps[a.prop]]||o.cssHooks[a.prop])?o.style(a.elem,a.prop,a.now+a.unit):a.elem[a.prop]=a.now}}},Kb.propHooks.scrollTop=Kb.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},o.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2}},o.fx=Kb.prototype.init,o.fx.step={};var Lb,Mb,Nb=/^(?:toggle|show|hide)$/,Ob=new RegExp("^(?:([+-])=|)("+Q+")([a-z%]*)$","i"),Pb=/queueHooks$/,Qb=[Vb],Rb={"*":[function(a,b){var c=this.createTween(a,b),d=c.cur(),e=Ob.exec(b),f=e&&e[3]||(o.cssNumber[a]?"":"px"),g=(o.cssNumber[a]||"px"!==f&&+d)&&Ob.exec(o.css(c.elem,a)),h=1,i=20;if(g&&g[3]!==f){f=f||g[3],e=e||[],g=+d||1;do h=h||".5",g/=h,o.style(c.elem,a,g+f);while(h!==(h=c.cur()/d)&&1!==h&&--i)}return e&&(g=c.start=+g||+d||0,c.unit=f,c.end=e[1]?g+(e[1]+1)*e[2]:+e[2]),c}]};function Sb(){return setTimeout(function(){Lb=void 0}),Lb=o.now()}function Tb(a,b){var c,d=0,e={height:a};for(b=b?1:0;4>d;d+=2-b)c=R[d],e["margin"+c]=e["padding"+c]=a;return b&&(e.opacity=e.width=a),e}function Ub(a,b,c){for(var d,e=(Rb[b]||[]).concat(Rb["*"]),f=0,g=e.length;g>f;f++)if(d=e[f].call(c,b,a))return d}function Vb(a,b,c){var d,e,f,g,h,i,j,k=this,l={},m=a.style,n=a.nodeType&&S(a),p=L.get(a,"fxshow");c.queue||(h=o._queueHooks(a,"fx"),null==h.unqueued&&(h.unqueued=0,i=h.empty.fire,h.empty.fire=function(){h.unqueued||i()}),h.unqueued++,k.always(function(){k.always(function(){h.unqueued--,o.queue(a,"fx").length||h.empty.fire()})})),1===a.nodeType&&("height"in b||"width"in b)&&(c.overflow=[m.overflow,m.overflowX,m.overflowY],j=o.css(a,"display"),"none"===j&&(j=tb(a.nodeName)),"inline"===j&&"none"===o.css(a,"float")&&(m.display="inline-block")),c.overflow&&(m.overflow="hidden",k.always(function(){m.overflow=c.overflow[0],m.overflowX=c.overflow[1],m.overflowY=c.overflow[2]}));for(d in b)if(e=b[d],Nb.exec(e)){if(delete b[d],f=f||"toggle"===e,e===(n?"hide":"show")){if("show"!==e||!p||void 0===p[d])continue;n=!0}l[d]=p&&p[d]||o.style(a,d)}if(!o.isEmptyObject(l)){p?"hidden"in p&&(n=p.hidden):p=L.access(a,"fxshow",{}),f&&(p.hidden=!n),n?o(a).show():k.done(function(){o(a).hide()}),k.done(function(){var b;L.remove(a,"fxshow");for(b in l)o.style(a,b,l[b])});for(d in l)g=Ub(n?p[d]:0,d,k),d in p||(p[d]=g.start,n&&(g.end=g.start,g.start="width"===d||"height"===d?1:0))}}function Wb(a,b){var c,d,e,f,g;for(c in a)if(d=o.camelCase(c),e=b[d],f=a[c],o.isArray(f)&&(e=f[1],f=a[c]=f[0]),c!==d&&(a[d]=f,delete a[c]),g=o.cssHooks[d],g&&"expand"in g){f=g.expand(f),delete a[d];for(c in f)c in a||(a[c]=f[c],b[c]=e)}else b[d]=e}function Xb(a,b,c){var d,e,f=0,g=Qb.length,h=o.Deferred().always(function(){delete i.elem}),i=function(){if(e)return!1;for(var b=Lb||Sb(),c=Math.max(0,j.startTime+j.duration-b),d=c/j.duration||0,f=1-d,g=0,i=j.tweens.length;i>g;g++)j.tweens[g].run(f);return h.notifyWith(a,[j,f,c]),1>f&&i?c:(h.resolveWith(a,[j]),!1)},j=h.promise({elem:a,props:o.extend({},b),opts:o.extend(!0,{specialEasing:{}},c),originalProperties:b,originalOptions:c,startTime:Lb||Sb(),duration:c.duration,tweens:[],createTween:function(b,c){var d=o.Tween(a,j.opts,b,c,j.opts.specialEasing[b]||j.opts.easing);return j.tweens.push(d),d},stop:function(b){var c=0,d=b?j.tweens.length:0;if(e)return this;for(e=!0;d>c;c++)j.tweens[c].run(1);return b?h.resolveWith(a,[j,b]):h.rejectWith(a,[j,b]),this}}),k=j.props;for(Wb(k,j.opts.specialEasing);g>f;f++)if(d=Qb[f].call(j,a,k,j.opts))return d;return o.map(k,Ub,j),o.isFunction(j.opts.start)&&j.opts.start.call(a,j),o.fx.timer(o.extend(i,{elem:a,anim:j,queue:j.opts.queue})),j.progress(j.opts.progress).done(j.opts.done,j.opts.complete).fail(j.opts.fail).always(j.opts.always)}o.Animation=o.extend(Xb,{tweener:function(a,b){o.isFunction(a)?(b=a,a=["*"]):a=a.split(" ");for(var c,d=0,e=a.length;e>d;d++)c=a[d],Rb[c]=Rb[c]||[],Rb[c].unshift(b)},prefilter:function(a,b){b?Qb.unshift(a):Qb.push(a)}}),o.speed=function(a,b,c){var d=a&&"object"==typeof a?o.extend({},a):{complete:c||!c&&b||o.isFunction(a)&&a,duration:a,easing:c&&b||b&&!o.isFunction(b)&&b};return d.duration=o.fx.off?0:"number"==typeof d.duration?d.duration:d.duration in o.fx.speeds?o.fx.speeds[d.duration]:o.fx.speeds._default,(null==d.queue||d.queue===!0)&&(d.queue="fx"),d.old=d.complete,d.complete=function(){o.isFunction(d.old)&&d.old.call(this),d.queue&&o.dequeue(this,d.queue)},d},o.fn.extend({fadeTo:function(a,b,c,d){return this.filter(S).css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){var e=o.isEmptyObject(a),f=o.speed(b,c,d),g=function(){var b=Xb(this,o.extend({},a),f);(e||L.get(this,"finish"))&&b.stop(!0)};return g.finish=g,e||f.queue===!1?this.each(g):this.queue(f.queue,g)},stop:function(a,b,c){var d=function(a){var b=a.stop;delete a.stop,b(c)};return"string"!=typeof a&&(c=b,b=a,a=void 0),b&&a!==!1&&this.queue(a||"fx",[]),this.each(function(){var b=!0,e=null!=a&&a+"queueHooks",f=o.timers,g=L.get(this);if(e)g[e]&&g[e].stop&&d(g[e]);else for(e in g)g[e]&&g[e].stop&&Pb.test(e)&&d(g[e]);for(e=f.length;e--;)f[e].elem!==this||null!=a&&f[e].queue!==a||(f[e].anim.stop(c),b=!1,f.splice(e,1));(b||!c)&&o.dequeue(this,a)})},finish:function(a){return a!==!1&&(a=a||"fx"),this.each(function(){var b,c=L.get(this),d=c[a+"queue"],e=c[a+"queueHooks"],f=o.timers,g=d?d.length:0;for(c.finish=!0,o.queue(this,a,[]),e&&e.stop&&e.stop.call(this,!0),b=f.length;b--;)f[b].elem===this&&f[b].queue===a&&(f[b].anim.stop(!0),f.splice(b,1));for(b=0;g>b;b++)d[b]&&d[b].finish&&d[b].finish.call(this);delete c.finish})}}),o.each(["toggle","show","hide"],function(a,b){var c=o.fn[b];o.fn[b]=function(a,d,e){return null==a||"boolean"==typeof a?c.apply(this,arguments):this.animate(Tb(b,!0),a,d,e)}}),o.each({slideDown:Tb("show"),slideUp:Tb("hide"),slideToggle:Tb("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){o.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),o.timers=[],o.fx.tick=function(){var a,b=0,c=o.timers;for(Lb=o.now();b<c.length;b++)a=c[b],a()||c[b]!==a||c.splice(b--,1);c.length||o.fx.stop(),Lb=void 0},o.fx.timer=function(a){o.timers.push(a),a()?o.fx.start():o.timers.pop()},o.fx.interval=13,o.fx.start=function(){Mb||(Mb=setInterval(o.fx.tick,o.fx.interval))},o.fx.stop=function(){clearInterval(Mb),Mb=null},o.fx.speeds={slow:600,fast:200,_default:400},o.fn.delay=function(a,b){return a=o.fx?o.fx.speeds[a]||a:a,b=b||"fx",this.queue(b,function(b,c){var d=setTimeout(b,a);c.stop=function(){clearTimeout(d)}})},function(){var a=m.createElement("input"),b=m.createElement("select"),c=b.appendChild(m.createElement("option"));a.type="checkbox",l.checkOn=""!==a.value,l.optSelected=c.selected,b.disabled=!0,l.optDisabled=!c.disabled,a=m.createElement("input"),a.value="t",a.type="radio",l.radioValue="t"===a.value}();var Yb,Zb,$b=o.expr.attrHandle;o.fn.extend({attr:function(a,b){return J(this,o.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){o.removeAttr(this,a)})}}),o.extend({attr:function(a,b,c){var d,e,f=a.nodeType;if(a&&3!==f&&8!==f&&2!==f)return typeof a.getAttribute===U?o.prop(a,b,c):(1===f&&o.isXMLDoc(a)||(b=b.toLowerCase(),d=o.attrHooks[b]||(o.expr.match.bool.test(b)?Zb:Yb)),void 0===c?d&&"get"in d&&null!==(e=d.get(a,b))?e:(e=o.find.attr(a,b),null==e?void 0:e):null!==c?d&&"set"in d&&void 0!==(e=d.set(a,c,b))?e:(a.setAttribute(b,c+""),c):void o.removeAttr(a,b))},removeAttr:function(a,b){var c,d,e=0,f=b&&b.match(E);if(f&&1===a.nodeType)while(c=f[e++])d=o.propFix[c]||c,o.expr.match.bool.test(c)&&(a[d]=!1),a.removeAttribute(c)},attrHooks:{type:{set:function(a,b){if(!l.radioValue&&"radio"===b&&o.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}}}}),Zb={set:function(a,b,c){return b===!1?o.removeAttr(a,c):a.setAttribute(c,c),c}},o.each(o.expr.match.bool.source.match(/\w+/g),function(a,b){var c=$b[b]||o.find.attr;$b[b]=function(a,b,d){var e,f;
-return d||(f=$b[b],$b[b]=e,e=null!=c(a,b,d)?b.toLowerCase():null,$b[b]=f),e}});var _b=/^(?:input|select|textarea|button)$/i;o.fn.extend({prop:function(a,b){return J(this,o.prop,a,b,arguments.length>1)},removeProp:function(a){return this.each(function(){delete this[o.propFix[a]||a]})}}),o.extend({propFix:{"for":"htmlFor","class":"className"},prop:function(a,b,c){var d,e,f,g=a.nodeType;if(a&&3!==g&&8!==g&&2!==g)return f=1!==g||!o.isXMLDoc(a),f&&(b=o.propFix[b]||b,e=o.propHooks[b]),void 0!==c?e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:a[b]=c:e&&"get"in e&&null!==(d=e.get(a,b))?d:a[b]},propHooks:{tabIndex:{get:function(a){return a.hasAttribute("tabindex")||_b.test(a.nodeName)||a.href?a.tabIndex:-1}}}}),l.optSelected||(o.propHooks.selected={get:function(a){var b=a.parentNode;return b&&b.parentNode&&b.parentNode.selectedIndex,null}}),o.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){o.propFix[this.toLowerCase()]=this});var ac=/[\t\r\n\f]/g;o.fn.extend({addClass:function(a){var b,c,d,e,f,g,h="string"==typeof a&&a,i=0,j=this.length;if(o.isFunction(a))return this.each(function(b){o(this).addClass(a.call(this,b,this.className))});if(h)for(b=(a||"").match(E)||[];j>i;i++)if(c=this[i],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(ac," "):" ")){f=0;while(e=b[f++])d.indexOf(" "+e+" ")<0&&(d+=e+" ");g=o.trim(d),c.className!==g&&(c.className=g)}return this},removeClass:function(a){var b,c,d,e,f,g,h=0===arguments.length||"string"==typeof a&&a,i=0,j=this.length;if(o.isFunction(a))return this.each(function(b){o(this).removeClass(a.call(this,b,this.className))});if(h)for(b=(a||"").match(E)||[];j>i;i++)if(c=this[i],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(ac," "):"")){f=0;while(e=b[f++])while(d.indexOf(" "+e+" ")>=0)d=d.replace(" "+e+" "," ");g=a?o.trim(d):"",c.className!==g&&(c.className=g)}return this},toggleClass:function(a,b){var c=typeof a;return"boolean"==typeof b&&"string"===c?b?this.addClass(a):this.removeClass(a):this.each(o.isFunction(a)?function(c){o(this).toggleClass(a.call(this,c,this.className,b),b)}:function(){if("string"===c){var b,d=0,e=o(this),f=a.match(E)||[];while(b=f[d++])e.hasClass(b)?e.removeClass(b):e.addClass(b)}else(c===U||"boolean"===c)&&(this.className&&L.set(this,"__className__",this.className),this.className=this.className||a===!1?"":L.get(this,"__className__")||"")})},hasClass:function(a){for(var b=" "+a+" ",c=0,d=this.length;d>c;c++)if(1===this[c].nodeType&&(" "+this[c].className+" ").replace(ac," ").indexOf(b)>=0)return!0;return!1}});var bc=/\r/g;o.fn.extend({val:function(a){var b,c,d,e=this[0];{if(arguments.length)return d=o.isFunction(a),this.each(function(c){var e;1===this.nodeType&&(e=d?a.call(this,c,o(this).val()):a,null==e?e="":"number"==typeof e?e+="":o.isArray(e)&&(e=o.map(e,function(a){return null==a?"":a+""})),b=o.valHooks[this.type]||o.valHooks[this.nodeName.toLowerCase()],b&&"set"in b&&void 0!==b.set(this,e,"value")||(this.value=e))});if(e)return b=o.valHooks[e.type]||o.valHooks[e.nodeName.toLowerCase()],b&&"get"in b&&void 0!==(c=b.get(e,"value"))?c:(c=e.value,"string"==typeof c?c.replace(bc,""):null==c?"":c)}}}),o.extend({valHooks:{select:{get:function(a){for(var b,c,d=a.options,e=a.selectedIndex,f="select-one"===a.type||0>e,g=f?null:[],h=f?e+1:d.length,i=0>e?h:f?e:0;h>i;i++)if(c=d[i],!(!c.selected&&i!==e||(l.optDisabled?c.disabled:null!==c.getAttribute("disabled"))||c.parentNode.disabled&&o.nodeName(c.parentNode,"optgroup"))){if(b=o(c).val(),f)return b;g.push(b)}return g},set:function(a,b){var c,d,e=a.options,f=o.makeArray(b),g=e.length;while(g--)d=e[g],(d.selected=o.inArray(o(d).val(),f)>=0)&&(c=!0);return c||(a.selectedIndex=-1),f}}}}),o.each(["radio","checkbox"],function(){o.valHooks[this]={set:function(a,b){return o.isArray(b)?a.checked=o.inArray(o(a).val(),b)>=0:void 0}},l.checkOn||(o.valHooks[this].get=function(a){return null===a.getAttribute("value")?"on":a.value})}),o.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(a,b){o.fn[b]=function(a,c){return arguments.length>0?this.on(b,null,a,c):this.trigger(b)}}),o.fn.extend({hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)},bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return 1===arguments.length?this.off(a,"**"):this.off(b,a||"**",c)}});var cc=o.now(),dc=/\?/;o.parseJSON=function(a){return JSON.parse(a+"")},o.parseXML=function(a){var b,c;if(!a||"string"!=typeof a)return null;try{c=new DOMParser,b=c.parseFromString(a,"text/xml")}catch(d){b=void 0}return(!b||b.getElementsByTagName("parsererror").length)&&o.error("Invalid XML: "+a),b};var ec,fc,gc=/#.*$/,hc=/([?&])_=[^&]*/,ic=/^(.*?):[ \t]*([^\r\n]*)$/gm,jc=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,kc=/^(?:GET|HEAD)$/,lc=/^\/\//,mc=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,nc={},oc={},pc="*/".concat("*");try{fc=location.href}catch(qc){fc=m.createElement("a"),fc.href="",fc=fc.href}ec=mc.exec(fc.toLowerCase())||[];function rc(a){return function(b,c){"string"!=typeof b&&(c=b,b="*");var d,e=0,f=b.toLowerCase().match(E)||[];if(o.isFunction(c))while(d=f[e++])"+"===d[0]?(d=d.slice(1)||"*",(a[d]=a[d]||[]).unshift(c)):(a[d]=a[d]||[]).push(c)}}function sc(a,b,c,d){var e={},f=a===oc;function g(h){var i;return e[h]=!0,o.each(a[h]||[],function(a,h){var j=h(b,c,d);return"string"!=typeof j||f||e[j]?f?!(i=j):void 0:(b.dataTypes.unshift(j),g(j),!1)}),i}return g(b.dataTypes[0])||!e["*"]&&g("*")}function tc(a,b){var c,d,e=o.ajaxSettings.flatOptions||{};for(c in b)void 0!==b[c]&&((e[c]?a:d||(d={}))[c]=b[c]);return d&&o.extend(!0,a,d),a}function uc(a,b,c){var d,e,f,g,h=a.contents,i=a.dataTypes;while("*"===i[0])i.shift(),void 0===d&&(d=a.mimeType||b.getResponseHeader("Content-Type"));if(d)for(e in h)if(h[e]&&h[e].test(d)){i.unshift(e);break}if(i[0]in c)f=i[0];else{for(e in c){if(!i[0]||a.converters[e+" "+i[0]]){f=e;break}g||(g=e)}f=f||g}return f?(f!==i[0]&&i.unshift(f),c[f]):void 0}function vc(a,b,c,d){var e,f,g,h,i,j={},k=a.dataTypes.slice();if(k[1])for(g in a.converters)j[g.toLowerCase()]=a.converters[g];f=k.shift();while(f)if(a.responseFields[f]&&(c[a.responseFields[f]]=b),!i&&d&&a.dataFilter&&(b=a.dataFilter(b,a.dataType)),i=f,f=k.shift())if("*"===f)f=i;else if("*"!==i&&i!==f){if(g=j[i+" "+f]||j["* "+f],!g)for(e in j)if(h=e.split(" "),h[1]===f&&(g=j[i+" "+h[0]]||j["* "+h[0]])){g===!0?g=j[e]:j[e]!==!0&&(f=h[0],k.unshift(h[1]));break}if(g!==!0)if(g&&a["throws"])b=g(b);else try{b=g(b)}catch(l){return{state:"parsererror",error:g?l:"No conversion from "+i+" to "+f}}}return{state:"success",data:b}}o.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:fc,type:"GET",isLocal:jc.test(ec[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":pc,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":o.parseJSON,"text xml":o.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(a,b){return b?tc(tc(a,o.ajaxSettings),b):tc(o.ajaxSettings,a)},ajaxPrefilter:rc(nc),ajaxTransport:rc(oc),ajax:function(a,b){"object"==typeof a&&(b=a,a=void 0),b=b||{};var c,d,e,f,g,h,i,j,k=o.ajaxSetup({},b),l=k.context||k,m=k.context&&(l.nodeType||l.jquery)?o(l):o.event,n=o.Deferred(),p=o.Callbacks("once memory"),q=k.statusCode||{},r={},s={},t=0,u="canceled",v={readyState:0,getResponseHeader:function(a){var b;if(2===t){if(!f){f={};while(b=ic.exec(e))f[b[1].toLowerCase()]=b[2]}b=f[a.toLowerCase()]}return null==b?null:b},getAllResponseHeaders:function(){return 2===t?e:null},setRequestHeader:function(a,b){var c=a.toLowerCase();return t||(a=s[c]=s[c]||a,r[a]=b),this},overrideMimeType:function(a){return t||(k.mimeType=a),this},statusCode:function(a){var b;if(a)if(2>t)for(b in a)q[b]=[q[b],a[b]];else v.always(a[v.status]);return this},abort:function(a){var b=a||u;return c&&c.abort(b),x(0,b),this}};if(n.promise(v).complete=p.add,v.success=v.done,v.error=v.fail,k.url=((a||k.url||fc)+"").replace(gc,"").replace(lc,ec[1]+"//"),k.type=b.method||b.type||k.method||k.type,k.dataTypes=o.trim(k.dataType||"*").toLowerCase().match(E)||[""],null==k.crossDomain&&(h=mc.exec(k.url.toLowerCase()),k.crossDomain=!(!h||h[1]===ec[1]&&h[2]===ec[2]&&(h[3]||("http:"===h[1]?"80":"443"))===(ec[3]||("http:"===ec[1]?"80":"443")))),k.data&&k.processData&&"string"!=typeof k.data&&(k.data=o.param(k.data,k.traditional)),sc(nc,k,b,v),2===t)return v;i=k.global,i&&0===o.active++&&o.event.trigger("ajaxStart"),k.type=k.type.toUpperCase(),k.hasContent=!kc.test(k.type),d=k.url,k.hasContent||(k.data&&(d=k.url+=(dc.test(d)?"&":"?")+k.data,delete k.data),k.cache===!1&&(k.url=hc.test(d)?d.replace(hc,"$1_="+cc++):d+(dc.test(d)?"&":"?")+"_="+cc++)),k.ifModified&&(o.lastModified[d]&&v.setRequestHeader("If-Modified-Since",o.lastModified[d]),o.etag[d]&&v.setRequestHeader("If-None-Match",o.etag[d])),(k.data&&k.hasContent&&k.contentType!==!1||b.contentType)&&v.setRequestHeader("Content-Type",k.contentType),v.setRequestHeader("Accept",k.dataTypes[0]&&k.accepts[k.dataTypes[0]]?k.accepts[k.dataTypes[0]]+("*"!==k.dataTypes[0]?", "+pc+"; q=0.01":""):k.accepts["*"]);for(j in k.headers)v.setRequestHeader(j,k.headers[j]);if(k.beforeSend&&(k.beforeSend.call(l,v,k)===!1||2===t))return v.abort();u="abort";for(j in{success:1,error:1,complete:1})v[j](k[j]);if(c=sc(oc,k,b,v)){v.readyState=1,i&&m.trigger("ajaxSend",[v,k]),k.async&&k.timeout>0&&(g=setTimeout(function(){v.abort("timeout")},k.timeout));try{t=1,c.send(r,x)}catch(w){if(!(2>t))throw w;x(-1,w)}}else x(-1,"No Transport");function x(a,b,f,h){var j,r,s,u,w,x=b;2!==t&&(t=2,g&&clearTimeout(g),c=void 0,e=h||"",v.readyState=a>0?4:0,j=a>=200&&300>a||304===a,f&&(u=uc(k,v,f)),u=vc(k,u,v,j),j?(k.ifModified&&(w=v.getResponseHeader("Last-Modified"),w&&(o.lastModified[d]=w),w=v.getResponseHeader("etag"),w&&(o.etag[d]=w)),204===a||"HEAD"===k.type?x="nocontent":304===a?x="notmodified":(x=u.state,r=u.data,s=u.error,j=!s)):(s=x,(a||!x)&&(x="error",0>a&&(a=0))),v.status=a,v.statusText=(b||x)+"",j?n.resolveWith(l,[r,x,v]):n.rejectWith(l,[v,x,s]),v.statusCode(q),q=void 0,i&&m.trigger(j?"ajaxSuccess":"ajaxError",[v,k,j?r:s]),p.fireWith(l,[v,x]),i&&(m.trigger("ajaxComplete",[v,k]),--o.active||o.event.trigger("ajaxStop")))}return v},getJSON:function(a,b,c){return o.get(a,b,c,"json")},getScript:function(a,b){return o.get(a,void 0,b,"script")}}),o.each(["get","post"],function(a,b){o[b]=function(a,c,d,e){return o.isFunction(c)&&(e=e||d,d=c,c=void 0),o.ajax({url:a,type:b,dataType:e,data:c,success:d})}}),o.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(a,b){o.fn[b]=function(a){return this.on(b,a)}}),o._evalUrl=function(a){return o.ajax({url:a,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})},o.fn.extend({wrapAll:function(a){var b;return o.isFunction(a)?this.each(function(b){o(this).wrapAll(a.call(this,b))}):(this[0]&&(b=o(a,this[0].ownerDocument).eq(0).clone(!0),this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstElementChild)a=a.firstElementChild;return a}).append(this)),this)},wrapInner:function(a){return this.each(o.isFunction(a)?function(b){o(this).wrapInner(a.call(this,b))}:function(){var b=o(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=o.isFunction(a);return this.each(function(c){o(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){o.nodeName(this,"body")||o(this).replaceWith(this.childNodes)}).end()}}),o.expr.filters.hidden=function(a){return a.offsetWidth<=0&&a.offsetHeight<=0},o.expr.filters.visible=function(a){return!o.expr.filters.hidden(a)};var wc=/%20/g,xc=/\[\]$/,yc=/\r?\n/g,zc=/^(?:submit|button|image|reset|file)$/i,Ac=/^(?:input|select|textarea|keygen)/i;function Bc(a,b,c,d){var e;if(o.isArray(b))o.each(b,function(b,e){c||xc.test(a)?d(a,e):Bc(a+"["+("object"==typeof e?b:"")+"]",e,c,d)});else if(c||"object"!==o.type(b))d(a,b);else for(e in b)Bc(a+"["+e+"]",b[e],c,d)}o.param=function(a,b){var c,d=[],e=function(a,b){b=o.isFunction(b)?b():null==b?"":b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};if(void 0===b&&(b=o.ajaxSettings&&o.ajaxSettings.traditional),o.isArray(a)||a.jquery&&!o.isPlainObject(a))o.each(a,function(){e(this.name,this.value)});else for(c in a)Bc(c,a[c],b,e);return d.join("&").replace(wc,"+")},o.fn.extend({serialize:function(){return o.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var a=o.prop(this,"elements");return a?o.makeArray(a):this}).filter(function(){var a=this.type;return this.name&&!o(this).is(":disabled")&&Ac.test(this.nodeName)&&!zc.test(a)&&(this.checked||!T.test(a))}).map(function(a,b){var c=o(this).val();return null==c?null:o.isArray(c)?o.map(c,function(a){return{name:b.name,value:a.replace(yc,"\r\n")}}):{name:b.name,value:c.replace(yc,"\r\n")}}).get()}}),o.ajaxSettings.xhr=function(){try{return new XMLHttpRequest}catch(a){}};var Cc=0,Dc={},Ec={0:200,1223:204},Fc=o.ajaxSettings.xhr();a.ActiveXObject&&o(a).on("unload",function(){for(var a in Dc)Dc[a]()}),l.cors=!!Fc&&"withCredentials"in Fc,l.ajax=Fc=!!Fc,o.ajaxTransport(function(a){var b;return l.cors||Fc&&!a.crossDomain?{send:function(c,d){var e,f=a.xhr(),g=++Cc;if(f.open(a.type,a.url,a.async,a.username,a.password),a.xhrFields)for(e in a.xhrFields)f[e]=a.xhrFields[e];a.mimeType&&f.overrideMimeType&&f.overrideMimeType(a.mimeType),a.crossDomain||c["X-Requested-With"]||(c["X-Requested-With"]="XMLHttpRequest");for(e in c)f.setRequestHeader(e,c[e]);b=function(a){return function(){b&&(delete Dc[g],b=f.onload=f.onerror=null,"abort"===a?f.abort():"error"===a?d(f.status,f.statusText):d(Ec[f.status]||f.status,f.statusText,"string"==typeof f.responseText?{text:f.responseText}:void 0,f.getAllResponseHeaders()))}},f.onload=b(),f.onerror=b("error"),b=Dc[g]=b("abort"),f.send(a.hasContent&&a.data||null)},abort:function(){b&&b()}}:void 0}),o.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(a){return o.globalEval(a),a}}}),o.ajaxPrefilter("script",function(a){void 0===a.cache&&(a.cache=!1),a.crossDomain&&(a.type="GET")}),o.ajaxTransport("script",function(a){if(a.crossDomain){var b,c;return{send:function(d,e){b=o("<script>").prop({async:!0,charset:a.scriptCharset,src:a.url}).on("load error",c=function(a){b.remove(),c=null,a&&e("error"===a.type?404:200,a.type)}),m.head.appendChild(b[0])},abort:function(){c&&c()}}}});var Gc=[],Hc=/(=)\?(?=&|$)|\?\?/;o.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=Gc.pop()||o.expando+"_"+cc++;return this[a]=!0,a}}),o.ajaxPrefilter("json jsonp",function(b,c,d){var e,f,g,h=b.jsonp!==!1&&(Hc.test(b.url)?"url":"string"==typeof b.data&&!(b.contentType||"").indexOf("application/x-www-form-urlencoded")&&Hc.test(b.data)&&"data");return h||"jsonp"===b.dataTypes[0]?(e=b.jsonpCallback=o.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,h?b[h]=b[h].replace(Hc,"$1"+e):b.jsonp!==!1&&(b.url+=(dc.test(b.url)?"&":"?")+b.jsonp+"="+e),b.converters["script json"]=function(){return g||o.error(e+" was not called"),g[0]},b.dataTypes[0]="json",f=a[e],a[e]=function(){g=arguments},d.always(function(){a[e]=f,b[e]&&(b.jsonpCallback=c.jsonpCallback,Gc.push(e)),g&&o.isFunction(f)&&f(g[0]),g=f=void 0}),"script"):void 0}),o.parseHTML=function(a,b,c){if(!a||"string"!=typeof a)return null;"boolean"==typeof b&&(c=b,b=!1),b=b||m;var d=v.exec(a),e=!c&&[];return d?[b.createElement(d[1])]:(d=o.buildFragment([a],b,e),e&&e.length&&o(e).remove(),o.merge([],d.childNodes))};var Ic=o.fn.load;o.fn.load=function(a,b,c){if("string"!=typeof a&&Ic)return Ic.apply(this,arguments);var d,e,f,g=this,h=a.indexOf(" ");return h>=0&&(d=a.slice(h),a=a.slice(0,h)),o.isFunction(b)?(c=b,b=void 0):b&&"object"==typeof b&&(e="POST"),g.length>0&&o.ajax({url:a,type:e,dataType:"html",data:b}).done(function(a){f=arguments,g.html(d?o("<div>").append(o.parseHTML(a)).find(d):a)}).complete(c&&function(a,b){g.each(c,f||[a.responseText,b,a])}),this},o.expr.filters.animated=function(a){return o.grep(o.timers,function(b){return a===b.elem}).length};var Jc=a.document.documentElement;function Kc(a){return o.isWindow(a)?a:9===a.nodeType&&a.defaultView}o.offset={setOffset:function(a,b,c){var d,e,f,g,h,i,j,k=o.css(a,"position"),l=o(a),m={};"static"===k&&(a.style.position="relative"),h=l.offset(),f=o.css(a,"top"),i=o.css(a,"left"),j=("absolute"===k||"fixed"===k)&&(f+i).indexOf("auto")>-1,j?(d=l.position(),g=d.top,e=d.left):(g=parseFloat(f)||0,e=parseFloat(i)||0),o.isFunction(b)&&(b=b.call(a,c,h)),null!=b.top&&(m.top=b.top-h.top+g),null!=b.left&&(m.left=b.left-h.left+e),"using"in b?b.using.call(a,m):l.css(m)}},o.fn.extend({offset:function(a){if(arguments.length)return void 0===a?this:this.each(function(b){o.offset.setOffset(this,a,b)});var b,c,d=this[0],e={top:0,left:0},f=d&&d.ownerDocument;if(f)return b=f.documentElement,o.contains(b,d)?(typeof d.getBoundingClientRect!==U&&(e=d.getBoundingClientRect()),c=Kc(f),{top:e.top+c.pageYOffset-b.clientTop,left:e.left+c.pageXOffset-b.clientLeft}):e},position:function(){if(this[0]){var a,b,c=this[0],d={top:0,left:0};return"fixed"===o.css(c,"position")?b=c.getBoundingClientRect():(a=this.offsetParent(),b=this.offset(),o.nodeName(a[0],"html")||(d=a.offset()),d.top+=o.css(a[0],"borderTopWidth",!0),d.left+=o.css(a[0],"borderLeftWidth",!0)),{top:b.top-d.top-o.css(c,"marginTop",!0),left:b.left-d.left-o.css(c,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||Jc;while(a&&!o.nodeName(a,"html")&&"static"===o.css(a,"position"))a=a.offsetParent;return a||Jc})}}),o.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(b,c){var d="pageYOffset"===c;o.fn[b]=function(e){return J(this,function(b,e,f){var g=Kc(b);return void 0===f?g?g[c]:b[e]:void(g?g.scrollTo(d?a.pageXOffset:f,d?f:a.pageYOffset):b[e]=f)},b,e,arguments.length,null)}}),o.each(["top","left"],function(a,b){o.cssHooks[b]=yb(l.pixelPosition,function(a,c){return c?(c=xb(a,b),vb.test(c)?o(a).position()[b]+"px":c):void 0})}),o.each({Height:"height",Width:"width"},function(a,b){o.each({padding:"inner"+a,content:b,"":"outer"+a},function(c,d){o.fn[d]=function(d,e){var f=arguments.length&&(c||"boolean"!=typeof d),g=c||(d===!0||e===!0?"margin":"border");return J(this,function(b,c,d){var e;return o.isWindow(b)?b.document.documentElement["client"+a]:9===b.nodeType?(e=b.documentElement,Math.max(b.body["scroll"+a],e["scroll"+a],b.body["offset"+a],e["offset"+a],e["client"+a])):void 0===d?o.css(b,c,g):o.style(b,c,d,g)},b,f?d:void 0,f,null)}})}),o.fn.size=function(){return this.length},o.fn.andSelf=o.fn.addBack,"function"==typeof define&&define.amd&&define("jquery",[],function(){return o});var Lc=a.jQuery,Mc=a.$;return o.noConflict=function(b){return a.$===o&&(a.$=Mc),b&&a.jQuery===o&&(a.jQuery=Lc),o},typeof b===U&&(a.jQuery=a.$=o),o});
--- a/server/python/django/renkanmanager/static/renkanmanager/lib/jquery.mousewheel.js Fri Apr 24 13:05:09 2015 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,201 +0,0 @@
-/*! Copyright (c) 2013 Brandon Aaron (http://brandon.aaron.sh)
- * Licensed under the MIT License (LICENSE.txt).
- *
- * Version: 3.1.9
- *
- * Requires: jQuery 1.2.2+
- */
-
-(function (factory) {
- if ( typeof define === 'function' && define.amd ) {
- // AMD. Register as an anonymous module.
- define(['jquery'], factory);
- } else if (typeof exports === 'object') {
- // Node/CommonJS style for Browserify
- module.exports = factory;
- } else {
- // Browser globals
- factory(jQuery);
- }
-}(function ($) {
-
- var toFix = ['wheel', 'mousewheel', 'DOMMouseScroll', 'MozMousePixelScroll'],
- toBind = ( 'onwheel' in document || document.documentMode >= 9 ) ?
- ['wheel'] : ['mousewheel', 'DomMouseScroll', 'MozMousePixelScroll'],
- slice = Array.prototype.slice,
- nullLowestDeltaTimeout, lowestDelta;
-
- if ( $.event.fixHooks ) {
- for ( var i = toFix.length; i; ) {
- $.event.fixHooks[ toFix[--i] ] = $.event.mouseHooks;
- }
- }
-
- var special = $.event.special.mousewheel = {
- version: '3.1.9',
-
- setup: function() {
- if ( this.addEventListener ) {
- for ( var i = toBind.length; i; ) {
- this.addEventListener( toBind[--i], handler, false );
- }
- } else {
- this.onmousewheel = handler;
- }
- // Store the line height and page height for this particular element
- $.data(this, 'mousewheel-line-height', special.getLineHeight(this));
- $.data(this, 'mousewheel-page-height', special.getPageHeight(this));
- },
-
- teardown: function() {
- if ( this.removeEventListener ) {
- for ( var i = toBind.length; i; ) {
- this.removeEventListener( toBind[--i], handler, false );
- }
- } else {
- this.onmousewheel = null;
- }
- },
-
- getLineHeight: function(elem) {
- return parseInt($(elem)['offsetParent' in $.fn ? 'offsetParent' : 'parent']().css('fontSize'), 10);
- },
-
- getPageHeight: function(elem) {
- return $(elem).height();
- },
-
- settings: {
- adjustOldDeltas: true
- }
- };
-
- $.fn.extend({
- mousewheel: function(fn) {
- return fn ? this.bind('mousewheel', fn) : this.trigger('mousewheel');
- },
-
- unmousewheel: function(fn) {
- return this.unbind('mousewheel', fn);
- }
- });
-
-
- function handler(event) {
- var orgEvent = event || window.event,
- args = slice.call(arguments, 1),
- delta = 0,
- deltaX = 0,
- deltaY = 0,
- absDelta = 0;
- event = $.event.fix(orgEvent);
- event.type = 'mousewheel';
-
- // Old school scrollwheel delta
- if ( 'detail' in orgEvent ) { deltaY = orgEvent.detail * -1; }
- if ( 'wheelDelta' in orgEvent ) { deltaY = orgEvent.wheelDelta; }
- if ( 'wheelDeltaY' in orgEvent ) { deltaY = orgEvent.wheelDeltaY; }
- if ( 'wheelDeltaX' in orgEvent ) { deltaX = orgEvent.wheelDeltaX * -1; }
-
- // Firefox < 17 horizontal scrolling related to DOMMouseScroll event
- if ( 'axis' in orgEvent && orgEvent.axis === orgEvent.HORIZONTAL_AXIS ) {
- deltaX = deltaY * -1;
- deltaY = 0;
- }
-
- // Set delta to be deltaY or deltaX if deltaY is 0 for backwards compatabilitiy
- delta = deltaY === 0 ? deltaX : deltaY;
-
- // New school wheel delta (wheel event)
- if ( 'deltaY' in orgEvent ) {
- deltaY = orgEvent.deltaY * -1;
- delta = deltaY;
- }
- if ( 'deltaX' in orgEvent ) {
- deltaX = orgEvent.deltaX;
- if ( deltaY === 0 ) { delta = deltaX * -1; }
- }
-
- // No change actually happened, no reason to go any further
- if ( deltaY === 0 && deltaX === 0 ) { return; }
-
- // Need to convert lines and pages to pixels if we aren't already in pixels
- // There are three delta modes:
- // * deltaMode 0 is by pixels, nothing to do
- // * deltaMode 1 is by lines
- // * deltaMode 2 is by pages
- if ( orgEvent.deltaMode === 1 ) {
- var lineHeight = $.data(this, 'mousewheel-line-height');
- delta *= lineHeight;
- deltaY *= lineHeight;
- deltaX *= lineHeight;
- } else if ( orgEvent.deltaMode === 2 ) {
- var pageHeight = $.data(this, 'mousewheel-page-height');
- delta *= pageHeight;
- deltaY *= pageHeight;
- deltaX *= pageHeight;
- }
-
- // Store lowest absolute delta to normalize the delta values
- absDelta = Math.max( Math.abs(deltaY), Math.abs(deltaX) );
-
- if ( !lowestDelta || absDelta < lowestDelta ) {
- lowestDelta = absDelta;
-
- // Adjust older deltas if necessary
- if ( shouldAdjustOldDeltas(orgEvent, absDelta) ) {
- lowestDelta /= 40;
- }
- }
-
- // Adjust older deltas if necessary
- if ( shouldAdjustOldDeltas(orgEvent, absDelta) ) {
- // Divide all the things by 40!
- delta /= 40;
- deltaX /= 40;
- deltaY /= 40;
- }
-
- // Get a whole, normalized value for the deltas
- delta = Math[ delta >= 1 ? 'floor' : 'ceil' ](delta / lowestDelta);
- deltaX = Math[ deltaX >= 1 ? 'floor' : 'ceil' ](deltaX / lowestDelta);
- deltaY = Math[ deltaY >= 1 ? 'floor' : 'ceil' ](deltaY / lowestDelta);
-
- // Add information to the event object
- event.deltaX = deltaX;
- event.deltaY = deltaY;
- event.deltaFactor = lowestDelta;
- // Go ahead and set deltaMode to 0 since we converted to pixels
- // Although this is a little odd since we overwrite the deltaX/Y
- // properties with normalized deltas.
- event.deltaMode = 0;
-
- // Add event and delta to the front of the arguments
- args.unshift(event, delta, deltaX, deltaY);
-
- // Clearout lowestDelta after sometime to better
- // handle multiple device types that give different
- // a different lowestDelta
- // Ex: trackpad = 3 and mouse wheel = 120
- if (nullLowestDeltaTimeout) { clearTimeout(nullLowestDeltaTimeout); }
- nullLowestDeltaTimeout = setTimeout(nullLowestDelta, 200);
-
- return ($.event.dispatch || $.event.handle).apply(this, args);
- }
-
- function nullLowestDelta() {
- lowestDelta = null;
- }
-
- function shouldAdjustOldDeltas(orgEvent, absDelta) {
- // If this is an older event and the delta is divisable by 120,
- // then we are assuming that the browser is treating this as an
- // older mouse wheel event and that we should divide the deltas
- // by 40 to try and get a more usable deltaFactor.
- // Side note, this actually impacts the reported scroll distance
- // in older browsers and can cause scrolling to be slower than native.
- // Turn this off by setting $.event.special.mousewheel.settings.adjustOldDeltas to false.
- return special.settings.adjustOldDeltas && orgEvent.type === 'mousewheel' && absDelta % 120 === 0;
- }
-
-}));
--- a/server/python/django/renkanmanager/static/renkanmanager/lib/jquery.mousewheel.min.js Fri Apr 24 13:05:09 2015 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,201 +0,0 @@
-/*! Copyright (c) 2013 Brandon Aaron (http://brandon.aaron.sh)
- * Licensed under the MIT License (LICENSE.txt).
- *
- * Version: 3.1.9
- *
- * Requires: jQuery 1.2.2+
- */
-
-(function (factory) {
- if ( typeof define === 'function' && define.amd ) {
- // AMD. Register as an anonymous module.
- define(['jquery'], factory);
- } else if (typeof exports === 'object') {
- // Node/CommonJS style for Browserify
- module.exports = factory;
- } else {
- // Browser globals
- factory(jQuery);
- }
-}(function ($) {
-
- var toFix = ['wheel', 'mousewheel', 'DOMMouseScroll', 'MozMousePixelScroll'],
- toBind = ( 'onwheel' in document || document.documentMode >= 9 ) ?
- ['wheel'] : ['mousewheel', 'DomMouseScroll', 'MozMousePixelScroll'],
- slice = Array.prototype.slice,
- nullLowestDeltaTimeout, lowestDelta;
-
- if ( $.event.fixHooks ) {
- for ( var i = toFix.length; i; ) {
- $.event.fixHooks[ toFix[--i] ] = $.event.mouseHooks;
- }
- }
-
- var special = $.event.special.mousewheel = {
- version: '3.1.9',
-
- setup: function() {
- if ( this.addEventListener ) {
- for ( var i = toBind.length; i; ) {
- this.addEventListener( toBind[--i], handler, false );
- }
- } else {
- this.onmousewheel = handler;
- }
- // Store the line height and page height for this particular element
- $.data(this, 'mousewheel-line-height', special.getLineHeight(this));
- $.data(this, 'mousewheel-page-height', special.getPageHeight(this));
- },
-
- teardown: function() {
- if ( this.removeEventListener ) {
- for ( var i = toBind.length; i; ) {
- this.removeEventListener( toBind[--i], handler, false );
- }
- } else {
- this.onmousewheel = null;
- }
- },
-
- getLineHeight: function(elem) {
- return parseInt($(elem)['offsetParent' in $.fn ? 'offsetParent' : 'parent']().css('fontSize'), 10);
- },
-
- getPageHeight: function(elem) {
- return $(elem).height();
- },
-
- settings: {
- adjustOldDeltas: true
- }
- };
-
- $.fn.extend({
- mousewheel: function(fn) {
- return fn ? this.bind('mousewheel', fn) : this.trigger('mousewheel');
- },
-
- unmousewheel: function(fn) {
- return this.unbind('mousewheel', fn);
- }
- });
-
-
- function handler(event) {
- var orgEvent = event || window.event,
- args = slice.call(arguments, 1),
- delta = 0,
- deltaX = 0,
- deltaY = 0,
- absDelta = 0;
- event = $.event.fix(orgEvent);
- event.type = 'mousewheel';
-
- // Old school scrollwheel delta
- if ( 'detail' in orgEvent ) { deltaY = orgEvent.detail * -1; }
- if ( 'wheelDelta' in orgEvent ) { deltaY = orgEvent.wheelDelta; }
- if ( 'wheelDeltaY' in orgEvent ) { deltaY = orgEvent.wheelDeltaY; }
- if ( 'wheelDeltaX' in orgEvent ) { deltaX = orgEvent.wheelDeltaX * -1; }
-
- // Firefox < 17 horizontal scrolling related to DOMMouseScroll event
- if ( 'axis' in orgEvent && orgEvent.axis === orgEvent.HORIZONTAL_AXIS ) {
- deltaX = deltaY * -1;
- deltaY = 0;
- }
-
- // Set delta to be deltaY or deltaX if deltaY is 0 for backwards compatabilitiy
- delta = deltaY === 0 ? deltaX : deltaY;
-
- // New school wheel delta (wheel event)
- if ( 'deltaY' in orgEvent ) {
- deltaY = orgEvent.deltaY * -1;
- delta = deltaY;
- }
- if ( 'deltaX' in orgEvent ) {
- deltaX = orgEvent.deltaX;
- if ( deltaY === 0 ) { delta = deltaX * -1; }
- }
-
- // No change actually happened, no reason to go any further
- if ( deltaY === 0 && deltaX === 0 ) { return; }
-
- // Need to convert lines and pages to pixels if we aren't already in pixels
- // There are three delta modes:
- // * deltaMode 0 is by pixels, nothing to do
- // * deltaMode 1 is by lines
- // * deltaMode 2 is by pages
- if ( orgEvent.deltaMode === 1 ) {
- var lineHeight = $.data(this, 'mousewheel-line-height');
- delta *= lineHeight;
- deltaY *= lineHeight;
- deltaX *= lineHeight;
- } else if ( orgEvent.deltaMode === 2 ) {
- var pageHeight = $.data(this, 'mousewheel-page-height');
- delta *= pageHeight;
- deltaY *= pageHeight;
- deltaX *= pageHeight;
- }
-
- // Store lowest absolute delta to normalize the delta values
- absDelta = Math.max( Math.abs(deltaY), Math.abs(deltaX) );
-
- if ( !lowestDelta || absDelta < lowestDelta ) {
- lowestDelta = absDelta;
-
- // Adjust older deltas if necessary
- if ( shouldAdjustOldDeltas(orgEvent, absDelta) ) {
- lowestDelta /= 40;
- }
- }
-
- // Adjust older deltas if necessary
- if ( shouldAdjustOldDeltas(orgEvent, absDelta) ) {
- // Divide all the things by 40!
- delta /= 40;
- deltaX /= 40;
- deltaY /= 40;
- }
-
- // Get a whole, normalized value for the deltas
- delta = Math[ delta >= 1 ? 'floor' : 'ceil' ](delta / lowestDelta);
- deltaX = Math[ deltaX >= 1 ? 'floor' : 'ceil' ](deltaX / lowestDelta);
- deltaY = Math[ deltaY >= 1 ? 'floor' : 'ceil' ](deltaY / lowestDelta);
-
- // Add information to the event object
- event.deltaX = deltaX;
- event.deltaY = deltaY;
- event.deltaFactor = lowestDelta;
- // Go ahead and set deltaMode to 0 since we converted to pixels
- // Although this is a little odd since we overwrite the deltaX/Y
- // properties with normalized deltas.
- event.deltaMode = 0;
-
- // Add event and delta to the front of the arguments
- args.unshift(event, delta, deltaX, deltaY);
-
- // Clearout lowestDelta after sometime to better
- // handle multiple device types that give different
- // a different lowestDelta
- // Ex: trackpad = 3 and mouse wheel = 120
- if (nullLowestDeltaTimeout) { clearTimeout(nullLowestDeltaTimeout); }
- nullLowestDeltaTimeout = setTimeout(nullLowestDelta, 200);
-
- return ($.event.dispatch || $.event.handle).apply(this, args);
- }
-
- function nullLowestDelta() {
- lowestDelta = null;
- }
-
- function shouldAdjustOldDeltas(orgEvent, absDelta) {
- // If this is an older event and the delta is divisable by 120,
- // then we are assuming that the browser is treating this as an
- // older mouse wheel event and that we should divide the deltas
- // by 40 to try and get a more usable deltaFactor.
- // Side note, this actually impacts the reported scroll distance
- // in older browsers and can cause scrolling to be slower than native.
- // Turn this off by setting $.event.special.mousewheel.settings.adjustOldDeltas to false.
- return special.settings.adjustOldDeltas && orgEvent.type === 'mousewheel' && absDelta % 120 === 0;
- }
-
-}));
--- a/server/python/django/renkanmanager/static/renkanmanager/lib/paper.js Fri Apr 24 13:05:09 2015 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,12218 +0,0 @@
-/*!
- * Paper.js v0.9.15 - The Swiss Army Knife of Vector Graphics Scripting.
- * http://paperjs.org/
- *
- * Copyright (c) 2011 - 2013, Juerg Lehni & Jonathan Puckey
- * http://lehni.org/ & http://jonathanpuckey.com/
- *
- * Distributed under the MIT license. See LICENSE file for details.
- *
- * All rights reserved.
- *
- * Date: Sun Dec 1 23:54:52 2013 +0100
- *
- ***
- *
- * straps.js - Class inheritance library with support for bean-style accessors
- *
- * Copyright (c) 2006 - 2013 Juerg Lehni
- * http://lehni.org/
- *
- * Distributed under the MIT license.
- *
- ***
- *
- * acorn.js
- * http://marijnhaverbeke.nl/acorn/
- *
- * Acorn is a tiny, fast JavaScript parser written in JavaScript,
- * created by Marijn Haverbeke and released under an MIT license.
- *
- */
-
-var paper = new function(undefined) {
-
-var Base = new function() {
- var hidden = /^(statics|generics|preserve|enumerable|prototype|toString|valueOf)$/,
- slice = [].slice,
-
- forEach = [].forEach || function(iter, bind) {
- for (var i = 0, l = this.length; i < l; i++)
- iter.call(bind, this[i], i, this);
- },
-
- forIn = function(iter, bind) {
- for (var i in this)
- if (this.hasOwnProperty(i))
- iter.call(bind, this[i], i, this);
- },
-
- create = Object.create || function(proto) {
- return { __proto__: proto };
- },
-
- describe = Object.getOwnPropertyDescriptor || function(obj, name) {
- var get = obj.__lookupGetter__ && obj.__lookupGetter__(name);
- return get
- ? { get: get, set: obj.__lookupSetter__(name),
- enumerable: true, configurable: true }
- : obj.hasOwnProperty(name)
- ? { value: obj[name], enumerable: true,
- configurable: true, writable: true }
- : null;
- },
-
- _define = Object.defineProperty || function(obj, name, desc) {
- if ((desc.get || desc.set) && obj.__defineGetter__) {
- if (desc.get)
- obj.__defineGetter__(name, desc.get);
- if (desc.set)
- obj.__defineSetter__(name, desc.set);
- } else {
- obj[name] = desc.value;
- }
- return obj;
- },
-
- define = function(obj, name, desc) {
- delete obj[name];
- return _define(obj, name, desc);
- };
-
- function inject(dest, src, enumerable, base, preserve, generics) {
- var beans;
-
- function field(name, val, dontCheck, generics) {
- var val = val || (val = describe(src, name))
- && (val.get ? val : val.value);
- if (typeof val === 'string' && val[0] === '#')
- val = dest[val.substring(1)] || val;
- var isFunc = typeof val === 'function',
- res = val,
- prev = preserve || isFunc
- ? (val && val.get ? name in dest : dest[name]) : null,
- bean;
- if ((dontCheck || val !== undefined && src.hasOwnProperty(name))
- && (!preserve || !prev)) {
- if (isFunc && prev)
- val.base = prev;
- if (isFunc && beans && val.length === 0
- && (bean = name.match(/^(get|is)(([A-Z])(.*))$/)))
- beans.push([ bean[3].toLowerCase() + bean[4], bean[2] ]);
- if (!res || isFunc || !res.get || typeof res.get !== 'function'
- || res.get.length !== 0)
- res = { value: res, writable: true };
- if ((describe(dest, name)
- || { configurable: true }).configurable) {
- res.configurable = true;
- res.enumerable = enumerable;
- }
- define(dest, name, res);
- }
- if (generics && isFunc && (!preserve || !generics[name])) {
- generics[name] = function(bind) {
- return bind && dest[name].apply(bind,
- slice.call(arguments, 1));
- };
- }
- }
- if (src) {
- beans = [];
- for (var name in src)
- if (src.hasOwnProperty(name) && !hidden.test(name))
- field(name, null, true, generics);
- field('toString');
- field('valueOf');
- for (var i = 0, l = beans.length; i < l; i++) {
- var bean = beans[i],
- part = bean[1];
- field(bean[0], {
- get: dest['get' + part] || dest['is' + part],
- set: dest['set' + part]
- }, true);
- }
- }
- return dest;
- }
-
- function each(obj, iter, bind) {
- if (obj)
- ('length' in obj && !obj.getLength
- && typeof obj.length === 'number'
- ? forEach
- : forIn).call(obj, iter, bind = bind || obj);
- return bind;
- }
-
- function copy(dest, source) {
- for (var i in source)
- if (source.hasOwnProperty(i))
- dest[i] = source[i];
- return dest;
- }
-
- function clone(obj) {
- return copy(new obj.constructor(), obj);
- }
-
- return inject(function Base() {
- for (var i = 0, l = arguments.length; i < l; i++)
- copy(this, arguments[i]);
- }, {
- inject: function(src) {
- if (src) {
- var proto = this.prototype,
- base = Object.getPrototypeOf(proto).constructor,
- statics = src.statics === true ? src : src.statics;
- if (statics != src)
- inject(proto, src, src.enumerable, base && base.prototype,
- src.preserve, src.generics && this);
- inject(this, statics, true, base, src.preserve);
- }
- for (var i = 1, l = arguments.length; i < l; i++)
- this.inject(arguments[i]);
- return this;
- },
-
- extend: function() {
- var base = this,
- ctor;
- for (var i = 0, l = arguments.length; i < l; i++)
- if (ctor = arguments[i].initialize)
- break;
- ctor = ctor || function() {
- base.apply(this, arguments);
- };
- ctor.prototype = create(this.prototype);
- define(ctor.prototype, 'constructor',
- { value: ctor, writable: true, configurable: true });
- inject(ctor, this, true);
- return arguments.length ? this.inject.apply(ctor, arguments) : ctor;
- }
- }, true).inject({
- inject: function() {
- for (var i = 0, l = arguments.length; i < l; i++)
- inject(this, arguments[i], arguments[i].enumerable);
- return this;
- },
-
- extend: function() {
- var res = create(this);
- return res.inject.apply(res, arguments);
- },
-
- each: function(iter, bind) {
- return each(this, iter, bind);
- },
-
- clone: function() {
- return new this.constructor(this);
- },
-
- statics: {
- each: each,
- create: create,
- define: define,
- describe: describe,
- copy: copy,
-
- clone: function(obj) {
- return copy(new obj.constructor(), obj);
- },
-
- isPlainObject: function(obj) {
- var ctor = obj != null && obj.constructor;
- return ctor && (ctor === Object || ctor === Base
- || ctor.name === 'Object');
- },
-
- pick: function() {
- for (var i = 0, l = arguments.length; i < l; i++)
- if (arguments[i] !== undefined)
- return arguments[i];
- return null;
- }
- }
- });
-};
-
-if (typeof module !== 'undefined')
- module.exports = Base;
-
-Base.inject({
- generics: true,
-
- toString: function() {
- return this._id != null
- ? (this._class || 'Object') + (this._name
- ? " '" + this._name + "'"
- : ' @' + this._id)
- : '{ ' + Base.each(this, function(value, key) {
- if (!/^_/.test(key)) {
- var type = typeof value;
- this.push(key + ': ' + (type === 'number'
- ? Formatter.instance.number(value)
- : type === 'string' ? "'" + value + "'" : value));
- }
- }, []).join(', ') + ' }';
- },
-
- exportJSON: function(options) {
- return Base.exportJSON(this, options);
- },
-
- toJSON: function() {
- return Base.serialize(this);
- },
-
- _set: function(props, exclude) {
- if (props && Base.isPlainObject(props)) {
- var orig = props._filtering || props;
- for (var key in orig) {
- if (key in this && orig.hasOwnProperty(key)
- && (!exclude || !exclude[key])) {
- var value = props[key];
- if (value !== undefined)
- this[key] = value;
- }
- }
- return true;
- }
- },
-
- statics: {
-
- exports: {},
-
- extend: function extend() {
- var res = extend.base.apply(this, arguments),
- name = res.prototype._class;
- if (name && !Base.exports[name])
- Base.exports[name] = res;
- return res;
- },
-
- equals: function(obj1, obj2) {
- function checkKeys(o1, o2) {
- for (var i in o1)
- if (o1.hasOwnProperty(i) && !o2.hasOwnProperty(i))
- return false;
- return true;
- }
- if (obj1 === obj2)
- return true;
- if (obj1 && obj1.equals)
- return obj1.equals(obj2);
- if (obj2 && obj2.equals)
- return obj2.equals(obj1);
- if (Array.isArray(obj1) && Array.isArray(obj2)) {
- if (obj1.length !== obj2.length)
- return false;
- for (var i = 0, l = obj1.length; i < l; i++) {
- if (!Base.equals(obj1[i], obj2[i]))
- return false;
- }
- return true;
- }
- if (obj1 && typeof obj1 === 'object'
- && obj2 && typeof obj2 === 'object') {
- if (!checkKeys(obj1, obj2) || !checkKeys(obj2, obj1))
- return false;
- for (var i in obj1) {
- if (obj1.hasOwnProperty(i) && !Base.equals(obj1[i], obj2[i]))
- return false;
- }
- return true;
- }
- return false;
- },
-
- read: function(list, start, length, options) {
- if (this === Base) {
- var value = this.peek(list, start);
- list._index++;
- list.__read = 1;
- return value;
- }
- var proto = this.prototype,
- readIndex = proto._readIndex,
- index = start || readIndex && list._index || 0;
- if (!length)
- length = list.length - index;
- var obj = list[index];
- if (obj instanceof this
- || options && options.readNull && obj == null && length <= 1) {
- if (readIndex)
- list._index = index + 1;
- return obj && options && options.clone ? obj.clone() : obj;
- }
- obj = Base.create(this.prototype);
- if (readIndex)
- obj.__read = true;
- if (options)
- obj.__options = options;
- obj = obj.initialize.apply(obj, index > 0 || length < list.length
- ? Array.prototype.slice.call(list, index, index + length)
- : list) || obj;
- if (readIndex) {
- list._index = index + obj.__read;
- list.__read = obj.__read;
- delete obj.__read;
- if (options)
- delete obj.__options;
- }
- return obj;
- },
-
- peek: function(list, start) {
- return list[list._index = start || list._index || 0];
- },
-
- readAll: function(list, start, options) {
- var res = [], entry;
- for (var i = start || 0, l = list.length; i < l; i++) {
- res.push(Array.isArray(entry = list[i])
- ? this.read(entry, 0, 0, options)
- : this.read(list, i, 1, options));
- }
- return res;
- },
-
- readNamed: function(list, name, start, length, options) {
- var value = this.getNamed(list, name),
- hasObject = value !== undefined;
- if (hasObject) {
- var filtered = list._filtered;
- if (!filtered) {
- filtered = list._filtered = Base.create(list[0]);
- filtered._filtering = list[0];
- }
- filtered[name] = undefined;
- }
- return this.read(hasObject ? [value] : list, start, length, options);
- },
-
- getNamed: function(list, name) {
- var arg = list[0];
- if (list._hasObject === undefined)
- list._hasObject = list.length === 1 && Base.isPlainObject(arg);
- if (list._hasObject)
- return name ? arg[name] : list._filtered || arg;
- },
-
- hasNamed: function(list, name) {
- return !!this.getNamed(list, name);
- },
-
- isPlainValue: function(obj) {
- return this.isPlainObject(obj) || Array.isArray(obj);
- },
-
- serialize: function(obj, options, compact, dictionary) {
- options = options || {};
-
- var root = !dictionary,
- res;
- if (root) {
- options.formatter = new Formatter(options.precision);
- dictionary = {
- length: 0,
- definitions: {},
- references: {},
- add: function(item, create) {
- var id = '#' + item._id,
- ref = this.references[id];
- if (!ref) {
- this.length++;
- var res = create.call(item),
- name = item._class;
- if (name && res[0] !== name)
- res.unshift(name);
- this.definitions[id] = res;
- ref = this.references[id] = [id];
- }
- return ref;
- }
- };
- }
- if (obj && obj._serialize) {
- res = obj._serialize(options, dictionary);
- var name = obj._class;
- if (name && !compact && !res._compact && res[0] !== name)
- res.unshift(name);
- } else if (Array.isArray(obj)) {
- res = [];
- for (var i = 0, l = obj.length; i < l; i++)
- res[i] = Base.serialize(obj[i], options, compact,
- dictionary);
- if (compact)
- res._compact = true;
- } else if (Base.isPlainObject(obj)) {
- res = {};
- for (var i in obj)
- if (obj.hasOwnProperty(i))
- res[i] = Base.serialize(obj[i], options, compact,
- dictionary);
- } else if (typeof obj === 'number') {
- res = options.formatter.number(obj, options.precision);
- } else {
- res = obj;
- }
- return root && dictionary.length > 0
- ? [['dictionary', dictionary.definitions], res]
- : res;
- },
-
- deserialize: function(json, create, _data) {
- var res = json;
- _data = _data || {};
- if (Array.isArray(json)) {
- var type = json[0],
- isDictionary = type === 'dictionary';
- if (!isDictionary) {
- if (_data.dictionary && json.length == 1 && /^#/.test(type))
- return _data.dictionary[type];
- type = Base.exports[type];
- }
- res = [];
- for (var i = type ? 1 : 0, l = json.length; i < l; i++)
- res.push(Base.deserialize(json[i], create, _data));
- if (isDictionary) {
- _data.dictionary = res[0];
- } else if (type) {
- var args = res;
- if (create) {
- res = create(type, args);
- } else {
- res = Base.create(type.prototype);
- type.apply(res, args);
- }
- }
- } else if (Base.isPlainObject(json)) {
- res = {};
- for (var key in json)
- res[key] = Base.deserialize(json[key], create, _data);
- }
- return res;
- },
-
- exportJSON: function(obj, options) {
- return JSON.stringify(Base.serialize(obj, options));
- },
-
- importJSON: function(json, target) {
- return Base.deserialize(
- typeof json === 'string' ? JSON.parse(json) : json,
- function(type, args) {
- var obj = target && target.constructor === type
- ? target
- : Base.create(type.prototype),
- isTarget = obj === target;
- if (args.length === 1 && obj instanceof Item
- && (!(obj instanceof Layer) || isTarget)) {
- var arg = args[0];
- if (Base.isPlainObject(arg))
- arg.insert = false;
- }
- type.apply(obj, args);
- if (isTarget)
- target = null;
- return obj;
- });
- },
-
- splice: function(list, items, index, remove) {
- var amount = items && items.length,
- append = index === undefined;
- index = append ? list.length : index;
- if (index > list.length)
- index = list.length;
- for (var i = 0; i < amount; i++)
- items[i]._index = index + i;
- if (append) {
- list.push.apply(list, items);
- return [];
- } else {
- var args = [index, remove];
- if (items)
- args.push.apply(args, items);
- var removed = list.splice.apply(list, args);
- for (var i = 0, l = removed.length; i < l; i++)
- delete removed[i]._index;
- for (var i = index + amount, l = list.length; i < l; i++)
- list[i]._index = i;
- return removed;
- }
- },
-
- capitalize: function(str) {
- return str.replace(/\b[a-z]/g, function(match) {
- return match.toUpperCase();
- });
- },
-
- camelize: function(str) {
- return str.replace(/-(.)/g, function(all, chr) {
- return chr.toUpperCase();
- });
- },
-
- hyphenate: function(str) {
- return str.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
- }
- }
-});
-
-var Callback = {
- attach: function(type, func) {
- if (typeof type !== 'string') {
- Base.each(type, function(value, key) {
- this.attach(key, value);
- }, this);
- return;
- }
- var entry = this._eventTypes[type];
- if (entry) {
- var handlers = this._handlers = this._handlers || {};
- handlers = handlers[type] = handlers[type] || [];
- if (handlers.indexOf(func) == -1) {
- handlers.push(func);
- if (entry.install && handlers.length == 1)
- entry.install.call(this, type);
- }
- }
- },
-
- detach: function(type, func) {
- if (typeof type !== 'string') {
- Base.each(type, function(value, key) {
- this.detach(key, value);
- }, this);
- return;
- }
- var entry = this._eventTypes[type],
- handlers = this._handlers && this._handlers[type],
- index;
- if (entry && handlers) {
- if (!func || (index = handlers.indexOf(func)) != -1
- && handlers.length == 1) {
- if (entry.uninstall)
- entry.uninstall.call(this, type);
- delete this._handlers[type];
- } else if (index != -1) {
- handlers.splice(index, 1);
- }
- }
- },
-
- once: function(type, func) {
- this.attach(type, function() {
- func.apply(this, arguments);
- this.detach(type, func);
- });
- },
-
- fire: function(type, event) {
- var handlers = this._handlers && this._handlers[type];
- if (!handlers)
- return false;
- var args = [].slice.call(arguments, 1),
- PaperScript = paper.PaperScript,
- handleException = PaperScript && PaperScript.handleException,
- that = this;
-
- function callHandlers() {
- for (var i in handlers) {
- if (handlers[i].apply(that, args) === false
- && event && event.stop)
- event.stop();
- }
- }
-
- if (handleException) {
- try {
- callHandlers();
- } catch (e) {
- handleException(e);
- }
- } else {
- callHandlers();
- }
- return true;
- },
-
- responds: function(type) {
- return !!(this._handlers && this._handlers[type]);
- },
-
- on: '#attach',
- off: '#detach',
- trigger: '#fire',
-
- statics: {
- inject: function inject() {
- for (var i = 0, l = arguments.length; i < l; i++) {
- var src = arguments[i],
- events = src._events;
- if (events) {
- var types = {};
- Base.each(events, function(entry, key) {
- var isString = typeof entry === 'string',
- name = isString ? entry : key,
- part = Base.capitalize(name),
- type = name.substring(2).toLowerCase();
- types[type] = isString ? {} : entry;
- name = '_' + name;
- src['get' + part] = function() {
- return this[name];
- };
- src['set' + part] = function(func) {
- if (func) {
- this.attach(type, func);
- } else if (this[name]) {
- this.detach(type, this[name]);
- }
- this[name] = func;
- };
- });
- src._eventTypes = types;
- }
- inject.base.call(this, src);
- }
- return this;
- }
- }
-};
-
-var PaperScope = Base.extend({
- _class: 'PaperScope',
-
- initialize: function PaperScope(script) {
- paper = this;
- this.project = null;
- this.projects = [];
- this.tools = [];
- this.palettes = [];
- this._id = script && (script.getAttribute('id') || script.src)
- || ('paperscope-' + (PaperScope._id++));
- if (script)
- script.setAttribute('id', this._id);
- PaperScope._scopes[this._id] = this;
- if (!this.support) {
- var ctx = CanvasProvider.getContext(1, 1);
- PaperScope.prototype.support = {
- nativeDash: 'setLineDash' in ctx || 'mozDash' in ctx,
- nativeBlendModes: BlendMode.nativeModes
- };
- CanvasProvider.release(ctx);
- }
- },
-
- version: '0.9.15',
-
- getView: function() {
- return this.project && this.project.view;
- },
-
- getTool: function() {
- if (!this._tool)
- this._tool = new Tool();
- return this._tool;
- },
-
- getPaper: function() {
- return this;
- },
-
- evaluate: function(code) {
- var res = paper.PaperScript.evaluate(code, this);
- View.updateFocus();
- return res;
- },
-
- install: function(scope) {
- var that = this;
- Base.each(['project', 'view', 'tool'], function(key) {
- Base.define(scope, key, {
- configurable: true,
- get: function() {
- return that[key];
- }
- });
- });
- for (var key in this) {
- if (!/^(version|_id)/.test(key))
- scope[key] = this[key];
- }
- },
-
- setup: function(canvas) {
- paper = this;
- this.project = new Project(canvas);
- return this;
- },
-
- activate: function() {
- paper = this;
- },
-
- clear: function() {
- for (var i = this.projects.length - 1; i >= 0; i--)
- this.projects[i].remove();
- for (var i = this.tools.length - 1; i >= 0; i--)
- this.tools[i].remove();
- for (var i = this.palettes.length - 1; i >= 0; i--)
- this.palettes[i].remove();
- },
-
- remove: function() {
- this.clear();
- delete PaperScope._scopes[this._id];
- },
-
- statics: new function() {
- function handleAttribute(name) {
- name += 'Attribute';
- return function(el, attr) {
- return el[name](attr) || el[name]('data-paper-' + attr);
- };
- }
-
- return {
- _scopes: {},
- _id: 0,
-
- get: function(id) {
- if (typeof id === 'object')
- id = id.getAttribute('id');
- return this._scopes[id] || null;
- },
-
- getAttribute: handleAttribute('get'),
- hasAttribute: handleAttribute('has')
- };
- }
-});
-
-var PaperScopeItem = Base.extend(Callback, {
-
- initialize: function(activate) {
- this._scope = paper;
- this._index = this._scope[this._list].push(this) - 1;
- if (activate || !this._scope[this._reference])
- this.activate();
- },
-
- activate: function() {
- if (!this._scope)
- return false;
- var prev = this._scope[this._reference];
- if (prev && prev !== this)
- prev.fire('deactivate');
- this._scope[this._reference] = this;
- this.fire('activate', prev);
- return true;
- },
-
- isActive: function() {
- return this._scope[this._reference] === this;
- },
-
- remove: function() {
- if (this._index == null)
- return false;
- Base.splice(this._scope[this._list], null, this._index, 1);
- if (this._scope[this._reference] == this)
- this._scope[this._reference] = null;
- this._scope = null;
- return true;
- }
-});
-
-var Formatter = Base.extend({
- initialize: function(precision) {
- this.precision = precision || 5;
- this.multiplier = Math.pow(10, this.precision);
- },
-
- number: function(val) {
- return Math.round(val * this.multiplier) / this.multiplier;
- },
-
- point: function(val, separator) {
- return this.number(val.x) + (separator || ',') + this.number(val.y);
- },
-
- size: function(val, separator) {
- return this.number(val.width) + (separator || ',')
- + this.number(val.height);
- },
-
- rectangle: function(val, separator) {
- return this.point(val, separator) + (separator || ',')
- + this.size(val, separator);
- }
-});
-
-Formatter.instance = new Formatter();
-
-var Numerical = new function() {
-
- var abscissas = [
- [ 0.5773502691896257645091488],
- [0,0.7745966692414833770358531],
- [ 0.3399810435848562648026658,0.8611363115940525752239465],
- [0,0.5384693101056830910363144,0.9061798459386639927976269],
- [ 0.2386191860831969086305017,0.6612093864662645136613996,0.9324695142031520278123016],
- [0,0.4058451513773971669066064,0.7415311855993944398638648,0.9491079123427585245261897],
- [ 0.1834346424956498049394761,0.5255324099163289858177390,0.7966664774136267395915539,0.9602898564975362316835609],
- [0,0.3242534234038089290385380,0.6133714327005903973087020,0.8360311073266357942994298,0.9681602395076260898355762],
- [ 0.1488743389816312108848260,0.4333953941292471907992659,0.6794095682990244062343274,0.8650633666889845107320967,0.9739065285171717200779640],
- [0,0.2695431559523449723315320,0.5190961292068118159257257,0.7301520055740493240934163,0.8870625997680952990751578,0.9782286581460569928039380],
- [ 0.1252334085114689154724414,0.3678314989981801937526915,0.5873179542866174472967024,0.7699026741943046870368938,0.9041172563704748566784659,0.9815606342467192506905491],
- [0,0.2304583159551347940655281,0.4484927510364468528779129,0.6423493394403402206439846,0.8015780907333099127942065,0.9175983992229779652065478,0.9841830547185881494728294],
- [ 0.1080549487073436620662447,0.3191123689278897604356718,0.5152486363581540919652907,0.6872929048116854701480198,0.8272013150697649931897947,0.9284348836635735173363911,0.9862838086968123388415973],
- [0,0.2011940939974345223006283,0.3941513470775633698972074,0.5709721726085388475372267,0.7244177313601700474161861,0.8482065834104272162006483,0.9372733924007059043077589,0.9879925180204854284895657],
- [ 0.0950125098376374401853193,0.2816035507792589132304605,0.4580167776572273863424194,0.6178762444026437484466718,0.7554044083550030338951012,0.8656312023878317438804679,0.9445750230732325760779884,0.9894009349916499325961542]
- ];
-
- var weights = [
- [1],
- [0.8888888888888888888888889,0.5555555555555555555555556],
- [0.6521451548625461426269361,0.3478548451374538573730639],
- [0.5688888888888888888888889,0.4786286704993664680412915,0.2369268850561890875142640],
- [0.4679139345726910473898703,0.3607615730481386075698335,0.1713244923791703450402961],
- [0.4179591836734693877551020,0.3818300505051189449503698,0.2797053914892766679014678,0.1294849661688696932706114],
- [0.3626837833783619829651504,0.3137066458778872873379622,0.2223810344533744705443560,0.1012285362903762591525314],
- [0.3302393550012597631645251,0.3123470770400028400686304,0.2606106964029354623187429,0.1806481606948574040584720,0.0812743883615744119718922],
- [0.2955242247147528701738930,0.2692667193099963550912269,0.2190863625159820439955349,0.1494513491505805931457763,0.0666713443086881375935688],
- [0.2729250867779006307144835,0.2628045445102466621806889,0.2331937645919904799185237,0.1862902109277342514260976,0.1255803694649046246346943,0.0556685671161736664827537],
- [0.2491470458134027850005624,0.2334925365383548087608499,0.2031674267230659217490645,0.1600783285433462263346525,0.1069393259953184309602547,0.0471753363865118271946160],
- [0.2325515532308739101945895,0.2262831802628972384120902,0.2078160475368885023125232,0.1781459807619457382800467,0.1388735102197872384636018,0.0921214998377284479144218,0.0404840047653158795200216],
- [0.2152638534631577901958764,0.2051984637212956039659241,0.1855383974779378137417166,0.1572031671581935345696019,0.1215185706879031846894148,0.0801580871597602098056333,0.0351194603317518630318329],
- [0.2025782419255612728806202,0.1984314853271115764561183,0.1861610000155622110268006,0.1662692058169939335532009,0.1395706779261543144478048,0.1071592204671719350118695,0.0703660474881081247092674,0.0307532419961172683546284],
- [0.1894506104550684962853967,0.1826034150449235888667637,0.1691565193950025381893121,0.1495959888165767320815017,0.1246289712555338720524763,0.0951585116824927848099251,0.0622535239386478928628438,0.0271524594117540948517806]
- ];
-
- var abs = Math.abs,
- sqrt = Math.sqrt,
- pow = Math.pow,
- cos = Math.cos,
- PI = Math.PI;
-
- return {
- TOLERANCE: 10e-6,
- EPSILON: 10e-12,
- KAPPA: 4 * (sqrt(2) - 1) / 3,
-
- isZero: function(val) {
- return abs(val) <= Numerical.EPSILON;
- },
-
- integrate: function(f, a, b, n) {
- var x = abscissas[n - 2],
- w = weights[n - 2],
- A = 0.5 * (b - a),
- B = A + a,
- i = 0,
- m = (n + 1) >> 1,
- sum = n & 1 ? w[i++] * f(B) : 0;
- while (i < m) {
- var Ax = A * x[i];
- sum += w[i++] * (f(B + Ax) + f(B - Ax));
- }
- return A * sum;
- },
-
- findRoot: function(f, df, x, a, b, n, tolerance) {
- for (var i = 0; i < n; i++) {
- var fx = f(x),
- dx = fx / df(x);
- if (abs(dx) < tolerance)
- return x;
- var nx = x - dx;
- if (fx > 0) {
- b = x;
- x = nx <= a ? 0.5 * (a + b) : nx;
- } else {
- a = x;
- x = nx >= b ? 0.5 * (a + b) : nx;
- }
- }
- },
-
- solveQuadratic: function(a, b, c, roots, min, max) {
- var epsilon = Numerical.EPSILON,
- unbound = min === undefined,
- minE = min - epsilon,
- maxE = max + epsilon,
- count = 0;
-
- function add(root) {
- if (unbound || root > minE && root < maxE)
- roots[count++] = root < min ? min : root > max ? max : root;
- return count;
- }
-
- if (abs(a) < epsilon) {
- if (abs(b) >= epsilon)
- return add(-c / b);
- return abs(c) < epsilon ? -1 : 0;
- }
- var p = b / (2 * a);
- var q = c / a;
- var p2 = p * p;
- if (p2 < q - epsilon)
- return 0;
- var s = p2 > q ? sqrt(p2 - q) : 0;
- add (s - p);
- if (s > 0)
- add(-s - p);
- return count;
- },
-
- solveCubic: function(a, b, c, d, roots, min, max) {
- var epsilon = Numerical.EPSILON;
- if (abs(a) < epsilon)
- return Numerical.solveQuadratic(b, c, d, roots, min, max);
-
- var unbound = min === undefined,
- minE = min - epsilon,
- maxE = max + epsilon,
- count = 0;
-
- function add(root) {
- if (unbound || root > minE && root < maxE)
- roots[count++] = root < min ? min : root > max ? max : root;
- return count;
- }
-
- b /= a;
- c /= a;
- d /= a;
- var bb = b * b,
- p = (bb - 3 * c) / 9,
- q = (2 * bb * b - 9 * b * c + 27 * d) / 54,
- ppp = p * p * p,
- D = q * q - ppp;
- b /= 3;
- if (abs(D) < epsilon) {
- if (abs(q) < epsilon)
- return add(-b);
- var sqp = sqrt(p),
- snq = q > 0 ? 1 : -1;
- add(-snq * 2 * sqp - b);
- return add(snq * sqp - b);
- }
- if (D < 0) {
- var sqp = sqrt(p),
- phi = Math.acos(q / (sqp * sqp * sqp)) / 3,
- t = -2 * sqp,
- o = 2 * PI / 3;
- add(t * cos(phi) - b);
- add(t * cos(phi + o) - b);
- return add(t * cos(phi - o) - b);
- }
- var A = (q > 0 ? -1 : 1) * pow(abs(q) + sqrt(D), 1 / 3);
- return add(A + p / A - b);
- }
- };
-};
-
-var Point = Base.extend({
- _class: 'Point',
- _readIndex: true,
-
- initialize: function Point(arg0, arg1) {
- var type = typeof arg0;
- if (type === 'number') {
- var hasY = typeof arg1 === 'number';
- this.x = arg0;
- this.y = hasY ? arg1 : arg0;
- if (this.__read)
- this.__read = hasY ? 2 : 1;
- } else if (type === 'undefined' || arg0 === null) {
- this.x = this.y = 0;
- if (this.__read)
- this.__read = arg0 === null ? 1 : 0;
- } else {
- if (Array.isArray(arg0)) {
- this.x = arg0[0];
- this.y = arg0.length > 1 ? arg0[1] : arg0[0];
- } else if (arg0.x != null) {
- this.x = arg0.x;
- this.y = arg0.y;
- } else if (arg0.width != null) {
- this.x = arg0.width;
- this.y = arg0.height;
- } else if (arg0.angle != null) {
- this.x = arg0.length;
- this.y = 0;
- this.setAngle(arg0.angle);
- } else {
- this.x = this.y = 0;
- if (this.__read)
- this.__read = 0;
- }
- if (this.__read)
- this.__read = 1;
- }
- },
-
- set: function(x, y) {
- this.x = x;
- this.y = y;
- return this;
- },
-
- equals: function(point) {
- return point === this || point && (this.x === point.x
- && this.y === point.y
- || Array.isArray(point) && this.x === point[0]
- && this.y === point[1]) || false;
- },
-
- clone: function() {
- return new Point(this.x, this.y);
- },
-
- toString: function() {
- var f = Formatter.instance;
- return '{ x: ' + f.number(this.x) + ', y: ' + f.number(this.y) + ' }';
- },
-
- _serialize: function(options) {
- var f = options.formatter;
- return [f.number(this.x), f.number(this.y)];
- },
-
- add: function(point) {
- point = Point.read(arguments);
- return new Point(this.x + point.x, this.y + point.y);
- },
-
- subtract: function(point) {
- point = Point.read(arguments);
- return new Point(this.x - point.x, this.y - point.y);
- },
-
- multiply: function(point) {
- point = Point.read(arguments);
- return new Point(this.x * point.x, this.y * point.y);
- },
-
- divide: function(point) {
- point = Point.read(arguments);
- return new Point(this.x / point.x, this.y / point.y);
- },
-
- modulo: function(point) {
- point = Point.read(arguments);
- return new Point(this.x % point.x, this.y % point.y);
- },
-
- negate: function() {
- return new Point(-this.x, -this.y);
- },
-
- transform: function(matrix) {
- return matrix ? matrix._transformPoint(this) : this;
- },
-
- getDistance: function(point, squared) {
- point = Point.read(arguments);
- var x = point.x - this.x,
- y = point.y - this.y,
- d = x * x + y * y;
- return squared ? d : Math.sqrt(d);
- },
-
- getLength: function() {
- var length = this.x * this.x + this.y * this.y;
- return arguments.length && arguments[0] ? length : Math.sqrt(length);
- },
-
- setLength: function(length) {
- if (this.isZero()) {
- var angle = this._angle || 0;
- this.set(
- Math.cos(angle) * length,
- Math.sin(angle) * length
- );
- } else {
- var scale = length / this.getLength();
- if (Numerical.isZero(scale))
- this.getAngle();
- this.set(
- this.x * scale,
- this.y * scale
- );
- }
- return this;
- },
-
- normalize: function(length) {
- if (length === undefined)
- length = 1;
- var current = this.getLength(),
- scale = current !== 0 ? length / current : 0,
- point = new Point(this.x * scale, this.y * scale);
- point._angle = this._angle;
- return point;
- },
-
- getAngle: function() {
- return this.getAngleInRadians(arguments[0]) * 180 / Math.PI;
- },
-
- setAngle: function(angle) {
- angle = this._angle = angle * Math.PI / 180;
- if (!this.isZero()) {
- var length = this.getLength();
- this.set(
- Math.cos(angle) * length,
- Math.sin(angle) * length
- );
- }
- return this;
- },
-
- getAngleInRadians: function() {
- if (arguments[0] === undefined) {
- return this.isZero()
- ? this._angle || 0
- : this._angle = Math.atan2(this.y, this.x);
- } else {
- var point = Point.read(arguments),
- div = this.getLength() * point.getLength();
- if (Numerical.isZero(div)) {
- return NaN;
- } else {
- return Math.acos(this.dot(point) / div);
- }
- }
- },
-
- getAngleInDegrees: function() {
- return this.getAngle(arguments[0]);
- },
-
- getQuadrant: function() {
- return this.x >= 0 ? this.y >= 0 ? 1 : 4 : this.y >= 0 ? 2 : 3;
- },
-
- getDirectedAngle: function(point) {
- point = Point.read(arguments);
- return Math.atan2(this.cross(point), this.dot(point)) * 180 / Math.PI;
- },
-
- rotate: function(angle, center) {
- if (angle === 0)
- return this.clone();
- angle = angle * Math.PI / 180;
- var point = center ? this.subtract(center) : this,
- s = Math.sin(angle),
- c = Math.cos(angle);
- point = new Point(
- point.x * c - point.y * s,
- point.y * c + point.x * s
- );
- return center ? point.add(center) : point;
- },
-
- isInside: function(rect) {
- return rect.contains(this);
- },
-
- isClose: function(point, tolerance) {
- return this.getDistance(point) < tolerance;
- },
-
- isColinear: function(point) {
- return this.cross(point) < 0.00001;
- },
-
- isOrthogonal: function(point) {
- return this.dot(point) < 0.00001;
- },
-
- isZero: function() {
- return Numerical.isZero(this.x) && Numerical.isZero(this.y);
- },
-
- isNaN: function() {
- return isNaN(this.x) || isNaN(this.y);
- },
-
- dot: function(point) {
- point = Point.read(arguments);
- return this.x * point.x + this.y * point.y;
- },
-
- cross: function(point) {
- point = Point.read(arguments);
- return this.x * point.y - this.y * point.x;
- },
-
- project: function(point) {
- point = Point.read(arguments);
- if (point.isZero()) {
- return new Point(0, 0);
- } else {
- var scale = this.dot(point) / point.dot(point);
- return new Point(
- point.x * scale,
- point.y * scale
- );
- }
- },
-
- statics: {
- min: function() {
- var point1 = Point.read(arguments);
- point2 = Point.read(arguments);
- return new Point(
- Math.min(point1.x, point2.x),
- Math.min(point1.y, point2.y)
- );
- },
-
- max: function() {
- var point1 = Point.read(arguments);
- point2 = Point.read(arguments);
- return new Point(
- Math.max(point1.x, point2.x),
- Math.max(point1.y, point2.y)
- );
- },
-
- random: function() {
- return new Point(Math.random(), Math.random());
- }
- }
-}, Base.each(['round', 'ceil', 'floor', 'abs'], function(name) {
- var op = Math[name];
- this[name] = function() {
- return new Point(op(this.x), op(this.y));
- };
-}, {}));
-
-var LinkedPoint = Point.extend({
- initialize: function Point(x, y, owner, setter) {
- this._x = x;
- this._y = y;
- this._owner = owner;
- this._setter = setter;
- },
-
- set: function(x, y, _dontNotify) {
- this._x = x;
- this._y = y;
- if (!_dontNotify)
- this._owner[this._setter](this);
- return this;
- },
-
- getX: function() {
- return this._x;
- },
-
- setX: function(x) {
- this._x = x;
- this._owner[this._setter](this);
- },
-
- getY: function() {
- return this._y;
- },
-
- setY: function(y) {
- this._y = y;
- this._owner[this._setter](this);
- }
-});
-
-var Size = Base.extend({
- _class: 'Size',
- _readIndex: true,
-
- initialize: function Size(arg0, arg1) {
- var type = typeof arg0;
- if (type === 'number') {
- var hasHeight = typeof arg1 === 'number';
- this.width = arg0;
- this.height = hasHeight ? arg1 : arg0;
- if (this.__read)
- this.__read = hasHeight ? 2 : 1;
- } else if (type === 'undefined' || arg0 === null) {
- this.width = this.height = 0;
- if (this.__read)
- this.__read = arg0 === null ? 1 : 0;
- } else {
- if (Array.isArray(arg0)) {
- this.width = arg0[0];
- this.height = arg0.length > 1 ? arg0[1] : arg0[0];
- } else if (arg0.width != null) {
- this.width = arg0.width;
- this.height = arg0.height;
- } else if (arg0.x != null) {
- this.width = arg0.x;
- this.height = arg0.y;
- } else {
- this.width = this.height = 0;
- if (this.__read)
- this.__read = 0;
- }
- if (this.__read)
- this.__read = 1;
- }
- },
-
- set: function(width, height) {
- this.width = width;
- this.height = height;
- return this;
- },
-
- equals: function(size) {
- return size === this || size && (this.width === size.width
- && this.height === size.height
- || Array.isArray(size) && this.width === size[0]
- && this.height === size[1]) || false;
- },
-
- clone: function() {
- return new Size(this.width, this.height);
- },
-
- toString: function() {
- var f = Formatter.instance;
- return '{ width: ' + f.number(this.width)
- + ', height: ' + f.number(this.height) + ' }';
- },
-
- _serialize: function(options) {
- var f = options.formatter;
- return [f.number(this.width),
- f.number(this.height)];
- },
-
- add: function(size) {
- size = Size.read(arguments);
- return new Size(this.width + size.width, this.height + size.height);
- },
-
- subtract: function(size) {
- size = Size.read(arguments);
- return new Size(this.width - size.width, this.height - size.height);
- },
-
- multiply: function(size) {
- size = Size.read(arguments);
- return new Size(this.width * size.width, this.height * size.height);
- },
-
- divide: function(size) {
- size = Size.read(arguments);
- return new Size(this.width / size.width, this.height / size.height);
- },
-
- modulo: function(size) {
- size = Size.read(arguments);
- return new Size(this.width % size.width, this.height % size.height);
- },
-
- negate: function() {
- return new Size(-this.width, -this.height);
- },
-
- isZero: function() {
- return Numerical.isZero(this.width) && Numerical.isZero(this.height);
- },
-
- isNaN: function() {
- return isNaN(this.width) || isNaN(this.height);
- },
-
- statics: {
- min: function(size1, size2) {
- return new Size(
- Math.min(size1.width, size2.width),
- Math.min(size1.height, size2.height));
- },
-
- max: function(size1, size2) {
- return new Size(
- Math.max(size1.width, size2.width),
- Math.max(size1.height, size2.height));
- },
-
- random: function() {
- return new Size(Math.random(), Math.random());
- }
- }
-}, Base.each(['round', 'ceil', 'floor', 'abs'], function(name) {
- var op = Math[name];
- this[name] = function() {
- return new Size(op(this.width), op(this.height));
- };
-}, {}));
-
-var LinkedSize = Size.extend({
- initialize: function Size(width, height, owner, setter) {
- this._width = width;
- this._height = height;
- this._owner = owner;
- this._setter = setter;
- },
-
- set: function(width, height, _dontNotify) {
- this._width = width;
- this._height = height;
- if (!_dontNotify)
- this._owner[this._setter](this);
- return this;
- },
-
- getWidth: function() {
- return this._width;
- },
-
- setWidth: function(width) {
- this._width = width;
- this._owner[this._setter](this);
- },
-
- getHeight: function() {
- return this._height;
- },
-
- setHeight: function(height) {
- this._height = height;
- this._owner[this._setter](this);
- }
-});
-
-var Rectangle = Base.extend({
- _class: 'Rectangle',
- _readIndex: true,
-
- initialize: function Rectangle(arg0, arg1, arg2, arg3) {
- var type = typeof arg0,
- read = 0;
- if (type === 'number') {
- this.x = arg0;
- this.y = arg1;
- this.width = arg2;
- this.height = arg3;
- read = 4;
- } else if (type === 'undefined' || arg0 === null) {
- this.x = this.y = this.width = this.height = 0;
- read = arg0 === null ? 1 : 0;
- } else if (arguments.length === 1) {
- if (Array.isArray(arg0)) {
- this.x = arg0[0];
- this.y = arg0[1];
- this.width = arg0[2];
- this.height = arg0[3];
- read = 1;
- } else if (arg0.x !== undefined || arg0.width !== undefined) {
- this.x = arg0.x || 0;
- this.y = arg0.y || 0;
- this.width = arg0.width || 0;
- this.height = arg0.height || 0;
- read = 1;
- } else if (arg0.from === undefined && arg0.to === undefined) {
- this.x = this.y = this.width = this.height = 0;
- this._set(arg0);
- read = 1;
- }
- }
- if (!read) {
- var point = Point.readNamed(arguments, 'from'),
- next = Base.peek(arguments);
- this.x = point.x;
- this.y = point.y;
- if (next && next.x !== undefined || Base.hasNamed(arguments, 'to')) {
- var to = Point.readNamed(arguments, 'to');
- this.width = to.x - point.x;
- this.height = to.y - point.y;
- if (this.width < 0) {
- this.x = to.x;
- this.width = -this.width;
- }
- if (this.height < 0) {
- this.y = to.y;
- this.height = -this.height;
- }
- } else {
- var size = Size.read(arguments);
- this.width = size.width;
- this.height = size.height;
- }
- read = arguments._index;
- }
- if (this.__read)
- this.__read = read;
- },
-
- set: function(x, y, width, height) {
- this.x = x;
- this.y = y;
- this.width = width;
- this.height = height;
- return this;
- },
-
- clone: function() {
- return new Rectangle(this.x, this.y, this.width, this.height);
- },
-
- equals: function(rect) {
- if (Base.isPlainValue(rect))
- rect = Rectangle.read(arguments);
- return rect === this
- || rect && this.x === rect.x && this.y === rect.y
- && this.width === rect.width && this.height === rect.height
- || false;
- },
-
- toString: function() {
- var f = Formatter.instance;
- return '{ x: ' + f.number(this.x)
- + ', y: ' + f.number(this.y)
- + ', width: ' + f.number(this.width)
- + ', height: ' + f.number(this.height)
- + ' }';
- },
-
- _serialize: function(options) {
- var f = options.formatter;
- return [f.number(this.x),
- f.number(this.y),
- f.number(this.width),
- f.number(this.height)];
- },
-
- getPoint: function() {
- return new (arguments[0] ? Point : LinkedPoint)
- (this.x, this.y, this, 'setPoint');
- },
-
- setPoint: function(point) {
- point = Point.read(arguments);
- this.x = point.x;
- this.y = point.y;
- },
-
- getSize: function() {
- return new (arguments[0] ? Size : LinkedSize)
- (this.width, this.height, this, 'setSize');
- },
-
- setSize: function(size) {
- size = Size.read(arguments);
- if (this._fixX)
- this.x += (this.width - size.width) * this._fixX;
- if (this._fixY)
- this.y += (this.height - size.height) * this._fixY;
- this.width = size.width;
- this.height = size.height;
- this._fixW = 1;
- this._fixH = 1;
- },
-
- getLeft: function() {
- return this.x;
- },
-
- setLeft: function(left) {
- if (!this._fixW)
- this.width -= left - this.x;
- this.x = left;
- this._fixX = 0;
- },
-
- getTop: function() {
- return this.y;
- },
-
- setTop: function(top) {
- if (!this._fixH)
- this.height -= top - this.y;
- this.y = top;
- this._fixY = 0;
- },
-
- getRight: function() {
- return this.x + this.width;
- },
-
- setRight: function(right) {
- if (this._fixX !== undefined && this._fixX !== 1)
- this._fixW = 0;
- if (this._fixW)
- this.x = right - this.width;
- else
- this.width = right - this.x;
- this._fixX = 1;
- },
-
- getBottom: function() {
- return this.y + this.height;
- },
-
- setBottom: function(bottom) {
- if (this._fixY !== undefined && this._fixY !== 1)
- this._fixH = 0;
- if (this._fixH)
- this.y = bottom - this.height;
- else
- this.height = bottom - this.y;
- this._fixY = 1;
- },
-
- getCenterX: function() {
- return this.x + this.width * 0.5;
- },
-
- setCenterX: function(x) {
- this.x = x - this.width * 0.5;
- this._fixX = 0.5;
- },
-
- getCenterY: function() {
- return this.y + this.height * 0.5;
- },
-
- setCenterY: function(y) {
- this.y = y - this.height * 0.5;
- this._fixY = 0.5;
- },
-
- getCenter: function() {
- return new (arguments[0] ? Point : LinkedPoint)
- (this.getCenterX(), this.getCenterY(), this, 'setCenter');
- },
-
- setCenter: function(point) {
- point = Point.read(arguments);
- this.setCenterX(point.x);
- this.setCenterY(point.y);
- return this;
- },
-
- isEmpty: function() {
- return this.width == 0 || this.height == 0;
- },
-
- contains: function(arg) {
- return arg && arg.width !== undefined
- || (Array.isArray(arg) ? arg : arguments).length == 4
- ? this._containsRectangle(Rectangle.read(arguments))
- : this._containsPoint(Point.read(arguments));
- },
-
- _containsPoint: function(point) {
- var x = point.x,
- y = point.y;
- return x >= this.x && y >= this.y
- && x <= this.x + this.width
- && y <= this.y + this.height;
- },
-
- _containsRectangle: function(rect) {
- var x = rect.x,
- y = rect.y;
- return x >= this.x && y >= this.y
- && x + rect.width <= this.x + this.width
- && y + rect.height <= this.y + this.height;
- },
-
- intersects: function(rect) {
- rect = Rectangle.read(arguments);
- return rect.x + rect.width > this.x
- && rect.y + rect.height > this.y
- && rect.x < this.x + this.width
- && rect.y < this.y + this.height;
- },
-
- touches: function(rect) {
- rect = Rectangle.read(arguments);
- return rect.x + rect.width >= this.x
- && rect.y + rect.height >= this.y
- && rect.x <= this.x + this.width
- && rect.y <= this.y + this.height;
- },
-
- intersect: function(rect) {
- rect = Rectangle.read(arguments);
- var x1 = Math.max(this.x, rect.x),
- y1 = Math.max(this.y, rect.y),
- x2 = Math.min(this.x + this.width, rect.x + rect.width),
- y2 = Math.min(this.y + this.height, rect.y + rect.height);
- return new Rectangle(x1, y1, x2 - x1, y2 - y1);
- },
-
- unite: function(rect) {
- rect = Rectangle.read(arguments);
- var x1 = Math.min(this.x, rect.x),
- y1 = Math.min(this.y, rect.y),
- x2 = Math.max(this.x + this.width, rect.x + rect.width),
- y2 = Math.max(this.y + this.height, rect.y + rect.height);
- return new Rectangle(x1, y1, x2 - x1, y2 - y1);
- },
-
- include: function(point) {
- point = Point.read(arguments);
- var x1 = Math.min(this.x, point.x),
- y1 = Math.min(this.y, point.y),
- x2 = Math.max(this.x + this.width, point.x),
- y2 = Math.max(this.y + this.height, point.y);
- return new Rectangle(x1, y1, x2 - x1, y2 - y1);
- },
-
- expand: function(hor, ver) {
- if (ver === undefined)
- ver = hor;
- return new Rectangle(this.x - hor / 2, this.y - ver / 2,
- this.width + hor, this.height + ver);
- },
-
- scale: function(hor, ver) {
- return this.expand(this.width * hor - this.width,
- this.height * (ver === undefined ? hor : ver) - this.height);
- }
-}, new function() {
- return Base.each([
- ['Top', 'Left'], ['Top', 'Right'],
- ['Bottom', 'Left'], ['Bottom', 'Right'],
- ['Left', 'Center'], ['Top', 'Center'],
- ['Right', 'Center'], ['Bottom', 'Center']
- ],
- function(parts, index) {
- var part = parts.join('');
- var xFirst = /^[RL]/.test(part);
- if (index >= 4)
- parts[1] += xFirst ? 'Y' : 'X';
- var x = parts[xFirst ? 0 : 1],
- y = parts[xFirst ? 1 : 0],
- getX = 'get' + x,
- getY = 'get' + y,
- setX = 'set' + x,
- setY = 'set' + y,
- get = 'get' + part,
- set = 'set' + part;
- this[get] = function() {
- return new (arguments[0] ? Point : LinkedPoint)
- (this[getX](), this[getY](), this, set);
- };
- this[set] = function(point) {
- point = Point.read(arguments);
- this[setX](point.x);
- this[setY](point.y);
- };
- }, {});
-});
-
-var LinkedRectangle = Rectangle.extend({
- initialize: function Rectangle(x, y, width, height, owner, setter) {
- this.set(x, y, width, height, true);
- this._owner = owner;
- this._setter = setter;
- },
-
- set: function(x, y, width, height, _dontNotify) {
- this._x = x;
- this._y = y;
- this._width = width;
- this._height = height;
- if (!_dontNotify)
- this._owner[this._setter](this);
- return this;
- }
-}, new function() {
- var proto = Rectangle.prototype;
-
- return Base.each(['x', 'y', 'width', 'height'], function(key) {
- var part = Base.capitalize(key);
- var internal = '_' + key;
- this['get' + part] = function() {
- return this[internal];
- };
-
- this['set' + part] = function(value) {
- this[internal] = value;
- if (!this._dontNotify)
- this._owner[this._setter](this);
- };
- }, Base.each(['Point', 'Size', 'Center',
- 'Left', 'Top', 'Right', 'Bottom', 'CenterX', 'CenterY',
- 'TopLeft', 'TopRight', 'BottomLeft', 'BottomRight',
- 'LeftCenter', 'TopCenter', 'RightCenter', 'BottomCenter'],
- function(key) {
- var name = 'set' + key;
- this[name] = function() {
- this._dontNotify = true;
- proto[name].apply(this, arguments);
- delete this._dontNotify;
- this._owner[this._setter](this);
- };
- }, {
- isSelected: function() {
- return this._owner._boundsSelected;
- },
-
- setSelected: function(selected) {
- var owner = this._owner;
- if (owner.setSelected) {
- owner._boundsSelected = selected;
- owner.setSelected(selected || owner._selectedSegmentState > 0);
- }
- }
- })
- );
-});
-
-var Matrix = Base.extend({
- _class: 'Matrix',
-
- initialize: function Matrix(arg) {
- var count = arguments.length,
- ok = true;
- if (count === 6) {
- this.set.apply(this, arguments);
- } else if (count === 1) {
- if (arg instanceof Matrix) {
- this.set(arg._a, arg._c, arg._b, arg._d, arg._tx, arg._ty);
- } else if (Array.isArray(arg)) {
- this.set.apply(this, arg);
- } else {
- ok = false;
- }
- } else if (count === 0) {
- this.reset();
- } else {
- ok = false;
- }
- if (!ok)
- throw new Error('Unsupported matrix parameters');
- },
-
- set: function(a, c, b, d, tx, ty, _dontNotify) {
- this._a = a;
- this._c = c;
- this._b = b;
- this._d = d;
- this._tx = tx;
- this._ty = ty;
- if (!_dontNotify)
- this._changed();
- return this;
- },
-
- _serialize: function(options) {
- return Base.serialize(this.getValues(), options);
- },
-
- _changed: function() {
- if (this._owner)
- this._owner._changed(5);
- },
-
- clone: function() {
- return new Matrix(this._a, this._c, this._b, this._d,
- this._tx, this._ty);
- },
-
- equals: function(mx) {
- return mx === this || mx && this._a === mx._a && this._b === mx._b
- && this._c === mx._c && this._d === mx._d
- && this._tx === mx._tx && this._ty === mx._ty
- || false;
- },
-
- toString: function() {
- var f = Formatter.instance;
- return '[[' + [f.number(this._a), f.number(this._b),
- f.number(this._tx)].join(', ') + '], ['
- + [f.number(this._c), f.number(this._d),
- f.number(this._ty)].join(', ') + ']]';
- },
-
- reset: function() {
- this._a = this._d = 1;
- this._c = this._b = this._tx = this._ty = 0;
- this._changed();
- return this;
- },
-
- scale: function() {
- var scale = Point.read(arguments),
- center = Point.read(arguments, 0, 0, { readNull: true });
- if (center)
- this.translate(center);
- this._a *= scale.x;
- this._c *= scale.x;
- this._b *= scale.y;
- this._d *= scale.y;
- if (center)
- this.translate(center.negate());
- this._changed();
- return this;
- },
-
- translate: function(point) {
- point = Point.read(arguments);
- var x = point.x,
- y = point.y;
- this._tx += x * this._a + y * this._b;
- this._ty += x * this._c + y * this._d;
- this._changed();
- return this;
- },
-
- rotate: function(angle, center) {
- center = Point.read(arguments, 1);
- angle = angle * Math.PI / 180;
- var x = center.x,
- y = center.y,
- cos = Math.cos(angle),
- sin = Math.sin(angle),
- tx = x - x * cos + y * sin,
- ty = y - x * sin - y * cos,
- a = this._a,
- b = this._b,
- c = this._c,
- d = this._d;
- this._a = cos * a + sin * b;
- this._b = -sin * a + cos * b;
- this._c = cos * c + sin * d;
- this._d = -sin * c + cos * d;
- this._tx += tx * a + ty * b;
- this._ty += tx * c + ty * d;
- this._changed();
- return this;
- },
-
- shear: function() {
- var point = Point.read(arguments),
- center = Point.read(arguments, 0, 0, { readNull: true });
- if (center)
- this.translate(center);
- var a = this._a,
- c = this._c;
- this._a += point.y * this._b;
- this._c += point.y * this._d;
- this._b += point.x * a;
- this._d += point.x * c;
- if (center)
- this.translate(center.negate());
- this._changed();
- return this;
- },
-
- concatenate: function(mx) {
- var a = this._a,
- b = this._b,
- c = this._c,
- d = this._d;
- this._a = mx._a * a + mx._c * b;
- this._b = mx._b * a + mx._d * b;
- this._c = mx._a * c + mx._c * d;
- this._d = mx._b * c + mx._d * d;
- this._tx += mx._tx * a + mx._ty * b;
- this._ty += mx._tx * c + mx._ty * d;
- this._changed();
- return this;
- },
-
- preConcatenate: function(mx) {
- var a = this._a,
- b = this._b,
- c = this._c,
- d = this._d,
- tx = this._tx,
- ty = this._ty;
- this._a = mx._a * a + mx._b * c;
- this._b = mx._a * b + mx._b * d;
- this._c = mx._c * a + mx._d * c;
- this._d = mx._c * b + mx._d * d;
- this._tx = mx._a * tx + mx._b * ty + mx._tx;
- this._ty = mx._c * tx + mx._d * ty + mx._ty;
- this._changed();
- return this;
- },
-
- isIdentity: function() {
- return this._a === 1 && this._c === 0 && this._b === 0 && this._d === 1
- && this._tx === 0 && this._ty === 0;
- },
-
- isInvertible: function() {
- return !!this._getDeterminant();
- },
-
- isSingular: function() {
- return !this._getDeterminant();
- },
-
- transform: function( src, srcOffset, dst, dstOffset, count) {
- return arguments.length < 5
- ? this._transformPoint(Point.read(arguments))
- : this._transformCoordinates(src, srcOffset, dst, dstOffset, count);
- },
-
- _transformPoint: function(point, dest, _dontNotify) {
- var x = point.x,
- y = point.y;
- if (!dest)
- dest = new Point();
- return dest.set(
- x * this._a + y * this._b + this._tx,
- x * this._c + y * this._d + this._ty,
- _dontNotify
- );
- },
-
- _transformCoordinates: function(src, srcOffset, dst, dstOffset, count) {
- var i = srcOffset,
- j = dstOffset,
- max = i + 2 * count;
- while (i < max) {
- var x = src[i++],
- y = src[i++];
- dst[j++] = x * this._a + y * this._b + this._tx;
- dst[j++] = x * this._c + y * this._d + this._ty;
- }
- return dst;
- },
-
- _transformCorners: function(rect) {
- var x1 = rect.x,
- y1 = rect.y,
- x2 = x1 + rect.width,
- y2 = y1 + rect.height,
- coords = [ x1, y1, x2, y1, x2, y2, x1, y2 ];
- return this._transformCoordinates(coords, 0, coords, 0, 4);
- },
-
- _transformBounds: function(bounds, dest, _dontNotify) {
- var coords = this._transformCorners(bounds),
- min = coords.slice(0, 2),
- max = coords.slice();
- for (var i = 2; i < 8; i++) {
- var val = coords[i],
- j = i & 1;
- if (val < min[j])
- min[j] = val;
- else if (val > max[j])
- max[j] = val;
- }
- if (!dest)
- dest = new Rectangle();
- return dest.set(min[0], min[1], max[0] - min[0], max[1] - min[1],
- _dontNotify);
- },
-
- inverseTransform: function() {
- return this._inverseTransform(Point.read(arguments));
- },
-
- _getDeterminant: function() {
- var det = this._a * this._d - this._b * this._c;
- return isFinite(det) && !Numerical.isZero(det)
- && isFinite(this._tx) && isFinite(this._ty)
- ? det : null;
- },
-
- _inverseTransform: function(point, dest, _dontNotify) {
- var det = this._getDeterminant();
- if (!det)
- return null;
- var x = point.x - this._tx,
- y = point.y - this._ty;
- if (!dest)
- dest = new Point();
- return dest.set(
- (x * this._d - y * this._b) / det,
- (y * this._a - x * this._c) / det,
- _dontNotify
- );
- },
-
- decompose: function() {
- var a = this._a, b = this._b, c = this._c, d = this._d;
- if (Numerical.isZero(a * d - b * c))
- return null;
-
- var scaleX = Math.sqrt(a * a + b * b);
- a /= scaleX;
- b /= scaleX;
-
- var shear = a * c + b * d;
- c -= a * shear;
- d -= b * shear;
-
- var scaleY = Math.sqrt(c * c + d * d);
- c /= scaleY;
- d /= scaleY;
- shear /= scaleY;
-
- if (a * d < b * c) {
- a = -a;
- b = -b;
- shear = -shear;
- scaleX = -scaleX;
- }
-
- return {
- translation: this.getTranslation(),
- scaling: new Point(scaleX, scaleY),
- rotation: -Math.atan2(b, a) * 180 / Math.PI,
- shearing: shear
- };
- },
-
- getValues: function() {
- return [ this._a, this._c, this._b, this._d, this._tx, this._ty ];
- },
-
- getTranslation: function() {
- return new Point(this._tx, this._ty);
- },
-
- setTranslation: function() {
- var point = Point.read(arguments);
- this._tx = point.x;
- this._ty = point.y;
- this._changed();
- },
-
- getScaling: function() {
- return (this.decompose() || {}).scaling;
- },
-
- setScaling: function() {
- var scaling = this.getScaling();
- if (scaling != null) {
- var scale = Point.read(arguments);
- (this._owner || this).scale(
- scale.x / scaling.x, scale.y / scaling.y);
- }
- },
-
- getRotation: function() {
- return (this.decompose() || {}).rotation;
- },
-
- setRotation: function(angle) {
- var rotation = this.getRotation();
- if (rotation != null)
- (this._owner || this).rotate(angle - rotation);
- },
-
- inverted: function() {
- var det = this._getDeterminant();
- return det && new Matrix(
- this._d / det,
- -this._c / det,
- -this._b / det,
- this._a / det,
- (this._b * this._ty - this._d * this._tx) / det,
- (this._c * this._tx - this._a * this._ty) / det);
- },
-
- shiftless: function() {
- return new Matrix(this._a, this._c, this._b, this._d, 0, 0);
- },
-
- applyToContext: function(ctx) {
- ctx.transform(this._a, this._c, this._b, this._d, this._tx, this._ty);
- }
-}, new function() {
- return Base.each({
- scaleX: '_a',
- scaleY: '_d',
- translateX: '_tx',
- translateY: '_ty',
- shearX: '_b',
- shearY: '_c'
- }, function(prop, name) {
- name = Base.capitalize(name);
- this['get' + name] = function() {
- return this[prop];
- };
- this['set' + name] = function(value) {
- this[prop] = value;
- this._changed();
- };
- }, {});
-});
-
-var Line = Base.extend({
- _class: 'Line',
-
- initialize: function Line(arg0, arg1, arg2, arg3, arg4) {
- var asVector = false;
- if (arguments.length >= 4) {
- this._px = arg0;
- this._py = arg1;
- this._vx = arg2;
- this._vy = arg3;
- asVector = arg4;
- } else {
- this._px = arg0.x;
- this._py = arg0.y;
- this._vx = arg1.x;
- this._vy = arg1.y;
- asVector = arg2;
- }
- if (!asVector) {
- this._vx -= this._px;
- this._vy -= this._py;
- }
- },
-
- getPoint: function() {
- return new Point(this._px, this._py);
- },
-
- getVector: function() {
- return new Point(this._vx, this._vy);
- },
-
- getLength: function() {
- return this.getVector().getLength();
- },
-
- intersect: function(line, isInfinite) {
- return Line.intersect(
- this._px, this._py, this._vx, this._vy,
- line._px, line._py, line._vx, line._vy,
- true, isInfinite);
- },
-
- getSide: function(point) {
- return Line.getSide(
- this._px, this._py, this._vx, this._vy,
- point.x, point.y, true);
- },
-
- getDistance: function(point) {
- return Math.abs(Line.getSignedDistance(
- this._px, this._py, this._vx, this._vy,
- point.x, point.y, true));
- },
-
- statics: {
- intersect: function(apx, apy, avx, avy, bpx, bpy, bvx, bvy, asVector,
- isInfinite) {
- if (!asVector) {
- avx -= apx;
- avy -= apy;
- bvx -= bpx;
- bvy -= bpy;
- }
- var cross = bvy * avx - bvx * avy;
- if (!Numerical.isZero(cross)) {
- var dx = apx - bpx,
- dy = apy - bpy,
- ta = (bvx * dy - bvy * dx) / cross,
- tb = (avx * dy - avy * dx) / cross;
- if ((isInfinite || 0 <= ta && ta <= 1)
- && (isInfinite || 0 <= tb && tb <= 1))
- return new Point(
- apx + ta * avx,
- apy + ta * avy);
- }
- },
-
- getSide: function(px, py, vx, vy, x, y, asVector) {
- if (!asVector) {
- vx -= px;
- vy -= py;
- }
- var v2x = x - px,
- v2y = y - py,
- ccw = v2x * vy - v2y * vx;
- if (ccw === 0) {
- ccw = v2x * vx + v2y * vy;
- if (ccw > 0) {
- v2x -= vx;
- v2y -= vy;
- ccw = v2x * vx + v2y * vy;
- if (ccw < 0)
- ccw = 0;
- }
- }
- return ccw < 0 ? -1 : ccw > 0 ? 1 : 0;
- },
-
- getSignedDistance: function(px, py, vx, vy, x, y, asVector) {
- if (!asVector) {
- vx -= px;
- vy -= py;
- }
- var m = vy / vx,
- b = py - m * px;
- return (y - (m * x) - b) / Math.sqrt(m * m + 1);
- }
- }
-});
-
-var Project = PaperScopeItem.extend({
- _class: 'Project',
- _list: 'projects',
- _reference: 'project',
-
- initialize: function Project(view) {
- PaperScopeItem.call(this, true);
- this.layers = [];
- this.symbols = [];
- this._currentStyle = new Style();
- this.activeLayer = new Layer();
- if (view)
- this.view = view instanceof View ? view : View.create(view);
- this._selectedItems = {};
- this._selectedItemCount = 0;
- this._drawCount = 0;
- this.options = {};
- },
-
- _serialize: function(options, dictionary) {
- return Base.serialize(this.layers, options, true, dictionary);
- },
-
- clear: function() {
- for (var i = this.layers.length - 1; i >= 0; i--)
- this.layers[i].remove();
- this.symbols = [];
- },
-
- isEmpty: function() {
- return this.layers.length <= 1
- && (!this.activeLayer || this.activeLayer.isEmpty());
- },
-
- remove: function remove() {
- if (!remove.base.call(this))
- return false;
- if (this.view)
- this.view.remove();
- return true;
- },
-
- getCurrentStyle: function() {
- return this._currentStyle;
- },
-
- setCurrentStyle: function(style) {
- this._currentStyle.initialize(style);
- },
-
- getIndex: function() {
- return this._index;
- },
-
- addChild: function(child) {
- if (child instanceof Layer) {
- Base.splice(this.layers, [child]);
- if (!this.activeLayer)
- this.activeLayer = child;
- } else if (child instanceof Item) {
- (this.activeLayer
- || this.addChild(new Layer({ insert: false }))).addChild(child);
- } else {
- child = null;
- }
- return child;
- },
-
- getSelectedItems: function() {
- var items = [];
- for (var id in this._selectedItems) {
- var item = this._selectedItems[id];
- if (item.isInserted())
- items.push(item);
- }
- return items;
- },
-
- _updateSelection: function(item) {
- var id = item._id,
- selectedItems = this._selectedItems;
- if (item._selected) {
- if (selectedItems[id] !== item) {
- this._selectedItemCount++;
- selectedItems[id] = item;
- }
- } else if (selectedItems[id] === item) {
- this._selectedItemCount--;
- delete selectedItems[id];
- }
- },
-
- selectAll: function() {
- var layers = this.layers;
- for (var i = 0, l = layers.length; i < l; i++)
- layers[i].setFullySelected(true);
- },
-
- deselectAll: function() {
- var selectedItems = this._selectedItems;
- for (var i in selectedItems)
- selectedItems[i].setFullySelected(false);
- },
-
- hitTest: function(point, options) {
- point = Point.read(arguments);
- options = HitResult.getOptions(Base.read(arguments));
- for (var i = this.layers.length - 1; i >= 0; i--) {
- var res = this.layers[i].hitTest(point, options);
- if (res) return res;
- }
- return null;
- }
-}, new function() {
- function getItems(project, match, list) {
- var layers = project.layers,
- items = list && [];
- for (var i = 0, l = layers.length; i < l; i++) {
- var res = layers[i][list ? 'getItems' : 'getItem'](match);
- if (list) {
- items.push.apply(items, res);
- } else if (res)
- return res;
- }
- return list ? items : null;
- }
-
- return {
- getItems: function(match) {
- return getItems(this, match, true);
- },
-
- getItem: function(match) {
- return getItems(this, match, false);
- }
- };
-}, {
-
- importJSON: function(json) {
- this.activate();
- var layer = this.activeLayer;
- return Base.importJSON(json, layer && layer.isEmpty() && layer);
- },
-
- draw: function(ctx, matrix, ratio) {
- this._drawCount++;
- ctx.save();
- matrix.applyToContext(ctx);
- var param = new Base({
- offset: new Point(0, 0),
- ratio: ratio,
- transforms: [matrix],
- trackTransforms: true
- });
- for (var i = 0, l = this.layers.length; i < l; i++)
- this.layers[i].draw(ctx, param);
- ctx.restore();
-
- if (this._selectedItemCount > 0) {
- ctx.save();
- ctx.strokeWidth = 1;
- for (var id in this._selectedItems) {
- var item = this._selectedItems[id];
- if (item._drawCount === this._drawCount
- && (item._drawSelected || item._boundsSelected)) {
- var color = item.getSelectedColor()
- || item.getLayer().getSelectedColor();
- ctx.strokeStyle = ctx.fillStyle = color
- ? color.toCanvasStyle(ctx) : '#009dec';
- var mx = item._globalMatrix;
- if (item._drawSelected)
- item._drawSelected(ctx, mx);
- if (item._boundsSelected) {
- var coords = mx._transformCorners(
- item._getBounds('getBounds'));
- ctx.beginPath();
- for (var i = 0; i < 8; i++)
- ctx[i === 0 ? 'moveTo' : 'lineTo'](
- coords[i], coords[++i]);
- ctx.closePath();
- ctx.stroke();
- for (var i = 0; i < 8; i++) {
- ctx.beginPath();
- ctx.rect(coords[i] - 2, coords[++i] - 2, 4, 4);
- ctx.fill();
- }
- }
- }
- }
- ctx.restore();
- }
- }
-});
-
-var Symbol = Base.extend({
- _class: 'Symbol',
-
- initialize: function Symbol(item, dontCenter) {
- this._id = Symbol._id = (Symbol._id || 0) + 1;
- this.project = paper.project;
- this.project.symbols.push(this);
- if (item)
- this.setDefinition(item, dontCenter);
- this._instances = {};
- },
-
- _serialize: function(options, dictionary) {
- return dictionary.add(this, function() {
- return Base.serialize([this._class, this._definition],
- options, false, dictionary);
- });
- },
-
- _changed: function(flags) {
- Base.each(this._instances, function(item) {
- item._changed(flags);
- });
- },
-
- getDefinition: function() {
- return this._definition;
- },
-
- setDefinition: function(item ) {
- if (item._parentSymbol)
- item = item.clone();
- if (this._definition)
- delete this._definition._parentSymbol;
- this._definition = item;
- item.remove();
- item.setSelected(false);
- if (!arguments[1])
- item.setPosition(new Point());
- item._parentSymbol = this;
- this._changed(5);
- },
-
- place: function(position) {
- return new PlacedSymbol(this, position);
- },
-
- clone: function() {
- return new Symbol(this._definition.clone(false));
- }
-});
-
-var Item = Base.extend(Callback, {
- statics: {
- extend: function extend(src) {
- if (src._serializeFields)
- src._serializeFields = new Base(
- this.prototype._serializeFields, src._serializeFields);
- var res = extend.base.apply(this, arguments),
- proto = res.prototype,
- name = proto._class;
- if (name)
- proto._type = Base.hyphenate(name);
- return res;
- }
- },
-
- _class: 'Item',
- _transformContent: true,
- _boundsSelected: false,
- _serializeFields: {
- name: null,
- matrix: new Matrix(),
- locked: false,
- visible: true,
- blendMode: 'normal',
- opacity: 1,
- guide: false,
- selected: false,
- clipMask: false,
- data: {}
- },
-
- initialize: function Item() {
- },
-
- _initialize: function(props, point) {
- this._id = Item._id = (Item._id || 0) + 1;
- if (!this._project) {
- var project = paper.project;
- if (props && props.insert === false) {
- this._setProject(project);
- } else {
- (project.activeLayer || new Layer()).addChild(this);
- }
- }
- this._style = new Style(this._project._currentStyle, this);
- var matrix = this._matrix = new Matrix();
- if (point)
- matrix.translate(point);
- matrix._owner = this;
- return props ? this._set(props, { insert: true }) : true;
- },
-
- _events: new function() {
-
- var mouseFlags = {
- mousedown: {
- mousedown: 1,
- mousedrag: 1,
- click: 1,
- doubleclick: 1
- },
- mouseup: {
- mouseup: 1,
- mousedrag: 1,
- click: 1,
- doubleclick: 1
- },
- mousemove: {
- mousedrag: 1,
- mousemove: 1,
- mouseenter: 1,
- mouseleave: 1
- }
- };
-
- var mouseEvent = {
- install: function(type) {
- var counters = this._project.view._eventCounters;
- if (counters) {
- for (var key in mouseFlags) {
- counters[key] = (counters[key] || 0)
- + (mouseFlags[key][type] || 0);
- }
- }
- },
- uninstall: function(type) {
- var counters = this._project.view._eventCounters;
- if (counters) {
- for (var key in mouseFlags)
- counters[key] -= mouseFlags[key][type] || 0;
- }
- }
- };
-
- return Base.each(['onMouseDown', 'onMouseUp', 'onMouseDrag', 'onClick',
- 'onDoubleClick', 'onMouseMove', 'onMouseEnter', 'onMouseLeave'],
- function(name) {
- this[name] = mouseEvent;
- }, {
- onFrame: {
- install: function() {
- this._animateItem(true);
- },
- uninstall: function() {
- this._animateItem(false);
- }
- },
-
- onLoad: {}
- }
- );
- },
-
- _animateItem: function(animate) {
- this._project.view._animateItem(this, animate);
- },
-
- _serialize: function(options, dictionary) {
- var props = {},
- that = this;
-
- function serialize(fields) {
- for (var key in fields) {
- var value = that[key];
- if (!Base.equals(value, key === 'leading'
- ? fields.fontSize * 1.2 : fields[key])) {
- props[key] = Base.serialize(value, options,
- key !== 'data', dictionary);
- }
- }
- }
-
- serialize(this._serializeFields);
- if (!(this instanceof Group))
- serialize(this._style._defaults);
- return [ this._class, props ];
- },
-
- _changed: function(flags) {
- var parent = this._parent,
- project = this._project,
- symbol = this._parentSymbol;
- this._drawCount = null;
- if (flags & 4) {
- delete this._bounds;
- delete this._position;
- }
- if (parent && (flags
- & (4 | 8))) {
- parent._clearBoundsCache();
- }
- if (flags & 2) {
- this._clearBoundsCache();
- }
- if (project) {
- if (flags & 1) {
- project._needsRedraw = true;
- }
- if (project._changes) {
- var entry = project._changesById[this._id];
- if (entry) {
- entry.flags |= flags;
- } else {
- entry = { item: this, flags: flags };
- project._changesById[this._id] = entry;
- project._changes.push(entry);
- }
- }
- }
- if (symbol)
- symbol._changed(flags);
- },
-
- set: function(props) {
- if (props)
- this._set(props);
- return this;
- },
-
- getId: function() {
- return this._id;
- },
-
- getType: function() {
- return this._type;
- },
-
- getName: function() {
- return this._name;
- },
-
- setName: function(name, unique) {
-
- if (this._name)
- this._removeNamed();
- if (name === (+name) + '')
- throw new Error(
- 'Names consisting only of numbers are not supported.');
- if (name && this._parent) {
- var children = this._parent._children,
- namedChildren = this._parent._namedChildren,
- orig = name,
- i = 1;
- while (unique && children[name])
- name = orig + ' ' + (i++);
- (namedChildren[name] = namedChildren[name] || []).push(this);
- children[name] = this;
- }
- this._name = name || undefined;
- this._changed(32);
- },
-
- getStyle: function() {
- return this._style;
- },
-
- setStyle: function(style) {
- this.getStyle().set(style);
- },
-
- hasFill: function() {
- return this.getStyle().hasFill();
- },
-
- hasStroke: function() {
- return this.getStyle().hasStroke();
- },
-
- hasShadow: function() {
- return this.getStyle().hasShadow();
- }
-}, Base.each(['locked', 'visible', 'blendMode', 'opacity', 'guide'],
- function(name) {
- var part = Base.capitalize(name),
- name = '_' + name;
- this['get' + part] = function() {
- return this[name];
- };
- this['set' + part] = function(value) {
- if (value != this[name]) {
- this[name] = value;
- this._changed(name === '_locked'
- ? 32 : 33);
- }
- };
-}, {}), {
-
- _locked: false,
-
- _visible: true,
-
- _blendMode: 'normal',
-
- _opacity: 1,
-
- _guide: false,
-
- isSelected: function() {
- if (this._children) {
- for (var i = 0, l = this._children.length; i < l; i++)
- if (this._children[i].isSelected())
- return true;
- }
- return this._selected;
- },
-
- setSelected: function(selected ) {
- if (this._children && !arguments[1]) {
- for (var i = 0, l = this._children.length; i < l; i++)
- this._children[i].setSelected(selected);
- }
- if ((selected = !!selected) != this._selected) {
- this._selected = selected;
- this._project._updateSelection(this);
- this._changed(33);
- }
- },
-
- _selected: false,
-
- isFullySelected: function() {
- if (this._children && this._selected) {
- for (var i = 0, l = this._children.length; i < l; i++)
- if (!this._children[i].isFullySelected())
- return false;
- return true;
- }
- return this._selected;
- },
-
- setFullySelected: function(selected) {
- if (this._children) {
- for (var i = 0, l = this._children.length; i < l; i++)
- this._children[i].setFullySelected(selected);
- }
- this.setSelected(selected, true);
- },
-
- isClipMask: function() {
- return this._clipMask;
- },
-
- setClipMask: function(clipMask) {
- if (this._clipMask != (clipMask = !!clipMask)) {
- this._clipMask = clipMask;
- if (clipMask) {
- this.setFillColor(null);
- this.setStrokeColor(null);
- }
- this._changed(33);
- if (this._parent)
- this._parent._changed(256);
- }
- },
-
- _clipMask: false,
-
- getData: function() {
- if (!this._data)
- this._data = {};
- return this._data;
- },
-
- setData: function(data) {
- this._data = data;
- },
-
- getPosition: function() {
- var pos = this._position
- || (this._position = this.getBounds().getCenter(true));
- return new (arguments[0] ? Point : LinkedPoint)
- (pos.x, pos.y, this, 'setPosition');
- },
-
- setPosition: function() {
- this.translate(Point.read(arguments).subtract(this.getPosition(true)));
- }
-}, Base.each(['getBounds', 'getStrokeBounds', 'getHandleBounds', 'getRoughBounds'],
- function(name) {
- this[name] = function() {
- var getter = this._boundsGetter,
- bounds = this._getCachedBounds(typeof getter == 'string'
- ? getter : getter && getter[name] || name, arguments[0]);
- return name === 'getBounds'
- ? new LinkedRectangle(bounds.x, bounds.y, bounds.width,
- bounds.height, this, 'setBounds')
- : bounds;
- };
- },
-{
- _getCachedBounds: function(getter, matrix, cacheItem) {
- var cache = (!matrix || matrix.equals(this._matrix)) && getter;
- if (cacheItem && this._parent) {
- var id = cacheItem._id,
- ref = this._parent._boundsCache
- = this._parent._boundsCache || {
- ids: {},
- list: []
- };
- if (!ref.ids[id]) {
- ref.list.push(cacheItem);
- ref.ids[id] = cacheItem;
- }
- }
- if (cache && this._bounds && this._bounds[cache])
- return this._bounds[cache].clone();
- var identity = this._matrix.isIdentity();
- matrix = !matrix || matrix.isIdentity()
- ? identity ? null : this._matrix
- : identity ? matrix : matrix.clone().concatenate(this._matrix);
- var bounds = this._getBounds(getter, matrix, cache ? this : cacheItem);
- if (cache) {
- if (!this._bounds)
- this._bounds = {};
- this._bounds[cache] = bounds.clone();
- }
- return bounds;
- },
-
- _clearBoundsCache: function() {
- if (this._boundsCache) {
- for (var i = 0, list = this._boundsCache.list, l = list.length;
- i < l; i++) {
- var item = list[i];
- delete item._bounds;
- if (item != this && item._boundsCache)
- item._clearBoundsCache();
- }
- delete this._boundsCache;
- }
- },
-
- _getBounds: function(getter, matrix, cacheItem) {
- var children = this._children;
- if (!children || children.length == 0)
- return new Rectangle();
- var x1 = Infinity,
- x2 = -x1,
- y1 = x1,
- y2 = x2;
- for (var i = 0, l = children.length; i < l; i++) {
- var child = children[i];
- if (child._visible && !child.isEmpty()) {
- var rect = child._getCachedBounds(getter, matrix, cacheItem);
- x1 = Math.min(rect.x, x1);
- y1 = Math.min(rect.y, y1);
- x2 = Math.max(rect.x + rect.width, x2);
- y2 = Math.max(rect.y + rect.height, y2);
- }
- }
- return isFinite(x1)
- ? new Rectangle(x1, y1, x2 - x1, y2 - y1)
- : new Rectangle();
- },
-
- setBounds: function(rect) {
- rect = Rectangle.read(arguments);
- var bounds = this.getBounds(),
- matrix = new Matrix(),
- center = rect.getCenter();
- matrix.translate(center);
- if (rect.width != bounds.width || rect.height != bounds.height) {
- matrix.scale(
- bounds.width != 0 ? rect.width / bounds.width : 1,
- bounds.height != 0 ? rect.height / bounds.height : 1);
- }
- center = bounds.getCenter();
- matrix.translate(-center.x, -center.y);
- this.transform(matrix);
- }
-
-}), {
- getMatrix: function() {
- return this._matrix;
- },
-
- setMatrix: function(matrix) {
- this._matrix.initialize(matrix);
- if (this._transformContent)
- this.applyMatrix(true);
- this._changed(5);
- },
-
- getGlobalMatrix: function() {
- return this._drawCount === this._project._drawCount
- && this._globalMatrix || null;
- },
-
- getTransformContent: function() {
- return this._transformContent;
- },
-
- setTransformContent: function(transform) {
- this._transformContent = transform;
- if (transform)
- this.applyMatrix();
- },
-
- getProject: function() {
- return this._project;
- },
-
- _setProject: function(project) {
- if (this._project != project) {
- var hasOnFrame = this.responds('frame');
- if (hasOnFrame)
- this._animateItem(false);
- this._project = project;
- if (hasOnFrame)
- this._animateItem(true);
- if (this._children) {
- for (var i = 0, l = this._children.length; i < l; i++) {
- this._children[i]._setProject(project);
- }
- }
- }
- },
-
- getLayer: function() {
- var parent = this;
- while (parent = parent._parent) {
- if (parent instanceof Layer)
- return parent;
- }
- return null;
- },
-
- getParent: function() {
- return this._parent;
- },
-
- setParent: function(item) {
- return item.addChild(this);
- },
-
- getChildren: function() {
- return this._children;
- },
-
- setChildren: function(items) {
- this.removeChildren();
- this.addChildren(items);
- },
-
- getFirstChild: function() {
- return this._children && this._children[0] || null;
- },
-
- getLastChild: function() {
- return this._children && this._children[this._children.length - 1]
- || null;
- },
-
- getNextSibling: function() {
- return this._parent && this._parent._children[this._index + 1] || null;
- },
-
- getPreviousSibling: function() {
- return this._parent && this._parent._children[this._index - 1] || null;
- },
-
- getIndex: function() {
- return this._index;
- },
-
- isInserted: function() {
- return this._parent ? this._parent.isInserted() : false;
- },
-
- equals: function(item) {
- return item === this || item && this._class === item._class
- && this._style.equals(item._style)
- && this._matrix.equals(item._matrix)
- && this._locked === item._locked
- && this._visible === item._visible
- && this._blendMode === item._blendMode
- && this._opacity === item._opacity
- && this._clipMask === item._clipMask
- && this._guide === item._guide
- && this._equals(item)
- || false;
- },
-
- _equals: function(item) {
- return Base.equals(this._children, item._children);
- },
-
- clone: function(insert) {
- return this._clone(new this.constructor({ insert: false }), insert);
- },
-
- _clone: function(copy, insert) {
- copy.setStyle(this._style);
- if (this._children) {
- for (var i = 0, l = this._children.length; i < l; i++)
- copy.addChild(this._children[i].clone(false), true);
- }
- if (insert || insert === undefined)
- copy.insertAbove(this);
- var keys = ['_locked', '_visible', '_blendMode', '_opacity',
- '_clipMask', '_guide'];
- for (var i = 0, l = keys.length; i < l; i++) {
- var key = keys[i];
- if (this.hasOwnProperty(key))
- copy[key] = this[key];
- }
- copy._matrix.initialize(this._matrix);
- copy._data = this._data ? Base.clone(this._data) : null;
- copy.setSelected(this._selected);
- if (this._name)
- copy.setName(this._name, true);
- return copy;
- },
-
- copyTo: function(itemOrProject) {
- return itemOrProject.addChild(this.clone(false));
- },
-
- rasterize: function(resolution) {
- var bounds = this.getStrokeBounds(),
- scale = (resolution || 72) / 72,
- topLeft = bounds.getTopLeft().floor(),
- bottomRight = bounds.getBottomRight().ceil()
- size = new Size(bottomRight.subtract(topLeft)),
- canvas = CanvasProvider.getCanvas(size),
- ctx = canvas.getContext('2d'),
- matrix = new Matrix().scale(scale).translate(topLeft.negate());
- ctx.save();
- matrix.applyToContext(ctx);
- this.draw(ctx, new Base({ transforms: [matrix] }));
- ctx.restore();
- var raster = new Raster({
- canvas: canvas,
- insert: false
- });
- raster.setPosition(topLeft.add(size.divide(2)));
- raster.insertAbove(this);
- return raster;
- },
-
- contains: function() {
- return !!this._contains(
- this._matrix._inverseTransform(Point.read(arguments)));
- },
-
- _contains: function(point) {
- if (this._children) {
- for (var i = this._children.length - 1; i >= 0; i--) {
- if (this._children[i].contains(point))
- return true;
- }
- return false;
- }
- return point.isInside(this._getBounds('getBounds'));
- },
-
- hitTest: function(point, options) {
- point = Point.read(arguments);
- options = HitResult.getOptions(Base.read(arguments));
-
- if (this._locked || !this._visible || this._guide && !options.guides)
- return null;
-
- if (!this._children && !this.getRoughBounds()
- .expand(2 * options.tolerance)._containsPoint(point))
- return null;
- point = this._matrix._inverseTransform(point);
-
- var that = this,
- res;
- function checkBounds(type, part) {
- var pt = bounds['get' + part]();
- if (point.getDistance(pt) < options.tolerance)
- return new HitResult(type, that,
- { name: Base.hyphenate(part), point: pt });
- }
-
- if ((options.center || options.bounds) &&
- !(this instanceof Layer && !this._parent)) {
- var bounds = this._getBounds('getBounds');
- if (options.center)
- res = checkBounds('center', 'Center');
- if (!res && options.bounds) {
- var points = [
- 'TopLeft', 'TopRight', 'BottomLeft', 'BottomRight',
- 'LeftCenter', 'TopCenter', 'RightCenter', 'BottomCenter'
- ];
- for (var i = 0; i < 8 && !res; i++)
- res = checkBounds('bounds', points[i]);
- }
- }
-
- if ((res || (res = this._children || !(options.guides && !this._guide
- || options.selected && !this._selected)
- ? this._hitTest(point, options) : null))
- && res.point) {
- res.point = that._matrix.transform(res.point);
- }
- return res;
- },
-
- _hitTest: function(point, options) {
- var children = this._children;
- if (children) {
- for (var i = children.length - 1, res; i >= 0; i--)
- if (res = children[i].hitTest(point, options))
- return res;
- } else if (options.fill && this.hasFill() && this._contains(point)) {
- return new HitResult('fill', this);
- }
- },
-
- matches: function(match) {
- function matchObject(obj1, obj2) {
- for (var i in obj1) {
- if (obj1.hasOwnProperty(i)) {
- var val1 = obj1[i],
- val2 = obj2[i];
- if (Base.isPlainObject(val1) && Base.isPlainObject(val2)) {
- if (!matchObject(val1, val2))
- return false;
- } else if (!Base.equals(val1, val2)) {
- return false;
- }
- }
- }
- return true;
- }
- for (var key in match) {
- if (match.hasOwnProperty(key)) {
- var value = this[key],
- compare = match[key];
- if (compare instanceof RegExp) {
- if (!compare.test(value))
- return false;
- } else if (typeof compare === 'function') {
- if (!compare(value))
- return false;
- } else if (Base.isPlainObject(compare)) {
- if (!matchObject(compare, value))
- return false;
- } else if (!Base.equals(value, compare)) {
- return false;
- }
- }
- }
- return true;
- }
-}, new function() {
- function getItems(item, match, list) {
- var children = item._children,
- items = list && [];
- for (var i = 0, l = children && children.length; i < l; i++) {
- var child = children[i];
- if (child.matches(match)) {
- if (list) {
- items.push(child);
- } else {
- return child;
- }
- }
- var res = getItems(child, match, list);
- if (list) {
- items.push.apply(items, res);
- } else if (res) {
- return res;
- }
- }
- return list ? items : null;
- }
-
- return {
- getItems: function(match) {
- return getItems(this, match, true);
- },
-
- getItem: function(match) {
- return getItems(this, match, false);
- }
- };
-}, {
-
- importJSON: function(json) {
- var res = Base.importJSON(json, this);
- return res !== this
- ? this.addChild(res)
- : res;
- },
-
- addChild: function(item, _preserve) {
- return this.insertChild(undefined, item, _preserve);
- },
-
- insertChild: function(index, item, _preserve) {
- var res = this.insertChildren(index, [item], _preserve);
- return res && res[0];
- },
-
- addChildren: function(items, _preserve) {
- return this.insertChildren(this._children.length, items, _preserve);
- },
-
- insertChildren: function(index, items, _preserve, _type) {
- var children = this._children;
- if (children && items && items.length > 0) {
- items = Array.prototype.slice.apply(items);
- for (var i = items.length - 1; i >= 0; i--) {
- var item = items[i];
- if (_type && item._type !== _type)
- items.splice(i, 1);
- else
- item._remove(true);
- }
- Base.splice(children, items, index, 0);
- for (var i = 0, l = items.length; i < l; i++) {
- var item = items[i];
- item._parent = this;
- item._setProject(this._project);
- if (item._name)
- item.setName(item._name);
- }
- this._changed(7);
- } else {
- items = null;
- }
- return items;
- },
-
- _insert: function(above, item, _preserve) {
- if (!item._parent)
- return null;
- var index = item._index + (above ? 1 : 0);
- if (item._parent === this._parent && index > this._index)
- index--;
- return item._parent.insertChild(index, this, _preserve);
- },
-
- insertAbove: function(item, _preserve) {
- return this._insert(true, item, _preserve);
- },
-
- insertBelow: function(item, _preserve) {
- return this._insert(false, item, _preserve);
- },
-
- sendToBack: function() {
- return this._parent.insertChild(0, this);
- },
-
- bringToFront: function() {
- return this._parent.addChild(this);
- },
-
- appendTop: '#addChild',
-
- appendBottom: function(item) {
- return this.insertChild(0, item);
- },
-
- moveAbove: '#insertAbove',
-
- moveBelow: '#insertBelow',
-
- reduce: function() {
- if (this._children && this._children.length === 1) {
- var child = this._children[0];
- child.insertAbove(this);
- child.setStyle(this._style);
- this.remove();
- return child;
- }
- return this;
- },
-
- _removeNamed: function() {
- var children = this._parent._children,
- namedChildren = this._parent._namedChildren,
- name = this._name,
- namedArray = namedChildren[name],
- index = namedArray ? namedArray.indexOf(this) : -1;
- if (index == -1)
- return;
- if (children[name] == this)
- delete children[name];
- namedArray.splice(index, 1);
- if (namedArray.length) {
- children[name] = namedArray[namedArray.length - 1];
- } else {
- delete namedChildren[name];
- }
- },
-
- _remove: function(notify) {
- if (this._parent) {
- if (this._name)
- this._removeNamed();
- if (this._index != null)
- Base.splice(this._parent._children, null, this._index, 1);
- if (this.responds('frame'))
- this._animateItem(false);
- if (notify)
- this._parent._changed(7);
- this._parent = null;
- return true;
- }
- return false;
- },
-
- remove: function() {
- return this._remove(true);
- },
-
- removeChildren: function(from, to) {
- if (!this._children)
- return null;
- from = from || 0;
- to = Base.pick(to, this._children.length);
- var removed = Base.splice(this._children, null, from, to - from);
- for (var i = removed.length - 1; i >= 0; i--)
- removed[i]._remove(false);
- if (removed.length > 0)
- this._changed(7);
- return removed;
- },
-
- clear: '#removeChildren',
-
- reverseChildren: function() {
- if (this._children) {
- this._children.reverse();
- for (var i = 0, l = this._children.length; i < l; i++)
- this._children[i]._index = i;
- this._changed(7);
- }
- },
-
- isEmpty: function() {
- return !this._children || this._children.length == 0;
- },
-
- isEditable: function() {
- var item = this;
- while (item) {
- if (!item._visible || item._locked)
- return false;
- item = item._parent;
- }
- return true;
- },
-
- _getOrder: function(item) {
- function getList(item) {
- var list = [];
- do {
- list.unshift(item);
- } while (item = item._parent);
- return list;
- }
- var list1 = getList(this),
- list2 = getList(item);
- for (var i = 0, l = Math.min(list1.length, list2.length); i < l; i++) {
- if (list1[i] != list2[i]) {
- return list1[i]._index < list2[i]._index ? 1 : -1;
- }
- }
- return 0;
- },
-
- hasChildren: function() {
- return this._children && this._children.length > 0;
- },
-
- isAbove: function(item) {
- return this._getOrder(item) === -1;
- },
-
- isBelow: function(item) {
- return this._getOrder(item) === 1;
- },
-
- isParent: function(item) {
- return this._parent === item;
- },
-
- isChild: function(item) {
- return item && item._parent === this;
- },
-
- isDescendant: function(item) {
- var parent = this;
- while (parent = parent._parent) {
- if (parent == item)
- return true;
- }
- return false;
- },
-
- isAncestor: function(item) {
- return item ? item.isDescendant(this) : false;
- },
-
- isGroupedWith: function(item) {
- var parent = this._parent;
- while (parent) {
- if (parent._parent
- && /^(group|layer|compound-path)$/.test(parent._type)
- && item.isDescendant(parent))
- return true;
- parent = parent._parent;
- }
- return false;
- },
-
- scale: function(hor, ver , center) {
- if (arguments.length < 2 || typeof ver === 'object') {
- center = ver;
- ver = hor;
- }
- return this.transform(new Matrix().scale(hor, ver,
- center || this.getPosition(true)));
- },
-
- translate: function() {
- var mx = new Matrix();
- return this.transform(mx.translate.apply(mx, arguments));
- },
-
- rotate: function(angle, center) {
- return this.transform(new Matrix().rotate(angle,
- center || this.getPosition(true)));
- },
-
- shear: function(hor, ver, center) {
- if (arguments.length < 2 || typeof ver === 'object') {
- center = ver;
- ver = hor;
- }
- return this.transform(new Matrix().shear(hor, ver,
- center || this.getPosition(true)));
- },
-
- transform: function(matrix ) {
- var bounds = this._bounds,
- position = this._position;
- this._matrix.preConcatenate(matrix);
- if (this._transformContent || arguments[1])
- this.applyMatrix(true);
- this._changed(5);
- if (bounds && matrix.getRotation() % 90 === 0) {
- for (var key in bounds) {
- var rect = bounds[key];
- matrix._transformBounds(rect, rect);
- }
- var getter = this._boundsGetter,
- rect = bounds[getter && getter.getBounds || getter || 'getBounds'];
- if (rect)
- this._position = rect.getCenter(true);
- this._bounds = bounds;
- } else if (position) {
- this._position = matrix._transformPoint(position, position);
- }
- return this;
- },
-
- _applyMatrix: function(matrix, applyMatrix) {
- var children = this._children;
- if (children && children.length > 0) {
- for (var i = 0, l = children.length; i < l; i++)
- children[i].transform(matrix, applyMatrix);
- return true;
- }
- },
-
- applyMatrix: function(_dontNotify) {
- var matrix = this._matrix;
- if (this._applyMatrix(matrix, true)) {
- var style = this._style,
- fillColor = style.getFillColor(true),
- strokeColor = style.getStrokeColor(true);
- if (fillColor)
- fillColor.transform(matrix);
- if (strokeColor)
- strokeColor.transform(matrix);
- matrix.reset();
- }
- if (!_dontNotify)
- this._changed(5);
- },
-
- globalToLocal: function() {
- var matrix = this.getGlobalMatrix();
- return matrix && matrix._transformPoint(Point.read(arguments));
- },
-
- localToGlobal: function() {
- var matrix = this.getGlobalMatrix();
- return matrix && matrix._inverseTransform(Point.read(arguments));
- },
-
- fitBounds: function(rectangle, fill) {
- rectangle = Rectangle.read(arguments);
- var bounds = this.getBounds(),
- itemRatio = bounds.height / bounds.width,
- rectRatio = rectangle.height / rectangle.width,
- scale = (fill ? itemRatio > rectRatio : itemRatio < rectRatio)
- ? rectangle.width / bounds.width
- : rectangle.height / bounds.height,
- newBounds = new Rectangle(new Point(),
- new Size(bounds.width * scale, bounds.height * scale));
- newBounds.setCenter(rectangle.getCenter());
- this.setBounds(newBounds);
- },
-
- _setStyles: function(ctx) {
- var style = this._style,
- fillColor = style.getFillColor(),
- strokeColor = style.getStrokeColor(),
- shadowColor = style.getShadowColor();
- if (fillColor)
- ctx.fillStyle = fillColor.toCanvasStyle(ctx);
- if (strokeColor) {
- var strokeWidth = style.getStrokeWidth();
- if (strokeWidth > 0) {
- ctx.strokeStyle = strokeColor.toCanvasStyle(ctx);
- ctx.lineWidth = strokeWidth;
- var strokeJoin = style.getStrokeJoin(),
- strokeCap = style.getStrokeCap(),
- miterLimit = style.getMiterLimit();
- if (strokeJoin)
- ctx.lineJoin = strokeJoin;
- if (strokeCap)
- ctx.lineCap = strokeCap;
- if (miterLimit)
- ctx.miterLimit = miterLimit;
- if (paper.support.nativeDash) {
- var dashArray = style.getDashArray(),
- dashOffset = style.getDashOffset();
- if (dashArray && dashArray.length) {
- if ('setLineDash' in ctx) {
- ctx.setLineDash(dashArray);
- ctx.lineDashOffset = dashOffset;
- } else {
- ctx.mozDash = dashArray;
- ctx.mozDashOffset = dashOffset;
- }
- }
- }
- }
- }
- if (shadowColor) {
- var shadowBlur = style.getShadowBlur();
- if (shadowBlur > 0) {
- ctx.shadowColor = shadowColor.toCanvasStyle(ctx);
- ctx.shadowBlur = shadowBlur;
- var offset = this.getShadowOffset();
- ctx.shadowOffsetX = offset.x;
- ctx.shadowOffsetY = offset.y;
- }
- }
- },
-
- draw: function(ctx, param) {
- if (!this._visible || this._opacity === 0)
- return;
- this._drawCount = this._project._drawCount;
- var trackTransforms = param.trackTransforms,
- transforms = param.transforms,
- parentMatrix = transforms[transforms.length - 1],
- globalMatrix = parentMatrix.clone().concatenate(this._matrix);
- if (trackTransforms)
- transforms.push(this._globalMatrix = globalMatrix);
- var blendMode = this._blendMode,
- opacity = this._opacity,
- normalBlend = blendMode === 'normal',
- nativeBlend = BlendMode.nativeModes[blendMode],
- direct = normalBlend && opacity === 1
- || (nativeBlend || normalBlend && opacity < 1)
- && this._canComposite(),
- mainCtx, itemOffset, prevOffset;
- if (!direct) {
- var bounds = this.getStrokeBounds(parentMatrix);
- if (!bounds.width || !bounds.height)
- return;
- prevOffset = param.offset;
- itemOffset = param.offset = bounds.getTopLeft().floor();
- mainCtx = ctx;
- ctx = CanvasProvider.getContext(
- bounds.getSize().ceil().add(new Size(1, 1)), param.ratio);
- }
- ctx.save();
- if (direct) {
- ctx.globalAlpha = opacity;
- if (nativeBlend)
- ctx.globalCompositeOperation = blendMode;
- } else {
- ctx.translate(-itemOffset.x, -itemOffset.y);
- }
- (direct ? this._matrix : globalMatrix).applyToContext(ctx);
- if (!direct && param.clipItem)
- param.clipItem.draw(ctx, param.extend({ clip: true }));
- this._draw(ctx, param);
- ctx.restore();
- if (trackTransforms)
- transforms.pop();
- if (param.clip)
- ctx.clip();
- if (!direct) {
- BlendMode.process(blendMode, ctx, mainCtx, opacity,
- itemOffset.subtract(prevOffset).multiply(param.ratio));
- CanvasProvider.release(ctx);
- param.offset = prevOffset;
- }
- },
-
- _canComposite: function() {
- return false;
- }
-}, Base.each(['down', 'drag', 'up', 'move'], function(name) {
- this['removeOn' + Base.capitalize(name)] = function() {
- var hash = {};
- hash[name] = true;
- return this.removeOn(hash);
- };
-}, {
-
- removeOn: function(obj) {
- for (var name in obj) {
- if (obj[name]) {
- var key = 'mouse' + name,
- project = this._project,
- sets = project._removeSets = project._removeSets || {};
- sets[key] = sets[key] || {};
- sets[key][this._id] = this;
- }
- }
- return this;
- }
-}));
-
-var Group = Item.extend({
- _class: 'Group',
- _serializeFields: {
- children: []
- },
-
- initialize: function Group(arg) {
- this._children = [];
- this._namedChildren = {};
- if (!this._initialize(arg))
- this.addChildren(Array.isArray(arg) ? arg : arguments);
- },
-
- _changed: function _changed(flags) {
- _changed.base.call(this, flags);
- if (flags & 2 && this._transformContent
- && !this._matrix.isIdentity()) {
- this.applyMatrix();
- }
- if (flags & (2 | 256)) {
- delete this._clipItem;
- }
- },
-
- _getClipItem: function() {
- if (this._clipItem !== undefined)
- return this._clipItem;
- for (var i = 0, l = this._children.length; i < l; i++) {
- var child = this._children[i];
- if (child._clipMask)
- return this._clipItem = child;
- }
- return this._clipItem = null;
- },
-
- isClipped: function() {
- return !!this._getClipItem();
- },
-
- setClipped: function(clipped) {
- var child = this.getFirstChild();
- if (child)
- child.setClipMask(clipped);
- },
-
- _draw: function(ctx, param) {
- var clipItem = param.clipItem = this._getClipItem();
- if (clipItem)
- clipItem.draw(ctx, param.extend({ clip: true }));
- for (var i = 0, l = this._children.length; i < l; i++) {
- var item = this._children[i];
- if (item !== clipItem)
- item.draw(ctx, param);
- }
- param.clipItem = null;
- }
-});
-
-var Layer = Group.extend({
- _class: 'Layer',
-
- initialize: function Layer(arg) {
- var props = Base.isPlainObject(arg)
- ? new Base(arg)
- : { children: Array.isArray(arg) ? arg : arguments },
- insert = props.insert;
- props.insert = false;
- Group.call(this, props);
- if (insert || insert === undefined) {
- this._project.addChild(this);
- this.activate();
- }
- },
-
- _remove: function _remove(notify) {
- if (this._parent)
- return _remove.base.call(this, notify);
- if (this._index != null) {
- if (this._project.activeLayer === this)
- this._project.activeLayer = this.getNextSibling()
- || this.getPreviousSibling();
- Base.splice(this._project.layers, null, this._index, 1);
- this._project._needsRedraw = true;
- return true;
- }
- return false;
- },
-
- getNextSibling: function getNextSibling() {
- return this._parent ? getNextSibling.base.call(this)
- : this._project.layers[this._index + 1] || null;
- },
-
- getPreviousSibling: function getPreviousSibling() {
- return this._parent ? getPreviousSibling.base.call(this)
- : this._project.layers[this._index - 1] || null;
- },
-
- isInserted: function isInserted() {
- return this._parent ? isInserted.base.call(this) : this._index != null;
- },
-
- activate: function() {
- this._project.activeLayer = this;
- },
-
- _insert: function _insert(above, item, _preserve) {
- if (item instanceof Layer && !item._parent) {
- this._remove(true);
- Base.splice(item._project.layers, [this],
- item._index + (above ? 1 : 0), 0);
- this._setProject(item._project);
- return this;
- }
- return _insert.base.call(this, above, item, _preserve);
- }
-});
-
-var Shape = Item.extend({
- _class: 'Shape',
- _transformContent: false,
- _boundsSelected: true,
-
- initialize: function Shape(shape, center, size, radius, props) {
- this._shape = shape;
- this._size = size;
- this._radius = radius;
- this._initialize(props, center);
- },
-
- _equals: function(item) {
- return this._shape === item._shape
- && this._size.equals(item._size)
- && Base.equals(this._radius, item._radius);
- },
-
- clone: function(insert) {
- return this._clone(new Shape(this._shape, this.getPosition(true),
- this._size.clone(),
- this._radius.clone ? this._radius.clone() : this._radius,
- { insert: false }), insert);
- },
-
- getShape: function() {
- return this._shape;
- },
-
- getSize: function() {
- var size = this._size;
- return new LinkedSize(size.width, size.height, this, 'setSize');
- },
-
- setSize: function() {
- var shape = this._shape,
- size = Size.read(arguments);
- if (!this._size.equals(size)) {
- var width = size.width,
- height = size.height;
- if (shape === 'rectangle') {
- var radius = Size.min(this._radius, size.divide(2));
- this._radius.set(radius.width, radius.height);
- } else if (shape === 'circle') {
- width = height = (width + height) / 2;
- this._radius = width / 2;
- } else if (shape === 'ellipse') {
- this._radius.set(width / 2, height / 2);
- }
- this._size.set(width, height);
- this._changed(5);
- }
- },
-
- getRadius: function() {
- var rad = this._radius;
- return this._shape === 'circle'
- ? rad
- : new LinkedSize(rad.width, rad.height, this, 'setRadius');
- },
-
- setRadius: function(radius) {
- var shape = this._shape;
- if (shape === 'circle') {
- if (radius === this._radius)
- return;
- var size = radius * 2;
- this._radius = radius;
- this._size.set(size, size);
- } else {
- radius = Size.read(arguments);
- if (this._radius.equals(radius))
- return;
- this._radius.set(radius.width, radius.height);
- if (shape === 'rectangle') {
- var size = Size.max(this._size, radius.multiply(2));
- this._size.set(size.width, size.height);
- } else if (shape === 'ellipse') {
- this._size.set(radius.width * 2, radius.height * 2);
- }
- }
- this._changed(5);
- },
-
- isEmpty: function() {
- return false;
- },
-
- toPath: function(insert) {
- var path = new Path[Base.capitalize(this._shape)]({
- center: new Point(),
- size: this._size,
- radius: this._radius,
- insert: false
- });
- path.setStyle(this._style);
- path.transform(this._matrix);
- if (insert || insert === undefined)
- path.insertAbove(this);
- return path;
- },
-
- _draw: function(ctx, param) {
- var style = this._style,
- hasFill = style.hasFill(),
- hasStroke = style.hasStroke(),
- clip = param.clip;
- if (hasFill || hasStroke || clip) {
- var radius = this._radius,
- shape = this._shape;
- ctx.beginPath();
- if (shape === 'circle') {
- ctx.arc(0, 0, radius, 0, Math.PI * 2, true);
- } else {
- var rx = radius.width,
- ry = radius.height,
- kappa = Numerical.KAPPA;
- if (shape === 'ellipse') {
- var cx = rx * kappa,
- cy = ry * kappa;
- ctx.moveTo(-rx, 0);
- ctx.bezierCurveTo(-rx, -cy, -cx, -ry, 0, -ry);
- ctx.bezierCurveTo(cx, -ry, rx, -cy, rx, 0);
- ctx.bezierCurveTo(rx, cy, cx, ry, 0, ry);
- ctx.bezierCurveTo(-cx, ry, -rx, cy, -rx, 0);
- } else {
- var size = this._size,
- width = size.width,
- height = size.height;
- if (rx === 0 && ry === 0) {
- ctx.rect(-width / 2, -height / 2, width, height);
- } else {
- kappa = 1 - kappa;
- var x = width / 2,
- y = height / 2,
- cx = rx * kappa,
- cy = ry * kappa;
- ctx.moveTo(-x, -y + ry);
- ctx.bezierCurveTo(-x, -y + cy, -x + cx, -y, -x + rx, -y);
- ctx.lineTo(x - rx, -y);
- ctx.bezierCurveTo(x - cx, -y, x, -y + cy, x, -y + ry);
- ctx.lineTo(x, y - ry);
- ctx.bezierCurveTo(x, y - cy, x - cx, y, x - rx, y);
- ctx.lineTo(-x + rx, y);
- ctx.bezierCurveTo(-x + cx, y, -x, y - cy, -x, y - ry);
- }
- }
- }
- ctx.closePath();
- }
- if (!clip && (hasFill || hasStroke)) {
- this._setStyles(ctx);
- if (hasFill) {
- ctx.fill(style.getWindingRule());
- ctx.shadowColor = 'rgba(0,0,0,0)';
- }
- if (hasStroke)
- ctx.stroke();
- }
- },
-
- _canComposite: function() {
- return !(this.hasFill() && this.hasStroke());
- },
-
- _getBounds: function(getter, matrix) {
- var rect = new Rectangle(this._size).setCenter(0, 0);
- if (getter !== 'getBounds' && this.hasStroke())
- rect = rect.expand(this.getStrokeWidth());
- return matrix ? matrix._transformBounds(rect) : rect;
- }
-},
-new function() {
-
- function getCornerCenter(that, point, expand) {
- var radius = that._radius;
- if (!radius.isZero()) {
- var halfSize = that._size.divide(2);
- for (var i = 0; i < 4; i++) {
- var dir = new Point(i & 1 ? 1 : -1, i > 1 ? 1 : -1),
- corner = dir.multiply(halfSize),
- center = corner.subtract(dir.multiply(radius)),
- rect = new Rectangle(corner, center);
- if ((expand ? rect.expand(expand) : rect).contains(point))
- return center;
- }
- }
- }
-
- function getEllipseRadius(point, radius) {
- var angle = point.getAngleInRadians(),
- width = radius.width * 2,
- height = radius.height * 2,
- x = width * Math.sin(angle),
- y = height * Math.cos(angle);
- return width * height / (2 * Math.sqrt(x * x + y * y));
- }
-
- return {
- _contains: function _contains(point) {
- if (this._shape === 'rectangle') {
- var center = getCornerCenter(this, point);
- return center
- ? point.subtract(center).divide(this._radius)
- .getLength() <= 1
- : _contains.base.call(this, point);
- } else {
- return point.divide(this.size).getLength() <= 0.5;
- }
- },
-
- _hitTest: function _hitTest(point, options) {
- var hit = false;
- if (this.hasStroke()) {
- var shape = this._shape,
- radius = this._radius,
- strokeWidth = this.getStrokeWidth() + 2 * options.tolerance;
- if (shape === 'rectangle') {
- var center = getCornerCenter(this, point, strokeWidth);
- if (center) {
- var pt = point.subtract(center);
- hit = 2 * Math.abs(pt.getLength()
- - getEllipseRadius(pt, radius)) <= strokeWidth;
- } else {
- var rect = new Rectangle(this._size).setCenter(0, 0),
- outer = rect.expand(strokeWidth),
- inner = rect.expand(-strokeWidth);
- hit = outer._containsPoint(point)
- && !inner._containsPoint(point);
- }
- } else {
- if (shape === 'ellipse')
- radius = getEllipseRadius(point, radius);
- hit = 2 * Math.abs(point.getLength() - radius)
- <= strokeWidth;
- }
- }
- return hit
- ? new HitResult('stroke', this)
- : _hitTest.base.apply(this, arguments);
- }
- };
-}, {
-
-statics: new function() {
- function createShape(shape, point, size, radius, args) {
- return new Shape(shape, point, size, radius, Base.getNamed(args));
- }
-
- return {
- Circle: function() {
- var center = Point.readNamed(arguments, 'center'),
- radius = Base.readNamed(arguments, 'radius');
- return createShape('circle', center, new Size(radius * 2), radius,
- arguments);
- },
-
- Rectangle: function() {
- var rect = Rectangle.readNamed(arguments, 'rectangle'),
- radius = Size.min(Size.readNamed(arguments, 'radius'),
- rect.getSize(true).divide(2));
- return createShape('rectangle', rect.getCenter(true),
- rect.getSize(true), radius, arguments);
- },
-
- Ellipse: function() {
- var ellipse = Shape._readEllipse(arguments);
- radius = ellipse.radius;
- return createShape('ellipse', ellipse.center, radius.multiply(2),
- radius, arguments);
- },
-
- _readEllipse: function(args) {
- var center,
- radius;
- if (Base.hasNamed(args, 'radius')) {
- center = Point.readNamed(args, 'center');
- radius = Size.readNamed(args, 'radius');
- } else {
- var rect = Rectangle.readNamed(args, 'rectangle');
- center = rect.getCenter(true);
- radius = rect.getSize(true).divide(2);
- }
- return { center: center, radius: radius };
- }
- };
-}});
-
-var Raster = Item.extend({
- _class: 'Raster',
- _transformContent: false,
- _boundsGetter: 'getBounds',
- _boundsSelected: true,
- _serializeFields: {
- source: null
- },
-
- initialize: function Raster(object, position) {
- if (!this._initialize(object,
- position !== undefined && Point.read(arguments, 1))) {
- if (typeof object === 'string') {
- this.setSource(object);
- } else {
- this.setImage(object);
- }
- }
- if (!this._size)
- this._size = new Size();
- },
-
- _equals: function(item) {
- return this.getSource() === item.getSource();
- },
-
- clone: function(insert) {
- var param = { insert: false },
- image = this._image;
- if (image) {
- param.image = image;
- } else if (this._canvas) {
- var canvas = param.canvas = CanvasProvider.getCanvas(this._size);
- canvas.getContext('2d').drawImage(this._canvas, 0, 0);
- }
- return this._clone(new Raster(param), insert);
- },
-
- getSize: function() {
- var size = this._size;
- return new LinkedSize(size.width, size.height, this, 'setSize');
- },
-
- setSize: function() {
- var size = Size.read(arguments);
- if (!this._size.equals(size)) {
- var element = this.getElement();
- this.setCanvas(CanvasProvider.getCanvas(size));
- if (element)
- this.getContext(true).drawImage(element, 0, 0,
- size.width, size.height);
- }
- },
-
- getWidth: function() {
- return this._size.width;
- },
-
- getHeight: function() {
- return this._size.height;
- },
-
- isEmpty: function() {
- return this._size.width == 0 && this._size.height == 0;
- },
-
- getPpi: function() {
- var matrix = this._matrix,
- orig = new Point(0, 0).transform(matrix),
- u = new Point(1, 0).transform(matrix).subtract(orig),
- v = new Point(0, 1).transform(matrix).subtract(orig);
- return new Size(
- 72 / u.getLength(),
- 72 / v.getLength()
- );
- },
-
- getImage: function() {
- return this._image;
- },
-
- setImage: function(image) {
- if (this._canvas)
- CanvasProvider.release(this._canvas);
- if (image.getContext) {
- this._image = null;
- this._canvas = image;
- } else {
- this._image = image;
- this._canvas = null;
- }
- this._size = new Size(
- image.naturalWidth || image.width,
- image.naturalHeight || image.height);
- this._context = null;
- this._changed(5 | 129);
- },
-
- getCanvas: function() {
- if (!this._canvas) {
- var ctx = CanvasProvider.getContext(this._size);
- try {
- if (this._image)
- ctx.drawImage(this._image, 0, 0);
- this._canvas = ctx.canvas;
- } catch (e) {
- CanvasProvider.release(ctx);
- }
- }
- return this._canvas;
- },
-
- setCanvas: '#setImage',
-
- getContext: function() {
- if (!this._context)
- this._context = this.getCanvas().getContext('2d');
- if (arguments[0]) {
- this._image = null;
- this._changed(129);
- }
- return this._context;
- },
-
- setContext: function(context) {
- this._context = context;
- },
-
- getSource: function() {
- return this._image && this._image.src || this.toDataURL();
- },
-
- setSource: function(src) {
- var that = this,
- image = document.getElementById(src) || new Image();
-
- function loaded() {
- var view = that._project.view;
- if (view)
- paper = view._scope;
- that.fire('load');
- if (view)
- view.draw(true);
- }
-
- if (image.naturalWidth && image.naturalHeight) {
- setTimeout(loaded, 0);
- } else {
- DomEvent.add(image, {
- load: function() {
- that.setImage(image);
- loaded();
- }
- });
- if (!image.src)
- image.src = src;
- }
- this.setImage(image);
- },
-
- getElement: function() {
- return this._canvas || this._image;
- },
-
- getSubCanvas: function(rect) {
- rect = Rectangle.read(arguments);
- var ctx = CanvasProvider.getContext(rect.getSize());
- ctx.drawImage(this.getCanvas(), rect.x, rect.y,
- rect.width, rect.height, 0, 0, rect.width, rect.height);
- return ctx.canvas;
- },
-
- getSubRaster: function(rect) {
- rect = Rectangle.read(arguments);
- var raster = new Raster({
- canvas: this.getSubCanvas(rect),
- insert: false
- });
- raster.translate(rect.getCenter().subtract(this.getSize().divide(2)));
- raster._matrix.preConcatenate(this._matrix);
- raster.insertAbove(this);
- return raster;
- },
-
- toDataURL: function() {
- var src = this._image && this._image.src;
- if (/^data:/.test(src))
- return src;
- var canvas = this.getCanvas();
- return canvas ? canvas.toDataURL() : null;
- },
-
- drawImage: function(image, point) {
- point = Point.read(arguments, 1);
- this.getContext(true).drawImage(image, point.x, point.y);
- },
-
- getAverageColor: function(object) {
- var bounds, path;
- if (!object) {
- bounds = this.getBounds();
- } else if (object instanceof PathItem) {
- path = object;
- bounds = object.getBounds();
- } else if (object.width) {
- bounds = new Rectangle(object);
- } else if (object.x) {
- bounds = new Rectangle(object.x - 0.5, object.y - 0.5, 1, 1);
- }
- var sampleSize = 32,
- width = Math.min(bounds.width, sampleSize),
- height = Math.min(bounds.height, sampleSize);
- var ctx = Raster._sampleContext;
- if (!ctx) {
- ctx = Raster._sampleContext = CanvasProvider.getContext(
- new Size(sampleSize));
- } else {
- ctx.clearRect(0, 0, sampleSize + 1, sampleSize + 1);
- }
- ctx.save();
- var matrix = new Matrix()
- .scale(width / bounds.width, height / bounds.height)
- .translate(-bounds.x, -bounds.y);
- matrix.applyToContext(ctx);
- if (path)
- path.draw(ctx, new Base({ clip: true, transforms: [matrix] }));
- this._matrix.applyToContext(ctx);
- ctx.drawImage(this.getElement(),
- -this._size.width / 2, -this._size.height / 2);
- ctx.restore();
- var pixels = ctx.getImageData(0.5, 0.5, Math.ceil(width),
- Math.ceil(height)).data,
- channels = [0, 0, 0],
- total = 0;
- for (var i = 0, l = pixels.length; i < l; i += 4) {
- var alpha = pixels[i + 3];
- total += alpha;
- alpha /= 255;
- channels[0] += pixels[i] * alpha;
- channels[1] += pixels[i + 1] * alpha;
- channels[2] += pixels[i + 2] * alpha;
- }
- for (var i = 0; i < 3; i++)
- channels[i] /= total;
- return total ? Color.read(channels) : null;
- },
-
- getPixel: function(point) {
- point = Point.read(arguments);
- var data = this.getContext().getImageData(point.x, point.y, 1, 1).data;
- return new Color('rgb', [data[0] / 255, data[1] / 255, data[2] / 255],
- data[3] / 255);
- },
-
- setPixel: function() {
- var point = Point.read(arguments),
- color = Color.read(arguments),
- components = color._convert('rgb'),
- alpha = color._alpha,
- ctx = this.getContext(true),
- imageData = ctx.createImageData(1, 1),
- data = imageData.data;
- data[0] = components[0] * 255;
- data[1] = components[1] * 255;
- data[2] = components[2] * 255;
- data[3] = alpha != null ? alpha * 255 : 255;
- ctx.putImageData(imageData, point.x, point.y);
- },
-
- createImageData: function(size) {
- size = Size.read(arguments);
- return this.getContext().createImageData(size.width, size.height);
- },
-
- getImageData: function(rect) {
- rect = Rectangle.read(arguments);
- if (rect.isEmpty())
- rect = new Rectangle(this._size);
- return this.getContext().getImageData(rect.x, rect.y,
- rect.width, rect.height);
- },
-
- setImageData: function(data, point) {
- point = Point.read(arguments, 1);
- this.getContext(true).putImageData(data, point.x, point.y);
- },
-
- _getBounds: function(getter, matrix) {
- var rect = new Rectangle(this._size).setCenter(0, 0);
- return matrix ? matrix._transformBounds(rect) : rect;
- },
-
- _hitTest: function(point) {
- if (this._contains(point)) {
- var that = this;
- return new HitResult('pixel', that, {
- offset: point.add(that._size.divide(2)).round(),
- color: {
- get: function() {
- return that.getPixel(this.offset);
- }
- }
- });
- }
- },
-
- _draw: function(ctx) {
- var element = this.getElement();
- if (element) {
- ctx.globalAlpha = this._opacity;
- ctx.drawImage(element,
- -this._size.width / 2, -this._size.height / 2);
- }
- },
-
- _canComposite: function() {
- return true;
- }
-});
-
-var PlacedSymbol = Item.extend({
- _class: 'PlacedSymbol',
- _transformContent: false,
- _boundsGetter: { getBounds: 'getStrokeBounds' },
- _boundsSelected: true,
- _serializeFields: {
- symbol: null
- },
-
- initialize: function PlacedSymbol(arg0, arg1) {
- if (!this._initialize(arg0,
- arg1 !== undefined && Point.read(arguments, 1)))
- this.setSymbol(arg0 instanceof Symbol ? arg0 : new Symbol(arg0));
- },
-
- _equals: function(item) {
- return this._symbol === item._symbol;
- },
-
- getSymbol: function() {
- return this._symbol;
- },
-
- setSymbol: function(symbol) {
- if (this._symbol)
- delete this._symbol._instances[this._id];
- this._symbol = symbol;
- symbol._instances[this._id] = this;
- },
-
- clone: function(insert) {
- return this._clone(new PlacedSymbol({
- symbol: this.symbol,
- insert: false
- }), insert);
- },
-
- isEmpty: function() {
- return this._symbol._definition.isEmpty();
- },
-
- _getBounds: function(getter, matrix) {
- return this.symbol._definition._getCachedBounds(getter, matrix);
- },
-
- _hitTest: function(point, options, matrix) {
- var result = this._symbol._definition._hitTest(point, options, matrix);
- if (result)
- result.item = this;
- return result;
- },
-
- _draw: function(ctx, param) {
- this.symbol._definition.draw(ctx, param);
- }
-
-});
-
-var HitResult = Base.extend({
- _class: 'HitResult',
-
- initialize: function HitResult(type, item, values) {
- this.type = type;
- this.item = item;
- if (values) {
- values.enumerable = true;
- this.inject(values);
- }
- },
-
- statics: {
- getOptions: function(options) {
- return options && options._merged ? options : new Base({
- type: null,
- tolerance: paper.project.options.hitTolerance || 2,
- fill: !options,
- stroke: !options,
- segments: !options,
- handles: false,
- ends: false,
- center: false,
- bounds: false,
- guides: false,
- selected: false,
- _merged: true
- }, options);
- }
- }
-});
-
-var Segment = Base.extend({
- _class: 'Segment',
-
- initialize: function Segment(arg0, arg1, arg2, arg3, arg4, arg5) {
- var count = arguments.length,
- point, handleIn, handleOut;
- if (count === 0) {
- } else if (count === 1) {
- if (arg0.point) {
- point = arg0.point;
- handleIn = arg0.handleIn;
- handleOut = arg0.handleOut;
- } else {
- point = arg0;
- }
- } else if (count === 2 && typeof arg0 === 'number') {
- point = arguments;
- } else if (count <= 3) {
- point = arg0;
- handleIn = arg1;
- handleOut = arg2;
- } else {
- point = arg0 !== undefined ? [ arg0, arg1 ] : null;
- handleIn = arg2 !== undefined ? [ arg2, arg3 ] : null;
- handleOut = arg4 !== undefined ? [ arg4, arg5 ] : null;
- }
- new SegmentPoint(point, this, '_point');
- new SegmentPoint(handleIn, this, '_handleIn');
- new SegmentPoint(handleOut, this, '_handleOut');
- },
-
- _serialize: function(options) {
- return Base.serialize(this.isLinear() ? this._point
- : [this._point, this._handleIn, this._handleOut], options, true);
- },
-
- _changed: function(point) {
- if (!this._path)
- return;
- var curve = this._path._curves && this.getCurve(),
- other;
- if (curve) {
- curve._changed();
- if (other = (curve[point == this._point
- || point == this._handleIn && curve._segment1 == this
- ? 'getPrevious' : 'getNext']())) {
- other._changed();
- }
- }
- this._path._changed(5);
- },
-
- getPoint: function() {
- return this._point;
- },
-
- setPoint: function(point) {
- point = Point.read(arguments);
- this._point.set(point.x, point.y);
- },
-
- getHandleIn: function() {
- return this._handleIn;
- },
-
- setHandleIn: function(point) {
- point = Point.read(arguments);
- this._handleIn.set(point.x, point.y);
- },
-
- getHandleOut: function() {
- return this._handleOut;
- },
-
- setHandleOut: function(point) {
- point = Point.read(arguments);
- this._handleOut.set(point.x, point.y);
- },
-
- isLinear: function() {
- return this._handleIn.isZero() && this._handleOut.isZero();
- },
-
- setLinear: function() {
- this._handleIn.set(0, 0);
- this._handleOut.set(0, 0);
- },
-
- isColinear: function(segment) {
- var next1 = this.getNext(),
- next2 = segment.getNext();
- return this._handleOut.isZero() && next1._handleIn.isZero()
- && segment._handleOut.isZero() && next2._handleIn.isZero()
- && next1._point.subtract(this._point).isColinear(
- next2._point.subtract(segment._point));
- },
-
- isOrthogonal: function() {
- var prev = this.getPrevious(),
- next = this.getNext();
- return prev._handleOut.isZero() && this._handleIn.isZero()
- && this._handleOut.isZero() && next._handleIn.isZero()
- && this._point.subtract(prev._point).isOrthogonal(
- next._point.subtract(this._point));
- },
-
- isArc: function() {
- var next = this.getNext(),
- handle1 = this._handleOut,
- handle2 = next._handleIn,
- kappa = Numerical.KAPPA;
- if (handle1.isOrthogonal(handle2)) {
- var from = this._point,
- to = next._point,
- corner = new Line(from, handle1, true).intersect(
- new Line(to, handle2, true), true);
- return corner && Numerical.isZero(handle1.getLength() /
- corner.subtract(from).getLength() - kappa)
- && Numerical.isZero(handle2.getLength() /
- corner.subtract(to).getLength() - kappa);
- }
- return false;
- },
-
- _isSelected: function(point) {
- var state = this._selectionState;
- return point == this._point ? !!(state & 4)
- : point == this._handleIn ? !!(state & 1)
- : point == this._handleOut ? !!(state & 2)
- : false;
- },
-
- _setSelected: function(point, selected) {
- var path = this._path,
- selected = !!selected,
- state = this._selectionState || 0,
- selection = [
- !!(state & 4),
- !!(state & 1),
- !!(state & 2)
- ];
- if (point === this._point) {
- if (selected) {
- selection[1] = selection[2] = false;
- } else {
- var previous = this.getPrevious(),
- next = this.getNext();
- selection[1] = previous && (previous._point.isSelected()
- || previous._handleOut.isSelected());
- selection[2] = next && (next._point.isSelected()
- || next._handleIn.isSelected());
- }
- selection[0] = selected;
- } else {
- var index = point === this._handleIn ? 1 : 2;
- if (selection[index] != selected) {
- if (selected)
- selection[0] = false;
- selection[index] = selected;
- }
- }
- this._selectionState = (selection[0] ? 4 : 0)
- | (selection[1] ? 1 : 0)
- | (selection[2] ? 2 : 0);
- if (path && state != this._selectionState) {
- path._updateSelection(this, state, this._selectionState);
- path._changed(33);
- }
- },
-
- isSelected: function() {
- return this._isSelected(this._point);
- },
-
- setSelected: function(selected) {
- this._setSelected(this._point, selected);
- },
-
- getIndex: function() {
- return this._index !== undefined ? this._index : null;
- },
-
- getPath: function() {
- return this._path || null;
- },
-
- getCurve: function() {
- var path = this._path,
- index = this._index;
- if (path) {
- if (!path._closed && index == path._segments.length - 1)
- index--;
- return path.getCurves()[index] || null;
- }
- return null;
- },
-
- getLocation: function() {
- var curve = this.getCurve();
- return curve ? new CurveLocation(curve, curve.getNext() ? 0 : 1) : null;
- },
-
- getNext: function() {
- var segments = this._path && this._path._segments;
- return segments && (segments[this._index + 1]
- || this._path._closed && segments[0]) || null;
- },
-
- getPrevious: function() {
- var segments = this._path && this._path._segments;
- return segments && (segments[this._index - 1]
- || this._path._closed && segments[segments.length - 1]) || null;
- },
-
- reverse: function() {
- return new Segment(this._point, this._handleOut, this._handleIn);
- },
-
- remove: function() {
- return this._path ? !!this._path.removeSegment(this._index) : false;
- },
-
- clone: function() {
- return new Segment(this._point, this._handleIn, this._handleOut);
- },
-
- equals: function(segment) {
- return segment === this || segment && this._class === segment._class
- && this._point.equals(segment._point)
- && this._handleIn.equals(segment._handleIn)
- && this._handleOut.equals(segment._handleOut)
- || false;
- },
-
- toString: function() {
- var parts = [ 'point: ' + this._point ];
- if (!this._handleIn.isZero())
- parts.push('handleIn: ' + this._handleIn);
- if (!this._handleOut.isZero())
- parts.push('handleOut: ' + this._handleOut);
- return '{ ' + parts.join(', ') + ' }';
- },
-
- _transformCoordinates: function(matrix, coords, change) {
- var point = this._point,
- handleIn = !change || !this._handleIn.isZero()
- ? this._handleIn : null,
- handleOut = !change || !this._handleOut.isZero()
- ? this._handleOut : null,
- x = point._x,
- y = point._y,
- i = 2;
- coords[0] = x;
- coords[1] = y;
- if (handleIn) {
- coords[i++] = handleIn._x + x;
- coords[i++] = handleIn._y + y;
- }
- if (handleOut) {
- coords[i++] = handleOut._x + x;
- coords[i++] = handleOut._y + y;
- }
- if (matrix) {
- matrix._transformCoordinates(coords, 0, coords, 0, i / 2);
- x = coords[0];
- y = coords[1];
- if (change) {
- point._x = x;
- point._y = y;
- i = 2;
- if (handleIn) {
- handleIn._x = coords[i++] - x;
- handleIn._y = coords[i++] - y;
- }
- if (handleOut) {
- handleOut._x = coords[i++] - x;
- handleOut._y = coords[i++] - y;
- }
- } else {
- if (!handleIn) {
- coords[i++] = x;
- coords[i++] = y;
- }
- if (!handleOut) {
- coords[i++] = x;
- coords[i++] = y;
- }
- }
- }
- return coords;
- }
-});
-
-var SegmentPoint = Point.extend({
- initialize: function SegmentPoint(point, owner, key) {
- var x, y, selected;
- if (!point) {
- x = y = 0;
- } else if ((x = point[0]) !== undefined) {
- y = point[1];
- } else {
- if ((x = point.x) === undefined) {
- point = Point.read(arguments);
- x = point.x;
- }
- y = point.y;
- selected = point.selected;
- }
- this._x = x;
- this._y = y;
- this._owner = owner;
- owner[key] = this;
- if (selected)
- this.setSelected(true);
- },
-
- set: function(x, y) {
- this._x = x;
- this._y = y;
- this._owner._changed(this);
- return this;
- },
-
- _serialize: function(options) {
- var f = options.formatter,
- x = f.number(this._x),
- y = f.number(this._y);
- return this.isSelected()
- ? { x: x, y: y, selected: true }
- : [x, y];
- },
-
- getX: function() {
- return this._x;
- },
-
- setX: function(x) {
- this._x = x;
- this._owner._changed(this);
- },
-
- getY: function() {
- return this._y;
- },
-
- setY: function(y) {
- this._y = y;
- this._owner._changed(this);
- },
-
- isZero: function() {
- return Numerical.isZero(this._x) && Numerical.isZero(this._y);
- },
-
- setSelected: function(selected) {
- this._owner._setSelected(this, selected);
- },
-
- isSelected: function() {
- return this._owner._isSelected(this);
- }
-});
-
-var Curve = Base.extend({
- _class: 'Curve',
- initialize: function Curve(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7) {
- var count = arguments.length;
- if (count === 3) {
- this._path = arg0;
- this._segment1 = arg1;
- this._segment2 = arg2;
- } else if (count === 0) {
- this._segment1 = new Segment();
- this._segment2 = new Segment();
- } else if (count === 1) {
- this._segment1 = new Segment(arg0.segment1);
- this._segment2 = new Segment(arg0.segment2);
- } else if (count === 2) {
- this._segment1 = new Segment(arg0);
- this._segment2 = new Segment(arg1);
- } else {
- var point1, handle1, handle2, point2;
- if (count === 4) {
- point1 = arg0;
- handle1 = arg1;
- handle2 = arg2;
- point2 = arg3;
- } else if (count === 8) {
- point1 = [arg0, arg1];
- point2 = [arg6, arg7];
- handle1 = [arg2 - arg0, arg3 - arg1];
- handle2 = [arg4 - arg6, arg5 - arg7];
- }
- this._segment1 = new Segment(point1, null, handle1);
- this._segment2 = new Segment(point2, handle2, null);
- }
- },
-
- _changed: function() {
- delete this._length;
- delete this._bounds;
- },
-
- getPoint1: function() {
- return this._segment1._point;
- },
-
- setPoint1: function(point) {
- point = Point.read(arguments);
- this._segment1._point.set(point.x, point.y);
- },
-
- getPoint2: function() {
- return this._segment2._point;
- },
-
- setPoint2: function(point) {
- point = Point.read(arguments);
- this._segment2._point.set(point.x, point.y);
- },
-
- getHandle1: function() {
- return this._segment1._handleOut;
- },
-
- setHandle1: function(point) {
- point = Point.read(arguments);
- this._segment1._handleOut.set(point.x, point.y);
- },
-
- getHandle2: function() {
- return this._segment2._handleIn;
- },
-
- setHandle2: function(point) {
- point = Point.read(arguments);
- this._segment2._handleIn.set(point.x, point.y);
- },
-
- getSegment1: function() {
- return this._segment1;
- },
-
- getSegment2: function() {
- return this._segment2;
- },
-
- getPath: function() {
- return this._path;
- },
-
- getIndex: function() {
- return this._segment1._index;
- },
-
- getNext: function() {
- var curves = this._path && this._path._curves;
- return curves && (curves[this._segment1._index + 1]
- || this._path._closed && curves[0]) || null;
- },
-
- getPrevious: function() {
- var curves = this._path && this._path._curves;
- return curves && (curves[this._segment1._index - 1]
- || this._path._closed && curves[curves.length - 1]) || null;
- },
-
- isSelected: function() {
- return this.getHandle1().isSelected() && this.getHandle2().isSelected();
- },
-
- setSelected: function(selected) {
- this.getHandle1().setSelected(selected);
- this.getHandle2().setSelected(selected);
- },
-
- getValues: function() {
- return Curve.getValues(this._segment1, this._segment2);
- },
-
- getPoints: function() {
- var coords = this.getValues(),
- points = [];
- for (var i = 0; i < 8; i += 2)
- points.push(new Point(coords[i], coords[i + 1]));
- return points;
- },
-
- getLength: function() {
- var from = arguments[0],
- to = arguments[1],
- fullLength = arguments.length === 0 || from === 0 && to === 1;
- if (fullLength && this._length != null)
- return this._length;
- var length = Curve.getLength(this.getValues(), from, to);
- if (fullLength)
- this._length = length;
- return length;
- },
-
- getArea: function() {
- return Curve.getArea(this.getValues());
- },
-
- getPart: function(from, to) {
- return new Curve(Curve.getPart(this.getValues(), from, to));
- },
-
- isLinear: function() {
- return this._segment1._handleOut.isZero()
- && this._segment2._handleIn.isZero();
- },
-
- getIntersections: function(curve) {
- return Curve.getIntersections(this.getValues(), curve.getValues(),
- this, curve, []);
- },
-
- reverse: function() {
- return new Curve(this._segment2.reverse(), this._segment1.reverse());
- },
-
- _getParameter: function(offset, isParameter) {
- return isParameter
- ? offset
- : offset && offset.curve === this
- ? offset.parameter
- : offset === undefined && isParameter === undefined
- ? 0.5
- : this.getParameterAt(offset, 0);
- },
-
- divide: function(offset, isParameter) {
- var parameter = this._getParameter(offset, isParameter),
- tolerance = 0.00001,
- res = null;
- if (parameter > tolerance && parameter < 1 - tolerance) {
- var parts = Curve.subdivide(this.getValues(), parameter),
- isLinear = this.isLinear(),
- left = parts[0],
- right = parts[1];
-
- if (!isLinear) {
- this._segment1._handleOut.set(left[2] - left[0],
- left[3] - left[1]);
- this._segment2._handleIn.set(right[4] - right[6],
- right[5] - right[7]);
- }
-
- var x = left[6], y = left[7],
- segment = new Segment(new Point(x, y),
- !isLinear && new Point(left[4] - x, left[5] - y),
- !isLinear && new Point(right[2] - x, right[3] - y));
-
- if (this._path) {
- if (this._segment1._index > 0 && this._segment2._index === 0) {
- this._path.add(segment);
- } else {
- this._path.insert(this._segment2._index, segment);
- }
- res = this;
- } else {
- var end = this._segment2;
- this._segment2 = segment;
- res = new Curve(segment, end);
- }
- }
- return res;
- },
-
- split: function(offset, isParameter) {
- return this._path
- ? this._path.split(this._segment1._index,
- this._getParameter(offset, isParameter))
- : null;
- },
-
- clone: function() {
- return new Curve(this._segment1, this._segment2);
- },
-
- toString: function() {
- var parts = [ 'point1: ' + this._segment1._point ];
- if (!this._segment1._handleOut.isZero())
- parts.push('handle1: ' + this._segment1._handleOut);
- if (!this._segment2._handleIn.isZero())
- parts.push('handle2: ' + this._segment2._handleIn);
- parts.push('point2: ' + this._segment2._point);
- return '{ ' + parts.join(', ') + ' }';
- },
-
-statics: {
- getValues: function(segment1, segment2) {
- var p1 = segment1._point,
- h1 = segment1._handleOut,
- h2 = segment2._handleIn,
- p2 = segment2._point;
- return [
- p1._x, p1._y,
- p1._x + h1._x, p1._y + h1._y,
- p2._x + h2._x, p2._y + h2._y,
- p2._x, p2._y
- ];
- },
-
- evaluate: function(v, t, type) {
- var p1x = v[0], p1y = v[1],
- c1x = v[2], c1y = v[3],
- c2x = v[4], c2y = v[5],
- p2x = v[6], p2y = v[7],
- x, y;
-
- if (type === 0 && (t === 0 || t === 1)) {
- x = t === 0 ? p1x : p2x;
- y = t === 0 ? p1y : p2y;
- } else {
- var cx = 3 * (c1x - p1x),
- bx = 3 * (c2x - c1x) - cx,
- ax = p2x - p1x - cx - bx,
-
- cy = 3 * (c1y - p1y),
- by = 3 * (c2y - c1y) - cy,
- ay = p2y - p1y - cy - by;
- if (type === 0) {
- x = ((ax * t + bx) * t + cx) * t + p1x;
- y = ((ay * t + by) * t + cy) * t + p1y;
- } else {
- var tolerance = 0.00001;
- if (t < tolerance && c1x === p1x && c1y === p1y
- || t > 1 - tolerance && c2x === p2x && c2y === p2y) {
- x = p2x - p1x;
- y = p2y - p1y;
- } else {
- x = (3 * ax * t + 2 * bx) * t + cx;
- y = (3 * ay * t + 2 * by) * t + cy;
- }
- if (type === 3) {
- var x2 = 6 * ax * t + 2 * bx,
- y2 = 6 * ay * t + 2 * by;
- return (x * y2 - y * x2) / Math.pow(x * x + y * y, 3 / 2);
- }
- }
- }
- return type == 2 ? new Point(y, -x) : new Point(x, y);
- },
-
- subdivide: function(v, t) {
- var p1x = v[0], p1y = v[1],
- c1x = v[2], c1y = v[3],
- c2x = v[4], c2y = v[5],
- p2x = v[6], p2y = v[7];
- if (t === undefined)
- t = 0.5;
- var u = 1 - t,
- p3x = u * p1x + t * c1x, p3y = u * p1y + t * c1y,
- p4x = u * c1x + t * c2x, p4y = u * c1y + t * c2y,
- p5x = u * c2x + t * p2x, p5y = u * c2y + t * p2y,
- p6x = u * p3x + t * p4x, p6y = u * p3y + t * p4y,
- p7x = u * p4x + t * p5x, p7y = u * p4y + t * p5y,
- p8x = u * p6x + t * p7x, p8y = u * p6y + t * p7y;
- return [
- [p1x, p1y, p3x, p3y, p6x, p6y, p8x, p8y],
- [p8x, p8y, p7x, p7y, p5x, p5y, p2x, p2y]
- ];
- },
-
- solveCubic: function (v, coord, val, roots, min, max) {
- var p1 = v[coord],
- c1 = v[coord + 2],
- c2 = v[coord + 4],
- p2 = v[coord + 6],
- c = 3 * (c1 - p1),
- b = 3 * (c2 - c1) - c,
- a = p2 - p1 - c - b;
- return Numerical.solveCubic(a, b, c, p1 - val, roots, min, max);
- },
-
- getParameterOf: function(v, x, y) {
- if (Math.abs(v[0] - x) < 0.00001
- && Math.abs(v[1] - y) < 0.00001)
- return 0;
- if (Math.abs(v[6] - x) < 0.00001
- && Math.abs(v[7] - y) < 0.00001)
- return 1;
- var txs = [],
- tys = [],
- sx = Curve.solveCubic(v, 0, x, txs),
- sy = Curve.solveCubic(v, 1, y, tys),
- tx, ty;
- for (var cx = 0; sx == -1 || cx < sx;) {
- if (sx == -1 || (tx = txs[cx++]) >= 0 && tx <= 1) {
- for (var cy = 0; sy == -1 || cy < sy;) {
- if (sy == -1 || (ty = tys[cy++]) >= 0 && ty <= 1) {
- if (sx == -1) tx = ty;
- else if (sy == -1) ty = tx;
- if (Math.abs(tx - ty) < 0.00001)
- return (tx + ty) * 0.5;
- }
- }
- if (sx == -1)
- break;
- }
- }
- return null;
- },
-
- getPart: function(v, from, to) {
- if (from > 0)
- v = Curve.subdivide(v, from)[1];
- if (to < 1)
- v = Curve.subdivide(v, (to - from) / (1 - from))[0];
- return v;
- },
-
- isLinear: function(v) {
- var isZero = Numerical.isZero;
- return isZero(v[0] - v[2]) && isZero(v[1] - v[3])
- && isZero(v[4] - v[6]) && isZero(v[5] - v[7]);
- },
-
- isFlatEnough: function(v, tolerance) {
- var p1x = v[0], p1y = v[1],
- c1x = v[2], c1y = v[3],
- c2x = v[4], c2y = v[5],
- p2x = v[6], p2y = v[7],
- ux = 3 * c1x - 2 * p1x - p2x,
- uy = 3 * c1y - 2 * p1y - p2y,
- vx = 3 * c2x - 2 * p2x - p1x,
- vy = 3 * c2y - 2 * p2y - p1y;
- return Math.max(ux * ux, vx * vx) + Math.max(uy * uy, vy * vy)
- < 10 * tolerance * tolerance;
- },
-
- getArea: function(v) {
- var p1x = v[0], p1y = v[1],
- c1x = v[2], c1y = v[3],
- c2x = v[4], c2y = v[5],
- p2x = v[6], p2y = v[7];
- return ( 3.0 * c1y * p1x - 1.5 * c1y * c2x
- - 1.5 * c1y * p2x - 3.0 * p1y * c1x
- - 1.5 * p1y * c2x - 0.5 * p1y * p2x
- + 1.5 * c2y * p1x + 1.5 * c2y * c1x
- - 3.0 * c2y * p2x + 0.5 * p2y * p1x
- + 1.5 * p2y * c1x + 3.0 * p2y * c2x) / 10;
- },
-
- getBounds: function(v) {
- var min = v.slice(0, 2),
- max = min.slice(),
- roots = [0, 0];
- for (var i = 0; i < 2; i++)
- Curve._addBounds(v[i], v[i + 2], v[i + 4], v[i + 6],
- i, 0, min, max, roots);
- return new Rectangle(min[0], min[1], max[0] - min[0], max[1] - min[1]);
- },
-
- _addBounds: function(v0, v1, v2, v3, coord, padding, min, max, roots) {
- function add(value, padding) {
- var left = value - padding,
- right = value + padding;
- if (left < min[coord])
- min[coord] = left;
- if (right > max[coord])
- max[coord] = right;
- }
- var a = 3 * (v1 - v2) - v0 + v3,
- b = 2 * (v0 + v2) - 4 * v1,
- c = v1 - v0,
- count = Numerical.solveQuadratic(a, b, c, roots),
- tMin = 0.00001,
- tMax = 1 - tMin;
- add(v3, 0);
- for (var i = 0; i < count; i++) {
- var t = roots[i],
- u = 1 - t;
- if (tMin < t && t < tMax)
- add(u * u * u * v0
- + 3 * u * u * t * v1
- + 3 * u * t * t * v2
- + t * t * t * v3,
- padding);
- }
- },
-
- _getWinding: function(v, prev, x, y, roots1, roots2) {
- var tolerance = 0.00001,
- abs = Math.abs;
-
- function getDirection(v) {
- var y0 = v[1],
- y1 = v[7],
- dir = y0 > y1 ? -1 : 1;
- return dir === 1 && (y < y0 || y > y1)
- || dir === -1 && (y < y1 || y > y0)
- ? 0
- : dir;
- }
-
- if (Curve.isLinear(v)) {
- var dir = getDirection(v);
- if (!dir)
- return 0;
- var cross = (v[6] - v[0]) * (y - v[1]) - (v[7] - v[1]) * (x - v[0]);
- return (cross < -tolerance ? -1 : 1) == dir ? 0 : dir;
- }
-
- var y0 = v[1],
- y1 = v[3],
- y2 = v[5],
- y3 = v[7];
- var a = 3 * (y1 - y2) - y0 + y3,
- b = 2 * (y0 + y2) - 4 * y1,
- c = y1 - y0;
- var count = Numerical.solveQuadratic(a, b, c, roots1, tolerance,
- 1 - tolerance),
- part,
- rest = v,
- t1 = roots1[0],
- winding = 0;
- for (var i = 0; i <= count; i++) {
- if (i === count) {
- part = rest;
- } else {
- var curves = Curve.subdivide(rest, t1);
- part = curves[0];
- rest = curves[1];
- t1 = roots1[i];
- t1 = (roots1[i + 1] - t1) / (1 - t1);
- }
- if (i > 0)
- part[3] = part[1];
- if (i < count)
- part[5] = rest[1];
- var dir = getDirection(part);
- if (!dir)
- continue;
- var t2,
- px;
- if (Curve.solveCubic(part, 1, y, roots2, -tolerance, 1 + -tolerance)
- === 1) {
- t2 = roots2[0];
- px = Curve.evaluate(part, t2, 0).x;
- } else {
- var mid = (part[1] + part[7]) / 2;
- t2 = y < mid && dir > 0 ? 0 : 1;
- if (t2 === 1 && y == part[7])
- continue;
- px = t2 === 0 ? part[0] : part[6];
- }
- var slope = Curve.evaluate(part, t2, 1).y,
- stationary = abs(slope) < tolerance || t2 < tolerance
- && Curve.evaluate(prev, 1, 1).y * slope < 0;
- if (x >= px + (stationary ? -tolerance : tolerance * dir)
- && !(stationary && (abs(t2) < tolerance
- && abs(x - part[0]) > tolerance
- || abs(t2 - 1) < tolerance
- && abs(x - part[6]) > tolerance))) {
- winding += stationary && abs(t2 - (dir > 0 ? 1 : 0)) < tolerance
- ? -dir : dir;
- }
- prev = part;
- }
- return winding;
- }
-}}, Base.each(['getBounds', 'getStrokeBounds', 'getHandleBounds', 'getRoughBounds'],
- function(name) {
- this[name] = function() {
- if (!this._bounds)
- this._bounds = {};
- var bounds = this._bounds[name];
- if (!bounds) {
- bounds = this._bounds[name] = Path[name]([this._segment1,
- this._segment2], false, this._path.getStyle());
- }
- return bounds.clone();
- };
- },
-{
-
-}), Base.each(['getPoint', 'getTangent', 'getNormal', 'getCurvature'],
- function(name, index) {
- this[name + 'At'] = function(offset, isParameter) {
- var values = this.getValues();
- return Curve.evaluate(values, isParameter
- ? offset : Curve.getParameterAt(values, offset, 0), index);
- };
- this[name] = function(parameter) {
- return Curve.evaluate(this.getValues(), parameter, index);
- };
- },
-{
- getParameterAt: function(offset, start) {
- return Curve.getParameterAt(this.getValues(), offset,
- start !== undefined ? start : offset < 0 ? 1 : 0);
- },
-
- getParameterOf: function(point) {
- point = Point.read(arguments);
- return Curve.getParameterOf(this.getValues(), point.x, point.y);
- },
-
- getLocationAt: function(offset, isParameter) {
- if (!isParameter)
- offset = this.getParameterAt(offset);
- return new CurveLocation(this, offset);
- },
-
- getLocationOf: function(point) {
- point = Point.read(arguments);
- var t = this.getParameterOf(point);
- return t != null ? new CurveLocation(this, t) : null;
- },
-
- getNearestLocation: function(point) {
- point = Point.read(arguments);
- var values = this.getValues(),
- count = 100,
- tolerance = Numerical.TOLERANCE,
- minDist = Infinity,
- minT = 0;
-
- function refine(t) {
- if (t >= 0 && t <= 1) {
- var dist = point.getDistance(
- Curve.evaluate(values, t, 0), true);
- if (dist < minDist) {
- minDist = dist;
- minT = t;
- return true;
- }
- }
- }
-
- for (var i = 0; i <= count; i++)
- refine(i / count);
-
- var step = 1 / (count * 2);
- while (step > tolerance) {
- if (!refine(minT - step) && !refine(minT + step))
- step /= 2;
- }
- var pt = Curve.evaluate(values, minT, 0);
- return new CurveLocation(this, minT, pt, null, null, null,
- point.getDistance(pt));
- },
-
- getNearestPoint: function(point) {
- point = Point.read(arguments);
- return this.getNearestLocation(point).getPoint();
- }
-
-}),
-new function() {
-
- function getLengthIntegrand(v) {
- var p1x = v[0], p1y = v[1],
- c1x = v[2], c1y = v[3],
- c2x = v[4], c2y = v[5],
- p2x = v[6], p2y = v[7],
-
- ax = 9 * (c1x - c2x) + 3 * (p2x - p1x),
- bx = 6 * (p1x + c2x) - 12 * c1x,
- cx = 3 * (c1x - p1x),
-
- ay = 9 * (c1y - c2y) + 3 * (p2y - p1y),
- by = 6 * (p1y + c2y) - 12 * c1y,
- cy = 3 * (c1y - p1y);
-
- return function(t) {
- var dx = (ax * t + bx) * t + cx,
- dy = (ay * t + by) * t + cy;
- return Math.sqrt(dx * dx + dy * dy);
- };
- }
-
- function getIterations(a, b) {
- return Math.max(2, Math.min(16, Math.ceil(Math.abs(b - a) * 32)));
- }
-
- return {
- statics: true,
-
- getLength: function(v, a, b) {
- if (a === undefined)
- a = 0;
- if (b === undefined)
- b = 1;
- var isZero = Numerical.isZero;
- if (isZero(v[0] - v[2]) && isZero(v[1] - v[3])
- && isZero(v[6] - v[4]) && isZero(v[7] - v[5])) {
- var dx = v[6] - v[0],
- dy = v[7] - v[1];
- return (b - a) * Math.sqrt(dx * dx + dy * dy);
- }
- var ds = getLengthIntegrand(v);
- return Numerical.integrate(ds, a, b, getIterations(a, b));
- },
-
- getParameterAt: function(v, offset, start) {
- if (offset === 0)
- return start;
- var forward = offset > 0,
- a = forward ? start : 0,
- b = forward ? 1 : start,
- offset = Math.abs(offset),
- ds = getLengthIntegrand(v),
- rangeLength = Numerical.integrate(ds, a, b,
- getIterations(a, b));
- if (offset >= rangeLength)
- return forward ? b : a;
- var guess = offset / rangeLength,
- length = 0;
- function f(t) {
- var count = getIterations(start, t);
- length += start < t
- ? Numerical.integrate(ds, start, t, count)
- : -Numerical.integrate(ds, t, start, count);
- start = t;
- return length - offset;
- }
- return Numerical.findRoot(f, ds,
- forward ? a + guess : b - guess,
- a, b, 16, 0.00001);
- }
- };
-}, new function() {
- function addLocation(locations, curve1, t1, point1, curve2, t2, point2) {
- var first = locations[0],
- last = locations[locations.length - 1];
- if ((!first || !point1.isClose(first._point, Numerical.EPSILON))
- && (!last || !point1.isClose(last._point, Numerical.EPSILON)))
- locations.push(
- new CurveLocation(curve1, t1, point1, curve2, t2, point2));
- }
-
- function addCurveIntersections(v1, v2, curve1, curve2, locations,
- range1, range2, recursion) {
- recursion = (recursion || 0) + 1;
- if (recursion > 20)
- return;
- range1 = range1 || [ 0, 1 ];
- range2 = range2 || [ 0, 1 ];
- var part1 = Curve.getPart(v1, range1[0], range1[1]),
- part2 = Curve.getPart(v2, range2[0], range2[1]),
- iteration = 0;
- while (iteration++ < 20) {
- var range,
- intersects1 = clipFatLine(part1, part2, range = range2.slice()),
- intersects2 = 0;
- if (intersects1 === 0)
- break;
- if (intersects1 > 0) {
- range2 = range;
- part2 = Curve.getPart(v2, range2[0], range2[1]);
- intersects2 = clipFatLine(part2, part1, range = range1.slice());
- if (intersects2 === 0)
- break;
- if (intersects1 > 0) {
- range1 = range;
- part1 = Curve.getPart(v1, range1[0], range1[1]);
- }
- }
- if (intersects1 < 0 || intersects2 < 0) {
- if (range1[1] - range1[0] > range2[1] - range2[0]) {
- var t = (range1[0] + range1[1]) / 2;
- addCurveIntersections(v1, v2, curve1, curve2, locations,
- [ range1[0], t ], range2, recursion);
- addCurveIntersections(v1, v2, curve1, curve2, locations,
- [ t, range1[1] ], range2, recursion);
- break;
- } else {
- var t = (range2[0] + range2[1]) / 2;
- addCurveIntersections(v1, v2, curve1, curve2, locations,
- range1, [ range2[0], t ], recursion);
- addCurveIntersections(v1, v2, curve1, curve2, locations,
- range1, [ t, range2[1] ], recursion);
- break;
- }
- }
- if (Math.abs(range1[1] - range1[0]) <= 0.00001 &&
- Math.abs(range2[1] - range2[0]) <= 0.00001) {
- var t1 = (range1[0] + range1[1]) / 2,
- t2 = (range2[0] + range2[1]) / 2;
- addLocation(locations,
- curve1, t1, Curve.evaluate(v1, t1, 0),
- curve2, t2, Curve.evaluate(v2, t2, 0));
- break;
- }
- }
- }
-
- function clipFatLine(v1, v2, range2) {
- var p0x = v1[0], p0y = v1[1], p1x = v1[2], p1y = v1[3],
- p2x = v1[4], p2y = v1[5], p3x = v1[6], p3y = v1[7],
- q0x = v2[0], q0y = v2[1], q1x = v2[2], q1y = v2[3],
- q2x = v2[4], q2y = v2[5], q3x = v2[6], q3y = v2[7],
- getSignedDistance = Line.getSignedDistance,
- d1 = getSignedDistance(p0x, p0y, p3x, p3y, p1x, p1y) || 0,
- d2 = getSignedDistance(p0x, p0y, p3x, p3y, p2x, p2y) || 0,
- factor = d1 * d2 > 0 ? 3 / 4 : 4 / 9,
- dmin = factor * Math.min(0, d1, d2),
- dmax = factor * Math.max(0, d1, d2),
- dq0 = getSignedDistance(p0x, p0y, p3x, p3y, q0x, q0y),
- dq1 = getSignedDistance(p0x, p0y, p3x, p3y, q1x, q1y),
- dq2 = getSignedDistance(p0x, p0y, p3x, p3y, q2x, q2y),
- dq3 = getSignedDistance(p0x, p0y, p3x, p3y, q3x, q3y);
- if (dmin > Math.max(dq0, dq1, dq2, dq3)
- || dmax < Math.min(dq0, dq1, dq2, dq3))
- return 0;
- var hull = getConvexHull(dq0, dq1, dq2, dq3),
- swap;
- if (dq3 < dq0) {
- swap = dmin;
- dmin = dmax;
- dmax = swap;
- }
- var tmaxdmin = -Infinity,
- tmin = Infinity,
- tmax = -Infinity;
- for (var i = 0, l = hull.length; i < l; i++) {
- var p1 = hull[i],
- p2 = hull[(i + 1) % l];
- if (p2[1] < p1[1]) {
- swap = p2;
- p2 = p1;
- p1 = swap;
- }
- var x1 = p1[0],
- y1 = p1[1],
- x2 = p2[0],
- y2 = p2[1];
- var inv = (y2 - y1) / (x2 - x1);
- if (dmin >= y1 && dmin <= y2) {
- var ixdx = x1 + (dmin - y1) / inv;
- if (ixdx < tmin)
- tmin = ixdx;
- if (ixdx > tmaxdmin)
- tmaxdmin = ixdx;
- }
- if (dmax >= y1 && dmax <= y2) {
- var ixdx = x1 + (dmax - y1) / inv;
- if (ixdx > tmax)
- tmax = ixdx;
- if (ixdx < tmin)
- tmin = 0;
- }
- }
- if (tmin !== Infinity && tmax !== -Infinity) {
- var min = Math.min(dmin, dmax),
- max = Math.max(dmin, dmax);
- if (dq3 > min && dq3 < max)
- tmax = 1;
- if (dq0 > min && dq0 < max)
- tmin = 0;
- if (tmaxdmin > tmax)
- tmax = 1;
- var v2tmin = range2[0],
- tdiff = range2[1] - v2tmin;
- range2[0] = v2tmin + tmin * tdiff;
- range2[1] = v2tmin + tmax * tdiff;
- if ((tdiff - (range2[1] - range2[0])) / tdiff >= 0.2)
- return 1;
- }
- if (Curve.getBounds(v1).touches(Curve.getBounds(v2)))
- return -1;
- return 0;
- }
-
- function getConvexHull(dq0, dq1, dq2, dq3) {
- var p0 = [ 0, dq0 ],
- p1 = [ 1 / 3, dq1 ],
- p2 = [ 2 / 3, dq2 ],
- p3 = [ 1, dq3 ],
- getSignedDistance = Line.getSignedDistance,
- dist1 = getSignedDistance(0, dq0, 1, dq3, 1 / 3, dq1),
- dist2 = getSignedDistance(0, dq0, 1, dq3, 2 / 3, dq2);
- if (dist1 * dist2 < 0) {
- return [ p0, p1, p3, p2 ];
- }
- var pmax, cross;
- if (Math.abs(dist1) > Math.abs(dist2)) {
- pmax = p1;
- cross = (dq3 - dq2 - (dq3 - dq0) / 3)
- * (2 * (dq3 - dq2) - dq3 + dq1) / 3;
- } else {
- pmax = p2;
- cross = (dq1 - dq0 + (dq0 - dq3) / 3)
- * (-2 * (dq0 - dq1) + dq0 - dq2) / 3;
- }
- return cross < 0
- ? [ p0, pmax, p3 ]
- : [ p0, p1, p2, p3 ];
- }
-
- function addCurveLineIntersections(v1, v2, curve1, curve2, locations) {
- var flip = Curve.isLinear(v1),
- vc = flip ? v2 : v1,
- vl = flip ? v1 : v2,
- lx1 = vl[0], ly1 = vl[1],
- lx2 = vl[6], ly2 = vl[7],
- ldx = lx2 - lx1,
- ldy = ly2 - ly1,
- angle = Math.atan2(-ldy, ldx),
- sin = Math.sin(angle),
- cos = Math.cos(angle),
- rlx2 = ldx * cos - ldy * sin,
- rvl = [0, 0, 0, 0, rlx2, 0, rlx2, 0],
- rvc = [];
- for(var i = 0; i < 8; i += 2) {
- var x = vc[i] - lx1,
- y = vc[i + 1] - ly1;
- rvc.push(
- x * cos - y * sin,
- y * cos + x * sin);
- }
- var roots = [],
- count = Curve.solveCubic(rvc, 1, 0, roots, 0, 1);
- for (var i = 0; i < count; i++) {
- var tc = roots[i],
- x = Curve.evaluate(rvc, tc, 0).x;
- if (x >= 0 && x <= rlx2) {
- var tl = Curve.getParameterOf(rvl, x, 0),
- t1 = flip ? tl : tc,
- t2 = flip ? tc : tl;
- addLocation(locations,
- curve1, t1, Curve.evaluate(v1, t1, 0),
- curve2, t2, Curve.evaluate(v2, t2, 0));
- }
- }
- }
-
- function addLineIntersection(v1, v2, curve1, curve2, locations) {
- var point = Line.intersect(
- v1[0], v1[1], v1[6], v1[7],
- v2[0], v2[1], v2[6], v2[7]);
- if (point)
- addLocation(locations, curve1, null, point, curve2);
- }
-
- return { statics: {
- getIntersections: function(v1, v2, curve1, curve2, locations) {
- var linear1 = Curve.isLinear(v1),
- linear2 = Curve.isLinear(v2),
- c1p1 = curve1.getPoint1(),
- c1p2 = curve1.getPoint2(),
- c2p1 = curve2.getPoint1(),
- c2p2 = curve2.getPoint2(),
- tolerance = 0.00001;
- if (c1p1.isClose(c2p1, tolerance))
- addLocation(locations, curve1, 0, c1p1, curve2, 0, c1p1);
- if (c1p1.isClose(c2p2, tolerance))
- addLocation(locations, curve1, 0, c1p1, curve2, 1, c1p1);
- (linear1 && linear2
- ? addLineIntersection
- : linear1 || linear2
- ? addCurveLineIntersections
- : addCurveIntersections)(v1, v2, curve1, curve2, locations);
- if (c1p2.isClose(c2p1, tolerance))
- addLocation(locations, curve1, 1, c1p2, curve2, 0, c1p2);
- if (c1p2.isClose(c2p2, tolerance))
- addLocation(locations, curve1, 1, c1p2, curve2, 1, c1p2);
- return locations;
- }
- }};
-});
-
-var CurveLocation = Base.extend({
- _class: 'CurveLocation',
- initialize: function CurveLocation(curve, parameter, point, _curve2,
- _parameter2, _point2, _distance) {
- this._id = CurveLocation._id = (CurveLocation._id || 0) + 1;
- this._curve = curve;
- this._segment1 = curve._segment1;
- this._segment2 = curve._segment2;
- this._parameter = parameter;
- this._point = point;
- this._curve2 = _curve2;
- this._parameter2 = _parameter2;
- this._point2 = _point2;
- this._distance = _distance;
- },
-
- getSegment: function() {
- if (!this._segment) {
- var curve = this.getCurve(),
- parameter = this.getParameter();
- if (parameter === 1) {
- this._segment = curve._segment2;
- } else if (parameter === 0 || arguments[0]) {
- this._segment = curve._segment1;
- } else if (parameter == null) {
- return null;
- } else {
- this._segment = curve.getLength(0, parameter)
- < curve.getLength(parameter, 1)
- ? curve._segment1
- : curve._segment2;
- }
- }
- return this._segment;
- },
-
- getCurve: function() {
- if (!this._curve || arguments[0]) {
- this._curve = this._segment1.getCurve();
- if (this._curve.getParameterOf(this._point) == null)
- this._curve = this._segment2.getPrevious().getCurve();
- }
- return this._curve;
- },
-
- getIntersection: function() {
- var intersection = this._intersection;
- if (!intersection && this._curve2) {
- var param = this._parameter2;
- this._intersection = intersection = new CurveLocation(
- this._curve2, param, this._point2 || this._point, this);
- intersection._intersection = this;
- }
- return intersection;
- },
-
- getPath: function() {
- var curve = this.getCurve();
- return curve && curve._path;
- },
-
- getIndex: function() {
- var curve = this.getCurve();
- return curve && curve.getIndex();
- },
-
- getOffset: function() {
- var path = this.getPath();
- return path && path._getOffset(this);
- },
-
- getCurveOffset: function() {
- var curve = this.getCurve(),
- parameter = this.getParameter();
- return parameter != null && curve && curve.getLength(0, parameter);
- },
-
- getParameter: function() {
- if ((this._parameter == null || arguments[0]) && this._point) {
- var curve = this.getCurve(arguments[0] && this._point);
- this._parameter = curve && curve.getParameterOf(this._point);
- }
- return this._parameter;
- },
-
- getPoint: function() {
- if ((!this._point || arguments[0]) && this._parameter != null) {
- var curve = this.getCurve();
- this._point = curve && curve.getPointAt(this._parameter, true);
- }
- return this._point;
- },
-
- getTangent: function() {
- var parameter = this.getParameter(),
- curve = this.getCurve();
- return parameter != null && curve && curve.getTangentAt(parameter, true);
- },
-
- getNormal: function() {
- var parameter = this.getParameter(),
- curve = this.getCurve();
- return parameter != null && curve && curve.getNormalAt(parameter, true);
- },
-
- getDistance: function() {
- return this._distance;
- },
-
- divide: function() {
- var curve = this.getCurve(true);
- return curve && curve.divide(this.getParameter(true), true);
- },
-
- split: function() {
- var curve = this.getCurve(true);
- return curve && curve.split(this.getParameter(true), true);
- },
-
- toString: function() {
- var parts = [],
- point = this.getPoint(),
- f = Formatter.instance;
- if (point)
- parts.push('point: ' + point);
- var index = this.getIndex();
- if (index != null)
- parts.push('index: ' + index);
- var parameter = this.getParameter();
- if (parameter != null)
- parts.push('parameter: ' + f.number(parameter));
- if (this._distance != null)
- parts.push('distance: ' + f.number(this._distance));
- return '{ ' + parts.join(', ') + ' }';
- }
-});
-
-var PathItem = Item.extend({
- _class: 'PathItem',
-
- initialize: function PathItem() {
- },
-
- getIntersections: function(path) {
- if (!this.getBounds().touches(path.getBounds()))
- return [];
- var locations = [],
- curves1 = this.getCurves(),
- curves2 = path.getCurves(),
- length2 = curves2.length,
- values2 = [];
- for (var i = 0; i < length2; i++)
- values2[i] = curves2[i].getValues();
- for (var i = 0, l = curves1.length; i < l; i++) {
- var curve1 = curves1[i],
- values1 = curve1.getValues();
- for (var j = 0; j < length2; j++)
- Curve.getIntersections(values1, values2[j], curve1, curves2[j],
- locations);
- }
- return locations;
- },
-
- setPathData: function(data) {
-
- var parts = data.match(/[mlhvcsqtaz][^mlhvcsqtaz]*/ig),
- coords,
- relative = false,
- control,
- current = new Point();
-
- function getCoord(index, coord, isCurrent) {
- var val = parseFloat(coords[index]);
- if (relative)
- val += current[coord];
- if (isCurrent)
- current[coord] = val;
- return val;
- }
-
- function getPoint(index, isCurrent) {
- return new Point(
- getCoord(index, 'x', isCurrent),
- getCoord(index + 1, 'y', isCurrent)
- );
- }
-
- this.clear();
-
- for (var i = 0, l = parts.length; i < l; i++) {
- var part = parts[i],
- cmd = part[0],
- lower = cmd.toLowerCase();
- coords = part.match(/[+-]?(?:\d*\.\d+|\d+\.?)(?:[eE][+-]?\d+)?/g);
- var length = coords && coords.length;
- relative = cmd === lower;
- switch (lower) {
- case 'm':
- case 'l':
- for (var j = 0; j < length; j += 2)
- this[j === 0 && lower === 'm' ? 'moveTo' : 'lineTo'](
- getPoint(j, true));
- control = current;
- break;
- case 'h':
- case 'v':
- var coord = lower == 'h' ? 'x' : 'y';
- for (var j = 0; j < length; j++) {
- getCoord(j, coord, true);
- this.lineTo(current);
- }
- control = current;
- break;
- case 'c':
- for (var j = 0; j < length; j += 6) {
- this.cubicCurveTo(
- getPoint(j),
- control = getPoint(j + 2),
- getPoint(j + 4, true));
- }
- break;
- case 's':
- for (var j = 0; j < length; j += 4) {
- this.cubicCurveTo(
- current.multiply(2).subtract(control),
- control = getPoint(j),
- getPoint(j + 2, true));
- }
- break;
- case 'q':
- for (var j = 0; j < length; j += 4) {
- this.quadraticCurveTo(
- control = getPoint(j),
- getPoint(j + 2, true));
- }
- break;
- case 't':
- for (var j = 0; j < length; j += 2) {
- this.quadraticCurveTo(
- control = current.multiply(2).subtract(control),
- getPoint(j, true));
- }
- break;
- case 'a':
- break;
- case 'z':
- this.closePath();
- break;
- }
- }
- },
-
- _canComposite: function() {
- return !(this.hasFill() && this.hasStroke());
- },
-
- _contains: function(point) {
- var winding = this._getWinding(point);
- return !!(this.getWindingRule() === 'evenodd' ? winding & 1 : winding);
- }
-
-});
-
-var Path = PathItem.extend({
- _class: 'Path',
- _serializeFields: {
- segments: [],
- closed: false
- },
-
- initialize: function Path(arg) {
- this._closed = false;
- this._segments = [];
- var segments = Array.isArray(arg)
- ? typeof arg[0] === 'object'
- ? arg
- : arguments
- : arg && (arg.point !== undefined && arg.size === undefined
- || arg.x !== undefined)
- ? arguments
- : null;
- this.setSegments(segments || []);
- this._initialize(!segments && arg);
- },
-
- _equals: function(item) {
- return Base.equals(this._segments, item._segments);
- },
-
- clone: function(insert) {
- var copy = this._clone(new Path({
- segments: this._segments,
- insert: false
- }), insert);
- copy._closed = this._closed;
- if (this._clockwise !== undefined)
- copy._clockwise = this._clockwise;
- return copy;
- },
-
- _changed: function _changed(flags) {
- _changed.base.call(this, flags);
- if (flags & 4) {
- delete this._length;
- delete this._clockwise;
- if (this._curves) {
- for (var i = 0, l = this._curves.length; i < l; i++)
- this._curves[i]._changed(5);
- }
- } else if (flags & 8) {
- delete this._bounds;
- }
- },
-
- getSegments: function() {
- return this._segments;
- },
-
- setSegments: function(segments) {
- var fullySelected = this.isFullySelected();
- this._segments.length = 0;
- this._selectedSegmentState = 0;
- delete this._curves;
- this._add(Segment.readAll(segments));
- if (fullySelected)
- this.setFullySelected(true);
- },
-
- getFirstSegment: function() {
- return this._segments[0];
- },
-
- getLastSegment: function() {
- return this._segments[this._segments.length - 1];
- },
-
- getCurves: function() {
- var curves = this._curves,
- segments = this._segments;
- if (!curves) {
- var length = this._countCurves();
- curves = this._curves = new Array(length);
- for (var i = 0; i < length; i++)
- curves[i] = new Curve(this, segments[i],
- segments[i + 1] || segments[0]);
- }
- return curves;
- },
-
- getFirstCurve: function() {
- return this.getCurves()[0];
- },
-
- getLastCurve: function() {
- var curves = this.getCurves();
- return curves[curves.length - 1];
- },
-
- getPathData: function() {
- var segments = this._segments,
- precision = arguments[0],
- f = Formatter.instance,
- parts = [];
-
- function addCurve(seg1, seg2, skipLine) {
- var point1 = seg1._point,
- point2 = seg2._point,
- handle1 = seg1._handleOut,
- handle2 = seg2._handleIn;
- if (handle1.isZero() && handle2.isZero()) {
- if (!skipLine) {
- parts.push('L' + f.point(point2, precision));
- }
- } else {
- var end = point2.subtract(point1);
- parts.push('c' + f.point(handle1, precision)
- + ' ' + f.point(end.add(handle2), precision)
- + ' ' + f.point(end, precision));
- }
- }
-
- if (segments.length === 0)
- return '';
- parts.push('M' + f.point(segments[0]._point));
- for (var i = 0, l = segments.length - 1; i < l; i++)
- addCurve(segments[i], segments[i + 1], false);
- if (this._closed) {
- addCurve(segments[segments.length - 1], segments[0], true);
- parts.push('z');
- }
- return parts.join('');
- },
-
- isClosed: function() {
- return this._closed;
- },
-
- setClosed: function(closed) {
- if (this._closed != (closed = !!closed)) {
- this._closed = closed;
- if (this._curves) {
- var length = this._curves.length = this._countCurves();
- if (closed)
- this._curves[length - 1] = new Curve(this,
- this._segments[length - 1], this._segments[0]);
- }
- this._changed(5);
- }
- },
-
- isEmpty: function() {
- return this._segments.length === 0;
- },
-
- isPolygon: function() {
- for (var i = 0, l = this._segments.length; i < l; i++) {
- if (!this._segments[i].isLinear())
- return false;
- }
- return true;
- },
-
- _applyMatrix: function(matrix) {
- var coords = new Array(6);
- for (var i = 0, l = this._segments.length; i < l; i++)
- this._segments[i]._transformCoordinates(matrix, coords, true);
- return true;
- },
-
- _add: function(segs, index) {
- var segments = this._segments,
- curves = this._curves,
- amount = segs.length,
- append = index == null,
- index = append ? segments.length : index;
- for (var i = 0; i < amount; i++) {
- var segment = segs[i];
- if (segment._path)
- segment = segs[i] = segment.clone();
- segment._path = this;
- segment._index = index + i;
- if (segment._selectionState)
- this._updateSelection(segment, 0, segment._selectionState);
- }
- if (append) {
- segments.push.apply(segments, segs);
- } else {
- segments.splice.apply(segments, [index, 0].concat(segs));
- for (var i = index + amount, l = segments.length; i < l; i++)
- segments[i]._index = i;
- }
- if (curves || segs._curves) {
- if (!curves)
- curves = this._curves = [];
- var from = index > 0 ? index - 1 : index,
- start = from,
- to = Math.min(from + amount, this._countCurves());
- if (segs._curves) {
- curves.splice.apply(curves, [from, 0].concat(segs._curves));
- start += segs._curves.length;
- }
- for (var i = start; i < to; i++)
- curves.splice(i, 0, new Curve(this, null, null));
- this._adjustCurves(from, to);
- }
- this._changed(5);
- return segs;
- },
-
- _adjustCurves: function(from, to) {
- var segments = this._segments,
- curves = this._curves,
- curve;
- for (var i = from; i < to; i++) {
- curve = curves[i];
- curve._path = this;
- curve._segment1 = segments[i];
- curve._segment2 = segments[i + 1] || segments[0];
- }
- if (curve = curves[this._closed && from === 0 ? segments.length - 1
- : from - 1])
- curve._segment2 = segments[from] || segments[0];
- if (curve = curves[to])
- curve._segment1 = segments[to];
- },
-
- _countCurves: function() {
- var length = this._segments.length;
- return !this._closed && length > 0 ? length - 1 : length;
- },
-
- add: function(segment1 ) {
- return arguments.length > 1 && typeof segment1 !== 'number'
- ? this._add(Segment.readAll(arguments))
- : this._add([ Segment.read(arguments) ])[0];
- },
-
- insert: function(index, segment1 ) {
- return arguments.length > 2 && typeof segment1 !== 'number'
- ? this._add(Segment.readAll(arguments, 1), index)
- : this._add([ Segment.read(arguments, 1) ], index)[0];
- },
-
- addSegment: function() {
- return this._add([ Segment.read(arguments) ])[0];
- },
-
- insertSegment: function(index ) {
- return this._add([ Segment.read(arguments, 1) ], index)[0];
- },
-
- addSegments: function(segments) {
- return this._add(Segment.readAll(segments));
- },
-
- insertSegments: function(index, segments) {
- return this._add(Segment.readAll(segments), index);
- },
-
- removeSegment: function(index) {
- return this.removeSegments(index, index + 1)[0] || null;
- },
-
- removeSegments: function(from, to) {
- from = from || 0;
- to = Base.pick(to, this._segments.length);
- var segments = this._segments,
- curves = this._curves,
- count = segments.length,
- removed = segments.splice(from, to - from),
- amount = removed.length;
- if (!amount)
- return removed;
- for (var i = 0; i < amount; i++) {
- var segment = removed[i];
- if (segment._selectionState)
- this._updateSelection(segment, segment._selectionState, 0);
- delete segment._index;
- delete segment._path;
- }
- for (var i = from, l = segments.length; i < l; i++)
- segments[i]._index = i;
- if (curves) {
- var index = from > 0 && to === count + (this._closed ? 1 : 0)
- ? from - 1
- : from,
- curves = curves.splice(index, amount);
- if (arguments[2])
- removed._curves = curves.slice(1);
- this._adjustCurves(index, index);
- }
- this._changed(5);
- return removed;
- },
-
- clear: '#removeSegments',
-
- isFullySelected: function() {
- var length = this._segments.length;
- return this._selected && length > 0 && this._selectedSegmentState
- === length * 4;
- },
-
- setFullySelected: function(selected) {
- if (selected)
- this._selectSegments(true);
- this.setSelected(selected);
- },
-
- setSelected: function setSelected(selected) {
- if (!selected)
- this._selectSegments(false);
- setSelected.base.call(this, selected);
- },
-
- _selectSegments: function(selected) {
- var length = this._segments.length;
- this._selectedSegmentState = selected
- ? length * 4 : 0;
- for (var i = 0; i < length; i++)
- this._segments[i]._selectionState = selected
- ? 4 : 0;
- },
-
- _updateSelection: function(segment, oldState, newState) {
- segment._selectionState = newState;
- var total = this._selectedSegmentState += newState - oldState;
- if (total > 0)
- this.setSelected(true);
- },
-
- flatten: function(maxDistance) {
- var flattener = new PathFlattener(this),
- pos = 0,
- step = flattener.length / Math.ceil(flattener.length / maxDistance),
- end = flattener.length + (this._closed ? -step : step) / 2;
- var segments = [];
- while (pos <= end) {
- segments.push(new Segment(flattener.evaluate(pos, 0)));
- pos += step;
- }
- this.setSegments(segments);
- },
-
- simplify: function(tolerance) {
- if (this._segments.length > 2) {
- var fitter = new PathFitter(this, tolerance || 2.5);
- this.setSegments(fitter.fit());
- }
- },
-
- split: function(index, parameter) {
- if (parameter === null)
- return;
- if (arguments.length === 1) {
- var arg = index;
- if (typeof arg === 'number')
- arg = this.getLocationAt(arg);
- index = arg.index;
- parameter = arg.parameter;
- }
- if (parameter >= 1) {
- index++;
- parameter--;
- }
- var curves = this.getCurves();
- if (index >= 0 && index < curves.length) {
- if (parameter > 0) {
- curves[index++].divide(parameter, true);
- }
- var segs = this.removeSegments(index, this._segments.length, true),
- path;
- if (this._closed) {
- this.setClosed(false);
- path = this;
- } else if (index > 0) {
- path = this._clone(new Path().insertAbove(this, true));
- }
- path._add(segs, 0);
- this.addSegment(segs[0]);
- return path;
- }
- return null;
- },
-
- isClockwise: function() {
- if (this._clockwise !== undefined)
- return this._clockwise;
- return Path.isClockwise(this._segments);
- },
-
- setClockwise: function(clockwise) {
- if (this.isClockwise() != (clockwise = !!clockwise))
- this.reverse();
- this._clockwise = clockwise;
- },
-
- reverse: function() {
- this._segments.reverse();
- for (var i = 0, l = this._segments.length; i < l; i++) {
- var segment = this._segments[i];
- var handleIn = segment._handleIn;
- segment._handleIn = segment._handleOut;
- segment._handleOut = handleIn;
- segment._index = i;
- }
- delete this._curves;
- if (this._clockwise !== undefined)
- this._clockwise = !this._clockwise;
- },
-
- join: function(path) {
- if (path) {
- var segments = path._segments,
- last1 = this.getLastSegment(),
- last2 = path.getLastSegment();
- if (last1._point.equals(last2._point))
- path.reverse();
- var first1,
- first2 = path.getFirstSegment();
- if (last1._point.equals(first2._point)) {
- last1.setHandleOut(first2._handleOut);
- this._add(segments.slice(1));
- } else {
- first1 = this.getFirstSegment();
- if (first1._point.equals(first2._point))
- path.reverse();
- last2 = path.getLastSegment();
- if (first1._point.equals(last2._point)) {
- first1.setHandleIn(last2._handleIn);
- this._add(segments.slice(0, segments.length - 1), 0);
- } else {
- this._add(segments.slice());
- }
- }
- if (path.closed)
- this._add([segments[0]]);
- path.remove();
- first1 = this.getFirstSegment();
- last1 = this.getLastSegment();
- if (last1._point.equals(first1._point)) {
- first1.setHandleIn(last1._handleIn);
- last1.remove();
- this.setClosed(true);
- }
- this._changed(5);
- return true;
- }
- return false;
- },
-
- getLength: function() {
- if (this._length == null) {
- var curves = this.getCurves();
- this._length = 0;
- for (var i = 0, l = curves.length; i < l; i++)
- this._length += curves[i].getLength();
- }
- return this._length;
- },
-
- getArea: function() {
- var curves = this.getCurves();
- var area = 0;
- for (var i = 0, l = curves.length; i < l; i++)
- area += curves[i].getArea();
- return area;
- },
-
- _getOffset: function(location) {
- var index = location && location.getIndex();
- if (index != null) {
- var curves = this.getCurves(),
- offset = 0;
- for (var i = 0; i < index; i++)
- offset += curves[i].getLength();
- var curve = curves[index];
- return offset + curve.getLength(0, location.getParameter());
- }
- return null;
- },
-
- getLocationOf: function(point) {
- point = Point.read(arguments);
- var curves = this.getCurves();
- for (var i = 0, l = curves.length; i < l; i++) {
- var loc = curves[i].getLocationOf(point);
- if (loc)
- return loc;
- }
- return null;
- },
-
- getLocationAt: function(offset, isParameter) {
- var curves = this.getCurves(),
- length = 0;
- if (isParameter) {
- var index = ~~offset;
- return curves[index].getLocationAt(offset - index, true);
- }
- for (var i = 0, l = curves.length; i < l; i++) {
- var start = length,
- curve = curves[i];
- length += curve.getLength();
- if (length >= offset) {
- return curve.getLocationAt(offset - start);
- }
- }
- if (offset <= this.getLength())
- return new CurveLocation(curves[curves.length - 1], 1);
- return null;
- },
-
- getPointAt: function(offset, isParameter) {
- var loc = this.getLocationAt(offset, isParameter);
- return loc && loc.getPoint();
- },
-
- getTangentAt: function(offset, isParameter) {
- var loc = this.getLocationAt(offset, isParameter);
- return loc && loc.getTangent();
- },
-
- getNormalAt: function(offset, isParameter) {
- var loc = this.getLocationAt(offset, isParameter);
- return loc && loc.getNormal();
- },
-
- getNearestLocation: function(point) {
- point = Point.read(arguments);
- var curves = this.getCurves(),
- minDist = Infinity,
- minLoc = null;
- for (var i = 0, l = curves.length; i < l; i++) {
- var loc = curves[i].getNearestLocation(point);
- if (loc._distance < minDist) {
- minDist = loc._distance;
- minLoc = loc;
- }
- }
- return minLoc;
- },
-
- getNearestPoint: function(point) {
- point = Point.read(arguments);
- return this.getNearestLocation(point).getPoint();
- },
-
- getStyle: function() {
- var parent = this._parent;
- return (parent && parent._type === 'compound-path'
- ? parent : this)._style;
- },
-
- toShape: function(insert) {
- if (!this._closed)
- return null;
-
- var segments = this._segments,
- type,
- size,
- radius,
- topCenter;
-
- function isColinear(i, j) {
- return segments[i].isColinear(segments[j]);
- }
-
- function isOrthogonal(i) {
- return segments[i].isOrthogonal();
- }
-
- function isArc(i) {
- return segments[i].isArc();
- }
-
- function getDistance(i, j) {
- return segments[i]._point.getDistance(segments[j]._point);
- }
-
- if (this.isPolygon() && segments.length === 4
- && isColinear(0, 2) && isColinear(1, 3) && isOrthogonal(1)) {
- type = Shape.Rectangle;
- size = new Size(getDistance(0, 3), getDistance(0, 1));
- topCenter = segments[1]._point.add(segments[2]._point).divide(2);
- } else if (segments.length === 8 && isArc(0) && isArc(2) && isArc(4)
- && isArc(6) && isColinear(1, 5) && isColinear(3, 7)) {
- type = Shape.Rectangle;
- size = new Size(getDistance(1, 6), getDistance(0, 3));
- radius = size.subtract(new Size(getDistance(0, 7),
- getDistance(1, 2))).divide(2);
- topCenter = segments[3]._point.add(segments[4]._point).divide(2);
- } else if (segments.length === 4
- && isArc(0) && isArc(1) && isArc(2) && isArc(3)) {
- if (Numerical.isZero(getDistance(0, 2) - getDistance(1, 3))) {
- type = Shape.Circle;
- radius = getDistance(0, 2) / 2;
- } else {
- type = Shape.Ellipse;
- radius = new Size(getDistance(2, 0) / 2, getDistance(3, 1) / 2);
- }
- topCenter = segments[1]._point;
- }
-
- if (type) {
- var center = this.getPosition(true),
- shape = new type({
- center: center,
- size: size,
- radius: radius,
- insert: false
- });
- shape.rotate(topCenter.subtract(center).getAngle() + 90);
- shape.setStyle(this._style);
- if (insert || insert === undefined)
- shape.insertAbove(this);
- return shape;
- }
- return null;
- },
-
- _getWinding: function(point) {
- var closed = this._closed;
- if (!closed && !this.hasFill()
- || !this._getBounds('getRoughBounds')._containsPoint(point))
- return 0;
- var curves = this.getCurves(),
- segments = this._segments,
- winding = 0,
- roots1 = [],
- roots2 = [],
- last = (closed
- ? curves[curves.length - 1]
- : new Curve(segments[segments.length - 1]._point,
- segments[0]._point)).getValues(),
- previous = last;
- for (var i = 0, l = curves.length; i < l; i++) {
- var curve = curves[i].getValues(),
- x = curve[0],
- y = curve[1];
- if (!(x === curve[2] && y === curve[3] && x === curve[4]
- && y === curve[5] && x === curve[6] && y === curve[7])) {
- winding += Curve._getWinding(curve, previous, point.x, point.y,
- roots1, roots2);
- previous = curve;
- }
- }
- if (!closed) {
- winding += Curve._getWinding(last, previous, point.x, point.y,
- roots1, roots2);
- }
- return winding;
- },
-
- _hitTest: function(point, options) {
- var style = this.getStyle(),
- segments = this._segments,
- closed = this._closed,
- tolerance = options.tolerance,
- radius = 0, join, cap, miterLimit,
- that = this,
- area, loc, res;
-
- if (options.stroke) {
- radius = style.getStrokeWidth() / 2;
- if (radius > 0) {
- join = style.getStrokeJoin();
- cap = style.getStrokeCap();
- miterLimit = radius * style.getMiterLimit();
- } else {
- join = cap = 'round';
- }
- radius += tolerance;
- }
-
- function checkPoint(seg, pt, name) {
- if (point.getDistance(pt) < tolerance)
- return new HitResult(name, that, { segment: seg, point: pt });
- }
-
- function checkSegmentPoints(seg, ends) {
- var pt = seg._point;
- return (ends || options.segments) && checkPoint(seg, pt, 'segment')
- || (!ends && options.handles) && (
- checkPoint(seg, pt.add(seg._handleIn), 'handle-in') ||
- checkPoint(seg, pt.add(seg._handleOut), 'handle-out'));
- }
-
- function addAreaPoint(point) {
- area.push(point);
- }
-
- function getAreaCurve(index) {
- var p1 = area[index],
- p2 = area[(index + 1) % area.length];
- return [p1.x, p1.y, p1.x, p1.y, p2.x, p2.y, p2.x ,p2.y];
- }
-
- function isInArea(point) {
- var length = area.length,
- previous = getAreaCurve(length - 1),
- roots1 = [],
- roots2 = [],
- winding = 0;
- for (var i = 0; i < length; i++) {
- var curve = getAreaCurve(i);
- winding += Curve._getWinding(curve, previous, point.x, point.y,
- roots1, roots2);
- previous = curve;
- }
- return !!winding;
- }
-
- function checkSegmentStroke(segment) {
- if (join !== 'round' || cap !== 'round') {
- area = [];
- if (closed || segment._index > 0
- && segment._index < segments.length - 1) {
- if (join !== 'round' && (segment._handleIn.isZero()
- || segment._handleOut.isZero()))
- Path._addSquareJoin(segment, join, radius, miterLimit,
- addAreaPoint, true);
- } else if (cap !== 'round') {
- Path._addSquareCap(segment, cap, radius, addAreaPoint, true);
- }
- if (area.length > 0)
- return isInArea(point);
- }
- return point.getDistance(segment._point) <= radius;
- }
-
- if (options.ends && !options.segments && !closed) {
- if (res = checkSegmentPoints(segments[0], true)
- || checkSegmentPoints(segments[segments.length - 1], true))
- return res;
- } else if (options.segments || options.handles) {
- for (var i = 0, l = segments.length; i < l; i++) {
- if (res = checkSegmentPoints(segments[i]))
- return res;
- }
- }
- if (radius > 0) {
- loc = this.getNearestLocation(point);
- if (loc) {
- var parameter = loc.getParameter();
- if (parameter === 0 || parameter === 1) {
- if (!checkSegmentStroke(loc.getSegment()))
- loc = null;
- } else if (loc._distance > radius) {
- loc = null;
- }
- }
- if (!loc && join === 'miter') {
- for (var i = 0, l = segments.length; i < l; i++) {
- var segment = segments[i];
- if (point.getDistance(segment._point) <= miterLimit
- && checkSegmentStroke(segment)) {
- loc = segment.getLocation();
- break;
- }
- }
- }
- }
- return !loc && options.fill && this.hasFill() && this._contains(point)
- ? new HitResult('fill', this)
- : loc
- ? new HitResult('stroke', this, { location: loc })
- : null;
- }
-
-}, new function() {
-
- function drawHandles(ctx, segments, matrix, size) {
- var half = size / 2;
-
- function drawHandle(index) {
- var hX = coords[index],
- hY = coords[index + 1];
- if (pX != hX || pY != hY) {
- ctx.beginPath();
- ctx.moveTo(pX, pY);
- ctx.lineTo(hX, hY);
- ctx.stroke();
- ctx.beginPath();
- ctx.arc(hX, hY, half, 0, Math.PI * 2, true);
- ctx.fill();
- }
- }
-
- var coords = new Array(6);
- for (var i = 0, l = segments.length; i < l; i++) {
- var segment = segments[i];
- segment._transformCoordinates(matrix, coords, false);
- var state = segment._selectionState,
- selected = state & 4,
- pX = coords[0],
- pY = coords[1];
- if (selected || (state & 1))
- drawHandle(2);
- if (selected || (state & 2))
- drawHandle(4);
- ctx.save();
- ctx.beginPath();
- ctx.rect(pX - half, pY - half, size, size);
- ctx.fill();
- if (!selected) {
- ctx.beginPath();
- ctx.rect(pX - half + 1, pY - half + 1, size - 2, size - 2);
- ctx.fillStyle = '#ffffff';
- ctx.fill();
- }
- ctx.restore();
- }
- }
-
- function drawSegments(ctx, path, matrix) {
- var segments = path._segments,
- length = segments.length,
- coords = new Array(6),
- first = true,
- curX, curY,
- prevX, prevY,
- inX, inY,
- outX, outY;
-
- function drawSegment(i) {
- var segment = segments[i];
- if (matrix) {
- segment._transformCoordinates(matrix, coords, false);
- curX = coords[0];
- curY = coords[1];
- } else {
- var point = segment._point;
- curX = point._x;
- curY = point._y;
- }
- if (first) {
- ctx.moveTo(curX, curY);
- first = false;
- } else {
- if (matrix) {
- inX = coords[2];
- inY = coords[3];
- } else {
- var handle = segment._handleIn;
- inX = curX + handle._x;
- inY = curY + handle._y;
- }
- if (inX == curX && inY == curY && outX == prevX && outY == prevY) {
- ctx.lineTo(curX, curY);
- } else {
- ctx.bezierCurveTo(outX, outY, inX, inY, curX, curY);
- }
- }
- prevX = curX;
- prevY = curY;
- if (matrix) {
- outX = coords[4];
- outY = coords[5];
- } else {
- var handle = segment._handleOut;
- outX = prevX + handle._x;
- outY = prevY + handle._y;
- }
- }
-
- for (var i = 0; i < length; i++)
- drawSegment(i);
- if (path._closed && length > 1)
- drawSegment(0);
- }
-
- return {
- _draw: function(ctx, param) {
- var clip = param.clip,
- compound = param.compound;
- if (!compound)
- ctx.beginPath();
-
- var style = this.getStyle(),
- hasFill = style.hasFill(),
- hasStroke = style.hasStroke(),
- dashArray = style.getDashArray(),
- dashLength = !paper.support.nativeDash && hasStroke
- && dashArray && dashArray.length;
-
- function getOffset(i) {
- return dashArray[((i % dashLength) + dashLength) % dashLength];
- }
-
- if (hasFill || hasStroke && !dashLength || compound || clip)
- drawSegments(ctx, this);
- if (this._closed)
- ctx.closePath();
-
- if (!clip && !compound && (hasFill || hasStroke)) {
- this._setStyles(ctx);
- if (hasFill) {
- ctx.fill(style.getWindingRule());
- ctx.shadowColor = 'rgba(0,0,0,0)';
- }
- if (hasStroke) {
- if (dashLength) {
- ctx.beginPath();
- var flattener = new PathFlattener(this),
- length = flattener.length,
- from = -style.getDashOffset(), to,
- i = 0;
- from = from % length;
- while (from > 0) {
- from -= getOffset(i--) + getOffset(i--);
- }
- while (from < length) {
- to = from + getOffset(i++);
- if (from > 0 || to > 0)
- flattener.drawPart(ctx,
- Math.max(from, 0), Math.max(to, 0));
- from = to + getOffset(i++);
- }
- }
- ctx.stroke();
- }
- }
- },
-
- _drawSelected: function(ctx, matrix) {
- ctx.beginPath();
- drawSegments(ctx, this, matrix);
- ctx.stroke();
- drawHandles(ctx, this._segments, matrix,
- this._project.options.handleSize || 4);
- }
- };
-}, new function() {
-
- function getFirstControlPoints(rhs) {
- var n = rhs.length,
- x = [],
- tmp = [],
- b = 2;
- x[0] = rhs[0] / b;
- for (var i = 1; i < n; i++) {
- tmp[i] = 1 / b;
- b = (i < n - 1 ? 4 : 2) - tmp[i];
- x[i] = (rhs[i] - x[i - 1]) / b;
- }
- for (var i = 1; i < n; i++) {
- x[n - i - 1] -= tmp[n - i] * x[n - i];
- }
- return x;
- }
-
- return {
- smooth: function() {
- var segments = this._segments,
- size = segments.length,
- closed = this._closed,
- n = size,
- overlap = 0;
- if (size <= 2)
- return;
- if (closed) {
- overlap = Math.min(size, 4);
- n += Math.min(size, overlap) * 2;
- }
- var knots = [];
- for (var i = 0; i < size; i++)
- knots[i + overlap] = segments[i]._point;
- if (closed) {
- for (var i = 0; i < overlap; i++) {
- knots[i] = segments[i + size - overlap]._point;
- knots[i + size + overlap] = segments[i]._point;
- }
- } else {
- n--;
- }
- var rhs = [];
-
- for (var i = 1; i < n - 1; i++)
- rhs[i] = 4 * knots[i]._x + 2 * knots[i + 1]._x;
- rhs[0] = knots[0]._x + 2 * knots[1]._x;
- rhs[n - 1] = 3 * knots[n - 1]._x;
- var x = getFirstControlPoints(rhs);
-
- for (var i = 1; i < n - 1; i++)
- rhs[i] = 4 * knots[i]._y + 2 * knots[i + 1]._y;
- rhs[0] = knots[0]._y + 2 * knots[1]._y;
- rhs[n - 1] = 3 * knots[n - 1]._y;
- var y = getFirstControlPoints(rhs);
-
- if (closed) {
- for (var i = 0, j = size; i < overlap; i++, j++) {
- var f1 = i / overlap,
- f2 = 1 - f1,
- ie = i + overlap,
- je = j + overlap;
- x[j] = x[i] * f1 + x[j] * f2;
- y[j] = y[i] * f1 + y[j] * f2;
- x[je] = x[ie] * f2 + x[je] * f1;
- y[je] = y[ie] * f2 + y[je] * f1;
- }
- n--;
- }
- var handleIn = null;
- for (var i = overlap; i <= n - overlap; i++) {
- var segment = segments[i - overlap];
- if (handleIn)
- segment.setHandleIn(handleIn.subtract(segment._point));
- if (i < n) {
- segment.setHandleOut(
- new Point(x[i], y[i]).subtract(segment._point));
- handleIn = i < n - 1
- ? new Point(
- 2 * knots[i + 1]._x - x[i + 1],
- 2 * knots[i + 1]._y - y[i + 1])
- : new Point(
- (knots[n]._x + x[n - 1]) / 2,
- (knots[n]._y + y[n - 1]) / 2);
- }
- }
- if (closed && handleIn) {
- var segment = this._segments[0];
- segment.setHandleIn(handleIn.subtract(segment._point));
- }
- }
- };
-}, new function() {
- function getCurrentSegment(that) {
- var segments = that._segments;
- if (segments.length == 0)
- throw new Error('Use a moveTo() command first');
- return segments[segments.length - 1];
- }
-
- return {
- moveTo: function() {
- if (this._segments.length === 1)
- this.removeSegment(0);
- if (!this._segments.length)
- this._add([ new Segment(Point.read(arguments)) ]);
- },
-
- moveBy: function() {
- throw new Error('moveBy() is unsupported on Path items.');
- },
-
- lineTo: function() {
- this._add([ new Segment(Point.read(arguments)) ]);
- },
-
- cubicCurveTo: function() {
- var handle1 = Point.read(arguments),
- handle2 = Point.read(arguments),
- to = Point.read(arguments),
- current = getCurrentSegment(this);
- current.setHandleOut(handle1.subtract(current._point));
- this._add([ new Segment(to, handle2.subtract(to)) ]);
- },
-
- quadraticCurveTo: function() {
- var handle = Point.read(arguments),
- to = Point.read(arguments),
- current = getCurrentSegment(this)._point;
- this.cubicCurveTo(
- handle.add(current.subtract(handle).multiply(1 / 3)),
- handle.add(to.subtract(handle).multiply(1 / 3)),
- to
- );
- },
-
- curveTo: function() {
- var through = Point.read(arguments),
- to = Point.read(arguments),
- t = Base.pick(Base.read(arguments), 0.5),
- t1 = 1 - t,
- current = getCurrentSegment(this)._point,
- handle = through.subtract(current.multiply(t1 * t1))
- .subtract(to.multiply(t * t)).divide(2 * t * t1);
- if (handle.isNaN())
- throw new Error(
- 'Cannot put a curve through points with parameter = ' + t);
- this.quadraticCurveTo(handle, to);
- },
-
- arcTo: function() {
- var current = getCurrentSegment(this),
- from = current._point,
- through,
- to = Point.read(arguments),
- clockwise = Base.pick(Base.peek(arguments), true);
- if (typeof clockwise === 'boolean') {
- var middle = from.add(to).divide(2),
- through = middle.add(middle.subtract(from).rotate(
- clockwise ? -90 : 90));
- } else {
- through = to;
- to = Point.read(arguments);
- }
- var l1 = new Line(from.add(through).divide(2),
- through.subtract(from).rotate(90), true),
- l2 = new Line(through.add(to).divide(2),
- to.subtract(through).rotate(90), true),
- center = l1.intersect(l2, true),
- line = new Line(from, to),
- throughSide = line.getSide(through);
- if (!center) {
- if (!throughSide)
- return this.lineTo(to);
- throw new Error('Cannot put an arc through the given points: '
- + [from, through, to]);
- }
- var vector = from.subtract(center),
- extent = vector.getDirectedAngle(to.subtract(center)),
- centerSide = line.getSide(center);
- if (centerSide == 0) {
- extent = throughSide * Math.abs(extent);
- } else if (throughSide == centerSide) {
- extent -= 360 * (extent < 0 ? -1 : 1);
- }
- var ext = Math.abs(extent),
- count = ext >= 360 ? 4 : Math.ceil(ext / 90),
- inc = extent / count,
- half = inc * Math.PI / 360,
- z = 4 / 3 * Math.sin(half) / (1 + Math.cos(half)),
- segments = [];
- for (var i = 0; i <= count; i++) {
- var pt = i < count ? center.add(vector) : to;
- var out = i < count ? vector.rotate(90).multiply(z) : null;
- if (i == 0) {
- current.setHandleOut(out);
- } else {
- segments.push(
- new Segment(pt, vector.rotate(-90).multiply(z), out));
- }
- vector = vector.rotate(inc);
- }
- this._add(segments);
- },
-
- lineBy: function() {
- var to = Point.read(arguments),
- current = getCurrentSegment(this)._point;
- this.lineTo(current.add(to));
- },
-
- curveBy: function() {
- var through = Point.read(arguments),
- to = Point.read(arguments),
- parameter = Base.read(arguments),
- current = getCurrentSegment(this)._point;
- this.curveTo(current.add(through), current.add(to), parameter);
- },
-
- cubicCurveBy: function() {
- var handle1 = Point.read(arguments),
- handle2 = Point.read(arguments),
- to = Point.read(arguments),
- current = getCurrentSegment(this)._point;
- this.cubicCurveTo(current.add(handle1), current.add(handle2),
- current.add(to));
- },
-
- quadraticCurveBy: function() {
- var handle = Point.read(arguments),
- to = Point.read(arguments),
- current = getCurrentSegment(this)._point;
- this.quadraticCurveTo(current.add(handle), current.add(to));
- },
-
- arcBy: function() {
- var current = getCurrentSegment(this)._point,
- point = current.add(Point.read(arguments)),
- clockwise = Base.pick(Base.peek(arguments), true);
- if (typeof clockwise === 'boolean') {
- this.arcTo(point, clockwise);
- } else {
- this.arcTo(point, current.add(Point.read(arguments)));
- }
- },
-
- closePath: function() {
- var first = this.getFirstSegment(),
- last = this.getLastSegment();
- if (first._point.equals(last._point)) {
- first.setHandleIn(last._handleIn);
- last.remove();
- }
- this.setClosed(true);
- }
- };
-}, {
-
- _getBounds: function(getter, matrix) {
- return Path[getter](this._segments, this._closed, this.getStyle(),
- matrix);
- },
-
-statics: {
- isClockwise: function(segments) {
- var sum = 0;
- for (var i = 0, l = segments.length; i < l; i++) {
- var v = Curve.getValues(
- segments[i], segments[i + 1 < l ? i + 1 : 0]);
- for (var j = 2; j < 8; j += 2)
- sum += (v[j - 2] - v[j]) * (v[j + 1] + v[j - 1]);
- }
- return sum > 0;
- },
-
- getBounds: function(segments, closed, style, matrix, strokePadding) {
- var first = segments[0];
- if (!first)
- return new Rectangle();
- var coords = new Array(6),
- prevCoords = first._transformCoordinates(matrix, new Array(6), false),
- min = prevCoords.slice(0, 2),
- max = min.slice(),
- roots = new Array(2);
-
- function processSegment(segment) {
- segment._transformCoordinates(matrix, coords, false);
- for (var i = 0; i < 2; i++) {
- Curve._addBounds(
- prevCoords[i],
- prevCoords[i + 4],
- coords[i + 2],
- coords[i],
- i, strokePadding ? strokePadding[i] : 0, min, max, roots);
- }
- var tmp = prevCoords;
- prevCoords = coords;
- coords = tmp;
- }
-
- for (var i = 1, l = segments.length; i < l; i++)
- processSegment(segments[i]);
- if (closed)
- processSegment(first);
- return new Rectangle(min[0], min[1], max[0] - min[0], max[1] - min[1]);
- },
-
- getStrokeBounds: function(segments, closed, style, matrix) {
- function getPenPadding(radius, matrix) {
- if (!matrix)
- return [radius, radius];
- var mx = matrix.shiftless(),
- hor = mx.transform(new Point(radius, 0)),
- ver = mx.transform(new Point(0, radius)),
- phi = hor.getAngleInRadians(),
- a = hor.getLength(),
- b = ver.getLength();
- var sin = Math.sin(phi),
- cos = Math.cos(phi),
- tan = Math.tan(phi),
- tx = -Math.atan(b * tan / a),
- ty = Math.atan(b / (tan * a));
- return [Math.abs(a * Math.cos(tx) * cos - b * Math.sin(tx) * sin),
- Math.abs(b * Math.sin(ty) * cos + a * Math.cos(ty) * sin)];
- }
-
- if (!style.hasStroke())
- return Path.getBounds(segments, closed, style, matrix);
- var length = segments.length - (closed ? 0 : 1),
- radius = style.getStrokeWidth() / 2,
- padding = getPenPadding(radius, matrix),
- bounds = Path.getBounds(segments, closed, style, matrix, padding),
- join = style.getStrokeJoin(),
- cap = style.getStrokeCap(),
- miterLimit = radius * style.getMiterLimit();
- var joinBounds = new Rectangle(new Size(padding).multiply(2));
-
- function add(point) {
- bounds = bounds.include(matrix
- ? matrix._transformPoint(point, point) : point);
- }
-
- function addJoin(segment, join) {
- if (join === 'round' || !segment._handleIn.isZero()
- && !segment._handleOut.isZero()) {
- bounds = bounds.unite(joinBounds.setCenter(matrix
- ? matrix._transformPoint(segment._point) : segment._point));
- } else {
- Path._addSquareJoin(segment, join, radius, miterLimit, add);
- }
- }
-
- function addCap(segment, cap) {
- switch (cap) {
- case 'round':
- addJoin(segment, cap);
- break;
- case 'butt':
- case 'square':
- Path._addSquareCap(segment, cap, radius, add);
- break;
- }
- }
-
- for (var i = 1; i < length; i++)
- addJoin(segments[i], join);
- if (closed) {
- addJoin(segments[0], join);
- } else {
- addCap(segments[0], cap);
- addCap(segments[segments.length - 1], cap);
- }
- return bounds;
- },
-
- _addSquareJoin: function(segment, join, radius, miterLimit, addPoint, area) {
- var curve2 = segment.getCurve(),
- curve1 = curve2.getPrevious(),
- point = curve2.getPointAt(0, true),
- normal1 = curve1.getNormalAt(1, true),
- normal2 = curve2.getNormalAt(0, true),
- step = normal1.getDirectedAngle(normal2) < 0 ? -radius : radius;
- normal1.setLength(step);
- normal2.setLength(step);
- if (area) {
- addPoint(point);
- addPoint(point.add(normal1));
- }
- if (join === 'miter') {
- var corner = new Line(
- point.add(normal1),
- new Point(-normal1.y, normal1.x), true
- ).intersect(new Line(
- point.add(normal2),
- new Point(-normal2.y, normal2.x), true
- ), true);
- if (corner && point.getDistance(corner) <= miterLimit) {
- addPoint(corner);
- if (!area)
- return;
- }
- }
- if (!area)
- addPoint(point.add(normal1));
- addPoint(point.add(normal2));
- },
-
- _addSquareCap: function(segment, cap, radius, addPoint, area) {
- var point = segment._point,
- loc = segment.getLocation(),
- normal = loc.getNormal().normalize(radius);
- if (area) {
- addPoint(point.subtract(normal));
- addPoint(point.add(normal));
- }
- if (cap === 'square')
- point = point.add(normal.rotate(loc.getParameter() == 0 ? -90 : 90));
- addPoint(point.add(normal));
- addPoint(point.subtract(normal));
- },
-
- getHandleBounds: function(segments, closed, style, matrix, strokePadding,
- joinPadding) {
- var coords = new Array(6),
- x1 = Infinity,
- x2 = -x1,
- y1 = x1,
- y2 = x2;
- strokePadding = strokePadding / 2 || 0;
- joinPadding = joinPadding / 2 || 0;
- for (var i = 0, l = segments.length; i < l; i++) {
- var segment = segments[i];
- segment._transformCoordinates(matrix, coords, false);
- for (var j = 0; j < 6; j += 2) {
- var padding = j == 0 ? joinPadding : strokePadding,
- x = coords[j],
- y = coords[j + 1],
- xn = x - padding,
- xx = x + padding,
- yn = y - padding,
- yx = y + padding;
- if (xn < x1) x1 = xn;
- if (xx > x2) x2 = xx;
- if (yn < y1) y1 = yn;
- if (yx > y2) y2 = yx;
- }
- }
- return new Rectangle(x1, y1, x2 - x1, y2 - y1);
- },
-
- getRoughBounds: function(segments, closed, style, matrix) {
- var strokeWidth = style.getStrokeColor() ? style.getStrokeWidth() : 0,
- joinWidth = strokeWidth;
- if (strokeWidth === 0) {
- strokeWidth = 0.00001;
- } else {
- if (style.getStrokeJoin() === 'miter')
- joinWidth = strokeWidth * style.getMiterLimit();
- if (style.getStrokeCap() === 'square')
- joinWidth = Math.max(joinWidth, strokeWidth * Math.sqrt(2));
- }
- return Path.getHandleBounds(segments, closed, style, matrix,
- strokeWidth, joinWidth);
- }
-}});
-
-Path.inject({ statics: new function() {
-
- var kappa = Numerical.KAPPA,
- ellipseSegments = [
- new Segment([-1, 0], [0, kappa ], [0, -kappa]),
- new Segment([0, -1], [-kappa, 0], [kappa, 0 ]),
- new Segment([1, 0], [0, -kappa], [0, kappa ]),
- new Segment([0, 1], [kappa, 0 ], [-kappa, 0])
- ];
-
- function createEllipse(center, radius, args) {
- var path = new Path(),
- segments = new Array(4);
- for (var i = 0; i < 4; i++) {
- var segment = ellipseSegments[i];
- segments[i] = new Segment(
- segment._point.multiply(radius).add(center),
- segment._handleIn.multiply(radius),
- segment._handleOut.multiply(radius)
- );
- }
- path._add(segments);
- path._closed = true;
- return path.set(Base.getNamed(args));
- }
-
- return {
- Line: function() {
- return new Path(
- Point.readNamed(arguments, 'from'),
- Point.readNamed(arguments, 'to')
- ).set(Base.getNamed(arguments));
- },
-
- Circle: function() {
- var center = Point.readNamed(arguments, 'center'),
- radius = Base.readNamed(arguments, 'radius');
- return createEllipse(center, new Size(radius), arguments);
- },
-
- Rectangle: function() {
- var rect = Rectangle.readNamed(arguments, 'rectangle'),
- radius = Size.readNamed(arguments, 'radius', 0, 0,
- { readNull: true }),
- bl = rect.getBottomLeft(true),
- tl = rect.getTopLeft(true),
- tr = rect.getTopRight(true),
- br = rect.getBottomRight(true);
- path = new Path();
- if (!radius || radius.isZero()) {
- path._add([
- new Segment(bl),
- new Segment(tl),
- new Segment(tr),
- new Segment(br)
- ]);
- } else {
- radius = Size.min(radius, rect.getSize(true).divide(2));
- var rx = radius.width,
- ry = radius.height,
- hx = rx * kappa,
- hy = ry * kappa;
- path._add([
- new Segment(bl.add(rx, 0), null, [-hx, 0]),
- new Segment(bl.subtract(0, ry), [0, hy]),
- new Segment(tl.add(0, ry), null, [0, -hy]),
- new Segment(tl.add(rx, 0), [-hx, 0], null),
- new Segment(tr.subtract(rx, 0), null, [hx, 0]),
- new Segment(tr.add(0, ry), [0, -hy], null),
- new Segment(br.subtract(0, ry), null, [0, hy]),
- new Segment(br.subtract(rx, 0), [hx, 0])
- ]);
- }
- path._closed = true;
- return path.set(Base.getNamed(arguments));
- },
-
- RoundRectangle: '#Rectangle',
-
- Ellipse: function() {
- var ellipse = Shape._readEllipse(arguments);
- return createEllipse(ellipse.center, ellipse.radius, arguments);
- },
-
- Oval: '#Ellipse',
-
- Arc: function() {
- var from = Point.readNamed(arguments, 'from'),
- through = Point.readNamed(arguments, 'through'),
- to = Point.readNamed(arguments, 'to'),
- path = new Path();
- path.moveTo(from);
- path.arcTo(through, to);
- return path.set(Base.getNamed(arguments));
- },
-
- RegularPolygon: function() {
- var center = Point.readNamed(arguments, 'center'),
- sides = Base.readNamed(arguments, 'sides'),
- radius = Base.readNamed(arguments, 'radius'),
- path = new Path(),
- step = 360 / sides,
- three = !(sides % 3),
- vector = new Point(0, three ? -radius : radius),
- offset = three ? -1 : 0.5,
- segments = new Array(sides);
- for (var i = 0; i < sides; i++) {
- segments[i] = new Segment(center.add(
- vector.rotate((i + offset) * step)));
- }
- path._add(segments);
- path._closed = true;
- return path.set(Base.getNamed(arguments));
- },
-
- Star: function() {
- var center = Point.readNamed(arguments, 'center'),
- points = Base.readNamed(arguments, 'points') * 2,
- radius1 = Base.readNamed(arguments, 'radius1'),
- radius2 = Base.readNamed(arguments, 'radius2'),
- path = new Path(),
- step = 360 / points,
- vector = new Point(0, -1),
- segments = new Array(points);
- for (var i = 0; i < points; i++) {
- segments[i] = new Segment(center.add(
- vector.rotate(step * i).multiply(i % 2 ? radius2 : radius1)));
- }
- path._add(segments);
- path._closed = true;
- return path.set(Base.getNamed(arguments));
- }
- };
-}});
-
-var CompoundPath = PathItem.extend({
- _class: 'CompoundPath',
- _serializeFields: {
- children: []
- },
-
- initialize: function CompoundPath(arg) {
- this._children = [];
- this._namedChildren = {};
- if (!this._initialize(arg))
- this.addChildren(Array.isArray(arg) ? arg : arguments);
- },
-
- insertChildren: function insertChildren(index, items, _preserve) {
- items = insertChildren.base.call(this, index, items, _preserve, 'path');
- for (var i = 0, l = !_preserve && items && items.length; i < l; i++) {
- var item = items[i];
- if (item._clockwise === undefined)
- item.setClockwise(item._index === 0);
- }
- return items;
- },
-
- reverse: function() {
- var children = this._children;
- for (var i = 0, l = children.length; i < l; i++)
- children[i].reverse();
- },
-
- smooth: function() {
- for (var i = 0, l = this._children.length; i < l; i++)
- this._children[i].smooth();
- },
-
- isClockwise: function() {
- var child = this.getFirstChild();
- return child && child.isClockwise();
- },
-
- setClockwise: function(clockwise) {
- if (this.isClockwise() != !!clockwise)
- this.reverse();
- },
-
- getFirstSegment: function() {
- var first = this.getFirstChild();
- return first && first.getFirstSegment();
- },
-
- getLastSegment: function() {
- var last = this.getLastChild();
- return last && last.getLastSegment();
- },
-
- getCurves: function() {
- var children = this._children,
- curves = [];
- for (var i = 0, l = children.length; i < l; i++)
- curves = curves.concat(children[i].getCurves());
- return curves;
- },
-
- getFirstCurve: function() {
- var first = this.getFirstChild();
- return first && first.getFirstCurve();
- },
-
- getLastCurve: function() {
- var last = this.getLastChild();
- return last && last.getFirstCurve();
- },
-
- getArea: function() {
- var children = this._children,
- area = 0;
- for (var i = 0, l = children.length; i < l; i++)
- area += children[i].getArea();
- return area;
- },
-
- getPathData: function() {
- var children = this._children,
- paths = [];
- for (var i = 0, l = children.length; i < l; i++)
- paths.push(children[i].getPathData(arguments[0]));
- return paths.join(' ');
- },
-
- _getWinding: function(point) {
- var children = this._children,
- winding = 0;
- for (var i = 0, l = children.length; i < l; i++)
- winding += children[i]._getWinding(point);
- return winding;
- },
-
- _hitTest : function _hitTest(point, options) {
- var res = _hitTest.base.call(this, point,
- new Base(options, { fill: false }));
- if (!res) {
- if (options.compoundChildren) {
- var children = this._children;
- for (var i = children.length - 1; i >= 0 && !res; i--)
- res = children[i]._hitTest(point, options);
- } else if (options.fill && this.hasFill()
- && this._contains(point)) {
- res = new HitResult('fill', this);
- }
- }
- return res;
- },
-
- _draw: function(ctx, param) {
- var children = this._children;
- if (children.length === 0)
- return;
-
- ctx.beginPath();
- param = param.extend({ compound: true });
- for (var i = 0, l = children.length; i < l; i++)
- children[i].draw(ctx, param);
-
- if (!param.clip) {
- this._setStyles(ctx);
- var style = this._style;
- if (style.hasFill()) {
- ctx.fill(style.getWindingRule());
- ctx.shadowColor = 'rgba(0,0,0,0)';
- }
- if (style.hasStroke())
- ctx.stroke();
- }
- }
-}, new function() {
- function getCurrentPath(that) {
- if (!that._children.length)
- throw new Error('Use a moveTo() command first');
- return that._children[that._children.length - 1];
- }
-
- var fields = {
- moveTo: function() {
- var path = new Path();
- this.addChild(path);
- path.moveTo.apply(path, arguments);
- },
-
- moveBy: function() {
- this.moveTo(getCurrentPath(this).getLastSegment()._point.add(
- Point.read(arguments)));
- },
-
- closePath: function() {
- getCurrentPath(this).closePath();
- }
- };
-
- Base.each(['lineTo', 'cubicCurveTo', 'quadraticCurveTo', 'curveTo', 'arcTo',
- 'lineBy', 'cubicCurveBy', 'quadraticCurveBy', 'curveBy', 'arcBy'],
- function(key) {
- fields[key] = function() {
- var path = getCurrentPath(this);
- path[key].apply(path, arguments);
- };
- }
- );
-
- return fields;
-});
-
-var PathFlattener = Base.extend({
- initialize: function(path) {
- this.curves = [];
- this.parts = [];
- this.length = 0;
- this.index = 0;
-
- var segments = path._segments,
- segment1 = segments[0],
- segment2,
- that = this;
-
- function addCurve(segment1, segment2) {
- var curve = Curve.getValues(segment1, segment2);
- that.curves.push(curve);
- that._computeParts(curve, segment1._index, 0, 1);
- }
-
- for (var i = 1, l = segments.length; i < l; i++) {
- segment2 = segments[i];
- addCurve(segment1, segment2);
- segment1 = segment2;
- }
- if (path._closed)
- addCurve(segment2, segments[0]);
- },
-
- _computeParts: function(curve, index, minT, maxT) {
- if ((maxT - minT) > 1 / 32 && !Curve.isFlatEnough(curve, 0.25)) {
- var curves = Curve.subdivide(curve);
- var halfT = (minT + maxT) / 2;
- this._computeParts(curves[0], index, minT, halfT);
- this._computeParts(curves[1], index, halfT, maxT);
- } else {
- var x = curve[6] - curve[0],
- y = curve[7] - curve[1],
- dist = Math.sqrt(x * x + y * y);
- if (dist > 0.00001) {
- this.length += dist;
- this.parts.push({
- offset: this.length,
- value: maxT,
- index: index
- });
- }
- }
- },
-
- getParameterAt: function(offset) {
- var i, j = this.index;
- for (;;) {
- i = j;
- if (j == 0 || this.parts[--j].offset < offset)
- break;
- }
- for (var l = this.parts.length; i < l; i++) {
- var part = this.parts[i];
- if (part.offset >= offset) {
- this.index = i;
- var prev = this.parts[i - 1];
- var prevVal = prev && prev.index == part.index ? prev.value : 0,
- prevLen = prev ? prev.offset : 0;
- return {
- value: prevVal + (part.value - prevVal)
- * (offset - prevLen) / (part.offset - prevLen),
- index: part.index
- };
- }
- }
- var part = this.parts[this.parts.length - 1];
- return {
- value: 1,
- index: part.index
- };
- },
-
- evaluate: function(offset, type) {
- var param = this.getParameterAt(offset);
- return Curve.evaluate(this.curves[param.index], param.value, type);
- },
-
- drawPart: function(ctx, from, to) {
- from = this.getParameterAt(from);
- to = this.getParameterAt(to);
- for (var i = from.index; i <= to.index; i++) {
- var curve = Curve.getPart(this.curves[i],
- i == from.index ? from.value : 0,
- i == to.index ? to.value : 1);
- if (i == from.index)
- ctx.moveTo(curve[0], curve[1]);
- ctx.bezierCurveTo.apply(ctx, curve.slice(2));
- }
- }
-});
-
-var PathFitter = Base.extend({
- initialize: function(path, error) {
- this.points = [];
- var segments = path._segments,
- prev;
- for (var i = 0, l = segments.length; i < l; i++) {
- var point = segments[i].point.clone();
- if (!prev || !prev.equals(point)) {
- this.points.push(point);
- prev = point;
- }
- }
- this.error = error;
- },
-
- fit: function() {
- var points = this.points,
- length = points.length;
- this.segments = length > 0 ? [new Segment(points[0])] : [];
- if (length > 1)
- this.fitCubic(0, length - 1,
- points[1].subtract(points[0]).normalize(),
- points[length - 2].subtract(points[length - 1]).normalize());
- return this.segments;
- },
-
- fitCubic: function(first, last, tan1, tan2) {
- if (last - first == 1) {
- var pt1 = this.points[first],
- pt2 = this.points[last],
- dist = pt1.getDistance(pt2) / 3;
- this.addCurve([pt1, pt1.add(tan1.normalize(dist)),
- pt2.add(tan2.normalize(dist)), pt2]);
- return;
- }
- var uPrime = this.chordLengthParameterize(first, last),
- maxError = Math.max(this.error, this.error * this.error),
- split;
- for (var i = 0; i <= 4; i++) {
- var curve = this.generateBezier(first, last, uPrime, tan1, tan2);
- var max = this.findMaxError(first, last, curve, uPrime);
- if (max.error < this.error) {
- this.addCurve(curve);
- return;
- }
- split = max.index;
- if (max.error >= maxError)
- break;
- this.reparameterize(first, last, uPrime, curve);
- maxError = max.error;
- }
- var V1 = this.points[split - 1].subtract(this.points[split]),
- V2 = this.points[split].subtract(this.points[split + 1]),
- tanCenter = V1.add(V2).divide(2).normalize();
- this.fitCubic(first, split, tan1, tanCenter);
- this.fitCubic(split, last, tanCenter.negate(), tan2);
- },
-
- addCurve: function(curve) {
- var prev = this.segments[this.segments.length - 1];
- prev.setHandleOut(curve[1].subtract(curve[0]));
- this.segments.push(
- new Segment(curve[3], curve[2].subtract(curve[3])));
- },
-
- generateBezier: function(first, last, uPrime, tan1, tan2) {
- var epsilon = 1e-11,
- pt1 = this.points[first],
- pt2 = this.points[last],
- C = [[0, 0], [0, 0]],
- X = [0, 0];
-
- for (var i = 0, l = last - first + 1; i < l; i++) {
- var u = uPrime[i],
- t = 1 - u,
- b = 3 * u * t,
- b0 = t * t * t,
- b1 = b * t,
- b2 = b * u,
- b3 = u * u * u,
- a1 = tan1.normalize(b1),
- a2 = tan2.normalize(b2),
- tmp = this.points[first + i]
- .subtract(pt1.multiply(b0 + b1))
- .subtract(pt2.multiply(b2 + b3));
- C[0][0] += a1.dot(a1);
- C[0][1] += a1.dot(a2);
- C[1][0] = C[0][1];
- C[1][1] += a2.dot(a2);
- X[0] += a1.dot(tmp);
- X[1] += a2.dot(tmp);
- }
-
- var detC0C1 = C[0][0] * C[1][1] - C[1][0] * C[0][1],
- alpha1, alpha2;
- if (Math.abs(detC0C1) > epsilon) {
- var detC0X = C[0][0] * X[1] - C[1][0] * X[0],
- detXC1 = X[0] * C[1][1] - X[1] * C[0][1];
- alpha1 = detXC1 / detC0C1;
- alpha2 = detC0X / detC0C1;
- } else {
- var c0 = C[0][0] + C[0][1],
- c1 = C[1][0] + C[1][1];
- if (Math.abs(c0) > epsilon) {
- alpha1 = alpha2 = X[0] / c0;
- } else if (Math.abs(c1) > epsilon) {
- alpha1 = alpha2 = X[1] / c1;
- } else {
- alpha1 = alpha2 = 0;
- }
- }
-
- var segLength = pt2.getDistance(pt1);
- epsilon *= segLength;
- if (alpha1 < epsilon || alpha2 < epsilon) {
- alpha1 = alpha2 = segLength / 3;
- }
-
- return [pt1, pt1.add(tan1.normalize(alpha1)),
- pt2.add(tan2.normalize(alpha2)), pt2];
- },
-
- reparameterize: function(first, last, u, curve) {
- for (var i = first; i <= last; i++) {
- u[i - first] = this.findRoot(curve, this.points[i], u[i - first]);
- }
- },
-
- findRoot: function(curve, point, u) {
- var curve1 = [],
- curve2 = [];
- for (var i = 0; i <= 2; i++) {
- curve1[i] = curve[i + 1].subtract(curve[i]).multiply(3);
- }
- for (var i = 0; i <= 1; i++) {
- curve2[i] = curve1[i + 1].subtract(curve1[i]).multiply(2);
- }
- var pt = this.evaluate(3, curve, u),
- pt1 = this.evaluate(2, curve1, u),
- pt2 = this.evaluate(1, curve2, u),
- diff = pt.subtract(point),
- df = pt1.dot(pt1) + diff.dot(pt2);
- if (Math.abs(df) < 0.00001)
- return u;
- return u - diff.dot(pt1) / df;
- },
-
- evaluate: function(degree, curve, t) {
- var tmp = curve.slice();
- for (var i = 1; i <= degree; i++) {
- for (var j = 0; j <= degree - i; j++) {
- tmp[j] = tmp[j].multiply(1 - t).add(tmp[j + 1].multiply(t));
- }
- }
- return tmp[0];
- },
-
- chordLengthParameterize: function(first, last) {
- var u = [0];
- for (var i = first + 1; i <= last; i++) {
- u[i - first] = u[i - first - 1]
- + this.points[i].getDistance(this.points[i - 1]);
- }
- for (var i = 1, m = last - first; i <= m; i++) {
- u[i] /= u[m];
- }
- return u;
- },
-
- findMaxError: function(first, last, curve, u) {
- var index = Math.floor((last - first + 1) / 2),
- maxDist = 0;
- for (var i = first + 1; i < last; i++) {
- var P = this.evaluate(3, curve, u[i - first]);
- var v = P.subtract(this.points[i]);
- var dist = v.x * v.x + v.y * v.y;
- if (dist >= maxDist) {
- maxDist = dist;
- index = i;
- }
- }
- return {
- error: maxDist,
- index: index
- };
- }
-});
-
-PathItem.inject(new function() {
-
- function splitPath(intersections, collectOthers) {
- intersections.sort(function(loc1, loc2) {
- var path1 = loc1.getPath(),
- path2 = loc2.getPath();
- return path1 === path2
- ? (loc1.getIndex() + loc1.getParameter())
- - (loc2.getIndex() + loc2.getParameter())
- : path1._id - path2._id;
- });
- var others = collectOthers && [];
- for (var i = intersections.length - 1; i >= 0; i--) {
- var loc = intersections[i],
- other = loc.getIntersection(),
- curve = loc.divide(),
- segment = curve && curve.getSegment1() || loc.getSegment();
- if (others)
- others.push(other);
- segment._intersection = other;
- loc._segment = segment;
- }
- return others;
- }
-
- function reorientPath(path) {
- if (path instanceof CompoundPath) {
- var children = path.removeChildren(),
- length = children.length,
- bounds = new Array(length),
- counters = new Array(length),
- clockwise;
- children.sort(function(a, b){
- var b1 = a.getBounds(), b2 = b.getBounds();
- return b1._width * b1._height < b2._width * b2._height;
- });
- path.addChildren(children);
- clockwise = children[0].isClockwise();
- for (var i = 0; i < length; i++) {
- bounds[i] = children[i].getBounds();
- counters[i] = 0;
- }
- for (var i = 0; i < length; i++) {
- for (var j = 1; j < length; j++) {
- if (i !== j && bounds[i].contains(bounds[j]))
- counters[j]++;
- }
- if (i > 0 && counters[i] % 2 === 0)
- children[i].setClockwise(clockwise);
- }
- }
- return path;
- }
-
- function computeBoolean(path1, path2, operator, subtract) {
- path1 = reorientPath(path1.clone(false));
- path2 = reorientPath(path2.clone(false));
- var path1Clockwise = path1.isClockwise(),
- path2Clockwise = path2.isClockwise(),
- intersections = path1.getIntersections(path2);
- splitPath(splitPath(intersections, true));
- if (!path1Clockwise)
- path1.reverse();
- if (!(subtract ^ path2Clockwise))
- path2.reverse();
- path1Clockwise = true;
- path2Clockwise = !subtract;
- var paths = []
- .concat(path1._children || [path1])
- .concat(path2._children || [path2]),
- segments = [],
- result = new CompoundPath();
- for (var i = 0, l = paths.length; i < l; i++) {
- var path = paths[i],
- parent = path._parent,
- clockwise = path.isClockwise(),
- segs = path._segments;
- path = parent instanceof CompoundPath ? parent : path;
- for (var j = segs.length - 1; j >= 0; j--) {
- var segment = segs[j],
- midPoint = segment.getCurve().getPoint(0.5),
- insidePath1 = path !== path1 && path1.contains(midPoint)
- && (clockwise === path1Clockwise || subtract
- || !testOnCurve(path1, midPoint)),
- insidePath2 = path !== path2 && path2.contains(midPoint)
- && (clockwise === path2Clockwise
- || !testOnCurve(path2, midPoint));
- if (operator(path === path1, insidePath1, insidePath2)) {
- segment._invalid = true;
- } else {
- segments.push(segment);
- }
- }
- }
- for (var i = 0, l = segments.length; i < l; i++) {
- var segment = segments[i];
- if (segment._visited)
- continue;
- var path = new Path(),
- loc = segment._intersection,
- intersection = loc && loc.getSegment(true);
- if (segment.getPrevious()._invalid)
- segment.setHandleIn(intersection
- ? intersection._handleIn
- : new Point(0, 0));
- do {
- segment._visited = true;
- if (segment._invalid && segment._intersection) {
- var inter = segment._intersection.getSegment(true);
- path.add(new Segment(segment._point, segment._handleIn,
- inter._handleOut));
- inter._visited = true;
- segment = inter;
- } else {
- path.add(segment.clone());
- }
- segment = segment.getNext();
- } while (segment && !segment._visited && segment !== intersection);
- var amount = path._segments.length;
- if (amount > 1 && (amount > 2 || !path.isPolygon())) {
- path.setClosed(true);
- result.addChild(path, true);
- } else {
- path.remove();
- }
- }
- path1.remove();
- path2.remove();
- return result.reduce();
- }
-
- function testOnCurve(path, point) {
- var curves = path.getCurves(),
- bounds = path.getBounds();
- if (bounds.contains(point)) {
- for (var i = 0, l = curves.length; i < l; i++) {
- var curve = curves[i];
- if (curve.getBounds().contains(point)
- && curve.getParameterOf(point))
- return true;
- }
- }
- return false;
- }
-
- return {
- unite: function(path) {
- return computeBoolean(this, path,
- function(isPath1, isInPath1, isInPath2) {
- return isInPath1 || isInPath2;
- });
- },
-
- intersect: function(path) {
- return computeBoolean(this, path,
- function(isPath1, isInPath1, isInPath2) {
- return !(isInPath1 || isInPath2);
- });
- },
-
- subtract: function(path) {
- return computeBoolean(this, path,
- function(isPath1, isInPath1, isInPath2) {
- return isPath1 && isInPath2 || !isPath1 && !isInPath1;
- }, true);
- },
-
- exclude: function(path) {
- return new Group([this.subtract(path), path.subtract(this)]);
- },
-
- divide: function(path) {
- return new Group([this.subtract(path), this.intersect(path)]);
- }
- };
-});
-
-var TextItem = Item.extend({
- _class: 'TextItem',
- _boundsSelected: true,
- _serializeFields: {
- content: null
- },
- _boundsGetter: 'getBounds',
-
- initialize: function TextItem(arg) {
- this._content = '';
- this._lines = [];
- var hasProps = arg && Base.isPlainObject(arg)
- && arg.x === undefined && arg.y === undefined;
- this._initialize(hasProps && arg, !hasProps && Point.read(arguments));
- },
-
- _equals: function(item) {
- return this._content === item._content;
- },
-
- _clone: function _clone(copy) {
- copy.setContent(this._content);
- return _clone.base.call(this, copy);
- },
-
- getContent: function() {
- return this._content;
- },
-
- setContent: function(content) {
- this._content = '' + content;
- this._lines = this._content.split(/\r\n|\n|\r/mg);
- this._changed(69);
- },
-
- isEmpty: function() {
- return !this._content;
- },
-
- getCharacterStyle: '#getStyle',
- setCharacterStyle: '#setStyle',
-
- getParagraphStyle: '#getStyle',
- setParagraphStyle: '#setStyle'
-});
-
-var PointText = TextItem.extend({
- _class: 'PointText',
-
- initialize: function PointText() {
- TextItem.apply(this, arguments);
- },
-
- clone: function(insert) {
- return this._clone(new PointText({ insert: false }), insert);
- },
-
- getPoint: function() {
- var point = this._matrix.getTranslation();
- return new LinkedPoint(point.x, point.y, this, 'setPoint');
- },
-
- setPoint: function(point) {
- point = Point.read(arguments);
- this.translate(point.subtract(this._matrix.getTranslation()));
- },
-
- _draw: function(ctx) {
- if (!this._content)
- return;
- this._setStyles(ctx);
- var style = this._style,
- lines = this._lines,
- leading = style.getLeading(),
- shadowColor = ctx.shadowColor;
-
- ctx.font = style.getFontStyle();
- ctx.textAlign = style.getJustification();
- for (var i = 0, l = lines.length; i < l; i++) {
- ctx.shadowColor = shadowColor;
- var line = lines[i];
- if (style.hasFill()) {
- ctx.fillText(line, 0, 0);
- ctx.shadowColor = 'rgba(0,0,0,0)';
- }
- if (style.hasStroke())
- ctx.strokeText(line, 0, 0);
- ctx.translate(0, leading);
- }
- }
-}, new function() {
- var measureCtx = null;
-
- return {
- _getBounds: function(getter, matrix) {
- if (!measureCtx)
- measureCtx = CanvasProvider.getContext(1, 1);
- var style = this._style,
- lines = this._lines,
- count = lines.length,
- justification = style.getJustification(),
- leading = style.getLeading(),
- x = 0;
- measureCtx.font = style.getFontStyle();
- var width = 0;
- for (var i = 0; i < count; i++)
- width = Math.max(width, measureCtx.measureText(lines[i]).width);
- if (justification !== 'left')
- x -= width / (justification === 'center' ? 2: 1);
- var bounds = new Rectangle(x,
- count ? - 0.75 * leading : 0,
- width, count * leading);
- return matrix ? matrix._transformBounds(bounds, bounds) : bounds;
- }
- };
-});
-
-var Color = Base.extend(new function() {
-
- var types = {
- gray: ['gray'],
- rgb: ['red', 'green', 'blue'],
- hsb: ['hue', 'saturation', 'brightness'],
- hsl: ['hue', 'saturation', 'lightness'],
- gradient: ['gradient', 'origin', 'destination', 'highlight']
- };
-
- var componentParsers = {},
- colorCache = {},
- colorCtx;
-
- function fromCSS(string) {
- var match = string.match(/^#(\w{1,2})(\w{1,2})(\w{1,2})$/),
- components;
- if (match) {
- components = [0, 0, 0];
- for (var i = 0; i < 3; i++) {
- var value = match[i + 1];
- components[i] = parseInt(value.length == 1
- ? value + value : value, 16) / 255;
- }
- } else if (match = string.match(/^rgba?\((.*)\)$/)) {
- components = match[1].split(',');
- for (var i = 0, l = components.length; i < l; i++) {
- var value = parseFloat(components[i]);
- components[i] = i < 3 ? value / 255 : value;
- }
- } else {
- var cached = colorCache[string];
- if (!cached) {
- if (!colorCtx) {
- colorCtx = CanvasProvider.getContext(1, 1);
- colorCtx.globalCompositeOperation = 'copy';
- }
- colorCtx.fillStyle = 'rgba(0,0,0,0)';
- colorCtx.fillStyle = string;
- colorCtx.fillRect(0, 0, 1, 1);
- var data = colorCtx.getImageData(0, 0, 1, 1).data;
- cached = colorCache[string] = [
- data[0] / 255,
- data[1] / 255,
- data[2] / 255
- ];
- }
- components = cached.slice();
- }
- return components;
- }
-
- var hsbIndices = [
- [0, 3, 1],
- [2, 0, 1],
- [1, 0, 3],
- [1, 2, 0],
- [3, 1, 0],
- [0, 1, 2]
- ];
-
- var converters = {
- 'rgb-hsb': function(r, g, b) {
- var max = Math.max(r, g, b),
- min = Math.min(r, g, b),
- delta = max - min,
- h = delta === 0 ? 0
- : ( max == r ? (g - b) / delta + (g < b ? 6 : 0)
- : max == g ? (b - r) / delta + 2
- : (r - g) / delta + 4) * 60;
- return [h, max === 0 ? 0 : delta / max, max];
- },
-
- 'hsb-rgb': function(h, s, b) {
- var h = (h / 60) % 6,
- i = Math.floor(h),
- f = h - i,
- i = hsbIndices[i],
- v = [
- b,
- b * (1 - s),
- b * (1 - s * f),
- b * (1 - s * (1 - f))
- ];
- return [v[i[0]], v[i[1]], v[i[2]]];
- },
-
- 'rgb-hsl': function(r, g, b) {
- var max = Math.max(r, g, b),
- min = Math.min(r, g, b),
- delta = max - min,
- achromatic = delta === 0,
- h = achromatic ? 0
- : ( max == r ? (g - b) / delta + (g < b ? 6 : 0)
- : max == g ? (b - r) / delta + 2
- : (r - g) / delta + 4) * 60,
- l = (max + min) / 2,
- s = achromatic ? 0 : l < 0.5
- ? delta / (max + min)
- : delta / (2 - max - min);
- return [h, s, l];
- },
-
- 'hsl-rgb': function(h, s, l) {
- h /= 360;
- if (s === 0)
- return [l, l, l];
- var t3s = [ h + 1 / 3, h, h - 1 / 3 ],
- t2 = l < 0.5 ? l * (1 + s) : l + s - l * s,
- t1 = 2 * l - t2,
- c = [];
- for (var i = 0; i < 3; i++) {
- var t3 = t3s[i];
- if (t3 < 0) t3 += 1;
- if (t3 > 1) t3 -= 1;
- c[i] = 6 * t3 < 1
- ? t1 + (t2 - t1) * 6 * t3
- : 2 * t3 < 1
- ? t2
- : 3 * t3 < 2
- ? t1 + (t2 - t1) * ((2 / 3) - t3) * 6
- : t1;
- }
- return c;
- },
-
- 'rgb-gray': function(r, g, b) {
- return [r * 0.2989 + g * 0.587 + b * 0.114];
- },
-
- 'gray-rgb': function(g) {
- return [g, g, g];
- },
-
- 'gray-hsb': function(g) {
- return [0, 0, g];
- },
-
- 'gray-hsl': function(g) {
- return [0, 0, g];
- },
-
- 'gradient-rgb': function() {
- return [];
- },
-
- 'rgb-gradient': function() {
- return [];
- }
-
- };
-
- return Base.each(types, function(properties, type) {
- componentParsers[type] = [];
- Base.each(properties, function(name, index) {
- var part = Base.capitalize(name),
- hasOverlap = /^(hue|saturation)$/.test(name),
- parser = componentParsers[type][index] = name === 'gradient'
- ? function(value) {
- var current = this._components[0];
- value = Gradient.read(
- Array.isArray(value) ? value : arguments,
- 0, 0, { readNull: true });
- if (current !== value) {
- if (current)
- current._removeOwner(this);
- if (value)
- value._addOwner(this);
- }
- return value;
- }
- : name === 'hue'
- ? function(value) {
- return isNaN(value) ? 0
- : ((value % 360) + 360) % 360;
- }
- : type === 'gradient'
- ? function() {
- return Point.read(arguments, 0, 0, {
- readNull: name === 'highlight',
- clone: true
- });
- }
- : function(value) {
- return isNaN(value) ? 0
- : Math.min(Math.max(value, 0), 1);
- };
-
- this['get' + part] = function() {
- return this._type === type
- || hasOverlap && /^hs[bl]$/.test(this._type)
- ? this._components[index]
- : this._convert(type)[index];
- };
-
- this['set' + part] = function(value) {
- if (this._type !== type
- && !(hasOverlap && /^hs[bl]$/.test(this._type))) {
- this._components = this._convert(type);
- this._properties = types[type];
- this._type = type;
- }
- value = parser.call(this, value);
- if (value != null) {
- this._components[index] = value;
- this._changed();
- }
- };
- }, this);
- }, {
- _class: 'Color',
- _readIndex: true,
-
- initialize: function Color(arg) {
- var slice = Array.prototype.slice,
- args = arguments,
- read = 0,
- parse = true,
- type,
- components,
- alpha,
- values;
- if (Array.isArray(arg)) {
- args = arg;
- arg = args[0];
- }
- var argType = arg != null && typeof arg;
- if (argType === 'string' && arg in types) {
- type = arg;
- arg = args[1];
- if (Array.isArray(arg)) {
- components = arg;
- alpha = args[2];
- } else {
- if (this.__read)
- read = 1;
- args = slice.call(args, 1);
- argType = typeof arg;
- }
- }
- if (!components) {
- parse = !(this.__options && this.__options.dontParse);
- values = argType === 'number'
- ? args
- : argType === 'object' && arg.length != null
- ? arg
- : null;
- if (values) {
- if (!type)
- type = values.length >= 3
- ? 'rgb'
- : 'gray';
- var length = types[type].length;
- alpha = values[length];
- if (this.__read)
- read += values === arguments
- ? length + (alpha != null ? 1 : 0)
- : 1;
- if (values.length > length)
- values = slice.call(values, 0, length);
- } else if (argType === 'string') {
- type = 'rgb';
- components = fromCSS(arg);
- if (components.length === 4) {
- alpha = components[3];
- components.length--;
- }
- } else if (argType === 'object') {
- if (arg.constructor === Color) {
- type = arg._type;
- components = arg._components.slice();
- alpha = arg._alpha;
- if (type === 'gradient') {
- for (var i = 1, l = components.length; i < l; i++) {
- var point = components[i];
- if (point)
- components[i] = point.clone();
- }
- }
- } else if (arg.constructor === Gradient) {
- type = 'gradient';
- values = args;
- } else {
- type = 'hue' in arg
- ? 'lightness' in arg
- ? 'hsl'
- : 'hsb'
- : 'gradient' in arg || 'stops' in arg
- || 'radial' in arg
- ? 'gradient'
- : 'gray' in arg
- ? 'gray'
- : 'rgb';
- var properties = types[type];
- parsers = parse && componentParsers[type];
- this._components = components = [];
- for (var i = 0, l = properties.length; i < l; i++) {
- var value = arg[properties[i]];
- if (value == null && i === 0 && type === 'gradient'
- && 'stops' in arg) {
- value = {
- stops: arg.stops,
- radial: arg.radial
- };
- }
- if (parse)
- value = parsers[i].call(this, value);
- if (value != null)
- components[i] = value;
- }
- alpha = arg.alpha;
- }
- }
- if (this.__read && type)
- read = 1;
- }
- this._type = type || 'rgb';
- if (type === 'gradient')
- this._id = Color._id = (Color._id || 0) + 1;
- if (!components) {
- this._components = components = [];
- var parsers = componentParsers[this._type];
- for (var i = 0, l = parsers.length; i < l; i++) {
- var value = values && values[i];
- if (parse)
- value = parsers[i].call(this, value);
- if (value != null)
- components[i] = value;
- }
- }
- this._components = components;
- this._properties = types[this._type];
- this._alpha = alpha;
- if (this.__read)
- this.__read = read;
- },
-
- _serialize: function(options, dictionary) {
- var components = this.getComponents();
- return Base.serialize(
- /^(gray|rgb)$/.test(this._type)
- ? components
- : [this._type].concat(components),
- options, true, dictionary);
- },
-
- _changed: function() {
- this._canvasStyle = null;
- if (this._owner)
- this._owner._changed(17);
- },
-
- _convert: function(type) {
- var converter;
- return this._type === type
- ? this._components.slice()
- : (converter = converters[this._type + '-' + type])
- ? converter.apply(this, this._components)
- : converters['rgb-' + type].apply(this,
- converters[this._type + '-rgb'].apply(this,
- this._components));
- },
-
- convert: function(type) {
- return new Color(type, this._convert(type), this._alpha);
- },
-
- getType: function() {
- return this._type;
- },
-
- setType: function(type) {
- this._components = this._convert(type);
- this._properties = types[type];
- this._type = type;
- },
-
- getComponents: function() {
- var components = this._components.slice();
- if (this._alpha != null)
- components.push(this._alpha);
- return components;
- },
-
- getAlpha: function() {
- return this._alpha != null ? this._alpha : 1;
- },
-
- setAlpha: function(alpha) {
- this._alpha = alpha == null ? null : Math.min(Math.max(alpha, 0), 1);
- this._changed();
- },
-
- hasAlpha: function() {
- return this._alpha != null;
- },
-
- equals: function(color) {
- if (Base.isPlainValue(color))
- color = Color.read(arguments);
- return color === this || color && this._class === color._class
- && this._type === color._type
- && this._alpha === color._alpha
- && Base.equals(this._components, color._components)
- || false;
- },
-
- toString: function() {
- var properties = this._properties,
- parts = [],
- isGradient = this._type === 'gradient',
- f = Formatter.instance;
- for (var i = 0, l = properties.length; i < l; i++) {
- var value = this._components[i];
- if (value != null)
- parts.push(properties[i] + ': '
- + (isGradient ? value : f.number(value)));
- }
- if (this._alpha != null)
- parts.push('alpha: ' + f.number(this._alpha));
- return '{ ' + parts.join(', ') + ' }';
- },
-
- toCSS: function(hex) {
- var components = this._convert('rgb'),
- alpha = hex || this._alpha == null ? 1 : this._alpha;
- components = [
- Math.round(components[0] * 255),
- Math.round(components[1] * 255),
- Math.round(components[2] * 255)
- ];
- if (alpha < 1)
- components.push(alpha);
- return hex
- ? '#' + ((1 << 24) + (components[0] << 16)
- + (components[1] << 8)
- + components[2]).toString(16).slice(1)
- : (components.length == 4 ? 'rgba(' : 'rgb(')
- + components.join(',') + ')';
- },
-
- toCanvasStyle: function(ctx) {
- if (this._canvasStyle)
- return this._canvasStyle;
- if (this._type !== 'gradient')
- return this._canvasStyle = this.toCSS();
- var components = this._components,
- gradient = components[0],
- stops = gradient._stops,
- origin = components[1],
- destination = components[2],
- canvasGradient;
- if (gradient._radial) {
- var radius = destination.getDistance(origin),
- highlight = components[3];
- if (highlight) {
- var vector = highlight.subtract(origin);
- if (vector.getLength() > radius)
- highlight = origin.add(vector.normalize(radius - 0.1));
- }
- var start = highlight || origin;
- canvasGradient = ctx.createRadialGradient(start.x, start.y,
- 0, origin.x, origin.y, radius);
- } else {
- canvasGradient = ctx.createLinearGradient(origin.x, origin.y,
- destination.x, destination.y);
- }
- for (var i = 0, l = stops.length; i < l; i++) {
- var stop = stops[i];
- canvasGradient.addColorStop(stop._rampPoint,
- stop._color.toCanvasStyle());
- }
- return this._canvasStyle = canvasGradient;
- },
-
- transform: function(matrix) {
- if (this._type === 'gradient') {
- var components = this._components;
- for (var i = 1, l = components.length; i < l; i++) {
- var point = components[i];
- matrix._transformPoint(point, point, true);
- }
- this._changed();
- }
- },
-
- statics: {
- _types: types,
-
- random: function() {
- var random = Math.random;
- return new Color(random(), random(), random());
- }
- }
- });
-}, new function() {
- function clamp(value, hue) {
- return value < 0
- ? 0
- : hue && value > 360
- ? 360
- : !hue && value > 1
- ? 1
- : value;
- }
-
- var operators = {
- add: function(a, b, hue) {
- return clamp(a + b, hue);
- },
-
- subtract: function(a, b, hue) {
- return clamp(a - b, hue);
- },
-
- multiply: function(a, b, hue) {
- return clamp(a * b, hue);
- },
-
- divide: function(a, b, hue) {
- return clamp(a / b, hue);
- }
- };
-
- return Base.each(operators, function(operator, name) {
- var options = { dontParse: /^(multiply|divide)$/.test(name) };
-
- this[name] = function(color) {
- color = Color.read(arguments, 0, 0, options);
- var type = this._type,
- properties = this._properties,
- components1 = this._components,
- components2 = color._convert(type);
- for (var i = 0, l = components1.length; i < l; i++)
- components2[i] = operator(components1[i], components2[i],
- properties[i] === 'hue');
- return new Color(type, components2,
- this._alpha != null
- ? operator(this._alpha, color.getAlpha())
- : null);
- };
- }, {
- });
-});
-
-Base.each(Color._types, function(properties, type) {
- var ctor = this[Base.capitalize(type) + 'Color'] = function(arg) {
- var argType = arg != null && typeof arg,
- components = argType === 'object' && arg.length != null
- ? arg
- : argType === 'string'
- ? null
- : arguments;
- return components
- ? new Color(type, components)
- : new Color(arg);
- };
- if (type.length == 3) {
- var acronym = type.toUpperCase();
- Color[acronym] = this[acronym + 'Color'] = ctor;
- }
-}, Base.exports);
-
-var Gradient = Base.extend({
- _class: 'Gradient',
-
- initialize: function Gradient(stops, radial) {
- this._id = Gradient._id = (Gradient._id || 0) + 1;
- if (stops && this._set(stops))
- stops = radial = null;
- if (!this._stops)
- this.setStops(stops || ['white', 'black']);
- if (this._radial == null)
- this.setRadial(typeof radial === 'string' && radial === 'radial'
- || radial || false);
- },
-
- _serialize: function(options, dictionary) {
- return dictionary.add(this, function() {
- return Base.serialize([this._stops, this._radial],
- options, true, dictionary);
- });
- },
-
- _changed: function() {
- for (var i = 0, l = this._owners && this._owners.length; i < l; i++)
- this._owners[i]._changed();
- },
-
- _addOwner: function(color) {
- if (!this._owners)
- this._owners = [];
- this._owners.push(color);
- },
-
- _removeOwner: function(color) {
- var index = this._owners ? this._owners.indexOf(color) : -1;
- if (index != -1) {
- this._owners.splice(index, 1);
- if (this._owners.length === 0)
- delete this._owners;
- }
- },
-
- clone: function() {
- var stops = [];
- for (var i = 0, l = this._stops.length; i < l; i++)
- stops[i] = this._stops[i].clone();
- return new Gradient(stops);
- },
-
- getStops: function() {
- return this._stops;
- },
-
- setStops: function(stops) {
- if (this.stops) {
- for (var i = 0, l = this._stops.length; i < l; i++)
- delete this._stops[i]._owner;
- }
- if (stops.length < 2)
- throw new Error(
- 'Gradient stop list needs to contain at least two stops.');
- this._stops = GradientStop.readAll(stops, 0, false, true);
- for (var i = 0, l = this._stops.length; i < l; i++) {
- var stop = this._stops[i];
- stop._owner = this;
- if (stop._defaultRamp)
- stop.setRampPoint(i / (l - 1));
- }
- this._changed();
- },
-
- getRadial: function() {
- return this._radial;
- },
-
- setRadial: function(radial) {
- this._radial = radial;
- this._changed();
- },
-
- equals: function(gradient) {
- if (gradient === this)
- return true;
- if (gradient && this._class === gradient._class
- && this._stops.length === gradient._stops.length) {
- for (var i = 0, l = this._stops.length; i < l; i++) {
- if (!this._stops[i].equals(gradient._stops[i]))
- return false;
- }
- return true;
- }
- return false;
- }
-});
-
-var GradientStop = Base.extend({
- _class: 'GradientStop',
-
- initialize: function GradientStop(arg0, arg1) {
- if (arg0) {
- var color, rampPoint;
- if (arg1 === undefined && Array.isArray(arg0)) {
- color = arg0[0];
- rampPoint = arg0[1];
- } else if (arg0.color) {
- color = arg0.color;
- rampPoint = arg0.rampPoint;
- } else {
- color = arg0;
- rampPoint = arg1;
- }
- this.setColor(color);
- this.setRampPoint(rampPoint);
- }
- },
-
- clone: function() {
- return new GradientStop(this._color.clone(), this._rampPoint);
- },
-
- _serialize: function(options, dictionary) {
- return Base.serialize([this._color, this._rampPoint], options, true,
- dictionary);
- },
-
- _changed: function() {
- if (this._owner)
- this._owner._changed(17);
- },
-
- getRampPoint: function() {
- return this._rampPoint;
- },
-
- setRampPoint: function(rampPoint) {
- this._defaultRamp = rampPoint == null;
- this._rampPoint = rampPoint || 0;
- this._changed();
- },
-
- getColor: function() {
- return this._color;
- },
-
- setColor: function(color) {
- this._color = Color.read(arguments);
- if (this._color === color)
- this._color = color.clone();
- this._color._owner = this;
- this._changed();
- },
-
- equals: function(stop) {
- return stop === this || stop && this._class === stop._class
- && this._color.equals(stop._color)
- && this._rampPoint == stop._rampPoint
- || false;
- }
-});
-
-var Style = Base.extend(new function() {
- var defaults = {
- fillColor: undefined,
- strokeColor: undefined,
- strokeWidth: 1,
- strokeCap: 'butt',
- strokeJoin: 'miter',
- miterLimit: 10,
- dashOffset: 0,
- dashArray: [],
- windingRule: 'nonzero',
- shadowColor: undefined,
- shadowBlur: 0,
- shadowOffset: new Point(),
- selectedColor: undefined,
- font: 'sans-serif',
- fontSize: 12,
- leading: null,
- justification: 'left'
- };
-
- var flags = {
- strokeWidth: 25,
- strokeCap: 25,
- strokeJoin: 25,
- miterLimit: 25,
- font: 5,
- fontSize: 5,
- leading: 5,
- justification: 5
- };
-
- var item = {},
- fields = {
- _defaults: defaults,
- _textDefaults: new Base(defaults, {
- fillColor: new Color()
- })
- };
-
- Base.each(defaults, function(value, key) {
- var isColor = /Color$/.test(key),
- part = Base.capitalize(key),
- flag = flags[key],
- set = 'set' + part,
- get = 'get' + part;
-
- fields[set] = function(value) {
- var children = this._item && this._item._children;
- if (children && children.length > 0
- && this._item._type !== 'compound-path') {
- for (var i = 0, l = children.length; i < l; i++)
- children[i]._style[set](value);
- } else {
- var old = this._values[key];
- if (old != value) {
- if (isColor) {
- if (old)
- delete old._owner;
- if (value && value.constructor === Color) {
- if (value._owner)
- value = value.clone();
- value._owner = this._item;
- }
- }
- this._values[key] = value;
- if (this._item)
- this._item._changed(flag || 17);
- }
- }
- };
-
- fields[get] = function() {
- var value,
- children = this._item && this._item._children;
- if (!children || children.length === 0 || arguments[0]
- || this._item._type === 'compound-path') {
- var value = this._values[key];
- if (value === undefined) {
- value = this._defaults[key];
- if (value && value.clone)
- value = value.clone();
- this._values[key] = value;
- } else if (isColor && !(value && value.constructor === Color)) {
- this._values[key] = value = Color.read(
- [value], 0, 0, { readNull: true, clone: true });
- if (value)
- value._owner = this._item;
- }
- return value;
- }
- for (var i = 0, l = children.length; i < l; i++) {
- var childValue = children[i]._style[get]();
- if (i === 0) {
- value = childValue;
- } else if (!Base.equals(value, childValue)) {
- return undefined;
- }
- }
- return value;
- };
-
- item[get] = function() {
- return this._style[get]();
- };
-
- item[set] = function(value) {
- this._style[set](value);
- };
- });
-
- Item.inject(item);
- return fields;
-}, {
- _class: 'Style',
-
- initialize: function Style(style, _item) {
- this._values = {};
- this._item = _item;
- if (_item instanceof TextItem)
- this._defaults = this._textDefaults;
- if (style)
- this.set(style);
- },
-
- set: function(style) {
- var isStyle = style instanceof Style,
- values = isStyle ? style._values : style;
- if (values) {
- for (var key in values) {
- if (key in this._defaults) {
- var value = values[key];
- this[key] = value && isStyle && value.clone
- ? value.clone() : value;
- }
- }
- }
- },
-
- equals: function(style) {
- return style === this || style && this._class === style._class
- && Base.equals(this._values, style._values)
- || false;
- },
-
- hasFill: function() {
- return !!this.getFillColor();
- },
-
- hasStroke: function() {
- return !!this.getStrokeColor() && this.getStrokeWidth() > 0;
- },
-
- hasShadow: function() {
- return !!this.getShadowColor() && this.getShadowBlur() > 0;
- },
-
- getLeading: function getLeading() {
- var leading = getLeading.base.call(this);
- return leading != null ? leading : this.getFontSize() * 1.2;
- },
-
- getFontStyle: function() {
- var size = this.getFontSize();
- return size + (/[a-z]/i.test(size + '') ? ' ' : 'px ') + this.getFont();
- }
-
-});
-
-var DomElement = new function() {
-
- var special = /^(checked|value|selected|disabled)$/i,
- translated = { text: 'textContent', html: 'innerHTML' },
- unitless = { lineHeight: 1, zoom: 1, zIndex: 1, opacity: 1 };
-
- function create(nodes, parent) {
- var res = [];
- for (var i = 0, l = nodes && nodes.length; i < l;) {
- var el = nodes[i++];
- if (typeof el === 'string') {
- el = document.createElement(el);
- } else if (!el || !el.nodeType) {
- continue;
- }
- if (Base.isPlainObject(nodes[i]))
- DomElement.set(el, nodes[i++]);
- if (Array.isArray(nodes[i]))
- create(nodes[i++], el);
- if (parent)
- parent.appendChild(el);
- res.push(el);
- }
- return res;
- }
-
- return {
- create: function(nodes, parent) {
- var isArray = Array.isArray(nodes),
- res = create(isArray ? nodes : arguments, isArray ? parent : null);
- return res.length == 1 ? res[0] : res;
- },
-
- find: function(selector, root) {
- return (root || document).querySelector(selector);
- },
-
- findAll: function(selector, root) {
- return (root || document).querySelectorAll(selector);
- },
-
- get: function(el, key) {
- return el
- ? special.test(key)
- ? key === 'value' || typeof el[key] !== 'string'
- ? el[key]
- : true
- : key in translated
- ? el[translated[key]]
- : el.getAttribute(key)
- : null;
- },
-
- set: function(el, key, value) {
- if (typeof key !== 'string') {
- for (var name in key)
- if (key.hasOwnProperty(name))
- this.set(el, name, key[name]);
- } else if (!el || value === undefined) {
- return el;
- } else if (special.test(key)) {
- el[key] = value;
- } else if (key in translated) {
- el[translated[key]] = value;
- } else if (key === 'style') {
- this.setStyle(el, value);
- } else if (key === 'events') {
- DomEvent.add(el, value);
- } else {
- el.setAttribute(key, value);
- }
- return el;
- },
-
- getStyles: function(el) {
- var doc = el && el.nodeType !== 9 ? el.ownerDocument : el,
- view = doc && doc.defaultView;
- return view && view.getComputedStyle(el, '');
- },
-
- getStyle: function(el, key) {
- return el && el.style[key] || this.getStyles(el)[key] || null;
- },
-
- setStyle: function(el, key, value) {
- if (typeof key !== 'string') {
- for (var name in key)
- if (key.hasOwnProperty(name))
- this.setStyle(el, name, key[name]);
- } else {
- if (/^-?[\d\.]+$/.test(value) && !(key in unitless))
- value += 'px';
- el.style[key] = value;
- }
- return el;
- },
-
- hasClass: function(el, cls) {
- return new RegExp('\\s*' + cls + '\\s*').test(el.className);
- },
-
- addClass: function(el, cls) {
- el.className = (el.className + ' ' + cls).trim();
- },
-
- removeClass: function(el, cls) {
- el.className = el.className.replace(
- new RegExp('\\s*' + cls + '\\s*'), ' ').trim();
- },
-
- remove: function(el) {
- if (el.parentNode)
- el.parentNode.removeChild(el);
- },
-
- removeChildren: function(el) {
- while (el.firstChild)
- el.removeChild(el.firstChild);
- },
-
- getBounds: function(el, viewport) {
- var doc = el.ownerDocument,
- body = doc.body,
- html = doc.documentElement,
- rect;
- try {
- rect = el.getBoundingClientRect();
- } catch (e) {
- rect = { left: 0, top: 0, width: 0, height: 0 };
- }
- var x = rect.left - (html.clientLeft || body.clientLeft || 0),
- y = rect.top - (html.clientTop || body.clientTop || 0);
- if (!viewport) {
- var view = doc.defaultView;
- x += view.pageXOffset || html.scrollLeft || body.scrollLeft;
- y += view.pageYOffset || html.scrollTop || body.scrollTop;
- }
- return new Rectangle(x, y, rect.width, rect.height);
- },
-
- getViewportBounds: function(el) {
- var doc = el.ownerDocument,
- view = doc.defaultView,
- html = doc.documentElement;
- return new Rectangle(0, 0,
- view.innerWidth || html.clientWidth,
- view.innerHeight || html.clientHeight
- );
- },
-
- getOffset: function(el, viewport) {
- return this.getBounds(el, viewport).getPoint();
- },
-
- getSize: function(el) {
- return this.getBounds(el, true).getSize();
- },
-
- isInvisible: function(el) {
- return this.getSize(el).equals(new Size(0, 0));
- },
-
- isInView: function(el) {
- return !this.isInvisible(el) && this.getViewportBounds(el).intersects(
- this.getBounds(el, true));
- },
-
- getPrefixValue: function(el, name) {
- var value = el[name],
- prefixes = ['webkit', 'moz', 'ms', 'o'],
- suffix = name[0].toUpperCase() + name.substring(1);
- for (var i = 0; i < 4 && value == null; i++)
- value = el[prefixes[i] + suffix];
- return value;
- }
- };
-};
-
-var DomEvent = {
- add: function(el, events) {
- for (var type in events) {
- var func = events[type];
- if (el.addEventListener) {
- el.addEventListener(type, func, false);
- } else if (el.attachEvent) {
- el.attachEvent('on' + type, func.bound = function() {
- func.call(el, window.event);
- });
- }
- }
- },
-
- remove: function(el, events) {
- for (var type in events) {
- var func = events[type];
- if (el.removeEventListener) {
- el.removeEventListener(type, func, false);
- } else if (el.detachEvent) {
- el.detachEvent('on' + type, func.bound);
- }
- }
- },
-
- getPoint: function(event) {
- var pos = event.targetTouches
- ? event.targetTouches.length
- ? event.targetTouches[0]
- : event.changedTouches[0]
- : event;
- return new Point(
- pos.pageX || pos.clientX + document.documentElement.scrollLeft,
- pos.pageY || pos.clientY + document.documentElement.scrollTop
- );
- },
-
- getTarget: function(event) {
- return event.target || event.srcElement;
- },
-
- getOffset: function(event, target) {
- return DomEvent.getPoint(event).subtract(DomElement.getOffset(
- target || DomEvent.getTarget(event)));
- },
-
- preventDefault: function(event) {
- if (event.preventDefault) {
- event.preventDefault();
- } else {
- event.returnValue = false;
- }
- },
-
- stopPropagation: function(event) {
- if (event.stopPropagation) {
- event.stopPropagation();
- } else {
- event.cancelBubble = true;
- }
- },
-
- stop: function(event) {
- DomEvent.stopPropagation(event);
- DomEvent.preventDefault(event);
- }
-};
-
-DomEvent.requestAnimationFrame = new function() {
- var nativeRequest = DomElement.getPrefixValue(window,
- 'requestAnimationFrame'),
- requested = false,
- callbacks = [],
- focused = true,
- timer;
-
- DomEvent.add(window, {
- focus: function() {
- focused = true;
- },
- blur: function() {
- focused = false;
- }
- });
-
- function handleCallbacks() {
- for (var i = callbacks.length - 1; i >= 0; i--) {
- var entry = callbacks[i],
- func = entry[0],
- el = entry[1];
- if (!el || (PaperScope.getAttribute(el, 'keepalive') == 'true'
- || focused) && DomElement.isInView(el)) {
- callbacks.splice(i, 1);
- func();
- }
- }
- if (nativeRequest) {
- if (callbacks.length) {
- nativeRequest(handleCallbacks);
- } else {
- requested = false;
- }
- }
- }
-
- return function(callback, element) {
- callbacks.push([callback, element]);
- if (nativeRequest) {
- if (!requested) {
- nativeRequest(handleCallbacks);
- requested = true;
- }
- } else if (!timer) {
- timer = setInterval(handleCallbacks, 1000 / 60);
- }
- };
-};
-
-var View = Base.extend(Callback, {
- _class: 'View',
-
- initialize: function View(element) {
- this._scope = paper;
- this._project = paper.project;
- this._element = element;
- var size;
- this._id = element.getAttribute('id');
- if (this._id == null)
- element.setAttribute('id', this._id = 'view-' + View._id++);
- DomEvent.add(element, this._viewHandlers);
- if (PaperScope.hasAttribute(element, 'resize')) {
- var offset = DomElement.getOffset(element, true),
- that = this;
- size = DomElement.getViewportBounds(element)
- .getSize().subtract(offset);
- this._windowHandlers = {
- resize: function() {
- if (!DomElement.isInvisible(element))
- offset = DomElement.getOffset(element, true);
- that.setViewSize(DomElement.getViewportBounds(element)
- .getSize().subtract(offset));
- }
- };
- DomEvent.add(window, this._windowHandlers);
- } else {
- size = DomElement.getSize(element);
- if (size.isNaN() || size.isZero())
- size = new Size(parseInt(element.getAttribute('width'), 10),
- parseInt(element.getAttribute('height'), 10));
- }
- this._setViewSize(size);
- if (PaperScope.hasAttribute(element, 'stats')
- && typeof Stats !== 'undefined') {
- this._stats = new Stats();
- var stats = this._stats.domElement,
- style = stats.style,
- offset = DomElement.getOffset(element);
- style.position = 'absolute';
- style.left = offset.x + 'px';
- style.top = offset.y + 'px';
- document.body.appendChild(stats);
- }
- View._views.push(this);
- View._viewsById[this._id] = this;
- this._viewSize = size;
- (this._matrix = new Matrix())._owner = this;
- this._zoom = 1;
- if (!View._focused)
- View._focused = this;
- this._frameItems = {};
- this._frameItemCount = 0;
- },
-
- remove: function() {
- if (!this._project)
- return false;
- if (View._focused == this)
- View._focused = null;
- View._views.splice(View._views.indexOf(this), 1);
- delete View._viewsById[this._id];
- if (this._project.view == this)
- this._project.view = null;
- DomEvent.remove(this._element, this._viewHandlers);
- DomEvent.remove(window, this._windowHandlers);
- this._element = this._project = null;
- this.detach('frame');
- this._frameItems = {};
- return true;
- },
-
- _events: {
- onFrame: {
- install: function() {
- this._animate = true;
- if (!this._requested)
- this._requestFrame();
- },
-
- uninstall: function() {
- this._animate = false;
- }
- },
-
- onResize: {}
- },
-
- _animate: false,
- _time: 0,
- _count: 0,
-
- _requestFrame: function() {
- var that = this;
- DomEvent.requestAnimationFrame(function() {
- that._requested = false;
- if (!that._animate)
- return;
- that._requestFrame();
- that._handleFrame();
- }, this._element);
- this._requested = true;
- },
-
- _handleFrame: function() {
- paper = this._scope;
- var now = Date.now() / 1000,
- delta = this._before ? now - this._before : 0;
- this._before = now;
- this._handlingFrame = true;
- this.fire('frame', new Base({
- delta: delta,
- time: this._time += delta,
- count: this._count++
- }));
- if (this._stats)
- this._stats.update();
- this._handlingFrame = false;
- this.draw(true);
- },
-
- _animateItem: function(item, animate) {
- var items = this._frameItems;
- if (animate) {
- items[item._id] = {
- item: item,
- time: 0,
- count: 0
- };
- if (++this._frameItemCount === 1)
- this.attach('frame', this._handleFrameItems);
- } else {
- delete items[item._id];
- if (--this._frameItemCount === 0) {
- this.detach('frame', this._handleFrameItems);
- }
- }
- },
-
- _handleFrameItems: function(event) {
- for (var i in this._frameItems) {
- var entry = this._frameItems[i];
- entry.item.fire('frame', new Base(event, {
- time: entry.time += event.delta,
- count: entry.count++
- }));
- }
- },
-
- _redraw: function() {
- this._project._needsRedraw = true;
- if (this._handlingFrame)
- return;
- if (this._animate) {
- this._handleFrame();
- } else {
- this.draw();
- }
- },
-
- _changed: function(flags) {
- if (flags & 1)
- this._project._needsRedraw = true;
- },
-
- _transform: function(matrix) {
- this._matrix.concatenate(matrix);
- this._bounds = null;
- this._redraw();
- },
-
- getElement: function() {
- return this._element;
- },
-
- getViewSize: function() {
- var size = this._viewSize;
- return new LinkedSize(size.width, size.height, this, 'setViewSize');
- },
-
- setViewSize: function(size) {
- size = Size.read(arguments);
- var delta = size.subtract(this._viewSize);
- if (delta.isZero())
- return;
- this._viewSize.set(size.width, size.height);
- this._setViewSize(size);
- this._bounds = null;
- this.fire('resize', {
- size: size,
- delta: delta
- });
- this._redraw();
- },
-
- _setViewSize: function(size) {
- var element = this._element;
- element.width = size.width;
- element.height = size.height;
- },
-
- getBounds: function() {
- if (!this._bounds)
- this._bounds = this._matrix.inverted()._transformBounds(
- new Rectangle(new Point(), this._viewSize));
- return this._bounds;
- },
-
- getSize: function() {
- return this.getBounds().getSize(arguments[0]);
- },
-
- getCenter: function() {
- return this.getBounds().getCenter(arguments[0]);
- },
-
- setCenter: function(center) {
- center = Point.read(arguments);
- this.scrollBy(center.subtract(this.getCenter()));
- },
-
- getZoom: function() {
- return this._zoom;
- },
-
- setZoom: function(zoom) {
- this._transform(new Matrix().scale(zoom / this._zoom,
- this.getCenter()));
- this._zoom = zoom;
- },
-
- isVisible: function() {
- return DomElement.isInView(this._element);
- },
-
- scrollBy: function() {
- this._transform(new Matrix().translate(Point.read(arguments).negate()));
- },
-
- projectToView: function() {
- return this._matrix._transformPoint(Point.read(arguments));
- },
-
- viewToProject: function() {
- return this._matrix._inverseTransform(Point.read(arguments));
- },
-
-}, {
- statics: {
- _views: [],
- _viewsById: {},
- _id: 0,
-
- create: function(element) {
- if (typeof element === 'string')
- element = document.getElementById(element);
- return new CanvasView(element);
- }
- }
-}, new function() {
- var tool,
- prevFocus,
- tempFocus,
- dragging = false;
-
- function getView(event) {
- var target = DomEvent.getTarget(event);
- return target.getAttribute && View._viewsById[target.getAttribute('id')];
- }
-
- function viewToProject(view, event) {
- return view.viewToProject(DomEvent.getOffset(event, view._element));
- }
-
- function updateFocus() {
- if (!View._focused || !View._focused.isVisible()) {
- for (var i = 0, l = View._views.length; i < l; i++) {
- var view = View._views[i];
- if (view && view.isVisible()) {
- View._focused = tempFocus = view;
- break;
- }
- }
- }
- }
-
- function mousedown(event) {
- var view = View._focused = getView(event),
- point = viewToProject(view, event);
- dragging = true;
- if (view._onMouseDown)
- view._onMouseDown(event, point);
- if (tool = view._scope._tool)
- tool._onHandleEvent('mousedown', point, event);
- view.draw(true);
- }
-
- function mousemove(event) {
- var view;
- if (!dragging) {
- view = getView(event);
- if (view) {
- prevFocus = View._focused;
- View._focused = tempFocus = view;
- } else if (tempFocus && tempFocus == View._focused) {
- View._focused = prevFocus;
- updateFocus();
- }
- }
- if (!(view = view || View._focused))
- return;
- var point = event && viewToProject(view, event);
- if (view._onMouseMove)
- view._onMouseMove(event, point);
- if (tool = view._scope._tool) {
- if (tool._onHandleEvent(dragging && tool.responds('mousedrag')
- ? 'mousedrag' : 'mousemove', point, event))
- DomEvent.stop(event);
- }
- view.draw(true);
- }
-
- function mouseup(event) {
- var view = View._focused;
- if (!view || !dragging)
- return;
- var point = viewToProject(view, event);
- curPoint = null;
- dragging = false;
- if (view._onMouseUp)
- view._onMouseUp(event, point);
- if (tool && tool._onHandleEvent('mouseup', point, event))
- DomEvent.stop(event);
- view.draw(true);
- }
-
- function selectstart(event) {
- if (dragging)
- DomEvent.stop(event);
- }
-
- DomEvent.add(document, {
- mousemove: mousemove,
- mouseup: mouseup,
- touchmove: mousemove,
- touchend: mouseup,
- selectstart: selectstart,
- scroll: updateFocus
- });
-
- DomEvent.add(window, {
- load: updateFocus
- });
-
- return {
- _viewHandlers: {
- mousedown: mousedown,
- touchstart: mousedown,
- selectstart: selectstart
- },
-
- statics: {
- updateFocus: updateFocus
- }
- };
-});
-
-var CanvasView = View.extend({
- _class: 'CanvasView',
-
- initialize: function CanvasView(canvas) {
- if (!(canvas instanceof HTMLCanvasElement)) {
- var size = Size.read(arguments);
- if (size.isZero())
- throw new Error(
- 'Cannot create CanvasView with the provided argument: '
- + canvas);
- canvas = CanvasProvider.getCanvas(size);
- }
- this._context = canvas.getContext('2d');
- this._eventCounters = {};
- this._ratio = 1;
- if (PaperScope.getAttribute(canvas, 'hidpi') !== 'off') {
- var deviceRatio = window.devicePixelRatio || 1,
- backingStoreRatio = DomElement.getPrefixValue(this._context,
- 'backingStorePixelRatio') || 1;
- this._ratio = deviceRatio / backingStoreRatio;
- }
- View.call(this, canvas);
- },
-
- _setViewSize: function(size) {
- var width = size.width,
- height = size.height,
- ratio = this._ratio,
- element = this._element,
- style = element.style;
- element.width = width * ratio;
- element.height = height * ratio;
- if (ratio !== 1) {
- style.width = width + 'px';
- style.height = height + 'px';
- this._context.scale(ratio, ratio);
- }
- },
-
- draw: function(checkRedraw) {
- if (checkRedraw && !this._project._needsRedraw)
- return false;
- var ctx = this._context,
- size = this._viewSize;
- ctx.clearRect(0, 0, size.width + 1, size.height + 1);
- this._project.draw(ctx, this._matrix, this._ratio);
- this._project._needsRedraw = false;
- return true;
- }
-}, new function() {
-
- var downPoint,
- lastPoint,
- overPoint,
- downItem,
- lastItem,
- overItem,
- hasDrag,
- doubleClick,
- clickTime;
-
- function callEvent(type, event, point, target, lastPoint, bubble) {
- var item = target,
- mouseEvent;
- while (item) {
- if (item.responds(type)) {
- if (!mouseEvent)
- mouseEvent = new MouseEvent(type, event, point, target,
- lastPoint ? point.subtract(lastPoint) : null);
- if (item.fire(type, mouseEvent)
- && (!bubble || mouseEvent._stopped))
- return false;
- }
- item = item.getParent();
- }
- return true;
- }
-
- function handleEvent(view, type, event, point, lastPoint) {
- if (view._eventCounters[type]) {
- var project = view._project,
- hit = project.hitTest(point, {
- tolerance: project.options.hitTolerance || 0,
- fill: true,
- stroke: true
- }),
- item = hit && hit.item;
- if (item) {
- if (type === 'mousemove' && item != overItem)
- lastPoint = point;
- if (type !== 'mousemove' || !hasDrag)
- callEvent(type, event, point, item, lastPoint);
- return item;
- }
- }
- }
-
- return {
- _onMouseDown: function(event, point) {
- var item = handleEvent(this, 'mousedown', event, point);
- doubleClick = lastItem == item && (Date.now() - clickTime < 300);
- downItem = lastItem = item;
- downPoint = lastPoint = overPoint = point;
- hasDrag = downItem && downItem.responds('mousedrag');
- },
-
- _onMouseUp: function(event, point) {
- var item = handleEvent(this, 'mouseup', event, point);
- if (hasDrag) {
- if (lastPoint && !lastPoint.equals(point))
- callEvent('mousedrag', event, point, downItem, lastPoint);
- if (item != downItem) {
- overPoint = point;
- callEvent('mousemove', event, point, item, overPoint);
- }
- }
- if (item === downItem) {
- clickTime = Date.now();
- if (!doubleClick
- || callEvent('doubleclick', event, downPoint, item))
- callEvent('click', event, downPoint, item);
- doubleClick = false;
- }
- downItem = null;
- hasDrag = false;
- },
-
- _onMouseMove: function(event, point) {
- if (downItem)
- callEvent('mousedrag', event, point, downItem, lastPoint);
- var item = handleEvent(this, 'mousemove', event, point, overPoint);
- lastPoint = overPoint = point;
- if (item !== overItem) {
- callEvent('mouseleave', event, point, overItem);
- overItem = item;
- callEvent('mouseenter', event, point, item);
- }
- }
- };
-});
-
-var Event = Base.extend({
- _class: 'Event',
-
- initialize: function Event(event) {
- this.event = event;
- },
-
- preventDefault: function() {
- this._prevented = true;
- DomEvent.preventDefault(this.event);
- },
-
- stopPropagation: function() {
- this._stopped = true;
- DomEvent.stopPropagation(this.event);
- },
-
- stop: function() {
- this.stopPropagation();
- this.preventDefault();
- },
-
- getModifiers: function() {
- return Key.modifiers;
- }
-});
-
-var KeyEvent = Event.extend({
- _class: 'KeyEvent',
-
- initialize: function KeyEvent(down, key, character, event) {
- Event.call(this, event);
- this.type = down ? 'keydown' : 'keyup';
- this.key = key;
- this.character = character;
- },
-
- toString: function() {
- return "{ type: '" + this.type
- + "', key: '" + this.key
- + "', character: '" + this.character
- + "', modifiers: " + this.getModifiers()
- + " }";
- }
-});
-
-var Key = new function() {
-
- var specialKeys = {
- 8: 'backspace',
- 9: 'tab',
- 13: 'enter',
- 16: 'shift',
- 17: 'control',
- 18: 'option',
- 19: 'pause',
- 20: 'caps-lock',
- 27: 'escape',
- 32: 'space',
- 35: 'end',
- 36: 'home',
- 37: 'left',
- 38: 'up',
- 39: 'right',
- 40: 'down',
- 46: 'delete',
- 91: 'command',
- 93: 'command',
- 224: 'command'
- },
-
- specialChars = {
- 9: true,
- 13: true,
- 32: true
- },
-
- modifiers = new Base({
- shift: false,
- control: false,
- option: false,
- command: false,
- capsLock: false,
- space: false
- }),
-
- charCodeMap = {},
- keyMap = {},
- downCode;
-
- function handleKey(down, keyCode, charCode, event) {
- var character = charCode ? String.fromCharCode(charCode) : '',
- specialKey = specialKeys[keyCode],
- key = specialKey || character.toLowerCase(),
- type = down ? 'keydown' : 'keyup',
- view = View._focused,
- scope = view && view.isVisible() && view._scope,
- tool = scope && scope._tool,
- name;
- keyMap[key] = down;
- if (specialKey && (name = Base.camelize(specialKey)) in modifiers)
- modifiers[name] = down;
- if (down) {
- charCodeMap[keyCode] = charCode;
- } else {
- delete charCodeMap[keyCode];
- }
- if (tool && tool.responds(type)) {
- paper = scope;
- tool.fire(type, new KeyEvent(down, key, character, event));
- if (view)
- view.draw(true);
- }
- }
-
- DomEvent.add(document, {
- keydown: function(event) {
- var code = event.which || event.keyCode;
- if (code in specialKeys) {
- handleKey(true, code, code in specialChars ? code : 0, event);
- } else {
- downCode = code;
- }
- },
-
- keypress: function(event) {
- if (downCode != null) {
- handleKey(true, downCode, event.which || event.keyCode, event);
- downCode = null;
- }
- },
-
- keyup: function(event) {
- var code = event.which || event.keyCode;
- if (code in charCodeMap)
- handleKey(false, code, charCodeMap[code], event);
- }
- });
-
- DomEvent.add(window, {
- blur: function(event) {
- for (var code in charCodeMap)
- handleKey(false, code, charCodeMap[code], event);
- }
- });
-
- return {
- modifiers: modifiers,
-
- isDown: function(key) {
- return !!keyMap[key];
- }
- };
-};
-
-var MouseEvent = Event.extend({
- _class: 'MouseEvent',
-
- initialize: function MouseEvent(type, event, point, target, delta) {
- Event.call(this, event);
- this.type = type;
- this.point = point;
- this.target = target;
- this.delta = delta;
- },
-
- toString: function() {
- return "{ type: '" + this.type
- + "', point: " + this.point
- + ', target: ' + this.target
- + (this.delta ? ', delta: ' + this.delta : '')
- + ', modifiers: ' + this.getModifiers()
- + ' }';
- }
-});
-
- Base.extend(Callback, {
- _class: 'Palette',
- _events: [ 'onChange' ],
-
- initialize: function Palette(title, components, values) {
- var parent = DomElement.find('.palettejs-panel')
- || DomElement.find('body').appendChild(
- DomElement.create('div', { 'class': 'palettejs-panel' }));
- this._element = parent.appendChild(
- DomElement.create('table', { 'class': 'palettejs-pane' }));
- this._title = title;
- if (!values)
- values = {};
- for (var name in (this.components = components)) {
- var component = components[name];
- if (!(component instanceof Component)) {
- if (component.value == null)
- component.value = values[name];
- component.name = name;
- component = components[name] = new Component(component);
- }
- this._element.appendChild(component._element);
- component._palette = this;
- if (values[name] === undefined)
- values[name] = component.value;
- }
- this.values = Base.each(values, function(value, name) {
- var component = components[name];
- if (component) {
- Base.define(values, name, {
- enumerable: true,
- configurable: true,
- get: function() {
- return component._value;
- },
- set: function(val) {
- component.setValue(val);
- }
- });
- }
- });
- if (window.paper)
- paper.palettes.push(this);
- },
-
- reset: function() {
- for (var i in this.components)
- this.components[i].reset();
- },
-
- remove: function() {
- DomElement.remove(this._element);
- }
-});
-
-var Component = Base.extend(Callback, {
- _class: 'Component',
- _events: [ 'onChange', 'onClick' ],
-
- _types: {
- 'boolean': {
- type: 'checkbox',
- value: 'checked'
- },
-
- string: {
- type: 'text'
- },
-
- number: {
- type: 'number',
- number: true
- },
-
- button: {
- type: 'button'
- },
-
- text: {
- tag: 'div',
- value: 'text'
- },
-
- slider: {
- type: 'range',
- number: true
- },
-
- list: {
- tag: 'select',
-
- setOptions: function() {
- DomElement.removeChildren(this._input);
- DomElement.create(Base.each(this._options, function(option) {
- this.push('option', { value: option, text: option });
- }, []), this._input);
- }
- },
-
- color: {
- type: 'color',
-
- getValue: function(value) {
- return new Color(value);
- },
-
- setValue: function(value) {
- return new Color(value).toCSS(
- DomElement.get(this._input, 'type') === 'color');
- }
- }
- },
-
- initialize: function Component(obj) {
- this._id = Component._id = (Component._id || 0) + 1;
- this._type = obj.type in this._types
- ? obj.type
- : 'options' in obj
- ? 'list'
- : 'onClick' in obj
- ? 'button'
- : typeof obj.value;
- this._meta = this._types[this._type] || { type: this._type };
- var that = this,
- id = 'component-' + this._id;
- this._dontFire = true;
- this._input = DomElement.create(this._meta.tag || 'input', {
- id: id,
- type: this._meta.type,
- events: {
- change: function() {
- that.setValue(
- DomElement.get(this, that._meta.value || 'value'));
- },
- click: function() {
- that.fire('click');
- }
- }
- });
- this.attach('change', function(value) {
- if (!this._dontFire)
- this._palette.fire('change', this, this.name, value);
- });
- this._element = DomElement.create('tr', [
- 'td', [this._label = DomElement.create('label', { 'for': id })],
- 'td', [this._input]
- ]);
- Base.each(obj, function(value, key) {
- this[key] = value;
- }, this);
- this._defaultValue = this._value;
- this._dontFire = false;
- },
-
- getType: function() {
- return this._type;
- },
-
- getLabel: function() {
- return this.__label;
- },
-
- setLabel: function(label) {
- this.__label = label;
- DomElement.set(this._label, 'text', label + ':');
- },
-
- getOptions: function() {
- return this._options;
- },
-
- setOptions: function(options) {
- this._options = options;
- var setOptions = this._meta.setOptions;
- if (setOptions)
- setOptions.call(this);
- },
-
- getValue: function() {
- var value = this._value,
- getValue = this._meta.getValue;
- return getValue ? getValue.call(this, value) : value;
- },
-
- setValue: function(value) {
- var key = this._meta.value || 'value',
- setValue = this._meta.setValue;
- if (setValue)
- value = setValue.call(this, value);
- DomElement.set(this._input, key, value);
- value = DomElement.get(this._input, key);
- if (this._meta.number)
- value = parseFloat(value, 10);
- if (this._value !== value) {
- this._value = value;
- if (!this._dontFire)
- this.fire('change', this.getValue());
- }
- },
-
- getRange: function() {
- return [parseFloat(DomElement.get(this._input, 'min')),
- parseFloat(DomElement.get(this._input, 'max'))];
- },
-
- setRange: function(min, max) {
- var range = Array.isArray(min) ? min : [min, max];
- DomElement.set(this._input, { min: range[0], max: range[1] });
- },
-
- getMin: function() {
- return this.getRange()[0];
- },
-
- setMin: function(min) {
- this.setRange(min, this.getMax());
- },
-
- getMax: function() {
- return this.getRange()[1];
- },
-
- setMax: function(max) {
- this.setRange(this.getMin(), max);
- },
-
- getStep: function() {
- return parseFloat(DomElement.get(this._input, 'step'));
- },
-
- setStep: function(step) {
- DomElement.set(this._input, 'step', step);
- },
-
- reset: function() {
- this.setValue(this._defaultValue);
- }
-});
-
-var ToolEvent = Event.extend({
- _class: 'ToolEvent',
- _item: null,
-
- initialize: function ToolEvent(tool, type, event) {
- this.tool = tool;
- this.type = type;
- this.event = event;
- },
-
- _choosePoint: function(point, toolPoint) {
- return point ? point : toolPoint ? toolPoint.clone() : null;
- },
-
- getPoint: function() {
- return this._choosePoint(this._point, this.tool._point);
- },
-
- setPoint: function(point) {
- this._point = point;
- },
-
- getLastPoint: function() {
- return this._choosePoint(this._lastPoint, this.tool._lastPoint);
- },
-
- setLastPoint: function(lastPoint) {
- this._lastPoint = lastPoint;
- },
-
- getDownPoint: function() {
- return this._choosePoint(this._downPoint, this.tool._downPoint);
- },
-
- setDownPoint: function(downPoint) {
- this._downPoint = downPoint;
- },
-
- getMiddlePoint: function() {
- if (!this._middlePoint && this.tool._lastPoint) {
- return this.tool._point.add(this.tool._lastPoint).divide(2);
- }
- return this._middlePoint;
- },
-
- setMiddlePoint: function(middlePoint) {
- this._middlePoint = middlePoint;
- },
-
- getDelta: function() {
- return !this._delta && this.tool._lastPoint
- ? this.tool._point.subtract(this.tool._lastPoint)
- : this._delta;
- },
-
- setDelta: function(delta) {
- this._delta = delta;
- },
-
- getCount: function() {
- return /^mouse(down|up)$/.test(this.type)
- ? this.tool._downCount
- : this.tool._count;
- },
-
- setCount: function(count) {
- this.tool[/^mouse(down|up)$/.test(this.type) ? 'downCount' : 'count']
- = count;
- },
-
- getItem: function() {
- if (!this._item) {
- var result = this.tool._scope.project.hitTest(this.getPoint());
- if (result) {
- var item = result.item,
- parent = item._parent;
- while (/^(group|compound-path)$/.test(parent._type)) {
- item = parent;
- parent = parent._parent;
- }
- this._item = item;
- }
- }
- return this._item;
- },
- setItem: function(item) {
- this._item = item;
- },
-
- toString: function() {
- return '{ type: ' + this.type
- + ', point: ' + this.getPoint()
- + ', count: ' + this.getCount()
- + ', modifiers: ' + this.getModifiers()
- + ' }';
- }
-});
-
-var Tool = PaperScopeItem.extend({
- _class: 'Tool',
- _list: 'tools',
- _reference: '_tool',
- _events: [ 'onActivate', 'onDeactivate', 'onEditOptions',
- 'onMouseDown', 'onMouseUp', 'onMouseDrag', 'onMouseMove',
- 'onKeyDown', 'onKeyUp' ],
-
- initialize: function Tool(props) {
- PaperScopeItem.call(this);
- this._firstMove = true;
- this._count = 0;
- this._downCount = 0;
- this._set(props);
- },
-
- getMinDistance: function() {
- return this._minDistance;
- },
-
- setMinDistance: function(minDistance) {
- this._minDistance = minDistance;
- if (this._minDistance != null && this._maxDistance != null
- && this._minDistance > this._maxDistance) {
- this._maxDistance = this._minDistance;
- }
- },
-
- getMaxDistance: function() {
- return this._maxDistance;
- },
-
- setMaxDistance: function(maxDistance) {
- this._maxDistance = maxDistance;
- if (this._minDistance != null && this._maxDistance != null
- && this._maxDistance < this._minDistance) {
- this._minDistance = maxDistance;
- }
- },
-
- getFixedDistance: function() {
- return this._minDistance == this._maxDistance
- ? this._minDistance : null;
- },
-
- setFixedDistance: function(distance) {
- this._minDistance = distance;
- this._maxDistance = distance;
- },
-
- _updateEvent: function(type, point, minDistance, maxDistance, start,
- needsChange, matchMaxDistance) {
- if (!start) {
- if (minDistance != null || maxDistance != null) {
- var minDist = minDistance != null ? minDistance : 0,
- vector = point.subtract(this._point),
- distance = vector.getLength();
- if (distance < minDist)
- return false;
- var maxDist = maxDistance != null ? maxDistance : 0;
- if (maxDist != 0) {
- if (distance > maxDist) {
- point = this._point.add(vector.normalize(maxDist));
- } else if (matchMaxDistance) {
- return false;
- }
- }
- }
- if (needsChange && point.equals(this._point))
- return false;
- }
- this._lastPoint = start && type == 'mousemove' ? point : this._point;
- this._point = point;
- switch (type) {
- case 'mousedown':
- this._lastPoint = this._downPoint;
- this._downPoint = this._point;
- this._downCount++;
- break;
- case 'mouseup':
- this._lastPoint = this._downPoint;
- break;
- }
- this._count = start ? 0 : this._count + 1;
- return true;
- },
-
- _fireEvent: function(type, event) {
- var sets = paper.project._removeSets;
- if (sets) {
- if (type === 'mouseup')
- sets.mousedrag = null;
- var set = sets[type];
- if (set) {
- for (var id in set) {
- var item = set[id];
- for (var key in sets) {
- var other = sets[key];
- if (other && other != set)
- delete other[item._id];
- }
- item.remove();
- }
- sets[type] = null;
- }
- }
- return this.responds(type)
- && this.fire(type, new ToolEvent(this, type, event));
- },
-
- _onHandleEvent: function(type, point, event) {
- paper = this._scope;
- var called = false;
- switch (type) {
- case 'mousedown':
- this._updateEvent(type, point, null, null, true, false, false);
- called = this._fireEvent(type, event);
- break;
- case 'mousedrag':
- var needsChange = false,
- matchMaxDistance = false;
- while (this._updateEvent(type, point, this.minDistance,
- this.maxDistance, false, needsChange, matchMaxDistance)) {
- called = this._fireEvent(type, event) || called;
- needsChange = true;
- matchMaxDistance = true;
- }
- break;
- case 'mouseup':
- if (!point.equals(this._point)
- && this._updateEvent('mousedrag', point, this.minDistance,
- this.maxDistance, false, false, false)) {
- called = this._fireEvent('mousedrag', event);
- }
- this._updateEvent(type, point, null, this.maxDistance, false,
- false, false);
- called = this._fireEvent(type, event) || called;
- this._updateEvent(type, point, null, null, true, false, false);
- this._firstMove = true;
- break;
- case 'mousemove':
- while (this._updateEvent(type, point, this.minDistance,
- this.maxDistance, this._firstMove, true, false)) {
- called = this._fireEvent(type, event) || called;
- this._firstMove = false;
- }
- break;
- }
- return called;
- }
-
-});
-
-var Http = {
- request: function(method, url, callback) {
- var xhr = new (window.ActiveXObject || XMLHttpRequest)(
- 'Microsoft.XMLHTTP');
- xhr.open(method.toUpperCase(), url, true);
- if ('overrideMimeType' in xhr)
- xhr.overrideMimeType('text/plain');
- xhr.onreadystatechange = function() {
- if (xhr.readyState === 4) {
- var status = xhr.status;
- if (status === 0 || status === 200) {
- callback.call(xhr, xhr.responseText);
- } else {
- throw new Error('Could not load ' + url + ' (Error '
- + status + ')');
- }
- }
- };
- return xhr.send(null);
- }
-};
-
-var CanvasProvider = {
- canvases: [],
-
- getCanvas: function(width, height, ratio) {
- var canvas,
- init = true;
- if (typeof width === 'object') {
- ratio = height;
- height = width.height;
- width = width.width;
- }
- if (!ratio) {
- ratio = 1;
- } else if (ratio !== 1) {
- width *= ratio;
- height *= ratio;
- }
- if (this.canvases.length) {
- canvas = this.canvases.pop();
- } else {
- canvas = document.createElement('canvas');
- }
- var ctx = canvas.getContext('2d');
- if (canvas.width === width && canvas.height === height) {
- if (init)
- ctx.clearRect(0, 0, width + 1, height + 1);
- } else {
- canvas.width = width;
- canvas.height = height;
- }
- ctx.save();
- if (ratio !== 1)
- ctx.scale(ratio, ratio);
- return canvas;
- },
-
- getContext: function(width, height) {
- return this.getCanvas(width, height).getContext('2d');
- },
-
- release: function(obj) {
- var canvas = obj.canvas ? obj.canvas : obj;
- canvas.getContext('2d').restore();
- this.canvases.push(canvas);
- }
-};
-
-var BlendMode = new function() {
- var min = Math.min,
- max = Math.max,
- abs = Math.abs,
- sr, sg, sb, sa,
- br, bg, bb, ba,
- dr, dg, db;
-
- function getLum(r, g, b) {
- return 0.2989 * r + 0.587 * g + 0.114 * b;
- }
-
- function setLum(r, g, b, l) {
- var d = l - getLum(r, g, b);
- dr = r + d;
- dg = g + d;
- db = b + d;
- var l = getLum(dr, dg, db),
- mn = min(dr, dg, db),
- mx = max(dr, dg, db);
- if (mn < 0) {
- var lmn = l - mn;
- dr = l + (dr - l) * l / lmn;
- dg = l + (dg - l) * l / lmn;
- db = l + (db - l) * l / lmn;
- }
- if (mx > 255) {
- var ln = 255 - l,
- mxl = mx - l;
- dr = l + (dr - l) * ln / mxl;
- dg = l + (dg - l) * ln / mxl;
- db = l + (db - l) * ln / mxl;
- }
- }
-
- function getSat(r, g, b) {
- return max(r, g, b) - min(r, g, b);
- }
-
- function setSat(r, g, b, s) {
- var col = [r, g, b],
- mx = max(r, g, b),
- mn = min(r, g, b),
- md;
- mn = mn === r ? 0 : mn === g ? 1 : 2;
- mx = mx === r ? 0 : mx === g ? 1 : 2;
- md = min(mn, mx) === 0 ? max(mn, mx) === 1 ? 2 : 1 : 0;
- if (col[mx] > col[mn]) {
- col[md] = (col[md] - col[mn]) * s / (col[mx] - col[mn]);
- col[mx] = s;
- } else {
- col[md] = col[mx] = 0;
- }
- col[mn] = 0;
- dr = col[0];
- dg = col[1];
- db = col[2];
- }
-
- var modes = {
- multiply: function() {
- dr = br * sr / 255;
- dg = bg * sg / 255;
- db = bb * sb / 255;
- },
-
- screen: function() {
- dr = br + sr - (br * sr / 255);
- dg = bg + sg - (bg * sg / 255);
- db = bb + sb - (bb * sb / 255);
- },
-
- overlay: function() {
- dr = br < 128 ? 2 * br * sr / 255 : 255 - 2 * (255 - br) * (255 - sr) / 255;
- dg = bg < 128 ? 2 * bg * sg / 255 : 255 - 2 * (255 - bg) * (255 - sg) / 255;
- db = bb < 128 ? 2 * bb * sb / 255 : 255 - 2 * (255 - bb) * (255 - sb) / 255;
- },
-
- 'soft-light': function() {
- var t = sr * br / 255;
- dr = t + br * (255 - (255 - br) * (255 - sr) / 255 - t) / 255;
- t = sg * bg / 255;
- dg = t + bg * (255 - (255 - bg) * (255 - sg) / 255 - t) / 255;
- t = sb * bb / 255;
- db = t + bb * (255 - (255 - bb) * (255 - sb) / 255 - t) / 255;
- },
-
- 'hard-light': function() {
- dr = sr < 128 ? 2 * sr * br / 255 : 255 - 2 * (255 - sr) * (255 - br) / 255;
- dg = sg < 128 ? 2 * sg * bg / 255 : 255 - 2 * (255 - sg) * (255 - bg) / 255;
- db = sb < 128 ? 2 * sb * bb / 255 : 255 - 2 * (255 - sb) * (255 - bb) / 255;
- },
-
- 'color-dodge': function() {
- dr = br === 0 ? 0 : sr === 255 ? 255 : min(255, 255 * br / (255 - sr));
- dg = bg === 0 ? 0 : sg === 255 ? 255 : min(255, 255 * bg / (255 - sg));
- db = bb === 0 ? 0 : sb === 255 ? 255 : min(255, 255 * bb / (255 - sb));
- },
-
- 'color-burn': function() {
- dr = br === 255 ? 255 : sr === 0 ? 0 : max(0, 255 - (255 - br) * 255 / sr);
- dg = bg === 255 ? 255 : sg === 0 ? 0 : max(0, 255 - (255 - bg) * 255 / sg);
- db = bb === 255 ? 255 : sb === 0 ? 0 : max(0, 255 - (255 - bb) * 255 / sb);
- },
-
- darken: function() {
- dr = br < sr ? br : sr;
- dg = bg < sg ? bg : sg;
- db = bb < sb ? bb : sb;
- },
-
- lighten: function() {
- dr = br > sr ? br : sr;
- dg = bg > sg ? bg : sg;
- db = bb > sb ? bb : sb;
- },
-
- difference: function() {
- dr = br - sr;
- if (dr < 0)
- dr = -dr;
- dg = bg - sg;
- if (dg < 0)
- dg = -dg;
- db = bb - sb;
- if (db < 0)
- db = -db;
- },
-
- exclusion: function() {
- dr = br + sr * (255 - br - br) / 255;
- dg = bg + sg * (255 - bg - bg) / 255;
- db = bb + sb * (255 - bb - bb) / 255;
- },
-
- hue: function() {
- setSat(sr, sg, sb, getSat(br, bg, bb));
- setLum(dr, dg, db, getLum(br, bg, bb));
- },
-
- saturation: function() {
- setSat(br, bg, bb, getSat(sr, sg, sb));
- setLum(dr, dg, db, getLum(br, bg, bb));
- },
-
- luminosity: function() {
- setLum(br, bg, bb, getLum(sr, sg, sb));
- },
-
- color: function() {
- setLum(sr, sg, sb, getLum(br, bg, bb));
- },
-
- add: function() {
- dr = min(br + sr, 255);
- dg = min(bg + sg, 255);
- db = min(bb + sb, 255);
- },
-
- subtract: function() {
- dr = max(br - sr, 0);
- dg = max(bg - sg, 0);
- db = max(bb - sb, 0);
- },
-
- average: function() {
- dr = (br + sr) / 2;
- dg = (bg + sg) / 2;
- db = (bb + sb) / 2;
- },
-
- negation: function() {
- dr = 255 - abs(255 - sr - br);
- dg = 255 - abs(255 - sg - bg);
- db = 255 - abs(255 - sb - bb);
- }
- };
-
- var nativeModes = this.nativeModes = Base.each([
- 'source-over', 'source-in', 'source-out', 'source-atop',
- 'destination-over', 'destination-in', 'destination-out',
- 'destination-atop', 'lighter', 'darker', 'copy', 'xor'
- ], function(mode) {
- this[mode] = true;
- }, {});
-
- var ctx = CanvasProvider.getContext(1, 1);
- Base.each(modes, function(func, mode) {
- ctx.save();
- var darken = mode === 'darken',
- ok = false;
- ctx.fillStyle = darken ? '#300' : '#a00';
- ctx.fillRect(0, 0, 1, 1);
- ctx.globalCompositeOperation = mode;
- if (ctx.globalCompositeOperation === mode) {
- ctx.fillStyle = darken ? '#a00' : '#300';
- ctx.fillRect(0, 0, 1, 1);
- ok = ctx.getImageData(0, 0, 1, 1).data[0] !== (darken ? 170 : 51);
- }
- nativeModes[mode] = ok;
- ctx.restore();
- });
- CanvasProvider.release(ctx);
-
- this.process = function(mode, srcContext, dstContext, alpha, offset) {
- var srcCanvas = srcContext.canvas,
- normal = mode === 'normal';
- if (normal || nativeModes[mode]) {
- dstContext.save();
- dstContext.setTransform(1, 0, 0, 1, 0, 0);
- dstContext.globalAlpha = alpha;
- if (!normal)
- dstContext.globalCompositeOperation = mode;
- dstContext.drawImage(srcCanvas, offset.x, offset.y);
- dstContext.restore();
- } else {
- var process = modes[mode];
- if (!process)
- return;
- var dstData = dstContext.getImageData(offset.x, offset.y,
- srcCanvas.width, srcCanvas.height),
- dst = dstData.data,
- src = srcContext.getImageData(0, 0,
- srcCanvas.width, srcCanvas.height).data;
- for (var i = 0, l = dst.length; i < l; i += 4) {
- sr = src[i];
- br = dst[i];
- sg = src[i + 1];
- bg = dst[i + 1];
- sb = src[i + 2];
- bb = dst[i + 2];
- sa = src[i + 3];
- ba = dst[i + 3];
- process();
- var a1 = sa * alpha / 255,
- a2 = 1 - a1;
- dst[i] = a1 * dr + a2 * br;
- dst[i + 1] = a1 * dg + a2 * bg;
- dst[i + 2] = a1 * db + a2 * bb;
- dst[i + 3] = sa * alpha + a2 * ba;
- }
- dstContext.putImageData(dstData, offset.x, offset.y);
- }
- };
-};
-
-var SVGStyles = Base.each({
- fillColor: ['fill', 'color'],
- strokeColor: ['stroke', 'color'],
- strokeWidth: ['stroke-width', 'number'],
- strokeCap: ['stroke-linecap', 'string'],
- strokeJoin: ['stroke-linejoin', 'string'],
- miterLimit: ['stroke-miterlimit', 'number'],
- dashArray: ['stroke-dasharray', 'array'],
- dashOffset: ['stroke-dashoffset', 'number'],
- font: ['font-family', 'string'],
- fontSize: ['font-size', 'number'],
- justification: ['text-anchor', 'lookup', {
- left: 'start',
- center: 'middle',
- right: 'end'
- }],
- opacity: ['opacity', 'number'],
- blendMode: ['mix-blend-mode', 'string']
-}, function(entry, key) {
- var part = Base.capitalize(key),
- lookup = entry[2];
- this[key] = {
- type: entry[1],
- property: key,
- attribute: entry[0],
- toSVG: lookup,
- fromSVG: lookup && Base.each(lookup, function(value, name) {
- this[value] = name;
- }, {}),
- get: 'get' + part,
- set: 'set' + part
- };
-}, {});
-
-var SVGNamespaces = {
- href: 'http://www.w3.org/1999/xlink',
- xlink: 'http://www.w3.org/2000/xmlns'
-};
-
-new function() {
- var formatter;
-
- function setAttributes(node, attrs) {
- for (var key in attrs) {
- var val = attrs[key],
- namespace = SVGNamespaces[key];
- if (typeof val === 'number')
- val = formatter.number(val);
- if (namespace) {
- node.setAttributeNS(namespace, key, val);
- } else {
- node.setAttribute(key, val);
- }
- }
- return node;
- }
-
- function createElement(tag, attrs) {
- return setAttributes(
- document.createElementNS('http://www.w3.org/2000/svg', tag), attrs);
- }
-
- function getTransform(item, coordinates, center) {
- var matrix = item._matrix,
- trans = matrix.getTranslation(),
- attrs = {};
- if (coordinates) {
- matrix = matrix.shiftless();
- var point = matrix._inverseTransform(trans);
- attrs[center ? 'cx' : 'x'] = point.x;
- attrs[center ? 'cy' : 'y'] = point.y;
- trans = null;
- }
- if (matrix.isIdentity())
- return attrs;
- var decomposed = matrix.decompose();
- if (decomposed && !decomposed.shearing) {
- var parts = [],
- angle = decomposed.rotation,
- scale = decomposed.scaling;
- if (trans && !trans.isZero())
- parts.push('translate(' + formatter.point(trans) + ')');
- if (!Numerical.isZero(scale.x - 1) || !Numerical.isZero(scale.y - 1))
- parts.push('scale(' + formatter.point(scale) +')');
- if (angle)
- parts.push('rotate(' + formatter.number(angle) + ')');
- attrs.transform = parts.join(' ');
- } else {
- attrs.transform = 'matrix(' + matrix.getValues().join(',') + ')';
- }
- return attrs;
- }
-
- function exportGroup(item, options) {
- var attrs = getTransform(item),
- children = item._children;
- var node = createElement('g', attrs);
- for (var i = 0, l = children.length; i < l; i++) {
- var child = children[i];
- var childNode = exportSVG(child, options);
- if (childNode) {
- if (child.isClipMask()) {
- var clip = createElement('clipPath');
- clip.appendChild(childNode);
- setDefinition(child, clip, 'clip');
- setAttributes(node, {
- 'clip-path': 'url(#' + clip.id + ')'
- });
- } else {
- node.appendChild(childNode);
- }
- }
- }
- return node;
- }
-
- function exportRaster(item) {
- var attrs = getTransform(item, true),
- size = item.getSize();
- attrs.x -= size.width / 2;
- attrs.y -= size.height / 2;
- attrs.width = size.width;
- attrs.height = size.height;
- attrs.href = item.toDataURL();
- return createElement('image', attrs);
- }
-
- function exportPath(item, options) {
- if (options.matchShapes) {
- var shape = item.toShape(false);
- if (shape)
- return exportShape(shape, options);
- }
- var segments = item._segments,
- type,
- attrs;
- if (segments.length === 0)
- return null;
- if (item.isPolygon()) {
- if (segments.length >= 3) {
- type = item._closed ? 'polygon' : 'polyline';
- var parts = [];
- for(i = 0, l = segments.length; i < l; i++)
- parts.push(formatter.point(segments[i]._point));
- attrs = {
- points: parts.join(' ')
- };
- } else {
- type = 'line';
- var first = segments[0]._point,
- last = segments[segments.length - 1]._point;
- attrs = {
- x1: first.x,
- y1: first.y,
- x2: last.x,
- y2: last.y
- };
- }
- } else {
- type = 'path';
- var data = item.getPathData();
- attrs = data && { d: data };
- }
- return createElement(type, attrs);
- }
-
- function exportShape(item) {
- var shape = item._shape,
- radius = item._radius,
- attrs = getTransform(item, true, shape !== 'rectangle');
- if (shape === 'rectangle') {
- shape = 'rect';
- var size = item._size,
- width = size.width,
- height = size.height;
- attrs.x -= width / 2;
- attrs.y -= height / 2;
- attrs.width = width;
- attrs.height = height;
- if (radius.isZero())
- radius = null;
- }
- if (radius) {
- if (shape === 'circle') {
- attrs.r = radius;
- } else {
- attrs.rx = radius.width;
- attrs.ry = radius.height;
- }
- }
- return createElement(shape, attrs);
- }
-
- function exportCompoundPath(item) {
- var attrs = getTransform(item, true);
- var data = item.getPathData();
- if (data)
- attrs.d = data;
- return createElement('path', attrs);
- }
-
- function exportPlacedSymbol(item, options) {
- var attrs = getTransform(item, true),
- symbol = item.getSymbol(),
- symbolNode = getDefinition(symbol, 'symbol'),
- definition = symbol.getDefinition(),
- bounds = definition.getBounds();
- if (!symbolNode) {
- symbolNode = createElement('symbol', {
- viewBox: formatter.rectangle(bounds)
- });
- symbolNode.appendChild(exportSVG(definition, options));
- setDefinition(symbol, symbolNode, 'symbol');
- }
- attrs.href = '#' + symbolNode.id;
- attrs.x += bounds.x;
- attrs.y += bounds.y;
- attrs.width = formatter.number(bounds.width);
- attrs.height = formatter.number(bounds.height);
- return createElement('use', attrs);
- }
-
- function exportGradient(color) {
- var gradientNode = getDefinition(color, 'color');
- if (!gradientNode) {
- var gradient = color.getGradient(),
- radial = gradient._radial,
- origin = color.getOrigin().transform(),
- destination = color.getDestination().transform(),
- attrs;
- if (radial) {
- attrs = {
- cx: origin.x,
- cy: origin.y,
- r: origin.getDistance(destination)
- };
- var highlight = color.getHighlight();
- if (highlight) {
- highlight = highlight.transform();
- attrs.fx = highlight.x;
- attrs.fy = highlight.y;
- }
- } else {
- attrs = {
- x1: origin.x,
- y1: origin.y,
- x2: destination.x,
- y2: destination.y
- };
- }
- attrs.gradientUnits = 'userSpaceOnUse';
- gradientNode = createElement(
- (radial ? 'radial' : 'linear') + 'Gradient', attrs);
- var stops = gradient._stops;
- for (var i = 0, l = stops.length; i < l; i++) {
- var stop = stops[i],
- stopColor = stop._color,
- alpha = stopColor.getAlpha();
- attrs = {
- offset: stop._rampPoint,
- 'stop-color': stopColor.toCSS(true)
- };
- if (alpha < 1)
- attrs['stop-opacity'] = alpha;
- gradientNode.appendChild(createElement('stop', attrs));
- }
- setDefinition(color, gradientNode, 'color');
- }
- return 'url(#' + gradientNode.id + ')';
- }
-
- function exportText(item) {
- var node = createElement('text', getTransform(item, true));
- node.textContent = item._content;
- return node;
- }
-
- var exporters = {
- group: exportGroup,
- layer: exportGroup,
- raster: exportRaster,
- path: exportPath,
- shape: exportShape,
- 'compound-path': exportCompoundPath,
- 'placed-symbol': exportPlacedSymbol,
- 'point-text': exportText
- };
-
- function applyStyle(item, node) {
- var attrs = {},
- parent = item.getParent();
-
- if (item._name != null)
- attrs.id = item._name;
-
- Base.each(SVGStyles, function(entry) {
- var get = entry.get,
- type = entry.type,
- value = item[get]();
- if (!parent || !Base.equals(parent[get](), value)) {
- if (type === 'color' && value != null) {
- var alpha = value.getAlpha();
- if (alpha < 1)
- attrs[entry.attribute + '-opacity'] = alpha;
- }
- attrs[entry.attribute] = value == null
- ? 'none'
- : type === 'number'
- ? formatter.number(value)
- : type === 'color'
- ? value.gradient
- ? exportGradient(value, item)
- : value.toCSS(true)
- : type === 'array'
- ? value.join(',')
- : type === 'lookup'
- ? entry.toSVG[value]
- : value;
- }
- });
-
- if (attrs.opacity === 1)
- delete attrs.opacity;
-
- if (item._visibility != null && !item._visibility)
- attrs.visibility = 'hidden';
-
- return setAttributes(node, attrs);
- }
-
- var definitions;
- function getDefinition(item, type) {
- if (!definitions)
- definitions = { ids: {}, svgs: {} };
- return item && definitions.svgs[type + '-' + item._id];
- }
-
- function setDefinition(item, node, type) {
- if (!definitions)
- getDefinition();
- var id = definitions.ids[type] = (definitions.ids[type] || 0) + 1;
- node.id = type + '-' + id;
- definitions.svgs[type + '-' + item._id] = node;
- }
-
- function exportDefinitions(node, options) {
- var svg = node,
- defs = null;
- if (definitions) {
- svg = node.nodeName.toLowerCase() === 'svg' && node;
- for (var i in definitions.svgs) {
- if (!defs) {
- if (!svg) {
- svg = createElement('svg');
- svg.appendChild(node);
- }
- defs = svg.insertBefore(createElement('defs'),
- svg.firstChild);
- }
- defs.appendChild(definitions.svgs[i]);
- }
- definitions = null;
- }
- return options.asString
- ? new XMLSerializer().serializeToString(svg)
- : svg;
- }
-
- function exportSVG(item, options) {
- var exporter = exporters[item._type],
- node = exporter && exporter(item, options);
- if (node && item._data)
- node.setAttribute('data-paper-data', JSON.stringify(item._data));
- return node && applyStyle(item, node);
- }
-
- function setOptions(options) {
- if (!options)
- options = {};
- formatter = new Formatter(options.precision);
- return options;
- }
-
- Item.inject({
- exportSVG: function(options) {
- options = setOptions(options);
- return exportDefinitions(exportSVG(this, options), options);
- }
- });
-
- Project.inject({
- exportSVG: function(options) {
- options = setOptions(options);
- var layers = this.layers,
- size = this.view.getSize(),
- node = createElement('svg', {
- x: 0,
- y: 0,
- width: size.width,
- height: size.height,
- version: '1.1',
- xmlns: 'http://www.w3.org/2000/svg',
- 'xmlns:xlink': 'http://www.w3.org/1999/xlink'
- });
- for (var i = 0, l = layers.length; i < l; i++)
- node.appendChild(exportSVG(layers[i], options));
- return exportDefinitions(node, options);
- }
- });
-};
-
-new function() {
-
- function getValue(node, name, isString, allowNull) {
- var namespace = SVGNamespaces[name],
- value = namespace
- ? node.getAttributeNS(namespace, name)
- : node.getAttribute(name);
- if (value === 'null')
- value = null;
- return value == null
- ? allowNull
- ? null
- : isString
- ? ''
- : 0
- : isString
- ? value
- : parseFloat(value);
- }
-
- function getPoint(node, x, y, allowNull) {
- x = getValue(node, x, false, allowNull);
- y = getValue(node, y, false, allowNull);
- return allowNull && (x == null || y == null) ? null
- : new Point(x, y);
- }
-
- function getSize(node, w, h, allowNull) {
- w = getValue(node, w, false, allowNull);
- h = getValue(node, h, false, allowNull);
- return allowNull && (w == null || h == null) ? null
- : new Size(w, h);
- }
-
- function convertValue(value, type, lookup) {
- return value === 'none'
- ? null
- : type === 'number'
- ? parseFloat(value)
- : type === 'array'
- ? value ? value.split(/[\s,]+/g).map(parseFloat) : []
- : type === 'color'
- ? getDefinition(value) || value
- : type === 'lookup'
- ? lookup[value]
- : value;
- }
-
- function importGroup(node, type, isRoot, options) {
- var nodes = node.childNodes,
- isClip = type === 'clippath',
- item = new Group(),
- project = item._project,
- currentStyle = project._currentStyle,
- children = [];
- if (!isClip) {
- item._transformContent = false;
- item = applyAttributes(item, node, isRoot);
- project._currentStyle = item._style.clone();
- }
- for (var i = 0, l = nodes.length; i < l; i++) {
- var childNode = nodes[i],
- child;
- if (childNode.nodeType === 1
- && (child = importSVG(childNode, false, options))
- && !(child instanceof Symbol))
- children.push(child);
- }
- item.addChildren(children);
- if (isClip)
- item = applyAttributes(item.reduce(), node, isRoot);
- project._currentStyle = currentStyle;
- if (isClip || type === 'defs') {
- item.remove();
- item = null;
- }
- return item;
- }
-
- function importPoly(node, type) {
- var path = new Path(),
- points = node.points;
- path.moveTo(points.getItem(0));
- for (var i = 1, l = points.numberOfItems; i < l; i++)
- path.lineTo(points.getItem(i));
- if (type === 'polygon')
- path.closePath();
- return path;
- }
-
- function importPath(node) {
- var data = node.getAttribute('d'),
- path = data.match(/m/gi).length > 1
- ? new CompoundPath()
- : new Path();
- path.setPathData(data);
- return path;
- }
-
- function importGradient(node, type) {
- var nodes = node.childNodes,
- stops = [];
- for (var i = 0, l = nodes.length; i < l; i++) {
- var child = nodes[i];
- if (child.nodeType === 1)
- stops.push(applyAttributes(new GradientStop(), child));
- }
- var isRadial = type === 'radialgradient',
- gradient = new Gradient(stops, isRadial),
- origin, destination, highlight;
- if (isRadial) {
- origin = getPoint(node, 'cx', 'cy');
- destination = origin.add(getValue(node, 'r'), 0);
- highlight = getPoint(node, 'fx', 'fy', true);
- } else {
- origin = getPoint(node, 'x1', 'y1');
- destination = getPoint(node, 'x2', 'y2');
- }
- applyAttributes(
- new Color(gradient, origin, destination, highlight), node);
- return null;
- }
-
- var importers = {
- '#document': function (node, type, isRoot, options) {
- var nodes = node.childNodes;
- for (var i = 0, l = nodes.length; i < l; i++) {
- var child = nodes[i];
- if (child.nodeType === 1) {
- var next = child.nextSibling;
- document.body.appendChild(child);
- var item = importSVG(child, isRoot, options);
- if (next) {
- node.insertBefore(child, next);
- } else {
- node.appendChild(child);
- }
- return item;
- }
- }
- },
- g: importGroup,
- svg: importGroup,
- clippath: importGroup,
- polygon: importPoly,
- polyline: importPoly,
- path: importPath,
- lineargradient: importGradient,
- radialgradient: importGradient,
-
- image: function (node) {
- var raster = new Raster(getValue(node, 'href', true));
- raster.attach('load', function() {
- var size = getSize(node, 'width', 'height');
- this.setSize(size);
- var center = this._matrix._transformPoint(
- getPoint(node, 'x', 'y').add(size.divide(2)));
- this.translate(center);
- });
- return raster;
- },
-
- symbol: function(node, type, isRoot, options) {
- return new Symbol(importGroup(node, type, isRoot, options), true);
- },
-
- defs: importGroup,
-
- use: function(node) {
- var id = (getValue(node, 'href', true) || '').substring(1),
- definition = definitions[id],
- point = getPoint(node, 'x', 'y');
- return definition
- ? definition instanceof Symbol
- ? definition.place(point)
- : definition.clone().translate(point)
- : null;
- },
-
- circle: function(node) {
- return new Shape.Circle(getPoint(node, 'cx', 'cy'),
- getValue(node, 'r'));
- },
-
- ellipse: function(node) {
- return new Shape.Ellipse({
- center: getPoint(node, 'cx', 'cy'),
- radius: getSize(node, 'rx', 'ry')
- });
- },
-
- rect: function(node) {
- var point = getPoint(node, 'x', 'y'),
- size = getSize(node, 'width', 'height'),
- radius = getSize(node, 'rx', 'ry');
- return new Shape.Rectangle(new Rectangle(point, size), radius);
- },
-
- line: function(node) {
- return new Path.Line(getPoint(node, 'x1', 'y1'),
- getPoint(node, 'x2', 'y2'));
- },
-
- text: function(node) {
- var text = new PointText(getPoint(node, 'x', 'y')
- .add(getPoint(node, 'dx', 'dy')));
- text.setContent(node.textContent.trim() || '');
- return text;
- }
- };
-
- function applyTransform(item, value, name, node) {
- var transforms = (node.getAttribute(name) || '').split(/\)\s*/g),
- matrix = new Matrix();
- for (var i = 0, l = transforms.length; i < l; i++) {
- var transform = transforms[i];
- if (!transform)
- break;
- var parts = transform.split('('),
- command = parts[0],
- v = parts[1].split(/[\s,]+/g);
- for (var j = 0, m = v.length; j < m; j++)
- v[j] = parseFloat(v[j]);
- switch (command) {
- case 'matrix':
- matrix.concatenate(
- new Matrix(v[0], v[1], v[2], v[3], v[4], v[5]));
- break;
- case 'rotate':
- matrix.rotate(v[0], v[1], v[2]);
- break;
- case 'translate':
- matrix.translate(v[0], v[1]);
- break;
- case 'scale':
- matrix.scale(v);
- break;
- case 'skewX':
- case 'skewY':
- var value = Math.tan(v[0] * Math.PI / 180),
- isX = command == 'skewX';
- matrix.shear(isX ? value : 0, isX ? 0 : value);
- break;
- }
- }
- item.transform(matrix);
- }
-
- function applyOpacity(item, value, name) {
- var color = item[name === 'fill-opacity' ? 'getFillColor'
- : 'getStrokeColor']();
- if (color)
- color.setAlpha(parseFloat(value));
- }
-
- var attributes = Base.each(SVGStyles, function(entry) {
- this[entry.attribute] = function(item, value) {
- item[entry.set](convertValue(value, entry.type, entry.fromSVG));
- if (entry.type === 'color' && item instanceof Shape) {
- var color = item[entry.get]();
- if (color)
- color.transform(new Matrix().translate(
- item.getPosition(true).negate()));
- }
- };
- }, {
- id: function(item, value) {
- definitions[value] = item;
- if (item.setName)
- item.setName(value);
- },
-
- 'clip-path': function(item, value) {
- var clip = getDefinition(value);
- if (clip) {
- clip = clip.clone();
- clip.setClipMask(true);
- if (item instanceof Group) {
- item.insertChild(0, clip);
- } else {
- return new Group(clip, item);
- }
- }
- },
-
- gradientTransform: applyTransform,
- transform: applyTransform,
-
- 'fill-opacity': applyOpacity,
- 'stroke-opacity': applyOpacity,
-
- visibility: function(item, value) {
- item.setVisible(value === 'visible');
- },
-
- 'stop-color': function(item, value) {
- if (item.setColor)
- item.setColor(value);
- },
-
- 'stop-opacity': function(item, value) {
- if (item._color)
- item._color.setAlpha(parseFloat(value));
- },
-
- offset: function(item, value) {
- var percentage = value.match(/(.*)%$/);
- item.setRampPoint(percentage
- ? percentage[1] / 100
- : parseFloat(value));
- },
-
- viewBox: function(item, value, name, node, styles) {
- var rect = new Rectangle(convertValue(value, 'array')),
- size = getSize(node, 'width', 'height', true);
- if (item instanceof Group) {
- var scale = size ? rect.getSize().divide(size) : 1,
- matrix = new Matrix().translate(rect.getPoint()).scale(scale);
- item.transform(matrix.inverted());
- } else if (item instanceof Symbol) {
- if (size)
- rect.setSize(size);
- var clip = getAttribute(node, 'overflow', styles) != 'visible',
- group = item._definition;
- if (clip && !rect.contains(group.getBounds())) {
- clip = new Shape.Rectangle(rect).transform(group._matrix);
- clip.setClipMask(true);
- group.addChild(clip);
- }
- }
- }
- });
-
- function getAttribute(node, name, styles) {
- var attr = node.attributes[name],
- value = attr && attr.value;
- if (!value) {
- var style = Base.camelize(name);
- value = node.style[style];
- if (!value && styles.node[style] !== styles.parent[style])
- value = styles.node[style];
- }
- return !value
- ? undefined
- : value === 'none'
- ? null
- : value;
- }
-
- function applyAttributes(item, node, isRoot) {
- var styles = {
- node: DomElement.getStyles(node) || {},
- parent: !isRoot && DomElement.getStyles(node.parentNode) || {}
- };
- Base.each(attributes, function(apply, name) {
- var value = getAttribute(node, name, styles);
- if (value !== undefined)
- item = Base.pick(apply(item, value, name, node, styles), item);
- });
- return item;
- }
-
- var definitions = {};
- function getDefinition(value) {
- var match = value && value.match(/\((?:#|)([^)']+)/);
- return match && definitions[match[1]];
- }
-
- function importSVG(source, isRoot, options) {
- if (!source)
- return null;
- if (!options) {
- options = {};
- } else if (typeof options === 'function') {
- options = { onLoad: options };
- }
-
- var node = source,
- scope = paper;
-
- function onLoadCallback(svg) {
- paper = scope;
- var item = importSVG(svg, isRoot, options),
- onLoad = options.onLoad,
- view = scope.project && scope.project.view;
- if (onLoad)
- onLoad.call(this, item);
- view.draw(true);
- }
-
- if (isRoot) {
- if (typeof source === 'string' && !/^.*</.test(source)) {
- node = document.getElementById(source);
- if (node) {
- source = null;
- } else {
- return Http.request('get', source, onLoadCallback);
- }
- } else if (typeof File !== 'undefined' && source instanceof File) {
- var reader = new FileReader();
- reader.onload = function() {
- onLoadCallback(reader.result);
- };
- return reader.readAsText(source);
- }
- }
-
- if (typeof source === 'string')
- node = new DOMParser().parseFromString(source, 'image/svg+xml');
- if (!node.nodeName)
- throw new Error('Unsupported SVG source: ' + source);
- var type = node.nodeName.toLowerCase(),
- importer = importers[type],
- item = importer && importer(node, type, isRoot, options) || null,
- data = node.getAttribute && node.getAttribute('data-paper-data');
- if (item) {
- if (!(item instanceof Group))
- item = applyAttributes(item, node, isRoot);
- if (options.expandShapes && item instanceof Shape) {
- item.remove();
- item = item.toPath();
- }
- if (data)
- item._data = JSON.parse(data);
- }
- if (isRoot)
- definitions = {};
- return item;
- }
-
- Item.inject({
- importSVG: function(node, options) {
- return this.addChild(importSVG(node, true, options));
- }
- });
-
- Project.inject({
- importSVG: function(node, options) {
- this.activate();
- return importSVG(node, true, options);
- }
- });
-};
-
-paper = new (PaperScope.inject(new Base(Base.exports, {
- enumerable: true,
- Base: Base,
- Numerical: Numerical,
- DomElement: DomElement,
- DomEvent: DomEvent,
- Http: Http,
- Key: Key
-})))();
-
-if (typeof define === 'function' && define.amd)
- define('paper', paper);
-
-return paper;
-};
-
-paper.PaperScope.prototype.PaperScript = (function(root) {
- var Base = paper.Base,
- PaperScope = paper.PaperScope,
- PaperScript,
- exports, define,
- scope = this;
-!function(e,r){return"object"==typeof exports&&"object"==typeof module?r(exports):"function"==typeof define&&define.amd?define(["exports"],r):(r(e.acorn||(e.acorn={})),void 0)}(this,function(e){"use strict";function r(e){fr=e||{};for(var r in hr)Object.prototype.hasOwnProperty.call(fr,r)||(fr[r]=hr[r]);mr=fr.sourceFile||null}function t(e,r){var t=vr(pr,e);r+=" ("+t.line+":"+t.column+")";var n=new SyntaxError(r);throw n.pos=e,n.loc=t,n.raisedAt=br,n}function n(e){function r(e){if(1==e.length)return t+="return str === "+JSON.stringify(e[0])+";";t+="switch(str){";for(var r=0;r<e.length;++r)t+="case "+JSON.stringify(e[r])+":";t+="return true}return false;"}e=e.split(" ");var t="",n=[];e:for(var a=0;a<e.length;++a){for(var o=0;o<n.length;++o)if(n[o][0].length==e[a].length){n[o].push(e[a]);continue e}n.push([e[a]])}if(n.length>3){n.sort(function(e,r){return r.length-e.length}),t+="switch(str.length){";for(var a=0;a<n.length;++a){var i=n[a];t+="case "+i[0].length+":",r(i)}t+="}"}else r(e);return new Function("str",t)}function a(){this.line=Ar,this.column=br-Sr}function o(){Ar=1,br=Sr=0,Er=!0,u()}function i(e,r){gr=br,fr.locations&&(kr=new a),wr=e,u(),Cr=r,Er=e.beforeExpr}function s(){var e=fr.onComment&&fr.locations&&new a,r=br,n=pr.indexOf("*/",br+=2);if(-1===n&&t(br-2,"Unterminated comment"),br=n+2,fr.locations){Kt.lastIndex=r;for(var o;(o=Kt.exec(pr))&&o.index<br;)++Ar,Sr=o.index+o[0].length}fr.onComment&&fr.onComment(!0,pr.slice(r+2,n),r,br,e,fr.locations&&new a)}function c(){for(var e=br,r=fr.onComment&&fr.locations&&new a,t=pr.charCodeAt(br+=2);dr>br&&10!==t&&13!==t&&8232!==t&&8329!==t;)++br,t=pr.charCodeAt(br);fr.onComment&&fr.onComment(!1,pr.slice(e+2,br),e,br,r,fr.locations&&new a)}function u(){for(;dr>br;){var e=pr.charCodeAt(br);if(32===e)++br;else if(13===e){++br;var r=pr.charCodeAt(br);10===r&&++br,fr.locations&&(++Ar,Sr=br)}else if(10===e)++br,++Ar,Sr=br;else if(14>e&&e>8)++br;else if(47===e){var r=pr.charCodeAt(br+1);if(42===r)s();else{if(47!==r)break;c()}}else if(160===e)++br;else{if(!(e>=5760&&Jt.test(String.fromCharCode(e))))break;++br}}}function l(){var e=pr.charCodeAt(br+1);return e>=48&&57>=e?E(!0):(++br,i(xt))}function f(){var e=pr.charCodeAt(br+1);return Er?(++br,k()):61===e?x(Et,2):x(wt,1)}function p(){var e=pr.charCodeAt(br+1);return 61===e?x(Et,2):x(Ft,1)}function d(e){var r=pr.charCodeAt(br+1);return r===e?x(124===e?Lt:Ut,2):61===r?x(Et,2):x(124===e?Rt:Vt,1)}function m(){var e=pr.charCodeAt(br+1);return 61===e?x(Et,2):x(Tt,1)}function h(e){var r=pr.charCodeAt(br+1);return r===e?x(St,2):61===r?x(Et,2):x(At,1)}function v(e){var r=pr.charCodeAt(br+1),t=1;return r===e?(t=62===e&&62===pr.charCodeAt(br+2)?3:2,61===pr.charCodeAt(br+t)?x(Et,t+1):x(jt,t)):(61===r&&(t=61===pr.charCodeAt(br+2)?3:2),x(Ot,t))}function b(e){var r=pr.charCodeAt(br+1);return 61===r?x(qt,61===pr.charCodeAt(br+2)?3:2):x(61===e?Ct:It,1)}function y(e){switch(e){case 46:return l();case 40:return++br,i(ht);case 41:return++br,i(vt);case 59:return++br,i(yt);case 44:return++br,i(bt);case 91:return++br,i(ft);case 93:return++br,i(pt);case 123:return++br,i(dt);case 125:return++br,i(mt);case 58:return++br,i(gt);case 63:return++br,i(kt);case 48:var r=pr.charCodeAt(br+1);if(120===r||88===r)return C();case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return E(!1);case 34:case 39:return A(e);case 47:return f(e);case 37:case 42:return p();case 124:case 38:return d(e);case 94:return m();case 43:case 45:return h(e);case 60:case 62:return v(e);case 61:case 33:return b(e);case 126:return x(It,1)}return!1}function g(e){if(e?br=yr+1:yr=br,fr.locations&&(xr=new a),e)return k();if(br>=dr)return i(Br);var r=pr.charCodeAt(br);if(Qt(r)||92===r)return L();var n=y(r);if(n===!1){var o=String.fromCharCode(r);if("\\"===o||$t.test(o))return L();t(br,"Unexpected character '"+o+"'")}return n}function x(e,r){var t=pr.slice(br,br+r);br+=r,i(e,t)}function k(){for(var e,r,n="",a=br;;){br>=dr&&t(a,"Unterminated regular expression");var o=pr.charAt(br);if(Gt.test(o)&&t(a,"Unterminated regular expression"),e)e=!1;else{if("["===o)r=!0;else if("]"===o&&r)r=!1;else if("/"===o&&!r)break;e="\\"===o}++br}var n=pr.slice(a,br);++br;var s=I();return s&&!/^[gmsiy]*$/.test(s)&&t(a,"Invalid regexp flag"),i(jr,new RegExp(n,s))}function w(e,r){for(var t=br,n=0,a=0,o=null==r?1/0:r;o>a;++a){var i,s=pr.charCodeAt(br);if(i=s>=97?s-97+10:s>=65?s-65+10:s>=48&&57>=s?s-48:1/0,i>=e)break;++br,n=n*e+i}return br===t||null!=r&&br-t!==r?null:n}function C(){br+=2;var e=w(16);return null==e&&t(yr+2,"Expected hexadecimal number"),Qt(pr.charCodeAt(br))&&t(br,"Identifier directly after number"),i(Or,e)}function E(e){var r=br,n=!1,a=48===pr.charCodeAt(br);e||null!==w(10)||t(r,"Invalid number"),46===pr.charCodeAt(br)&&(++br,w(10),n=!0);var o=pr.charCodeAt(br);(69===o||101===o)&&(o=pr.charCodeAt(++br),(43===o||45===o)&&++br,null===w(10)&&t(r,"Invalid number"),n=!0),Qt(pr.charCodeAt(br))&&t(br,"Identifier directly after number");var s,c=pr.slice(r,br);return n?s=parseFloat(c):a&&1!==c.length?/[89]/.test(c)||Vr?t(r,"Invalid number"):s=parseInt(c,8):s=parseInt(c,10),i(Or,s)}function A(e){br++;for(var r="";;){br>=dr&&t(yr,"Unterminated string constant");var n=pr.charCodeAt(br);if(n===e)return++br,i(Fr,r);if(92===n){n=pr.charCodeAt(++br);var a=/^[0-7]+/.exec(pr.slice(br,br+3));for(a&&(a=a[0]);a&&parseInt(a,8)>255;)a=a.slice(0,a.length-1);if("0"===a&&(a=null),++br,a)Vr&&t(br-2,"Octal literal in strict mode"),r+=String.fromCharCode(parseInt(a,8)),br+=a.length-1;else switch(n){case 110:r+="\n";break;case 114:r+="\r";break;case 120:r+=String.fromCharCode(S(2));break;case 117:r+=String.fromCharCode(S(4));break;case 85:r+=String.fromCharCode(S(8));break;case 116:r+=" ";break;case 98:r+="\b";break;case 118:r+="";break;case 102:r+="\f";break;case 48:r+="\0";break;case 13:10===pr.charCodeAt(br)&&++br;case 10:fr.locations&&(Sr=br,++Ar);break;default:r+=String.fromCharCode(n)}}else(13===n||10===n||8232===n||8329===n)&&t(yr,"Unterminated string constant"),r+=String.fromCharCode(n),++br}}function S(e){var r=w(16,e);return null===r&&t(yr,"Bad character escape sequence"),r}function I(){Bt=!1;for(var e,r=!0,n=br;;){var a=pr.charCodeAt(br);if(Yt(a))Bt&&(e+=pr.charAt(br)),++br;else{if(92!==a)break;Bt||(e=pr.slice(n,br)),Bt=!0,117!=pr.charCodeAt(++br)&&t(br,"Expecting Unicode escape sequence \\uXXXX"),++br;var o=S(4),i=String.fromCharCode(o);i||t(br-1,"Invalid Unicode escape"),(r?Qt(o):Yt(o))||t(br-4,"Invalid Unicode escape"),e+=i}r=!1}return Bt?e:pr.slice(n,br)}function L(){var e=I(),r=Dr;return Bt||(Wt(e)?r=lt[e]:(fr.forbidReserved&&(3===fr.ecmaVersion?Mt:zt)(e)||Vr&&Xt(e))&&t(yr,"The keyword '"+e+"' is reserved")),i(r,e)}function U(){Ir=yr,Lr=gr,Ur=kr,g()}function R(e){for(Vr=e,br=Lr;Sr>br;)Sr=pr.lastIndexOf("\n",Sr-2)+1,--Ar;u(),g()}function T(){this.type=null,this.start=yr,this.end=null}function V(){this.start=xr,this.end=null,null!==mr&&(this.source=mr)}function q(){var e=new T;return fr.locations&&(e.loc=new V),fr.ranges&&(e.range=[yr,0]),e}function O(e){var r=new T;return r.start=e.start,fr.locations&&(r.loc=new V,r.loc.start=e.loc.start),fr.ranges&&(r.range=[e.range[0],0]),r}function j(e,r){return e.type=r,e.end=Lr,fr.locations&&(e.loc.end=Ur),fr.ranges&&(e.range[1]=Lr),e}function F(e){return fr.ecmaVersion>=5&&"ExpressionStatement"===e.type&&"Literal"===e.expression.type&&"use strict"===e.expression.value}function D(e){return wr===e?(U(),!0):void 0}function B(){return!fr.strictSemicolons&&(wr===Br||wr===mt||Gt.test(pr.slice(Lr,yr)))}function M(){D(yt)||B()||X()}function z(e){wr===e?U():X()}function X(){t(yr,"Unexpected token")}function N(e){"Identifier"!==e.type&&"MemberExpression"!==e.type&&t(e.start,"Assigning to rvalue"),Vr&&"Identifier"===e.type&&Nt(e.name)&&t(e.start,"Assigning to "+e.name+" in strict mode")}function W(e){Ir=Lr=br,fr.locations&&(Ur=new a),Rr=Vr=null,Tr=[],g();var r=e||q(),t=!0;for(e||(r.body=[]);wr!==Br;){var n=J();r.body.push(n),t&&F(n)&&R(!0),t=!1}return j(r,"Program")}function J(){wr===wt&&g(!0);var e=wr,r=q();switch(e){case Mr:case Nr:U();var n=e===Mr;D(yt)||B()?r.label=null:wr!==Dr?X():(r.label=lr(),M());for(var a=0;a<Tr.length;++a){var o=Tr[a];if(null==r.label||o.name===r.label.name){if(null!=o.kind&&(n||"loop"===o.kind))break;if(r.label&&n)break}}return a===Tr.length&&t(r.start,"Unsyntactic "+e.keyword),j(r,n?"BreakStatement":"ContinueStatement");case Wr:return U(),M(),j(r,"DebuggerStatement");case Pr:return U(),Tr.push(Zt),r.body=J(),Tr.pop(),z(tt),r.test=P(),M(),j(r,"DoWhileStatement");case _r:if(U(),Tr.push(Zt),z(ht),wr===yt)return $(r,null);if(wr===rt){var i=q();return U(),G(i,!0),1===i.declarations.length&&D(ut)?_(r,i):$(r,i)}var i=K(!1,!0);return D(ut)?(N(i),_(r,i)):$(r,i);case Gr:return U(),cr(r,!0);case Kr:return U(),r.test=P(),r.consequent=J(),r.alternate=D(Hr)?J():null,j(r,"IfStatement");case Qr:return Rr||t(yr,"'return' outside of function"),U(),D(yt)||B()?r.argument=null:(r.argument=K(),M()),j(r,"ReturnStatement");case Yr:U(),r.discriminant=P(),r.cases=[],z(dt),Tr.push(en);for(var s,c;wr!=mt;)if(wr===zr||wr===Jr){var u=wr===zr;s&&j(s,"SwitchCase"),r.cases.push(s=q()),s.consequent=[],U(),u?s.test=K():(c&&t(Ir,"Multiple default clauses"),c=!0,s.test=null),z(gt)}else s||X(),s.consequent.push(J());return s&&j(s,"SwitchCase"),U(),Tr.pop(),j(r,"SwitchStatement");case Zr:return U(),Gt.test(pr.slice(Lr,yr))&&t(Lr,"Illegal newline after throw"),r.argument=K(),M(),j(r,"ThrowStatement");case et:if(U(),r.block=H(),r.handler=null,wr===Xr){var l=q();U(),z(ht),l.param=lr(),Vr&&Nt(l.param.name)&&t(l.param.start,"Binding "+l.param.name+" in strict mode"),z(vt),l.guard=null,l.body=H(),r.handler=j(l,"CatchClause")}return r.guardedHandlers=qr,r.finalizer=D($r)?H():null,r.handler||r.finalizer||t(r.start,"Missing catch or finally clause"),j(r,"TryStatement");case rt:return U(),r=G(r),M(),r;case tt:return U(),r.test=P(),Tr.push(Zt),r.body=J(),Tr.pop(),j(r,"WhileStatement");case nt:return Vr&&t(yr,"'with' in strict mode"),U(),r.object=P(),r.body=J(),j(r,"WithStatement");case dt:return H();case yt:return U(),j(r,"EmptyStatement");default:var f=Cr,p=K();if(e===Dr&&"Identifier"===p.type&&D(gt)){for(var a=0;a<Tr.length;++a)Tr[a].name===f&&t(p.start,"Label '"+f+"' is already declared");var d=wr.isLoop?"loop":wr===Yr?"switch":null;return Tr.push({name:f,kind:d}),r.body=J(),Tr.pop(),r.label=p,j(r,"LabeledStatement")}return r.expression=p,M(),j(r,"ExpressionStatement")}}function P(){z(ht);var e=K();return z(vt),e}function H(e){var r,t=q(),n=!0,a=!1;for(t.body=[],z(dt);!D(mt);){var o=J();t.body.push(o),n&&e&&F(o)&&(r=a,R(a=!0)),n=!1}return a&&!r&&R(!1),j(t,"BlockStatement")}function $(e,r){return e.init=r,z(yt),e.test=wr===yt?null:K(),z(yt),e.update=wr===vt?null:K(),z(vt),e.body=J(),Tr.pop(),j(e,"ForStatement")}function _(e,r){return e.left=r,e.right=K(),z(vt),e.body=J(),Tr.pop(),j(e,"ForInStatement")}function G(e,r){for(e.declarations=[],e.kind="var";;){var n=q();if(n.id=lr(),Vr&&Nt(n.id.name)&&t(n.id.start,"Binding "+n.id.name+" in strict mode"),n.init=D(Ct)?K(!0,r):null,e.declarations.push(j(n,"VariableDeclarator")),!D(bt))break}return j(e,"VariableDeclaration")}function K(e,r){var t=Q(r);if(!e&&wr===bt){var n=O(t);for(n.expressions=[t];D(bt);)n.expressions.push(Q(r));return j(n,"SequenceExpression")}return t}function Q(e){var r=Y(e);if(wr.isAssign){var t=O(r);return t.operator=Cr,t.left=r,U(),t.right=Q(e),N(r),j(t,"AssignmentExpression")}return r}function Y(e){var r=Z(e);if(D(kt)){var t=O(r);return t.test=r,t.consequent=K(!0),z(gt),t.alternate=K(!0,e),j(t,"ConditionalExpression")}return r}function Z(e){return er(rr(),-1,e)}function er(e,r,t){var n=wr.binop;if(null!=n&&(!t||wr!==ut)&&n>r){var a=O(e);a.left=e,a.operator=Cr,U(),a.right=er(rr(),n,t);var a=j(a,/&&|\|\|/.test(a.operator)?"LogicalExpression":"BinaryExpression");return er(a,r,t)}return e}function rr(){if(wr.prefix){var e=q(),r=wr.isUpdate;return e.operator=Cr,e.prefix=!0,U(),e.argument=rr(),r?N(e.argument):Vr&&"delete"===e.operator&&"Identifier"===e.argument.type&&t(e.start,"Deleting local variable in strict mode"),j(e,r?"UpdateExpression":"UnaryExpression")}for(var n=tr();wr.postfix&&!B();){var e=O(n);e.operator=Cr,e.prefix=!1,e.argument=n,N(n),U(),n=j(e,"UpdateExpression")}return n}function tr(){return nr(ar())}function nr(e,r){if(D(xt)){var t=O(e);return t.object=e,t.property=lr(!0),t.computed=!1,nr(j(t,"MemberExpression"),r)}if(D(ft)){var t=O(e);return t.object=e,t.property=K(),t.computed=!0,z(pt),nr(j(t,"MemberExpression"),r)}if(!r&&D(ht)){var t=O(e);return t.callee=e,t.arguments=ur(vt,!1),nr(j(t,"CallExpression"),r)}return e}function ar(){switch(wr){case ot:var e=q();return U(),j(e,"ThisExpression");case Dr:return lr();case Or:case Fr:case jr:var e=q();return e.value=Cr,e.raw=pr.slice(yr,gr),U(),j(e,"Literal");case it:case st:case ct:var e=q();return e.value=wr.atomValue,e.raw=wr.keyword,U(),j(e,"Literal");case ht:var r=xr,t=yr;U();var n=K();return n.start=t,n.end=gr,fr.locations&&(n.loc.start=r,n.loc.end=kr),fr.ranges&&(n.range=[t,gr]),z(vt),n;case ft:var e=q();return U(),e.elements=ur(pt,!0,!0),j(e,"ArrayExpression");case dt:return ir();case Gr:var e=q();return U(),cr(e,!1);case at:return or();default:X()}}function or(){var e=q();return U(),e.callee=nr(ar(),!0),e.arguments=D(ht)?ur(vt,!1):qr,j(e,"NewExpression")}function ir(){var e=q(),r=!0,n=!1;for(e.properties=[],U();!D(mt);){if(r)r=!1;else if(z(bt),fr.allowTrailingCommas&&D(mt))break;var a,o={key:sr()},i=!1;if(D(gt)?(o.value=K(!0),a=o.kind="init"):fr.ecmaVersion>=5&&"Identifier"===o.key.type&&("get"===o.key.name||"set"===o.key.name)?(i=n=!0,a=o.kind=o.key.name,o.key=sr(),wr!==ht&&X(),o.value=cr(q(),!1)):X(),"Identifier"===o.key.type&&(Vr||n))for(var s=0;s<e.properties.length;++s){var c=e.properties[s];if(c.key.name===o.key.name){var u=a==c.kind||i&&"init"===c.kind||"init"===a&&("get"===c.kind||"set"===c.kind);u&&!Vr&&"init"===a&&"init"===c.kind&&(u=!1),u&&t(o.key.start,"Redefinition of property")}}e.properties.push(o)}return j(e,"ObjectExpression")}function sr(){return wr===Or||wr===Fr?ar():lr(!0)}function cr(e,r){wr===Dr?e.id=lr():r?X():e.id=null,e.params=[];var n=!0;for(z(ht);!D(vt);)n?n=!1:z(bt),e.params.push(lr());var a=Rr,o=Tr;if(Rr=!0,Tr=[],e.body=H(!0),Rr=a,Tr=o,Vr||e.body.body.length&&F(e.body.body[0]))for(var i=e.id?-1:0;i<e.params.length;++i){var s=0>i?e.id:e.params[i];if((Xt(s.name)||Nt(s.name))&&t(s.start,"Defining '"+s.name+"' in strict mode"),i>=0)for(var c=0;i>c;++c)s.name===e.params[c].name&&t(s.start,"Argument name clash in strict mode")}return j(e,r?"FunctionDeclaration":"FunctionExpression")}function ur(e,r,t){for(var n=[],a=!0;!D(e);){if(a)a=!1;else if(z(bt),r&&fr.allowTrailingCommas&&D(e))break;t&&wr===bt?n.push(null):n.push(K(!0))}return n}function lr(e){var r=q();return r.name=wr===Dr?Cr:e&&!fr.forbidReserved&&wr.keyword||X(),U(),j(r,"Identifier")}e.version="0.3.2";var fr,pr,dr,mr;e.parse=function(e,t){return pr=String(e),dr=pr.length,r(t),o(),W(fr.program)};var hr=e.defaultOptions={ecmaVersion:5,strictSemicolons:!1,allowTrailingCommas:!0,forbidReserved:!1,locations:!1,onComment:null,ranges:!1,program:null,sourceFile:null},vr=e.getLineInfo=function(e,r){for(var t=1,n=0;;){Kt.lastIndex=n;var a=Kt.exec(e);if(!(a&&a.index<r))break;++t,n=a.index+a[0].length}return{line:t,column:r-n}};e.tokenize=function(e,t){function n(e){return g(e),a.start=yr,a.end=gr,a.startLoc=xr,a.endLoc=kr,a.type=wr,a.value=Cr,a}pr=String(e),dr=pr.length,r(t),o();var a={};return n.jumpTo=function(e,r){if(br=e,fr.locations){Ar=1,Sr=Kt.lastIndex=0;for(var t;(t=Kt.exec(pr))&&t.index<e;)++Ar,Sr=t.index+t[0].length}Er=r,u()},n};var br,yr,gr,xr,kr,wr,Cr,Er,Ar,Sr,Ir,Lr,Ur,Rr,Tr,Vr,qr=[],Or={type:"num"},jr={type:"regexp"},Fr={type:"string"},Dr={type:"name"},Br={type:"eof"},Mr={keyword:"break"},zr={keyword:"case",beforeExpr:!0},Xr={keyword:"catch"},Nr={keyword:"continue"},Wr={keyword:"debugger"},Jr={keyword:"default"},Pr={keyword:"do",isLoop:!0},Hr={keyword:"else",beforeExpr:!0},$r={keyword:"finally"},_r={keyword:"for",isLoop:!0},Gr={keyword:"function"},Kr={keyword:"if"},Qr={keyword:"return",beforeExpr:!0},Yr={keyword:"switch"},Zr={keyword:"throw",beforeExpr:!0},et={keyword:"try"},rt={keyword:"var"},tt={keyword:"while",isLoop:!0},nt={keyword:"with"},at={keyword:"new",beforeExpr:!0},ot={keyword:"this"},it={keyword:"null",atomValue:null},st={keyword:"true",atomValue:!0},ct={keyword:"false",atomValue:!1},ut={keyword:"in",binop:7,beforeExpr:!0},lt={"break":Mr,"case":zr,"catch":Xr,"continue":Nr,"debugger":Wr,"default":Jr,"do":Pr,"else":Hr,"finally":$r,"for":_r,"function":Gr,"if":Kr,"return":Qr,"switch":Yr,"throw":Zr,"try":et,"var":rt,"while":tt,"with":nt,"null":it,"true":st,"false":ct,"new":at,"in":ut,"instanceof":{keyword:"instanceof",binop:7,beforeExpr:!0},"this":ot,"typeof":{keyword:"typeof",prefix:!0,beforeExpr:!0},"void":{keyword:"void",prefix:!0,beforeExpr:!0},"delete":{keyword:"delete",prefix:!0,beforeExpr:!0}},ft={type:"[",beforeExpr:!0},pt={type:"]"},dt={type:"{",beforeExpr:!0},mt={type:"}"},ht={type:"(",beforeExpr:!0},vt={type:")"},bt={type:",",beforeExpr:!0},yt={type:";",beforeExpr:!0},gt={type:":",beforeExpr:!0},xt={type:"."},kt={type:"?",beforeExpr:!0},wt={binop:10,beforeExpr:!0},Ct={isAssign:!0,beforeExpr:!0},Et={isAssign:!0,beforeExpr:!0},At={binop:9,prefix:!0,beforeExpr:!0},St={postfix:!0,prefix:!0,isUpdate:!0},It={prefix:!0,beforeExpr:!0},Lt={binop:1,beforeExpr:!0},Ut={binop:2,beforeExpr:!0},Rt={binop:3,beforeExpr:!0},Tt={binop:4,beforeExpr:!0},Vt={binop:5,beforeExpr:!0},qt={binop:6,beforeExpr:!0},Ot={binop:7,beforeExpr:!0},jt={binop:8,beforeExpr:!0},Ft={binop:10,beforeExpr:!0};e.tokTypes={bracketL:ft,bracketR:pt,braceL:dt,braceR:mt,parenL:ht,parenR:vt,comma:bt,semi:yt,colon:gt,dot:xt,question:kt,slash:wt,eq:Ct,name:Dr,eof:Br,num:Or,regexp:jr,string:Fr};for(var Dt in lt)e.tokTypes["_"+Dt]=lt[Dt];var Bt,Mt=n("abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile"),zt=n("class enum extends super const export import"),Xt=n("implements interface let package private protected public static yield"),Nt=n("eval arguments"),Wt=n("break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this"),Jt=/[\u1680\u180e\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]/,Pt="\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05d0-\u05ea\u05f0-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u08a0\u08a2-\u08ac\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097f\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d\u0c58\u0c59\u0c60\u0c61\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d60\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191c\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19c1-\u19c7\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2e2f\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua697\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa80-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc",Ht="\u0300-\u036f\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u0620-\u0649\u0672-\u06d3\u06e7-\u06e8\u06fb-\u06fc\u0730-\u074a\u0800-\u0814\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0840-\u0857\u08e4-\u08fe\u0900-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962-\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09d7\u09df-\u09e0\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2-\u0ae3\u0ae6-\u0aef\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b56\u0b57\u0b5f-\u0b60\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c01-\u0c03\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62-\u0c63\u0c66-\u0c6f\u0c82\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2-\u0ce3\u0ce6-\u0cef\u0d02\u0d03\u0d46-\u0d48\u0d57\u0d62-\u0d63\u0d66-\u0d6f\u0d82\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0df2\u0df3\u0e34-\u0e3a\u0e40-\u0e45\u0e50-\u0e59\u0eb4-\u0eb9\u0ec8-\u0ecd\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f41-\u0f47\u0f71-\u0f84\u0f86-\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u1000-\u1029\u1040-\u1049\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u170e-\u1710\u1720-\u1730\u1740-\u1750\u1772\u1773\u1780-\u17b2\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u1920-\u192b\u1930-\u193b\u1951-\u196d\u19b0-\u19c0\u19c8-\u19c9\u19d0-\u19d9\u1a00-\u1a15\u1a20-\u1a53\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1b46-\u1b4b\u1b50-\u1b59\u1b6b-\u1b73\u1bb0-\u1bb9\u1be6-\u1bf3\u1c00-\u1c22\u1c40-\u1c49\u1c5b-\u1c7d\u1cd0-\u1cd2\u1d00-\u1dbe\u1e01-\u1f15\u200c\u200d\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2d81-\u2d96\u2de0-\u2dff\u3021-\u3028\u3099\u309a\ua640-\ua66d\ua674-\ua67d\ua69f\ua6f0-\ua6f1\ua7f8-\ua800\ua806\ua80b\ua823-\ua827\ua880-\ua881\ua8b4-\ua8c4\ua8d0-\ua8d9\ua8f3-\ua8f7\ua900-\ua909\ua926-\ua92d\ua930-\ua945\ua980-\ua983\ua9b3-\ua9c0\uaa00-\uaa27\uaa40-\uaa41\uaa4c-\uaa4d\uaa50-\uaa59\uaa7b\uaae0-\uaae9\uaaf2-\uaaf3\uabc0-\uabe1\uabec\uabed\uabf0-\uabf9\ufb20-\ufb28\ufe00-\ufe0f\ufe20-\ufe26\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f",$t=new RegExp("["+Pt+"]"),_t=new RegExp("["+Pt+Ht+"]"),Gt=/[\n\r\u2028\u2029]/,Kt=/\r\n|[\n\r\u2028\u2029]/g,Qt=e.isIdentifierStart=function(e){return 65>e?36===e:91>e?!0:97>e?95===e:123>e?!0:e>=170&&$t.test(String.fromCharCode(e))},Yt=e.isIdentifierChar=function(e){return 48>e?36===e:58>e?!0:65>e?!1:91>e?!0:97>e?95===e:123>e?!0:e>=170&&_t.test(String.fromCharCode(e))},Zt={kind:"loop"},en={kind:"switch"}});
-
- var binaryOperators = {
- '+': '_add',
- '-': '_subtract',
- '*': '_multiply',
- '/': '_divide',
- '%': '_modulo',
- '==': 'equals',
- '!=': 'equals'
- };
-
- var unaryOperators = {
- '-': '_negate',
- '+': null
- };
-
- var fields = Base.each(
- ['add', 'subtract', 'multiply', 'divide', 'modulo', 'negate'],
- function(name) {
- this['_' + name] = '#' + name;
- },
- {}
- );
- paper.Point.inject(fields);
- paper.Size.inject(fields);
- paper.Color.inject(fields);
-
- function _$_(left, operator, right) {
- var handler = binaryOperators[operator];
- if (left && left[handler]) {
- var res = left[handler](right);
- return operator === '!=' ? !res : res;
- }
- switch (operator) {
- case '+': return left + right;
- case '-': return left - right;
- case '*': return left * right;
- case '/': return left / right;
- case '%': return left % right;
- case '==': return left == right;
- case '!=': return left != right;
- }
- }
-
- function $_(operator, value) {
- var handler = unaryOperators[operator];
- if (handler && value && value[handler])
- return value[handler]();
- switch (operator) {
- case '+': return +value;
- case '-': return -value;
- }
- }
-
- function compile(code) {
-
- var insertions = [];
-
- function getOffset(offset) {
- for (var i = 0, l = insertions.length; i < l; i++) {
- var insertion = insertions[i];
- if (insertion[0] >= offset)
- break;
- offset += insertion[1];
- }
- return offset;
- }
-
- function getCode(node) {
- return code.substring(getOffset(node.range[0]),
- getOffset(node.range[1]));
- }
-
- function replaceCode(node, str) {
- var start = getOffset(node.range[0]),
- end = getOffset(node.range[1]);
- var insert = 0;
- for (var i = insertions.length - 1; i >= 0; i--) {
- if (start > insertions[i][0]) {
- insert = i + 1;
- break;
- }
- }
- insertions.splice(insert, 0, [start, str.length - end + start]);
- code = code.substring(0, start) + str + code.substring(end);
- }
-
- function walkAST(node, parent) {
- if (!node)
- return;
- for (var key in node) {
- if (key === 'range')
- continue;
- var value = node[key];
- if (Array.isArray(value)) {
- for (var i = 0, l = value.length; i < l; i++)
- walkAST(value[i], node);
- } else if (value && typeof value === 'object') {
- walkAST(value, node);
- }
- }
- switch (node && node.type) {
- case 'BinaryExpression':
- if (node.operator in binaryOperators
- && node.left.type !== 'Literal') {
- var left = getCode(node.left),
- right = getCode(node.right);
- replaceCode(node, '_$_(' + left + ', "' + node.operator
- + '", ' + right + ')');
- }
- break;
- case 'AssignmentExpression':
- if (/^.=$/.test(node.operator)
- && node.left.type !== 'Literal') {
- var left = getCode(node.left),
- right = getCode(node.right);
- replaceCode(node, left + ' = _$_(' + left + ', "'
- + node.operator[0] + '", ' + right + ')');
- }
- break;
- case 'UpdateExpression':
- if (!node.prefix && !(parent && (
- parent.type === 'BinaryExpression'
- && /^[=!<>]/.test(parent.operator)
- || parent.type === 'MemberExpression'
- && parent.computed))) {
- var arg = getCode(node.argument);
- replaceCode(node, arg + ' = _$_(' + arg + ', "'
- + node.operator[0] + '", 1)');
- }
- break;
- case 'UnaryExpression':
- if (node.operator in unaryOperators
- && node.argument.type !== 'Literal') {
- var arg = getCode(node.argument);
- replaceCode(node, '$_("' + node.operator + '", '
- + arg + ')');
- }
- break;
- }
- }
- walkAST(scope.acorn.parse(code, { ranges: true }));
- return code;
- }
-
- function evaluate(code, scope) {
- paper = scope;
- var view = scope.project && scope.project.view,
- res;
- with (scope) {
- (function() {
- var onActivate, onDeactivate, onEditOptions,
- onMouseDown, onMouseUp, onMouseDrag, onMouseMove,
- onKeyDown, onKeyUp, onFrame, onResize;
- code = compile(code);
- if (root.InstallTrigger) {
- var handle = PaperScript.handleException;
- if (!handle) {
- handle = PaperScript.handleException = function(e) {
- throw e.lineNumber >= lineNumber
- ? new Error(e.message, e.fileName,
- e.lineNumber - lineNumber)
- : e;
- }
- var lineNumber = new Error().lineNumber;
- lineNumber += (new Error().lineNumber - lineNumber) * 3;
- }
- try {
- res = eval(';' + code);
- } catch (e) {
- handle(e);
- }
- } else {
- res = eval(code);
- }
- if (/on(?:Key|Mouse)(?:Up|Down|Move|Drag)/.test(code)) {
- Base.each(paper.Tool.prototype._events, function(key) {
- var value = eval(key);
- if (value) {
- scope.getTool()[key] = value;
- }
- });
- }
- if (view) {
- view.setOnResize(onResize);
- view.fire('resize', {
- size: view.size,
- delta: new Point()
- });
- if (onFrame)
- view.setOnFrame(onFrame);
- view.draw();
- }
- }).call(scope);
- }
- return res;
- }
-
- function load() {
- Base.each(document.getElementsByTagName('script'), function(script) {
- if (/^text\/(?:x-|)paperscript$/.test(script.type)
- && !script.getAttribute('data-paper-ignore')) {
- var canvas = PaperScope.getAttribute(script, 'canvas'),
- scope = PaperScope.get(canvas)
- || new PaperScope(script).setup(canvas),
- src = script.src;
- if (src) {
- paper.Http.request('get', src, function(code) {
- evaluate(code, scope);
- });
- } else {
- evaluate(script.innerHTML, scope);
- }
- script.setAttribute('data-paper-ignore', true);
- }
- }, this);
- }
-
- if (document.readyState === 'complete') {
- setTimeout(load);
- } else {
- paper.DomEvent.add(window, { load: load });
- }
-
- return PaperScript = {
- compile: compile,
- evaluate: evaluate,
- load: load,
- lineNumberBase: 0
- };
-
-})(this);
--- a/server/python/django/renkanmanager/static/renkanmanager/lib/paper.js.orig Fri Apr 24 13:05:09 2015 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,12218 +0,0 @@
-/*!
- * Paper.js v0.9.15 - The Swiss Army Knife of Vector Graphics Scripting.
- * http://paperjs.org/
- *
- * Copyright (c) 2011 - 2013, Juerg Lehni & Jonathan Puckey
- * http://lehni.org/ & http://jonathanpuckey.com/
- *
- * Distributed under the MIT license. See LICENSE file for details.
- *
- * All rights reserved.
- *
- * Date: Sun Dec 1 23:54:52 2013 +0100
- *
- ***
- *
- * straps.js - Class inheritance library with support for bean-style accessors
- *
- * Copyright (c) 2006 - 2013 Juerg Lehni
- * http://lehni.org/
- *
- * Distributed under the MIT license.
- *
- ***
- *
- * acorn.js
- * http://marijnhaverbeke.nl/acorn/
- *
- * Acorn is a tiny, fast JavaScript parser written in JavaScript,
- * created by Marijn Haverbeke and released under an MIT license.
- *
- */
-
-var paper = new function(undefined) {
-
-var Base = new function() {
- var hidden = /^(statics|generics|preserve|enumerable|prototype|toString|valueOf)$/,
- slice = [].slice,
-
- forEach = [].forEach || function(iter, bind) {
- for (var i = 0, l = this.length; i < l; i++)
- iter.call(bind, this[i], i, this);
- },
-
- forIn = function(iter, bind) {
- for (var i in this)
- if (this.hasOwnProperty(i))
- iter.call(bind, this[i], i, this);
- },
-
- create = Object.create || function(proto) {
- return { __proto__: proto };
- },
-
- describe = Object.getOwnPropertyDescriptor || function(obj, name) {
- var get = obj.__lookupGetter__ && obj.__lookupGetter__(name);
- return get
- ? { get: get, set: obj.__lookupSetter__(name),
- enumerable: true, configurable: true }
- : obj.hasOwnProperty(name)
- ? { value: obj[name], enumerable: true,
- configurable: true, writable: true }
- : null;
- },
-
- _define = Object.defineProperty || function(obj, name, desc) {
- if ((desc.get || desc.set) && obj.__defineGetter__) {
- if (desc.get)
- obj.__defineGetter__(name, desc.get);
- if (desc.set)
- obj.__defineSetter__(name, desc.set);
- } else {
- obj[name] = desc.value;
- }
- return obj;
- },
-
- define = function(obj, name, desc) {
- delete obj[name];
- return _define(obj, name, desc);
- };
-
- function inject(dest, src, enumerable, base, preserve, generics) {
- var beans;
-
- function field(name, val, dontCheck, generics) {
- var val = val || (val = describe(src, name))
- && (val.get ? val : val.value);
- if (typeof val === 'string' && val[0] === '#')
- val = dest[val.substring(1)] || val;
- var isFunc = typeof val === 'function',
- res = val,
- prev = preserve || isFunc
- ? (val && val.get ? name in dest : dest[name]) : null,
- bean;
- if ((dontCheck || val !== undefined && src.hasOwnProperty(name))
- && (!preserve || !prev)) {
- if (isFunc && prev)
- val.base = prev;
- if (isFunc && beans && val.length === 0
- && (bean = name.match(/^(get|is)(([A-Z])(.*))$/)))
- beans.push([ bean[3].toLowerCase() + bean[4], bean[2] ]);
- if (!res || isFunc || !res.get || typeof res.get !== 'function'
- || res.get.length !== 0)
- res = { value: res, writable: true };
- if ((describe(dest, name)
- || { configurable: true }).configurable) {
- res.configurable = true;
- res.enumerable = enumerable;
- }
- define(dest, name, res);
- }
- if (generics && isFunc && (!preserve || !generics[name])) {
- generics[name] = function(bind) {
- return bind && dest[name].apply(bind,
- slice.call(arguments, 1));
- };
- }
- }
- if (src) {
- beans = [];
- for (var name in src)
- if (src.hasOwnProperty(name) && !hidden.test(name))
- field(name, null, true, generics);
- field('toString');
- field('valueOf');
- for (var i = 0, l = beans.length; i < l; i++) {
- var bean = beans[i],
- part = bean[1];
- field(bean[0], {
- get: dest['get' + part] || dest['is' + part],
- set: dest['set' + part]
- }, true);
- }
- }
- return dest;
- }
-
- function each(obj, iter, bind) {
- if (obj)
- ('length' in obj && !obj.getLength
- && typeof obj.length === 'number'
- ? forEach
- : forIn).call(obj, iter, bind = bind || obj);
- return bind;
- }
-
- function copy(dest, source) {
- for (var i in source)
- if (source.hasOwnProperty(i))
- dest[i] = source[i];
- return dest;
- }
-
- function clone(obj) {
- return copy(new obj.constructor(), obj);
- }
-
- return inject(function Base() {
- for (var i = 0, l = arguments.length; i < l; i++)
- copy(this, arguments[i]);
- }, {
- inject: function(src) {
- if (src) {
- var proto = this.prototype,
- base = Object.getPrototypeOf(proto).constructor,
- statics = src.statics === true ? src : src.statics;
- if (statics != src)
- inject(proto, src, src.enumerable, base && base.prototype,
- src.preserve, src.generics && this);
- inject(this, statics, true, base, src.preserve);
- }
- for (var i = 1, l = arguments.length; i < l; i++)
- this.inject(arguments[i]);
- return this;
- },
-
- extend: function() {
- var base = this,
- ctor;
- for (var i = 0, l = arguments.length; i < l; i++)
- if (ctor = arguments[i].initialize)
- break;
- ctor = ctor || function() {
- base.apply(this, arguments);
- };
- ctor.prototype = create(this.prototype);
- define(ctor.prototype, 'constructor',
- { value: ctor, writable: true, configurable: true });
- inject(ctor, this, true);
- return arguments.length ? this.inject.apply(ctor, arguments) : ctor;
- }
- }, true).inject({
- inject: function() {
- for (var i = 0, l = arguments.length; i < l; i++)
- inject(this, arguments[i], arguments[i].enumerable);
- return this;
- },
-
- extend: function() {
- var res = create(this);
- return res.inject.apply(res, arguments);
- },
-
- each: function(iter, bind) {
- return each(this, iter, bind);
- },
-
- clone: function() {
- return new this.constructor(this);
- },
-
- statics: {
- each: each,
- create: create,
- define: define,
- describe: describe,
- copy: copy,
-
- clone: function(obj) {
- return copy(new obj.constructor(), obj);
- },
-
- isPlainObject: function(obj) {
- var ctor = obj != null && obj.constructor;
- return ctor && (ctor === Object || ctor === Base
- || ctor.name === 'Object');
- },
-
- pick: function() {
- for (var i = 0, l = arguments.length; i < l; i++)
- if (arguments[i] !== undefined)
- return arguments[i];
- return null;
- }
- }
- });
-};
-
-if (typeof module !== 'undefined')
- module.exports = Base;
-
-Base.inject({
- generics: true,
-
- toString: function() {
- return this._id != null
- ? (this._class || 'Object') + (this._name
- ? " '" + this._name + "'"
- : ' @' + this._id)
- : '{ ' + Base.each(this, function(value, key) {
- if (!/^_/.test(key)) {
- var type = typeof value;
- this.push(key + ': ' + (type === 'number'
- ? Formatter.instance.number(value)
- : type === 'string' ? "'" + value + "'" : value));
- }
- }, []).join(', ') + ' }';
- },
-
- exportJSON: function(options) {
- return Base.exportJSON(this, options);
- },
-
- toJSON: function() {
- return Base.serialize(this);
- },
-
- _set: function(props, exclude) {
- if (props && Base.isPlainObject(props)) {
- var orig = props._filtering || props;
- for (var key in orig) {
- if (key in this && orig.hasOwnProperty(key)
- && (!exclude || !exclude[key])) {
- var value = props[key];
- if (value !== undefined)
- this[key] = value;
- }
- }
- return true;
- }
- },
-
- statics: {
-
- exports: {},
-
- extend: function extend() {
- var res = extend.base.apply(this, arguments),
- name = res.prototype._class;
- if (name && !Base.exports[name])
- Base.exports[name] = res;
- return res;
- },
-
- equals: function(obj1, obj2) {
- function checkKeys(o1, o2) {
- for (var i in o1)
- if (o1.hasOwnProperty(i) && !o2.hasOwnProperty(i))
- return false;
- return true;
- }
- if (obj1 === obj2)
- return true;
- if (obj1 && obj1.equals)
- return obj1.equals(obj2);
- if (obj2 && obj2.equals)
- return obj2.equals(obj1);
- if (Array.isArray(obj1) && Array.isArray(obj2)) {
- if (obj1.length !== obj2.length)
- return false;
- for (var i = 0, l = obj1.length; i < l; i++) {
- if (!Base.equals(obj1[i], obj2[i]))
- return false;
- }
- return true;
- }
- if (obj1 && typeof obj1 === 'object'
- && obj2 && typeof obj2 === 'object') {
- if (!checkKeys(obj1, obj2) || !checkKeys(obj2, obj1))
- return false;
- for (var i in obj1) {
- if (obj1.hasOwnProperty(i) && !Base.equals(obj1[i], obj2[i]))
- return false;
- }
- return true;
- }
- return false;
- },
-
- read: function(list, start, length, options) {
- if (this === Base) {
- var value = this.peek(list, start);
- list._index++;
- list.__read = 1;
- return value;
- }
- var proto = this.prototype,
- readIndex = proto._readIndex,
- index = start || readIndex && list._index || 0;
- if (!length)
- length = list.length - index;
- var obj = list[index];
- if (obj instanceof this
- || options && options.readNull && obj == null && length <= 1) {
- if (readIndex)
- list._index = index + 1;
- return obj && options && options.clone ? obj.clone() : obj;
- }
- obj = Base.create(this.prototype);
- if (readIndex)
- obj.__read = true;
- if (options)
- obj.__options = options;
- obj = obj.initialize.apply(obj, index > 0 || length < list.length
- ? Array.prototype.slice.call(list, index, index + length)
- : list) || obj;
- if (readIndex) {
- list._index = index + obj.__read;
- list.__read = obj.__read;
- delete obj.__read;
- if (options)
- delete obj.__options;
- }
- return obj;
- },
-
- peek: function(list, start) {
- return list[list._index = start || list._index || 0];
- },
-
- readAll: function(list, start, options) {
- var res = [], entry;
- for (var i = start || 0, l = list.length; i < l; i++) {
- res.push(Array.isArray(entry = list[i])
- ? this.read(entry, 0, 0, options)
- : this.read(list, i, 1, options));
- }
- return res;
- },
-
- readNamed: function(list, name, start, length, options) {
- var value = this.getNamed(list, name),
- hasObject = value !== undefined;
- if (hasObject) {
- var filtered = list._filtered;
- if (!filtered) {
- filtered = list._filtered = Base.create(list[0]);
- filtered._filtering = list[0];
- }
- filtered[name] = undefined;
- }
- return this.read(hasObject ? [value] : list, start, length, options);
- },
-
- getNamed: function(list, name) {
- var arg = list[0];
- if (list._hasObject === undefined)
- list._hasObject = list.length === 1 && Base.isPlainObject(arg);
- if (list._hasObject)
- return name ? arg[name] : list._filtered || arg;
- },
-
- hasNamed: function(list, name) {
- return !!this.getNamed(list, name);
- },
-
- isPlainValue: function(obj) {
- return this.isPlainObject(obj) || Array.isArray(obj);
- },
-
- serialize: function(obj, options, compact, dictionary) {
- options = options || {};
-
- var root = !dictionary,
- res;
- if (root) {
- options.formatter = new Formatter(options.precision);
- dictionary = {
- length: 0,
- definitions: {},
- references: {},
- add: function(item, create) {
- var id = '#' + item._id,
- ref = this.references[id];
- if (!ref) {
- this.length++;
- var res = create.call(item),
- name = item._class;
- if (name && res[0] !== name)
- res.unshift(name);
- this.definitions[id] = res;
- ref = this.references[id] = [id];
- }
- return ref;
- }
- };
- }
- if (obj && obj._serialize) {
- res = obj._serialize(options, dictionary);
- var name = obj._class;
- if (name && !compact && !res._compact && res[0] !== name)
- res.unshift(name);
- } else if (Array.isArray(obj)) {
- res = [];
- for (var i = 0, l = obj.length; i < l; i++)
- res[i] = Base.serialize(obj[i], options, compact,
- dictionary);
- if (compact)
- res._compact = true;
- } else if (Base.isPlainObject(obj)) {
- res = {};
- for (var i in obj)
- if (obj.hasOwnProperty(i))
- res[i] = Base.serialize(obj[i], options, compact,
- dictionary);
- } else if (typeof obj === 'number') {
- res = options.formatter.number(obj, options.precision);
- } else {
- res = obj;
- }
- return root && dictionary.length > 0
- ? [['dictionary', dictionary.definitions], res]
- : res;
- },
-
- deserialize: function(json, create, _data) {
- var res = json;
- _data = _data || {};
- if (Array.isArray(json)) {
- var type = json[0],
- isDictionary = type === 'dictionary';
- if (!isDictionary) {
- if (_data.dictionary && json.length == 1 && /^#/.test(type))
- return _data.dictionary[type];
- type = Base.exports[type];
- }
- res = [];
- for (var i = type ? 1 : 0, l = json.length; i < l; i++)
- res.push(Base.deserialize(json[i], create, _data));
- if (isDictionary) {
- _data.dictionary = res[0];
- } else if (type) {
- var args = res;
- if (create) {
- res = create(type, args);
- } else {
- res = Base.create(type.prototype);
- type.apply(res, args);
- }
- }
- } else if (Base.isPlainObject(json)) {
- res = {};
- for (var key in json)
- res[key] = Base.deserialize(json[key], create, _data);
- }
- return res;
- },
-
- exportJSON: function(obj, options) {
- return JSON.stringify(Base.serialize(obj, options));
- },
-
- importJSON: function(json, target) {
- return Base.deserialize(
- typeof json === 'string' ? JSON.parse(json) : json,
- function(type, args) {
- var obj = target && target.constructor === type
- ? target
- : Base.create(type.prototype),
- isTarget = obj === target;
- if (args.length === 1 && obj instanceof Item
- && (!(obj instanceof Layer) || isTarget)) {
- var arg = args[0];
- if (Base.isPlainObject(arg))
- arg.insert = false;
- }
- type.apply(obj, args);
- if (isTarget)
- target = null;
- return obj;
- });
- },
-
- splice: function(list, items, index, remove) {
- var amount = items && items.length,
- append = index === undefined;
- index = append ? list.length : index;
- if (index > list.length)
- index = list.length;
- for (var i = 0; i < amount; i++)
- items[i]._index = index + i;
- if (append) {
- list.push.apply(list, items);
- return [];
- } else {
- var args = [index, remove];
- if (items)
- args.push.apply(args, items);
- var removed = list.splice.apply(list, args);
- for (var i = 0, l = removed.length; i < l; i++)
- delete removed[i]._index;
- for (var i = index + amount, l = list.length; i < l; i++)
- list[i]._index = i;
- return removed;
- }
- },
-
- capitalize: function(str) {
- return str.replace(/\b[a-z]/g, function(match) {
- return match.toUpperCase();
- });
- },
-
- camelize: function(str) {
- return str.replace(/-(.)/g, function(all, chr) {
- return chr.toUpperCase();
- });
- },
-
- hyphenate: function(str) {
- return str.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
- }
- }
-});
-
-var Callback = {
- attach: function(type, func) {
- if (typeof type !== 'string') {
- Base.each(type, function(value, key) {
- this.attach(key, value);
- }, this);
- return;
- }
- var entry = this._eventTypes[type];
- if (entry) {
- var handlers = this._handlers = this._handlers || {};
- handlers = handlers[type] = handlers[type] || [];
- if (handlers.indexOf(func) == -1) {
- handlers.push(func);
- if (entry.install && handlers.length == 1)
- entry.install.call(this, type);
- }
- }
- },
-
- detach: function(type, func) {
- if (typeof type !== 'string') {
- Base.each(type, function(value, key) {
- this.detach(key, value);
- }, this);
- return;
- }
- var entry = this._eventTypes[type],
- handlers = this._handlers && this._handlers[type],
- index;
- if (entry && handlers) {
- if (!func || (index = handlers.indexOf(func)) != -1
- && handlers.length == 1) {
- if (entry.uninstall)
- entry.uninstall.call(this, type);
- delete this._handlers[type];
- } else if (index != -1) {
- handlers.splice(index, 1);
- }
- }
- },
-
- once: function(type, func) {
- this.attach(type, function() {
- func.apply(this, arguments);
- this.detach(type, func);
- });
- },
-
- fire: function(type, event) {
- var handlers = this._handlers && this._handlers[type];
- if (!handlers)
- return false;
- var args = [].slice.call(arguments, 1),
- PaperScript = paper.PaperScript,
- handleException = PaperScript && PaperScript.handleException,
- that = this;
-
- function callHandlers() {
- for (var i in handlers) {
- if (handlers[i].apply(that, args) === false
- && event && event.stop)
- event.stop();
- }
- }
-
- if (handleException) {
- try {
- callHandlers();
- } catch (e) {
- handleException(e);
- }
- } else {
- callHandlers();
- }
- return true;
- },
-
- responds: function(type) {
- return !!(this._handlers && this._handlers[type]);
- },
-
- on: '#attach',
- off: '#detach',
- trigger: '#fire',
-
- statics: {
- inject: function inject() {
- for (var i = 0, l = arguments.length; i < l; i++) {
- var src = arguments[i],
- events = src._events;
- if (events) {
- var types = {};
- Base.each(events, function(entry, key) {
- var isString = typeof entry === 'string',
- name = isString ? entry : key,
- part = Base.capitalize(name),
- type = name.substring(2).toLowerCase();
- types[type] = isString ? {} : entry;
- name = '_' + name;
- src['get' + part] = function() {
- return this[name];
- };
- src['set' + part] = function(func) {
- if (func) {
- this.attach(type, func);
- } else if (this[name]) {
- this.detach(type, this[name]);
- }
- this[name] = func;
- };
- });
- src._eventTypes = types;
- }
- inject.base.call(this, src);
- }
- return this;
- }
- }
-};
-
-var PaperScope = Base.extend({
- _class: 'PaperScope',
-
- initialize: function PaperScope(script) {
- paper = this;
- this.project = null;
- this.projects = [];
- this.tools = [];
- this.palettes = [];
- this._id = script && (script.getAttribute('id') || script.src)
- || ('paperscope-' + (PaperScope._id++));
- if (script)
- script.setAttribute('id', this._id);
- PaperScope._scopes[this._id] = this;
- if (!this.support) {
- var ctx = CanvasProvider.getContext(1, 1);
- PaperScope.prototype.support = {
- nativeDash: 'setLineDash' in ctx || 'mozDash' in ctx,
- nativeBlendModes: BlendMode.nativeModes
- };
- CanvasProvider.release(ctx);
- }
- },
-
- version: '0.9.15',
-
- getView: function() {
- return this.project && this.project.view;
- },
-
- getTool: function() {
- if (!this._tool)
- this._tool = new Tool();
- return this._tool;
- },
-
- getPaper: function() {
- return this;
- },
-
- evaluate: function(code) {
- var res = paper.PaperScript.evaluate(code, this);
- View.updateFocus();
- return res;
- },
-
- install: function(scope) {
- var that = this;
- Base.each(['project', 'view', 'tool'], function(key) {
- Base.define(scope, key, {
- configurable: true,
- get: function() {
- return that[key];
- }
- });
- });
- for (var key in this) {
- if (!/^(version|_id)/.test(key))
- scope[key] = this[key];
- }
- },
-
- setup: function(canvas) {
- paper = this;
- this.project = new Project(canvas);
- return this;
- },
-
- activate: function() {
- paper = this;
- },
-
- clear: function() {
- for (var i = this.projects.length - 1; i >= 0; i--)
- this.projects[i].remove();
- for (var i = this.tools.length - 1; i >= 0; i--)
- this.tools[i].remove();
- for (var i = this.palettes.length - 1; i >= 0; i--)
- this.palettes[i].remove();
- },
-
- remove: function() {
- this.clear();
- delete PaperScope._scopes[this._id];
- },
-
- statics: new function() {
- function handleAttribute(name) {
- name += 'Attribute';
- return function(el, attr) {
- return el[name](attr) || el[name]('data-paper-' + attr);
- };
- }
-
- return {
- _scopes: {},
- _id: 0,
-
- get: function(id) {
- if (typeof id === 'object')
- id = id.getAttribute('id');
- return this._scopes[id] || null;
- },
-
- getAttribute: handleAttribute('get'),
- hasAttribute: handleAttribute('has')
- };
- }
-});
-
-var PaperScopeItem = Base.extend(Callback, {
-
- initialize: function(activate) {
- this._scope = paper;
- this._index = this._scope[this._list].push(this) - 1;
- if (activate || !this._scope[this._reference])
- this.activate();
- },
-
- activate: function() {
- if (!this._scope)
- return false;
- var prev = this._scope[this._reference];
- if (prev && prev !== this)
- prev.fire('deactivate');
- this._scope[this._reference] = this;
- this.fire('activate', prev);
- return true;
- },
-
- isActive: function() {
- return this._scope[this._reference] === this;
- },
-
- remove: function() {
- if (this._index == null)
- return false;
- Base.splice(this._scope[this._list], null, this._index, 1);
- if (this._scope[this._reference] == this)
- this._scope[this._reference] = null;
- this._scope = null;
- return true;
- }
-});
-
-var Formatter = Base.extend({
- initialize: function(precision) {
- this.precision = precision || 5;
- this.multiplier = Math.pow(10, this.precision);
- },
-
- number: function(val) {
- return Math.round(val * this.multiplier) / this.multiplier;
- },
-
- point: function(val, separator) {
- return this.number(val.x) + (separator || ',') + this.number(val.y);
- },
-
- size: function(val, separator) {
- return this.number(val.width) + (separator || ',')
- + this.number(val.height);
- },
-
- rectangle: function(val, separator) {
- return this.point(val, separator) + (separator || ',')
- + this.size(val, separator);
- }
-});
-
-Formatter.instance = new Formatter();
-
-var Numerical = new function() {
-
- var abscissas = [
- [ 0.5773502691896257645091488],
- [0,0.7745966692414833770358531],
- [ 0.3399810435848562648026658,0.8611363115940525752239465],
- [0,0.5384693101056830910363144,0.9061798459386639927976269],
- [ 0.2386191860831969086305017,0.6612093864662645136613996,0.9324695142031520278123016],
- [0,0.4058451513773971669066064,0.7415311855993944398638648,0.9491079123427585245261897],
- [ 0.1834346424956498049394761,0.5255324099163289858177390,0.7966664774136267395915539,0.9602898564975362316835609],
- [0,0.3242534234038089290385380,0.6133714327005903973087020,0.8360311073266357942994298,0.9681602395076260898355762],
- [ 0.1488743389816312108848260,0.4333953941292471907992659,0.6794095682990244062343274,0.8650633666889845107320967,0.9739065285171717200779640],
- [0,0.2695431559523449723315320,0.5190961292068118159257257,0.7301520055740493240934163,0.8870625997680952990751578,0.9782286581460569928039380],
- [ 0.1252334085114689154724414,0.3678314989981801937526915,0.5873179542866174472967024,0.7699026741943046870368938,0.9041172563704748566784659,0.9815606342467192506905491],
- [0,0.2304583159551347940655281,0.4484927510364468528779129,0.6423493394403402206439846,0.8015780907333099127942065,0.9175983992229779652065478,0.9841830547185881494728294],
- [ 0.1080549487073436620662447,0.3191123689278897604356718,0.5152486363581540919652907,0.6872929048116854701480198,0.8272013150697649931897947,0.9284348836635735173363911,0.9862838086968123388415973],
- [0,0.2011940939974345223006283,0.3941513470775633698972074,0.5709721726085388475372267,0.7244177313601700474161861,0.8482065834104272162006483,0.9372733924007059043077589,0.9879925180204854284895657],
- [ 0.0950125098376374401853193,0.2816035507792589132304605,0.4580167776572273863424194,0.6178762444026437484466718,0.7554044083550030338951012,0.8656312023878317438804679,0.9445750230732325760779884,0.9894009349916499325961542]
- ];
-
- var weights = [
- [1],
- [0.8888888888888888888888889,0.5555555555555555555555556],
- [0.6521451548625461426269361,0.3478548451374538573730639],
- [0.5688888888888888888888889,0.4786286704993664680412915,0.2369268850561890875142640],
- [0.4679139345726910473898703,0.3607615730481386075698335,0.1713244923791703450402961],
- [0.4179591836734693877551020,0.3818300505051189449503698,0.2797053914892766679014678,0.1294849661688696932706114],
- [0.3626837833783619829651504,0.3137066458778872873379622,0.2223810344533744705443560,0.1012285362903762591525314],
- [0.3302393550012597631645251,0.3123470770400028400686304,0.2606106964029354623187429,0.1806481606948574040584720,0.0812743883615744119718922],
- [0.2955242247147528701738930,0.2692667193099963550912269,0.2190863625159820439955349,0.1494513491505805931457763,0.0666713443086881375935688],
- [0.2729250867779006307144835,0.2628045445102466621806889,0.2331937645919904799185237,0.1862902109277342514260976,0.1255803694649046246346943,0.0556685671161736664827537],
- [0.2491470458134027850005624,0.2334925365383548087608499,0.2031674267230659217490645,0.1600783285433462263346525,0.1069393259953184309602547,0.0471753363865118271946160],
- [0.2325515532308739101945895,0.2262831802628972384120902,0.2078160475368885023125232,0.1781459807619457382800467,0.1388735102197872384636018,0.0921214998377284479144218,0.0404840047653158795200216],
- [0.2152638534631577901958764,0.2051984637212956039659241,0.1855383974779378137417166,0.1572031671581935345696019,0.1215185706879031846894148,0.0801580871597602098056333,0.0351194603317518630318329],
- [0.2025782419255612728806202,0.1984314853271115764561183,0.1861610000155622110268006,0.1662692058169939335532009,0.1395706779261543144478048,0.1071592204671719350118695,0.0703660474881081247092674,0.0307532419961172683546284],
- [0.1894506104550684962853967,0.1826034150449235888667637,0.1691565193950025381893121,0.1495959888165767320815017,0.1246289712555338720524763,0.0951585116824927848099251,0.0622535239386478928628438,0.0271524594117540948517806]
- ];
-
- var abs = Math.abs,
- sqrt = Math.sqrt,
- pow = Math.pow,
- cos = Math.cos,
- PI = Math.PI;
-
- return {
- TOLERANCE: 10e-6,
- EPSILON: 10e-12,
- KAPPA: 4 * (sqrt(2) - 1) / 3,
-
- isZero: function(val) {
- return abs(val) <= Numerical.EPSILON;
- },
-
- integrate: function(f, a, b, n) {
- var x = abscissas[n - 2],
- w = weights[n - 2],
- A = 0.5 * (b - a),
- B = A + a,
- i = 0,
- m = (n + 1) >> 1,
- sum = n & 1 ? w[i++] * f(B) : 0;
- while (i < m) {
- var Ax = A * x[i];
- sum += w[i++] * (f(B + Ax) + f(B - Ax));
- }
- return A * sum;
- },
-
- findRoot: function(f, df, x, a, b, n, tolerance) {
- for (var i = 0; i < n; i++) {
- var fx = f(x),
- dx = fx / df(x);
- if (abs(dx) < tolerance)
- return x;
- var nx = x - dx;
- if (fx > 0) {
- b = x;
- x = nx <= a ? 0.5 * (a + b) : nx;
- } else {
- a = x;
- x = nx >= b ? 0.5 * (a + b) : nx;
- }
- }
- },
-
- solveQuadratic: function(a, b, c, roots, min, max) {
- var epsilon = Numerical.EPSILON,
- unbound = min === undefined,
- minE = min - epsilon,
- maxE = max + epsilon,
- count = 0;
-
- function add(root) {
- if (unbound || root > minE && root < maxE)
- roots[count++] = root < min ? min : root > max ? max : root;
- return count;
- }
-
- if (abs(a) < epsilon) {
- if (abs(b) >= epsilon)
- return add(-c / b);
- return abs(c) < epsilon ? -1 : 0;
- }
- var p = b / (2 * a);
- var q = c / a;
- var p2 = p * p;
- if (p2 < q - epsilon)
- return 0;
- var s = p2 > q ? sqrt(p2 - q) : 0;
- add (s - p);
- if (s > 0)
- add(-s - p);
- return count;
- },
-
- solveCubic: function(a, b, c, d, roots, min, max) {
- var epsilon = Numerical.EPSILON;
- if (abs(a) < epsilon)
- return Numerical.solveQuadratic(b, c, d, roots, min, max);
-
- var unbound = min === undefined,
- minE = min - epsilon,
- maxE = max + epsilon,
- count = 0;
-
- function add(root) {
- if (unbound || root > minE && root < maxE)
- roots[count++] = root < min ? min : root > max ? max : root;
- return count;
- }
-
- b /= a;
- c /= a;
- d /= a;
- var bb = b * b,
- p = (bb - 3 * c) / 9,
- q = (2 * bb * b - 9 * b * c + 27 * d) / 54,
- ppp = p * p * p,
- D = q * q - ppp;
- b /= 3;
- if (abs(D) < epsilon) {
- if (abs(q) < epsilon)
- return add(-b);
- var sqp = sqrt(p),
- snq = q > 0 ? 1 : -1;
- add(-snq * 2 * sqp - b);
- return add(snq * sqp - b);
- }
- if (D < 0) {
- var sqp = sqrt(p),
- phi = Math.acos(q / (sqp * sqp * sqp)) / 3,
- t = -2 * sqp,
- o = 2 * PI / 3;
- add(t * cos(phi) - b);
- add(t * cos(phi + o) - b);
- return add(t * cos(phi - o) - b);
- }
- var A = (q > 0 ? -1 : 1) * pow(abs(q) + sqrt(D), 1 / 3);
- return add(A + p / A - b);
- }
- };
-};
-
-var Point = Base.extend({
- _class: 'Point',
- _readIndex: true,
-
- initialize: function Point(arg0, arg1) {
- var type = typeof arg0;
- if (type === 'number') {
- var hasY = typeof arg1 === 'number';
- this.x = arg0;
- this.y = hasY ? arg1 : arg0;
- if (this.__read)
- this.__read = hasY ? 2 : 1;
- } else if (type === 'undefined' || arg0 === null) {
- this.x = this.y = 0;
- if (this.__read)
- this.__read = arg0 === null ? 1 : 0;
- } else {
- if (Array.isArray(arg0)) {
- this.x = arg0[0];
- this.y = arg0.length > 1 ? arg0[1] : arg0[0];
- } else if (arg0.x != null) {
- this.x = arg0.x;
- this.y = arg0.y;
- } else if (arg0.width != null) {
- this.x = arg0.width;
- this.y = arg0.height;
- } else if (arg0.angle != null) {
- this.x = arg0.length;
- this.y = 0;
- this.setAngle(arg0.angle);
- } else {
- this.x = this.y = 0;
- if (this.__read)
- this.__read = 0;
- }
- if (this.__read)
- this.__read = 1;
- }
- },
-
- set: function(x, y) {
- this.x = x;
- this.y = y;
- return this;
- },
-
- equals: function(point) {
- return point === this || point && (this.x === point.x
- && this.y === point.y
- || Array.isArray(point) && this.x === point[0]
- && this.y === point[1]) || false;
- },
-
- clone: function() {
- return new Point(this.x, this.y);
- },
-
- toString: function() {
- var f = Formatter.instance;
- return '{ x: ' + f.number(this.x) + ', y: ' + f.number(this.y) + ' }';
- },
-
- _serialize: function(options) {
- var f = options.formatter;
- return [f.number(this.x), f.number(this.y)];
- },
-
- add: function(point) {
- point = Point.read(arguments);
- return new Point(this.x + point.x, this.y + point.y);
- },
-
- subtract: function(point) {
- point = Point.read(arguments);
- return new Point(this.x - point.x, this.y - point.y);
- },
-
- multiply: function(point) {
- point = Point.read(arguments);
- return new Point(this.x * point.x, this.y * point.y);
- },
-
- divide: function(point) {
- point = Point.read(arguments);
- return new Point(this.x / point.x, this.y / point.y);
- },
-
- modulo: function(point) {
- point = Point.read(arguments);
- return new Point(this.x % point.x, this.y % point.y);
- },
-
- negate: function() {
- return new Point(-this.x, -this.y);
- },
-
- transform: function(matrix) {
- return matrix ? matrix._transformPoint(this) : this;
- },
-
- getDistance: function(point, squared) {
- point = Point.read(arguments);
- var x = point.x - this.x,
- y = point.y - this.y,
- d = x * x + y * y;
- return squared ? d : Math.sqrt(d);
- },
-
- getLength: function() {
- var length = this.x * this.x + this.y * this.y;
- return arguments.length && arguments[0] ? length : Math.sqrt(length);
- },
-
- setLength: function(length) {
- if (this.isZero()) {
- var angle = this._angle || 0;
- this.set(
- Math.cos(angle) * length,
- Math.sin(angle) * length
- );
- } else {
- var scale = length / this.getLength();
- if (Numerical.isZero(scale))
- this.getAngle();
- this.set(
- this.x * scale,
- this.y * scale
- );
- }
- return this;
- },
-
- normalize: function(length) {
- if (length === undefined)
- length = 1;
- var current = this.getLength(),
- scale = current !== 0 ? length / current : 0,
- point = new Point(this.x * scale, this.y * scale);
- point._angle = this._angle;
- return point;
- },
-
- getAngle: function() {
- return this.getAngleInRadians(arguments[0]) * 180 / Math.PI;
- },
-
- setAngle: function(angle) {
- angle = this._angle = angle * Math.PI / 180;
- if (!this.isZero()) {
- var length = this.getLength();
- this.set(
- Math.cos(angle) * length,
- Math.sin(angle) * length
- );
- }
- return this;
- },
-
- getAngleInRadians: function() {
- if (arguments[0] === undefined) {
- return this.isZero()
- ? this._angle || 0
- : this._angle = Math.atan2(this.y, this.x);
- } else {
- var point = Point.read(arguments),
- div = this.getLength() * point.getLength();
- if (Numerical.isZero(div)) {
- return NaN;
- } else {
- return Math.acos(this.dot(point) / div);
- }
- }
- },
-
- getAngleInDegrees: function() {
- return this.getAngle(arguments[0]);
- },
-
- getQuadrant: function() {
- return this.x >= 0 ? this.y >= 0 ? 1 : 4 : this.y >= 0 ? 2 : 3;
- },
-
- getDirectedAngle: function(point) {
- point = Point.read(arguments);
- return Math.atan2(this.cross(point), this.dot(point)) * 180 / Math.PI;
- },
-
- rotate: function(angle, center) {
- if (angle === 0)
- return this.clone();
- angle = angle * Math.PI / 180;
- var point = center ? this.subtract(center) : this,
- s = Math.sin(angle),
- c = Math.cos(angle);
- point = new Point(
- point.x * c - point.y * s,
- point.y * c + point.x * s
- );
- return center ? point.add(center) : point;
- },
-
- isInside: function(rect) {
- return rect.contains(this);
- },
-
- isClose: function(point, tolerance) {
- return this.getDistance(point) < tolerance;
- },
-
- isColinear: function(point) {
- return this.cross(point) < 0.00001;
- },
-
- isOrthogonal: function(point) {
- return this.dot(point) < 0.00001;
- },
-
- isZero: function() {
- return Numerical.isZero(this.x) && Numerical.isZero(this.y);
- },
-
- isNaN: function() {
- return isNaN(this.x) || isNaN(this.y);
- },
-
- dot: function(point) {
- point = Point.read(arguments);
- return this.x * point.x + this.y * point.y;
- },
-
- cross: function(point) {
- point = Point.read(arguments);
- return this.x * point.y - this.y * point.x;
- },
-
- project: function(point) {
- point = Point.read(arguments);
- if (point.isZero()) {
- return new Point(0, 0);
- } else {
- var scale = this.dot(point) / point.dot(point);
- return new Point(
- point.x * scale,
- point.y * scale
- );
- }
- },
-
- statics: {
- min: function() {
- var point1 = Point.read(arguments);
- point2 = Point.read(arguments);
- return new Point(
- Math.min(point1.x, point2.x),
- Math.min(point1.y, point2.y)
- );
- },
-
- max: function() {
- var point1 = Point.read(arguments);
- point2 = Point.read(arguments);
- return new Point(
- Math.max(point1.x, point2.x),
- Math.max(point1.y, point2.y)
- );
- },
-
- random: function() {
- return new Point(Math.random(), Math.random());
- }
- }
-}, Base.each(['round', 'ceil', 'floor', 'abs'], function(name) {
- var op = Math[name];
- this[name] = function() {
- return new Point(op(this.x), op(this.y));
- };
-}, {}));
-
-var LinkedPoint = Point.extend({
- initialize: function Point(x, y, owner, setter) {
- this._x = x;
- this._y = y;
- this._owner = owner;
- this._setter = setter;
- },
-
- set: function(x, y, _dontNotify) {
- this._x = x;
- this._y = y;
- if (!_dontNotify)
- this._owner[this._setter](this);
- return this;
- },
-
- getX: function() {
- return this._x;
- },
-
- setX: function(x) {
- this._x = x;
- this._owner[this._setter](this);
- },
-
- getY: function() {
- return this._y;
- },
-
- setY: function(y) {
- this._y = y;
- this._owner[this._setter](this);
- }
-});
-
-var Size = Base.extend({
- _class: 'Size',
- _readIndex: true,
-
- initialize: function Size(arg0, arg1) {
- var type = typeof arg0;
- if (type === 'number') {
- var hasHeight = typeof arg1 === 'number';
- this.width = arg0;
- this.height = hasHeight ? arg1 : arg0;
- if (this.__read)
- this.__read = hasHeight ? 2 : 1;
- } else if (type === 'undefined' || arg0 === null) {
- this.width = this.height = 0;
- if (this.__read)
- this.__read = arg0 === null ? 1 : 0;
- } else {
- if (Array.isArray(arg0)) {
- this.width = arg0[0];
- this.height = arg0.length > 1 ? arg0[1] : arg0[0];
- } else if (arg0.width != null) {
- this.width = arg0.width;
- this.height = arg0.height;
- } else if (arg0.x != null) {
- this.width = arg0.x;
- this.height = arg0.y;
- } else {
- this.width = this.height = 0;
- if (this.__read)
- this.__read = 0;
- }
- if (this.__read)
- this.__read = 1;
- }
- },
-
- set: function(width, height) {
- this.width = width;
- this.height = height;
- return this;
- },
-
- equals: function(size) {
- return size === this || size && (this.width === size.width
- && this.height === size.height
- || Array.isArray(size) && this.width === size[0]
- && this.height === size[1]) || false;
- },
-
- clone: function() {
- return new Size(this.width, this.height);
- },
-
- toString: function() {
- var f = Formatter.instance;
- return '{ width: ' + f.number(this.width)
- + ', height: ' + f.number(this.height) + ' }';
- },
-
- _serialize: function(options) {
- var f = options.formatter;
- return [f.number(this.width),
- f.number(this.height)];
- },
-
- add: function(size) {
- size = Size.read(arguments);
- return new Size(this.width + size.width, this.height + size.height);
- },
-
- subtract: function(size) {
- size = Size.read(arguments);
- return new Size(this.width - size.width, this.height - size.height);
- },
-
- multiply: function(size) {
- size = Size.read(arguments);
- return new Size(this.width * size.width, this.height * size.height);
- },
-
- divide: function(size) {
- size = Size.read(arguments);
- return new Size(this.width / size.width, this.height / size.height);
- },
-
- modulo: function(size) {
- size = Size.read(arguments);
- return new Size(this.width % size.width, this.height % size.height);
- },
-
- negate: function() {
- return new Size(-this.width, -this.height);
- },
-
- isZero: function() {
- return Numerical.isZero(this.width) && Numerical.isZero(this.height);
- },
-
- isNaN: function() {
- return isNaN(this.width) || isNaN(this.height);
- },
-
- statics: {
- min: function(size1, size2) {
- return new Size(
- Math.min(size1.width, size2.width),
- Math.min(size1.height, size2.height));
- },
-
- max: function(size1, size2) {
- return new Size(
- Math.max(size1.width, size2.width),
- Math.max(size1.height, size2.height));
- },
-
- random: function() {
- return new Size(Math.random(), Math.random());
- }
- }
-}, Base.each(['round', 'ceil', 'floor', 'abs'], function(name) {
- var op = Math[name];
- this[name] = function() {
- return new Size(op(this.width), op(this.height));
- };
-}, {}));
-
-var LinkedSize = Size.extend({
- initialize: function Size(width, height, owner, setter) {
- this._width = width;
- this._height = height;
- this._owner = owner;
- this._setter = setter;
- },
-
- set: function(width, height, _dontNotify) {
- this._width = width;
- this._height = height;
- if (!_dontNotify)
- this._owner[this._setter](this);
- return this;
- },
-
- getWidth: function() {
- return this._width;
- },
-
- setWidth: function(width) {
- this._width = width;
- this._owner[this._setter](this);
- },
-
- getHeight: function() {
- return this._height;
- },
-
- setHeight: function(height) {
- this._height = height;
- this._owner[this._setter](this);
- }
-});
-
-var Rectangle = Base.extend({
- _class: 'Rectangle',
- _readIndex: true,
-
- initialize: function Rectangle(arg0, arg1, arg2, arg3) {
- var type = typeof arg0,
- read = 0;
- if (type === 'number') {
- this.x = arg0;
- this.y = arg1;
- this.width = arg2;
- this.height = arg3;
- read = 4;
- } else if (type === 'undefined' || arg0 === null) {
- this.x = this.y = this.width = this.height = 0;
- read = arg0 === null ? 1 : 0;
- } else if (arguments.length === 1) {
- if (Array.isArray(arg0)) {
- this.x = arg0[0];
- this.y = arg0[1];
- this.width = arg0[2];
- this.height = arg0[3];
- read = 1;
- } else if (arg0.x !== undefined || arg0.width !== undefined) {
- this.x = arg0.x || 0;
- this.y = arg0.y || 0;
- this.width = arg0.width || 0;
- this.height = arg0.height || 0;
- read = 1;
- } else if (arg0.from === undefined && arg0.to === undefined) {
- this.x = this.y = this.width = this.height = 0;
- this._set(arg0);
- read = 1;
- }
- }
- if (!read) {
- var point = Point.readNamed(arguments, 'from'),
- next = Base.peek(arguments);
- this.x = point.x;
- this.y = point.y;
- if (next && next.x !== undefined || Base.hasNamed(arguments, 'to')) {
- var to = Point.readNamed(arguments, 'to');
- this.width = to.x - point.x;
- this.height = to.y - point.y;
- if (this.width < 0) {
- this.x = to.x;
- this.width = -this.width;
- }
- if (this.height < 0) {
- this.y = to.y;
- this.height = -this.height;
- }
- } else {
- var size = Size.read(arguments);
- this.width = size.width;
- this.height = size.height;
- }
- read = arguments._index;
- }
- if (this.__read)
- this.__read = read;
- },
-
- set: function(x, y, width, height) {
- this.x = x;
- this.y = y;
- this.width = width;
- this.height = height;
- return this;
- },
-
- clone: function() {
- return new Rectangle(this.x, this.y, this.width, this.height);
- },
-
- equals: function(rect) {
- if (Base.isPlainValue(rect))
- rect = Rectangle.read(arguments);
- return rect === this
- || rect && this.x === rect.x && this.y === rect.y
- && this.width === rect.width && this.height === rect.height
- || false;
- },
-
- toString: function() {
- var f = Formatter.instance;
- return '{ x: ' + f.number(this.x)
- + ', y: ' + f.number(this.y)
- + ', width: ' + f.number(this.width)
- + ', height: ' + f.number(this.height)
- + ' }';
- },
-
- _serialize: function(options) {
- var f = options.formatter;
- return [f.number(this.x),
- f.number(this.y),
- f.number(this.width),
- f.number(this.height)];
- },
-
- getPoint: function() {
- return new (arguments[0] ? Point : LinkedPoint)
- (this.x, this.y, this, 'setPoint');
- },
-
- setPoint: function(point) {
- point = Point.read(arguments);
- this.x = point.x;
- this.y = point.y;
- },
-
- getSize: function() {
- return new (arguments[0] ? Size : LinkedSize)
- (this.width, this.height, this, 'setSize');
- },
-
- setSize: function(size) {
- size = Size.read(arguments);
- if (this._fixX)
- this.x += (this.width - size.width) * this._fixX;
- if (this._fixY)
- this.y += (this.height - size.height) * this._fixY;
- this.width = size.width;
- this.height = size.height;
- this._fixW = 1;
- this._fixH = 1;
- },
-
- getLeft: function() {
- return this.x;
- },
-
- setLeft: function(left) {
- if (!this._fixW)
- this.width -= left - this.x;
- this.x = left;
- this._fixX = 0;
- },
-
- getTop: function() {
- return this.y;
- },
-
- setTop: function(top) {
- if (!this._fixH)
- this.height -= top - this.y;
- this.y = top;
- this._fixY = 0;
- },
-
- getRight: function() {
- return this.x + this.width;
- },
-
- setRight: function(right) {
- if (this._fixX !== undefined && this._fixX !== 1)
- this._fixW = 0;
- if (this._fixW)
- this.x = right - this.width;
- else
- this.width = right - this.x;
- this._fixX = 1;
- },
-
- getBottom: function() {
- return this.y + this.height;
- },
-
- setBottom: function(bottom) {
- if (this._fixY !== undefined && this._fixY !== 1)
- this._fixH = 0;
- if (this._fixH)
- this.y = bottom - this.height;
- else
- this.height = bottom - this.y;
- this._fixY = 1;
- },
-
- getCenterX: function() {
- return this.x + this.width * 0.5;
- },
-
- setCenterX: function(x) {
- this.x = x - this.width * 0.5;
- this._fixX = 0.5;
- },
-
- getCenterY: function() {
- return this.y + this.height * 0.5;
- },
-
- setCenterY: function(y) {
- this.y = y - this.height * 0.5;
- this._fixY = 0.5;
- },
-
- getCenter: function() {
- return new (arguments[0] ? Point : LinkedPoint)
- (this.getCenterX(), this.getCenterY(), this, 'setCenter');
- },
-
- setCenter: function(point) {
- point = Point.read(arguments);
- this.setCenterX(point.x);
- this.setCenterY(point.y);
- return this;
- },
-
- isEmpty: function() {
- return this.width == 0 || this.height == 0;
- },
-
- contains: function(arg) {
- return arg && arg.width !== undefined
- || (Array.isArray(arg) ? arg : arguments).length == 4
- ? this._containsRectangle(Rectangle.read(arguments))
- : this._containsPoint(Point.read(arguments));
- },
-
- _containsPoint: function(point) {
- var x = point.x,
- y = point.y;
- return x >= this.x && y >= this.y
- && x <= this.x + this.width
- && y <= this.y + this.height;
- },
-
- _containsRectangle: function(rect) {
- var x = rect.x,
- y = rect.y;
- return x >= this.x && y >= this.y
- && x + rect.width <= this.x + this.width
- && y + rect.height <= this.y + this.height;
- },
-
- intersects: function(rect) {
- rect = Rectangle.read(arguments);
- return rect.x + rect.width > this.x
- && rect.y + rect.height > this.y
- && rect.x < this.x + this.width
- && rect.y < this.y + this.height;
- },
-
- touches: function(rect) {
- rect = Rectangle.read(arguments);
- return rect.x + rect.width >= this.x
- && rect.y + rect.height >= this.y
- && rect.x <= this.x + this.width
- && rect.y <= this.y + this.height;
- },
-
- intersect: function(rect) {
- rect = Rectangle.read(arguments);
- var x1 = Math.max(this.x, rect.x),
- y1 = Math.max(this.y, rect.y),
- x2 = Math.min(this.x + this.width, rect.x + rect.width),
- y2 = Math.min(this.y + this.height, rect.y + rect.height);
- return new Rectangle(x1, y1, x2 - x1, y2 - y1);
- },
-
- unite: function(rect) {
- rect = Rectangle.read(arguments);
- var x1 = Math.min(this.x, rect.x),
- y1 = Math.min(this.y, rect.y),
- x2 = Math.max(this.x + this.width, rect.x + rect.width),
- y2 = Math.max(this.y + this.height, rect.y + rect.height);
- return new Rectangle(x1, y1, x2 - x1, y2 - y1);
- },
-
- include: function(point) {
- point = Point.read(arguments);
- var x1 = Math.min(this.x, point.x),
- y1 = Math.min(this.y, point.y),
- x2 = Math.max(this.x + this.width, point.x),
- y2 = Math.max(this.y + this.height, point.y);
- return new Rectangle(x1, y1, x2 - x1, y2 - y1);
- },
-
- expand: function(hor, ver) {
- if (ver === undefined)
- ver = hor;
- return new Rectangle(this.x - hor / 2, this.y - ver / 2,
- this.width + hor, this.height + ver);
- },
-
- scale: function(hor, ver) {
- return this.expand(this.width * hor - this.width,
- this.height * (ver === undefined ? hor : ver) - this.height);
- }
-}, new function() {
- return Base.each([
- ['Top', 'Left'], ['Top', 'Right'],
- ['Bottom', 'Left'], ['Bottom', 'Right'],
- ['Left', 'Center'], ['Top', 'Center'],
- ['Right', 'Center'], ['Bottom', 'Center']
- ],
- function(parts, index) {
- var part = parts.join('');
- var xFirst = /^[RL]/.test(part);
- if (index >= 4)
- parts[1] += xFirst ? 'Y' : 'X';
- var x = parts[xFirst ? 0 : 1],
- y = parts[xFirst ? 1 : 0],
- getX = 'get' + x,
- getY = 'get' + y,
- setX = 'set' + x,
- setY = 'set' + y,
- get = 'get' + part,
- set = 'set' + part;
- this[get] = function() {
- return new (arguments[0] ? Point : LinkedPoint)
- (this[getX](), this[getY](), this, set);
- };
- this[set] = function(point) {
- point = Point.read(arguments);
- this[setX](point.x);
- this[setY](point.y);
- };
- }, {});
-});
-
-var LinkedRectangle = Rectangle.extend({
- initialize: function Rectangle(x, y, width, height, owner, setter) {
- this.set(x, y, width, height, true);
- this._owner = owner;
- this._setter = setter;
- },
-
- set: function(x, y, width, height, _dontNotify) {
- this._x = x;
- this._y = y;
- this._width = width;
- this._height = height;
- if (!_dontNotify)
- this._owner[this._setter](this);
- return this;
- }
-}, new function() {
- var proto = Rectangle.prototype;
-
- return Base.each(['x', 'y', 'width', 'height'], function(key) {
- var part = Base.capitalize(key);
- var internal = '_' + key;
- this['get' + part] = function() {
- return this[internal];
- };
-
- this['set' + part] = function(value) {
- this[internal] = value;
- if (!this._dontNotify)
- this._owner[this._setter](this);
- };
- }, Base.each(['Point', 'Size', 'Center',
- 'Left', 'Top', 'Right', 'Bottom', 'CenterX', 'CenterY',
- 'TopLeft', 'TopRight', 'BottomLeft', 'BottomRight',
- 'LeftCenter', 'TopCenter', 'RightCenter', 'BottomCenter'],
- function(key) {
- var name = 'set' + key;
- this[name] = function() {
- this._dontNotify = true;
- proto[name].apply(this, arguments);
- delete this._dontNotify;
- this._owner[this._setter](this);
- };
- }, {
- isSelected: function() {
- return this._owner._boundsSelected;
- },
-
- setSelected: function(selected) {
- var owner = this._owner;
- if (owner.setSelected) {
- owner._boundsSelected = selected;
- owner.setSelected(selected || owner._selectedSegmentState > 0);
- }
- }
- })
- );
-});
-
-var Matrix = Base.extend({
- _class: 'Matrix',
-
- initialize: function Matrix(arg) {
- var count = arguments.length,
- ok = true;
- if (count === 6) {
- this.set.apply(this, arguments);
- } else if (count === 1) {
- if (arg instanceof Matrix) {
- this.set(arg._a, arg._c, arg._b, arg._d, arg._tx, arg._ty);
- } else if (Array.isArray(arg)) {
- this.set.apply(this, arg);
- } else {
- ok = false;
- }
- } else if (count === 0) {
- this.reset();
- } else {
- ok = false;
- }
- if (!ok)
- throw new Error('Unsupported matrix parameters');
- },
-
- set: function(a, c, b, d, tx, ty, _dontNotify) {
- this._a = a;
- this._c = c;
- this._b = b;
- this._d = d;
- this._tx = tx;
- this._ty = ty;
- if (!_dontNotify)
- this._changed();
- return this;
- },
-
- _serialize: function(options) {
- return Base.serialize(this.getValues(), options);
- },
-
- _changed: function() {
- if (this._owner)
- this._owner._changed(5);
- },
-
- clone: function() {
- return new Matrix(this._a, this._c, this._b, this._d,
- this._tx, this._ty);
- },
-
- equals: function(mx) {
- return mx === this || mx && this._a === mx._a && this._b === mx._b
- && this._c === mx._c && this._d === mx._d
- && this._tx === mx._tx && this._ty === mx._ty
- || false;
- },
-
- toString: function() {
- var f = Formatter.instance;
- return '[[' + [f.number(this._a), f.number(this._b),
- f.number(this._tx)].join(', ') + '], ['
- + [f.number(this._c), f.number(this._d),
- f.number(this._ty)].join(', ') + ']]';
- },
-
- reset: function() {
- this._a = this._d = 1;
- this._c = this._b = this._tx = this._ty = 0;
- this._changed();
- return this;
- },
-
- scale: function() {
- var scale = Point.read(arguments),
- center = Point.read(arguments, 0, 0, { readNull: true });
- if (center)
- this.translate(center);
- this._a *= scale.x;
- this._c *= scale.x;
- this._b *= scale.y;
- this._d *= scale.y;
- if (center)
- this.translate(center.negate());
- this._changed();
- return this;
- },
-
- translate: function(point) {
- point = Point.read(arguments);
- var x = point.x,
- y = point.y;
- this._tx += x * this._a + y * this._b;
- this._ty += x * this._c + y * this._d;
- this._changed();
- return this;
- },
-
- rotate: function(angle, center) {
- center = Point.read(arguments, 1);
- angle = angle * Math.PI / 180;
- var x = center.x,
- y = center.y,
- cos = Math.cos(angle),
- sin = Math.sin(angle),
- tx = x - x * cos + y * sin,
- ty = y - x * sin - y * cos,
- a = this._a,
- b = this._b,
- c = this._c,
- d = this._d;
- this._a = cos * a + sin * b;
- this._b = -sin * a + cos * b;
- this._c = cos * c + sin * d;
- this._d = -sin * c + cos * d;
- this._tx += tx * a + ty * b;
- this._ty += tx * c + ty * d;
- this._changed();
- return this;
- },
-
- shear: function() {
- var point = Point.read(arguments),
- center = Point.read(arguments, 0, 0, { readNull: true });
- if (center)
- this.translate(center);
- var a = this._a,
- c = this._c;
- this._a += point.y * this._b;
- this._c += point.y * this._d;
- this._b += point.x * a;
- this._d += point.x * c;
- if (center)
- this.translate(center.negate());
- this._changed();
- return this;
- },
-
- concatenate: function(mx) {
- var a = this._a,
- b = this._b,
- c = this._c,
- d = this._d;
- this._a = mx._a * a + mx._c * b;
- this._b = mx._b * a + mx._d * b;
- this._c = mx._a * c + mx._c * d;
- this._d = mx._b * c + mx._d * d;
- this._tx += mx._tx * a + mx._ty * b;
- this._ty += mx._tx * c + mx._ty * d;
- this._changed();
- return this;
- },
-
- preConcatenate: function(mx) {
- var a = this._a,
- b = this._b,
- c = this._c,
- d = this._d,
- tx = this._tx,
- ty = this._ty;
- this._a = mx._a * a + mx._b * c;
- this._b = mx._a * b + mx._b * d;
- this._c = mx._c * a + mx._d * c;
- this._d = mx._c * b + mx._d * d;
- this._tx = mx._a * tx + mx._b * ty + mx._tx;
- this._ty = mx._c * tx + mx._d * ty + mx._ty;
- this._changed();
- return this;
- },
-
- isIdentity: function() {
- return this._a === 1 && this._c === 0 && this._b === 0 && this._d === 1
- && this._tx === 0 && this._ty === 0;
- },
-
- isInvertible: function() {
- return !!this._getDeterminant();
- },
-
- isSingular: function() {
- return !this._getDeterminant();
- },
-
- transform: function( src, srcOffset, dst, dstOffset, count) {
- return arguments.length < 5
- ? this._transformPoint(Point.read(arguments))
- : this._transformCoordinates(src, srcOffset, dst, dstOffset, count);
- },
-
- _transformPoint: function(point, dest, _dontNotify) {
- var x = point.x,
- y = point.y;
- if (!dest)
- dest = new Point();
- return dest.set(
- x * this._a + y * this._b + this._tx,
- x * this._c + y * this._d + this._ty,
- _dontNotify
- );
- },
-
- _transformCoordinates: function(src, srcOffset, dst, dstOffset, count) {
- var i = srcOffset,
- j = dstOffset,
- max = i + 2 * count;
- while (i < max) {
- var x = src[i++],
- y = src[i++];
- dst[j++] = x * this._a + y * this._b + this._tx;
- dst[j++] = x * this._c + y * this._d + this._ty;
- }
- return dst;
- },
-
- _transformCorners: function(rect) {
- var x1 = rect.x,
- y1 = rect.y,
- x2 = x1 + rect.width,
- y2 = y1 + rect.height,
- coords = [ x1, y1, x2, y1, x2, y2, x1, y2 ];
- return this._transformCoordinates(coords, 0, coords, 0, 4);
- },
-
- _transformBounds: function(bounds, dest, _dontNotify) {
- var coords = this._transformCorners(bounds),
- min = coords.slice(0, 2),
- max = coords.slice();
- for (var i = 2; i < 8; i++) {
- var val = coords[i],
- j = i & 1;
- if (val < min[j])
- min[j] = val;
- else if (val > max[j])
- max[j] = val;
- }
- if (!dest)
- dest = new Rectangle();
- return dest.set(min[0], min[1], max[0] - min[0], max[1] - min[1],
- _dontNotify);
- },
-
- inverseTransform: function() {
- return this._inverseTransform(Point.read(arguments));
- },
-
- _getDeterminant: function() {
- var det = this._a * this._d - this._b * this._c;
- return isFinite(det) && !Numerical.isZero(det)
- && isFinite(this._tx) && isFinite(this._ty)
- ? det : null;
- },
-
- _inverseTransform: function(point, dest, _dontNotify) {
- var det = this._getDeterminant();
- if (!det)
- return null;
- var x = point.x - this._tx,
- y = point.y - this._ty;
- if (!dest)
- dest = new Point();
- return dest.set(
- (x * this._d - y * this._b) / det,
- (y * this._a - x * this._c) / det,
- _dontNotify
- );
- },
-
- decompose: function() {
- var a = this._a, b = this._b, c = this._c, d = this._d;
- if (Numerical.isZero(a * d - b * c))
- return null;
-
- var scaleX = Math.sqrt(a * a + b * b);
- a /= scaleX;
- b /= scaleX;
-
- var shear = a * c + b * d;
- c -= a * shear;
- d -= b * shear;
-
- var scaleY = Math.sqrt(c * c + d * d);
- c /= scaleY;
- d /= scaleY;
- shear /= scaleY;
-
- if (a * d < b * c) {
- a = -a;
- b = -b;
- shear = -shear;
- scaleX = -scaleX;
- }
-
- return {
- translation: this.getTranslation(),
- scaling: new Point(scaleX, scaleY),
- rotation: -Math.atan2(b, a) * 180 / Math.PI,
- shearing: shear
- };
- },
-
- getValues: function() {
- return [ this._a, this._c, this._b, this._d, this._tx, this._ty ];
- },
-
- getTranslation: function() {
- return new Point(this._tx, this._ty);
- },
-
- setTranslation: function() {
- var point = Point.read(arguments);
- this._tx = point.x;
- this._ty = point.y;
- this._changed();
- },
-
- getScaling: function() {
- return (this.decompose() || {}).scaling;
- },
-
- setScaling: function() {
- var scaling = this.getScaling();
- if (scaling != null) {
- var scale = Point.read(arguments);
- (this._owner || this).scale(
- scale.x / scaling.x, scale.y / scaling.y);
- }
- },
-
- getRotation: function() {
- return (this.decompose() || {}).rotation;
- },
-
- setRotation: function(angle) {
- var rotation = this.getRotation();
- if (rotation != null)
- (this._owner || this).rotate(angle - rotation);
- },
-
- inverted: function() {
- var det = this._getDeterminant();
- return det && new Matrix(
- this._d / det,
- -this._c / det,
- -this._b / det,
- this._a / det,
- (this._b * this._ty - this._d * this._tx) / det,
- (this._c * this._tx - this._a * this._ty) / det);
- },
-
- shiftless: function() {
- return new Matrix(this._a, this._c, this._b, this._d, 0, 0);
- },
-
- applyToContext: function(ctx) {
- ctx.transform(this._a, this._c, this._b, this._d, this._tx, this._ty);
- }
-}, new function() {
- return Base.each({
- scaleX: '_a',
- scaleY: '_d',
- translateX: '_tx',
- translateY: '_ty',
- shearX: '_b',
- shearY: '_c'
- }, function(prop, name) {
- name = Base.capitalize(name);
- this['get' + name] = function() {
- return this[prop];
- };
- this['set' + name] = function(value) {
- this[prop] = value;
- this._changed();
- };
- }, {});
-});
-
-var Line = Base.extend({
- _class: 'Line',
-
- initialize: function Line(arg0, arg1, arg2, arg3, arg4) {
- var asVector = false;
- if (arguments.length >= 4) {
- this._px = arg0;
- this._py = arg1;
- this._vx = arg2;
- this._vy = arg3;
- asVector = arg4;
- } else {
- this._px = arg0.x;
- this._py = arg0.y;
- this._vx = arg1.x;
- this._vy = arg1.y;
- asVector = arg2;
- }
- if (!asVector) {
- this._vx -= this._px;
- this._vy -= this._py;
- }
- },
-
- getPoint: function() {
- return new Point(this._px, this._py);
- },
-
- getVector: function() {
- return new Point(this._vx, this._vy);
- },
-
- getLength: function() {
- return this.getVector().getLength();
- },
-
- intersect: function(line, isInfinite) {
- return Line.intersect(
- this._px, this._py, this._vx, this._vy,
- line._px, line._py, line._vx, line._vy,
- true, isInfinite);
- },
-
- getSide: function(point) {
- return Line.getSide(
- this._px, this._py, this._vx, this._vy,
- point.x, point.y, true);
- },
-
- getDistance: function(point) {
- return Math.abs(Line.getSignedDistance(
- this._px, this._py, this._vx, this._vy,
- point.x, point.y, true));
- },
-
- statics: {
- intersect: function(apx, apy, avx, avy, bpx, bpy, bvx, bvy, asVector,
- isInfinite) {
- if (!asVector) {
- avx -= apx;
- avy -= apy;
- bvx -= bpx;
- bvy -= bpy;
- }
- var cross = bvy * avx - bvx * avy;
- if (!Numerical.isZero(cross)) {
- var dx = apx - bpx,
- dy = apy - bpy,
- ta = (bvx * dy - bvy * dx) / cross,
- tb = (avx * dy - avy * dx) / cross;
- if ((isInfinite || 0 <= ta && ta <= 1)
- && (isInfinite || 0 <= tb && tb <= 1))
- return new Point(
- apx + ta * avx,
- apy + ta * avy);
- }
- },
-
- getSide: function(px, py, vx, vy, x, y, asVector) {
- if (!asVector) {
- vx -= px;
- vy -= py;
- }
- var v2x = x - px,
- v2y = y - py,
- ccw = v2x * vy - v2y * vx;
- if (ccw === 0) {
- ccw = v2x * vx + v2y * vy;
- if (ccw > 0) {
- v2x -= vx;
- v2y -= vy;
- ccw = v2x * vx + v2y * vy;
- if (ccw < 0)
- ccw = 0;
- }
- }
- return ccw < 0 ? -1 : ccw > 0 ? 1 : 0;
- },
-
- getSignedDistance: function(px, py, vx, vy, x, y, asVector) {
- if (!asVector) {
- vx -= px;
- vy -= py;
- }
- var m = vy / vx,
- b = py - m * px;
- return (y - (m * x) - b) / Math.sqrt(m * m + 1);
- }
- }
-});
-
-var Project = PaperScopeItem.extend({
- _class: 'Project',
- _list: 'projects',
- _reference: 'project',
-
- initialize: function Project(view) {
- PaperScopeItem.call(this, true);
- this.layers = [];
- this.symbols = [];
- this._currentStyle = new Style();
- this.activeLayer = new Layer();
- if (view)
- this.view = view instanceof View ? view : View.create(view);
- this._selectedItems = {};
- this._selectedItemCount = 0;
- this._drawCount = 0;
- this.options = {};
- },
-
- _serialize: function(options, dictionary) {
- return Base.serialize(this.layers, options, true, dictionary);
- },
-
- clear: function() {
- for (var i = this.layers.length - 1; i >= 0; i--)
- this.layers[i].remove();
- this.symbols = [];
- },
-
- isEmpty: function() {
- return this.layers.length <= 1
- && (!this.activeLayer || this.activeLayer.isEmpty());
- },
-
- remove: function remove() {
- if (!remove.base.call(this))
- return false;
- if (this.view)
- this.view.remove();
- return true;
- },
-
- getCurrentStyle: function() {
- return this._currentStyle;
- },
-
- setCurrentStyle: function(style) {
- this._currentStyle.initialize(style);
- },
-
- getIndex: function() {
- return this._index;
- },
-
- addChild: function(child) {
- if (child instanceof Layer) {
- Base.splice(this.layers, [child]);
- if (!this.activeLayer)
- this.activeLayer = child;
- } else if (child instanceof Item) {
- (this.activeLayer
- || this.addChild(new Layer({ insert: false }))).addChild(child);
- } else {
- child = null;
- }
- return child;
- },
-
- getSelectedItems: function() {
- var items = [];
- for (var id in this._selectedItems) {
- var item = this._selectedItems[id];
- if (item.isInserted())
- items.push(item);
- }
- return items;
- },
-
- _updateSelection: function(item) {
- var id = item._id,
- selectedItems = this._selectedItems;
- if (item._selected) {
- if (selectedItems[id] !== item) {
- this._selectedItemCount++;
- selectedItems[id] = item;
- }
- } else if (selectedItems[id] === item) {
- this._selectedItemCount--;
- delete selectedItems[id];
- }
- },
-
- selectAll: function() {
- var layers = this.layers;
- for (var i = 0, l = layers.length; i < l; i++)
- layers[i].setFullySelected(true);
- },
-
- deselectAll: function() {
- var selectedItems = this._selectedItems;
- for (var i in selectedItems)
- selectedItems[i].setFullySelected(false);
- },
-
- hitTest: function(point, options) {
- point = Point.read(arguments);
- options = HitResult.getOptions(Base.read(arguments));
- for (var i = this.layers.length - 1; i >= 0; i--) {
- var res = this.layers[i].hitTest(point, options);
- if (res) return res;
- }
- return null;
- }
-}, new function() {
- function getItems(project, match, list) {
- var layers = project.layers,
- items = list && [];
- for (var i = 0, l = layers.length; i < l; i++) {
- var res = layers[i][list ? 'getItems' : 'getItem'](match);
- if (list) {
- items.push.apply(items, res);
- } else if (res)
- return res;
- }
- return list ? items : null;
- }
-
- return {
- getItems: function(match) {
- return getItems(this, match, true);
- },
-
- getItem: function(match) {
- return getItems(this, match, false);
- }
- };
-}, {
-
- importJSON: function(json) {
- this.activate();
- var layer = this.activeLayer;
- return Base.importJSON(json, layer && layer.isEmpty() && layer);
- },
-
- draw: function(ctx, matrix, ratio) {
- this._drawCount++;
- ctx.save();
- matrix.applyToContext(ctx);
- var param = new Base({
- offset: new Point(0, 0),
- ratio: ratio,
- transforms: [matrix],
- trackTransforms: true
- });
- for (var i = 0, l = this.layers.length; i < l; i++)
- this.layers[i].draw(ctx, param);
- ctx.restore();
-
- if (this._selectedItemCount > 0) {
- ctx.save();
- ctx.strokeWidth = 1;
- for (var id in this._selectedItems) {
- var item = this._selectedItems[id];
- if (item._drawCount === this._drawCount
- && (item._drawSelected || item._boundsSelected)) {
- var color = item.getSelectedColor()
- || item.getLayer().getSelectedColor();
- ctx.strokeStyle = ctx.fillStyle = color
- ? color.toCanvasStyle(ctx) : '#009dec';
- var mx = item._globalMatrix;
- if (item._drawSelected)
- item._drawSelected(ctx, mx);
- if (item._boundsSelected) {
- var coords = mx._transformCorners(
- item._getBounds('getBounds'));
- ctx.beginPath();
- for (var i = 0; i < 8; i++)
- ctx[i === 0 ? 'moveTo' : 'lineTo'](
- coords[i], coords[++i]);
- ctx.closePath();
- ctx.stroke();
- for (var i = 0; i < 8; i++) {
- ctx.beginPath();
- ctx.rect(coords[i] - 2, coords[++i] - 2, 4, 4);
- ctx.fill();
- }
- }
- }
- }
- ctx.restore();
- }
- }
-});
-
-var Symbol = Base.extend({
- _class: 'Symbol',
-
- initialize: function Symbol(item, dontCenter) {
- this._id = Symbol._id = (Symbol._id || 0) + 1;
- this.project = paper.project;
- this.project.symbols.push(this);
- if (item)
- this.setDefinition(item, dontCenter);
- this._instances = {};
- },
-
- _serialize: function(options, dictionary) {
- return dictionary.add(this, function() {
- return Base.serialize([this._class, this._definition],
- options, false, dictionary);
- });
- },
-
- _changed: function(flags) {
- Base.each(this._instances, function(item) {
- item._changed(flags);
- });
- },
-
- getDefinition: function() {
- return this._definition;
- },
-
- setDefinition: function(item ) {
- if (item._parentSymbol)
- item = item.clone();
- if (this._definition)
- delete this._definition._parentSymbol;
- this._definition = item;
- item.remove();
- item.setSelected(false);
- if (!arguments[1])
- item.setPosition(new Point());
- item._parentSymbol = this;
- this._changed(5);
- },
-
- place: function(position) {
- return new PlacedSymbol(this, position);
- },
-
- clone: function() {
- return new Symbol(this._definition.clone(false));
- }
-});
-
-var Item = Base.extend(Callback, {
- statics: {
- extend: function extend(src) {
- if (src._serializeFields)
- src._serializeFields = new Base(
- this.prototype._serializeFields, src._serializeFields);
- var res = extend.base.apply(this, arguments),
- proto = res.prototype,
- name = proto._class;
- if (name)
- proto._type = Base.hyphenate(name);
- return res;
- }
- },
-
- _class: 'Item',
- _transformContent: true,
- _boundsSelected: false,
- _serializeFields: {
- name: null,
- matrix: new Matrix(),
- locked: false,
- visible: true,
- blendMode: 'normal',
- opacity: 1,
- guide: false,
- selected: false,
- clipMask: false,
- data: {}
- },
-
- initialize: function Item() {
- },
-
- _initialize: function(props, point) {
- this._id = Item._id = (Item._id || 0) + 1;
- if (!this._project) {
- var project = paper.project;
- if (props && props.insert === false) {
- this._setProject(project);
- } else {
- (project.activeLayer || new Layer()).addChild(this);
- }
- }
- this._style = new Style(this._project._currentStyle, this);
- var matrix = this._matrix = new Matrix();
- if (point)
- matrix.translate(point);
- matrix._owner = this;
- return props ? this._set(props, { insert: true }) : true;
- },
-
- _events: new function() {
-
- var mouseFlags = {
- mousedown: {
- mousedown: 1,
- mousedrag: 1,
- click: 1,
- doubleclick: 1
- },
- mouseup: {
- mouseup: 1,
- mousedrag: 1,
- click: 1,
- doubleclick: 1
- },
- mousemove: {
- mousedrag: 1,
- mousemove: 1,
- mouseenter: 1,
- mouseleave: 1
- }
- };
-
- var mouseEvent = {
- install: function(type) {
- var counters = this._project.view._eventCounters;
- if (counters) {
- for (var key in mouseFlags) {
- counters[key] = (counters[key] || 0)
- + (mouseFlags[key][type] || 0);
- }
- }
- },
- uninstall: function(type) {
- var counters = this._project.view._eventCounters;
- if (counters) {
- for (var key in mouseFlags)
- counters[key] -= mouseFlags[key][type] || 0;
- }
- }
- };
-
- return Base.each(['onMouseDown', 'onMouseUp', 'onMouseDrag', 'onClick',
- 'onDoubleClick', 'onMouseMove', 'onMouseEnter', 'onMouseLeave'],
- function(name) {
- this[name] = mouseEvent;
- }, {
- onFrame: {
- install: function() {
- this._animateItem(true);
- },
- uninstall: function() {
- this._animateItem(false);
- }
- },
-
- onLoad: {}
- }
- );
- },
-
- _animateItem: function(animate) {
- this._project.view._animateItem(this, animate);
- },
-
- _serialize: function(options, dictionary) {
- var props = {},
- that = this;
-
- function serialize(fields) {
- for (var key in fields) {
- var value = that[key];
- if (!Base.equals(value, key === 'leading'
- ? fields.fontSize * 1.2 : fields[key])) {
- props[key] = Base.serialize(value, options,
- key !== 'data', dictionary);
- }
- }
- }
-
- serialize(this._serializeFields);
- if (!(this instanceof Group))
- serialize(this._style._defaults);
- return [ this._class, props ];
- },
-
- _changed: function(flags) {
- var parent = this._parent,
- project = this._project,
- symbol = this._parentSymbol;
- this._drawCount = null;
- if (flags & 4) {
- delete this._bounds;
- delete this._position;
- }
- if (parent && (flags
- & (4 | 8))) {
- parent._clearBoundsCache();
- }
- if (flags & 2) {
- this._clearBoundsCache();
- }
- if (project) {
- if (flags & 1) {
- project._needsRedraw = true;
- }
- if (project._changes) {
- var entry = project._changesById[this._id];
- if (entry) {
- entry.flags |= flags;
- } else {
- entry = { item: this, flags: flags };
- project._changesById[this._id] = entry;
- project._changes.push(entry);
- }
- }
- }
- if (symbol)
- symbol._changed(flags);
- },
-
- set: function(props) {
- if (props)
- this._set(props);
- return this;
- },
-
- getId: function() {
- return this._id;
- },
-
- getType: function() {
- return this._type;
- },
-
- getName: function() {
- return this._name;
- },
-
- setName: function(name, unique) {
-
- if (this._name)
- this._removeNamed();
- if (name === (+name) + '')
- throw new Error(
- 'Names consisting only of numbers are not supported.');
- if (name && this._parent) {
- var children = this._parent._children,
- namedChildren = this._parent._namedChildren,
- orig = name,
- i = 1;
- while (unique && children[name])
- name = orig + ' ' + (i++);
- (namedChildren[name] = namedChildren[name] || []).push(this);
- children[name] = this;
- }
- this._name = name || undefined;
- this._changed(32);
- },
-
- getStyle: function() {
- return this._style;
- },
-
- setStyle: function(style) {
- this.getStyle().set(style);
- },
-
- hasFill: function() {
- return this.getStyle().hasFill();
- },
-
- hasStroke: function() {
- return this.getStyle().hasStroke();
- },
-
- hasShadow: function() {
- return this.getStyle().hasShadow();
- }
-}, Base.each(['locked', 'visible', 'blendMode', 'opacity', 'guide'],
- function(name) {
- var part = Base.capitalize(name),
- name = '_' + name;
- this['get' + part] = function() {
- return this[name];
- };
- this['set' + part] = function(value) {
- if (value != this[name]) {
- this[name] = value;
- this._changed(name === '_locked'
- ? 32 : 33);
- }
- };
-}, {}), {
-
- _locked: false,
-
- _visible: true,
-
- _blendMode: 'normal',
-
- _opacity: 1,
-
- _guide: false,
-
- isSelected: function() {
- if (this._children) {
- for (var i = 0, l = this._children.length; i < l; i++)
- if (this._children[i].isSelected())
- return true;
- }
- return this._selected;
- },
-
- setSelected: function(selected ) {
- if (this._children && !arguments[1]) {
- for (var i = 0, l = this._children.length; i < l; i++)
- this._children[i].setSelected(selected);
- }
- if ((selected = !!selected) != this._selected) {
- this._selected = selected;
- this._project._updateSelection(this);
- this._changed(33);
- }
- },
-
- _selected: false,
-
- isFullySelected: function() {
- if (this._children && this._selected) {
- for (var i = 0, l = this._children.length; i < l; i++)
- if (!this._children[i].isFullySelected())
- return false;
- return true;
- }
- return this._selected;
- },
-
- setFullySelected: function(selected) {
- if (this._children) {
- for (var i = 0, l = this._children.length; i < l; i++)
- this._children[i].setFullySelected(selected);
- }
- this.setSelected(selected, true);
- },
-
- isClipMask: function() {
- return this._clipMask;
- },
-
- setClipMask: function(clipMask) {
- if (this._clipMask != (clipMask = !!clipMask)) {
- this._clipMask = clipMask;
- if (clipMask) {
- this.setFillColor(null);
- this.setStrokeColor(null);
- }
- this._changed(33);
- if (this._parent)
- this._parent._changed(256);
- }
- },
-
- _clipMask: false,
-
- getData: function() {
- if (!this._data)
- this._data = {};
- return this._data;
- },
-
- setData: function(data) {
- this._data = data;
- },
-
- getPosition: function() {
- var pos = this._position
- || (this._position = this.getBounds().getCenter(true));
- return new (arguments[0] ? Point : LinkedPoint)
- (pos.x, pos.y, this, 'setPosition');
- },
-
- setPosition: function() {
- this.translate(Point.read(arguments).subtract(this.getPosition(true)));
- }
-}, Base.each(['getBounds', 'getStrokeBounds', 'getHandleBounds', 'getRoughBounds'],
- function(name) {
- this[name] = function() {
- var getter = this._boundsGetter,
- bounds = this._getCachedBounds(typeof getter == 'string'
- ? getter : getter && getter[name] || name, arguments[0]);
- return name === 'getBounds'
- ? new LinkedRectangle(bounds.x, bounds.y, bounds.width,
- bounds.height, this, 'setBounds')
- : bounds;
- };
- },
-{
- _getCachedBounds: function(getter, matrix, cacheItem) {
- var cache = (!matrix || matrix.equals(this._matrix)) && getter;
- if (cacheItem && this._parent) {
- var id = cacheItem._id,
- ref = this._parent._boundsCache
- = this._parent._boundsCache || {
- ids: {},
- list: []
- };
- if (!ref.ids[id]) {
- ref.list.push(cacheItem);
- ref.ids[id] = cacheItem;
- }
- }
- if (cache && this._bounds && this._bounds[cache])
- return this._bounds[cache].clone();
- var identity = this._matrix.isIdentity();
- matrix = !matrix || matrix.isIdentity()
- ? identity ? null : this._matrix
- : identity ? matrix : matrix.clone().concatenate(this._matrix);
- var bounds = this._getBounds(getter, matrix, cache ? this : cacheItem);
- if (cache) {
- if (!this._bounds)
- this._bounds = {};
- this._bounds[cache] = bounds.clone();
- }
- return bounds;
- },
-
- _clearBoundsCache: function() {
- if (this._boundsCache) {
- for (var i = 0, list = this._boundsCache.list, l = list.length;
- i < l; i++) {
- var item = list[i];
- delete item._bounds;
- if (item != this && item._boundsCache)
- item._clearBoundsCache();
- }
- delete this._boundsCache;
- }
- },
-
- _getBounds: function(getter, matrix, cacheItem) {
- var children = this._children;
- if (!children || children.length == 0)
- return new Rectangle();
- var x1 = Infinity,
- x2 = -x1,
- y1 = x1,
- y2 = x2;
- for (var i = 0, l = children.length; i < l; i++) {
- var child = children[i];
- if (child._visible && !child.isEmpty()) {
- var rect = child._getCachedBounds(getter, matrix, cacheItem);
- x1 = Math.min(rect.x, x1);
- y1 = Math.min(rect.y, y1);
- x2 = Math.max(rect.x + rect.width, x2);
- y2 = Math.max(rect.y + rect.height, y2);
- }
- }
- return isFinite(x1)
- ? new Rectangle(x1, y1, x2 - x1, y2 - y1)
- : new Rectangle();
- },
-
- setBounds: function(rect) {
- rect = Rectangle.read(arguments);
- var bounds = this.getBounds(),
- matrix = new Matrix(),
- center = rect.getCenter();
- matrix.translate(center);
- if (rect.width != bounds.width || rect.height != bounds.height) {
- matrix.scale(
- bounds.width != 0 ? rect.width / bounds.width : 1,
- bounds.height != 0 ? rect.height / bounds.height : 1);
- }
- center = bounds.getCenter();
- matrix.translate(-center.x, -center.y);
- this.transform(matrix);
- }
-
-}), {
- getMatrix: function() {
- return this._matrix;
- },
-
- setMatrix: function(matrix) {
- this._matrix.initialize(matrix);
- if (this._transformContent)
- this.applyMatrix(true);
- this._changed(5);
- },
-
- getGlobalMatrix: function() {
- return this._drawCount === this._project._drawCount
- && this._globalMatrix || null;
- },
-
- getTransformContent: function() {
- return this._transformContent;
- },
-
- setTransformContent: function(transform) {
- this._transformContent = transform;
- if (transform)
- this.applyMatrix();
- },
-
- getProject: function() {
- return this._project;
- },
-
- _setProject: function(project) {
- if (this._project != project) {
- var hasOnFrame = this.responds('frame');
- if (hasOnFrame)
- this._animateItem(false);
- this._project = project;
- if (hasOnFrame)
- this._animateItem(true);
- if (this._children) {
- for (var i = 0, l = this._children.length; i < l; i++) {
- this._children[i]._setProject(project);
- }
- }
- }
- },
-
- getLayer: function() {
- var parent = this;
- while (parent = parent._parent) {
- if (parent instanceof Layer)
- return parent;
- }
- return null;
- },
-
- getParent: function() {
- return this._parent;
- },
-
- setParent: function(item) {
- return item.addChild(this);
- },
-
- getChildren: function() {
- return this._children;
- },
-
- setChildren: function(items) {
- this.removeChildren();
- this.addChildren(items);
- },
-
- getFirstChild: function() {
- return this._children && this._children[0] || null;
- },
-
- getLastChild: function() {
- return this._children && this._children[this._children.length - 1]
- || null;
- },
-
- getNextSibling: function() {
- return this._parent && this._parent._children[this._index + 1] || null;
- },
-
- getPreviousSibling: function() {
- return this._parent && this._parent._children[this._index - 1] || null;
- },
-
- getIndex: function() {
- return this._index;
- },
-
- isInserted: function() {
- return this._parent ? this._parent.isInserted() : false;
- },
-
- equals: function(item) {
- return item === this || item && this._class === item._class
- && this._style.equals(item._style)
- && this._matrix.equals(item._matrix)
- && this._locked === item._locked
- && this._visible === item._visible
- && this._blendMode === item._blendMode
- && this._opacity === item._opacity
- && this._clipMask === item._clipMask
- && this._guide === item._guide
- && this._equals(item)
- || false;
- },
-
- _equals: function(item) {
- return Base.equals(this._children, item._children);
- },
-
- clone: function(insert) {
- return this._clone(new this.constructor({ insert: false }), insert);
- },
-
- _clone: function(copy, insert) {
- copy.setStyle(this._style);
- if (this._children) {
- for (var i = 0, l = this._children.length; i < l; i++)
- copy.addChild(this._children[i].clone(false), true);
- }
- if (insert || insert === undefined)
- copy.insertAbove(this);
- var keys = ['_locked', '_visible', '_blendMode', '_opacity',
- '_clipMask', '_guide'];
- for (var i = 0, l = keys.length; i < l; i++) {
- var key = keys[i];
- if (this.hasOwnProperty(key))
- copy[key] = this[key];
- }
- copy._matrix.initialize(this._matrix);
- copy._data = this._data ? Base.clone(this._data) : null;
- copy.setSelected(this._selected);
- if (this._name)
- copy.setName(this._name, true);
- return copy;
- },
-
- copyTo: function(itemOrProject) {
- return itemOrProject.addChild(this.clone(false));
- },
-
- rasterize: function(resolution) {
- var bounds = this.getStrokeBounds(),
- scale = (resolution || 72) / 72,
- topLeft = bounds.getTopLeft().floor(),
- bottomRight = bounds.getBottomRight().ceil()
- size = new Size(bottomRight.subtract(topLeft)),
- canvas = CanvasProvider.getCanvas(size),
- ctx = canvas.getContext('2d'),
- matrix = new Matrix().scale(scale).translate(topLeft.negate());
- ctx.save();
- matrix.applyToContext(ctx);
- this.draw(ctx, new Base({ transforms: [matrix] }));
- ctx.restore();
- var raster = new Raster({
- canvas: canvas,
- insert: false
- });
- raster.setPosition(topLeft.add(size.divide(2)));
- raster.insertAbove(this);
- return raster;
- },
-
- contains: function() {
- return !!this._contains(
- this._matrix._inverseTransform(Point.read(arguments)));
- },
-
- _contains: function(point) {
- if (this._children) {
- for (var i = this._children.length - 1; i >= 0; i--) {
- if (this._children[i].contains(point))
- return true;
- }
- return false;
- }
- return point.isInside(this._getBounds('getBounds'));
- },
-
- hitTest: function(point, options) {
- point = Point.read(arguments);
- options = HitResult.getOptions(Base.read(arguments));
-
- if (this._locked || !this._visible || this._guide && !options.guides)
- return null;
-
- if (!this._children && !this.getRoughBounds()
- .expand(2 * options.tolerance)._containsPoint(point))
- return null;
- point = this._matrix._inverseTransform(point);
-
- var that = this,
- res;
- function checkBounds(type, part) {
- var pt = bounds['get' + part]();
- if (point.getDistance(pt) < options.tolerance)
- return new HitResult(type, that,
- { name: Base.hyphenate(part), point: pt });
- }
-
- if ((options.center || options.bounds) &&
- !(this instanceof Layer && !this._parent)) {
- var bounds = this._getBounds('getBounds');
- if (options.center)
- res = checkBounds('center', 'Center');
- if (!res && options.bounds) {
- var points = [
- 'TopLeft', 'TopRight', 'BottomLeft', 'BottomRight',
- 'LeftCenter', 'TopCenter', 'RightCenter', 'BottomCenter'
- ];
- for (var i = 0; i < 8 && !res; i++)
- res = checkBounds('bounds', points[i]);
- }
- }
-
- if ((res || (res = this._children || !(options.guides && !this._guide
- || options.selected && !this._selected)
- ? this._hitTest(point, options) : null))
- && res.point) {
- res.point = that._matrix.transform(res.point);
- }
- return res;
- },
-
- _hitTest: function(point, options) {
- var children = this._children;
- if (children) {
- for (var i = children.length - 1, res; i >= 0; i--)
- if (res = children[i].hitTest(point, options))
- return res;
- } else if (options.fill && this.hasFill() && this._contains(point)) {
- return new HitResult('fill', this);
- }
- },
-
- matches: function(match) {
- function matchObject(obj1, obj2) {
- for (var i in obj1) {
- if (obj1.hasOwnProperty(i)) {
- var val1 = obj1[i],
- val2 = obj2[i];
- if (Base.isPlainObject(val1) && Base.isPlainObject(val2)) {
- if (!matchObject(val1, val2))
- return false;
- } else if (!Base.equals(val1, val2)) {
- return false;
- }
- }
- }
- return true;
- }
- for (var key in match) {
- if (match.hasOwnProperty(key)) {
- var value = this[key],
- compare = match[key];
- if (compare instanceof RegExp) {
- if (!compare.test(value))
- return false;
- } else if (typeof compare === 'function') {
- if (!compare(value))
- return false;
- } else if (Base.isPlainObject(compare)) {
- if (!matchObject(compare, value))
- return false;
- } else if (!Base.equals(value, compare)) {
- return false;
- }
- }
- }
- return true;
- }
-}, new function() {
- function getItems(item, match, list) {
- var children = item._children,
- items = list && [];
- for (var i = 0, l = children && children.length; i < l; i++) {
- var child = children[i];
- if (child.matches(match)) {
- if (list) {
- items.push(child);
- } else {
- return child;
- }
- }
- var res = getItems(child, match, list);
- if (list) {
- items.push.apply(items, res);
- } else if (res) {
- return res;
- }
- }
- return list ? items : null;
- }
-
- return {
- getItems: function(match) {
- return getItems(this, match, true);
- },
-
- getItem: function(match) {
- return getItems(this, match, false);
- }
- };
-}, {
-
- importJSON: function(json) {
- var res = Base.importJSON(json, this);
- return res !== this
- ? this.addChild(res)
- : res;
- },
-
- addChild: function(item, _preserve) {
- return this.insertChild(undefined, item, _preserve);
- },
-
- insertChild: function(index, item, _preserve) {
- var res = this.insertChildren(index, [item], _preserve);
- return res && res[0];
- },
-
- addChildren: function(items, _preserve) {
- return this.insertChildren(this._children.length, items, _preserve);
- },
-
- insertChildren: function(index, items, _preserve, _type) {
- var children = this._children;
- if (children && items && items.length > 0) {
- items = Array.prototype.slice.apply(items);
- for (var i = items.length - 1; i >= 0; i--) {
- var item = items[i];
- if (_type && item._type !== _type)
- items.splice(i, 1);
- else
- item._remove(true);
- }
- Base.splice(children, items, index, 0);
- for (var i = 0, l = items.length; i < l; i++) {
- var item = items[i];
- item._parent = this;
- item._setProject(this._project);
- if (item._name)
- item.setName(item._name);
- }
- this._changed(7);
- } else {
- items = null;
- }
- return items;
- },
-
- _insert: function(above, item, _preserve) {
- if (!item._parent)
- return null;
- var index = item._index + (above ? 1 : 0);
- if (item._parent === this._parent && index > this._index)
- index--;
- return item._parent.insertChild(index, this, _preserve);
- },
-
- insertAbove: function(item, _preserve) {
- return this._insert(true, item, _preserve);
- },
-
- insertBelow: function(item, _preserve) {
- return this._insert(false, item, _preserve);
- },
-
- sendToBack: function() {
- return this._parent.insertChild(0, this);
- },
-
- bringToFront: function() {
- return this._parent.addChild(this);
- },
-
- appendTop: '#addChild',
-
- appendBottom: function(item) {
- return this.insertChild(0, item);
- },
-
- moveAbove: '#insertAbove',
-
- moveBelow: '#insertBelow',
-
- reduce: function() {
- if (this._children && this._children.length === 1) {
- var child = this._children[0];
- child.insertAbove(this);
- child.setStyle(this._style);
- this.remove();
- return child;
- }
- return this;
- },
-
- _removeNamed: function() {
- var children = this._parent._children,
- namedChildren = this._parent._namedChildren,
- name = this._name,
- namedArray = namedChildren[name],
- index = namedArray ? namedArray.indexOf(this) : -1;
- if (index == -1)
- return;
- if (children[name] == this)
- delete children[name];
- namedArray.splice(index, 1);
- if (namedArray.length) {
- children[name] = namedArray[namedArray.length - 1];
- } else {
- delete namedChildren[name];
- }
- },
-
- _remove: function(notify) {
- if (this._parent) {
- if (this._name)
- this._removeNamed();
- if (this._index != null)
- Base.splice(this._parent._children, null, this._index, 1);
- if (this.responds('frame'))
- this._animateItem(false);
- if (notify)
- this._parent._changed(7);
- this._parent = null;
- return true;
- }
- return false;
- },
-
- remove: function() {
- return this._remove(true);
- },
-
- removeChildren: function(from, to) {
- if (!this._children)
- return null;
- from = from || 0;
- to = Base.pick(to, this._children.length);
- var removed = Base.splice(this._children, null, from, to - from);
- for (var i = removed.length - 1; i >= 0; i--)
- removed[i]._remove(false);
- if (removed.length > 0)
- this._changed(7);
- return removed;
- },
-
- clear: '#removeChildren',
-
- reverseChildren: function() {
- if (this._children) {
- this._children.reverse();
- for (var i = 0, l = this._children.length; i < l; i++)
- this._children[i]._index = i;
- this._changed(7);
- }
- },
-
- isEmpty: function() {
- return !this._children || this._children.length == 0;
- },
-
- isEditable: function() {
- var item = this;
- while (item) {
- if (!item._visible || item._locked)
- return false;
- item = item._parent;
- }
- return true;
- },
-
- _getOrder: function(item) {
- function getList(item) {
- var list = [];
- do {
- list.unshift(item);
- } while (item = item._parent);
- return list;
- }
- var list1 = getList(this),
- list2 = getList(item);
- for (var i = 0, l = Math.min(list1.length, list2.length); i < l; i++) {
- if (list1[i] != list2[i]) {
- return list1[i]._index < list2[i]._index ? 1 : -1;
- }
- }
- return 0;
- },
-
- hasChildren: function() {
- return this._children && this._children.length > 0;
- },
-
- isAbove: function(item) {
- return this._getOrder(item) === -1;
- },
-
- isBelow: function(item) {
- return this._getOrder(item) === 1;
- },
-
- isParent: function(item) {
- return this._parent === item;
- },
-
- isChild: function(item) {
- return item && item._parent === this;
- },
-
- isDescendant: function(item) {
- var parent = this;
- while (parent = parent._parent) {
- if (parent == item)
- return true;
- }
- return false;
- },
-
- isAncestor: function(item) {
- return item ? item.isDescendant(this) : false;
- },
-
- isGroupedWith: function(item) {
- var parent = this._parent;
- while (parent) {
- if (parent._parent
- && /^(group|layer|compound-path)$/.test(parent._type)
- && item.isDescendant(parent))
- return true;
- parent = parent._parent;
- }
- return false;
- },
-
- scale: function(hor, ver , center) {
- if (arguments.length < 2 || typeof ver === 'object') {
- center = ver;
- ver = hor;
- }
- return this.transform(new Matrix().scale(hor, ver,
- center || this.getPosition(true)));
- },
-
- translate: function() {
- var mx = new Matrix();
- return this.transform(mx.translate.apply(mx, arguments));
- },
-
- rotate: function(angle, center) {
- return this.transform(new Matrix().rotate(angle,
- center || this.getPosition(true)));
- },
-
- shear: function(hor, ver, center) {
- if (arguments.length < 2 || typeof ver === 'object') {
- center = ver;
- ver = hor;
- }
- return this.transform(new Matrix().shear(hor, ver,
- center || this.getPosition(true)));
- },
-
- transform: function(matrix ) {
- var bounds = this._bounds,
- position = this._position;
- this._matrix.preConcatenate(matrix);
- if (this._transformContent || arguments[1])
- this.applyMatrix(true);
- this._changed(5);
- if (bounds && matrix.getRotation() % 90 === 0) {
- for (var key in bounds) {
- var rect = bounds[key];
- matrix._transformBounds(rect, rect);
- }
- var getter = this._boundsGetter,
- rect = bounds[getter && getter.getBounds || getter || 'getBounds'];
- if (rect)
- this._position = rect.getCenter(true);
- this._bounds = bounds;
- } else if (position) {
- this._position = matrix._transformPoint(position, position);
- }
- return this;
- },
-
- _applyMatrix: function(matrix, applyMatrix) {
- var children = this._children;
- if (children && children.length > 0) {
- for (var i = 0, l = children.length; i < l; i++)
- children[i].transform(matrix, applyMatrix);
- return true;
- }
- },
-
- applyMatrix: function(_dontNotify) {
- var matrix = this._matrix;
- if (this._applyMatrix(matrix, true)) {
- var style = this._style,
- fillColor = style.getFillColor(true),
- strokeColor = style.getStrokeColor(true);
- if (fillColor)
- fillColor.transform(matrix);
- if (strokeColor)
- strokeColor.transform(matrix);
- matrix.reset();
- }
- if (!_dontNotify)
- this._changed(5);
- },
-
- globalToLocal: function() {
- var matrix = this.getGlobalMatrix();
- return matrix && matrix._transformPoint(Point.read(arguments));
- },
-
- localToGlobal: function() {
- var matrix = this.getGlobalMatrix();
- return matrix && matrix._inverseTransform(Point.read(arguments));
- },
-
- fitBounds: function(rectangle, fill) {
- rectangle = Rectangle.read(arguments);
- var bounds = this.getBounds(),
- itemRatio = bounds.height / bounds.width,
- rectRatio = rectangle.height / rectangle.width,
- scale = (fill ? itemRatio > rectRatio : itemRatio < rectRatio)
- ? rectangle.width / bounds.width
- : rectangle.height / bounds.height,
- newBounds = new Rectangle(new Point(),
- new Size(bounds.width * scale, bounds.height * scale));
- newBounds.setCenter(rectangle.getCenter());
- this.setBounds(newBounds);
- },
-
- _setStyles: function(ctx) {
- var style = this._style,
- fillColor = style.getFillColor(),
- strokeColor = style.getStrokeColor(),
- shadowColor = style.getShadowColor();
- if (fillColor)
- ctx.fillStyle = fillColor.toCanvasStyle(ctx);
- if (strokeColor) {
- var strokeWidth = style.getStrokeWidth();
- if (strokeWidth > 0) {
- ctx.strokeStyle = strokeColor.toCanvasStyle(ctx);
- ctx.lineWidth = strokeWidth;
- var strokeJoin = style.getStrokeJoin(),
- strokeCap = style.getStrokeCap(),
- miterLimit = style.getMiterLimit();
- if (strokeJoin)
- ctx.lineJoin = strokeJoin;
- if (strokeCap)
- ctx.lineCap = strokeCap;
- if (miterLimit)
- ctx.miterLimit = miterLimit;
- if (paper.support.nativeDash) {
- var dashArray = style.getDashArray(),
- dashOffset = style.getDashOffset();
- if (dashArray && dashArray.length) {
- if ('setLineDash' in ctx) {
- ctx.setLineDash(dashArray);
- ctx.lineDashOffset = dashOffset;
- } else {
- ctx.mozDash = dashArray;
- ctx.mozDashOffset = dashOffset;
- }
- }
- }
- }
- }
- if (shadowColor) {
- var shadowBlur = style.getShadowBlur();
- if (shadowBlur > 0) {
- ctx.shadowColor = shadowColor.toCanvasStyle(ctx);
- ctx.shadowBlur = shadowBlur;
- var offset = this.getShadowOffset();
- ctx.shadowOffsetX = offset.x;
- ctx.shadowOffsetY = offset.y;
- }
- }
- },
-
- draw: function(ctx, param) {
- if (!this._visible || this._opacity === 0)
- return;
- this._drawCount = this._project._drawCount;
- var trackTransforms = param.trackTransforms,
- transforms = param.transforms,
- parentMatrix = transforms[transforms.length - 1],
- globalMatrix = parentMatrix.clone().concatenate(this._matrix);
- if (trackTransforms)
- transforms.push(this._globalMatrix = globalMatrix);
- var blendMode = this._blendMode,
- opacity = this._opacity,
- normalBlend = blendMode === 'normal',
- nativeBlend = BlendMode.nativeModes[blendMode],
- direct = normalBlend && opacity === 1
- || (nativeBlend || normalBlend && opacity < 1)
- && this._canComposite(),
- mainCtx, itemOffset, prevOffset;
- if (!direct) {
- var bounds = this.getStrokeBounds(parentMatrix);
- if (!bounds.width || !bounds.height)
- return;
- prevOffset = param.offset;
- itemOffset = param.offset = bounds.getTopLeft().floor();
- mainCtx = ctx;
- ctx = CanvasProvider.getContext(
- bounds.getSize().ceil().add(new Size(1, 1)), param.ratio);
- }
- ctx.save();
- if (direct) {
- ctx.globalAlpha = opacity;
- if (nativeBlend)
- ctx.globalCompositeOperation = blendMode;
- } else {
- ctx.translate(-itemOffset.x, -itemOffset.y);
- }
- (direct ? this._matrix : globalMatrix).applyToContext(ctx);
- if (!direct && param.clipItem)
- param.clipItem.draw(ctx, param.extend({ clip: true }));
- this._draw(ctx, param);
- ctx.restore();
- if (trackTransforms)
- transforms.pop();
- if (param.clip)
- ctx.clip();
- if (!direct) {
- BlendMode.process(blendMode, ctx, mainCtx, opacity,
- itemOffset.subtract(prevOffset).multiply(param.ratio));
- CanvasProvider.release(ctx);
- param.offset = prevOffset;
- }
- },
-
- _canComposite: function() {
- return false;
- }
-}, Base.each(['down', 'drag', 'up', 'move'], function(name) {
- this['removeOn' + Base.capitalize(name)] = function() {
- var hash = {};
- hash[name] = true;
- return this.removeOn(hash);
- };
-}, {
-
- removeOn: function(obj) {
- for (var name in obj) {
- if (obj[name]) {
- var key = 'mouse' + name,
- project = this._project,
- sets = project._removeSets = project._removeSets || {};
- sets[key] = sets[key] || {};
- sets[key][this._id] = this;
- }
- }
- return this;
- }
-}));
-
-var Group = Item.extend({
- _class: 'Group',
- _serializeFields: {
- children: []
- },
-
- initialize: function Group(arg) {
- this._children = [];
- this._namedChildren = {};
- if (!this._initialize(arg))
- this.addChildren(Array.isArray(arg) ? arg : arguments);
- },
-
- _changed: function _changed(flags) {
- _changed.base.call(this, flags);
- if (flags & 2 && this._transformContent
- && !this._matrix.isIdentity()) {
- this.applyMatrix();
- }
- if (flags & (2 | 256)) {
- delete this._clipItem;
- }
- },
-
- _getClipItem: function() {
- if (this._clipItem !== undefined)
- return this._clipItem;
- for (var i = 0, l = this._children.length; i < l; i++) {
- var child = this._children[i];
- if (child._clipMask)
- return this._clipItem = child;
- }
- return this._clipItem = null;
- },
-
- isClipped: function() {
- return !!this._getClipItem();
- },
-
- setClipped: function(clipped) {
- var child = this.getFirstChild();
- if (child)
- child.setClipMask(clipped);
- },
-
- _draw: function(ctx, param) {
- var clipItem = param.clipItem = this._getClipItem();
- if (clipItem)
- clipItem.draw(ctx, param.extend({ clip: true }));
- for (var i = 0, l = this._children.length; i < l; i++) {
- var item = this._children[i];
- if (item !== clipItem)
- item.draw(ctx, param);
- }
- param.clipItem = null;
- }
-});
-
-var Layer = Group.extend({
- _class: 'Layer',
-
- initialize: function Layer(arg) {
- var props = Base.isPlainObject(arg)
- ? new Base(arg)
- : { children: Array.isArray(arg) ? arg : arguments },
- insert = props.insert;
- props.insert = false;
- Group.call(this, props);
- if (insert || insert === undefined) {
- this._project.addChild(this);
- this.activate();
- }
- },
-
- _remove: function _remove(notify) {
- if (this._parent)
- return _remove.base.call(this, notify);
- if (this._index != null) {
- if (this._project.activeLayer === this)
- this._project.activeLayer = this.getNextSibling()
- || this.getPreviousSibling();
- Base.splice(this._project.layers, null, this._index, 1);
- this._project._needsRedraw = true;
- return true;
- }
- return false;
- },
-
- getNextSibling: function getNextSibling() {
- return this._parent ? getNextSibling.base.call(this)
- : this._project.layers[this._index + 1] || null;
- },
-
- getPreviousSibling: function getPreviousSibling() {
- return this._parent ? getPreviousSibling.base.call(this)
- : this._project.layers[this._index - 1] || null;
- },
-
- isInserted: function isInserted() {
- return this._parent ? isInserted.base.call(this) : this._index != null;
- },
-
- activate: function() {
- this._project.activeLayer = this;
- },
-
- _insert: function _insert(above, item, _preserve) {
- if (item instanceof Layer && !item._parent) {
- this._remove(true);
- Base.splice(item._project.layers, [this],
- item._index + (above ? 1 : 0), 0);
- this._setProject(item._project);
- return this;
- }
- return _insert.base.call(this, above, item, _preserve);
- }
-});
-
-var Shape = Item.extend({
- _class: 'Shape',
- _transformContent: false,
- _boundsSelected: true,
-
- initialize: function Shape(shape, center, size, radius, props) {
- this._shape = shape;
- this._size = size;
- this._radius = radius;
- this._initialize(props, center);
- },
-
- _equals: function(item) {
- return this._shape === item._shape
- && this._size.equals(item._size)
- && Base.equals(this._radius, item._radius);
- },
-
- clone: function(insert) {
- return this._clone(new Shape(this._shape, this.getPosition(true),
- this._size.clone(),
- this._radius.clone ? this._radius.clone() : this._radius,
- { insert: false }), insert);
- },
-
- getShape: function() {
- return this._shape;
- },
-
- getSize: function() {
- var size = this._size;
- return new LinkedSize(size.width, size.height, this, 'setSize');
- },
-
- setSize: function() {
- var shape = this._shape,
- size = Size.read(arguments);
- if (!this._size.equals(size)) {
- var width = size.width,
- height = size.height;
- if (shape === 'rectangle') {
- var radius = Size.min(this._radius, size.divide(2));
- this._radius.set(radius.width, radius.height);
- } else if (shape === 'circle') {
- width = height = (width + height) / 2;
- this._radius = width / 2;
- } else if (shape === 'ellipse') {
- this._radius.set(width / 2, height / 2);
- }
- this._size.set(width, height);
- this._changed(5);
- }
- },
-
- getRadius: function() {
- var rad = this._radius;
- return this._shape === 'circle'
- ? rad
- : new LinkedSize(rad.width, rad.height, this, 'setRadius');
- },
-
- setRadius: function(radius) {
- var shape = this._shape;
- if (shape === 'circle') {
- if (radius === this._radius)
- return;
- var size = radius * 2;
- this._radius = radius;
- this._size.set(size, size);
- } else {
- radius = Size.read(arguments);
- if (this._radius.equals(radius))
- return;
- this._radius.set(radius.width, radius.height);
- if (shape === 'rectangle') {
- var size = Size.max(this._size, radius.multiply(2));
- this._size.set(size.width, size.height);
- } else if (shape === 'ellipse') {
- this._size.set(radius.width * 2, radius.height * 2);
- }
- }
- this._changed(5);
- },
-
- isEmpty: function() {
- return false;
- },
-
- toPath: function(insert) {
- var path = new Path[Base.capitalize(this._shape)]({
- center: new Point(),
- size: this._size,
- radius: this._radius,
- insert: false
- });
- path.setStyle(this._style);
- path.transform(this._matrix);
- if (insert || insert === undefined)
- path.insertAbove(this);
- return path;
- },
-
- _draw: function(ctx, param) {
- var style = this._style,
- hasFill = style.hasFill(),
- hasStroke = style.hasStroke(),
- clip = param.clip;
- if (hasFill || hasStroke || clip) {
- var radius = this._radius,
- shape = this._shape;
- ctx.beginPath();
- if (shape === 'circle') {
- ctx.arc(0, 0, radius, 0, Math.PI * 2, true);
- } else {
- var rx = radius.width,
- ry = radius.height,
- kappa = Numerical.KAPPA;
- if (shape === 'ellipse') {
- var cx = rx * kappa,
- cy = ry * kappa;
- ctx.moveTo(-rx, 0);
- ctx.bezierCurveTo(-rx, -cy, -cx, -ry, 0, -ry);
- ctx.bezierCurveTo(cx, -ry, rx, -cy, rx, 0);
- ctx.bezierCurveTo(rx, cy, cx, ry, 0, ry);
- ctx.bezierCurveTo(-cx, ry, -rx, cy, -rx, 0);
- } else {
- var size = this._size,
- width = size.width,
- height = size.height;
- if (rx === 0 && ry === 0) {
- ctx.rect(-width / 2, -height / 2, width, height);
- } else {
- kappa = 1 - kappa;
- var x = width / 2,
- y = height / 2,
- cx = rx * kappa,
- cy = ry * kappa;
- ctx.moveTo(-x, -y + ry);
- ctx.bezierCurveTo(-x, -y + cy, -x + cx, -y, -x + rx, -y);
- ctx.lineTo(x - rx, -y);
- ctx.bezierCurveTo(x - cx, -y, x, -y + cy, x, -y + ry);
- ctx.lineTo(x, y - ry);
- ctx.bezierCurveTo(x, y - cy, x - cx, y, x - rx, y);
- ctx.lineTo(-x + rx, y);
- ctx.bezierCurveTo(-x + cx, y, -x, y - cy, -x, y - ry);
- }
- }
- }
- ctx.closePath();
- }
- if (!clip && (hasFill || hasStroke)) {
- this._setStyles(ctx);
- if (hasFill) {
- ctx.fill(style.getWindingRule());
- ctx.shadowColor = 'rgba(0,0,0,0)';
- }
- if (hasStroke)
- ctx.stroke();
- }
- },
-
- _canComposite: function() {
- return !(this.hasFill() && this.hasStroke());
- },
-
- _getBounds: function(getter, matrix) {
- var rect = new Rectangle(this._size).setCenter(0, 0);
- if (getter !== 'getBounds' && this.hasStroke())
- rect = rect.expand(this.getStrokeWidth());
- return matrix ? matrix._transformBounds(rect) : rect;
- }
-},
-new function() {
-
- function getCornerCenter(that, point, expand) {
- var radius = that._radius;
- if (!radius.isZero()) {
- var halfSize = that._size.divide(2);
- for (var i = 0; i < 4; i++) {
- var dir = new Point(i & 1 ? 1 : -1, i > 1 ? 1 : -1),
- corner = dir.multiply(halfSize),
- center = corner.subtract(dir.multiply(radius)),
- rect = new Rectangle(corner, center);
- if ((expand ? rect.expand(expand) : rect).contains(point))
- return center;
- }
- }
- }
-
- function getEllipseRadius(point, radius) {
- var angle = point.getAngleInRadians(),
- width = radius.width * 2,
- height = radius.height * 2,
- x = width * Math.sin(angle),
- y = height * Math.cos(angle);
- return width * height / (2 * Math.sqrt(x * x + y * y));
- }
-
- return {
- _contains: function _contains(point) {
- if (this._shape === 'rectangle') {
- var center = getCornerCenter(this, point);
- return center
- ? point.subtract(center).divide(this._radius)
- .getLength() <= 1
- : _contains.base.call(this, point);
- } else {
- return point.divide(this.size).getLength() <= 0.5;
- }
- },
-
- _hitTest: function _hitTest(point, options) {
- var hit = false;
- if (this.hasStroke()) {
- var shape = this._shape,
- radius = this._radius,
- strokeWidth = this.getStrokeWidth() + 2 * options.tolerance;
- if (shape === 'rectangle') {
- var center = getCornerCenter(this, point, strokeWidth);
- if (center) {
- var pt = point.subtract(center);
- hit = 2 * Math.abs(pt.getLength()
- - getEllipseRadius(pt, radius)) <= strokeWidth;
- } else {
- var rect = new Rectangle(this._size).setCenter(0, 0),
- outer = rect.expand(strokeWidth),
- inner = rect.expand(-strokeWidth);
- hit = outer._containsPoint(point)
- && !inner._containsPoint(point);
- }
- } else {
- if (shape === 'ellipse')
- radius = getEllipseRadius(point, radius);
- hit = 2 * Math.abs(point.getLength() - radius)
- <= strokeWidth;
- }
- }
- return hit
- ? new HitResult('stroke', this)
- : _hitTest.base.apply(this, arguments);
- }
- };
-}, {
-
-statics: new function() {
- function createShape(shape, point, size, radius, args) {
- return new Shape(shape, point, size, radius, Base.getNamed(args));
- }
-
- return {
- Circle: function() {
- var center = Point.readNamed(arguments, 'center'),
- radius = Base.readNamed(arguments, 'radius');
- return createShape('circle', center, new Size(radius * 2), radius,
- arguments);
- },
-
- Rectangle: function() {
- var rect = Rectangle.readNamed(arguments, 'rectangle'),
- radius = Size.min(Size.readNamed(arguments, 'radius'),
- rect.getSize(true).divide(2));
- return createShape('rectangle', rect.getCenter(true),
- rect.getSize(true), radius, arguments);
- },
-
- Ellipse: function() {
- var ellipse = Shape._readEllipse(arguments);
- radius = ellipse.radius;
- return createShape('ellipse', ellipse.center, radius.multiply(2),
- radius, arguments);
- },
-
- _readEllipse: function(args) {
- var center,
- radius;
- if (Base.hasNamed(args, 'radius')) {
- center = Point.readNamed(args, 'center');
- radius = Size.readNamed(args, 'radius');
- } else {
- var rect = Rectangle.readNamed(args, 'rectangle');
- center = rect.getCenter(true);
- radius = rect.getSize(true).divide(2);
- }
- return { center: center, radius: radius };
- }
- };
-}});
-
-var Raster = Item.extend({
- _class: 'Raster',
- _transformContent: false,
- _boundsGetter: 'getBounds',
- _boundsSelected: true,
- _serializeFields: {
- source: null
- },
-
- initialize: function Raster(object, position) {
- if (!this._initialize(object,
- position !== undefined && Point.read(arguments, 1))) {
- if (typeof object === 'string') {
- this.setSource(object);
- } else {
- this.setImage(object);
- }
- }
- if (!this._size)
- this._size = new Size();
- },
-
- _equals: function(item) {
- return this.getSource() === item.getSource();
- },
-
- clone: function(insert) {
- var param = { insert: false },
- image = this._image;
- if (image) {
- param.image = image;
- } else if (this._canvas) {
- var canvas = param.canvas = CanvasProvider.getCanvas(this._size);
- canvas.getContext('2d').drawImage(this._canvas, 0, 0);
- }
- return this._clone(new Raster(param), insert);
- },
-
- getSize: function() {
- var size = this._size;
- return new LinkedSize(size.width, size.height, this, 'setSize');
- },
-
- setSize: function() {
- var size = Size.read(arguments);
- if (!this._size.equals(size)) {
- var element = this.getElement();
- this.setCanvas(CanvasProvider.getCanvas(size));
- if (element)
- this.getContext(true).drawImage(element, 0, 0,
- size.width, size.height);
- }
- },
-
- getWidth: function() {
- return this._size.width;
- },
-
- getHeight: function() {
- return this._size.height;
- },
-
- isEmpty: function() {
- return this._size.width == 0 && this._size.height == 0;
- },
-
- getPpi: function() {
- var matrix = this._matrix,
- orig = new Point(0, 0).transform(matrix),
- u = new Point(1, 0).transform(matrix).subtract(orig),
- v = new Point(0, 1).transform(matrix).subtract(orig);
- return new Size(
- 72 / u.getLength(),
- 72 / v.getLength()
- );
- },
-
- getImage: function() {
- return this._image;
- },
-
- setImage: function(image) {
- if (this._canvas)
- CanvasProvider.release(this._canvas);
- if (image.getContext) {
- this._image = null;
- this._canvas = image;
- } else {
- this._image = image;
- this._canvas = null;
- }
- this._size = new Size(
- image.naturalWidth || image.width,
- image.naturalHeight || image.height);
- this._context = null;
- this._changed(5 | 129);
- },
-
- getCanvas: function() {
- if (!this._canvas) {
- var ctx = CanvasProvider.getContext(this._size);
- try {
- if (this._image)
- ctx.drawImage(this._image, 0, 0);
- this._canvas = ctx.canvas;
- } catch (e) {
- CanvasProvider.release(ctx);
- }
- }
- return this._canvas;
- },
-
- setCanvas: '#setImage',
-
- getContext: function() {
- if (!this._context)
- this._context = this.getCanvas().getContext('2d');
- if (arguments[0]) {
- this._image = null;
- this._changed(129);
- }
- return this._context;
- },
-
- setContext: function(context) {
- this._context = context;
- },
-
- getSource: function() {
- return this._image && this._image.src || this.toDataURL();
- },
-
- setSource: function(src) {
- var that = this,
- image = document.getElementById(src) || new Image();
-
- function loaded() {
- var view = that._project.view;
- if (view)
- paper = view._scope;
- that.fire('load');
- if (view)
- view.draw(true);
- }
-
- if (image.naturalWidth && image.naturalHeight) {
- setTimeout(loaded, 0);
- } else {
- DomEvent.add(image, {
- load: function() {
- that.setImage(image);
- loaded();
- }
- });
- if (!image.src)
- image.src = src;
- }
- this.setImage(image);
- },
-
- getElement: function() {
- return this._canvas || this._image;
- },
-
- getSubCanvas: function(rect) {
- rect = Rectangle.read(arguments);
- var ctx = CanvasProvider.getContext(rect.getSize());
- ctx.drawImage(this.getCanvas(), rect.x, rect.y,
- rect.width, rect.height, 0, 0, rect.width, rect.height);
- return ctx.canvas;
- },
-
- getSubRaster: function(rect) {
- rect = Rectangle.read(arguments);
- var raster = new Raster({
- canvas: this.getSubCanvas(rect),
- insert: false
- });
- raster.translate(rect.getCenter().subtract(this.getSize().divide(2)));
- raster._matrix.preConcatenate(this._matrix);
- raster.insertAbove(this);
- return raster;
- },
-
- toDataURL: function() {
- var src = this._image && this._image.src;
- if (/^data:/.test(src))
- return src;
- var canvas = this.getCanvas();
- return canvas ? canvas.toDataURL() : null;
- },
-
- drawImage: function(image, point) {
- point = Point.read(arguments, 1);
- this.getContext(true).drawImage(image, point.x, point.y);
- },
-
- getAverageColor: function(object) {
- var bounds, path;
- if (!object) {
- bounds = this.getBounds();
- } else if (object instanceof PathItem) {
- path = object;
- bounds = object.getBounds();
- } else if (object.width) {
- bounds = new Rectangle(object);
- } else if (object.x) {
- bounds = new Rectangle(object.x - 0.5, object.y - 0.5, 1, 1);
- }
- var sampleSize = 32,
- width = Math.min(bounds.width, sampleSize),
- height = Math.min(bounds.height, sampleSize);
- var ctx = Raster._sampleContext;
- if (!ctx) {
- ctx = Raster._sampleContext = CanvasProvider.getContext(
- new Size(sampleSize));
- } else {
- ctx.clearRect(0, 0, sampleSize + 1, sampleSize + 1);
- }
- ctx.save();
- var matrix = new Matrix()
- .scale(width / bounds.width, height / bounds.height)
- .translate(-bounds.x, -bounds.y);
- matrix.applyToContext(ctx);
- if (path)
- path.draw(ctx, new Base({ clip: true, transforms: [matrix] }));
- this._matrix.applyToContext(ctx);
- ctx.drawImage(this.getElement(),
- -this._size.width / 2, -this._size.height / 2);
- ctx.restore();
- var pixels = ctx.getImageData(0.5, 0.5, Math.ceil(width),
- Math.ceil(height)).data,
- channels = [0, 0, 0],
- total = 0;
- for (var i = 0, l = pixels.length; i < l; i += 4) {
- var alpha = pixels[i + 3];
- total += alpha;
- alpha /= 255;
- channels[0] += pixels[i] * alpha;
- channels[1] += pixels[i + 1] * alpha;
- channels[2] += pixels[i + 2] * alpha;
- }
- for (var i = 0; i < 3; i++)
- channels[i] /= total;
- return total ? Color.read(channels) : null;
- },
-
- getPixel: function(point) {
- point = Point.read(arguments);
- var data = this.getContext().getImageData(point.x, point.y, 1, 1).data;
- return new Color('rgb', [data[0] / 255, data[1] / 255, data[2] / 255],
- data[3] / 255);
- },
-
- setPixel: function() {
- var point = Point.read(arguments),
- color = Color.read(arguments),
- components = color._convert('rgb'),
- alpha = color._alpha,
- ctx = this.getContext(true),
- imageData = ctx.createImageData(1, 1),
- data = imageData.data;
- data[0] = components[0] * 255;
- data[1] = components[1] * 255;
- data[2] = components[2] * 255;
- data[3] = alpha != null ? alpha * 255 : 255;
- ctx.putImageData(imageData, point.x, point.y);
- },
-
- createImageData: function(size) {
- size = Size.read(arguments);
- return this.getContext().createImageData(size.width, size.height);
- },
-
- getImageData: function(rect) {
- rect = Rectangle.read(arguments);
- if (rect.isEmpty())
- rect = new Rectangle(this._size);
- return this.getContext().getImageData(rect.x, rect.y,
- rect.width, rect.height);
- },
-
- setImageData: function(data, point) {
- point = Point.read(arguments, 1);
- this.getContext(true).putImageData(data, point.x, point.y);
- },
-
- _getBounds: function(getter, matrix) {
- var rect = new Rectangle(this._size).setCenter(0, 0);
- return matrix ? matrix._transformBounds(rect) : rect;
- },
-
- _hitTest: function(point) {
- if (this._contains(point)) {
- var that = this;
- return new HitResult('pixel', that, {
- offset: point.add(that._size.divide(2)).round(),
- color: {
- get: function() {
- return that.getPixel(this.offset);
- }
- }
- });
- }
- },
-
- _draw: function(ctx) {
- var element = this.getElement();
- if (element) {
- ctx.globalAlpha = this._opacity;
- ctx.drawImage(element,
- -this._size.width / 2, -this._size.height / 2);
- }
- },
-
- _canComposite: function() {
- return true;
- }
-});
-
-var PlacedSymbol = Item.extend({
- _class: 'PlacedSymbol',
- _transformContent: false,
- _boundsGetter: { getBounds: 'getStrokeBounds' },
- _boundsSelected: true,
- _serializeFields: {
- symbol: null
- },
-
- initialize: function PlacedSymbol(arg0, arg1) {
- if (!this._initialize(arg0,
- arg1 !== undefined && Point.read(arguments, 1)))
- this.setSymbol(arg0 instanceof Symbol ? arg0 : new Symbol(arg0));
- },
-
- _equals: function(item) {
- return this._symbol === item._symbol;
- },
-
- getSymbol: function() {
- return this._symbol;
- },
-
- setSymbol: function(symbol) {
- if (this._symbol)
- delete this._symbol._instances[this._id];
- this._symbol = symbol;
- symbol._instances[this._id] = this;
- },
-
- clone: function(insert) {
- return this._clone(new PlacedSymbol({
- symbol: this.symbol,
- insert: false
- }), insert);
- },
-
- isEmpty: function() {
- return this._symbol._definition.isEmpty();
- },
-
- _getBounds: function(getter, matrix) {
- return this.symbol._definition._getCachedBounds(getter, matrix);
- },
-
- _hitTest: function(point, options, matrix) {
- var result = this._symbol._definition._hitTest(point, options, matrix);
- if (result)
- result.item = this;
- return result;
- },
-
- _draw: function(ctx, param) {
- this.symbol._definition.draw(ctx, param);
- }
-
-});
-
-var HitResult = Base.extend({
- _class: 'HitResult',
-
- initialize: function HitResult(type, item, values) {
- this.type = type;
- this.item = item;
- if (values) {
- values.enumerable = true;
- this.inject(values);
- }
- },
-
- statics: {
- getOptions: function(options) {
- return options && options._merged ? options : new Base({
- type: null,
- tolerance: paper.project.options.hitTolerance || 2,
- fill: !options,
- stroke: !options,
- segments: !options,
- handles: false,
- ends: false,
- center: false,
- bounds: false,
- guides: false,
- selected: false,
- _merged: true
- }, options);
- }
- }
-});
-
-var Segment = Base.extend({
- _class: 'Segment',
-
- initialize: function Segment(arg0, arg1, arg2, arg3, arg4, arg5) {
- var count = arguments.length,
- point, handleIn, handleOut;
- if (count === 0) {
- } else if (count === 1) {
- if (arg0.point) {
- point = arg0.point;
- handleIn = arg0.handleIn;
- handleOut = arg0.handleOut;
- } else {
- point = arg0;
- }
- } else if (count === 2 && typeof arg0 === 'number') {
- point = arguments;
- } else if (count <= 3) {
- point = arg0;
- handleIn = arg1;
- handleOut = arg2;
- } else {
- point = arg0 !== undefined ? [ arg0, arg1 ] : null;
- handleIn = arg2 !== undefined ? [ arg2, arg3 ] : null;
- handleOut = arg4 !== undefined ? [ arg4, arg5 ] : null;
- }
- new SegmentPoint(point, this, '_point');
- new SegmentPoint(handleIn, this, '_handleIn');
- new SegmentPoint(handleOut, this, '_handleOut');
- },
-
- _serialize: function(options) {
- return Base.serialize(this.isLinear() ? this._point
- : [this._point, this._handleIn, this._handleOut], options, true);
- },
-
- _changed: function(point) {
- if (!this._path)
- return;
- var curve = this._path._curves && this.getCurve(),
- other;
- if (curve) {
- curve._changed();
- if (other = (curve[point == this._point
- || point == this._handleIn && curve._segment1 == this
- ? 'getPrevious' : 'getNext']())) {
- other._changed();
- }
- }
- this._path._changed(5);
- },
-
- getPoint: function() {
- return this._point;
- },
-
- setPoint: function(point) {
- point = Point.read(arguments);
- this._point.set(point.x, point.y);
- },
-
- getHandleIn: function() {
- return this._handleIn;
- },
-
- setHandleIn: function(point) {
- point = Point.read(arguments);
- this._handleIn.set(point.x, point.y);
- },
-
- getHandleOut: function() {
- return this._handleOut;
- },
-
- setHandleOut: function(point) {
- point = Point.read(arguments);
- this._handleOut.set(point.x, point.y);
- },
-
- isLinear: function() {
- return this._handleIn.isZero() && this._handleOut.isZero();
- },
-
- setLinear: function() {
- this._handleIn.set(0, 0);
- this._handleOut.set(0, 0);
- },
-
- isColinear: function(segment) {
- var next1 = this.getNext(),
- next2 = segment.getNext();
- return this._handleOut.isZero() && next1._handleIn.isZero()
- && segment._handleOut.isZero() && next2._handleIn.isZero()
- && next1._point.subtract(this._point).isColinear(
- next2._point.subtract(segment._point));
- },
-
- isOrthogonal: function() {
- var prev = this.getPrevious(),
- next = this.getNext();
- return prev._handleOut.isZero() && this._handleIn.isZero()
- && this._handleOut.isZero() && next._handleIn.isZero()
- && this._point.subtract(prev._point).isOrthogonal(
- next._point.subtract(this._point));
- },
-
- isArc: function() {
- var next = this.getNext(),
- handle1 = this._handleOut,
- handle2 = next._handleIn,
- kappa = Numerical.KAPPA;
- if (handle1.isOrthogonal(handle2)) {
- var from = this._point,
- to = next._point,
- corner = new Line(from, handle1, true).intersect(
- new Line(to, handle2, true), true);
- return corner && Numerical.isZero(handle1.getLength() /
- corner.subtract(from).getLength() - kappa)
- && Numerical.isZero(handle2.getLength() /
- corner.subtract(to).getLength() - kappa);
- }
- return false;
- },
-
- _isSelected: function(point) {
- var state = this._selectionState;
- return point == this._point ? !!(state & 4)
- : point == this._handleIn ? !!(state & 1)
- : point == this._handleOut ? !!(state & 2)
- : false;
- },
-
- _setSelected: function(point, selected) {
- var path = this._path,
- selected = !!selected,
- state = this._selectionState || 0,
- selection = [
- !!(state & 4),
- !!(state & 1),
- !!(state & 2)
- ];
- if (point === this._point) {
- if (selected) {
- selection[1] = selection[2] = false;
- } else {
- var previous = this.getPrevious(),
- next = this.getNext();
- selection[1] = previous && (previous._point.isSelected()
- || previous._handleOut.isSelected());
- selection[2] = next && (next._point.isSelected()
- || next._handleIn.isSelected());
- }
- selection[0] = selected;
- } else {
- var index = point === this._handleIn ? 1 : 2;
- if (selection[index] != selected) {
- if (selected)
- selection[0] = false;
- selection[index] = selected;
- }
- }
- this._selectionState = (selection[0] ? 4 : 0)
- | (selection[1] ? 1 : 0)
- | (selection[2] ? 2 : 0);
- if (path && state != this._selectionState) {
- path._updateSelection(this, state, this._selectionState);
- path._changed(33);
- }
- },
-
- isSelected: function() {
- return this._isSelected(this._point);
- },
-
- setSelected: function(selected) {
- this._setSelected(this._point, selected);
- },
-
- getIndex: function() {
- return this._index !== undefined ? this._index : null;
- },
-
- getPath: function() {
- return this._path || null;
- },
-
- getCurve: function() {
- var path = this._path,
- index = this._index;
- if (path) {
- if (!path._closed && index == path._segments.length - 1)
- index--;
- return path.getCurves()[index] || null;
- }
- return null;
- },
-
- getLocation: function() {
- var curve = this.getCurve();
- return curve ? new CurveLocation(curve, curve.getNext() ? 0 : 1) : null;
- },
-
- getNext: function() {
- var segments = this._path && this._path._segments;
- return segments && (segments[this._index + 1]
- || this._path._closed && segments[0]) || null;
- },
-
- getPrevious: function() {
- var segments = this._path && this._path._segments;
- return segments && (segments[this._index - 1]
- || this._path._closed && segments[segments.length - 1]) || null;
- },
-
- reverse: function() {
- return new Segment(this._point, this._handleOut, this._handleIn);
- },
-
- remove: function() {
- return this._path ? !!this._path.removeSegment(this._index) : false;
- },
-
- clone: function() {
- return new Segment(this._point, this._handleIn, this._handleOut);
- },
-
- equals: function(segment) {
- return segment === this || segment && this._class === segment._class
- && this._point.equals(segment._point)
- && this._handleIn.equals(segment._handleIn)
- && this._handleOut.equals(segment._handleOut)
- || false;
- },
-
- toString: function() {
- var parts = [ 'point: ' + this._point ];
- if (!this._handleIn.isZero())
- parts.push('handleIn: ' + this._handleIn);
- if (!this._handleOut.isZero())
- parts.push('handleOut: ' + this._handleOut);
- return '{ ' + parts.join(', ') + ' }';
- },
-
- _transformCoordinates: function(matrix, coords, change) {
- var point = this._point,
- handleIn = !change || !this._handleIn.isZero()
- ? this._handleIn : null,
- handleOut = !change || !this._handleOut.isZero()
- ? this._handleOut : null,
- x = point._x,
- y = point._y,
- i = 2;
- coords[0] = x;
- coords[1] = y;
- if (handleIn) {
- coords[i++] = handleIn._x + x;
- coords[i++] = handleIn._y + y;
- }
- if (handleOut) {
- coords[i++] = handleOut._x + x;
- coords[i++] = handleOut._y + y;
- }
- if (matrix) {
- matrix._transformCoordinates(coords, 0, coords, 0, i / 2);
- x = coords[0];
- y = coords[1];
- if (change) {
- point._x = x;
- point._y = y;
- i = 2;
- if (handleIn) {
- handleIn._x = coords[i++] - x;
- handleIn._y = coords[i++] - y;
- }
- if (handleOut) {
- handleOut._x = coords[i++] - x;
- handleOut._y = coords[i++] - y;
- }
- } else {
- if (!handleIn) {
- coords[i++] = x;
- coords[i++] = y;
- }
- if (!handleOut) {
- coords[i++] = x;
- coords[i++] = y;
- }
- }
- }
- return coords;
- }
-});
-
-var SegmentPoint = Point.extend({
- initialize: function SegmentPoint(point, owner, key) {
- var x, y, selected;
- if (!point) {
- x = y = 0;
- } else if ((x = point[0]) !== undefined) {
- y = point[1];
- } else {
- if ((x = point.x) === undefined) {
- point = Point.read(arguments);
- x = point.x;
- }
- y = point.y;
- selected = point.selected;
- }
- this._x = x;
- this._y = y;
- this._owner = owner;
- owner[key] = this;
- if (selected)
- this.setSelected(true);
- },
-
- set: function(x, y) {
- this._x = x;
- this._y = y;
- this._owner._changed(this);
- return this;
- },
-
- _serialize: function(options) {
- var f = options.formatter,
- x = f.number(this._x),
- y = f.number(this._y);
- return this.isSelected()
- ? { x: x, y: y, selected: true }
- : [x, y];
- },
-
- getX: function() {
- return this._x;
- },
-
- setX: function(x) {
- this._x = x;
- this._owner._changed(this);
- },
-
- getY: function() {
- return this._y;
- },
-
- setY: function(y) {
- this._y = y;
- this._owner._changed(this);
- },
-
- isZero: function() {
- return Numerical.isZero(this._x) && Numerical.isZero(this._y);
- },
-
- setSelected: function(selected) {
- this._owner._setSelected(this, selected);
- },
-
- isSelected: function() {
- return this._owner._isSelected(this);
- }
-});
-
-var Curve = Base.extend({
- _class: 'Curve',
- initialize: function Curve(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7) {
- var count = arguments.length;
- if (count === 3) {
- this._path = arg0;
- this._segment1 = arg1;
- this._segment2 = arg2;
- } else if (count === 0) {
- this._segment1 = new Segment();
- this._segment2 = new Segment();
- } else if (count === 1) {
- this._segment1 = new Segment(arg0.segment1);
- this._segment2 = new Segment(arg0.segment2);
- } else if (count === 2) {
- this._segment1 = new Segment(arg0);
- this._segment2 = new Segment(arg1);
- } else {
- var point1, handle1, handle2, point2;
- if (count === 4) {
- point1 = arg0;
- handle1 = arg1;
- handle2 = arg2;
- point2 = arg3;
- } else if (count === 8) {
- point1 = [arg0, arg1];
- point2 = [arg6, arg7];
- handle1 = [arg2 - arg0, arg3 - arg1];
- handle2 = [arg4 - arg6, arg5 - arg7];
- }
- this._segment1 = new Segment(point1, null, handle1);
- this._segment2 = new Segment(point2, handle2, null);
- }
- },
-
- _changed: function() {
- delete this._length;
- delete this._bounds;
- },
-
- getPoint1: function() {
- return this._segment1._point;
- },
-
- setPoint1: function(point) {
- point = Point.read(arguments);
- this._segment1._point.set(point.x, point.y);
- },
-
- getPoint2: function() {
- return this._segment2._point;
- },
-
- setPoint2: function(point) {
- point = Point.read(arguments);
- this._segment2._point.set(point.x, point.y);
- },
-
- getHandle1: function() {
- return this._segment1._handleOut;
- },
-
- setHandle1: function(point) {
- point = Point.read(arguments);
- this._segment1._handleOut.set(point.x, point.y);
- },
-
- getHandle2: function() {
- return this._segment2._handleIn;
- },
-
- setHandle2: function(point) {
- point = Point.read(arguments);
- this._segment2._handleIn.set(point.x, point.y);
- },
-
- getSegment1: function() {
- return this._segment1;
- },
-
- getSegment2: function() {
- return this._segment2;
- },
-
- getPath: function() {
- return this._path;
- },
-
- getIndex: function() {
- return this._segment1._index;
- },
-
- getNext: function() {
- var curves = this._path && this._path._curves;
- return curves && (curves[this._segment1._index + 1]
- || this._path._closed && curves[0]) || null;
- },
-
- getPrevious: function() {
- var curves = this._path && this._path._curves;
- return curves && (curves[this._segment1._index - 1]
- || this._path._closed && curves[curves.length - 1]) || null;
- },
-
- isSelected: function() {
- return this.getHandle1().isSelected() && this.getHandle2().isSelected();
- },
-
- setSelected: function(selected) {
- this.getHandle1().setSelected(selected);
- this.getHandle2().setSelected(selected);
- },
-
- getValues: function() {
- return Curve.getValues(this._segment1, this._segment2);
- },
-
- getPoints: function() {
- var coords = this.getValues(),
- points = [];
- for (var i = 0; i < 8; i += 2)
- points.push(new Point(coords[i], coords[i + 1]));
- return points;
- },
-
- getLength: function() {
- var from = arguments[0],
- to = arguments[1],
- fullLength = arguments.length === 0 || from === 0 && to === 1;
- if (fullLength && this._length != null)
- return this._length;
- var length = Curve.getLength(this.getValues(), from, to);
- if (fullLength)
- this._length = length;
- return length;
- },
-
- getArea: function() {
- return Curve.getArea(this.getValues());
- },
-
- getPart: function(from, to) {
- return new Curve(Curve.getPart(this.getValues(), from, to));
- },
-
- isLinear: function() {
- return this._segment1._handleOut.isZero()
- && this._segment2._handleIn.isZero();
- },
-
- getIntersections: function(curve) {
- return Curve.getIntersections(this.getValues(), curve.getValues(),
- this, curve, []);
- },
-
- reverse: function() {
- return new Curve(this._segment2.reverse(), this._segment1.reverse());
- },
-
- _getParameter: function(offset, isParameter) {
- return isParameter
- ? offset
- : offset && offset.curve === this
- ? offset.parameter
- : offset === undefined && isParameter === undefined
- ? 0.5
- : this.getParameterAt(offset, 0);
- },
-
- divide: function(offset, isParameter) {
- var parameter = this._getParameter(offset, isParameter),
- tolerance = 0.00001,
- res = null;
- if (parameter > tolerance && parameter < 1 - tolerance) {
- var parts = Curve.subdivide(this.getValues(), parameter),
- isLinear = this.isLinear(),
- left = parts[0],
- right = parts[1];
-
- if (!isLinear) {
- this._segment1._handleOut.set(left[2] - left[0],
- left[3] - left[1]);
- this._segment2._handleIn.set(right[4] - right[6],
- right[5] - right[7]);
- }
-
- var x = left[6], y = left[7],
- segment = new Segment(new Point(x, y),
- !isLinear && new Point(left[4] - x, left[5] - y),
- !isLinear && new Point(right[2] - x, right[3] - y));
-
- if (this._path) {
- if (this._segment1._index > 0 && this._segment2._index === 0) {
- this._path.add(segment);
- } else {
- this._path.insert(this._segment2._index, segment);
- }
- res = this;
- } else {
- var end = this._segment2;
- this._segment2 = segment;
- res = new Curve(segment, end);
- }
- }
- return res;
- },
-
- split: function(offset, isParameter) {
- return this._path
- ? this._path.split(this._segment1._index,
- this._getParameter(offset, isParameter))
- : null;
- },
-
- clone: function() {
- return new Curve(this._segment1, this._segment2);
- },
-
- toString: function() {
- var parts = [ 'point1: ' + this._segment1._point ];
- if (!this._segment1._handleOut.isZero())
- parts.push('handle1: ' + this._segment1._handleOut);
- if (!this._segment2._handleIn.isZero())
- parts.push('handle2: ' + this._segment2._handleIn);
- parts.push('point2: ' + this._segment2._point);
- return '{ ' + parts.join(', ') + ' }';
- },
-
-statics: {
- getValues: function(segment1, segment2) {
- var p1 = segment1._point,
- h1 = segment1._handleOut,
- h2 = segment2._handleIn,
- p2 = segment2._point;
- return [
- p1._x, p1._y,
- p1._x + h1._x, p1._y + h1._y,
- p2._x + h2._x, p2._y + h2._y,
- p2._x, p2._y
- ];
- },
-
- evaluate: function(v, t, type) {
- var p1x = v[0], p1y = v[1],
- c1x = v[2], c1y = v[3],
- c2x = v[4], c2y = v[5],
- p2x = v[6], p2y = v[7],
- x, y;
-
- if (type === 0 && (t === 0 || t === 1)) {
- x = t === 0 ? p1x : p2x;
- y = t === 0 ? p1y : p2y;
- } else {
- var cx = 3 * (c1x - p1x),
- bx = 3 * (c2x - c1x) - cx,
- ax = p2x - p1x - cx - bx,
-
- cy = 3 * (c1y - p1y),
- by = 3 * (c2y - c1y) - cy,
- ay = p2y - p1y - cy - by;
- if (type === 0) {
- x = ((ax * t + bx) * t + cx) * t + p1x;
- y = ((ay * t + by) * t + cy) * t + p1y;
- } else {
- var tolerance = 0.00001;
- if (t < tolerance && c1x === p1x && c1y === p1y
- || t > 1 - tolerance && c2x === p2x && c2y === p2y) {
- x = p2x - p1x;
- y = p2y - p1y;
- } else {
- x = (3 * ax * t + 2 * bx) * t + cx;
- y = (3 * ay * t + 2 * by) * t + cy;
- }
- if (type === 3) {
- var x2 = 6 * ax * t + 2 * bx,
- y2 = 6 * ay * t + 2 * by;
- return (x * y2 - y * x2) / Math.pow(x * x + y * y, 3 / 2);
- }
- }
- }
- return type == 2 ? new Point(y, -x) : new Point(x, y);
- },
-
- subdivide: function(v, t) {
- var p1x = v[0], p1y = v[1],
- c1x = v[2], c1y = v[3],
- c2x = v[4], c2y = v[5],
- p2x = v[6], p2y = v[7];
- if (t === undefined)
- t = 0.5;
- var u = 1 - t,
- p3x = u * p1x + t * c1x, p3y = u * p1y + t * c1y,
- p4x = u * c1x + t * c2x, p4y = u * c1y + t * c2y,
- p5x = u * c2x + t * p2x, p5y = u * c2y + t * p2y,
- p6x = u * p3x + t * p4x, p6y = u * p3y + t * p4y,
- p7x = u * p4x + t * p5x, p7y = u * p4y + t * p5y,
- p8x = u * p6x + t * p7x, p8y = u * p6y + t * p7y;
- return [
- [p1x, p1y, p3x, p3y, p6x, p6y, p8x, p8y],
- [p8x, p8y, p7x, p7y, p5x, p5y, p2x, p2y]
- ];
- },
-
- solveCubic: function (v, coord, val, roots, min, max) {
- var p1 = v[coord],
- c1 = v[coord + 2],
- c2 = v[coord + 4],
- p2 = v[coord + 6],
- c = 3 * (c1 - p1),
- b = 3 * (c2 - c1) - c,
- a = p2 - p1 - c - b;
- return Numerical.solveCubic(a, b, c, p1 - val, roots, min, max);
- },
-
- getParameterOf: function(v, x, y) {
- if (Math.abs(v[0] - x) < 0.00001
- && Math.abs(v[1] - y) < 0.00001)
- return 0;
- if (Math.abs(v[6] - x) < 0.00001
- && Math.abs(v[7] - y) < 0.00001)
- return 1;
- var txs = [],
- tys = [],
- sx = Curve.solveCubic(v, 0, x, txs),
- sy = Curve.solveCubic(v, 1, y, tys),
- tx, ty;
- for (var cx = 0; sx == -1 || cx < sx;) {
- if (sx == -1 || (tx = txs[cx++]) >= 0 && tx <= 1) {
- for (var cy = 0; sy == -1 || cy < sy;) {
- if (sy == -1 || (ty = tys[cy++]) >= 0 && ty <= 1) {
- if (sx == -1) tx = ty;
- else if (sy == -1) ty = tx;
- if (Math.abs(tx - ty) < 0.00001)
- return (tx + ty) * 0.5;
- }
- }
- if (sx == -1)
- break;
- }
- }
- return null;
- },
-
- getPart: function(v, from, to) {
- if (from > 0)
- v = Curve.subdivide(v, from)[1];
- if (to < 1)
- v = Curve.subdivide(v, (to - from) / (1 - from))[0];
- return v;
- },
-
- isLinear: function(v) {
- var isZero = Numerical.isZero;
- return isZero(v[0] - v[2]) && isZero(v[1] - v[3])
- && isZero(v[4] - v[6]) && isZero(v[5] - v[7]);
- },
-
- isFlatEnough: function(v, tolerance) {
- var p1x = v[0], p1y = v[1],
- c1x = v[2], c1y = v[3],
- c2x = v[4], c2y = v[5],
- p2x = v[6], p2y = v[7],
- ux = 3 * c1x - 2 * p1x - p2x,
- uy = 3 * c1y - 2 * p1y - p2y,
- vx = 3 * c2x - 2 * p2x - p1x,
- vy = 3 * c2y - 2 * p2y - p1y;
- return Math.max(ux * ux, vx * vx) + Math.max(uy * uy, vy * vy)
- < 10 * tolerance * tolerance;
- },
-
- getArea: function(v) {
- var p1x = v[0], p1y = v[1],
- c1x = v[2], c1y = v[3],
- c2x = v[4], c2y = v[5],
- p2x = v[6], p2y = v[7];
- return ( 3.0 * c1y * p1x - 1.5 * c1y * c2x
- - 1.5 * c1y * p2x - 3.0 * p1y * c1x
- - 1.5 * p1y * c2x - 0.5 * p1y * p2x
- + 1.5 * c2y * p1x + 1.5 * c2y * c1x
- - 3.0 * c2y * p2x + 0.5 * p2y * p1x
- + 1.5 * p2y * c1x + 3.0 * p2y * c2x) / 10;
- },
-
- getBounds: function(v) {
- var min = v.slice(0, 2),
- max = min.slice(),
- roots = [0, 0];
- for (var i = 0; i < 2; i++)
- Curve._addBounds(v[i], v[i + 2], v[i + 4], v[i + 6],
- i, 0, min, max, roots);
- return new Rectangle(min[0], min[1], max[0] - min[0], max[1] - min[1]);
- },
-
- _addBounds: function(v0, v1, v2, v3, coord, padding, min, max, roots) {
- function add(value, padding) {
- var left = value - padding,
- right = value + padding;
- if (left < min[coord])
- min[coord] = left;
- if (right > max[coord])
- max[coord] = right;
- }
- var a = 3 * (v1 - v2) - v0 + v3,
- b = 2 * (v0 + v2) - 4 * v1,
- c = v1 - v0,
- count = Numerical.solveQuadratic(a, b, c, roots),
- tMin = 0.00001,
- tMax = 1 - tMin;
- add(v3, 0);
- for (var i = 0; i < count; i++) {
- var t = roots[i],
- u = 1 - t;
- if (tMin < t && t < tMax)
- add(u * u * u * v0
- + 3 * u * u * t * v1
- + 3 * u * t * t * v2
- + t * t * t * v3,
- padding);
- }
- },
-
- _getWinding: function(v, prev, x, y, roots1, roots2) {
- var tolerance = 0.00001,
- abs = Math.abs;
-
- function getDirection(v) {
- var y0 = v[1],
- y1 = v[7],
- dir = y0 > y1 ? -1 : 1;
- return dir === 1 && (y < y0 || y > y1)
- || dir === -1 && (y < y1 || y > y0)
- ? 0
- : dir;
- }
-
- if (Curve.isLinear(v)) {
- var dir = getDirection(v);
- if (!dir)
- return 0;
- var cross = (v[6] - v[0]) * (y - v[1]) - (v[7] - v[1]) * (x - v[0]);
- return (cross < -tolerance ? -1 : 1) == dir ? 0 : dir;
- }
-
- var y0 = v[1],
- y1 = v[3],
- y2 = v[5],
- y3 = v[7];
- var a = 3 * (y1 - y2) - y0 + y3,
- b = 2 * (y0 + y2) - 4 * y1,
- c = y1 - y0;
- var count = Numerical.solveQuadratic(a, b, c, roots1, tolerance,
- 1 - tolerance),
- part,
- rest = v,
- t1 = roots1[0],
- winding = 0;
- for (var i = 0; i <= count; i++) {
- if (i === count) {
- part = rest;
- } else {
- var curves = Curve.subdivide(rest, t1);
- part = curves[0];
- rest = curves[1];
- t1 = roots1[i];
- t1 = (roots1[i + 1] - t1) / (1 - t1);
- }
- if (i > 0)
- part[3] = part[1];
- if (i < count)
- part[5] = rest[1];
- var dir = getDirection(part);
- if (!dir)
- continue;
- var t2,
- px;
- if (Curve.solveCubic(part, 1, y, roots2, -tolerance, 1 + -tolerance)
- === 1) {
- t2 = roots2[0];
- px = Curve.evaluate(part, t2, 0).x;
- } else {
- var mid = (part[1] + part[7]) / 2;
- t2 = y < mid && dir > 0 ? 0 : 1;
- if (t2 === 1 && y == part[7])
- continue;
- px = t2 === 0 ? part[0] : part[6];
- }
- var slope = Curve.evaluate(part, t2, 1).y,
- stationary = abs(slope) < tolerance || t2 < tolerance
- && Curve.evaluate(prev, 1, 1).y * slope < 0;
- if (x >= px + (stationary ? -tolerance : tolerance * dir)
- && !(stationary && (abs(t2) < tolerance
- && abs(x - part[0]) > tolerance
- || abs(t2 - 1) < tolerance
- && abs(x - part[6]) > tolerance))) {
- winding += stationary && abs(t2 - (dir > 0 ? 1 : 0)) < tolerance
- ? -dir : dir;
- }
- prev = part;
- }
- return winding;
- }
-}}, Base.each(['getBounds', 'getStrokeBounds', 'getHandleBounds', 'getRoughBounds'],
- function(name) {
- this[name] = function() {
- if (!this._bounds)
- this._bounds = {};
- var bounds = this._bounds[name];
- if (!bounds) {
- bounds = this._bounds[name] = Path[name]([this._segment1,
- this._segment2], false, this._path.getStyle());
- }
- return bounds.clone();
- };
- },
-{
-
-}), Base.each(['getPoint', 'getTangent', 'getNormal', 'getCurvature'],
- function(name, index) {
- this[name + 'At'] = function(offset, isParameter) {
- var values = this.getValues();
- return Curve.evaluate(values, isParameter
- ? offset : Curve.getParameterAt(values, offset, 0), index);
- };
- this[name] = function(parameter) {
- return Curve.evaluate(this.getValues(), parameter, index);
- };
- },
-{
- getParameterAt: function(offset, start) {
- return Curve.getParameterAt(this.getValues(), offset,
- start !== undefined ? start : offset < 0 ? 1 : 0);
- },
-
- getParameterOf: function(point) {
- point = Point.read(arguments);
- return Curve.getParameterOf(this.getValues(), point.x, point.y);
- },
-
- getLocationAt: function(offset, isParameter) {
- if (!isParameter)
- offset = this.getParameterAt(offset);
- return new CurveLocation(this, offset);
- },
-
- getLocationOf: function(point) {
- point = Point.read(arguments);
- var t = this.getParameterOf(point);
- return t != null ? new CurveLocation(this, t) : null;
- },
-
- getNearestLocation: function(point) {
- point = Point.read(arguments);
- var values = this.getValues(),
- count = 100,
- tolerance = Numerical.TOLERANCE,
- minDist = Infinity,
- minT = 0;
-
- function refine(t) {
- if (t >= 0 && t <= 1) {
- var dist = point.getDistance(
- Curve.evaluate(values, t, 0), true);
- if (dist < minDist) {
- minDist = dist;
- minT = t;
- return true;
- }
- }
- }
-
- for (var i = 0; i <= count; i++)
- refine(i / count);
-
- var step = 1 / (count * 2);
- while (step > tolerance) {
- if (!refine(minT - step) && !refine(minT + step))
- step /= 2;
- }
- var pt = Curve.evaluate(values, minT, 0);
- return new CurveLocation(this, minT, pt, null, null, null,
- point.getDistance(pt));
- },
-
- getNearestPoint: function(point) {
- point = Point.read(arguments);
- return this.getNearestLocation(point).getPoint();
- }
-
-}),
-new function() {
-
- function getLengthIntegrand(v) {
- var p1x = v[0], p1y = v[1],
- c1x = v[2], c1y = v[3],
- c2x = v[4], c2y = v[5],
- p2x = v[6], p2y = v[7],
-
- ax = 9 * (c1x - c2x) + 3 * (p2x - p1x),
- bx = 6 * (p1x + c2x) - 12 * c1x,
- cx = 3 * (c1x - p1x),
-
- ay = 9 * (c1y - c2y) + 3 * (p2y - p1y),
- by = 6 * (p1y + c2y) - 12 * c1y,
- cy = 3 * (c1y - p1y);
-
- return function(t) {
- var dx = (ax * t + bx) * t + cx,
- dy = (ay * t + by) * t + cy;
- return Math.sqrt(dx * dx + dy * dy);
- };
- }
-
- function getIterations(a, b) {
- return Math.max(2, Math.min(16, Math.ceil(Math.abs(b - a) * 32)));
- }
-
- return {
- statics: true,
-
- getLength: function(v, a, b) {
- if (a === undefined)
- a = 0;
- if (b === undefined)
- b = 1;
- var isZero = Numerical.isZero;
- if (isZero(v[0] - v[2]) && isZero(v[1] - v[3])
- && isZero(v[6] - v[4]) && isZero(v[7] - v[5])) {
- var dx = v[6] - v[0],
- dy = v[7] - v[1];
- return (b - a) * Math.sqrt(dx * dx + dy * dy);
- }
- var ds = getLengthIntegrand(v);
- return Numerical.integrate(ds, a, b, getIterations(a, b));
- },
-
- getParameterAt: function(v, offset, start) {
- if (offset === 0)
- return start;
- var forward = offset > 0,
- a = forward ? start : 0,
- b = forward ? 1 : start,
- offset = Math.abs(offset),
- ds = getLengthIntegrand(v),
- rangeLength = Numerical.integrate(ds, a, b,
- getIterations(a, b));
- if (offset >= rangeLength)
- return forward ? b : a;
- var guess = offset / rangeLength,
- length = 0;
- function f(t) {
- var count = getIterations(start, t);
- length += start < t
- ? Numerical.integrate(ds, start, t, count)
- : -Numerical.integrate(ds, t, start, count);
- start = t;
- return length - offset;
- }
- return Numerical.findRoot(f, ds,
- forward ? a + guess : b - guess,
- a, b, 16, 0.00001);
- }
- };
-}, new function() {
- function addLocation(locations, curve1, t1, point1, curve2, t2, point2) {
- var first = locations[0],
- last = locations[locations.length - 1];
- if ((!first || !point1.isClose(first._point, Numerical.EPSILON))
- && (!last || !point1.isClose(last._point, Numerical.EPSILON)))
- locations.push(
- new CurveLocation(curve1, t1, point1, curve2, t2, point2));
- }
-
- function addCurveIntersections(v1, v2, curve1, curve2, locations,
- range1, range2, recursion) {
- recursion = (recursion || 0) + 1;
- if (recursion > 20)
- return;
- range1 = range1 || [ 0, 1 ];
- range2 = range2 || [ 0, 1 ];
- var part1 = Curve.getPart(v1, range1[0], range1[1]),
- part2 = Curve.getPart(v2, range2[0], range2[1]),
- iteration = 0;
- while (iteration++ < 20) {
- var range,
- intersects1 = clipFatLine(part1, part2, range = range2.slice()),
- intersects2 = 0;
- if (intersects1 === 0)
- break;
- if (intersects1 > 0) {
- range2 = range;
- part2 = Curve.getPart(v2, range2[0], range2[1]);
- intersects2 = clipFatLine(part2, part1, range = range1.slice());
- if (intersects2 === 0)
- break;
- if (intersects1 > 0) {
- range1 = range;
- part1 = Curve.getPart(v1, range1[0], range1[1]);
- }
- }
- if (intersects1 < 0 || intersects2 < 0) {
- if (range1[1] - range1[0] > range2[1] - range2[0]) {
- var t = (range1[0] + range1[1]) / 2;
- addCurveIntersections(v1, v2, curve1, curve2, locations,
- [ range1[0], t ], range2, recursion);
- addCurveIntersections(v1, v2, curve1, curve2, locations,
- [ t, range1[1] ], range2, recursion);
- break;
- } else {
- var t = (range2[0] + range2[1]) / 2;
- addCurveIntersections(v1, v2, curve1, curve2, locations,
- range1, [ range2[0], t ], recursion);
- addCurveIntersections(v1, v2, curve1, curve2, locations,
- range1, [ t, range2[1] ], recursion);
- break;
- }
- }
- if (Math.abs(range1[1] - range1[0]) <= 0.00001 &&
- Math.abs(range2[1] - range2[0]) <= 0.00001) {
- var t1 = (range1[0] + range1[1]) / 2,
- t2 = (range2[0] + range2[1]) / 2;
- addLocation(locations,
- curve1, t1, Curve.evaluate(v1, t1, 0),
- curve2, t2, Curve.evaluate(v2, t2, 0));
- break;
- }
- }
- }
-
- function clipFatLine(v1, v2, range2) {
- var p0x = v1[0], p0y = v1[1], p1x = v1[2], p1y = v1[3],
- p2x = v1[4], p2y = v1[5], p3x = v1[6], p3y = v1[7],
- q0x = v2[0], q0y = v2[1], q1x = v2[2], q1y = v2[3],
- q2x = v2[4], q2y = v2[5], q3x = v2[6], q3y = v2[7],
- getSignedDistance = Line.getSignedDistance,
- d1 = getSignedDistance(p0x, p0y, p3x, p3y, p1x, p1y) || 0,
- d2 = getSignedDistance(p0x, p0y, p3x, p3y, p2x, p2y) || 0,
- factor = d1 * d2 > 0 ? 3 / 4 : 4 / 9,
- dmin = factor * Math.min(0, d1, d2),
- dmax = factor * Math.max(0, d1, d2),
- dq0 = getSignedDistance(p0x, p0y, p3x, p3y, q0x, q0y),
- dq1 = getSignedDistance(p0x, p0y, p3x, p3y, q1x, q1y),
- dq2 = getSignedDistance(p0x, p0y, p3x, p3y, q2x, q2y),
- dq3 = getSignedDistance(p0x, p0y, p3x, p3y, q3x, q3y);
- if (dmin > Math.max(dq0, dq1, dq2, dq3)
- || dmax < Math.min(dq0, dq1, dq2, dq3))
- return 0;
- var hull = getConvexHull(dq0, dq1, dq2, dq3),
- swap;
- if (dq3 < dq0) {
- swap = dmin;
- dmin = dmax;
- dmax = swap;
- }
- var tmaxdmin = -Infinity,
- tmin = Infinity,
- tmax = -Infinity;
- for (var i = 0, l = hull.length; i < l; i++) {
- var p1 = hull[i],
- p2 = hull[(i + 1) % l];
- if (p2[1] < p1[1]) {
- swap = p2;
- p2 = p1;
- p1 = swap;
- }
- var x1 = p1[0],
- y1 = p1[1],
- x2 = p2[0],
- y2 = p2[1];
- var inv = (y2 - y1) / (x2 - x1);
- if (dmin >= y1 && dmin <= y2) {
- var ixdx = x1 + (dmin - y1) / inv;
- if (ixdx < tmin)
- tmin = ixdx;
- if (ixdx > tmaxdmin)
- tmaxdmin = ixdx;
- }
- if (dmax >= y1 && dmax <= y2) {
- var ixdx = x1 + (dmax - y1) / inv;
- if (ixdx > tmax)
- tmax = ixdx;
- if (ixdx < tmin)
- tmin = 0;
- }
- }
- if (tmin !== Infinity && tmax !== -Infinity) {
- var min = Math.min(dmin, dmax),
- max = Math.max(dmin, dmax);
- if (dq3 > min && dq3 < max)
- tmax = 1;
- if (dq0 > min && dq0 < max)
- tmin = 0;
- if (tmaxdmin > tmax)
- tmax = 1;
- var v2tmin = range2[0],
- tdiff = range2[1] - v2tmin;
- range2[0] = v2tmin + tmin * tdiff;
- range2[1] = v2tmin + tmax * tdiff;
- if ((tdiff - (range2[1] - range2[0])) / tdiff >= 0.2)
- return 1;
- }
- if (Curve.getBounds(v1).touches(Curve.getBounds(v2)))
- return -1;
- return 0;
- }
-
- function getConvexHull(dq0, dq1, dq2, dq3) {
- var p0 = [ 0, dq0 ],
- p1 = [ 1 / 3, dq1 ],
- p2 = [ 2 / 3, dq2 ],
- p3 = [ 1, dq3 ],
- getSignedDistance = Line.getSignedDistance,
- dist1 = getSignedDistance(0, dq0, 1, dq3, 1 / 3, dq1),
- dist2 = getSignedDistance(0, dq0, 1, dq3, 2 / 3, dq2);
- if (dist1 * dist2 < 0) {
- return [ p0, p1, p3, p2 ];
- }
- var pmax, cross;
- if (Math.abs(dist1) > Math.abs(dist2)) {
- pmax = p1;
- cross = (dq3 - dq2 - (dq3 - dq0) / 3)
- * (2 * (dq3 - dq2) - dq3 + dq1) / 3;
- } else {
- pmax = p2;
- cross = (dq1 - dq0 + (dq0 - dq3) / 3)
- * (-2 * (dq0 - dq1) + dq0 - dq2) / 3;
- }
- return cross < 0
- ? [ p0, pmax, p3 ]
- : [ p0, p1, p2, p3 ];
- }
-
- function addCurveLineIntersections(v1, v2, curve1, curve2, locations) {
- var flip = Curve.isLinear(v1),
- vc = flip ? v2 : v1,
- vl = flip ? v1 : v2,
- lx1 = vl[0], ly1 = vl[1],
- lx2 = vl[6], ly2 = vl[7],
- ldx = lx2 - lx1,
- ldy = ly2 - ly1,
- angle = Math.atan2(-ldy, ldx),
- sin = Math.sin(angle),
- cos = Math.cos(angle),
- rlx2 = ldx * cos - ldy * sin,
- rvl = [0, 0, 0, 0, rlx2, 0, rlx2, 0],
- rvc = [];
- for(var i = 0; i < 8; i += 2) {
- var x = vc[i] - lx1,
- y = vc[i + 1] - ly1;
- rvc.push(
- x * cos - y * sin,
- y * cos + x * sin);
- }
- var roots = [],
- count = Curve.solveCubic(rvc, 1, 0, roots, 0, 1);
- for (var i = 0; i < count; i++) {
- var tc = roots[i],
- x = Curve.evaluate(rvc, tc, 0).x;
- if (x >= 0 && x <= rlx2) {
- var tl = Curve.getParameterOf(rvl, x, 0),
- t1 = flip ? tl : tc,
- t2 = flip ? tc : tl;
- addLocation(locations,
- curve1, t1, Curve.evaluate(v1, t1, 0),
- curve2, t2, Curve.evaluate(v2, t2, 0));
- }
- }
- }
-
- function addLineIntersection(v1, v2, curve1, curve2, locations) {
- var point = Line.intersect(
- v1[0], v1[1], v1[6], v1[7],
- v2[0], v2[1], v2[6], v2[7]);
- if (point)
- addLocation(locations, curve1, null, point, curve2);
- }
-
- return { statics: {
- getIntersections: function(v1, v2, curve1, curve2, locations) {
- var linear1 = Curve.isLinear(v1),
- linear2 = Curve.isLinear(v2),
- c1p1 = curve1.getPoint1(),
- c1p2 = curve1.getPoint2(),
- c2p1 = curve2.getPoint1(),
- c2p2 = curve2.getPoint2(),
- tolerance = 0.00001;
- if (c1p1.isClose(c2p1, tolerance))
- addLocation(locations, curve1, 0, c1p1, curve2, 0, c1p1);
- if (c1p1.isClose(c2p2, tolerance))
- addLocation(locations, curve1, 0, c1p1, curve2, 1, c1p1);
- (linear1 && linear2
- ? addLineIntersection
- : linear1 || linear2
- ? addCurveLineIntersections
- : addCurveIntersections)(v1, v2, curve1, curve2, locations);
- if (c1p2.isClose(c2p1, tolerance))
- addLocation(locations, curve1, 1, c1p2, curve2, 0, c1p2);
- if (c1p2.isClose(c2p2, tolerance))
- addLocation(locations, curve1, 1, c1p2, curve2, 1, c1p2);
- return locations;
- }
- }};
-});
-
-var CurveLocation = Base.extend({
- _class: 'CurveLocation',
- initialize: function CurveLocation(curve, parameter, point, _curve2,
- _parameter2, _point2, _distance) {
- this._id = CurveLocation._id = (CurveLocation._id || 0) + 1;
- this._curve = curve;
- this._segment1 = curve._segment1;
- this._segment2 = curve._segment2;
- this._parameter = parameter;
- this._point = point;
- this._curve2 = _curve2;
- this._parameter2 = _parameter2;
- this._point2 = _point2;
- this._distance = _distance;
- },
-
- getSegment: function() {
- if (!this._segment) {
- var curve = this.getCurve(),
- parameter = this.getParameter();
- if (parameter === 1) {
- this._segment = curve._segment2;
- } else if (parameter === 0 || arguments[0]) {
- this._segment = curve._segment1;
- } else if (parameter == null) {
- return null;
- } else {
- this._segment = curve.getLength(0, parameter)
- < curve.getLength(parameter, 1)
- ? curve._segment1
- : curve._segment2;
- }
- }
- return this._segment;
- },
-
- getCurve: function() {
- if (!this._curve || arguments[0]) {
- this._curve = this._segment1.getCurve();
- if (this._curve.getParameterOf(this._point) == null)
- this._curve = this._segment2.getPrevious().getCurve();
- }
- return this._curve;
- },
-
- getIntersection: function() {
- var intersection = this._intersection;
- if (!intersection && this._curve2) {
- var param = this._parameter2;
- this._intersection = intersection = new CurveLocation(
- this._curve2, param, this._point2 || this._point, this);
- intersection._intersection = this;
- }
- return intersection;
- },
-
- getPath: function() {
- var curve = this.getCurve();
- return curve && curve._path;
- },
-
- getIndex: function() {
- var curve = this.getCurve();
- return curve && curve.getIndex();
- },
-
- getOffset: function() {
- var path = this.getPath();
- return path && path._getOffset(this);
- },
-
- getCurveOffset: function() {
- var curve = this.getCurve(),
- parameter = this.getParameter();
- return parameter != null && curve && curve.getLength(0, parameter);
- },
-
- getParameter: function() {
- if ((this._parameter == null || arguments[0]) && this._point) {
- var curve = this.getCurve(arguments[0] && this._point);
- this._parameter = curve && curve.getParameterOf(this._point);
- }
- return this._parameter;
- },
-
- getPoint: function() {
- if ((!this._point || arguments[0]) && this._parameter != null) {
- var curve = this.getCurve();
- this._point = curve && curve.getPointAt(this._parameter, true);
- }
- return this._point;
- },
-
- getTangent: function() {
- var parameter = this.getParameter(),
- curve = this.getCurve();
- return parameter != null && curve && curve.getTangentAt(parameter, true);
- },
-
- getNormal: function() {
- var parameter = this.getParameter(),
- curve = this.getCurve();
- return parameter != null && curve && curve.getNormalAt(parameter, true);
- },
-
- getDistance: function() {
- return this._distance;
- },
-
- divide: function() {
- var curve = this.getCurve(true);
- return curve && curve.divide(this.getParameter(true), true);
- },
-
- split: function() {
- var curve = this.getCurve(true);
- return curve && curve.split(this.getParameter(true), true);
- },
-
- toString: function() {
- var parts = [],
- point = this.getPoint(),
- f = Formatter.instance;
- if (point)
- parts.push('point: ' + point);
- var index = this.getIndex();
- if (index != null)
- parts.push('index: ' + index);
- var parameter = this.getParameter();
- if (parameter != null)
- parts.push('parameter: ' + f.number(parameter));
- if (this._distance != null)
- parts.push('distance: ' + f.number(this._distance));
- return '{ ' + parts.join(', ') + ' }';
- }
-});
-
-var PathItem = Item.extend({
- _class: 'PathItem',
-
- initialize: function PathItem() {
- },
-
- getIntersections: function(path) {
- if (!this.getBounds().touches(path.getBounds()))
- return [];
- var locations = [],
- curves1 = this.getCurves(),
- curves2 = path.getCurves(),
- length2 = curves2.length,
- values2 = [];
- for (var i = 0; i < length2; i++)
- values2[i] = curves2[i].getValues();
- for (var i = 0, l = curves1.length; i < l; i++) {
- var curve1 = curves1[i],
- values1 = curve1.getValues();
- for (var j = 0; j < length2; j++)
- Curve.getIntersections(values1, values2[j], curve1, curves2[j],
- locations);
- }
- return locations;
- },
-
- setPathData: function(data) {
-
- var parts = data.match(/[mlhvcsqtaz][^mlhvcsqtaz]*/ig),
- coords,
- relative = false,
- control,
- current = new Point();
-
- function getCoord(index, coord, isCurrent) {
- var val = parseFloat(coords[index]);
- if (relative)
- val += current[coord];
- if (isCurrent)
- current[coord] = val;
- return val;
- }
-
- function getPoint(index, isCurrent) {
- return new Point(
- getCoord(index, 'x', isCurrent),
- getCoord(index + 1, 'y', isCurrent)
- );
- }
-
- this.clear();
-
- for (var i = 0, l = parts.length; i < l; i++) {
- var part = parts[i],
- cmd = part[0],
- lower = cmd.toLowerCase();
- coords = part.match(/[+-]?(?:\d*\.\d+|\d+\.?)(?:[eE][+-]?\d+)?/g);
- var length = coords && coords.length;
- relative = cmd === lower;
- switch (lower) {
- case 'm':
- case 'l':
- for (var j = 0; j < length; j += 2)
- this[j === 0 && lower === 'm' ? 'moveTo' : 'lineTo'](
- getPoint(j, true));
- control = current;
- break;
- case 'h':
- case 'v':
- var coord = lower == 'h' ? 'x' : 'y';
- for (var j = 0; j < length; j++) {
- getCoord(j, coord, true);
- this.lineTo(current);
- }
- control = current;
- break;
- case 'c':
- for (var j = 0; j < length; j += 6) {
- this.cubicCurveTo(
- getPoint(j),
- control = getPoint(j + 2),
- getPoint(j + 4, true));
- }
- break;
- case 's':
- for (var j = 0; j < length; j += 4) {
- this.cubicCurveTo(
- current.multiply(2).subtract(control),
- control = getPoint(j),
- getPoint(j + 2, true));
- }
- break;
- case 'q':
- for (var j = 0; j < length; j += 4) {
- this.quadraticCurveTo(
- control = getPoint(j),
- getPoint(j + 2, true));
- }
- break;
- case 't':
- for (var j = 0; j < length; j += 2) {
- this.quadraticCurveTo(
- control = current.multiply(2).subtract(control),
- getPoint(j, true));
- }
- break;
- case 'a':
- break;
- case 'z':
- this.closePath();
- break;
- }
- }
- },
-
- _canComposite: function() {
- return !(this.hasFill() && this.hasStroke());
- },
-
- _contains: function(point) {
- var winding = this._getWinding(point);
- return !!(this.getWindingRule() === 'evenodd' ? winding & 1 : winding);
- }
-
-});
-
-var Path = PathItem.extend({
- _class: 'Path',
- _serializeFields: {
- segments: [],
- closed: false
- },
-
- initialize: function Path(arg) {
- this._closed = false;
- this._segments = [];
- var segments = Array.isArray(arg)
- ? typeof arg[0] === 'object'
- ? arg
- : arguments
- : arg && (arg.point !== undefined && arg.size === undefined
- || arg.x !== undefined)
- ? arguments
- : null;
- this.setSegments(segments || []);
- this._initialize(!segments && arg);
- },
-
- _equals: function(item) {
- return Base.equals(this._segments, item._segments);
- },
-
- clone: function(insert) {
- var copy = this._clone(new Path({
- segments: this._segments,
- insert: false
- }), insert);
- copy._closed = this._closed;
- if (this._clockwise !== undefined)
- copy._clockwise = this._clockwise;
- return copy;
- },
-
- _changed: function _changed(flags) {
- _changed.base.call(this, flags);
- if (flags & 4) {
- delete this._length;
- delete this._clockwise;
- if (this._curves) {
- for (var i = 0, l = this._curves.length; i < l; i++)
- this._curves[i]._changed(5);
- }
- } else if (flags & 8) {
- delete this._bounds;
- }
- },
-
- getSegments: function() {
- return this._segments;
- },
-
- setSegments: function(segments) {
- var fullySelected = this.isFullySelected();
- this._segments.length = 0;
- this._selectedSegmentState = 0;
- delete this._curves;
- this._add(Segment.readAll(segments));
- if (fullySelected)
- this.setFullySelected(true);
- },
-
- getFirstSegment: function() {
- return this._segments[0];
- },
-
- getLastSegment: function() {
- return this._segments[this._segments.length - 1];
- },
-
- getCurves: function() {
- var curves = this._curves,
- segments = this._segments;
- if (!curves) {
- var length = this._countCurves();
- curves = this._curves = new Array(length);
- for (var i = 0; i < length; i++)
- curves[i] = new Curve(this, segments[i],
- segments[i + 1] || segments[0]);
- }
- return curves;
- },
-
- getFirstCurve: function() {
- return this.getCurves()[0];
- },
-
- getLastCurve: function() {
- var curves = this.getCurves();
- return curves[curves.length - 1];
- },
-
- getPathData: function() {
- var segments = this._segments,
- precision = arguments[0],
- f = Formatter.instance,
- parts = [];
-
- function addCurve(seg1, seg2, skipLine) {
- var point1 = seg1._point,
- point2 = seg2._point,
- handle1 = seg1._handleOut,
- handle2 = seg2._handleIn;
- if (handle1.isZero() && handle2.isZero()) {
- if (!skipLine) {
- parts.push('L' + f.point(point2, precision));
- }
- } else {
- var end = point2.subtract(point1);
- parts.push('c' + f.point(handle1, precision)
- + ' ' + f.point(end.add(handle2), precision)
- + ' ' + f.point(end, precision));
- }
- }
-
- if (segments.length === 0)
- return '';
- parts.push('M' + f.point(segments[0]._point));
- for (var i = 0, l = segments.length - 1; i < l; i++)
- addCurve(segments[i], segments[i + 1], false);
- if (this._closed) {
- addCurve(segments[segments.length - 1], segments[0], true);
- parts.push('z');
- }
- return parts.join('');
- },
-
- isClosed: function() {
- return this._closed;
- },
-
- setClosed: function(closed) {
- if (this._closed != (closed = !!closed)) {
- this._closed = closed;
- if (this._curves) {
- var length = this._curves.length = this._countCurves();
- if (closed)
- this._curves[length - 1] = new Curve(this,
- this._segments[length - 1], this._segments[0]);
- }
- this._changed(5);
- }
- },
-
- isEmpty: function() {
- return this._segments.length === 0;
- },
-
- isPolygon: function() {
- for (var i = 0, l = this._segments.length; i < l; i++) {
- if (!this._segments[i].isLinear())
- return false;
- }
- return true;
- },
-
- _applyMatrix: function(matrix) {
- var coords = new Array(6);
- for (var i = 0, l = this._segments.length; i < l; i++)
- this._segments[i]._transformCoordinates(matrix, coords, true);
- return true;
- },
-
- _add: function(segs, index) {
- var segments = this._segments,
- curves = this._curves,
- amount = segs.length,
- append = index == null,
- index = append ? segments.length : index;
- for (var i = 0; i < amount; i++) {
- var segment = segs[i];
- if (segment._path)
- segment = segs[i] = segment.clone();
- segment._path = this;
- segment._index = index + i;
- if (segment._selectionState)
- this._updateSelection(segment, 0, segment._selectionState);
- }
- if (append) {
- segments.push.apply(segments, segs);
- } else {
- segments.splice.apply(segments, [index, 0].concat(segs));
- for (var i = index + amount, l = segments.length; i < l; i++)
- segments[i]._index = i;
- }
- if (curves || segs._curves) {
- if (!curves)
- curves = this._curves = [];
- var from = index > 0 ? index - 1 : index,
- start = from,
- to = Math.min(from + amount, this._countCurves());
- if (segs._curves) {
- curves.splice.apply(curves, [from, 0].concat(segs._curves));
- start += segs._curves.length;
- }
- for (var i = start; i < to; i++)
- curves.splice(i, 0, new Curve(this, null, null));
- this._adjustCurves(from, to);
- }
- this._changed(5);
- return segs;
- },
-
- _adjustCurves: function(from, to) {
- var segments = this._segments,
- curves = this._curves,
- curve;
- for (var i = from; i < to; i++) {
- curve = curves[i];
- curve._path = this;
- curve._segment1 = segments[i];
- curve._segment2 = segments[i + 1] || segments[0];
- }
- if (curve = curves[this._closed && from === 0 ? segments.length - 1
- : from - 1])
- curve._segment2 = segments[from] || segments[0];
- if (curve = curves[to])
- curve._segment1 = segments[to];
- },
-
- _countCurves: function() {
- var length = this._segments.length;
- return !this._closed && length > 0 ? length - 1 : length;
- },
-
- add: function(segment1 ) {
- return arguments.length > 1 && typeof segment1 !== 'number'
- ? this._add(Segment.readAll(arguments))
- : this._add([ Segment.read(arguments) ])[0];
- },
-
- insert: function(index, segment1 ) {
- return arguments.length > 2 && typeof segment1 !== 'number'
- ? this._add(Segment.readAll(arguments, 1), index)
- : this._add([ Segment.read(arguments, 1) ], index)[0];
- },
-
- addSegment: function() {
- return this._add([ Segment.read(arguments) ])[0];
- },
-
- insertSegment: function(index ) {
- return this._add([ Segment.read(arguments, 1) ], index)[0];
- },
-
- addSegments: function(segments) {
- return this._add(Segment.readAll(segments));
- },
-
- insertSegments: function(index, segments) {
- return this._add(Segment.readAll(segments), index);
- },
-
- removeSegment: function(index) {
- return this.removeSegments(index, index + 1)[0] || null;
- },
-
- removeSegments: function(from, to) {
- from = from || 0;
- to = Base.pick(to, this._segments.length);
- var segments = this._segments,
- curves = this._curves,
- count = segments.length,
- removed = segments.splice(from, to - from),
- amount = removed.length;
- if (!amount)
- return removed;
- for (var i = 0; i < amount; i++) {
- var segment = removed[i];
- if (segment._selectionState)
- this._updateSelection(segment, segment._selectionState, 0);
- delete segment._index;
- delete segment._path;
- }
- for (var i = from, l = segments.length; i < l; i++)
- segments[i]._index = i;
- if (curves) {
- var index = from > 0 && to === count + (this._closed ? 1 : 0)
- ? from - 1
- : from,
- curves = curves.splice(index, amount);
- if (arguments[2])
- removed._curves = curves.slice(1);
- this._adjustCurves(index, index);
- }
- this._changed(5);
- return removed;
- },
-
- clear: '#removeSegments',
-
- isFullySelected: function() {
- var length = this._segments.length;
- return this._selected && length > 0 && this._selectedSegmentState
- === length * 4;
- },
-
- setFullySelected: function(selected) {
- if (selected)
- this._selectSegments(true);
- this.setSelected(selected);
- },
-
- setSelected: function setSelected(selected) {
- if (!selected)
- this._selectSegments(false);
- setSelected.base.call(this, selected);
- },
-
- _selectSegments: function(selected) {
- var length = this._segments.length;
- this._selectedSegmentState = selected
- ? length * 4 : 0;
- for (var i = 0; i < length; i++)
- this._segments[i]._selectionState = selected
- ? 4 : 0;
- },
-
- _updateSelection: function(segment, oldState, newState) {
- segment._selectionState = newState;
- var total = this._selectedSegmentState += newState - oldState;
- if (total > 0)
- this.setSelected(true);
- },
-
- flatten: function(maxDistance) {
- var flattener = new PathFlattener(this),
- pos = 0,
- step = flattener.length / Math.ceil(flattener.length / maxDistance),
- end = flattener.length + (this._closed ? -step : step) / 2;
- var segments = [];
- while (pos <= end) {
- segments.push(new Segment(flattener.evaluate(pos, 0)));
- pos += step;
- }
- this.setSegments(segments);
- },
-
- simplify: function(tolerance) {
- if (this._segments.length > 2) {
- var fitter = new PathFitter(this, tolerance || 2.5);
- this.setSegments(fitter.fit());
- }
- },
-
- split: function(index, parameter) {
- if (parameter === null)
- return;
- if (arguments.length === 1) {
- var arg = index;
- if (typeof arg === 'number')
- arg = this.getLocationAt(arg);
- index = arg.index;
- parameter = arg.parameter;
- }
- if (parameter >= 1) {
- index++;
- parameter--;
- }
- var curves = this.getCurves();
- if (index >= 0 && index < curves.length) {
- if (parameter > 0) {
- curves[index++].divide(parameter, true);
- }
- var segs = this.removeSegments(index, this._segments.length, true),
- path;
- if (this._closed) {
- this.setClosed(false);
- path = this;
- } else if (index > 0) {
- path = this._clone(new Path().insertAbove(this, true));
- }
- path._add(segs, 0);
- this.addSegment(segs[0]);
- return path;
- }
- return null;
- },
-
- isClockwise: function() {
- if (this._clockwise !== undefined)
- return this._clockwise;
- return Path.isClockwise(this._segments);
- },
-
- setClockwise: function(clockwise) {
- if (this.isClockwise() != (clockwise = !!clockwise))
- this.reverse();
- this._clockwise = clockwise;
- },
-
- reverse: function() {
- this._segments.reverse();
- for (var i = 0, l = this._segments.length; i < l; i++) {
- var segment = this._segments[i];
- var handleIn = segment._handleIn;
- segment._handleIn = segment._handleOut;
- segment._handleOut = handleIn;
- segment._index = i;
- }
- delete this._curves;
- if (this._clockwise !== undefined)
- this._clockwise = !this._clockwise;
- },
-
- join: function(path) {
- if (path) {
- var segments = path._segments,
- last1 = this.getLastSegment(),
- last2 = path.getLastSegment();
- if (last1._point.equals(last2._point))
- path.reverse();
- var first1,
- first2 = path.getFirstSegment();
- if (last1._point.equals(first2._point)) {
- last1.setHandleOut(first2._handleOut);
- this._add(segments.slice(1));
- } else {
- first1 = this.getFirstSegment();
- if (first1._point.equals(first2._point))
- path.reverse();
- last2 = path.getLastSegment();
- if (first1._point.equals(last2._point)) {
- first1.setHandleIn(last2._handleIn);
- this._add(segments.slice(0, segments.length - 1), 0);
- } else {
- this._add(segments.slice());
- }
- }
- if (path.closed)
- this._add([segments[0]]);
- path.remove();
- first1 = this.getFirstSegment();
- last1 = this.getLastSegment();
- if (last1._point.equals(first1._point)) {
- first1.setHandleIn(last1._handleIn);
- last1.remove();
- this.setClosed(true);
- }
- this._changed(5);
- return true;
- }
- return false;
- },
-
- getLength: function() {
- if (this._length == null) {
- var curves = this.getCurves();
- this._length = 0;
- for (var i = 0, l = curves.length; i < l; i++)
- this._length += curves[i].getLength();
- }
- return this._length;
- },
-
- getArea: function() {
- var curves = this.getCurves();
- var area = 0;
- for (var i = 0, l = curves.length; i < l; i++)
- area += curves[i].getArea();
- return area;
- },
-
- _getOffset: function(location) {
- var index = location && location.getIndex();
- if (index != null) {
- var curves = this.getCurves(),
- offset = 0;
- for (var i = 0; i < index; i++)
- offset += curves[i].getLength();
- var curve = curves[index];
- return offset + curve.getLength(0, location.getParameter());
- }
- return null;
- },
-
- getLocationOf: function(point) {
- point = Point.read(arguments);
- var curves = this.getCurves();
- for (var i = 0, l = curves.length; i < l; i++) {
- var loc = curves[i].getLocationOf(point);
- if (loc)
- return loc;
- }
- return null;
- },
-
- getLocationAt: function(offset, isParameter) {
- var curves = this.getCurves(),
- length = 0;
- if (isParameter) {
- var index = ~~offset;
- return curves[index].getLocationAt(offset - index, true);
- }
- for (var i = 0, l = curves.length; i < l; i++) {
- var start = length,
- curve = curves[i];
- length += curve.getLength();
- if (length >= offset) {
- return curve.getLocationAt(offset - start);
- }
- }
- if (offset <= this.getLength())
- return new CurveLocation(curves[curves.length - 1], 1);
- return null;
- },
-
- getPointAt: function(offset, isParameter) {
- var loc = this.getLocationAt(offset, isParameter);
- return loc && loc.getPoint();
- },
-
- getTangentAt: function(offset, isParameter) {
- var loc = this.getLocationAt(offset, isParameter);
- return loc && loc.getTangent();
- },
-
- getNormalAt: function(offset, isParameter) {
- var loc = this.getLocationAt(offset, isParameter);
- return loc && loc.getNormal();
- },
-
- getNearestLocation: function(point) {
- point = Point.read(arguments);
- var curves = this.getCurves(),
- minDist = Infinity,
- minLoc = null;
- for (var i = 0, l = curves.length; i < l; i++) {
- var loc = curves[i].getNearestLocation(point);
- if (loc._distance < minDist) {
- minDist = loc._distance;
- minLoc = loc;
- }
- }
- return minLoc;
- },
-
- getNearestPoint: function(point) {
- point = Point.read(arguments);
- return this.getNearestLocation(point).getPoint();
- },
-
- getStyle: function() {
- var parent = this._parent;
- return (parent && parent._type === 'compound-path'
- ? parent : this)._style;
- },
-
- toShape: function(insert) {
- if (!this._closed)
- return null;
-
- var segments = this._segments,
- type,
- size,
- radius,
- topCenter;
-
- function isColinear(i, j) {
- return segments[i].isColinear(segments[j]);
- }
-
- function isOrthogonal(i) {
- return segments[i].isOrthogonal();
- }
-
- function isArc(i) {
- return segments[i].isArc();
- }
-
- function getDistance(i, j) {
- return segments[i]._point.getDistance(segments[j]._point);
- }
-
- if (this.isPolygon() && segments.length === 4
- && isColinear(0, 2) && isColinear(1, 3) && isOrthogonal(1)) {
- type = Shape.Rectangle;
- size = new Size(getDistance(0, 3), getDistance(0, 1));
- topCenter = segments[1]._point.add(segments[2]._point).divide(2);
- } else if (segments.length === 8 && isArc(0) && isArc(2) && isArc(4)
- && isArc(6) && isColinear(1, 5) && isColinear(3, 7)) {
- type = Shape.Rectangle;
- size = new Size(getDistance(1, 6), getDistance(0, 3));
- radius = size.subtract(new Size(getDistance(0, 7),
- getDistance(1, 2))).divide(2);
- topCenter = segments[3]._point.add(segments[4]._point).divide(2);
- } else if (segments.length === 4
- && isArc(0) && isArc(1) && isArc(2) && isArc(3)) {
- if (Numerical.isZero(getDistance(0, 2) - getDistance(1, 3))) {
- type = Shape.Circle;
- radius = getDistance(0, 2) / 2;
- } else {
- type = Shape.Ellipse;
- radius = new Size(getDistance(2, 0) / 2, getDistance(3, 1) / 2);
- }
- topCenter = segments[1]._point;
- }
-
- if (type) {
- var center = this.getPosition(true),
- shape = new type({
- center: center,
- size: size,
- radius: radius,
- insert: false
- });
- shape.rotate(topCenter.subtract(center).getAngle() + 90);
- shape.setStyle(this._style);
- if (insert || insert === undefined)
- shape.insertAbove(this);
- return shape;
- }
- return null;
- },
-
- _getWinding: function(point) {
- var closed = this._closed;
- if (!closed && !this.hasFill()
- || !this._getBounds('getRoughBounds')._containsPoint(point))
- return 0;
- var curves = this.getCurves(),
- segments = this._segments,
- winding = 0,
- roots1 = [],
- roots2 = [],
- last = (closed
- ? curves[curves.length - 1]
- : new Curve(segments[segments.length - 1]._point,
- segments[0]._point)).getValues(),
- previous = last;
- for (var i = 0, l = curves.length; i < l; i++) {
- var curve = curves[i].getValues(),
- x = curve[0],
- y = curve[1];
- if (!(x === curve[2] && y === curve[3] && x === curve[4]
- && y === curve[5] && x === curve[6] && y === curve[7])) {
- winding += Curve._getWinding(curve, previous, point.x, point.y,
- roots1, roots2);
- previous = curve;
- }
- }
- if (!closed) {
- winding += Curve._getWinding(last, previous, point.x, point.y,
- roots1, roots2);
- }
- return winding;
- },
-
- _hitTest: function(point, options) {
- var style = this.getStyle(),
- segments = this._segments,
- closed = this._closed,
- tolerance = options.tolerance,
- radius = 0, join, cap, miterLimit,
- that = this,
- area, loc, res;
-
- if (options.stroke) {
- radius = style.getStrokeWidth() / 2;
- if (radius > 0) {
- join = style.getStrokeJoin();
- cap = style.getStrokeCap();
- miterLimit = radius * style.getMiterLimit();
- } else {
- join = cap = 'round';
- }
- radius += tolerance;
- }
-
- function checkPoint(seg, pt, name) {
- if (point.getDistance(pt) < tolerance)
- return new HitResult(name, that, { segment: seg, point: pt });
- }
-
- function checkSegmentPoints(seg, ends) {
- var pt = seg._point;
- return (ends || options.segments) && checkPoint(seg, pt, 'segment')
- || (!ends && options.handles) && (
- checkPoint(seg, pt.add(seg._handleIn), 'handle-in') ||
- checkPoint(seg, pt.add(seg._handleOut), 'handle-out'));
- }
-
- function addAreaPoint(point) {
- area.push(point);
- }
-
- function getAreaCurve(index) {
- var p1 = area[index],
- p2 = area[(index + 1) % area.length];
- return [p1.x, p1.y, p1.x, p1.y, p2.x, p2.y, p2.x ,p2.y];
- }
-
- function isInArea(point) {
- var length = area.length,
- previous = getAreaCurve(length - 1),
- roots1 = [],
- roots2 = [],
- winding = 0;
- for (var i = 0; i < length; i++) {
- var curve = getAreaCurve(i);
- winding += Curve._getWinding(curve, previous, point.x, point.y,
- roots1, roots2);
- previous = curve;
- }
- return !!winding;
- }
-
- function checkSegmentStroke(segment) {
- if (join !== 'round' || cap !== 'round') {
- area = [];
- if (closed || segment._index > 0
- && segment._index < segments.length - 1) {
- if (join !== 'round' && (segment._handleIn.isZero()
- || segment._handleOut.isZero()))
- Path._addSquareJoin(segment, join, radius, miterLimit,
- addAreaPoint, true);
- } else if (cap !== 'round') {
- Path._addSquareCap(segment, cap, radius, addAreaPoint, true);
- }
- if (area.length > 0)
- return isInArea(point);
- }
- return point.getDistance(segment._point) <= radius;
- }
-
- if (options.ends && !options.segments && !closed) {
- if (res = checkSegmentPoints(segments[0], true)
- || checkSegmentPoints(segments[segments.length - 1], true))
- return res;
- } else if (options.segments || options.handles) {
- for (var i = 0, l = segments.length; i < l; i++) {
- if (res = checkSegmentPoints(segments[i]))
- return res;
- }
- }
- if (radius > 0) {
- loc = this.getNearestLocation(point);
- if (loc) {
- var parameter = loc.getParameter();
- if (parameter === 0 || parameter === 1) {
- if (!checkSegmentStroke(loc.getSegment()))
- loc = null;
- } else if (loc._distance > radius) {
- loc = null;
- }
- }
- if (!loc && join === 'miter') {
- for (var i = 0, l = segments.length; i < l; i++) {
- var segment = segments[i];
- if (point.getDistance(segment._point) <= miterLimit
- && checkSegmentStroke(segment)) {
- loc = segment.getLocation();
- break;
- }
- }
- }
- }
- return !loc && options.fill && this.hasFill() && this._contains(point)
- ? new HitResult('fill', this)
- : loc
- ? new HitResult('stroke', this, { location: loc })
- : null;
- }
-
-}, new function() {
-
- function drawHandles(ctx, segments, matrix, size) {
- var half = size / 2;
-
- function drawHandle(index) {
- var hX = coords[index],
- hY = coords[index + 1];
- if (pX != hX || pY != hY) {
- ctx.beginPath();
- ctx.moveTo(pX, pY);
- ctx.lineTo(hX, hY);
- ctx.stroke();
- ctx.beginPath();
- ctx.arc(hX, hY, half, 0, Math.PI * 2, true);
- ctx.fill();
- }
- }
-
- var coords = new Array(6);
- for (var i = 0, l = segments.length; i < l; i++) {
- var segment = segments[i];
- segment._transformCoordinates(matrix, coords, false);
- var state = segment._selectionState,
- selected = state & 4,
- pX = coords[0],
- pY = coords[1];
- if (selected || (state & 1))
- drawHandle(2);
- if (selected || (state & 2))
- drawHandle(4);
- ctx.save();
- ctx.beginPath();
- ctx.rect(pX - half, pY - half, size, size);
- ctx.fill();
- if (!selected) {
- ctx.beginPath();
- ctx.rect(pX - half + 1, pY - half + 1, size - 2, size - 2);
- ctx.fillStyle = '#ffffff';
- ctx.fill();
- }
- ctx.restore();
- }
- }
-
- function drawSegments(ctx, path, matrix) {
- var segments = path._segments,
- length = segments.length,
- coords = new Array(6),
- first = true,
- curX, curY,
- prevX, prevY,
- inX, inY,
- outX, outY;
-
- function drawSegment(i) {
- var segment = segments[i];
- if (matrix) {
- segment._transformCoordinates(matrix, coords, false);
- curX = coords[0];
- curY = coords[1];
- } else {
- var point = segment._point;
- curX = point._x;
- curY = point._y;
- }
- if (first) {
- ctx.moveTo(curX, curY);
- first = false;
- } else {
- if (matrix) {
- inX = coords[2];
- inY = coords[3];
- } else {
- var handle = segment._handleIn;
- inX = curX + handle._x;
- inY = curY + handle._y;
- }
- if (inX == curX && inY == curY && outX == prevX && outY == prevY) {
- ctx.lineTo(curX, curY);
- } else {
- ctx.bezierCurveTo(outX, outY, inX, inY, curX, curY);
- }
- }
- prevX = curX;
- prevY = curY;
- if (matrix) {
- outX = coords[4];
- outY = coords[5];
- } else {
- var handle = segment._handleOut;
- outX = prevX + handle._x;
- outY = prevY + handle._y;
- }
- }
-
- for (var i = 0; i < length; i++)
- drawSegment(i);
- if (path._closed && length > 1)
- drawSegment(0);
- }
-
- return {
- _draw: function(ctx, param) {
- var clip = param.clip,
- compound = param.compound;
- if (!compound)
- ctx.beginPath();
-
- var style = this.getStyle(),
- hasFill = style.hasFill(),
- hasStroke = style.hasStroke(),
- dashArray = style.getDashArray(),
- dashLength = !paper.support.nativeDash && hasStroke
- && dashArray && dashArray.length;
-
- function getOffset(i) {
- return dashArray[((i % dashLength) + dashLength) % dashLength];
- }
-
- if (hasFill || hasStroke && !dashLength || compound || clip)
- drawSegments(ctx, this);
- if (this._closed)
- ctx.closePath();
-
- if (!clip && !compound && (hasFill || hasStroke)) {
- this._setStyles(ctx);
- if (hasFill) {
- ctx.fill(style.getWindingRule());
- ctx.shadowColor = 'rgba(0,0,0,0)';
- }
- if (hasStroke) {
- if (dashLength) {
- ctx.beginPath();
- var flattener = new PathFlattener(this),
- length = flattener.length,
- from = -style.getDashOffset(), to,
- i = 0;
- from = from % length;
- while (from > 0) {
- from -= getOffset(i--) + getOffset(i--);
- }
- while (from < length) {
- to = from + getOffset(i++);
- if (from > 0 || to > 0)
- flattener.drawPart(ctx,
- Math.max(from, 0), Math.max(to, 0));
- from = to + getOffset(i++);
- }
- }
- ctx.stroke();
- }
- }
- },
-
- _drawSelected: function(ctx, matrix) {
- ctx.beginPath();
- drawSegments(ctx, this, matrix);
- ctx.stroke();
- drawHandles(ctx, this._segments, matrix,
- this._project.options.handleSize || 4);
- }
- };
-}, new function() {
-
- function getFirstControlPoints(rhs) {
- var n = rhs.length,
- x = [],
- tmp = [],
- b = 2;
- x[0] = rhs[0] / b;
- for (var i = 1; i < n; i++) {
- tmp[i] = 1 / b;
- b = (i < n - 1 ? 4 : 2) - tmp[i];
- x[i] = (rhs[i] - x[i - 1]) / b;
- }
- for (var i = 1; i < n; i++) {
- x[n - i - 1] -= tmp[n - i] * x[n - i];
- }
- return x;
- }
-
- return {
- smooth: function() {
- var segments = this._segments,
- size = segments.length,
- closed = this._closed,
- n = size,
- overlap = 0;
- if (size <= 2)
- return;
- if (closed) {
- overlap = Math.min(size, 4);
- n += Math.min(size, overlap) * 2;
- }
- var knots = [];
- for (var i = 0; i < size; i++)
- knots[i + overlap] = segments[i]._point;
- if (closed) {
- for (var i = 0; i < overlap; i++) {
- knots[i] = segments[i + size - overlap]._point;
- knots[i + size + overlap] = segments[i]._point;
- }
- } else {
- n--;
- }
- var rhs = [];
-
- for (var i = 1; i < n - 1; i++)
- rhs[i] = 4 * knots[i]._x + 2 * knots[i + 1]._x;
- rhs[0] = knots[0]._x + 2 * knots[1]._x;
- rhs[n - 1] = 3 * knots[n - 1]._x;
- var x = getFirstControlPoints(rhs);
-
- for (var i = 1; i < n - 1; i++)
- rhs[i] = 4 * knots[i]._y + 2 * knots[i + 1]._y;
- rhs[0] = knots[0]._y + 2 * knots[1]._y;
- rhs[n - 1] = 3 * knots[n - 1]._y;
- var y = getFirstControlPoints(rhs);
-
- if (closed) {
- for (var i = 0, j = size; i < overlap; i++, j++) {
- var f1 = i / overlap,
- f2 = 1 - f1,
- ie = i + overlap,
- je = j + overlap;
- x[j] = x[i] * f1 + x[j] * f2;
- y[j] = y[i] * f1 + y[j] * f2;
- x[je] = x[ie] * f2 + x[je] * f1;
- y[je] = y[ie] * f2 + y[je] * f1;
- }
- n--;
- }
- var handleIn = null;
- for (var i = overlap; i <= n - overlap; i++) {
- var segment = segments[i - overlap];
- if (handleIn)
- segment.setHandleIn(handleIn.subtract(segment._point));
- if (i < n) {
- segment.setHandleOut(
- new Point(x[i], y[i]).subtract(segment._point));
- handleIn = i < n - 1
- ? new Point(
- 2 * knots[i + 1]._x - x[i + 1],
- 2 * knots[i + 1]._y - y[i + 1])
- : new Point(
- (knots[n]._x + x[n - 1]) / 2,
- (knots[n]._y + y[n - 1]) / 2);
- }
- }
- if (closed && handleIn) {
- var segment = this._segments[0];
- segment.setHandleIn(handleIn.subtract(segment._point));
- }
- }
- };
-}, new function() {
- function getCurrentSegment(that) {
- var segments = that._segments;
- if (segments.length == 0)
- throw new Error('Use a moveTo() command first');
- return segments[segments.length - 1];
- }
-
- return {
- moveTo: function() {
- if (this._segments.length === 1)
- this.removeSegment(0);
- if (!this._segments.length)
- this._add([ new Segment(Point.read(arguments)) ]);
- },
-
- moveBy: function() {
- throw new Error('moveBy() is unsupported on Path items.');
- },
-
- lineTo: function() {
- this._add([ new Segment(Point.read(arguments)) ]);
- },
-
- cubicCurveTo: function() {
- var handle1 = Point.read(arguments),
- handle2 = Point.read(arguments),
- to = Point.read(arguments),
- current = getCurrentSegment(this);
- current.setHandleOut(handle1.subtract(current._point));
- this._add([ new Segment(to, handle2.subtract(to)) ]);
- },
-
- quadraticCurveTo: function() {
- var handle = Point.read(arguments),
- to = Point.read(arguments),
- current = getCurrentSegment(this)._point;
- this.cubicCurveTo(
- handle.add(current.subtract(handle).multiply(1 / 3)),
- handle.add(to.subtract(handle).multiply(1 / 3)),
- to
- );
- },
-
- curveTo: function() {
- var through = Point.read(arguments),
- to = Point.read(arguments),
- t = Base.pick(Base.read(arguments), 0.5),
- t1 = 1 - t,
- current = getCurrentSegment(this)._point,
- handle = through.subtract(current.multiply(t1 * t1))
- .subtract(to.multiply(t * t)).divide(2 * t * t1);
- if (handle.isNaN())
- throw new Error(
- 'Cannot put a curve through points with parameter = ' + t);
- this.quadraticCurveTo(handle, to);
- },
-
- arcTo: function() {
- var current = getCurrentSegment(this),
- from = current._point,
- through,
- to = Point.read(arguments),
- clockwise = Base.pick(Base.peek(arguments), true);
- if (typeof clockwise === 'boolean') {
- var middle = from.add(to).divide(2),
- through = middle.add(middle.subtract(from).rotate(
- clockwise ? -90 : 90));
- } else {
- through = to;
- to = Point.read(arguments);
- }
- var l1 = new Line(from.add(through).divide(2),
- through.subtract(from).rotate(90), true),
- l2 = new Line(through.add(to).divide(2),
- to.subtract(through).rotate(90), true),
- center = l1.intersect(l2, true),
- line = new Line(from, to),
- throughSide = line.getSide(through);
- if (!center) {
- if (!throughSide)
- return this.lineTo(to);
- throw new Error('Cannot put an arc through the given points: '
- + [from, through, to]);
- }
- var vector = from.subtract(center),
- extent = vector.getDirectedAngle(to.subtract(center)),
- centerSide = line.getSide(center);
- if (centerSide == 0) {
- extent = throughSide * Math.abs(extent);
- } else if (throughSide == centerSide) {
- extent -= 360 * (extent < 0 ? -1 : 1);
- }
- var ext = Math.abs(extent),
- count = ext >= 360 ? 4 : Math.ceil(ext / 90),
- inc = extent / count,
- half = inc * Math.PI / 360,
- z = 4 / 3 * Math.sin(half) / (1 + Math.cos(half)),
- segments = [];
- for (var i = 0; i <= count; i++) {
- var pt = i < count ? center.add(vector) : to;
- var out = i < count ? vector.rotate(90).multiply(z) : null;
- if (i == 0) {
- current.setHandleOut(out);
- } else {
- segments.push(
- new Segment(pt, vector.rotate(-90).multiply(z), out));
- }
- vector = vector.rotate(inc);
- }
- this._add(segments);
- },
-
- lineBy: function() {
- var to = Point.read(arguments),
- current = getCurrentSegment(this)._point;
- this.lineTo(current.add(to));
- },
-
- curveBy: function() {
- var through = Point.read(arguments),
- to = Point.read(arguments),
- parameter = Base.read(arguments),
- current = getCurrentSegment(this)._point;
- this.curveTo(current.add(through), current.add(to), parameter);
- },
-
- cubicCurveBy: function() {
- var handle1 = Point.read(arguments),
- handle2 = Point.read(arguments),
- to = Point.read(arguments),
- current = getCurrentSegment(this)._point;
- this.cubicCurveTo(current.add(handle1), current.add(handle2),
- current.add(to));
- },
-
- quadraticCurveBy: function() {
- var handle = Point.read(arguments),
- to = Point.read(arguments),
- current = getCurrentSegment(this)._point;
- this.quadraticCurveTo(current.add(handle), current.add(to));
- },
-
- arcBy: function() {
- var current = getCurrentSegment(this)._point,
- point = current.add(Point.read(arguments)),
- clockwise = Base.pick(Base.peek(arguments), true);
- if (typeof clockwise === 'boolean') {
- this.arcTo(point, clockwise);
- } else {
- this.arcTo(point, current.add(Point.read(arguments)));
- }
- },
-
- closePath: function() {
- var first = this.getFirstSegment(),
- last = this.getLastSegment();
- if (first._point.equals(last._point)) {
- first.setHandleIn(last._handleIn);
- last.remove();
- }
- this.setClosed(true);
- }
- };
-}, {
-
- _getBounds: function(getter, matrix) {
- return Path[getter](this._segments, this._closed, this.getStyle(),
- matrix);
- },
-
-statics: {
- isClockwise: function(segments) {
- var sum = 0;
- for (var i = 0, l = segments.length; i < l; i++) {
- var v = Curve.getValues(
- segments[i], segments[i + 1 < l ? i + 1 : 0]);
- for (var j = 2; j < 8; j += 2)
- sum += (v[j - 2] - v[j]) * (v[j + 1] + v[j - 1]);
- }
- return sum > 0;
- },
-
- getBounds: function(segments, closed, style, matrix, strokePadding) {
- var first = segments[0];
- if (!first)
- return new Rectangle();
- var coords = new Array(6),
- prevCoords = first._transformCoordinates(matrix, new Array(6), false),
- min = prevCoords.slice(0, 2),
- max = min.slice(),
- roots = new Array(2);
-
- function processSegment(segment) {
- segment._transformCoordinates(matrix, coords, false);
- for (var i = 0; i < 2; i++) {
- Curve._addBounds(
- prevCoords[i],
- prevCoords[i + 4],
- coords[i + 2],
- coords[i],
- i, strokePadding ? strokePadding[i] : 0, min, max, roots);
- }
- var tmp = prevCoords;
- prevCoords = coords;
- coords = tmp;
- }
-
- for (var i = 1, l = segments.length; i < l; i++)
- processSegment(segments[i]);
- if (closed)
- processSegment(first);
- return new Rectangle(min[0], min[1], max[0] - min[0], max[1] - min[1]);
- },
-
- getStrokeBounds: function(segments, closed, style, matrix) {
- function getPenPadding(radius, matrix) {
- if (!matrix)
- return [radius, radius];
- var mx = matrix.shiftless(),
- hor = mx.transform(new Point(radius, 0)),
- ver = mx.transform(new Point(0, radius)),
- phi = hor.getAngleInRadians(),
- a = hor.getLength(),
- b = ver.getLength();
- var sin = Math.sin(phi),
- cos = Math.cos(phi),
- tan = Math.tan(phi),
- tx = -Math.atan(b * tan / a),
- ty = Math.atan(b / (tan * a));
- return [Math.abs(a * Math.cos(tx) * cos - b * Math.sin(tx) * sin),
- Math.abs(b * Math.sin(ty) * cos + a * Math.cos(ty) * sin)];
- }
-
- if (!style.hasStroke())
- return Path.getBounds(segments, closed, style, matrix);
- var length = segments.length - (closed ? 0 : 1),
- radius = style.getStrokeWidth() / 2,
- padding = getPenPadding(radius, matrix),
- bounds = Path.getBounds(segments, closed, style, matrix, padding),
- join = style.getStrokeJoin(),
- cap = style.getStrokeCap(),
- miterLimit = radius * style.getMiterLimit();
- var joinBounds = new Rectangle(new Size(padding).multiply(2));
-
- function add(point) {
- bounds = bounds.include(matrix
- ? matrix._transformPoint(point, point) : point);
- }
-
- function addJoin(segment, join) {
- if (join === 'round' || !segment._handleIn.isZero()
- && !segment._handleOut.isZero()) {
- bounds = bounds.unite(joinBounds.setCenter(matrix
- ? matrix._transformPoint(segment._point) : segment._point));
- } else {
- Path._addSquareJoin(segment, join, radius, miterLimit, add);
- }
- }
-
- function addCap(segment, cap) {
- switch (cap) {
- case 'round':
- addJoin(segment, cap);
- break;
- case 'butt':
- case 'square':
- Path._addSquareCap(segment, cap, radius, add);
- break;
- }
- }
-
- for (var i = 1; i < length; i++)
- addJoin(segments[i], join);
- if (closed) {
- addJoin(segments[0], join);
- } else {
- addCap(segments[0], cap);
- addCap(segments[segments.length - 1], cap);
- }
- return bounds;
- },
-
- _addSquareJoin: function(segment, join, radius, miterLimit, addPoint, area) {
- var curve2 = segment.getCurve(),
- curve1 = curve2.getPrevious(),
- point = curve2.getPointAt(0, true),
- normal1 = curve1.getNormalAt(1, true),
- normal2 = curve2.getNormalAt(0, true),
- step = normal1.getDirectedAngle(normal2) < 0 ? -radius : radius;
- normal1.setLength(step);
- normal2.setLength(step);
- if (area) {
- addPoint(point);
- addPoint(point.add(normal1));
- }
- if (join === 'miter') {
- var corner = new Line(
- point.add(normal1),
- new Point(-normal1.y, normal1.x), true
- ).intersect(new Line(
- point.add(normal2),
- new Point(-normal2.y, normal2.x), true
- ), true);
- if (corner && point.getDistance(corner) <= miterLimit) {
- addPoint(corner);
- if (!area)
- return;
- }
- }
- if (!area)
- addPoint(point.add(normal1));
- addPoint(point.add(normal2));
- },
-
- _addSquareCap: function(segment, cap, radius, addPoint, area) {
- var point = segment._point,
- loc = segment.getLocation(),
- normal = loc.getNormal().normalize(radius);
- if (area) {
- addPoint(point.subtract(normal));
- addPoint(point.add(normal));
- }
- if (cap === 'square')
- point = point.add(normal.rotate(loc.getParameter() == 0 ? -90 : 90));
- addPoint(point.add(normal));
- addPoint(point.subtract(normal));
- },
-
- getHandleBounds: function(segments, closed, style, matrix, strokePadding,
- joinPadding) {
- var coords = new Array(6),
- x1 = Infinity,
- x2 = -x1,
- y1 = x1,
- y2 = x2;
- strokePadding = strokePadding / 2 || 0;
- joinPadding = joinPadding / 2 || 0;
- for (var i = 0, l = segments.length; i < l; i++) {
- var segment = segments[i];
- segment._transformCoordinates(matrix, coords, false);
- for (var j = 0; j < 6; j += 2) {
- var padding = j == 0 ? joinPadding : strokePadding,
- x = coords[j],
- y = coords[j + 1],
- xn = x - padding,
- xx = x + padding,
- yn = y - padding,
- yx = y + padding;
- if (xn < x1) x1 = xn;
- if (xx > x2) x2 = xx;
- if (yn < y1) y1 = yn;
- if (yx > y2) y2 = yx;
- }
- }
- return new Rectangle(x1, y1, x2 - x1, y2 - y1);
- },
-
- getRoughBounds: function(segments, closed, style, matrix) {
- var strokeWidth = style.getStrokeColor() ? style.getStrokeWidth() : 0,
- joinWidth = strokeWidth;
- if (strokeWidth === 0) {
- strokeWidth = 0.00001;
- } else {
- if (style.getStrokeJoin() === 'miter')
- joinWidth = strokeWidth * style.getMiterLimit();
- if (style.getStrokeCap() === 'square')
- joinWidth = Math.max(joinWidth, strokeWidth * Math.sqrt(2));
- }
- return Path.getHandleBounds(segments, closed, style, matrix,
- strokeWidth, joinWidth);
- }
-}});
-
-Path.inject({ statics: new function() {
-
- var kappa = Numerical.KAPPA,
- ellipseSegments = [
- new Segment([-1, 0], [0, kappa ], [0, -kappa]),
- new Segment([0, -1], [-kappa, 0], [kappa, 0 ]),
- new Segment([1, 0], [0, -kappa], [0, kappa ]),
- new Segment([0, 1], [kappa, 0 ], [-kappa, 0])
- ];
-
- function createEllipse(center, radius, args) {
- var path = new Path(),
- segments = new Array(4);
- for (var i = 0; i < 4; i++) {
- var segment = ellipseSegments[i];
- segments[i] = new Segment(
- segment._point.multiply(radius).add(center),
- segment._handleIn.multiply(radius),
- segment._handleOut.multiply(radius)
- );
- }
- path._add(segments);
- path._closed = true;
- return path.set(Base.getNamed(args));
- }
-
- return {
- Line: function() {
- return new Path(
- Point.readNamed(arguments, 'from'),
- Point.readNamed(arguments, 'to')
- ).set(Base.getNamed(arguments));
- },
-
- Circle: function() {
- var center = Point.readNamed(arguments, 'center'),
- radius = Base.readNamed(arguments, 'radius');
- return createEllipse(center, new Size(radius), arguments);
- },
-
- Rectangle: function() {
- var rect = Rectangle.readNamed(arguments, 'rectangle'),
- radius = Size.readNamed(arguments, 'radius', 0, 0,
- { readNull: true }),
- bl = rect.getBottomLeft(true),
- tl = rect.getTopLeft(true),
- tr = rect.getTopRight(true),
- br = rect.getBottomRight(true);
- path = new Path();
- if (!radius || radius.isZero()) {
- path._add([
- new Segment(bl),
- new Segment(tl),
- new Segment(tr),
- new Segment(br)
- ]);
- } else {
- radius = Size.min(radius, rect.getSize(true).divide(2));
- var rx = radius.width,
- ry = radius.height,
- hx = rx * kappa,
- hy = ry * kappa;
- path._add([
- new Segment(bl.add(rx, 0), null, [-hx, 0]),
- new Segment(bl.subtract(0, ry), [0, hy]),
- new Segment(tl.add(0, ry), null, [0, -hy]),
- new Segment(tl.add(rx, 0), [-hx, 0], null),
- new Segment(tr.subtract(rx, 0), null, [hx, 0]),
- new Segment(tr.add(0, ry), [0, -hy], null),
- new Segment(br.subtract(0, ry), null, [0, hy]),
- new Segment(br.subtract(rx, 0), [hx, 0])
- ]);
- }
- path._closed = true;
- return path.set(Base.getNamed(arguments));
- },
-
- RoundRectangle: '#Rectangle',
-
- Ellipse: function() {
- var ellipse = Shape._readEllipse(arguments);
- return createEllipse(ellipse.center, ellipse.radius, arguments);
- },
-
- Oval: '#Ellipse',
-
- Arc: function() {
- var from = Point.readNamed(arguments, 'from'),
- through = Point.readNamed(arguments, 'through'),
- to = Point.readNamed(arguments, 'to'),
- path = new Path();
- path.moveTo(from);
- path.arcTo(through, to);
- return path.set(Base.getNamed(arguments));
- },
-
- RegularPolygon: function() {
- var center = Point.readNamed(arguments, 'center'),
- sides = Base.readNamed(arguments, 'sides'),
- radius = Base.readNamed(arguments, 'radius'),
- path = new Path(),
- step = 360 / sides,
- three = !(sides % 3),
- vector = new Point(0, three ? -radius : radius),
- offset = three ? -1 : 0.5,
- segments = new Array(sides);
- for (var i = 0; i < sides; i++) {
- segments[i] = new Segment(center.add(
- vector.rotate((i + offset) * step)));
- }
- path._add(segments);
- path._closed = true;
- return path.set(Base.getNamed(arguments));
- },
-
- Star: function() {
- var center = Point.readNamed(arguments, 'center'),
- points = Base.readNamed(arguments, 'points') * 2,
- radius1 = Base.readNamed(arguments, 'radius1'),
- radius2 = Base.readNamed(arguments, 'radius2'),
- path = new Path(),
- step = 360 / points,
- vector = new Point(0, -1),
- segments = new Array(points);
- for (var i = 0; i < points; i++) {
- segments[i] = new Segment(center.add(
- vector.rotate(step * i).multiply(i % 2 ? radius2 : radius1)));
- }
- path._add(segments);
- path._closed = true;
- return path.set(Base.getNamed(arguments));
- }
- };
-}});
-
-var CompoundPath = PathItem.extend({
- _class: 'CompoundPath',
- _serializeFields: {
- children: []
- },
-
- initialize: function CompoundPath(arg) {
- this._children = [];
- this._namedChildren = {};
- if (!this._initialize(arg))
- this.addChildren(Array.isArray(arg) ? arg : arguments);
- },
-
- insertChildren: function insertChildren(index, items, _preserve) {
- items = insertChildren.base.call(this, index, items, _preserve, 'path');
- for (var i = 0, l = !_preserve && items && items.length; i < l; i++) {
- var item = items[i];
- if (item._clockwise === undefined)
- item.setClockwise(item._index === 0);
- }
- return items;
- },
-
- reverse: function() {
- var children = this._children;
- for (var i = 0, l = children.length; i < l; i++)
- children[i].reverse();
- },
-
- smooth: function() {
- for (var i = 0, l = this._children.length; i < l; i++)
- this._children[i].smooth();
- },
-
- isClockwise: function() {
- var child = this.getFirstChild();
- return child && child.isClockwise();
- },
-
- setClockwise: function(clockwise) {
- if (this.isClockwise() != !!clockwise)
- this.reverse();
- },
-
- getFirstSegment: function() {
- var first = this.getFirstChild();
- return first && first.getFirstSegment();
- },
-
- getLastSegment: function() {
- var last = this.getLastChild();
- return last && last.getLastSegment();
- },
-
- getCurves: function() {
- var children = this._children,
- curves = [];
- for (var i = 0, l = children.length; i < l; i++)
- curves = curves.concat(children[i].getCurves());
- return curves;
- },
-
- getFirstCurve: function() {
- var first = this.getFirstChild();
- return first && first.getFirstCurve();
- },
-
- getLastCurve: function() {
- var last = this.getLastChild();
- return last && last.getFirstCurve();
- },
-
- getArea: function() {
- var children = this._children,
- area = 0;
- for (var i = 0, l = children.length; i < l; i++)
- area += children[i].getArea();
- return area;
- },
-
- getPathData: function() {
- var children = this._children,
- paths = [];
- for (var i = 0, l = children.length; i < l; i++)
- paths.push(children[i].getPathData(arguments[0]));
- return paths.join(' ');
- },
-
- _getWinding: function(point) {
- var children = this._children,
- winding = 0;
- for (var i = 0, l = children.length; i < l; i++)
- winding += children[i]._getWinding(point);
- return winding;
- },
-
- _hitTest : function _hitTest(point, options) {
- var res = _hitTest.base.call(this, point,
- new Base(options, { fill: false }));
- if (!res) {
- if (options.compoundChildren) {
- var children = this._children;
- for (var i = children.length - 1; i >= 0 && !res; i--)
- res = children[i]._hitTest(point, options);
- } else if (options.fill && this.hasFill()
- && this._contains(point)) {
- res = new HitResult('fill', this);
- }
- }
- return res;
- },
-
- _draw: function(ctx, param) {
- var children = this._children;
- if (children.length === 0)
- return;
-
- ctx.beginPath();
- param = param.extend({ compound: true });
- for (var i = 0, l = children.length; i < l; i++)
- children[i].draw(ctx, param);
-
- if (!param.clip) {
- this._setStyles(ctx);
- var style = this._style;
- if (style.hasFill()) {
- ctx.fill(style.getWindingRule());
- ctx.shadowColor = 'rgba(0,0,0,0)';
- }
- if (style.hasStroke())
- ctx.stroke();
- }
- }
-}, new function() {
- function getCurrentPath(that) {
- if (!that._children.length)
- throw new Error('Use a moveTo() command first');
- return that._children[that._children.length - 1];
- }
-
- var fields = {
- moveTo: function() {
- var path = new Path();
- this.addChild(path);
- path.moveTo.apply(path, arguments);
- },
-
- moveBy: function() {
- this.moveTo(getCurrentPath(this).getLastSegment()._point.add(
- Point.read(arguments)));
- },
-
- closePath: function() {
- getCurrentPath(this).closePath();
- }
- };
-
- Base.each(['lineTo', 'cubicCurveTo', 'quadraticCurveTo', 'curveTo', 'arcTo',
- 'lineBy', 'cubicCurveBy', 'quadraticCurveBy', 'curveBy', 'arcBy'],
- function(key) {
- fields[key] = function() {
- var path = getCurrentPath(this);
- path[key].apply(path, arguments);
- };
- }
- );
-
- return fields;
-});
-
-var PathFlattener = Base.extend({
- initialize: function(path) {
- this.curves = [];
- this.parts = [];
- this.length = 0;
- this.index = 0;
-
- var segments = path._segments,
- segment1 = segments[0],
- segment2,
- that = this;
-
- function addCurve(segment1, segment2) {
- var curve = Curve.getValues(segment1, segment2);
- that.curves.push(curve);
- that._computeParts(curve, segment1._index, 0, 1);
- }
-
- for (var i = 1, l = segments.length; i < l; i++) {
- segment2 = segments[i];
- addCurve(segment1, segment2);
- segment1 = segment2;
- }
- if (path._closed)
- addCurve(segment2, segments[0]);
- },
-
- _computeParts: function(curve, index, minT, maxT) {
- if ((maxT - minT) > 1 / 32 && !Curve.isFlatEnough(curve, 0.25)) {
- var curves = Curve.subdivide(curve);
- var halfT = (minT + maxT) / 2;
- this._computeParts(curves[0], index, minT, halfT);
- this._computeParts(curves[1], index, halfT, maxT);
- } else {
- var x = curve[6] - curve[0],
- y = curve[7] - curve[1],
- dist = Math.sqrt(x * x + y * y);
- if (dist > 0.00001) {
- this.length += dist;
- this.parts.push({
- offset: this.length,
- value: maxT,
- index: index
- });
- }
- }
- },
-
- getParameterAt: function(offset) {
- var i, j = this.index;
- for (;;) {
- i = j;
- if (j == 0 || this.parts[--j].offset < offset)
- break;
- }
- for (var l = this.parts.length; i < l; i++) {
- var part = this.parts[i];
- if (part.offset >= offset) {
- this.index = i;
- var prev = this.parts[i - 1];
- var prevVal = prev && prev.index == part.index ? prev.value : 0,
- prevLen = prev ? prev.offset : 0;
- return {
- value: prevVal + (part.value - prevVal)
- * (offset - prevLen) / (part.offset - prevLen),
- index: part.index
- };
- }
- }
- var part = this.parts[this.parts.length - 1];
- return {
- value: 1,
- index: part.index
- };
- },
-
- evaluate: function(offset, type) {
- var param = this.getParameterAt(offset);
- return Curve.evaluate(this.curves[param.index], param.value, type);
- },
-
- drawPart: function(ctx, from, to) {
- from = this.getParameterAt(from);
- to = this.getParameterAt(to);
- for (var i = from.index; i <= to.index; i++) {
- var curve = Curve.getPart(this.curves[i],
- i == from.index ? from.value : 0,
- i == to.index ? to.value : 1);
- if (i == from.index)
- ctx.moveTo(curve[0], curve[1]);
- ctx.bezierCurveTo.apply(ctx, curve.slice(2));
- }
- }
-});
-
-var PathFitter = Base.extend({
- initialize: function(path, error) {
- this.points = [];
- var segments = path._segments,
- prev;
- for (var i = 0, l = segments.length; i < l; i++) {
- var point = segments[i].point.clone();
- if (!prev || !prev.equals(point)) {
- this.points.push(point);
- prev = point;
- }
- }
- this.error = error;
- },
-
- fit: function() {
- var points = this.points,
- length = points.length;
- this.segments = length > 0 ? [new Segment(points[0])] : [];
- if (length > 1)
- this.fitCubic(0, length - 1,
- points[1].subtract(points[0]).normalize(),
- points[length - 2].subtract(points[length - 1]).normalize());
- return this.segments;
- },
-
- fitCubic: function(first, last, tan1, tan2) {
- if (last - first == 1) {
- var pt1 = this.points[first],
- pt2 = this.points[last],
- dist = pt1.getDistance(pt2) / 3;
- this.addCurve([pt1, pt1.add(tan1.normalize(dist)),
- pt2.add(tan2.normalize(dist)), pt2]);
- return;
- }
- var uPrime = this.chordLengthParameterize(first, last),
- maxError = Math.max(this.error, this.error * this.error),
- split;
- for (var i = 0; i <= 4; i++) {
- var curve = this.generateBezier(first, last, uPrime, tan1, tan2);
- var max = this.findMaxError(first, last, curve, uPrime);
- if (max.error < this.error) {
- this.addCurve(curve);
- return;
- }
- split = max.index;
- if (max.error >= maxError)
- break;
- this.reparameterize(first, last, uPrime, curve);
- maxError = max.error;
- }
- var V1 = this.points[split - 1].subtract(this.points[split]),
- V2 = this.points[split].subtract(this.points[split + 1]),
- tanCenter = V1.add(V2).divide(2).normalize();
- this.fitCubic(first, split, tan1, tanCenter);
- this.fitCubic(split, last, tanCenter.negate(), tan2);
- },
-
- addCurve: function(curve) {
- var prev = this.segments[this.segments.length - 1];
- prev.setHandleOut(curve[1].subtract(curve[0]));
- this.segments.push(
- new Segment(curve[3], curve[2].subtract(curve[3])));
- },
-
- generateBezier: function(first, last, uPrime, tan1, tan2) {
- var epsilon = 1e-11,
- pt1 = this.points[first],
- pt2 = this.points[last],
- C = [[0, 0], [0, 0]],
- X = [0, 0];
-
- for (var i = 0, l = last - first + 1; i < l; i++) {
- var u = uPrime[i],
- t = 1 - u,
- b = 3 * u * t,
- b0 = t * t * t,
- b1 = b * t,
- b2 = b * u,
- b3 = u * u * u,
- a1 = tan1.normalize(b1),
- a2 = tan2.normalize(b2),
- tmp = this.points[first + i]
- .subtract(pt1.multiply(b0 + b1))
- .subtract(pt2.multiply(b2 + b3));
- C[0][0] += a1.dot(a1);
- C[0][1] += a1.dot(a2);
- C[1][0] = C[0][1];
- C[1][1] += a2.dot(a2);
- X[0] += a1.dot(tmp);
- X[1] += a2.dot(tmp);
- }
-
- var detC0C1 = C[0][0] * C[1][1] - C[1][0] * C[0][1],
- alpha1, alpha2;
- if (Math.abs(detC0C1) > epsilon) {
- var detC0X = C[0][0] * X[1] - C[1][0] * X[0],
- detXC1 = X[0] * C[1][1] - X[1] * C[0][1];
- alpha1 = detXC1 / detC0C1;
- alpha2 = detC0X / detC0C1;
- } else {
- var c0 = C[0][0] + C[0][1],
- c1 = C[1][0] + C[1][1];
- if (Math.abs(c0) > epsilon) {
- alpha1 = alpha2 = X[0] / c0;
- } else if (Math.abs(c1) > epsilon) {
- alpha1 = alpha2 = X[1] / c1;
- } else {
- alpha1 = alpha2 = 0;
- }
- }
-
- var segLength = pt2.getDistance(pt1);
- epsilon *= segLength;
- if (alpha1 < epsilon || alpha2 < epsilon) {
- alpha1 = alpha2 = segLength / 3;
- }
-
- return [pt1, pt1.add(tan1.normalize(alpha1)),
- pt2.add(tan2.normalize(alpha2)), pt2];
- },
-
- reparameterize: function(first, last, u, curve) {
- for (var i = first; i <= last; i++) {
- u[i - first] = this.findRoot(curve, this.points[i], u[i - first]);
- }
- },
-
- findRoot: function(curve, point, u) {
- var curve1 = [],
- curve2 = [];
- for (var i = 0; i <= 2; i++) {
- curve1[i] = curve[i + 1].subtract(curve[i]).multiply(3);
- }
- for (var i = 0; i <= 1; i++) {
- curve2[i] = curve1[i + 1].subtract(curve1[i]).multiply(2);
- }
- var pt = this.evaluate(3, curve, u),
- pt1 = this.evaluate(2, curve1, u),
- pt2 = this.evaluate(1, curve2, u),
- diff = pt.subtract(point),
- df = pt1.dot(pt1) + diff.dot(pt2);
- if (Math.abs(df) < 0.00001)
- return u;
- return u - diff.dot(pt1) / df;
- },
-
- evaluate: function(degree, curve, t) {
- var tmp = curve.slice();
- for (var i = 1; i <= degree; i++) {
- for (var j = 0; j <= degree - i; j++) {
- tmp[j] = tmp[j].multiply(1 - t).add(tmp[j + 1].multiply(t));
- }
- }
- return tmp[0];
- },
-
- chordLengthParameterize: function(first, last) {
- var u = [0];
- for (var i = first + 1; i <= last; i++) {
- u[i - first] = u[i - first - 1]
- + this.points[i].getDistance(this.points[i - 1]);
- }
- for (var i = 1, m = last - first; i <= m; i++) {
- u[i] /= u[m];
- }
- return u;
- },
-
- findMaxError: function(first, last, curve, u) {
- var index = Math.floor((last - first + 1) / 2),
- maxDist = 0;
- for (var i = first + 1; i < last; i++) {
- var P = this.evaluate(3, curve, u[i - first]);
- var v = P.subtract(this.points[i]);
- var dist = v.x * v.x + v.y * v.y;
- if (dist >= maxDist) {
- maxDist = dist;
- index = i;
- }
- }
- return {
- error: maxDist,
- index: index
- };
- }
-});
-
-PathItem.inject(new function() {
-
- function splitPath(intersections, collectOthers) {
- intersections.sort(function(loc1, loc2) {
- var path1 = loc1.getPath(),
- path2 = loc2.getPath();
- return path1 === path2
- ? (loc1.getIndex() + loc1.getParameter())
- - (loc2.getIndex() + loc2.getParameter())
- : path1._id - path2._id;
- });
- var others = collectOthers && [];
- for (var i = intersections.length - 1; i >= 0; i--) {
- var loc = intersections[i],
- other = loc.getIntersection(),
- curve = loc.divide(),
- segment = curve && curve.getSegment1() || loc.getSegment();
- if (others)
- others.push(other);
- segment._intersection = other;
- loc._segment = segment;
- }
- return others;
- }
-
- function reorientPath(path) {
- if (path instanceof CompoundPath) {
- var children = path.removeChildren(),
- length = children.length,
- bounds = new Array(length),
- counters = new Array(length),
- clockwise;
- children.sort(function(a, b){
- var b1 = a.getBounds(), b2 = b.getBounds();
- return b1._width * b1._height < b2._width * b2._height;
- });
- path.addChildren(children);
- clockwise = children[0].isClockwise();
- for (var i = 0; i < length; i++) {
- bounds[i] = children[i].getBounds();
- counters[i] = 0;
- }
- for (var i = 0; i < length; i++) {
- for (var j = 1; j < length; j++) {
- if (i !== j && bounds[i].contains(bounds[j]))
- counters[j]++;
- }
- if (i > 0 && counters[i] % 2 === 0)
- children[i].setClockwise(clockwise);
- }
- }
- return path;
- }
-
- function computeBoolean(path1, path2, operator, subtract) {
- path1 = reorientPath(path1.clone(false));
- path2 = reorientPath(path2.clone(false));
- var path1Clockwise = path1.isClockwise(),
- path2Clockwise = path2.isClockwise(),
- intersections = path1.getIntersections(path2);
- splitPath(splitPath(intersections, true));
- if (!path1Clockwise)
- path1.reverse();
- if (!(subtract ^ path2Clockwise))
- path2.reverse();
- path1Clockwise = true;
- path2Clockwise = !subtract;
- var paths = []
- .concat(path1._children || [path1])
- .concat(path2._children || [path2]),
- segments = [],
- result = new CompoundPath();
- for (var i = 0, l = paths.length; i < l; i++) {
- var path = paths[i],
- parent = path._parent,
- clockwise = path.isClockwise(),
- segs = path._segments;
- path = parent instanceof CompoundPath ? parent : path;
- for (var j = segs.length - 1; j >= 0; j--) {
- var segment = segs[j],
- midPoint = segment.getCurve().getPoint(0.5),
- insidePath1 = path !== path1 && path1.contains(midPoint)
- && (clockwise === path1Clockwise || subtract
- || !testOnCurve(path1, midPoint)),
- insidePath2 = path !== path2 && path2.contains(midPoint)
- && (clockwise === path2Clockwise
- || !testOnCurve(path2, midPoint));
- if (operator(path === path1, insidePath1, insidePath2)) {
- segment._invalid = true;
- } else {
- segments.push(segment);
- }
- }
- }
- for (var i = 0, l = segments.length; i < l; i++) {
- var segment = segments[i];
- if (segment._visited)
- continue;
- var path = new Path(),
- loc = segment._intersection,
- intersection = loc && loc.getSegment(true);
- if (segment.getPrevious()._invalid)
- segment.setHandleIn(intersection
- ? intersection._handleIn
- : new Point(0, 0));
- do {
- segment._visited = true;
- if (segment._invalid && segment._intersection) {
- var inter = segment._intersection.getSegment(true);
- path.add(new Segment(segment._point, segment._handleIn,
- inter._handleOut));
- inter._visited = true;
- segment = inter;
- } else {
- path.add(segment.clone());
- }
- segment = segment.getNext();
- } while (segment && !segment._visited && segment !== intersection);
- var amount = path._segments.length;
- if (amount > 1 && (amount > 2 || !path.isPolygon())) {
- path.setClosed(true);
- result.addChild(path, true);
- } else {
- path.remove();
- }
- }
- path1.remove();
- path2.remove();
- return result.reduce();
- }
-
- function testOnCurve(path, point) {
- var curves = path.getCurves(),
- bounds = path.getBounds();
- if (bounds.contains(point)) {
- for (var i = 0, l = curves.length; i < l; i++) {
- var curve = curves[i];
- if (curve.getBounds().contains(point)
- && curve.getParameterOf(point))
- return true;
- }
- }
- return false;
- }
-
- return {
- unite: function(path) {
- return computeBoolean(this, path,
- function(isPath1, isInPath1, isInPath2) {
- return isInPath1 || isInPath2;
- });
- },
-
- intersect: function(path) {
- return computeBoolean(this, path,
- function(isPath1, isInPath1, isInPath2) {
- return !(isInPath1 || isInPath2);
- });
- },
-
- subtract: function(path) {
- return computeBoolean(this, path,
- function(isPath1, isInPath1, isInPath2) {
- return isPath1 && isInPath2 || !isPath1 && !isInPath1;
- }, true);
- },
-
- exclude: function(path) {
- return new Group([this.subtract(path), path.subtract(this)]);
- },
-
- divide: function(path) {
- return new Group([this.subtract(path), this.intersect(path)]);
- }
- };
-});
-
-var TextItem = Item.extend({
- _class: 'TextItem',
- _boundsSelected: true,
- _serializeFields: {
- content: null
- },
- _boundsGetter: 'getBounds',
-
- initialize: function TextItem(arg) {
- this._content = '';
- this._lines = [];
- var hasProps = arg && Base.isPlainObject(arg)
- && arg.x === undefined && arg.y === undefined;
- this._initialize(hasProps && arg, !hasProps && Point.read(arguments));
- },
-
- _equals: function(item) {
- return this._content === item._content;
- },
-
- _clone: function _clone(copy) {
- copy.setContent(this._content);
- return _clone.base.call(this, copy);
- },
-
- getContent: function() {
- return this._content;
- },
-
- setContent: function(content) {
- this._content = '' + content;
- this._lines = this._content.split(/\r\n|\n|\r/mg);
- this._changed(69);
- },
-
- isEmpty: function() {
- return !this._content;
- },
-
- getCharacterStyle: '#getStyle',
- setCharacterStyle: '#setStyle',
-
- getParagraphStyle: '#getStyle',
- setParagraphStyle: '#setStyle'
-});
-
-var PointText = TextItem.extend({
- _class: 'PointText',
-
- initialize: function PointText() {
- TextItem.apply(this, arguments);
- },
-
- clone: function(insert) {
- return this._clone(new PointText({ insert: false }), insert);
- },
-
- getPoint: function() {
- var point = this._matrix.getTranslation();
- return new LinkedPoint(point.x, point.y, this, 'setPoint');
- },
-
- setPoint: function(point) {
- point = Point.read(arguments);
- this.translate(point.subtract(this._matrix.getTranslation()));
- },
-
- _draw: function(ctx) {
- if (!this._content)
- return;
- this._setStyles(ctx);
- var style = this._style,
- lines = this._lines,
- leading = style.getLeading(),
- shadowColor = ctx.shadowColor;
-
- ctx.font = style.getFontStyle();
- ctx.textAlign = style.getJustification();
- for (var i = 0, l = lines.length; i < l; i++) {
- ctx.shadowColor = shadowColor;
- var line = lines[i];
- if (style.hasFill()) {
- ctx.fillText(line, 0, 0);
- ctx.shadowColor = 'rgba(0,0,0,0)';
- }
- if (style.hasStroke())
- ctx.strokeText(line, 0, 0);
- ctx.translate(0, leading);
- }
- }
-}, new function() {
- var measureCtx = null;
-
- return {
- _getBounds: function(getter, matrix) {
- if (!measureCtx)
- measureCtx = CanvasProvider.getContext(1, 1);
- var style = this._style,
- lines = this._lines,
- count = lines.length,
- justification = style.getJustification(),
- leading = style.getLeading(),
- x = 0;
- measureCtx.font = style.getFontStyle();
- var width = 0;
- for (var i = 0; i < count; i++)
- width = Math.max(width, measureCtx.measureText(lines[i]).width);
- if (justification !== 'left')
- x -= width / (justification === 'center' ? 2: 1);
- var bounds = new Rectangle(x,
- count ? - 0.75 * leading : 0,
- width, count * leading);
- return matrix ? matrix._transformBounds(bounds, bounds) : bounds;
- }
- };
-});
-
-var Color = Base.extend(new function() {
-
- var types = {
- gray: ['gray'],
- rgb: ['red', 'green', 'blue'],
- hsb: ['hue', 'saturation', 'brightness'],
- hsl: ['hue', 'saturation', 'lightness'],
- gradient: ['gradient', 'origin', 'destination', 'highlight']
- };
-
- var componentParsers = {},
- colorCache = {},
- colorCtx;
-
- function fromCSS(string) {
- var match = string.match(/^#(\w{1,2})(\w{1,2})(\w{1,2})$/),
- components;
- if (match) {
- components = [0, 0, 0];
- for (var i = 0; i < 3; i++) {
- var value = match[i + 1];
- components[i] = parseInt(value.length == 1
- ? value + value : value, 16) / 255;
- }
- } else if (match = string.match(/^rgba?\((.*)\)$/)) {
- components = match[1].split(',');
- for (var i = 0, l = components.length; i < l; i++) {
- var value = parseFloat(components[i]);
- components[i] = i < 3 ? value / 255 : value;
- }
- } else {
- var cached = colorCache[string];
- if (!cached) {
- if (!colorCtx) {
- colorCtx = CanvasProvider.getContext(1, 1);
- colorCtx.globalCompositeOperation = 'copy';
- }
- colorCtx.fillStyle = 'rgba(0,0,0,0)';
- colorCtx.fillStyle = string;
- colorCtx.fillRect(0, 0, 1, 1);
- var data = colorCtx.getImageData(0, 0, 1, 1).data;
- cached = colorCache[string] = [
- data[0] / 255,
- data[1] / 255,
- data[2] / 255
- ];
- }
- components = cached.slice();
- }
- return components;
- }
-
- var hsbIndices = [
- [0, 3, 1],
- [2, 0, 1],
- [1, 0, 3],
- [1, 2, 0],
- [3, 1, 0],
- [0, 1, 2]
- ];
-
- var converters = {
- 'rgb-hsb': function(r, g, b) {
- var max = Math.max(r, g, b),
- min = Math.min(r, g, b),
- delta = max - min,
- h = delta === 0 ? 0
- : ( max == r ? (g - b) / delta + (g < b ? 6 : 0)
- : max == g ? (b - r) / delta + 2
- : (r - g) / delta + 4) * 60;
- return [h, max === 0 ? 0 : delta / max, max];
- },
-
- 'hsb-rgb': function(h, s, b) {
- var h = (h / 60) % 6,
- i = Math.floor(h),
- f = h - i,
- i = hsbIndices[i],
- v = [
- b,
- b * (1 - s),
- b * (1 - s * f),
- b * (1 - s * (1 - f))
- ];
- return [v[i[0]], v[i[1]], v[i[2]]];
- },
-
- 'rgb-hsl': function(r, g, b) {
- var max = Math.max(r, g, b),
- min = Math.min(r, g, b),
- delta = max - min,
- achromatic = delta === 0,
- h = achromatic ? 0
- : ( max == r ? (g - b) / delta + (g < b ? 6 : 0)
- : max == g ? (b - r) / delta + 2
- : (r - g) / delta + 4) * 60,
- l = (max + min) / 2,
- s = achromatic ? 0 : l < 0.5
- ? delta / (max + min)
- : delta / (2 - max - min);
- return [h, s, l];
- },
-
- 'hsl-rgb': function(h, s, l) {
- h /= 360;
- if (s === 0)
- return [l, l, l];
- var t3s = [ h + 1 / 3, h, h - 1 / 3 ],
- t2 = l < 0.5 ? l * (1 + s) : l + s - l * s,
- t1 = 2 * l - t2,
- c = [];
- for (var i = 0; i < 3; i++) {
- var t3 = t3s[i];
- if (t3 < 0) t3 += 1;
- if (t3 > 1) t3 -= 1;
- c[i] = 6 * t3 < 1
- ? t1 + (t2 - t1) * 6 * t3
- : 2 * t3 < 1
- ? t2
- : 3 * t3 < 2
- ? t1 + (t2 - t1) * ((2 / 3) - t3) * 6
- : t1;
- }
- return c;
- },
-
- 'rgb-gray': function(r, g, b) {
- return [r * 0.2989 + g * 0.587 + b * 0.114];
- },
-
- 'gray-rgb': function(g) {
- return [g, g, g];
- },
-
- 'gray-hsb': function(g) {
- return [0, 0, g];
- },
-
- 'gray-hsl': function(g) {
- return [0, 0, g];
- },
-
- 'gradient-rgb': function() {
- return [];
- },
-
- 'rgb-gradient': function() {
- return [];
- }
-
- };
-
- return Base.each(types, function(properties, type) {
- componentParsers[type] = [];
- Base.each(properties, function(name, index) {
- var part = Base.capitalize(name),
- hasOverlap = /^(hue|saturation)$/.test(name),
- parser = componentParsers[type][index] = name === 'gradient'
- ? function(value) {
- var current = this._components[0];
- value = Gradient.read(
- Array.isArray(value) ? value : arguments,
- 0, 0, { readNull: true });
- if (current !== value) {
- if (current)
- current._removeOwner(this);
- if (value)
- value._addOwner(this);
- }
- return value;
- }
- : name === 'hue'
- ? function(value) {
- return isNaN(value) ? 0
- : ((value % 360) + 360) % 360;
- }
- : type === 'gradient'
- ? function() {
- return Point.read(arguments, 0, 0, {
- readNull: name === 'highlight',
- clone: true
- });
- }
- : function(value) {
- return isNaN(value) ? 0
- : Math.min(Math.max(value, 0), 1);
- };
-
- this['get' + part] = function() {
- return this._type === type
- || hasOverlap && /^hs[bl]$/.test(this._type)
- ? this._components[index]
- : this._convert(type)[index];
- };
-
- this['set' + part] = function(value) {
- if (this._type !== type
- && !(hasOverlap && /^hs[bl]$/.test(this._type))) {
- this._components = this._convert(type);
- this._properties = types[type];
- this._type = type;
- }
- value = parser.call(this, value);
- if (value != null) {
- this._components[index] = value;
- this._changed();
- }
- };
- }, this);
- }, {
- _class: 'Color',
- _readIndex: true,
-
- initialize: function Color(arg) {
- var slice = Array.prototype.slice,
- args = arguments,
- read = 0,
- parse = true,
- type,
- components,
- alpha,
- values;
- if (Array.isArray(arg)) {
- args = arg;
- arg = args[0];
- }
- var argType = arg != null && typeof arg;
- if (argType === 'string' && arg in types) {
- type = arg;
- arg = args[1];
- if (Array.isArray(arg)) {
- components = arg;
- alpha = args[2];
- } else {
- if (this.__read)
- read = 1;
- args = slice.call(args, 1);
- argType = typeof arg;
- }
- }
- if (!components) {
- parse = !(this.__options && this.__options.dontParse);
- values = argType === 'number'
- ? args
- : argType === 'object' && arg.length != null
- ? arg
- : null;
- if (values) {
- if (!type)
- type = values.length >= 3
- ? 'rgb'
- : 'gray';
- var length = types[type].length;
- alpha = values[length];
- if (this.__read)
- read += values === arguments
- ? length + (alpha != null ? 1 : 0)
- : 1;
- if (values.length > length)
- values = slice.call(values, 0, length);
- } else if (argType === 'string') {
- type = 'rgb';
- components = fromCSS(arg);
- if (components.length === 4) {
- alpha = components[3];
- components.length--;
- }
- } else if (argType === 'object') {
- if (arg.constructor === Color) {
- type = arg._type;
- components = arg._components.slice();
- alpha = arg._alpha;
- if (type === 'gradient') {
- for (var i = 1, l = components.length; i < l; i++) {
- var point = components[i];
- if (point)
- components[i] = point.clone();
- }
- }
- } else if (arg.constructor === Gradient) {
- type = 'gradient';
- values = args;
- } else {
- type = 'hue' in arg
- ? 'lightness' in arg
- ? 'hsl'
- : 'hsb'
- : 'gradient' in arg || 'stops' in arg
- || 'radial' in arg
- ? 'gradient'
- : 'gray' in arg
- ? 'gray'
- : 'rgb';
- var properties = types[type];
- parsers = parse && componentParsers[type];
- this._components = components = [];
- for (var i = 0, l = properties.length; i < l; i++) {
- var value = arg[properties[i]];
- if (value == null && i === 0 && type === 'gradient'
- && 'stops' in arg) {
- value = {
- stops: arg.stops,
- radial: arg.radial
- };
- }
- if (parse)
- value = parsers[i].call(this, value);
- if (value != null)
- components[i] = value;
- }
- alpha = arg.alpha;
- }
- }
- if (this.__read && type)
- read = 1;
- }
- this._type = type || 'rgb';
- if (type === 'gradient')
- this._id = Color._id = (Color._id || 0) + 1;
- if (!components) {
- this._components = components = [];
- var parsers = componentParsers[this._type];
- for (var i = 0, l = parsers.length; i < l; i++) {
- var value = values && values[i];
- if (parse)
- value = parsers[i].call(this, value);
- if (value != null)
- components[i] = value;
- }
- }
- this._components = components;
- this._properties = types[this._type];
- this._alpha = alpha;
- if (this.__read)
- this.__read = read;
- },
-
- _serialize: function(options, dictionary) {
- var components = this.getComponents();
- return Base.serialize(
- /^(gray|rgb)$/.test(this._type)
- ? components
- : [this._type].concat(components),
- options, true, dictionary);
- },
-
- _changed: function() {
- this._canvasStyle = null;
- if (this._owner)
- this._owner._changed(17);
- },
-
- _convert: function(type) {
- var converter;
- return this._type === type
- ? this._components.slice()
- : (converter = converters[this._type + '-' + type])
- ? converter.apply(this, this._components)
- : converters['rgb-' + type].apply(this,
- converters[this._type + '-rgb'].apply(this,
- this._components));
- },
-
- convert: function(type) {
- return new Color(type, this._convert(type), this._alpha);
- },
-
- getType: function() {
- return this._type;
- },
-
- setType: function(type) {
- this._components = this._convert(type);
- this._properties = types[type];
- this._type = type;
- },
-
- getComponents: function() {
- var components = this._components.slice();
- if (this._alpha != null)
- components.push(this._alpha);
- return components;
- },
-
- getAlpha: function() {
- return this._alpha != null ? this._alpha : 1;
- },
-
- setAlpha: function(alpha) {
- this._alpha = alpha == null ? null : Math.min(Math.max(alpha, 0), 1);
- this._changed();
- },
-
- hasAlpha: function() {
- return this._alpha != null;
- },
-
- equals: function(color) {
- if (Base.isPlainValue(color))
- color = Color.read(arguments);
- return color === this || color && this._class === color._class
- && this._type === color._type
- && this._alpha === color._alpha
- && Base.equals(this._components, color._components)
- || false;
- },
-
- toString: function() {
- var properties = this._properties,
- parts = [],
- isGradient = this._type === 'gradient',
- f = Formatter.instance;
- for (var i = 0, l = properties.length; i < l; i++) {
- var value = this._components[i];
- if (value != null)
- parts.push(properties[i] + ': '
- + (isGradient ? value : f.number(value)));
- }
- if (this._alpha != null)
- parts.push('alpha: ' + f.number(this._alpha));
- return '{ ' + parts.join(', ') + ' }';
- },
-
- toCSS: function(hex) {
- var components = this._convert('rgb'),
- alpha = hex || this._alpha == null ? 1 : this._alpha;
- components = [
- Math.round(components[0] * 255),
- Math.round(components[1] * 255),
- Math.round(components[2] * 255)
- ];
- if (alpha < 1)
- components.push(alpha);
- return hex
- ? '#' + ((1 << 24) + (components[0] << 16)
- + (components[1] << 8)
- + components[2]).toString(16).slice(1)
- : (components.length == 4 ? 'rgba(' : 'rgb(')
- + components.join(',') + ')';
- },
-
- toCanvasStyle: function(ctx) {
- if (this._canvasStyle)
- return this._canvasStyle;
- if (this._type !== 'gradient')
- return this._canvasStyle = this.toCSS();
- var components = this._components,
- gradient = components[0],
- stops = gradient._stops,
- origin = components[1],
- destination = components[2],
- canvasGradient;
- if (gradient._radial) {
- var radius = destination.getDistance(origin),
- highlight = components[3];
- if (highlight) {
- var vector = highlight.subtract(origin);
- if (vector.getLength() > radius)
- highlight = origin.add(vector.normalize(radius - 0.1));
- }
- var start = highlight || origin;
- canvasGradient = ctx.createRadialGradient(start.x, start.y,
- 0, origin.x, origin.y, radius);
- } else {
- canvasGradient = ctx.createLinearGradient(origin.x, origin.y,
- destination.x, destination.y);
- }
- for (var i = 0, l = stops.length; i < l; i++) {
- var stop = stops[i];
- canvasGradient.addColorStop(stop._rampPoint,
- stop._color.toCanvasStyle());
- }
- return this._canvasStyle = canvasGradient;
- },
-
- transform: function(matrix) {
- if (this._type === 'gradient') {
- var components = this._components;
- for (var i = 1, l = components.length; i < l; i++) {
- var point = components[i];
- matrix._transformPoint(point, point, true);
- }
- this._changed();
- }
- },
-
- statics: {
- _types: types,
-
- random: function() {
- var random = Math.random;
- return new Color(random(), random(), random());
- }
- }
- });
-}, new function() {
- function clamp(value, hue) {
- return value < 0
- ? 0
- : hue && value > 360
- ? 360
- : !hue && value > 1
- ? 1
- : value;
- }
-
- var operators = {
- add: function(a, b, hue) {
- return clamp(a + b, hue);
- },
-
- subtract: function(a, b, hue) {
- return clamp(a - b, hue);
- },
-
- multiply: function(a, b, hue) {
- return clamp(a * b, hue);
- },
-
- divide: function(a, b, hue) {
- return clamp(a / b, hue);
- }
- };
-
- return Base.each(operators, function(operator, name) {
- var options = { dontParse: /^(multiply|divide)$/.test(name) };
-
- this[name] = function(color) {
- color = Color.read(arguments, 0, 0, options);
- var type = this._type,
- properties = this._properties,
- components1 = this._components,
- components2 = color._convert(type);
- for (var i = 0, l = components1.length; i < l; i++)
- components2[i] = operator(components1[i], components2[i],
- properties[i] === 'hue');
- return new Color(type, components2,
- this._alpha != null
- ? operator(this._alpha, color.getAlpha())
- : null);
- };
- }, {
- });
-});
-
-Base.each(Color._types, function(properties, type) {
- var ctor = this[Base.capitalize(type) + 'Color'] = function(arg) {
- var argType = arg != null && typeof arg,
- components = argType === 'object' && arg.length != null
- ? arg
- : argType === 'string'
- ? null
- : arguments;
- return components
- ? new Color(type, components)
- : new Color(arg);
- };
- if (type.length == 3) {
- var acronym = type.toUpperCase();
- Color[acronym] = this[acronym + 'Color'] = ctor;
- }
-}, Base.exports);
-
-var Gradient = Base.extend({
- _class: 'Gradient',
-
- initialize: function Gradient(stops, radial) {
- this._id = Gradient._id = (Gradient._id || 0) + 1;
- if (stops && this._set(stops))
- stops = radial = null;
- if (!this._stops)
- this.setStops(stops || ['white', 'black']);
- if (this._radial == null)
- this.setRadial(typeof radial === 'string' && radial === 'radial'
- || radial || false);
- },
-
- _serialize: function(options, dictionary) {
- return dictionary.add(this, function() {
- return Base.serialize([this._stops, this._radial],
- options, true, dictionary);
- });
- },
-
- _changed: function() {
- for (var i = 0, l = this._owners && this._owners.length; i < l; i++)
- this._owners[i]._changed();
- },
-
- _addOwner: function(color) {
- if (!this._owners)
- this._owners = [];
- this._owners.push(color);
- },
-
- _removeOwner: function(color) {
- var index = this._owners ? this._owners.indexOf(color) : -1;
- if (index != -1) {
- this._owners.splice(index, 1);
- if (this._owners.length === 0)
- delete this._owners;
- }
- },
-
- clone: function() {
- var stops = [];
- for (var i = 0, l = this._stops.length; i < l; i++)
- stops[i] = this._stops[i].clone();
- return new Gradient(stops);
- },
-
- getStops: function() {
- return this._stops;
- },
-
- setStops: function(stops) {
- if (this.stops) {
- for (var i = 0, l = this._stops.length; i < l; i++)
- delete this._stops[i]._owner;
- }
- if (stops.length < 2)
- throw new Error(
- 'Gradient stop list needs to contain at least two stops.');
- this._stops = GradientStop.readAll(stops, 0, false, true);
- for (var i = 0, l = this._stops.length; i < l; i++) {
- var stop = this._stops[i];
- stop._owner = this;
- if (stop._defaultRamp)
- stop.setRampPoint(i / (l - 1));
- }
- this._changed();
- },
-
- getRadial: function() {
- return this._radial;
- },
-
- setRadial: function(radial) {
- this._radial = radial;
- this._changed();
- },
-
- equals: function(gradient) {
- if (gradient === this)
- return true;
- if (gradient && this._class === gradient._class
- && this._stops.length === gradient._stops.length) {
- for (var i = 0, l = this._stops.length; i < l; i++) {
- if (!this._stops[i].equals(gradient._stops[i]))
- return false;
- }
- return true;
- }
- return false;
- }
-});
-
-var GradientStop = Base.extend({
- _class: 'GradientStop',
-
- initialize: function GradientStop(arg0, arg1) {
- if (arg0) {
- var color, rampPoint;
- if (arg1 === undefined && Array.isArray(arg0)) {
- color = arg0[0];
- rampPoint = arg0[1];
- } else if (arg0.color) {
- color = arg0.color;
- rampPoint = arg0.rampPoint;
- } else {
- color = arg0;
- rampPoint = arg1;
- }
- this.setColor(color);
- this.setRampPoint(rampPoint);
- }
- },
-
- clone: function() {
- return new GradientStop(this._color.clone(), this._rampPoint);
- },
-
- _serialize: function(options, dictionary) {
- return Base.serialize([this._color, this._rampPoint], options, true,
- dictionary);
- },
-
- _changed: function() {
- if (this._owner)
- this._owner._changed(17);
- },
-
- getRampPoint: function() {
- return this._rampPoint;
- },
-
- setRampPoint: function(rampPoint) {
- this._defaultRamp = rampPoint == null;
- this._rampPoint = rampPoint || 0;
- this._changed();
- },
-
- getColor: function() {
- return this._color;
- },
-
- setColor: function(color) {
- this._color = Color.read(arguments);
- if (this._color === color)
- this._color = color.clone();
- this._color._owner = this;
- this._changed();
- },
-
- equals: function(stop) {
- return stop === this || stop && this._class === stop._class
- && this._color.equals(stop._color)
- && this._rampPoint == stop._rampPoint
- || false;
- }
-});
-
-var Style = Base.extend(new function() {
- var defaults = {
- fillColor: undefined,
- strokeColor: undefined,
- strokeWidth: 1,
- strokeCap: 'butt',
- strokeJoin: 'miter',
- miterLimit: 10,
- dashOffset: 0,
- dashArray: [],
- windingRule: 'nonzero',
- shadowColor: undefined,
- shadowBlur: 0,
- shadowOffset: new Point(),
- selectedColor: undefined,
- font: 'sans-serif',
- fontSize: 12,
- leading: null,
- justification: 'left'
- };
-
- var flags = {
- strokeWidth: 25,
- strokeCap: 25,
- strokeJoin: 25,
- miterLimit: 25,
- font: 5,
- fontSize: 5,
- leading: 5,
- justification: 5
- };
-
- var item = {},
- fields = {
- _defaults: defaults,
- _textDefaults: new Base(defaults, {
- fillColor: new Color()
- })
- };
-
- Base.each(defaults, function(value, key) {
- var isColor = /Color$/.test(key),
- part = Base.capitalize(key),
- flag = flags[key],
- set = 'set' + part,
- get = 'get' + part;
-
- fields[set] = function(value) {
- var children = this._item && this._item._children;
- if (children && children.length > 0
- && this._item._type !== 'compound-path') {
- for (var i = 0, l = children.length; i < l; i++)
- children[i]._style[set](value);
- } else {
- var old = this._values[key];
- if (old != value) {
- if (isColor) {
- if (old)
- delete old._owner;
- if (value && value.constructor === Color) {
- if (value._owner)
- value = value.clone();
- value._owner = this._item;
- }
- }
- this._values[key] = value;
- if (this._item)
- this._item._changed(flag || 17);
- }
- }
- };
-
- fields[get] = function() {
- var value,
- children = this._item && this._item._children;
- if (!children || children.length === 0 || arguments[0]
- || this._item._type === 'compound-path') {
- var value = this._values[key];
- if (value === undefined) {
- value = this._defaults[key];
- if (value && value.clone)
- value = value.clone();
- this._values[key] = value;
- } else if (isColor && !(value && value.constructor === Color)) {
- this._values[key] = value = Color.read(
- [value], 0, 0, { readNull: true, clone: true });
- if (value)
- value._owner = this._item;
- }
- return value;
- }
- for (var i = 0, l = children.length; i < l; i++) {
- var childValue = children[i]._style[get]();
- if (i === 0) {
- value = childValue;
- } else if (!Base.equals(value, childValue)) {
- return undefined;
- }
- }
- return value;
- };
-
- item[get] = function() {
- return this._style[get]();
- };
-
- item[set] = function(value) {
- this._style[set](value);
- };
- });
-
- Item.inject(item);
- return fields;
-}, {
- _class: 'Style',
-
- initialize: function Style(style, _item) {
- this._values = {};
- this._item = _item;
- if (_item instanceof TextItem)
- this._defaults = this._textDefaults;
- if (style)
- this.set(style);
- },
-
- set: function(style) {
- var isStyle = style instanceof Style,
- values = isStyle ? style._values : style;
- if (values) {
- for (var key in values) {
- if (key in this._defaults) {
- var value = values[key];
- this[key] = value && isStyle && value.clone
- ? value.clone() : value;
- }
- }
- }
- },
-
- equals: function(style) {
- return style === this || style && this._class === style._class
- && Base.equals(this._values, style._values)
- || false;
- },
-
- hasFill: function() {
- return !!this.getFillColor();
- },
-
- hasStroke: function() {
- return !!this.getStrokeColor() && this.getStrokeWidth() > 0;
- },
-
- hasShadow: function() {
- return !!this.getShadowColor() && this.getShadowBlur() > 0;
- },
-
- getLeading: function getLeading() {
- var leading = getLeading.base.call(this);
- return leading != null ? leading : this.getFontSize() * 1.2;
- },
-
- getFontStyle: function() {
- var size = this.getFontSize();
- return size + (/[a-z]/i.test(size + '') ? ' ' : 'px ') + this.getFont();
- }
-
-});
-
-var DomElement = new function() {
-
- var special = /^(checked|value|selected|disabled)$/i,
- translated = { text: 'textContent', html: 'innerHTML' },
- unitless = { lineHeight: 1, zoom: 1, zIndex: 1, opacity: 1 };
-
- function create(nodes, parent) {
- var res = [];
- for (var i = 0, l = nodes && nodes.length; i < l;) {
- var el = nodes[i++];
- if (typeof el === 'string') {
- el = document.createElement(el);
- } else if (!el || !el.nodeType) {
- continue;
- }
- if (Base.isPlainObject(nodes[i]))
- DomElement.set(el, nodes[i++]);
- if (Array.isArray(nodes[i]))
- create(nodes[i++], el);
- if (parent)
- parent.appendChild(el);
- res.push(el);
- }
- return res;
- }
-
- return {
- create: function(nodes, parent) {
- var isArray = Array.isArray(nodes),
- res = create(isArray ? nodes : arguments, isArray ? parent : null);
- return res.length == 1 ? res[0] : res;
- },
-
- find: function(selector, root) {
- return (root || document).querySelector(selector);
- },
-
- findAll: function(selector, root) {
- return (root || document).querySelectorAll(selector);
- },
-
- get: function(el, key) {
- return el
- ? special.test(key)
- ? key === 'value' || typeof el[key] !== 'string'
- ? el[key]
- : true
- : key in translated
- ? el[translated[key]]
- : el.getAttribute(key)
- : null;
- },
-
- set: function(el, key, value) {
- if (typeof key !== 'string') {
- for (var name in key)
- if (key.hasOwnProperty(name))
- this.set(el, name, key[name]);
- } else if (!el || value === undefined) {
- return el;
- } else if (special.test(key)) {
- el[key] = value;
- } else if (key in translated) {
- el[translated[key]] = value;
- } else if (key === 'style') {
- this.setStyle(el, value);
- } else if (key === 'events') {
- DomEvent.add(el, value);
- } else {
- el.setAttribute(key, value);
- }
- return el;
- },
-
- getStyles: function(el) {
- var doc = el && el.nodeType !== 9 ? el.ownerDocument : el,
- view = doc && doc.defaultView;
- return view && view.getComputedStyle(el, '');
- },
-
- getStyle: function(el, key) {
- return el && el.style[key] || this.getStyles(el)[key] || null;
- },
-
- setStyle: function(el, key, value) {
- if (typeof key !== 'string') {
- for (var name in key)
- if (key.hasOwnProperty(name))
- this.setStyle(el, name, key[name]);
- } else {
- if (/^-?[\d\.]+$/.test(value) && !(key in unitless))
- value += 'px';
- el.style[key] = value;
- }
- return el;
- },
-
- hasClass: function(el, cls) {
- return new RegExp('\\s*' + cls + '\\s*').test(el.className);
- },
-
- addClass: function(el, cls) {
- el.className = (el.className + ' ' + cls).trim();
- },
-
- removeClass: function(el, cls) {
- el.className = el.className.replace(
- new RegExp('\\s*' + cls + '\\s*'), ' ').trim();
- },
-
- remove: function(el) {
- if (el.parentNode)
- el.parentNode.removeChild(el);
- },
-
- removeChildren: function(el) {
- while (el.firstChild)
- el.removeChild(el.firstChild);
- },
-
- getBounds: function(el, viewport) {
- var doc = el.ownerDocument,
- body = doc.body,
- html = doc.documentElement,
- rect;
- try {
- rect = el.getBoundingClientRect();
- } catch (e) {
- rect = { left: 0, top: 0, width: 0, height: 0 };
- }
- var x = rect.left - (html.clientLeft || body.clientLeft || 0),
- y = rect.top - (html.clientTop || body.clientTop || 0);
- if (!viewport) {
- var view = doc.defaultView;
- x += view.pageXOffset || html.scrollLeft || body.scrollLeft;
- y += view.pageYOffset || html.scrollTop || body.scrollTop;
- }
- return new Rectangle(x, y, rect.width, rect.height);
- },
-
- getViewportBounds: function(el) {
- var doc = el.ownerDocument,
- view = doc.defaultView,
- html = doc.documentElement;
- return new Rectangle(0, 0,
- view.innerWidth || html.clientWidth,
- view.innerHeight || html.clientHeight
- );
- },
-
- getOffset: function(el, viewport) {
- return this.getBounds(el, viewport).getPoint();
- },
-
- getSize: function(el) {
- return this.getBounds(el, true).getSize();
- },
-
- isInvisible: function(el) {
- return this.getSize(el).equals(new Size(0, 0));
- },
-
- isInView: function(el) {
- return !this.isInvisible(el) && this.getViewportBounds(el).intersects(
- this.getBounds(el, true));
- },
-
- getPrefixValue: function(el, name) {
- var value = el[name],
- prefixes = ['webkit', 'moz', 'ms', 'o'],
- suffix = name[0].toUpperCase() + name.substring(1);
- for (var i = 0; i < 4 && value == null; i++)
- value = el[prefixes[i] + suffix];
- return value;
- }
- };
-};
-
-var DomEvent = {
- add: function(el, events) {
- for (var type in events) {
- var func = events[type];
- if (el.addEventListener) {
- el.addEventListener(type, func, false);
- } else if (el.attachEvent) {
- el.attachEvent('on' + type, func.bound = function() {
- func.call(el, window.event);
- });
- }
- }
- },
-
- remove: function(el, events) {
- for (var type in events) {
- var func = events[type];
- if (el.removeEventListener) {
- el.removeEventListener(type, func, false);
- } else if (el.detachEvent) {
- el.detachEvent('on' + type, func.bound);
- }
- }
- },
-
- getPoint: function(event) {
- var pos = event.targetTouches
- ? event.targetTouches.length
- ? event.targetTouches[0]
- : event.changedTouches[0]
- : event;
- return new Point(
- pos.pageX || pos.clientX + document.documentElement.scrollLeft,
- pos.pageY || pos.clientY + document.documentElement.scrollTop
- );
- },
-
- getTarget: function(event) {
- return event.target || event.srcElement;
- },
-
- getOffset: function(event, target) {
- return DomEvent.getPoint(event).subtract(DomElement.getOffset(
- target || DomEvent.getTarget(event)));
- },
-
- preventDefault: function(event) {
- if (event.preventDefault) {
- event.preventDefault();
- } else {
- event.returnValue = false;
- }
- },
-
- stopPropagation: function(event) {
- if (event.stopPropagation) {
- event.stopPropagation();
- } else {
- event.cancelBubble = true;
- }
- },
-
- stop: function(event) {
- DomEvent.stopPropagation(event);
- DomEvent.preventDefault(event);
- }
-};
-
-DomEvent.requestAnimationFrame = new function() {
- var nativeRequest = DomElement.getPrefixValue(window,
- 'requestAnimationFrame'),
- requested = false,
- callbacks = [],
- focused = true,
- timer;
-
- DomEvent.add(window, {
- focus: function() {
- focused = true;
- },
- blur: function() {
- focused = false;
- }
- });
-
- function handleCallbacks() {
- for (var i = callbacks.length - 1; i >= 0; i--) {
- var entry = callbacks[i],
- func = entry[0],
- el = entry[1];
- if (!el || (PaperScope.getAttribute(el, 'keepalive') == 'true'
- || focused) && DomElement.isInView(el)) {
- callbacks.splice(i, 1);
- func();
- }
- }
- if (nativeRequest) {
- if (callbacks.length) {
- nativeRequest(handleCallbacks);
- } else {
- requested = false;
- }
- }
- }
-
- return function(callback, element) {
- callbacks.push([callback, element]);
- if (nativeRequest) {
- if (!requested) {
- nativeRequest(handleCallbacks);
- requested = true;
- }
- } else if (!timer) {
- timer = setInterval(handleCallbacks, 1000 / 60);
- }
- };
-};
-
-var View = Base.extend(Callback, {
- _class: 'View',
-
- initialize: function View(element) {
- this._scope = paper;
- this._project = paper.project;
- this._element = element;
- var size;
- this._id = element.getAttribute('id');
- if (this._id == null)
- element.setAttribute('id', this._id = 'view-' + View._id++);
- DomEvent.add(element, this._viewHandlers);
- if (PaperScope.hasAttribute(element, 'resize')) {
- var offset = DomElement.getOffset(element, true),
- that = this;
- size = DomElement.getViewportBounds(element)
- .getSize().subtract(offset);
- this._windowHandlers = {
- resize: function() {
- if (!DomElement.isInvisible(element))
- offset = DomElement.getOffset(element, true);
- that.setViewSize(DomElement.getViewportBounds(element)
- .getSize().subtract(offset));
- }
- };
- DomEvent.add(window, this._windowHandlers);
- } else {
- size = DomElement.getSize(element);
- if (size.isNaN() || size.isZero())
- size = new Size(parseInt(element.getAttribute('width'), 10),
- parseInt(element.getAttribute('height'), 10));
- }
- this._setViewSize(size);
- if (PaperScope.hasAttribute(element, 'stats')
- && typeof Stats !== 'undefined') {
- this._stats = new Stats();
- var stats = this._stats.domElement,
- style = stats.style,
- offset = DomElement.getOffset(element);
- style.position = 'absolute';
- style.left = offset.x + 'px';
- style.top = offset.y + 'px';
- document.body.appendChild(stats);
- }
- View._views.push(this);
- View._viewsById[this._id] = this;
- this._viewSize = size;
- (this._matrix = new Matrix())._owner = this;
- this._zoom = 1;
- if (!View._focused)
- View._focused = this;
- this._frameItems = {};
- this._frameItemCount = 0;
- },
-
- remove: function() {
- if (!this._project)
- return false;
- if (View._focused == this)
- View._focused = null;
- View._views.splice(View._views.indexOf(this), 1);
- delete View._viewsById[this._id];
- if (this._project.view == this)
- this._project.view = null;
- DomEvent.remove(this._element, this._viewHandlers);
- DomEvent.remove(window, this._windowHandlers);
- this._element = this._project = null;
- this.detach('frame');
- this._frameItems = {};
- return true;
- },
-
- _events: {
- onFrame: {
- install: function() {
- this._animate = true;
- if (!this._requested)
- this._requestFrame();
- },
-
- uninstall: function() {
- this._animate = false;
- }
- },
-
- onResize: {}
- },
-
- _animate: false,
- _time: 0,
- _count: 0,
-
- _requestFrame: function() {
- var that = this;
- DomEvent.requestAnimationFrame(function() {
- that._requested = false;
- if (!that._animate)
- return;
- that._requestFrame();
- that._handleFrame();
- }, this._element);
- this._requested = true;
- },
-
- _handleFrame: function() {
- paper = this._scope;
- var now = Date.now() / 1000,
- delta = this._before ? now - this._before : 0;
- this._before = now;
- this._handlingFrame = true;
- this.fire('frame', new Base({
- delta: delta,
- time: this._time += delta,
- count: this._count++
- }));
- if (this._stats)
- this._stats.update();
- this._handlingFrame = false;
- this.draw(true);
- },
-
- _animateItem: function(item, animate) {
- var items = this._frameItems;
- if (animate) {
- items[item._id] = {
- item: item,
- time: 0,
- count: 0
- };
- if (++this._frameItemCount === 1)
- this.attach('frame', this._handleFrameItems);
- } else {
- delete items[item._id];
- if (--this._frameItemCount === 0) {
- this.detach('frame', this._handleFrameItems);
- }
- }
- },
-
- _handleFrameItems: function(event) {
- for (var i in this._frameItems) {
- var entry = this._frameItems[i];
- entry.item.fire('frame', new Base(event, {
- time: entry.time += event.delta,
- count: entry.count++
- }));
- }
- },
-
- _redraw: function() {
- this._project._needsRedraw = true;
- if (this._handlingFrame)
- return;
- if (this._animate) {
- this._handleFrame();
- } else {
- this.draw();
- }
- },
-
- _changed: function(flags) {
- if (flags & 1)
- this._project._needsRedraw = true;
- },
-
- _transform: function(matrix) {
- this._matrix.concatenate(matrix);
- this._bounds = null;
- this._redraw();
- },
-
- getElement: function() {
- return this._element;
- },
-
- getViewSize: function() {
- var size = this._viewSize;
- return new LinkedSize(size.width, size.height, this, 'setViewSize');
- },
-
- setViewSize: function(size) {
- size = Size.read(arguments);
- var delta = size.subtract(this._viewSize);
- if (delta.isZero())
- return;
- this._viewSize.set(size.width, size.height);
- this._setViewSize(size);
- this._bounds = null;
- this.fire('resize', {
- size: size,
- delta: delta
- });
- this._redraw();
- },
-
- _setViewSize: function(size) {
- var element = this._element;
- element.width = size.width;
- element.height = size.height;
- },
-
- getBounds: function() {
- if (!this._bounds)
- this._bounds = this._matrix.inverted()._transformBounds(
- new Rectangle(new Point(), this._viewSize));
- return this._bounds;
- },
-
- getSize: function() {
- return this.getBounds().getSize(arguments[0]);
- },
-
- getCenter: function() {
- return this.getBounds().getCenter(arguments[0]);
- },
-
- setCenter: function(center) {
- center = Point.read(arguments);
- this.scrollBy(center.subtract(this.getCenter()));
- },
-
- getZoom: function() {
- return this._zoom;
- },
-
- setZoom: function(zoom) {
- this._transform(new Matrix().scale(zoom / this._zoom,
- this.getCenter()));
- this._zoom = zoom;
- },
-
- isVisible: function() {
- return DomElement.isInView(this._element);
- },
-
- scrollBy: function() {
- this._transform(new Matrix().translate(Point.read(arguments).negate()));
- },
-
- projectToView: function() {
- return this._matrix._transformPoint(Point.read(arguments));
- },
-
- viewToProject: function() {
- return this._matrix._inverseTransform(Point.read(arguments));
- },
-
-}, {
- statics: {
- _views: [],
- _viewsById: {},
- _id: 0,
-
- create: function(element) {
- if (typeof element === 'string')
- element = document.getElementById(element);
- return new CanvasView(element);
- }
- }
-}, new function() {
- var tool,
- prevFocus,
- tempFocus,
- dragging = false;
-
- function getView(event) {
- var target = DomEvent.getTarget(event);
- return target.getAttribute && View._viewsById[target.getAttribute('id')];
- }
-
- function viewToProject(view, event) {
- return view.viewToProject(DomEvent.getOffset(event, view._element));
- }
-
- function updateFocus() {
- if (!View._focused || !View._focused.isVisible()) {
- for (var i = 0, l = View._views.length; i < l; i++) {
- var view = View._views[i];
- if (view && view.isVisible()) {
- View._focused = tempFocus = view;
- break;
- }
- }
- }
- }
-
- function mousedown(event) {
- var view = View._focused = getView(event),
- point = viewToProject(view, event);
- dragging = true;
- if (view._onMouseDown)
- view._onMouseDown(event, point);
- if (tool = view._scope._tool)
- tool._onHandleEvent('mousedown', point, event);
- view.draw(true);
- }
-
- function mousemove(event) {
- var view;
- if (!dragging) {
- view = getView(event);
- if (view) {
- prevFocus = View._focused;
- View._focused = tempFocus = view;
- } else if (tempFocus && tempFocus == View._focused) {
- View._focused = prevFocus;
- updateFocus();
- }
- }
- if (!(view = view || View._focused))
- return;
- var point = event && viewToProject(view, event);
- if (view._onMouseMove)
- view._onMouseMove(event, point);
- if (tool = view._scope._tool) {
- if (tool._onHandleEvent(dragging && tool.responds('mousedrag')
- ? 'mousedrag' : 'mousemove', point, event))
- DomEvent.stop(event);
- }
- view.draw(true);
- }
-
- function mouseup(event) {
- var view = View._focused;
- if (!view || !dragging)
- return;
- var point = viewToProject(view, event);
- curPoint = null;
- dragging = false;
- if (view._onMouseUp)
- view._onMouseUp(event, point);
- if (tool && tool._onHandleEvent('mouseup', point, event))
- DomEvent.stop(event);
- view.draw(true);
- }
-
- function selectstart(event) {
- if (dragging)
- DomEvent.stop(event);
- }
-
- DomEvent.add(document, {
- mousemove: mousemove,
- mouseup: mouseup,
- touchmove: mousemove,
- touchend: mouseup,
- selectstart: selectstart,
- scroll: updateFocus
- });
-
- DomEvent.add(window, {
- load: updateFocus
- });
-
- return {
- _viewHandlers: {
- mousedown: mousedown,
- touchstart: mousedown,
- selectstart: selectstart
- },
-
- statics: {
- updateFocus: updateFocus
- }
- };
-});
-
-var CanvasView = View.extend({
- _class: 'CanvasView',
-
- initialize: function CanvasView(canvas) {
- if (!(canvas instanceof HTMLCanvasElement)) {
- var size = Size.read(arguments);
- if (size.isZero())
- throw new Error(
- 'Cannot create CanvasView with the provided argument: '
- + canvas);
- canvas = CanvasProvider.getCanvas(size);
- }
- this._context = canvas.getContext('2d');
- this._eventCounters = {};
- this._ratio = 1;
- if (PaperScope.getAttribute(canvas, 'hidpi') !== 'off') {
- var deviceRatio = window.devicePixelRatio || 1,
- backingStoreRatio = DomElement.getPrefixValue(this._context,
- 'backingStorePixelRatio') || 1;
- this._ratio = deviceRatio / backingStoreRatio;
- }
- View.call(this, canvas);
- },
-
- _setViewSize: function(size) {
- var width = size.width,
- height = size.height,
- ratio = this._ratio,
- element = this._element,
- style = element.style;
- element.width = width * ratio;
- element.height = height * ratio;
- if (ratio !== 1) {
- style.width = width + 'px';
- style.height = height + 'px';
- this._context.scale(ratio, ratio);
- }
- },
-
- draw: function(checkRedraw) {
- if (checkRedraw && !this._project._needsRedraw)
- return false;
- var ctx = this._context,
- size = this._viewSize;
- ctx.clearRect(0, 0, size.width + 1, size.height + 1);
- this._project.draw(ctx, this._matrix, this._ratio);
- this._project._needsRedraw = false;
- return true;
- }
-}, new function() {
-
- var downPoint,
- lastPoint,
- overPoint,
- downItem,
- lastItem,
- overItem,
- hasDrag,
- doubleClick,
- clickTime;
-
- function callEvent(type, event, point, target, lastPoint, bubble) {
- var item = target,
- mouseEvent;
- while (item) {
- if (item.responds(type)) {
- if (!mouseEvent)
- mouseEvent = new MouseEvent(type, event, point, target,
- lastPoint ? point.subtract(lastPoint) : null);
- if (item.fire(type, mouseEvent)
- && (!bubble || mouseEvent._stopped))
- return false;
- }
- item = item.getParent();
- }
- return true;
- }
-
- function handleEvent(view, type, event, point, lastPoint) {
- if (view._eventCounters[type]) {
- var project = view._project,
- hit = project.hitTest(point, {
- tolerance: project.options.hitTolerance || 0,
- fill: true,
- stroke: true
- }),
- item = hit && hit.item;
- if (item) {
- if (type === 'mousemove' && item != overItem)
- lastPoint = point;
- if (type !== 'mousemove' || !hasDrag)
- callEvent(type, event, point, item, lastPoint);
- return item;
- }
- }
- }
-
- return {
- _onMouseDown: function(event, point) {
- var item = handleEvent(this, 'mousedown', event, point);
- doubleClick = lastItem == item && (Date.now() - clickTime < 300);
- downItem = lastItem = item;
- downPoint = lastPoint = overPoint = point;
- hasDrag = downItem && downItem.responds('mousedrag');
- },
-
- _onMouseUp: function(event, point) {
- var item = handleEvent(this, 'mouseup', event, point);
- if (hasDrag) {
- if (lastPoint && !lastPoint.equals(point))
- callEvent('mousedrag', event, point, downItem, lastPoint);
- if (item != downItem) {
- overPoint = point;
- callEvent('mousemove', event, point, item, overPoint);
- }
- }
- if (item === downItem) {
- clickTime = Date.now();
- if (!doubleClick
- || callEvent('doubleclick', event, downPoint, item))
- callEvent('click', event, downPoint, item);
- doubleClick = false;
- }
- downItem = null;
- hasDrag = false;
- },
-
- _onMouseMove: function(event, point) {
- if (downItem)
- callEvent('mousedrag', event, point, downItem, lastPoint);
- var item = handleEvent(this, 'mousemove', event, point, overPoint);
- lastPoint = overPoint = point;
- if (item !== overItem) {
- callEvent('mouseleave', event, point, overItem);
- overItem = item;
- callEvent('mouseenter', event, point, item);
- }
- }
- };
-});
-
-var Event = Base.extend({
- _class: 'Event',
-
- initialize: function Event(event) {
- this.event = event;
- },
-
- preventDefault: function() {
- this._prevented = true;
- DomEvent.preventDefault(this.event);
- },
-
- stopPropagation: function() {
- this._stopped = true;
- DomEvent.stopPropagation(this.event);
- },
-
- stop: function() {
- this.stopPropagation();
- this.preventDefault();
- },
-
- getModifiers: function() {
- return Key.modifiers;
- }
-});
-
-var KeyEvent = Event.extend({
- _class: 'KeyEvent',
-
- initialize: function KeyEvent(down, key, character, event) {
- Event.call(this, event);
- this.type = down ? 'keydown' : 'keyup';
- this.key = key;
- this.character = character;
- },
-
- toString: function() {
- return "{ type: '" + this.type
- + "', key: '" + this.key
- + "', character: '" + this.character
- + "', modifiers: " + this.getModifiers()
- + " }";
- }
-});
-
-var Key = new function() {
-
- var specialKeys = {
- 8: 'backspace',
- 9: 'tab',
- 13: 'enter',
- 16: 'shift',
- 17: 'control',
- 18: 'option',
- 19: 'pause',
- 20: 'caps-lock',
- 27: 'escape',
- 32: 'space',
- 35: 'end',
- 36: 'home',
- 37: 'left',
- 38: 'up',
- 39: 'right',
- 40: 'down',
- 46: 'delete',
- 91: 'command',
- 93: 'command',
- 224: 'command'
- },
-
- specialChars = {
- 9: true,
- 13: true,
- 32: true
- },
-
- modifiers = new Base({
- shift: false,
- control: false,
- option: false,
- command: false,
- capsLock: false,
- space: false
- }),
-
- charCodeMap = {},
- keyMap = {},
- downCode;
-
- function handleKey(down, keyCode, charCode, event) {
- var character = charCode ? String.fromCharCode(charCode) : '',
- specialKey = specialKeys[keyCode],
- key = specialKey || character.toLowerCase(),
- type = down ? 'keydown' : 'keyup',
- view = View._focused,
- scope = view && view.isVisible() && view._scope,
- tool = scope && scope._tool,
- name;
- keyMap[key] = down;
- if (specialKey && (name = Base.camelize(specialKey)) in modifiers)
- modifiers[name] = down;
- if (down) {
- charCodeMap[keyCode] = charCode;
- } else {
- delete charCodeMap[keyCode];
- }
- if (tool && tool.responds(type)) {
- paper = scope;
- tool.fire(type, new KeyEvent(down, key, character, event));
- if (view)
- view.draw(true);
- }
- }
-
- DomEvent.add(document, {
- keydown: function(event) {
- var code = event.which || event.keyCode;
- if (code in specialKeys) {
- handleKey(true, code, code in specialChars ? code : 0, event);
- } else {
- downCode = code;
- }
- },
-
- keypress: function(event) {
- if (downCode != null) {
- handleKey(true, downCode, event.which || event.keyCode, event);
- downCode = null;
- }
- },
-
- keyup: function(event) {
- var code = event.which || event.keyCode;
- if (code in charCodeMap)
- handleKey(false, code, charCodeMap[code], event);
- }
- });
-
- DomEvent.add(window, {
- blur: function(event) {
- for (var code in charCodeMap)
- handleKey(false, code, charCodeMap[code], event);
- }
- });
-
- return {
- modifiers: modifiers,
-
- isDown: function(key) {
- return !!keyMap[key];
- }
- };
-};
-
-var MouseEvent = Event.extend({
- _class: 'MouseEvent',
-
- initialize: function MouseEvent(type, event, point, target, delta) {
- Event.call(this, event);
- this.type = type;
- this.point = point;
- this.target = target;
- this.delta = delta;
- },
-
- toString: function() {
- return "{ type: '" + this.type
- + "', point: " + this.point
- + ', target: ' + this.target
- + (this.delta ? ', delta: ' + this.delta : '')
- + ', modifiers: ' + this.getModifiers()
- + ' }';
- }
-});
-
- Base.extend(Callback, {
- _class: 'Palette',
- _events: [ 'onChange' ],
-
- initialize: function Palette(title, components, values) {
- var parent = DomElement.find('.palettejs-panel')
- || DomElement.find('body').appendChild(
- DomElement.create('div', { 'class': 'palettejs-panel' }));
- this._element = parent.appendChild(
- DomElement.create('table', { 'class': 'palettejs-pane' }));
- this._title = title;
- if (!values)
- values = {};
- for (var name in (this.components = components)) {
- var component = components[name];
- if (!(component instanceof Component)) {
- if (component.value == null)
- component.value = values[name];
- component.name = name;
- component = components[name] = new Component(component);
- }
- this._element.appendChild(component._element);
- component._palette = this;
- if (values[name] === undefined)
- values[name] = component.value;
- }
- this.values = Base.each(values, function(value, name) {
- var component = components[name];
- if (component) {
- Base.define(values, name, {
- enumerable: true,
- configurable: true,
- get: function() {
- return component._value;
- },
- set: function(val) {
- component.setValue(val);
- }
- });
- }
- });
- if (window.paper)
- paper.palettes.push(this);
- },
-
- reset: function() {
- for (var i in this.components)
- this.components[i].reset();
- },
-
- remove: function() {
- DomElement.remove(this._element);
- }
-});
-
-var Component = Base.extend(Callback, {
- _class: 'Component',
- _events: [ 'onChange', 'onClick' ],
-
- _types: {
- 'boolean': {
- type: 'checkbox',
- value: 'checked'
- },
-
- string: {
- type: 'text'
- },
-
- number: {
- type: 'number',
- number: true
- },
-
- button: {
- type: 'button'
- },
-
- text: {
- tag: 'div',
- value: 'text'
- },
-
- slider: {
- type: 'range',
- number: true
- },
-
- list: {
- tag: 'select',
-
- setOptions: function() {
- DomElement.removeChildren(this._input);
- DomElement.create(Base.each(this._options, function(option) {
- this.push('option', { value: option, text: option });
- }, []), this._input);
- }
- },
-
- color: {
- type: 'color',
-
- getValue: function(value) {
- return new Color(value);
- },
-
- setValue: function(value) {
- return new Color(value).toCSS(
- DomElement.get(this._input, 'type') === 'color');
- }
- }
- },
-
- initialize: function Component(obj) {
- this._id = Component._id = (Component._id || 0) + 1;
- this._type = obj.type in this._types
- ? obj.type
- : 'options' in obj
- ? 'list'
- : 'onClick' in obj
- ? 'button'
- : typeof obj.value;
- this._meta = this._types[this._type] || { type: this._type };
- var that = this,
- id = 'component-' + this._id;
- this._dontFire = true;
- this._input = DomElement.create(this._meta.tag || 'input', {
- id: id,
- type: this._meta.type,
- events: {
- change: function() {
- that.setValue(
- DomElement.get(this, that._meta.value || 'value'));
- },
- click: function() {
- that.fire('click');
- }
- }
- });
- this.attach('change', function(value) {
- if (!this._dontFire)
- this._palette.fire('change', this, this.name, value);
- });
- this._element = DomElement.create('tr', [
- 'td', [this._label = DomElement.create('label', { 'for': id })],
- 'td', [this._input]
- ]);
- Base.each(obj, function(value, key) {
- this[key] = value;
- }, this);
- this._defaultValue = this._value;
- this._dontFire = false;
- },
-
- getType: function() {
- return this._type;
- },
-
- getLabel: function() {
- return this.__label;
- },
-
- setLabel: function(label) {
- this.__label = label;
- DomElement.set(this._label, 'text', label + ':');
- },
-
- getOptions: function() {
- return this._options;
- },
-
- setOptions: function(options) {
- this._options = options;
- var setOptions = this._meta.setOptions;
- if (setOptions)
- setOptions.call(this);
- },
-
- getValue: function() {
- var value = this._value,
- getValue = this._meta.getValue;
- return getValue ? getValue.call(this, value) : value;
- },
-
- setValue: function(value) {
- var key = this._meta.value || 'value',
- setValue = this._meta.setValue;
- if (setValue)
- value = setValue.call(this, value);
- DomElement.set(this._input, key, value);
- value = DomElement.get(this._input, key);
- if (this._meta.number)
- value = parseFloat(value, 10);
- if (this._value !== value) {
- this._value = value;
- if (!this._dontFire)
- this.fire('change', this.getValue());
- }
- },
-
- getRange: function() {
- return [parseFloat(DomElement.get(this._input, 'min')),
- parseFloat(DomElement.get(this._input, 'max'))];
- },
-
- setRange: function(min, max) {
- var range = Array.isArray(min) ? min : [min, max];
- DomElement.set(this._input, { min: range[0], max: range[1] });
- },
-
- getMin: function() {
- return this.getRange()[0];
- },
-
- setMin: function(min) {
- this.setRange(min, this.getMax());
- },
-
- getMax: function() {
- return this.getRange()[1];
- },
-
- setMax: function(max) {
- this.setRange(this.getMin(), max);
- },
-
- getStep: function() {
- return parseFloat(DomElement.get(this._input, 'step'));
- },
-
- setStep: function(step) {
- DomElement.set(this._input, 'step', step);
- },
-
- reset: function() {
- this.setValue(this._defaultValue);
- }
-});
-
-var ToolEvent = Event.extend({
- _class: 'ToolEvent',
- _item: null,
-
- initialize: function ToolEvent(tool, type, event) {
- this.tool = tool;
- this.type = type;
- this.event = event;
- },
-
- _choosePoint: function(point, toolPoint) {
- return point ? point : toolPoint ? toolPoint.clone() : null;
- },
-
- getPoint: function() {
- return this._choosePoint(this._point, this.tool._point);
- },
-
- setPoint: function(point) {
- this._point = point;
- },
-
- getLastPoint: function() {
- return this._choosePoint(this._lastPoint, this.tool._lastPoint);
- },
-
- setLastPoint: function(lastPoint) {
- this._lastPoint = lastPoint;
- },
-
- getDownPoint: function() {
- return this._choosePoint(this._downPoint, this.tool._downPoint);
- },
-
- setDownPoint: function(downPoint) {
- this._downPoint = downPoint;
- },
-
- getMiddlePoint: function() {
- if (!this._middlePoint && this.tool._lastPoint) {
- return this.tool._point.add(this.tool._lastPoint).divide(2);
- }
- return this._middlePoint;
- },
-
- setMiddlePoint: function(middlePoint) {
- this._middlePoint = middlePoint;
- },
-
- getDelta: function() {
- return !this._delta && this.tool._lastPoint
- ? this.tool._point.subtract(this.tool._lastPoint)
- : this._delta;
- },
-
- setDelta: function(delta) {
- this._delta = delta;
- },
-
- getCount: function() {
- return /^mouse(down|up)$/.test(this.type)
- ? this.tool._downCount
- : this.tool._count;
- },
-
- setCount: function(count) {
- this.tool[/^mouse(down|up)$/.test(this.type) ? 'downCount' : 'count']
- = count;
- },
-
- getItem: function() {
- if (!this._item) {
- var result = this.tool._scope.project.hitTest(this.getPoint());
- if (result) {
- var item = result.item,
- parent = item._parent;
- while (/^(group|compound-path)$/.test(parent._type)) {
- item = parent;
- parent = parent._parent;
- }
- this._item = item;
- }
- }
- return this._item;
- },
- setItem: function(item) {
- this._item = item;
- },
-
- toString: function() {
- return '{ type: ' + this.type
- + ', point: ' + this.getPoint()
- + ', count: ' + this.getCount()
- + ', modifiers: ' + this.getModifiers()
- + ' }';
- }
-});
-
-var Tool = PaperScopeItem.extend({
- _class: 'Tool',
- _list: 'tools',
- _reference: '_tool',
- _events: [ 'onActivate', 'onDeactivate', 'onEditOptions',
- 'onMouseDown', 'onMouseUp', 'onMouseDrag', 'onMouseMove',
- 'onKeyDown', 'onKeyUp' ],
-
- initialize: function Tool(props) {
- PaperScopeItem.call(this);
- this._firstMove = true;
- this._count = 0;
- this._downCount = 0;
- this._set(props);
- },
-
- getMinDistance: function() {
- return this._minDistance;
- },
-
- setMinDistance: function(minDistance) {
- this._minDistance = minDistance;
- if (this._minDistance != null && this._maxDistance != null
- && this._minDistance > this._maxDistance) {
- this._maxDistance = this._minDistance;
- }
- },
-
- getMaxDistance: function() {
- return this._maxDistance;
- },
-
- setMaxDistance: function(maxDistance) {
- this._maxDistance = maxDistance;
- if (this._minDistance != null && this._maxDistance != null
- && this._maxDistance < this._minDistance) {
- this._minDistance = maxDistance;
- }
- },
-
- getFixedDistance: function() {
- return this._minDistance == this._maxDistance
- ? this._minDistance : null;
- },
-
- setFixedDistance: function(distance) {
- this._minDistance = distance;
- this._maxDistance = distance;
- },
-
- _updateEvent: function(type, point, minDistance, maxDistance, start,
- needsChange, matchMaxDistance) {
- if (!start) {
- if (minDistance != null || maxDistance != null) {
- var minDist = minDistance != null ? minDistance : 0,
- vector = point.subtract(this._point),
- distance = vector.getLength();
- if (distance < minDist)
- return false;
- var maxDist = maxDistance != null ? maxDistance : 0;
- if (maxDist != 0) {
- if (distance > maxDist) {
- point = this._point.add(vector.normalize(maxDist));
- } else if (matchMaxDistance) {
- return false;
- }
- }
- }
- if (needsChange && point.equals(this._point))
- return false;
- }
- this._lastPoint = start && type == 'mousemove' ? point : this._point;
- this._point = point;
- switch (type) {
- case 'mousedown':
- this._lastPoint = this._downPoint;
- this._downPoint = this._point;
- this._downCount++;
- break;
- case 'mouseup':
- this._lastPoint = this._downPoint;
- break;
- }
- this._count = start ? 0 : this._count + 1;
- return true;
- },
-
- _fireEvent: function(type, event) {
- var sets = paper.project._removeSets;
- if (sets) {
- if (type === 'mouseup')
- sets.mousedrag = null;
- var set = sets[type];
- if (set) {
- for (var id in set) {
- var item = set[id];
- for (var key in sets) {
- var other = sets[key];
- if (other && other != set)
- delete other[item._id];
- }
- item.remove();
- }
- sets[type] = null;
- }
- }
- return this.responds(type)
- && this.fire(type, new ToolEvent(this, type, event));
- },
-
- _onHandleEvent: function(type, point, event) {
- paper = this._scope;
- var called = false;
- switch (type) {
- case 'mousedown':
- this._updateEvent(type, point, null, null, true, false, false);
- called = this._fireEvent(type, event);
- break;
- case 'mousedrag':
- var needsChange = false,
- matchMaxDistance = false;
- while (this._updateEvent(type, point, this.minDistance,
- this.maxDistance, false, needsChange, matchMaxDistance)) {
- called = this._fireEvent(type, event) || called;
- needsChange = true;
- matchMaxDistance = true;
- }
- break;
- case 'mouseup':
- if (!point.equals(this._point)
- && this._updateEvent('mousedrag', point, this.minDistance,
- this.maxDistance, false, false, false)) {
- called = this._fireEvent('mousedrag', event);
- }
- this._updateEvent(type, point, null, this.maxDistance, false,
- false, false);
- called = this._fireEvent(type, event) || called;
- this._updateEvent(type, point, null, null, true, false, false);
- this._firstMove = true;
- break;
- case 'mousemove':
- while (this._updateEvent(type, point, this.minDistance,
- this.maxDistance, this._firstMove, true, false)) {
- called = this._fireEvent(type, event) || called;
- this._firstMove = false;
- }
- break;
- }
- return called;
- }
-
-});
-
-var Http = {
- request: function(method, url, callback) {
- var xhr = new (window.ActiveXObject || XMLHttpRequest)(
- 'Microsoft.XMLHTTP');
- xhr.open(method.toUpperCase(), url, true);
- if ('overrideMimeType' in xhr)
- xhr.overrideMimeType('text/plain');
- xhr.onreadystatechange = function() {
- if (xhr.readyState === 4) {
- var status = xhr.status;
- if (status === 0 || status === 200) {
- callback.call(xhr, xhr.responseText);
- } else {
- throw new Error('Could not load ' + url + ' (Error '
- + status + ')');
- }
- }
- };
- return xhr.send(null);
- }
-};
-
-var CanvasProvider = {
- canvases: [],
-
- getCanvas: function(width, height, ratio) {
- var canvas,
- init = true;
- if (typeof width === 'object') {
- ratio = height;
- height = width.height;
- width = width.width;
- }
- if (!ratio) {
- ratio = 1;
- } else if (ratio !== 1) {
- width *= ratio;
- height *= ratio;
- }
- if (this.canvases.length) {
- canvas = this.canvases.pop();
- } else {
- canvas = document.createElement('canvas');
- }
- var ctx = canvas.getContext('2d');
- if (canvas.width === width && canvas.height === height) {
- if (init)
- ctx.clearRect(0, 0, width + 1, height + 1);
- } else {
- canvas.width = width;
- canvas.height = height;
- }
- ctx.save();
- if (ratio !== 1)
- ctx.scale(ratio, ratio);
- return canvas;
- },
-
- getContext: function(width, height) {
- return this.getCanvas(width, height).getContext('2d');
- },
-
- release: function(obj) {
- var canvas = obj.canvas ? obj.canvas : obj;
- canvas.getContext('2d').restore();
- this.canvases.push(canvas);
- }
-};
-
-var BlendMode = new function() {
- var min = Math.min,
- max = Math.max,
- abs = Math.abs,
- sr, sg, sb, sa,
- br, bg, bb, ba,
- dr, dg, db;
-
- function getLum(r, g, b) {
- return 0.2989 * r + 0.587 * g + 0.114 * b;
- }
-
- function setLum(r, g, b, l) {
- var d = l - getLum(r, g, b);
- dr = r + d;
- dg = g + d;
- db = b + d;
- var l = getLum(dr, dg, db),
- mn = min(dr, dg, db),
- mx = max(dr, dg, db);
- if (mn < 0) {
- var lmn = l - mn;
- dr = l + (dr - l) * l / lmn;
- dg = l + (dg - l) * l / lmn;
- db = l + (db - l) * l / lmn;
- }
- if (mx > 255) {
- var ln = 255 - l,
- mxl = mx - l;
- dr = l + (dr - l) * ln / mxl;
- dg = l + (dg - l) * ln / mxl;
- db = l + (db - l) * ln / mxl;
- }
- }
-
- function getSat(r, g, b) {
- return max(r, g, b) - min(r, g, b);
- }
-
- function setSat(r, g, b, s) {
- var col = [r, g, b],
- mx = max(r, g, b),
- mn = min(r, g, b),
- md;
- mn = mn === r ? 0 : mn === g ? 1 : 2;
- mx = mx === r ? 0 : mx === g ? 1 : 2;
- md = min(mn, mx) === 0 ? max(mn, mx) === 1 ? 2 : 1 : 0;
- if (col[mx] > col[mn]) {
- col[md] = (col[md] - col[mn]) * s / (col[mx] - col[mn]);
- col[mx] = s;
- } else {
- col[md] = col[mx] = 0;
- }
- col[mn] = 0;
- dr = col[0];
- dg = col[1];
- db = col[2];
- }
-
- var modes = {
- multiply: function() {
- dr = br * sr / 255;
- dg = bg * sg / 255;
- db = bb * sb / 255;
- },
-
- screen: function() {
- dr = br + sr - (br * sr / 255);
- dg = bg + sg - (bg * sg / 255);
- db = bb + sb - (bb * sb / 255);
- },
-
- overlay: function() {
- dr = br < 128 ? 2 * br * sr / 255 : 255 - 2 * (255 - br) * (255 - sr) / 255;
- dg = bg < 128 ? 2 * bg * sg / 255 : 255 - 2 * (255 - bg) * (255 - sg) / 255;
- db = bb < 128 ? 2 * bb * sb / 255 : 255 - 2 * (255 - bb) * (255 - sb) / 255;
- },
-
- 'soft-light': function() {
- var t = sr * br / 255;
- dr = t + br * (255 - (255 - br) * (255 - sr) / 255 - t) / 255;
- t = sg * bg / 255;
- dg = t + bg * (255 - (255 - bg) * (255 - sg) / 255 - t) / 255;
- t = sb * bb / 255;
- db = t + bb * (255 - (255 - bb) * (255 - sb) / 255 - t) / 255;
- },
-
- 'hard-light': function() {
- dr = sr < 128 ? 2 * sr * br / 255 : 255 - 2 * (255 - sr) * (255 - br) / 255;
- dg = sg < 128 ? 2 * sg * bg / 255 : 255 - 2 * (255 - sg) * (255 - bg) / 255;
- db = sb < 128 ? 2 * sb * bb / 255 : 255 - 2 * (255 - sb) * (255 - bb) / 255;
- },
-
- 'color-dodge': function() {
- dr = br === 0 ? 0 : sr === 255 ? 255 : min(255, 255 * br / (255 - sr));
- dg = bg === 0 ? 0 : sg === 255 ? 255 : min(255, 255 * bg / (255 - sg));
- db = bb === 0 ? 0 : sb === 255 ? 255 : min(255, 255 * bb / (255 - sb));
- },
-
- 'color-burn': function() {
- dr = br === 255 ? 255 : sr === 0 ? 0 : max(0, 255 - (255 - br) * 255 / sr);
- dg = bg === 255 ? 255 : sg === 0 ? 0 : max(0, 255 - (255 - bg) * 255 / sg);
- db = bb === 255 ? 255 : sb === 0 ? 0 : max(0, 255 - (255 - bb) * 255 / sb);
- },
-
- darken: function() {
- dr = br < sr ? br : sr;
- dg = bg < sg ? bg : sg;
- db = bb < sb ? bb : sb;
- },
-
- lighten: function() {
- dr = br > sr ? br : sr;
- dg = bg > sg ? bg : sg;
- db = bb > sb ? bb : sb;
- },
-
- difference: function() {
- dr = br - sr;
- if (dr < 0)
- dr = -dr;
- dg = bg - sg;
- if (dg < 0)
- dg = -dg;
- db = bb - sb;
- if (db < 0)
- db = -db;
- },
-
- exclusion: function() {
- dr = br + sr * (255 - br - br) / 255;
- dg = bg + sg * (255 - bg - bg) / 255;
- db = bb + sb * (255 - bb - bb) / 255;
- },
-
- hue: function() {
- setSat(sr, sg, sb, getSat(br, bg, bb));
- setLum(dr, dg, db, getLum(br, bg, bb));
- },
-
- saturation: function() {
- setSat(br, bg, bb, getSat(sr, sg, sb));
- setLum(dr, dg, db, getLum(br, bg, bb));
- },
-
- luminosity: function() {
- setLum(br, bg, bb, getLum(sr, sg, sb));
- },
-
- color: function() {
- setLum(sr, sg, sb, getLum(br, bg, bb));
- },
-
- add: function() {
- dr = min(br + sr, 255);
- dg = min(bg + sg, 255);
- db = min(bb + sb, 255);
- },
-
- subtract: function() {
- dr = max(br - sr, 0);
- dg = max(bg - sg, 0);
- db = max(bb - sb, 0);
- },
-
- average: function() {
- dr = (br + sr) / 2;
- dg = (bg + sg) / 2;
- db = (bb + sb) / 2;
- },
-
- negation: function() {
- dr = 255 - abs(255 - sr - br);
- dg = 255 - abs(255 - sg - bg);
- db = 255 - abs(255 - sb - bb);
- }
- };
-
- var nativeModes = this.nativeModes = Base.each([
- 'source-over', 'source-in', 'source-out', 'source-atop',
- 'destination-over', 'destination-in', 'destination-out',
- 'destination-atop', 'lighter', 'darker', 'copy', 'xor'
- ], function(mode) {
- this[mode] = true;
- }, {});
-
- var ctx = CanvasProvider.getContext(1, 1);
- Base.each(modes, function(func, mode) {
- ctx.save();
- var darken = mode === 'darken',
- ok = false;
- ctx.fillStyle = darken ? '#300' : '#a00';
- ctx.fillRect(0, 0, 1, 1);
- ctx.globalCompositeOperation = mode;
- if (ctx.globalCompositeOperation === mode) {
- ctx.fillStyle = darken ? '#a00' : '#300';
- ctx.fillRect(0, 0, 1, 1);
- ok = ctx.getImageData(0, 0, 1, 1).data[0] !== (darken ? 170 : 51);
- }
- nativeModes[mode] = ok;
- ctx.restore();
- });
- CanvasProvider.release(ctx);
-
- this.process = function(mode, srcContext, dstContext, alpha, offset) {
- var srcCanvas = srcContext.canvas,
- normal = mode === 'normal';
- if (normal || nativeModes[mode]) {
- dstContext.save();
- dstContext.setTransform(1, 0, 0, 1, 0, 0);
- dstContext.globalAlpha = alpha;
- if (!normal)
- dstContext.globalCompositeOperation = mode;
- dstContext.drawImage(srcCanvas, offset.x, offset.y);
- dstContext.restore();
- } else {
- var process = modes[mode];
- if (!process)
- return;
- var dstData = dstContext.getImageData(offset.x, offset.y,
- srcCanvas.width, srcCanvas.height),
- dst = dstData.data,
- src = srcContext.getImageData(0, 0,
- srcCanvas.width, srcCanvas.height).data;
- for (var i = 0, l = dst.length; i < l; i += 4) {
- sr = src[i];
- br = dst[i];
- sg = src[i + 1];
- bg = dst[i + 1];
- sb = src[i + 2];
- bb = dst[i + 2];
- sa = src[i + 3];
- ba = dst[i + 3];
- process();
- var a1 = sa * alpha / 255,
- a2 = 1 - a1;
- dst[i] = a1 * dr + a2 * br;
- dst[i + 1] = a1 * dg + a2 * bg;
- dst[i + 2] = a1 * db + a2 * bb;
- dst[i + 3] = sa * alpha + a2 * ba;
- }
- dstContext.putImageData(dstData, offset.x, offset.y);
- }
- };
-};
-
-var SVGStyles = Base.each({
- fillColor: ['fill', 'color'],
- strokeColor: ['stroke', 'color'],
- strokeWidth: ['stroke-width', 'number'],
- strokeCap: ['stroke-linecap', 'string'],
- strokeJoin: ['stroke-linejoin', 'string'],
- miterLimit: ['stroke-miterlimit', 'number'],
- dashArray: ['stroke-dasharray', 'array'],
- dashOffset: ['stroke-dashoffset', 'number'],
- font: ['font-family', 'string'],
- fontSize: ['font-size', 'number'],
- justification: ['text-anchor', 'lookup', {
- left: 'start',
- center: 'middle',
- right: 'end'
- }],
- opacity: ['opacity', 'number'],
- blendMode: ['mix-blend-mode', 'string']
-}, function(entry, key) {
- var part = Base.capitalize(key),
- lookup = entry[2];
- this[key] = {
- type: entry[1],
- property: key,
- attribute: entry[0],
- toSVG: lookup,
- fromSVG: lookup && Base.each(lookup, function(value, name) {
- this[value] = name;
- }, {}),
- get: 'get' + part,
- set: 'set' + part
- };
-}, {});
-
-var SVGNamespaces = {
- href: 'http://www.w3.org/1999/xlink',
- xlink: 'http://www.w3.org/2000/xmlns'
-};
-
-new function() {
- var formatter;
-
- function setAttributes(node, attrs) {
- for (var key in attrs) {
- var val = attrs[key],
- namespace = SVGNamespaces[key];
- if (typeof val === 'number')
- val = formatter.number(val);
- if (namespace) {
- node.setAttributeNS(namespace, key, val);
- } else {
- node.setAttribute(key, val);
- }
- }
- return node;
- }
-
- function createElement(tag, attrs) {
- return setAttributes(
- document.createElementNS('http://www.w3.org/2000/svg', tag), attrs);
- }
-
- function getTransform(item, coordinates, center) {
- var matrix = item._matrix,
- trans = matrix.getTranslation(),
- attrs = {};
- if (coordinates) {
- matrix = matrix.shiftless();
- var point = matrix._inverseTransform(trans);
- attrs[center ? 'cx' : 'x'] = point.x;
- attrs[center ? 'cy' : 'y'] = point.y;
- trans = null;
- }
- if (matrix.isIdentity())
- return attrs;
- var decomposed = matrix.decompose();
- if (decomposed && !decomposed.shearing) {
- var parts = [],
- angle = decomposed.rotation,
- scale = decomposed.scaling;
- if (trans && !trans.isZero())
- parts.push('translate(' + formatter.point(trans) + ')');
- if (!Numerical.isZero(scale.x - 1) || !Numerical.isZero(scale.y - 1))
- parts.push('scale(' + formatter.point(scale) +')');
- if (angle)
- parts.push('rotate(' + formatter.number(angle) + ')');
- attrs.transform = parts.join(' ');
- } else {
- attrs.transform = 'matrix(' + matrix.getValues().join(',') + ')';
- }
- return attrs;
- }
-
- function exportGroup(item, options) {
- var attrs = getTransform(item),
- children = item._children;
- var node = createElement('g', attrs);
- for (var i = 0, l = children.length; i < l; i++) {
- var child = children[i];
- var childNode = exportSVG(child, options);
- if (childNode) {
- if (child.isClipMask()) {
- var clip = createElement('clipPath');
- clip.appendChild(childNode);
- setDefinition(child, clip, 'clip');
- setAttributes(node, {
- 'clip-path': 'url(#' + clip.id + ')'
- });
- } else {
- node.appendChild(childNode);
- }
- }
- }
- return node;
- }
-
- function exportRaster(item) {
- var attrs = getTransform(item, true),
- size = item.getSize();
- attrs.x -= size.width / 2;
- attrs.y -= size.height / 2;
- attrs.width = size.width;
- attrs.height = size.height;
- attrs.href = item.toDataURL();
- return createElement('image', attrs);
- }
-
- function exportPath(item, options) {
- if (options.matchShapes) {
- var shape = item.toShape(false);
- if (shape)
- return exportShape(shape, options);
- }
- var segments = item._segments,
- type,
- attrs;
- if (segments.length === 0)
- return null;
- if (item.isPolygon()) {
- if (segments.length >= 3) {
- type = item._closed ? 'polygon' : 'polyline';
- var parts = [];
- for(i = 0, l = segments.length; i < l; i++)
- parts.push(formatter.point(segments[i]._point));
- attrs = {
- points: parts.join(' ')
- };
- } else {
- type = 'line';
- var first = segments[0]._point,
- last = segments[segments.length - 1]._point;
- attrs = {
- x1: first.x,
- y1: first.y,
- x2: last.x,
- y2: last.y
- };
- }
- } else {
- type = 'path';
- var data = item.getPathData();
- attrs = data && { d: data };
- }
- return createElement(type, attrs);
- }
-
- function exportShape(item) {
- var shape = item._shape,
- radius = item._radius,
- attrs = getTransform(item, true, shape !== 'rectangle');
- if (shape === 'rectangle') {
- shape = 'rect';
- var size = item._size,
- width = size.width,
- height = size.height;
- attrs.x -= width / 2;
- attrs.y -= height / 2;
- attrs.width = width;
- attrs.height = height;
- if (radius.isZero())
- radius = null;
- }
- if (radius) {
- if (shape === 'circle') {
- attrs.r = radius;
- } else {
- attrs.rx = radius.width;
- attrs.ry = radius.height;
- }
- }
- return createElement(shape, attrs);
- }
-
- function exportCompoundPath(item) {
- var attrs = getTransform(item, true);
- var data = item.getPathData();
- if (data)
- attrs.d = data;
- return createElement('path', attrs);
- }
-
- function exportPlacedSymbol(item, options) {
- var attrs = getTransform(item, true),
- symbol = item.getSymbol(),
- symbolNode = getDefinition(symbol, 'symbol'),
- definition = symbol.getDefinition(),
- bounds = definition.getBounds();
- if (!symbolNode) {
- symbolNode = createElement('symbol', {
- viewBox: formatter.rectangle(bounds)
- });
- symbolNode.appendChild(exportSVG(definition, options));
- setDefinition(symbol, symbolNode, 'symbol');
- }
- attrs.href = '#' + symbolNode.id;
- attrs.x += bounds.x;
- attrs.y += bounds.y;
- attrs.width = formatter.number(bounds.width);
- attrs.height = formatter.number(bounds.height);
- return createElement('use', attrs);
- }
-
- function exportGradient(color) {
- var gradientNode = getDefinition(color, 'color');
- if (!gradientNode) {
- var gradient = color.getGradient(),
- radial = gradient._radial,
- origin = color.getOrigin().transform(),
- destination = color.getDestination().transform(),
- attrs;
- if (radial) {
- attrs = {
- cx: origin.x,
- cy: origin.y,
- r: origin.getDistance(destination)
- };
- var highlight = color.getHighlight();
- if (highlight) {
- highlight = highlight.transform();
- attrs.fx = highlight.x;
- attrs.fy = highlight.y;
- }
- } else {
- attrs = {
- x1: origin.x,
- y1: origin.y,
- x2: destination.x,
- y2: destination.y
- };
- }
- attrs.gradientUnits = 'userSpaceOnUse';
- gradientNode = createElement(
- (radial ? 'radial' : 'linear') + 'Gradient', attrs);
- var stops = gradient._stops;
- for (var i = 0, l = stops.length; i < l; i++) {
- var stop = stops[i],
- stopColor = stop._color,
- alpha = stopColor.getAlpha();
- attrs = {
- offset: stop._rampPoint,
- 'stop-color': stopColor.toCSS(true)
- };
- if (alpha < 1)
- attrs['stop-opacity'] = alpha;
- gradientNode.appendChild(createElement('stop', attrs));
- }
- setDefinition(color, gradientNode, 'color');
- }
- return 'url(#' + gradientNode.id + ')';
- }
-
- function exportText(item) {
- var node = createElement('text', getTransform(item, true));
- node.textContent = item._content;
- return node;
- }
-
- var exporters = {
- group: exportGroup,
- layer: exportGroup,
- raster: exportRaster,
- path: exportPath,
- shape: exportShape,
- 'compound-path': exportCompoundPath,
- 'placed-symbol': exportPlacedSymbol,
- 'point-text': exportText
- };
-
- function applyStyle(item, node) {
- var attrs = {},
- parent = item.getParent();
-
- if (item._name != null)
- attrs.id = item._name;
-
- Base.each(SVGStyles, function(entry) {
- var get = entry.get,
- type = entry.type,
- value = item[get]();
- if (!parent || !Base.equals(parent[get](), value)) {
- if (type === 'color' && value != null) {
- var alpha = value.getAlpha();
- if (alpha < 1)
- attrs[entry.attribute + '-opacity'] = alpha;
- }
- attrs[entry.attribute] = value == null
- ? 'none'
- : type === 'number'
- ? formatter.number(value)
- : type === 'color'
- ? value.gradient
- ? exportGradient(value, item)
- : value.toCSS(true)
- : type === 'array'
- ? value.join(',')
- : type === 'lookup'
- ? entry.toSVG[value]
- : value;
- }
- });
-
- if (attrs.opacity === 1)
- delete attrs.opacity;
-
- if (item._visibility != null && !item._visibility)
- attrs.visibility = 'hidden';
-
- return setAttributes(node, attrs);
- }
-
- var definitions;
- function getDefinition(item, type) {
- if (!definitions)
- definitions = { ids: {}, svgs: {} };
- return item && definitions.svgs[type + '-' + item._id];
- }
-
- function setDefinition(item, node, type) {
- if (!definitions)
- getDefinition();
- var id = definitions.ids[type] = (definitions.ids[type] || 0) + 1;
- node.id = type + '-' + id;
- definitions.svgs[type + '-' + item._id] = node;
- }
-
- function exportDefinitions(node, options) {
- var svg = node,
- defs = null;
- if (definitions) {
- svg = node.nodeName.toLowerCase() === 'svg' && node;
- for (var i in definitions.svgs) {
- if (!defs) {
- if (!svg) {
- svg = createElement('svg');
- svg.appendChild(node);
- }
- defs = svg.insertBefore(createElement('defs'),
- svg.firstChild);
- }
- defs.appendChild(definitions.svgs[i]);
- }
- definitions = null;
- }
- return options.asString
- ? new XMLSerializer().serializeToString(svg)
- : svg;
- }
-
- function exportSVG(item, options) {
- var exporter = exporters[item._type],
- node = exporter && exporter(item, options);
- if (node && item._data)
- node.setAttribute('data-paper-data', JSON.stringify(item._data));
- return node && applyStyle(item, node);
- }
-
- function setOptions(options) {
- if (!options)
- options = {};
- formatter = new Formatter(options.precision);
- return options;
- }
-
- Item.inject({
- exportSVG: function(options) {
- options = setOptions(options);
- return exportDefinitions(exportSVG(this, options), options);
- }
- });
-
- Project.inject({
- exportSVG: function(options) {
- options = setOptions(options);
- var layers = this.layers,
- size = this.view.getSize(),
- node = createElement('svg', {
- x: 0,
- y: 0,
- width: size.width,
- height: size.height,
- version: '1.1',
- xmlns: 'http://www.w3.org/2000/svg',
- 'xmlns:xlink': 'http://www.w3.org/1999/xlink'
- });
- for (var i = 0, l = layers.length; i < l; i++)
- node.appendChild(exportSVG(layers[i], options));
- return exportDefinitions(node, options);
- }
- });
-};
-
-new function() {
-
- function getValue(node, name, isString, allowNull) {
- var namespace = SVGNamespaces[name],
- value = namespace
- ? node.getAttributeNS(namespace, name)
- : node.getAttribute(name);
- if (value === 'null')
- value = null;
- return value == null
- ? allowNull
- ? null
- : isString
- ? ''
- : 0
- : isString
- ? value
- : parseFloat(value);
- }
-
- function getPoint(node, x, y, allowNull) {
- x = getValue(node, x, false, allowNull);
- y = getValue(node, y, false, allowNull);
- return allowNull && (x == null || y == null) ? null
- : new Point(x, y);
- }
-
- function getSize(node, w, h, allowNull) {
- w = getValue(node, w, false, allowNull);
- h = getValue(node, h, false, allowNull);
- return allowNull && (w == null || h == null) ? null
- : new Size(w, h);
- }
-
- function convertValue(value, type, lookup) {
- return value === 'none'
- ? null
- : type === 'number'
- ? parseFloat(value)
- : type === 'array'
- ? value ? value.split(/[\s,]+/g).map(parseFloat) : []
- : type === 'color'
- ? getDefinition(value) || value
- : type === 'lookup'
- ? lookup[value]
- : value;
- }
-
- function importGroup(node, type, isRoot, options) {
- var nodes = node.childNodes,
- isClip = type === 'clippath',
- item = new Group(),
- project = item._project,
- currentStyle = project._currentStyle,
- children = [];
- if (!isClip) {
- item._transformContent = false;
- item = applyAttributes(item, node, isRoot);
- project._currentStyle = item._style.clone();
- }
- for (var i = 0, l = nodes.length; i < l; i++) {
- var childNode = nodes[i],
- child;
- if (childNode.nodeType === 1
- && (child = importSVG(childNode, false, options))
- && !(child instanceof Symbol))
- children.push(child);
- }
- item.addChildren(children);
- if (isClip)
- item = applyAttributes(item.reduce(), node, isRoot);
- project._currentStyle = currentStyle;
- if (isClip || type === 'defs') {
- item.remove();
- item = null;
- }
- return item;
- }
-
- function importPoly(node, type) {
- var path = new Path(),
- points = node.points;
- path.moveTo(points.getItem(0));
- for (var i = 1, l = points.numberOfItems; i < l; i++)
- path.lineTo(points.getItem(i));
- if (type === 'polygon')
- path.closePath();
- return path;
- }
-
- function importPath(node) {
- var data = node.getAttribute('d'),
- path = data.match(/m/gi).length > 1
- ? new CompoundPath()
- : new Path();
- path.setPathData(data);
- return path;
- }
-
- function importGradient(node, type) {
- var nodes = node.childNodes,
- stops = [];
- for (var i = 0, l = nodes.length; i < l; i++) {
- var child = nodes[i];
- if (child.nodeType === 1)
- stops.push(applyAttributes(new GradientStop(), child));
- }
- var isRadial = type === 'radialgradient',
- gradient = new Gradient(stops, isRadial),
- origin, destination, highlight;
- if (isRadial) {
- origin = getPoint(node, 'cx', 'cy');
- destination = origin.add(getValue(node, 'r'), 0);
- highlight = getPoint(node, 'fx', 'fy', true);
- } else {
- origin = getPoint(node, 'x1', 'y1');
- destination = getPoint(node, 'x2', 'y2');
- }
- applyAttributes(
- new Color(gradient, origin, destination, highlight), node);
- return null;
- }
-
- var importers = {
- '#document': function (node, type, isRoot, options) {
- var nodes = node.childNodes;
- for (var i = 0, l = nodes.length; i < l; i++) {
- var child = nodes[i];
- if (child.nodeType === 1) {
- var next = child.nextSibling;
- document.body.appendChild(child);
- var item = importSVG(child, isRoot, options);
- if (next) {
- node.insertBefore(child, next);
- } else {
- node.appendChild(child);
- }
- return item;
- }
- }
- },
- g: importGroup,
- svg: importGroup,
- clippath: importGroup,
- polygon: importPoly,
- polyline: importPoly,
- path: importPath,
- lineargradient: importGradient,
- radialgradient: importGradient,
-
- image: function (node) {
- var raster = new Raster(getValue(node, 'href', true));
- raster.attach('load', function() {
- var size = getSize(node, 'width', 'height');
- this.setSize(size);
- var center = this._matrix._transformPoint(
- getPoint(node, 'x', 'y').add(size.divide(2)));
- this.translate(center);
- });
- return raster;
- },
-
- symbol: function(node, type, isRoot, options) {
- return new Symbol(importGroup(node, type, isRoot, options), true);
- },
-
- defs: importGroup,
-
- use: function(node) {
- var id = (getValue(node, 'href', true) || '').substring(1),
- definition = definitions[id],
- point = getPoint(node, 'x', 'y');
- return definition
- ? definition instanceof Symbol
- ? definition.place(point)
- : definition.clone().translate(point)
- : null;
- },
-
- circle: function(node) {
- return new Shape.Circle(getPoint(node, 'cx', 'cy'),
- getValue(node, 'r'));
- },
-
- ellipse: function(node) {
- return new Shape.Ellipse({
- center: getPoint(node, 'cx', 'cy'),
- radius: getSize(node, 'rx', 'ry')
- });
- },
-
- rect: function(node) {
- var point = getPoint(node, 'x', 'y'),
- size = getSize(node, 'width', 'height'),
- radius = getSize(node, 'rx', 'ry');
- return new Shape.Rectangle(new Rectangle(point, size), radius);
- },
-
- line: function(node) {
- return new Path.Line(getPoint(node, 'x1', 'y1'),
- getPoint(node, 'x2', 'y2'));
- },
-
- text: function(node) {
- var text = new PointText(getPoint(node, 'x', 'y')
- .add(getPoint(node, 'dx', 'dy')));
- text.setContent(node.textContent.trim() || '');
- return text;
- }
- };
-
- function applyTransform(item, value, name, node) {
- var transforms = (node.getAttribute(name) || '').split(/\)\s*/g),
- matrix = new Matrix();
- for (var i = 0, l = transforms.length; i < l; i++) {
- var transform = transforms[i];
- if (!transform)
- break;
- var parts = transform.split('('),
- command = parts[0],
- v = parts[1].split(/[\s,]+/g);
- for (var j = 0, m = v.length; j < m; j++)
- v[j] = parseFloat(v[j]);
- switch (command) {
- case 'matrix':
- matrix.concatenate(
- new Matrix(v[0], v[1], v[2], v[3], v[4], v[5]));
- break;
- case 'rotate':
- matrix.rotate(v[0], v[1], v[2]);
- break;
- case 'translate':
- matrix.translate(v[0], v[1]);
- break;
- case 'scale':
- matrix.scale(v);
- break;
- case 'skewX':
- case 'skewY':
- var value = Math.tan(v[0] * Math.PI / 180),
- isX = command == 'skewX';
- matrix.shear(isX ? value : 0, isX ? 0 : value);
- break;
- }
- }
- item.transform(matrix);
- }
-
- function applyOpacity(item, value, name) {
- var color = item[name === 'fill-opacity' ? 'getFillColor'
- : 'getStrokeColor']();
- if (color)
- color.setAlpha(parseFloat(value));
- }
-
- var attributes = Base.each(SVGStyles, function(entry) {
- this[entry.attribute] = function(item, value) {
- item[entry.set](convertValue(value, entry.type, entry.fromSVG));
- if (entry.type === 'color' && item instanceof Shape) {
- var color = item[entry.get]();
- if (color)
- color.transform(new Matrix().translate(
- item.getPosition(true).negate()));
- }
- };
- }, {
- id: function(item, value) {
- definitions[value] = item;
- if (item.setName)
- item.setName(value);
- },
-
- 'clip-path': function(item, value) {
- var clip = getDefinition(value);
- if (clip) {
- clip = clip.clone();
- clip.setClipMask(true);
- if (item instanceof Group) {
- item.insertChild(0, clip);
- } else {
- return new Group(clip, item);
- }
- }
- },
-
- gradientTransform: applyTransform,
- transform: applyTransform,
-
- 'fill-opacity': applyOpacity,
- 'stroke-opacity': applyOpacity,
-
- visibility: function(item, value) {
- item.setVisible(value === 'visible');
- },
-
- 'stop-color': function(item, value) {
- if (item.setColor)
- item.setColor(value);
- },
-
- 'stop-opacity': function(item, value) {
- if (item._color)
- item._color.setAlpha(parseFloat(value));
- },
-
- offset: function(item, value) {
- var percentage = value.match(/(.*)%$/);
- item.setRampPoint(percentage
- ? percentage[1] / 100
- : parseFloat(value));
- },
-
- viewBox: function(item, value, name, node, styles) {
- var rect = new Rectangle(convertValue(value, 'array')),
- size = getSize(node, 'width', 'height', true);
- if (item instanceof Group) {
- var scale = size ? rect.getSize().divide(size) : 1,
- matrix = new Matrix().translate(rect.getPoint()).scale(scale);
- item.transform(matrix.inverted());
- } else if (item instanceof Symbol) {
- if (size)
- rect.setSize(size);
- var clip = getAttribute(node, 'overflow', styles) != 'visible',
- group = item._definition;
- if (clip && !rect.contains(group.getBounds())) {
- clip = new Shape.Rectangle(rect).transform(group._matrix);
- clip.setClipMask(true);
- group.addChild(clip);
- }
- }
- }
- });
-
- function getAttribute(node, name, styles) {
- var attr = node.attributes[name],
- value = attr && attr.value;
- if (!value) {
- var style = Base.camelize(name);
- value = node.style[style];
- if (!value && styles.node[style] !== styles.parent[style])
- value = styles.node[style];
- }
- return !value
- ? undefined
- : value === 'none'
- ? null
- : value;
- }
-
- function applyAttributes(item, node, isRoot) {
- var styles = {
- node: DomElement.getStyles(node) || {},
- parent: !isRoot && DomElement.getStyles(node.parentNode) || {}
- };
- Base.each(attributes, function(apply, name) {
- var value = getAttribute(node, name, styles);
- if (value !== undefined)
- item = Base.pick(apply(item, value, name, node, styles), item);
- });
- return item;
- }
-
- var definitions = {};
- function getDefinition(value) {
- var match = value && value.match(/\((?:#|)([^)']+)/);
- return match && definitions[match[1]];
- }
-
- function importSVG(source, isRoot, options) {
- if (!source)
- return null;
- if (!options) {
- options = {};
- } else if (typeof options === 'function') {
- options = { onLoad: options };
- }
-
- var node = source,
- scope = paper;
-
- function onLoadCallback(svg) {
- paper = scope;
- var item = importSVG(svg, isRoot, options),
- onLoad = options.onLoad,
- view = scope.project && scope.project.view;
- if (onLoad)
- onLoad.call(this, item);
- view.draw(true);
- }
-
- if (isRoot) {
- if (typeof source === 'string' && !/^.*</.test(source)) {
- node = document.getElementById(source);
- if (node) {
- source = null;
- } else {
- return Http.request('get', source, onLoadCallback);
- }
- } else if (typeof File !== 'undefined' && source instanceof File) {
- var reader = new FileReader();
- reader.onload = function() {
- onLoadCallback(reader.result);
- };
- return reader.readAsText(source);
- }
- }
-
- if (typeof source === 'string')
- node = new DOMParser().parseFromString(source, 'image/svg+xml');
- if (!node.nodeName)
- throw new Error('Unsupported SVG source: ' + source);
- var type = node.nodeName.toLowerCase(),
- importer = importers[type],
- item = importer && importer(node, type, isRoot, options) || null,
- data = node.getAttribute && node.getAttribute('data-paper-data');
- if (item) {
- if (!(item instanceof Group))
- item = applyAttributes(item, node, isRoot);
- if (options.expandShapes && item instanceof Shape) {
- item.remove();
- item = item.toPath();
- }
- if (data)
- item._data = JSON.parse(data);
- }
- if (isRoot)
- definitions = {};
- return item;
- }
-
- Item.inject({
- importSVG: function(node, options) {
- return this.addChild(importSVG(node, true, options));
- }
- });
-
- Project.inject({
- importSVG: function(node, options) {
- this.activate();
- return importSVG(node, true, options);
- }
- });
-};
-
-paper = new (PaperScope.inject(new Base(Base.exports, {
- enumerable: true,
- Base: Base,
- Numerical: Numerical,
- DomElement: DomElement,
- DomEvent: DomEvent,
- Http: Http,
- Key: Key
-})))();
-
-if (typeof define === 'function' && define.amd)
- define('paper', paper);
-
-return paper;
-};
-
-paper.PaperScope.prototype.PaperScript = (function(root) {
- var Base = paper.Base,
- PaperScope = paper.PaperScope,
- PaperScript,
- exports, define,
- scope = this;
-!function(e,r){return"object"==typeof exports&&"object"==typeof module?r(exports):"function"==typeof define&&define.amd?define(["exports"],r):(r(e.acorn||(e.acorn={})),void 0)}(this,function(e){"use strict";function r(e){fr=e||{};for(var r in hr)Object.prototype.hasOwnProperty.call(fr,r)||(fr[r]=hr[r]);mr=fr.sourceFile||null}function t(e,r){var t=vr(pr,e);r+=" ("+t.line+":"+t.column+")";var n=new SyntaxError(r);throw n.pos=e,n.loc=t,n.raisedAt=br,n}function n(e){function r(e){if(1==e.length)return t+="return str === "+JSON.stringify(e[0])+";";t+="switch(str){";for(var r=0;r<e.length;++r)t+="case "+JSON.stringify(e[r])+":";t+="return true}return false;"}e=e.split(" ");var t="",n=[];e:for(var a=0;a<e.length;++a){for(var o=0;o<n.length;++o)if(n[o][0].length==e[a].length){n[o].push(e[a]);continue e}n.push([e[a]])}if(n.length>3){n.sort(function(e,r){return r.length-e.length}),t+="switch(str.length){";for(var a=0;a<n.length;++a){var i=n[a];t+="case "+i[0].length+":",r(i)}t+="}"}else r(e);return new Function("str",t)}function a(){this.line=Ar,this.column=br-Sr}function o(){Ar=1,br=Sr=0,Er=!0,u()}function i(e,r){gr=br,fr.locations&&(kr=new a),wr=e,u(),Cr=r,Er=e.beforeExpr}function s(){var e=fr.onComment&&fr.locations&&new a,r=br,n=pr.indexOf("*/",br+=2);if(-1===n&&t(br-2,"Unterminated comment"),br=n+2,fr.locations){Kt.lastIndex=r;for(var o;(o=Kt.exec(pr))&&o.index<br;)++Ar,Sr=o.index+o[0].length}fr.onComment&&fr.onComment(!0,pr.slice(r+2,n),r,br,e,fr.locations&&new a)}function c(){for(var e=br,r=fr.onComment&&fr.locations&&new a,t=pr.charCodeAt(br+=2);dr>br&&10!==t&&13!==t&&8232!==t&&8329!==t;)++br,t=pr.charCodeAt(br);fr.onComment&&fr.onComment(!1,pr.slice(e+2,br),e,br,r,fr.locations&&new a)}function u(){for(;dr>br;){var e=pr.charCodeAt(br);if(32===e)++br;else if(13===e){++br;var r=pr.charCodeAt(br);10===r&&++br,fr.locations&&(++Ar,Sr=br)}else if(10===e)++br,++Ar,Sr=br;else if(14>e&&e>8)++br;else if(47===e){var r=pr.charCodeAt(br+1);if(42===r)s();else{if(47!==r)break;c()}}else if(160===e)++br;else{if(!(e>=5760&&Jt.test(String.fromCharCode(e))))break;++br}}}function l(){var e=pr.charCodeAt(br+1);return e>=48&&57>=e?E(!0):(++br,i(xt))}function f(){var e=pr.charCodeAt(br+1);return Er?(++br,k()):61===e?x(Et,2):x(wt,1)}function p(){var e=pr.charCodeAt(br+1);return 61===e?x(Et,2):x(Ft,1)}function d(e){var r=pr.charCodeAt(br+1);return r===e?x(124===e?Lt:Ut,2):61===r?x(Et,2):x(124===e?Rt:Vt,1)}function m(){var e=pr.charCodeAt(br+1);return 61===e?x(Et,2):x(Tt,1)}function h(e){var r=pr.charCodeAt(br+1);return r===e?x(St,2):61===r?x(Et,2):x(At,1)}function v(e){var r=pr.charCodeAt(br+1),t=1;return r===e?(t=62===e&&62===pr.charCodeAt(br+2)?3:2,61===pr.charCodeAt(br+t)?x(Et,t+1):x(jt,t)):(61===r&&(t=61===pr.charCodeAt(br+2)?3:2),x(Ot,t))}function b(e){var r=pr.charCodeAt(br+1);return 61===r?x(qt,61===pr.charCodeAt(br+2)?3:2):x(61===e?Ct:It,1)}function y(e){switch(e){case 46:return l();case 40:return++br,i(ht);case 41:return++br,i(vt);case 59:return++br,i(yt);case 44:return++br,i(bt);case 91:return++br,i(ft);case 93:return++br,i(pt);case 123:return++br,i(dt);case 125:return++br,i(mt);case 58:return++br,i(gt);case 63:return++br,i(kt);case 48:var r=pr.charCodeAt(br+1);if(120===r||88===r)return C();case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return E(!1);case 34:case 39:return A(e);case 47:return f(e);case 37:case 42:return p();case 124:case 38:return d(e);case 94:return m();case 43:case 45:return h(e);case 60:case 62:return v(e);case 61:case 33:return b(e);case 126:return x(It,1)}return!1}function g(e){if(e?br=yr+1:yr=br,fr.locations&&(xr=new a),e)return k();if(br>=dr)return i(Br);var r=pr.charCodeAt(br);if(Qt(r)||92===r)return L();var n=y(r);if(n===!1){var o=String.fromCharCode(r);if("\\"===o||$t.test(o))return L();t(br,"Unexpected character '"+o+"'")}return n}function x(e,r){var t=pr.slice(br,br+r);br+=r,i(e,t)}function k(){for(var e,r,n="",a=br;;){br>=dr&&t(a,"Unterminated regular expression");var o=pr.charAt(br);if(Gt.test(o)&&t(a,"Unterminated regular expression"),e)e=!1;else{if("["===o)r=!0;else if("]"===o&&r)r=!1;else if("/"===o&&!r)break;e="\\"===o}++br}var n=pr.slice(a,br);++br;var s=I();return s&&!/^[gmsiy]*$/.test(s)&&t(a,"Invalid regexp flag"),i(jr,new RegExp(n,s))}function w(e,r){for(var t=br,n=0,a=0,o=null==r?1/0:r;o>a;++a){var i,s=pr.charCodeAt(br);if(i=s>=97?s-97+10:s>=65?s-65+10:s>=48&&57>=s?s-48:1/0,i>=e)break;++br,n=n*e+i}return br===t||null!=r&&br-t!==r?null:n}function C(){br+=2;var e=w(16);return null==e&&t(yr+2,"Expected hexadecimal number"),Qt(pr.charCodeAt(br))&&t(br,"Identifier directly after number"),i(Or,e)}function E(e){var r=br,n=!1,a=48===pr.charCodeAt(br);e||null!==w(10)||t(r,"Invalid number"),46===pr.charCodeAt(br)&&(++br,w(10),n=!0);var o=pr.charCodeAt(br);(69===o||101===o)&&(o=pr.charCodeAt(++br),(43===o||45===o)&&++br,null===w(10)&&t(r,"Invalid number"),n=!0),Qt(pr.charCodeAt(br))&&t(br,"Identifier directly after number");var s,c=pr.slice(r,br);return n?s=parseFloat(c):a&&1!==c.length?/[89]/.test(c)||Vr?t(r,"Invalid number"):s=parseInt(c,8):s=parseInt(c,10),i(Or,s)}function A(e){br++;for(var r="";;){br>=dr&&t(yr,"Unterminated string constant");var n=pr.charCodeAt(br);if(n===e)return++br,i(Fr,r);if(92===n){n=pr.charCodeAt(++br);var a=/^[0-7]+/.exec(pr.slice(br,br+3));for(a&&(a=a[0]);a&&parseInt(a,8)>255;)a=a.slice(0,a.length-1);if("0"===a&&(a=null),++br,a)Vr&&t(br-2,"Octal literal in strict mode"),r+=String.fromCharCode(parseInt(a,8)),br+=a.length-1;else switch(n){case 110:r+="\n";break;case 114:r+="\r";break;case 120:r+=String.fromCharCode(S(2));break;case 117:r+=String.fromCharCode(S(4));break;case 85:r+=String.fromCharCode(S(8));break;case 116:r+=" ";break;case 98:r+="\b";break;case 118:r+="";break;case 102:r+="\f";break;case 48:r+="\0";break;case 13:10===pr.charCodeAt(br)&&++br;case 10:fr.locations&&(Sr=br,++Ar);break;default:r+=String.fromCharCode(n)}}else(13===n||10===n||8232===n||8329===n)&&t(yr,"Unterminated string constant"),r+=String.fromCharCode(n),++br}}function S(e){var r=w(16,e);return null===r&&t(yr,"Bad character escape sequence"),r}function I(){Bt=!1;for(var e,r=!0,n=br;;){var a=pr.charCodeAt(br);if(Yt(a))Bt&&(e+=pr.charAt(br)),++br;else{if(92!==a)break;Bt||(e=pr.slice(n,br)),Bt=!0,117!=pr.charCodeAt(++br)&&t(br,"Expecting Unicode escape sequence \\uXXXX"),++br;var o=S(4),i=String.fromCharCode(o);i||t(br-1,"Invalid Unicode escape"),(r?Qt(o):Yt(o))||t(br-4,"Invalid Unicode escape"),e+=i}r=!1}return Bt?e:pr.slice(n,br)}function L(){var e=I(),r=Dr;return Bt||(Wt(e)?r=lt[e]:(fr.forbidReserved&&(3===fr.ecmaVersion?Mt:zt)(e)||Vr&&Xt(e))&&t(yr,"The keyword '"+e+"' is reserved")),i(r,e)}function U(){Ir=yr,Lr=gr,Ur=kr,g()}function R(e){for(Vr=e,br=Lr;Sr>br;)Sr=pr.lastIndexOf("\n",Sr-2)+1,--Ar;u(),g()}function T(){this.type=null,this.start=yr,this.end=null}function V(){this.start=xr,this.end=null,null!==mr&&(this.source=mr)}function q(){var e=new T;return fr.locations&&(e.loc=new V),fr.ranges&&(e.range=[yr,0]),e}function O(e){var r=new T;return r.start=e.start,fr.locations&&(r.loc=new V,r.loc.start=e.loc.start),fr.ranges&&(r.range=[e.range[0],0]),r}function j(e,r){return e.type=r,e.end=Lr,fr.locations&&(e.loc.end=Ur),fr.ranges&&(e.range[1]=Lr),e}function F(e){return fr.ecmaVersion>=5&&"ExpressionStatement"===e.type&&"Literal"===e.expression.type&&"use strict"===e.expression.value}function D(e){return wr===e?(U(),!0):void 0}function B(){return!fr.strictSemicolons&&(wr===Br||wr===mt||Gt.test(pr.slice(Lr,yr)))}function M(){D(yt)||B()||X()}function z(e){wr===e?U():X()}function X(){t(yr,"Unexpected token")}function N(e){"Identifier"!==e.type&&"MemberExpression"!==e.type&&t(e.start,"Assigning to rvalue"),Vr&&"Identifier"===e.type&&Nt(e.name)&&t(e.start,"Assigning to "+e.name+" in strict mode")}function W(e){Ir=Lr=br,fr.locations&&(Ur=new a),Rr=Vr=null,Tr=[],g();var r=e||q(),t=!0;for(e||(r.body=[]);wr!==Br;){var n=J();r.body.push(n),t&&F(n)&&R(!0),t=!1}return j(r,"Program")}function J(){wr===wt&&g(!0);var e=wr,r=q();switch(e){case Mr:case Nr:U();var n=e===Mr;D(yt)||B()?r.label=null:wr!==Dr?X():(r.label=lr(),M());for(var a=0;a<Tr.length;++a){var o=Tr[a];if(null==r.label||o.name===r.label.name){if(null!=o.kind&&(n||"loop"===o.kind))break;if(r.label&&n)break}}return a===Tr.length&&t(r.start,"Unsyntactic "+e.keyword),j(r,n?"BreakStatement":"ContinueStatement");case Wr:return U(),M(),j(r,"DebuggerStatement");case Pr:return U(),Tr.push(Zt),r.body=J(),Tr.pop(),z(tt),r.test=P(),M(),j(r,"DoWhileStatement");case _r:if(U(),Tr.push(Zt),z(ht),wr===yt)return $(r,null);if(wr===rt){var i=q();return U(),G(i,!0),1===i.declarations.length&&D(ut)?_(r,i):$(r,i)}var i=K(!1,!0);return D(ut)?(N(i),_(r,i)):$(r,i);case Gr:return U(),cr(r,!0);case Kr:return U(),r.test=P(),r.consequent=J(),r.alternate=D(Hr)?J():null,j(r,"IfStatement");case Qr:return Rr||t(yr,"'return' outside of function"),U(),D(yt)||B()?r.argument=null:(r.argument=K(),M()),j(r,"ReturnStatement");case Yr:U(),r.discriminant=P(),r.cases=[],z(dt),Tr.push(en);for(var s,c;wr!=mt;)if(wr===zr||wr===Jr){var u=wr===zr;s&&j(s,"SwitchCase"),r.cases.push(s=q()),s.consequent=[],U(),u?s.test=K():(c&&t(Ir,"Multiple default clauses"),c=!0,s.test=null),z(gt)}else s||X(),s.consequent.push(J());return s&&j(s,"SwitchCase"),U(),Tr.pop(),j(r,"SwitchStatement");case Zr:return U(),Gt.test(pr.slice(Lr,yr))&&t(Lr,"Illegal newline after throw"),r.argument=K(),M(),j(r,"ThrowStatement");case et:if(U(),r.block=H(),r.handler=null,wr===Xr){var l=q();U(),z(ht),l.param=lr(),Vr&&Nt(l.param.name)&&t(l.param.start,"Binding "+l.param.name+" in strict mode"),z(vt),l.guard=null,l.body=H(),r.handler=j(l,"CatchClause")}return r.guardedHandlers=qr,r.finalizer=D($r)?H():null,r.handler||r.finalizer||t(r.start,"Missing catch or finally clause"),j(r,"TryStatement");case rt:return U(),r=G(r),M(),r;case tt:return U(),r.test=P(),Tr.push(Zt),r.body=J(),Tr.pop(),j(r,"WhileStatement");case nt:return Vr&&t(yr,"'with' in strict mode"),U(),r.object=P(),r.body=J(),j(r,"WithStatement");case dt:return H();case yt:return U(),j(r,"EmptyStatement");default:var f=Cr,p=K();if(e===Dr&&"Identifier"===p.type&&D(gt)){for(var a=0;a<Tr.length;++a)Tr[a].name===f&&t(p.start,"Label '"+f+"' is already declared");var d=wr.isLoop?"loop":wr===Yr?"switch":null;return Tr.push({name:f,kind:d}),r.body=J(),Tr.pop(),r.label=p,j(r,"LabeledStatement")}return r.expression=p,M(),j(r,"ExpressionStatement")}}function P(){z(ht);var e=K();return z(vt),e}function H(e){var r,t=q(),n=!0,a=!1;for(t.body=[],z(dt);!D(mt);){var o=J();t.body.push(o),n&&e&&F(o)&&(r=a,R(a=!0)),n=!1}return a&&!r&&R(!1),j(t,"BlockStatement")}function $(e,r){return e.init=r,z(yt),e.test=wr===yt?null:K(),z(yt),e.update=wr===vt?null:K(),z(vt),e.body=J(),Tr.pop(),j(e,"ForStatement")}function _(e,r){return e.left=r,e.right=K(),z(vt),e.body=J(),Tr.pop(),j(e,"ForInStatement")}function G(e,r){for(e.declarations=[],e.kind="var";;){var n=q();if(n.id=lr(),Vr&&Nt(n.id.name)&&t(n.id.start,"Binding "+n.id.name+" in strict mode"),n.init=D(Ct)?K(!0,r):null,e.declarations.push(j(n,"VariableDeclarator")),!D(bt))break}return j(e,"VariableDeclaration")}function K(e,r){var t=Q(r);if(!e&&wr===bt){var n=O(t);for(n.expressions=[t];D(bt);)n.expressions.push(Q(r));return j(n,"SequenceExpression")}return t}function Q(e){var r=Y(e);if(wr.isAssign){var t=O(r);return t.operator=Cr,t.left=r,U(),t.right=Q(e),N(r),j(t,"AssignmentExpression")}return r}function Y(e){var r=Z(e);if(D(kt)){var t=O(r);return t.test=r,t.consequent=K(!0),z(gt),t.alternate=K(!0,e),j(t,"ConditionalExpression")}return r}function Z(e){return er(rr(),-1,e)}function er(e,r,t){var n=wr.binop;if(null!=n&&(!t||wr!==ut)&&n>r){var a=O(e);a.left=e,a.operator=Cr,U(),a.right=er(rr(),n,t);var a=j(a,/&&|\|\|/.test(a.operator)?"LogicalExpression":"BinaryExpression");return er(a,r,t)}return e}function rr(){if(wr.prefix){var e=q(),r=wr.isUpdate;return e.operator=Cr,e.prefix=!0,U(),e.argument=rr(),r?N(e.argument):Vr&&"delete"===e.operator&&"Identifier"===e.argument.type&&t(e.start,"Deleting local variable in strict mode"),j(e,r?"UpdateExpression":"UnaryExpression")}for(var n=tr();wr.postfix&&!B();){var e=O(n);e.operator=Cr,e.prefix=!1,e.argument=n,N(n),U(),n=j(e,"UpdateExpression")}return n}function tr(){return nr(ar())}function nr(e,r){if(D(xt)){var t=O(e);return t.object=e,t.property=lr(!0),t.computed=!1,nr(j(t,"MemberExpression"),r)}if(D(ft)){var t=O(e);return t.object=e,t.property=K(),t.computed=!0,z(pt),nr(j(t,"MemberExpression"),r)}if(!r&&D(ht)){var t=O(e);return t.callee=e,t.arguments=ur(vt,!1),nr(j(t,"CallExpression"),r)}return e}function ar(){switch(wr){case ot:var e=q();return U(),j(e,"ThisExpression");case Dr:return lr();case Or:case Fr:case jr:var e=q();return e.value=Cr,e.raw=pr.slice(yr,gr),U(),j(e,"Literal");case it:case st:case ct:var e=q();return e.value=wr.atomValue,e.raw=wr.keyword,U(),j(e,"Literal");case ht:var r=xr,t=yr;U();var n=K();return n.start=t,n.end=gr,fr.locations&&(n.loc.start=r,n.loc.end=kr),fr.ranges&&(n.range=[t,gr]),z(vt),n;case ft:var e=q();return U(),e.elements=ur(pt,!0,!0),j(e,"ArrayExpression");case dt:return ir();case Gr:var e=q();return U(),cr(e,!1);case at:return or();default:X()}}function or(){var e=q();return U(),e.callee=nr(ar(),!0),e.arguments=D(ht)?ur(vt,!1):qr,j(e,"NewExpression")}function ir(){var e=q(),r=!0,n=!1;for(e.properties=[],U();!D(mt);){if(r)r=!1;else if(z(bt),fr.allowTrailingCommas&&D(mt))break;var a,o={key:sr()},i=!1;if(D(gt)?(o.value=K(!0),a=o.kind="init"):fr.ecmaVersion>=5&&"Identifier"===o.key.type&&("get"===o.key.name||"set"===o.key.name)?(i=n=!0,a=o.kind=o.key.name,o.key=sr(),wr!==ht&&X(),o.value=cr(q(),!1)):X(),"Identifier"===o.key.type&&(Vr||n))for(var s=0;s<e.properties.length;++s){var c=e.properties[s];if(c.key.name===o.key.name){var u=a==c.kind||i&&"init"===c.kind||"init"===a&&("get"===c.kind||"set"===c.kind);u&&!Vr&&"init"===a&&"init"===c.kind&&(u=!1),u&&t(o.key.start,"Redefinition of property")}}e.properties.push(o)}return j(e,"ObjectExpression")}function sr(){return wr===Or||wr===Fr?ar():lr(!0)}function cr(e,r){wr===Dr?e.id=lr():r?X():e.id=null,e.params=[];var n=!0;for(z(ht);!D(vt);)n?n=!1:z(bt),e.params.push(lr());var a=Rr,o=Tr;if(Rr=!0,Tr=[],e.body=H(!0),Rr=a,Tr=o,Vr||e.body.body.length&&F(e.body.body[0]))for(var i=e.id?-1:0;i<e.params.length;++i){var s=0>i?e.id:e.params[i];if((Xt(s.name)||Nt(s.name))&&t(s.start,"Defining '"+s.name+"' in strict mode"),i>=0)for(var c=0;i>c;++c)s.name===e.params[c].name&&t(s.start,"Argument name clash in strict mode")}return j(e,r?"FunctionDeclaration":"FunctionExpression")}function ur(e,r,t){for(var n=[],a=!0;!D(e);){if(a)a=!1;else if(z(bt),r&&fr.allowTrailingCommas&&D(e))break;t&&wr===bt?n.push(null):n.push(K(!0))}return n}function lr(e){var r=q();return r.name=wr===Dr?Cr:e&&!fr.forbidReserved&&wr.keyword||X(),U(),j(r,"Identifier")}e.version="0.3.2";var fr,pr,dr,mr;e.parse=function(e,t){return pr=String(e),dr=pr.length,r(t),o(),W(fr.program)};var hr=e.defaultOptions={ecmaVersion:5,strictSemicolons:!1,allowTrailingCommas:!0,forbidReserved:!1,locations:!1,onComment:null,ranges:!1,program:null,sourceFile:null},vr=e.getLineInfo=function(e,r){for(var t=1,n=0;;){Kt.lastIndex=n;var a=Kt.exec(e);if(!(a&&a.index<r))break;++t,n=a.index+a[0].length}return{line:t,column:r-n}};e.tokenize=function(e,t){function n(e){return g(e),a.start=yr,a.end=gr,a.startLoc=xr,a.endLoc=kr,a.type=wr,a.value=Cr,a}pr=String(e),dr=pr.length,r(t),o();var a={};return n.jumpTo=function(e,r){if(br=e,fr.locations){Ar=1,Sr=Kt.lastIndex=0;for(var t;(t=Kt.exec(pr))&&t.index<e;)++Ar,Sr=t.index+t[0].length}Er=r,u()},n};var br,yr,gr,xr,kr,wr,Cr,Er,Ar,Sr,Ir,Lr,Ur,Rr,Tr,Vr,qr=[],Or={type:"num"},jr={type:"regexp"},Fr={type:"string"},Dr={type:"name"},Br={type:"eof"},Mr={keyword:"break"},zr={keyword:"case",beforeExpr:!0},Xr={keyword:"catch"},Nr={keyword:"continue"},Wr={keyword:"debugger"},Jr={keyword:"default"},Pr={keyword:"do",isLoop:!0},Hr={keyword:"else",beforeExpr:!0},$r={keyword:"finally"},_r={keyword:"for",isLoop:!0},Gr={keyword:"function"},Kr={keyword:"if"},Qr={keyword:"return",beforeExpr:!0},Yr={keyword:"switch"},Zr={keyword:"throw",beforeExpr:!0},et={keyword:"try"},rt={keyword:"var"},tt={keyword:"while",isLoop:!0},nt={keyword:"with"},at={keyword:"new",beforeExpr:!0},ot={keyword:"this"},it={keyword:"null",atomValue:null},st={keyword:"true",atomValue:!0},ct={keyword:"false",atomValue:!1},ut={keyword:"in",binop:7,beforeExpr:!0},lt={"break":Mr,"case":zr,"catch":Xr,"continue":Nr,"debugger":Wr,"default":Jr,"do":Pr,"else":Hr,"finally":$r,"for":_r,"function":Gr,"if":Kr,"return":Qr,"switch":Yr,"throw":Zr,"try":et,"var":rt,"while":tt,"with":nt,"null":it,"true":st,"false":ct,"new":at,"in":ut,"instanceof":{keyword:"instanceof",binop:7,beforeExpr:!0},"this":ot,"typeof":{keyword:"typeof",prefix:!0,beforeExpr:!0},"void":{keyword:"void",prefix:!0,beforeExpr:!0},"delete":{keyword:"delete",prefix:!0,beforeExpr:!0}},ft={type:"[",beforeExpr:!0},pt={type:"]"},dt={type:"{",beforeExpr:!0},mt={type:"}"},ht={type:"(",beforeExpr:!0},vt={type:")"},bt={type:",",beforeExpr:!0},yt={type:";",beforeExpr:!0},gt={type:":",beforeExpr:!0},xt={type:"."},kt={type:"?",beforeExpr:!0},wt={binop:10,beforeExpr:!0},Ct={isAssign:!0,beforeExpr:!0},Et={isAssign:!0,beforeExpr:!0},At={binop:9,prefix:!0,beforeExpr:!0},St={postfix:!0,prefix:!0,isUpdate:!0},It={prefix:!0,beforeExpr:!0},Lt={binop:1,beforeExpr:!0},Ut={binop:2,beforeExpr:!0},Rt={binop:3,beforeExpr:!0},Tt={binop:4,beforeExpr:!0},Vt={binop:5,beforeExpr:!0},qt={binop:6,beforeExpr:!0},Ot={binop:7,beforeExpr:!0},jt={binop:8,beforeExpr:!0},Ft={binop:10,beforeExpr:!0};e.tokTypes={bracketL:ft,bracketR:pt,braceL:dt,braceR:mt,parenL:ht,parenR:vt,comma:bt,semi:yt,colon:gt,dot:xt,question:kt,slash:wt,eq:Ct,name:Dr,eof:Br,num:Or,regexp:jr,string:Fr};for(var Dt in lt)e.tokTypes["_"+Dt]=lt[Dt];var Bt,Mt=n("abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile"),zt=n("class enum extends super const export import"),Xt=n("implements interface let package private protected public static yield"),Nt=n("eval arguments"),Wt=n("break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this"),Jt=/[\u1680\u180e\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]/,Pt="\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05d0-\u05ea\u05f0-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u08a0\u08a2-\u08ac\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097f\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d\u0c58\u0c59\u0c60\u0c61\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d60\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191c\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19c1-\u19c7\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2e2f\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua697\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa80-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc",Ht="\u0300-\u036f\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u0620-\u0649\u0672-\u06d3\u06e7-\u06e8\u06fb-\u06fc\u0730-\u074a\u0800-\u0814\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0840-\u0857\u08e4-\u08fe\u0900-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962-\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09d7\u09df-\u09e0\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2-\u0ae3\u0ae6-\u0aef\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b56\u0b57\u0b5f-\u0b60\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c01-\u0c03\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62-\u0c63\u0c66-\u0c6f\u0c82\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2-\u0ce3\u0ce6-\u0cef\u0d02\u0d03\u0d46-\u0d48\u0d57\u0d62-\u0d63\u0d66-\u0d6f\u0d82\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0df2\u0df3\u0e34-\u0e3a\u0e40-\u0e45\u0e50-\u0e59\u0eb4-\u0eb9\u0ec8-\u0ecd\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f41-\u0f47\u0f71-\u0f84\u0f86-\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u1000-\u1029\u1040-\u1049\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u170e-\u1710\u1720-\u1730\u1740-\u1750\u1772\u1773\u1780-\u17b2\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u1920-\u192b\u1930-\u193b\u1951-\u196d\u19b0-\u19c0\u19c8-\u19c9\u19d0-\u19d9\u1a00-\u1a15\u1a20-\u1a53\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1b46-\u1b4b\u1b50-\u1b59\u1b6b-\u1b73\u1bb0-\u1bb9\u1be6-\u1bf3\u1c00-\u1c22\u1c40-\u1c49\u1c5b-\u1c7d\u1cd0-\u1cd2\u1d00-\u1dbe\u1e01-\u1f15\u200c\u200d\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2d81-\u2d96\u2de0-\u2dff\u3021-\u3028\u3099\u309a\ua640-\ua66d\ua674-\ua67d\ua69f\ua6f0-\ua6f1\ua7f8-\ua800\ua806\ua80b\ua823-\ua827\ua880-\ua881\ua8b4-\ua8c4\ua8d0-\ua8d9\ua8f3-\ua8f7\ua900-\ua909\ua926-\ua92d\ua930-\ua945\ua980-\ua983\ua9b3-\ua9c0\uaa00-\uaa27\uaa40-\uaa41\uaa4c-\uaa4d\uaa50-\uaa59\uaa7b\uaae0-\uaae9\uaaf2-\uaaf3\uabc0-\uabe1\uabec\uabed\uabf0-\uabf9\ufb20-\ufb28\ufe00-\ufe0f\ufe20-\ufe26\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f",$t=new RegExp("["+Pt+"]"),_t=new RegExp("["+Pt+Ht+"]"),Gt=/[\n\r\u2028\u2029]/,Kt=/\r\n|[\n\r\u2028\u2029]/g,Qt=e.isIdentifierStart=function(e){return 65>e?36===e:91>e?!0:97>e?95===e:123>e?!0:e>=170&&$t.test(String.fromCharCode(e))},Yt=e.isIdentifierChar=function(e){return 48>e?36===e:58>e?!0:65>e?!1:91>e?!0:97>e?95===e:123>e?!0:e>=170&&_t.test(String.fromCharCode(e))},Zt={kind:"loop"},en={kind:"switch"}});
-
- var binaryOperators = {
- '+': '_add',
- '-': '_subtract',
- '*': '_multiply',
- '/': '_divide',
- '%': '_modulo',
- '==': 'equals',
- '!=': 'equals'
- };
-
- var unaryOperators = {
- '-': '_negate',
- '+': null
- };
-
- var fields = Base.each(
- ['add', 'subtract', 'multiply', 'divide', 'modulo', 'negate'],
- function(name) {
- this['_' + name] = '#' + name;
- },
- {}
- );
- paper.Point.inject(fields);
- paper.Size.inject(fields);
- paper.Color.inject(fields);
-
- function _$_(left, operator, right) {
- var handler = binaryOperators[operator];
- if (left && left[handler]) {
- var res = left[handler](right);
- return operator === '!=' ? !res : res;
- }
- switch (operator) {
- case '+': return left + right;
- case '-': return left - right;
- case '*': return left * right;
- case '/': return left / right;
- case '%': return left % right;
- case '==': return left == right;
- case '!=': return left != right;
- }
- }
-
- function $_(operator, value) {
- var handler = unaryOperators[operator];
- if (handler && value && value[handler])
- return value[handler]();
- switch (operator) {
- case '+': return +value;
- case '-': return -value;
- }
- }
-
- function compile(code) {
-
- var insertions = [];
-
- function getOffset(offset) {
- for (var i = 0, l = insertions.length; i < l; i++) {
- var insertion = insertions[i];
- if (insertion[0] >= offset)
- break;
- offset += insertion[1];
- }
- return offset;
- }
-
- function getCode(node) {
- return code.substring(getOffset(node.range[0]),
- getOffset(node.range[1]));
- }
-
- function replaceCode(node, str) {
- var start = getOffset(node.range[0]),
- end = getOffset(node.range[1]);
- var insert = 0;
- for (var i = insertions.length - 1; i >= 0; i--) {
- if (start > insertions[i][0]) {
- insert = i + 1;
- break;
- }
- }
- insertions.splice(insert, 0, [start, str.length - end + start]);
- code = code.substring(0, start) + str + code.substring(end);
- }
-
- function walkAST(node, parent) {
- if (!node)
- return;
- for (var key in node) {
- if (key === 'range')
- continue;
- var value = node[key];
- if (Array.isArray(value)) {
- for (var i = 0, l = value.length; i < l; i++)
- walkAST(value[i], node);
- } else if (value && typeof value === 'object') {
- walkAST(value, node);
- }
- }
- switch (node && node.type) {
- case 'BinaryExpression':
- if (node.operator in binaryOperators
- && node.left.type !== 'Literal') {
- var left = getCode(node.left),
- right = getCode(node.right);
- replaceCode(node, '_$_(' + left + ', "' + node.operator
- + '", ' + right + ')');
- }
- break;
- case 'AssignmentExpression':
- if (/^.=$/.test(node.operator)
- && node.left.type !== 'Literal') {
- var left = getCode(node.left),
- right = getCode(node.right);
- replaceCode(node, left + ' = _$_(' + left + ', "'
- + node.operator[0] + '", ' + right + ')');
- }
- break;
- case 'UpdateExpression':
- if (!node.prefix && !(parent && (
- parent.type === 'BinaryExpression'
- && /^[=!<>]/.test(parent.operator)
- || parent.type === 'MemberExpression'
- && parent.computed))) {
- var arg = getCode(node.argument);
- replaceCode(node, arg + ' = _$_(' + arg + ', "'
- + node.operator[0] + '", 1)');
- }
- break;
- case 'UnaryExpression':
- if (node.operator in unaryOperators
- && node.argument.type !== 'Literal') {
- var arg = getCode(node.argument);
- replaceCode(node, '$_("' + node.operator + '", '
- + arg + ')');
- }
- break;
- }
- }
- walkAST(scope.acorn.parse(code, { ranges: true }));
- return code;
- }
-
- function evaluate(code, scope) {
- paper = scope;
- var view = scope.project && scope.project.view,
- res;
- with (scope) {
- (function() {
- var onActivate, onDeactivate, onEditOptions,
- onMouseDown, onMouseUp, onMouseDrag, onMouseMove,
- onKeyDown, onKeyUp, onFrame, onResize;
- code = compile(code);
- if (root.InstallTrigger) {
- var handle = PaperScript.handleException;
- if (!handle) {
- handle = PaperScript.handleException = function(e) {
- throw e.lineNumber >= lineNumber
- ? new Error(e.message, e.fileName,
- e.lineNumber - lineNumber)
- : e;
- }
- var lineNumber = new Error().lineNumber;
- lineNumber += (new Error().lineNumber - lineNumber) * 3;
- }
- try {
- res = eval(';' + code);
- } catch (e) {
- handle(e);
- }
- } else {
- res = eval(code);
- }
- if (/on(?:Key|Mouse)(?:Up|Down|Move|Drag)/.test(code)) {
- Base.each(paper.Tool.prototype._events, function(key) {
- var value = eval(key);
- if (value) {
- scope.getTool()[key] = value;
- }
- });
- }
- if (view) {
- view.setOnResize(onResize);
- view.fire('resize', {
- size: view.size,
- delta: new Point()
- });
- if (onFrame)
- view.setOnFrame(onFrame);
- view.draw();
- }
- }).call(scope);
- }
- return res;
- }
-
- function load() {
- Base.each(document.getElementsByTagName('script'), function(script) {
- if (/^text\/(?:x-|)paperscript$/.test(script.type)
- && !script.getAttribute('data-paper-ignore')) {
- var canvas = PaperScope.getAttribute(script, 'canvas'),
- scope = PaperScope.get(canvas)
- || new PaperScope(script).setup(canvas),
- src = script.src;
- if (src) {
- paper.Http.request('get', src, function(code) {
- evaluate(code, scope);
- });
- } else {
- evaluate(script.innerHTML, scope);
- }
- script.setAttribute('data-paper-ignore', true);
- }
- }, this);
- }
-
- if (document.readyState === 'complete') {
- setTimeout(load);
- } else {
- paper.DomEvent.add(window, { load: load });
- }
-
- return PaperScript = {
- compile: compile,
- evaluate: evaluate,
- load: load,
- lineNumberBase: 0
- };
-
-})(this);
--- a/server/python/django/renkanmanager/static/renkanmanager/lib/require.js Fri Apr 24 13:05:09 2015 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,36 +0,0 @@
-/*
- RequireJS 2.1.11 Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
- Available via the MIT or new BSD license.
- see: http://github.com/jrburke/requirejs for details
-*/
-var requirejs,require,define;
-(function(ca){function G(b){return"[object Function]"===M.call(b)}function H(b){return"[object Array]"===M.call(b)}function v(b,c){if(b){var d;for(d=0;d<b.length&&(!b[d]||!c(b[d],d,b));d+=1);}}function U(b,c){if(b){var d;for(d=b.length-1;-1<d&&(!b[d]||!c(b[d],d,b));d-=1);}}function s(b,c){return ga.call(b,c)}function j(b,c){return s(b,c)&&b[c]}function B(b,c){for(var d in b)if(s(b,d)&&c(b[d],d))break}function V(b,c,d,g){c&&B(c,function(c,h){if(d||!s(b,h))g&&"object"===typeof c&&c&&!H(c)&&!G(c)&&!(c instanceof
-RegExp)?(b[h]||(b[h]={}),V(b[h],c,d,g)):b[h]=c});return b}function t(b,c){return function(){return c.apply(b,arguments)}}function da(b){throw b;}function ea(b){if(!b)return b;var c=ca;v(b.split("."),function(b){c=c[b]});return c}function C(b,c,d,g){c=Error(c+"\nhttp://requirejs.org/docs/errors.html#"+b);c.requireType=b;c.requireModules=g;d&&(c.originalError=d);return c}function ha(b){function c(a,e,b){var f,n,c,d,g,h,i,I=e&&e.split("/");n=I;var m=l.map,k=m&&m["*"];if(a&&"."===a.charAt(0))if(e){n=
-I.slice(0,I.length-1);a=a.split("/");e=a.length-1;l.nodeIdCompat&&R.test(a[e])&&(a[e]=a[e].replace(R,""));n=a=n.concat(a);d=n.length;for(e=0;e<d;e++)if(c=n[e],"."===c)n.splice(e,1),e-=1;else if(".."===c)if(1===e&&(".."===n[2]||".."===n[0]))break;else 0<e&&(n.splice(e-1,2),e-=2);a=a.join("/")}else 0===a.indexOf("./")&&(a=a.substring(2));if(b&&m&&(I||k)){n=a.split("/");e=n.length;a:for(;0<e;e-=1){d=n.slice(0,e).join("/");if(I)for(c=I.length;0<c;c-=1)if(b=j(m,I.slice(0,c).join("/")))if(b=j(b,d)){f=b;
-g=e;break a}!h&&(k&&j(k,d))&&(h=j(k,d),i=e)}!f&&h&&(f=h,g=i);f&&(n.splice(0,g,f),a=n.join("/"))}return(f=j(l.pkgs,a))?f:a}function d(a){z&&v(document.getElementsByTagName("script"),function(e){if(e.getAttribute("data-requiremodule")===a&&e.getAttribute("data-requirecontext")===i.contextName)return e.parentNode.removeChild(e),!0})}function g(a){var e=j(l.paths,a);if(e&&H(e)&&1<e.length)return e.shift(),i.require.undef(a),i.require([a]),!0}function u(a){var e,b=a?a.indexOf("!"):-1;-1<b&&(e=a.substring(0,
-b),a=a.substring(b+1,a.length));return[e,a]}function m(a,e,b,f){var n,d,g=null,h=e?e.name:null,l=a,m=!0,k="";a||(m=!1,a="_@r"+(M+=1));a=u(a);g=a[0];a=a[1];g&&(g=c(g,h,f),d=j(p,g));a&&(g?k=d&&d.normalize?d.normalize(a,function(a){return c(a,h,f)}):c(a,h,f):(k=c(a,h,f),a=u(k),g=a[0],k=a[1],b=!0,n=i.nameToUrl(k)));b=g&&!d&&!b?"_unnormalized"+(Q+=1):"";return{prefix:g,name:k,parentMap:e,unnormalized:!!b,url:n,originalName:l,isDefine:m,id:(g?g+"!"+k:k)+b}}function q(a){var e=a.id,b=j(k,e);b||(b=k[e]=new i.Module(a));
-return b}function r(a,e,b){var f=a.id,n=j(k,f);if(s(p,f)&&(!n||n.defineEmitComplete))"defined"===e&&b(p[f]);else if(n=q(a),n.error&&"error"===e)b(n.error);else n.on(e,b)}function w(a,e){var b=a.requireModules,f=!1;if(e)e(a);else if(v(b,function(e){if(e=j(k,e))e.error=a,e.events.error&&(f=!0,e.emit("error",a))}),!f)h.onError(a)}function x(){S.length&&(ia.apply(A,[A.length,0].concat(S)),S=[])}function y(a){delete k[a];delete W[a]}function F(a,e,b){var f=a.map.id;a.error?a.emit("error",a.error):(e[f]=
-!0,v(a.depMaps,function(f,c){var d=f.id,g=j(k,d);g&&(!a.depMatched[c]&&!b[d])&&(j(e,d)?(a.defineDep(c,p[d]),a.check()):F(g,e,b))}),b[f]=!0)}function D(){var a,e,b=(a=1E3*l.waitSeconds)&&i.startTime+a<(new Date).getTime(),f=[],c=[],h=!1,k=!0;if(!X){X=!0;B(W,function(a){var i=a.map,m=i.id;if(a.enabled&&(i.isDefine||c.push(a),!a.error))if(!a.inited&&b)g(m)?h=e=!0:(f.push(m),d(m));else if(!a.inited&&(a.fetched&&i.isDefine)&&(h=!0,!i.prefix))return k=!1});if(b&&f.length)return a=C("timeout","Load timeout for modules: "+
-f,null,f),a.contextName=i.contextName,w(a);k&&v(c,function(a){F(a,{},{})});if((!b||e)&&h)if((z||fa)&&!Y)Y=setTimeout(function(){Y=0;D()},50);X=!1}}function E(a){s(p,a[0])||q(m(a[0],null,!0)).init(a[1],a[2])}function K(a){var a=a.currentTarget||a.srcElement,e=i.onScriptLoad;a.detachEvent&&!Z?a.detachEvent("onreadystatechange",e):a.removeEventListener("load",e,!1);e=i.onScriptError;(!a.detachEvent||Z)&&a.removeEventListener("error",e,!1);return{node:a,id:a&&a.getAttribute("data-requiremodule")}}function L(){var a;
-for(x();A.length;){a=A.shift();if(null===a[0])return w(C("mismatch","Mismatched anonymous define() module: "+a[a.length-1]));E(a)}}var X,$,i,N,Y,l={waitSeconds:7,baseUrl:"./",paths:{},bundles:{},pkgs:{},shim:{},config:{}},k={},W={},aa={},A=[],p={},T={},ba={},M=1,Q=1;N={require:function(a){return a.require?a.require:a.require=i.makeRequire(a.map)},exports:function(a){a.usingExports=!0;if(a.map.isDefine)return a.exports?p[a.map.id]=a.exports:a.exports=p[a.map.id]={}},module:function(a){return a.module?
-a.module:a.module={id:a.map.id,uri:a.map.url,config:function(){return j(l.config,a.map.id)||{}},exports:a.exports||(a.exports={})}}};$=function(a){this.events=j(aa,a.id)||{};this.map=a;this.shim=j(l.shim,a.id);this.depExports=[];this.depMaps=[];this.depMatched=[];this.pluginMaps={};this.depCount=0};$.prototype={init:function(a,e,b,f){f=f||{};if(!this.inited){this.factory=e;if(b)this.on("error",b);else this.events.error&&(b=t(this,function(a){this.emit("error",a)}));this.depMaps=a&&a.slice(0);this.errback=
-b;this.inited=!0;this.ignore=f.ignore;f.enabled||this.enabled?this.enable():this.check()}},defineDep:function(a,e){this.depMatched[a]||(this.depMatched[a]=!0,this.depCount-=1,this.depExports[a]=e)},fetch:function(){if(!this.fetched){this.fetched=!0;i.startTime=(new Date).getTime();var a=this.map;if(this.shim)i.makeRequire(this.map,{enableBuildCallback:!0})(this.shim.deps||[],t(this,function(){return a.prefix?this.callPlugin():this.load()}));else return a.prefix?this.callPlugin():this.load()}},load:function(){var a=
-this.map.url;T[a]||(T[a]=!0,i.load(this.map.id,a))},check:function(){if(this.enabled&&!this.enabling){var a,e,b=this.map.id;e=this.depExports;var f=this.exports,c=this.factory;if(this.inited)if(this.error)this.emit("error",this.error);else{if(!this.defining){this.defining=!0;if(1>this.depCount&&!this.defined){if(G(c)){if(this.events.error&&this.map.isDefine||h.onError!==da)try{f=i.execCb(b,c,e,f)}catch(d){a=d}else f=i.execCb(b,c,e,f);this.map.isDefine&&void 0===f&&((e=this.module)?f=e.exports:this.usingExports&&
-(f=this.exports));if(a)return a.requireMap=this.map,a.requireModules=this.map.isDefine?[this.map.id]:null,a.requireType=this.map.isDefine?"define":"require",w(this.error=a)}else f=c;this.exports=f;if(this.map.isDefine&&!this.ignore&&(p[b]=f,h.onResourceLoad))h.onResourceLoad(i,this.map,this.depMaps);y(b);this.defined=!0}this.defining=!1;this.defined&&!this.defineEmitted&&(this.defineEmitted=!0,this.emit("defined",this.exports),this.defineEmitComplete=!0)}}else this.fetch()}},callPlugin:function(){var a=
-this.map,b=a.id,d=m(a.prefix);this.depMaps.push(d);r(d,"defined",t(this,function(f){var d,g;g=j(ba,this.map.id);var J=this.map.name,u=this.map.parentMap?this.map.parentMap.name:null,p=i.makeRequire(a.parentMap,{enableBuildCallback:!0});if(this.map.unnormalized){if(f.normalize&&(J=f.normalize(J,function(a){return c(a,u,!0)})||""),f=m(a.prefix+"!"+J,this.map.parentMap),r(f,"defined",t(this,function(a){this.init([],function(){return a},null,{enabled:!0,ignore:!0})})),g=j(k,f.id)){this.depMaps.push(f);
-if(this.events.error)g.on("error",t(this,function(a){this.emit("error",a)}));g.enable()}}else g?(this.map.url=i.nameToUrl(g),this.load()):(d=t(this,function(a){this.init([],function(){return a},null,{enabled:!0})}),d.error=t(this,function(a){this.inited=!0;this.error=a;a.requireModules=[b];B(k,function(a){0===a.map.id.indexOf(b+"_unnormalized")&&y(a.map.id)});w(a)}),d.fromText=t(this,function(f,c){var g=a.name,J=m(g),k=O;c&&(f=c);k&&(O=!1);q(J);s(l.config,b)&&(l.config[g]=l.config[b]);try{h.exec(f)}catch(j){return w(C("fromtexteval",
-"fromText eval for "+b+" failed: "+j,j,[b]))}k&&(O=!0);this.depMaps.push(J);i.completeLoad(g);p([g],d)}),f.load(a.name,p,d,l))}));i.enable(d,this);this.pluginMaps[d.id]=d},enable:function(){W[this.map.id]=this;this.enabling=this.enabled=!0;v(this.depMaps,t(this,function(a,b){var c,f;if("string"===typeof a){a=m(a,this.map.isDefine?this.map:this.map.parentMap,!1,!this.skipMap);this.depMaps[b]=a;if(c=j(N,a.id)){this.depExports[b]=c(this);return}this.depCount+=1;r(a,"defined",t(this,function(a){this.defineDep(b,
-a);this.check()}));this.errback&&r(a,"error",t(this,this.errback))}c=a.id;f=k[c];!s(N,c)&&(f&&!f.enabled)&&i.enable(a,this)}));B(this.pluginMaps,t(this,function(a){var b=j(k,a.id);b&&!b.enabled&&i.enable(a,this)}));this.enabling=!1;this.check()},on:function(a,b){var c=this.events[a];c||(c=this.events[a]=[]);c.push(b)},emit:function(a,b){v(this.events[a],function(a){a(b)});"error"===a&&delete this.events[a]}};i={config:l,contextName:b,registry:k,defined:p,urlFetched:T,defQueue:A,Module:$,makeModuleMap:m,
-nextTick:h.nextTick,onError:w,configure:function(a){a.baseUrl&&"/"!==a.baseUrl.charAt(a.baseUrl.length-1)&&(a.baseUrl+="/");var b=l.shim,c={paths:!0,bundles:!0,config:!0,map:!0};B(a,function(a,b){c[b]?(l[b]||(l[b]={}),V(l[b],a,!0,!0)):l[b]=a});a.bundles&&B(a.bundles,function(a,b){v(a,function(a){a!==b&&(ba[a]=b)})});a.shim&&(B(a.shim,function(a,c){H(a)&&(a={deps:a});if((a.exports||a.init)&&!a.exportsFn)a.exportsFn=i.makeShimExports(a);b[c]=a}),l.shim=b);a.packages&&v(a.packages,function(a){var b,
-a="string"===typeof a?{name:a}:a;b=a.name;a.location&&(l.paths[b]=a.location);l.pkgs[b]=a.name+"/"+(a.main||"main").replace(ja,"").replace(R,"")});B(k,function(a,b){!a.inited&&!a.map.unnormalized&&(a.map=m(b))});if(a.deps||a.callback)i.require(a.deps||[],a.callback)},makeShimExports:function(a){return function(){var b;a.init&&(b=a.init.apply(ca,arguments));return b||a.exports&&ea(a.exports)}},makeRequire:function(a,e){function g(f,c,d){var j,l;e.enableBuildCallback&&(c&&G(c))&&(c.__requireJsBuild=
-!0);if("string"===typeof f){if(G(c))return w(C("requireargs","Invalid require call"),d);if(a&&s(N,f))return N[f](k[a.id]);if(h.get)return h.get(i,f,a,g);j=m(f,a,!1,!0);j=j.id;return!s(p,j)?w(C("notloaded",'Module name "'+j+'" has not been loaded yet for context: '+b+(a?"":". Use require([])"))):p[j]}L();i.nextTick(function(){L();l=q(m(null,a));l.skipMap=e.skipMap;l.init(f,c,d,{enabled:!0});D()});return g}e=e||{};V(g,{isBrowser:z,toUrl:function(b){var e,d=b.lastIndexOf("."),g=b.split("/")[0];if(-1!==
-d&&(!("."===g||".."===g)||1<d))e=b.substring(d,b.length),b=b.substring(0,d);return i.nameToUrl(c(b,a&&a.id,!0),e,!0)},defined:function(b){return s(p,m(b,a,!1,!0).id)},specified:function(b){b=m(b,a,!1,!0).id;return s(p,b)||s(k,b)}});a||(g.undef=function(b){x();var c=m(b,a,!0),e=j(k,b);d(b);delete p[b];delete T[c.url];delete aa[b];U(A,function(a,c){a[0]===b&&A.splice(c,1)});e&&(e.events.defined&&(aa[b]=e.events),y(b))});return g},enable:function(a){j(k,a.id)&&q(a).enable()},completeLoad:function(a){var b,
-c,f=j(l.shim,a)||{},d=f.exports;for(x();A.length;){c=A.shift();if(null===c[0]){c[0]=a;if(b)break;b=!0}else c[0]===a&&(b=!0);E(c)}c=j(k,a);if(!b&&!s(p,a)&&c&&!c.inited){if(l.enforceDefine&&(!d||!ea(d)))return g(a)?void 0:w(C("nodefine","No define call for "+a,null,[a]));E([a,f.deps||[],f.exportsFn])}D()},nameToUrl:function(a,b,c){var f,d,g;(f=j(l.pkgs,a))&&(a=f);if(f=j(ba,a))return i.nameToUrl(f,b,c);if(h.jsExtRegExp.test(a))f=a+(b||"");else{f=l.paths;a=a.split("/");for(d=a.length;0<d;d-=1)if(g=a.slice(0,
-d).join("/"),g=j(f,g)){H(g)&&(g=g[0]);a.splice(0,d,g);break}f=a.join("/");f+=b||(/^data\:|\?/.test(f)||c?"":".js");f=("/"===f.charAt(0)||f.match(/^[\w\+\.\-]+:/)?"":l.baseUrl)+f}return l.urlArgs?f+((-1===f.indexOf("?")?"?":"&")+l.urlArgs):f},load:function(a,b){h.load(i,a,b)},execCb:function(a,b,c,d){return b.apply(d,c)},onScriptLoad:function(a){if("load"===a.type||ka.test((a.currentTarget||a.srcElement).readyState))P=null,a=K(a),i.completeLoad(a.id)},onScriptError:function(a){var b=K(a);if(!g(b.id))return w(C("scripterror",
-"Script error for: "+b.id,a,[b.id]))}};i.require=i.makeRequire();return i}var h,x,y,D,K,E,P,L,q,Q,la=/(\/\*([\s\S]*?)\*\/|([^:]|^)\/\/(.*)$)/mg,ma=/[^.]\s*require\s*\(\s*["']([^'"\s]+)["']\s*\)/g,R=/\.js$/,ja=/^\.\//;x=Object.prototype;var M=x.toString,ga=x.hasOwnProperty,ia=Array.prototype.splice,z=!!("undefined"!==typeof window&&"undefined"!==typeof navigator&&window.document),fa=!z&&"undefined"!==typeof importScripts,ka=z&&"PLAYSTATION 3"===navigator.platform?/^complete$/:/^(complete|loaded)$/,
-Z="undefined"!==typeof opera&&"[object Opera]"===opera.toString(),F={},r={},S=[],O=!1;if("undefined"===typeof define){if("undefined"!==typeof requirejs){if(G(requirejs))return;r=requirejs;requirejs=void 0}"undefined"!==typeof require&&!G(require)&&(r=require,require=void 0);h=requirejs=function(b,c,d,g){var u,m="_";!H(b)&&"string"!==typeof b&&(u=b,H(c)?(b=c,c=d,d=g):b=[]);u&&u.context&&(m=u.context);(g=j(F,m))||(g=F[m]=h.s.newContext(m));u&&g.configure(u);return g.require(b,c,d)};h.config=function(b){return h(b)};
-h.nextTick="undefined"!==typeof setTimeout?function(b){setTimeout(b,4)}:function(b){b()};require||(require=h);h.version="2.1.11";h.jsExtRegExp=/^\/|:|\?|\.js$/;h.isBrowser=z;x=h.s={contexts:F,newContext:ha};h({});v(["toUrl","undef","defined","specified"],function(b){h[b]=function(){var c=F._;return c.require[b].apply(c,arguments)}});if(z&&(y=x.head=document.getElementsByTagName("head")[0],D=document.getElementsByTagName("base")[0]))y=x.head=D.parentNode;h.onError=da;h.createNode=function(b){var c=
-b.xhtml?document.createElementNS("http://www.w3.org/1999/xhtml","html:script"):document.createElement("script");c.type=b.scriptType||"text/javascript";c.charset="utf-8";c.async=!0;return c};h.load=function(b,c,d){var g=b&&b.config||{};if(z)return g=h.createNode(g,c,d),g.setAttribute("data-requirecontext",b.contextName),g.setAttribute("data-requiremodule",c),g.attachEvent&&!(g.attachEvent.toString&&0>g.attachEvent.toString().indexOf("[native code"))&&!Z?(O=!0,g.attachEvent("onreadystatechange",b.onScriptLoad)):
-(g.addEventListener("load",b.onScriptLoad,!1),g.addEventListener("error",b.onScriptError,!1)),g.src=d,L=g,D?y.insertBefore(g,D):y.appendChild(g),L=null,g;if(fa)try{importScripts(d),b.completeLoad(c)}catch(j){b.onError(C("importscripts","importScripts failed for "+c+" at "+d,j,[c]))}};z&&!r.skipDataMain&&U(document.getElementsByTagName("script"),function(b){y||(y=b.parentNode);if(K=b.getAttribute("data-main"))return q=K,r.baseUrl||(E=q.split("/"),q=E.pop(),Q=E.length?E.join("/")+"/":"./",r.baseUrl=
-Q),q=q.replace(R,""),h.jsExtRegExp.test(q)&&(q=K),r.deps=r.deps?r.deps.concat(q):[q],!0});define=function(b,c,d){var g,h;"string"!==typeof b&&(d=c,c=b,b=null);H(c)||(d=c,c=null);!c&&G(d)&&(c=[],d.length&&(d.toString().replace(la,"").replace(ma,function(b,d){c.push(d)}),c=(1===d.length?["require"]:["require","exports","module"]).concat(c)));if(O){if(!(g=L))P&&"interactive"===P.readyState||U(document.getElementsByTagName("script"),function(b){if("interactive"===b.readyState)return P=b}),g=P;g&&(b||
-(b=g.getAttribute("data-requiremodule")),h=F[g.getAttribute("data-requirecontext")])}(h?h.defQueue:S).push([b,c,d])};define.amd={jQuery:!0};h.exec=function(b){return eval(b)};h(r)}})(this);
--- a/server/python/django/renkanmanager/static/renkanmanager/lib/underscore-min.js Fri Apr 24 13:05:09 2015 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,6 +0,0 @@
-// Underscore.js 1.6.0
-// http://underscorejs.org
-// (c) 2009-2014 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
-// Underscore may be freely distributed under the MIT license.
-(function(){var n=this,t=n._,r={},e=Array.prototype,u=Object.prototype,i=Function.prototype,a=e.push,o=e.slice,c=e.concat,l=u.toString,f=u.hasOwnProperty,s=e.forEach,p=e.map,h=e.reduce,v=e.reduceRight,g=e.filter,d=e.every,m=e.some,y=e.indexOf,b=e.lastIndexOf,x=Array.isArray,w=Object.keys,_=i.bind,j=function(n){return n instanceof j?n:this instanceof j?void(this._wrapped=n):new j(n)};"undefined"!=typeof exports?("undefined"!=typeof module&&module.exports&&(exports=module.exports=j),exports._=j):n._=j,j.VERSION="1.6.0";var A=j.each=j.forEach=function(n,t,e){if(null==n)return n;if(s&&n.forEach===s)n.forEach(t,e);else if(n.length===+n.length){for(var u=0,i=n.length;i>u;u++)if(t.call(e,n[u],u,n)===r)return}else for(var a=j.keys(n),u=0,i=a.length;i>u;u++)if(t.call(e,n[a[u]],a[u],n)===r)return;return n};j.map=j.collect=function(n,t,r){var e=[];return null==n?e:p&&n.map===p?n.map(t,r):(A(n,function(n,u,i){e.push(t.call(r,n,u,i))}),e)};var O="Reduce of empty array with no initial value";j.reduce=j.foldl=j.inject=function(n,t,r,e){var u=arguments.length>2;if(null==n&&(n=[]),h&&n.reduce===h)return e&&(t=j.bind(t,e)),u?n.reduce(t,r):n.reduce(t);if(A(n,function(n,i,a){u?r=t.call(e,r,n,i,a):(r=n,u=!0)}),!u)throw new TypeError(O);return r},j.reduceRight=j.foldr=function(n,t,r,e){var u=arguments.length>2;if(null==n&&(n=[]),v&&n.reduceRight===v)return e&&(t=j.bind(t,e)),u?n.reduceRight(t,r):n.reduceRight(t);var i=n.length;if(i!==+i){var a=j.keys(n);i=a.length}if(A(n,function(o,c,l){c=a?a[--i]:--i,u?r=t.call(e,r,n[c],c,l):(r=n[c],u=!0)}),!u)throw new TypeError(O);return r},j.find=j.detect=function(n,t,r){var e;return k(n,function(n,u,i){return t.call(r,n,u,i)?(e=n,!0):void 0}),e},j.filter=j.select=function(n,t,r){var e=[];return null==n?e:g&&n.filter===g?n.filter(t,r):(A(n,function(n,u,i){t.call(r,n,u,i)&&e.push(n)}),e)},j.reject=function(n,t,r){return j.filter(n,function(n,e,u){return!t.call(r,n,e,u)},r)},j.every=j.all=function(n,t,e){t||(t=j.identity);var u=!0;return null==n?u:d&&n.every===d?n.every(t,e):(A(n,function(n,i,a){return(u=u&&t.call(e,n,i,a))?void 0:r}),!!u)};var k=j.some=j.any=function(n,t,e){t||(t=j.identity);var u=!1;return null==n?u:m&&n.some===m?n.some(t,e):(A(n,function(n,i,a){return u||(u=t.call(e,n,i,a))?r:void 0}),!!u)};j.contains=j.include=function(n,t){return null==n?!1:y&&n.indexOf===y?n.indexOf(t)!=-1:k(n,function(n){return n===t})},j.invoke=function(n,t){var r=o.call(arguments,2),e=j.isFunction(t);return j.map(n,function(n){return(e?t:n[t]).apply(n,r)})},j.pluck=function(n,t){return j.map(n,j.property(t))},j.where=function(n,t){return j.filter(n,j.matches(t))},j.findWhere=function(n,t){return j.find(n,j.matches(t))},j.max=function(n,t,r){if(!t&&j.isArray(n)&&n[0]===+n[0]&&n.length<65535)return Math.max.apply(Math,n);var e=-1/0,u=-1/0;return A(n,function(n,i,a){var o=t?t.call(r,n,i,a):n;o>u&&(e=n,u=o)}),e},j.min=function(n,t,r){if(!t&&j.isArray(n)&&n[0]===+n[0]&&n.length<65535)return Math.min.apply(Math,n);var e=1/0,u=1/0;return A(n,function(n,i,a){var o=t?t.call(r,n,i,a):n;u>o&&(e=n,u=o)}),e},j.shuffle=function(n){var t,r=0,e=[];return A(n,function(n){t=j.random(r++),e[r-1]=e[t],e[t]=n}),e},j.sample=function(n,t,r){return null==t||r?(n.length!==+n.length&&(n=j.values(n)),n[j.random(n.length-1)]):j.shuffle(n).slice(0,Math.max(0,t))};var E=function(n){return null==n?j.identity:j.isFunction(n)?n:j.property(n)};j.sortBy=function(n,t,r){return t=E(t),j.pluck(j.map(n,function(n,e,u){return{value:n,index:e,criteria:t.call(r,n,e,u)}}).sort(function(n,t){var r=n.criteria,e=t.criteria;if(r!==e){if(r>e||r===void 0)return 1;if(e>r||e===void 0)return-1}return n.index-t.index}),"value")};var F=function(n){return function(t,r,e){var u={};return r=E(r),A(t,function(i,a){var o=r.call(e,i,a,t);n(u,o,i)}),u}};j.groupBy=F(function(n,t,r){j.has(n,t)?n[t].push(r):n[t]=[r]}),j.indexBy=F(function(n,t,r){n[t]=r}),j.countBy=F(function(n,t){j.has(n,t)?n[t]++:n[t]=1}),j.sortedIndex=function(n,t,r,e){r=E(r);for(var u=r.call(e,t),i=0,a=n.length;a>i;){var o=i+a>>>1;r.call(e,n[o])<u?i=o+1:a=o}return i},j.toArray=function(n){return n?j.isArray(n)?o.call(n):n.length===+n.length?j.map(n,j.identity):j.values(n):[]},j.size=function(n){return null==n?0:n.length===+n.length?n.length:j.keys(n).length},j.first=j.head=j.take=function(n,t,r){return null==n?void 0:null==t||r?n[0]:0>t?[]:o.call(n,0,t)},j.initial=function(n,t,r){return o.call(n,0,n.length-(null==t||r?1:t))},j.last=function(n,t,r){return null==n?void 0:null==t||r?n[n.length-1]:o.call(n,Math.max(n.length-t,0))},j.rest=j.tail=j.drop=function(n,t,r){return o.call(n,null==t||r?1:t)},j.compact=function(n){return j.filter(n,j.identity)};var M=function(n,t,r){return t&&j.every(n,j.isArray)?c.apply(r,n):(A(n,function(n){j.isArray(n)||j.isArguments(n)?t?a.apply(r,n):M(n,t,r):r.push(n)}),r)};j.flatten=function(n,t){return M(n,t,[])},j.without=function(n){return j.difference(n,o.call(arguments,1))},j.partition=function(n,t){var r=[],e=[];return A(n,function(n){(t(n)?r:e).push(n)}),[r,e]},j.uniq=j.unique=function(n,t,r,e){j.isFunction(t)&&(e=r,r=t,t=!1);var u=r?j.map(n,r,e):n,i=[],a=[];return A(u,function(r,e){(t?e&&a[a.length-1]===r:j.contains(a,r))||(a.push(r),i.push(n[e]))}),i},j.union=function(){return j.uniq(j.flatten(arguments,!0))},j.intersection=function(n){var t=o.call(arguments,1);return j.filter(j.uniq(n),function(n){return j.every(t,function(t){return j.contains(t,n)})})},j.difference=function(n){var t=c.apply(e,o.call(arguments,1));return j.filter(n,function(n){return!j.contains(t,n)})},j.zip=function(){for(var n=j.max(j.pluck(arguments,"length").concat(0)),t=new Array(n),r=0;n>r;r++)t[r]=j.pluck(arguments,""+r);return t},j.object=function(n,t){if(null==n)return{};for(var r={},e=0,u=n.length;u>e;e++)t?r[n[e]]=t[e]:r[n[e][0]]=n[e][1];return r},j.indexOf=function(n,t,r){if(null==n)return-1;var e=0,u=n.length;if(r){if("number"!=typeof r)return e=j.sortedIndex(n,t),n[e]===t?e:-1;e=0>r?Math.max(0,u+r):r}if(y&&n.indexOf===y)return n.indexOf(t,r);for(;u>e;e++)if(n[e]===t)return e;return-1},j.lastIndexOf=function(n,t,r){if(null==n)return-1;var e=null!=r;if(b&&n.lastIndexOf===b)return e?n.lastIndexOf(t,r):n.lastIndexOf(t);for(var u=e?r:n.length;u--;)if(n[u]===t)return u;return-1},j.range=function(n,t,r){arguments.length<=1&&(t=n||0,n=0),r=arguments[2]||1;for(var e=Math.max(Math.ceil((t-n)/r),0),u=0,i=new Array(e);e>u;)i[u++]=n,n+=r;return i};var R=function(){};j.bind=function(n,t){var r,e;if(_&&n.bind===_)return _.apply(n,o.call(arguments,1));if(!j.isFunction(n))throw new TypeError;return r=o.call(arguments,2),e=function(){if(!(this instanceof e))return n.apply(t,r.concat(o.call(arguments)));R.prototype=n.prototype;var u=new R;R.prototype=null;var i=n.apply(u,r.concat(o.call(arguments)));return Object(i)===i?i:u}},j.partial=function(n){var t=o.call(arguments,1);return function(){for(var r=0,e=t.slice(),u=0,i=e.length;i>u;u++)e[u]===j&&(e[u]=arguments[r++]);for(;r<arguments.length;)e.push(arguments[r++]);return n.apply(this,e)}},j.bindAll=function(n){var t=o.call(arguments,1);if(0===t.length)throw new Error("bindAll must be passed function names");return A(t,function(t){n[t]=j.bind(n[t],n)}),n},j.memoize=function(n,t){var r={};return t||(t=j.identity),function(){var e=t.apply(this,arguments);return j.has(r,e)?r[e]:r[e]=n.apply(this,arguments)}},j.delay=function(n,t){var r=o.call(arguments,2);return setTimeout(function(){return n.apply(null,r)},t)},j.defer=function(n){return j.delay.apply(j,[n,1].concat(o.call(arguments,1)))},j.throttle=function(n,t,r){var e,u,i,a=null,o=0;r||(r={});var c=function(){o=r.leading===!1?0:j.now(),a=null,i=n.apply(e,u),e=u=null};return function(){var l=j.now();o||r.leading!==!1||(o=l);var f=t-(l-o);return e=this,u=arguments,0>=f?(clearTimeout(a),a=null,o=l,i=n.apply(e,u),e=u=null):a||r.trailing===!1||(a=setTimeout(c,f)),i}},j.debounce=function(n,t,r){var e,u,i,a,o,c=function(){var l=j.now()-a;t>l?e=setTimeout(c,t-l):(e=null,r||(o=n.apply(i,u),i=u=null))};return function(){i=this,u=arguments,a=j.now();var l=r&&!e;return e||(e=setTimeout(c,t)),l&&(o=n.apply(i,u),i=u=null),o}},j.once=function(n){var t,r=!1;return function(){return r?t:(r=!0,t=n.apply(this,arguments),n=null,t)}},j.wrap=function(n,t){return j.partial(t,n)},j.compose=function(){var n=arguments;return function(){for(var t=arguments,r=n.length-1;r>=0;r--)t=[n[r].apply(this,t)];return t[0]}},j.after=function(n,t){return function(){return--n<1?t.apply(this,arguments):void 0}},j.keys=function(n){if(!j.isObject(n))return[];if(w)return w(n);var t=[];for(var r in n)j.has(n,r)&&t.push(r);return t},j.values=function(n){for(var t=j.keys(n),r=t.length,e=new Array(r),u=0;r>u;u++)e[u]=n[t[u]];return e},j.pairs=function(n){for(var t=j.keys(n),r=t.length,e=new Array(r),u=0;r>u;u++)e[u]=[t[u],n[t[u]]];return e},j.invert=function(n){for(var t={},r=j.keys(n),e=0,u=r.length;u>e;e++)t[n[r[e]]]=r[e];return t},j.functions=j.methods=function(n){var t=[];for(var r in n)j.isFunction(n[r])&&t.push(r);return t.sort()},j.extend=function(n){return A(o.call(arguments,1),function(t){if(t)for(var r in t)n[r]=t[r]}),n},j.pick=function(n){var t={},r=c.apply(e,o.call(arguments,1));return A(r,function(r){r in n&&(t[r]=n[r])}),t},j.omit=function(n){var t={},r=c.apply(e,o.call(arguments,1));for(var u in n)j.contains(r,u)||(t[u]=n[u]);return t},j.defaults=function(n){return A(o.call(arguments,1),function(t){if(t)for(var r in t)n[r]===void 0&&(n[r]=t[r])}),n},j.clone=function(n){return j.isObject(n)?j.isArray(n)?n.slice():j.extend({},n):n},j.tap=function(n,t){return t(n),n};var S=function(n,t,r,e){if(n===t)return 0!==n||1/n==1/t;if(null==n||null==t)return n===t;n instanceof j&&(n=n._wrapped),t instanceof j&&(t=t._wrapped);var u=l.call(n);if(u!=l.call(t))return!1;switch(u){case"[object String]":return n==String(t);case"[object Number]":return n!=+n?t!=+t:0==n?1/n==1/t:n==+t;case"[object Date]":case"[object Boolean]":return+n==+t;case"[object RegExp]":return n.source==t.source&&n.global==t.global&&n.multiline==t.multiline&&n.ignoreCase==t.ignoreCase}if("object"!=typeof n||"object"!=typeof t)return!1;for(var i=r.length;i--;)if(r[i]==n)return e[i]==t;var a=n.constructor,o=t.constructor;if(a!==o&&!(j.isFunction(a)&&a instanceof a&&j.isFunction(o)&&o instanceof o)&&"constructor"in n&&"constructor"in t)return!1;r.push(n),e.push(t);var c=0,f=!0;if("[object Array]"==u){if(c=n.length,f=c==t.length)for(;c--&&(f=S(n[c],t[c],r,e)););}else{for(var s in n)if(j.has(n,s)&&(c++,!(f=j.has(t,s)&&S(n[s],t[s],r,e))))break;if(f){for(s in t)if(j.has(t,s)&&!c--)break;f=!c}}return r.pop(),e.pop(),f};j.isEqual=function(n,t){return S(n,t,[],[])},j.isEmpty=function(n){if(null==n)return!0;if(j.isArray(n)||j.isString(n))return 0===n.length;for(var t in n)if(j.has(n,t))return!1;return!0},j.isElement=function(n){return!(!n||1!==n.nodeType)},j.isArray=x||function(n){return"[object Array]"==l.call(n)},j.isObject=function(n){return n===Object(n)},A(["Arguments","Function","String","Number","Date","RegExp"],function(n){j["is"+n]=function(t){return l.call(t)=="[object "+n+"]"}}),j.isArguments(arguments)||(j.isArguments=function(n){return!(!n||!j.has(n,"callee"))}),"function"!=typeof/./&&(j.isFunction=function(n){return"function"==typeof n}),j.isFinite=function(n){return isFinite(n)&&!isNaN(parseFloat(n))},j.isNaN=function(n){return j.isNumber(n)&&n!=+n},j.isBoolean=function(n){return n===!0||n===!1||"[object Boolean]"==l.call(n)},j.isNull=function(n){return null===n},j.isUndefined=function(n){return n===void 0},j.has=function(n,t){return f.call(n,t)},j.noConflict=function(){return n._=t,this},j.identity=function(n){return n},j.constant=function(n){return function(){return n}},j.property=function(n){return function(t){return t[n]}},j.matches=function(n){return function(t){if(t===n)return!0;for(var r in n)if(n[r]!==t[r])return!1;return!0}},j.times=function(n,t,r){for(var e=Array(Math.max(0,n)),u=0;n>u;u++)e[u]=t.call(r,u);return e},j.random=function(n,t){return null==t&&(t=n,n=0),n+Math.floor(Math.random()*(t-n+1))},j.now=Date.now||function(){return(new Date).getTime()};var T={escape:{"&":"&","<":"<",">":">",'"':""","'":"'"}};T.unescape=j.invert(T.escape);var I={escape:new RegExp("["+j.keys(T.escape).join("")+"]","g"),unescape:new RegExp("("+j.keys(T.unescape).join("|")+")","g")};j.each(["escape","unescape"],function(n){j[n]=function(t){return null==t?"":(""+t).replace(I[n],function(t){return T[n][t]})}}),j.result=function(n,t){if(null==n)return void 0;var r=n[t];return j.isFunction(r)?r.call(n):r},j.mixin=function(n){A(j.functions(n),function(t){var r=j[t]=n[t];j.prototype[t]=function(){var n=[this._wrapped];return a.apply(n,arguments),z.call(this,r.apply(j,n))}})};var N=0;j.uniqueId=function(n){var t=++N+"";return n?n+t:t},j.templateSettings={evaluate:/<%([\s\S]+?)%>/g,interpolate:/<%=([\s\S]+?)%>/g,escape:/<%-([\s\S]+?)%>/g};var q=/(.)^/,B={"'":"'","\\":"\\","\r":"r","\n":"n"," ":"t","\u2028":"u2028","\u2029":"u2029"},D=/\\|'|\r|\n|\t|\u2028|\u2029/g;j.template=function(n,t,r){var e;r=j.defaults({},r,j.templateSettings);var u=new RegExp([(r.escape||q).source,(r.interpolate||q).source,(r.evaluate||q).source].join("|")+"|$","g"),i=0,a="__p+='";n.replace(u,function(t,r,e,u,o){return a+=n.slice(i,o).replace(D,function(n){return"\\"+B[n]}),r&&(a+="'+\n((__t=("+r+"))==null?'':_.escape(__t))+\n'"),e&&(a+="'+\n((__t=("+e+"))==null?'':__t)+\n'"),u&&(a+="';\n"+u+"\n__p+='"),i=o+t.length,t}),a+="';\n",r.variable||(a="with(obj||{}){\n"+a+"}\n"),a="var __t,__p='',__j=Array.prototype.join,"+"print=function(){__p+=__j.call(arguments,'');};\n"+a+"return __p;\n";try{e=new Function(r.variable||"obj","_",a)}catch(o){throw o.source=a,o}if(t)return e(t,j);var c=function(n){return e.call(this,n,j)};return c.source="function("+(r.variable||"obj")+"){\n"+a+"}",c},j.chain=function(n){return j(n).chain()};var z=function(n){return this._chain?j(n).chain():n};j.mixin(j),A(["pop","push","reverse","shift","sort","splice","unshift"],function(n){var t=e[n];j.prototype[n]=function(){var r=this._wrapped;return t.apply(r,arguments),"shift"!=n&&"splice"!=n||0!==r.length||delete r[0],z.call(this,r)}}),A(["concat","join","slice"],function(n){var t=e[n];j.prototype[n]=function(){return z.call(this,t.apply(this._wrapped,arguments))}}),j.extend(j.prototype,{chain:function(){return this._chain=!0,this},value:function(){return this._wrapped}}),"function"==typeof define&&define.amd&&define("underscore",[],function(){return j})}).call(this);
-//# sourceMappingURL=underscore-min.map
\ No newline at end of file
--- a/server/python/django/renkanmanager/static/renkanmanager/lib/underscore.js Fri Apr 24 13:05:09 2015 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,1344 +0,0 @@
-// Underscore.js 1.6.0
-// http://underscorejs.org
-// (c) 2009-2014 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
-// Underscore may be freely distributed under the MIT license.
-
-(function() {
-
- // Baseline setup
- // --------------
-
- // Establish the root object, `window` in the browser, or `exports` on the server.
- var root = this;
-
- // Save the previous value of the `_` variable.
- var previousUnderscore = root._;
-
- // Establish the object that gets returned to break out of a loop iteration.
- var breaker = {};
-
- // Save bytes in the minified (but not gzipped) version:
- var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype;
-
- // Create quick reference variables for speed access to core prototypes.
- var
- push = ArrayProto.push,
- slice = ArrayProto.slice,
- concat = ArrayProto.concat,
- toString = ObjProto.toString,
- hasOwnProperty = ObjProto.hasOwnProperty;
-
- // All **ECMAScript 5** native function implementations that we hope to use
- // are declared here.
- var
- nativeForEach = ArrayProto.forEach,
- nativeMap = ArrayProto.map,
- nativeReduce = ArrayProto.reduce,
- nativeReduceRight = ArrayProto.reduceRight,
- nativeFilter = ArrayProto.filter,
- nativeEvery = ArrayProto.every,
- nativeSome = ArrayProto.some,
- nativeIndexOf = ArrayProto.indexOf,
- nativeLastIndexOf = ArrayProto.lastIndexOf,
- nativeIsArray = Array.isArray,
- nativeKeys = Object.keys,
- nativeBind = FuncProto.bind;
-
- // Create a safe reference to the Underscore object for use below.
- var _ = function(obj) {
- if (obj instanceof _) return obj;
- if (!(this instanceof _)) return new _(obj);
- this._wrapped = obj;
- };
-
- // Export the Underscore object for **Node.js**, with
- // backwards-compatibility for the old `require()` API. If we're in
- // the browser, add `_` as a global object via a string identifier,
- // for Closure Compiler "advanced" mode.
- if (typeof exports !== 'undefined') {
- if (typeof module !== 'undefined' && module.exports) {
- exports = module.exports = _;
- }
- exports._ = _;
- } else {
- root._ = _;
- }
-
- // Current version.
- _.VERSION = '1.6.0';
-
- // Collection Functions
- // --------------------
-
- // The cornerstone, an `each` implementation, aka `forEach`.
- // Handles objects with the built-in `forEach`, arrays, and raw objects.
- // Delegates to **ECMAScript 5**'s native `forEach` if available.
- var each = _.each = _.forEach = function(obj, iterator, context) {
- if (obj == null) return obj;
- if (nativeForEach && obj.forEach === nativeForEach) {
- obj.forEach(iterator, context);
- } else if (obj.length === +obj.length) {
- for (var i = 0, length = obj.length; i < length; i++) {
- if (iterator.call(context, obj[i], i, obj) === breaker) return;
- }
- } else {
- var keys = _.keys(obj);
- for (var i = 0, length = keys.length; i < length; i++) {
- if (iterator.call(context, obj[keys[i]], keys[i], obj) === breaker) return;
- }
- }
- return obj;
- };
-
- // Return the results of applying the iterator to each element.
- // Delegates to **ECMAScript 5**'s native `map` if available.
- _.map = _.collect = function(obj, iterator, context) {
- var results = [];
- if (obj == null) return results;
- if (nativeMap && obj.map === nativeMap) return obj.map(iterator, context);
- each(obj, function(value, index, list) {
- results.push(iterator.call(context, value, index, list));
- });
- return results;
- };
-
- var reduceError = 'Reduce of empty array with no initial value';
-
- // **Reduce** builds up a single result from a list of values, aka `inject`,
- // or `foldl`. Delegates to **ECMAScript 5**'s native `reduce` if available.
- _.reduce = _.foldl = _.inject = function(obj, iterator, memo, context) {
- var initial = arguments.length > 2;
- if (obj == null) obj = [];
- if (nativeReduce && obj.reduce === nativeReduce) {
- if (context) iterator = _.bind(iterator, context);
- return initial ? obj.reduce(iterator, memo) : obj.reduce(iterator);
- }
- each(obj, function(value, index, list) {
- if (!initial) {
- memo = value;
- initial = true;
- } else {
- memo = iterator.call(context, memo, value, index, list);
- }
- });
- if (!initial) throw new TypeError(reduceError);
- return memo;
- };
-
- // The right-associative version of reduce, also known as `foldr`.
- // Delegates to **ECMAScript 5**'s native `reduceRight` if available.
- _.reduceRight = _.foldr = function(obj, iterator, memo, context) {
- var initial = arguments.length > 2;
- if (obj == null) obj = [];
- if (nativeReduceRight && obj.reduceRight === nativeReduceRight) {
- if (context) iterator = _.bind(iterator, context);
- return initial ? obj.reduceRight(iterator, memo) : obj.reduceRight(iterator);
- }
- var length = obj.length;
- if (length !== +length) {
- var keys = _.keys(obj);
- length = keys.length;
- }
- each(obj, function(value, index, list) {
- index = keys ? keys[--length] : --length;
- if (!initial) {
- memo = obj[index];
- initial = true;
- } else {
- memo = iterator.call(context, memo, obj[index], index, list);
- }
- });
- if (!initial) throw new TypeError(reduceError);
- return memo;
- };
-
- // Return the first value which passes a truth test. Aliased as `detect`.
- _.find = _.detect = function(obj, predicate, context) {
- var result;
- any(obj, function(value, index, list) {
- if (predicate.call(context, value, index, list)) {
- result = value;
- return true;
- }
- });
- return result;
- };
-
- // Return all the elements that pass a truth test.
- // Delegates to **ECMAScript 5**'s native `filter` if available.
- // Aliased as `select`.
- _.filter = _.select = function(obj, predicate, context) {
- var results = [];
- if (obj == null) return results;
- if (nativeFilter && obj.filter === nativeFilter) return obj.filter(predicate, context);
- each(obj, function(value, index, list) {
- if (predicate.call(context, value, index, list)) results.push(value);
- });
- return results;
- };
-
- // Return all the elements for which a truth test fails.
- _.reject = function(obj, predicate, context) {
- return _.filter(obj, function(value, index, list) {
- return !predicate.call(context, value, index, list);
- }, context);
- };
-
- // Determine whether all of the elements match a truth test.
- // Delegates to **ECMAScript 5**'s native `every` if available.
- // Aliased as `all`.
- _.every = _.all = function(obj, predicate, context) {
- predicate || (predicate = _.identity);
- var result = true;
- if (obj == null) return result;
- if (nativeEvery && obj.every === nativeEvery) return obj.every(predicate, context);
- each(obj, function(value, index, list) {
- if (!(result = result && predicate.call(context, value, index, list))) return breaker;
- });
- return !!result;
- };
-
- // Determine if at least one element in the object matches a truth test.
- // Delegates to **ECMAScript 5**'s native `some` if available.
- // Aliased as `any`.
- var any = _.some = _.any = function(obj, predicate, context) {
- predicate || (predicate = _.identity);
- var result = false;
- if (obj == null) return result;
- if (nativeSome && obj.some === nativeSome) return obj.some(predicate, context);
- each(obj, function(value, index, list) {
- if (result || (result = predicate.call(context, value, index, list))) return breaker;
- });
- return !!result;
- };
-
- // Determine if the array or object contains a given value (using `===`).
- // Aliased as `include`.
- _.contains = _.include = function(obj, target) {
- if (obj == null) return false;
- if (nativeIndexOf && obj.indexOf === nativeIndexOf) return obj.indexOf(target) != -1;
- return any(obj, function(value) {
- return value === target;
- });
- };
-
- // Invoke a method (with arguments) on every item in a collection.
- _.invoke = function(obj, method) {
- var args = slice.call(arguments, 2);
- var isFunc = _.isFunction(method);
- return _.map(obj, function(value) {
- return (isFunc ? method : value[method]).apply(value, args);
- });
- };
-
- // Convenience version of a common use case of `map`: fetching a property.
- _.pluck = function(obj, key) {
- return _.map(obj, _.property(key));
- };
-
- // Convenience version of a common use case of `filter`: selecting only objects
- // containing specific `key:value` pairs.
- _.where = function(obj, attrs) {
- return _.filter(obj, _.matches(attrs));
- };
-
- // Convenience version of a common use case of `find`: getting the first object
- // containing specific `key:value` pairs.
- _.findWhere = function(obj, attrs) {
- return _.find(obj, _.matches(attrs));
- };
-
- // Return the maximum element or (element-based computation).
- // Can't optimize arrays of integers longer than 65,535 elements.
- // See [WebKit Bug 80797](https://bugs.webkit.org/show_bug.cgi?id=80797)
- _.max = function(obj, iterator, context) {
- if (!iterator && _.isArray(obj) && obj[0] === +obj[0] && obj.length < 65535) {
- return Math.max.apply(Math, obj);
- }
- var result = -Infinity, lastComputed = -Infinity;
- each(obj, function(value, index, list) {
- var computed = iterator ? iterator.call(context, value, index, list) : value;
- if (computed > lastComputed) {
- result = value;
- lastComputed = computed;
- }
- });
- return result;
- };
-
- // Return the minimum element (or element-based computation).
- _.min = function(obj, iterator, context) {
- if (!iterator && _.isArray(obj) && obj[0] === +obj[0] && obj.length < 65535) {
- return Math.min.apply(Math, obj);
- }
- var result = Infinity, lastComputed = Infinity;
- each(obj, function(value, index, list) {
- var computed = iterator ? iterator.call(context, value, index, list) : value;
- if (computed < lastComputed) {
- result = value;
- lastComputed = computed;
- }
- });
- return result;
- };
-
- // Shuffle an array, using the modern version of the
- // [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Fisher–Yates_shuffle).
- _.shuffle = function(obj) {
- var rand;
- var index = 0;
- var shuffled = [];
- each(obj, function(value) {
- rand = _.random(index++);
- shuffled[index - 1] = shuffled[rand];
- shuffled[rand] = value;
- });
- return shuffled;
- };
-
- // Sample **n** random values from a collection.
- // If **n** is not specified, returns a single random element.
- // The internal `guard` argument allows it to work with `map`.
- _.sample = function(obj, n, guard) {
- if (n == null || guard) {
- if (obj.length !== +obj.length) obj = _.values(obj);
- return obj[_.random(obj.length - 1)];
- }
- return _.shuffle(obj).slice(0, Math.max(0, n));
- };
-
- // An internal function to generate lookup iterators.
- var lookupIterator = function(value) {
- if (value == null) return _.identity;
- if (_.isFunction(value)) return value;
- return _.property(value);
- };
-
- // Sort the object's values by a criterion produced by an iterator.
- _.sortBy = function(obj, iterator, context) {
- iterator = lookupIterator(iterator);
- return _.pluck(_.map(obj, function(value, index, list) {
- return {
- value: value,
- index: index,
- criteria: iterator.call(context, value, index, list)
- };
- }).sort(function(left, right) {
- var a = left.criteria;
- var b = right.criteria;
- if (a !== b) {
- if (a > b || a === void 0) return 1;
- if (a < b || b === void 0) return -1;
- }
- return left.index - right.index;
- }), 'value');
- };
-
- // An internal function used for aggregate "group by" operations.
- var group = function(behavior) {
- return function(obj, iterator, context) {
- var result = {};
- iterator = lookupIterator(iterator);
- each(obj, function(value, index) {
- var key = iterator.call(context, value, index, obj);
- behavior(result, key, value);
- });
- return result;
- };
- };
-
- // Groups the object's values by a criterion. Pass either a string attribute
- // to group by, or a function that returns the criterion.
- _.groupBy = group(function(result, key, value) {
- _.has(result, key) ? result[key].push(value) : result[key] = [value];
- });
-
- // Indexes the object's values by a criterion, similar to `groupBy`, but for
- // when you know that your index values will be unique.
- _.indexBy = group(function(result, key, value) {
- result[key] = value;
- });
-
- // Counts instances of an object that group by a certain criterion. Pass
- // either a string attribute to count by, or a function that returns the
- // criterion.
- _.countBy = group(function(result, key) {
- _.has(result, key) ? result[key]++ : result[key] = 1;
- });
-
- // Use a comparator function to figure out the smallest index at which
- // an object should be inserted so as to maintain order. Uses binary search.
- _.sortedIndex = function(array, obj, iterator, context) {
- iterator = lookupIterator(iterator);
- var value = iterator.call(context, obj);
- var low = 0, high = array.length;
- while (low < high) {
- var mid = (low + high) >>> 1;
- iterator.call(context, array[mid]) < value ? low = mid + 1 : high = mid;
- }
- return low;
- };
-
- // Safely create a real, live array from anything iterable.
- _.toArray = function(obj) {
- if (!obj) return [];
- if (_.isArray(obj)) return slice.call(obj);
- if (obj.length === +obj.length) return _.map(obj, _.identity);
- return _.values(obj);
- };
-
- // Return the number of elements in an object.
- _.size = function(obj) {
- if (obj == null) return 0;
- return (obj.length === +obj.length) ? obj.length : _.keys(obj).length;
- };
-
- // Array Functions
- // ---------------
-
- // Get the first element of an array. Passing **n** will return the first N
- // values in the array. Aliased as `head` and `take`. The **guard** check
- // allows it to work with `_.map`.
- _.first = _.head = _.take = function(array, n, guard) {
- if (array == null) return void 0;
- if ((n == null) || guard) return array[0];
- if (n < 0) return [];
- return slice.call(array, 0, n);
- };
-
- // Returns everything but the last entry of the array. Especially useful on
- // the arguments object. Passing **n** will return all the values in
- // the array, excluding the last N. The **guard** check allows it to work with
- // `_.map`.
- _.initial = function(array, n, guard) {
- return slice.call(array, 0, array.length - ((n == null) || guard ? 1 : n));
- };
-
- // Get the last element of an array. Passing **n** will return the last N
- // values in the array. The **guard** check allows it to work with `_.map`.
- _.last = function(array, n, guard) {
- if (array == null) return void 0;
- if ((n == null) || guard) return array[array.length - 1];
- return slice.call(array, Math.max(array.length - n, 0));
- };
-
- // Returns everything but the first entry of the array. Aliased as `tail` and `drop`.
- // Especially useful on the arguments object. Passing an **n** will return
- // the rest N values in the array. The **guard**
- // check allows it to work with `_.map`.
- _.rest = _.tail = _.drop = function(array, n, guard) {
- return slice.call(array, (n == null) || guard ? 1 : n);
- };
-
- // Trim out all falsy values from an array.
- _.compact = function(array) {
- return _.filter(array, _.identity);
- };
-
- // Internal implementation of a recursive `flatten` function.
- var flatten = function(input, shallow, output) {
- if (shallow && _.every(input, _.isArray)) {
- return concat.apply(output, input);
- }
- each(input, function(value) {
- if (_.isArray(value) || _.isArguments(value)) {
- shallow ? push.apply(output, value) : flatten(value, shallow, output);
- } else {
- output.push(value);
- }
- });
- return output;
- };
-
- // Flatten out an array, either recursively (by default), or just one level.
- _.flatten = function(array, shallow) {
- return flatten(array, shallow, []);
- };
-
- // Return a version of the array that does not contain the specified value(s).
- _.without = function(array) {
- return _.difference(array, slice.call(arguments, 1));
- };
-
- // Split an array into two arrays: one whose elements all satisfy the given
- // predicate, and one whose elements all do not satisfy the predicate.
- _.partition = function(array, predicate, context) {
- predicate = lookupIterator(predicate);
- var pass = [], fail = [];
- each(array, function(elem) {
- (predicate.call(context, elem) ? pass : fail).push(elem);
- });
- return [pass, fail];
- };
-
- // Produce a duplicate-free version of the array. If the array has already
- // been sorted, you have the option of using a faster algorithm.
- // Aliased as `unique`.
- _.uniq = _.unique = function(array, isSorted, iterator, context) {
- if (_.isFunction(isSorted)) {
- context = iterator;
- iterator = isSorted;
- isSorted = false;
- }
- var initial = iterator ? _.map(array, iterator, context) : array;
- var results = [];
- var seen = [];
- each(initial, function(value, index) {
- if (isSorted ? (!index || seen[seen.length - 1] !== value) : !_.contains(seen, value)) {
- seen.push(value);
- results.push(array[index]);
- }
- });
- return results;
- };
-
- // Produce an array that contains the union: each distinct element from all of
- // the passed-in arrays.
- _.union = function() {
- return _.uniq(_.flatten(arguments, true));
- };
-
- // Produce an array that contains every item shared between all the
- // passed-in arrays.
- _.intersection = function(array) {
- var rest = slice.call(arguments, 1);
- return _.filter(_.uniq(array), function(item) {
- return _.every(rest, function(other) {
- return _.contains(other, item);
- });
- });
- };
-
- // Take the difference between one array and a number of other arrays.
- // Only the elements present in just the first array will remain.
- _.difference = function(array) {
- var rest = concat.apply(ArrayProto, slice.call(arguments, 1));
- return _.filter(array, function(value){ return !_.contains(rest, value); });
- };
-
- // Zip together multiple lists into a single array -- elements that share
- // an index go together.
- _.zip = function() {
- var length = _.max(_.pluck(arguments, 'length').concat(0));
- var results = new Array(length);
- for (var i = 0; i < length; i++) {
- results[i] = _.pluck(arguments, '' + i);
- }
- return results;
- };
-
- // Converts lists into objects. Pass either a single array of `[key, value]`
- // pairs, or two parallel arrays of the same length -- one of keys, and one of
- // the corresponding values.
- _.object = function(list, values) {
- if (list == null) return {};
- var result = {};
- for (var i = 0, length = list.length; i < length; i++) {
- if (values) {
- result[list[i]] = values[i];
- } else {
- result[list[i][0]] = list[i][1];
- }
- }
- return result;
- };
-
- // If the browser doesn't supply us with indexOf (I'm looking at you, **MSIE**),
- // we need this function. Return the position of the first occurrence of an
- // item in an array, or -1 if the item is not included in the array.
- // Delegates to **ECMAScript 5**'s native `indexOf` if available.
- // If the array is large and already in sort order, pass `true`
- // for **isSorted** to use binary search.
- _.indexOf = function(array, item, isSorted) {
- if (array == null) return -1;
- var i = 0, length = array.length;
- if (isSorted) {
- if (typeof isSorted == 'number') {
- i = (isSorted < 0 ? Math.max(0, length + isSorted) : isSorted);
- } else {
- i = _.sortedIndex(array, item);
- return array[i] === item ? i : -1;
- }
- }
- if (nativeIndexOf && array.indexOf === nativeIndexOf) return array.indexOf(item, isSorted);
- for (; i < length; i++) if (array[i] === item) return i;
- return -1;
- };
-
- // Delegates to **ECMAScript 5**'s native `lastIndexOf` if available.
- _.lastIndexOf = function(array, item, from) {
- if (array == null) return -1;
- var hasIndex = from != null;
- if (nativeLastIndexOf && array.lastIndexOf === nativeLastIndexOf) {
- return hasIndex ? array.lastIndexOf(item, from) : array.lastIndexOf(item);
- }
- var i = (hasIndex ? from : array.length);
- while (i--) if (array[i] === item) return i;
- return -1;
- };
-
- // Generate an integer Array containing an arithmetic progression. A port of
- // the native Python `range()` function. See
- // [the Python documentation](http://docs.python.org/library/functions.html#range).
- _.range = function(start, stop, step) {
- if (arguments.length <= 1) {
- stop = start || 0;
- start = 0;
- }
- step = arguments[2] || 1;
-
- var length = Math.max(Math.ceil((stop - start) / step), 0);
- var idx = 0;
- var range = new Array(length);
-
- while(idx < length) {
- range[idx++] = start;
- start += step;
- }
-
- return range;
- };
-
- // Function (ahem) Functions
- // ------------------
-
- // Reusable constructor function for prototype setting.
- var ctor = function(){};
-
- // Create a function bound to a given object (assigning `this`, and arguments,
- // optionally). Delegates to **ECMAScript 5**'s native `Function.bind` if
- // available.
- _.bind = function(func, context) {
- var args, bound;
- if (nativeBind && func.bind === nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));
- if (!_.isFunction(func)) throw new TypeError;
- args = slice.call(arguments, 2);
- return bound = function() {
- if (!(this instanceof bound)) return func.apply(context, args.concat(slice.call(arguments)));
- ctor.prototype = func.prototype;
- var self = new ctor;
- ctor.prototype = null;
- var result = func.apply(self, args.concat(slice.call(arguments)));
- if (Object(result) === result) return result;
- return self;
- };
- };
-
- // Partially apply a function by creating a version that has had some of its
- // arguments pre-filled, without changing its dynamic `this` context. _ acts
- // as a placeholder, allowing any combination of arguments to be pre-filled.
- _.partial = function(func) {
- var boundArgs = slice.call(arguments, 1);
- return function() {
- var position = 0;
- var args = boundArgs.slice();
- for (var i = 0, length = args.length; i < length; i++) {
- if (args[i] === _) args[i] = arguments[position++];
- }
- while (position < arguments.length) args.push(arguments[position++]);
- return func.apply(this, args);
- };
- };
-
- // Bind a number of an object's methods to that object. Remaining arguments
- // are the method names to be bound. Useful for ensuring that all callbacks
- // defined on an object belong to it.
- _.bindAll = function(obj) {
- var funcs = slice.call(arguments, 1);
- if (funcs.length === 0) throw new Error('bindAll must be passed function names');
- each(funcs, function(f) { obj[f] = _.bind(obj[f], obj); });
- return obj;
- };
-
- // Memoize an expensive function by storing its results.
- _.memoize = function(func, hasher) {
- var memo = {};
- hasher || (hasher = _.identity);
- return function() {
- var key = hasher.apply(this, arguments);
- return _.has(memo, key) ? memo[key] : (memo[key] = func.apply(this, arguments));
- };
- };
-
- // Delays a function for the given number of milliseconds, and then calls
- // it with the arguments supplied.
- _.delay = function(func, wait) {
- var args = slice.call(arguments, 2);
- return setTimeout(function(){ return func.apply(null, args); }, wait);
- };
-
- // Defers a function, scheduling it to run after the current call stack has
- // cleared.
- _.defer = function(func) {
- return _.delay.apply(_, [func, 1].concat(slice.call(arguments, 1)));
- };
-
- // Returns a function, that, when invoked, will only be triggered at most once
- // during a given window of time. Normally, the throttled function will run
- // as much as it can, without ever going more than once per `wait` duration;
- // but if you'd like to disable the execution on the leading edge, pass
- // `{leading: false}`. To disable execution on the trailing edge, ditto.
- _.throttle = function(func, wait, options) {
- var context, args, result;
- var timeout = null;
- var previous = 0;
- options || (options = {});
- var later = function() {
- previous = options.leading === false ? 0 : _.now();
- timeout = null;
- result = func.apply(context, args);
- context = args = null;
- };
- return function() {
- var now = _.now();
- if (!previous && options.leading === false) previous = now;
- var remaining = wait - (now - previous);
- context = this;
- args = arguments;
- if (remaining <= 0) {
- clearTimeout(timeout);
- timeout = null;
- previous = now;
- result = func.apply(context, args);
- context = args = null;
- } else if (!timeout && options.trailing !== false) {
- timeout = setTimeout(later, remaining);
- }
- return result;
- };
- };
-
- // Returns a function, that, as long as it continues to be invoked, will not
- // be triggered. The function will be called after it stops being called for
- // N milliseconds. If `immediate` is passed, trigger the function on the
- // leading edge, instead of the trailing.
- _.debounce = function(func, wait, immediate) {
- var timeout, args, context, timestamp, result;
-
- var later = function() {
- var last = _.now() - timestamp;
- if (last < wait) {
- timeout = setTimeout(later, wait - last);
- } else {
- timeout = null;
- if (!immediate) {
- result = func.apply(context, args);
- context = args = null;
- }
- }
- };
-
- return function() {
- context = this;
- args = arguments;
- timestamp = _.now();
- var callNow = immediate && !timeout;
- if (!timeout) {
- timeout = setTimeout(later, wait);
- }
- if (callNow) {
- result = func.apply(context, args);
- context = args = null;
- }
-
- return result;
- };
- };
-
- // Returns a function that will be executed at most one time, no matter how
- // often you call it. Useful for lazy initialization.
- _.once = function(func) {
- var ran = false, memo;
- return function() {
- if (ran) return memo;
- ran = true;
- memo = func.apply(this, arguments);
- func = null;
- return memo;
- };
- };
-
- // Returns the first function passed as an argument to the second,
- // allowing you to adjust arguments, run code before and after, and
- // conditionally execute the original function.
- _.wrap = function(func, wrapper) {
- return _.partial(wrapper, func);
- };
-
- // Returns a function that is the composition of a list of functions, each
- // consuming the return value of the function that follows.
- _.compose = function() {
- var funcs = arguments;
- return function() {
- var args = arguments;
- for (var i = funcs.length - 1; i >= 0; i--) {
- args = [funcs[i].apply(this, args)];
- }
- return args[0];
- };
- };
-
- // Returns a function that will only be executed after being called N times.
- _.after = function(times, func) {
- return function() {
- if (--times < 1) {
- return func.apply(this, arguments);
- }
- };
- };
-
- // Object Functions
- // ----------------
-
- // Retrieve the names of an object's properties.
- // Delegates to **ECMAScript 5**'s native `Object.keys`
- _.keys = function(obj) {
- if (!_.isObject(obj)) return [];
- if (nativeKeys) return nativeKeys(obj);
- var keys = [];
- for (var key in obj) if (_.has(obj, key)) keys.push(key);
- return keys;
- };
-
- // Retrieve the values of an object's properties.
- _.values = function(obj) {
- var keys = _.keys(obj);
- var length = keys.length;
- var values = new Array(length);
- for (var i = 0; i < length; i++) {
- values[i] = obj[keys[i]];
- }
- return values;
- };
-
- // Convert an object into a list of `[key, value]` pairs.
- _.pairs = function(obj) {
- var keys = _.keys(obj);
- var length = keys.length;
- var pairs = new Array(length);
- for (var i = 0; i < length; i++) {
- pairs[i] = [keys[i], obj[keys[i]]];
- }
- return pairs;
- };
-
- // Invert the keys and values of an object. The values must be serializable.
- _.invert = function(obj) {
- var result = {};
- var keys = _.keys(obj);
- for (var i = 0, length = keys.length; i < length; i++) {
- result[obj[keys[i]]] = keys[i];
- }
- return result;
- };
-
- // Return a sorted list of the function names available on the object.
- // Aliased as `methods`
- _.functions = _.methods = function(obj) {
- var names = [];
- for (var key in obj) {
- if (_.isFunction(obj[key])) names.push(key);
- }
- return names.sort();
- };
-
- // Extend a given object with all the properties in passed-in object(s).
- _.extend = function(obj) {
- each(slice.call(arguments, 1), function(source) {
- if (source) {
- for (var prop in source) {
- obj[prop] = source[prop];
- }
- }
- });
- return obj;
- };
-
- // Return a copy of the object only containing the whitelisted properties.
- _.pick = function(obj) {
- var copy = {};
- var keys = concat.apply(ArrayProto, slice.call(arguments, 1));
- each(keys, function(key) {
- if (key in obj) copy[key] = obj[key];
- });
- return copy;
- };
-
- // Return a copy of the object without the blacklisted properties.
- _.omit = function(obj) {
- var copy = {};
- var keys = concat.apply(ArrayProto, slice.call(arguments, 1));
- for (var key in obj) {
- if (!_.contains(keys, key)) copy[key] = obj[key];
- }
- return copy;
- };
-
- // Fill in a given object with default properties.
- _.defaults = function(obj) {
- each(slice.call(arguments, 1), function(source) {
- if (source) {
- for (var prop in source) {
- if (obj[prop] === void 0) obj[prop] = source[prop];
- }
- }
- });
- return obj;
- };
-
- // Create a (shallow-cloned) duplicate of an object.
- _.clone = function(obj) {
- if (!_.isObject(obj)) return obj;
- return _.isArray(obj) ? obj.slice() : _.extend({}, obj);
- };
-
- // Invokes interceptor with the obj, and then returns obj.
- // The primary purpose of this method is to "tap into" a method chain, in
- // order to perform operations on intermediate results within the chain.
- _.tap = function(obj, interceptor) {
- interceptor(obj);
- return obj;
- };
-
- // Internal recursive comparison function for `isEqual`.
- var eq = function(a, b, aStack, bStack) {
- // Identical objects are equal. `0 === -0`, but they aren't identical.
- // See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal).
- if (a === b) return a !== 0 || 1 / a == 1 / b;
- // A strict comparison is necessary because `null == undefined`.
- if (a == null || b == null) return a === b;
- // Unwrap any wrapped objects.
- if (a instanceof _) a = a._wrapped;
- if (b instanceof _) b = b._wrapped;
- // Compare `[[Class]]` names.
- var className = toString.call(a);
- if (className != toString.call(b)) return false;
- switch (className) {
- // Strings, numbers, dates, and booleans are compared by value.
- case '[object String]':
- // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
- // equivalent to `new String("5")`.
- return a == String(b);
- case '[object Number]':
- // `NaN`s are equivalent, but non-reflexive. An `egal` comparison is performed for
- // other numeric values.
- return a != +a ? b != +b : (a == 0 ? 1 / a == 1 / b : a == +b);
- case '[object Date]':
- case '[object Boolean]':
- // Coerce dates and booleans to numeric primitive values. Dates are compared by their
- // millisecond representations. Note that invalid dates with millisecond representations
- // of `NaN` are not equivalent.
- return +a == +b;
- // RegExps are compared by their source patterns and flags.
- case '[object RegExp]':
- return a.source == b.source &&
- a.global == b.global &&
- a.multiline == b.multiline &&
- a.ignoreCase == b.ignoreCase;
- }
- if (typeof a != 'object' || typeof b != 'object') return false;
- // Assume equality for cyclic structures. The algorithm for detecting cyclic
- // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.
- var length = aStack.length;
- while (length--) {
- // Linear search. Performance is inversely proportional to the number of
- // unique nested structures.
- if (aStack[length] == a) return bStack[length] == b;
- }
- // Objects with different constructors are not equivalent, but `Object`s
- // from different frames are.
- var aCtor = a.constructor, bCtor = b.constructor;
- if (aCtor !== bCtor && !(_.isFunction(aCtor) && (aCtor instanceof aCtor) &&
- _.isFunction(bCtor) && (bCtor instanceof bCtor))
- && ('constructor' in a && 'constructor' in b)) {
- return false;
- }
- // Add the first object to the stack of traversed objects.
- aStack.push(a);
- bStack.push(b);
- var size = 0, result = true;
- // Recursively compare objects and arrays.
- if (className == '[object Array]') {
- // Compare array lengths to determine if a deep comparison is necessary.
- size = a.length;
- result = size == b.length;
- if (result) {
- // Deep compare the contents, ignoring non-numeric properties.
- while (size--) {
- if (!(result = eq(a[size], b[size], aStack, bStack))) break;
- }
- }
- } else {
- // Deep compare objects.
- for (var key in a) {
- if (_.has(a, key)) {
- // Count the expected number of properties.
- size++;
- // Deep compare each member.
- if (!(result = _.has(b, key) && eq(a[key], b[key], aStack, bStack))) break;
- }
- }
- // Ensure that both objects contain the same number of properties.
- if (result) {
- for (key in b) {
- if (_.has(b, key) && !(size--)) break;
- }
- result = !size;
- }
- }
- // Remove the first object from the stack of traversed objects.
- aStack.pop();
- bStack.pop();
- return result;
- };
-
- // Perform a deep comparison to check if two objects are equal.
- _.isEqual = function(a, b) {
- return eq(a, b, [], []);
- };
-
- // Is a given array, string, or object empty?
- // An "empty" object has no enumerable own-properties.
- _.isEmpty = function(obj) {
- if (obj == null) return true;
- if (_.isArray(obj) || _.isString(obj)) return obj.length === 0;
- for (var key in obj) if (_.has(obj, key)) return false;
- return true;
- };
-
- // Is a given value a DOM element?
- _.isElement = function(obj) {
- return !!(obj && obj.nodeType === 1);
- };
-
- // Is a given value an array?
- // Delegates to ECMA5's native Array.isArray
- _.isArray = nativeIsArray || function(obj) {
- return toString.call(obj) == '[object Array]';
- };
-
- // Is a given variable an object?
- _.isObject = function(obj) {
- return obj === Object(obj);
- };
-
- // Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp.
- each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp'], function(name) {
- _['is' + name] = function(obj) {
- return toString.call(obj) == '[object ' + name + ']';
- };
- });
-
- // Define a fallback version of the method in browsers (ahem, IE), where
- // there isn't any inspectable "Arguments" type.
- if (!_.isArguments(arguments)) {
- _.isArguments = function(obj) {
- return !!(obj && _.has(obj, 'callee'));
- };
- }
-
- // Optimize `isFunction` if appropriate.
- if (typeof (/./) !== 'function') {
- _.isFunction = function(obj) {
- return typeof obj === 'function';
- };
- }
-
- // Is a given object a finite number?
- _.isFinite = function(obj) {
- return isFinite(obj) && !isNaN(parseFloat(obj));
- };
-
- // Is the given value `NaN`? (NaN is the only number which does not equal itself).
- _.isNaN = function(obj) {
- return _.isNumber(obj) && obj != +obj;
- };
-
- // Is a given value a boolean?
- _.isBoolean = function(obj) {
- return obj === true || obj === false || toString.call(obj) == '[object Boolean]';
- };
-
- // Is a given value equal to null?
- _.isNull = function(obj) {
- return obj === null;
- };
-
- // Is a given variable undefined?
- _.isUndefined = function(obj) {
- return obj === void 0;
- };
-
- // Shortcut function for checking if an object has a given property directly
- // on itself (in other words, not on a prototype).
- _.has = function(obj, key) {
- return hasOwnProperty.call(obj, key);
- };
-
- // Utility Functions
- // -----------------
-
- // Run Underscore.js in *noConflict* mode, returning the `_` variable to its
- // previous owner. Returns a reference to the Underscore object.
- _.noConflict = function() {
- root._ = previousUnderscore;
- return this;
- };
-
- // Keep the identity function around for default iterators.
- _.identity = function(value) {
- return value;
- };
-
- _.constant = function(value) {
- return function () {
- return value;
- };
- };
-
- _.property = function(key) {
- return function(obj) {
- return obj[key];
- };
- };
-
- // Returns a predicate for checking whether an object has a given set of `key:value` pairs.
- _.matches = function(attrs) {
- return function(obj) {
- if (obj === attrs) return true; //avoid comparing an object to itself.
- for (var key in attrs) {
- if (attrs[key] !== obj[key])
- return false;
- }
- return true;
- }
- };
-
- // Run a function **n** times.
- _.times = function(n, iterator, context) {
- var accum = Array(Math.max(0, n));
- for (var i = 0; i < n; i++) accum[i] = iterator.call(context, i);
- return accum;
- };
-
- // Return a random integer between min and max (inclusive).
- _.random = function(min, max) {
- if (max == null) {
- max = min;
- min = 0;
- }
- return min + Math.floor(Math.random() * (max - min + 1));
- };
-
- // A (possibly faster) way to get the current timestamp as an integer.
- _.now = Date.now || function() { return new Date().getTime(); };
-
- // List of HTML entities for escaping.
- var entityMap = {
- escape: {
- '&': '&',
- '<': '<',
- '>': '>',
- '"': '"',
- "'": '''
- }
- };
- entityMap.unescape = _.invert(entityMap.escape);
-
- // Regexes containing the keys and values listed immediately above.
- var entityRegexes = {
- escape: new RegExp('[' + _.keys(entityMap.escape).join('') + ']', 'g'),
- unescape: new RegExp('(' + _.keys(entityMap.unescape).join('|') + ')', 'g')
- };
-
- // Functions for escaping and unescaping strings to/from HTML interpolation.
- _.each(['escape', 'unescape'], function(method) {
- _[method] = function(string) {
- if (string == null) return '';
- return ('' + string).replace(entityRegexes[method], function(match) {
- return entityMap[method][match];
- });
- };
- });
-
- // If the value of the named `property` is a function then invoke it with the
- // `object` as context; otherwise, return it.
- _.result = function(object, property) {
- if (object == null) return void 0;
- var value = object[property];
- return _.isFunction(value) ? value.call(object) : value;
- };
-
- // Add your own custom functions to the Underscore object.
- _.mixin = function(obj) {
- each(_.functions(obj), function(name) {
- var func = _[name] = obj[name];
- _.prototype[name] = function() {
- var args = [this._wrapped];
- push.apply(args, arguments);
- return result.call(this, func.apply(_, args));
- };
- });
- };
-
- // Generate a unique integer id (unique within the entire client session).
- // Useful for temporary DOM ids.
- var idCounter = 0;
- _.uniqueId = function(prefix) {
- var id = ++idCounter + '';
- return prefix ? prefix + id : id;
- };
-
- // By default, Underscore uses ERB-style template delimiters, change the
- // following template settings to use alternative delimiters.
- _.templateSettings = {
- evaluate : /<%([\s\S]+?)%>/g,
- interpolate : /<%=([\s\S]+?)%>/g,
- escape : /<%-([\s\S]+?)%>/g
- };
-
- // When customizing `templateSettings`, if you don't want to define an
- // interpolation, evaluation or escaping regex, we need one that is
- // guaranteed not to match.
- var noMatch = /(.)^/;
-
- // Certain characters need to be escaped so that they can be put into a
- // string literal.
- var escapes = {
- "'": "'",
- '\\': '\\',
- '\r': 'r',
- '\n': 'n',
- '\t': 't',
- '\u2028': 'u2028',
- '\u2029': 'u2029'
- };
-
- var escaper = /\\|'|\r|\n|\t|\u2028|\u2029/g;
-
- // JavaScript micro-templating, similar to John Resig's implementation.
- // Underscore templating handles arbitrary delimiters, preserves whitespace,
- // and correctly escapes quotes within interpolated code.
- _.template = function(text, data, settings) {
- var render;
- settings = _.defaults({}, settings, _.templateSettings);
-
- // Combine delimiters into one regular expression via alternation.
- var matcher = new RegExp([
- (settings.escape || noMatch).source,
- (settings.interpolate || noMatch).source,
- (settings.evaluate || noMatch).source
- ].join('|') + '|$', 'g');
-
- // Compile the template source, escaping string literals appropriately.
- var index = 0;
- var source = "__p+='";
- text.replace(matcher, function(match, escape, interpolate, evaluate, offset) {
- source += text.slice(index, offset)
- .replace(escaper, function(match) { return '\\' + escapes[match]; });
-
- if (escape) {
- source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'";
- }
- if (interpolate) {
- source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'";
- }
- if (evaluate) {
- source += "';\n" + evaluate + "\n__p+='";
- }
- index = offset + match.length;
- return match;
- });
- source += "';\n";
-
- // If a variable is not specified, place data values in local scope.
- if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n';
-
- source = "var __t,__p='',__j=Array.prototype.join," +
- "print=function(){__p+=__j.call(arguments,'');};\n" +
- source + "return __p;\n";
-
- try {
- render = new Function(settings.variable || 'obj', '_', source);
- } catch (e) {
- e.source = source;
- throw e;
- }
-
- if (data) return render(data, _);
- var template = function(data) {
- return render.call(this, data, _);
- };
-
- // Provide the compiled function source as a convenience for precompilation.
- template.source = 'function(' + (settings.variable || 'obj') + '){\n' + source + '}';
-
- return template;
- };
-
- // Add a "chain" function, which will delegate to the wrapper.
- _.chain = function(obj) {
- return _(obj).chain();
- };
-
- // OOP
- // ---------------
- // If Underscore is called as a function, it returns a wrapped object that
- // can be used OO-style. This wrapper holds altered versions of all the
- // underscore functions. Wrapped objects may be chained.
-
- // Helper function to continue chaining intermediate results.
- var result = function(obj) {
- return this._chain ? _(obj).chain() : obj;
- };
-
- // Add all of the Underscore functions to the wrapper object.
- _.mixin(_);
-
- // Add all mutator Array functions to the wrapper.
- each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) {
- var method = ArrayProto[name];
- _.prototype[name] = function() {
- var obj = this._wrapped;
- method.apply(obj, arguments);
- if ((name == 'shift' || name == 'splice') && obj.length === 0) delete obj[0];
- return result.call(this, obj);
- };
- });
-
- // Add all accessor Array functions to the wrapper.
- each(['concat', 'join', 'slice'], function(name) {
- var method = ArrayProto[name];
- _.prototype[name] = function() {
- return result.call(this, method.apply(this._wrapped, arguments));
- };
- });
-
- _.extend(_.prototype, {
-
- // Start chaining a wrapped Underscore object.
- chain: function() {
- this._chain = true;
- return this;
- },
-
- // Extracts the result from a wrapped and chained object.
- value: function() {
- return this._wrapped;
- }
-
- });
-
- // AMD registration happens at the end for compatibility with AMD loaders
- // that may not enforce next-turn semantics on modules. Even though general
- // practice for AMD registration is to be anonymous, underscore registers
- // as a named module because, like jQuery, it is a base library that is
- // popular enough to be bundled in a third party lib, but not be part of
- // an AMD load request. Those cases could generate an error when an
- // anonymous define() is called outside of a loader request.
- if (typeof define === 'function' && define.amd) {
- define('underscore', [], function() {
- return _;
- });
- }
-}).call(this);