diff --git a/client/GruntFile.js b/client/GruntFile.js index 0f5af13f719..31f632d4de1 100644 --- a/client/GruntFile.js +++ b/client/GruntFile.js @@ -1,171 +1,181 @@ module.exports = function(grunt) { + var DEV_PATH = './galaxy/scripts', + DIST_PATH = '../static/scripts', + MAPS_PATH = '../static/maps', + // this symlink allows us to serve uncompressed scripts in DEV_PATH for use with sourcemaps + SRC_SYMLINK = '../static/src'; - // Project configuration. - grunt.initConfig({ - pkg: grunt.file.readJSON( 'package.json' ), + // Project configuration. + grunt.initConfig({ + pkg: grunt.file.readJSON( 'package.json' ), - // default task - // use 'grunt copy' to copy the entire /client/galaxy/scripts dir into /static/scripts - copy: { - main: { - files: [ - { + uglify: { + target : { + files: [{ + expand : true, + cwd : SRC_SYMLINK, + src : '**/*.js', + dest : DIST_PATH + }], + options : { + sourceMap : true, + sourceMapName : function( path ){ + // rewrite name to have all source maps in 'static/maps' + return path.replace( DIST_PATH, MAPS_PATH ) + '.map'; + } + } + }, + options : { + mangle : { + screw_ie8 : true + }, + compress : { + // high compression options + screw_ie8 : true, + sequences: true, + dead_code : true, + drop_debugger : true, + comparisons : true, + conditionals : true, + evaluate : true, + booleans : true, + loops : true, + unused : true, + hoist_funs : true, + if_return : true, + join_vars : true, + cascade : true, + drop_console : true + } + } + }, + + // use 'grunt watch' (from a new tab in your terminal) to have grunt re-copy changed files automatically + watch: { + // watch for changes in the src dir + files: [ SRC_SYMLINK + '/**' ], + tasks: [ 'uglify' ], + // tasks: [ 'copy', 'pack' ], + options: { + spawn: false + } + }, + + // call bower to install libraries and other external resources + "bower-install-simple" : { + options: { + color: true + }, + "prod": { + options: { + production: true + } + }, + "dev": { + options: { + production: false + } + } + }, + // where to move fetched bower components into the build structure (libName: [ bower-location, libs-location ]) + libraryLocations : { + "jquery": [ "dist/jquery.js", "jquery/jquery.js" ], + "jquery-migrate": [ "jquery-migrate.js", "jquery/jquery.migrate.js" ], + "traceKit": [ "tracekit.js", "tracekit.js" ], + "ravenjs": [ "dist/raven.js", "raven.js" ], + "underscore": [ "underscore.js", "underscore.js" ], + "handlebars": [ "handlebars.runtime.js", "handlebars.runtime.js" ], + "lunr.js": [ "lunr.js", "lunr.js" ], + "backbone": [ "backbone.js", "backbone/backbone.js" ], + + // these need to be updated and tested + //"require": [ "build/require.js", "require.js" ], + //"d3": [ "d3.js", "d3.js" ], + //"farbtastic": [ "src/farbtastic.js", "farbtastic.js" ], + //"jQTouch": [ "src/reference/jqtouch.js", "jquery/jqtouch.js" ], + //"bib2json": [ "Parser.js", "bibtex.js" ], + //"jquery-form": [ "jquery.form.js", "jquery/jquery.form.js" ], + //"jquery-autocomplete": [ "src/jquery.autocomplete.js", "jquery/jquery.autocomplete.js" ], + //"select2": [ "select2.js", "jquery/select2.js" ], + //"jStorage": [ "jstorage.js", "jquery/jstorage.js" ], + //"jquery.cookie": [ "", "jquery/jquery.cookie.js" ], + //"dynatree": [ "dist/jquery.dynatree.js", "jquery/jquery.dynatree.js" ], + //"jquery-mousewheel": [ "jquery.mousewheel.js", "jquery/jquery.mousewheel.js" ], + //"jquery.event.drag-drop": [ + // [ "event.drag/jquery.event.drag.js", "jquery/jquery.event.drag.js" ], + // [ "event.drag/jquery.event.drop.js", "jquery/jquery.event.drop.js" ] + //], + + // these are complicated by additional css/less + //"toastr": [ "toastr.js", "toastr.js" ], + //"wymeditor": [ "dist/wymeditor/jquery.wymeditor.js", "jquery/jquery.wymeditor.js" ], + //"jstree": [ "jstree.js", "jquery/jstree.js" ], + + // these have been customized by Galaxy + //"bootstrap": [ "dist/js/bootstrap.js", "bootstrap.js" ], + //"jquery-ui": [ + // // multiple components now + // [ "", "jquery/jquery-ui.js" ] + //], + + } + + }); + + grunt.loadNpmTasks( 'grunt-contrib-watch' ); + grunt.loadNpmTasks( 'grunt-contrib-uglify' ); + grunt.loadNpmTasks( 'grunt-bower-install-simple'); + + grunt.registerTask( 'default', [ 'uglify' ] ); + + // -------------------------------------------------------------------------- copy,pack only those changed + // adapted from grunt-contrib-watch jslint example + //TODO: a bit hacky and there's prob. a better way + //NOTE: copy will fail silently if a file isn't found + + // outer scope variable for the event handler and onChange fn - begin with empty hash + var changedFiles = Object.create(null); + + // when files are changed, set the copy src and packScripts target to the filenames of the updated files + var onChange = grunt.util._.debounce(function() { + grunt.log.writeln( 'onChange, changedFiles:', Object.keys( changedFiles ) ); + grunt.config( 'uglify.target.files', [{ expand : true, - cwd : 'galaxy/scripts/', - src : '**', - dest : '../static/scripts' - } - ] - } - }, + cwd : SRC_SYMLINK, + src : Object.keys( changedFiles ), + dest : DIST_PATH + }]); + changedFiles = Object.create(null); + }, 200); - // use 'grunt pack' to call pack_scripts.py to pack all or selected files in static/scripts - exec: { - packScripts: { - cwd: '../static/scripts', - target: [], - cmd: function(){ - var targets = grunt.config( 'exec.packScripts.target' ); - // if nothing was passed in pack all scripts - if( !targets.length ){ - return './pack_scripts.py'; - } + grunt.event.on( 'watch', function( action, filepath ) { + // store each filepath in a Files obj, the debounced fn above will use it as an aggregate list for copying + // we need to take galaxy/scripts out of the filepath or it will be copied to the wrong loc + filepath = filepath.replace( SRC_SYMLINK + '/', '' ); + grunt.log.writeln( 'on.watch, filepath:', filepath ); + changedFiles[filepath] = action; + onChange(); + }); - grunt.log.write( 'packing: ' + targets + '\n' ); - return targets.map( function( target ){ - return './pack_scripts.py ' + target; - }).join( '; ' ); + // -------------------------------------------------------------------------- fetch/update external libraries + /** copy external libraries from bower components to scripts/libs */ + function copyLibs(){ + var LIB_PATH = DEV_PATH + '/libs/', + libraryLocations = grunt.config( 'libraryLocations' ); + for( var libName in libraryLocations ){ + if( libraryLocations.hasOwnProperty( libName ) ){ + var BOWER_DIR = 'bower_components', + location = libraryLocations[ libName ], + source = [ BOWER_DIR, libName, location[0] ].join( '/' ), + destination = LIB_PATH + location[1]; + grunt.log.writeln( source + ' -> ' + destination ); + grunt.file.copy( source, destination ); + } } - } - }, - - // use 'grunt watch' (from a new tab in your terminal) to have grunt re-copy changed files automatically - watch: { - // watch for changes in the src dir - files: [ 'galaxy/scripts/**' ], - tasks: [ 'copy', 'pack' ], - options: { - spawn: false - } - }, - - // call bower to install libraries and other external resources - "bower-install-simple" : { - options: { - color: true - }, - "prod": { - options: { - production: true - } - }, - "dev": { - options: { - production: false - } - } - }, - // where to move fetched bower components into the build structure (libName: [ bower-location, libs-location ]) - libraryLocations : { - "jquery": [ "dist/jquery.js", "jquery/jquery.js" ], - "jquery-migrate": [ "jquery-migrate.js", "jquery/jquery.migrate.js" ], - "traceKit": [ "tracekit.js", "tracekit.js" ], - "ravenjs": [ "dist/raven.js", "raven.js" ], - "underscore": [ "underscore.js", "underscore.js" ], - "handlebars": [ "handlebars.runtime.js", "handlebars.runtime.js" ], - "lunr.js": [ "lunr.js", "lunr.js" ], - "backbone": [ "backbone.js", "backbone/backbone.js" ], - - // these need to be updated and tested - //"require": [ "build/require.js", "require.js" ], - //"d3": [ "d3.js", "d3.js" ], - //"farbtastic": [ "src/farbtastic.js", "farbtastic.js" ], - //"jQTouch": [ "src/reference/jqtouch.js", "jquery/jqtouch.js" ], - //"bib2json": [ "Parser.js", "bibtex.js" ], - //"jquery-form": [ "jquery.form.js", "jquery/jquery.form.js" ], - //"jquery-autocomplete": [ "src/jquery.autocomplete.js", "jquery/jquery.autocomplete.js" ], - //"select2": [ "select2.js", "jquery/select2.js" ], - //"jStorage": [ "jstorage.js", "jquery/jstorage.js" ], - //"jquery.cookie": [ "", "jquery/jquery.cookie.js" ], - //"dynatree": [ "dist/jquery.dynatree.js", "jquery/jquery.dynatree.js" ], - //"jquery-mousewheel": [ "jquery.mousewheel.js", "jquery/jquery.mousewheel.js" ], - //"jquery.event.drag-drop": [ - // [ "event.drag/jquery.event.drag.js", "jquery/jquery.event.drag.js" ], - // [ "event.drag/jquery.event.drop.js", "jquery/jquery.event.drop.js" ] - //], - - // these are complicated by additional css/less - //"toastr": [ "toastr.js", "toastr.js" ], - //"wymeditor": [ "dist/wymeditor/jquery.wymeditor.js", "jquery/jquery.wymeditor.js" ], - //"jstree": [ "jstree.js", "jquery/jstree.js" ], - - // these have been customized by Galaxy - //"bootstrap": [ "dist/js/bootstrap.js", "bootstrap.js" ], - //"jquery-ui": [ - // // multiple components now - // [ "", "jquery/jquery-ui.js" ] - //], - } - }); - - grunt.loadNpmTasks( 'grunt-contrib-watch' ); - grunt.loadNpmTasks( 'grunt-contrib-copy'); - grunt.loadNpmTasks( 'grunt-bower-install-simple'); - grunt.loadNpmTasks( 'grunt-exec' ); - - grunt.registerTask( 'pack', [ 'exec' ] ); - grunt.registerTask( 'default', [ 'copy:main', 'pack' ] ); - - - // -------------------------------------------------------------------------- copy,pack only those changed - // adapted from grunt-contrib-watch jslint example - //TODO: a bit hacky and there's prob. a better way - //NOTE: copy will fail silently if a file isn't found - - // outer scope variable for the event handler and onChange fn - begin with empty hash - var changedFiles = Object.create(null); - - // when files are changed, set the copy src and packScripts target to the filenames of the updated files - var onChange = grunt.util._.debounce(function() { - grunt.config( 'copy.main.files', [{ - expand: true, - cwd: 'galaxy/scripts', - src: Object.keys( changedFiles ), - dest: '../static/scripts/' - }]); - grunt.config( 'exec.packScripts.target', Object.keys( changedFiles ) ); - changedFiles = Object.create(null); - }, 200); - - grunt.event.on('watch', function(action, filepath) { - // store each filepath in a Files obj, the debounced fn above will use it as an aggregate list for copying - // we need to take galaxy/scripts out of the filepath or it will be copied to the wrong loc - filepath = filepath.replace( /galaxy\/scripts\//, '' ); - changedFiles[filepath] = action; - onChange(); - }); - - // -------------------------------------------------------------------------- fetch/update external libraries - /** copy external libraries from bower components to scripts/libs */ - function copyLibs(){ - var libraryLocations = grunt.config( 'libraryLocations' ); - for( var libName in libraryLocations ){ - if( libraryLocations.hasOwnProperty( libName ) ){ - - var BOWER_DIR = 'bower_components', - location = libraryLocations[ libName ], - source = [ BOWER_DIR, libName, location[0] ].join( '/' ), - destination = 'galaxy/scripts/libs/' + location[1]; - grunt.log.writeln( source + ' -> ' + destination ); - grunt.file.copy( source, destination ); - } - } - } - - grunt.registerTask( 'copy-libs', 'copy external libraries to src', copyLibs ); - grunt.registerTask( 'install-libs', 'fetch external libraries and copy to src', + grunt.registerTask( 'copy-libs', 'copy external libraries to src', copyLibs ); + grunt.registerTask( 'install-libs', 'fetch external libraries and copy to src', [ 'bower-install-simple:prod', 'copy-libs' ] ); }; diff --git a/client/package.json b/client/package.json index 81e0e9757b9..3bf2bcf1f1b 100644 --- a/client/package.json +++ b/client/package.json @@ -9,6 +9,7 @@ "grunt": "^0.4.5", "grunt-bower-install-simple": "^1.1.0", "grunt-contrib-copy": "^0.5.0", + "grunt-contrib-uglify": "^0.8.0", "grunt-contrib-watch": "^0.6.1", "grunt-exec": "^0.4.6", "grunt-webpack": "^1.0.8", diff --git a/config/galaxy.ini.sample b/config/galaxy.ini.sample index 643cb664248..8764fe621cc 100644 --- a/config/galaxy.ini.sample +++ b/config/galaxy.ini.sample @@ -523,12 +523,6 @@ nglims_config_file = tool-data/nglims.yaml #static_style_dir = static/june_2007_style/blue #static_robots_txt = static/robots.txt -# Pack javascript at launch (/static/scripts/*.js) -# This only happens if the modified timestamp of the source .js is newer -# than the version (if it exists) in /static/scripts/packed/ -# Note that this requires java > 1.4 for executing yuicompressor.jar -#pack_scripts = False - # Cloud Launch #enable_cloud_launch = False @@ -798,7 +792,7 @@ use_interactive = True # Expose user list. Setting this to true will expose the user list to authenticated users. This # makes sharing datasets in smaller galaxy instances much easier as they can type a name/email and -# have the correct user show up. This makes less sense on large public galaxy instances where +# have the correct user show up. This makes less sense on large public galaxy instances where # that data shouldn't be exposed. For semi-public galaxies, it may make sense to expose just the # username and not email, or vice versa. #expose_user_name = False diff --git a/lib/galaxy/webapps/galaxy/buildapp.py b/lib/galaxy/webapps/galaxy/buildapp.py index d7492408b52..78b89abc674 100644 --- a/lib/galaxy/webapps/galaxy/buildapp.py +++ b/lib/galaxy/webapps/galaxy/buildapp.py @@ -101,9 +101,6 @@ def app_factory( global_conf, **kwargs ): log.error("Static middleware is enabled in your configuration but this is a uwsgi process. Refusing to wrap in static middleware.") else: webapp = wrap_in_static( webapp, global_conf, plugin_frameworks=[ app.visualizations_registry ], **kwargs ) - if asbool(kwargs.get('pack_scripts', False)): - log.warn( "The 'pack_scripts' option is deprecated" ) - pack_scripts() # Close any pooled database connections before forking try: galaxy.model.mapping.metadata.engine.connection_provider._pool.dispose() @@ -530,21 +527,6 @@ def populate_api_routes( webapp, app ): webapp.mapper.connect( "create", "/api/metrics", controller="metrics", action="create", conditions=dict( method=["POST"] ) ) - -def pack_scripts(): - from glob import glob - from subprocess import call - cmd = "java -jar scripts/yuicompressor.jar --type js static/scripts/%(fname)s -o static/scripts/packed/%(fname)s" - raw_js = [os.path.basename(g) for g in glob( "static/scripts/*.js" )] - for fname in raw_js: - if os.path.exists('static/scripts/packed/%s' % fname): - if os.path.getmtime('static/scripts/packed/%s' % fname) > os.path.getmtime('static/scripts/%s' % fname): - continue # Skip, packed is newer than source. - d = dict( fname=fname ) - log.info("%(fname)s --> packed/%(fname)s" % d) - call( cmd % d, shell=True ) - - def _add_item_tags_controller( webapp, name_prefix, path_prefix, **kwd ): # Not just using map.resources because actions should be based on name not id controller = "%stags" % name_prefix diff --git a/static/scripts/base.js b/static/scripts/base.js index 24a5e6eb63b..57760d577b8 100644 --- a/static/scripts/base.js +++ b/static/scripts/base.js @@ -1,15 +1,2 @@ -define( ["libs/backbone/backbone"], function( Backbone ) { - - var Base = function() { - if( this.initialize ) { - this.initialize.apply(this, arguments); - } - }; - Base.extend = Backbone.Model.extend; - - return { - Base: Base, - Backbone: Backbone - }; - -}); \ No newline at end of file +define(["libs/backbone/backbone"],function(a){var b=function(){this.initialize&&this.initialize.apply(this,arguments)};return b.extend=a.Model.extend,{Base:b,Backbone:a}}); +//# sourceMappingURL=../maps/base.js.map \ No newline at end of file diff --git a/static/scripts/galaxy-app-base.js b/static/scripts/galaxy-app-base.js index 1a2f20532be..2a936f67005 100644 --- a/static/scripts/galaxy-app-base.js +++ b/static/scripts/galaxy-app-base.js @@ -1,160 +1,2 @@ -define([ - 'mvc/user/user-model', - 'utils/metrics-logger', - 'utils/add-logging', - 'utils/localization', - 'bootstrapped-data' -], function( userModel, metricsLogger, addLogging, localize, bootstrapped ){ -// ============================================================================ -/** Base galaxy client-side application. - * Iniitializes: - * logger : the logger/metrics-logger - * localize : the string localizer - * config : the current configuration (any k/v in - * galaxy.ini available from the configuration API) - * user : the current user (as a mvc/user/user-model) - */ -function GalaxyApp( options ){ - var self = this; - return self._init( options || {} ); -} - -// add logging shortcuts for this object -addLogging( GalaxyApp, 'GalaxyApp' ); - -/** default options */ -GalaxyApp.prototype.defaultOptions = { - /** monkey patch attributes from existing window.Galaxy object? */ - patchExisting : true, - /** root url of this app */ - // move to self.root? - root : '/' -}; - -/** initalize options and sub-components */ -GalaxyApp.prototype._init = function init( options ){ - var self = this; - _.extend( self, Backbone.Events ); - - self._processOptions( options ); - self.debug( 'GalaxyApp.options: ', self.options ); - - self._patchGalaxy( window.Galaxy ); - - self._initLogger( options.loggerOptions || {} ); - self.debug( 'GalaxyApp.logger: ', self.logger ); - - self._initLocale(); - self.debug( 'GalaxyApp.localize: ', self.localize ); - - self.config = options.config || bootstrapped.config || {}; - self.debug( 'GalaxyApp.config: ', self.config ); - - self._initUser( options.user || bootstrapped.user || {} ); - self.debug( 'GalaxyApp.user: ', self.user ); - - //TODO: temp - self.trigger( 'ready', self ); - //if( typeof options.onload === 'function' ){ - // options.onload(); - //} - - self._setUpListeners(); - - return self; -}; - -/** add an option from options if the key matches an option in defaultOptions */ -GalaxyApp.prototype._processOptions = function _processOptions( options ){ - var self = this, - defaults = self.defaultOptions; - self.debug( '_processOptions: ', options ); - - self.options = {}; - for( var k in defaults ){ - if( defaults.hasOwnProperty( k ) ){ - self.options[ k ] = ( options.hasOwnProperty( k ) )?( options[ k ] ):( defaults[ k ] ); - } - } - return self; -}; - -/** add an option from options if the key matches an option in defaultOptions */ -GalaxyApp.prototype._patchGalaxy = function _processOptions( patchWith ){ - var self = this; - // in case req or plain script tag order has created a prev. version of the Galaxy obj... - if( self.options.patchExisting && patchWith ){ - self.debug( 'found existing Galaxy object:', patchWith ); - // ...(for now) monkey patch any added attributes that the previous Galaxy may have had - //TODO: move those attributes to more formal assignment in GalaxyApp - for( var k in patchWith ){ - if( patchWith.hasOwnProperty( k ) ){ - self.debug( '\t patching in ' + k + ' to Galaxy' ); - self[ k ] = patchWith[ k ]; - } - } - } -}; - -/** set up the metrics logger (utils/metrics-logger) and pass loggerOptions */ -GalaxyApp.prototype._initLogger = function _initLogger( loggerOptions ){ - var self = this; - self.debug( '_initLogger:', loggerOptions ); - self.logger = new metricsLogger.MetricsLogger( loggerOptions ); - return self; -}; - -/** add the localize fn to this object and the window namespace (as '_l') */ -GalaxyApp.prototype._initLocale = function _initLocale( options ){ - var self = this; - self.debug( '_initLocale:', options ); - self.localize = localize; - // add to window as global shortened alias - window._l = self.localize; - return self; -}; - -/** set up the current user as a Backbone model (mvc/user/user-model) */ -GalaxyApp.prototype._initUser = function _initUser( userJSON ){ - var self = this; - self.debug( '_initUser:', userJSON ); - self.user = new userModel.User( userJSON ); - //TODO: temp - old alias - self.currUser = self.user; - return self; -}; - -/** Set up DOM/jQuery/Backbone event listeners enabled for all pages */ -GalaxyApp.prototype._setUpListeners = function _setUpListeners(){ - var self = this; - - // hook to jq beforeSend to record the most recent ajax call and cache some data about it - /** cached info about the last ajax call made through jQuery */ - self.lastAjax = {}; - $( document ).bind( 'ajaxSend', function( ev, xhr, options ){ - var data = options.data; - try { - data = JSON.parse( data ); - } catch( err ){} - - self.lastAjax = { - url : location.href.slice( 0, -1 ) + options.url, - data : data - }; - //TODO:?? we might somehow manage to *retry* ajax using either this hook or Backbone.sync - }); - -}; - -/** string rep */ -GalaxyApp.prototype.toString = function toString(){ - var userEmail = this.user.get( 'email' ) || '(anonymous)'; - return 'GalaxyApp(' + userEmail + ')'; -}; - - -// ============================================================================ - return { - GalaxyApp : GalaxyApp - }; -}); +define(["mvc/user/user-model","utils/metrics-logger","utils/add-logging","utils/localization","bootstrapped-data"],function(a,b,c,d,e){function f(a){var b=this;return b._init(a||{})}return c(f,"GalaxyApp"),f.prototype.defaultOptions={patchExisting:!0,root:"/"},f.prototype._init=function(a){var b=this;return _.extend(b,Backbone.Events),b._processOptions(a),b.debug("GalaxyApp.options: ",b.options),b._patchGalaxy(window.Galaxy),b._initLogger(a.loggerOptions||{}),b.debug("GalaxyApp.logger: ",b.logger),b._initLocale(),b.debug("GalaxyApp.localize: ",b.localize),b.config=a.config||e.config||{},b.debug("GalaxyApp.config: ",b.config),b._initUser(a.user||e.user||{}),b.debug("GalaxyApp.user: ",b.user),b.trigger("ready",b),b._setUpListeners(),b},f.prototype._processOptions=function(a){var b=this,c=b.defaultOptions;b.debug("_processOptions: ",a),b.options={};for(var d in c)c.hasOwnProperty(d)&&(b.options[d]=a.hasOwnProperty(d)?a[d]:c[d]);return b},f.prototype._patchGalaxy=function(a){var b=this;if(b.options.patchExisting&&a){b.debug("found existing Galaxy object:",a);for(var c in a)a.hasOwnProperty(c)&&(b.debug(" patching in "+c+" to Galaxy"),b[c]=a[c])}},f.prototype._initLogger=function(a){var c=this;return c.debug("_initLogger:",a),c.logger=new b.MetricsLogger(a),c},f.prototype._initLocale=function(a){var b=this;return b.debug("_initLocale:",a),b.localize=d,window._l=b.localize,b},f.prototype._initUser=function(b){var c=this;return c.debug("_initUser:",b),c.user=new a.User(b),c.currUser=c.user,c},f.prototype._setUpListeners=function(){var a=this;a.lastAjax={},$(document).bind("ajaxSend",function(b,c,d){var e=d.data;try{e=JSON.parse(e)}catch(f){}a.lastAjax={url:location.href.slice(0,-1)+d.url,data:e}})},f.prototype.toString=function(){var a=this.user.get("email")||"(anonymous)";return"GalaxyApp("+a+")"},{GalaxyApp:f}}); +//# sourceMappingURL=../maps/galaxy-app-base.js.map \ No newline at end of file diff --git a/static/scripts/galaxy.autocom_tagging.js b/static/scripts/galaxy.autocom_tagging.js index 9f61f008fb2..af8aadfdac5 100644 --- a/static/scripts/galaxy.autocom_tagging.js +++ b/static/scripts/galaxy.autocom_tagging.js @@ -1,368 +1,2 @@ -/** -* JQuery extension for tagging with autocomplete. -* @author: Jeremy Goecks -* @require: jquery.autocomplete plugin -*/ -// -// Initialize "tag click functions" for tags. -// -function init_tag_click_function(tag_elt, click_func) { - $(tag_elt).find('.tag-name').each( function() { - $(this).click( function() { - var tag_str = $(this).text(); - var tag_name_and_value = tag_str.split(":"); - click_func(tag_name_and_value[0], tag_name_and_value[1]); - return true; - }); - }); -} - -jQuery.fn.autocomplete_tagging = function(options) { - - var defaults = { - get_toggle_link_text_fn: function(tags) { - var text = ""; - var num_tags = obj_length(tags); - if (num_tags > 0) { - text = num_tags + (num_tags > 1 ? " Tags" : " Tag"); - } else { - text = "Add tags"; - } - return text; - }, - tag_click_fn : function (name, value) {}, - editable: true, - input_size: 20, - in_form: false, - tags : {}, - use_toggle_link: true, - item_id: "", - add_tag_img: "", - add_tag_img_rollover: "", - delete_tag_img: "", - ajax_autocomplete_tag_url: "", - ajax_retag_url: "", - ajax_delete_tag_url: "", - ajax_add_tag_url: "" - }; - - var settings = jQuery.extend(defaults, options); - - // - // Initalize object's elements. - // - - // Get elements for this object. For this_obj, assume the last element with the id is the "this"; this is somewhat of a hack to address the problem - // that there may be two tagging elements for a single item if there are both community and individual tags for an element. - var this_obj = $(this); - var tag_area = this_obj.find('.tag-area'); - var toggle_link = this_obj.find('.toggle-link'); - var tag_input_field = this_obj.find('.tag-input'); - var add_tag_button = this_obj.find('.add-tag-button'); - - // Initialize toggle link. - toggle_link.click( function() { - // Take special actions depending on whether toggle is showing or hiding link. - var after_toggle_fn; - if (tag_area.is(":hidden")) { - after_toggle_fn = function() { - // If there are no tags, go right to editing mode by generating a click on the area. - var num_tags = $(this).find('.tag-button').length; - if (num_tags === 0) { - tag_area.click(); - } - }; - } else { - after_toggle_fn = function() { - tag_area.blur(); - }; - } - tag_area.slideToggle("fast", after_toggle_fn); - return $(this); - }); - - // Initialize tag input field. - if (settings.editable) { - tag_input_field.hide(); - } - tag_input_field.keyup( function(e) { - if ( e.keyCode === 27 ) { - // Escape key - $(this).trigger( "blur" ); - } else if ( - ( e.keyCode === 13 ) || // Return Key - ( e.keyCode === 188 ) || // Comma - ( e.keyCode === 32 ) // Space - ) { - // - // Check input. - // - - var new_value = this.value; - - // Suppress space after a ":" - if ( new_value.indexOf(": ", new_value.length - 2) !== -1) { - this.value = new_value.substring(0, new_value.length-1); - return false; - } - - // Remove trigger keys from input. - if ( (e.keyCode === 188) || (e.keyCode === 32) ) { - new_value = new_value.substring( 0 , new_value.length - 1 ); - } - - // Trim whitespace. - new_value = $.trim(new_value); - - // Too short? - if (new_value.length < 2) { - return false; - } - - // - // New tag OK - apply it. - // - - this.value = ""; // Reset text field now that tag is being added - - // Add button for tag after all other tag buttons. - var new_tag_button = build_tag_button(new_value); - var tag_buttons = tag_area.children(".tag-button"); - if (tag_buttons.length !== 0) { - var last_tag_button = tag_buttons.slice(tag_buttons.length-1); - last_tag_button.after(new_tag_button); - } else { - tag_area.prepend(new_tag_button); - } - - // Add tag to internal list. - var tag_name_and_value = new_value.split(":"); - settings.tags[tag_name_and_value[0]] = tag_name_and_value[1]; - - // Update toggle link text. - var new_text = settings.get_toggle_link_text_fn(settings.tags); - toggle_link.text(new_text); - - // Commit tag to server. - var zz = $(this); - $.ajax({ - url: settings.ajax_add_tag_url, - data: { new_tag: new_value }, - error: function() { - // Failed. Roll back changes and show alert. - new_tag_button.remove(); - delete settings.tags[tag_name_and_value[0]]; - var new_text = settings.get_toggle_link_text_fn(settings.tags); - toggle_link.text(new_text); - alert( "Add tag failed" ); - }, - success: function() { - // Flush autocomplete cache because it's not out of date. - // TODO: in the future, we could remove the particular item - // that was chosen from the cache rather than flush it. - zz.data('autocompleter').cacheFlush(); - } - }); - - return false; - } - }); - - // Add autocomplete to input. - var format_item_func = function(key, row_position, num_rows, value, search_term) { - var tag_name_and_value = value.split(":"); - return (tag_name_and_value.length === 1 ? tag_name_and_value[0] : tag_name_and_value[1]); - }; - var autocomplete_options = { selectFirst: false, formatItem: format_item_func, - autoFill: false, highlight: false }; - tag_input_field.autocomplete(settings.ajax_autocomplete_tag_url, autocomplete_options); - - - // Initialize delete tag images for current tags. - this_obj.find('.delete-tag-img').each(function() { - init_delete_tag_image( $(this) ); - }); - - - // Initialize tag click function. - init_tag_click_function($(this), settings.tag_click_fn); - - // Initialize "add tag" button. - add_tag_button.click( function() { - $(this).hide(); - - // Clicking on button is the same as clicking on the tag area. - tag_area.click(); - return false; - }); - - // - // Set up tag area interactions; these are needed only if tags are editable. - // - if (settings.editable) { - // When the tag area blurs, go to "view tag" mode. - tag_area.bind("blur", function(e) { - if (obj_length(settings.tags) > 0) { - add_tag_button.show(); - tag_input_field.hide(); - tag_area.removeClass("active-tag-area"); - // tag_area.addClass("tooltip"); - } else { - // No tags, so do nothing to ensure that input is still visible. - } - }); - - // On click, enable user to add tags. - tag_area.click( function(e) { - var is_active = $(this).hasClass("active-tag-area"); - - // If a "delete image" object was pressed and area is inactive, do nothing. - if ($(e.target).hasClass("delete-tag-img") && !is_active) { - return false; - } - - // If a "tag name" object was pressed and area is inactive, do nothing. - if ($(e.target).hasClass("tag-name") && !is_active) { - return false; - } - - // Remove tooltip. - // $(this).removeClass("tooltip"); - - // Hide add tag button, show tag_input field. Change background to show - // area is active. - $(this).addClass("active-tag-area"); - add_tag_button.hide(); - tag_input_field.show(); - tag_input_field.focus(); - - // Add handler to document that will call blur when the tag area is blurred; - // a tag area is blurred when a user clicks on an element outside the area. - var handle_document_click = function(e) { - var check_click = function(tag_area, target) { - var tag_area_id = tag_area.attr("id"); - // Blur the tag area if the element clicked on is not in the tag area. - if (target !== tag_area) { - tag_area.blur(); - $(window).unbind("click.tagging_blur"); - $(this).addClass("tooltip"); - } - }; - check_click(tag_area, $(e.target)); - }; - // TODO: we should attach the click handler to all frames in order to capture - // clicks outside the frame that this element is in. - //window.parent.document.onclick = handle_document_click; - //var temp = $(window.parent.document.body).contents().find("iframe").html(); - //alert(temp); - //$(document).parent().click(handle_document_click); - $(window).bind("click.tagging_blur", handle_document_click); - - return false; - }); - } - - // If using toggle link, hide the tag area. Otherwise, show the tag area. - if (settings.use_toggle_link) { - tag_area.hide(); - } - - // - // Helper functions. - // - - // - // Collapse tag name + value into a single string. - // - function build_tag_str(tag_name, tag_value) { - return tag_name + ( tag_value ? ":" + tag_value : ""); - } - - - // Initialize a "delete tag image": when click, delete tag from UI and send delete request to server. - function init_delete_tag_image(delete_img) { - $(delete_img).mouseenter( function () { - $(this).attr("src", settings.delete_tag_img_rollover); - }); - $(delete_img).mouseleave( function () { - $(this).attr("src", settings.delete_tag_img); - }); - $(delete_img).click( function () { - // Tag button is image's parent. - var tag_button = $(this).parent(); - - // Get tag name, value. - var tag_name_elt = tag_button.find(".tag-name").eq(0); - var tag_str = tag_name_elt.text(); - var tag_name_and_value = tag_str.split(":"); - var tag_name = tag_name_and_value[0]; - var tag_value = tag_name_and_value[1]; - - var prev_button = tag_button.prev(); - tag_button.remove(); - - // Remove tag from local list for consistency. - delete settings.tags[tag_name]; - - // Update toggle link text. - var new_text = settings.get_toggle_link_text_fn(settings.tags); - toggle_link.text(new_text); - - // Delete tag. - $.ajax({ - url: settings.ajax_delete_tag_url, - data: { tag_name: tag_name }, - error: function() { - // Failed. Roll back changes and show alert. - settings.tags[tag_name] = tag_value; - if (prev_button.hasClass("tag-button")) { - prev_button.after(tag_button); - } else { - tag_area.prepend(tag_button); - } - alert( "Remove tag failed" ); - - toggle_link.text(settings.get_toggle_link_text_fn(settings.tags)); - - // TODO: no idea why it's necessary to set this up again. - delete_img.mouseenter( function () { - $(this).attr("src", settings.delete_tag_img_rollover); - }); - delete_img.mouseleave( function () { - $(this).attr("src", settings.delete_tag_img); - }); - }, - success: function() {} - }); - - return true; - }); - } - - // - // Function that builds a tag button. - // - function build_tag_button(tag_str) { - // Build "delete tag" image. - var delete_img = $("").attr("src", settings.delete_tag_img).addClass("delete-tag-img"); - init_delete_tag_image(delete_img); - - // Build tag button. - var tag_name_elt = $("").text(tag_str).addClass("tag-name"); - tag_name_elt.click( function() { - var tag_name_and_value = tag_str.split(":"); - settings.tag_click_fn(tag_name_and_value[0], tag_name_and_value[1]); - return true; - }); - - var tag_button = $("").addClass("tag-button"); - tag_button.append(tag_name_elt); - // Allow delete only if element is editable. - if (settings.editable) { - tag_button.append(delete_img); - } - - return tag_button; - } - -}; +function init_tag_click_function(a,b){$(a).find(".tag-name").each(function(){$(this).click(function(){var a=$(this).text(),c=a.split(":");return b(c[0],c[1]),!0})})}jQuery.fn.autocomplete_tagging=function(a){function b(a){$(a).mouseenter(function(){$(this).attr("src",e.delete_tag_img_rollover)}),$(a).mouseleave(function(){$(this).attr("src",e.delete_tag_img)}),$(a).click(function(){var b=$(this).parent(),c=b.find(".tag-name").eq(0),d=c.text(),f=d.split(":"),i=f[0],j=f[1],k=b.prev();b.remove(),delete e.tags[i];var l=e.get_toggle_link_text_fn(e.tags);return h.text(l),$.ajax({url:e.ajax_delete_tag_url,data:{tag_name:i},error:function(){e.tags[i]=j,k.hasClass("tag-button")?k.after(b):g.prepend(b),alert("Remove tag failed"),h.text(e.get_toggle_link_text_fn(e.tags)),a.mouseenter(function(){$(this).attr("src",e.delete_tag_img_rollover)}),a.mouseleave(function(){$(this).attr("src",e.delete_tag_img)})},success:function(){}}),!0})}function c(a){var c=$("").attr("src",e.delete_tag_img).addClass("delete-tag-img");b(c);var d=$("").text(a).addClass("tag-name");d.click(function(){var b=a.split(":");return e.tag_click_fn(b[0],b[1]),!0});var f=$("").addClass("tag-button");return f.append(d),e.editable&&f.append(c),f}var d={get_toggle_link_text_fn:function(a){var b="",c=obj_length(a);return b=c>0?c+(c>1?" Tags":" Tag"):"Add tags"},tag_click_fn:function(){},editable:!0,input_size:20,in_form:!1,tags:{},use_toggle_link:!0,item_id:"",add_tag_img:"",add_tag_img_rollover:"",delete_tag_img:"",ajax_autocomplete_tag_url:"",ajax_retag_url:"",ajax_delete_tag_url:"",ajax_add_tag_url:""},e=jQuery.extend(d,a),f=$(this),g=f.find(".tag-area"),h=f.find(".toggle-link"),i=f.find(".tag-input"),j=f.find(".add-tag-button");h.click(function(){var a;return a=g.is(":hidden")?function(){var a=$(this).find(".tag-button").length;0===a&&g.click()}:function(){g.blur()},g.slideToggle("fast",a),$(this)}),e.editable&&i.hide(),i.keyup(function(a){if(27===a.keyCode)$(this).trigger("blur");else if(13===a.keyCode||188===a.keyCode||32===a.keyCode){var b=this.value;if(-1!==b.indexOf(": ",b.length-2))return this.value=b.substring(0,b.length-1),!1;if((188===a.keyCode||32===a.keyCode)&&(b=b.substring(0,b.length-1)),b=$.trim(b),b.length<2)return!1;this.value="";var d=c(b),f=g.children(".tag-button");if(0!==f.length){var i=f.slice(f.length-1);i.after(d)}else g.prepend(d);var j=b.split(":");e.tags[j[0]]=j[1];var k=e.get_toggle_link_text_fn(e.tags);h.text(k);var l=$(this);return $.ajax({url:e.ajax_add_tag_url,data:{new_tag:b},error:function(){d.remove(),delete e.tags[j[0]];var a=e.get_toggle_link_text_fn(e.tags);h.text(a),alert("Add tag failed")},success:function(){l.data("autocompleter").cacheFlush()}}),!1}});var k=function(a,b,c,d){var e=d.split(":");return 1===e.length?e[0]:e[1]},l={selectFirst:!1,formatItem:k,autoFill:!1,highlight:!1};i.autocomplete(e.ajax_autocomplete_tag_url,l),f.find(".delete-tag-img").each(function(){b($(this))}),init_tag_click_function($(this),e.tag_click_fn),j.click(function(){return $(this).hide(),g.click(),!1}),e.editable&&(g.bind("blur",function(){obj_length(e.tags)>0&&(j.show(),i.hide(),g.removeClass("active-tag-area"))}),g.click(function(a){var b=$(this).hasClass("active-tag-area");if($(a.target).hasClass("delete-tag-img")&&!b)return!1;if($(a.target).hasClass("tag-name")&&!b)return!1;$(this).addClass("active-tag-area"),j.hide(),i.show(),i.focus();var c=function(a){var b=function(a,b){a.attr("id");b!==a&&(a.blur(),$(window).unbind("click.tagging_blur"),$(this).addClass("tooltip"))};b(g,$(a.target))};return $(window).bind("click.tagging_blur",c),!1})),e.use_toggle_link&&g.hide()}; +//# sourceMappingURL=../maps/galaxy.autocom_tagging.js.map \ No newline at end of file diff --git a/static/scripts/galaxy.base.js b/static/scripts/galaxy.base.js index c6adb1963f4..b9f51ab9cfc 100644 --- a/static/scripts/galaxy.base.js +++ b/static/scripts/galaxy.base.js @@ -1,634 +1,2 @@ -// requestAnimationFrame polyfill -(function() { - var lastTime = 0; - var vendors = ['ms', 'moz', 'webkit', 'o']; - for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) { - window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame']; - window.cancelRequestAnimationFrame = window[vendors[x]+ - 'CancelRequestAnimationFrame']; - } - - if (!window.requestAnimationFrame) - window.requestAnimationFrame = function(callback, element) { - var currTime = new Date().getTime(); - var timeToCall = Math.max(0, 16 - (currTime - lastTime)); - var id = window.setTimeout(function() { callback(currTime + timeToCall); }, - timeToCall); - lastTime = currTime + timeToCall; - return id; - }; - - if (!window.cancelAnimationFrame) - window.cancelAnimationFrame = function(id) { - clearTimeout(id); - }; -}()); - -// IE doesn't implement Array.indexOf -if (!Array.indexOf) { - Array.prototype.indexOf = function(obj) { - for (var i = 0, len = this.length; i < len; i++) { - if (this[i] == obj) { - return i; - } - } - return -1; - }; -} - -// Returns the number of keys (elements) in an array/dictionary. -function obj_length(obj) { - if (obj.length !== undefined) { - return obj.length; - } - - var count = 0; - for (var element in obj) { - count++; - } - return count; -} - -$.fn.makeAbsolute = function(rebase) { - return this.each(function() { - var el = $(this); - var pos = el.position(); - el.css({ - position: "absolute", - marginLeft: 0, marginTop: 0, - top: pos.top, left: pos.left, - right: $(window).width() - ( pos.left + el.width() ) - }); - if (rebase) { - el.remove().appendTo("body"); - } - }); -}; - -/** - * Sets up popupmenu rendering and binds options functions to the appropriate links. - * initial_options is a dict with text describing the option pointing to either (a) a - * function to perform; or (b) another dict with two required keys, 'url' and 'action' (the - * function to perform. (b) is useful for exposing the underlying URL of the option. - */ -function make_popupmenu(button_element, initial_options) { - /* Use the $.data feature to store options with the link element. - This allows options to be changed at a later time - */ - var element_menu_exists = (button_element.data("menu_options")); - button_element.data("menu_options", initial_options); - - // If element already has menu, nothing else to do since HTML and actions are already set. - if (element_menu_exists) { return; } - - button_element.bind("click.show_popup", function(e) { - // Close existing visible menus - $(".popmenu-wrapper").remove(); - - // Need setTimeouts so clicks don't interfere with each other - setTimeout( function() { - // Dynamically generate the wrapper holding all the selectable options of the menu. - var menu_element = $( "" ); - var options = button_element.data("menu_options"); - if (obj_length(options) <= 0) { - $("
  • No Options.
  • ").appendTo(menu_element); - } - $.each( options, function( k, v ) { - if (v) { - // Action can be either an anonymous function and a mapped dict. - var action = v.action || v; - menu_element.append( $("
  • ").append( $("").attr("href", v.url).html(k).click(action) ) ); - } else { - menu_element.append( $("
  • ").addClass( "head" ).append( $("
    ").html(k) ) ); - } - }); - var wrapper = $( "
    " ) - .append( menu_element ).appendTo( "body" ); - - var x = e.pageX - wrapper.width() / 2 ; - x = Math.min( x, $(document).scrollLeft() + $(window).width() - $(wrapper).width() - 5 ); - x = Math.max( x, $(document).scrollLeft() + 5 ); - - wrapper.css({ - top: e.pageY, - left: x - }); - }, 10); - - setTimeout( function() { - // Bind click event to current window and all frames to remove any visible menus - // Bind to document object instead of window object for IE compat - var close_popup = function(el) { - $(el).bind("click.close_popup", function() { - $(".popmenu-wrapper").remove(); - el.unbind("click.close_popup"); - }); - }; - close_popup( $(window.document) ); // Current frame - close_popup( $(window.top.document) ); // Parent frame - for (var frame_id = window.top.frames.length; frame_id--;) { // Sibling frames - var frame = $(window.top.frames[frame_id].document); - close_popup(frame); - } - }, 50); - - return false; - }); - -} - -/** - * Convert two seperate (often adjacent) divs into galaxy popupmenu - * - div 1 contains a number of anchors which become the menu options - * - div 1 should have a 'popupmenu' attribute - * - this popupmenu attribute contains the id of div 2 - * - div 2 becomes the 'face' of the popupmenu - * - * NOTE: make_popup_menus finds and operates on all divs with a popupmenu attr (no need to point it at something) - * but (since that selector searches the dom on the page), you can send a parent in - * NOTE: make_popup_menus, and make_popupmenu are horrible names - */ -function make_popup_menus( parent ) { - // find all popupmenu menu divs (divs that contains anchors to be converted to menu options) - // either in the parent or the document if no parent passed - parent = parent || document; - $( parent ).find( "div[popupmenu]" ).each( function() { - var options = {}; - var menu = $(this); - - // find each anchor in the menu, convert them into an options map: { a.text : click_function } - menu.find( "a" ).each( function() { - var link = $(this), - link_dom = link.get(0), - confirmtext = link_dom.getAttribute( "confirm" ), - href = link_dom.getAttribute( "href" ), - target = link_dom.getAttribute( "target" ); - - // no href - no function (gen. a label) - if (!href) { - options[ link.text() ] = null; - - } else { - options[ link.text() ] = { - url: href, - action: function( event ) { - - // if theres confirm text, send the dialog - if ( !confirmtext || confirm( confirmtext ) ) { - // link.click() doesn't use target for some reason, - // so manually do it here. - if (target) { - window.open(href, target); - return false; - } - // For all other links, do the default action. - else { - link.click(); - } - } else { - event.preventDefault(); - } - - } - }; - } - }); - // locate the element with the id corresponding to the menu's popupmenu attr - var box = $( parent ).find( "#" + menu.attr( 'popupmenu' ) ); - - // For menus with clickable link text, make clicking on the link go through instead - // of activating the popup menu - box.find("a").bind("click", function(e) { - e.stopPropagation(); // Stop bubbling so clicking on the link goes through - return true; - }); - - // attach the click events and menu box building to the box element - make_popupmenu(box, options); - box.addClass("popup"); - menu.remove(); - }); -} - -$.fn.refresh_select2 = function() { - var select_elt = $(this); - var options = { placeholder:'Click to select', - closeOnSelect: !select_elt.is("[MULTIPLE]"), - dropdownAutoWidth : true, - containerCssClass: 'select2-minwidth' - }; - return select_elt.select2( options ); -} - -// Replace select box with a text input box + autocomplete. -function replace_big_select_inputs(min_length, max_length, select_elts) { - // To do replace, the select2 plugin must be loaded. - - if (!jQuery.fn.select2) { - return; - } - - // Set default for min_length and max_length - if (min_length === undefined) { - min_length = 20; - } - if (max_length === undefined) { - max_length = 3000; - } - - select_elts = select_elts || $('select'); - - select_elts.each( function() { - var select_elt = $(this).not('[multiple]'); - // Make sure that options is within range. - var num_options = select_elt.find('option').length; - if ( (num_options < min_length) || (num_options > max_length) ) { - return; - } - - if (select_elt.hasClass("no-autocomplete")) { - return; - } - - /* Replaced jQuery.autocomplete with select2, notes: - * - multiple selects are supported - * - the original element is updated with the value, convert_to_values should not be needed - * - events are fired when updating the original element, so refresh_on_change should just work - * - * - should we still sort dbkey fields here? - */ - select_elt.refresh_select2(); - }); -} - -/** - * Make an element with text editable: (a) when user clicks on text, a textbox/area - * is provided for editing; (b) when enter key pressed, element's text is set and on_finish - * is called. - */ -// TODO: use this function to implement async_save_text (implemented below). -$.fn.make_text_editable = function(config_dict) { - // Get config options. - var num_cols = ("num_cols" in config_dict ? config_dict.num_cols : 30), - num_rows = ("num_rows" in config_dict ? config_dict.num_rows : 4), - use_textarea = ("use_textarea" in config_dict ? config_dict.use_textarea : false), - on_finish = ("on_finish" in config_dict ? config_dict.on_finish : null), - help_text = ("help_text" in config_dict ? config_dict.help_text : null); - - // Add element behavior. - var container = $(this); - container.addClass("editable-text").click(function(e) { - // If there's already an input element, editing is active, so do nothing. - if ($(this).children(":input").length > 0) { - return; - } - - container.removeClass("editable-text"); - - // Handler for setting element text. - var set_text = function(new_text) { - container.find(":input").remove(); - - if (new_text !== "") { - container.text(new_text); - } - else { - // No text; need a line so that there is a click target. - container.html("
    "); - } - container.addClass("editable-text"); - - if (on_finish) { - on_finish(new_text); - } - }; - - // Create input element(s) for editing. - var cur_text = ("cur_text" in config_dict ? config_dict.cur_text : container.text() ), - input_elt, button_elt; - - if (use_textarea) { - input_elt = $("").attr({ rows: num_rows, cols: num_cols }).text( $.trim(old_text) ); - } else { - t = $("").attr({ value: $.trim(old_text), size: num_cols }); - } - t.attr("id", "renaming-active"); - t.blur( function() { - $(this).remove(); - text_elt.show(); - if (on_finish) { - on_finish(t); - } - }); - t.keyup( function( e ) { - if ( e.keyCode === 27 ) { - // Escape key - $(this).trigger( "blur" ); - } else if ( e.keyCode === 13 ) { - // Enter key submits - var ajax_data = {}; - ajax_data[text_parm_name] = $(this).val(); - $(this).trigger( "blur" ); - $.ajax({ - url: save_url, - data: ajax_data, - error: function() { - alert( "Text editing for elt " + text_elt_id + " failed" ); - // TODO: call finish or no? For now, let's not because error occurred. - }, - success: function(processed_text) { - // Set new text and call finish method. - if (processed_text !== "") { - text_elt.text(processed_text); - } else { - text_elt.html("None"); - } - if (on_finish) { - on_finish(t); - } - } - }); - } - }); - - if (on_start) { - on_start(t); - } - // Replace text with input object and focus & select. - text_elt.hide(); - t.insertAfter(text_elt); - t.focus(); - t.select(); - - return; - }); -} - -function commatize( number ) { - number += ''; // Convert to string - var rgx = /(\d+)(\d{3})/; - while (rgx.test(number)) { - number = number.replace(rgx, '$1' + ',' + '$2'); - } - return number; -} - -// Reset tool search to start state. -function reset_tool_search( initValue ) { - // Function may be called in top frame or in tool_menu_frame; - // in either case, get the tool menu frame. - var tool_menu_frame = $("#galaxy_tools").contents(); - if (tool_menu_frame.length === 0) { - tool_menu_frame = $(document); - } - - // Remove classes that indicate searching is active. - $(this).removeClass("search_active"); - tool_menu_frame.find(".toolTitle").removeClass("search_match"); - - // Reset visibility of tools and labels. - tool_menu_frame.find(".toolSectionBody").hide(); - tool_menu_frame.find(".toolTitle").show(); - tool_menu_frame.find(".toolPanelLabel").show(); - tool_menu_frame.find(".toolSectionWrapper").each( function() { - if ($(this).attr('id') !== 'recently_used_wrapper') { - // Default action. - $(this).show(); - } else if ($(this).hasClass("user_pref_visible")) { - $(this).show(); - } - }); - tool_menu_frame.find("#search-no-results").hide(); - - // Reset search input. - tool_menu_frame.find("#search-spinner").hide(); - if (initValue) { - var search_input = tool_menu_frame.find("#tool-search-query"); - search_input.val("search tools"); - } -} - -// Create GalaxyAsync object. -var GalaxyAsync = function(log_action) { - this.url_dict = {}; - this.log_action = (log_action === undefined ? false : log_action); -}; - -GalaxyAsync.prototype.set_func_url = function( func_name, url ) { - this.url_dict[func_name] = url; -}; - -// Set user preference asynchronously. -GalaxyAsync.prototype.set_user_pref = function( pref_name, pref_value ) { - // Get URL. - var url = this.url_dict[arguments.callee]; - if (url === undefined) { return false; } - $.ajax({ - url: url, - data: { "pref_name" : pref_name, "pref_value" : pref_value }, - error: function() { return false; }, - success: function() { return true; } - }); -}; - -// Log user action asynchronously. -GalaxyAsync.prototype.log_user_action = function( action, context, params ) { - if (!this.log_action) { return; } - - // Get URL. - var url = this.url_dict[arguments.callee]; - if (url === undefined) { return false; } - $.ajax({ - url: url, - data: { "action" : action, "context" : context, "params" : params }, - error: function() { return false; }, - success: function() { return true; } - }); -}; - -// Initialize refresh events. -function init_refresh_on_change () { - $("select[refresh_on_change='true']") - .off('change') - .change(function() { - var select_field = $(this), - select_val = select_field.val(), - refresh = false, - ref_on_change_vals = select_field.attr("refresh_on_change_values"); - if (ref_on_change_vals) { - ref_on_change_vals = ref_on_change_vals.split(','); - var last_selected_value = select_field.attr("last_selected_value"); - if ($.inArray(select_val, ref_on_change_vals) === -1 && $.inArray(last_selected_value, ref_on_change_vals) === -1) { - return; - } - } - $(window).trigger("refresh_on_change"); - $(document).trigger("convert_to_values"); // Convert autocomplete text to values - select_field.get(0).form.submit(); - }); - - // checkboxes refresh on change - $(":checkbox[refresh_on_change='true']") - .off('click') - .click( function() { - var select_field = $(this), - select_val = select_field.val(), - refresh = false, - ref_on_change_vals = select_field.attr("refresh_on_change_values"); - if (ref_on_change_vals) { - ref_on_change_vals = ref_on_change_vals.split(','); - var last_selected_value = select_field.attr("last_selected_value"); - if ($.inArray(select_val, ref_on_change_vals) === -1 && $.inArray(last_selected_value, ref_on_change_vals) === -1) { - return; - } - } - $(window).trigger("refresh_on_change"); - select_field.get(0).form.submit(); - }); - - // Links with confirmation - $( "a[confirm]" ) - .off('click') - .click( function() { - return confirm( $(this).attr("confirm") ); - }); -}; - - -// jQuery plugin to prevent double submission of forms -// Ref: http://stackoverflow.com/questions/2830542/prevent-double-submission-of-forms-in-jquery -jQuery.fn.preventDoubleSubmission = function() { - $(this).on('submit',function(e){ - var $form = $(this); - - if ($form.data('submitted') === true) { - // Previously submitted - don't submit again - e.preventDefault(); - } else { - // Mark it so that the next submit can be ignored - $form.data('submitted', true); - } - }); - - // Keep chainability - return this; -}; - -$(document).ready( function() { - - // Refresh events for form fields. - init_refresh_on_change(); - - // Tooltips - if ( $.fn.tooltip ) { - // Put tooltips below items in panel header so that they do not overlap masthead. - $(".unified-panel-header [title]").tooltip( { placement: 'bottom' } ); - - // default tooltip initialization, it will follow the data-placement tag for tooltip location - // and fallback to 'top' if not present - $("[title]").tooltip(); - } - // Make popup menus. - make_popup_menus(); - - // Replace big selects. - replace_big_select_inputs(20, 1500); - - // If galaxy_main frame does not exist and link targets galaxy_main, - // add use_panels=True and set target to self. - $("a").click( function() { - var anchor = $(this); - var galaxy_main_exists = (parent.frames && parent.frames.galaxy_main); - if ( ( anchor.attr( "target" ) == "galaxy_main" ) && ( !galaxy_main_exists ) ) { - var href = anchor.attr("href"); - if (href.indexOf("?") == -1) { - href += "?"; - } - else { - href += "&"; - } - href += "use_panels=True"; - anchor.attr("href", href); - anchor.attr("target", "_self"); - } - return anchor; - }); - -}); +function obj_length(a){if(void 0!==a.length)return a.length;var b=0;for(var c in a)b++;return b}function make_popupmenu(a,b){var c=a.data("menu_options");a.data("menu_options",b),c||a.bind("click.show_popup",function(b){return $(".popmenu-wrapper").remove(),setTimeout(function(){var c=$(""),d=a.data("menu_options");obj_length(d)<=0&&$("
  • No Options.
  • ").appendTo(c),$.each(d,function(a,b){if(b){var d=b.action||b;c.append($("
  • ").append($("").attr("href",b.url).html(a).click(d)))}else c.append($("
  • ").addClass("head").append($("
    ").html(a)))});var e=$("
    ").append(c).appendTo("body"),f=b.pageX-e.width()/2;f=Math.min(f,$(document).scrollLeft()+$(window).width()-$(e).width()-5),f=Math.max(f,$(document).scrollLeft()+5),e.css({top:b.pageY,left:f})},10),setTimeout(function(){var a=function(a){$(a).bind("click.close_popup",function(){$(".popmenu-wrapper").remove(),a.unbind("click.close_popup")})};a($(window.document)),a($(window.top.document));for(var b=window.top.frames.length;b--;){var c=$(window.top.frames[b].document);a(c)}},50),!1})}function make_popup_menus(a){a=a||document,$(a).find("div[popupmenu]").each(function(){var b={},c=$(this);c.find("a").each(function(){var a=$(this),c=a.get(0),d=c.getAttribute("confirm"),e=c.getAttribute("href"),f=c.getAttribute("target");b[a.text()]=e?{url:e,action:function(b){if(!d||confirm(d)){if(f)return window.open(e,f),!1;a.click()}else b.preventDefault()}}:null});var d=$(a).find("#"+c.attr("popupmenu"));d.find("a").bind("click",function(a){return a.stopPropagation(),!0}),make_popupmenu(d,b),d.addClass("popup"),c.remove()})}function replace_big_select_inputs(a,b,c){jQuery.fn.select2&&(void 0===a&&(a=20),void 0===b&&(b=3e3),c=c||$("select"),c.each(function(){var c=$(this).not("[multiple]"),d=c.find("option").length;a>d||d>b||c.hasClass("no-autocomplete")||c.refresh_select2()}))}function async_save_text(a,b,c,d,e,f,g,h,i){void 0===e&&(e=30),void 0===g&&(g=4),$("#"+a).click(function(){if(!($("#renaming-active").length>0)){var a,j=$("#"+b),k=j.text();a=f?$("").attr({rows:g,cols:e}).text($.trim(k)):$("").attr({value:$.trim(k),size:e}),a.attr("id","renaming-active"),a.blur(function(){$(this).remove(),j.show(),i&&i(a)}),a.keyup(function(e){if(27===e.keyCode)$(this).trigger("blur");else if(13===e.keyCode){var f={};f[d]=$(this).val(),$(this).trigger("blur"),$.ajax({url:c,data:f,error:function(){alert("Text editing for elt "+b+" failed")},success:function(b){""!==b?j.text(b):j.html("None"),i&&i(a)}})}}),h&&h(a),j.hide(),a.insertAfter(j),a.focus(),a.select()}})}function commatize(a){a+="";for(var b=/(\d+)(\d{3})/;b.test(a);)a=a.replace(b,"$1,$2");return a}function reset_tool_search(a){var b=$("#galaxy_tools").contents();if(0===b.length&&(b=$(document)),$(this).removeClass("search_active"),b.find(".toolTitle").removeClass("search_match"),b.find(".toolSectionBody").hide(),b.find(".toolTitle").show(),b.find(".toolPanelLabel").show(),b.find(".toolSectionWrapper").each(function(){"recently_used_wrapper"!==$(this).attr("id")?$(this).show():$(this).hasClass("user_pref_visible")&&$(this).show()}),b.find("#search-no-results").hide(),b.find("#search-spinner").hide(),a){var c=b.find("#tool-search-query");c.val("search tools")}}function init_refresh_on_change(){$("select[refresh_on_change='true']").off("change").change(function(){var a=$(this),b=a.val(),c=a.attr("refresh_on_change_values");if(c){c=c.split(",");var d=a.attr("last_selected_value");if(-1===$.inArray(b,c)&&-1===$.inArray(d,c))return}$(window).trigger("refresh_on_change"),$(document).trigger("convert_to_values"),a.get(0).form.submit()}),$(":checkbox[refresh_on_change='true']").off("click").click(function(){var a=$(this),b=a.val(),c=a.attr("refresh_on_change_values");if(c){c=c.split(",");var d=a.attr("last_selected_value");if(-1===$.inArray(b,c)&&-1===$.inArray(d,c))return}$(window).trigger("refresh_on_change"),a.get(0).form.submit()}),$("a[confirm]").off("click").click(function(){return confirm($(this).attr("confirm"))})}!function(){for(var a=0,b=["ms","moz","webkit","o"],c=0;cb;b++)if(this[b]==a)return b;return-1}),$.fn.makeAbsolute=function(a){return this.each(function(){var b=$(this),c=b.position();b.css({position:"absolute",marginLeft:0,marginTop:0,top:c.top,left:c.left,right:$(window).width()-(c.left+b.width())}),a&&b.remove().appendTo("body")})},$.fn.refresh_select2=function(){var a=$(this),b={placeholder:"Click to select",closeOnSelect:!a.is("[MULTIPLE]"),dropdownAutoWidth:!0,containerCssClass:"select2-minwidth"};return a.select2(b)},$.fn.make_text_editable=function(a){var b="num_cols"in a?a.num_cols:30,c="num_rows"in a?a.num_rows:4,d="use_textarea"in a?a.use_textarea:!1,e="on_finish"in a?a.on_finish:null,f="help_text"in a?a.help_text:null,g=$(this);return g.addClass("editable-text").click(function(f){if(!($(this).children(":input").length>0)){g.removeClass("editable-text");var h,i,j=function(a){g.find(":input").remove(),""!==a?g.text(a):g.html("
    "),g.addClass("editable-text"),e&&e(a)},k="cur_text"in a?a.cur_text:g.text();d?(h=$(" \ -
    Add an annotation or notes to this step; annotations are available when a workflow is viewed.
    \ - \ - \ - " ); - } - // Add step actions. - if (node && node.type=='tool'){ - pjastr = "

    Edit Step Actions
    \ - " + display_pja_list() + "
    "+ display_file_list(node) + "
    Create
    \ -
    \ -
    "; - pjastr += "
    Add actions to this step; actions are applied when this workflow step completes.
    "; - $("#right-content").find(".toolForm").after( pjastr ); - for (var key in node.post_job_actions){ - if (key != "undefined"){ //To make sure we haven't just deleted it. - display_pja(node.post_job_actions[key], node); - } - } - $("#add_pja").click(function (){ - new_pja($("#new_pja_list").val(),$("#node_data_list").val(), node); - }); - } - $("#right-content").find( "form" ).ajaxForm( { - type: 'POST', - dataType: 'json', - success: function( data ) { - workflow.active_form_has_changes = false; - node.update_field_data( data ); - show_workflow_parameters(); - }, - beforeSubmit: function( data ) { - data.push( { name: 'tool_state', value: node.tool_state } ); - data.push( { name: '_', value: "true" } ); - } - }).each( function() { - var form = this; - $(this).find( "select[refresh_on_change='true']").change( function() { - $(form).submit(); - }); - $(this).find( "input[refresh_on_change='true']").change( function() { - $(form).submit(); - }); - $(this).find( ".popupmenu" ).each( function() { - var id = $(this).parents( "div.form-row" ).attr( 'id' ); - var b = $('▼'); - var options = {}; - $(this).find( "button" ).each( function() { - var name = $(this).attr( 'name' ); - var value = $(this).attr( 'value' ); - options[ $(this).text() ] = function() { - $(form).append( "" ).submit(); - }; - }); - b.insertAfter( this ); - $(this).remove(); - make_popupmenu( b, options ); - }); - // Implements auto-saving based on whether the inputs change. We consider - // "changed" to be when a field is accessed and not necessarily modified - // because of an issue where "onchange" is not triggered when activating - // another node, or saving the workflow. - $(this).find("input,textarea,select").each( function() { - $(this).bind("focus click", function() { - workflow.active_form_has_changes = true; - }); - }); - }); -} - -var close_editor = function() { - workflow.check_changes_in_active_form(); - if ( workflow && workflow.has_changes ) { - do_close = function() { - window.onbeforeunload = undefined; - window.document.location = workflow_index_url; - }; - show_modal( "Close workflow editor", - "There are unsaved changes to your workflow which will be lost.", - { - "Cancel" : hide_modal, - "Save Changes" : function() { - save_current_workflow( null, do_close ); - } - }, { - "Don't Save": do_close - } ); - } else { - window.document.location = workflow_index_url; - } -}; - -var save_current_workflow = function ( eventObj, success_callback ) { - show_message( "Saving workflow", "progress" ); - workflow.check_changes_in_active_form(); - if (!workflow.has_changes) { - hide_modal(); - if ( success_callback ) { - success_callback(); - } - return; - } - workflow.rectify_workflow_outputs(); - var savefn = function(callback) { - $.ajax( { - url: save_workflow_url, - type: "POST", - data: { - id: workflow_id, - workflow_data: function() { return JSON.stringify( workflow.to_simple() ); }, - "_": "true" - }, - dataType: 'json', - success: function( data ) { - var body = $("
    ").text( data.message ); - if ( data.errors ) { - body.addClass( "warningmark" ); - var errlist = $( "
      " ); - $.each( data.errors, function( i, v ) { - $("
    • ").text( v ).appendTo( errlist ); - }); - body.append( errlist ); - } else { - body.addClass( "donemark" ); - } - workflow.name = data.name; - workflow.has_changes = false; - workflow.stored = true; - show_workflow_parameters(); - if ( data.errors ) { - show_modal( "Saving workflow", body, { "Ok" : hide_modal } ); - } else { - if (callback) { - callback(); - } - hide_modal(); - } - } - }); - }; - - // We bind to ajaxStop because of auto-saving, since the form submission ajax - // call needs to be completed so that the new data is saved - if (active_ajax_call) { - $(document).bind('ajaxStop.save_workflow', function() { - $(document).unbind('ajaxStop.save_workflow'); - savefn(); - $(document).unbind('ajaxStop.save_workflow'); // IE7 needs it here - active_ajax_call = false; - }); - } else { - savefn(success_callback); - } -}; +function reset(){workflow&&workflow.remove_all(),workflow=new Workflow($("#canvas-container"))}function scroll_to_nodes(){var a,b,c=$("#canvas-viewport"),d=$("#canvas-container");b=d.width().toolForm:last>.toolFormTitle>.buttons").click(function(){action_to_rem=$(this).closest(".toolForm",".action_tag").children(".action_tag:first").text(),$(this).closest(".toolForm").remove(),delete workflow.active_node.post_job_actions[action_to_rem],workflow.active_form_has_changes=!0})}function display_pja_list(){return pja_list}function display_file_list(a){addlist="",addlist}function new_pja(a,b,c){if(void 0===c.post_job_actions&&(c.post_job_actions={}),void 0===c.post_job_actions[a+b]){var d={};return d.action_type=a,d.output_name=b,c.post_job_actions[a+b]=null,c.post_job_actions[a+b]=d,display_pja(d,c),workflow.active_form_has_changes=!0,!0}return!1}function show_workflow_parameters(){var a=/\$\{.+?\}/g,b=[],c=$("#workflow-parameters-container"),d=$("#workflow-parameters-box"),e="",f=[];$.each(workflow.nodes,function(c,d){var e=d.form_html.match(a);e&&(f=f.concat(e)),d.post_job_actions&&($.each(d.post_job_actions,function(b,c){c.action_arguments&&$.each(c.action_arguments,function(b,c){var d=c.match(a);d&&(f=f.concat(d))})}),f&&$.each(f,function(a,c){-1===$.inArray(c,b)&&b.push(c)}))}),b&&0!==b.length?($.each(b,function(a,b){e+="
      "+b.substring(2,b.length-1)+"
      "}),c.html(e),d.show()):(c.html(e),d.hide())}function show_form_for_tool(a,b){if($(".right-content").hide(),$("#right-content").show().html(a),b&&$("#right-content").find(".toolForm:first").after("

      Edit Step Attributes
      Add an annotation or notes to this step; annotations are available when a workflow is viewed.
      "),b&&"tool"==b.type){pjastr="

      Edit Step Actions
      "+display_pja_list()+"
      "+display_file_list(b)+"
      Create
      ",pjastr+="
      Add actions to this step; actions are applied when this workflow step completes.
      ",$("#right-content").find(".toolForm").after(pjastr);for(var c in b.post_job_actions)"undefined"!=c&&display_pja(b.post_job_actions[c],b);$("#add_pja").click(function(){new_pja($("#new_pja_list").val(),$("#node_data_list").val(),b)})}$("#right-content").find("form").ajaxForm({type:"POST",dataType:"json",success:function(a){workflow.active_form_has_changes=!1,b.update_field_data(a),show_workflow_parameters()},beforeSubmit:function(a){a.push({name:"tool_state",value:b.tool_state}),a.push({name:"_",value:"true"})}}).each(function(){var a=this;$(this).find("select[refresh_on_change='true']").change(function(){$(a).submit()}),$(this).find("input[refresh_on_change='true']").change(function(){$(a).submit()}),$(this).find(".popupmenu").each(function(){var b=$(this).parents("div.form-row").attr("id"),c=$('▼'),d={};$(this).find("button").each(function(){var b=$(this).attr("name"),c=$(this).attr("value");d[$(this).text()]=function(){$(a).append("").submit()}}),c.insertAfter(this),$(this).remove(),make_popupmenu(c,d)}),$(this).find("input,textarea,select").each(function(){$(this).bind("focus click",function(){workflow.active_form_has_changes=!0})})})}$(function(){function a(){workflow.layout(),workflow.fit_canvas_to_nodes(),scroll_to_nodes(),canvas_manager.draw_overview()}function b(){workflow.clear_active_node(),$(".right-content").hide(),$("#edit-attributes").show()}function c(){$.jStorage.set("overview-off",!1),$("#overview-border").css("right","0px"),$("#close-viewport").css("background-position","0px 0px")}function d(){$.jStorage.set("overview-off",!0),$("#overview-border").css("right","20000px"),$("#close-viewport").css("background-position","12px 0px")}if(window.lt_ie_7)return void show_modal("Browser not supported","Sorry, the workflow editor is not supported for IE6 and below.");$("#tool-search-query").click(function(){$(this).focus(),$(this).select()}).keyup(function(){if($(this).css("font-style","normal"),this.value.length<3)reset_tool_search(!1);else if(this.value!=this.lastValue){$(this).addClass("search_active");var a=this.value;this.timer&&clearTimeout(this.timer),$("#search-spinner").show(),this.timer=setTimeout(function(){$.get(tool_search_url,{query:a},function(a){if($("#search-no-results").hide(),$(".toolSectionWrapper").hide(),$(".toolSectionWrapper").find(".toolTitle").hide(),0!=a.length){var b=$.map(a,function(a){return"link-"+a});$(b).each(function(a,b){$("[id='"+b+"']").parent().addClass("search_match"),$("[id='"+b+"']").parent().show().parent().parent().show().parent().show()}),$(".toolPanelLabel").each(function(){for(var a=$(this),b=a.next(),c=!0;0!==b.length&&b.hasClass("toolTitle");){if(b.is(":visible")){c=!1;break}b=b.next()}c&&a.hide()})}else $("#search-no-results").show();$("#search-spinner").hide()},"json")},200)}this.lastValue=this.value}),canvas_manager=new CanvasManager($("#canvas-viewport"),$("#overview")),reset(),$.ajax({url:get_datatypes_url,dataType:"json",cache:!1,success:function(a){populate_datatype_info(a),$.ajax({url:load_workflow_url,data:{id:workflow_id,_:"true"},dataType:"json",cache:!1,success:function(a){reset(),workflow.from_simple(a),workflow.has_changes=!1,workflow.fit_canvas_to_nodes(),scroll_to_nodes(),canvas_manager.draw_overview(),upgrade_message="",$.each(a.upgrade_messages,function(a,b){upgrade_message+="
    • Step "+(parseInt(a,10)+1)+": "+workflow.nodes[a].name+"
        ",$.each(b,function(a,b){upgrade_message+="
      • "+b+"
      • "}),upgrade_message+="
    • "}),upgrade_message?show_modal("Workflow loaded with changes","Problems were encountered loading this workflow (possibly a result of tool upgrades). Please review the following parameters and then save.
        "+upgrade_message+"
      ",{Continue:hide_modal}):hide_modal(),show_workflow_parameters()},beforeSubmit:function(){show_message("Loading workflow","progress")}})}}),$(document).ajaxStart(function(){active_ajax_call=!0,$(document).bind("ajaxStop.global",function(){active_ajax_call=!1})}),$(document).ajaxError(function(a,b){var c=b.responseText||b.statusText||"Could not connect to server";return show_modal("Server error",c,{"Ignore error":hide_modal}),!1}),make_popupmenu($("#workflow-options-button"),{Save:save_current_workflow,Run:function(){window.location=run_workflow_url},"Edit Attributes":b,"Auto Re-layout":a,Close:close_editor}),overview_size=$.jStorage.get("overview-size"),void 0!==overview_size&&$("#overview-border").css({width:overview_size,height:overview_size}),$.jStorage.get("overview-off")?d():c(),$("#overview-border").bind("dragend",function(a,b){var c=$(this).offsetParent(),d=c.offset(),e=Math.max(c.width()-(b.offsetX-d.left),c.height()-(b.offsetY-d.top));$.jStorage.set("overview-size",e+"px")}),$("#close-viewport").click(function(){"0px"===$("#overview-border").css("right")?d():c()}),window.onbeforeunload=function(){return workflow&&workflow.has_changes?"There are unsaved changes to your workflow which will be lost.":void 0},$("div.toolSectionBody").hide(),$("div.toolSectionTitle > span").wrap("");var e=null;$("div.toolSectionTitle").each(function(){var a=$(this).next("div.toolSectionBody");$(this).click(function(){a.is(":hidden")?(e&&e.slideUp("fast"),e=a,a.slideDown("fast")):(a.slideUp("fast"),e=null)})}),async_save_text("workflow-name","workflow-name",rename_async_url,"new_name"),$("#workflow-tag").click(function(){return $(".tag-area").click(),!1}),async_save_text("workflow-annotation","workflow-annotation",annotate_async_url,"new_annotation",25,!0,4)});var close_editor=function(){workflow.check_changes_in_active_form(),workflow&&workflow.has_changes?(do_close=function(){window.onbeforeunload=void 0,window.document.location=workflow_index_url},show_modal("Close workflow editor","There are unsaved changes to your workflow which will be lost.",{Cancel:hide_modal,"Save Changes":function(){save_current_workflow(null,do_close)}},{"Don't Save":do_close})):window.document.location=workflow_index_url},save_current_workflow=function(a,b){if(show_message("Saving workflow","progress"),workflow.check_changes_in_active_form(),!workflow.has_changes)return hide_modal(),void(b&&b());workflow.rectify_workflow_outputs();var c=function(a){$.ajax({url:save_workflow_url,type:"POST",data:{id:workflow_id,workflow_data:function(){return JSON.stringify(workflow.to_simple())},_:"true"},dataType:"json",success:function(b){var c=$("
      ").text(b.message);if(b.errors){c.addClass("warningmark");var d=$("
        ");$.each(b.errors,function(a,b){$("
      • ").text(b).appendTo(d)}),c.append(d)}else c.addClass("donemark");workflow.name=b.name,workflow.has_changes=!1,workflow.stored=!0,show_workflow_parameters(),b.errors?show_modal("Saving workflow",c,{Ok:hide_modal}):(a&&a(),hide_modal())}})};active_ajax_call?$(document).bind("ajaxStop.save_workflow",function(){$(document).unbind("ajaxStop.save_workflow"),c(),$(document).unbind("ajaxStop.save_workflow"),active_ajax_call=!1}):c(b)}; +//# sourceMappingURL=../maps/galaxy.workflows.js.map \ No newline at end of file diff --git a/static/scripts/i18n.js b/static/scripts/i18n.js index 9fa0c2646a7..defe0d2c6d6 100644 --- a/static/scripts/i18n.js +++ b/static/scripts/i18n.js @@ -1,183 +1,2 @@ -/** - * @license RequireJS i18n 2.0.4 Copyright (c) 2010-2012, The Dojo Foundation All Rights Reserved. - * Available via the MIT or new BSD license. - * see: http://github.com/requirejs/i18n for details - */ -/*jslint regexp: true */ -/*global require: false, navigator: false, define: false */ - -/** - * This plugin handles i18n! prefixed modules. It does the following: - * - * 1) A regular module can have a dependency on an i18n bundle, but the regular - * module does not want to specify what locale to load. So it just specifies - * the top-level bundle, like "i18n!nls/colors". - * - * This plugin will load the i18n bundle at nls/colors, see that it is a root/master - * bundle since it does not have a locale in its name. It will then try to find - * the best match locale available in that master bundle, then request all the - * locale pieces for that best match locale. For instance, if the locale is "en-us", - * then the plugin will ask for the "en-us", "en" and "root" bundles to be loaded - * (but only if they are specified on the master bundle). - * - * Once all the bundles for the locale pieces load, then it mixes in all those - * locale pieces into each other, then finally sets the context.defined value - * for the nls/colors bundle to be that mixed in locale. - * - * 2) A regular module specifies a specific locale to load. For instance, - * i18n!nls/fr-fr/colors. In this case, the plugin needs to load the master bundle - * first, at nls/colors, then figure out what the best match locale is for fr-fr, - * since maybe only fr or just root is defined for that locale. Once that best - * fit is found, all of its locale pieces need to have their bundles loaded. - * - * Once all the bundles for the locale pieces load, then it mixes in all those - * locale pieces into each other, then finally sets the context.defined value - * for the nls/fr-fr/colors bundle to be that mixed in locale. - */ -(function () { - 'use strict'; - - //regexp for reconstructing the master bundle name from parts of the regexp match - //nlsRegExp.exec("foo/bar/baz/nls/en-ca/foo") gives: - //["foo/bar/baz/nls/en-ca/foo", "foo/bar/baz/nls/", "/", "/", "en-ca", "foo"] - //nlsRegExp.exec("foo/bar/baz/nls/foo") gives: - //["foo/bar/baz/nls/foo", "foo/bar/baz/nls/", "/", "/", "foo", ""] - //so, if match[5] is blank, it means this is the top bundle definition. - var nlsRegExp = /(^.*(^|\/)nls(\/|$))([^\/]*)\/?([^\/]*)/; - - //Helper function to avoid repeating code. Lots of arguments in the - //desire to stay functional and support RequireJS contexts without having - //to know about the RequireJS contexts. - function addPart(locale, master, needed, toLoad, prefix, suffix) { - if (master[locale]) { - needed.push(locale); - if (master[locale] === true || master[locale] === 1) { - toLoad.push(prefix + locale + '/' + suffix); - } - } - } - - function addIfExists(req, locale, toLoad, prefix, suffix) { - var fullName = prefix + locale + '/' + suffix; - if (require._fileExists(req.toUrl(fullName + '.js'))) { - toLoad.push(fullName); - } - } - - /** - * Simple function to mix in properties from source into target, - * but only if target does not already have a property of the same name. - * This is not robust in IE for transferring methods that match - * Object.prototype names, but the uses of mixin here seem unlikely to - * trigger a problem related to that. - */ - function mixin(target, source, force) { - var prop; - for (prop in source) { - if (source.hasOwnProperty(prop) && (!target.hasOwnProperty(prop) || force)) { - target[prop] = source[prop]; - } else if (typeof source[prop] === 'object') { - if (!target[prop] && source[prop]) { - target[prop] = {}; - } - mixin(target[prop], source[prop], force); - } - } - } - - define(['module'], function (module) { - var masterConfig = module.config ? module.config() : {}; - - return { - version: '2.0.4', - /** - * Called when a dependency needs to be loaded. - */ - load: function (name, req, onLoad, config) { - config = config || {}; - - if (config.locale) { - masterConfig.locale = config.locale; - } - - var masterName, - match = nlsRegExp.exec(name), - prefix = match[1], - locale = match[4], - suffix = match[5], - parts = locale.split("-"), - toLoad = [], - value = {}, - i, part, current = ""; - - //If match[5] is blank, it means this is the top bundle definition, - //so it does not have to be handled. Locale-specific requests - //will have a match[4] value but no match[5] - if (match[5]) { - //locale-specific bundle - prefix = match[1]; - masterName = prefix + suffix; - } else { - //Top-level bundle. - masterName = name; - suffix = match[4]; - locale = masterConfig.locale; - if (!locale) { - locale = masterConfig.locale = - typeof navigator === "undefined" ? "root" : - (navigator.language || - navigator.userLanguage || "root").toLowerCase(); - } - parts = locale.split("-"); - } - - if (config.isBuild) { - //Check for existence of all locale possible files and - //require them if exist. - toLoad.push(masterName); - addIfExists(req, "root", toLoad, prefix, suffix); - for (i = 0; i < parts.length; i++) { - part = parts[i]; - current += (current ? "-" : "") + part; - addIfExists(req, current, toLoad, prefix, suffix); - } - - req(toLoad, function () { - onLoad(); - }); - } else { - //First, fetch the master bundle, it knows what locales are available. - req([masterName], function (master) { - //Figure out the best fit - var needed = [], - part; - - //Always allow for root, then do the rest of the locale parts. - addPart("root", master, needed, toLoad, prefix, suffix); - for (i = 0; i < parts.length; i++) { - part = parts[i]; - current += (current ? "-" : "") + part; - addPart(current, master, needed, toLoad, prefix, suffix); - } - - //Load all the parts missing. - req(toLoad, function () { - var i, partBundle, part; - for (i = needed.length - 1; i > -1 && needed[i]; i--) { - part = needed[i]; - partBundle = master[part]; - if (partBundle === true || partBundle === 1) { - partBundle = req(prefix + part + '/' + suffix); - } - mixin(value, partBundle); - } - - //All done, notify the loader. - onLoad(value); - }); - }); - } - } - }; - }); -}()); +!function(){"use strict";function a(a,b,c,d,e,f){b[a]&&(c.push(a),(b[a]===!0||1===b[a])&&d.push(e+a+"/"+f))}function b(a,b,c,d,e){var f=d+b+"/"+e;require._fileExists(a.toUrl(f+".js"))&&c.push(f)}function c(a,b,d){var e;for(e in b)!b.hasOwnProperty(e)||a.hasOwnProperty(e)&&!d?"object"==typeof b[e]&&(!a[e]&&b[e]&&(a[e]={}),c(a[e],b[e],d)):a[e]=b[e]}var d=/(^.*(^|\/)nls(\/|$))([^\/]*)\/?([^\/]*)/;define(["module"],function(e){var f=e.config?e.config():{};return{version:"2.0.4",load:function(e,g,h,i){i=i||{},i.locale&&(f.locale=i.locale);var j,k,l,m=d.exec(e),n=m[1],o=m[4],p=m[5],q=o.split("-"),r=[],s={},t="";if(m[5]?(n=m[1],j=n+p):(j=e,p=m[4],o=f.locale,o||(o=f.locale="undefined"==typeof navigator?"root":(navigator.language||navigator.userLanguage||"root").toLowerCase()),q=o.split("-")),i.isBuild){for(r.push(j),b(g,"root",r,n,p),k=0;k-1&&e[a];a--)f=e[a],d=b[f],(d===!0||1===d)&&(d=g(n+f+"/"+p)),c(s,d);h(s)})})}}})}(); +//# sourceMappingURL=../maps/i18n.js.map \ No newline at end of file diff --git a/static/scripts/libs/IE/IE7.js b/static/scripts/libs/IE/IE7.js index 13d1ac444fb..3990670d486 100644 --- a/static/scripts/libs/IE/IE7.js +++ b/static/scripts/libs/IE/IE7.js @@ -1,2205 +1,4 @@ -// timestamp: Sun, 03 Feb 2008 19:26:22 -/* - IE7/IE8.js - copyright 2004-2008, Dean Edwards - http://dean.edwards.name/IE7/ - http://www.opensource.org/licenses/mit-license.php -*/ +!function(){function makePath(a,b){return RELATIVE.test(a)&&(a=(b||"")+a),a}function getPath(a,b){return a=makePath(a,b),a.slice(0,a.lastIndexOf("/")+1)}function loadFile(a,b){try{a=makePath(a,b),fileCache[a]||(httpRequest.open("GET",a,!1),httpRequest.send(),(0==httpRequest.status||200==httpRequest.status)&&(fileCache[a]=httpRequest.responseText))}catch(c){}finally{return fileCache[a]||""}}function Base(){}function extend(a,b){if(a&&b){var c,d=("function"==typeof b?Function:Object).prototype,e=_HIDDEN.length;if(prototyping)for(;c=_HIDDEN[--e];){var f=b[c];f!=d[c]&&(_BASE.test(f)?_override(a,c,f):a[c]=f)}for(c in b)if(void 0===d[c]){var f=b[c];a[c]&&"function"==typeof f&&_BASE.test(f)?_override(a,c,f):a[c]=f}}return a}function _override(a,b,c){var d=a[b];a[b]=function(){var a=this.base;this.base=d;var b=c.apply(this,arguments);return this.base=a,b}}function combine(a,b){b||(b=a);var c={};for(var d in a)c[d]=b[d];return c}function format(a){var b=arguments,c=new RegExp("%([1-"+arguments.length+"])","g");return String(a).replace(c,function(a,c){return c1?2:0;var block=cssParser.exec(selectors[i])||"if(0){";_wild&&(block+=format("if(e%1.nodeName!='!'){",_index));var store=_duplicate>1?_TEST:"";block+=format(store+_STORE,_index),block+=Array(match(block,/\{/g).length+1).join("}"),fn+=block}eval(format(_FN,reg)+cssParser.unescape(fn)+"return s?null:r}"),_cache[selector]=_selectorFunction}return _cache[selector](context||document,single)}function fixImage(a){if(PNG.test(a.src)){var b=new Image(a.width,a.height);b.onload=function(){a.width=b.width,a.height=b.height,b=null},b.src=a.src,a.pngSrc=a.src,addFilter(a)}}function addFilter(a,b){var c=a.filters[ALPHA_IMAGE_LOADER];c?(c.src=a.src,c.enabled=!0):(a.runtimeStyle.filter=format(PNG_FILTER,a.src,b||"scale"),filtered.push(a)),a.src=BLANK_GIF}function removeFilter(a){a.src=a.pngSrc,a.filters[ALPHA_IMAGE_LOADER].enabled=!1}function ie7Quirks(){function a(a){var b=1;for(j.style.fontFamily=a.currentStyle.fontFamily,j.style.lineHeight=a.currentStyle.lineHeight;a!=body;){var c=a.currentStyle["ie7-font-size"];if(c)if(h.test(c))b*=parseFloat(c);else if(PERCENT.test(c))b*=parseFloat(c)/100;else{if(!i.test(c))return j.style.fontSize=c,1;b*=parseFloat(c)/2}a=a.parentElement}return b}function b(a){5.5>appVersion&&IE7.Layout.boxSizing(a.parentElement);var b=a.parentElement,d=b.offsetWidth-a.offsetWidth-c(b),e=a.currentStyle["ie7-margin"]&&"auto"==a.currentStyle.marginRight||"auto"==a.currentStyle["ie7-margin-right"];switch(b.currentStyle.textAlign){case"right":d=e?parseInt(d/2):0,a.runtimeStyle.marginRight=d+"px";break;case"center":e&&(d=0);default:e&&(d/=2),a.runtimeStyle.marginLeft=parseInt(d)+"px"}}function c(a){return getPixelValue(a,a.currentStyle.paddingLeft)+getPixelValue(a,a.currentStyle.paddingRight)}for(var d="xx-small,x-small,small,medium,large,x-large,xx-large".split(","),e=0;eappVersion){var f=/^\-/,g=/(em|ex)$/i,h=/em$/i,i=/ex$/i;getPixelValue=function(b,c){if(PIXEL.test(c))return parseInt(c)||0;var d=f.test(c)?-1:1;return g.test(c)&&(d*=a(b)),j.style.width=0>d?c.slice(1):c,body.appendChild(j),c=d*j.offsetWidth,j.removeNode(),parseInt(c)};var j=createTempElement();IE7.CSS.addFix(/cursor\s*:\s*pointer/,"cursor:hand"),IE7.CSS.addFix(/display\s*:\s*list-item/,"display:block")}IE7.CSS.addRecalc("margin(-left|-right)?","[^};]*auto",function(a){register(b,a,a.parentElement&&"block"==a.currentStyle.display&&"auto"==a.currentStyle.marginLeft&&"absolute"!=a.currentStyle.position)&&b(a)}),addResize(function(){for(var a in b.elements){var c=b.elements[a];c.runtimeStyle.marginLeft=c.runtimeStyle.marginRight="",b(c)}})}IE7={toString:function(){return"IE7 version 2.0 (beta3)"}};var appVersion=IE7.appVersion=navigator.appVersion.match(/MSIE (\d\.\d)/)[1];if(!(/ie7_off/.test(top.location.search)||5>appVersion)){var Undefined=K(),quirksMode="CSS1Compat"!=document.compatMode,documentElement=document.documentElement,body,viewport,ANON="!",HEADER=":link{ie7-link:link}:visited{ie7-link:visited}",RELATIVE=/^[\w\.]+[^:]*$/,script=document.scripts[document.scripts.length-1],path=getPath(script.src);try{var httpRequest=new ActiveXObject("Microsoft.XMLHTTP")}catch(e){}var fileCache={};if(5.5>appVersion){void 0=Undefined(),ANON="HTML:!";var GLOBAL=/(g|gi)$/,_String_replace=String.prototype.replace;String.prototype.replace=function(a,b){if("function"==typeof b){if(a&&a.constructor==RegExp){var c=a,d=c.global;null==d&&(d=GLOBAL.test(c)),d&&(c=new RegExp(c.source))}else c=new RegExp(rescape(a));for(var e,f=this,g="";f&&(e=c.exec(f))&&(g+=f.slice(0,e.index)+b.apply(this,e),f=f.slice(e.index+e[0].length),d););return g+f}return _String_replace.apply(this,arguments)},Array.prototype.pop=function(){if(this.length){var a=this[this.length-1];return this.length--,a}return void 0},Array.prototype.push=function(){for(var a=0;a":"","\\/\\*[^*]*\\*+([^\\/][^*]*\\*+)*\\/":"","@(namespace|import)[^;\\n]+[;\\n]":"","'(\\\\.|[^'\\\\])*'":encodeString,'"(\\\\.|[^"\\\\])*"':encodeString,"\\s+":" "}),rotater=new RegGrp({Width:"Height",width:"height",Left:"Top",left:"top",Right:"Bottom",right:"bottom",onX:"onY"}),eventHandlers=[];addEventHandler(window,"onunload",function(){for(var a;a=eventHandlers.pop();)removeEventHandler(a[0],a[1],a[2])}),addEventHandler(window,"onbeforeprint",function(){IE7.CSS.print||new StyleSheet("print"),IE7.CSS.print.recalc()});var PIXEL=/^\d+(px)?$/i,PERCENT=/^\d+%$/,getPixelValue=function(a,b){if(PIXEL.test(b))return parseInt(b);var c=a.style.left,d=a.runtimeStyle.left;return a.runtimeStyle.left=a.currentStyle.left,a.style.left=b||0,b=a.style.pixelLeft,a.style.left=c,a.runtimeStyle.left=d,b},$IE7="ie7-",Fix=Base.extend({constructor:function(){this.fixes=[],this.recalcs=[]},init:Undefined}),recalcs=[];IE7.recalc=function(){IE7.HTML.recalc(),IE7.CSS.recalc();for(var a=0;aappVersion,_EVALUATED=/^(href|src)$/,_ATTRIBUTES={"class":"className","for":"htmlFor"};IE7._indexed=1,IE7._byId=function(a,b){var c=a.all[b]||null;if(!c||c.id==b)return c;for(var d=0;d+~,]|[^(]\+|^)([#.:\[])/g,IMPLIED_SPACE=/(^|,)([^\s>+~])/g,WHITESPACE=/\s*([\s>+~(),]|^|$)\s*/g,WILD_CARD=/\s\*\s/g,CSSParser=RegGrp.extend({constructor:function(a){this.base(a),this.sorter=new RegGrp,this.sorter.add(/:not\([^)]*\)/,RegGrp.IGNORE),this.sorter.add(/([ >](\*|[\w-]+))([^: >+~]*)(:\w+-child(\([^)]+\))?)([^: >+~]*)/,"$1$3$6$4")},ignoreCase:!0,escape:function(a){return this.optimise(this.format(a))},format:function(a){return a.replace(WHITESPACE,"$1").replace(IMPLIED_SPACE,"$1 $2").replace(IMPLIED_ASTERISK,"$1*$2")},optimise:function(a){return this.sorter.exec(a.replace(WILD_CARD,">* "))},unescape:function(a){return decode(a)}}),_OPERATORS={"":"%1!=null","=":"%1=='%2'","~=":/(^| )%1( |$)/,"|=":/^%1(-|$)/,"^=":/^%1/,"$=":/%1$/,"*=":/%1/},_PSEUDO_CLASSES={"first-child":"!IE7._getPreviousElementSibling(e%1)",link:"e%1.currentStyle['ie7-link']=='link'",visited:"e%1.currentStyle['ie7-link']=='visited'"},_VAR="var p%2=0,i%2,e%2,n%2=e%1.",_ID="e%1.sourceIndex",_TEST="var g="+_ID+";if(!p[g]){p[g]=1;",_STORE="r[r.length]=e%1;if(s)return e%1;",_FN="var _selectorFunction=function(e0,s){IE7._indexed++;var r=[],p={},reg=[%1],d=document;",reg,_index,_wild,_list,_duplicate,_cache={},cssParser=new CSSParser({" (\\*|[\\w-]+)#([\\w-]+)":function(a,b,c){_wild=!1;var d="var e%2=IE7._byId(d,'%4');if(e%2&&";return"*"!=b&&(d+="e%2.nodeName=='%3'&&"),d+="(e%1==d||e%1.contains(e%2))){",_list&&(d+=format("i%1=n%1.length;",_list)),format(d,_index++,_index,b.toUpperCase(),c)}," (\\*|[\\w-]+)":function(a,b){_duplicate++,_wild="*"==b;var c=_VAR;return c+=_wild&&_MSIE5?"all":"getElementsByTagName('%3')",c+=";for(i%2=0;(e%2=n%2[i%2]);i%2++){",format(c,_index++,_list=_index,b.toUpperCase())},">(\\*|[\\w-]+)":function(a,b){var c=_list;_wild="*"==b;var d=_VAR;return d+=c?"children":"childNodes",!_wild&&c&&(d+=".tags('%3')"),d+=";for(i%2=0;(e%2=n%2[i%2]);i%2++){",_wild?(d+="if(e%2.nodeType==1){",_wild=_MSIE5):c||(d+="if(e%2.nodeName=='%3'){"),format(d,_index++,_list=_index,b.toUpperCase())},"\\+(\\*|[\\w-]+)":function(a,b){var c="";return _wild&&(c+="if(e%1.nodeName!='!'){"),_wild=!1,c+="e%1=IE7._getNextElementSibling(e%1);if(e%1","*"!=b&&(c+="&&e%1.nodeName=='%2'"),c+="){",format(c,_index,b.toUpperCase())},"~(\\*|[\\w-]+)":function(a,b){var c="";return _wild&&(c+="if(e%1.nodeName!='!'){"),_wild=!1,_duplicate=2,c+="while(e%1=e%1.nextSibling){if(e%1.ie7_adjacent==IE7._indexed)break;if(","*"==b?(c+="e%1.nodeType==1",_MSIE5&&(c+="&&e%1.nodeName!='!'")):c+="e%1.nodeName=='%2'",c+="){e%1.ie7_adjacent=IE7._indexed;",format(c,_index,b.toUpperCase())},"#([\\w-]+)":function(a,b){_wild=!1;var c="if(e%1.id=='%2'){";return _list&&(c+=format("i%1=n%1.length;",_list)),format(c,_index,b)},"\\.([\\w-]+)":function(a,b){return _wild=!1,reg.push(new RegExp("(^|\\s)"+rescape(b)+"(\\s|$)")),format("if(e%1.className&®[%2].test(e%1.className)){",_index,reg.length-1)},"\\[([\\w-]+)\\s*([^=]?=)?\\s*([^\\]]*)\\]":function(a,b,c,d){var e=_ATTRIBUTES[b]||b;if(c){var f="e%1.getAttribute('%2',2)";_EVALUATED.test(b)||(f="e%1.%3||"+f),b=format("("+f+")",_index,b,e)}else b=format("IE7._getAttribute(e%1,'%2')",_index,b);var g=_OPERATORS[c||""]||"0";return g&&g.source&&(reg.push(new RegExp(format(g.source,rescape(cssParser.unescape(d))))),g="reg[%2].test(%1)",d=reg.length-1),"if("+format(g,b,d)+"){"},":+([\\w-]+)(\\(([^)]+)\\))?":function(a,b,c,d){return b=_PSEUDO_CLASSES[b],"if("+(b?format(b,_index,d||""):"0")+"){"}}),HYPERLINK=/a(#[\w-]+)?(\.[\w-]+)?:(hover|active)/i,BRACE1=/\s*\{\s*/,BRACE2=/\s*\}\s*/,COMMA=/\s*\,\s*/,FIRST_LINE_LETTER=/(.*)(:first-(line|letter))/,styleSheets=document.styleSheets;IE7.CSS=new(Fix.extend({parser:new Parser,screen:"",print:"",styles:[],rules:[],pseudoClasses:7>appVersion?"first\\-child":"",dynamicPseudoClasses:{toString:function(){var a=[];for(var b in this)a.push(b);return a.join("|")}},init:function(){var a="^$",b="\\[class=?[^\\]]*\\]",c=[];this.pseudoClasses&&c.push(this.pseudoClasses);var d=this.dynamicPseudoClasses.toString();d&&c.push(d),c=c.join("|");var e=7>appVersion?["[>+~[(]|([:.])\\w+\\1"]:[b];c&&e.push(":("+c+")"),this.UNKNOWN=new RegExp(e.join("|")||a,"i");var f=7>appVersion?["\\[[^\\]]+\\]|[^\\s(\\[]+\\s*[+~]"]:[b],g=f.concat();c&&g.push(":("+c+")"),Rule.COMPLEX=new RegExp(g.join("|")||a,"ig"),this.pseudoClasses&&f.push(":("+this.pseudoClasses+")"),DynamicRule.COMPLEX=new RegExp(f.join("|")||a,"i"),DynamicRule.MATCH=new RegExp(d?"(.*):("+d+")(.*)":a,"i"),this.createStyleSheet(),this.refresh()},addEventHandler:function(){addEventHandler.apply(null,arguments)},addFix:function(a,b){this.parser.add(a,b)},addRecalc:function(a,b,c,d){b=new RegExp("([{;\\s])"+a+"\\s*:\\s*"+b+"[^;}]*");var e=this.recalcs.length;return d&&(d=a+":"+d),this.addFix(b,function(a,b){return(d?b+d:a)+";ie7-"+a.slice(1)+";ie7_recalc"+e+":1"}),this.recalcs.push(arguments),e},apply:function(){this.getInlineStyles(),new StyleSheet("screen"),this.trash()},createStyleSheet:function(){this.styleSheet=document.createStyleSheet(),this.styleSheet.ie7=!0,this.styleSheet.owningElement.ie7=!0,this.styleSheet.cssText=HEADER},getInlineStyles:function(){for(var a,b=document.getElementsByTagName("style"),c=b.length-1;a=b[c];c--)a.disabled||a.ie7||this.styles.push(a.innerHTML)},getText:function(a,b){try{var c=a.cssText}catch(d){c=""}return httpRequest&&(c=loadFile(a.href,b)||c),c},recalc:function(){this.screen.recalc();var a,b,c,d,e,f,g,h,i,j=/ie7_recalc\d+/g,k=HEADER.match(/[{,]/g).length,l=k+(this.screen.cssText.match(/\{/g)||"").length,m=this.styleSheet.rules;for(f=k;l>f;f++){a=m[f];var n=a.style.cssText;if(a&&(b=n.match(j))&&(d=cssQuery(a.selectorText),d.length))for(g=0;gi)for(var k=0;kappVersion&&(b=b.replace(Rule.MULTI,""));for(var c=match(b,Rule.TAGS).length-match(a,Rule.TAGS).length,d=match(b,Rule.CLASSES).length-match(a,Rule.CLASSES).length+1;d>0&&Rule.CLASS.test(b);)b=b.replace(Rule.CLASS,""),d--;for(;c>0&&Rule.TAG.test(b);)b=b.replace(Rule.TAG,"$1*"),c--;b+="."+this.className,d=Math.min(d,2),c=Math.min(c,2);var e=-10*d-c;return e>0&&(b=b+","+Rule.MAP[e]+" "+b),b},remove:function(a){a.className=a.className.replace(this.MATCH,"$1")},toString:function(){return format("%1 {%2}",this.selectorText,this.cssText)}},{CHILD:/>/g,CLASS:/\.[\w-]+/,CLASSES:/[.:\[]/g,MULTI:/(\.[\w-]+)+/g,PREFIX:"ie7_class",TAG:/^\w+|([\s>+~])\w+/,TAGS:/^\w|[\s>+~]\w/g,MAP:{1:"html",2:"html body",10:".ie7_html",11:"html.ie7_html",12:"html.ie7_html body",20:".ie7_html .ie7_body",21:"html.ie7_html .ie7_body",22:"html.ie7_html body.ie7_body"}}),DynamicRule=Rule.extend({constructor:function(a,b,c,d,e){this.attach=b||"*",this.dynamicPseudoClass=IE7.CSS.dynamicPseudoClasses[c],this.target=d,this.base(a,e)},recalc:function(){for(var a,b=cssQuery(this.attach),c=0;a=b[c];c++){var d=this.target?cssQuery(this.target,a):[a];d.length&&this.dynamicPseudoClass.apply(a,d,this)}}}),DynamicPseudoClass=Base.extend({constructor:function(a,b){this.name=a,this.apply=b,this.instances={},IE7.CSS.dynamicPseudoClasses[a]=this},register:function(a){var b=a[2];if(a.id=b.id+a[0].uniqueID,!this.instances[a.id]){var c,d=a[1];for(c=0;cappVersion){var Hover=new DynamicPseudoClass("hover",function(a){var b=arguments;IE7.CSS.addEventHandler(a,5.5>appVersion?"onmouseover":"onmouseenter",function(){Hover.register(b)}),IE7.CSS.addEventHandler(a,5.5>appVersion?"onmouseout":"onmouseleave",function(){Hover.unregister(b)})});addEventHandler(document,"onmouseup",function(){var a=Hover.instances;for(var b in a)a[b][0].contains(event.srcElement)||Hover.unregister(a[b])})}IE7.CSS.addRecalc("[\\w-]+","inherit",function(a,b){for(var c=b.match(/[\w-]+\s*:\s*inherit/g),d=0;dappVersion&&(document.createElement("abbr"),IE7.HTML.addRecalc("label",function(a){if(!a.htmlFor){var b=cssQuery("input,textarea",a,!0);b&&addEventHandler(a,"onclick",function(){b.click()})}}));var NUMERIC="[.\\d]";!new function(_){function collapseMargins(a){a!=viewport&&"absolute"!=a.currentStyle.position&&(collapseMargin(a,"marginTop"),collapseMargin(a,"marginBottom"))}function collapseMargin(a,b){if(!a.runtimeStyle[b]){var c=a.parentElement;if(c&&IE7.hasLayout(c)&&!IE7["marginTop"==b?"_getPreviousElementSibling":"_getNextElementSibling"](a))return;var d=cssQuery(">*:"+("marginTop"==b?"first":"last")+"-child",a,!0);d&&"none"==d.currentStyle.styleFloat&&IE7.hasLayout(d)&&(collapseMargin(d,b),margin=_getMargin(a,a.currentStyle[b]),childMargin=_getMargin(d,d.currentStyle[b]),a.runtimeStyle[b]=margin<0||childMargin<0?margin+childMargin:Math.max(childMargin,margin),d.runtimeStyle[b]="0px")}}function _getMargin(a,b){return"auto"==b?0:getPixelValue(a,b)}var layout=IE7.Layout=this;HEADER+="*{boxSizing:content-box}",IE7.hasLayout=5.5>appVersion?function(a){return a.clientWidth}:function(a){return a.currentStyle.hasLayout},layout.boxSizing=function(a){IE7.hasLayout(a)||(a.style.height="0cm","auto"==a.currentStyle.verticalAlign&&(a.runtimeStyle.verticalAlign="top"),collapseMargins(a))};var UNIT=/^[.\d][\w%]*$/,AUTO=/^(auto|0cm)$/,applyWidth,applyHeight;IE7.Layout.borderBox=function(a){applyWidth(a),applyHeight(a)};var fixWidth=function(HEIGHT){function fixWidth(a,b){a.runtimeStyle.fixedWidth||(b||(b=a.currentStyle.width),a.runtimeStyle.fixedWidth=UNIT.test(b)?Math.max(0,getFixedWidth(a,b)):b,setOverrideStyle(a,"width",a.runtimeStyle.fixedWidth))}function layoutWidth(a){if(!isFixed(a))for(var b=a.offsetParent;b&&!IE7.hasLayout(b);)b=b.offsetParent;return(b||viewport).clientWidth}function getPixelWidth(a,b){return PERCENT.test(b)?parseInt(parseFloat(b)/100*layoutWidth(a)):getPixelValue(a,b)}function getBorderWidth(a){return a.offsetWidth-a.clientWidth}function getWidth(a,b){return getPixelWidth(a,a.currentStyle[b+"Left"])+getPixelWidth(a,a.currentStyle[b+"Right"])}function resizeWidth(a){var b=a.getBoundingClientRect(),c=b.right-b.left;a.runtimeStyle.width="none"!=a.currentStyle.minWidth&&c<=getFixedWidth(a,a.currentStyle.minWidth)?a.currentStyle.minWidth:"none"!=a.currentStyle.maxWidth&&c>=getFixedWidth(a,a.currentStyle.maxWidth)?a.currentStyle.maxWidth:a.runtimeStyle.fixedWidth}function fixRight(a){register(fixRight,a,/^(fixed|absolute)$/.test(a.currentStyle.position)&&"auto"!=getDefinedStyle(a,"left")&&"auto"!=getDefinedStyle(a,"right")&&AUTO.test(getDefinedStyle(a,"width")))&&(resizeRight(a),IE7.Layout.boxSizing(a))}function resizeRight(a){var b=getPixelWidth(a,a.runtimeStyle._left||a.currentStyle.left),c=layoutWidth(a)-getPixelWidth(a,a.currentStyle.right)-b-getWidth(a,"margin");parseInt(a.runtimeStyle.width)!=c&&(a.runtimeStyle.width="",(isFixed(a)||HEIGHT||a.offsetWidthc&&(c=0),a.runtimeStyle.fixedWidth=c,setOverrideStyle(a,"width",c)))}applyWidth=function(a){PERCENT.test(a.currentStyle.width)||fixWidth(a),collapseMargins(a)};var getFixedWidth=function(a,b){var c="border-box"==a.currentStyle["box-sizing"],d=0;return quirksMode&&!c?d+=getBorderWidth(a)+getWidth(a,"padding"):!quirksMode&&c&&(d-=getBorderWidth(a)+getWidth(a,"padding")),getPixelWidth(a,b)+d};HEADER+="*{minWidth:none;maxWidth:none;min-width:none;max-width:none}",layout.minWidth=function(a){null!=a.currentStyle["min-width"]&&(a.style.minWidth=a.currentStyle["min-width"]),register(arguments.callee,a,"none"!=a.currentStyle.minWidth)&&(layout.boxSizing(a),fixWidth(a),resizeWidth(a))},eval("IE7.Layout.maxWidth="+String(layout.minWidth).replace(/min/g,"max")),IE7.Layout.fixRight=fixRight;var clientWidth=0;addResize(function(){if(viewport){var a,b=clientWidthappVersion&&(IE7.CSS.addRecalc("min-width",NUMERIC,layout.minWidth),IE7.CSS.addRecalc("max-width",NUMERIC,layout.maxWidth),IE7.CSS.addRecalc("right",NUMERIC,fixRight))};eval("var fixHeight="+rotate(fixWidth)),fixWidth(),fixHeight(!0)};var BLANK_GIF=makePath("blank.gif",path),ALPHA_IMAGE_LOADER="DXImageTransform.Microsoft.AlphaImageLoader",PNG_FILTER="progid:"+ALPHA_IMAGE_LOADER+"(src='%1',sizingMethod='%2')",PNG,filtered=[];if(appVersion>=5.5&&7>appVersion){IE7.CSS.addFix(/background(-image)?\s*:\s*([^};]*)?url\(([^\)]+)\)([^;}]*)?/,function(a,b,c,d,e){return d=getString(d),PNG.test(d)?"filter:"+format(PNG_FILTER,d,"crop")+";zoom:1;background"+(b||"")+":"+(c||"")+"none"+(e||""):a}),IE7.HTML.addRecalc("img,input",function(a){("INPUT"!=a.tagName||"image"==a.type)&&(fixImage(a),addEventHandler(a,"onpropertychange",function(){printing||"src"!=event.propertyName||-1!=a.src.indexOf(BLANK_GIF)||fixImage(a)}))});var printing=!1;addEventHandler(window,"onbeforeprint",function(){printing=!0;for(var a=0;a=0)return a.runtimeStyle.borderRightWidth="0px",d=Math.max(getPixelValue(a,a.currentStyle.width)-d,0),setOverrideStyle(a,"width",d),d}}function positionLeft(a,b){!b&&PERCENT.test(a.currentStyle.width)&&(a.runtimeStyle.fixWidth=a.currentStyle.width),a.runtimeStyle.fixWidth&&(a.runtimeStyle.width=getPixelWidth(a,a.runtimeStyle.fixWidth)),a.runtimeStyle.shiftLeft=0,a.runtimeStyle._left=a.currentStyle.left,a.runtimeStyle.autoLeft="auto"!=a.currentStyle.right&&"auto"==a.currentStyle.left,a.runtimeStyle.left="",a.runtimeStyle.screenLeft=getScreenLeft(a),a.runtimeStyle.pixelLeft=a.runtimeStyle.screenLeft,b||_isFixed(a.offsetParent)||_setExpression(a,"pixelLeft","runtimeStyle.screenLeft+runtimeStyle.shiftLeft+document."+$viewport+".scrollLeft"); -/* W3C compliance for Microsoft Internet Explorer */ - -/* credits/thanks: - Shaggy, Martijn Wargers, Jimmy Cerra, Mark D Anderson, - Lars Dieckow, Erik Arvidsson, Gellért Gyuris, James Denny, - Unknown W Brackets, Benjamin Westfarer, Rob Eberhardt, - Bill Edney, Kevin Newman, James Crompton, Matthew Mastracci, - Doug Wright, Richard York, Kenneth Kolano, MegaZone, - Thomas Verelst, Mark 'Tarquin' Wilton-Jones, Rainer Åhlfors, - David Zulaica, Ken Kolano, Kevin Newman -*/ - -// ======================================================================= -// TO DO -// ======================================================================= - -// PNG - unclickable content - -// ======================================================================= -// TEST/BUGGY -// ======================================================================= - -// hr{margin:1em auto} (doesn't look right in IE5) - -(function() { - -IE7 = { - toString: function(){return "IE7 version 2.0 (beta3)"} -}; -var appVersion = IE7.appVersion = navigator.appVersion.match(/MSIE (\d\.\d)/)[1]; - -if (/ie7_off/.test(top.location.search) || appVersion < 5) return; - -var Undefined = K(); -var quirksMode = document.compatMode != "CSS1Compat"; -var documentElement = document.documentElement, body, viewport; -var ANON = "!"; -var HEADER = ":link{ie7-link:link}:visited{ie7-link:visited}"; - -// ----------------------------------------------------------------------- -// external -// ----------------------------------------------------------------------- - -var RELATIVE = /^[\w\.]+[^:]*$/; -function makePath(href, path) { - if (RELATIVE.test(href)) href = (path || "") + href; - return href; -}; - -function getPath(href, path) { - href = makePath(href, path); - return href.slice(0, href.lastIndexOf("/") + 1); -}; - -// get the path to this script -var script = document.scripts[document.scripts.length - 1]; -var path = getPath(script.src); - -// we'll use microsoft's http request object to load external files -try { - var httpRequest = new ActiveXObject("Microsoft.XMLHTTP"); -} catch (e) { - // ActiveX disabled -} - -var fileCache = {}; -function loadFile(href, path) { -try { - href = makePath(href, path); - if (!fileCache[href]) { - // easy to load a file huh? - httpRequest.open("GET", href, false); - httpRequest.send(); - if (httpRequest.status == 0 || httpRequest.status == 200) { - fileCache[href] = httpRequest.responseText; - } - } -} catch (e) { - // ignore errors -} finally { - return fileCache[href] || ""; -}}; - -// ----------------------------------------------------------------------- -// IE5.0 compatibility -// ----------------------------------------------------------------------- - - -if (appVersion < 5.5) { - undefined = Undefined(); - - ANON = "HTML:!"; // for anonymous content - - // Fix String.replace (Safari1.x/IE5.0). - var GLOBAL = /(g|gi)$/; - var _String_replace = String.prototype.replace; - String.prototype.replace = function(expression, replacement) { - if (typeof replacement == "function") { // Safari doesn't like functions - if (expression && expression.constructor == RegExp) { - var regexp = expression; - var global = regexp.global; - if (global == null) global = GLOBAL.test(regexp); - // we have to convert global RexpExps for exec() to work consistently - if (global) regexp = new RegExp(regexp.source); // non-global - } else { - regexp = new RegExp(rescape(expression)); - } - var match, string = this, result = ""; - while (string && (match = regexp.exec(string))) { - result += string.slice(0, match.index) + replacement.apply(this, match); - string = string.slice(match.index + match[0].length); - if (!global) break; - } - return result + string; - } - return _String_replace.apply(this, arguments); - }; - - Array.prototype.pop = function() { - if (this.length) { - var i = this[this.length - 1]; - this.length--; - return i; - } - return undefined; - }; - - Array.prototype.push = function() { - for (var i = 0; i < arguments.length; i++) { - this[this.length] = arguments[i]; - } - return this.length; - }; - - var ns = this; - Function.prototype.apply = function(o, a) { - if (o === undefined) o = ns; - else if (o == null) o = window; - else if (typeof o == "string") o = new String(o); - else if (typeof o == "number") o = new Number(o); - else if (typeof o == "boolean") o = new Boolean(o); - if (arguments.length == 1) a = []; - else if (a[0] && a[0].writeln) a[0] = a[0].documentElement.document || a[0]; - var $ = "#ie7_apply", r; - o[$] = this; - switch (a.length) { // unroll for speed - case 0: r = o[$](); break; - case 1: r = o[$](a[0]); break; - case 2: r = o[$](a[0],a[1]); break; - case 3: r = o[$](a[0],a[1],a[2]); break; - case 4: r = o[$](a[0],a[1],a[2],a[3]); break; - case 5: r = o[$](a[0],a[1],a[2],a[3],a[4]); break; - default: - var b = [], i = a.length - 1; - do b[i] = "a[" + i + "]"; while (i--); - eval("r=o[$](" + b + ")"); - } - if (typeof o.valueOf == "function") { // not a COM object - delete o[$]; - } else { - o[$] = undefined; - if (r && r.writeln) r = r.documentElement.document || r; - } - return r; - }; - - Function.prototype.call = function(o) { - return this.apply(o, _slice.apply(arguments, [1])); - }; - - // block elements are "inline" according to IE5.0 so we'll fix it - HEADER += "address,blockquote,body,dd,div,dt,fieldset,form,"+ - "frame,frameset,h1,h2,h3,h4,h5,h6,iframe,noframes,object,p,"+ - "hr,applet,center,dir,menu,pre,dl,li,ol,ul{display:block}"; -} - -// ----------------------------------------------------------------------- -// OO support -// ----------------------------------------------------------------------- - - -// This is a cut-down version of base2 (http://code.google.com/p/base2/) - -var _slice = Array.prototype.slice; - -// private -var _FORMAT = /%([1-9])/g; -var _LTRIM = /^\s\s*/; -var _RTRIM = /\s\s*$/; -var _RESCAPE = /([\/()[\]{}|*+-.,^$?\\])/g; // safe regular expressions -var _BASE = /\bbase\b/; -var _HIDDEN = ["constructor", "toString"]; // only override these when prototyping - -var prototyping; - -function Base(){}; -Base.extend = function(_instance, _static) { - // Build the prototype. - prototyping = true; - var _prototype = new this; - extend(_prototype, _instance); - prototyping = false; - - // Create the wrapper for the constructor function. - var _constructor = _prototype.constructor; - function klass() { - // Don't call the constructor function when prototyping. - if (!prototyping) _constructor.apply(this, arguments); - }; - _prototype.constructor = klass; - - // Build the static interface. - klass.extend = arguments.callee; - extend(klass, _static); - klass.prototype = _prototype; - return klass; -}; -Base.prototype.extend = function(source) { - return extend(this, source); -}; - -// A collection of regular expressions and their associated replacement values. -// A Base class for creating parsers. - -var _HASH = "#"; -var _KEYS = "~"; - -var _RG_ESCAPE_CHARS = /\\./g; -var _RG_ESCAPE_BRACKETS = /\(\?[:=!]|\[[^\]]+\]/g; -var _RG_BRACKETS = /\(/g; - -var RegGrp = Base.extend({ - constructor: function(values) { - this[_KEYS] = []; - this.merge(values); - }, - - exec: function(string) { - var items = this, keys = this[_KEYS]; - return String(string).replace(new RegExp(this, this.ignoreCase ? "gi" : "g"), function() { - var item, offset = 1, i = 0; - // Loop through the RegGrp items. - while ((item = items[_HASH + keys[i++]])) { - var next = offset + item.length + 1; - if (arguments[offset]) { // do we have a result? - var replacement = item.replacement; - switch (typeof replacement) { - case "function": - return replacement.apply(items, _slice.call(arguments, offset, next)); - case "number": - return arguments[offset + replacement]; - default: - return replacement; - } - } - offset = next; - } - }); - }, - - add: function(expression, replacement) { - if (expression instanceof RegExp) { - expression = expression.source; - } - if (!this[_HASH + expression]) this[_KEYS].push(String(expression)); - this[_HASH + expression] = new RegGrp.Item(expression, replacement); - }, - - merge: function(values) { - for (var i in values) this.add(i, values[i]); - }, - - toString: function() { - // back references not supported in simple RegGrp - return "(" + this[_KEYS].join(")|(") + ")"; - } -}, { - IGNORE: "$0", - - Item: Base.extend({ - constructor: function(expression, replacement) { - expression = expression instanceof RegExp ? expression.source : String(expression); - - if (typeof replacement == "number") replacement = String(replacement); - else if (replacement == null) replacement = ""; - - // does the pattern use sub-expressions? - if (typeof replacement == "string" && /\$(\d+)/.test(replacement)) { - // a simple lookup? (e.g. "$2") - if (/^\$\d+$/.test(replacement)) { - // store the index (used for fast retrieval of matched strings) - replacement = parseInt(replacement.slice(1)); - } else { // a complicated lookup (e.g. "Hello $2 $1") - // build a function to do the lookup - var Q = /'/.test(replacement.replace(/\\./g, "")) ? '"' : "'"; - replacement = replacement.replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\$(\d+)/g, Q + - "+(arguments[$1]||" + Q+Q + ")+" + Q); - replacement = new Function("return " + Q + replacement.replace(/(['"])\1\+(.*)\+\1\1$/, "$1") + Q); - } - } - - this.length = RegGrp.count(expression); - this.replacement = replacement; - this.toString = K(expression); - } - }), - - count: function(expression) { - // Count the number of sub-expressions in a RegExp/RegGrp.Item. - expression = String(expression).replace(_RG_ESCAPE_CHARS, "").replace(_RG_ESCAPE_BRACKETS, ""); - return match(expression, _RG_BRACKETS).length; - } -}); - -// ========================================================================= -// lang/extend.js -// ========================================================================= - -function extend(object, source) { // or extend(object, key, value) - if (object && source) { - var proto = (typeof source == "function" ? Function : Object).prototype; - // Add constructor, toString etc - var i = _HIDDEN.length, key; - if (prototyping) while (key = _HIDDEN[--i]) { - var value = source[key]; - if (value != proto[key]) { - if (_BASE.test(value)) { - _override(object, key, value) - } else { - object[key] = value; - } - } - } - // Copy each of the source object's properties to the target object. - for (key in source) if (proto[key] === undefined) { - var value = source[key]; - // Check for method overriding. - if (object[key] && typeof value == "function" && _BASE.test(value)) { - _override(object, key, value); - } else { - object[key] = value; - } - } - } - return object; -}; - -function _override(object, name, method) { - // Override an existing method. - var ancestor = object[name]; - object[name] = function() { - var previous = this.base; - this.base = ancestor; - var returnValue = method.apply(this, arguments); - this.base = previous; - return returnValue; - }; -}; - -function combine(keys, values) { - // Combine two arrays to make a hash. - if (!values) values = keys; - var hash = {}; - for (var i in keys) hash[i] = values[i]; - return hash; -}; - -function format(string) { - // Replace %n with arguments[n]. - // e.g. format("%1 %2%3 %2a %1%3", "she", "se", "lls"); - // ==> "she sells sea shells" - // Only %1 - %9 supported. - var args = arguments; - var _FORMAT = new RegExp("%([1-" + arguments.length + "])", "g"); - return String(string).replace(_FORMAT, function(match, index) { - return index < args.length ? args[index] : match; - }); -}; - -function match(string, expression) { - // Same as String.match() except that this function will return an empty - // array if there is no match. - return String(string).match(expression) || []; -}; - -function rescape(string) { - // Make a string safe for creating a RegExp. - return String(string).replace(_RESCAPE, "\\$1"); -}; - -// http://blog.stevenlevithan.com/archives/faster-trim-javascript -function trim(string) { - return String(string).replace(_LTRIM, "").replace(_RTRIM, ""); -}; - -function K(k) { - return function() { - return k; - }; -}; - -// ----------------------------------------------------------------------- -// parsing -// ----------------------------------------------------------------------- - -var Parser = RegGrp.extend({ignoreCase: true}); - -var ENCODED = /\x01(\d+)/g, - QUOTES = /'/g, - STRING = /^\x01/, - UNICODE = /\\([\da-fA-F]{1,4})/g; - -var _strings = []; - -var encoder = new Parser({ - // comments - "": "", - "\\/\\*[^*]*\\*+([^\\/][^*]*\\*+)*\\/": "", - // get rid - "@(namespace|import)[^;\\n]+[;\\n]": "", - // strings - "'(\\\\.|[^'\\\\])*'": encodeString, - '"(\\\\.|[^"\\\\])*"': encodeString, - // white space - "\\s+": " " -}); - -function encode(cssText) { - return encoder.exec(cssText); -}; - -function decode(cssText) { - return cssText.replace(ENCODED, function(match, index) { - return _strings[index - 1]; - }); -}; - -function encodeString(string) { - return "\x01" + _strings.push(string.replace(UNICODE, function(match, chr) { - return eval("'\\u" + "0000".slice(chr.length) + chr + "'"); - }).slice(1, -1).replace(QUOTES, "\\'")); -}; - -function getString(value) { - return STRING.test(value) ? _strings[value.slice(1) - 1] : value; -}; - -// clone a "width" function to create a "height" function -var rotater = new RegGrp({ - Width: "Height", - width: "height", - Left: "Top", - left: "top", - Right: "Bottom", - right: "bottom", - onX: "onY" -}); - -function rotate(fn) { - return rotater.exec(fn); -}; - -// ----------------------------------------------------------------------- -// event handling -// ----------------------------------------------------------------------- - -var eventHandlers = []; - -function addResize(handler) { - addRecalc(handler); - addEventHandler(window, "onresize", handler); -}; - -// add an event handler (function) to an element -function addEventHandler(element, type, handler) { - element.attachEvent(type, handler); - // store the handler so it can be detached later - eventHandlers.push(arguments); -}; - -// remove an event handler assigned to an element by IE7 -function removeEventHandler(element, type, handler) { -try { - element.detachEvent(type, handler); -} catch (ignore) { - // write a letter of complaint to microsoft.. -}}; - -// remove event handlers (they eat memory) -addEventHandler(window, "onunload", function() { - var handler; - while (handler = eventHandlers.pop()) { - removeEventHandler(handler[0], handler[1], handler[2]); - } -}); - -function register(handler, element, condition) { // -@DRE - //var set = handler[element.uniqueID]; - if (!handler.elements) handler.elements = {}; - if (condition) handler.elements[element.uniqueID] = element; - else delete handler.elements[element.uniqueID]; - //return !set && condition; - return condition; -}; - -addEventHandler(window, "onbeforeprint", function() { - if (!IE7.CSS.print) new StyleSheet("print"); - IE7.CSS.print.recalc(); -}); - -// ----------------------------------------------------------------------- -// pixel conversion -// ----------------------------------------------------------------------- - -// this is handy because it means that web developers can mix and match -// measurement units in their style sheets. it is not uncommon to -// express something like padding in "em" units whilst border thickness -// is most often expressed in pixels. - -var PIXEL = /^\d+(px)?$/i; -var PERCENT = /^\d+%$/; -var getPixelValue = function(element, value) { - if (PIXEL.test(value)) return parseInt(value); - var style = element.style.left; - var runtimeStyle = element.runtimeStyle.left; - element.runtimeStyle.left = element.currentStyle.left; - element.style.left = value || 0; - value = element.style.pixelLeft; - element.style.left = style; - element.runtimeStyle.left = runtimeStyle; - return value; -}; - -// ----------------------------------------------------------------------- -// generic -// ----------------------------------------------------------------------- - -var $IE7 = "ie7-"; - -var Fix = Base.extend({ - constructor: function() { - this.fixes = []; - this.recalcs = []; - }, - init: Undefined -}); - -// a store for functions that will be called when refreshing IE7 -var recalcs = []; -function addRecalc(recalc) { - recalcs.push(recalc); -}; - -IE7.recalc = function() { - IE7.HTML.recalc(); - // re-apply style sheet rules (re-calculate ie7 classes) - IE7.CSS.recalc(); - // apply global fixes to the document - for (var i = 0; i < recalcs.length; i++) recalcs[i](); -}; - -function isFixed(element) { - return element.currentStyle["ie7-position"] == "fixed"; -}; - -// original style -function getDefinedStyle(element, propertyName) { - return element.currentStyle[$IE7 + propertyName] || element.currentStyle[propertyName]; -}; - -function setOverrideStyle(element, propertyName, value) { - if (element.currentStyle[$IE7 + propertyName] == null) { - element.runtimeStyle[$IE7 + propertyName] = element.currentStyle[propertyName]; - } - element.runtimeStyle[propertyName] = value; -}; - -// create a temporary element which is used to inherit styles -// from the target element. the temporary element can be resized -// to determine pixel widths/heights -function createTempElement(tagName) { - var element = document.createElement(tagName || "object"); - element.style.cssText = "position:absolute;padding:0;display:block;border:none;clip:rect(0 0 0 0);left:-9999"; - element.ie7_anon = true; - return element; -}; - - -// ========================================================================= -// ie7-cssQuery.js -// ========================================================================= - -function cssQuery(selector, context, single) { - if (!_cache[selector]) { - reg = []; // store for RegExp objects - var fn = ""; - var selectors = cssParser.escape(selector).split(","); - for (var i = 0; i < selectors.length; i++) { - _wild = _index = _list = 0; // reset - _duplicate = selectors.length > 1 ? 2 : 0; // reset - var block = cssParser.exec(selectors[i]) || "if(0){"; - if (_wild) { // IE's pesky comment nodes - block += format("if(e%1.nodeName!='!'){", _index); - } - // check for duplicates before storing results - var store = _duplicate > 1 ? _TEST : ""; - block += format(store + _STORE, _index); - // add closing braces - block += Array(match(block, /\{/g).length + 1).join("}"); - fn += block; - } - eval(format(_FN, reg) + cssParser.unescape(fn) + "return s?null:r}"); - _cache[selector] = _selectorFunction; - } - return _cache[selector](context || document, single); -}; - -var _MSIE5 = appVersion < 6; - -var _EVALUATED = /^(href|src)$/; -var _ATTRIBUTES = { - "class": "className", - "for": "htmlFor" -}; - -IE7._indexed = 1; - -IE7._byId = function(document, id) { - var result = document.all[id] || null; - // returns a single element or a collection - if (!result || result.id == id) return result; - // document.all has returned a collection of elements with name/id - for (var i = 0; i < result.length; i++) { - if (result[i].id == id) return result[i]; - } - return null; -}; - -IE7._getAttribute = function(element, name) { - if (name == "src" && element.pngSrc) return element.pngSrc; - - var attribute = _MSIE5 ? (element.attributes[name] || element.attributes[_ATTRIBUTES[name.toLowerCase()]]) : element.getAttributeNode(name); - if (attribute && (attribute.specified || name == "value")) { - if (_EVALUATED.test(name)) { - return element.getAttribute(name, 2); - } else if (name == "class") { - return element.className.replace(/\sie7_\w+/g, ""); - } else if (name == "style") { - return element.style.cssText; - } else { - return attribute.nodeValue; - } - } - return null; -}; - -var names = "colSpan,rowSpan,vAlign,dateTime,accessKey,tabIndex,encType,maxLength,readOnly,longDesc"; -// Convert the list of strings to a hash, mapping the lowercase name to the camelCase name. -extend(_ATTRIBUTES, combine(names.toLowerCase().split(","), names.split(","))); - -IE7._getNextElementSibling = function(node) { - // return the next element to the supplied element - // nextSibling is not good enough as it might return a text or comment node - while (node && (node = node.nextSibling) && (node.nodeType != 1 || node.nodeName == "!")) continue; - return node; -}; - -IE7._getPreviousElementSibling = function(node) { - // return the previous element to the supplied element - while (node && (node = node.previousSibling) && (node.nodeType != 1 || node.nodeName == "!")) continue; - return node; -}; - -// ========================================================================= -// CSSParser -// ========================================================================= - -var IMPLIED_ASTERISK = /([\s>+~,]|[^(]\+|^)([#.:\[])/g, - IMPLIED_SPACE = /(^|,)([^\s>+~])/g, - WHITESPACE = /\s*([\s>+~(),]|^|$)\s*/g, - WILD_CARD = /\s\*\s/g;; - -var CSSParser = RegGrp.extend({ - constructor: function(items) { - this.base(items); - this.sorter = new RegGrp; - this.sorter.add(/:not\([^)]*\)/, RegGrp.IGNORE); - this.sorter.add(/([ >](\*|[\w-]+))([^: >+~]*)(:\w+-child(\([^)]+\))?)([^: >+~]*)/, "$1$3$6$4"); - }, - - ignoreCase: true, - - escape: function(selector) { - return this.optimise(this.format(selector)); - }, - - format: function(selector) { - return selector - .replace(WHITESPACE, "$1") - .replace(IMPLIED_SPACE, "$1 $2") - .replace(IMPLIED_ASTERISK, "$1*$2"); - }, - - optimise: function(selector) { - // optimise wild card descendant selectors - return this.sorter.exec(selector.replace(WILD_CARD, ">* ")); - }, - - unescape: function(selector) { - return decode(selector); - } -}); - -// some constants -var _OPERATORS = { - "": "%1!=null", - "=": "%1=='%2'", - "~=": /(^| )%1( |$)/, - "|=": /^%1(-|$)/, - "^=": /^%1/, - "$=": /%1$/, - "*=": /%1/ -}; - -var _PSEUDO_CLASSES = { - "first-child": "!IE7._getPreviousElementSibling(e%1)", - "link": "e%1.currentStyle['ie7-link']=='link'", - "visited": "e%1.currentStyle['ie7-link']=='visited'" -}; - -var _VAR = "var p%2=0,i%2,e%2,n%2=e%1."; -var _ID = "e%1.sourceIndex"; -var _TEST = "var g=" + _ID + ";if(!p[g]){p[g]=1;"; -var _STORE = "r[r.length]=e%1;if(s)return e%1;"; -var _FN = "var _selectorFunction=function(e0,s){IE7._indexed++;var r=[],p={},reg=[%1],d=document;"; -var reg; // a store for RexExp objects -var _index; -var _wild; // need to flag certain _wild card selectors as MSIE includes comment nodes -var _list; // are we processing a node _list? -var _duplicate; // possible duplicates? -var _cache = {}; // store parsed selectors - -// a hideous parser -var cssParser = new CSSParser({ - " (\\*|[\\w-]+)#([\\w-]+)": function(match, tagName, id) { // descendant selector followed by ID - _wild = false; - var replacement = "var e%2=IE7._byId(d,'%4');if(e%2&&"; - if (tagName != "*") replacement += "e%2.nodeName=='%3'&&"; - replacement += "(e%1==d||e%1.contains(e%2))){"; - if (_list) replacement += format("i%1=n%1.length;", _list); - return format(replacement, _index++, _index, tagName.toUpperCase(), id); - }, - - " (\\*|[\\w-]+)": function(match, tagName) { // descendant selector - _duplicate++; // this selector may produce duplicates - _wild = tagName == "*"; - var replacement = _VAR; - // IE5.x does not support getElementsByTagName("*"); - replacement += (_wild && _MSIE5) ? "all" : "getElementsByTagName('%3')"; - replacement += ";for(i%2=0;(e%2=n%2[i%2]);i%2++){"; - return format(replacement, _index++, _list = _index, tagName.toUpperCase()); - }, - - ">(\\*|[\\w-]+)": function(match, tagName) { // child selector - var children = _list; - _wild = tagName == "*"; - var replacement = _VAR; - // use the children property for MSIE as it does not contain text nodes - // (but the children collection still includes comments). - // the document object does not have a children collection - replacement += children ? "children": "childNodes"; - if (!_wild && children) replacement += ".tags('%3')"; - replacement += ";for(i%2=0;(e%2=n%2[i%2]);i%2++){"; - if (_wild) { - replacement += "if(e%2.nodeType==1){"; - _wild = _MSIE5; - } else { - if (!children) replacement += "if(e%2.nodeName=='%3'){"; - } - return format(replacement, _index++, _list = _index, tagName.toUpperCase()); - }, - - "\\+(\\*|[\\w-]+)": function(match, tagName) { // direct adjacent selector - var replacement = ""; - if (_wild) replacement += "if(e%1.nodeName!='!'){"; - _wild = false; - replacement += "e%1=IE7._getNextElementSibling(e%1);if(e%1"; - if (tagName != "*") replacement += "&&e%1.nodeName=='%2'"; - replacement += "){"; - return format(replacement, _index, tagName.toUpperCase()); - }, - - "~(\\*|[\\w-]+)": function(match, tagName) { // indirect adjacent selector - var replacement = ""; - if (_wild) replacement += "if(e%1.nodeName!='!'){"; - _wild = false; - _duplicate = 2; // this selector may produce duplicates - replacement += "while(e%1=e%1.nextSibling){if(e%1.ie7_adjacent==IE7._indexed)break;if("; - if (tagName == "*") { - replacement += "e%1.nodeType==1"; - if (_MSIE5) replacement += "&&e%1.nodeName!='!'"; - } else replacement += "e%1.nodeName=='%2'"; - replacement += "){e%1.ie7_adjacent=IE7._indexed;"; - return format(replacement, _index, tagName.toUpperCase()); - }, - - "#([\\w-]+)": function(match, id) { // ID selector - _wild = false; - var replacement = "if(e%1.id=='%2'){"; - if (_list) replacement += format("i%1=n%1.length;", _list); - return format(replacement, _index, id); - }, - - "\\.([\\w-]+)": function(match, className) { // class selector - _wild = false; - // store RegExp objects - slightly faster on IE - reg.push(new RegExp("(^|\\s)" + rescape(className) + "(\\s|$)")); - return format("if(e%1.className&®[%2].test(e%1.className)){", _index, reg.length - 1); - }, - - "\\[([\\w-]+)\\s*([^=]?=)?\\s*([^\\]]*)\\]": function(match, attr, operator, value) { // attribute selectors - var alias = _ATTRIBUTES[attr] || attr; - if (operator) { - var getAttribute = "e%1.getAttribute('%2',2)"; - if (!_EVALUATED.test(attr)) { - getAttribute = "e%1.%3||" + getAttribute; - } - attr = format("(" + getAttribute + ")", _index, attr, alias); - } else { - attr = format("IE7._getAttribute(e%1,'%2')", _index, attr); - } - var replacement = _OPERATORS[operator || ""] || "0"; - if (replacement && replacement.source) { - reg.push(new RegExp(format(replacement.source, rescape(cssParser.unescape(value))))); - replacement = "reg[%2].test(%1)"; - value = reg.length - 1; - } - return "if(" + format(replacement, attr, value) + "){"; - }, - - ":+([\\w-]+)(\\(([^)]+)\\))?": function(match, pseudoClass, $2, args) { // pseudo class selectors - pseudoClass = _PSEUDO_CLASSES[pseudoClass]; - return "if(" + (pseudoClass ? format(pseudoClass, _index, args || "") : "0") + "){"; - } -}); - -// ========================================================================= -// ie7-css.js -// ========================================================================= - -var HYPERLINK = /a(#[\w-]+)?(\.[\w-]+)?:(hover|active)/i; -var BRACE1 = /\s*\{\s*/, BRACE2 = /\s*\}\s*/, COMMA = /\s*\,\s*/; -var FIRST_LINE_LETTER = /(.*)(:first-(line|letter))/; - -//var UNKNOWN = /UNKNOWN|([:.])\w+\1/i; - -var styleSheets = document.styleSheets; - -IE7.CSS = new (Fix.extend({ // single instance - parser: new Parser, - screen: "", - print: "", - styles: [], - rules: [], - pseudoClasses: appVersion < 7 ? "first\\-child" : "", - dynamicPseudoClasses: { - toString: function() { - var strings = []; - for (var pseudoClass in this) strings.push(pseudoClass); - return strings.join("|"); - } - }, - - init: function() { - var NONE = "^\x01$"; - var CLASS = "\\[class=?[^\\]]*\\]"; - var pseudoClasses = []; - if (this.pseudoClasses) pseudoClasses.push(this.pseudoClasses); - var dynamicPseudoClasses = this.dynamicPseudoClasses.toString(); - if (dynamicPseudoClasses) pseudoClasses.push(dynamicPseudoClasses); - pseudoClasses = pseudoClasses.join("|"); - var unknown = appVersion < 7 ? ["[>+~[(]|([:.])\\w+\\1"] : [CLASS]; - if (pseudoClasses) unknown.push(":(" + pseudoClasses + ")"); - this.UNKNOWN = new RegExp(unknown.join("|") || NONE, "i"); - var complex = appVersion < 7 ? ["\\[[^\\]]+\\]|[^\\s(\\[]+\\s*[+~]"] : [CLASS]; - var complexRule = complex.concat(); - if (pseudoClasses) complexRule.push(":(" + pseudoClasses + ")"); - Rule.COMPLEX = new RegExp(complexRule.join("|") || NONE, "ig"); - if (this.pseudoClasses) complex.push(":(" + this.pseudoClasses + ")"); - DynamicRule.COMPLEX = new RegExp(complex.join("|") || NONE, "i"); - DynamicRule.MATCH = new RegExp(dynamicPseudoClasses ? "(.*):(" + dynamicPseudoClasses + ")(.*)" : NONE, "i"); - - this.createStyleSheet(); - this.refresh(); - }, - - addEventHandler: function() { - addEventHandler.apply(null, arguments); - }, - - addFix: function(expression, replacement) { - this.parser.add(expression, replacement); - }, - - addRecalc: function(propertyName, test, handler, replacement) { - // recalcs occur whenever the document is refreshed using document.recalc() - test = new RegExp("([{;\\s])" + propertyName + "\\s*:\\s*" + test + "[^;}]*"); - var id = this.recalcs.length; - if (replacement) replacement = propertyName + ":" + replacement; - this.addFix(test, function(match, $1) { - return (replacement ? $1 + replacement : match) + ";ie7-" + match.slice(1) + ";ie7_recalc" + id + ":1"; - }); - this.recalcs.push(arguments); - return id; - }, - - apply: function() { - this.getInlineStyles(); - new StyleSheet("screen"); - this.trash(); - }, - - createStyleSheet: function() { - // create the IE7 style sheet - this.styleSheet = document.createStyleSheet(); - // flag it so we can ignore it during parsing - this.styleSheet.ie7 = true; - this.styleSheet.owningElement.ie7 = true; - this.styleSheet.cssText = HEADER; - }, - - getInlineStyles: function() { - // load inline styles - var styleSheets = document.getElementsByTagName("style"), styleSheet; - for (var i = styleSheets.length - 1; (styleSheet = styleSheets[i]); i--) { - if (!styleSheet.disabled && !styleSheet.ie7) { - this.styles.push(styleSheet.innerHTML); - } - } - }, - - getText: function(styleSheet, path) { - // explorer will trash unknown selectors (it converts them to "UNKNOWN"). - // so we must reload external style sheets (internal style sheets can have their text - // extracted through the innerHTML property). - // load the style sheet text from an external file - try { - var cssText = styleSheet.cssText; - } catch (e) { - cssText = ""; - } - if (httpRequest) cssText = loadFile(styleSheet.href, path) || cssText; - return cssText; - }, - - recalc: function() { - this.screen.recalc(); - // we're going to read through all style rules. - // certain rules have had ie7 properties added to them. - // e.g. p{top:0; ie7_recalc2:1; left:0} - // this flags a property in the rule as needing a fix. - // the selector text is then used to query the document. - // we can then loop through the results of the query - // and fix the elements. - // we ignore the IE7 rules - so count them in the header - var RECALCS = /ie7_recalc\d+/g; - var start = HEADER.match(/[{,]/g).length; - // only calculate screen fixes. print fixes don't show up anyway - var stop = start + (this.screen.cssText.match(/\{/g)||"").length; - var rules = this.styleSheet.rules, rule; - var calcs, calc, elements, element, i, j, k, id; - // loop through all rules - for (i = start; i < stop; i++) { - rule = rules[i]; - var cssText = rule.style.cssText; - // search for the "ie7_recalc" flag (there may be more than one) - if (rule && (calcs = cssText.match(RECALCS))) { - // use the selector text to query the document - elements = cssQuery(rule.selectorText); - // if there are matching elements then loop - // through the recalc functions and apply them - // to each element - if (elements.length) for (j = 0; j < calcs.length; j++) { - // get the matching flag (e.g. ie7_recalc3) - id = calcs[j]; - // extract the numeric id from the end of the flag - // and use it to index the collection of recalc - // functions - calc = IE7.CSS.recalcs[id.slice(10)][2]; - for (k = 0; (element = elements[k]); k++) { - // apply the fix - if (element.currentStyle[id]) calc(element, cssText); - } - } - } - } - }, - - refresh: function() { - this.styleSheet.cssText = HEADER + this.screen + this.print; - }, - - trash: function() { - // trash the old style sheets - for (var i = 0; i < styleSheets.length; i++) { - if (!styleSheets[i].ie7) { - try { - var cssText = styleSheets[i].cssText; - } catch (e) { - cssText = ""; - } - if (cssText) styleSheets[i].cssText = ""; - } - } - } -})); - -// ----------------------------------------------------------------------- -// IE7 StyleSheet class -// ----------------------------------------------------------------------- - -var StyleSheet = Base.extend({ - constructor: function(media) { - this.media = media; - this.load(); - IE7.CSS[media] = this; - IE7.CSS.refresh(); - }, - - createRule: function(selector, cssText) { - if (IE7.CSS.UNKNOWN.test(selector)) { - var match; - if (PseudoElement && (match = selector.match(PseudoElement.MATCH))) { - return new PseudoElement(match[1], match[2], cssText); - } else if (match = selector.match(DynamicRule.MATCH)) { - if (!HYPERLINK.test(match[0]) || DynamicRule.COMPLEX.test(match[0])) { - return new DynamicRule(selector, match[1], match[2], match[3], cssText); - } - } else return new Rule(selector, cssText); - } - return selector + " {" + cssText + "}"; - }, - - getText: function() { - // store for style sheet text - var _inlineStyles = [].concat(IE7.CSS.styles); - // parse media decalarations - var MEDIA = /@media\s+([^{]*)\{([^@]+\})\s*\}/gi; - var ALL = /\ball\b|^$/i, SCREEN = /\bscreen\b/i, PRINT = /\bprint\b/i; - function _parseMedia(cssText, media) { - _filterMedia.value = media; - return cssText.replace(MEDIA, _filterMedia); - }; - function _filterMedia(match, media, cssText) { - media = _simpleMedia(media); - switch (media) { - case "screen": - case "print": - if (media != _filterMedia.value) return ""; - case "all": - return cssText; - } - return ""; - }; - function _simpleMedia(media) { - if (ALL.test(media)) return "all"; - else if (SCREEN.test(media)) return (PRINT.test(media)) ? "all" : "screen"; - else if (PRINT.test(media)) return "print"; - }; - var self = this; - function _getCSSText(styleSheet, path, media, level) { - var cssText = ""; - if (!level) { - media = _simpleMedia(styleSheet.media); - level = 0; - } - if (media == "all" || media == self.media) { - // IE only allows importing style sheets three levels deep. - // it will crash if you try to access a level below this - if (level < 3) { - // loop through imported style sheets - for (var i = 0; i < styleSheet.imports.length; i++) { - // call this function recursively to get all imported style sheets - cssText += _getCSSText(styleSheet.imports[i], getPath(styleSheet.href, path), media, level + 1); - } - } - // retrieve inline style or load an external style sheet - cssText += encode(styleSheet.href ? _loadStyleSheet(styleSheet, path) : _inlineStyles.pop() || ""); - cssText = _parseMedia(cssText, self.media); - } - return cssText; - }; - // store loaded cssText URLs - var fileCache = {}; - // load an external style sheet - function _loadStyleSheet(styleSheet, path) { - var url = makePath(styleSheet.href, path); - // if the style sheet has already loaded then don't duplicate it - if (fileCache[url]) return ""; - // load from source - fileCache[url] = (styleSheet.disabled) ? "" : - _fixUrls(IE7.CSS.getText(styleSheet, path), getPath(styleSheet.href, path)); - return fileCache[url]; - }; - // fix css paths - // we're lumping all css text into one big style sheet so relative - // paths have to be fixed. this is necessary anyway because of other - // explorer bugs. - var URL = /(url\s*\(\s*['"]?)([\w\.]+[^:\)]*['"]?\))/gi; - function _fixUrls(cssText, pathname) { - // hack & slash - return cssText.replace(URL, "$1" + pathname.slice(0, pathname.lastIndexOf("/") + 1) + "$2"); - }; - - // load all style sheets in the document - for (var i = 0; i < styleSheets.length; i++) { - if (!styleSheets[i].disabled && !styleSheets[i].ie7) { - this.cssText += _getCSSText(styleSheets[i]); - } - } - }, - - load: function() { - this.cssText = ""; - this.getText(); - this.parse(); - this.cssText = decode(this.cssText); - fileCache = {}; - }, - - parse: function() { - this.cssText = IE7.CSS.parser.exec(this.cssText); - - // parse the style sheet - var offset = IE7.CSS.rules.length; - var rules = this.cssText.split(BRACE2), rule; - var selectors, cssText, i, j; - for (i = 0; i < rules.length; i++) { - rule = rules[i].split(BRACE1); - selectors = rule[0].split(COMMA); - cssText = rule[1]; - for (j = 0; j < selectors.length; j++) { - selectors[j] = cssText ? this.createRule(selectors[j], cssText) : ""; - } - rules[i] = selectors.join("\n"); - } - this.cssText = rules.join("\n"); - this.rules = IE7.CSS.rules.slice(offset); - }, - - recalc: function() { - var rule, i; - for (i = 0; (rule = this.rules[i]); i++) rule.recalc(); - }, - - toString: function() { - return "@media " + this.media + "{" + this.cssText + "}"; - } -}); - -var PseudoElement; - -// ----------------------------------------------------------------------- -// IE7 style rules -// ----------------------------------------------------------------------- - -var Rule = IE7.Rule = Base.extend({ - // properties - constructor: function(selector, cssText) { - this.id = IE7.CSS.rules.length; - this.className = Rule.PREFIX + this.id; - selector = selector.match(FIRST_LINE_LETTER) || selector || "*"; - this.selector = selector[1] || selector; - this.selectorText = this.parse(this.selector) + (selector[2] || ""); - this.cssText = cssText; - this.MATCH = new RegExp("\\s" + this.className + "(\\s|$)", "g"); - IE7.CSS.rules.push(this); - this.init(); - }, - - init: Undefined, - - add: function(element) { - // allocate this class - element.className += " " + this.className; - }, - - recalc: function() { - // execute the underlying css query for this class - var match = cssQuery(this.selector); - // add the class name for all matching elements - for (var i = 0; i < match.length; i++) this.add(match[i]); - }, - - parse: function(selector) { - // attempt to preserve specificity for "loose" parsing by - // removing unknown tokens from a css selector but keep as - // much as we can.. - var simple = selector.replace(Rule.CHILD, " ").replace(Rule.COMPLEX, ""); - if (appVersion < 7) simple = simple.replace(Rule.MULTI, ""); - var tags = match(simple, Rule.TAGS).length - match(selector, Rule.TAGS).length; - var classes = match(simple, Rule.CLASSES).length - match(selector, Rule.CLASSES).length + 1; - while (classes > 0 && Rule.CLASS.test(simple)) { - simple = simple.replace(Rule.CLASS, ""); - classes--; - } - while (tags > 0 && Rule.TAG.test(simple)) { - simple = simple.replace(Rule.TAG, "$1*"); - tags--; - } - simple += "." + this.className; - classes = Math.min(classes, 2); - tags = Math.min(tags, 2); - var score = -10 * classes - tags; - if (score > 0) { - simple = simple + "," + Rule.MAP[score] + " " + simple; - } - return simple; - }, - - remove: function(element) { - // deallocate this class - element.className = element.className.replace(this.MATCH, "$1"); - }, - - toString: function() { - return format("%1 {%2}", this.selectorText, this.cssText); - } -}, { - CHILD: />/g, - CLASS: /\.[\w-]+/, - CLASSES: /[.:\[]/g, - MULTI: /(\.[\w-]+)+/g, - PREFIX: "ie7_class", - TAG: /^\w+|([\s>+~])\w+/, - TAGS: /^\w|[\s>+~]\w/g, - MAP: { - 1: "html", - 2: "html body", - 10: ".ie7_html", - 11: "html.ie7_html", - 12: "html.ie7_html body", - 20: ".ie7_html .ie7_body", - 21: "html.ie7_html .ie7_body", - 22: "html.ie7_html body.ie7_body" - } -}); - -// ----------------------------------------------------------------------- -// IE7 dynamic style -// ----------------------------------------------------------------------- - -// object properties: -// attach: the element that an event handler will be attached to -// target: the element that will have the IE7 class applied - -var DynamicRule = Rule.extend({ - // properties - constructor: function(selector, attach, dynamicPseudoClass, target, cssText) { - // initialise object properties - this.attach = attach || "*"; - this.dynamicPseudoClass = IE7.CSS.dynamicPseudoClasses[dynamicPseudoClass]; - this.target = target; - this.base(selector, cssText); - }, - - recalc: function() { - // execute the underlying css query for this class - var attaches = cssQuery(this.attach), attach; - // process results - for (var i = 0; attach = attaches[i]; i++) { - // retrieve the event handler's target element(s) - var target = this.target ? cssQuery(this.target, attach) : [attach]; - // attach event handlers for dynamic pseudo-classes - if (target.length) this.dynamicPseudoClass.apply(attach, target, this); - } - } -}); - -// ----------------------------------------------------------------------- -// IE7 dynamic pseudo-classes -// ----------------------------------------------------------------------- - -var DynamicPseudoClass = Base.extend({ - constructor: function(name, apply) { - this.name = name; - this.apply = apply; - this.instances = {}; - IE7.CSS.dynamicPseudoClasses[name] = this; - }, - - register: function(instance) { - // an "instance" is actually an Arguments object - var _class = instance[2]; - instance.id = _class.id + instance[0].uniqueID; - if (!this.instances[instance.id]) { - var target = instance[1], j; - for (j = 0; j < target.length; j++) _class.add(target[j]); - this.instances[instance.id] = instance; - } - }, - - unregister: function(instance) { - if (this.instances[instance.id]) { - var _class = instance[2]; - var target = instance[1], j; - for (j = 0; j < target.length; j++) _class.remove(target[j]); - delete this.instances[instance.id]; - } - } -}); - -// ----------------------------------------------------------------------- -// dynamic pseudo-classes -// ----------------------------------------------------------------------- - -if (appVersion < 7) { - var Hover = new DynamicPseudoClass("hover", function(element) { - var instance = arguments; - IE7.CSS.addEventHandler(element, appVersion < 5.5 ? "onmouseover" : "onmouseenter", function() { - Hover.register(instance); - }); - IE7.CSS.addEventHandler(element, appVersion < 5.5 ? "onmouseout" : "onmouseleave", function() { - Hover.unregister(instance); - }); - }); - - // globally trap the mouseup event (thanks Martijn!) - addEventHandler(document, "onmouseup", function() { - var instances = Hover.instances; - for (var i in instances) - if (!instances[i][0].contains(event.srcElement)) - Hover.unregister(instances[i]); - }); -} - -// ----------------------------------------------------------------------- -// propertyName: inherit; -// ----------------------------------------------------------------------- - -IE7.CSS.addRecalc("[\\w-]+", "inherit", function(element, cssText) { - var inherited = cssText.match(/[\w-]+\s*:\s*inherit/g); - for (var i = 0; i < inherited.length; i++) { - var propertyName = inherited[i].replace(/ie7\-|\s*:\s*inherit/g, "").replace(/\-([a-z])/g, function(match, chr) { - return chr.toUpperCase() - }); - element.runtimeStyle[propertyName] = element.parentElement.currentStyle[propertyName]; - } -}); - -// ========================================================================= -// ie7-html.js -// ========================================================================= - -// default font-sizes -//HEADER += "h1{font-size:2em}h2{font-size:1.5em;}h3{font-size:1.17em;}h4{font-size:1em}h5{font-size:.83em}h6{font-size:.67em}"; - -IE7.HTML = new (Fix.extend({ // single instance - fixed: {}, - - init: Undefined, - - addFix: function() { - // fixes are a one-off, they are applied when the document is loaded - this.fixes.push(arguments); - }, - - apply: function() { - for (var i = 0; i < this.fixes.length; i++) { - var match = cssQuery(this.fixes[i][0]); - var fix = this.fixes[i][1]; - for (var j = 0; j < match.length; j++) fix(match[j]); - } - }, - - addRecalc: function() { - // recalcs occur whenever the document is refreshed using document.recalc() - this.recalcs.push(arguments); - }, - - recalc: function() { - // loop through the fixes - for (var i = 0; i < this.recalcs.length; i++) { - var match = cssQuery(this.recalcs[i][0]); - var recalc = this.recalcs[i][1], element; - var key = Math.pow(2, i); - for (var j = 0; (element = match[j]); j++) { - var uniqueID = element.uniqueID; - if ((this.fixed[uniqueID] & key) == 0) { - element = recalc(element) || element; - this.fixed[uniqueID] |= key; - } - } - } - } -})); - -if (appVersion < 7) { - // provide support for the tag. - // this is a proper fix, it preserves the DOM structure and - // elements report the correct tagName & namespace prefix - document.createElement("abbr"); - - // bind to the first child control - IE7.HTML.addRecalc("label", function(label) { - if (!label.htmlFor) { - var firstChildControl = cssQuery("input,textarea", label, true); - if (firstChildControl) { - addEventHandler(label, "onclick", function() { - firstChildControl.click(); - }); - } - } - }); -} - -// ========================================================================= -// ie7-layout.js -// ========================================================================= - -var NUMERIC = "[.\\d]"; - -new function(_) { -var layout = IE7.Layout = this; - - // big, ugly box-model hack + min/max stuff - - // #tantek > #erik > #dean { voice-family: hacker; } - - // ----------------------------------------------------------------------- - // "layout" - // ----------------------------------------------------------------------- - - HEADER += "*{boxSizing:content-box}"; - - // does an element have "layout" ? - IE7.hasLayout = appVersion < 5.5 ? function(element) { - // element.currentStyle.hasLayout doesn't work for IE5.0 - return element.clientWidth; - } : function(element) { - return element.currentStyle.hasLayout; - }; - - // give an element "layout" - layout.boxSizing = function(element) { - if (!IE7.hasLayout(element)) { - //# element.runtimeStyle.fixedHeight = - element.style.height = "0cm"; - if (element.currentStyle.verticalAlign == "auto") - element.runtimeStyle.verticalAlign = "top"; - // when an element acquires "layout", margins no longer collapse correctly - collapseMargins(element); - } - }; - - // ----------------------------------------------------------------------- - // Margin Collapse - // ----------------------------------------------------------------------- - - function collapseMargins(element) { - if (element != viewport && element.currentStyle.position != "absolute") { - collapseMargin(element, "marginTop"); - collapseMargin(element, "marginBottom"); - } - }; - - function collapseMargin(element, type) { - if (!element.runtimeStyle[type]) { - var parentElement = element.parentElement; - if (parentElement && IE7.hasLayout(parentElement) && !IE7[type == "marginTop" ? "_getPreviousElementSibling" : "_getNextElementSibling"](element)) return; - var child = cssQuery(">*:" + (type == "marginTop" ? "first" : "last") + "-child", element, true); - if (child && child.currentStyle.styleFloat == "none" && IE7.hasLayout(child)) { - collapseMargin(child, type); - margin = _getMargin(element, element.currentStyle[type]); - childMargin = _getMargin(child, child.currentStyle[type]); - if (margin < 0 || childMargin < 0) { - element.runtimeStyle[type] = margin + childMargin; - } else { - element.runtimeStyle[type] = Math.max(childMargin, margin); - } - child.runtimeStyle[type] = "0px"; - } - } - }; - - function _getMargin(element, value) { - return value == "auto" ? 0 : getPixelValue(element, value); - }; - - // ----------------------------------------------------------------------- - // box-model - // ----------------------------------------------------------------------- - - // constants - var UNIT = /^[.\d][\w%]*$/, AUTO = /^(auto|0cm)$/; - - var applyWidth, applyHeight; - IE7.Layout.borderBox = function(element){ - applyWidth(element); - applyHeight(element); - }; - - var fixWidth = function(HEIGHT) { - applyWidth = function(element) { - if (!PERCENT.test(element.currentStyle.width)) fixWidth(element); - collapseMargins(element); - }; - - function fixWidth(element, value) { - if (!element.runtimeStyle.fixedWidth) { - if (!value) value = element.currentStyle.width; - element.runtimeStyle.fixedWidth = (UNIT.test(value)) ? Math.max(0, getFixedWidth(element, value)) : value; - setOverrideStyle(element, "width", element.runtimeStyle.fixedWidth); - } - }; - - function layoutWidth(element) { - if (!isFixed(element)) { - var layoutParent = element.offsetParent; - while (layoutParent && !IE7.hasLayout(layoutParent)) layoutParent = layoutParent.offsetParent; - } - return (layoutParent || viewport).clientWidth; - }; - - function getPixelWidth(element, value) { - if (PERCENT.test(value)) return parseInt(parseFloat(value) / 100 * layoutWidth(element)); - return getPixelValue(element, value); - }; - - var getFixedWidth = function(element, value) { - var borderBox = element.currentStyle["box-sizing"] == "border-box"; - var adjustment = 0; - if (quirksMode && !borderBox) - adjustment += getBorderWidth(element) + getWidth(element, "padding"); - else if (!quirksMode && borderBox) - adjustment -= getBorderWidth(element) + getWidth(element, "padding"); - return getPixelWidth(element, value) + adjustment; - }; - - // easy way to get border thickness for elements with "layout" - function getBorderWidth(element) { - return element.offsetWidth - element.clientWidth; - }; - - // have to do some pixel conversion to get padding/margin thickness :-( - function getWidth(element, type) { - return getPixelWidth(element, element.currentStyle[type + "Left"]) + getPixelWidth(element, element.currentStyle[type + "Right"]); - }; - - // ----------------------------------------------------------------------- - // min/max - // ----------------------------------------------------------------------- - - HEADER += "*{minWidth:none;maxWidth:none;min-width:none;max-width:none}"; - - // handle min-width property - layout.minWidth = function(element) { - // IE6 supports min-height so we frig it here - //#if (element.currentStyle.minHeight == "auto") element.runtimeStyle.minHeight = 0; - if (element.currentStyle["min-width"] != null) { - element.style.minWidth = element.currentStyle["min-width"]; - } - if (register(arguments.callee, element, element.currentStyle.minWidth != "none")) { - layout.boxSizing(element); - fixWidth(element); - resizeWidth(element); - } - }; - - // clone the minWidth function to make a maxWidth function - eval("IE7.Layout.maxWidth=" + String(layout.minWidth).replace(/min/g, "max")); - - // apply min/max restrictions - function resizeWidth(element) { - // check boundaries - var rect = element.getBoundingClientRect(); - var width = rect.right - rect.left; - - if (element.currentStyle.minWidth != "none" && width <= getFixedWidth(element, element.currentStyle.minWidth)) { - element.runtimeStyle.width = element.currentStyle.minWidth; - } else if (element.currentStyle.maxWidth != "none" && width >= getFixedWidth(element, element.currentStyle.maxWidth)) { - element.runtimeStyle.width = element.currentStyle.maxWidth; - } else { - element.runtimeStyle.width = element.runtimeStyle.fixedWidth; // || "auto"; - } - }; - - // ----------------------------------------------------------------------- - // right/bottom - // ----------------------------------------------------------------------- - - function fixRight(element) { - if (register(fixRight, element, /^(fixed|absolute)$/.test(element.currentStyle.position) && - getDefinedStyle(element, "left") != "auto" && - getDefinedStyle(element, "right") != "auto" && - AUTO.test(getDefinedStyle(element, "width")))) { - resizeRight(element); - IE7.Layout.boxSizing(element); - } - }; - IE7.Layout.fixRight = fixRight; - - function resizeRight(element) { - var left = getPixelWidth(element, element.runtimeStyle._left || element.currentStyle.left); - var width = layoutWidth(element) - getPixelWidth(element, element.currentStyle.right) - left - getWidth(element, "margin"); - if (parseInt(element.runtimeStyle.width) == width) return; - element.runtimeStyle.width = ""; - if (isFixed(element) || HEIGHT || element.offsetWidth < width) { - if (!quirksMode) width -= getBorderWidth(element) + getWidth(element, "padding"); - if (width < 0) width = 0; - element.runtimeStyle.fixedWidth = width; - setOverrideStyle(element, "width", width); - } - }; - - // ----------------------------------------------------------------------- - // window.onresize - // ----------------------------------------------------------------------- - - // handle window resize - var clientWidth = 0; - addResize(function() { - if (!viewport) return; - var i, wider = (clientWidth < viewport.clientWidth); - clientWidth = viewport.clientWidth; - // resize elements with "min-width" set - var elements = layout.minWidth.elements; - for (i in elements) { - var element = elements[i]; - var fixedWidth = (parseInt(element.runtimeStyle.width) == getFixedWidth(element, element.currentStyle.minWidth)); - if (wider && fixedWidth) element.runtimeStyle.width = ""; - if (wider == fixedWidth) resizeWidth(element); - } - // resize elements with "max-width" set - var elements = layout.maxWidth.elements; - for (i in elements) { - var element = elements[i]; - var fixedWidth = (parseInt(element.runtimeStyle.width) == getFixedWidth(element, element.currentStyle.maxWidth)); - if (!wider && fixedWidth) element.runtimeStyle.width = ""; - if (wider != fixedWidth) resizeWidth(element); - } - // resize elements with "right" set - for (i in fixRight.elements) resizeRight(fixRight.elements[i]); - }); - - // ----------------------------------------------------------------------- - // fix CSS - // ----------------------------------------------------------------------- - if (quirksMode) { - IE7.CSS.addRecalc("width", NUMERIC, applyWidth); - } - if (appVersion < 7) { - IE7.CSS.addRecalc("min-width", NUMERIC, layout.minWidth); - IE7.CSS.addRecalc("max-width", NUMERIC, layout.maxWidth); - IE7.CSS.addRecalc("right", NUMERIC, fixRight); - } - }; - - eval("var fixHeight=" + rotate(fixWidth)); - - // apply box-model + min/max fixes - fixWidth(); - fixHeight(true); -}; - -// ========================================================================= -// ie7-graphics.js -// ========================================================================= - -// a small transparent image used as a placeholder -var BLANK_GIF = makePath("blank.gif", path); - -var ALPHA_IMAGE_LOADER = "DXImageTransform.Microsoft.AlphaImageLoader"; -var PNG_FILTER = "progid:" + ALPHA_IMAGE_LOADER + "(src='%1',sizingMethod='%2')"; - -// regular expression version of the above -var PNG; - -var filtered = []; - -function fixImage(element) { - if (PNG.test(element.src)) { - // we have to preserve width and height - var image = new Image(element.width, element.height); - image.onload = function() { - element.width = image.width; - element.height = image.height; - image = null; - }; - image.src = element.src; - // store the original url (we'll put it back when it's printed) - element.pngSrc = element.src; - // add the AlphaImageLoader thingy - addFilter(element); - } -}; - -if (appVersion >= 5.5 && appVersion < 7) { - // ** IE7 VARIABLE - // e.g. only apply the hack to files ending in ".png" - // IE7_PNG_SUFFIX = ".png"; - - // replace background(-image): url(..) .. with background(-image): .. ;filter: ..; - IE7.CSS.addFix(/background(-image)?\s*:\s*([^};]*)?url\(([^\)]+)\)([^;}]*)?/, function(match, $1, $2, url, $4) { - url = getString(url); - return PNG.test(url) ? "filter:" + format(PNG_FILTER, url, "crop") + - ";zoom:1;background" + ($1||"") + ":" + ($2||"") + "none" + ($4||"") : match; - }); - - // ----------------------------------------------------------------------- - // fix PNG transparency (HTML images) - // ----------------------------------------------------------------------- - - IE7.HTML.addRecalc("img,input", function(element) { - if (element.tagName == "INPUT" && element.type != "image") return; - fixImage(element); - addEventHandler(element, "onpropertychange", function() { - if (!printing && event.propertyName == "src" && - element.src.indexOf(BLANK_GIF) == -1) fixImage(element); - }); - }); - - // assume that background images should not be printed - // (if they are not transparent then they'll just obscure content) - // but we'll put foreground images back... - var printing = false; - addEventHandler(window, "onbeforeprint", function() { - printing = true; - for (var i = 0; i < filtered.length; i++) removeFilter(filtered[i]); - }); - addEventHandler(window, "onafterprint", function() { - for (var i = 0; i < filtered.length; i++) addFilter(filtered[i]); - printing = false; - }); -} - -// apply a filter -function addFilter(element, sizingMethod) { - var filter = element.filters[ALPHA_IMAGE_LOADER]; - if (filter) { - filter.src = element.src; - filter.enabled = true; - } else { - element.runtimeStyle.filter = format(PNG_FILTER, element.src, sizingMethod || "scale"); - filtered.push(element); - } - // remove the real image - element.src = BLANK_GIF; -}; - -function removeFilter(element) { - element.src = element.pngSrc; - element.filters[ALPHA_IMAGE_LOADER].enabled = false; -}; - -// ========================================================================= -// ie7-fixed.js -// ========================================================================= - -new function(_) { - if (appVersion >= 7) return; - - // some things to consider for this hack. - // the document body requires a fixed background. even if - // it is just a blank image. - // you have to use setExpression instead of onscroll, this - // together with a fixed body background helps avoid the - // annoying screen flicker of other solutions. - - IE7.CSS.addRecalc("position", "fixed", _positionFixed, "absolute"); - IE7.CSS.addRecalc("background(-attachment)?", "[^};]*fixed", _backgroundFixed); - - // scrolling is relative to the documentElement (HTML tag) when in - // standards mode, otherwise it's relative to the document body - var $viewport = quirksMode ? "body" : "documentElement"; - - function _fixBackground() { - // this is required by both position:fixed and background-attachment:fixed. - // it is necessary for the document to also have a fixed background image. - // we can fake this with a blank image if necessary - if (body.currentStyle.backgroundAttachment != "fixed") { - if (body.currentStyle.backgroundImage == "none") { - body.runtimeStyle.backgroundRepeat = "no-repeat"; - body.runtimeStyle.backgroundImage = "url(" + BLANK_GIF + ")"; // dummy - } - body.runtimeStyle.backgroundAttachment = "fixed"; - } - _fixBackground = Undefined; - }; - - var _tmp = createTempElement("img"); - - function _isFixed(element) { - return element ? isFixed(element) || _isFixed(element.parentElement) : false; - }; - - function _setExpression(element, propertyName, expression) { - setTimeout("document.all." + element.uniqueID + ".runtimeStyle.setExpression('" + propertyName + "','" + expression + "')", 0); - }; - - // ----------------------------------------------------------------------- - // backgroundAttachment: fixed - // ----------------------------------------------------------------------- - - function _backgroundFixed(element) { - if (register(_backgroundFixed, element, element.currentStyle.backgroundAttachment == "fixed" && !element.contains(body))) { - _fixBackground(); - bgLeft(element); - bgTop(element); - _backgroundPosition(element); - } - }; - - function _backgroundPosition(element) { - _tmp.src = element.currentStyle.backgroundImage.slice(5, -2); - var parentElement = element.canHaveChildren ? element : element.parentElement; - parentElement.appendChild(_tmp); - setOffsetLeft(element); - setOffsetTop(element); - parentElement.removeChild(_tmp); - }; - - function bgLeft(element) { - element.style.backgroundPositionX = element.currentStyle.backgroundPositionX; - if (!_isFixed(element)) { - _setExpression(element, "backgroundPositionX", "(parseInt(runtimeStyle.offsetLeft)+document." + $viewport + ".scrollLeft)||0"); - } - }; - eval(rotate(bgLeft)); - - function setOffsetLeft(element) { - var propertyName = _isFixed(element) ? "backgroundPositionX" : "offsetLeft"; - element.runtimeStyle[propertyName] = - getOffsetLeft(element, element.style.backgroundPositionX) - - element.getBoundingClientRect().left - element.clientLeft + 2; - }; - eval(rotate(setOffsetLeft)); - - function getOffsetLeft(element, position) { - switch (position) { - case "left": - case "top": - return 0; - case "right": - case "bottom": - return viewport.clientWidth - _tmp.offsetWidth; - case "center": - return (viewport.clientWidth - _tmp.offsetWidth) / 2; - default: - if (PERCENT.test(position)) { - return parseInt((viewport.clientWidth - _tmp.offsetWidth) * parseFloat(position) / 100); - } - _tmp.style.left = position; - return _tmp.offsetLeft; - } - }; - eval(rotate(getOffsetLeft)); - - // ----------------------------------------------------------------------- - // position: fixed - // ----------------------------------------------------------------------- - - function _positionFixed(element) { - if (register(_positionFixed, element, isFixed(element))) { - setOverrideStyle(element, "position", "absolute"); - setOverrideStyle(element, "left", element.currentStyle.left); - setOverrideStyle(element, "top", element.currentStyle.top); - _fixBackground(); - IE7.Layout.fixRight(element); - _foregroundPosition(element); - } - }; - - function _foregroundPosition(element, recalc) { - positionTop(element, recalc); - positionLeft(element, recalc, true); - if (!element.runtimeStyle.autoLeft && element.currentStyle.marginLeft == "auto" && - element.currentStyle.right != "auto") { - var left = viewport.clientWidth - getPixelWidth(element, element.currentStyle.right) - - getPixelWidth(element, element.runtimeStyle._left) - element.clientWidth; - if (element.currentStyle.marginRight == "auto") left = parseInt(left / 2); - if (_isFixed(element.offsetParent)) element.runtimeStyle.pixelLeft += left; - else element.runtimeStyle.shiftLeft = left; - } - clipWidth(element); - clipHeight(element); - }; - - function clipWidth(element) { - var fixWidth = element.runtimeStyle.fixWidth; - element.runtimeStyle.borderRightWidth = ""; - element.runtimeStyle.width = fixWidth ? getPixelWidth(element, fixWidth) : ""; - if (element.currentStyle.width != "auto") { - var rect = element.getBoundingClientRect(); - var width = element.offsetWidth - viewport.clientWidth + rect.left - 2; - if (width >= 0) { - element.runtimeStyle.borderRightWidth = "0px"; - width = Math.max(getPixelValue(element, element.currentStyle.width) - width, 0); - setOverrideStyle(element, "width", width); - return width; - } - } - }; - eval(rotate(clipWidth)); - - function positionLeft(element, recalc) { - // if the element's width is in % units then it must be recalculated - // with respect to the viewport - if (!recalc && PERCENT.test(element.currentStyle.width)) { - element.runtimeStyle.fixWidth = element.currentStyle.width; - } - if (element.runtimeStyle.fixWidth) { - element.runtimeStyle.width = getPixelWidth(element, element.runtimeStyle.fixWidth); - } - //if (recalc) { - // // if the element is fixed on the right then no need to recalculate - // if (!element.runtimeStyle.autoLeft) return; - //} else { - element.runtimeStyle.shiftLeft = 0; - element.runtimeStyle._left = element.currentStyle.left; - // is the element fixed on the right? - element.runtimeStyle.autoLeft = element.currentStyle.right != "auto" && - element.currentStyle.left == "auto"; - //} - // reset the element's "left" value and get its natural position - element.runtimeStyle.left = ""; - element.runtimeStyle.screenLeft = getScreenLeft(element); - element.runtimeStyle.pixelLeft = element.runtimeStyle.screenLeft; - // if the element is contained by another fixed element then there is no need to - // continually recalculate its left position - if (!recalc && !_isFixed(element.offsetParent)) { - // onsrcoll produces jerky movement, so we use an expression - _setExpression(element, "pixelLeft", "runtimeStyle.screenLeft+runtimeStyle.shiftLeft+document." + $viewport + ".scrollLeft"); - } - }; - // clone this function so we can do "top" - eval(rotate(positionLeft)); - - // I've forgotten how this works... - function getScreenLeft(element) { // thanks to kevin newman (captainn) - var screenLeft = element.offsetLeft, nested = 1; - if (element.runtimeStyle.autoLeft) { - screenLeft = viewport.clientWidth - element.offsetWidth - getPixelWidth(element, element.currentStyle.right); - } - // accommodate margins - if (element.currentStyle.marginLeft != "auto") { - screenLeft -= getPixelWidth(element, element.currentStyle.marginLeft); - } - while (element = element.offsetParent) { - if (element.currentStyle.position != "static") nested = -1; - screenLeft += element.offsetLeft * nested; - } - return screenLeft; - }; - eval(rotate(getScreenLeft)); - - function getPixelWidth(element, value) { - return PERCENT.test(value) ? parseInt(parseFloat(value) / 100 * viewport.clientWidth) : getPixelValue(element, value); - }; - eval(rotate(getPixelWidth)); - - // ----------------------------------------------------------------------- - // capture window resize - // ----------------------------------------------------------------------- - - function _resize() { - // if the window has been resized then some positions need to be - // recalculated (especially those aligned to "right" or "top" - var elements = _backgroundFixed.elements; - for (var i in elements) _backgroundPosition(elements[i]); - elements = _positionFixed.elements; - for (i in elements) { - _foregroundPosition(elements[i], true); - // do this twice to be sure - hackish, I know :-) - _foregroundPosition(elements[i], true); - } - _timer = 0; - }; - - // use a timer for some reason. - // (sometimes this is a good way to prevent resize loops) - var _timer; - addResize(function() { - if (!_timer) _timer = setTimeout(_resize, 0); - }); -}; - -// ========================================================================= -// ie7-oveflow.js -// ========================================================================= - -/* --------------------------------------------------------------------- - - This module alters the structure of the document. - It may adversely affect other CSS rules. Be warned. - ---------------------------------------------------------------------- */ - -var WRAPPER_STYLE = { - backgroundColor: "transparent", - backgroundImage: "none", - backgroundPositionX: null, - backgroundPositionY: null, - backgroundRepeat: null, - borderTopWidth: 0, - borderRightWidth: 0, - borderBottomWidth: 0, - borderLeftStyle: "none", - borderTopStyle: "none", - borderRightStyle: "none", - borderBottomStyle: "none", - borderLeftWidth: 0, - height: null, - marginTop: 0, - marginBottom: 0, - marginRight: 0, - marginLeft: 0, - width: "100%" -}; - -IE7.CSS.addRecalc("overflow", "visible", function(element) { - // don't do this again - if (element.parentNode.ie7_wrapped) return; - - // if max-height is applied, makes sure it gets applied first - if (IE7.Layout && element.currentStyle["max-height"] != "auto") { - IE7.Layout.maxHeight(element); - } - - if (element.currentStyle.marginLeft == "auto") element.style.marginLeft = 0; - if (element.currentStyle.marginRight == "auto") element.style.marginRight = 0; - - var wrapper = document.createElement(ANON); - wrapper.ie7_wrapped = element; - for (var propertyName in WRAPPER_STYLE) { - wrapper.style[propertyName] = element.currentStyle[propertyName]; - if (WRAPPER_STYLE[propertyName] != null) { - element.runtimeStyle[propertyName] = WRAPPER_STYLE[propertyName]; - } - } - wrapper.style.display = "block"; - wrapper.style.position = "relative"; - element.runtimeStyle.position = "absolute"; - element.parentNode.insertBefore(wrapper, element); - wrapper.appendChild(element); -}); - -// ========================================================================= -// ie7-quirks.js -// ========================================================================= - -function ie7Quirks() { - var FONT_SIZES = "xx-small,x-small,small,medium,large,x-large,xx-large".split(","); - for (var i = 0; i < FONT_SIZES.length; i++) { - FONT_SIZES[FONT_SIZES[i]] = FONT_SIZES[i - 1] || "0.67em"; - } - - IE7.CSS.addFix(/(font(-size)?\s*:\s*)([\w.-]+)/, function(match, label, size, value) { - return label + (FONT_SIZES[value] || value); - }); - - if (appVersion < 6) { - var NEGATIVE = /^\-/, LENGTH = /(em|ex)$/i; - var EM = /em$/i, EX = /ex$/i; - - getPixelValue = function(element, value) { - if (PIXEL.test(value)) return parseInt(value)||0; - var scale = NEGATIVE.test(value)? -1 : 1; - if (LENGTH.test(value)) scale *= getFontScale(element); - temp.style.width = (scale < 0) ? value.slice(1) : value; - body.appendChild(temp); - // retrieve pixel width - value = scale * temp.offsetWidth; - // remove the temporary element - temp.removeNode(); - return parseInt(value); - }; - - var temp = createTempElement(); - function getFontScale(element) { - var scale = 1; - temp.style.fontFamily = element.currentStyle.fontFamily; - temp.style.lineHeight = element.currentStyle.lineHeight; - //temp.style.fontSize = ""; - while (element != body) { - var fontSize = element.currentStyle["ie7-font-size"]; - if (fontSize) { - if (EM.test(fontSize)) scale *= parseFloat(fontSize); - else if (PERCENT.test(fontSize)) scale *= (parseFloat(fontSize) / 100); - else if (EX.test(fontSize)) scale *= (parseFloat(fontSize) / 2); - else { - temp.style.fontSize = fontSize; - return 1; - } - } - element = element.parentElement; - } - return scale; - }; - - // cursor:pointer (IE5.x) - IE7.CSS.addFix(/cursor\s*:\s*pointer/, "cursor:hand"); - // display:list-item (IE5.x) - IE7.CSS.addFix(/display\s*:\s*list-item/, "display:block"); - } - - // ----------------------------------------------------------------------- - // margin:auto - // ----------------------------------------------------------------------- - - function fixMargin(element) { - if (appVersion < 5.5) IE7.Layout.boxSizing(element.parentElement); - var parent = element.parentElement; - var margin = parent.offsetWidth - element.offsetWidth - getPaddingWidth(parent); - var autoRight = (element.currentStyle["ie7-margin"] && element.currentStyle.marginRight == "auto") || - element.currentStyle["ie7-margin-right"] == "auto"; - switch (parent.currentStyle.textAlign) { - case "right": - margin = autoRight ? parseInt(margin / 2) : 0; - element.runtimeStyle.marginRight = margin + "px"; - break; - case "center": - if (autoRight) margin = 0; - default: - if (autoRight) margin /= 2; - element.runtimeStyle.marginLeft = parseInt(margin) + "px"; - } - }; - - function getPaddingWidth(element) { - return getPixelValue(element, element.currentStyle.paddingLeft) + - getPixelValue(element, element.currentStyle.paddingRight); - }; - - IE7.CSS.addRecalc("margin(-left|-right)?", "[^};]*auto", function(element) { - if (register(fixMargin, element, - element.parentElement && - element.currentStyle.display == "block" && - element.currentStyle.marginLeft == "auto" && - element.currentStyle.position != "absolute")) { - fixMargin(element); - } - }); - - addResize(function() { - for (var i in fixMargin.elements) { - var element = fixMargin.elements[i]; - element.runtimeStyle.marginLeft = - element.runtimeStyle.marginRight = ""; - fixMargin(element); - } - }); -}; - - -// ----------------------------------------------------------------------- -// initialisation -// ----------------------------------------------------------------------- - -IE7.loaded = true; - -(function() { - try { - // http://javascript.nwbox.com/IEContentLoaded/ - documentElement.doScroll("left"); - } catch (e) { - setTimeout(arguments.callee, 1); - return; - } - // execute the inner text of the IE7 script - try { - eval(script.innerHTML); - } catch (e) { - // ignore errors - } - PNG = new RegExp(rescape(typeof IE7_PNG_SUFFIX == "string" ? IE7_PNG_SUFFIX : "-trans.png") + "$", "i"); - - // frequently used references - body = document.body; - viewport = quirksMode ? body : documentElement; - - // classes - body.className += " ie7_body"; - documentElement.className += " ie7_html"; - - if (quirksMode) ie7Quirks(); - - IE7.CSS.init(); - IE7.HTML.init(); - - IE7.HTML.apply(); - IE7.CSS.apply(); - - IE7.recalc(); -})(); - - -})(); +}function getScreenLeft(a){var b=a.offsetLeft,c=1;for(a.runtimeStyle.autoLeft&&(b=viewport.clientWidth-a.offsetWidth-getPixelWidth(a,a.currentStyle.right)),"auto"!=a.currentStyle.marginLeft&&(b-=getPixelWidth(a,a.currentStyle.marginLeft));a=a.offsetParent;)"static"!=a.currentStyle.position&&(c=-1),b+=a.offsetLeft*c;return b}function getPixelWidth(a,b){return PERCENT.test(b)?parseInt(parseFloat(b)/100*viewport.clientWidth):getPixelValue(a,b)}function _resize(){var a=_backgroundFixed.elements;for(var b in a)_backgroundPosition(a[b]);a=_positionFixed.elements;for(b in a)_foregroundPosition(a[b],!0),_foregroundPosition(a[b],!0);_timer=0}if(!(appVersion>=7)){IE7.CSS.addRecalc("position","fixed",_positionFixed,"absolute"),IE7.CSS.addRecalc("background(-attachment)?","[^};]*fixed",_backgroundFixed);var $viewport=quirksMode?"body":"documentElement",_tmp=createTempElement("img");eval(rotate(bgLeft)),eval(rotate(setOffsetLeft)),eval(rotate(getOffsetLeft)),eval(rotate(clipWidth)),eval(rotate(positionLeft)),eval(rotate(getScreenLeft)),eval(rotate(getPixelWidth));var _timer;addResize(function(){_timer||(_timer=setTimeout(_resize,0))})}};var WRAPPER_STYLE={backgroundColor:"transparent",backgroundImage:"none",backgroundPositionX:null,backgroundPositionY:null,backgroundRepeat:null,borderTopWidth:0,borderRightWidth:0,borderBottomWidth:0,borderLeftStyle:"none",borderTopStyle:"none",borderRightStyle:"none",borderBottomStyle:"none",borderLeftWidth:0,height:null,marginTop:0,marginBottom:0,marginRight:0,marginLeft:0,width:"100%"};IE7.CSS.addRecalc("overflow","visible",function(a){if(!a.parentNode.ie7_wrapped){IE7.Layout&&"auto"!=a.currentStyle["max-height"]&&IE7.Layout.maxHeight(a),"auto"==a.currentStyle.marginLeft&&(a.style.marginLeft=0),"auto"==a.currentStyle.marginRight&&(a.style.marginRight=0);var b=document.createElement(ANON);b.ie7_wrapped=a;for(var c in WRAPPER_STYLE)b.style[c]=a.currentStyle[c],null!=WRAPPER_STYLE[c]&&(a.runtimeStyle[c]=WRAPPER_STYLE[c]);b.style.display="block",b.style.position="relative",a.runtimeStyle.position="absolute",a.parentNode.insertBefore(b,a),b.appendChild(a)}}),IE7.loaded=!0,function(){try{documentElement.doScroll("left")}catch(e){return void setTimeout(arguments.callee,1)}try{eval(script.innerHTML)}catch(e){}PNG=new RegExp(rescape("string"==typeof IE7_PNG_SUFFIX?IE7_PNG_SUFFIX:"-trans.png")+"$","i"),body=document.body,viewport=quirksMode?body:documentElement,body.className+=" ie7_body",documentElement.className+=" ie7_html",quirksMode&&ie7Quirks(),IE7.CSS.init(),IE7.HTML.init(),IE7.HTML.apply(),IE7.CSS.apply(),IE7.recalc()}()}}(); +//# sourceMappingURL=../../../maps/libs/IE/IE7.js.map \ No newline at end of file diff --git a/static/scripts/libs/IE/IE8.js b/static/scripts/libs/IE/IE8.js index 0a758eab935..0899af208e2 100644 --- a/static/scripts/libs/IE/IE8.js +++ b/static/scripts/libs/IE/IE8.js @@ -1,2601 +1,3 @@ -// timestamp: Sun, 03 Feb 2008 19:26:22 -/* - IE7/IE8.js - copyright 2004-2008, Dean Edwards - http://dean.edwards.name/IE7/ - http://www.opensource.org/licenses/mit-license.php -*/ - -/* W3C compliance for Microsoft Internet Explorer */ - -/* credits/thanks: - Shaggy, Martijn Wargers, Jimmy Cerra, Mark D Anderson, - Lars Dieckow, Erik Arvidsson, Gellért Gyuris, James Denny, - Unknown W Brackets, Benjamin Westfarer, Rob Eberhardt, - Bill Edney, Kevin Newman, James Crompton, Matthew Mastracci, - Doug Wright, Richard York, Kenneth Kolano, MegaZone, - Thomas Verelst, Mark 'Tarquin' Wilton-Jones, Rainer Åhlfors, - David Zulaica, Ken Kolano, Kevin Newman -*/ - -// ======================================================================= -// TO DO -// ======================================================================= - -// PNG - unclickable content - -// ======================================================================= -// TEST/BUGGY -// ======================================================================= - -// hr{margin:1em auto} (doesn't look right in IE5) - -(function() { - -IE7 = { - toString: function(){return "IE7 version 2.0 (beta3)"} -}; -var appVersion = IE7.appVersion = navigator.appVersion.match(/MSIE (\d\.\d)/)[1]; - -if (/ie7_off/.test(top.location.search) || appVersion < 5) return; - -var Undefined = K(); -var quirksMode = document.compatMode != "CSS1Compat"; -var documentElement = document.documentElement, body, viewport; -var ANON = "!"; -var HEADER = ":link{ie7-link:link}:visited{ie7-link:visited}"; - -// ----------------------------------------------------------------------- -// external -// ----------------------------------------------------------------------- - -var RELATIVE = /^[\w\.]+[^:]*$/; -function makePath(href, path) { - if (RELATIVE.test(href)) href = (path || "") + href; - return href; -}; - -function getPath(href, path) { - href = makePath(href, path); - return href.slice(0, href.lastIndexOf("/") + 1); -}; - -// get the path to this script -var script = document.scripts[document.scripts.length - 1]; -var path = getPath(script.src); - -// we'll use microsoft's http request object to load external files -try { - var httpRequest = new ActiveXObject("Microsoft.XMLHTTP"); -} catch (e) { - // ActiveX disabled -} - -var fileCache = {}; -function loadFile(href, path) { -try { - href = makePath(href, path); - if (!fileCache[href]) { - // easy to load a file huh? - httpRequest.open("GET", href, false); - httpRequest.send(); - if (httpRequest.status == 0 || httpRequest.status == 200) { - fileCache[href] = httpRequest.responseText; - } - } -} catch (e) { - // ignore errors -} finally { - return fileCache[href] || ""; -}}; - -// ----------------------------------------------------------------------- -// IE5.0 compatibility -// ----------------------------------------------------------------------- - - -if (appVersion < 5.5) { - undefined = Undefined(); - - ANON = "HTML:!"; // for anonymous content - - // Fix String.replace (Safari1.x/IE5.0). - var GLOBAL = /(g|gi)$/; - var _String_replace = String.prototype.replace; - String.prototype.replace = function(expression, replacement) { - if (typeof replacement == "function") { // Safari doesn't like functions - if (expression && expression.constructor == RegExp) { - var regexp = expression; - var global = regexp.global; - if (global == null) global = GLOBAL.test(regexp); - // we have to convert global RexpExps for exec() to work consistently - if (global) regexp = new RegExp(regexp.source); // non-global - } else { - regexp = new RegExp(rescape(expression)); - } - var match, string = this, result = ""; - while (string && (match = regexp.exec(string))) { - result += string.slice(0, match.index) + replacement.apply(this, match); - string = string.slice(match.index + match[0].length); - if (!global) break; - } - return result + string; - } - return _String_replace.apply(this, arguments); - }; - - Array.prototype.pop = function() { - if (this.length) { - var i = this[this.length - 1]; - this.length--; - return i; - } - return undefined; - }; - - Array.prototype.push = function() { - for (var i = 0; i < arguments.length; i++) { - this[this.length] = arguments[i]; - } - return this.length; - }; - - var ns = this; - Function.prototype.apply = function(o, a) { - if (o === undefined) o = ns; - else if (o == null) o = window; - else if (typeof o == "string") o = new String(o); - else if (typeof o == "number") o = new Number(o); - else if (typeof o == "boolean") o = new Boolean(o); - if (arguments.length == 1) a = []; - else if (a[0] && a[0].writeln) a[0] = a[0].documentElement.document || a[0]; - var $ = "#ie7_apply", r; - o[$] = this; - switch (a.length) { // unroll for speed - case 0: r = o[$](); break; - case 1: r = o[$](a[0]); break; - case 2: r = o[$](a[0],a[1]); break; - case 3: r = o[$](a[0],a[1],a[2]); break; - case 4: r = o[$](a[0],a[1],a[2],a[3]); break; - case 5: r = o[$](a[0],a[1],a[2],a[3],a[4]); break; - default: - var b = [], i = a.length - 1; - do b[i] = "a[" + i + "]"; while (i--); - eval("r=o[$](" + b + ")"); - } - if (typeof o.valueOf == "function") { // not a COM object - delete o[$]; - } else { - o[$] = undefined; - if (r && r.writeln) r = r.documentElement.document || r; - } - return r; - }; - - Function.prototype.call = function(o) { - return this.apply(o, _slice.apply(arguments, [1])); - }; - - // block elements are "inline" according to IE5.0 so we'll fix it - HEADER += "address,blockquote,body,dd,div,dt,fieldset,form,"+ - "frame,frameset,h1,h2,h3,h4,h5,h6,iframe,noframes,object,p,"+ - "hr,applet,center,dir,menu,pre,dl,li,ol,ul{display:block}"; -} - -// ----------------------------------------------------------------------- -// OO support -// ----------------------------------------------------------------------- - - -// This is a cut-down version of base2 (http://code.google.com/p/base2/) - -var _slice = Array.prototype.slice; - -// private -var _FORMAT = /%([1-9])/g; -var _LTRIM = /^\s\s*/; -var _RTRIM = /\s\s*$/; -var _RESCAPE = /([\/()[\]{}|*+-.,^$?\\])/g; // safe regular expressions -var _BASE = /\bbase\b/; -var _HIDDEN = ["constructor", "toString"]; // only override these when prototyping - -var prototyping; - -function Base(){}; -Base.extend = function(_instance, _static) { - // Build the prototype. - prototyping = true; - var _prototype = new this; - extend(_prototype, _instance); - prototyping = false; - - // Create the wrapper for the constructor function. - var _constructor = _prototype.constructor; - function klass() { - // Don't call the constructor function when prototyping. - if (!prototyping) _constructor.apply(this, arguments); - }; - _prototype.constructor = klass; - - // Build the static interface. - klass.extend = arguments.callee; - extend(klass, _static); - klass.prototype = _prototype; - return klass; -}; -Base.prototype.extend = function(source) { - return extend(this, source); -}; - -// A collection of regular expressions and their associated replacement values. -// A Base class for creating parsers. - -var _HASH = "#"; -var _KEYS = "~"; - -var _RG_ESCAPE_CHARS = /\\./g; -var _RG_ESCAPE_BRACKETS = /\(\?[:=!]|\[[^\]]+\]/g; -var _RG_BRACKETS = /\(/g; - -var RegGrp = Base.extend({ - constructor: function(values) { - this[_KEYS] = []; - this.merge(values); - }, - - exec: function(string) { - var items = this, keys = this[_KEYS]; - return String(string).replace(new RegExp(this, this.ignoreCase ? "gi" : "g"), function() { - var item, offset = 1, i = 0; - // Loop through the RegGrp items. - while ((item = items[_HASH + keys[i++]])) { - var next = offset + item.length + 1; - if (arguments[offset]) { // do we have a result? - var replacement = item.replacement; - switch (typeof replacement) { - case "function": - return replacement.apply(items, _slice.call(arguments, offset, next)); - case "number": - return arguments[offset + replacement]; - default: - return replacement; - } - } - offset = next; - } - }); - }, - - add: function(expression, replacement) { - if (expression instanceof RegExp) { - expression = expression.source; - } - if (!this[_HASH + expression]) this[_KEYS].push(String(expression)); - this[_HASH + expression] = new RegGrp.Item(expression, replacement); - }, - - merge: function(values) { - for (var i in values) this.add(i, values[i]); - }, - - toString: function() { - // back references not supported in simple RegGrp - return "(" + this[_KEYS].join(")|(") + ")"; - } -}, { - IGNORE: "$0", - - Item: Base.extend({ - constructor: function(expression, replacement) { - expression = expression instanceof RegExp ? expression.source : String(expression); - - if (typeof replacement == "number") replacement = String(replacement); - else if (replacement == null) replacement = ""; - - // does the pattern use sub-expressions? - if (typeof replacement == "string" && /\$(\d+)/.test(replacement)) { - // a simple lookup? (e.g. "$2") - if (/^\$\d+$/.test(replacement)) { - // store the index (used for fast retrieval of matched strings) - replacement = parseInt(replacement.slice(1)); - } else { // a complicated lookup (e.g. "Hello $2 $1") - // build a function to do the lookup - var Q = /'/.test(replacement.replace(/\\./g, "")) ? '"' : "'"; - replacement = replacement.replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\$(\d+)/g, Q + - "+(arguments[$1]||" + Q+Q + ")+" + Q); - replacement = new Function("return " + Q + replacement.replace(/(['"])\1\+(.*)\+\1\1$/, "$1") + Q); - } - } - - this.length = RegGrp.count(expression); - this.replacement = replacement; - this.toString = K(expression); - } - }), - - count: function(expression) { - // Count the number of sub-expressions in a RegExp/RegGrp.Item. - expression = String(expression).replace(_RG_ESCAPE_CHARS, "").replace(_RG_ESCAPE_BRACKETS, ""); - return match(expression, _RG_BRACKETS).length; - } -}); - -// ========================================================================= -// lang/extend.js -// ========================================================================= - -function extend(object, source) { // or extend(object, key, value) - if (object && source) { - var proto = (typeof source == "function" ? Function : Object).prototype; - // Add constructor, toString etc - var i = _HIDDEN.length, key; - if (prototyping) while (key = _HIDDEN[--i]) { - var value = source[key]; - if (value != proto[key]) { - if (_BASE.test(value)) { - _override(object, key, value) - } else { - object[key] = value; - } - } - } - // Copy each of the source object's properties to the target object. - for (key in source) if (proto[key] === undefined) { - var value = source[key]; - // Check for method overriding. - if (object[key] && typeof value == "function" && _BASE.test(value)) { - _override(object, key, value); - } else { - object[key] = value; - } - } - } - return object; -}; - -function _override(object, name, method) { - // Override an existing method. - var ancestor = object[name]; - object[name] = function() { - var previous = this.base; - this.base = ancestor; - var returnValue = method.apply(this, arguments); - this.base = previous; - return returnValue; - }; -}; - -function combine(keys, values) { - // Combine two arrays to make a hash. - if (!values) values = keys; - var hash = {}; - for (var i in keys) hash[i] = values[i]; - return hash; -}; - -function format(string) { - // Replace %n with arguments[n]. - // e.g. format("%1 %2%3 %2a %1%3", "she", "se", "lls"); - // ==> "she sells sea shells" - // Only %1 - %9 supported. - var args = arguments; - var _FORMAT = new RegExp("%([1-" + arguments.length + "])", "g"); - return String(string).replace(_FORMAT, function(match, index) { - return index < args.length ? args[index] : match; - }); -}; - -function match(string, expression) { - // Same as String.match() except that this function will return an empty - // array if there is no match. - return String(string).match(expression) || []; -}; - -function rescape(string) { - // Make a string safe for creating a RegExp. - return String(string).replace(_RESCAPE, "\\$1"); -}; - -// http://blog.stevenlevithan.com/archives/faster-trim-javascript -function trim(string) { - return String(string).replace(_LTRIM, "").replace(_RTRIM, ""); -}; - -function K(k) { - return function() { - return k; - }; -}; - -// ----------------------------------------------------------------------- -// parsing -// ----------------------------------------------------------------------- - -var Parser = RegGrp.extend({ignoreCase: true}); - -var ENCODED = /\x01(\d+)/g, - QUOTES = /'/g, - STRING = /^\x01/, - UNICODE = /\\([\da-fA-F]{1,4})/g; - -var _strings = []; - -var encoder = new Parser({ - // comments - "": "", - "\\/\\*[^*]*\\*+([^\\/][^*]*\\*+)*\\/": "", - // get rid - "@(namespace|import)[^;\\n]+[;\\n]": "", - // strings - "'(\\\\.|[^'\\\\])*'": encodeString, - '"(\\\\.|[^"\\\\])*"': encodeString, - // white space - "\\s+": " " -}); - -function encode(cssText) { - return encoder.exec(cssText); -}; - -function decode(cssText) { - return cssText.replace(ENCODED, function(match, index) { - return _strings[index - 1]; - }); -}; - -function encodeString(string) { - return "\x01" + _strings.push(string.replace(UNICODE, function(match, chr) { - return eval("'\\u" + "0000".slice(chr.length) + chr + "'"); - }).slice(1, -1).replace(QUOTES, "\\'")); -}; - -function getString(value) { - return STRING.test(value) ? _strings[value.slice(1) - 1] : value; -}; - -// clone a "width" function to create a "height" function -var rotater = new RegGrp({ - Width: "Height", - width: "height", - Left: "Top", - left: "top", - Right: "Bottom", - right: "bottom", - onX: "onY" -}); - -function rotate(fn) { - return rotater.exec(fn); -}; - -// ----------------------------------------------------------------------- -// event handling -// ----------------------------------------------------------------------- - -var eventHandlers = []; - -function addResize(handler) { - addRecalc(handler); - addEventHandler(window, "onresize", handler); -}; - -// add an event handler (function) to an element -function addEventHandler(element, type, handler) { - element.attachEvent(type, handler); - // store the handler so it can be detached later - eventHandlers.push(arguments); -}; - -// remove an event handler assigned to an element by IE7 -function removeEventHandler(element, type, handler) { -try { - element.detachEvent(type, handler); -} catch (ignore) { - // write a letter of complaint to microsoft.. -}}; - -// remove event handlers (they eat memory) -addEventHandler(window, "onunload", function() { - var handler; - while (handler = eventHandlers.pop()) { - removeEventHandler(handler[0], handler[1], handler[2]); - } -}); - -function register(handler, element, condition) { // -@DRE - //var set = handler[element.uniqueID]; - if (!handler.elements) handler.elements = {}; - if (condition) handler.elements[element.uniqueID] = element; - else delete handler.elements[element.uniqueID]; - //return !set && condition; - return condition; -}; - -addEventHandler(window, "onbeforeprint", function() { - if (!IE7.CSS.print) new StyleSheet("print"); - IE7.CSS.print.recalc(); -}); - -// ----------------------------------------------------------------------- -// pixel conversion -// ----------------------------------------------------------------------- - -// this is handy because it means that web developers can mix and match -// measurement units in their style sheets. it is not uncommon to -// express something like padding in "em" units whilst border thickness -// is most often expressed in pixels. - -var PIXEL = /^\d+(px)?$/i; -var PERCENT = /^\d+%$/; -var getPixelValue = function(element, value) { - if (PIXEL.test(value)) return parseInt(value); - var style = element.style.left; - var runtimeStyle = element.runtimeStyle.left; - element.runtimeStyle.left = element.currentStyle.left; - element.style.left = value || 0; - value = element.style.pixelLeft; - element.style.left = style; - element.runtimeStyle.left = runtimeStyle; - return value; -}; - -// ----------------------------------------------------------------------- -// generic -// ----------------------------------------------------------------------- - -var $IE7 = "ie7-"; - -var Fix = Base.extend({ - constructor: function() { - this.fixes = []; - this.recalcs = []; - }, - init: Undefined -}); - -// a store for functions that will be called when refreshing IE7 -var recalcs = []; -function addRecalc(recalc) { - recalcs.push(recalc); -}; - -IE7.recalc = function() { - IE7.HTML.recalc(); - // re-apply style sheet rules (re-calculate ie7 classes) - IE7.CSS.recalc(); - // apply global fixes to the document - for (var i = 0; i < recalcs.length; i++) recalcs[i](); -}; - -function isFixed(element) { - return element.currentStyle["ie7-position"] == "fixed"; -}; - -// original style -function getDefinedStyle(element, propertyName) { - return element.currentStyle[$IE7 + propertyName] || element.currentStyle[propertyName]; -}; - -function setOverrideStyle(element, propertyName, value) { - if (element.currentStyle[$IE7 + propertyName] == null) { - element.runtimeStyle[$IE7 + propertyName] = element.currentStyle[propertyName]; - } - element.runtimeStyle[propertyName] = value; -}; - -// create a temporary element which is used to inherit styles -// from the target element. the temporary element can be resized -// to determine pixel widths/heights -function createTempElement(tagName) { - var element = document.createElement(tagName || "object"); - element.style.cssText = "position:absolute;padding:0;display:block;border:none;clip:rect(0 0 0 0);left:-9999"; - element.ie7_anon = true; - return element; -}; - - -// ========================================================================= -// ie7-cssQuery.js -// ========================================================================= - -function cssQuery(selector, context, single) { - if (!_cache[selector]) { - reg = []; // store for RegExp objects - var fn = ""; - var selectors = cssParser.escape(selector).split(","); - for (var i = 0; i < selectors.length; i++) { - _wild = _index = _list = 0; // reset - _duplicate = selectors.length > 1 ? 2 : 0; // reset - var block = cssParser.exec(selectors[i]) || "if(0){"; - if (_wild) { // IE's pesky comment nodes - block += format("if(e%1.nodeName!='!'){", _index); - } - // check for duplicates before storing results - var store = _duplicate > 1 ? _TEST : ""; - block += format(store + _STORE, _index); - // add closing braces - block += Array(match(block, /\{/g).length + 1).join("}"); - fn += block; - } - eval(format(_FN, reg) + cssParser.unescape(fn) + "return s?null:r}"); - _cache[selector] = _selectorFunction; - } - return _cache[selector](context || document, single); -}; - -var _MSIE5 = appVersion < 6; - -var _EVALUATED = /^(href|src)$/; -var _ATTRIBUTES = { - "class": "className", - "for": "htmlFor" -}; - -IE7._indexed = 1; - -IE7._byId = function(document, id) { - var result = document.all[id] || null; - // returns a single element or a collection - if (!result || result.id == id) return result; - // document.all has returned a collection of elements with name/id - for (var i = 0; i < result.length; i++) { - if (result[i].id == id) return result[i]; - } - return null; -}; - -IE7._getAttribute = function(element, name) { - if (name == "src" && element.pngSrc) return element.pngSrc; - - var attribute = _MSIE5 ? (element.attributes[name] || element.attributes[_ATTRIBUTES[name.toLowerCase()]]) : element.getAttributeNode(name); - if (attribute && (attribute.specified || name == "value")) { - if (_EVALUATED.test(name)) { - return element.getAttribute(name, 2); - } else if (name == "class") { - return element.className.replace(/\sie7_\w+/g, ""); - } else if (name == "style") { - return element.style.cssText; - } else { - return attribute.nodeValue; - } - } - return null; -}; - -var names = "colSpan,rowSpan,vAlign,dateTime,accessKey,tabIndex,encType,maxLength,readOnly,longDesc"; -// Convert the list of strings to a hash, mapping the lowercase name to the camelCase name. -extend(_ATTRIBUTES, combine(names.toLowerCase().split(","), names.split(","))); - -IE7._getNextElementSibling = function(node) { - // return the next element to the supplied element - // nextSibling is not good enough as it might return a text or comment node - while (node && (node = node.nextSibling) && (node.nodeType != 1 || node.nodeName == "!")) continue; - return node; -}; - -IE7._getPreviousElementSibling = function(node) { - // return the previous element to the supplied element - while (node && (node = node.previousSibling) && (node.nodeType != 1 || node.nodeName == "!")) continue; - return node; -}; - -// ========================================================================= -// CSSParser -// ========================================================================= - -var IMPLIED_ASTERISK = /([\s>+~,]|[^(]\+|^)([#.:\[])/g, - IMPLIED_SPACE = /(^|,)([^\s>+~])/g, - WHITESPACE = /\s*([\s>+~(),]|^|$)\s*/g, - WILD_CARD = /\s\*\s/g;; - -var CSSParser = RegGrp.extend({ - constructor: function(items) { - this.base(items); - this.sorter = new RegGrp; - this.sorter.add(/:not\([^)]*\)/, RegGrp.IGNORE); - this.sorter.add(/([ >](\*|[\w-]+))([^: >+~]*)(:\w+-child(\([^)]+\))?)([^: >+~]*)/, "$1$3$6$4"); - }, - - ignoreCase: true, - - escape: function(selector) { - return this.optimise(this.format(selector)); - }, - - format: function(selector) { - return selector - .replace(WHITESPACE, "$1") - .replace(IMPLIED_SPACE, "$1 $2") - .replace(IMPLIED_ASTERISK, "$1*$2"); - }, - - optimise: function(selector) { - // optimise wild card descendant selectors - return this.sorter.exec(selector.replace(WILD_CARD, ">* ")); - }, - - unescape: function(selector) { - return decode(selector); - } -}); - -// some constants -var _OPERATORS = { - "": "%1!=null", - "=": "%1=='%2'", - "~=": /(^| )%1( |$)/, - "|=": /^%1(-|$)/, - "^=": /^%1/, - "$=": /%1$/, - "*=": /%1/ -}; - -var _PSEUDO_CLASSES = { - "first-child": "!IE7._getPreviousElementSibling(e%1)", - "link": "e%1.currentStyle['ie7-link']=='link'", - "visited": "e%1.currentStyle['ie7-link']=='visited'" -}; - -var _VAR = "var p%2=0,i%2,e%2,n%2=e%1."; -var _ID = "e%1.sourceIndex"; -var _TEST = "var g=" + _ID + ";if(!p[g]){p[g]=1;"; -var _STORE = "r[r.length]=e%1;if(s)return e%1;"; -var _FN = "var _selectorFunction=function(e0,s){IE7._indexed++;var r=[],p={},reg=[%1],d=document;"; -var reg; // a store for RexExp objects -var _index; -var _wild; // need to flag certain _wild card selectors as MSIE includes comment nodes -var _list; // are we processing a node _list? -var _duplicate; // possible duplicates? -var _cache = {}; // store parsed selectors - -// a hideous parser -var cssParser = new CSSParser({ - " (\\*|[\\w-]+)#([\\w-]+)": function(match, tagName, id) { // descendant selector followed by ID - _wild = false; - var replacement = "var e%2=IE7._byId(d,'%4');if(e%2&&"; - if (tagName != "*") replacement += "e%2.nodeName=='%3'&&"; - replacement += "(e%1==d||e%1.contains(e%2))){"; - if (_list) replacement += format("i%1=n%1.length;", _list); - return format(replacement, _index++, _index, tagName.toUpperCase(), id); - }, - - " (\\*|[\\w-]+)": function(match, tagName) { // descendant selector - _duplicate++; // this selector may produce duplicates - _wild = tagName == "*"; - var replacement = _VAR; - // IE5.x does not support getElementsByTagName("*"); - replacement += (_wild && _MSIE5) ? "all" : "getElementsByTagName('%3')"; - replacement += ";for(i%2=0;(e%2=n%2[i%2]);i%2++){"; - return format(replacement, _index++, _list = _index, tagName.toUpperCase()); - }, - - ">(\\*|[\\w-]+)": function(match, tagName) { // child selector - var children = _list; - _wild = tagName == "*"; - var replacement = _VAR; - // use the children property for MSIE as it does not contain text nodes - // (but the children collection still includes comments). - // the document object does not have a children collection - replacement += children ? "children": "childNodes"; - if (!_wild && children) replacement += ".tags('%3')"; - replacement += ";for(i%2=0;(e%2=n%2[i%2]);i%2++){"; - if (_wild) { - replacement += "if(e%2.nodeType==1){"; - _wild = _MSIE5; - } else { - if (!children) replacement += "if(e%2.nodeName=='%3'){"; - } - return format(replacement, _index++, _list = _index, tagName.toUpperCase()); - }, - - "\\+(\\*|[\\w-]+)": function(match, tagName) { // direct adjacent selector - var replacement = ""; - if (_wild) replacement += "if(e%1.nodeName!='!'){"; - _wild = false; - replacement += "e%1=IE7._getNextElementSibling(e%1);if(e%1"; - if (tagName != "*") replacement += "&&e%1.nodeName=='%2'"; - replacement += "){"; - return format(replacement, _index, tagName.toUpperCase()); - }, - - "~(\\*|[\\w-]+)": function(match, tagName) { // indirect adjacent selector - var replacement = ""; - if (_wild) replacement += "if(e%1.nodeName!='!'){"; - _wild = false; - _duplicate = 2; // this selector may produce duplicates - replacement += "while(e%1=e%1.nextSibling){if(e%1.ie7_adjacent==IE7._indexed)break;if("; - if (tagName == "*") { - replacement += "e%1.nodeType==1"; - if (_MSIE5) replacement += "&&e%1.nodeName!='!'"; - } else replacement += "e%1.nodeName=='%2'"; - replacement += "){e%1.ie7_adjacent=IE7._indexed;"; - return format(replacement, _index, tagName.toUpperCase()); - }, - - "#([\\w-]+)": function(match, id) { // ID selector - _wild = false; - var replacement = "if(e%1.id=='%2'){"; - if (_list) replacement += format("i%1=n%1.length;", _list); - return format(replacement, _index, id); - }, - - "\\.([\\w-]+)": function(match, className) { // class selector - _wild = false; - // store RegExp objects - slightly faster on IE - reg.push(new RegExp("(^|\\s)" + rescape(className) + "(\\s|$)")); - return format("if(e%1.className&®[%2].test(e%1.className)){", _index, reg.length - 1); - }, - - "\\[([\\w-]+)\\s*([^=]?=)?\\s*([^\\]]*)\\]": function(match, attr, operator, value) { // attribute selectors - var alias = _ATTRIBUTES[attr] || attr; - if (operator) { - var getAttribute = "e%1.getAttribute('%2',2)"; - if (!_EVALUATED.test(attr)) { - getAttribute = "e%1.%3||" + getAttribute; - } - attr = format("(" + getAttribute + ")", _index, attr, alias); - } else { - attr = format("IE7._getAttribute(e%1,'%2')", _index, attr); - } - var replacement = _OPERATORS[operator || ""] || "0"; - if (replacement && replacement.source) { - reg.push(new RegExp(format(replacement.source, rescape(cssParser.unescape(value))))); - replacement = "reg[%2].test(%1)"; - value = reg.length - 1; - } - return "if(" + format(replacement, attr, value) + "){"; - }, - - ":+([\\w-]+)(\\(([^)]+)\\))?": function(match, pseudoClass, $2, args) { // pseudo class selectors - pseudoClass = _PSEUDO_CLASSES[pseudoClass]; - return "if(" + (pseudoClass ? format(pseudoClass, _index, args || "") : "0") + "){"; - } -}); - -// ========================================================================= -// ie7-css.js -// ========================================================================= - -var HYPERLINK = /a(#[\w-]+)?(\.[\w-]+)?:(hover|active)/i; -var BRACE1 = /\s*\{\s*/, BRACE2 = /\s*\}\s*/, COMMA = /\s*\,\s*/; -var FIRST_LINE_LETTER = /(.*)(:first-(line|letter))/; - -//var UNKNOWN = /UNKNOWN|([:.])\w+\1/i; - -var styleSheets = document.styleSheets; - -IE7.CSS = new (Fix.extend({ // single instance - parser: new Parser, - screen: "", - print: "", - styles: [], - rules: [], - pseudoClasses: appVersion < 7 ? "first\\-child" : "", - dynamicPseudoClasses: { - toString: function() { - var strings = []; - for (var pseudoClass in this) strings.push(pseudoClass); - return strings.join("|"); - } - }, - - init: function() { - var NONE = "^\x01$"; - var CLASS = "\\[class=?[^\\]]*\\]"; - var pseudoClasses = []; - if (this.pseudoClasses) pseudoClasses.push(this.pseudoClasses); - var dynamicPseudoClasses = this.dynamicPseudoClasses.toString(); - if (dynamicPseudoClasses) pseudoClasses.push(dynamicPseudoClasses); - pseudoClasses = pseudoClasses.join("|"); - var unknown = appVersion < 7 ? ["[>+~[(]|([:.])\\w+\\1"] : [CLASS]; - if (pseudoClasses) unknown.push(":(" + pseudoClasses + ")"); - this.UNKNOWN = new RegExp(unknown.join("|") || NONE, "i"); - var complex = appVersion < 7 ? ["\\[[^\\]]+\\]|[^\\s(\\[]+\\s*[+~]"] : [CLASS]; - var complexRule = complex.concat(); - if (pseudoClasses) complexRule.push(":(" + pseudoClasses + ")"); - Rule.COMPLEX = new RegExp(complexRule.join("|") || NONE, "ig"); - if (this.pseudoClasses) complex.push(":(" + this.pseudoClasses + ")"); - DynamicRule.COMPLEX = new RegExp(complex.join("|") || NONE, "i"); - DynamicRule.MATCH = new RegExp(dynamicPseudoClasses ? "(.*):(" + dynamicPseudoClasses + ")(.*)" : NONE, "i"); - - this.createStyleSheet(); - this.refresh(); - }, - - addEventHandler: function() { - addEventHandler.apply(null, arguments); - }, - - addFix: function(expression, replacement) { - this.parser.add(expression, replacement); - }, - - addRecalc: function(propertyName, test, handler, replacement) { - // recalcs occur whenever the document is refreshed using document.recalc() - test = new RegExp("([{;\\s])" + propertyName + "\\s*:\\s*" + test + "[^;}]*"); - var id = this.recalcs.length; - if (replacement) replacement = propertyName + ":" + replacement; - this.addFix(test, function(match, $1) { - return (replacement ? $1 + replacement : match) + ";ie7-" + match.slice(1) + ";ie7_recalc" + id + ":1"; - }); - this.recalcs.push(arguments); - return id; - }, - - apply: function() { - this.getInlineStyles(); - new StyleSheet("screen"); - this.trash(); - }, - - createStyleSheet: function() { - // create the IE7 style sheet - this.styleSheet = document.createStyleSheet(); - // flag it so we can ignore it during parsing - this.styleSheet.ie7 = true; - this.styleSheet.owningElement.ie7 = true; - this.styleSheet.cssText = HEADER; - }, - - getInlineStyles: function() { - // load inline styles - var styleSheets = document.getElementsByTagName("style"), styleSheet; - for (var i = styleSheets.length - 1; (styleSheet = styleSheets[i]); i--) { - if (!styleSheet.disabled && !styleSheet.ie7) { - this.styles.push(styleSheet.innerHTML); - } - } - }, - - getText: function(styleSheet, path) { - // explorer will trash unknown selectors (it converts them to "UNKNOWN"). - // so we must reload external style sheets (internal style sheets can have their text - // extracted through the innerHTML property). - // load the style sheet text from an external file - try { - var cssText = styleSheet.cssText; - } catch (e) { - cssText = ""; - } - if (httpRequest) cssText = loadFile(styleSheet.href, path) || cssText; - return cssText; - }, - - recalc: function() { - this.screen.recalc(); - // we're going to read through all style rules. - // certain rules have had ie7 properties added to them. - // e.g. p{top:0; ie7_recalc2:1; left:0} - // this flags a property in the rule as needing a fix. - // the selector text is then used to query the document. - // we can then loop through the results of the query - // and fix the elements. - // we ignore the IE7 rules - so count them in the header - var RECALCS = /ie7_recalc\d+/g; - var start = HEADER.match(/[{,]/g).length; - // only calculate screen fixes. print fixes don't show up anyway - var stop = start + (this.screen.cssText.match(/\{/g)||"").length; - var rules = this.styleSheet.rules, rule; - var calcs, calc, elements, element, i, j, k, id; - // loop through all rules - for (i = start; i < stop; i++) { - rule = rules[i]; - var cssText = rule.style.cssText; - // search for the "ie7_recalc" flag (there may be more than one) - if (rule && (calcs = cssText.match(RECALCS))) { - // use the selector text to query the document - elements = cssQuery(rule.selectorText); - // if there are matching elements then loop - // through the recalc functions and apply them - // to each element - if (elements.length) for (j = 0; j < calcs.length; j++) { - // get the matching flag (e.g. ie7_recalc3) - id = calcs[j]; - // extract the numeric id from the end of the flag - // and use it to index the collection of recalc - // functions - calc = IE7.CSS.recalcs[id.slice(10)][2]; - for (k = 0; (element = elements[k]); k++) { - // apply the fix - if (element.currentStyle[id]) calc(element, cssText); - } - } - } - } - }, - - refresh: function() { - this.styleSheet.cssText = HEADER + this.screen + this.print; - }, - - trash: function() { - // trash the old style sheets - for (var i = 0; i < styleSheets.length; i++) { - if (!styleSheets[i].ie7) { - try { - var cssText = styleSheets[i].cssText; - } catch (e) { - cssText = ""; - } - if (cssText) styleSheets[i].cssText = ""; - } - } - } -})); - -// ----------------------------------------------------------------------- -// IE7 StyleSheet class -// ----------------------------------------------------------------------- - -var StyleSheet = Base.extend({ - constructor: function(media) { - this.media = media; - this.load(); - IE7.CSS[media] = this; - IE7.CSS.refresh(); - }, - - createRule: function(selector, cssText) { - if (IE7.CSS.UNKNOWN.test(selector)) { - var match; - if (PseudoElement && (match = selector.match(PseudoElement.MATCH))) { - return new PseudoElement(match[1], match[2], cssText); - } else if (match = selector.match(DynamicRule.MATCH)) { - if (!HYPERLINK.test(match[0]) || DynamicRule.COMPLEX.test(match[0])) { - return new DynamicRule(selector, match[1], match[2], match[3], cssText); - } - } else return new Rule(selector, cssText); - } - return selector + " {" + cssText + "}"; - }, - - getText: function() { - // store for style sheet text - var _inlineStyles = [].concat(IE7.CSS.styles); - // parse media decalarations - var MEDIA = /@media\s+([^{]*)\{([^@]+\})\s*\}/gi; - var ALL = /\ball\b|^$/i, SCREEN = /\bscreen\b/i, PRINT = /\bprint\b/i; - function _parseMedia(cssText, media) { - _filterMedia.value = media; - return cssText.replace(MEDIA, _filterMedia); - }; - function _filterMedia(match, media, cssText) { - media = _simpleMedia(media); - switch (media) { - case "screen": - case "print": - if (media != _filterMedia.value) return ""; - case "all": - return cssText; - } - return ""; - }; - function _simpleMedia(media) { - if (ALL.test(media)) return "all"; - else if (SCREEN.test(media)) return (PRINT.test(media)) ? "all" : "screen"; - else if (PRINT.test(media)) return "print"; - }; - var self = this; - function _getCSSText(styleSheet, path, media, level) { - var cssText = ""; - if (!level) { - media = _simpleMedia(styleSheet.media); - level = 0; - } - if (media == "all" || media == self.media) { - // IE only allows importing style sheets three levels deep. - // it will crash if you try to access a level below this - if (level < 3) { - // loop through imported style sheets - for (var i = 0; i < styleSheet.imports.length; i++) { - // call this function recursively to get all imported style sheets - cssText += _getCSSText(styleSheet.imports[i], getPath(styleSheet.href, path), media, level + 1); - } - } - // retrieve inline style or load an external style sheet - cssText += encode(styleSheet.href ? _loadStyleSheet(styleSheet, path) : _inlineStyles.pop() || ""); - cssText = _parseMedia(cssText, self.media); - } - return cssText; - }; - // store loaded cssText URLs - var fileCache = {}; - // load an external style sheet - function _loadStyleSheet(styleSheet, path) { - var url = makePath(styleSheet.href, path); - // if the style sheet has already loaded then don't duplicate it - if (fileCache[url]) return ""; - // load from source - fileCache[url] = (styleSheet.disabled) ? "" : - _fixUrls(IE7.CSS.getText(styleSheet, path), getPath(styleSheet.href, path)); - return fileCache[url]; - }; - // fix css paths - // we're lumping all css text into one big style sheet so relative - // paths have to be fixed. this is necessary anyway because of other - // explorer bugs. - var URL = /(url\s*\(\s*['"]?)([\w\.]+[^:\)]*['"]?\))/gi; - function _fixUrls(cssText, pathname) { - // hack & slash - return cssText.replace(URL, "$1" + pathname.slice(0, pathname.lastIndexOf("/") + 1) + "$2"); - }; - - // load all style sheets in the document - for (var i = 0; i < styleSheets.length; i++) { - if (!styleSheets[i].disabled && !styleSheets[i].ie7) { - this.cssText += _getCSSText(styleSheets[i]); - } - } - }, - - load: function() { - this.cssText = ""; - this.getText(); - this.parse(); - this.cssText = decode(this.cssText); - fileCache = {}; - }, - - parse: function() { - this.cssText = IE7.CSS.parser.exec(this.cssText); - - // parse the style sheet - var offset = IE7.CSS.rules.length; - var rules = this.cssText.split(BRACE2), rule; - var selectors, cssText, i, j; - for (i = 0; i < rules.length; i++) { - rule = rules[i].split(BRACE1); - selectors = rule[0].split(COMMA); - cssText = rule[1]; - for (j = 0; j < selectors.length; j++) { - selectors[j] = cssText ? this.createRule(selectors[j], cssText) : ""; - } - rules[i] = selectors.join("\n"); - } - this.cssText = rules.join("\n"); - this.rules = IE7.CSS.rules.slice(offset); - }, - - recalc: function() { - var rule, i; - for (i = 0; (rule = this.rules[i]); i++) rule.recalc(); - }, - - toString: function() { - return "@media " + this.media + "{" + this.cssText + "}"; - } -}); - -var PseudoElement; - -// ----------------------------------------------------------------------- -// IE7 style rules -// ----------------------------------------------------------------------- - -var Rule = IE7.Rule = Base.extend({ - // properties - constructor: function(selector, cssText) { - this.id = IE7.CSS.rules.length; - this.className = Rule.PREFIX + this.id; - selector = selector.match(FIRST_LINE_LETTER) || selector || "*"; - this.selector = selector[1] || selector; - this.selectorText = this.parse(this.selector) + (selector[2] || ""); - this.cssText = cssText; - this.MATCH = new RegExp("\\s" + this.className + "(\\s|$)", "g"); - IE7.CSS.rules.push(this); - this.init(); - }, - - init: Undefined, - - add: function(element) { - // allocate this class - element.className += " " + this.className; - }, - - recalc: function() { - // execute the underlying css query for this class - var match = cssQuery(this.selector); - // add the class name for all matching elements - for (var i = 0; i < match.length; i++) this.add(match[i]); - }, - - parse: function(selector) { - // attempt to preserve specificity for "loose" parsing by - // removing unknown tokens from a css selector but keep as - // much as we can.. - var simple = selector.replace(Rule.CHILD, " ").replace(Rule.COMPLEX, ""); - if (appVersion < 7) simple = simple.replace(Rule.MULTI, ""); - var tags = match(simple, Rule.TAGS).length - match(selector, Rule.TAGS).length; - var classes = match(simple, Rule.CLASSES).length - match(selector, Rule.CLASSES).length + 1; - while (classes > 0 && Rule.CLASS.test(simple)) { - simple = simple.replace(Rule.CLASS, ""); - classes--; - } - while (tags > 0 && Rule.TAG.test(simple)) { - simple = simple.replace(Rule.TAG, "$1*"); - tags--; - } - simple += "." + this.className; - classes = Math.min(classes, 2); - tags = Math.min(tags, 2); - var score = -10 * classes - tags; - if (score > 0) { - simple = simple + "," + Rule.MAP[score] + " " + simple; - } - return simple; - }, - - remove: function(element) { - // deallocate this class - element.className = element.className.replace(this.MATCH, "$1"); - }, - - toString: function() { - return format("%1 {%2}", this.selectorText, this.cssText); - } -}, { - CHILD: />/g, - CLASS: /\.[\w-]+/, - CLASSES: /[.:\[]/g, - MULTI: /(\.[\w-]+)+/g, - PREFIX: "ie7_class", - TAG: /^\w+|([\s>+~])\w+/, - TAGS: /^\w|[\s>+~]\w/g, - MAP: { - 1: "html", - 2: "html body", - 10: ".ie7_html", - 11: "html.ie7_html", - 12: "html.ie7_html body", - 20: ".ie7_html .ie7_body", - 21: "html.ie7_html .ie7_body", - 22: "html.ie7_html body.ie7_body" - } -}); - -// ----------------------------------------------------------------------- -// IE7 dynamic style -// ----------------------------------------------------------------------- - -// object properties: -// attach: the element that an event handler will be attached to -// target: the element that will have the IE7 class applied - -var DynamicRule = Rule.extend({ - // properties - constructor: function(selector, attach, dynamicPseudoClass, target, cssText) { - // initialise object properties - this.attach = attach || "*"; - this.dynamicPseudoClass = IE7.CSS.dynamicPseudoClasses[dynamicPseudoClass]; - this.target = target; - this.base(selector, cssText); - }, - - recalc: function() { - // execute the underlying css query for this class - var attaches = cssQuery(this.attach), attach; - // process results - for (var i = 0; attach = attaches[i]; i++) { - // retrieve the event handler's target element(s) - var target = this.target ? cssQuery(this.target, attach) : [attach]; - // attach event handlers for dynamic pseudo-classes - if (target.length) this.dynamicPseudoClass.apply(attach, target, this); - } - } -}); - -// ----------------------------------------------------------------------- -// IE7 dynamic pseudo-classes -// ----------------------------------------------------------------------- - -var DynamicPseudoClass = Base.extend({ - constructor: function(name, apply) { - this.name = name; - this.apply = apply; - this.instances = {}; - IE7.CSS.dynamicPseudoClasses[name] = this; - }, - - register: function(instance) { - // an "instance" is actually an Arguments object - var _class = instance[2]; - instance.id = _class.id + instance[0].uniqueID; - if (!this.instances[instance.id]) { - var target = instance[1], j; - for (j = 0; j < target.length; j++) _class.add(target[j]); - this.instances[instance.id] = instance; - } - }, - - unregister: function(instance) { - if (this.instances[instance.id]) { - var _class = instance[2]; - var target = instance[1], j; - for (j = 0; j < target.length; j++) _class.remove(target[j]); - delete this.instances[instance.id]; - } - } -}); - -// ----------------------------------------------------------------------- -// dynamic pseudo-classes -// ----------------------------------------------------------------------- - -if (appVersion < 7) { - var Hover = new DynamicPseudoClass("hover", function(element) { - var instance = arguments; - IE7.CSS.addEventHandler(element, appVersion < 5.5 ? "onmouseover" : "onmouseenter", function() { - Hover.register(instance); - }); - IE7.CSS.addEventHandler(element, appVersion < 5.5 ? "onmouseout" : "onmouseleave", function() { - Hover.unregister(instance); - }); - }); - - // globally trap the mouseup event (thanks Martijn!) - addEventHandler(document, "onmouseup", function() { - var instances = Hover.instances; - for (var i in instances) - if (!instances[i][0].contains(event.srcElement)) - Hover.unregister(instances[i]); - }); -} - -// ----------------------------------------------------------------------- -// propertyName: inherit; -// ----------------------------------------------------------------------- - -IE7.CSS.addRecalc("[\\w-]+", "inherit", function(element, cssText) { - var inherited = cssText.match(/[\w-]+\s*:\s*inherit/g); - for (var i = 0; i < inherited.length; i++) { - var propertyName = inherited[i].replace(/ie7\-|\s*:\s*inherit/g, "").replace(/\-([a-z])/g, function(match, chr) { - return chr.toUpperCase() - }); - element.runtimeStyle[propertyName] = element.parentElement.currentStyle[propertyName]; - } -}); - -// ========================================================================= -// ie7-html.js -// ========================================================================= - -// default font-sizes -//HEADER += "h1{font-size:2em}h2{font-size:1.5em;}h3{font-size:1.17em;}h4{font-size:1em}h5{font-size:.83em}h6{font-size:.67em}"; - -IE7.HTML = new (Fix.extend({ // single instance - fixed: {}, - - init: Undefined, - - addFix: function() { - // fixes are a one-off, they are applied when the document is loaded - this.fixes.push(arguments); - }, - - apply: function() { - for (var i = 0; i < this.fixes.length; i++) { - var match = cssQuery(this.fixes[i][0]); - var fix = this.fixes[i][1]; - for (var j = 0; j < match.length; j++) fix(match[j]); - } - }, - - addRecalc: function() { - // recalcs occur whenever the document is refreshed using document.recalc() - this.recalcs.push(arguments); - }, - - recalc: function() { - // loop through the fixes - for (var i = 0; i < this.recalcs.length; i++) { - var match = cssQuery(this.recalcs[i][0]); - var recalc = this.recalcs[i][1], element; - var key = Math.pow(2, i); - for (var j = 0; (element = match[j]); j++) { - var uniqueID = element.uniqueID; - if ((this.fixed[uniqueID] & key) == 0) { - element = recalc(element) || element; - this.fixed[uniqueID] |= key; - } - } - } - } -})); - -if (appVersion < 7) { - // provide support for the tag. - // this is a proper fix, it preserves the DOM structure and - // elements report the correct tagName & namespace prefix - document.createElement("abbr"); - - // bind to the first child control - IE7.HTML.addRecalc("label", function(label) { - if (!label.htmlFor) { - var firstChildControl = cssQuery("input,textarea", label, true); - if (firstChildControl) { - addEventHandler(label, "onclick", function() { - firstChildControl.click(); - }); - } - } - }); -} - -// ========================================================================= -// ie7-layout.js -// ========================================================================= - -var NUMERIC = "[.\\d]"; - -new function(_) { -var layout = IE7.Layout = this; - - // big, ugly box-model hack + min/max stuff - - // #tantek > #erik > #dean { voice-family: hacker; } - - // ----------------------------------------------------------------------- - // "layout" - // ----------------------------------------------------------------------- - - HEADER += "*{boxSizing:content-box}"; - - // does an element have "layout" ? - IE7.hasLayout = appVersion < 5.5 ? function(element) { - // element.currentStyle.hasLayout doesn't work for IE5.0 - return element.clientWidth; - } : function(element) { - return element.currentStyle.hasLayout; - }; - - // give an element "layout" - layout.boxSizing = function(element) { - if (!IE7.hasLayout(element)) { - //# element.runtimeStyle.fixedHeight = - element.style.height = "0cm"; - if (element.currentStyle.verticalAlign == "auto") - element.runtimeStyle.verticalAlign = "top"; - // when an element acquires "layout", margins no longer collapse correctly - collapseMargins(element); - } - }; - - // ----------------------------------------------------------------------- - // Margin Collapse - // ----------------------------------------------------------------------- - - function collapseMargins(element) { - if (element != viewport && element.currentStyle.position != "absolute") { - collapseMargin(element, "marginTop"); - collapseMargin(element, "marginBottom"); - } - }; - - function collapseMargin(element, type) { - if (!element.runtimeStyle[type]) { - var parentElement = element.parentElement; - if (parentElement && IE7.hasLayout(parentElement) && !IE7[type == "marginTop" ? "_getPreviousElementSibling" : "_getNextElementSibling"](element)) return; - var child = cssQuery(">*:" + (type == "marginTop" ? "first" : "last") + "-child", element, true); - if (child && child.currentStyle.styleFloat == "none" && IE7.hasLayout(child)) { - collapseMargin(child, type); - margin = _getMargin(element, element.currentStyle[type]); - childMargin = _getMargin(child, child.currentStyle[type]); - if (margin < 0 || childMargin < 0) { - element.runtimeStyle[type] = margin + childMargin; - } else { - element.runtimeStyle[type] = Math.max(childMargin, margin); - } - child.runtimeStyle[type] = "0px"; - } - } - }; - - function _getMargin(element, value) { - return value == "auto" ? 0 : getPixelValue(element, value); - }; - - // ----------------------------------------------------------------------- - // box-model - // ----------------------------------------------------------------------- - - // constants - var UNIT = /^[.\d][\w%]*$/, AUTO = /^(auto|0cm)$/; - - var applyWidth, applyHeight; - IE7.Layout.borderBox = function(element){ - applyWidth(element); - applyHeight(element); - }; - - var fixWidth = function(HEIGHT) { - applyWidth = function(element) { - if (!PERCENT.test(element.currentStyle.width)) fixWidth(element); - collapseMargins(element); - }; - - function fixWidth(element, value) { - if (!element.runtimeStyle.fixedWidth) { - if (!value) value = element.currentStyle.width; - element.runtimeStyle.fixedWidth = (UNIT.test(value)) ? Math.max(0, getFixedWidth(element, value)) : value; - setOverrideStyle(element, "width", element.runtimeStyle.fixedWidth); - } - }; - - function layoutWidth(element) { - if (!isFixed(element)) { - var layoutParent = element.offsetParent; - while (layoutParent && !IE7.hasLayout(layoutParent)) layoutParent = layoutParent.offsetParent; - } - return (layoutParent || viewport).clientWidth; - }; - - function getPixelWidth(element, value) { - if (PERCENT.test(value)) return parseInt(parseFloat(value) / 100 * layoutWidth(element)); - return getPixelValue(element, value); - }; - - var getFixedWidth = function(element, value) { - var borderBox = element.currentStyle["box-sizing"] == "border-box"; - var adjustment = 0; - if (quirksMode && !borderBox) - adjustment += getBorderWidth(element) + getWidth(element, "padding"); - else if (!quirksMode && borderBox) - adjustment -= getBorderWidth(element) + getWidth(element, "padding"); - return getPixelWidth(element, value) + adjustment; - }; - - // easy way to get border thickness for elements with "layout" - function getBorderWidth(element) { - return element.offsetWidth - element.clientWidth; - }; - - // have to do some pixel conversion to get padding/margin thickness :-( - function getWidth(element, type) { - return getPixelWidth(element, element.currentStyle[type + "Left"]) + getPixelWidth(element, element.currentStyle[type + "Right"]); - }; - - // ----------------------------------------------------------------------- - // min/max - // ----------------------------------------------------------------------- - - HEADER += "*{minWidth:none;maxWidth:none;min-width:none;max-width:none}"; - - // handle min-width property - layout.minWidth = function(element) { - // IE6 supports min-height so we frig it here - //#if (element.currentStyle.minHeight == "auto") element.runtimeStyle.minHeight = 0; - if (element.currentStyle["min-width"] != null) { - element.style.minWidth = element.currentStyle["min-width"]; - } - if (register(arguments.callee, element, element.currentStyle.minWidth != "none")) { - layout.boxSizing(element); - fixWidth(element); - resizeWidth(element); - } - }; - - // clone the minWidth function to make a maxWidth function - eval("IE7.Layout.maxWidth=" + String(layout.minWidth).replace(/min/g, "max")); - - // apply min/max restrictions - function resizeWidth(element) { - // check boundaries - var rect = element.getBoundingClientRect(); - var width = rect.right - rect.left; - - if (element.currentStyle.minWidth != "none" && width <= getFixedWidth(element, element.currentStyle.minWidth)) { - element.runtimeStyle.width = element.currentStyle.minWidth; - } else if (element.currentStyle.maxWidth != "none" && width >= getFixedWidth(element, element.currentStyle.maxWidth)) { - element.runtimeStyle.width = element.currentStyle.maxWidth; - } else { - element.runtimeStyle.width = element.runtimeStyle.fixedWidth; // || "auto"; - } - }; - - // ----------------------------------------------------------------------- - // right/bottom - // ----------------------------------------------------------------------- - - function fixRight(element) { - if (register(fixRight, element, /^(fixed|absolute)$/.test(element.currentStyle.position) && - getDefinedStyle(element, "left") != "auto" && - getDefinedStyle(element, "right") != "auto" && - AUTO.test(getDefinedStyle(element, "width")))) { - resizeRight(element); - IE7.Layout.boxSizing(element); - } - }; - IE7.Layout.fixRight = fixRight; - - function resizeRight(element) { - var left = getPixelWidth(element, element.runtimeStyle._left || element.currentStyle.left); - var width = layoutWidth(element) - getPixelWidth(element, element.currentStyle.right) - left - getWidth(element, "margin"); - if (parseInt(element.runtimeStyle.width) == width) return; - element.runtimeStyle.width = ""; - if (isFixed(element) || HEIGHT || element.offsetWidth < width) { - if (!quirksMode) width -= getBorderWidth(element) + getWidth(element, "padding"); - if (width < 0) width = 0; - element.runtimeStyle.fixedWidth = width; - setOverrideStyle(element, "width", width); - } - }; - - // ----------------------------------------------------------------------- - // window.onresize - // ----------------------------------------------------------------------- - - // handle window resize - var clientWidth = 0; - addResize(function() { - if (!viewport) return; - var i, wider = (clientWidth < viewport.clientWidth); - clientWidth = viewport.clientWidth; - // resize elements with "min-width" set - var elements = layout.minWidth.elements; - for (i in elements) { - var element = elements[i]; - var fixedWidth = (parseInt(element.runtimeStyle.width) == getFixedWidth(element, element.currentStyle.minWidth)); - if (wider && fixedWidth) element.runtimeStyle.width = ""; - if (wider == fixedWidth) resizeWidth(element); - } - // resize elements with "max-width" set - var elements = layout.maxWidth.elements; - for (i in elements) { - var element = elements[i]; - var fixedWidth = (parseInt(element.runtimeStyle.width) == getFixedWidth(element, element.currentStyle.maxWidth)); - if (!wider && fixedWidth) element.runtimeStyle.width = ""; - if (wider != fixedWidth) resizeWidth(element); - } - // resize elements with "right" set - for (i in fixRight.elements) resizeRight(fixRight.elements[i]); - }); - - // ----------------------------------------------------------------------- - // fix CSS - // ----------------------------------------------------------------------- - if (quirksMode) { - IE7.CSS.addRecalc("width", NUMERIC, applyWidth); - } - if (appVersion < 7) { - IE7.CSS.addRecalc("min-width", NUMERIC, layout.minWidth); - IE7.CSS.addRecalc("max-width", NUMERIC, layout.maxWidth); - IE7.CSS.addRecalc("right", NUMERIC, fixRight); - } - }; - - eval("var fixHeight=" + rotate(fixWidth)); - - // apply box-model + min/max fixes - fixWidth(); - fixHeight(true); -}; - -// ========================================================================= -// ie7-graphics.js -// ========================================================================= - -// a small transparent image used as a placeholder -var BLANK_GIF = makePath("blank.gif", path); - -var ALPHA_IMAGE_LOADER = "DXImageTransform.Microsoft.AlphaImageLoader"; -var PNG_FILTER = "progid:" + ALPHA_IMAGE_LOADER + "(src='%1',sizingMethod='%2')"; - -// regular expression version of the above -var PNG; - -var filtered = []; - -function fixImage(element) { - if (PNG.test(element.src)) { - // we have to preserve width and height - var image = new Image(element.width, element.height); - image.onload = function() { - element.width = image.width; - element.height = image.height; - image = null; - }; - image.src = element.src; - // store the original url (we'll put it back when it's printed) - element.pngSrc = element.src; - // add the AlphaImageLoader thingy - addFilter(element); - } -}; - -if (appVersion >= 5.5 && appVersion < 7) { - // ** IE7 VARIABLE - // e.g. only apply the hack to files ending in ".png" - // IE7_PNG_SUFFIX = ".png"; - - // replace background(-image): url(..) .. with background(-image): .. ;filter: ..; - IE7.CSS.addFix(/background(-image)?\s*:\s*([^};]*)?url\(([^\)]+)\)([^;}]*)?/, function(match, $1, $2, url, $4) { - url = getString(url); - return PNG.test(url) ? "filter:" + format(PNG_FILTER, url, "crop") + - ";zoom:1;background" + ($1||"") + ":" + ($2||"") + "none" + ($4||"") : match; - }); - - // ----------------------------------------------------------------------- - // fix PNG transparency (HTML images) - // ----------------------------------------------------------------------- - - IE7.HTML.addRecalc("img,input", function(element) { - if (element.tagName == "INPUT" && element.type != "image") return; - fixImage(element); - addEventHandler(element, "onpropertychange", function() { - if (!printing && event.propertyName == "src" && - element.src.indexOf(BLANK_GIF) == -1) fixImage(element); - }); - }); - - // assume that background images should not be printed - // (if they are not transparent then they'll just obscure content) - // but we'll put foreground images back... - var printing = false; - addEventHandler(window, "onbeforeprint", function() { - printing = true; - for (var i = 0; i < filtered.length; i++) removeFilter(filtered[i]); - }); - addEventHandler(window, "onafterprint", function() { - for (var i = 0; i < filtered.length; i++) addFilter(filtered[i]); - printing = false; - }); -} - -// apply a filter -function addFilter(element, sizingMethod) { - var filter = element.filters[ALPHA_IMAGE_LOADER]; - if (filter) { - filter.src = element.src; - filter.enabled = true; - } else { - element.runtimeStyle.filter = format(PNG_FILTER, element.src, sizingMethod || "scale"); - filtered.push(element); - } - // remove the real image - element.src = BLANK_GIF; -}; - -function removeFilter(element) { - element.src = element.pngSrc; - element.filters[ALPHA_IMAGE_LOADER].enabled = false; -}; - -// ========================================================================= -// ie7-fixed.js -// ========================================================================= - -new function(_) { - if (appVersion >= 7) return; - - // some things to consider for this hack. - // the document body requires a fixed background. even if - // it is just a blank image. - // you have to use setExpression instead of onscroll, this - // together with a fixed body background helps avoid the - // annoying screen flicker of other solutions. - - IE7.CSS.addRecalc("position", "fixed", _positionFixed, "absolute"); - IE7.CSS.addRecalc("background(-attachment)?", "[^};]*fixed", _backgroundFixed); - - // scrolling is relative to the documentElement (HTML tag) when in - // standards mode, otherwise it's relative to the document body - var $viewport = quirksMode ? "body" : "documentElement"; - - function _fixBackground() { - // this is required by both position:fixed and background-attachment:fixed. - // it is necessary for the document to also have a fixed background image. - // we can fake this with a blank image if necessary - if (body.currentStyle.backgroundAttachment != "fixed") { - if (body.currentStyle.backgroundImage == "none") { - body.runtimeStyle.backgroundRepeat = "no-repeat"; - body.runtimeStyle.backgroundImage = "url(" + BLANK_GIF + ")"; // dummy - } - body.runtimeStyle.backgroundAttachment = "fixed"; - } - _fixBackground = Undefined; - }; - - var _tmp = createTempElement("img"); - - function _isFixed(element) { - return element ? isFixed(element) || _isFixed(element.parentElement) : false; - }; - - function _setExpression(element, propertyName, expression) { - setTimeout("document.all." + element.uniqueID + ".runtimeStyle.setExpression('" + propertyName + "','" + expression + "')", 0); - }; - - // ----------------------------------------------------------------------- - // backgroundAttachment: fixed - // ----------------------------------------------------------------------- - - function _backgroundFixed(element) { - if (register(_backgroundFixed, element, element.currentStyle.backgroundAttachment == "fixed" && !element.contains(body))) { - _fixBackground(); - bgLeft(element); - bgTop(element); - _backgroundPosition(element); - } - }; - - function _backgroundPosition(element) { - _tmp.src = element.currentStyle.backgroundImage.slice(5, -2); - var parentElement = element.canHaveChildren ? element : element.parentElement; - parentElement.appendChild(_tmp); - setOffsetLeft(element); - setOffsetTop(element); - parentElement.removeChild(_tmp); - }; - - function bgLeft(element) { - element.style.backgroundPositionX = element.currentStyle.backgroundPositionX; - if (!_isFixed(element)) { - _setExpression(element, "backgroundPositionX", "(parseInt(runtimeStyle.offsetLeft)+document." + $viewport + ".scrollLeft)||0"); - } - }; - eval(rotate(bgLeft)); - - function setOffsetLeft(element) { - var propertyName = _isFixed(element) ? "backgroundPositionX" : "offsetLeft"; - element.runtimeStyle[propertyName] = - getOffsetLeft(element, element.style.backgroundPositionX) - - element.getBoundingClientRect().left - element.clientLeft + 2; - }; - eval(rotate(setOffsetLeft)); - - function getOffsetLeft(element, position) { - switch (position) { - case "left": - case "top": - return 0; - case "right": - case "bottom": - return viewport.clientWidth - _tmp.offsetWidth; - case "center": - return (viewport.clientWidth - _tmp.offsetWidth) / 2; - default: - if (PERCENT.test(position)) { - return parseInt((viewport.clientWidth - _tmp.offsetWidth) * parseFloat(position) / 100); - } - _tmp.style.left = position; - return _tmp.offsetLeft; - } - }; - eval(rotate(getOffsetLeft)); - - // ----------------------------------------------------------------------- - // position: fixed - // ----------------------------------------------------------------------- - - function _positionFixed(element) { - if (register(_positionFixed, element, isFixed(element))) { - setOverrideStyle(element, "position", "absolute"); - setOverrideStyle(element, "left", element.currentStyle.left); - setOverrideStyle(element, "top", element.currentStyle.top); - _fixBackground(); - IE7.Layout.fixRight(element); - _foregroundPosition(element); - } - }; - - function _foregroundPosition(element, recalc) { - positionTop(element, recalc); - positionLeft(element, recalc, true); - if (!element.runtimeStyle.autoLeft && element.currentStyle.marginLeft == "auto" && - element.currentStyle.right != "auto") { - var left = viewport.clientWidth - getPixelWidth(element, element.currentStyle.right) - - getPixelWidth(element, element.runtimeStyle._left) - element.clientWidth; - if (element.currentStyle.marginRight == "auto") left = parseInt(left / 2); - if (_isFixed(element.offsetParent)) element.runtimeStyle.pixelLeft += left; - else element.runtimeStyle.shiftLeft = left; - } - clipWidth(element); - clipHeight(element); - }; - - function clipWidth(element) { - var fixWidth = element.runtimeStyle.fixWidth; - element.runtimeStyle.borderRightWidth = ""; - element.runtimeStyle.width = fixWidth ? getPixelWidth(element, fixWidth) : ""; - if (element.currentStyle.width != "auto") { - var rect = element.getBoundingClientRect(); - var width = element.offsetWidth - viewport.clientWidth + rect.left - 2; - if (width >= 0) { - element.runtimeStyle.borderRightWidth = "0px"; - width = Math.max(getPixelValue(element, element.currentStyle.width) - width, 0); - setOverrideStyle(element, "width", width); - return width; - } - } - }; - eval(rotate(clipWidth)); - - function positionLeft(element, recalc) { - // if the element's width is in % units then it must be recalculated - // with respect to the viewport - if (!recalc && PERCENT.test(element.currentStyle.width)) { - element.runtimeStyle.fixWidth = element.currentStyle.width; - } - if (element.runtimeStyle.fixWidth) { - element.runtimeStyle.width = getPixelWidth(element, element.runtimeStyle.fixWidth); - } - //if (recalc) { - // // if the element is fixed on the right then no need to recalculate - // if (!element.runtimeStyle.autoLeft) return; - //} else { - element.runtimeStyle.shiftLeft = 0; - element.runtimeStyle._left = element.currentStyle.left; - // is the element fixed on the right? - element.runtimeStyle.autoLeft = element.currentStyle.right != "auto" && - element.currentStyle.left == "auto"; - //} - // reset the element's "left" value and get its natural position - element.runtimeStyle.left = ""; - element.runtimeStyle.screenLeft = getScreenLeft(element); - element.runtimeStyle.pixelLeft = element.runtimeStyle.screenLeft; - // if the element is contained by another fixed element then there is no need to - // continually recalculate its left position - if (!recalc && !_isFixed(element.offsetParent)) { - // onsrcoll produces jerky movement, so we use an expression - _setExpression(element, "pixelLeft", "runtimeStyle.screenLeft+runtimeStyle.shiftLeft+document." + $viewport + ".scrollLeft"); - } - }; - // clone this function so we can do "top" - eval(rotate(positionLeft)); - - // I've forgotten how this works... - function getScreenLeft(element) { // thanks to kevin newman (captainn) - var screenLeft = element.offsetLeft, nested = 1; - if (element.runtimeStyle.autoLeft) { - screenLeft = viewport.clientWidth - element.offsetWidth - getPixelWidth(element, element.currentStyle.right); - } - // accommodate margins - if (element.currentStyle.marginLeft != "auto") { - screenLeft -= getPixelWidth(element, element.currentStyle.marginLeft); - } - while (element = element.offsetParent) { - if (element.currentStyle.position != "static") nested = -1; - screenLeft += element.offsetLeft * nested; - } - return screenLeft; - }; - eval(rotate(getScreenLeft)); - - function getPixelWidth(element, value) { - return PERCENT.test(value) ? parseInt(parseFloat(value) / 100 * viewport.clientWidth) : getPixelValue(element, value); - }; - eval(rotate(getPixelWidth)); - - // ----------------------------------------------------------------------- - // capture window resize - // ----------------------------------------------------------------------- - - function _resize() { - // if the window has been resized then some positions need to be - // recalculated (especially those aligned to "right" or "top" - var elements = _backgroundFixed.elements; - for (var i in elements) _backgroundPosition(elements[i]); - elements = _positionFixed.elements; - for (i in elements) { - _foregroundPosition(elements[i], true); - // do this twice to be sure - hackish, I know :-) - _foregroundPosition(elements[i], true); - } - _timer = 0; - }; - - // use a timer for some reason. - // (sometimes this is a good way to prevent resize loops) - var _timer; - addResize(function() { - if (!_timer) _timer = setTimeout(_resize, 0); - }); -}; - -// ========================================================================= -// ie7-oveflow.js -// ========================================================================= - -/* --------------------------------------------------------------------- - - This module alters the structure of the document. - It may adversely affect other CSS rules. Be warned. - ---------------------------------------------------------------------- */ - -var WRAPPER_STYLE = { - backgroundColor: "transparent", - backgroundImage: "none", - backgroundPositionX: null, - backgroundPositionY: null, - backgroundRepeat: null, - borderTopWidth: 0, - borderRightWidth: 0, - borderBottomWidth: 0, - borderLeftStyle: "none", - borderTopStyle: "none", - borderRightStyle: "none", - borderBottomStyle: "none", - borderLeftWidth: 0, - height: null, - marginTop: 0, - marginBottom: 0, - marginRight: 0, - marginLeft: 0, - width: "100%" -}; - -IE7.CSS.addRecalc("overflow", "visible", function(element) { - // don't do this again - if (element.parentNode.ie7_wrapped) return; - - // if max-height is applied, makes sure it gets applied first - if (IE7.Layout && element.currentStyle["max-height"] != "auto") { - IE7.Layout.maxHeight(element); - } - - if (element.currentStyle.marginLeft == "auto") element.style.marginLeft = 0; - if (element.currentStyle.marginRight == "auto") element.style.marginRight = 0; - - var wrapper = document.createElement(ANON); - wrapper.ie7_wrapped = element; - for (var propertyName in WRAPPER_STYLE) { - wrapper.style[propertyName] = element.currentStyle[propertyName]; - if (WRAPPER_STYLE[propertyName] != null) { - element.runtimeStyle[propertyName] = WRAPPER_STYLE[propertyName]; - } - } - wrapper.style.display = "block"; - wrapper.style.position = "relative"; - element.runtimeStyle.position = "absolute"; - element.parentNode.insertBefore(wrapper, element); - wrapper.appendChild(element); -}); - -// ========================================================================= -// ie7-quirks.js -// ========================================================================= - -function ie7Quirks() { - var FONT_SIZES = "xx-small,x-small,small,medium,large,x-large,xx-large".split(","); - for (var i = 0; i < FONT_SIZES.length; i++) { - FONT_SIZES[FONT_SIZES[i]] = FONT_SIZES[i - 1] || "0.67em"; - } - - IE7.CSS.addFix(/(font(-size)?\s*:\s*)([\w.-]+)/, function(match, label, size, value) { - return label + (FONT_SIZES[value] || value); - }); - - if (appVersion < 6) { - var NEGATIVE = /^\-/, LENGTH = /(em|ex)$/i; - var EM = /em$/i, EX = /ex$/i; - - getPixelValue = function(element, value) { - if (PIXEL.test(value)) return parseInt(value)||0; - var scale = NEGATIVE.test(value)? -1 : 1; - if (LENGTH.test(value)) scale *= getFontScale(element); - temp.style.width = (scale < 0) ? value.slice(1) : value; - body.appendChild(temp); - // retrieve pixel width - value = scale * temp.offsetWidth; - // remove the temporary element - temp.removeNode(); - return parseInt(value); - }; - - var temp = createTempElement(); - function getFontScale(element) { - var scale = 1; - temp.style.fontFamily = element.currentStyle.fontFamily; - temp.style.lineHeight = element.currentStyle.lineHeight; - //temp.style.fontSize = ""; - while (element != body) { - var fontSize = element.currentStyle["ie7-font-size"]; - if (fontSize) { - if (EM.test(fontSize)) scale *= parseFloat(fontSize); - else if (PERCENT.test(fontSize)) scale *= (parseFloat(fontSize) / 100); - else if (EX.test(fontSize)) scale *= (parseFloat(fontSize) / 2); - else { - temp.style.fontSize = fontSize; - return 1; - } - } - element = element.parentElement; - } - return scale; - }; - - // cursor:pointer (IE5.x) - IE7.CSS.addFix(/cursor\s*:\s*pointer/, "cursor:hand"); - // display:list-item (IE5.x) - IE7.CSS.addFix(/display\s*:\s*list-item/, "display:block"); - } - - // ----------------------------------------------------------------------- - // margin:auto - // ----------------------------------------------------------------------- - - function fixMargin(element) { - if (appVersion < 5.5) IE7.Layout.boxSizing(element.parentElement); - var parent = element.parentElement; - var margin = parent.offsetWidth - element.offsetWidth - getPaddingWidth(parent); - var autoRight = (element.currentStyle["ie7-margin"] && element.currentStyle.marginRight == "auto") || - element.currentStyle["ie7-margin-right"] == "auto"; - switch (parent.currentStyle.textAlign) { - case "right": - margin = autoRight ? parseInt(margin / 2) : 0; - element.runtimeStyle.marginRight = margin + "px"; - break; - case "center": - if (autoRight) margin = 0; - default: - if (autoRight) margin /= 2; - element.runtimeStyle.marginLeft = parseInt(margin) + "px"; - } - }; - - function getPaddingWidth(element) { - return getPixelValue(element, element.currentStyle.paddingLeft) + - getPixelValue(element, element.currentStyle.paddingRight); - }; - - IE7.CSS.addRecalc("margin(-left|-right)?", "[^};]*auto", function(element) { - if (register(fixMargin, element, - element.parentElement && - element.currentStyle.display == "block" && - element.currentStyle.marginLeft == "auto" && - element.currentStyle.position != "absolute")) { - fixMargin(element); - } - }); - - addResize(function() { - for (var i in fixMargin.elements) { - var element = fixMargin.elements[i]; - element.runtimeStyle.marginLeft = - element.runtimeStyle.marginRight = ""; - fixMargin(element); - } - }); -}; - - -// ========================================================================= -// ie8-cssQuery.js -// ========================================================================= - -IE7._isEmpty = function(element) { - element = element.firstChild; - while (element) { - if (element.nodeType == 3 || (element.nodeType == 1 && element.nodeName != "!")) return false; - element = element.nextSibling; - } - return true; -}; - -IE7._isLang = function(element, code) { - while (element && !element.getAttribute("lang")) element = element.parentNode; - return element && new RegExp("^" + rescape(code), "i").test(element.getAttribute("lang")); -}; - -function _nthChild(match, args, position, last) { - // ugly but it works... - last = /last/i.test(match) ? last + "+1-" : ""; - if (!isNaN(args)) args = "0n+" + args; - else if (args == "even") args = "2n"; - else if (args == "odd") args = "2n+1"; - args = args.split("n"); - var a = args[0] ? (args[0] == "-") ? -1 : parseInt(args[0]) : 1; - var b = parseInt(args[1]) || 0; - var negate = a < 0; - if (negate) { - a = -a; - if (a == 1) b++; - } - var query = format(a == 0 ? "%3%7" + (last + b) : "(%4%3-%2)%6%1%70%5%4%3>=%2", a, b, position, last, "&&", "%", "=="); - if (negate) query = "!(" + query + ")"; - return query; -}; - -_PSEUDO_CLASSES = { - "link": "e%1.currentStyle['ie7-link']=='link'", - "visited": "e%1.currentStyle['ie7-link']=='visited'", - "checked": "e%1.checked", - "contains": "e%1.innerText.indexOf('%2')!=-1", - "disabled": "e%1.isDisabled", - "empty": "IE7._isEmpty(e%1)", - "enabled": "e%1.disabled===false", - "first-child": "!IE7._getPreviousElementSibling(e%1)", - "lang": "IE7._isLang(e%1,'%2')", - "last-child": "!IE7._getNextElementSibling(e%1)", - "only-child": "!IE7._getPreviousElementSibling(e%1)&&!IE7._getNextElementSibling(e%1)", - "target": "e%1.id==location.hash.slice(1)", - "indeterminate": "e%1.indeterminate" -}; - - -// register a node and index its children -IE7._register = function(element) { - if (element.rows) { - element.ie7_length = element.rows.length; - element.ie7_lookup = "rowIndex"; - } else if (element.cells) { - element.ie7_length = element.cells.length; - element.ie7_lookup = "cellIndex"; - } else if (element.ie7_indexed != IE7._indexed) { - var index = 0; - var child = element.firstChild; - while (child) { - if (child.nodeType == 1 && child.nodeName != "!") { - child.ie7_index = ++index; - } - child = child.nextSibling; - } - element.ie7_length = index; - element.ie7_lookup = "ie7_index"; - } - element.ie7_indexed = IE7._indexed; - return element; -}; - -var keys = cssParser[_KEYS]; -var pseudoClass = keys[keys.length - 1]; -keys.length--; - -cssParser.merge({ - ":not\\((\\*|[\\w-]+)?([^)]*)\\)": function(match, tagName, filters) { // :not pseudo class - var replacement = (tagName && tagName != "*") ? format("if(e%1.nodeName=='%2'){", _index, tagName.toUpperCase()) : ""; - replacement += cssParser.exec(filters); - return "if(!" + replacement.slice(2, -1).replace(/\)\{if\(/g, "&&") + "){"; - }, - - ":nth(-last)?-child\\(([^)]+)\\)": function(match, last, args) { // :nth-child pseudo classes - _wild = false; - last = format("e%1.parentNode.ie7_length", _index); - var replacement = "if(p%1!==e%1.parentNode)p%1=IE7._register(e%1.parentNode);"; - replacement += "var i=e%1[p%1.ie7_lookup];if(p%1.ie7_lookup!='ie7_index')i++;if("; - return format(replacement, _index) + _nthChild(match, args, "i", last) + "){"; - } -}); - -keys.push(pseudoClass); - -// ========================================================================= -// ie8-css.js -// ========================================================================= - -var BRACKETS = "\\([^)]*\\)"; - -if (IE7.CSS.pseudoClasses) IE7.CSS.pseudoClasses += "|"; -IE7.CSS.pseudoClasses += "before|after|last\\-child|only\\-child|empty|root|" + - "not|nth\\-child|nth\\-last\\-child|contains|lang".split("|").join(BRACKETS + "|") + BRACKETS; - -// pseudo-elements can be declared with a double colon -encoder.add(/::/, ":"); - -// ----------------------------------------------------------------------- -// dynamic pseudo-classes -// ----------------------------------------------------------------------- - -var Focus = new DynamicPseudoClass("focus", function(element) { - var instance = arguments; - - IE7.CSS.addEventHandler(element, "onfocus", function() { - Focus.unregister(instance); // in case it starts with focus - Focus.register(instance); - }); - - IE7.CSS.addEventHandler(element, "onblur", function() { - Focus.unregister(instance); - }); - - // check the active element for initial state - if (element == document.activeElement) { - Focus.register(instance) - } -}); - -var Active = new DynamicPseudoClass("active", function(element) { - var instance = arguments; - IE7.CSS.addEventHandler(element, "onmousedown", function() { - Active.register(instance); - }); -}); - -// globally trap the mouseup event (thanks Martijn!) -addEventHandler(document, "onmouseup", function() { - var instances = Active.instances; - for (var i in instances) Active.unregister(instances[i]); -}); - -// :checked -var Checked = new DynamicPseudoClass("checked", function(element) { - if (typeof element.checked != "boolean") return; - var instance = arguments; - IE7.CSS.addEventHandler(element, "onpropertychange", function() { - if (event.propertyName == "checked") { - if (element.checked) Checked.register(instance); - else Checked.unregister(instance); - } - }); - // check current checked state - if (element.checked) Checked.register(instance); -}); - -// :enabled -var Enabled = new DynamicPseudoClass("enabled", function(element) { - if (typeof element.disabled != "boolean") return; - var instance = arguments; - IE7.CSS.addEventHandler(element, "onpropertychange", function() { - if (event.propertyName == "disabled") { - if (!element.isDisabled) Enabled.register(instance); - else Enabled.unregister(instance); - } - }); - // check current disabled state - if (!element.isDisabled) Enabled.register(instance); -}); - -// :disabled -var Disabled = new DynamicPseudoClass("disabled", function(element) { - if (typeof element.disabled != "boolean") return; - var instance = arguments; - IE7.CSS.addEventHandler(element, "onpropertychange", function() { - if (event.propertyName == "disabled") { - if (element.isDisabled) Disabled.register(instance); - else Disabled.unregister(instance); - } - }); - // check current disabled state - if (element.isDisabled) Disabled.register(instance); -}); - -// :indeterminate (Kevin Newman) -var Indeterminate = new DynamicPseudoClass("indeterminate", function(element) { - if (typeof element.indeterminate != "boolean") return; - var instance = arguments; - IE7.CSS.addEventHandler(element, "onpropertychange", function() { - if (event.propertyName == "indeterminate") { - if (element.indeterminate) Indeterminate.register(instance); - else Indeterminate.unregister(instance); - } - }); - IE7.CSS.addEventHandler(element, "onclick", function() { - Indeterminate.unregister(instance); - }); - // clever Kev says no need to check this up front -}); - -// :target -var Target = new DynamicPseudoClass("target", function(element) { - var instance = arguments; - // if an element has a tabIndex then it can become "active". - // The default is zero anyway but it works... - if (!element.tabIndex) element.tabIndex = 0; - // this doesn't detect the back button. I don't know how to do that :-( - IE7.CSS.addEventHandler(document, "onpropertychange", function() { - if (event.propertyName == "activeElement") { - if (element.id && element.id == location.hash.slice(1)) Target.register(instance); - else Target.unregister(instance); - } - }); - // check the current location - if (element.id && element.id == location.hash.slice(1)) Target.register(instance); -}); - -// ----------------------------------------------------------------------- -// IE7 pseudo elements -// ----------------------------------------------------------------------- - -// constants -var ATTR = /^attr/; -var URL = /^url\s*\(\s*([^)]*)\)$/; -var POSITION_MAP = { - before0: "beforeBegin", - before1: "afterBegin", - after0: "afterEnd", - after1: "beforeEnd" -}; - -var PseudoElement = IE7.PseudoElement = Rule.extend({ - constructor: function(selector, position, cssText) { - // initialise object properties - this.position = position; - var content = cssText.match(PseudoElement.CONTENT), match, entity; - if (content) { - content = content[1]; - match = content.split(/\s+/); - for (var i = 0; (entity = match[i]); i++) { - match[i] = ATTR.test(entity) ? {attr: entity.slice(5, -1)} : - (entity.charAt(0) == "'") ? getString(entity) : decode(entity); - } - content = match; - } - this.content = content; - // CSS text needs to be decoded immediately - this.base(selector, decode(cssText)); - }, - - init: function() { - // execute the underlying css query for this class - this.match = cssQuery(this.selector); - for (var i = 0; i < this.match.length; i++) { - var runtimeStyle = this.match[i].runtimeStyle; - if (!runtimeStyle[this.position]) runtimeStyle[this.position] = {cssText:""}; - runtimeStyle[this.position].cssText += ";" + this.cssText; - if (this.content != null) runtimeStyle[this.position].content = this.content; - } - }, - - create: function(target) { - var generated = target.runtimeStyle[this.position]; - if (generated) { - // copy the array of values - var content = [].concat(generated.content || ""); - for (var j = 0; j < content.length; j++) { - if (typeof content[j] == "object") { - content[j] = target.getAttribute(content[j].attr); - } - } - content = content.join(""); - var url = content.match(URL); - var cssText = "overflow:hidden;" + generated.cssText.replace(/'/g, '"'); - if (target.currentStyle.styleFloat != "none") { - //cssText = cssText.replace(/display\s*:\s*block/, "display:inline-block"); - } - var position = POSITION_MAP[this.position + Number(target.canHaveChildren)]; - var id = 'ie7_pseudo' + PseudoElement.count++; - target.insertAdjacentHTML(position, format(PseudoElement.ANON, this.className, id, cssText, url ? "" : content)); - if (url) { - var pseudoElement = document.getElementById(id); - pseudoElement.src = getString(url[1]); - addFilter(pseudoElement, "crop"); - } - target.runtimeStyle[this.position] = null; - } - }, - - recalc: function() { - if (this.content == null) return; - for (var i = 0; i < this.match.length; i++) { - this.create(this.match[i]); - } - }, - - toString: function() { - return "." + this.className + "{display:inline}"; - } -}, { - CONTENT: /content\s*:\s*([^;]*)(;|$)/, - ANON: "%4", - MATCH: /(.*):(before|after).*/, - - count: 0 -}); - -// ========================================================================= -// ie8-html.js -// ========================================================================= - -var UNSUCCESSFUL = /^(submit|reset|button)$/; - -// ----------------------------------------------------------------------- -//
      "); - this._data.core.li_height = this.get_container_ul().children("li:eq(0)").height() || 24; - /** - * triggered after the loading text is shown and before loading starts - * @event - * @name loading.jstree - */ - this.trigger("loading"); - this.load_node('#'); - }, - /** - * destroy an instance - * @name destroy() - * @param {Boolean} keep_html if not set to `true` the container will be emptied, otherwise the current DOM elements will be kept intact - */ - destroy : function (keep_html) { - if(!keep_html) { this.element.empty(); } - this.element.unbind("destroyed", this.teardown); - this.teardown(); - }, - /** - * part of the destroying of an instance. Used internally. - * @private - * @name teardown() - */ - teardown : function () { - this.unbind(); - this.element - .removeClass('jstree') - .removeData('jstree') - .find("[class^='jstree']") - .addBack() - .attr("class", function () { return this.className.replace(/jstree[^ ]*|$/ig,''); }); - this.element = null; - }, - /** - * bind all events. Used internally. - * @private - * @name bind() - */ - bind : function () { - this.element - .on("dblclick.jstree", function () { - if(document.selection && document.selection.empty) { - document.selection.empty(); - } - else { - if(window.getSelection) { - var sel = window.getSelection(); - try { - sel.removeAllRanges(); - sel.collapse(); - } catch (ignore) { } - } - } - }) - .on("click.jstree", ".jstree-ocl", $.proxy(function (e) { - this.toggle_node(e.target); - }, this)) - .on("click.jstree", ".jstree-anchor", $.proxy(function (e) { - e.preventDefault(); - $(e.currentTarget).focus(); - this.activate_node(e.currentTarget, e); - }, this)) - .on('keydown.jstree', '.jstree-anchor', $.proxy(function (e) { - if(e.target.tagName === "INPUT") { return true; } - var o = null; - switch(e.which) { - case 13: - case 32: - e.type = "click"; - $(e.currentTarget).trigger(e); - break; - case 37: - e.preventDefault(); - if(this.is_open(e.currentTarget)) { - this.close_node(e.currentTarget); - } - else { - o = this.get_prev_dom(e.currentTarget); - if(o && o.length) { o.children('.jstree-anchor').focus(); } - } - break; - case 38: - e.preventDefault(); - o = this.get_prev_dom(e.currentTarget); - if(o && o.length) { o.children('.jstree-anchor').focus(); } - break; - case 39: - e.preventDefault(); - if(this.is_closed(e.currentTarget)) { - this.open_node(e.currentTarget, function (o) { this.get_node(o, true).children('.jstree-anchor').focus(); }); - } - else { - o = this.get_next_dom(e.currentTarget); - if(o && o.length) { o.children('.jstree-anchor').focus(); } - } - break; - case 40: - e.preventDefault(); - o = this.get_next_dom(e.currentTarget); - if(o && o.length) { o.children('.jstree-anchor').focus(); } - break; - // delete - case 46: - e.preventDefault(); - o = this.get_node(e.currentTarget); - if(o && o.id && o.id !== '#') { - o = this.is_selected(o) ? this.get_selected() : o; - // this.delete_node(o); - } - break; - // f2 - case 113: - e.preventDefault(); - o = this.get_node(e.currentTarget); - /*! - if(o && o.id && o.id !== '#') { - // this.edit(o); - } - */ - break; - default: - // console.log(e.which); - break; - } - }, this)) - .on("load_node.jstree", $.proxy(function (e, data) { - if(data.status) { - if(data.node.id === '#' && !this._data.core.loaded) { - this._data.core.loaded = true; - /** - * triggered after the root node is loaded for the first time - * @event - * @name loaded.jstree - */ - this.trigger("loaded"); - } - if(!this._data.core.ready && !this.get_container_ul().find('.jstree-loading:eq(0)').length) { - this._data.core.ready = true; - if(this._data.core.selected.length) { - if(this.settings.core.expand_selected_onload) { - var tmp = [], i, j; - for(i = 0, j = this._data.core.selected.length; i < j; i++) { - tmp = tmp.concat(this._model.data[this._data.core.selected[i]].parents); - } - tmp = $.vakata.array_unique(tmp); - for(i = 0, j = tmp.length; i < j; i++) { - this.open_node(tmp[i], false, 0); - } - } - this.trigger('changed', { 'action' : 'ready', 'selected' : this._data.core.selected }); - } - /** - * triggered after all nodes are finished loading - * @event - * @name ready.jstree - */ - setTimeout($.proxy(function () { this.trigger("ready"); }, this), 0); - } - } - }, this)) - // THEME RELATED - .on("init.jstree", $.proxy(function () { - var s = this.settings.core.themes; - this._data.core.themes.dots = s.dots; - this._data.core.themes.stripes = s.stripes; - this._data.core.themes.icons = s.icons; - this.set_theme(s.name || "default", s.url); - this.set_theme_variant(s.variant); - }, this)) - .on("loading.jstree", $.proxy(function () { - this[ this._data.core.themes.dots ? "show_dots" : "hide_dots" ](); - this[ this._data.core.themes.icons ? "show_icons" : "hide_icons" ](); - this[ this._data.core.themes.stripes ? "show_stripes" : "hide_stripes" ](); - }, this)) - .on('blur.jstree', '.jstree-anchor', $.proxy(function (e) { - $(e.currentTarget).filter('.jstree-hovered').mouseleave(); - }, this)) - .on('focus.jstree', '.jstree-anchor', $.proxy(function (e) { - this.element.find('.jstree-hovered').not(e.currentTarget).mouseleave(); - $(e.currentTarget).mouseenter(); - }, this)) - .on('mouseenter.jstree', '.jstree-anchor', $.proxy(function (e) { - this.hover_node(e.currentTarget); - }, this)) - .on('mouseleave.jstree', '.jstree-anchor', $.proxy(function (e) { - this.dehover_node(e.currentTarget); - }, this)); - }, - /** - * part of the destroying of an instance. Used internally. - * @private - * @name unbind() - */ - unbind : function () { - this.element.off('.jstree'); - $(document).off('.jstree-' + this._id); - }, - /** - * trigger an event. Used internally. - * @private - * @name trigger(ev [, data]) - * @param {String} ev the name of the event to trigger - * @param {Object} data additional data to pass with the event - */ - trigger : function (ev, data) { - if(!data) { - data = {}; - } - data.instance = this; - this.element.triggerHandler(ev.replace('.jstree','') + '.jstree', data); - }, - /** - * returns the jQuery extended instance container - * @name get_container() - * @return {jQuery} - */ - get_container : function () { - return this.element; - }, - /** - * returns the jQuery extended main UL node inside the instance container. Used internally. - * @private - * @name get_container_ul() - * @return {jQuery} - */ - get_container_ul : function () { - return this.element.children(".jstree-children:eq(0)"); - }, - /** - * gets string replacements (localization). Used internally. - * @private - * @name get_string(key) - * @param {String} key - * @return {String} - */ - get_string : function (key) { - var a = this.settings.core.strings; - if($.isFunction(a)) { return a.call(this, key); } - if(a && a[key]) { return a[key]; } - return key; - }, - /** - * gets the first child of a DOM node. Used internally. - * @private - * @name _firstChild(dom) - * @param {DOMElement} dom - * @return {DOMElement} - */ - _firstChild : function (dom) { - dom = dom ? dom.firstChild : null; - while(dom !== null && dom.nodeType !== 1) { - dom = dom.nextSibling; - } - return dom; - }, - /** - * gets the next sibling of a DOM node. Used internally. - * @private - * @name _nextSibling(dom) - * @param {DOMElement} dom - * @return {DOMElement} - */ - _nextSibling : function (dom) { - dom = dom ? dom.nextSibling : null; - while(dom !== null && dom.nodeType !== 1) { - dom = dom.nextSibling; - } - return dom; - }, - /** - * gets the previous sibling of a DOM node. Used internally. - * @private - * @name _previousSibling(dom) - * @param {DOMElement} dom - * @return {DOMElement} - */ - _previousSibling : function (dom) { - dom = dom ? dom.previousSibling : null; - while(dom !== null && dom.nodeType !== 1) { - dom = dom.previousSibling; - } - return dom; - }, - /** - * get the JSON representation of a node (or the actual jQuery extended DOM node) by using any input (child DOM element, ID string, selector, etc) - * @name get_node(obj [, as_dom]) - * @param {mixed} obj - * @param {Boolean} as_dom - * @return {Object|jQuery} - */ - get_node : function (obj, as_dom) { - if(obj && obj.id) { - obj = obj.id; - } - var dom; - try { - if(this._model.data[obj]) { - obj = this._model.data[obj]; - } - else if(((dom = $(obj, this.element)).length || (dom = $('#' + obj.replace($.jstree.idregex,'\\$&'), this.element)).length) && this._model.data[dom.closest('.jstree-node').attr('id')]) { - obj = this._model.data[dom.closest('.jstree-node').attr('id')]; - } - else if((dom = $(obj, this.element)).length && dom.hasClass('jstree')) { - obj = this._model.data['#']; - } - else { - return false; - } - - if(as_dom) { - obj = obj.id === '#' ? this.element : $('#' + obj.id.replace($.jstree.idregex,'\\$&'), this.element); - } - return obj; - } catch (ex) { return false; } - }, - /** - * get the path to a node, either consisting of node texts, or of node IDs, optionally glued together (otherwise an array) - * @name get_path(obj [, glue, ids]) - * @param {mixed} obj the node - * @param {String} glue if you want the path as a string - pass the glue here (for example '/'), if a falsy value is supplied here, an array is returned - * @param {Boolean} ids if set to true build the path using ID, otherwise node text is used - * @return {mixed} - */ - get_path : function (obj, glue, ids) { - obj = obj.parents ? obj : this.get_node(obj); - if(!obj || obj.id === '#' || !obj.parents) { - return false; - } - var i, j, p = []; - p.push(ids ? obj.id : obj.text); - for(i = 0, j = obj.parents.length; i < j; i++) { - p.push(ids ? obj.parents[i] : this.get_text(obj.parents[i])); - } - p = p.reverse().slice(1); - return glue ? p.join(glue) : p; - }, - /** - * get the next visible node that is below the `obj` node. If `strict` is set to `true` only sibling nodes are returned. - * @name get_next_dom(obj [, strict]) - * @param {mixed} obj - * @param {Boolean} strict - * @return {jQuery} - */ - get_next_dom : function (obj, strict) { - var tmp; - obj = this.get_node(obj, true); - if(obj[0] === this.element[0]) { - tmp = this._firstChild(this.get_container_ul()[0]); - return tmp ? $(tmp) : false; - } - if(!obj || !obj.length) { - return false; - } - if(strict) { - tmp = this._nextSibling(obj[0]); - return tmp ? $(tmp) : false; - } - if(obj.hasClass("jstree-open")) { - tmp = this._firstChild(obj.children('.jstree-children')[0]); - return tmp ? $(tmp) : false; - } - if((tmp = this._nextSibling(obj[0])) !== null) { - return $(tmp); - } - return obj.parentsUntil(".jstree",".jstree-node").next(".jstree-node").eq(0); - }, - /** - * get the previous visible node that is above the `obj` node. If `strict` is set to `true` only sibling nodes are returned. - * @name get_prev_dom(obj [, strict]) - * @param {mixed} obj - * @param {Boolean} strict - * @return {jQuery} - */ - get_prev_dom : function (obj, strict) { - var tmp; - obj = this.get_node(obj, true); - if(obj[0] === this.element[0]) { - tmp = this.get_container_ul()[0].lastChild; - return tmp ? $(tmp) : false; - } - if(!obj || !obj.length) { - return false; - } - if(strict) { - tmp = this._previousSibling(obj[0]); - return tmp ? $(tmp) : false; - } - if((tmp = this._previousSibling(obj[0])) !== null) { - obj = $(tmp); - while(obj.hasClass("jstree-open")) { - obj = obj.children(".jstree-children:eq(0)").children(".jstree-node:last"); - } - return obj; - } - tmp = obj[0].parentNode.parentNode; - return tmp && tmp.className && tmp.className.indexOf('jstree-node') !== -1 ? $(tmp) : false; - }, - /** - * get the parent ID of a node - * @name get_parent(obj) - * @param {mixed} obj - * @return {String} - */ - get_parent : function (obj) { - obj = this.get_node(obj); - if(!obj || obj.id === '#') { - return false; - } - return obj.parent; - }, - /** - * get a jQuery collection of all the children of a node (node must be rendered) - * @name get_children_dom(obj) - * @param {mixed} obj - * @return {jQuery} - */ - get_children_dom : function (obj) { - obj = this.get_node(obj, true); - if(obj[0] === this.element[0]) { - return this.get_container_ul().children(".jstree-node"); - } - if(!obj || !obj.length) { - return false; - } - return obj.children(".jstree-children").children(".jstree-node"); - }, - /** - * checks if a node has children - * @name is_parent(obj) - * @param {mixed} obj - * @return {Boolean} - */ - is_parent : function (obj) { - obj = this.get_node(obj); - return obj && (obj.state.loaded === false || obj.children.length > 0); - }, - /** - * checks if a node is loaded (its children are available) - * @name is_loaded(obj) - * @param {mixed} obj - * @return {Boolean} - */ - is_loaded : function (obj) { - obj = this.get_node(obj); - return obj && obj.state.loaded; - }, - /** - * check if a node is currently loading (fetching children) - * @name is_loading(obj) - * @param {mixed} obj - * @return {Boolean} - */ - is_loading : function (obj) { - obj = this.get_node(obj); - return obj && obj.state && obj.state.loading; - }, - /** - * check if a node is opened - * @name is_open(obj) - * @param {mixed} obj - * @return {Boolean} - */ - is_open : function (obj) { - obj = this.get_node(obj); - return obj && obj.state.opened; - }, - /** - * check if a node is in a closed state - * @name is_closed(obj) - * @param {mixed} obj - * @return {Boolean} - */ - is_closed : function (obj) { - obj = this.get_node(obj); - return obj && this.is_parent(obj) && !obj.state.opened; - }, - /** - * check if a node has no children - * @name is_leaf(obj) - * @param {mixed} obj - * @return {Boolean} - */ - is_leaf : function (obj) { - return !this.is_parent(obj); - }, - /** - * loads a node (fetches its children using the `core.data` setting). Multiple nodes can be passed to by using an array. - * @name load_node(obj [, callback]) - * @param {mixed} obj - * @param {function} callback a function to be executed once loading is complete, the function is executed in the instance's scope and receives two arguments - the node and a boolean status - * @return {Boolean} - * @trigger load_node.jstree - */ - load_node : function (obj, callback) { - var k, l, i, j, c; - if($.isArray(obj)) { - this._load_nodes(obj.slice(), callback); - return true; - } - obj = this.get_node(obj); - if(!obj) { - if(callback) { callback.call(this, obj, false); } - return false; - } - // if(obj.state.loading) { } // the node is already loading - just wait for it to load and invoke callback? but if called implicitly it should be loaded again? - if(obj.state.loaded) { - obj.state.loaded = false; - for(k = 0, l = obj.children_d.length; k < l; k++) { - for(i = 0, j = obj.parents.length; i < j; i++) { - this._model.data[obj.parents[i]].children_d = $.vakata.array_remove_item(this._model.data[obj.parents[i]].children_d, obj.children_d[k]); - } - if(this._model.data[obj.children_d[k]].state.selected) { - c = true; - this._data.core.selected = $.vakata.array_remove_item(this._data.core.selected, obj.children_d[k]); - } - delete this._model.data[obj.children_d[k]]; - } - obj.children = []; - obj.children_d = []; - if(c) { - this.trigger('changed', { 'action' : 'load_node', 'node' : obj, 'selected' : this._data.core.selected }); - } - } - obj.state.loading = true; - this.get_node(obj, true).addClass("jstree-loading"); - this._load_node(obj, $.proxy(function (status) { - obj = this._model.data[obj.id]; - obj.state.loading = false; - obj.state.loaded = status; - var dom = this.get_node(obj, true); - if(obj.state.loaded && !obj.children.length && dom && dom.length && !dom.hasClass('jstree-leaf')) { - dom.removeClass('jstree-closed jstree-open').addClass('jstree-leaf'); - } - dom.removeClass("jstree-loading"); - /** - * triggered after a node is loaded - * @event - * @name load_node.jstree - * @param {Object} node the node that was loading - * @param {Boolean} status was the node loaded successfully - */ - this.trigger('load_node', { "node" : obj, "status" : status }); - if(callback) { - callback.call(this, obj, status); - } - }, this)); - return true; - }, - /** - * load an array of nodes (will also load unavailable nodes as soon as the appear in the structure). Used internally. - * @private - * @name _load_nodes(nodes [, callback]) - * @param {array} nodes - * @param {function} callback a function to be executed once loading is complete, the function is executed in the instance's scope and receives one argument - the array passed to _load_nodes - */ - _load_nodes : function (nodes, callback, is_callback) { - var r = true, - c = function () { this._load_nodes(nodes, callback, true); }, - m = this._model.data, i, j; - for(i = 0, j = nodes.length; i < j; i++) { - if(m[nodes[i]] && (!m[nodes[i]].state.loaded || !is_callback)) { - if(!this.is_loading(nodes[i])) { - this.load_node(nodes[i], c); - } - r = false; - } - } - if(r) { - if(callback && !callback.done) { - callback.call(this, nodes); - callback.done = true; - } - } - }, - /** - * handles the actual loading of a node. Used only internally. - * @private - * @name _load_node(obj [, callback]) - * @param {mixed} obj - * @param {function} callback a function to be executed once loading is complete, the function is executed in the instance's scope and receives one argument - a boolean status - * @return {Boolean} - */ - _load_node : function (obj, callback) { - var s = this.settings.core.data, t; - // use original HTML - if(!s) { - if(obj.id === '#') { - return this._append_html_data(obj, this._data.core.original_container_html.clone(true), function (status) { - callback.call(this, status); - }); - } - else { - return callback.call(this, false); - } - // return callback.call(this, obj.id === '#' ? this._append_html_data(obj, this._data.core.original_container_html.clone(true)) : false); - } - if($.isFunction(s)) { - return s.call(this, obj, $.proxy(function (d) { - if(d === false) { - callback.call(this, false); - } - this[typeof d === 'string' ? '_append_html_data' : '_append_json_data'](obj, typeof d === 'string' ? $(d) : d, function (status) { - callback.call(this, status); - }); - // return d === false ? callback.call(this, false) : callback.call(this, this[typeof d === 'string' ? '_append_html_data' : '_append_json_data'](obj, typeof d === 'string' ? $(d) : d)); - }, this)); - } - if(typeof s === 'object') { - if(s.url) { - s = $.extend(true, {}, s); - if($.isFunction(s.url)) { - s.url = s.url.call(this, obj); - } - if($.isFunction(s.data)) { - s.data = s.data.call(this, obj); - } - return $.ajax(s) - .done($.proxy(function (d,t,x) { - var type = x.getResponseHeader('Content-Type'); - if(type.indexOf('json') !== -1 || typeof d === "object") { - return this._append_json_data(obj, d, function (status) { callback.call(this, status); }); - //return callback.call(this, this._append_json_data(obj, d)); - } - if(type.indexOf('html') !== -1 || typeof d === "string") { - return this._append_html_data(obj, $(d), function (status) { callback.call(this, status); }); - // return callback.call(this, this._append_html_data(obj, $(d))); - } - this._data.core.last_error = { 'error' : 'ajax', 'plugin' : 'core', 'id' : 'core_04', 'reason' : 'Could not load node', 'data' : JSON.stringify({ 'id' : obj.id, 'xhr' : x }) }; - this.settings.core.error.call(this, this._data.core.last_error); - return callback.call(this, false); - }, this)) - .fail($.proxy(function (f) { - callback.call(this, false); - this._data.core.last_error = { 'error' : 'ajax', 'plugin' : 'core', 'id' : 'core_04', 'reason' : 'Could not load node', 'data' : JSON.stringify({ 'id' : obj.id, 'xhr' : f }) }; - this.settings.core.error.call(this, this._data.core.last_error); - }, this)); - } - t = ($.isArray(s) || $.isPlainObject(s)) ? JSON.parse(JSON.stringify(s)) : s; - if(obj.id === '#') { - return this._append_json_data(obj, t, function (status) { - callback.call(this, status); - }); - } - else { - this._data.core.last_error = { 'error' : 'nodata', 'plugin' : 'core', 'id' : 'core_05', 'reason' : 'Could not load node', 'data' : JSON.stringify({ 'id' : obj.id }) }; - this.settings.core.error.call(this, this._data.core.last_error); - return callback.call(this, false); - } - //return callback.call(this, (obj.id === "#" ? this._append_json_data(obj, t) : false) ); - } - if(typeof s === 'string') { - if(obj.id === '#') { - return this._append_html_data(obj, $(s), function (status) { - callback.call(this, status); - }); - } - else { - this._data.core.last_error = { 'error' : 'nodata', 'plugin' : 'core', 'id' : 'core_06', 'reason' : 'Could not load node', 'data' : JSON.stringify({ 'id' : obj.id }) }; - this.settings.core.error.call(this, this._data.core.last_error); - return callback.call(this, false); - } - //return callback.call(this, (obj.id === "#" ? this._append_html_data(obj, $(s)) : false) ); - } - return callback.call(this, false); - }, - /** - * adds a node to the list of nodes to redraw. Used only internally. - * @private - * @name _node_changed(obj [, callback]) - * @param {mixed} obj - */ - _node_changed : function (obj) { - obj = this.get_node(obj); - if(obj) { - this._model.changed.push(obj.id); - } - }, - /** - * appends HTML content to the tree. Used internally. - * @private - * @name _append_html_data(obj, data) - * @param {mixed} obj the node to append to - * @param {String} data the HTML string to parse and append - * @trigger model.jstree, changed.jstree - */ - _append_html_data : function (dom, data, cb) { - dom = this.get_node(dom); - dom.children = []; - dom.children_d = []; - var dat = data.is('ul') ? data.children() : data, - par = dom.id, - chd = [], - dpc = [], - m = this._model.data, - p = m[par], - s = this._data.core.selected.length, - tmp, i, j; - dat.each($.proxy(function (i, v) { - tmp = this._parse_model_from_html($(v), par, p.parents.concat()); - if(tmp) { - chd.push(tmp); - dpc.push(tmp); - if(m[tmp].children_d.length) { - dpc = dpc.concat(m[tmp].children_d); - } - } - }, this)); - p.children = chd; - p.children_d = dpc; - for(i = 0, j = p.parents.length; i < j; i++) { - m[p.parents[i]].children_d = m[p.parents[i]].children_d.concat(dpc); - } - /** - * triggered when new data is inserted to the tree model - * @event - * @name model.jstree - * @param {Array} nodes an array of node IDs - * @param {String} parent the parent ID of the nodes - */ - this.trigger('model', { "nodes" : dpc, 'parent' : par }); - if(par !== '#') { - this._node_changed(par); - this.redraw(); - } - else { - this.get_container_ul().children('.jstree-initial-node').remove(); - this.redraw(true); - } - if(this._data.core.selected.length !== s) { - this.trigger('changed', { 'action' : 'model', 'selected' : this._data.core.selected }); - } - cb.call(this, true); - }, - /** - * appends JSON content to the tree. Used internally. - * @private - * @name _append_json_data(obj, data) - * @param {mixed} obj the node to append to - * @param {String} data the JSON object to parse and append - * @trigger model.jstree, changed.jstree - */ - _append_json_data : function (dom, data, cb) { - dom = this.get_node(dom); - dom.children = []; - dom.children_d = []; - // *%$@!!! - if(data.d) { - data = data.d; - if(typeof data === "string") { - data = JSON.parse(data); - } - } - if(!$.isArray(data)) { data = [data]; } - var w = null, - args = { - 'df' : this._model.default_state, - 'dat' : data, - 'par' : dom.id, - 'm' : this._model.data, - 't_id' : this._id, - 't_cnt' : this._cnt, - 'sel' : this._data.core.selected - }, - func = function (data, undefined) { - if(data.data) { data = data.data; } - var dat = data.dat, - par = data.par, - chd = [], - dpc = [], - add = [], - df = data.df, - t_id = data.t_id, - t_cnt = data.t_cnt, - m = data.m, - p = m[par], - sel = data.sel, - tmp, i, j, rslt, - parse_flat = function (d, p, ps) { - if(!ps) { ps = []; } - else { ps = ps.concat(); } - if(p) { ps.unshift(p); } - var tid = d.id.toString(), - i, j, c, e, - tmp = { - id : tid, - text : d.text || '', - icon : d.icon !== undefined ? d.icon : true, - parent : p, - parents : ps, - children : d.children || [], - children_d : d.children_d || [], - data : d.data, - state : { }, - li_attr : { id : false }, - a_attr : { href : '#' }, - original : false - }; - for(i in df) { - if(df.hasOwnProperty(i)) { - tmp.state[i] = df[i]; - } - } - if(d && d.data && d.data.jstree && d.data.jstree.icon) { - tmp.icon = d.data.jstree.icon; - } - if(d && d.data) { - tmp.data = d.data; - if(d.data.jstree) { - for(i in d.data.jstree) { - if(d.data.jstree.hasOwnProperty(i)) { - tmp.state[i] = d.data.jstree[i]; - } - } - } - } - if(d && typeof d.state === 'object') { - for (i in d.state) { - if(d.state.hasOwnProperty(i)) { - tmp.state[i] = d.state[i]; - } - } - } - if(d && typeof d.li_attr === 'object') { - for (i in d.li_attr) { - if(d.li_attr.hasOwnProperty(i)) { - tmp.li_attr[i] = d.li_attr[i]; - } - } - } - if(!tmp.li_attr.id) { - tmp.li_attr.id = tid; - } - if(d && typeof d.a_attr === 'object') { - for (i in d.a_attr) { - if(d.a_attr.hasOwnProperty(i)) { - tmp.a_attr[i] = d.a_attr[i]; - } - } - } - if(d && d.children && d.children === true) { - tmp.state.loaded = false; - tmp.children = []; - tmp.children_d = []; - } - m[tmp.id] = tmp; - for(i = 0, j = tmp.children.length; i < j; i++) { - c = parse_flat(m[tmp.children[i]], tmp.id, ps); - e = m[c]; - tmp.children_d.push(c); - if(e.children_d.length) { - tmp.children_d = tmp.children_d.concat(e.children_d); - } - } - delete d.data; - delete d.children; - m[tmp.id].original = d; - if(tmp.state.selected) { - add.push(tmp.id); - } - return tmp.id; - }, - parse_nest = function (d, p, ps) { - if(!ps) { ps = []; } - else { ps = ps.concat(); } - if(p) { ps.unshift(p); } - var tid = false, i, j, c, e, tmp; - do { - tid = 'j' + t_id + '_' + (++t_cnt); - } while(m[tid]); - - tmp = { - id : false, - text : typeof d === 'string' ? d : '', - icon : typeof d === 'object' && d.icon !== undefined ? d.icon : true, - parent : p, - parents : ps, - children : [], - children_d : [], - data : null, - state : { }, - li_attr : { id : false }, - a_attr : { href : '#' }, - original : false - }; - for(i in df) { - if(df.hasOwnProperty(i)) { - tmp.state[i] = df[i]; - } - } - if(d && d.id) { tmp.id = d.id.toString(); } - if(d && d.text) { tmp.text = d.text; } - if(d && d.data && d.data.jstree && d.data.jstree.icon) { - tmp.icon = d.data.jstree.icon; - } - if(d && d.data) { - tmp.data = d.data; - if(d.data.jstree) { - for(i in d.data.jstree) { - if(d.data.jstree.hasOwnProperty(i)) { - tmp.state[i] = d.data.jstree[i]; - } - } - } - } - if(d && typeof d.state === 'object') { - for (i in d.state) { - if(d.state.hasOwnProperty(i)) { - tmp.state[i] = d.state[i]; - } - } - } - if(d && typeof d.li_attr === 'object') { - for (i in d.li_attr) { - if(d.li_attr.hasOwnProperty(i)) { - tmp.li_attr[i] = d.li_attr[i]; - } - } - } - if(tmp.li_attr.id && !tmp.id) { - tmp.id = tmp.li_attr.id.toString(); - } - if(!tmp.id) { - tmp.id = tid; - } - if(!tmp.li_attr.id) { - tmp.li_attr.id = tmp.id; - } - if(d && typeof d.a_attr === 'object') { - for (i in d.a_attr) { - if(d.a_attr.hasOwnProperty(i)) { - tmp.a_attr[i] = d.a_attr[i]; - } - } - } - if(d && d.children && d.children.length) { - for(i = 0, j = d.children.length; i < j; i++) { - c = parse_nest(d.children[i], tmp.id, ps); - e = m[c]; - tmp.children.push(c); - if(e.children_d.length) { - tmp.children_d = tmp.children_d.concat(e.children_d); - } - } - tmp.children_d = tmp.children_d.concat(tmp.children); - } - if(d && d.children && d.children === true) { - tmp.state.loaded = false; - tmp.children = []; - tmp.children_d = []; - } - delete d.data; - delete d.children; - tmp.original = d; - m[tmp.id] = tmp; - if(tmp.state.selected) { - add.push(tmp.id); - } - return tmp.id; - }; - - if(dat.length && dat[0].id !== undefined && dat[0].parent !== undefined) { - // Flat JSON support (for easy import from DB): - // 1) convert to object (foreach) - for(i = 0, j = dat.length; i < j; i++) { - if(!dat[i].children) { - dat[i].children = []; - } - m[dat[i].id.toString()] = dat[i]; - } - // 2) populate children (foreach) - for(i = 0, j = dat.length; i < j; i++) { - m[dat[i].parent.toString()].children.push(dat[i].id.toString()); - // populate parent.children_d - p.children_d.push(dat[i].id.toString()); - } - // 3) normalize && populate parents and children_d with recursion - for(i = 0, j = p.children.length; i < j; i++) { - tmp = parse_flat(m[p.children[i]], par, p.parents.concat()); - dpc.push(tmp); - if(m[tmp].children_d.length) { - dpc = dpc.concat(m[tmp].children_d); - } - } - for(i = 0, j = p.parents.length; i < j; i++) { - m[p.parents[i]].children_d = m[p.parents[i]].children_d.concat(dpc); - } - // ?) three_state selection - p.state.selected && t - (if three_state foreach(dat => ch) -> foreach(parents) if(parent.selected) child.selected = true; - rslt = { - 'cnt' : t_cnt, - 'mod' : m, - 'sel' : sel, - 'par' : par, - 'dpc' : dpc, - 'add' : add - }; - } - else { - for(i = 0, j = dat.length; i < j; i++) { - tmp = parse_nest(dat[i], par, p.parents.concat()); - if(tmp) { - chd.push(tmp); - dpc.push(tmp); - if(m[tmp].children_d.length) { - dpc = dpc.concat(m[tmp].children_d); - } - } - } - p.children = chd; - p.children_d = dpc; - for(i = 0, j = p.parents.length; i < j; i++) { - m[p.parents[i]].children_d = m[p.parents[i]].children_d.concat(dpc); - } - rslt = { - 'cnt' : t_cnt, - 'mod' : m, - 'sel' : sel, - 'par' : par, - 'dpc' : dpc, - 'add' : add - }; - } - return rslt; - }, - rslt = function (rslt, worker) { - this._cnt = rslt.cnt; - this._model.data = rslt.mod; // breaks the reference in load_node - careful - - if(worker) { - var i, j, a = rslt.add, r = rslt.sel, s = this._data.core.selected.slice(), m = this._model.data; - // if selection was changed while calculating in worker - if(r.length !== s.length || $.vakata.array_unique(r.concat(s)).length !== r.length) { - // deselect nodes that are no longer selected - for(i = 0, j = r.length; i < j; i++) { - if($.inArray(r[i], a) === -1 && $.inArray(r[i], s) === -1) { - m[r[i]].state.selected = false; - } - } - // select nodes that were selected in the mean time - for(i = 0, j = s.length; i < j; i++) { - if($.inArray(s[i], r) === -1) { - m[s[i]].state.selected = true; - } - } - } - } - if(rslt.add.length) { - this._data.core.selected = this._data.core.selected.concat(rslt.add); - } - - this.trigger('model', { "nodes" : rslt.dpc, 'parent' : rslt.par }); - - if(rslt.par !== '#') { - this._node_changed(rslt.par); - this.redraw(); - } - else { - // this.get_container_ul().children('.jstree-initial-node').remove(); - this.redraw(true); - } - if(rslt.add.length) { - this.trigger('changed', { 'action' : 'model', 'selected' : this._data.core.selected }); - } - cb.call(this, true); - }; - if(this.settings.core.worker && window.Blob && window.URL && window.Worker) { - try { - if(this._wrk === null) { - this._wrk = window.URL.createObjectURL( - new window.Blob( - ['self.onmessage = ' + func.toString().replace(/return ([^;}]+)[\s;}]+$/, 'postMessage($1);}')], - {type:"text/javascript"} - ) - ); - } - w = new window.Worker(this._wrk); - w.onmessage = $.proxy(function (e) { - rslt.call(this, e.data, true); - this._data.core.working = false; - if(this._data.core.worker_queue.length) { - this._append_json_data.apply(this, this._data.core.worker_queue.shift()); - } - }, this); - if(!this._data.core.working) { - this._data.core.working = true; - w.postMessage(args); - } - else { - this._data.core.worker_queue.push([dom, data, cb]); - } - } - catch(e) { - rslt.call(this, func(args), false); - } - } - else { - rslt.call(this, func(args), false); - } - }, - /** - * parses a node from a jQuery object and appends them to the in memory tree model. Used internally. - * @private - * @name _parse_model_from_html(d [, p, ps]) - * @param {jQuery} d the jQuery object to parse - * @param {String} p the parent ID - * @param {Array} ps list of all parents - * @return {String} the ID of the object added to the model - */ - _parse_model_from_html : function (d, p, ps) { - if(!ps) { ps = []; } - else { ps = [].concat(ps); } - if(p) { ps.unshift(p); } - var c, e, m = this._model.data, - data = { - id : false, - text : false, - icon : true, - parent : p, - parents : ps, - children : [], - children_d : [], - data : null, - state : { }, - li_attr : { id : false }, - a_attr : { href : '#' }, - original : false - }, i, tmp, tid; - for(i in this._model.default_state) { - if(this._model.default_state.hasOwnProperty(i)) { - data.state[i] = this._model.default_state[i]; - } - } - tmp = $.vakata.attributes(d, true); - $.each(tmp, function (i, v) { - v = $.trim(v); - if(!v.length) { return true; } - data.li_attr[i] = v; - if(i === 'id') { - data.id = v.toString(); - } - }); - tmp = d.children('a').eq(0); - if(tmp.length) { - tmp = $.vakata.attributes(tmp, true); - $.each(tmp, function (i, v) { - v = $.trim(v); - if(v.length) { - data.a_attr[i] = v; - } - }); - } - tmp = d.children("a:eq(0)").length ? d.children("a:eq(0)").clone() : d.clone(); - tmp.children("ins, i, ul").remove(); - tmp = tmp.html(); - tmp = $('
      ').html(tmp); - data.text = this.settings.core.force_text ? tmp.text() : tmp.html(); - tmp = d.data(); - data.data = tmp ? $.extend(true, {}, tmp) : null; - data.state.opened = d.hasClass('jstree-open'); - data.state.selected = d.children('a').hasClass('jstree-clicked'); - data.state.disabled = d.children('a').hasClass('jstree-disabled'); - if(data.data && data.data.jstree) { - for(i in data.data.jstree) { - if(data.data.jstree.hasOwnProperty(i)) { - data.state[i] = data.data.jstree[i]; - } - } - } - tmp = d.children("a").children(".jstree-themeicon"); - if(tmp.length) { - data.icon = tmp.hasClass('jstree-themeicon-hidden') ? false : tmp.attr('rel'); - } - if(data.state.icon) { - data.icon = data.state.icon; - } - tmp = d.children("ul").children("li"); - do { - tid = 'j' + this._id + '_' + (++this._cnt); - } while(m[tid]); - data.id = data.li_attr.id ? data.li_attr.id.toString() : tid; - if(tmp.length) { - tmp.each($.proxy(function (i, v) { - c = this._parse_model_from_html($(v), data.id, ps); - e = this._model.data[c]; - data.children.push(c); - if(e.children_d.length) { - data.children_d = data.children_d.concat(e.children_d); - } - }, this)); - data.children_d = data.children_d.concat(data.children); - } - else { - if(d.hasClass('jstree-closed')) { - data.state.loaded = false; - } - } - if(data.li_attr['class']) { - data.li_attr['class'] = data.li_attr['class'].replace('jstree-closed','').replace('jstree-open',''); - } - if(data.a_attr['class']) { - data.a_attr['class'] = data.a_attr['class'].replace('jstree-clicked','').replace('jstree-disabled',''); - } - m[data.id] = data; - if(data.state.selected) { - this._data.core.selected.push(data.id); - } - return data.id; - }, - /** - * parses a node from a JSON object (used when dealing with flat data, which has no nesting of children, but has id and parent properties) and appends it to the in memory tree model. Used internally. - * @private - * @name _parse_model_from_flat_json(d [, p, ps]) - * @param {Object} d the JSON object to parse - * @param {String} p the parent ID - * @param {Array} ps list of all parents - * @return {String} the ID of the object added to the model - */ - _parse_model_from_flat_json : function (d, p, ps) { - if(!ps) { ps = []; } - else { ps = ps.concat(); } - if(p) { ps.unshift(p); } - var tid = d.id.toString(), - m = this._model.data, - df = this._model.default_state, - i, j, c, e, - tmp = { - id : tid, - text : d.text || '', - icon : d.icon !== undefined ? d.icon : true, - parent : p, - parents : ps, - children : d.children || [], - children_d : d.children_d || [], - data : d.data, - state : { }, - li_attr : { id : false }, - a_attr : { href : '#' }, - original : false - }; - for(i in df) { - if(df.hasOwnProperty(i)) { - tmp.state[i] = df[i]; - } - } - if(d && d.data && d.data.jstree && d.data.jstree.icon) { - tmp.icon = d.data.jstree.icon; - } - if(d && d.data) { - tmp.data = d.data; - if(d.data.jstree) { - for(i in d.data.jstree) { - if(d.data.jstree.hasOwnProperty(i)) { - tmp.state[i] = d.data.jstree[i]; - } - } - } - } - if(d && typeof d.state === 'object') { - for (i in d.state) { - if(d.state.hasOwnProperty(i)) { - tmp.state[i] = d.state[i]; - } - } - } - if(d && typeof d.li_attr === 'object') { - for (i in d.li_attr) { - if(d.li_attr.hasOwnProperty(i)) { - tmp.li_attr[i] = d.li_attr[i]; - } - } - } - if(!tmp.li_attr.id) { - tmp.li_attr.id = tid; - } - if(d && typeof d.a_attr === 'object') { - for (i in d.a_attr) { - if(d.a_attr.hasOwnProperty(i)) { - tmp.a_attr[i] = d.a_attr[i]; - } - } - } - if(d && d.children && d.children === true) { - tmp.state.loaded = false; - tmp.children = []; - tmp.children_d = []; - } - m[tmp.id] = tmp; - for(i = 0, j = tmp.children.length; i < j; i++) { - c = this._parse_model_from_flat_json(m[tmp.children[i]], tmp.id, ps); - e = m[c]; - tmp.children_d.push(c); - if(e.children_d.length) { - tmp.children_d = tmp.children_d.concat(e.children_d); - } - } - delete d.data; - delete d.children; - m[tmp.id].original = d; - if(tmp.state.selected) { - this._data.core.selected.push(tmp.id); - } - return tmp.id; - }, - /** - * parses a node from a JSON object and appends it to the in memory tree model. Used internally. - * @private - * @name _parse_model_from_json(d [, p, ps]) - * @param {Object} d the JSON object to parse - * @param {String} p the parent ID - * @param {Array} ps list of all parents - * @return {String} the ID of the object added to the model - */ - _parse_model_from_json : function (d, p, ps) { - if(!ps) { ps = []; } - else { ps = ps.concat(); } - if(p) { ps.unshift(p); } - var tid = false, i, j, c, e, m = this._model.data, df = this._model.default_state, tmp; - do { - tid = 'j' + this._id + '_' + (++this._cnt); - } while(m[tid]); - - tmp = { - id : false, - text : typeof d === 'string' ? d : '', - icon : typeof d === 'object' && d.icon !== undefined ? d.icon : true, - parent : p, - parents : ps, - children : [], - children_d : [], - data : null, - state : { }, - li_attr : { id : false }, - a_attr : { href : '#' }, - original : false - }; - for(i in df) { - if(df.hasOwnProperty(i)) { - tmp.state[i] = df[i]; - } - } - if(d && d.id) { tmp.id = d.id.toString(); } - if(d && d.text) { tmp.text = d.text; } - if(d && d.data && d.data.jstree && d.data.jstree.icon) { - tmp.icon = d.data.jstree.icon; - } - if(d && d.data) { - tmp.data = d.data; - if(d.data.jstree) { - for(i in d.data.jstree) { - if(d.data.jstree.hasOwnProperty(i)) { - tmp.state[i] = d.data.jstree[i]; - } - } - } - } - if(d && typeof d.state === 'object') { - for (i in d.state) { - if(d.state.hasOwnProperty(i)) { - tmp.state[i] = d.state[i]; - } - } - } - if(d && typeof d.li_attr === 'object') { - for (i in d.li_attr) { - if(d.li_attr.hasOwnProperty(i)) { - tmp.li_attr[i] = d.li_attr[i]; - } - } - } - if(tmp.li_attr.id && !tmp.id) { - tmp.id = tmp.li_attr.id.toString(); - } - if(!tmp.id) { - tmp.id = tid; - } - if(!tmp.li_attr.id) { - tmp.li_attr.id = tmp.id; - } - if(d && typeof d.a_attr === 'object') { - for (i in d.a_attr) { - if(d.a_attr.hasOwnProperty(i)) { - tmp.a_attr[i] = d.a_attr[i]; - } - } - } - if(d && d.children && d.children.length) { - for(i = 0, j = d.children.length; i < j; i++) { - c = this._parse_model_from_json(d.children[i], tmp.id, ps); - e = m[c]; - tmp.children.push(c); - if(e.children_d.length) { - tmp.children_d = tmp.children_d.concat(e.children_d); - } - } - tmp.children_d = tmp.children_d.concat(tmp.children); - } - if(d && d.children && d.children === true) { - tmp.state.loaded = false; - tmp.children = []; - tmp.children_d = []; - } - delete d.data; - delete d.children; - tmp.original = d; - m[tmp.id] = tmp; - if(tmp.state.selected) { - this._data.core.selected.push(tmp.id); - } - return tmp.id; - }, - /** - * redraws all nodes that need to be redrawn. Used internally. - * @private - * @name _redraw() - * @trigger redraw.jstree - */ - _redraw : function () { - var nodes = this._model.force_full_redraw ? this._model.data['#'].children.concat([]) : this._model.changed.concat([]), - f = document.createElement('UL'), tmp, i, j; - for(i = 0, j = nodes.length; i < j; i++) { - tmp = this.redraw_node(nodes[i], true, this._model.force_full_redraw); - if(tmp && this._model.force_full_redraw) { - f.appendChild(tmp); - } - } - if(this._model.force_full_redraw) { - f.className = this.get_container_ul()[0].className; - this.element.empty().append(f); - //this.get_container_ul()[0].appendChild(f); - } - this._model.force_full_redraw = false; - this._model.changed = []; - /** - * triggered after nodes are redrawn - * @event - * @name redraw.jstree - * @param {array} nodes the redrawn nodes - */ - this.trigger('redraw', { "nodes" : nodes }); - }, - /** - * redraws all nodes that need to be redrawn or optionally - the whole tree - * @name redraw([full]) - * @param {Boolean} full if set to `true` all nodes are redrawn. - */ - redraw : function (full) { - if(full) { - this._model.force_full_redraw = true; - } - //if(this._model.redraw_timeout) { - // clearTimeout(this._model.redraw_timeout); - //} - //this._model.redraw_timeout = setTimeout($.proxy(this._redraw, this),0); - this._redraw(); - }, - /** - * redraws a single node. Used internally. - * @private - * @name redraw_node(node, deep, is_callback) - * @param {mixed} node the node to redraw - * @param {Boolean} deep should child nodes be redrawn too - * @param {Boolean} is_callback is this a recursion call - */ - redraw_node : function (node, deep, is_callback) { - var obj = this.get_node(node), - par = false, - ind = false, - old = false, - i = false, - j = false, - k = false, - c = '', - d = document, - m = this._model.data, - f = false, - s = false, - tmp = null; - if(!obj) { return false; } - if(obj.id === '#') { return this.redraw(true); } - deep = deep || obj.children.length === 0; - node = !document.querySelector ? document.getElementById(obj.id) : this.element[0].querySelector('#' + ("0123456789".indexOf(obj.id[0]) !== -1 ? '\\3' + obj.id[0] + ' ' + obj.id.substr(1).replace($.jstree.idregex,'\\$&') : obj.id.replace($.jstree.idregex,'\\$&')) ); //, this.element); - if(!node) { - deep = true; - //node = d.createElement('LI'); - if(!is_callback) { - par = obj.parent !== '#' ? $('#' + obj.parent.replace($.jstree.idregex,'\\$&'), this.element)[0] : null; - if(par !== null && (!par || !m[obj.parent].state.opened)) { - return false; - } - ind = $.inArray(obj.id, par === null ? m['#'].children : m[obj.parent].children); - } - } - else { - node = $(node); - if(!is_callback) { - par = node.parent().parent()[0]; - if(par === this.element[0]) { - par = null; - } - ind = node.index(); - } - // m[obj.id].data = node.data(); // use only node's data, no need to touch jquery storage - if(!deep && obj.children.length && !node.children('.jstree-children').length) { - deep = true; - } - if(!deep) { - old = node.children('.jstree-children')[0]; - } - s = node.attr('aria-selected'); - f = node.children('.jstree-anchor')[0] === document.activeElement; - node.remove(); - //node = d.createElement('LI'); - //node = node[0]; - } - node = _node.cloneNode(true); - // node is DOM, deep is boolean - - c = 'jstree-node '; - for(i in obj.li_attr) { - if(obj.li_attr.hasOwnProperty(i)) { - if(i === 'id') { continue; } - if(i !== 'class') { - node.setAttribute(i, obj.li_attr[i]); - } - else { - c += obj.li_attr[i]; - } - } - } - if(s && s !== "false") { - node.setAttribute('aria-selected', true); - } - if(obj.state.loaded && !obj.children.length) { - c += ' jstree-leaf'; - } - else { - c += obj.state.opened && obj.state.loaded ? ' jstree-open' : ' jstree-closed'; - node.setAttribute('aria-expanded', (obj.state.opened && obj.state.loaded) ); - } - if(obj.parent !== null && m[obj.parent].children[m[obj.parent].children.length - 1] === obj.id) { - c += ' jstree-last'; - } - node.id = obj.id; - node.className = c; - c = ( obj.state.selected ? ' jstree-clicked' : '') + ( obj.state.disabled ? ' jstree-disabled' : ''); - for(j in obj.a_attr) { - if(obj.a_attr.hasOwnProperty(j)) { - if(j === 'href' && obj.a_attr[j] === '#') { continue; } - if(j !== 'class') { - node.childNodes[1].setAttribute(j, obj.a_attr[j]); - } - else { - c += ' ' + obj.a_attr[j]; - } - } - } - if(c.length) { - node.childNodes[1].className = 'jstree-anchor ' + c; - } - if((obj.icon && obj.icon !== true) || obj.icon === false) { - if(obj.icon === false) { - node.childNodes[1].childNodes[0].className += ' jstree-themeicon-hidden'; - } - else if(obj.icon.indexOf('/') === -1 && obj.icon.indexOf('.') === -1) { - node.childNodes[1].childNodes[0].className += ' ' + obj.icon + ' jstree-themeicon-custom'; - } - else { - node.childNodes[1].childNodes[0].style.backgroundImage = 'url('+obj.icon+')'; - node.childNodes[1].childNodes[0].style.backgroundPosition = 'center center'; - node.childNodes[1].childNodes[0].style.backgroundSize = 'auto'; - node.childNodes[1].childNodes[0].className += ' jstree-themeicon-custom'; - } - } - - if(this.settings.core.force_text) { - node.childNodes[1].appendChild(d.createTextNode(obj.text)); - } - else { - node.childNodes[1].innerHTML += obj.text; - } - - if(deep && obj.children.length && obj.state.opened && obj.state.loaded) { - k = d.createElement('UL'); - k.setAttribute('role', 'group'); - k.className = 'jstree-children'; - for(i = 0, j = obj.children.length; i < j; i++) { - k.appendChild(this.redraw_node(obj.children[i], deep, true)); - } - node.appendChild(k); - } - if(old) { - node.appendChild(old); - } - if(!is_callback) { - // append back using par / ind - if(!par) { - par = this.element[0]; - } - for(i = 0, j = par.childNodes.length; i < j; i++) { - if(par.childNodes[i] && par.childNodes[i].className && par.childNodes[i].className.indexOf('jstree-children') !== -1) { - tmp = par.childNodes[i]; - break; - } - } - if(!tmp) { - tmp = d.createElement('UL'); - tmp.setAttribute('role', 'group'); - tmp.className = 'jstree-children'; - par.appendChild(tmp); - } - par = tmp; - - if(ind < par.childNodes.length) { - par.insertBefore(node, par.childNodes[ind]); - } - else { - par.appendChild(node); - } - if(f) { - node.childNodes[1].focus(); - } - } - if(obj.state.opened && !obj.state.loaded) { - obj.state.opened = false; - setTimeout($.proxy(function () { - this.open_node(obj.id, false, 0); - }, this), 0); - } - return node; - }, - /** - * opens a node, revaling its children. If the node is not loaded it will be loaded and opened once ready. - * @name open_node(obj [, callback, animation]) - * @param {mixed} obj the node to open - * @param {Function} callback a function to execute once the node is opened - * @param {Number} animation the animation duration in milliseconds when opening the node (overrides the `core.animation` setting). Use `false` for no animation. - * @trigger open_node.jstree, after_open.jstree, before_open.jstree - */ - open_node : function (obj, callback, animation) { - var t1, t2, d, t; - if($.isArray(obj)) { - obj = obj.slice(); - for(t1 = 0, t2 = obj.length; t1 < t2; t1++) { - this.open_node(obj[t1], callback, animation); - } - return true; - } - obj = this.get_node(obj); - if(!obj || obj.id === '#') { - return false; - } - animation = animation === undefined ? this.settings.core.animation : animation; - if(!this.is_closed(obj)) { - if(callback) { - callback.call(this, obj, false); - } - return false; - } - if(!this.is_loaded(obj)) { - if(this.is_loading(obj)) { - return setTimeout($.proxy(function () { - this.open_node(obj, callback, animation); - }, this), 500); - } - this.load_node(obj, function (o, ok) { - return ok ? this.open_node(o, callback, animation) : (callback ? callback.call(this, o, false) : false); - }); - } - else { - d = this.get_node(obj, true); - t = this; - if(d.length) { - if(obj.children.length && !this._firstChild(d.children('.jstree-children')[0])) { - obj.state.opened = true; - this.redraw_node(obj, true); - d = this.get_node(obj, true); - } - if(!animation) { - this.trigger('before_open', { "node" : obj }); - d[0].className = d[0].className.replace('jstree-closed', 'jstree-open'); - d[0].setAttribute("aria-expanded", true); - } - else { - this.trigger('before_open', { "node" : obj }); - d - .children(".jstree-children").css("display","none").end() - .removeClass("jstree-closed").addClass("jstree-open").attr("aria-expanded", true) - .children(".jstree-children").stop(true, true) - .slideDown(animation, function () { - this.style.display = ""; - t.trigger("after_open", { "node" : obj }); - }); - } - } - obj.state.opened = true; - if(callback) { - callback.call(this, obj, true); - } - if(!d.length) { - /** - * triggered when a node is about to be opened (if the node is supposed to be in the DOM, it will be, but it won't be visible yet) - * @event - * @name before_open.jstree - * @param {Object} node the opened node - */ - this.trigger('before_open', { "node" : obj }); - } - /** - * triggered when a node is opened (if there is an animation it will not be completed yet) - * @event - * @name open_node.jstree - * @param {Object} node the opened node - */ - this.trigger('open_node', { "node" : obj }); - if(!animation || !d.length) { - /** - * triggered when a node is opened and the animation is complete - * @event - * @name after_open.jstree - * @param {Object} node the opened node - */ - this.trigger("after_open", { "node" : obj }); - } - } - }, - /** - * opens every parent of a node (node should be loaded) - * @name _open_to(obj) - * @param {mixed} obj the node to reveal - * @private - */ - _open_to : function (obj) { - obj = this.get_node(obj); - if(!obj || obj.id === '#') { - return false; - } - var i, j, p = obj.parents; - for(i = 0, j = p.length; i < j; i+=1) { - if(i !== '#') { - this.open_node(p[i], false, 0); - } - } - return $('#' + obj.id.replace($.jstree.idregex,'\\$&'), this.element); - }, - /** - * closes a node, hiding its children - * @name close_node(obj [, animation]) - * @param {mixed} obj the node to close - * @param {Number} animation the animation duration in milliseconds when closing the node (overrides the `core.animation` setting). Use `false` for no animation. - * @trigger close_node.jstree, after_close.jstree - */ - close_node : function (obj, animation) { - var t1, t2, t, d; - if($.isArray(obj)) { - obj = obj.slice(); - for(t1 = 0, t2 = obj.length; t1 < t2; t1++) { - this.close_node(obj[t1], animation); - } - return true; - } - obj = this.get_node(obj); - if(!obj || obj.id === '#') { - return false; - } - if(this.is_closed(obj)) { - return false; - } - animation = animation === undefined ? this.settings.core.animation : animation; - t = this; - d = this.get_node(obj, true); - if(d.length) { - if(!animation) { - d[0].className = d[0].className.replace('jstree-open', 'jstree-closed'); - d.attr("aria-expanded", false).children('.jstree-children').remove(); - } - else { - d - .children(".jstree-children").attr("style","display:block !important").end() - .removeClass("jstree-open").addClass("jstree-closed").attr("aria-expanded", false) - .children(".jstree-children").stop(true, true).slideUp(animation, function () { - this.style.display = ""; - d.children('.jstree-children').remove(); - t.trigger("after_close", { "node" : obj }); - }); - } - } - obj.state.opened = false; - /** - * triggered when a node is closed (if there is an animation it will not be complete yet) - * @event - * @name close_node.jstree - * @param {Object} node the closed node - */ - this.trigger('close_node',{ "node" : obj }); - if(!animation || !d.length) { - /** - * triggered when a node is closed and the animation is complete - * @event - * @name after_close.jstree - * @param {Object} node the closed node - */ - this.trigger("after_close", { "node" : obj }); - } - }, - /** - * toggles a node - closing it if it is open, opening it if it is closed - * @name toggle_node(obj) - * @param {mixed} obj the node to toggle - */ - toggle_node : function (obj) { - var t1, t2; - if($.isArray(obj)) { - obj = obj.slice(); - for(t1 = 0, t2 = obj.length; t1 < t2; t1++) { - this.toggle_node(obj[t1]); - } - return true; - } - if(this.is_closed(obj)) { - return this.open_node(obj); - } - if(this.is_open(obj)) { - return this.close_node(obj); - } - }, - /** - * opens all nodes within a node (or the tree), revaling their children. If the node is not loaded it will be loaded and opened once ready. - * @name open_all([obj, animation, original_obj]) - * @param {mixed} obj the node to open recursively, omit to open all nodes in the tree - * @param {Number} animation the animation duration in milliseconds when opening the nodes, the default is no animation - * @param {jQuery} reference to the node that started the process (internal use) - * @trigger open_all.jstree - */ - open_all : function (obj, animation, original_obj) { - if(!obj) { obj = '#'; } - obj = this.get_node(obj); - if(!obj) { return false; } - var dom = obj.id === '#' ? this.get_container_ul() : this.get_node(obj, true), i, j, _this; - if(!dom.length) { - for(i = 0, j = obj.children_d.length; i < j; i++) { - if(this.is_closed(this._model.data[obj.children_d[i]])) { - this._model.data[obj.children_d[i]].state.opened = true; - } - } - return this.trigger('open_all', { "node" : obj }); - } - original_obj = original_obj || dom; - _this = this; - dom = this.is_closed(obj) ? dom.find('.jstree-closed').addBack() : dom.find('.jstree-closed'); - dom.each(function () { - _this.open_node( - this, - function(node, status) { if(status && this.is_parent(node)) { this.open_all(node, animation, original_obj); } }, - animation || 0 - ); - }); - if(original_obj.find('.jstree-closed').length === 0) { - /** - * triggered when an `open_all` call completes - * @event - * @name open_all.jstree - * @param {Object} node the opened node - */ - this.trigger('open_all', { "node" : this.get_node(original_obj) }); - } - }, - /** - * closes all nodes within a node (or the tree), revaling their children - * @name close_all([obj, animation]) - * @param {mixed} obj the node to close recursively, omit to close all nodes in the tree - * @param {Number} animation the animation duration in milliseconds when closing the nodes, the default is no animation - * @trigger close_all.jstree - */ - close_all : function (obj, animation) { - if(!obj) { obj = '#'; } - obj = this.get_node(obj); - if(!obj) { return false; } - var dom = obj.id === '#' ? this.get_container_ul() : this.get_node(obj, true), - _this = this, i, j; - if(!dom.length) { - for(i = 0, j = obj.children_d.length; i < j; i++) { - this._model.data[obj.children_d[i]].state.opened = false; - } - return this.trigger('close_all', { "node" : obj }); - } - dom = this.is_open(obj) ? dom.find('.jstree-open').addBack() : dom.find('.jstree-open'); - $(dom.get().reverse()).each(function () { _this.close_node(this, animation || 0); }); - /** - * triggered when an `close_all` call completes - * @event - * @name close_all.jstree - * @param {Object} node the closed node - */ - this.trigger('close_all', { "node" : obj }); - }, - /** - * checks if a node is disabled (not selectable) - * @name is_disabled(obj) - * @param {mixed} obj - * @return {Boolean} - */ - is_disabled : function (obj) { - obj = this.get_node(obj); - return obj && obj.state && obj.state.disabled; - }, - /** - * enables a node - so that it can be selected - * @name enable_node(obj) - * @param {mixed} obj the node to enable - * @trigger enable_node.jstree - */ - enable_node : function (obj) { - var t1, t2; - if($.isArray(obj)) { - obj = obj.slice(); - for(t1 = 0, t2 = obj.length; t1 < t2; t1++) { - this.enable_node(obj[t1]); - } - return true; - } - obj = this.get_node(obj); - if(!obj || obj.id === '#') { - return false; - } - obj.state.disabled = false; - this.get_node(obj,true).children('.jstree-anchor').removeClass('jstree-disabled'); - /** - * triggered when an node is enabled - * @event - * @name enable_node.jstree - * @param {Object} node the enabled node - */ - this.trigger('enable_node', { 'node' : obj }); - }, - /** - * disables a node - so that it can not be selected - * @name disable_node(obj) - * @param {mixed} obj the node to disable - * @trigger disable_node.jstree - */ - disable_node : function (obj) { - var t1, t2; - if($.isArray(obj)) { - obj = obj.slice(); - for(t1 = 0, t2 = obj.length; t1 < t2; t1++) { - this.disable_node(obj[t1]); - } - return true; - } - obj = this.get_node(obj); - if(!obj || obj.id === '#') { - return false; - } - obj.state.disabled = true; - this.get_node(obj,true).children('.jstree-anchor').addClass('jstree-disabled'); - /** - * triggered when an node is disabled - * @event - * @name disable_node.jstree - * @param {Object} node the disabled node - */ - this.trigger('disable_node', { 'node' : obj }); - }, - /** - * called when a node is selected by the user. Used internally. - * @private - * @name activate_node(obj, e) - * @param {mixed} obj the node - * @param {Object} e the related event - * @trigger activate_node.jstree - */ - activate_node : function (obj, e) { - if(this.is_disabled(obj)) { - return false; - } - - // ensure last_clicked is still in the DOM, make it fresh (maybe it was moved?) and make sure it is still selected, if not - make last_clicked the last selected node - this._data.core.last_clicked = this._data.core.last_clicked && this._data.core.last_clicked.id !== undefined ? this.get_node(this._data.core.last_clicked.id) : null; - if(this._data.core.last_clicked && !this._data.core.last_clicked.state.selected) { this._data.core.last_clicked = null; } - if(!this._data.core.last_clicked && this._data.core.selected.length) { this._data.core.last_clicked = this.get_node(this._data.core.selected[this._data.core.selected.length - 1]); } - - if(!this.settings.core.multiple || (!e.metaKey && !e.ctrlKey && !e.shiftKey) || (e.shiftKey && (!this._data.core.last_clicked || !this.get_parent(obj) || this.get_parent(obj) !== this._data.core.last_clicked.parent ) )) { - if(!this.settings.core.multiple && (e.metaKey || e.ctrlKey || e.shiftKey) && this.is_selected(obj)) { - this.deselect_node(obj, false, e); - } - else { - this.deselect_all(true); - this.select_node(obj, false, false, e); - this._data.core.last_clicked = this.get_node(obj); - } - } - else { - if(e.shiftKey) { - var o = this.get_node(obj).id, - l = this._data.core.last_clicked.id, - p = this.get_node(this._data.core.last_clicked.parent).children, - c = false, - i, j; - for(i = 0, j = p.length; i < j; i += 1) { - // separate IFs work whem o and l are the same - if(p[i] === o) { - c = !c; - } - if(p[i] === l) { - c = !c; - } - if(c || p[i] === o || p[i] === l) { - this.select_node(p[i], false, false, e); - } - else { - this.deselect_node(p[i], false, e); - } - } - } - else { - if(!this.is_selected(obj)) { - this.select_node(obj, false, false, e); - } - else { - this.deselect_node(obj, false, e); - } - } - } - /** - * triggered when an node is clicked or intercated with by the user - * @event - * @name activate_node.jstree - * @param {Object} node - */ - this.trigger('activate_node', { 'node' : this.get_node(obj) }); - }, - /** - * applies the hover state on a node, called when a node is hovered by the user. Used internally. - * @private - * @name hover_node(obj) - * @param {mixed} obj - * @trigger hover_node.jstree - */ - hover_node : function (obj) { - obj = this.get_node(obj, true); - if(!obj || !obj.length || obj.children('.jstree-hovered').length) { - return false; - } - var o = this.element.find('.jstree-hovered'), t = this.element; - if(o && o.length) { this.dehover_node(o); } - - obj.children('.jstree-anchor').addClass('jstree-hovered'); - /** - * triggered when an node is hovered - * @event - * @name hover_node.jstree - * @param {Object} node - */ - this.trigger('hover_node', { 'node' : this.get_node(obj) }); - setTimeout(function () { t.attr('aria-activedescendant', obj[0].id); obj.attr('aria-selected', true); }, 0); - }, - /** - * removes the hover state from a nodecalled when a node is no longer hovered by the user. Used internally. - * @private - * @name dehover_node(obj) - * @param {mixed} obj - * @trigger dehover_node.jstree - */ - dehover_node : function (obj) { - obj = this.get_node(obj, true); - if(!obj || !obj.length || !obj.children('.jstree-hovered').length) { - return false; - } - obj.attr('aria-selected', false).children('.jstree-anchor').removeClass('jstree-hovered'); - /** - * triggered when an node is no longer hovered - * @event - * @name dehover_node.jstree - * @param {Object} node - */ - this.trigger('dehover_node', { 'node' : this.get_node(obj) }); - }, - /** - * select a node - * @name select_node(obj [, supress_event, prevent_open]) - * @param {mixed} obj an array can be used to select multiple nodes - * @param {Boolean} supress_event if set to `true` the `changed.jstree` event won't be triggered - * @param {Boolean} prevent_open if set to `true` parents of the selected node won't be opened - * @trigger select_node.jstree, changed.jstree - */ - select_node : function (obj, supress_event, prevent_open, e) { - var dom, t1, t2, th; - if($.isArray(obj)) { - obj = obj.slice(); - for(t1 = 0, t2 = obj.length; t1 < t2; t1++) { - this.select_node(obj[t1], supress_event, prevent_open, e); - } - return true; - } - obj = this.get_node(obj); - if(!obj || obj.id === '#') { - return false; - } - dom = this.get_node(obj, true); - if(!obj.state.selected) { - obj.state.selected = true; - this._data.core.selected.push(obj.id); - if(!prevent_open) { - dom = this._open_to(obj); - } - if(dom && dom.length) { - dom.children('.jstree-anchor').addClass('jstree-clicked'); - } - /** - * triggered when an node is selected - * @event - * @name select_node.jstree - * @param {Object} node - * @param {Array} selected the current selection - * @param {Object} event the event (if any) that triggered this select_node - */ - this.trigger('select_node', { 'node' : obj, 'selected' : this._data.core.selected, 'event' : e }); - if(!supress_event) { - /** - * triggered when selection changes - * @event - * @name changed.jstree - * @param {Object} node - * @param {Object} action the action that caused the selection to change - * @param {Array} selected the current selection - * @param {Object} event the event (if any) that triggered this changed event - */ - this.trigger('changed', { 'action' : 'select_node', 'node' : obj, 'selected' : this._data.core.selected, 'event' : e }); - } - } - }, - /** - * deselect a node - * @name deselect_node(obj [, supress_event]) - * @param {mixed} obj an array can be used to deselect multiple nodes - * @param {Boolean} supress_event if set to `true` the `changed.jstree` event won't be triggered - * @trigger deselect_node.jstree, changed.jstree - */ - deselect_node : function (obj, supress_event, e) { - var t1, t2, dom; - if($.isArray(obj)) { - obj = obj.slice(); - for(t1 = 0, t2 = obj.length; t1 < t2; t1++) { - this.deselect_node(obj[t1], supress_event, e); - } - return true; - } - obj = this.get_node(obj); - if(!obj || obj.id === '#') { - return false; - } - dom = this.get_node(obj, true); - if(obj.state.selected) { - obj.state.selected = false; - this._data.core.selected = $.vakata.array_remove_item(this._data.core.selected, obj.id); - if(dom.length) { - dom.children('.jstree-anchor').removeClass('jstree-clicked'); - } - /** - * triggered when an node is deselected - * @event - * @name deselect_node.jstree - * @param {Object} node - * @param {Array} selected the current selection - * @param {Object} event the event (if any) that triggered this deselect_node - */ - this.trigger('deselect_node', { 'node' : obj, 'selected' : this._data.core.selected, 'event' : e }); - if(!supress_event) { - this.trigger('changed', { 'action' : 'deselect_node', 'node' : obj, 'selected' : this._data.core.selected, 'event' : e }); - } - } - }, - /** - * select all nodes in the tree - * @name select_all([supress_event]) - * @param {Boolean} supress_event if set to `true` the `changed.jstree` event won't be triggered - * @trigger select_all.jstree, changed.jstree - */ - select_all : function (supress_event) { - var tmp = this._data.core.selected.concat([]), i, j; - this._data.core.selected = this._model.data['#'].children_d.concat(); - for(i = 0, j = this._data.core.selected.length; i < j; i++) { - if(this._model.data[this._data.core.selected[i]]) { - this._model.data[this._data.core.selected[i]].state.selected = true; - } - } - this.redraw(true); - /** - * triggered when all nodes are selected - * @event - * @name select_all.jstree - * @param {Array} selected the current selection - */ - this.trigger('select_all', { 'selected' : this._data.core.selected }); - if(!supress_event) { - this.trigger('changed', { 'action' : 'select_all', 'selected' : this._data.core.selected, 'old_selection' : tmp }); - } - }, - /** - * deselect all selected nodes - * @name deselect_all([supress_event]) - * @param {Boolean} supress_event if set to `true` the `changed.jstree` event won't be triggered - * @trigger deselect_all.jstree, changed.jstree - */ - deselect_all : function (supress_event) { - var tmp = this._data.core.selected.concat([]), i, j; - for(i = 0, j = this._data.core.selected.length; i < j; i++) { - if(this._model.data[this._data.core.selected[i]]) { - this._model.data[this._data.core.selected[i]].state.selected = false; - } - } - this._data.core.selected = []; - this.element.find('.jstree-clicked').removeClass('jstree-clicked'); - /** - * triggered when all nodes are deselected - * @event - * @name deselect_all.jstree - * @param {Object} node the previous selection - * @param {Array} selected the current selection - */ - this.trigger('deselect_all', { 'selected' : this._data.core.selected, 'node' : tmp }); - if(!supress_event) { - this.trigger('changed', { 'action' : 'deselect_all', 'selected' : this._data.core.selected, 'old_selection' : tmp }); - } - }, - /** - * checks if a node is selected - * @name is_selected(obj) - * @param {mixed} obj - * @return {Boolean} - */ - is_selected : function (obj) { - obj = this.get_node(obj); - if(!obj || obj.id === '#') { - return false; - } - return obj.state.selected; - }, - /** - * get an array of all selected nodes - * @name get_selected([full]) - * @param {mixed} full if set to `true` the returned array will consist of the full node objects, otherwise - only IDs will be returned - * @return {Array} - */ - get_selected : function (full) { - return full ? $.map(this._data.core.selected, $.proxy(function (i) { return this.get_node(i); }, this)) : this._data.core.selected.slice(); - }, - /** - * get an array of all top level selected nodes (ignoring children of selected nodes) - * @name get_top_selected([full]) - * @param {mixed} full if set to `true` the returned array will consist of the full node objects, otherwise - only IDs will be returned - * @return {Array} - */ - get_top_selected : function (full) { - var tmp = this.get_selected(true), - obj = {}, i, j, k, l; - for(i = 0, j = tmp.length; i < j; i++) { - obj[tmp[i].id] = tmp[i]; - } - for(i = 0, j = tmp.length; i < j; i++) { - for(k = 0, l = tmp[i].children_d.length; k < l; k++) { - if(obj[tmp[i].children_d[k]]) { - delete obj[tmp[i].children_d[k]]; - } - } - } - tmp = []; - for(i in obj) { - if(obj.hasOwnProperty(i)) { - tmp.push(i); - } - } - return full ? $.map(tmp, $.proxy(function (i) { return this.get_node(i); }, this)) : tmp; - }, - /** - * get an array of all bottom level selected nodes (ignoring selected parents) - * @name get_bottom_selected([full]) - * @param {mixed} full if set to `true` the returned array will consist of the full node objects, otherwise - only IDs will be returned - * @return {Array} - */ - get_bottom_selected : function (full) { - var tmp = this.get_selected(true), - obj = [], i, j; - for(i = 0, j = tmp.length; i < j; i++) { - if(!tmp[i].children.length) { - obj.push(tmp[i].id); - } - } - return full ? $.map(obj, $.proxy(function (i) { return this.get_node(i); }, this)) : obj; - }, - /** - * gets the current state of the tree so that it can be restored later with `set_state(state)`. Used internally. - * @name get_state() - * @private - * @return {Object} - */ - get_state : function () { - var state = { - 'core' : { - 'open' : [], - 'scroll' : { - 'left' : this.element.scrollLeft(), - 'top' : this.element.scrollTop() - }, - /*! - 'themes' : { - 'name' : this.get_theme(), - 'icons' : this._data.core.themes.icons, - 'dots' : this._data.core.themes.dots - }, - */ - 'selected' : [] - } - }, i; - for(i in this._model.data) { - if(this._model.data.hasOwnProperty(i)) { - if(i !== '#') { - if(this._model.data[i].state.opened) { - state.core.open.push(i); - } - if(this._model.data[i].state.selected) { - state.core.selected.push(i); - } - } - } - } - return state; - }, - /** - * sets the state of the tree. Used internally. - * @name set_state(state [, callback]) - * @private - * @param {Object} state the state to restore - * @param {Function} callback an optional function to execute once the state is restored. - * @trigger set_state.jstree - */ - set_state : function (state, callback) { - if(state) { - if(state.core) { - var res, n, t, _this; - if(state.core.open) { - if(!$.isArray(state.core.open)) { - delete state.core.open; - this.set_state(state, callback); - return false; - } - res = true; - n = false; - t = this; - $.each(state.core.open.concat([]), function (i, v) { - n = t.get_node(v); - if(n) { - if(t.is_loaded(v)) { - if(t.is_closed(v)) { - t.open_node(v, false, 0); - } - if(state && state.core && state.core.open) { - $.vakata.array_remove_item(state.core.open, v); - } - } - else { - if(!t.is_loading(v)) { - t.open_node(v, $.proxy(function (o, s) { - if(!s && state && state.core && state.core.open) { - $.vakata.array_remove_item(state.core.open, o.id); - } - this.set_state(state, callback); - }, t), 0); - } - // there will be some async activity - so wait for it - res = false; - } - } - }); - if(res) { - delete state.core.open; - this.set_state(state, callback); - } - return false; - } - if(state.core.scroll) { - if(state.core.scroll && state.core.scroll.left !== undefined) { - this.element.scrollLeft(state.core.scroll.left); - } - if(state.core.scroll && state.core.scroll.top !== undefined) { - this.element.scrollTop(state.core.scroll.top); - } - delete state.core.scroll; - this.set_state(state, callback); - return false; - } - /*! - if(state.core.themes) { - if(state.core.themes.name) { - this.set_theme(state.core.themes.name); - } - if(typeof state.core.themes.dots !== 'undefined') { - this[ state.core.themes.dots ? "show_dots" : "hide_dots" ](); - } - if(typeof state.core.themes.icons !== 'undefined') { - this[ state.core.themes.icons ? "show_icons" : "hide_icons" ](); - } - delete state.core.themes; - delete state.core.open; - this.set_state(state, callback); - return false; - } - */ - if(state.core.selected) { - _this = this; - this.deselect_all(); - $.each(state.core.selected, function (i, v) { - _this.select_node(v); - }); - delete state.core.selected; - this.set_state(state, callback); - return false; - } - if($.isEmptyObject(state.core)) { - delete state.core; - this.set_state(state, callback); - return false; - } - } - if($.isEmptyObject(state)) { - state = null; - if(callback) { callback.call(this); } - /** - * triggered when a `set_state` call completes - * @event - * @name set_state.jstree - */ - this.trigger('set_state'); - return false; - } - return true; - } - return false; - }, - /** - * refreshes the tree - all nodes are reloaded with calls to `load_node`. - * @name refresh() - * @param {Boolean} skip_loading an option to skip showing the loading indicator - * @param {Mixed} forget_state if set to `true` state will not be reapplied, if set to a function (receiving the current state as argument) the result of that function will be used as state - * @trigger refresh.jstree - */ - refresh : function (skip_loading, forget_state) { - this._data.core.state = forget_state === true ? {} : this.get_state(); - if(forget_state && $.isFunction(forget_state)) { this._data.core.state = forget_state.call(this, this._data.core.state); } - this._cnt = 0; - this._model.data = { - '#' : { - id : '#', - parent : null, - parents : [], - children : [], - children_d : [], - state : { loaded : false } - } - }; - var c = this.get_container_ul()[0].className; - if(!skip_loading) { - this.element.html("<"+"ul class='"+c+"'><"+"li class='jstree-initial-node jstree-loading jstree-leaf jstree-last'><"+"a class='jstree-anchor' href='#'>" + this.get_string("Loading ...") + "
    "); - } - this.load_node('#', function (o, s) { - if(s) { - this.get_container_ul()[0].className = c; - this.set_state($.extend(true, {}, this._data.core.state), function () { - /** - * triggered when a `refresh` call completes - * @event - * @name refresh.jstree - */ - this.trigger('refresh'); - }); - } - this._data.core.state = null; - }); - }, - /** - * refreshes a node in the tree (reload its children) all opened nodes inside that node are reloaded with calls to `load_node`. - * @name refresh_node(obj) - * @param {mixed} obj the node - * @trigger refresh_node.jstree - */ - refresh_node : function (obj) { - obj = this.get_node(obj); - if(!obj || obj.id === '#') { return false; } - var opened = [], to_load = [], s = this._data.core.selected.concat([]); - to_load.push(obj.id); - if(obj.state.opened === true) { opened.push(obj.id); } - this.get_node(obj, true).find('.jstree-open').each(function() { opened.push(this.id); }); - this._load_nodes(to_load, $.proxy(function (nodes) { - this.open_node(opened, false, 0); - this.select_node(this._data.core.selected); - /** - * triggered when a node is refreshed - * @event - * @name refresh_node.jstree - * @param {Object} node - the refreshed node - * @param {Array} nodes - an array of the IDs of the nodes that were reloaded - */ - this.trigger('refresh_node', { 'node' : obj, 'nodes' : nodes }); - }, this)); - }, - /** - * set (change) the ID of a node - * @name set_id(obj, id) - * @param {mixed} obj the node - * @param {String} id the new ID - * @return {Boolean} - */ - set_id : function (obj, id) { - obj = this.get_node(obj); - if(!obj || obj.id === '#') { return false; } - var i, j, m = this._model.data; - id = id.toString(); - // update parents (replace current ID with new one in children and children_d) - m[obj.parent].children[$.inArray(obj.id, m[obj.parent].children)] = id; - for(i = 0, j = obj.parents.length; i < j; i++) { - m[obj.parents[i]].children_d[$.inArray(obj.id, m[obj.parents[i]].children_d)] = id; - } - // update children (replace current ID with new one in parent and parents) - for(i = 0, j = obj.children.length; i < j; i++) { - m[obj.children[i]].parent = id; - } - for(i = 0, j = obj.children_d.length; i < j; i++) { - m[obj.children_d[i]].parents[$.inArray(obj.id, m[obj.children_d[i]].parents)] = id; - } - i = $.inArray(obj.id, this._data.core.selected); - if(i !== -1) { this._data.core.selected[i] = id; } - // update model and obj itself (obj.id, this._model.data[KEY]) - i = this.get_node(obj.id, true); - if(i) { - i.attr('id', id); - } - delete m[obj.id]; - obj.id = id; - m[id] = obj; - return true; - }, - /** - * get the text value of a node - * @name get_text(obj) - * @param {mixed} obj the node - * @return {String} - */ - get_text : function (obj) { - obj = this.get_node(obj); - return (!obj || obj.id === '#') ? false : obj.text; - }, - /** - * set the text value of a node. Used internally, please use `rename_node(obj, val)`. - * @private - * @name set_text(obj, val) - * @param {mixed} obj the node, you can pass an array to set the text on multiple nodes - * @param {String} val the new text value - * @return {Boolean} - * @trigger set_text.jstree - */ - set_text : function (obj, val) { - var t1, t2; - if($.isArray(obj)) { - obj = obj.slice(); - for(t1 = 0, t2 = obj.length; t1 < t2; t1++) { - this.set_text(obj[t1], val); - } - return true; - } - obj = this.get_node(obj); - if(!obj || obj.id === '#') { return false; } - obj.text = val; - if(this.get_node(obj, true).length) { - this.redraw_node(obj.id); - } - /** - * triggered when a node text value is changed - * @event - * @name set_text.jstree - * @param {Object} obj - * @param {String} text the new value - */ - this.trigger('set_text',{ "obj" : obj, "text" : val }); - return true; - }, - /** - * gets a JSON representation of a node (or the whole tree) - * @name get_json([obj, options]) - * @param {mixed} obj - * @param {Object} options - * @param {Boolean} options.no_state do not return state information - * @param {Boolean} options.no_id do not return ID - * @param {Boolean} options.no_children do not include children - * @param {Boolean} options.no_data do not include node data - * @param {Boolean} options.flat return flat JSON instead of nested - * @return {Object} - */ - get_json : function (obj, options, flat) { - obj = this.get_node(obj || '#'); - if(!obj) { return false; } - if(options && options.flat && !flat) { flat = []; } - var tmp = { - 'id' : obj.id, - 'text' : obj.text, - 'icon' : this.get_icon(obj), - 'li_attr' : obj.li_attr, - 'a_attr' : obj.a_attr, - 'state' : {}, - 'data' : options && options.no_data ? false : obj.data - //( this.get_node(obj, true).length ? this.get_node(obj, true).data() : obj.data ), - }, i, j; - if(options && options.flat) { - tmp.parent = obj.parent; - } - else { - tmp.children = []; - } - if(!options || !options.no_state) { - for(i in obj.state) { - if(obj.state.hasOwnProperty(i)) { - tmp.state[i] = obj.state[i]; - } - } - } - if(options && options.no_id) { - delete tmp.id; - if(tmp.li_attr && tmp.li_attr.id) { - delete tmp.li_attr.id; - } - } - if(options && options.flat && obj.id !== '#') { - flat.push(tmp); - } - if(!options || !options.no_children) { - for(i = 0, j = obj.children.length; i < j; i++) { - if(options && options.flat) { - this.get_json(obj.children[i], options, flat); - } - else { - tmp.children.push(this.get_json(obj.children[i], options)); - } - } - } - return options && options.flat ? flat : (obj.id === '#' ? tmp.children : tmp); - }, - /** - * create a new node (do not confuse with load_node) - * @name create_node([obj, node, pos, callback, is_loaded]) - * @param {mixed} par the parent node (to create a root node use either "#" (string) or `null`) - * @param {mixed} node the data for the new node (a valid JSON object, or a simple string with the name) - * @param {mixed} pos the index at which to insert the node, "first" and "last" are also supported, default is "last" - * @param {Function} callback a function to be called once the node is created - * @param {Boolean} is_loaded internal argument indicating if the parent node was succesfully loaded - * @return {String} the ID of the newly create node - * @trigger model.jstree, create_node.jstree - */ - create_node : function (par, node, pos, callback, is_loaded) { - if(par === null) { par = "#"; } - par = this.get_node(par); - if(!par) { return false; } - pos = pos === undefined ? "last" : pos; - if(!pos.toString().match(/^(before|after)$/) && !is_loaded && !this.is_loaded(par)) { - return this.load_node(par, function () { this.create_node(par, node, pos, callback, true); }); - } - if(!node) { node = { "text" : this.get_string('New node') }; } - if(node.text === undefined) { node.text = this.get_string('New node'); } - var tmp, dpc, i, j; - - if(par.id === '#') { - if(pos === "before") { pos = "first"; } - if(pos === "after") { pos = "last"; } - } - switch(pos) { - case "before": - tmp = this.get_node(par.parent); - pos = $.inArray(par.id, tmp.children); - par = tmp; - break; - case "after" : - tmp = this.get_node(par.parent); - pos = $.inArray(par.id, tmp.children) + 1; - par = tmp; - break; - case "inside": - case "first": - pos = 0; - break; - case "last": - pos = par.children.length; - break; - default: - if(!pos) { pos = 0; } - break; - } - if(pos > par.children.length) { pos = par.children.length; } - if(!node.id) { node.id = true; } - if(!this.check("create_node", node, par, pos)) { - this.settings.core.error.call(this, this._data.core.last_error); - return false; - } - if(node.id === true) { delete node.id; } - node = this._parse_model_from_json(node, par.id, par.parents.concat()); - if(!node) { return false; } - tmp = this.get_node(node); - dpc = []; - dpc.push(node); - dpc = dpc.concat(tmp.children_d); - this.trigger('model', { "nodes" : dpc, "parent" : par.id }); - - par.children_d = par.children_d.concat(dpc); - for(i = 0, j = par.parents.length; i < j; i++) { - this._model.data[par.parents[i]].children_d = this._model.data[par.parents[i]].children_d.concat(dpc); - } - node = tmp; - tmp = []; - for(i = 0, j = par.children.length; i < j; i++) { - tmp[i >= pos ? i+1 : i] = par.children[i]; - } - tmp[pos] = node.id; - par.children = tmp; - - this.redraw_node(par, true); - if(callback) { callback.call(this, this.get_node(node)); } - /** - * triggered when a node is created - * @event - * @name create_node.jstree - * @param {Object} node - * @param {String} parent the parent's ID - * @param {Number} position the position of the new node among the parent's children - */ - this.trigger('create_node', { "node" : this.get_node(node), "parent" : par.id, "position" : pos }); - return node.id; - }, - /** - * set the text value of a node - * @name rename_node(obj, val) - * @param {mixed} obj the node, you can pass an array to rename multiple nodes to the same name - * @param {String} val the new text value - * @return {Boolean} - * @trigger rename_node.jstree - */ - rename_node : function (obj, val) { - var t1, t2, old; - if($.isArray(obj)) { - obj = obj.slice(); - for(t1 = 0, t2 = obj.length; t1 < t2; t1++) { - this.rename_node(obj[t1], val); - } - return true; - } - obj = this.get_node(obj); - if(!obj || obj.id === '#') { return false; } - old = obj.text; - if(!this.check("rename_node", obj, this.get_parent(obj), val)) { - this.settings.core.error.call(this, this._data.core.last_error); - return false; - } - this.set_text(obj, val); // .apply(this, Array.prototype.slice.call(arguments)) - /** - * triggered when a node is renamed - * @event - * @name rename_node.jstree - * @param {Object} node - * @param {String} text the new value - * @param {String} old the old value - */ - this.trigger('rename_node', { "node" : obj, "text" : val, "old" : old }); - return true; - }, - /** - * remove a node - * @name delete_node(obj) - * @param {mixed} obj the node, you can pass an array to delete multiple nodes - * @return {Boolean} - * @trigger delete_node.jstree, changed.jstree - */ - delete_node : function (obj) { - var t1, t2, par, pos, tmp, i, j, k, l, c; - if($.isArray(obj)) { - obj = obj.slice(); - for(t1 = 0, t2 = obj.length; t1 < t2; t1++) { - this.delete_node(obj[t1]); - } - return true; - } - obj = this.get_node(obj); - if(!obj || obj.id === '#') { return false; } - par = this.get_node(obj.parent); - pos = $.inArray(obj.id, par.children); - c = false; - if(!this.check("delete_node", obj, par, pos)) { - this.settings.core.error.call(this, this._data.core.last_error); - return false; - } - if(pos !== -1) { - par.children = $.vakata.array_remove(par.children, pos); - } - tmp = obj.children_d.concat([]); - tmp.push(obj.id); - for(k = 0, l = tmp.length; k < l; k++) { - for(i = 0, j = obj.parents.length; i < j; i++) { - pos = $.inArray(tmp[k], this._model.data[obj.parents[i]].children_d); - if(pos !== -1) { - this._model.data[obj.parents[i]].children_d = $.vakata.array_remove(this._model.data[obj.parents[i]].children_d, pos); - } - } - if(this._model.data[tmp[k]].state.selected) { - c = true; - pos = $.inArray(tmp[k], this._data.core.selected); - if(pos !== -1) { - this._data.core.selected = $.vakata.array_remove(this._data.core.selected, pos); - } - } - } - /** - * triggered when a node is deleted - * @event - * @name delete_node.jstree - * @param {Object} node - * @param {String} parent the parent's ID - */ - this.trigger('delete_node', { "node" : obj, "parent" : par.id }); - if(c) { - this.trigger('changed', { 'action' : 'delete_node', 'node' : obj, 'selected' : this._data.core.selected, 'parent' : par.id }); - } - for(k = 0, l = tmp.length; k < l; k++) { - delete this._model.data[tmp[k]]; - } - this.redraw_node(par, true); - return true; - }, - /** - * check if an operation is premitted on the tree. Used internally. - * @private - * @name check(chk, obj, par, pos) - * @param {String} chk the operation to check, can be "create_node", "rename_node", "delete_node", "copy_node" or "move_node" - * @param {mixed} obj the node - * @param {mixed} par the parent - * @param {mixed} pos the position to insert at, or if "rename_node" - the new name - * @param {mixed} more some various additional information, for example if a "move_node" operations is triggered by DND this will be the hovered node - * @return {Boolean} - */ - check : function (chk, obj, par, pos, more) { - obj = obj && obj.id ? obj : this.get_node(obj); - par = par && par.id ? par : this.get_node(par); - var tmp = chk.match(/^move_node|copy_node|create_node$/i) ? par : obj, - chc = this.settings.core.check_callback; - if(chk === "move_node" || chk === "copy_node") { - if((!more || !more.is_multi) && (obj.id === par.id || $.inArray(obj.id, par.children) === pos || $.inArray(par.id, obj.children_d) !== -1)) { - this._data.core.last_error = { 'error' : 'check', 'plugin' : 'core', 'id' : 'core_01', 'reason' : 'Moving parent inside child', 'data' : JSON.stringify({ 'chk' : chk, 'pos' : pos, 'obj' : obj && obj.id ? obj.id : false, 'par' : par && par.id ? par.id : false }) }; - return false; - } - } - if(tmp && tmp.data) { tmp = tmp.data; } - if(tmp && tmp.functions && (tmp.functions[chk] === false || tmp.functions[chk] === true)) { - if(tmp.functions[chk] === false) { - this._data.core.last_error = { 'error' : 'check', 'plugin' : 'core', 'id' : 'core_02', 'reason' : 'Node data prevents function: ' + chk, 'data' : JSON.stringify({ 'chk' : chk, 'pos' : pos, 'obj' : obj && obj.id ? obj.id : false, 'par' : par && par.id ? par.id : false }) }; - } - return tmp.functions[chk]; - } - if(chc === false || ($.isFunction(chc) && chc.call(this, chk, obj, par, pos, more) === false) || (chc && chc[chk] === false)) { - this._data.core.last_error = { 'error' : 'check', 'plugin' : 'core', 'id' : 'core_03', 'reason' : 'User config for core.check_callback prevents function: ' + chk, 'data' : JSON.stringify({ 'chk' : chk, 'pos' : pos, 'obj' : obj && obj.id ? obj.id : false, 'par' : par && par.id ? par.id : false }) }; - return false; - } - return true; - }, - /** - * get the last error - * @name last_error() - * @return {Object} - */ - last_error : function () { - return this._data.core.last_error; - }, - /** - * move a node to a new parent - * @name move_node(obj, par [, pos, callback, is_loaded]) - * @param {mixed} obj the node to move, pass an array to move multiple nodes - * @param {mixed} par the new parent - * @param {mixed} pos the position to insert at (besides integer values, "first" and "last" are supported, as well as "before" and "after"), defaults to integer `0` - * @param {function} callback a function to call once the move is completed, receives 3 arguments - the node, the new parent and the position - * @param {Boolean} internal parameter indicating if the parent node has been loaded - * @trigger move_node.jstree - */ - move_node : function (obj, par, pos, callback, is_loaded) { - var t1, t2, old_par, old_pos, new_par, old_ins, is_multi, dpc, tmp, i, j, k, l, p; - - par = this.get_node(par); - pos = pos === undefined ? 0 : pos; - if(!par) { return false; } - if(!pos.toString().match(/^(before|after)$/) && !is_loaded && !this.is_loaded(par)) { - return this.load_node(par, function () { this.move_node(obj, par, pos, callback, true); }); - } - - if($.isArray(obj)) { - obj = obj.reverse().slice(); - for(t1 = 0, t2 = obj.length; t1 < t2; t1++) { - this.move_node(obj[t1], par, pos, callback, is_loaded); - } - return true; - } - obj = obj && obj.id ? obj : this.get_node(obj); - - if(!obj || obj.id === '#') { return false; } - - old_par = (obj.parent || '#').toString(); - new_par = (!pos.toString().match(/^(before|after)$/) || par.id === '#') ? par : this.get_node(par.parent); - old_ins = obj.instance ? obj.instance : (this._model.data[obj.id] ? this : $.jstree.reference(obj.id)); - is_multi = !old_ins || !old_ins._id || (this._id !== old_ins._id); - old_pos = old_ins && old_ins._id && old_par && old_ins._model.data[old_par] && old_ins._model.data[old_par].children ? $.inArray(obj.id, old_ins._model.data[old_par].children) : -1; - if(is_multi) { - if(this.copy_node(obj, par, pos, callback, is_loaded)) { - if(old_ins) { old_ins.delete_node(obj); } - return true; - } - return false; - } - //var m = this._model.data; - if(new_par.id === '#') { - if(pos === "before") { pos = "first"; } - if(pos === "after") { pos = "last"; } - } - switch(pos) { - case "before": - pos = $.inArray(par.id, new_par.children); - break; - case "after" : - pos = $.inArray(par.id, new_par.children) + 1; - break; - case "inside": - case "first": - pos = 0; - break; - case "last": - pos = new_par.children.length; - break; - default: - if(!pos) { pos = 0; } - break; - } - if(pos > new_par.children.length) { pos = new_par.children.length; } - if(!this.check("move_node", obj, new_par, pos, { 'core' : true, 'is_multi' : (old_ins && old_ins._id && old_ins._id !== this._id), 'is_foreign' : (!old_ins || !old_ins._id) })) { - this.settings.core.error.call(this, this._data.core.last_error); - return false; - } - if(obj.parent === new_par.id) { - dpc = new_par.children.concat(); - tmp = $.inArray(obj.id, dpc); - if(tmp !== -1) { - dpc = $.vakata.array_remove(dpc, tmp); - if(pos > tmp) { pos--; } - } - tmp = []; - for(i = 0, j = dpc.length; i < j; i++) { - tmp[i >= pos ? i+1 : i] = dpc[i]; - } - tmp[pos] = obj.id; - new_par.children = tmp; - this._node_changed(new_par.id); - this.redraw(new_par.id === '#'); - } - else { - // clean old parent and up - tmp = obj.children_d.concat(); - tmp.push(obj.id); - for(i = 0, j = obj.parents.length; i < j; i++) { - dpc = []; - p = old_ins._model.data[obj.parents[i]].children_d; - for(k = 0, l = p.length; k < l; k++) { - if($.inArray(p[k], tmp) === -1) { - dpc.push(p[k]); - } - } - old_ins._model.data[obj.parents[i]].children_d = dpc; - } - old_ins._model.data[old_par].children = $.vakata.array_remove_item(old_ins._model.data[old_par].children, obj.id); - - // insert into new parent and up - for(i = 0, j = new_par.parents.length; i < j; i++) { - this._model.data[new_par.parents[i]].children_d = this._model.data[new_par.parents[i]].children_d.concat(tmp); - } - dpc = []; - for(i = 0, j = new_par.children.length; i < j; i++) { - dpc[i >= pos ? i+1 : i] = new_par.children[i]; - } - dpc[pos] = obj.id; - new_par.children = dpc; - new_par.children_d.push(obj.id); - new_par.children_d = new_par.children_d.concat(obj.children_d); - - // update object - obj.parent = new_par.id; - tmp = new_par.parents.concat(); - tmp.unshift(new_par.id); - p = obj.parents.length; - obj.parents = tmp; - - // update object children - tmp = tmp.concat(); - for(i = 0, j = obj.children_d.length; i < j; i++) { - this._model.data[obj.children_d[i]].parents = this._model.data[obj.children_d[i]].parents.slice(0,p*-1); - Array.prototype.push.apply(this._model.data[obj.children_d[i]].parents, tmp); - } - - this._node_changed(old_par); - this._node_changed(new_par.id); - this.redraw(old_par === '#' || new_par.id === '#'); - } - if(callback) { callback.call(this, obj, new_par, pos); } - /** - * triggered when a node is moved - * @event - * @name move_node.jstree - * @param {Object} node - * @param {String} parent the parent's ID - * @param {Number} position the position of the node among the parent's children - * @param {String} old_parent the old parent of the node - * @param {Number} old_position the old position of the node - * @param {Boolean} is_multi do the node and new parent belong to different instances - * @param {jsTree} old_instance the instance the node came from - * @param {jsTree} new_instance the instance of the new parent - */ - this.trigger('move_node', { "node" : obj, "parent" : new_par.id, "position" : pos, "old_parent" : old_par, "old_position" : old_pos, 'is_multi' : (old_ins && old_ins._id && old_ins._id !== this._id), 'is_foreign' : (!old_ins || !old_ins._id), 'old_instance' : old_ins, 'new_instance' : this }); - return true; - }, - /** - * copy a node to a new parent - * @name copy_node(obj, par [, pos, callback, is_loaded]) - * @param {mixed} obj the node to copy, pass an array to copy multiple nodes - * @param {mixed} par the new parent - * @param {mixed} pos the position to insert at (besides integer values, "first" and "last" are supported, as well as "before" and "after"), defaults to integer `0` - * @param {function} callback a function to call once the move is completed, receives 3 arguments - the node, the new parent and the position - * @param {Boolean} internal parameter indicating if the parent node has been loaded - * @trigger model.jstree copy_node.jstree - */ - copy_node : function (obj, par, pos, callback, is_loaded) { - var t1, t2, dpc, tmp, i, j, node, old_par, new_par, old_ins, is_multi; - - par = this.get_node(par); - pos = pos === undefined ? 0 : pos; - if(!par) { return false; } - if(!pos.toString().match(/^(before|after)$/) && !is_loaded && !this.is_loaded(par)) { - return this.load_node(par, function () { this.copy_node(obj, par, pos, callback, true); }); - } - - if($.isArray(obj)) { - obj = obj.reverse().slice(); - for(t1 = 0, t2 = obj.length; t1 < t2; t1++) { - this.copy_node(obj[t1], par, pos, callback, is_loaded); - } - return true; - } - obj = obj && obj.id ? obj : this.get_node(obj); - if(!obj || obj.id === '#') { return false; } - - old_par = (obj.parent || '#').toString(); - new_par = (!pos.toString().match(/^(before|after)$/) || par.id === '#') ? par : this.get_node(par.parent); - old_ins = obj.instance ? obj.instance : (this._model.data[obj.id] ? this : $.jstree.reference(obj.id)); - is_multi = !old_ins || !old_ins._id || (this._id !== old_ins._id); - if(new_par.id === '#') { - if(pos === "before") { pos = "first"; } - if(pos === "after") { pos = "last"; } - } - switch(pos) { - case "before": - pos = $.inArray(par.id, new_par.children); - break; - case "after" : - pos = $.inArray(par.id, new_par.children) + 1; - break; - case "inside": - case "first": - pos = 0; - break; - case "last": - pos = new_par.children.length; - break; - default: - if(!pos) { pos = 0; } - break; - } - if(pos > new_par.children.length) { pos = new_par.children.length; } - if(!this.check("copy_node", obj, new_par, pos, { 'core' : true, 'is_multi' : (old_ins && old_ins._id && old_ins._id !== this._id), 'is_foreign' : (!old_ins || !old_ins._id) })) { - this.settings.core.error.call(this, this._data.core.last_error); - return false; - } - node = old_ins ? old_ins.get_json(obj, { no_id : true, no_data : true, no_state : true }) : obj; - if(!node) { return false; } - if(node.id === true) { delete node.id; } - node = this._parse_model_from_json(node, new_par.id, new_par.parents.concat()); - if(!node) { return false; } - tmp = this.get_node(node); - if(obj && obj.state && obj.state.loaded === false) { tmp.state.loaded = false; } - dpc = []; - dpc.push(node); - dpc = dpc.concat(tmp.children_d); - this.trigger('model', { "nodes" : dpc, "parent" : new_par.id }); - - // insert into new parent and up - for(i = 0, j = new_par.parents.length; i < j; i++) { - this._model.data[new_par.parents[i]].children_d = this._model.data[new_par.parents[i]].children_d.concat(dpc); - } - dpc = []; - for(i = 0, j = new_par.children.length; i < j; i++) { - dpc[i >= pos ? i+1 : i] = new_par.children[i]; - } - dpc[pos] = tmp.id; - new_par.children = dpc; - new_par.children_d.push(tmp.id); - new_par.children_d = new_par.children_d.concat(tmp.children_d); - - this._node_changed(new_par.id); - this.redraw(new_par.id === '#'); - if(callback) { callback.call(this, tmp, new_par, pos); } - /** - * triggered when a node is copied - * @event - * @name copy_node.jstree - * @param {Object} node the copied node - * @param {Object} original the original node - * @param {String} parent the parent's ID - * @param {Number} position the position of the node among the parent's children - * @param {String} old_parent the old parent of the node - * @param {Number} old_position the position of the original node - * @param {Boolean} is_multi do the node and new parent belong to different instances - * @param {jsTree} old_instance the instance the node came from - * @param {jsTree} new_instance the instance of the new parent - */ - this.trigger('copy_node', { "node" : tmp, "original" : obj, "parent" : new_par.id, "position" : pos, "old_parent" : old_par, "old_position" : old_ins && old_ins._id && old_par && old_ins._model.data[old_par] && old_ins._model.data[old_par].children ? $.inArray(obj.id, old_ins._model.data[old_par].children) : -1,'is_multi' : (old_ins && old_ins._id && old_ins._id !== this._id), 'is_foreign' : (!old_ins || !old_ins._id), 'old_instance' : old_ins, 'new_instance' : this }); - return tmp.id; - }, - /** - * cut a node (a later call to `paste(obj)` would move the node) - * @name cut(obj) - * @param {mixed} obj multiple objects can be passed using an array - * @trigger cut.jstree - */ - cut : function (obj) { - if(!obj) { obj = this._data.core.selected.concat(); } - if(!$.isArray(obj)) { obj = [obj]; } - if(!obj.length) { return false; } - var tmp = [], o, t1, t2; - for(t1 = 0, t2 = obj.length; t1 < t2; t1++) { - o = this.get_node(obj[t1]); - if(o && o.id && o.id !== '#') { tmp.push(o); } - } - if(!tmp.length) { return false; } - ccp_node = tmp; - ccp_inst = this; - ccp_mode = 'move_node'; - /** - * triggered when nodes are added to the buffer for moving - * @event - * @name cut.jstree - * @param {Array} node - */ - this.trigger('cut', { "node" : obj }); - }, - /** - * copy a node (a later call to `paste(obj)` would copy the node) - * @name copy(obj) - * @param {mixed} obj multiple objects can be passed using an array - * @trigger copy.jstre - */ - copy : function (obj) { - if(!obj) { obj = this._data.core.selected.concat(); } - if(!$.isArray(obj)) { obj = [obj]; } - if(!obj.length) { return false; } - var tmp = [], o, t1, t2; - for(t1 = 0, t2 = obj.length; t1 < t2; t1++) { - o = this.get_node(obj[t1]); - if(o && o.id && o.id !== '#') { tmp.push(o); } - } - if(!tmp.length) { return false; } - ccp_node = tmp; - ccp_inst = this; - ccp_mode = 'copy_node'; - /** - * triggered when nodes are added to the buffer for copying - * @event - * @name copy.jstree - * @param {Array} node - */ - this.trigger('copy', { "node" : obj }); - }, - /** - * get the current buffer (any nodes that are waiting for a paste operation) - * @name get_buffer() - * @return {Object} an object consisting of `mode` ("copy_node" or "move_node"), `node` (an array of objects) and `inst` (the instance) - */ - get_buffer : function () { - return { 'mode' : ccp_mode, 'node' : ccp_node, 'inst' : ccp_inst }; - }, - /** - * check if there is something in the buffer to paste - * @name can_paste() - * @return {Boolean} - */ - can_paste : function () { - return ccp_mode !== false && ccp_node !== false; // && ccp_inst._model.data[ccp_node]; - }, - /** - * copy or move the previously cut or copied nodes to a new parent - * @name paste(obj [, pos]) - * @param {mixed} obj the new parent - * @param {mixed} pos the position to insert at (besides integer, "first" and "last" are supported), defaults to integer `0` - * @trigger paste.jstree - */ - paste : function (obj, pos) { - obj = this.get_node(obj); - if(!obj || !ccp_mode || !ccp_mode.match(/^(copy_node|move_node)$/) || !ccp_node) { return false; } - if(this[ccp_mode](ccp_node, obj, pos)) { - /** - * triggered when paste is invoked - * @event - * @name paste.jstree - * @param {String} parent the ID of the receiving node - * @param {Array} node the nodes in the buffer - * @param {String} mode the performed operation - "copy_node" or "move_node" - */ - this.trigger('paste', { "parent" : obj.id, "node" : ccp_node, "mode" : ccp_mode }); - } - ccp_node = false; - ccp_mode = false; - ccp_inst = false; - }, - /** - * put a node in edit mode (input field to rename the node) - * @name edit(obj [, default_text]) - * @param {mixed} obj - * @param {String} default_text the text to populate the input with (if omitted the node text value is used) - */ - edit : function (obj, default_text) { - obj = this.get_node(obj); - if(!obj) { return false; } - if(this.settings.core.check_callback === false) { - this._data.core.last_error = { 'error' : 'check', 'plugin' : 'core', 'id' : 'core_07', 'reason' : 'Could not edit node because of check_callback' }; - this.settings.core.error.call(this, this._data.core.last_error); - return false; - } - default_text = typeof default_text === 'string' ? default_text : obj.text; - this.set_text(obj, ""); - obj = this._open_to(obj); - - var rtl = this._data.core.rtl, - w = this.element.width(), - a = obj.children('.jstree-anchor'), - s = $(''), - /*! - oi = obj.children("i:visible"), - ai = a.children("i:visible"), - w1 = oi.width() * oi.length, - w2 = ai.width() * ai.length, - */ - t = default_text, - h1 = $("<"+"div />", { css : { "position" : "absolute", "top" : "-200px", "left" : (rtl ? "0px" : "-1000px"), "visibility" : "hidden" } }).appendTo("body"), - h2 = $("<"+"input />", { - "value" : t, - "class" : "jstree-rename-input", - // "size" : t.length, - "css" : { - "padding" : "0", - "border" : "1px solid silver", - "box-sizing" : "border-box", - "display" : "inline-block", - "height" : (this._data.core.li_height) + "px", - "lineHeight" : (this._data.core.li_height) + "px", - "width" : "150px" // will be set a bit further down - }, - "blur" : $.proxy(function () { - var i = s.children(".jstree-rename-input"), - v = i.val(); - if(v === "") { v = t; } - h1.remove(); - s.replaceWith(a); - s.remove(); - this.set_text(obj, t); - if(this.rename_node(obj, $('
    ').text(v)[this.settings.core.force_text ? 'text' : 'html']()) === false) { - this.set_text(obj, t); // move this up? and fix #483 - } - }, this), - "keydown" : function (event) { - var key = event.which; - if(key === 27) { - this.value = t; - } - if(key === 27 || key === 13 || key === 37 || key === 38 || key === 39 || key === 40 || key === 32) { - event.stopImmediatePropagation(); - } - if(key === 27 || key === 13) { - event.preventDefault(); - this.blur(); - } - }, - "click" : function (e) { e.stopImmediatePropagation(); }, - "mousedown" : function (e) { e.stopImmediatePropagation(); }, - "keyup" : function (event) { - h2.width(Math.min(h1.text("pW" + this.value).width(),w)); - }, - "keypress" : function(event) { - if(event.which === 13) { return false; } - } - }), - fn = { - fontFamily : a.css('fontFamily') || '', - fontSize : a.css('fontSize') || '', - fontWeight : a.css('fontWeight') || '', - fontStyle : a.css('fontStyle') || '', - fontStretch : a.css('fontStretch') || '', - fontVariant : a.css('fontVariant') || '', - letterSpacing : a.css('letterSpacing') || '', - wordSpacing : a.css('wordSpacing') || '' - }; - s.attr('class', a.attr('class')).append(a.contents().clone()).append(h2); - a.replaceWith(s); - h1.css(fn); - h2.css(fn).width(Math.min(h1.text("pW" + h2[0].value).width(),w))[0].select(); - }, - - - /** - * changes the theme - * @name set_theme(theme_name [, theme_url]) - * @param {String} theme_name the name of the new theme to apply - * @param {mixed} theme_url the location of the CSS file for this theme. Omit or set to `false` if you manually included the file. Set to `true` to autoload from the `core.themes.dir` directory. - * @trigger set_theme.jstree - */ - set_theme : function (theme_name, theme_url) { - if(!theme_name) { return false; } - if(theme_url === true) { - var dir = this.settings.core.themes.dir; - if(!dir) { dir = $.jstree.path + '/themes'; } - theme_url = dir + '/' + theme_name + '/style.css'; - } - if(theme_url && $.inArray(theme_url, themes_loaded) === -1) { - $('head').append('<'+'link rel="stylesheet" href="' + theme_url + '" type="text/css" />'); - themes_loaded.push(theme_url); - } - if(this._data.core.themes.name) { - this.element.removeClass('jstree-' + this._data.core.themes.name); - } - this._data.core.themes.name = theme_name; - this.element.addClass('jstree-' + theme_name); - this.element[this.settings.core.themes.responsive ? 'addClass' : 'removeClass' ]('jstree-' + theme_name + '-responsive'); - /** - * triggered when a theme is set - * @event - * @name set_theme.jstree - * @param {String} theme the new theme - */ - this.trigger('set_theme', { 'theme' : theme_name }); - }, - /** - * gets the name of the currently applied theme name - * @name get_theme() - * @return {String} - */ - get_theme : function () { return this._data.core.themes.name; }, - /** - * changes the theme variant (if the theme has variants) - * @name set_theme_variant(variant_name) - * @param {String|Boolean} variant_name the variant to apply (if `false` is used the current variant is removed) - */ - set_theme_variant : function (variant_name) { - if(this._data.core.themes.variant) { - this.element.removeClass('jstree-' + this._data.core.themes.name + '-' + this._data.core.themes.variant); - } - this._data.core.themes.variant = variant_name; - if(variant_name) { - this.element.addClass('jstree-' + this._data.core.themes.name + '-' + this._data.core.themes.variant); - } - }, - /** - * gets the name of the currently applied theme variant - * @name get_theme() - * @return {String} - */ - get_theme_variant : function () { return this._data.core.themes.variant; }, - /** - * shows a striped background on the container (if the theme supports it) - * @name show_stripes() - */ - show_stripes : function () { this._data.core.themes.stripes = true; this.get_container_ul().addClass("jstree-striped"); }, - /** - * hides the striped background on the container - * @name hide_stripes() - */ - hide_stripes : function () { this._data.core.themes.stripes = false; this.get_container_ul().removeClass("jstree-striped"); }, - /** - * toggles the striped background on the container - * @name toggle_stripes() - */ - toggle_stripes : function () { if(this._data.core.themes.stripes) { this.hide_stripes(); } else { this.show_stripes(); } }, - /** - * shows the connecting dots (if the theme supports it) - * @name show_dots() - */ - show_dots : function () { this._data.core.themes.dots = true; this.get_container_ul().removeClass("jstree-no-dots"); }, - /** - * hides the connecting dots - * @name hide_dots() - */ - hide_dots : function () { this._data.core.themes.dots = false; this.get_container_ul().addClass("jstree-no-dots"); }, - /** - * toggles the connecting dots - * @name toggle_dots() - */ - toggle_dots : function () { if(this._data.core.themes.dots) { this.hide_dots(); } else { this.show_dots(); } }, - /** - * show the node icons - * @name show_icons() - */ - show_icons : function () { this._data.core.themes.icons = true; this.get_container_ul().removeClass("jstree-no-icons"); }, - /** - * hide the node icons - * @name hide_icons() - */ - hide_icons : function () { this._data.core.themes.icons = false; this.get_container_ul().addClass("jstree-no-icons"); }, - /** - * toggle the node icons - * @name toggle_icons() - */ - toggle_icons : function () { if(this._data.core.themes.icons) { this.hide_icons(); } else { this.show_icons(); } }, - /** - * set the node icon for a node - * @name set_icon(obj, icon) - * @param {mixed} obj - * @param {String} icon the new icon - can be a path to an icon or a className, if using an image that is in the current directory use a `./` prefix, otherwise it will be detected as a class - */ - set_icon : function (obj, icon) { - var t1, t2, dom, old; - if($.isArray(obj)) { - obj = obj.slice(); - for(t1 = 0, t2 = obj.length; t1 < t2; t1++) { - this.set_icon(obj[t1], icon); - } - return true; - } - obj = this.get_node(obj); - if(!obj || obj.id === '#') { return false; } - old = obj.icon; - obj.icon = icon; - dom = this.get_node(obj, true).children(".jstree-anchor").children(".jstree-themeicon"); - if(icon === false) { - this.hide_icon(obj); - } - else if(icon === true) { - dom.removeClass('jstree-themeicon-custom ' + old).css("background","").removeAttr("rel"); - } - else if(icon.indexOf("/") === -1 && icon.indexOf(".") === -1) { - dom.removeClass(old).css("background",""); - dom.addClass(icon + ' jstree-themeicon-custom').attr("rel",icon); - } - else { - dom.removeClass(old).css("background",""); - dom.addClass('jstree-themeicon-custom').css("background", "url('" + icon + "') center center no-repeat").attr("rel",icon); - } - return true; - }, - /** - * get the node icon for a node - * @name get_icon(obj) - * @param {mixed} obj - * @return {String} - */ - get_icon : function (obj) { - obj = this.get_node(obj); - return (!obj || obj.id === '#') ? false : obj.icon; - }, - /** - * hide the icon on an individual node - * @name hide_icon(obj) - * @param {mixed} obj - */ - hide_icon : function (obj) { - var t1, t2; - if($.isArray(obj)) { - obj = obj.slice(); - for(t1 = 0, t2 = obj.length; t1 < t2; t1++) { - this.hide_icon(obj[t1]); - } - return true; - } - obj = this.get_node(obj); - if(!obj || obj === '#') { return false; } - obj.icon = false; - this.get_node(obj, true).children(".jstree-anchor").children(".jstree-themeicon").addClass('jstree-themeicon-hidden'); - return true; - }, - /** - * show the icon on an individual node - * @name show_icon(obj) - * @param {mixed} obj - */ - show_icon : function (obj) { - var t1, t2, dom; - if($.isArray(obj)) { - obj = obj.slice(); - for(t1 = 0, t2 = obj.length; t1 < t2; t1++) { - this.show_icon(obj[t1]); - } - return true; - } - obj = this.get_node(obj); - if(!obj || obj === '#') { return false; } - dom = this.get_node(obj, true); - obj.icon = dom.length ? dom.children(".jstree-anchor").children(".jstree-themeicon").attr('rel') : true; - if(!obj.icon) { obj.icon = true; } - dom.children(".jstree-anchor").children(".jstree-themeicon").removeClass('jstree-themeicon-hidden'); - return true; - } - }; - - // helpers - $.vakata = {}; - // collect attributes - $.vakata.attributes = function(node, with_values) { - node = $(node)[0]; - var attr = with_values ? {} : []; - if(node && node.attributes) { - $.each(node.attributes, function (i, v) { - if($.inArray(v.nodeName.toLowerCase(),['style','contenteditable','hasfocus','tabindex']) !== -1) { return; } - if(v.nodeValue !== null && $.trim(v.nodeValue) !== '') { - if(with_values) { attr[v.nodeName] = v.nodeValue; } - else { attr.push(v.nodeName); } - } - }); - } - return attr; - }; - $.vakata.array_unique = function(array) { - var a = [], i, j, l; - for(i = 0, l = array.length; i < l; i++) { - for(j = 0; j <= i; j++) { - if(array[i] === array[j]) { - break; - } - } - if(j === i) { a.push(array[i]); } - } - return a; - }; - // remove item from array - $.vakata.array_remove = function(array, from, to) { - var rest = array.slice((to || from) + 1 || array.length); - array.length = from < 0 ? array.length + from : from; - array.push.apply(array, rest); - return array; - }; - // remove item from array - $.vakata.array_remove_item = function(array, item) { - var tmp = $.inArray(item, array); - return tmp !== -1 ? $.vakata.array_remove(array, tmp) : array; - }; - -/** - * ### Checkbox plugin - * - * This plugin renders checkbox icons in front of each node, making multiple selection much easier. - * It also supports tri-state behavior, meaning that if a node has a few of its children checked it will be rendered as undetermined, and state will be propagated up. - */ - - var _i = document.createElement('I'); - _i.className = 'jstree-icon jstree-checkbox'; - /** - * stores all defaults for the checkbox plugin - * @name $.jstree.defaults.checkbox - * @plugin checkbox - */ - $.jstree.defaults.checkbox = { - /** - * a boolean indicating if checkboxes should be visible (can be changed at a later time using `show_checkboxes()` and `hide_checkboxes`). Defaults to `true`. - * @name $.jstree.defaults.checkbox.visible - * @plugin checkbox - */ - visible : true, - /** - * a boolean indicating if checkboxes should cascade down and have an undetermined state. Defaults to `true`. - * @name $.jstree.defaults.checkbox.three_state - * @plugin checkbox - */ - three_state : true, - /** - * a boolean indicating if clicking anywhere on the node should act as clicking on the checkbox. Defaults to `true`. - * @name $.jstree.defaults.checkbox.whole_node - * @plugin checkbox - */ - whole_node : true, - /** - * a boolean indicating if the selected style of a node should be kept, or removed. Defaults to `true`. - * @name $.jstree.defaults.checkbox.keep_selected_style - * @plugin checkbox - */ - keep_selected_style : true, - /** - * This setting controls how cascading and undetermined nodes are applied. - * If 'up' is in the string - cascading up is enabled, if 'down' is in the string - cascading down is enabled, if 'undetermined' is in the string - undetermined nodes will be used. - * If `three_state` is set to `true` this setting is automatically set to 'up+down+undetermined'. Defaults to ''. - * @name $.jstree.defaults.checkbox.cascade - * @plugin checkbox - */ - cascade : '', - /** - * This setting controls if checkbox are bound to the general tree selection or to an internal array maintained by the checkbox plugin. Defaults to `true`, only set to `false` if you know exactly what you are doing. - * @name $.jstree.defaults.checkbox.tie_selection - * @plugin checkbox - */ - tie_selection : true - }; - $.jstree.plugins.checkbox = function (options, parent) { - this.bind = function () { - parent.bind.call(this); - this._data.checkbox.uto = false; - this._data.checkbox.selected = []; - if(this.settings.checkbox.three_state) { - this.settings.checkbox.cascade = 'up+down+undetermined'; - } - this.element - .on("init.jstree", $.proxy(function () { - this._data.checkbox.visible = this.settings.checkbox.visible; - if(!this.settings.checkbox.keep_selected_style) { - this.element.addClass('jstree-checkbox-no-clicked'); - } - if(this.settings.checkbox.tie_selection) { - this.element.addClass('jstree-checkbox-selection'); - } - }, this)) - .on("loading.jstree", $.proxy(function () { - this[ this._data.checkbox.visible ? 'show_checkboxes' : 'hide_checkboxes' ](); - }, this)); - if(this.settings.checkbox.cascade.indexOf('undetermined') !== -1) { - this.element - .on('changed.jstree uncheck_node.jstree check_node.jstree uncheck_all.jstree check_all.jstree move_node.jstree copy_node.jstree redraw.jstree open_node.jstree', $.proxy(function () { - // only if undetermined is in setting - if(this._data.checkbox.uto) { clearTimeout(this._data.checkbox.uto); } - this._data.checkbox.uto = setTimeout($.proxy(this._undetermined, this), 50); - }, this)); - } - if(!this.settings.checkbox.tie_selection) { - this.element - .on('model.jstree', $.proxy(function (e, data) { - var m = this._model.data, - p = m[data.parent], - dpc = data.nodes, - i, j; - for(i = 0, j = dpc.length; i < j; i++) { - m[dpc[i]].state.checked = (m[dpc[i]].original && m[dpc[i]].original.state && m[dpc[i]].original.state.checked); - if(m[dpc[i]].state.checked) { - this._data.checkbox.selected.push(dpc[i]); - } - } - }, this)); - } - if(this.settings.checkbox.cascade.indexOf('up') !== -1 || this.settings.checkbox.cascade.indexOf('down') !== -1) { - this.element - .on('model.jstree', $.proxy(function (e, data) { - var m = this._model.data, - p = m[data.parent], - dpc = data.nodes, - chd = [], - c, i, j, k, l, tmp, s = this.settings.checkbox.cascade, t = this.settings.checkbox.tie_selection; - - if(s.indexOf('down') !== -1) { - // apply down - if(p.state[ t ? 'selected' : 'checked' ]) { - for(i = 0, j = dpc.length; i < j; i++) { - m[dpc[i]].state[ t ? 'selected' : 'checked' ] = true; - } - this._data[ t ? 'core' : 'checkbox' ].selected = this._data[ t ? 'core' : 'checkbox' ].selected.concat(dpc); - } - else { - for(i = 0, j = dpc.length; i < j; i++) { - if(m[dpc[i]].state[ t ? 'selected' : 'checked' ]) { - for(k = 0, l = m[dpc[i]].children_d.length; k < l; k++) { - m[m[dpc[i]].children_d[k]].state[ t ? 'selected' : 'checked' ] = true; - } - this._data[ t ? 'core' : 'checkbox' ].selected = this._data[ t ? 'core' : 'checkbox' ].selected.concat(m[dpc[i]].children_d); - } - } - } - } - - if(s.indexOf('up') !== -1) { - // apply up - for(i = 0, j = p.children_d.length; i < j; i++) { - if(!m[p.children_d[i]].children.length) { - chd.push(m[p.children_d[i]].parent); - } - } - chd = $.vakata.array_unique(chd); - for(k = 0, l = chd.length; k < l; k++) { - p = m[chd[k]]; - while(p && p.id !== '#') { - c = 0; - for(i = 0, j = p.children.length; i < j; i++) { - c += m[p.children[i]].state[ t ? 'selected' : 'checked' ]; - } - if(c === j) { - p.state[ t ? 'selected' : 'checked' ] = true; - this._data[ t ? 'core' : 'checkbox' ].selected.push(p.id); - tmp = this.get_node(p, true); - if(tmp && tmp.length) { - tmp.children('.jstree-anchor').addClass( t ? 'jstree-clicked' : 'jstree-checked'); - } - } - else { - break; - } - p = this.get_node(p.parent); - } - } - } - - this._data[ t ? 'core' : 'checkbox' ].selected = $.vakata.array_unique(this._data[ t ? 'core' : 'checkbox' ].selected); - }, this)) - .on(this.settings.checkbox.tie_selection ? 'select_node.jstree' : 'check_node.jstree', $.proxy(function (e, data) { - var obj = data.node, - m = this._model.data, - par = this.get_node(obj.parent), - dom = this.get_node(obj, true), - i, j, c, tmp, s = this.settings.checkbox.cascade, t = this.settings.checkbox.tie_selection; - - // apply down - if(s.indexOf('down') !== -1) { - this._data[ t ? 'core' : 'checkbox' ].selected = $.vakata.array_unique(this._data[ t ? 'core' : 'checkbox' ].selected.concat(obj.children_d)); - for(i = 0, j = obj.children_d.length; i < j; i++) { - tmp = m[obj.children_d[i]]; - tmp.state[ t ? 'selected' : 'checked' ] = true; - if(tmp && tmp.original && tmp.original.state && tmp.original.state.undetermined) { - tmp.original.state.undetermined = false; - } - } - } - - // apply up - if(s.indexOf('up') !== -1) { - while(par && par.id !== '#') { - c = 0; - for(i = 0, j = par.children.length; i < j; i++) { - c += m[par.children[i]].state[ t ? 'selected' : 'checked' ]; - } - if(c === j) { - par.state[ t ? 'selected' : 'checked' ] = true; - this._data[ t ? 'core' : 'checkbox' ].selected.push(par.id); - tmp = this.get_node(par, true); - if(tmp && tmp.length) { - tmp.children('.jstree-anchor').addClass(t ? 'jstree-clicked' : 'jstree-checked'); - } - } - else { - break; - } - par = this.get_node(par.parent); - } - } - - // apply down (process .children separately?) - if(s.indexOf('down') !== -1 && dom.length) { - dom.find('.jstree-anchor').addClass(t ? 'jstree-clicked' : 'jstree-checked'); - } - }, this)) - .on(this.settings.checkbox.tie_selection ? 'deselect_all.jstree' : 'uncheck_all.jstree', $.proxy(function (e, data) { - var obj = this.get_node('#'), - m = this._model.data, - i, j, tmp; - for(i = 0, j = obj.children_d.length; i < j; i++) { - tmp = m[obj.children_d[i]]; - if(tmp && tmp.original && tmp.original.state && tmp.original.state.undetermined) { - tmp.original.state.undetermined = false; - } - } - }, this)) - .on(this.settings.checkbox.tie_selection ? 'deselect_node.jstree' : 'uncheck_node.jstree', $.proxy(function (e, data) { - var obj = data.node, - dom = this.get_node(obj, true), - i, j, tmp, s = this.settings.checkbox.cascade, t = this.settings.checkbox.tie_selection; - if(obj && obj.original && obj.original.state && obj.original.state.undetermined) { - obj.original.state.undetermined = false; - } - - // apply down - if(s.indexOf('down') !== -1) { - for(i = 0, j = obj.children_d.length; i < j; i++) { - tmp = this._model.data[obj.children_d[i]]; - tmp.state[ t ? 'selected' : 'checked' ] = false; - if(tmp && tmp.original && tmp.original.state && tmp.original.state.undetermined) { - tmp.original.state.undetermined = false; - } - } - } - - // apply up - if(s.indexOf('up') !== -1) { - for(i = 0, j = obj.parents.length; i < j; i++) { - tmp = this._model.data[obj.parents[i]]; - tmp.state[ t ? 'selected' : 'checked' ] = false; - if(tmp && tmp.original && tmp.original.state && tmp.original.state.undetermined) { - tmp.original.state.undetermined = false; - } - tmp = this.get_node(obj.parents[i], true); - if(tmp && tmp.length) { - tmp.children('.jstree-anchor').removeClass(t ? 'jstree-clicked' : 'jstree-checked'); - } - } - } - tmp = []; - for(i = 0, j = this._data[ t ? 'core' : 'checkbox' ].selected.length; i < j; i++) { - // apply down + apply up - if( - (s.indexOf('down') === -1 || $.inArray(this._data[ t ? 'core' : 'checkbox' ].selected[i], obj.children_d) === -1) && - (s.indexOf('up') === -1 || $.inArray(this._data[ t ? 'core' : 'checkbox' ].selected[i], obj.parents) === -1) - ) { - tmp.push(this._data[ t ? 'core' : 'checkbox' ].selected[i]); - } - } - this._data[ t ? 'core' : 'checkbox' ].selected = $.vakata.array_unique(tmp); - - // apply down (process .children separately?) - if(s.indexOf('down') !== -1 && dom.length) { - dom.find('.jstree-anchor').removeClass(t ? 'jstree-clicked' : 'jstree-checked'); - } - }, this)); - } - if(this.settings.checkbox.cascade.indexOf('up') !== -1) { - this.element - .on('delete_node.jstree', $.proxy(function (e, data) { - // apply up (whole handler) - var p = this.get_node(data.parent), - m = this._model.data, - i, j, c, tmp, t = this.settings.checkbox.tie_selection; - while(p && p.id !== '#') { - c = 0; - for(i = 0, j = p.children.length; i < j; i++) { - c += m[p.children[i]].state[ t ? 'selected' : 'checked' ]; - } - if(c === j) { - p.state[ t ? 'selected' : 'checked' ] = true; - this._data[ t ? 'core' : 'checkbox' ].selected.push(p.id); - tmp = this.get_node(p, true); - if(tmp && tmp.length) { - tmp.children('.jstree-anchor').addClass(t ? 'jstree-clicked' : 'jstree-checked'); - } - } - else { - break; - } - p = this.get_node(p.parent); - } - }, this)) - .on('move_node.jstree', $.proxy(function (e, data) { - // apply up (whole handler) - var is_multi = data.is_multi, - old_par = data.old_parent, - new_par = this.get_node(data.parent), - m = this._model.data, - p, c, i, j, tmp, t = this.settings.checkbox.tie_selection; - if(!is_multi) { - p = this.get_node(old_par); - while(p && p.id !== '#') { - c = 0; - for(i = 0, j = p.children.length; i < j; i++) { - c += m[p.children[i]].state[ t ? 'selected' : 'checked' ]; - } - if(c === j) { - p.state[ t ? 'selected' : 'checked' ] = true; - this._data[ t ? 'core' : 'checkbox' ].selected.push(p.id); - tmp = this.get_node(p, true); - if(tmp && tmp.length) { - tmp.children('.jstree-anchor').addClass(t ? 'jstree-clicked' : 'jstree-checked'); - } - } - else { - break; - } - p = this.get_node(p.parent); - } - } - p = new_par; - while(p && p.id !== '#') { - c = 0; - for(i = 0, j = p.children.length; i < j; i++) { - c += m[p.children[i]].state[ t ? 'selected' : 'checked' ]; - } - if(c === j) { - if(!p.state[ t ? 'selected' : 'checked' ]) { - p.state[ t ? 'selected' : 'checked' ] = true; - this._data[ t ? 'core' : 'checkbox' ].selected.push(p.id); - tmp = this.get_node(p, true); - if(tmp && tmp.length) { - tmp.children('.jstree-anchor').addClass(t ? 'jstree-clicked' : 'jstree-checked'); - } - } - } - else { - if(p.state[ t ? 'selected' : 'checked' ]) { - p.state[ t ? 'selected' : 'checked' ] = false; - this._data[ t ? 'core' : 'checkbox' ].selected = $.vakata.array_remove_item(this._data[ t ? 'core' : 'checkbox' ].selected, p.id); - tmp = this.get_node(p, true); - if(tmp && tmp.length) { - tmp.children('.jstree-anchor').removeClass(t ? 'jstree-clicked' : 'jstree-checked'); - } - } - else { - break; - } - } - p = this.get_node(p.parent); - } - }, this)); - } - }; - /** - * set the undetermined state where and if necessary. Used internally. - * @private - * @name _undetermined() - * @plugin checkbox - */ - this._undetermined = function () { - var i, j, m = this._model.data, t = this.settings.checkbox.tie_selection, s = this._data[ t ? 'core' : 'checkbox' ].selected, p = [], tt = this; - for(i = 0, j = s.length; i < j; i++) { - if(m[s[i]] && m[s[i]].parents) { - p = p.concat(m[s[i]].parents); - } - } - // attempt for server side undetermined state - this.element.find('.jstree-closed').not(':has(.jstree-children)') - .each(function () { - var tmp = tt.get_node(this), tmp2; - if(!tmp.state.loaded) { - if(tmp.original && tmp.original.state && tmp.original.state.undetermined && tmp.original.state.undetermined === true) { - p.push(tmp.id); - p = p.concat(tmp.parents); - } - } - else { - for(i = 0, j = tmp.children_d.length; i < j; i++) { - tmp2 = m[tmp.children_d[i]]; - if(!tmp2.state.loaded && tmp2.original && tmp2.original.state && tmp2.original.state.undetermined && tmp2.original.state.undetermined === true) { - p.push(tmp2.id); - p = p.concat(tmp2.parents); - } - } - } - }); - p = $.vakata.array_unique(p); - p = $.vakata.array_remove_item(p,'#'); - - this.element.find('.jstree-undetermined').removeClass('jstree-undetermined'); - for(i = 0, j = p.length; i < j; i++) { - if(!m[p[i]].state[ t ? 'selected' : 'checked' ]) { - s = this.get_node(p[i], true); - if(s && s.length) { - s.children('.jstree-anchor').children('.jstree-checkbox').addClass('jstree-undetermined'); - } - } - } - }; - this.redraw_node = function(obj, deep, is_callback) { - obj = parent.redraw_node.call(this, obj, deep, is_callback); - if(obj) { - var i, j, tmp = null; - for(i = 0, j = obj.childNodes.length; i < j; i++) { - if(obj.childNodes[i] && obj.childNodes[i].className && obj.childNodes[i].className.indexOf("jstree-anchor") !== -1) { - tmp = obj.childNodes[i]; - break; - } - } - if(tmp) { - if(!this.settings.checkbox.tie_selection && this._model.data[obj.id].state.checked) { tmp.className += ' jstree-checked'; } - tmp.insertBefore(_i.cloneNode(false), tmp.childNodes[0]); - } - } - if(!is_callback && this.settings.checkbox.cascade.indexOf('undetermined') !== -1) { - if(this._data.checkbox.uto) { clearTimeout(this._data.checkbox.uto); } - this._data.checkbox.uto = setTimeout($.proxy(this._undetermined, this), 50); - } - return obj; - }; - /** - * show the node checkbox icons - * @name show_checkboxes() - * @plugin checkbox - */ - this.show_checkboxes = function () { this._data.core.themes.checkboxes = true; this.get_container_ul().removeClass("jstree-no-checkboxes"); }; - /** - * hide the node checkbox icons - * @name hide_checkboxes() - * @plugin checkbox - */ - this.hide_checkboxes = function () { this._data.core.themes.checkboxes = false; this.get_container_ul().addClass("jstree-no-checkboxes"); }; - /** - * toggle the node icons - * @name toggle_checkboxes() - * @plugin checkbox - */ - this.toggle_checkboxes = function () { if(this._data.core.themes.checkboxes) { this.hide_checkboxes(); } else { this.show_checkboxes(); } }; - /** - * checks if a node is in an undetermined state - * @name is_undetermined(obj) - * @param {mixed} obj - * @return {Boolean} - */ - this.is_undetermined = function (obj) { - obj = this.get_node(obj); - var s = this.settings.checkbox.cascade, i, j, t = this.settings.checkbox.tie_selection, d = this._data[ t ? 'core' : 'checkbox' ].selected, m = this._model.data; - if(!obj || obj.state[ t ? 'selected' : 'checked' ] === true || s.indexOf('undetermined') === -1 || (s.indexOf('down') === -1 && s.indexOf('up') === -1)) { - return false; - } - if(!obj.state.loaded && obj.original.state.undetermined === true) { - return true; - } - for(i = 0, j = obj.children_d.length; i < j; i++) { - if($.inArray(obj.children_d[i], d) !== -1 || (!m[obj.children_d[i]].state.loaded && m[obj.children_d[i]].original.state.undetermined)) { - return true; - } - } - return false; - }; - - this.activate_node = function (obj, e) { - if(this.settings.checkbox.tie_selection && (this.settings.checkbox.whole_node || $(e.target).hasClass('jstree-checkbox'))) { - e.ctrlKey = true; - } - if(this.settings.checkbox.tie_selection || (!this.settings.checkbox.whole_node && !$(e.target).hasClass('jstree-checkbox'))) { - return parent.activate_node.call(this, obj, e); - } - if(this.is_checked(obj)) { - this.uncheck_node(obj, e); - } - else { - this.check_node(obj, e); - } - this.trigger('activate_node', { 'node' : this.get_node(obj) }); - }; - - /** - * check a node (only if tie_selection in checkbox settings is false, otherwise select_node will be called internally) - * @name check_node(obj) - * @param {mixed} obj an array can be used to check multiple nodes - * @trigger check_node.jstree - * @plugin checkbox - */ - this.check_node = function (obj, e) { - if(this.settings.checkbox.tie_selection) { return this.select_node(obj, false, true, e); } - var dom, t1, t2, th; - if($.isArray(obj)) { - obj = obj.slice(); - for(t1 = 0, t2 = obj.length; t1 < t2; t1++) { - this.check_node(obj[t1], e); - } - return true; - } - obj = this.get_node(obj); - if(!obj || obj.id === '#') { - return false; - } - dom = this.get_node(obj, true); - if(!obj.state.checked) { - obj.state.checked = true; - this._data.checkbox.selected.push(obj.id); - if(dom && dom.length) { - dom.children('.jstree-anchor').addClass('jstree-checked'); - } - /** - * triggered when an node is checked (only if tie_selection in checkbox settings is false) - * @event - * @name check_node.jstree - * @param {Object} node - * @param {Array} selected the current selection - * @param {Object} event the event (if any) that triggered this check_node - * @plugin checkbox - */ - this.trigger('check_node', { 'node' : obj, 'selected' : this._data.checkbox.selected, 'event' : e }); - } - }; - /** - * uncheck a node (only if tie_selection in checkbox settings is false, otherwise deselect_node will be called internally) - * @name deselect_node(obj) - * @param {mixed} obj an array can be used to deselect multiple nodes - * @trigger uncheck_node.jstree - * @plugin checkbox - */ - this.uncheck_node = function (obj, e) { - if(this.settings.checkbox.tie_selection) { return this.deselect_node(obj, false, e); } - var t1, t2, dom; - if($.isArray(obj)) { - obj = obj.slice(); - for(t1 = 0, t2 = obj.length; t1 < t2; t1++) { - this.uncheck_node(obj[t1], e); - } - return true; - } - obj = this.get_node(obj); - if(!obj || obj.id === '#') { - return false; - } - dom = this.get_node(obj, true); - if(obj.state.checked) { - obj.state.checked = false; - this._data.checkbox.selected = $.vakata.array_remove_item(this._data.checkbox.selected, obj.id); - if(dom.length) { - dom.children('.jstree-anchor').removeClass('jstree-checked'); - } - /** - * triggered when an node is unchecked (only if tie_selection in checkbox settings is false) - * @event - * @name uncheck_node.jstree - * @param {Object} node - * @param {Array} selected the current selection - * @param {Object} event the event (if any) that triggered this uncheck_node - * @plugin checkbox - */ - this.trigger('uncheck_node', { 'node' : obj, 'selected' : this._data.checkbox.selected, 'event' : e }); - } - }; - /** - * checks all nodes in the tree (only if tie_selection in checkbox settings is false, otherwise select_all will be called internally) - * @name check_all() - * @trigger check_all.jstree, changed.jstree - * @plugin checkbox - */ - this.check_all = function () { - if(this.settings.checkbox.tie_selection) { return this.select_all(); } - var tmp = this._data.checkbox.selected.concat([]), i, j; - this._data.checkbox.selected = this._model.data['#'].children_d.concat(); - for(i = 0, j = this._data.checkbox.selected.length; i < j; i++) { - if(this._model.data[this._data.checkbox.selected[i]]) { - this._model.data[this._data.checkbox.selected[i]].state.checked = true; - } - } - this.redraw(true); - /** - * triggered when all nodes are checked (only if tie_selection in checkbox settings is false) - * @event - * @name check_all.jstree - * @param {Array} selected the current selection - * @plugin checkbox - */ - this.trigger('check_all', { 'selected' : this._data.checkbox.selected }); - }; - /** - * uncheck all checked nodes (only if tie_selection in checkbox settings is false, otherwise deselect_all will be called internally) - * @name uncheck_all() - * @trigger uncheck_all.jstree - * @plugin checkbox - */ - this.uncheck_all = function () { - if(this.settings.checkbox.tie_selection) { return this.deselect_all(); } - var tmp = this._data.checkbox.selected.concat([]), i, j; - for(i = 0, j = this._data.checkbox.selected.length; i < j; i++) { - if(this._model.data[this._data.checkbox.selected[i]]) { - this._model.data[this._data.checkbox.selected[i]].state.checked = false; - } - } - this._data.checkbox.selected = []; - this.element.find('.jstree-checked').removeClass('jstree-checked'); - /** - * triggered when all nodes are unchecked (only if tie_selection in checkbox settings is false) - * @event - * @name uncheck_all.jstree - * @param {Object} node the previous selection - * @param {Array} selected the current selection - * @plugin checkbox - */ - this.trigger('uncheck_all', { 'selected' : this._data.checkbox.selected, 'node' : tmp }); - }; - /** - * checks if a node is checked (if tie_selection is on in the settings this function will return the same as is_selected) - * @name is_checked(obj) - * @param {mixed} obj - * @return {Boolean} - * @plugin checkbox - */ - this.is_checked = function (obj) { - if(this.settings.checkbox.tie_selection) { return this.is_selected(obj); } - obj = this.get_node(obj); - if(!obj || obj.id === '#') { return false; } - return obj.state.checked; - }; - /** - * get an array of all checked nodes (if tie_selection is on in the settings this function will return the same as get_selected) - * @name get_checked([full]) - * @param {mixed} full if set to `true` the returned array will consist of the full node objects, otherwise - only IDs will be returned - * @return {Array} - * @plugin checkbox - */ - this.get_checked = function (full) { - if(this.settings.checkbox.tie_selection) { return this.get_selected(full); } - return full ? $.map(this._data.checkbox.selected, $.proxy(function (i) { return this.get_node(i); }, this)) : this._data.checkbox.selected; - }; - /** - * get an array of all top level checked nodes (ignoring children of checked nodes) (if tie_selection is on in the settings this function will return the same as get_top_selected) - * @name get_top_checked([full]) - * @param {mixed} full if set to `true` the returned array will consist of the full node objects, otherwise - only IDs will be returned - * @return {Array} - * @plugin checkbox - */ - this.get_top_checked = function (full) { - if(this.settings.checkbox.tie_selection) { return this.get_top_selected(full); } - var tmp = this.get_checked(true), - obj = {}, i, j, k, l; - for(i = 0, j = tmp.length; i < j; i++) { - obj[tmp[i].id] = tmp[i]; - } - for(i = 0, j = tmp.length; i < j; i++) { - for(k = 0, l = tmp[i].children_d.length; k < l; k++) { - if(obj[tmp[i].children_d[k]]) { - delete obj[tmp[i].children_d[k]]; - } - } - } - tmp = []; - for(i in obj) { - if(obj.hasOwnProperty(i)) { - tmp.push(i); - } - } - return full ? $.map(tmp, $.proxy(function (i) { return this.get_node(i); }, this)) : tmp; - }; - /** - * get an array of all bottom level checked nodes (ignoring selected parents) (if tie_selection is on in the settings this function will return the same as get_bottom_selected) - * @name get_bottom_checked([full]) - * @param {mixed} full if set to `true` the returned array will consist of the full node objects, otherwise - only IDs will be returned - * @return {Array} - * @plugin checkbox - */ - this.get_bottom_checked = function (full) { - if(this.settings.checkbox.tie_selection) { return this.get_bottom_selected(full); } - var tmp = this.get_checked(true), - obj = [], i, j; - for(i = 0, j = tmp.length; i < j; i++) { - if(!tmp[i].children.length) { - obj.push(tmp[i].id); - } - } - return full ? $.map(obj, $.proxy(function (i) { return this.get_node(i); }, this)) : obj; - }; - }; - - // include the checkbox plugin by default - // $.jstree.defaults.plugins.push("checkbox"); - -/** - * ### Contextmenu plugin - * - * Shows a context menu when a node is right-clicked. - */ -// TODO: move logic outside of function + check multiple move - - /** - * stores all defaults for the contextmenu plugin - * @name $.jstree.defaults.contextmenu - * @plugin contextmenu - */ - $.jstree.defaults.contextmenu = { - /** - * a boolean indicating if the node should be selected when the context menu is invoked on it. Defaults to `true`. - * @name $.jstree.defaults.contextmenu.select_node - * @plugin contextmenu - */ - select_node : true, - /** - * a boolean indicating if the menu should be shown aligned with the node. Defaults to `true`, otherwise the mouse coordinates are used. - * @name $.jstree.defaults.contextmenu.show_at_node - * @plugin contextmenu - */ - show_at_node : true, - /** - * an object of actions, or a function that accepts a node and a callback function and calls the callback function with an object of actions available for that node (you can also return the items too). - * - * Each action consists of a key (a unique name) and a value which is an object with the following properties (only label and action are required): - * - * * `separator_before` - a boolean indicating if there should be a separator before this item - * * `separator_after` - a boolean indicating if there should be a separator after this item - * * `_disabled` - a boolean indicating if this action should be disabled - * * `label` - a string - the name of the action (could be a function returning a string) - * * `action` - a function to be executed if this item is chosen - * * `icon` - a string, can be a path to an icon or a className, if using an image that is in the current directory use a `./` prefix, otherwise it will be detected as a class - * * `shortcut` - keyCode which will trigger the action if the menu is open (for example `113` for rename, which equals F2) - * * `shortcut_label` - shortcut label (like for example `F2` for rename) - * - * @name $.jstree.defaults.contextmenu.items - * @plugin contextmenu - */ - items : function (o, cb) { // Could be an object directly - return { - "create" : { - "separator_before" : false, - "separator_after" : true, - "_disabled" : false, //(this.check("create_node", data.reference, {}, "last")), - "label" : "Create", - "action" : function (data) { - var inst = $.jstree.reference(data.reference), - obj = inst.get_node(data.reference); - inst.create_node(obj, {}, "last", function (new_node) { - setTimeout(function () { inst.edit(new_node); },0); - }); - } - }, - "rename" : { - "separator_before" : false, - "separator_after" : false, - "_disabled" : false, //(this.check("rename_node", data.reference, this.get_parent(data.reference), "")), - "label" : "Rename", - /* - "shortcut" : 113, - "shortcut_label" : 'F2', - "icon" : "glyphicon glyphicon-leaf", - */ - "action" : function (data) { - var inst = $.jstree.reference(data.reference), - obj = inst.get_node(data.reference); - inst.edit(obj); - } - }, - "remove" : { - "separator_before" : false, - "icon" : false, - "separator_after" : false, - "_disabled" : false, //(this.check("delete_node", data.reference, this.get_parent(data.reference), "")), - "label" : "Delete", - "action" : function (data) { - var inst = $.jstree.reference(data.reference), - obj = inst.get_node(data.reference); - if(inst.is_selected(obj)) { - inst.delete_node(inst.get_selected()); - } - else { - inst.delete_node(obj); - } - } - }, - "ccp" : { - "separator_before" : true, - "icon" : false, - "separator_after" : false, - "label" : "Edit", - "action" : false, - "submenu" : { - "cut" : { - "separator_before" : false, - "separator_after" : false, - "label" : "Cut", - "action" : function (data) { - var inst = $.jstree.reference(data.reference), - obj = inst.get_node(data.reference); - if(inst.is_selected(obj)) { - inst.cut(inst.get_selected()); - } - else { - inst.cut(obj); - } - } - }, - "copy" : { - "separator_before" : false, - "icon" : false, - "separator_after" : false, - "label" : "Copy", - "action" : function (data) { - var inst = $.jstree.reference(data.reference), - obj = inst.get_node(data.reference); - if(inst.is_selected(obj)) { - inst.copy(inst.get_selected()); - } - else { - inst.copy(obj); - } - } - }, - "paste" : { - "separator_before" : false, - "icon" : false, - "_disabled" : function (data) { - return !$.jstree.reference(data.reference).can_paste(); - }, - "separator_after" : false, - "label" : "Paste", - "action" : function (data) { - var inst = $.jstree.reference(data.reference), - obj = inst.get_node(data.reference); - inst.paste(obj); - } - } - } - } - }; - } - }; - - $.jstree.plugins.contextmenu = function (options, parent) { - this.bind = function () { - parent.bind.call(this); - - var last_ts = 0; - this.element - .on("contextmenu.jstree", ".jstree-anchor", $.proxy(function (e) { - e.preventDefault(); - last_ts = e.ctrlKey ? e.timeStamp : 0; - if(!this.is_loading(e.currentTarget)) { - this.show_contextmenu(e.currentTarget, e.pageX, e.pageY, e); - } - }, this)) - .on("click.jstree", ".jstree-anchor", $.proxy(function (e) { - if(this._data.contextmenu.visible && (!last_ts || e.timeStamp - last_ts > 250)) { // work around safari & macOS ctrl+click - $.vakata.context.hide(); - } - }, this)); - /* - if(!('oncontextmenu' in document.body) && ('ontouchstart' in document.body)) { - var el = null, tm = null; - this.element - .on("touchstart", ".jstree-anchor", function (e) { - el = e.currentTarget; - tm = +new Date(); - $(document).one("touchend", function (e) { - e.target = document.elementFromPoint(e.originalEvent.targetTouches[0].pageX - window.pageXOffset, e.originalEvent.targetTouches[0].pageY - window.pageYOffset); - e.currentTarget = e.target; - tm = ((+(new Date())) - tm); - if(e.target === el && tm > 600 && tm < 1000) { - e.preventDefault(); - $(el).trigger('contextmenu', e); - } - el = null; - tm = null; - }); - }); - } - */ - $(document).on("context_hide.vakata", $.proxy(function () { this._data.contextmenu.visible = false; }, this)); - }; - this.teardown = function () { - if(this._data.contextmenu.visible) { - $.vakata.context.hide(); - } - parent.teardown.call(this); - }; - - /** - * prepare and show the context menu for a node - * @name show_contextmenu(obj [, x, y]) - * @param {mixed} obj the node - * @param {Number} x the x-coordinate relative to the document to show the menu at - * @param {Number} y the y-coordinate relative to the document to show the menu at - * @param {Object} e the event if available that triggered the contextmenu - * @plugin contextmenu - * @trigger show_contextmenu.jstree - */ - this.show_contextmenu = function (obj, x, y, e) { - obj = this.get_node(obj); - if(!obj || obj.id === '#') { return false; } - var s = this.settings.contextmenu, - d = this.get_node(obj, true), - a = d.children(".jstree-anchor"), - o = false, - i = false; - if(s.show_at_node || x === undefined || y === undefined) { - o = a.offset(); - x = o.left; - y = o.top + this._data.core.li_height; - } - if(this.settings.contextmenu.select_node && !this.is_selected(obj)) { - this.activate_node(obj, e); - } - - i = s.items; - if($.isFunction(i)) { - i = i.call(this, obj, $.proxy(function (i) { - this._show_contextmenu(obj, x, y, i); - }, this)); - } - if($.isPlainObject(i)) { - this._show_contextmenu(obj, x, y, i); - } - }; - /** - * show the prepared context menu for a node - * @name _show_contextmenu(obj, x, y, i) - * @param {mixed} obj the node - * @param {Number} x the x-coordinate relative to the document to show the menu at - * @param {Number} y the y-coordinate relative to the document to show the menu at - * @param {Number} i the object of items to show - * @plugin contextmenu - * @trigger show_contextmenu.jstree - * @private - */ - this._show_contextmenu = function (obj, x, y, i) { - var d = this.get_node(obj, true), - a = d.children(".jstree-anchor"); - $(document).one("context_show.vakata", $.proxy(function (e, data) { - var cls = 'jstree-contextmenu jstree-' + this.get_theme() + '-contextmenu'; - $(data.element).addClass(cls); - }, this)); - this._data.contextmenu.visible = true; - $.vakata.context.show(a, { 'x' : x, 'y' : y }, i); - /** - * triggered when the contextmenu is shown for a node - * @event - * @name show_contextmenu.jstree - * @param {Object} node the node - * @param {Number} x the x-coordinate of the menu relative to the document - * @param {Number} y the y-coordinate of the menu relative to the document - * @plugin contextmenu - */ - this.trigger('show_contextmenu', { "node" : obj, "x" : x, "y" : y }); - }; - }; - - // contextmenu helper - (function ($) { - var right_to_left = false, - vakata_context = { - element : false, - reference : false, - position_x : 0, - position_y : 0, - items : [], - html : "", - is_visible : false - }; - - $.vakata.context = { - settings : { - hide_onmouseleave : 0, - icons : true - }, - _trigger : function (event_name) { - $(document).triggerHandler("context_" + event_name + ".vakata", { - "reference" : vakata_context.reference, - "element" : vakata_context.element, - "position" : { - "x" : vakata_context.position_x, - "y" : vakata_context.position_y - } - }); - }, - _execute : function (i) { - i = vakata_context.items[i]; - return i && (!i._disabled || ($.isFunction(i._disabled) && !i._disabled({ "item" : i, "reference" : vakata_context.reference, "element" : vakata_context.element }))) && i.action ? i.action.call(null, { - "item" : i, - "reference" : vakata_context.reference, - "element" : vakata_context.element, - "position" : { - "x" : vakata_context.position_x, - "y" : vakata_context.position_y - } - }) : false; - }, - _parse : function (o, is_callback) { - if(!o) { return false; } - if(!is_callback) { - vakata_context.html = ""; - vakata_context.items = []; - } - var str = "", - sep = false, - tmp; - - if(is_callback) { str += "<"+"ul>"; } - $.each(o, function (i, val) { - if(!val) { return true; } - vakata_context.items.push(val); - if(!sep && val.separator_before) { - str += "<"+"li class='vakata-context-separator'><"+"a href='#' " + ($.vakata.context.settings.icons ? '' : 'style="margin-left:0px;"') + "> <"+"/a><"+"/li>"; - } - sep = false; - str += "<"+"li class='" + (val._class || "") + (val._disabled === true || ($.isFunction(val._disabled) && val._disabled({ "item" : val, "reference" : vakata_context.reference, "element" : vakata_context.element })) ? " vakata-contextmenu-disabled " : "") + "' "+(val.shortcut?" data-shortcut='"+val.shortcut+"' ":'')+">"; - str += "<"+"a href='#' rel='" + (vakata_context.items.length - 1) + "'>"; - if($.vakata.context.settings.icons) { - str += "<"+"i "; - if(val.icon) { - if(val.icon.indexOf("/") !== -1 || val.icon.indexOf(".") !== -1) { str += " style='background:url(\"" + val.icon + "\") center center no-repeat' "; } - else { str += " class='" + val.icon + "' "; } - } - str += "><"+"/i><"+"span class='vakata-contextmenu-sep'> <"+"/span>"; - } - str += ($.isFunction(val.label) ? val.label({ "item" : i, "reference" : vakata_context.reference, "element" : vakata_context.element }) : val.label) + (val.shortcut?' '+ (val.shortcut_label || '') +'':'') + "<"+"/a>"; - if(val.submenu) { - tmp = $.vakata.context._parse(val.submenu, true); - if(tmp) { str += tmp; } - } - str += "<"+"/li>"; - if(val.separator_after) { - str += "<"+"li class='vakata-context-separator'><"+"a href='#' " + ($.vakata.context.settings.icons ? '' : 'style="margin-left:0px;"') + "> <"+"/a><"+"/li>"; - sep = true; - } - }); - str = str.replace(/
  • <\/li\>$/,""); - if(is_callback) { str += ""; } - /** - * triggered on the document when the contextmenu is parsed (HTML is built) - * @event - * @plugin contextmenu - * @name context_parse.vakata - * @param {jQuery} reference the element that was right clicked - * @param {jQuery} element the DOM element of the menu itself - * @param {Object} position the x & y coordinates of the menu - */ - if(!is_callback) { vakata_context.html = str; $.vakata.context._trigger("parse"); } - return str.length > 10 ? str : false; - }, - _show_submenu : function (o) { - o = $(o); - if(!o.length || !o.children("ul").length) { return; } - var e = o.children("ul"), - x = o.offset().left + o.outerWidth(), - y = o.offset().top, - w = e.width(), - h = e.height(), - dw = $(window).width() + $(window).scrollLeft(), - dh = $(window).height() + $(window).scrollTop(); - // може да се спести е една проверка - дали няма някой от класовете вече нагоре - if(right_to_left) { - o[x - (w + 10 + o.outerWidth()) < 0 ? "addClass" : "removeClass"]("vakata-context-left"); - } - else { - o[x + w + 10 > dw ? "addClass" : "removeClass"]("vakata-context-right"); - } - if(y + h + 10 > dh) { - e.css("bottom","-1px"); - } - e.show(); - }, - show : function (reference, position, data) { - var o, e, x, y, w, h, dw, dh, cond = true; - if(vakata_context.element && vakata_context.element.length) { - vakata_context.element.width(''); - } - switch(cond) { - case (!position && !reference): - return false; - case (!!position && !!reference): - vakata_context.reference = reference; - vakata_context.position_x = position.x; - vakata_context.position_y = position.y; - break; - case (!position && !!reference): - vakata_context.reference = reference; - o = reference.offset(); - vakata_context.position_x = o.left + reference.outerHeight(); - vakata_context.position_y = o.top; - break; - case (!!position && !reference): - vakata_context.position_x = position.x; - vakata_context.position_y = position.y; - break; - } - if(!!reference && !data && $(reference).data('vakata_contextmenu')) { - data = $(reference).data('vakata_contextmenu'); - } - if($.vakata.context._parse(data)) { - vakata_context.element.html(vakata_context.html); - } - if(vakata_context.items.length) { - e = vakata_context.element; - x = vakata_context.position_x; - y = vakata_context.position_y; - w = e.width(); - h = e.height(); - dw = $(window).width() + $(window).scrollLeft(); - dh = $(window).height() + $(window).scrollTop(); - if(right_to_left) { - x -= e.outerWidth(); - if(x < $(window).scrollLeft() + 20) { - x = $(window).scrollLeft() + 20; - } - } - if(x + w + 20 > dw) { - x = dw - (w + 20); - } - if(y + h + 20 > dh) { - y = dh - (h + 20); - } - - vakata_context.element - .css({ "left" : x, "top" : y }) - .show() - .find('a:eq(0)').focus().parent().addClass("vakata-context-hover"); - vakata_context.is_visible = true; - /** - * triggered on the document when the contextmenu is shown - * @event - * @plugin contextmenu - * @name context_show.vakata - * @param {jQuery} reference the element that was right clicked - * @param {jQuery} element the DOM element of the menu itself - * @param {Object} position the x & y coordinates of the menu - */ - $.vakata.context._trigger("show"); - } - }, - hide : function () { - if(vakata_context.is_visible) { - vakata_context.element.hide().find("ul").hide().end().find(':focus').blur(); - vakata_context.is_visible = false; - /** - * triggered on the document when the contextmenu is hidden - * @event - * @plugin contextmenu - * @name context_hide.vakata - * @param {jQuery} reference the element that was right clicked - * @param {jQuery} element the DOM element of the menu itself - * @param {Object} position the x & y coordinates of the menu - */ - $.vakata.context._trigger("hide"); - } - } - }; - $(function () { - right_to_left = $("body").css("direction") === "rtl"; - var to = false; - - vakata_context.element = $("
      "); - vakata_context.element - .on("mouseenter", "li", function (e) { - e.stopImmediatePropagation(); - - if($.contains(this, e.relatedTarget)) { - // премахнато заради delegate mouseleave по-долу - // $(this).find(".vakata-context-hover").removeClass("vakata-context-hover"); - return; - } - - if(to) { clearTimeout(to); } - vakata_context.element.find(".vakata-context-hover").removeClass("vakata-context-hover").end(); - - $(this) - .siblings().find("ul").hide().end().end() - .parentsUntil(".vakata-context", "li").addBack().addClass("vakata-context-hover"); - $.vakata.context._show_submenu(this); - }) - // тестово - дали не натоварва? - .on("mouseleave", "li", function (e) { - if($.contains(this, e.relatedTarget)) { return; } - $(this).find(".vakata-context-hover").addBack().removeClass("vakata-context-hover"); - }) - .on("mouseleave", function (e) { - $(this).find(".vakata-context-hover").removeClass("vakata-context-hover"); - if($.vakata.context.settings.hide_onmouseleave) { - to = setTimeout( - (function (t) { - return function () { $.vakata.context.hide(); }; - }(this)), $.vakata.context.settings.hide_onmouseleave); - } - }) - .on("click", "a", function (e) { - e.preventDefault(); - //}) - //.on("mouseup", "a", function (e) { - if(!$(this).blur().parent().hasClass("vakata-context-disabled") && $.vakata.context._execute($(this).attr("rel")) !== false) { - $.vakata.context.hide(); - } - }) - .on('keydown', 'a', function (e) { - var o = null; - switch(e.which) { - case 13: - case 32: - e.type = "mouseup"; - e.preventDefault(); - $(e.currentTarget).trigger(e); - break; - case 37: - if(vakata_context.is_visible) { - vakata_context.element.find(".vakata-context-hover").last().parents("li:eq(0)").find("ul").hide().find(".vakata-context-hover").removeClass("vakata-context-hover").end().end().children('a').focus(); - e.stopImmediatePropagation(); - e.preventDefault(); - } - break; - case 38: - if(vakata_context.is_visible) { - o = vakata_context.element.find("ul:visible").addBack().last().children(".vakata-context-hover").removeClass("vakata-context-hover").prevAll("li:not(.vakata-context-separator)").first(); - if(!o.length) { o = vakata_context.element.find("ul:visible").addBack().last().children("li:not(.vakata-context-separator)").last(); } - o.addClass("vakata-context-hover").children('a').focus(); - e.stopImmediatePropagation(); - e.preventDefault(); - } - break; - case 39: - if(vakata_context.is_visible) { - vakata_context.element.find(".vakata-context-hover").last().children("ul").show().children("li:not(.vakata-context-separator)").removeClass("vakata-context-hover").first().addClass("vakata-context-hover").children('a').focus(); - e.stopImmediatePropagation(); - e.preventDefault(); - } - break; - case 40: - if(vakata_context.is_visible) { - o = vakata_context.element.find("ul:visible").addBack().last().children(".vakata-context-hover").removeClass("vakata-context-hover").nextAll("li:not(.vakata-context-separator)").first(); - if(!o.length) { o = vakata_context.element.find("ul:visible").addBack().last().children("li:not(.vakata-context-separator)").first(); } - o.addClass("vakata-context-hover").children('a').focus(); - e.stopImmediatePropagation(); - e.preventDefault(); - } - break; - case 27: - $.vakata.context.hide(); - e.preventDefault(); - break; - default: - //console.log(e.which); - break; - } - }) - .on('keydown', function (e) { - e.preventDefault(); - var a = vakata_context.element.find('.vakata-contextmenu-shortcut-' + e.which).parent(); - if(a.parent().not('.vakata-context-disabled')) { - a.mouseup(); - } - }) - .appendTo("body"); - - $(document) - .on("mousedown", function (e) { - if(vakata_context.is_visible && !$.contains(vakata_context.element[0], e.target)) { $.vakata.context.hide(); } - }) - .on("context_show.vakata", function (e, data) { - vakata_context.element.find("li:has(ul)").children("a").addClass("vakata-context-parent"); - if(right_to_left) { - vakata_context.element.addClass("vakata-context-rtl").css("direction", "rtl"); - } - // also apply a RTL class? - vakata_context.element.find("ul").hide().end(); - }); - }); - }($)); - // $.jstree.defaults.plugins.push("contextmenu"); - -/** - * ### Drag'n'drop plugin - * - * Enables dragging and dropping of nodes in the tree, resulting in a move or copy operations. - */ - - /** - * stores all defaults for the drag'n'drop plugin - * @name $.jstree.defaults.dnd - * @plugin dnd - */ - $.jstree.defaults.dnd = { - /** - * a boolean indicating if a copy should be possible while dragging (by pressint the meta key or Ctrl). Defaults to `true`. - * @name $.jstree.defaults.dnd.copy - * @plugin dnd - */ - copy : true, - /** - * a number indicating how long a node should remain hovered while dragging to be opened. Defaults to `500`. - * @name $.jstree.defaults.dnd.open_timeout - * @plugin dnd - */ - open_timeout : 500, - /** - * a function invoked each time a node is about to be dragged, invoked in the tree's scope and receives the nodes about to be dragged as an argument (array) - return `false` to prevent dragging - * @name $.jstree.defaults.dnd.is_draggable - * @plugin dnd - */ - is_draggable : true, - /** - * a boolean indicating if checks should constantly be made while the user is dragging the node (as opposed to checking only on drop), default is `true` - * @name $.jstree.defaults.dnd.check_while_dragging - * @plugin dnd - */ - check_while_dragging : true, - /** - * a boolean indicating if nodes from this tree should only be copied with dnd (as opposed to moved), default is `false` - * @name $.jstree.defaults.dnd.always_copy - * @plugin dnd - */ - always_copy : false, - /** - * when dropping a node "inside", this setting indicates the position the node should go to - it can be an integer or a string: "first" (same as 0) or "last", default is `0` - * @name $.jstree.defaults.dnd.inside_pos - * @plugin dnd - */ - inside_pos : 0 - }; - // TODO: now check works by checking for each node individually, how about max_children, unique, etc? - // TODO: drop somewhere else - maybe demo only? - $.jstree.plugins.dnd = function (options, parent) { - this.bind = function () { - parent.bind.call(this); - - this.element - .on('mousedown.jstree touchstart.jstree', '.jstree-anchor', $.proxy(function (e) { - var obj = this.get_node(e.target), - mlt = this.is_selected(obj) ? this.get_selected().length : 1; - if(obj && obj.id && obj.id !== "#" && (e.which === 1 || e.type === "touchstart") && - (this.settings.dnd.is_draggable === true || ($.isFunction(this.settings.dnd.is_draggable) && this.settings.dnd.is_draggable.call(this, (mlt > 1 ? this.get_selected(true) : [obj])))) - ) { - this.element.trigger('mousedown.jstree'); - return $.vakata.dnd.start(e, { 'jstree' : true, 'origin' : this, 'obj' : this.get_node(obj,true), 'nodes' : mlt > 1 ? this.get_selected() : [obj.id] }, '
      ' + (mlt > 1 ? mlt + ' ' + this.get_string('nodes') : this.get_text(e.currentTarget, true)) + '
      '); - } - }, this)); - }; - }; - - $(function() { - // bind only once for all instances - var lastmv = false, - laster = false, - opento = false, - marker = $('
       
      ').hide().appendTo('body'); - - $(document) - .bind('dnd_start.vakata', function (e, data) { - lastmv = false; - }) - .bind('dnd_move.vakata', function (e, data) { - if(opento) { clearTimeout(opento); } - if(!data || !data.data || !data.data.jstree) { return; } - - // if we are hovering the marker image do nothing (can happen on "inside" drags) - if(data.event.target.id && data.event.target.id === 'jstree-marker') { - return; - } - - var ins = $.jstree.reference(data.event.target), - ref = false, - off = false, - rel = false, - l, t, h, p, i, o, ok, t1, t2, op, ps, pr, ip, tm; - // if we are over an instance - if(ins && ins._data && ins._data.dnd) { - marker.attr('class', 'jstree-' + ins.get_theme() + ( ins.settings.core.themes.responsive ? ' jstree-dnd-responsive' : '' )); - data.helper - .children().attr('class', 'jstree-' + ins.get_theme() + ( ins.settings.core.themes.responsive ? ' jstree-dnd-responsive' : '' )) - .find('.jstree-copy:eq(0)')[ data.data.origin && (data.data.origin.settings.dnd.always_copy || (data.data.origin.settings.dnd.copy && (data.event.metaKey || data.event.ctrlKey))) ? 'show' : 'hide' ](); - - - // if are hovering the container itself add a new root node - if( (data.event.target === ins.element[0] || data.event.target === ins.get_container_ul()[0]) && ins.get_container_ul().children().length === 0) { - ok = true; - for(t1 = 0, t2 = data.data.nodes.length; t1 < t2; t1++) { - ok = ok && ins.check( (data.data.origin && (data.data.origin.settings.dnd.always_copy || (data.data.origin.settings.dnd.copy && (data.event.metaKey || data.event.ctrlKey)) ) ? "copy_node" : "move_node"), (data.data.origin && data.data.origin !== ins ? data.data.origin.get_node(data.data.nodes[t1]) : data.data.nodes[t1]), '#', 'last', { 'dnd' : true, 'ref' : ins.get_node('#'), 'pos' : 'i', 'is_multi' : (data.data.origin && data.data.origin !== ins), 'is_foreign' : (!data.data.origin) }); - if(!ok) { break; } - } - if(ok) { - lastmv = { 'ins' : ins, 'par' : '#', 'pos' : 'last' }; - marker.hide(); - data.helper.find('.jstree-icon:eq(0)').removeClass('jstree-er').addClass('jstree-ok'); - return; - } - } - else { - // if we are hovering a tree node - ref = $(data.event.target).closest('.jstree-anchor'); - if(ref && ref.length && ref.parent().is('.jstree-closed, .jstree-open, .jstree-leaf')) { - off = ref.offset(); - rel = data.event.pageY - off.top; - h = ref.height(); - if(rel < h / 3) { - o = ['b', 'i', 'a']; - } - else if(rel > h - h / 3) { - o = ['a', 'i', 'b']; - } - else { - o = rel > h / 2 ? ['i', 'a', 'b'] : ['i', 'b', 'a']; - } - $.each(o, function (j, v) { - switch(v) { - case 'b': - l = off.left - 6; - t = off.top; - p = ins.get_parent(ref); - i = ref.parent().index(); - break; - case 'i': - ip = ins.settings.dnd.inside_pos; - tm = ins.get_node(ref.parent()); - l = off.left - 2; - t = off.top + h / 2 + 1; - p = tm.id; - i = ip === 'first' ? 0 : (ip === 'last' ? tm.children.length : Math.min(ip, tm.children.length)); - break; - case 'a': - l = off.left - 6; - t = off.top + h; - p = ins.get_parent(ref); - i = ref.parent().index() + 1; - break; - } - /*! - // TODO: moving inside, but the node is not yet loaded? - // the check will work anyway, as when moving the node will be loaded first and checked again - if(v === 'i' && !ins.is_loaded(p)) { } - */ - ok = true; - for(t1 = 0, t2 = data.data.nodes.length; t1 < t2; t1++) { - op = data.data.origin && (data.data.origin.settings.dnd.always_copy || (data.data.origin.settings.dnd.copy && (data.event.metaKey || data.event.ctrlKey))) ? "copy_node" : "move_node"; - ps = i; - if(op === "move_node" && v === 'a' && (data.data.origin && data.data.origin === ins) && p === ins.get_parent(data.data.nodes[t1])) { - pr = ins.get_node(p); - if(ps > $.inArray(data.data.nodes[t1], pr.children)) { - ps -= 1; - } - } - ok = ok && ( (ins && ins.settings && ins.settings.dnd && ins.settings.dnd.check_while_dragging === false) || ins.check(op, (data.data.origin && data.data.origin !== ins ? data.data.origin.get_node(data.data.nodes[t1]) : data.data.nodes[t1]), p, ps, { 'dnd' : true, 'ref' : ins.get_node(ref.parent()), 'pos' : v, 'is_multi' : (data.data.origin && data.data.origin !== ins), 'is_foreign' : (!data.data.origin) }) ); - if(!ok) { - if(ins && ins.last_error) { laster = ins.last_error(); } - break; - } - } - if(ok) { - if(v === 'i' && ref.parent().is('.jstree-closed') && ins.settings.dnd.open_timeout) { - opento = setTimeout((function (x, z) { return function () { x.open_node(z); }; }(ins, ref)), ins.settings.dnd.open_timeout); - } - lastmv = { 'ins' : ins, 'par' : p, 'pos' : v === 'i' && ip === 'last' && i === 0 && !ins.is_loaded(tm) ? 'last' : i }; - marker.css({ 'left' : l + 'px', 'top' : t + 'px' }).show(); - data.helper.find('.jstree-icon:eq(0)').removeClass('jstree-er').addClass('jstree-ok'); - laster = {}; - o = true; - return false; - } - }); - if(o === true) { return; } - } - } - } - lastmv = false; - data.helper.find('.jstree-icon').removeClass('jstree-ok').addClass('jstree-er'); - marker.hide(); - }) - .bind('dnd_scroll.vakata', function (e, data) { - if(!data || !data.data || !data.data.jstree) { return; } - marker.hide(); - lastmv = false; - data.helper.find('.jstree-icon:eq(0)').removeClass('jstree-ok').addClass('jstree-er'); - }) - .bind('dnd_stop.vakata', function (e, data) { - if(opento) { clearTimeout(opento); } - if(!data || !data.data || !data.data.jstree) { return; } - marker.hide(); - var i, j, nodes = []; - if(lastmv) { - for(i = 0, j = data.data.nodes.length; i < j; i++) { - nodes[i] = data.data.origin ? data.data.origin.get_node(data.data.nodes[i]) : data.data.nodes[i]; - if(data.data.origin) { - nodes[i].instance = data.data.origin; - } - } - lastmv.ins[ data.data.origin && (data.data.origin.settings.dnd.always_copy || (data.data.origin.settings.dnd.copy && (data.event.metaKey || data.event.ctrlKey))) ? 'copy_node' : 'move_node' ](nodes, lastmv.par, lastmv.pos); - } - else { - i = $(data.event.target).closest('.jstree'); - if(i.length && laster && laster.error && laster.error === 'check') { - i = i.jstree(true); - if(i) { - i.settings.core.error.call(this, laster); - } - } - } - }) - .bind('keyup keydown', function (e, data) { - data = $.vakata.dnd._get(); - if(data && data.data && data.data.jstree) { - data.helper.find('.jstree-copy:eq(0)')[ data.data.origin && (data.data.origin.settings.dnd.always_copy || (data.data.origin.settings.dnd.copy && (e.metaKey || e.ctrlKey))) ? 'show' : 'hide' ](); - } - }); - }); - - // helpers - (function ($) { - // private variable - var vakata_dnd = { - element : false, - target : false, - is_down : false, - is_drag : false, - helper : false, - helper_w: 0, - data : false, - init_x : 0, - init_y : 0, - scroll_l: 0, - scroll_t: 0, - scroll_e: false, - scroll_i: false, - is_touch: false - }; - $.vakata.dnd = { - settings : { - scroll_speed : 10, - scroll_proximity : 20, - helper_left : 5, - helper_top : 10, - threshold : 5, - threshold_touch : 50 - }, - _trigger : function (event_name, e) { - var data = $.vakata.dnd._get(); - data.event = e; - $(document).triggerHandler("dnd_" + event_name + ".vakata", data); - }, - _get : function () { - return { - "data" : vakata_dnd.data, - "element" : vakata_dnd.element, - "helper" : vakata_dnd.helper - }; - }, - _clean : function () { - if(vakata_dnd.helper) { vakata_dnd.helper.remove(); } - if(vakata_dnd.scroll_i) { clearInterval(vakata_dnd.scroll_i); vakata_dnd.scroll_i = false; } - vakata_dnd = { - element : false, - target : false, - is_down : false, - is_drag : false, - helper : false, - helper_w: 0, - data : false, - init_x : 0, - init_y : 0, - scroll_l: 0, - scroll_t: 0, - scroll_e: false, - scroll_i: false, - is_touch: false - }; - $(document).off("mousemove touchmove", $.vakata.dnd.drag); - $(document).off("mouseup touchend", $.vakata.dnd.stop); - }, - _scroll : function (init_only) { - if(!vakata_dnd.scroll_e || (!vakata_dnd.scroll_l && !vakata_dnd.scroll_t)) { - if(vakata_dnd.scroll_i) { clearInterval(vakata_dnd.scroll_i); vakata_dnd.scroll_i = false; } - return false; - } - if(!vakata_dnd.scroll_i) { - vakata_dnd.scroll_i = setInterval($.vakata.dnd._scroll, 100); - return false; - } - if(init_only === true) { return false; } - - var i = vakata_dnd.scroll_e.scrollTop(), - j = vakata_dnd.scroll_e.scrollLeft(); - vakata_dnd.scroll_e.scrollTop(i + vakata_dnd.scroll_t * $.vakata.dnd.settings.scroll_speed); - vakata_dnd.scroll_e.scrollLeft(j + vakata_dnd.scroll_l * $.vakata.dnd.settings.scroll_speed); - if(i !== vakata_dnd.scroll_e.scrollTop() || j !== vakata_dnd.scroll_e.scrollLeft()) { - /** - * triggered on the document when a drag causes an element to scroll - * @event - * @plugin dnd - * @name dnd_scroll.vakata - * @param {Mixed} data any data supplied with the call to $.vakata.dnd.start - * @param {DOM} element the DOM element being dragged - * @param {jQuery} helper the helper shown next to the mouse - * @param {jQuery} event the element that is scrolling - */ - $.vakata.dnd._trigger("scroll", vakata_dnd.scroll_e); - } - }, - start : function (e, data, html) { - if(e.type === "touchstart" && e.originalEvent && e.originalEvent.changedTouches && e.originalEvent.changedTouches[0]) { - e.pageX = e.originalEvent.changedTouches[0].pageX; - e.pageY = e.originalEvent.changedTouches[0].pageY; - e.target = document.elementFromPoint(e.originalEvent.changedTouches[0].pageX - window.pageXOffset, e.originalEvent.changedTouches[0].pageY - window.pageYOffset); - } - if(vakata_dnd.is_drag) { $.vakata.dnd.stop({}); } - try { - e.currentTarget.unselectable = "on"; - e.currentTarget.onselectstart = function() { return false; }; - if(e.currentTarget.style) { e.currentTarget.style.MozUserSelect = "none"; } - } catch(ignore) { } - vakata_dnd.init_x = e.pageX; - vakata_dnd.init_y = e.pageY; - vakata_dnd.data = data; - vakata_dnd.is_down = true; - vakata_dnd.element = e.currentTarget; - vakata_dnd.target = e.target; - vakata_dnd.is_touch = e.type === "touchstart"; - if(html !== false) { - vakata_dnd.helper = $("
      ").html(html).css({ - "display" : "block", - "margin" : "0", - "padding" : "0", - "position" : "absolute", - "top" : "-2000px", - "lineHeight" : "16px", - "zIndex" : "10000" - }); - } - $(document).bind("mousemove touchmove", $.vakata.dnd.drag); - $(document).bind("mouseup touchend", $.vakata.dnd.stop); - return false; - }, - drag : function (e) { - if(e.type === "touchmove" && e.originalEvent && e.originalEvent.changedTouches && e.originalEvent.changedTouches[0]) { - e.pageX = e.originalEvent.changedTouches[0].pageX; - e.pageY = e.originalEvent.changedTouches[0].pageY; - e.target = document.elementFromPoint(e.originalEvent.changedTouches[0].pageX - window.pageXOffset, e.originalEvent.changedTouches[0].pageY - window.pageYOffset); - } - if(!vakata_dnd.is_down) { return; } - if(!vakata_dnd.is_drag) { - if( - Math.abs(e.pageX - vakata_dnd.init_x) > (vakata_dnd.is_touch ? $.vakata.dnd.settings.threshold_touch : $.vakata.dnd.settings.threshold) || - Math.abs(e.pageY - vakata_dnd.init_y) > (vakata_dnd.is_touch ? $.vakata.dnd.settings.threshold_touch : $.vakata.dnd.settings.threshold) - ) { - if(vakata_dnd.helper) { - vakata_dnd.helper.appendTo("body"); - vakata_dnd.helper_w = vakata_dnd.helper.outerWidth(); - } - vakata_dnd.is_drag = true; - /** - * triggered on the document when a drag starts - * @event - * @plugin dnd - * @name dnd_start.vakata - * @param {Mixed} data any data supplied with the call to $.vakata.dnd.start - * @param {DOM} element the DOM element being dragged - * @param {jQuery} helper the helper shown next to the mouse - * @param {Object} event the event that caused the start (probably mousemove) - */ - $.vakata.dnd._trigger("start", e); - } - else { return; } - } - - var d = false, w = false, - dh = false, wh = false, - dw = false, ww = false, - dt = false, dl = false, - ht = false, hl = false; - - vakata_dnd.scroll_t = 0; - vakata_dnd.scroll_l = 0; - vakata_dnd.scroll_e = false; - $($(e.target).parentsUntil("body").addBack().get().reverse()) - .filter(function () { - return (/^auto|scroll$/).test($(this).css("overflow")) && - (this.scrollHeight > this.offsetHeight || this.scrollWidth > this.offsetWidth); - }) - .each(function () { - var t = $(this), o = t.offset(); - if(this.scrollHeight > this.offsetHeight) { - if(o.top + t.height() - e.pageY < $.vakata.dnd.settings.scroll_proximity) { vakata_dnd.scroll_t = 1; } - if(e.pageY - o.top < $.vakata.dnd.settings.scroll_proximity) { vakata_dnd.scroll_t = -1; } - } - if(this.scrollWidth > this.offsetWidth) { - if(o.left + t.width() - e.pageX < $.vakata.dnd.settings.scroll_proximity) { vakata_dnd.scroll_l = 1; } - if(e.pageX - o.left < $.vakata.dnd.settings.scroll_proximity) { vakata_dnd.scroll_l = -1; } - } - if(vakata_dnd.scroll_t || vakata_dnd.scroll_l) { - vakata_dnd.scroll_e = $(this); - return false; - } - }); - - if(!vakata_dnd.scroll_e) { - d = $(document); w = $(window); - dh = d.height(); wh = w.height(); - dw = d.width(); ww = w.width(); - dt = d.scrollTop(); dl = d.scrollLeft(); - if(dh > wh && e.pageY - dt < $.vakata.dnd.settings.scroll_proximity) { vakata_dnd.scroll_t = -1; } - if(dh > wh && wh - (e.pageY - dt) < $.vakata.dnd.settings.scroll_proximity) { vakata_dnd.scroll_t = 1; } - if(dw > ww && e.pageX - dl < $.vakata.dnd.settings.scroll_proximity) { vakata_dnd.scroll_l = -1; } - if(dw > ww && ww - (e.pageX - dl) < $.vakata.dnd.settings.scroll_proximity) { vakata_dnd.scroll_l = 1; } - if(vakata_dnd.scroll_t || vakata_dnd.scroll_l) { - vakata_dnd.scroll_e = d; - } - } - if(vakata_dnd.scroll_e) { $.vakata.dnd._scroll(true); } - - if(vakata_dnd.helper) { - ht = parseInt(e.pageY + $.vakata.dnd.settings.helper_top, 10); - hl = parseInt(e.pageX + $.vakata.dnd.settings.helper_left, 10); - if(dh && ht + 25 > dh) { ht = dh - 50; } - if(dw && hl + vakata_dnd.helper_w > dw) { hl = dw - (vakata_dnd.helper_w + 2); } - vakata_dnd.helper.css({ - left : hl + "px", - top : ht + "px" - }); - } - /** - * triggered on the document when a drag is in progress - * @event - * @plugin dnd - * @name dnd_move.vakata - * @param {Mixed} data any data supplied with the call to $.vakata.dnd.start - * @param {DOM} element the DOM element being dragged - * @param {jQuery} helper the helper shown next to the mouse - * @param {Object} event the event that caused this to trigger (most likely mousemove) - */ - $.vakata.dnd._trigger("move", e); - return false; - }, - stop : function (e) { - if(e.type === "touchend" && e.originalEvent && e.originalEvent.changedTouches && e.originalEvent.changedTouches[0]) { - e.pageX = e.originalEvent.changedTouches[0].pageX; - e.pageY = e.originalEvent.changedTouches[0].pageY; - e.target = document.elementFromPoint(e.originalEvent.changedTouches[0].pageX - window.pageXOffset, e.originalEvent.changedTouches[0].pageY - window.pageYOffset); - } - if(vakata_dnd.is_drag) { - /** - * triggered on the document when a drag stops (the dragged element is dropped) - * @event - * @plugin dnd - * @name dnd_stop.vakata - * @param {Mixed} data any data supplied with the call to $.vakata.dnd.start - * @param {DOM} element the DOM element being dragged - * @param {jQuery} helper the helper shown next to the mouse - * @param {Object} event the event that caused the stop - */ - $.vakata.dnd._trigger("stop", e); - } - else { - if(e.type === "touchend" && e.target === vakata_dnd.target) { - var to = setTimeout(function () { $(e.target).click(); }, 100); - $(e.target).one('click', function() { if(to) { clearTimeout(to); } }); - } - } - $.vakata.dnd._clean(); - return false; - } - }; - }($)); - - // include the dnd plugin by default - // $.jstree.defaults.plugins.push("dnd"); - - -/** - * ### Search plugin - * - * Adds search functionality to jsTree. - */ - - /** - * stores all defaults for the search plugin - * @name $.jstree.defaults.search - * @plugin search - */ - $.jstree.defaults.search = { - /** - * a jQuery-like AJAX config, which jstree uses if a server should be queried for results. - * - * A `str` (which is the search string) parameter will be added with the request. The expected result is a JSON array with nodes that need to be opened so that matching nodes will be revealed. - * Leave this setting as `false` to not query the server. You can also set this to a function, which will be invoked in the instance's scope and receive 2 parameters - the search string and the callback to call with the array of nodes to load. - * @name $.jstree.defaults.search.ajax - * @plugin search - */ - ajax : false, - /** - * Indicates if the search should be fuzzy or not (should `chnd3` match `child node 3`). Default is `false`. - * @name $.jstree.defaults.search.fuzzy - * @plugin search - */ - fuzzy : false, - /** - * Indicates if the search should be case sensitive. Default is `false`. - * @name $.jstree.defaults.search.case_sensitive - * @plugin search - */ - case_sensitive : false, - /** - * Indicates if the tree should be filtered to show only matching nodes (keep in mind this can be a heavy on large trees in old browsers). Default is `false`. - * @name $.jstree.defaults.search.show_only_matches - * @plugin search - */ - show_only_matches : false, - /** - * Indicates if all nodes opened to reveal the search result, should be closed when the search is cleared or a new search is performed. Default is `true`. - * @name $.jstree.defaults.search.close_opened_onclear - * @plugin search - */ - close_opened_onclear : true, - /** - * Indicates if only leaf nodes should be included in search results. Default is `false`. - * @name $.jstree.defaults.search.search_leaves_only - * @plugin search - */ - search_leaves_only : false, - /** - * If set to a function it wil be called in the instance's scope with two arguments - search string and node (where node will be every node in the structure, so use with caution). - * If the function returns a truthy value the node will be considered a match (it might not be displayed if search_only_leaves is set to true and the node is not a leaf). Default is `false`. - * @name $.jstree.defaults.search.search_callback - * @plugin search - */ - search_callback : false - }; - - $.jstree.plugins.search = function (options, parent) { - this.bind = function () { - parent.bind.call(this); - - this._data.search.str = ""; - this._data.search.dom = $(); - this._data.search.res = []; - this._data.search.opn = []; - - this.element.on('before_open.jstree', $.proxy(function (e, data) { - var i, j, f, r = this._data.search.res, s = [], o = $(); - if(r && r.length) { - this._data.search.dom = $(this.element[0].querySelectorAll('#' + $.map(r, function (v) { return "0123456789".indexOf(v[0]) !== -1 ? '\\3' + v[0] + ' ' + v.substr(1).replace($.jstree.idregex,'\\$&') : v.replace($.jstree.idregex,'\\$&'); }).join(', #'))); - this._data.search.dom.children(".jstree-anchor").addClass('jstree-search'); - if(this.settings.search.show_only_matches && this._data.search.res.length) { - for(i = 0, j = r.length; i < j; i++) { - s = s.concat(this.get_node(r[i]).parents); - } - s = $.vakata.array_remove_item($.vakata.array_unique(s),'#'); - o = s.length ? $(this.element[0].querySelectorAll('#' + $.map(s, function (v) { return "0123456789".indexOf(v[0]) !== -1 ? '\\3' + v[0] + ' ' + v.substr(1).replace($.jstree.idregex,'\\$&') : v.replace($.jstree.idregex,'\\$&'); }).join(', #'))) : $(); - - this.element.find(".jstree-node").hide().filter('.jstree-last').filter(function() { return this.nextSibling; }).removeClass('jstree-last'); - o = o.add(this._data.search.dom); - o.parentsUntil(".jstree").addBack().show() - .filter(".jstree-children").each(function () { $(this).children(".jstree-node:visible").eq(-1).addClass("jstree-last"); }); - } - } - }, this)); - if(this.settings.search.show_only_matches) { - this.element - .on("search.jstree", function (e, data) { - if(data.nodes.length) { - $(this).find(".jstree-node").hide().filter('.jstree-last').filter(function() { return this.nextSibling; }).removeClass('jstree-last'); - data.nodes.parentsUntil(".jstree").addBack().show() - .filter(".jstree-children").each(function () { $(this).children(".jstree-node:visible").eq(-1).addClass("jstree-last"); }); - } - }) - .on("clear_search.jstree", function (e, data) { - if(data.nodes.length) { - $(this).find(".jstree-node").css("display","").filter('.jstree-last').filter(function() { return this.nextSibling; }).removeClass('jstree-last'); - } - }); - } - }; - /** - * used to search the tree nodes for a given string - * @name search(str [, skip_async]) - * @param {String} str the search string - * @param {Boolean} skip_async if set to true server will not be queried even if configured - * @plugin search - * @trigger search.jstree - */ - this.search = function (str, skip_async) { - if(str === false || $.trim(str.toString()) === "") { - return this.clear_search(); - } - str = str.toString(); - var s = this.settings.search, - a = s.ajax ? s.ajax : false, - f = null, - r = [], - p = [], i, j; - if(this._data.search.res.length) { - this.clear_search(); - } - if(!skip_async && a !== false) { - if($.isFunction(a)) { - return a.call(this, str, $.proxy(function (d) { - if(d && d.d) { d = d.d; } - this._load_nodes(!$.isArray(d) ? [] : $.vakata.array_unique(d), function () { - this.search(str, true); - }, true); - }, this)); - } - else { - a = $.extend({}, a); - if(!a.data) { a.data = {}; } - a.data.str = str; - return $.ajax(a) - .fail($.proxy(function () { - this._data.core.last_error = { 'error' : 'ajax', 'plugin' : 'search', 'id' : 'search_01', 'reason' : 'Could not load search parents', 'data' : JSON.stringify(a) }; - this.settings.core.error.call(this, this._data.core.last_error); - }, this)) - .done($.proxy(function (d) { - if(d && d.d) { d = d.d; } - this._load_nodes(!$.isArray(d) ? [] : $.vakata.array_unique(d), function () { - this.search(str, true); - }, true); - }, this)); - } - } - this._data.search.str = str; - this._data.search.dom = $(); - this._data.search.res = []; - this._data.search.opn = []; - - f = new $.vakata.search(str, true, { caseSensitive : s.case_sensitive, fuzzy : s.fuzzy }); - - $.each(this._model.data, function (i, v) { - if(v.text && ( (s.search_callback && s.search_callback.call(this, str, v)) || (!s.search_callback && f.search(v.text).isMatch) ) && (!s.search_leaves_only || (v.state.loaded && v.children.length === 0)) ) { - r.push(i); - p = p.concat(v.parents); - } - }); - if(r.length) { - p = $.vakata.array_unique(p); - this._search_open(p); - this._data.search.dom = $(this.element[0].querySelectorAll('#' + $.map(r, function (v) { return "0123456789".indexOf(v[0]) !== -1 ? '\\3' + v[0] + ' ' + v.substr(1).replace($.jstree.idregex,'\\$&') : v.replace($.jstree.idregex,'\\$&'); }).join(', #'))); - this._data.search.res = r; - this._data.search.dom.children(".jstree-anchor").addClass('jstree-search'); - } - /** - * triggered after search is complete - * @event - * @name search.jstree - * @param {jQuery} nodes a jQuery collection of matching nodes - * @param {String} str the search string - * @param {Array} res a collection of objects represeing the matching nodes - * @plugin search - */ - this.trigger('search', { nodes : this._data.search.dom, str : str, res : this._data.search.res }); - }; - /** - * used to clear the last search (removes classes and shows all nodes if filtering is on) - * @name clear_search() - * @plugin search - * @trigger clear_search.jstree - */ - this.clear_search = function () { - this._data.search.dom.children(".jstree-anchor").removeClass("jstree-search"); - if(this.settings.search.close_opened_onclear) { - this.close_node(this._data.search.opn, 0); - } - /** - * triggered after search is complete - * @event - * @name clear_search.jstree - * @param {jQuery} nodes a jQuery collection of matching nodes (the result from the last search) - * @param {String} str the search string (the last search string) - * @param {Array} res a collection of objects represeing the matching nodes (the result from the last search) - * @plugin search - */ - this.trigger('clear_search', { 'nodes' : this._data.search.dom, str : this._data.search.str, res : this._data.search.res }); - this._data.search.str = ""; - this._data.search.res = []; - this._data.search.opn = []; - this._data.search.dom = $(); - }; - /** - * opens nodes that need to be opened to reveal the search results. Used only internally. - * @private - * @name _search_open(d) - * @param {Array} d an array of node IDs - * @plugin search - */ - this._search_open = function (d) { - var t = this; - $.each(d.concat([]), function (i, v) { - if(v === "#") { return true; } - try { v = $('#' + v.replace($.jstree.idregex,'\\$&'), t.element); } catch(ignore) { } - if(v && v.length) { - if(t.is_closed(v)) { - t._data.search.opn.push(v[0].id); - t.open_node(v, function () { t._search_open(d); }, 0); - } - } - }); - }; - }; - - // helpers - (function ($) { - // from http://kiro.me/projects/fuse.html - $.vakata.search = function(pattern, txt, options) { - options = options || {}; - if(options.fuzzy !== false) { - options.fuzzy = true; - } - pattern = options.caseSensitive ? pattern : pattern.toLowerCase(); - var MATCH_LOCATION = options.location || 0, - MATCH_DISTANCE = options.distance || 100, - MATCH_THRESHOLD = options.threshold || 0.6, - patternLen = pattern.length, - matchmask, pattern_alphabet, match_bitapScore, search; - if(patternLen > 32) { - options.fuzzy = false; - } - if(options.fuzzy) { - matchmask = 1 << (patternLen - 1); - pattern_alphabet = (function () { - var mask = {}, - i = 0; - for (i = 0; i < patternLen; i++) { - mask[pattern.charAt(i)] = 0; - } - for (i = 0; i < patternLen; i++) { - mask[pattern.charAt(i)] |= 1 << (patternLen - i - 1); - } - return mask; - }()); - match_bitapScore = function (e, x) { - var accuracy = e / patternLen, - proximity = Math.abs(MATCH_LOCATION - x); - if(!MATCH_DISTANCE) { - return proximity ? 1.0 : accuracy; - } - return accuracy + (proximity / MATCH_DISTANCE); - }; - } - search = function (text) { - text = options.caseSensitive ? text : text.toLowerCase(); - if(pattern === text || text.indexOf(pattern) !== -1) { - return { - isMatch: true, - score: 0 - }; - } - if(!options.fuzzy) { - return { - isMatch: false, - score: 1 - }; - } - var i, j, - textLen = text.length, - scoreThreshold = MATCH_THRESHOLD, - bestLoc = text.indexOf(pattern, MATCH_LOCATION), - binMin, binMid, - binMax = patternLen + textLen, - lastRd, start, finish, rd, charMatch, - score = 1, - locations = []; - if (bestLoc !== -1) { - scoreThreshold = Math.min(match_bitapScore(0, bestLoc), scoreThreshold); - bestLoc = text.lastIndexOf(pattern, MATCH_LOCATION + patternLen); - if (bestLoc !== -1) { - scoreThreshold = Math.min(match_bitapScore(0, bestLoc), scoreThreshold); - } - } - bestLoc = -1; - for (i = 0; i < patternLen; i++) { - binMin = 0; - binMid = binMax; - while (binMin < binMid) { - if (match_bitapScore(i, MATCH_LOCATION + binMid) <= scoreThreshold) { - binMin = binMid; - } else { - binMax = binMid; - } - binMid = Math.floor((binMax - binMin) / 2 + binMin); - } - binMax = binMid; - start = Math.max(1, MATCH_LOCATION - binMid + 1); - finish = Math.min(MATCH_LOCATION + binMid, textLen) + patternLen; - rd = new Array(finish + 2); - rd[finish + 1] = (1 << i) - 1; - for (j = finish; j >= start; j--) { - charMatch = pattern_alphabet[text.charAt(j - 1)]; - if (i === 0) { - rd[j] = ((rd[j + 1] << 1) | 1) & charMatch; - } else { - rd[j] = ((rd[j + 1] << 1) | 1) & charMatch | (((lastRd[j + 1] | lastRd[j]) << 1) | 1) | lastRd[j + 1]; - } - if (rd[j] & matchmask) { - score = match_bitapScore(i, j - 1); - if (score <= scoreThreshold) { - scoreThreshold = score; - bestLoc = j - 1; - locations.push(bestLoc); - if (bestLoc > MATCH_LOCATION) { - start = Math.max(1, 2 * MATCH_LOCATION - bestLoc); - } else { - break; - } - } - } - } - if (match_bitapScore(i + 1, MATCH_LOCATION) > scoreThreshold) { - break; - } - lastRd = rd; - } - return { - isMatch: bestLoc >= 0, - score: score - }; - }; - return txt === true ? { 'search' : search } : search(txt); - }; - }($)); - - // include the search plugin by default - // $.jstree.defaults.plugins.push("search"); - -/** - * ### Sort plugin - * - * Autmatically sorts all siblings in the tree according to a sorting function. - */ - - /** - * the settings function used to sort the nodes. - * It is executed in the tree's context, accepts two nodes as arguments and should return `1` or `-1`. - * @name $.jstree.defaults.sort - * @plugin sort - */ - $.jstree.defaults.sort = function (a, b) { - //return this.get_type(a) === this.get_type(b) ? (this.get_text(a) > this.get_text(b) ? 1 : -1) : this.get_type(a) >= this.get_type(b); - return this.get_text(a) > this.get_text(b) ? 1 : -1; - }; - $.jstree.plugins.sort = function (options, parent) { - this.bind = function () { - parent.bind.call(this); - this.element - .on("model.jstree", $.proxy(function (e, data) { - this.sort(data.parent, true); - }, this)) - .on("rename_node.jstree create_node.jstree", $.proxy(function (e, data) { - this.sort(data.parent || data.node.parent, false); - this.redraw_node(data.parent || data.node.parent, true); - }, this)) - .on("move_node.jstree copy_node.jstree", $.proxy(function (e, data) { - this.sort(data.parent, false); - this.redraw_node(data.parent, true); - }, this)); - }; - /** - * used to sort a node's children - * @private - * @name sort(obj [, deep]) - * @param {mixed} obj the node - * @param {Boolean} deep if set to `true` nodes are sorted recursively. - * @plugin sort - * @trigger search.jstree - */ - this.sort = function (obj, deep) { - var i, j; - obj = this.get_node(obj); - if(obj && obj.children && obj.children.length) { - obj.children.sort($.proxy(this.settings.sort, this)); - if(deep) { - for(i = 0, j = obj.children_d.length; i < j; i++) { - this.sort(obj.children_d[i], false); - } - } - } - }; - }; - - // include the sort plugin by default - // $.jstree.defaults.plugins.push("sort"); - -/** - * ### State plugin - * - * Saves the state of the tree (selected nodes, opened nodes) on the user's computer using available options (localStorage, cookies, etc) - */ - - var to = false; - /** - * stores all defaults for the state plugin - * @name $.jstree.defaults.state - * @plugin state - */ - $.jstree.defaults.state = { - /** - * A string for the key to use when saving the current tree (change if using multiple trees in your project). Defaults to `jstree`. - * @name $.jstree.defaults.state.key - * @plugin state - */ - key : 'jstree', - /** - * A space separated list of events that trigger a state save. Defaults to `changed.jstree open_node.jstree close_node.jstree`. - * @name $.jstree.defaults.state.events - * @plugin state - */ - events : 'changed.jstree open_node.jstree close_node.jstree', - /** - * Time in milliseconds after which the state will expire. Defaults to 'false' meaning - no expire. - * @name $.jstree.defaults.state.ttl - * @plugin state - */ - ttl : false, - /** - * A function that will be executed prior to restoring state with one argument - the state object. Can be used to clear unwanted parts of the state. - * @name $.jstree.defaults.state.filter - * @plugin state - */ - filter : false - }; - $.jstree.plugins.state = function (options, parent) { - this.bind = function () { - parent.bind.call(this); - var bind = $.proxy(function () { - this.element.on(this.settings.state.events, $.proxy(function () { - if(to) { clearTimeout(to); } - to = setTimeout($.proxy(function () { this.save_state(); }, this), 100); - }, this)); - }, this); - this.element - .on("ready.jstree", $.proxy(function (e, data) { - this.element.one("restore_state.jstree", bind); - if(!this.restore_state()) { bind(); } - }, this)); - }; - /** - * save the state - * @name save_state() - * @plugin state - */ - this.save_state = function () { - var st = { 'state' : this.get_state(), 'ttl' : this.settings.state.ttl, 'sec' : +(new Date()) }; - $.vakata.storage.set(this.settings.state.key, JSON.stringify(st)); - }; - /** - * restore the state from the user's computer - * @name restore_state() - * @plugin state - */ - this.restore_state = function () { - var k = $.vakata.storage.get(this.settings.state.key); - if(!!k) { try { k = JSON.parse(k); } catch(ex) { return false; } } - if(!!k && k.ttl && k.sec && +(new Date()) - k.sec > k.ttl) { return false; } - if(!!k && k.state) { k = k.state; } - if(!!k && $.isFunction(this.settings.state.filter)) { k = this.settings.state.filter.call(this, k); } - if(!!k) { - this.element.one("set_state.jstree", function (e, data) { data.instance.trigger('restore_state', { 'state' : $.extend(true, {}, k) }); }); - this.set_state(k); - return true; - } - return false; - }; - /** - * clear the state on the user's computer - * @name clear_state() - * @plugin state - */ - this.clear_state = function () { - return $.vakata.storage.del(this.settings.state.key); - }; - }; - - (function ($, undefined) { - $.vakata.storage = { - // simply specifying the functions in FF throws an error - set : function (key, val) { return window.localStorage.setItem(key, val); }, - get : function (key) { return window.localStorage.getItem(key); }, - del : function (key) { return window.localStorage.removeItem(key); } - }; - }($)); - - // include the state plugin by default - // $.jstree.defaults.plugins.push("state"); - -/** - * ### Types plugin - * - * Makes it possible to add predefined types for groups of nodes, which make it possible to easily control nesting rules and icon for each group. - */ - - /** - * An object storing all types as key value pairs, where the key is the type name and the value is an object that could contain following keys (all optional). - * - * * `max_children` the maximum number of immediate children this node type can have. Do not specify or set to `-1` for unlimited. - * * `max_depth` the maximum number of nesting this node type can have. A value of `1` would mean that the node can have children, but no grandchildren. Do not specify or set to `-1` for unlimited. - * * `valid_children` an array of node type strings, that nodes of this type can have as children. Do not specify or set to `-1` for no limits. - * * `icon` a string - can be a path to an icon or a className, if using an image that is in the current directory use a `./` prefix, otherwise it will be detected as a class. Omit to use the default icon from your theme. - * - * There are two predefined types: - * - * * `#` represents the root of the tree, for example `max_children` would control the maximum number of root nodes. - * * `default` represents the default node - any settings here will be applied to all nodes that do not have a type specified. - * - * @name $.jstree.defaults.types - * @plugin types - */ - $.jstree.defaults.types = { - '#' : {}, - 'default' : {} - }; - - $.jstree.plugins.types = function (options, parent) { - this.init = function (el, options) { - var i, j; - if(options && options.types && options.types['default']) { - for(i in options.types) { - if(i !== "default" && i !== "#" && options.types.hasOwnProperty(i)) { - for(j in options.types['default']) { - if(options.types['default'].hasOwnProperty(j) && options.types[i][j] === undefined) { - options.types[i][j] = options.types['default'][j]; - } - } - } - } - } - parent.init.call(this, el, options); - this._model.data['#'].type = '#'; - }; - this.refresh = function (skip_loading, forget_state) { - parent.refresh.call(this, skip_loading, forget_state); - this._model.data['#'].type = '#'; - }; - this.bind = function () { - this.element - .on('model.jstree', $.proxy(function (e, data) { - var m = this._model.data, - dpc = data.nodes, - t = this.settings.types, - i, j, c = 'default'; - for(i = 0, j = dpc.length; i < j; i++) { - c = 'default'; - if(m[dpc[i]].original && m[dpc[i]].original.type && t[m[dpc[i]].original.type]) { - c = m[dpc[i]].original.type; - } - if(m[dpc[i]].data && m[dpc[i]].data.jstree && m[dpc[i]].data.jstree.type && t[m[dpc[i]].data.jstree.type]) { - c = m[dpc[i]].data.jstree.type; - } - m[dpc[i]].type = c; - if(m[dpc[i]].icon === true && t[c].icon !== undefined) { - m[dpc[i]].icon = t[c].icon; - } - } - m['#'].type = '#'; - }, this)); - parent.bind.call(this); - }; - this.get_json = function (obj, options, flat) { - var i, j, - m = this._model.data, - opt = options ? $.extend(true, {}, options, {no_id:false}) : {}, - tmp = parent.get_json.call(this, obj, opt, flat); - if(tmp === false) { return false; } - if($.isArray(tmp)) { - for(i = 0, j = tmp.length; i < j; i++) { - tmp[i].type = tmp[i].id && m[tmp[i].id] && m[tmp[i].id].type ? m[tmp[i].id].type : "default"; - if(options && options.no_id) { - delete tmp[i].id; - if(tmp[i].li_attr && tmp[i].li_attr.id) { - delete tmp[i].li_attr.id; - } - } - } - } - else { - tmp.type = tmp.id && m[tmp.id] && m[tmp.id].type ? m[tmp.id].type : "default"; - if(options && options.no_id) { - tmp = this._delete_ids(tmp); - } - } - return tmp; - }; - this._delete_ids = function (tmp) { - if($.isArray(tmp)) { - for(var i = 0, j = tmp.length; i < j; i++) { - tmp[i] = this._delete_ids(tmp[i]); - } - return tmp; - } - delete tmp.id; - if(tmp.li_attr && tmp.li_attr.id) { - delete tmp.li_attr.id; - } - if(tmp.children && $.isArray(tmp.children)) { - tmp.children = this._delete_ids(tmp.children); - } - return tmp; - }; - this.check = function (chk, obj, par, pos, more) { - if(parent.check.call(this, chk, obj, par, pos, more) === false) { return false; } - obj = obj && obj.id ? obj : this.get_node(obj); - par = par && par.id ? par : this.get_node(par); - var m = obj && obj.id ? $.jstree.reference(obj.id) : null, tmp, d, i, j; - m = m && m._model && m._model.data ? m._model.data : null; - switch(chk) { - case "create_node": - case "move_node": - case "copy_node": - if(chk !== 'move_node' || $.inArray(obj.id, par.children) === -1) { - tmp = this.get_rules(par); - if(tmp.max_children !== undefined && tmp.max_children !== -1 && tmp.max_children === par.children.length) { - this._data.core.last_error = { 'error' : 'check', 'plugin' : 'types', 'id' : 'types_01', 'reason' : 'max_children prevents function: ' + chk, 'data' : JSON.stringify({ 'chk' : chk, 'pos' : pos, 'obj' : obj && obj.id ? obj.id : false, 'par' : par && par.id ? par.id : false }) }; - return false; - } - if(tmp.valid_children !== undefined && tmp.valid_children !== -1 && $.inArray(obj.type, tmp.valid_children) === -1) { - this._data.core.last_error = { 'error' : 'check', 'plugin' : 'types', 'id' : 'types_02', 'reason' : 'valid_children prevents function: ' + chk, 'data' : JSON.stringify({ 'chk' : chk, 'pos' : pos, 'obj' : obj && obj.id ? obj.id : false, 'par' : par && par.id ? par.id : false }) }; - return false; - } - if(m && obj.children_d && obj.parents) { - d = 0; - for(i = 0, j = obj.children_d.length; i < j; i++) { - d = Math.max(d, m[obj.children_d[i]].parents.length); - } - d = d - obj.parents.length + 1; - } - if(d <= 0 || d === undefined) { d = 1; } - do { - if(tmp.max_depth !== undefined && tmp.max_depth !== -1 && tmp.max_depth < d) { - this._data.core.last_error = { 'error' : 'check', 'plugin' : 'types', 'id' : 'types_03', 'reason' : 'max_depth prevents function: ' + chk, 'data' : JSON.stringify({ 'chk' : chk, 'pos' : pos, 'obj' : obj && obj.id ? obj.id : false, 'par' : par && par.id ? par.id : false }) }; - return false; - } - par = this.get_node(par.parent); - tmp = this.get_rules(par); - d++; - } while(par); - } - break; - } - return true; - }; - /** - * used to retrieve the type settings object for a node - * @name get_rules(obj) - * @param {mixed} obj the node to find the rules for - * @return {Object} - * @plugin types - */ - this.get_rules = function (obj) { - obj = this.get_node(obj); - if(!obj) { return false; } - var tmp = this.get_type(obj, true); - if(tmp.max_depth === undefined) { tmp.max_depth = -1; } - if(tmp.max_children === undefined) { tmp.max_children = -1; } - if(tmp.valid_children === undefined) { tmp.valid_children = -1; } - return tmp; - }; - /** - * used to retrieve the type string or settings object for a node - * @name get_type(obj [, rules]) - * @param {mixed} obj the node to find the rules for - * @param {Boolean} rules if set to `true` instead of a string the settings object will be returned - * @return {String|Object} - * @plugin types - */ - this.get_type = function (obj, rules) { - obj = this.get_node(obj); - return (!obj) ? false : ( rules ? $.extend({ 'type' : obj.type }, this.settings.types[obj.type]) : obj.type); - }; - /** - * used to change a node's type - * @name set_type(obj, type) - * @param {mixed} obj the node to change - * @param {String} type the new type - * @plugin types - */ - this.set_type = function (obj, type) { - var t, t1, t2, old_type, old_icon; - if($.isArray(obj)) { - obj = obj.slice(); - for(t1 = 0, t2 = obj.length; t1 < t2; t1++) { - this.set_type(obj[t1], type); - } - return true; - } - t = this.settings.types; - obj = this.get_node(obj); - if(!t[type] || !obj) { return false; } - old_type = obj.type; - old_icon = this.get_icon(obj); - obj.type = type; - if(old_icon === true || (t[old_type] && t[old_type].icon && old_icon === t[old_type].icon)) { - this.set_icon(obj, t[type].icon !== undefined ? t[type].icon : true); - } - return true; - }; - }; - // include the types plugin by default - // $.jstree.defaults.plugins.push("types"); - -/** - * ### Unique plugin - * - * Enforces that no nodes with the same name can coexist as siblings. - */ - - /** - * stores all defaults for the unique plugin - * @name $.jstree.defaults.unique - * @plugin unique - */ - $.jstree.defaults.unique = { - /** - * Indicates if the comparison should be case sensitive. Default is `false`. - * @name $.jstree.defaults.unique.case_sensitive - * @plugin unique - */ - case_sensitive : false, - /** - * A callback executed in the instance's scope when a new node is created and the name is already taken, the two arguments are the conflicting name and the counter. The default will produce results like `New node (2)`. - * @name $.jstree.defaults.unique.duplicate - * @plugin unique - */ - duplicate : function (name, counter) { - return name + ' (' + counter + ')'; - } - }; - - $.jstree.plugins.unique = function (options, parent) { - this.check = function (chk, obj, par, pos, more) { - if(parent.check.call(this, chk, obj, par, pos, more) === false) { return false; } - obj = obj && obj.id ? obj : this.get_node(obj); - par = par && par.id ? par : this.get_node(par); - if(!par || !par.children) { return true; } - var n = chk === "rename_node" ? pos : obj.text, - c = [], - s = this.settings.unique.case_sensitive, - m = this._model.data, i, j; - for(i = 0, j = par.children.length; i < j; i++) { - c.push(s ? m[par.children[i]].text : m[par.children[i]].text.toLowerCase()); - } - if(!s) { n = n.toLowerCase(); } - switch(chk) { - case "delete_node": - return true; - case "rename_node": - i = ($.inArray(n, c) === -1 || (obj.text && obj.text[ s ? 'toString' : 'toLowerCase']() === n)); - if(!i) { - this._data.core.last_error = { 'error' : 'check', 'plugin' : 'unique', 'id' : 'unique_01', 'reason' : 'Child with name ' + n + ' already exists. Preventing: ' + chk, 'data' : JSON.stringify({ 'chk' : chk, 'pos' : pos, 'obj' : obj && obj.id ? obj.id : false, 'par' : par && par.id ? par.id : false }) }; - } - return i; - case "create_node": - i = ($.inArray(n, c) === -1); - if(!i) { - this._data.core.last_error = { 'error' : 'check', 'plugin' : 'unique', 'id' : 'unique_04', 'reason' : 'Child with name ' + n + ' already exists. Preventing: ' + chk, 'data' : JSON.stringify({ 'chk' : chk, 'pos' : pos, 'obj' : obj && obj.id ? obj.id : false, 'par' : par && par.id ? par.id : false }) }; - } - return i; - case "copy_node": - i = ($.inArray(n, c) === -1); - if(!i) { - this._data.core.last_error = { 'error' : 'check', 'plugin' : 'unique', 'id' : 'unique_02', 'reason' : 'Child with name ' + n + ' already exists. Preventing: ' + chk, 'data' : JSON.stringify({ 'chk' : chk, 'pos' : pos, 'obj' : obj && obj.id ? obj.id : false, 'par' : par && par.id ? par.id : false }) }; - } - return i; - case "move_node": - i = (obj.parent === par.id || $.inArray(n, c) === -1); - if(!i) { - this._data.core.last_error = { 'error' : 'check', 'plugin' : 'unique', 'id' : 'unique_03', 'reason' : 'Child with name ' + n + ' already exists. Preventing: ' + chk, 'data' : JSON.stringify({ 'chk' : chk, 'pos' : pos, 'obj' : obj && obj.id ? obj.id : false, 'par' : par && par.id ? par.id : false }) }; - } - return i; - } - return true; - }; - this.create_node = function (par, node, pos, callback, is_loaded) { - if(!node || node.text === undefined) { - if(par === null) { - par = "#"; - } - par = this.get_node(par); - if(!par) { - return parent.create_node.call(this, par, node, pos, callback, is_loaded); - } - pos = pos === undefined ? "last" : pos; - if(!pos.toString().match(/^(before|after)$/) && !is_loaded && !this.is_loaded(par)) { - return parent.create_node.call(this, par, node, pos, callback, is_loaded); - } - if(!node) { node = {}; } - var tmp, n, dpc, i, j, m = this._model.data, s = this.settings.unique.case_sensitive, cb = this.settings.unique.duplicate; - n = tmp = this.get_string('New node'); - dpc = []; - for(i = 0, j = par.children.length; i < j; i++) { - dpc.push(s ? m[par.children[i]].text : m[par.children[i]].text.toLowerCase()); - } - i = 1; - while($.inArray(s ? n : n.toLowerCase(), dpc) !== -1) { - n = cb.call(this, tmp, (++i)).toString(); - } - node.text = n; - } - return parent.create_node.call(this, par, node, pos, callback, is_loaded); - }; - }; - - // include the unique plugin by default - // $.jstree.defaults.plugins.push("unique"); - - -/** - * ### Wholerow plugin - * - * Makes each node appear block level. Making selection easier. May cause slow down for large trees in old browsers. - */ - - var div = document.createElement('DIV'); - div.setAttribute('unselectable','on'); - div.className = 'jstree-wholerow'; - div.innerHTML = ' '; - $.jstree.plugins.wholerow = function (options, parent) { - this.bind = function () { - parent.bind.call(this); - - this.element - .on('ready.jstree set_state.jstree', $.proxy(function () { - this.hide_dots(); - }, this)) - .on("init.jstree loading.jstree ready.jstree", $.proxy(function () { - //div.style.height = this._data.core.li_height + 'px'; - this.get_container_ul().addClass('jstree-wholerow-ul'); - }, this)) - .on("deselect_all.jstree", $.proxy(function (e, data) { - this.element.find('.jstree-wholerow-clicked').removeClass('jstree-wholerow-clicked'); - }, this)) - .on("changed.jstree", $.proxy(function (e, data) { - this.element.find('.jstree-wholerow-clicked').removeClass('jstree-wholerow-clicked'); - var tmp = false, i, j; - for(i = 0, j = data.selected.length; i < j; i++) { - tmp = this.get_node(data.selected[i], true); - if(tmp && tmp.length) { - tmp.children('.jstree-wholerow').addClass('jstree-wholerow-clicked'); - } - } - }, this)) - .on("open_node.jstree", $.proxy(function (e, data) { - this.get_node(data.node, true).find('.jstree-clicked').parent().children('.jstree-wholerow').addClass('jstree-wholerow-clicked'); - }, this)) - .on("hover_node.jstree dehover_node.jstree", $.proxy(function (e, data) { - this.get_node(data.node, true).children('.jstree-wholerow')[e.type === "hover_node"?"addClass":"removeClass"]('jstree-wholerow-hovered'); - }, this)) - .on("contextmenu.jstree", ".jstree-wholerow", $.proxy(function (e) { - e.preventDefault(); - var tmp = $.Event('contextmenu', { metaKey : e.metaKey, ctrlKey : e.ctrlKey, altKey : e.altKey, shiftKey : e.shiftKey, pageX : e.pageX, pageY : e.pageY }); - $(e.currentTarget).closest(".jstree-node").children(".jstree-anchor:eq(0)").trigger(tmp); - }, this)) - .on("click.jstree", ".jstree-wholerow", function (e) { - e.stopImmediatePropagation(); - var tmp = $.Event('click', { metaKey : e.metaKey, ctrlKey : e.ctrlKey, altKey : e.altKey, shiftKey : e.shiftKey }); - $(e.currentTarget).closest(".jstree-node").children(".jstree-anchor:eq(0)").trigger(tmp).focus(); - }) - .on("click.jstree", ".jstree-leaf > .jstree-ocl", $.proxy(function (e) { - e.stopImmediatePropagation(); - var tmp = $.Event('click', { metaKey : e.metaKey, ctrlKey : e.ctrlKey, altKey : e.altKey, shiftKey : e.shiftKey }); - $(e.currentTarget).closest(".jstree-node").children(".jstree-anchor:eq(0)").trigger(tmp).focus(); - }, this)) - .on("mouseover.jstree", ".jstree-wholerow, .jstree-icon", $.proxy(function (e) { - e.stopImmediatePropagation(); - this.hover_node(e.currentTarget); - return false; - }, this)) - .on("mouseleave.jstree", ".jstree-node", $.proxy(function (e) { - this.dehover_node(e.currentTarget); - }, this)); - }; - this.teardown = function () { - if(this.settings.wholerow) { - this.element.find(".jstree-wholerow").remove(); - } - parent.teardown.call(this); - }; - this.redraw_node = function(obj, deep, callback) { - obj = parent.redraw_node.call(this, obj, deep, callback); - if(obj) { - var tmp = div.cloneNode(true); - //tmp.style.height = this._data.core.li_height + 'px'; - if($.inArray(obj.id, this._data.core.selected) !== -1) { tmp.className += ' jstree-wholerow-clicked'; } - obj.insertBefore(tmp, obj.childNodes[0]); - } - return obj; - }; - }; - // include the wholerow plugin by default - // $.jstree.defaults.plugins.push("wholerow"); - -})); +return this.trigger("close_all",{node:b})}f=this.is_open(b)?f.find(".jstree-open").addBack():f.find(".jstree-open"),a(f.get().reverse()).each(function(){g.close_node(this,c||0)}),this.trigger("close_all",{node:b})},is_disabled:function(a){return a=this.get_node(a),a&&a.state&&a.state.disabled},enable_node:function(b){var c,d;if(a.isArray(b)){for(b=b.slice(),c=0,d=b.length;d>c;c++)this.enable_node(b[c]);return!0}return b=this.get_node(b),b&&"#"!==b.id?(b.state.disabled=!1,this.get_node(b,!0).children(".jstree-anchor").removeClass("jstree-disabled"),void this.trigger("enable_node",{node:b})):!1},disable_node:function(b){var c,d;if(a.isArray(b)){for(b=b.slice(),c=0,d=b.length;d>c;c++)this.disable_node(b[c]);return!0}return b=this.get_node(b),b&&"#"!==b.id?(b.state.disabled=!0,this.get_node(b,!0).children(".jstree-anchor").addClass("jstree-disabled"),void this.trigger("disable_node",{node:b})):!1},activate_node:function(a,c){if(this.is_disabled(a))return!1;if(this._data.core.last_clicked=this._data.core.last_clicked&&this._data.core.last_clicked.id!==b?this.get_node(this._data.core.last_clicked.id):null,this._data.core.last_clicked&&!this._data.core.last_clicked.state.selected&&(this._data.core.last_clicked=null),!this._data.core.last_clicked&&this._data.core.selected.length&&(this._data.core.last_clicked=this.get_node(this._data.core.selected[this._data.core.selected.length-1])),this.settings.core.multiple&&(c.metaKey||c.ctrlKey||c.shiftKey)&&(!c.shiftKey||this._data.core.last_clicked&&this.get_parent(a)&&this.get_parent(a)===this._data.core.last_clicked.parent))if(c.shiftKey){var d,e,f=this.get_node(a).id,g=this._data.core.last_clicked.id,h=this.get_node(this._data.core.last_clicked.parent).children,i=!1;for(d=0,e=h.length;e>d;d+=1)h[d]===f&&(i=!i),h[d]===g&&(i=!i),i||h[d]===f||h[d]===g?this.select_node(h[d],!1,!1,c):this.deselect_node(h[d],!1,c)}else this.is_selected(a)?this.deselect_node(a,!1,c):this.select_node(a,!1,!1,c);else!this.settings.core.multiple&&(c.metaKey||c.ctrlKey||c.shiftKey)&&this.is_selected(a)?this.deselect_node(a,!1,c):(this.deselect_all(!0),this.select_node(a,!1,!1,c),this._data.core.last_clicked=this.get_node(a));this.trigger("activate_node",{node:this.get_node(a)})},hover_node:function(a){if(a=this.get_node(a,!0),!a||!a.length||a.children(".jstree-hovered").length)return!1;var b=this.element.find(".jstree-hovered"),c=this.element;b&&b.length&&this.dehover_node(b),a.children(".jstree-anchor").addClass("jstree-hovered"),this.trigger("hover_node",{node:this.get_node(a)}),setTimeout(function(){c.attr("aria-activedescendant",a[0].id),a.attr("aria-selected",!0)},0)},dehover_node:function(a){return a=this.get_node(a,!0),a&&a.length&&a.children(".jstree-hovered").length?(a.attr("aria-selected",!1).children(".jstree-anchor").removeClass("jstree-hovered"),void this.trigger("dehover_node",{node:this.get_node(a)})):!1},select_node:function(b,c,d,e){var f,g,h;if(a.isArray(b)){for(b=b.slice(),g=0,h=b.length;h>g;g++)this.select_node(b[g],c,d,e);return!0}return b=this.get_node(b),b&&"#"!==b.id?(f=this.get_node(b,!0),void(b.state.selected||(b.state.selected=!0,this._data.core.selected.push(b.id),d||(f=this._open_to(b)),f&&f.length&&f.children(".jstree-anchor").addClass("jstree-clicked"),this.trigger("select_node",{node:b,selected:this._data.core.selected,event:e}),c||this.trigger("changed",{action:"select_node",node:b,selected:this._data.core.selected,event:e})))):!1},deselect_node:function(b,c,d){var e,f,g;if(a.isArray(b)){for(b=b.slice(),e=0,f=b.length;f>e;e++)this.deselect_node(b[e],c,d);return!0}return b=this.get_node(b),b&&"#"!==b.id?(g=this.get_node(b,!0),void(b.state.selected&&(b.state.selected=!1,this._data.core.selected=a.vakata.array_remove_item(this._data.core.selected,b.id),g.length&&g.children(".jstree-anchor").removeClass("jstree-clicked"),this.trigger("deselect_node",{node:b,selected:this._data.core.selected,event:d}),c||this.trigger("changed",{action:"deselect_node",node:b,selected:this._data.core.selected,event:d})))):!1},select_all:function(a){var b,c,d=this._data.core.selected.concat([]);for(this._data.core.selected=this._model.data["#"].children_d.concat(),b=0,c=this._data.core.selected.length;c>b;b++)this._model.data[this._data.core.selected[b]]&&(this._model.data[this._data.core.selected[b]].state.selected=!0);this.redraw(!0),this.trigger("select_all",{selected:this._data.core.selected}),a||this.trigger("changed",{action:"select_all",selected:this._data.core.selected,old_selection:d})},deselect_all:function(a){var b,c,d=this._data.core.selected.concat([]);for(b=0,c=this._data.core.selected.length;c>b;b++)this._model.data[this._data.core.selected[b]]&&(this._model.data[this._data.core.selected[b]].state.selected=!1);this._data.core.selected=[],this.element.find(".jstree-clicked").removeClass("jstree-clicked"),this.trigger("deselect_all",{selected:this._data.core.selected,node:d}),a||this.trigger("changed",{action:"deselect_all",selected:this._data.core.selected,old_selection:d})},is_selected:function(a){return a=this.get_node(a),a&&"#"!==a.id?a.state.selected:!1},get_selected:function(b){return b?a.map(this._data.core.selected,a.proxy(function(a){return this.get_node(a)},this)):this._data.core.selected.slice()},get_top_selected:function(b){var c,d,e,f,g=this.get_selected(!0),h={};for(c=0,d=g.length;d>c;c++)h[g[c].id]=g[c];for(c=0,d=g.length;d>c;c++)for(e=0,f=g[c].children_d.length;f>e;e++)h[g[c].children_d[e]]&&delete h[g[c].children_d[e]];g=[];for(c in h)h.hasOwnProperty(c)&&g.push(c);return b?a.map(g,a.proxy(function(a){return this.get_node(a)},this)):g},get_bottom_selected:function(b){var c,d,e=this.get_selected(!0),f=[];for(c=0,d=e.length;d>c;c++)e[c].children.length||f.push(e[c].id);return b?a.map(f,a.proxy(function(a){return this.get_node(a)},this)):f},get_state:function(){var a,b={core:{open:[],scroll:{left:this.element.scrollLeft(),top:this.element.scrollTop()},selected:[]}};for(a in this._model.data)this._model.data.hasOwnProperty(a)&&"#"!==a&&(this._model.data[a].state.opened&&b.core.open.push(a),this._model.data[a].state.selected&&b.core.selected.push(a));return b},set_state:function(c,d){if(c){if(c.core){var e,f,g,h;if(c.core.open)return a.isArray(c.core.open)?(e=!0,f=!1,g=this,a.each(c.core.open.concat([]),function(b,h){f=g.get_node(h),f&&(g.is_loaded(h)?(g.is_closed(h)&&g.open_node(h,!1,0),c&&c.core&&c.core.open&&a.vakata.array_remove_item(c.core.open,h)):(g.is_loading(h)||g.open_node(h,a.proxy(function(b,e){!e&&c&&c.core&&c.core.open&&a.vakata.array_remove_item(c.core.open,b.id),this.set_state(c,d)},g),0),e=!1))}),e&&(delete c.core.open,this.set_state(c,d)),!1):(delete c.core.open,this.set_state(c,d),!1);if(c.core.scroll)return c.core.scroll&&c.core.scroll.left!==b&&this.element.scrollLeft(c.core.scroll.left),c.core.scroll&&c.core.scroll.top!==b&&this.element.scrollTop(c.core.scroll.top),delete c.core.scroll,this.set_state(c,d),!1;if(c.core.selected)return h=this,this.deselect_all(),a.each(c.core.selected,function(a,b){h.select_node(b)}),delete c.core.selected,this.set_state(c,d),!1;if(a.isEmptyObject(c.core))return delete c.core,this.set_state(c,d),!1}return a.isEmptyObject(c)?(c=null,d&&d.call(this),this.trigger("set_state"),!1):!0}return!1},refresh:function(b,c){this._data.core.state=c===!0?{}:this.get_state(),c&&a.isFunction(c)&&(this._data.core.state=c.call(this,this._data.core.state)),this._cnt=0,this._model.data={"#":{id:"#",parent:null,parents:[],children:[],children_d:[],state:{loaded:!1}}};var d=this.get_container_ul()[0].className;b||this.element.html(""),this.load_node("#",function(b,c){c&&(this.get_container_ul()[0].className=d,this.set_state(a.extend(!0,{},this._data.core.state),function(){this.trigger("refresh")})),this._data.core.state=null})},refresh_node:function(b){if(b=this.get_node(b),!b||"#"===b.id)return!1;{var c=[],d=[];this._data.core.selected.concat([])}d.push(b.id),b.state.opened===!0&&c.push(b.id),this.get_node(b,!0).find(".jstree-open").each(function(){c.push(this.id)}),this._load_nodes(d,a.proxy(function(a){this.open_node(c,!1,0),this.select_node(this._data.core.selected),this.trigger("refresh_node",{node:b,nodes:a})},this))},set_id:function(b,c){if(b=this.get_node(b),!b||"#"===b.id)return!1;var d,e,f=this._model.data;for(c=c.toString(),f[b.parent].children[a.inArray(b.id,f[b.parent].children)]=c,d=0,e=b.parents.length;e>d;d++)f[b.parents[d]].children_d[a.inArray(b.id,f[b.parents[d]].children_d)]=c;for(d=0,e=b.children.length;e>d;d++)f[b.children[d]].parent=c;for(d=0,e=b.children_d.length;e>d;d++)f[b.children_d[d]].parents[a.inArray(b.id,f[b.children_d[d]].parents)]=c;return d=a.inArray(b.id,this._data.core.selected),-1!==d&&(this._data.core.selected[d]=c),d=this.get_node(b.id,!0),d&&d.attr("id",c),delete f[b.id],b.id=c,f[c]=b,!0},get_text:function(a){return a=this.get_node(a),a&&"#"!==a.id?a.text:!1},set_text:function(b,c){var d,e;if(a.isArray(b)){for(b=b.slice(),d=0,e=b.length;e>d;d++)this.set_text(b[d],c);return!0}return b=this.get_node(b),b&&"#"!==b.id?(b.text=c,this.get_node(b,!0).length&&this.redraw_node(b.id),this.trigger("set_text",{obj:b,text:c}),!0):!1},get_json:function(a,b,c){if(a=this.get_node(a||"#"),!a)return!1;b&&b.flat&&!c&&(c=[]);var d,e,f={id:a.id,text:a.text,icon:this.get_icon(a),li_attr:a.li_attr,a_attr:a.a_attr,state:{},data:b&&b.no_data?!1:a.data};if(b&&b.flat?f.parent=a.parent:f.children=[],!b||!b.no_state)for(d in a.state)a.state.hasOwnProperty(d)&&(f.state[d]=a.state[d]);if(b&&b.no_id&&(delete f.id,f.li_attr&&f.li_attr.id&&delete f.li_attr.id),b&&b.flat&&"#"!==a.id&&c.push(f),!b||!b.no_children)for(d=0,e=a.children.length;e>d;d++)b&&b.flat?this.get_json(a.children[d],b,c):f.children.push(this.get_json(a.children[d],b));return b&&b.flat?c:"#"===a.id?f.children:f},create_node:function(c,d,e,f,g){if(null===c&&(c="#"),c=this.get_node(c),!c)return!1;if(e=e===b?"last":e,!e.toString().match(/^(before|after)$/)&&!g&&!this.is_loaded(c))return this.load_node(c,function(){this.create_node(c,d,e,f,!0)});d||(d={text:this.get_string("New node")}),d.text===b&&(d.text=this.get_string("New node"));var h,i,j,k;switch("#"===c.id&&("before"===e&&(e="first"),"after"===e&&(e="last")),e){case"before":h=this.get_node(c.parent),e=a.inArray(c.id,h.children),c=h;break;case"after":h=this.get_node(c.parent),e=a.inArray(c.id,h.children)+1,c=h;break;case"inside":case"first":e=0;break;case"last":e=c.children.length;break;default:e||(e=0)}if(e>c.children.length&&(e=c.children.length),d.id||(d.id=!0),!this.check("create_node",d,c,e))return this.settings.core.error.call(this,this._data.core.last_error),!1;if(d.id===!0&&delete d.id,d=this._parse_model_from_json(d,c.id,c.parents.concat()),!d)return!1;for(h=this.get_node(d),i=[],i.push(d),i=i.concat(h.children_d),this.trigger("model",{nodes:i,parent:c.id}),c.children_d=c.children_d.concat(i),j=0,k=c.parents.length;k>j;j++)this._model.data[c.parents[j]].children_d=this._model.data[c.parents[j]].children_d.concat(i);for(d=h,h=[],j=0,k=c.children.length;k>j;j++)h[j>=e?j+1:j]=c.children[j];return h[e]=d.id,c.children=h,this.redraw_node(c,!0),f&&f.call(this,this.get_node(d)),this.trigger("create_node",{node:this.get_node(d),parent:c.id,position:e}),d.id},rename_node:function(b,c){var d,e,f;if(a.isArray(b)){for(b=b.slice(),d=0,e=b.length;e>d;d++)this.rename_node(b[d],c);return!0}return b=this.get_node(b),b&&"#"!==b.id?(f=b.text,this.check("rename_node",b,this.get_parent(b),c)?(this.set_text(b,c),this.trigger("rename_node",{node:b,text:c,old:f}),!0):(this.settings.core.error.call(this,this._data.core.last_error),!1)):!1},delete_node:function(b){var c,d,e,f,g,h,i,j,k,l;if(a.isArray(b)){for(b=b.slice(),c=0,d=b.length;d>c;c++)this.delete_node(b[c]);return!0}if(b=this.get_node(b),!b||"#"===b.id)return!1;if(e=this.get_node(b.parent),f=a.inArray(b.id,e.children),l=!1,!this.check("delete_node",b,e,f))return this.settings.core.error.call(this,this._data.core.last_error),!1;for(-1!==f&&(e.children=a.vakata.array_remove(e.children,f)),g=b.children_d.concat([]),g.push(b.id),j=0,k=g.length;k>j;j++){for(h=0,i=b.parents.length;i>h;h++)f=a.inArray(g[j],this._model.data[b.parents[h]].children_d),-1!==f&&(this._model.data[b.parents[h]].children_d=a.vakata.array_remove(this._model.data[b.parents[h]].children_d,f));this._model.data[g[j]].state.selected&&(l=!0,f=a.inArray(g[j],this._data.core.selected),-1!==f&&(this._data.core.selected=a.vakata.array_remove(this._data.core.selected,f)))}for(this.trigger("delete_node",{node:b,parent:e.id}),l&&this.trigger("changed",{action:"delete_node",node:b,selected:this._data.core.selected,parent:e.id}),j=0,k=g.length;k>j;j++)delete this._model.data[g[j]];return this.redraw_node(e,!0),!0},check:function(b,c,d,e,f){c=c&&c.id?c:this.get_node(c),d=d&&d.id?d:this.get_node(d);var g=b.match(/^move_node|copy_node|create_node$/i)?d:c,h=this.settings.core.check_callback;return"move_node"!==b&&"copy_node"!==b||f&&f.is_multi||c.id!==d.id&&a.inArray(c.id,d.children)!==e&&-1===a.inArray(d.id,c.children_d)?(g&&g.data&&(g=g.data),g&&g.functions&&(g.functions[b]===!1||g.functions[b]===!0)?(g.functions[b]===!1&&(this._data.core.last_error={error:"check",plugin:"core",id:"core_02",reason:"Node data prevents function: "+b,data:JSON.stringify({chk:b,pos:e,obj:c&&c.id?c.id:!1,par:d&&d.id?d.id:!1})}),g.functions[b]):h===!1||a.isFunction(h)&&h.call(this,b,c,d,e,f)===!1||h&&h[b]===!1?(this._data.core.last_error={error:"check",plugin:"core",id:"core_03",reason:"User config for core.check_callback prevents function: "+b,data:JSON.stringify({chk:b,pos:e,obj:c&&c.id?c.id:!1,par:d&&d.id?d.id:!1})},!1):!0):(this._data.core.last_error={error:"check",plugin:"core",id:"core_01",reason:"Moving parent inside child",data:JSON.stringify({chk:b,pos:e,obj:c&&c.id?c.id:!1,par:d&&d.id?d.id:!1})},!1)},last_error:function(){return this._data.core.last_error},move_node:function(c,d,e,f,g){var h,i,j,k,l,m,n,o,p,q,r,s,t,u;if(d=this.get_node(d),e=e===b?0:e,!d)return!1;if(!e.toString().match(/^(before|after)$/)&&!g&&!this.is_loaded(d))return this.load_node(d,function(){this.move_node(c,d,e,f,!0)});if(a.isArray(c)){for(c=c.reverse().slice(),h=0,i=c.length;i>h;h++)this.move_node(c[h],d,e,f,g);return!0}if(c=c&&c.id?c:this.get_node(c),!c||"#"===c.id)return!1;if(j=(c.parent||"#").toString(),l=e.toString().match(/^(before|after)$/)&&"#"!==d.id?this.get_node(d.parent):d,m=c.instance?c.instance:this._model.data[c.id]?this:a.jstree.reference(c.id),n=!m||!m._id||this._id!==m._id,k=m&&m._id&&j&&m._model.data[j]&&m._model.data[j].children?a.inArray(c.id,m._model.data[j].children):-1,n)return this.copy_node(c,d,e,f,g)?(m&&m.delete_node(c),!0):!1;switch("#"===l.id&&("before"===e&&(e="first"),"after"===e&&(e="last")),e){case"before":e=a.inArray(d.id,l.children);break;case"after":e=a.inArray(d.id,l.children)+1;break;case"inside":case"first":e=0;break;case"last":e=l.children.length;break;default:e||(e=0)}if(e>l.children.length&&(e=l.children.length),!this.check("move_node",c,l,e,{core:!0,is_multi:m&&m._id&&m._id!==this._id,is_foreign:!m||!m._id}))return this.settings.core.error.call(this,this._data.core.last_error),!1;if(c.parent===l.id){for(o=l.children.concat(),p=a.inArray(c.id,o),-1!==p&&(o=a.vakata.array_remove(o,p),e>p&&e--),p=[],q=0,r=o.length;r>q;q++)p[q>=e?q+1:q]=o[q];p[e]=c.id,l.children=p,this._node_changed(l.id),this.redraw("#"===l.id)}else{for(p=c.children_d.concat(),p.push(c.id),q=0,r=c.parents.length;r>q;q++){for(o=[],u=m._model.data[c.parents[q]].children_d,s=0,t=u.length;t>s;s++)-1===a.inArray(u[s],p)&&o.push(u[s]);m._model.data[c.parents[q]].children_d=o}for(m._model.data[j].children=a.vakata.array_remove_item(m._model.data[j].children,c.id),q=0,r=l.parents.length;r>q;q++)this._model.data[l.parents[q]].children_d=this._model.data[l.parents[q]].children_d.concat(p);for(o=[],q=0,r=l.children.length;r>q;q++)o[q>=e?q+1:q]=l.children[q];for(o[e]=c.id,l.children=o,l.children_d.push(c.id),l.children_d=l.children_d.concat(c.children_d),c.parent=l.id,p=l.parents.concat(),p.unshift(l.id),u=c.parents.length,c.parents=p,p=p.concat(),q=0,r=c.children_d.length;r>q;q++)this._model.data[c.children_d[q]].parents=this._model.data[c.children_d[q]].parents.slice(0,-1*u),Array.prototype.push.apply(this._model.data[c.children_d[q]].parents,p);this._node_changed(j),this._node_changed(l.id),this.redraw("#"===j||"#"===l.id)}return f&&f.call(this,c,l,e),this.trigger("move_node",{node:c,parent:l.id,position:e,old_parent:j,old_position:k,is_multi:m&&m._id&&m._id!==this._id,is_foreign:!m||!m._id,old_instance:m,new_instance:this}),!0},copy_node:function(c,d,e,f,g){var h,i,j,k,l,m,n,o,p,q,r;if(d=this.get_node(d),e=e===b?0:e,!d)return!1;if(!e.toString().match(/^(before|after)$/)&&!g&&!this.is_loaded(d))return this.load_node(d,function(){this.copy_node(c,d,e,f,!0)});if(a.isArray(c)){for(c=c.reverse().slice(),h=0,i=c.length;i>h;h++)this.copy_node(c[h],d,e,f,g);return!0}if(c=c&&c.id?c:this.get_node(c),!c||"#"===c.id)return!1;switch(o=(c.parent||"#").toString(),p=e.toString().match(/^(before|after)$/)&&"#"!==d.id?this.get_node(d.parent):d,q=c.instance?c.instance:this._model.data[c.id]?this:a.jstree.reference(c.id),r=!q||!q._id||this._id!==q._id,"#"===p.id&&("before"===e&&(e="first"),"after"===e&&(e="last")),e){case"before":e=a.inArray(d.id,p.children);break;case"after":e=a.inArray(d.id,p.children)+1;break;case"inside":case"first":e=0;break;case"last":e=p.children.length;break;default:e||(e=0)}if(e>p.children.length&&(e=p.children.length),!this.check("copy_node",c,p,e,{core:!0,is_multi:q&&q._id&&q._id!==this._id,is_foreign:!q||!q._id}))return this.settings.core.error.call(this,this._data.core.last_error),!1;if(n=q?q.get_json(c,{no_id:!0,no_data:!0,no_state:!0}):c,!n)return!1;if(n.id===!0&&delete n.id,n=this._parse_model_from_json(n,p.id,p.parents.concat()),!n)return!1;for(k=this.get_node(n),c&&c.state&&c.state.loaded===!1&&(k.state.loaded=!1),j=[],j.push(n),j=j.concat(k.children_d),this.trigger("model",{nodes:j,parent:p.id}),l=0,m=p.parents.length;m>l;l++)this._model.data[p.parents[l]].children_d=this._model.data[p.parents[l]].children_d.concat(j);for(j=[],l=0,m=p.children.length;m>l;l++)j[l>=e?l+1:l]=p.children[l];return j[e]=k.id,p.children=j,p.children_d.push(k.id),p.children_d=p.children_d.concat(k.children_d),this._node_changed(p.id),this.redraw("#"===p.id),f&&f.call(this,k,p,e),this.trigger("copy_node",{node:k,original:c,parent:p.id,position:e,old_parent:o,old_position:q&&q._id&&o&&q._model.data[o]&&q._model.data[o].children?a.inArray(c.id,q._model.data[o].children):-1,is_multi:q&&q._id&&q._id!==this._id,is_foreign:!q||!q._id,old_instance:q,new_instance:this}),k.id},cut:function(b){if(b||(b=this._data.core.selected.concat()),a.isArray(b)||(b=[b]),!b.length)return!1;var c,d,e,i=[];for(d=0,e=b.length;e>d;d++)c=this.get_node(b[d]),c&&c.id&&"#"!==c.id&&i.push(c);return i.length?(f=i,h=this,g="move_node",void this.trigger("cut",{node:b})):!1},copy:function(b){if(b||(b=this._data.core.selected.concat()),a.isArray(b)||(b=[b]),!b.length)return!1;var c,d,e,i=[];for(d=0,e=b.length;e>d;d++)c=this.get_node(b[d]),c&&c.id&&"#"!==c.id&&i.push(c);return i.length?(f=i,h=this,g="copy_node",void this.trigger("copy",{node:b})):!1},get_buffer:function(){return{mode:g,node:f,inst:h}},can_paste:function(){return g!==!1&&f!==!1},paste:function(a,b){return a=this.get_node(a),a&&g&&g.match(/^(copy_node|move_node)$/)&&f?(this[g](f,a,b)&&this.trigger("paste",{parent:a.id,node:f,mode:g}),f=!1,g=!1,void(h=!1)):!1},edit:function(b,c){if(b=this.get_node(b),!b)return!1;if(this.settings.core.check_callback===!1)return this._data.core.last_error={error:"check",plugin:"core",id:"core_07",reason:"Could not edit node because of check_callback"},this.settings.core.error.call(this,this._data.core.last_error),!1;c="string"==typeof c?c:b.text,this.set_text(b,""),b=this._open_to(b);var d=this._data.core.rtl,e=this.element.width(),f=b.children(".jstree-anchor"),g=a(""),h=c,i=a("
      ",{css:{position:"absolute",top:"-200px",left:d?"0px":"-1000px",visibility:"hidden"}}).appendTo("body"),j=a("",{value:h,"class":"jstree-rename-input",css:{padding:"0",border:"1px solid silver","box-sizing":"border-box",display:"inline-block",height:this._data.core.li_height+"px",lineHeight:this._data.core.li_height+"px",width:"150px"},blur:a.proxy(function(){var c=g.children(".jstree-rename-input"),d=c.val();""===d&&(d=h),i.remove(),g.replaceWith(f),g.remove(),this.set_text(b,h),this.rename_node(b,a("
      ").text(d)[this.settings.core.force_text?"text":"html"]())===!1&&this.set_text(b,h)},this),keydown:function(a){var b=a.which;27===b&&(this.value=h),(27===b||13===b||37===b||38===b||39===b||40===b||32===b)&&a.stopImmediatePropagation(),(27===b||13===b)&&(a.preventDefault(),this.blur())},click:function(a){a.stopImmediatePropagation()},mousedown:function(a){a.stopImmediatePropagation()},keyup:function(){j.width(Math.min(i.text("pW"+this.value).width(),e))},keypress:function(a){return 13===a.which?!1:void 0}}),k={fontFamily:f.css("fontFamily")||"",fontSize:f.css("fontSize")||"",fontWeight:f.css("fontWeight")||"",fontStyle:f.css("fontStyle")||"",fontStretch:f.css("fontStretch")||"",fontVariant:f.css("fontVariant")||"",letterSpacing:f.css("letterSpacing")||"",wordSpacing:f.css("wordSpacing")||""};g.attr("class",f.attr("class")).append(f.contents().clone()).append(j),f.replaceWith(g),i.css(k),j.css(k).width(Math.min(i.text("pW"+j[0].value).width(),e))[0].select()},set_theme:function(b,c){if(!b)return!1;if(c===!0){var d=this.settings.core.themes.dir;d||(d=a.jstree.path+"/themes"),c=d+"/"+b+"/style.css"}c&&-1===a.inArray(c,i)&&(a("head").append(''),i.push(c)),this._data.core.themes.name&&this.element.removeClass("jstree-"+this._data.core.themes.name),this._data.core.themes.name=b,this.element.addClass("jstree-"+b),this.element[this.settings.core.themes.responsive?"addClass":"removeClass"]("jstree-"+b+"-responsive"),this.trigger("set_theme",{theme:b})},get_theme:function(){return this._data.core.themes.name},set_theme_variant:function(a){this._data.core.themes.variant&&this.element.removeClass("jstree-"+this._data.core.themes.name+"-"+this._data.core.themes.variant),this._data.core.themes.variant=a,a&&this.element.addClass("jstree-"+this._data.core.themes.name+"-"+this._data.core.themes.variant)},get_theme_variant:function(){return this._data.core.themes.variant},show_stripes:function(){this._data.core.themes.stripes=!0,this.get_container_ul().addClass("jstree-striped")},hide_stripes:function(){this._data.core.themes.stripes=!1,this.get_container_ul().removeClass("jstree-striped")},toggle_stripes:function(){this._data.core.themes.stripes?this.hide_stripes():this.show_stripes()},show_dots:function(){this._data.core.themes.dots=!0,this.get_container_ul().removeClass("jstree-no-dots")},hide_dots:function(){this._data.core.themes.dots=!1,this.get_container_ul().addClass("jstree-no-dots")},toggle_dots:function(){this._data.core.themes.dots?this.hide_dots():this.show_dots()},show_icons:function(){this._data.core.themes.icons=!0,this.get_container_ul().removeClass("jstree-no-icons")},hide_icons:function(){this._data.core.themes.icons=!1,this.get_container_ul().addClass("jstree-no-icons")},toggle_icons:function(){this._data.core.themes.icons?this.hide_icons():this.show_icons()},set_icon:function(b,c){var d,e,f,g;if(a.isArray(b)){for(b=b.slice(),d=0,e=b.length;e>d;d++)this.set_icon(b[d],c);return!0}return b=this.get_node(b),b&&"#"!==b.id?(g=b.icon,b.icon=c,f=this.get_node(b,!0).children(".jstree-anchor").children(".jstree-themeicon"),c===!1?this.hide_icon(b):c===!0?f.removeClass("jstree-themeicon-custom "+g).css("background","").removeAttr("rel"):-1===c.indexOf("/")&&-1===c.indexOf(".")?(f.removeClass(g).css("background",""),f.addClass(c+" jstree-themeicon-custom").attr("rel",c)):(f.removeClass(g).css("background",""),f.addClass("jstree-themeicon-custom").css("background","url('"+c+"') center center no-repeat").attr("rel",c)),!0):!1},get_icon:function(a){return a=this.get_node(a),a&&"#"!==a.id?a.icon:!1},hide_icon:function(b){var c,d;if(a.isArray(b)){for(b=b.slice(),c=0,d=b.length;d>c;c++)this.hide_icon(b[c]);return!0}return b=this.get_node(b),b&&"#"!==b?(b.icon=!1,this.get_node(b,!0).children(".jstree-anchor").children(".jstree-themeicon").addClass("jstree-themeicon-hidden"),!0):!1},show_icon:function(b){var c,d,e;if(a.isArray(b)){for(b=b.slice(),c=0,d=b.length;d>c;c++)this.show_icon(b[c]);return!0}return b=this.get_node(b),b&&"#"!==b?(e=this.get_node(b,!0),b.icon=e.length?e.children(".jstree-anchor").children(".jstree-themeicon").attr("rel"):!0,b.icon||(b.icon=!0),e.children(".jstree-anchor").children(".jstree-themeicon").removeClass("jstree-themeicon-hidden"),!0):!1}},a.vakata={},a.vakata.attributes=function(b,c){b=a(b)[0];var d=c?{}:[];return b&&b.attributes&&a.each(b.attributes,function(b,e){-1===a.inArray(e.nodeName.toLowerCase(),["style","contenteditable","hasfocus","tabindex"])&&null!==e.nodeValue&&""!==a.trim(e.nodeValue)&&(c?d[e.nodeName]=e.nodeValue:d.push(e.nodeName))}),d},a.vakata.array_unique=function(a){var b,c,d,e=[];for(b=0,d=a.length;d>b;b++){for(c=0;b>=c&&a[b]!==a[c];c++);c===b&&e.push(a[b])}return e},a.vakata.array_remove=function(a,b,c){var d=a.slice((c||b)+1||a.length);return a.length=0>b?a.length+b:b,a.push.apply(a,d),a},a.vakata.array_remove_item=function(b,c){var d=a.inArray(c,b);return-1!==d?a.vakata.array_remove(b,d):b};var m=document.createElement("I");m.className="jstree-icon jstree-checkbox",a.jstree.defaults.checkbox={visible:!0,three_state:!0,whole_node:!0,keep_selected_style:!0,cascade:"",tie_selection:!0},a.jstree.plugins.checkbox=function(b,c){this.bind=function(){c.bind.call(this),this._data.checkbox.uto=!1,this._data.checkbox.selected=[],this.settings.checkbox.three_state&&(this.settings.checkbox.cascade="up+down+undetermined"),this.element.on("init.jstree",a.proxy(function(){this._data.checkbox.visible=this.settings.checkbox.visible,this.settings.checkbox.keep_selected_style||this.element.addClass("jstree-checkbox-no-clicked"),this.settings.checkbox.tie_selection&&this.element.addClass("jstree-checkbox-selection")},this)).on("loading.jstree",a.proxy(function(){this[this._data.checkbox.visible?"show_checkboxes":"hide_checkboxes"]()},this)),-1!==this.settings.checkbox.cascade.indexOf("undetermined")&&this.element.on("changed.jstree uncheck_node.jstree check_node.jstree uncheck_all.jstree check_all.jstree move_node.jstree copy_node.jstree redraw.jstree open_node.jstree",a.proxy(function(){this._data.checkbox.uto&&clearTimeout(this._data.checkbox.uto),this._data.checkbox.uto=setTimeout(a.proxy(this._undetermined,this),50)},this)),this.settings.checkbox.tie_selection||this.element.on("model.jstree",a.proxy(function(a,b){var c,d,e=this._model.data,f=(e[b.parent],b.nodes);for(c=0,d=f.length;d>c;c++)e[f[c]].state.checked=e[f[c]].original&&e[f[c]].original.state&&e[f[c]].original.state.checked,e[f[c]].state.checked&&this._data.checkbox.selected.push(f[c])},this)),(-1!==this.settings.checkbox.cascade.indexOf("up")||-1!==this.settings.checkbox.cascade.indexOf("down"))&&this.element.on("model.jstree",a.proxy(function(b,c){var d,e,f,g,h,i,j=this._model.data,k=j[c.parent],l=c.nodes,m=[],n=this.settings.checkbox.cascade,o=this.settings.checkbox.tie_selection;if(-1!==n.indexOf("down"))if(k.state[o?"selected":"checked"]){for(e=0,f=l.length;f>e;e++)j[l[e]].state[o?"selected":"checked"]=!0;this._data[o?"core":"checkbox"].selected=this._data[o?"core":"checkbox"].selected.concat(l)}else for(e=0,f=l.length;f>e;e++)if(j[l[e]].state[o?"selected":"checked"]){for(g=0,h=j[l[e]].children_d.length;h>g;g++)j[j[l[e]].children_d[g]].state[o?"selected":"checked"]=!0;this._data[o?"core":"checkbox"].selected=this._data[o?"core":"checkbox"].selected.concat(j[l[e]].children_d)}if(-1!==n.indexOf("up")){for(e=0,f=k.children_d.length;f>e;e++)j[k.children_d[e]].children.length||m.push(j[k.children_d[e]].parent);for(m=a.vakata.array_unique(m),g=0,h=m.length;h>g;g++)for(k=j[m[g]];k&&"#"!==k.id;){for(d=0,e=0,f=k.children.length;f>e;e++)d+=j[k.children[e]].state[o?"selected":"checked"];if(d!==f)break;k.state[o?"selected":"checked"]=!0,this._data[o?"core":"checkbox"].selected.push(k.id),i=this.get_node(k,!0),i&&i.length&&i.children(".jstree-anchor").addClass(o?"jstree-clicked":"jstree-checked"),k=this.get_node(k.parent)}}this._data[o?"core":"checkbox"].selected=a.vakata.array_unique(this._data[o?"core":"checkbox"].selected)},this)).on(this.settings.checkbox.tie_selection?"select_node.jstree":"check_node.jstree",a.proxy(function(b,c){var d,e,f,g,h=c.node,i=this._model.data,j=this.get_node(h.parent),k=this.get_node(h,!0),l=this.settings.checkbox.cascade,m=this.settings.checkbox.tie_selection;if(-1!==l.indexOf("down"))for(this._data[m?"core":"checkbox"].selected=a.vakata.array_unique(this._data[m?"core":"checkbox"].selected.concat(h.children_d)),d=0,e=h.children_d.length;e>d;d++)g=i[h.children_d[d]],g.state[m?"selected":"checked"]=!0,g&&g.original&&g.original.state&&g.original.state.undetermined&&(g.original.state.undetermined=!1);if(-1!==l.indexOf("up"))for(;j&&"#"!==j.id;){for(f=0,d=0,e=j.children.length;e>d;d++)f+=i[j.children[d]].state[m?"selected":"checked"];if(f!==e)break;j.state[m?"selected":"checked"]=!0,this._data[m?"core":"checkbox"].selected.push(j.id),g=this.get_node(j,!0),g&&g.length&&g.children(".jstree-anchor").addClass(m?"jstree-clicked":"jstree-checked"),j=this.get_node(j.parent)}-1!==l.indexOf("down")&&k.length&&k.find(".jstree-anchor").addClass(m?"jstree-clicked":"jstree-checked")},this)).on(this.settings.checkbox.tie_selection?"deselect_all.jstree":"uncheck_all.jstree",a.proxy(function(){var a,b,c,d=this.get_node("#"),e=this._model.data;for(a=0,b=d.children_d.length;b>a;a++)c=e[d.children_d[a]],c&&c.original&&c.original.state&&c.original.state.undetermined&&(c.original.state.undetermined=!1)},this)).on(this.settings.checkbox.tie_selection?"deselect_node.jstree":"uncheck_node.jstree",a.proxy(function(b,c){var d,e,f,g=c.node,h=this.get_node(g,!0),i=this.settings.checkbox.cascade,j=this.settings.checkbox.tie_selection;if(g&&g.original&&g.original.state&&g.original.state.undetermined&&(g.original.state.undetermined=!1),-1!==i.indexOf("down"))for(d=0,e=g.children_d.length;e>d;d++)f=this._model.data[g.children_d[d]],f.state[j?"selected":"checked"]=!1,f&&f.original&&f.original.state&&f.original.state.undetermined&&(f.original.state.undetermined=!1);if(-1!==i.indexOf("up"))for(d=0,e=g.parents.length;e>d;d++)f=this._model.data[g.parents[d]],f.state[j?"selected":"checked"]=!1,f&&f.original&&f.original.state&&f.original.state.undetermined&&(f.original.state.undetermined=!1),f=this.get_node(g.parents[d],!0),f&&f.length&&f.children(".jstree-anchor").removeClass(j?"jstree-clicked":"jstree-checked");for(f=[],d=0,e=this._data[j?"core":"checkbox"].selected.length;e>d;d++)-1!==i.indexOf("down")&&-1!==a.inArray(this._data[j?"core":"checkbox"].selected[d],g.children_d)||-1!==i.indexOf("up")&&-1!==a.inArray(this._data[j?"core":"checkbox"].selected[d],g.parents)||f.push(this._data[j?"core":"checkbox"].selected[d]);this._data[j?"core":"checkbox"].selected=a.vakata.array_unique(f),-1!==i.indexOf("down")&&h.length&&h.find(".jstree-anchor").removeClass(j?"jstree-clicked":"jstree-checked")},this)),-1!==this.settings.checkbox.cascade.indexOf("up")&&this.element.on("delete_node.jstree",a.proxy(function(a,b){for(var c,d,e,f,g=this.get_node(b.parent),h=this._model.data,i=this.settings.checkbox.tie_selection;g&&"#"!==g.id;){for(e=0,c=0,d=g.children.length;d>c;c++)e+=h[g.children[c]].state[i?"selected":"checked"];if(e!==d)break;g.state[i?"selected":"checked"]=!0,this._data[i?"core":"checkbox"].selected.push(g.id),f=this.get_node(g,!0),f&&f.length&&f.children(".jstree-anchor").addClass(i?"jstree-clicked":"jstree-checked"), +g=this.get_node(g.parent)}},this)).on("move_node.jstree",a.proxy(function(b,c){var d,e,f,g,h,i=c.is_multi,j=c.old_parent,k=this.get_node(c.parent),l=this._model.data,m=this.settings.checkbox.tie_selection;if(!i)for(d=this.get_node(j);d&&"#"!==d.id;){for(e=0,f=0,g=d.children.length;g>f;f++)e+=l[d.children[f]].state[m?"selected":"checked"];if(e!==g)break;d.state[m?"selected":"checked"]=!0,this._data[m?"core":"checkbox"].selected.push(d.id),h=this.get_node(d,!0),h&&h.length&&h.children(".jstree-anchor").addClass(m?"jstree-clicked":"jstree-checked"),d=this.get_node(d.parent)}for(d=k;d&&"#"!==d.id;){for(e=0,f=0,g=d.children.length;g>f;f++)e+=l[d.children[f]].state[m?"selected":"checked"];if(e===g)d.state[m?"selected":"checked"]||(d.state[m?"selected":"checked"]=!0,this._data[m?"core":"checkbox"].selected.push(d.id),h=this.get_node(d,!0),h&&h.length&&h.children(".jstree-anchor").addClass(m?"jstree-clicked":"jstree-checked"));else{if(!d.state[m?"selected":"checked"])break;d.state[m?"selected":"checked"]=!1,this._data[m?"core":"checkbox"].selected=a.vakata.array_remove_item(this._data[m?"core":"checkbox"].selected,d.id),h=this.get_node(d,!0),h&&h.length&&h.children(".jstree-anchor").removeClass(m?"jstree-clicked":"jstree-checked")}d=this.get_node(d.parent)}},this))},this._undetermined=function(){var b,c,d=this._model.data,e=this.settings.checkbox.tie_selection,f=this._data[e?"core":"checkbox"].selected,g=[],h=this;for(b=0,c=f.length;c>b;b++)d[f[b]]&&d[f[b]].parents&&(g=g.concat(d[f[b]].parents));for(this.element.find(".jstree-closed").not(":has(.jstree-children)").each(function(){var a,e=h.get_node(this);if(e.state.loaded)for(b=0,c=e.children_d.length;c>b;b++)a=d[e.children_d[b]],!a.state.loaded&&a.original&&a.original.state&&a.original.state.undetermined&&a.original.state.undetermined===!0&&(g.push(a.id),g=g.concat(a.parents));else e.original&&e.original.state&&e.original.state.undetermined&&e.original.state.undetermined===!0&&(g.push(e.id),g=g.concat(e.parents))}),g=a.vakata.array_unique(g),g=a.vakata.array_remove_item(g,"#"),this.element.find(".jstree-undetermined").removeClass("jstree-undetermined"),b=0,c=g.length;c>b;b++)d[g[b]].state[e?"selected":"checked"]||(f=this.get_node(g[b],!0),f&&f.length&&f.children(".jstree-anchor").children(".jstree-checkbox").addClass("jstree-undetermined"))},this.redraw_node=function(b,d,e){if(b=c.redraw_node.call(this,b,d,e)){var f,g,h=null;for(f=0,g=b.childNodes.length;g>f;f++)if(b.childNodes[f]&&b.childNodes[f].className&&-1!==b.childNodes[f].className.indexOf("jstree-anchor")){h=b.childNodes[f];break}h&&(!this.settings.checkbox.tie_selection&&this._model.data[b.id].state.checked&&(h.className+=" jstree-checked"),h.insertBefore(m.cloneNode(!1),h.childNodes[0]))}return e||-1===this.settings.checkbox.cascade.indexOf("undetermined")||(this._data.checkbox.uto&&clearTimeout(this._data.checkbox.uto),this._data.checkbox.uto=setTimeout(a.proxy(this._undetermined,this),50)),b},this.show_checkboxes=function(){this._data.core.themes.checkboxes=!0,this.get_container_ul().removeClass("jstree-no-checkboxes")},this.hide_checkboxes=function(){this._data.core.themes.checkboxes=!1,this.get_container_ul().addClass("jstree-no-checkboxes")},this.toggle_checkboxes=function(){this._data.core.themes.checkboxes?this.hide_checkboxes():this.show_checkboxes()},this.is_undetermined=function(b){b=this.get_node(b);var c,d,e=this.settings.checkbox.cascade,f=this.settings.checkbox.tie_selection,g=this._data[f?"core":"checkbox"].selected,h=this._model.data;if(!b||b.state[f?"selected":"checked"]===!0||-1===e.indexOf("undetermined")||-1===e.indexOf("down")&&-1===e.indexOf("up"))return!1;if(!b.state.loaded&&b.original.state.undetermined===!0)return!0;for(c=0,d=b.children_d.length;d>c;c++)if(-1!==a.inArray(b.children_d[c],g)||!h[b.children_d[c]].state.loaded&&h[b.children_d[c]].original.state.undetermined)return!0;return!1},this.activate_node=function(b,d){return this.settings.checkbox.tie_selection&&(this.settings.checkbox.whole_node||a(d.target).hasClass("jstree-checkbox"))&&(d.ctrlKey=!0),this.settings.checkbox.tie_selection||!this.settings.checkbox.whole_node&&!a(d.target).hasClass("jstree-checkbox")?c.activate_node.call(this,b,d):(this.is_checked(b)?this.uncheck_node(b,d):this.check_node(b,d),void this.trigger("activate_node",{node:this.get_node(b)}))},this.check_node=function(b,c){if(this.settings.checkbox.tie_selection)return this.select_node(b,!1,!0,c);var d,e,f;if(a.isArray(b)){for(b=b.slice(),e=0,f=b.length;f>e;e++)this.check_node(b[e],c);return!0}return b=this.get_node(b),b&&"#"!==b.id?(d=this.get_node(b,!0),void(b.state.checked||(b.state.checked=!0,this._data.checkbox.selected.push(b.id),d&&d.length&&d.children(".jstree-anchor").addClass("jstree-checked"),this.trigger("check_node",{node:b,selected:this._data.checkbox.selected,event:c})))):!1},this.uncheck_node=function(b,c){if(this.settings.checkbox.tie_selection)return this.deselect_node(b,!1,c);var d,e,f;if(a.isArray(b)){for(b=b.slice(),d=0,e=b.length;e>d;d++)this.uncheck_node(b[d],c);return!0}return b=this.get_node(b),b&&"#"!==b.id?(f=this.get_node(b,!0),void(b.state.checked&&(b.state.checked=!1,this._data.checkbox.selected=a.vakata.array_remove_item(this._data.checkbox.selected,b.id),f.length&&f.children(".jstree-anchor").removeClass("jstree-checked"),this.trigger("uncheck_node",{node:b,selected:this._data.checkbox.selected,event:c})))):!1},this.check_all=function(){if(this.settings.checkbox.tie_selection)return this.select_all();{var a,b;this._data.checkbox.selected.concat([])}for(this._data.checkbox.selected=this._model.data["#"].children_d.concat(),a=0,b=this._data.checkbox.selected.length;b>a;a++)this._model.data[this._data.checkbox.selected[a]]&&(this._model.data[this._data.checkbox.selected[a]].state.checked=!0);this.redraw(!0),this.trigger("check_all",{selected:this._data.checkbox.selected})},this.uncheck_all=function(){if(this.settings.checkbox.tie_selection)return this.deselect_all();var a,b,c=this._data.checkbox.selected.concat([]);for(a=0,b=this._data.checkbox.selected.length;b>a;a++)this._model.data[this._data.checkbox.selected[a]]&&(this._model.data[this._data.checkbox.selected[a]].state.checked=!1);this._data.checkbox.selected=[],this.element.find(".jstree-checked").removeClass("jstree-checked"),this.trigger("uncheck_all",{selected:this._data.checkbox.selected,node:c})},this.is_checked=function(a){return this.settings.checkbox.tie_selection?this.is_selected(a):(a=this.get_node(a),a&&"#"!==a.id?a.state.checked:!1)},this.get_checked=function(b){return this.settings.checkbox.tie_selection?this.get_selected(b):b?a.map(this._data.checkbox.selected,a.proxy(function(a){return this.get_node(a)},this)):this._data.checkbox.selected},this.get_top_checked=function(b){if(this.settings.checkbox.tie_selection)return this.get_top_selected(b);var c,d,e,f,g=this.get_checked(!0),h={};for(c=0,d=g.length;d>c;c++)h[g[c].id]=g[c];for(c=0,d=g.length;d>c;c++)for(e=0,f=g[c].children_d.length;f>e;e++)h[g[c].children_d[e]]&&delete h[g[c].children_d[e]];g=[];for(c in h)h.hasOwnProperty(c)&&g.push(c);return b?a.map(g,a.proxy(function(a){return this.get_node(a)},this)):g},this.get_bottom_checked=function(b){if(this.settings.checkbox.tie_selection)return this.get_bottom_selected(b);var c,d,e=this.get_checked(!0),f=[];for(c=0,d=e.length;d>c;c++)e[c].children.length||f.push(e[c].id);return b?a.map(f,a.proxy(function(a){return this.get_node(a)},this)):f}},a.jstree.defaults.contextmenu={select_node:!0,show_at_node:!0,items:function(){return{create:{separator_before:!1,separator_after:!0,_disabled:!1,label:"Create",action:function(b){var c=a.jstree.reference(b.reference),d=c.get_node(b.reference);c.create_node(d,{},"last",function(a){setTimeout(function(){c.edit(a)},0)})}},rename:{separator_before:!1,separator_after:!1,_disabled:!1,label:"Rename",action:function(b){var c=a.jstree.reference(b.reference),d=c.get_node(b.reference);c.edit(d)}},remove:{separator_before:!1,icon:!1,separator_after:!1,_disabled:!1,label:"Delete",action:function(b){var c=a.jstree.reference(b.reference),d=c.get_node(b.reference);c.delete_node(c.is_selected(d)?c.get_selected():d)}},ccp:{separator_before:!0,icon:!1,separator_after:!1,label:"Edit",action:!1,submenu:{cut:{separator_before:!1,separator_after:!1,label:"Cut",action:function(b){var c=a.jstree.reference(b.reference),d=c.get_node(b.reference);c.cut(c.is_selected(d)?c.get_selected():d)}},copy:{separator_before:!1,icon:!1,separator_after:!1,label:"Copy",action:function(b){var c=a.jstree.reference(b.reference),d=c.get_node(b.reference);c.copy(c.is_selected(d)?c.get_selected():d)}},paste:{separator_before:!1,icon:!1,_disabled:function(b){return!a.jstree.reference(b.reference).can_paste()},separator_after:!1,label:"Paste",action:function(b){var c=a.jstree.reference(b.reference),d=c.get_node(b.reference);c.paste(d)}}}}}}},a.jstree.plugins.contextmenu=function(c,d){this.bind=function(){d.bind.call(this);var b=0;this.element.on("contextmenu.jstree",".jstree-anchor",a.proxy(function(a){a.preventDefault(),b=a.ctrlKey?a.timeStamp:0,this.is_loading(a.currentTarget)||this.show_contextmenu(a.currentTarget,a.pageX,a.pageY,a)},this)).on("click.jstree",".jstree-anchor",a.proxy(function(c){this._data.contextmenu.visible&&(!b||c.timeStamp-b>250)&&a.vakata.context.hide()},this)),a(document).on("context_hide.vakata",a.proxy(function(){this._data.contextmenu.visible=!1},this))},this.teardown=function(){this._data.contextmenu.visible&&a.vakata.context.hide(),d.teardown.call(this)},this.show_contextmenu=function(c,d,e,f){if(c=this.get_node(c),!c||"#"===c.id)return!1;var g=this.settings.contextmenu,h=this.get_node(c,!0),i=h.children(".jstree-anchor"),j=!1,k=!1;(g.show_at_node||d===b||e===b)&&(j=i.offset(),d=j.left,e=j.top+this._data.core.li_height),this.settings.contextmenu.select_node&&!this.is_selected(c)&&this.activate_node(c,f),k=g.items,a.isFunction(k)&&(k=k.call(this,c,a.proxy(function(a){this._show_contextmenu(c,d,e,a)},this))),a.isPlainObject(k)&&this._show_contextmenu(c,d,e,k)},this._show_contextmenu=function(b,c,d,e){var f=this.get_node(b,!0),g=f.children(".jstree-anchor");a(document).one("context_show.vakata",a.proxy(function(b,c){var d="jstree-contextmenu jstree-"+this.get_theme()+"-contextmenu";a(c.element).addClass(d)},this)),this._data.contextmenu.visible=!0,a.vakata.context.show(g,{x:c,y:d},e),this.trigger("show_contextmenu",{node:b,x:c,y:d})}},function(a){var b=!1,c={element:!1,reference:!1,position_x:0,position_y:0,items:[],html:"",is_visible:!1};a.vakata.context={settings:{hide_onmouseleave:0,icons:!0},_trigger:function(b){a(document).triggerHandler("context_"+b+".vakata",{reference:c.reference,element:c.element,position:{x:c.position_x,y:c.position_y}})},_execute:function(b){return b=c.items[b],b&&(!b._disabled||a.isFunction(b._disabled)&&!b._disabled({item:b,reference:c.reference,element:c.element}))&&b.action?b.action.call(null,{item:b,reference:c.reference,element:c.element,position:{x:c.position_x,y:c.position_y}}):!1},_parse:function(b,d){if(!b)return!1;d||(c.html="",c.items=[]);var e,f="",g=!1;return d&&(f+=""),d||(c.html=f,a.vakata.context._trigger("parse")),f.length>10?f:!1},_show_submenu:function(c){if(c=a(c),c.length&&c.children("ul").length){var d=c.children("ul"),e=c.offset().left+c.outerWidth(),f=c.offset().top,g=d.width(),h=d.height(),i=a(window).width()+a(window).scrollLeft(),j=a(window).height()+a(window).scrollTop();b?c[e-(g+10+c.outerWidth())<0?"addClass":"removeClass"]("vakata-context-left"):c[e+g+10>i?"addClass":"removeClass"]("vakata-context-right"),f+h+10>j&&d.css("bottom","-1px"),d.show()}},show:function(d,e,f){var g,h,i,j,k,l,m,n,o=!0;switch(c.element&&c.element.length&&c.element.width(""),o){case!e&&!d:return!1;case!!e&&!!d:c.reference=d,c.position_x=e.x,c.position_y=e.y;break;case!e&&!!d:c.reference=d,g=d.offset(),c.position_x=g.left+d.outerHeight(),c.position_y=g.top;break;case!!e&&!d:c.position_x=e.x,c.position_y=e.y}d&&!f&&a(d).data("vakata_contextmenu")&&(f=a(d).data("vakata_contextmenu")),a.vakata.context._parse(f)&&c.element.html(c.html),c.items.length&&(h=c.element,i=c.position_x,j=c.position_y,k=h.width(),l=h.height(),m=a(window).width()+a(window).scrollLeft(),n=a(window).height()+a(window).scrollTop(),b&&(i-=h.outerWidth(),im&&(i=m-(k+20)),j+l+20>n&&(j=n-(l+20)),c.element.css({left:i,top:j}).show().find("a:eq(0)").focus().parent().addClass("vakata-context-hover"),c.is_visible=!0,a.vakata.context._trigger("show"))},hide:function(){c.is_visible&&(c.element.hide().find("ul").hide().end().find(":focus").blur(),c.is_visible=!1,a.vakata.context._trigger("hide"))}},a(function(){b="rtl"===a("body").css("direction");var d=!1;c.element=a("
        "),c.element.on("mouseenter","li",function(b){b.stopImmediatePropagation(),a.contains(this,b.relatedTarget)||(d&&clearTimeout(d),c.element.find(".vakata-context-hover").removeClass("vakata-context-hover").end(),a(this).siblings().find("ul").hide().end().end().parentsUntil(".vakata-context","li").addBack().addClass("vakata-context-hover"),a.vakata.context._show_submenu(this))}).on("mouseleave","li",function(b){a.contains(this,b.relatedTarget)||a(this).find(".vakata-context-hover").addBack().removeClass("vakata-context-hover")}).on("mouseleave",function(){a(this).find(".vakata-context-hover").removeClass("vakata-context-hover"),a.vakata.context.settings.hide_onmouseleave&&(d=setTimeout(function(){return function(){a.vakata.context.hide()}}(this),a.vakata.context.settings.hide_onmouseleave))}).on("click","a",function(b){b.preventDefault(),a(this).blur().parent().hasClass("vakata-context-disabled")||a.vakata.context._execute(a(this).attr("rel"))===!1||a.vakata.context.hide()}).on("keydown","a",function(b){var d=null;switch(b.which){case 13:case 32:b.type="mouseup",b.preventDefault(),a(b.currentTarget).trigger(b);break;case 37:c.is_visible&&(c.element.find(".vakata-context-hover").last().parents("li:eq(0)").find("ul").hide().find(".vakata-context-hover").removeClass("vakata-context-hover").end().end().children("a").focus(),b.stopImmediatePropagation(),b.preventDefault());break;case 38:c.is_visible&&(d=c.element.find("ul:visible").addBack().last().children(".vakata-context-hover").removeClass("vakata-context-hover").prevAll("li:not(.vakata-context-separator)").first(),d.length||(d=c.element.find("ul:visible").addBack().last().children("li:not(.vakata-context-separator)").last()),d.addClass("vakata-context-hover").children("a").focus(),b.stopImmediatePropagation(),b.preventDefault());break;case 39:c.is_visible&&(c.element.find(".vakata-context-hover").last().children("ul").show().children("li:not(.vakata-context-separator)").removeClass("vakata-context-hover").first().addClass("vakata-context-hover").children("a").focus(),b.stopImmediatePropagation(),b.preventDefault());break;case 40:c.is_visible&&(d=c.element.find("ul:visible").addBack().last().children(".vakata-context-hover").removeClass("vakata-context-hover").nextAll("li:not(.vakata-context-separator)").first(),d.length||(d=c.element.find("ul:visible").addBack().last().children("li:not(.vakata-context-separator)").first()),d.addClass("vakata-context-hover").children("a").focus(),b.stopImmediatePropagation(),b.preventDefault());break;case 27:a.vakata.context.hide(),b.preventDefault()}}).on("keydown",function(a){a.preventDefault();var b=c.element.find(".vakata-contextmenu-shortcut-"+a.which).parent();b.parent().not(".vakata-context-disabled")&&b.mouseup()}).appendTo("body"),a(document).on("mousedown",function(b){c.is_visible&&!a.contains(c.element[0],b.target)&&a.vakata.context.hide()}).on("context_show.vakata",function(){c.element.find("li:has(ul)").children("a").addClass("vakata-context-parent"),b&&c.element.addClass("vakata-context-rtl").css("direction","rtl"),c.element.find("ul").hide().end()})})}(a),a.jstree.defaults.dnd={copy:!0,open_timeout:500,is_draggable:!0,check_while_dragging:!0,always_copy:!1,inside_pos:0},a.jstree.plugins.dnd=function(b,c){this.bind=function(){c.bind.call(this),this.element.on("mousedown.jstree touchstart.jstree",".jstree-anchor",a.proxy(function(b){var c=this.get_node(b.target),d=this.is_selected(c)?this.get_selected().length:1;return c&&c.id&&"#"!==c.id&&(1===b.which||"touchstart"===b.type)&&(this.settings.dnd.is_draggable===!0||a.isFunction(this.settings.dnd.is_draggable)&&this.settings.dnd.is_draggable.call(this,d>1?this.get_selected(!0):[c]))?(this.element.trigger("mousedown.jstree"),a.vakata.dnd.start(b,{jstree:!0,origin:this,obj:this.get_node(c,!0),nodes:d>1?this.get_selected():[c.id]},'
        '+(d>1?d+" "+this.get_string("nodes"):this.get_text(b.currentTarget,!0))+'
        ')):void 0},this))}},a(function(){var b=!1,c=!1,d=!1,e=a('
         
        ').hide().appendTo("body");a(document).bind("dnd_start.vakata",function(){b=!1}).bind("dnd_move.vakata",function(f,g){if(d&&clearTimeout(d),g&&g.data&&g.data.jstree&&(!g.event.target.id||"jstree-marker"!==g.event.target.id)){var h,i,j,k,l,m,n,o,p,q,r,s,t,u,v=a.jstree.reference(g.event.target),w=!1,x=!1,y=!1;if(v&&v._data&&v._data.dnd)if(e.attr("class","jstree-"+v.get_theme()+(v.settings.core.themes.responsive?" jstree-dnd-responsive":"")),g.helper.children().attr("class","jstree-"+v.get_theme()+(v.settings.core.themes.responsive?" jstree-dnd-responsive":"")).find(".jstree-copy:eq(0)")[g.data.origin&&(g.data.origin.settings.dnd.always_copy||g.data.origin.settings.dnd.copy&&(g.event.metaKey||g.event.ctrlKey))?"show":"hide"](),g.event.target!==v.element[0]&&g.event.target!==v.get_container_ul()[0]||0!==v.get_container_ul().children().length){if(w=a(g.event.target).closest(".jstree-anchor"),w&&w.length&&w.parent().is(".jstree-closed, .jstree-open, .jstree-leaf")&&(x=w.offset(),y=g.event.pageY-x.top,j=w.height(),m=j/3>y?["b","i","a"]:y>j-j/3?["a","i","b"]:y>j/2?["i","a","b"]:["i","b","a"],a.each(m,function(f,y){switch(y){case"b":h=x.left-6,i=x.top,k=v.get_parent(w),l=w.parent().index();break;case"i":t=v.settings.dnd.inside_pos,u=v.get_node(w.parent()),h=x.left-2,i=x.top+j/2+1,k=u.id,l="first"===t?0:"last"===t?u.children.length:Math.min(t,u.children.length);break;case"a":h=x.left-6,i=x.top+j,k=v.get_parent(w),l=w.parent().index()+1}for(n=!0,o=0,p=g.data.nodes.length;p>o;o++)if(q=g.data.origin&&(g.data.origin.settings.dnd.always_copy||g.data.origin.settings.dnd.copy&&(g.event.metaKey||g.event.ctrlKey))?"copy_node":"move_node",r=l,"move_node"===q&&"a"===y&&g.data.origin&&g.data.origin===v&&k===v.get_parent(g.data.nodes[o])&&(s=v.get_node(k),r>a.inArray(g.data.nodes[o],s.children)&&(r-=1)),n=n&&(v&&v.settings&&v.settings.dnd&&v.settings.dnd.check_while_dragging===!1||v.check(q,g.data.origin&&g.data.origin!==v?g.data.origin.get_node(g.data.nodes[o]):g.data.nodes[o],k,r,{dnd:!0,ref:v.get_node(w.parent()),pos:y,is_multi:g.data.origin&&g.data.origin!==v,is_foreign:!g.data.origin})),!n){v&&v.last_error&&(c=v.last_error());break}return n?("i"===y&&w.parent().is(".jstree-closed")&&v.settings.dnd.open_timeout&&(d=setTimeout(function(a,b){return function(){a.open_node(b)}}(v,w),v.settings.dnd.open_timeout)),b={ins:v,par:k,pos:"i"!==y||"last"!==t||0!==l||v.is_loaded(u)?l:"last"},e.css({left:h+"px",top:i+"px"}).show(),g.helper.find(".jstree-icon:eq(0)").removeClass("jstree-er").addClass("jstree-ok"),c={},m=!0,!1):void 0}),m===!0))return}else{for(n=!0,o=0,p=g.data.nodes.length;p>o&&(n=n&&v.check(g.data.origin&&(g.data.origin.settings.dnd.always_copy||g.data.origin.settings.dnd.copy&&(g.event.metaKey||g.event.ctrlKey))?"copy_node":"move_node",g.data.origin&&g.data.origin!==v?g.data.origin.get_node(g.data.nodes[o]):g.data.nodes[o],"#","last",{dnd:!0,ref:v.get_node("#"),pos:"i",is_multi:g.data.origin&&g.data.origin!==v,is_foreign:!g.data.origin}),n);o++);if(n)return b={ins:v,par:"#",pos:"last"},e.hide(),void g.helper.find(".jstree-icon:eq(0)").removeClass("jstree-er").addClass("jstree-ok")}b=!1,g.helper.find(".jstree-icon").removeClass("jstree-ok").addClass("jstree-er"),e.hide()}}).bind("dnd_scroll.vakata",function(a,c){c&&c.data&&c.data.jstree&&(e.hide(),b=!1,c.helper.find(".jstree-icon:eq(0)").removeClass("jstree-ok").addClass("jstree-er"))}).bind("dnd_stop.vakata",function(f,g){if(d&&clearTimeout(d),g&&g.data&&g.data.jstree){e.hide();var h,i,j=[];if(b){for(h=0,i=g.data.nodes.length;i>h;h++)j[h]=g.data.origin?g.data.origin.get_node(g.data.nodes[h]):g.data.nodes[h],g.data.origin&&(j[h].instance=g.data.origin);b.ins[g.data.origin&&(g.data.origin.settings.dnd.always_copy||g.data.origin.settings.dnd.copy&&(g.event.metaKey||g.event.ctrlKey))?"copy_node":"move_node"](j,b.par,b.pos)}else h=a(g.event.target).closest(".jstree"),h.length&&c&&c.error&&"check"===c.error&&(h=h.jstree(!0),h&&h.settings.core.error.call(this,c))}}).bind("keyup keydown",function(b,c){c=a.vakata.dnd._get(),c&&c.data&&c.data.jstree&&c.helper.find(".jstree-copy:eq(0)")[c.data.origin&&(c.data.origin.settings.dnd.always_copy||c.data.origin.settings.dnd.copy&&(b.metaKey||b.ctrlKey))?"show":"hide"]()})}),function(a){var b={element:!1,target:!1,is_down:!1,is_drag:!1,helper:!1,helper_w:0,data:!1,init_x:0,init_y:0,scroll_l:0,scroll_t:0,scroll_e:!1,scroll_i:!1,is_touch:!1};a.vakata.dnd={settings:{scroll_speed:10,scroll_proximity:20,helper_left:5,helper_top:10,threshold:5,threshold_touch:50},_trigger:function(b,c){var d=a.vakata.dnd._get();d.event=c,a(document).triggerHandler("dnd_"+b+".vakata",d)},_get:function(){return{data:b.data,element:b.element,helper:b.helper}},_clean:function(){b.helper&&b.helper.remove(),b.scroll_i&&(clearInterval(b.scroll_i),b.scroll_i=!1),b={element:!1,target:!1,is_down:!1,is_drag:!1,helper:!1,helper_w:0,data:!1,init_x:0,init_y:0,scroll_l:0,scroll_t:0,scroll_e:!1,scroll_i:!1,is_touch:!1},a(document).off("mousemove touchmove",a.vakata.dnd.drag),a(document).off("mouseup touchend",a.vakata.dnd.stop)},_scroll:function(c){if(!b.scroll_e||!b.scroll_l&&!b.scroll_t)return b.scroll_i&&(clearInterval(b.scroll_i),b.scroll_i=!1),!1;if(!b.scroll_i)return b.scroll_i=setInterval(a.vakata.dnd._scroll,100),!1;if(c===!0)return!1;var d=b.scroll_e.scrollTop(),e=b.scroll_e.scrollLeft();b.scroll_e.scrollTop(d+b.scroll_t*a.vakata.dnd.settings.scroll_speed),b.scroll_e.scrollLeft(e+b.scroll_l*a.vakata.dnd.settings.scroll_speed),(d!==b.scroll_e.scrollTop()||e!==b.scroll_e.scrollLeft())&&a.vakata.dnd._trigger("scroll",b.scroll_e)},start:function(c,d,e){"touchstart"===c.type&&c.originalEvent&&c.originalEvent.changedTouches&&c.originalEvent.changedTouches[0]&&(c.pageX=c.originalEvent.changedTouches[0].pageX,c.pageY=c.originalEvent.changedTouches[0].pageY,c.target=document.elementFromPoint(c.originalEvent.changedTouches[0].pageX-window.pageXOffset,c.originalEvent.changedTouches[0].pageY-window.pageYOffset)),b.is_drag&&a.vakata.dnd.stop({});try{c.currentTarget.unselectable="on",c.currentTarget.onselectstart=function(){return!1},c.currentTarget.style&&(c.currentTarget.style.MozUserSelect="none")}catch(f){}return b.init_x=c.pageX,b.init_y=c.pageY,b.data=d,b.is_down=!0,b.element=c.currentTarget,b.target=c.target,b.is_touch="touchstart"===c.type,e!==!1&&(b.helper=a("
        ").html(e).css({display:"block",margin:"0",padding:"0",position:"absolute",top:"-2000px",lineHeight:"16px",zIndex:"10000"})),a(document).bind("mousemove touchmove",a.vakata.dnd.drag),a(document).bind("mouseup touchend",a.vakata.dnd.stop),!1},drag:function(c){if("touchmove"===c.type&&c.originalEvent&&c.originalEvent.changedTouches&&c.originalEvent.changedTouches[0]&&(c.pageX=c.originalEvent.changedTouches[0].pageX,c.pageY=c.originalEvent.changedTouches[0].pageY,c.target=document.elementFromPoint(c.originalEvent.changedTouches[0].pageX-window.pageXOffset,c.originalEvent.changedTouches[0].pageY-window.pageYOffset)),b.is_down){if(!b.is_drag){if(!(Math.abs(c.pageX-b.init_x)>(b.is_touch?a.vakata.dnd.settings.threshold_touch:a.vakata.dnd.settings.threshold)||Math.abs(c.pageY-b.init_y)>(b.is_touch?a.vakata.dnd.settings.threshold_touch:a.vakata.dnd.settings.threshold)))return;b.helper&&(b.helper.appendTo("body"),b.helper_w=b.helper.outerWidth()),b.is_drag=!0,a.vakata.dnd._trigger("start",c)}var d=!1,e=!1,f=!1,g=!1,h=!1,i=!1,j=!1,k=!1,l=!1,m=!1;return b.scroll_t=0,b.scroll_l=0,b.scroll_e=!1,a(a(c.target).parentsUntil("body").addBack().get().reverse()).filter(function(){return/^auto|scroll$/.test(a(this).css("overflow"))&&(this.scrollHeight>this.offsetHeight||this.scrollWidth>this.offsetWidth)}).each(function(){var d=a(this),e=d.offset();return this.scrollHeight>this.offsetHeight&&(e.top+d.height()-c.pageYthis.offsetWidth&&(e.left+d.width()-c.pageXg&&c.pageY-jg&&g-(c.pageY-j)i&&c.pageX-ki&&i-(c.pageX-k)f&&(l=f-50),h&&m+b.helper_w>h&&(m=h-(b.helper_w+2)),b.helper.css({left:m+"px",top:l+"px"})),a.vakata.dnd._trigger("move",c),!1}},stop:function(c){if("touchend"===c.type&&c.originalEvent&&c.originalEvent.changedTouches&&c.originalEvent.changedTouches[0]&&(c.pageX=c.originalEvent.changedTouches[0].pageX,c.pageY=c.originalEvent.changedTouches[0].pageY,c.target=document.elementFromPoint(c.originalEvent.changedTouches[0].pageX-window.pageXOffset,c.originalEvent.changedTouches[0].pageY-window.pageYOffset)),b.is_drag)a.vakata.dnd._trigger("stop",c);else if("touchend"===c.type&&c.target===b.target){var d=setTimeout(function(){a(c.target).click()},100);a(c.target).one("click",function(){d&&clearTimeout(d)})}return a.vakata.dnd._clean(),!1}}}(a),a.jstree.defaults.search={ajax:!1,fuzzy:!1,case_sensitive:!1,show_only_matches:!1,close_opened_onclear:!0,search_leaves_only:!1,search_callback:!1},a.jstree.plugins.search=function(b,c){this.bind=function(){c.bind.call(this),this._data.search.str="",this._data.search.dom=a(),this._data.search.res=[],this._data.search.opn=[],this.element.on("before_open.jstree",a.proxy(function(){var b,c,d=this._data.search.res,e=[],f=a();if(d&&d.length&&(this._data.search.dom=a(this.element[0].querySelectorAll("#"+a.map(d,function(b){return-1!=="0123456789".indexOf(b[0])?"\\3"+b[0]+" "+b.substr(1).replace(a.jstree.idregex,"\\$&"):b.replace(a.jstree.idregex,"\\$&")}).join(", #"))),this._data.search.dom.children(".jstree-anchor").addClass("jstree-search"),this.settings.search.show_only_matches&&this._data.search.res.length)){for(b=0,c=d.length;c>b;b++)e=e.concat(this.get_node(d[b]).parents);e=a.vakata.array_remove_item(a.vakata.array_unique(e),"#"),f=e.length?a(this.element[0].querySelectorAll("#"+a.map(e,function(b){return-1!=="0123456789".indexOf(b[0])?"\\3"+b[0]+" "+b.substr(1).replace(a.jstree.idregex,"\\$&"):b.replace(a.jstree.idregex,"\\$&")}).join(", #"))):a(),this.element.find(".jstree-node").hide().filter(".jstree-last").filter(function(){return this.nextSibling}).removeClass("jstree-last"),f=f.add(this._data.search.dom),f.parentsUntil(".jstree").addBack().show().filter(".jstree-children").each(function(){a(this).children(".jstree-node:visible").eq(-1).addClass("jstree-last")})}},this)),this.settings.search.show_only_matches&&this.element.on("search.jstree",function(b,c){c.nodes.length&&(a(this).find(".jstree-node").hide().filter(".jstree-last").filter(function(){return this.nextSibling}).removeClass("jstree-last"),c.nodes.parentsUntil(".jstree").addBack().show().filter(".jstree-children").each(function(){a(this).children(".jstree-node:visible").eq(-1).addClass("jstree-last")}))}).on("clear_search.jstree",function(b,c){c.nodes.length&&a(this).find(".jstree-node").css("display","").filter(".jstree-last").filter(function(){return this.nextSibling}).removeClass("jstree-last")})},this.search=function(b,c){if(b===!1||""===a.trim(b.toString()))return this.clear_search();b=b.toString();var d=this.settings.search,e=d.ajax?d.ajax:!1,f=null,g=[],h=[];return this._data.search.res.length&&this.clear_search(),c||e===!1?(this._data.search.str=b,this._data.search.dom=a(),this._data.search.res=[],this._data.search.opn=[],f=new a.vakata.search(b,!0,{caseSensitive:d.case_sensitive,fuzzy:d.fuzzy}),a.each(this._model.data,function(a,c){c.text&&(d.search_callback&&d.search_callback.call(this,b,c)||!d.search_callback&&f.search(c.text).isMatch)&&(!d.search_leaves_only||c.state.loaded&&0===c.children.length)&&(g.push(a),h=h.concat(c.parents))}),g.length&&(h=a.vakata.array_unique(h),this._search_open(h),this._data.search.dom=a(this.element[0].querySelectorAll("#"+a.map(g,function(b){return-1!=="0123456789".indexOf(b[0])?"\\3"+b[0]+" "+b.substr(1).replace(a.jstree.idregex,"\\$&"):b.replace(a.jstree.idregex,"\\$&")}).join(", #"))),this._data.search.res=g,this._data.search.dom.children(".jstree-anchor").addClass("jstree-search")),void this.trigger("search",{nodes:this._data.search.dom,str:b,res:this._data.search.res})):a.isFunction(e)?e.call(this,b,a.proxy(function(c){c&&c.d&&(c=c.d),this._load_nodes(a.isArray(c)?a.vakata.array_unique(c):[],function(){this.search(b,!0)},!0)},this)):(e=a.extend({},e),e.data||(e.data={}),e.data.str=b,a.ajax(e).fail(a.proxy(function(){this._data.core.last_error={error:"ajax",plugin:"search",id:"search_01",reason:"Could not load search parents",data:JSON.stringify(e)},this.settings.core.error.call(this,this._data.core.last_error)},this)).done(a.proxy(function(c){c&&c.d&&(c=c.d),this._load_nodes(a.isArray(c)?a.vakata.array_unique(c):[],function(){this.search(b,!0)},!0)},this)))},this.clear_search=function(){this._data.search.dom.children(".jstree-anchor").removeClass("jstree-search"),this.settings.search.close_opened_onclear&&this.close_node(this._data.search.opn,0),this.trigger("clear_search",{nodes:this._data.search.dom,str:this._data.search.str,res:this._data.search.res}),this._data.search.str="",this._data.search.res=[], +this._data.search.opn=[],this._data.search.dom=a()},this._search_open=function(b){var c=this;a.each(b.concat([]),function(d,e){if("#"===e)return!0;try{e=a("#"+e.replace(a.jstree.idregex,"\\$&"),c.element)}catch(f){}e&&e.length&&c.is_closed(e)&&(c._data.search.opn.push(e[0].id),c.open_node(e,function(){c._search_open(b)},0))})}},function(a){a.vakata.search=function(a,b,c){c=c||{},c.fuzzy!==!1&&(c.fuzzy=!0),a=c.caseSensitive?a:a.toLowerCase();var d,e,f,g,h=c.location||0,i=c.distance||100,j=c.threshold||.6,k=a.length;return k>32&&(c.fuzzy=!1),c.fuzzy&&(d=1<c;c++)b[a.charAt(c)]=0;for(c=0;k>c;c++)b[a.charAt(c)]|=1<g;g++){for(l=0,m=v;m>l;)f(g,h+m)<=t?l=m:v=m,m=Math.floor((v-l)/2+l);for(v=m,o=Math.max(1,h-m+1),p=Math.min(h+m,s)+k,q=new Array(p+2),q[p+1]=(1<=o;i--)if(r=e[b.charAt(i-1)],q[i]=0===g?(q[i+1]<<1|1)&r:(q[i+1]<<1|1)&r|((n[i+1]|n[i])<<1|1)|n[i+1],q[i]&d&&(w=f(g,i-1),t>=w)){if(t=w,u=i-1,x.push(u),!(u>h))break;o=Math.max(1,2*h-u)}if(f(g+1,h)>t)break;n=q}return{isMatch:u>=0,score:w}},b===!0?{search:g}:g(b)}}(a),a.jstree.defaults.sort=function(a,b){return this.get_text(a)>this.get_text(b)?1:-1},a.jstree.plugins.sort=function(b,c){this.bind=function(){c.bind.call(this),this.element.on("model.jstree",a.proxy(function(a,b){this.sort(b.parent,!0)},this)).on("rename_node.jstree create_node.jstree",a.proxy(function(a,b){this.sort(b.parent||b.node.parent,!1),this.redraw_node(b.parent||b.node.parent,!0)},this)).on("move_node.jstree copy_node.jstree",a.proxy(function(a,b){this.sort(b.parent,!1),this.redraw_node(b.parent,!0)},this))},this.sort=function(b,c){var d,e;if(b=this.get_node(b),b&&b.children&&b.children.length&&(b.children.sort(a.proxy(this.settings.sort,this)),c))for(d=0,e=b.children_d.length;e>d;d++)this.sort(b.children_d[d],!1)}};var n=!1;a.jstree.defaults.state={key:"jstree",events:"changed.jstree open_node.jstree close_node.jstree",ttl:!1,filter:!1},a.jstree.plugins.state=function(b,c){this.bind=function(){c.bind.call(this);var b=a.proxy(function(){this.element.on(this.settings.state.events,a.proxy(function(){n&&clearTimeout(n),n=setTimeout(a.proxy(function(){this.save_state()},this),100)},this))},this);this.element.on("ready.jstree",a.proxy(function(){this.element.one("restore_state.jstree",b),this.restore_state()||b()},this))},this.save_state=function(){var b={state:this.get_state(),ttl:this.settings.state.ttl,sec:+new Date};a.vakata.storage.set(this.settings.state.key,JSON.stringify(b))},this.restore_state=function(){var b=a.vakata.storage.get(this.settings.state.key);if(b)try{b=JSON.parse(b)}catch(c){return!1}return b&&b.ttl&&b.sec&&+new Date-b.sec>b.ttl?!1:(b&&b.state&&(b=b.state),b&&a.isFunction(this.settings.state.filter)&&(b=this.settings.state.filter.call(this,b)),b?(this.element.one("set_state.jstree",function(c,d){d.instance.trigger("restore_state",{state:a.extend(!0,{},b)})}),this.set_state(b),!0):!1)},this.clear_state=function(){return a.vakata.storage.del(this.settings.state.key)}},function(a){a.vakata.storage={set:function(a,b){return window.localStorage.setItem(a,b)},get:function(a){return window.localStorage.getItem(a)},del:function(a){return window.localStorage.removeItem(a)}}}(a),a.jstree.defaults.types={"#":{},"default":{}},a.jstree.plugins.types=function(c,d){this.init=function(a,c){var e,f;if(c&&c.types&&c.types.default)for(e in c.types)if("default"!==e&&"#"!==e&&c.types.hasOwnProperty(e))for(f in c.types.default)c.types.default.hasOwnProperty(f)&&c.types[e][f]===b&&(c.types[e][f]=c.types.default[f]);d.init.call(this,a,c),this._model.data["#"].type="#"},this.refresh=function(a,b){d.refresh.call(this,a,b),this._model.data["#"].type="#"},this.bind=function(){this.element.on("model.jstree",a.proxy(function(a,c){var d,e,f=this._model.data,g=c.nodes,h=this.settings.types,i="default";for(d=0,e=g.length;e>d;d++)i="default",f[g[d]].original&&f[g[d]].original.type&&h[f[g[d]].original.type]&&(i=f[g[d]].original.type),f[g[d]].data&&f[g[d]].data.jstree&&f[g[d]].data.jstree.type&&h[f[g[d]].data.jstree.type]&&(i=f[g[d]].data.jstree.type),f[g[d]].type=i,f[g[d]].icon===!0&&h[i].icon!==b&&(f[g[d]].icon=h[i].icon);f["#"].type="#"},this)),d.bind.call(this)},this.get_json=function(b,c,e){var f,g,h=this._model.data,i=c?a.extend(!0,{},c,{no_id:!1}):{},j=d.get_json.call(this,b,i,e);if(j===!1)return!1;if(a.isArray(j))for(f=0,g=j.length;g>f;f++)j[f].type=j[f].id&&h[j[f].id]&&h[j[f].id].type?h[j[f].id].type:"default",c&&c.no_id&&(delete j[f].id,j[f].li_attr&&j[f].li_attr.id&&delete j[f].li_attr.id);else j.type=j.id&&h[j.id]&&h[j.id].type?h[j.id].type:"default",c&&c.no_id&&(j=this._delete_ids(j));return j},this._delete_ids=function(b){if(a.isArray(b)){for(var c=0,d=b.length;d>c;c++)b[c]=this._delete_ids(b[c]);return b}return delete b.id,b.li_attr&&b.li_attr.id&&delete b.li_attr.id,b.children&&a.isArray(b.children)&&(b.children=this._delete_ids(b.children)),b},this.check=function(c,e,f,g,h){if(d.check.call(this,c,e,f,g,h)===!1)return!1;e=e&&e.id?e:this.get_node(e),f=f&&f.id?f:this.get_node(f);var i,j,k,l,m=e&&e.id?a.jstree.reference(e.id):null;switch(m=m&&m._model&&m._model.data?m._model.data:null,c){case"create_node":case"move_node":case"copy_node":if("move_node"!==c||-1===a.inArray(e.id,f.children)){if(i=this.get_rules(f),i.max_children!==b&&-1!==i.max_children&&i.max_children===f.children.length)return this._data.core.last_error={error:"check",plugin:"types",id:"types_01",reason:"max_children prevents function: "+c,data:JSON.stringify({chk:c,pos:g,obj:e&&e.id?e.id:!1,par:f&&f.id?f.id:!1})},!1;if(i.valid_children!==b&&-1!==i.valid_children&&-1===a.inArray(e.type,i.valid_children))return this._data.core.last_error={error:"check",plugin:"types",id:"types_02",reason:"valid_children prevents function: "+c,data:JSON.stringify({chk:c,pos:g,obj:e&&e.id?e.id:!1,par:f&&f.id?f.id:!1})},!1;if(m&&e.children_d&&e.parents){for(j=0,k=0,l=e.children_d.length;l>k;k++)j=Math.max(j,m[e.children_d[k]].parents.length);j=j-e.parents.length+1}(0>=j||j===b)&&(j=1);do{if(i.max_depth!==b&&-1!==i.max_depth&&i.max_depthf;f++)this.set_type(c[f],d);return!0}return e=this.settings.types,c=this.get_node(c),e[d]&&c?(h=c.type,i=this.get_icon(c),c.type=d,(i===!0||e[h]&&e[h].icon&&i===e[h].icon)&&this.set_icon(c,e[d].icon!==b?e[d].icon:!0),!0):!1}},a.jstree.defaults.unique={case_sensitive:!1,duplicate:function(a,b){return a+" ("+b+")"}},a.jstree.plugins.unique=function(c,d){this.check=function(b,c,e,f,g){if(d.check.call(this,b,c,e,f,g)===!1)return!1;if(c=c&&c.id?c:this.get_node(c),e=e&&e.id?e:this.get_node(e),!e||!e.children)return!0;var h,i,j="rename_node"===b?f:c.text,k=[],l=this.settings.unique.case_sensitive,m=this._model.data;for(h=0,i=e.children.length;i>h;h++)k.push(l?m[e.children[h]].text:m[e.children[h]].text.toLowerCase());switch(l||(j=j.toLowerCase()),b){case"delete_node":return!0;case"rename_node":return h=-1===a.inArray(j,k)||c.text&&c.text[l?"toString":"toLowerCase"]()===j,h||(this._data.core.last_error={error:"check",plugin:"unique",id:"unique_01",reason:"Child with name "+j+" already exists. Preventing: "+b,data:JSON.stringify({chk:b,pos:f,obj:c&&c.id?c.id:!1,par:e&&e.id?e.id:!1})}),h;case"create_node":return h=-1===a.inArray(j,k),h||(this._data.core.last_error={error:"check",plugin:"unique",id:"unique_04",reason:"Child with name "+j+" already exists. Preventing: "+b,data:JSON.stringify({chk:b,pos:f,obj:c&&c.id?c.id:!1,par:e&&e.id?e.id:!1})}),h;case"copy_node":return h=-1===a.inArray(j,k),h||(this._data.core.last_error={error:"check",plugin:"unique",id:"unique_02",reason:"Child with name "+j+" already exists. Preventing: "+b,data:JSON.stringify({chk:b,pos:f,obj:c&&c.id?c.id:!1,par:e&&e.id?e.id:!1})}),h;case"move_node":return h=c.parent===e.id||-1===a.inArray(j,k),h||(this._data.core.last_error={error:"check",plugin:"unique",id:"unique_03",reason:"Child with name "+j+" already exists. Preventing: "+b,data:JSON.stringify({chk:b,pos:f,obj:c&&c.id?c.id:!1,par:e&&e.id?e.id:!1})}),h}return!0},this.create_node=function(c,e,f,g,h){if(!e||e.text===b){if(null===c&&(c="#"),c=this.get_node(c),!c)return d.create_node.call(this,c,e,f,g,h);if(f=f===b?"last":f,!f.toString().match(/^(before|after)$/)&&!h&&!this.is_loaded(c))return d.create_node.call(this,c,e,f,g,h);e||(e={});var i,j,k,l,m,n=this._model.data,o=this.settings.unique.case_sensitive,p=this.settings.unique.duplicate;for(j=i=this.get_string("New node"),k=[],l=0,m=c.children.length;m>l;l++)k.push(o?n[c.children[l]].text:n[c.children[l]].text.toLowerCase());for(l=1;-1!==a.inArray(o?j:j.toLowerCase(),k);)j=p.call(this,i,++l).toString();e.text=j}return d.create_node.call(this,c,e,f,g,h)}};var o=document.createElement("DIV");o.setAttribute("unselectable","on"),o.className="jstree-wholerow",o.innerHTML=" ",a.jstree.plugins.wholerow=function(b,c){this.bind=function(){c.bind.call(this),this.element.on("ready.jstree set_state.jstree",a.proxy(function(){this.hide_dots()},this)).on("init.jstree loading.jstree ready.jstree",a.proxy(function(){this.get_container_ul().addClass("jstree-wholerow-ul")},this)).on("deselect_all.jstree",a.proxy(function(){this.element.find(".jstree-wholerow-clicked").removeClass("jstree-wholerow-clicked")},this)).on("changed.jstree",a.proxy(function(a,b){this.element.find(".jstree-wholerow-clicked").removeClass("jstree-wholerow-clicked");var c,d,e=!1;for(c=0,d=b.selected.length;d>c;c++)e=this.get_node(b.selected[c],!0),e&&e.length&&e.children(".jstree-wholerow").addClass("jstree-wholerow-clicked")},this)).on("open_node.jstree",a.proxy(function(a,b){this.get_node(b.node,!0).find(".jstree-clicked").parent().children(".jstree-wholerow").addClass("jstree-wholerow-clicked")},this)).on("hover_node.jstree dehover_node.jstree",a.proxy(function(a,b){this.get_node(b.node,!0).children(".jstree-wholerow")["hover_node"===a.type?"addClass":"removeClass"]("jstree-wholerow-hovered")},this)).on("contextmenu.jstree",".jstree-wholerow",a.proxy(function(b){b.preventDefault();var c=a.Event("contextmenu",{metaKey:b.metaKey,ctrlKey:b.ctrlKey,altKey:b.altKey,shiftKey:b.shiftKey,pageX:b.pageX,pageY:b.pageY});a(b.currentTarget).closest(".jstree-node").children(".jstree-anchor:eq(0)").trigger(c)},this)).on("click.jstree",".jstree-wholerow",function(b){b.stopImmediatePropagation();var c=a.Event("click",{metaKey:b.metaKey,ctrlKey:b.ctrlKey,altKey:b.altKey,shiftKey:b.shiftKey});a(b.currentTarget).closest(".jstree-node").children(".jstree-anchor:eq(0)").trigger(c).focus()}).on("click.jstree",".jstree-leaf > .jstree-ocl",a.proxy(function(b){b.stopImmediatePropagation();var c=a.Event("click",{metaKey:b.metaKey,ctrlKey:b.ctrlKey,altKey:b.altKey,shiftKey:b.shiftKey});a(b.currentTarget).closest(".jstree-node").children(".jstree-anchor:eq(0)").trigger(c).focus()},this)).on("mouseover.jstree",".jstree-wholerow, .jstree-icon",a.proxy(function(a){return a.stopImmediatePropagation(),this.hover_node(a.currentTarget),!1},this)).on("mouseleave.jstree",".jstree-node",a.proxy(function(a){this.dehover_node(a.currentTarget)},this))},this.teardown=function(){this.settings.wholerow&&this.element.find(".jstree-wholerow").remove(),c.teardown.call(this)},this.redraw_node=function(b,d,e){if(b=c.redraw_node.call(this,b,d,e)){var f=o.cloneNode(!0);-1!==a.inArray(b.id,this._data.core.selected)&&(f.className+=" jstree-wholerow-clicked"),b.insertBefore(f,b.childNodes[0])}return b}}}}); +//# sourceMappingURL=../../../maps/libs/jquery/jstree.js.map \ No newline at end of file diff --git a/static/scripts/libs/jquery/select2.js b/static/scripts/libs/jquery/select2.js index 7116cd77288..2d4d533501e 100755 --- a/static/scripts/libs/jquery/select2.js +++ b/static/scripts/libs/jquery/select2.js @@ -1,3508 +1,4 @@ -/* -Copyright 2012 Igor Vaynberg +!function(a){"undefined"==typeof a.fn.each2&&a.extend(a.fn,{each2:function(b){for(var c=a([0]),d=-1,e=this.length;++dc;c+=1)if(g(a,b[c]))return c;return-1}function f(){var b=a(N);b.appendTo("body");var c={width:b.width()-b[0].clientWidth,height:b.height()-b[0].clientHeight};return b.remove(),c}function g(a,c){return a===c?!0:a===b||c===b?!1:null===a||null===c?!1:a.constructor===String?a+""==c+"":c.constructor===String?c+""==a+"":!1}function h(b,c){var d,e,f;if(null===b||b.length<1)return[];for(d=b.split(c),e=0,f=d.length;f>e;e+=1)d[e]=a.trim(d[e]);return d}function i(a){return a.outerWidth(!1)-a.width()}function j(c){var d="keyup-change-value";c.on("keydown",function(){a.data(c,d)===b&&a.data(c,d,c.val())}),c.on("keyup",function(){var e=a.data(c,d);e!==b&&c.val()!==e&&(a.removeData(c,d),c.trigger("keyup-change"))})}function k(c){c.on("mousemove",function(c){var d=M;(d===b||d.x!==c.pageX||d.y!==c.pageY)&&a(c.target).trigger("mousemove-filtered",c)})}function l(a,c,d){d=d||b;var e;return function(){var b=arguments;window.clearTimeout(e),e=window.setTimeout(function(){c.apply(d,b)},a)}}function m(a,b){var c=l(a,function(a){b.trigger("scroll-debounced",a)});b.on("scroll",function(a){e(a.target,b.get())>=0&&c(a)})}function n(a){a[0]!==document.activeElement&&window.setTimeout(function(){var b,c=a[0],d=a.val().length;a.focus();var e=c.offsetWidth>0||c.offsetHeight>0;e&&c===document.activeElement&&(c.setSelectionRange?c.setSelectionRange(d,d):c.createTextRange&&(b=c.createTextRange(),b.collapse(!1),b.select()))},0)}function o(b){b=a(b)[0];var c=0,d=0;if("selectionStart"in b)c=b.selectionStart,d=b.selectionEnd-c;else if("selection"in document){b.focus();var e=document.selection.createRange();d=document.selection.createRange().text.length,e.moveStart("character",-b.value.length),c=e.text.length-d}return{offset:c,length:d}}function p(a){a.preventDefault(),a.stopPropagation()}function q(a){a.preventDefault(),a.stopImmediatePropagation()}function r(b){if(!J){var c=b[0].currentStyle||window.getComputedStyle(b[0],null);J=a(document.createElement("div")).css({position:"absolute",left:"-10000px",top:"-10000px",display:"none",fontSize:c.fontSize,fontFamily:c.fontFamily,fontStyle:c.fontStyle,fontWeight:c.fontWeight,letterSpacing:c.letterSpacing,textTransform:c.textTransform,whiteSpace:"nowrap"}),J.attr("class","select2-sizer"),a("body").append(J)}return J.text(b.val()),J.width()}function s(b,c,d){var e,f,g=[];e=a.trim(b.attr("class")),e&&(e=""+e,a(e.split(/\s+/)).each2(function(){0===this.indexOf("select2-")&&g.push(this)})),e=a.trim(c.attr("class")),e&&(e=""+e,a(e.split(/\s+/)).each2(function(){0!==this.indexOf("select2-")&&(f=d(this),f&&g.push(f))})),b.attr("class",g.join(" "))}function t(a,b,c,e){var f=d(a.toUpperCase()).indexOf(d(b.toUpperCase())),g=b.length;return 0>f?void c.push(e(a)):(c.push(e(a.substring(0,f))),c.push(""),c.push(e(a.substring(f,f+g))),c.push(""),void c.push(e(a.substring(f+g,a.length))))}function u(a){var b={"\\":"\","&":"&","<":"<",">":">",'"':""","'":"'","/":"/"};return String(a).replace(/[&<>"'\/\\]/g,function(a){return b[a]})}function v(c){var d,e=null,f=c.quietMillis||100,g=c.url,h=this;return function(i){window.clearTimeout(d),d=window.setTimeout(function(){var d=c.data,f=g,j=c.transport||a.fn.select2.ajaxDefaults.transport,k={type:c.type||"GET",cache:c.cache||!1,jsonpCallback:c.jsonpCallback||b,dataType:c.dataType||"json"},l=a.extend({},a.fn.select2.ajaxDefaults.params,k);d=d?d.call(h,i.term,i.page,i.context):null,f="function"==typeof f?f.call(h,i.term,i.page,i.context):f,e&&"function"==typeof e.abort&&e.abort(),c.params&&(a.isFunction(c.params)?a.extend(l,c.params.call(h)):a.extend(l,c.params)),a.extend(l,{url:f,dataType:c.dataType,data:d,success:function(a){var b=c.results(a,i.page,i);i.callback(b)},error:function(a,b,c){var d={hasError:!0,jqXHR:a,textStatus:b,errorThrown:c};i.callback(d)}}),e=j.call(h,l)},f)}}function w(b){var c,d,e=b,f=function(a){return""+a.text};a.isArray(e)&&(d=e,e={results:d}),a.isFunction(e)===!1&&(d=e,e=function(){return d});var g=e();return g.text&&(f=g.text,a.isFunction(f)||(c=g.text,f=function(a){return a[c]})),function(b){var c,d=b.term,g={results:[]};return""===d?void b.callback(e()):(c=function(e,g){var h,i;if(e=e[0],e.children){h={};for(i in e)e.hasOwnProperty(i)&&(h[i]=e[i]);h.children=[],a(e.children).each2(function(a,b){c(b,h.children)}),(h.children.length||b.matcher(d,f(h),e))&&g.push(h)}else b.matcher(d,f(e),e)&&g.push(e)},a(e().results).each2(function(a,b){c(b,g.results)}),void b.callback(g))}}function x(c){var d=a.isFunction(c);return function(e){var f=e.term,g={results:[]},h=d?c(e):c;a.isArray(h)&&(a(h).each(function(){var a=this.text!==b,c=a?this.text:this;(""===f||e.matcher(f,c))&&g.results.push(a?this:{id:this,text:this})}),e.callback(g))}}function y(b,c){if(a.isFunction(b))return!0;if(!b)return!1;if("string"==typeof b)return!0;throw new Error(c+" must be a string, function, or falsy value")}function z(b,c){if(a.isFunction(b)){var d=Array.prototype.slice.call(arguments,2);return b.apply(c,d)}return b}function A(b){var c=0;return a.each(b,function(a,b){b.children?c+=A(b.children):c++}),c}function B(a,c,d,e){var f,h,i,j,k,l=a,m=!1;if(!e.createSearchChoice||!e.tokenSeparators||e.tokenSeparators.length<1)return b;for(;;){for(h=-1,i=0,j=e.tokenSeparators.length;j>i&&(k=e.tokenSeparators[i],h=a.indexOf(k),!(h>=0));i++);if(0>h)break;if(f=a.substring(0,h),a=a.substring(h+k.length),f.length>0&&(f=e.createSearchChoice.call(this,f,c),f!==b&&null!==f&&e.id(f)!==b&&null!==e.id(f))){for(m=!1,i=0,j=c.length;j>i;i++)if(g(e.id(f),e.id(c[i]))){m=!0;break}m||d(f)}}return l!==a?a:void 0}function C(){var b=this;a.each(arguments,function(a,c){b[c].remove(),b[c]=null})}function D(b,c){var d=function(){};return d.prototype=new b,d.prototype.constructor=d,d.prototype.parent=b.prototype,d.prototype=a.extend(d.prototype,c),d}if(window.Select2===b){var E,F,G,H,I,J,K,L,M={x:0,y:0},E={TAB:9,ENTER:13,ESC:27,SPACE:32,LEFT:37,UP:38,RIGHT:39,DOWN:40,SHIFT:16,CTRL:17,ALT:18,PAGE_UP:33,PAGE_DOWN:34,HOME:36,END:35,BACKSPACE:8,DELETE:46,isArrow:function(a){switch(a=a.which?a.which:a){case E.LEFT:case E.RIGHT:case E.UP:case E.DOWN:return!0}return!1},isControl:function(a){var b=a.which;switch(b){case E.SHIFT:case E.CTRL:case E.ALT:return!0}return a.metaKey?!0:!1},isFunctionKey:function(a){return a=a.which?a.which:a,a>=112&&123>=a}},N="
        ",O={"Ⓐ":"A","A":"A","À":"A","Á":"A","Â":"A","Ầ":"A","Ấ":"A","Ẫ":"A","Ẩ":"A","Ã":"A","Ā":"A","Ă":"A","Ằ":"A","Ắ":"A","Ẵ":"A","Ẳ":"A","Ȧ":"A","Ǡ":"A","Ä":"A","Ǟ":"A","Ả":"A","Å":"A","Ǻ":"A","Ǎ":"A","Ȁ":"A","Ȃ":"A","Ạ":"A","Ậ":"A","Ặ":"A","Ḁ":"A","Ą":"A","Ⱥ":"A","Ɐ":"A","Ꜳ":"AA","Æ":"AE","Ǽ":"AE","Ǣ":"AE","Ꜵ":"AO","Ꜷ":"AU","Ꜹ":"AV","Ꜻ":"AV","Ꜽ":"AY","Ⓑ":"B","B":"B","Ḃ":"B","Ḅ":"B","Ḇ":"B","Ƀ":"B","Ƃ":"B","Ɓ":"B","Ⓒ":"C","C":"C","Ć":"C","Ĉ":"C","Ċ":"C","Č":"C","Ç":"C","Ḉ":"C","Ƈ":"C","Ȼ":"C","Ꜿ":"C","Ⓓ":"D","D":"D","Ḋ":"D","Ď":"D","Ḍ":"D","Ḑ":"D","Ḓ":"D","Ḏ":"D","Đ":"D","Ƌ":"D","Ɗ":"D","Ɖ":"D","Ꝺ":"D","DZ":"DZ","DŽ":"DZ","Dz":"Dz","Dž":"Dz","Ⓔ":"E","E":"E","È":"E","É":"E","Ê":"E","Ề":"E","Ế":"E","Ễ":"E","Ể":"E","Ẽ":"E","Ē":"E","Ḕ":"E","Ḗ":"E","Ĕ":"E","Ė":"E","Ë":"E","Ẻ":"E","Ě":"E","Ȅ":"E","Ȇ":"E","Ẹ":"E","Ệ":"E","Ȩ":"E","Ḝ":"E","Ę":"E","Ḙ":"E","Ḛ":"E","Ɛ":"E","Ǝ":"E","Ⓕ":"F","F":"F","Ḟ":"F","Ƒ":"F","Ꝼ":"F","Ⓖ":"G","G":"G","Ǵ":"G","Ĝ":"G","Ḡ":"G","Ğ":"G","Ġ":"G","Ǧ":"G","Ģ":"G","Ǥ":"G","Ɠ":"G","Ꞡ":"G","Ᵹ":"G","Ꝿ":"G","Ⓗ":"H","H":"H","Ĥ":"H","Ḣ":"H","Ḧ":"H","Ȟ":"H","Ḥ":"H","Ḩ":"H","Ḫ":"H","Ħ":"H","Ⱨ":"H","Ⱶ":"H","Ɥ":"H","Ⓘ":"I","I":"I","Ì":"I","Í":"I","Î":"I","Ĩ":"I","Ī":"I","Ĭ":"I","İ":"I","Ï":"I","Ḯ":"I","Ỉ":"I","Ǐ":"I","Ȉ":"I","Ȋ":"I","Ị":"I","Į":"I","Ḭ":"I","Ɨ":"I","Ⓙ":"J","J":"J","Ĵ":"J","Ɉ":"J","Ⓚ":"K","K":"K","Ḱ":"K","Ǩ":"K","Ḳ":"K","Ķ":"K","Ḵ":"K","Ƙ":"K","Ⱪ":"K","Ꝁ":"K","Ꝃ":"K","Ꝅ":"K","Ꞣ":"K","Ⓛ":"L","L":"L","Ŀ":"L","Ĺ":"L","Ľ":"L","Ḷ":"L","Ḹ":"L","Ļ":"L","Ḽ":"L","Ḻ":"L","Ł":"L","Ƚ":"L","Ɫ":"L","Ⱡ":"L","Ꝉ":"L","Ꝇ":"L","Ꞁ":"L","LJ":"LJ","Lj":"Lj","Ⓜ":"M","M":"M","Ḿ":"M","Ṁ":"M","Ṃ":"M","Ɱ":"M","Ɯ":"M","Ⓝ":"N","N":"N","Ǹ":"N","Ń":"N","Ñ":"N","Ṅ":"N","Ň":"N","Ṇ":"N","Ņ":"N","Ṋ":"N","Ṉ":"N","Ƞ":"N","Ɲ":"N","Ꞑ":"N","Ꞥ":"N","NJ":"NJ","Nj":"Nj","Ⓞ":"O","O":"O","Ò":"O","Ó":"O","Ô":"O","Ồ":"O","Ố":"O","Ỗ":"O","Ổ":"O","Õ":"O","Ṍ":"O","Ȭ":"O","Ṏ":"O","Ō":"O","Ṑ":"O","Ṓ":"O","Ŏ":"O","Ȯ":"O","Ȱ":"O","Ö":"O","Ȫ":"O","Ỏ":"O","Ő":"O","Ǒ":"O","Ȍ":"O","Ȏ":"O","Ơ":"O","Ờ":"O","Ớ":"O","Ỡ":"O","Ở":"O","Ợ":"O","Ọ":"O","Ộ":"O","Ǫ":"O","Ǭ":"O","Ø":"O","Ǿ":"O","Ɔ":"O","Ɵ":"O","Ꝋ":"O","Ꝍ":"O","Ƣ":"OI","Ꝏ":"OO","Ȣ":"OU","Ⓟ":"P","P":"P","Ṕ":"P","Ṗ":"P","Ƥ":"P","Ᵽ":"P","Ꝑ":"P","Ꝓ":"P","Ꝕ":"P","Ⓠ":"Q","Q":"Q","Ꝗ":"Q","Ꝙ":"Q","Ɋ":"Q","Ⓡ":"R","R":"R","Ŕ":"R","Ṙ":"R","Ř":"R","Ȑ":"R","Ȓ":"R","Ṛ":"R","Ṝ":"R","Ŗ":"R","Ṟ":"R","Ɍ":"R","Ɽ":"R","Ꝛ":"R","Ꞧ":"R","Ꞃ":"R","Ⓢ":"S","S":"S","ẞ":"S","Ś":"S","Ṥ":"S","Ŝ":"S","Ṡ":"S","Š":"S","Ṧ":"S","Ṣ":"S","Ṩ":"S","Ș":"S","Ş":"S","Ȿ":"S","Ꞩ":"S","Ꞅ":"S","Ⓣ":"T","T":"T","Ṫ":"T","Ť":"T","Ṭ":"T","Ț":"T","Ţ":"T","Ṱ":"T","Ṯ":"T","Ŧ":"T","Ƭ":"T","Ʈ":"T","Ⱦ":"T","Ꞇ":"T","Ꜩ":"TZ","Ⓤ":"U","U":"U","Ù":"U","Ú":"U","Û":"U","Ũ":"U","Ṹ":"U","Ū":"U","Ṻ":"U","Ŭ":"U","Ü":"U","Ǜ":"U","Ǘ":"U","Ǖ":"U","Ǚ":"U","Ủ":"U","Ů":"U","Ű":"U","Ǔ":"U","Ȕ":"U","Ȗ":"U","Ư":"U","Ừ":"U","Ứ":"U","Ữ":"U","Ử":"U","Ự":"U","Ụ":"U","Ṳ":"U","Ų":"U","Ṷ":"U","Ṵ":"U","Ʉ":"U","Ⓥ":"V","V":"V","Ṽ":"V","Ṿ":"V","Ʋ":"V","Ꝟ":"V","Ʌ":"V","Ꝡ":"VY","Ⓦ":"W","W":"W","Ẁ":"W","Ẃ":"W","Ŵ":"W","Ẇ":"W","Ẅ":"W","Ẉ":"W","Ⱳ":"W","Ⓧ":"X","X":"X","Ẋ":"X","Ẍ":"X","Ⓨ":"Y","Y":"Y","Ỳ":"Y","Ý":"Y","Ŷ":"Y","Ỹ":"Y","Ȳ":"Y","Ẏ":"Y","Ÿ":"Y","Ỷ":"Y","Ỵ":"Y","Ƴ":"Y","Ɏ":"Y","Ỿ":"Y","Ⓩ":"Z","Z":"Z","Ź":"Z","Ẑ":"Z","Ż":"Z","Ž":"Z","Ẓ":"Z","Ẕ":"Z","Ƶ":"Z","Ȥ":"Z","Ɀ":"Z","Ⱬ":"Z","Ꝣ":"Z","ⓐ":"a","a":"a","ẚ":"a","à":"a","á":"a","â":"a","ầ":"a","ấ":"a","ẫ":"a","ẩ":"a","ã":"a","ā":"a","ă":"a","ằ":"a","ắ":"a","ẵ":"a","ẳ":"a","ȧ":"a","ǡ":"a","ä":"a","ǟ":"a","ả":"a","å":"a","ǻ":"a","ǎ":"a","ȁ":"a","ȃ":"a","ạ":"a","ậ":"a","ặ":"a","ḁ":"a","ą":"a","ⱥ":"a","ɐ":"a","ꜳ":"aa","æ":"ae","ǽ":"ae","ǣ":"ae","ꜵ":"ao","ꜷ":"au","ꜹ":"av","ꜻ":"av","ꜽ":"ay","ⓑ":"b","b":"b","ḃ":"b","ḅ":"b","ḇ":"b","ƀ":"b","ƃ":"b","ɓ":"b","ⓒ":"c","c":"c","ć":"c","ĉ":"c","ċ":"c","č":"c","ç":"c","ḉ":"c","ƈ":"c","ȼ":"c","ꜿ":"c","ↄ":"c","ⓓ":"d","d":"d","ḋ":"d","ď":"d","ḍ":"d","ḑ":"d","ḓ":"d","ḏ":"d","đ":"d","ƌ":"d","ɖ":"d","ɗ":"d","ꝺ":"d","dz":"dz","dž":"dz","ⓔ":"e","e":"e","è":"e","é":"e","ê":"e","ề":"e","ế":"e","ễ":"e","ể":"e","ẽ":"e","ē":"e","ḕ":"e","ḗ":"e","ĕ":"e","ė":"e","ë":"e","ẻ":"e","ě":"e","ȅ":"e","ȇ":"e","ẹ":"e","ệ":"e","ȩ":"e","ḝ":"e","ę":"e","ḙ":"e","ḛ":"e","ɇ":"e","ɛ":"e","ǝ":"e","ⓕ":"f","f":"f","ḟ":"f","ƒ":"f","ꝼ":"f","ⓖ":"g","g":"g","ǵ":"g","ĝ":"g","ḡ":"g","ğ":"g","ġ":"g","ǧ":"g","ģ":"g","ǥ":"g","ɠ":"g","ꞡ":"g","ᵹ":"g","ꝿ":"g","ⓗ":"h","h":"h","ĥ":"h","ḣ":"h","ḧ":"h","ȟ":"h","ḥ":"h","ḩ":"h","ḫ":"h","ẖ":"h","ħ":"h","ⱨ":"h","ⱶ":"h","ɥ":"h","ƕ":"hv","ⓘ":"i","i":"i","ì":"i","í":"i","î":"i","ĩ":"i","ī":"i","ĭ":"i","ï":"i","ḯ":"i","ỉ":"i","ǐ":"i","ȉ":"i","ȋ":"i","ị":"i","į":"i","ḭ":"i","ɨ":"i","ı":"i","ⓙ":"j","j":"j","ĵ":"j","ǰ":"j","ɉ":"j","ⓚ":"k","k":"k","ḱ":"k","ǩ":"k","ḳ":"k","ķ":"k","ḵ":"k","ƙ":"k","ⱪ":"k","ꝁ":"k","ꝃ":"k","ꝅ":"k","ꞣ":"k","ⓛ":"l","l":"l","ŀ":"l","ĺ":"l","ľ":"l","ḷ":"l","ḹ":"l","ļ":"l","ḽ":"l","ḻ":"l","ſ":"l","ł":"l","ƚ":"l","ɫ":"l","ⱡ":"l","ꝉ":"l","ꞁ":"l","ꝇ":"l","lj":"lj","ⓜ":"m","m":"m","ḿ":"m","ṁ":"m","ṃ":"m","ɱ":"m","ɯ":"m","ⓝ":"n","n":"n","ǹ":"n","ń":"n","ñ":"n","ṅ":"n","ň":"n","ṇ":"n","ņ":"n","ṋ":"n","ṉ":"n","ƞ":"n","ɲ":"n","ʼn":"n","ꞑ":"n","ꞥ":"n","nj":"nj","ⓞ":"o","o":"o","ò":"o","ó":"o","ô":"o","ồ":"o","ố":"o","ỗ":"o","ổ":"o","õ":"o","ṍ":"o","ȭ":"o","ṏ":"o","ō":"o","ṑ":"o","ṓ":"o","ŏ":"o","ȯ":"o","ȱ":"o","ö":"o","ȫ":"o","ỏ":"o","ő":"o","ǒ":"o","ȍ":"o","ȏ":"o","ơ":"o","ờ":"o","ớ":"o","ỡ":"o","ở":"o","ợ":"o","ọ":"o","ộ":"o","ǫ":"o","ǭ":"o","ø":"o","ǿ":"o","ɔ":"o","ꝋ":"o","ꝍ":"o","ɵ":"o","ƣ":"oi","ȣ":"ou","ꝏ":"oo","ⓟ":"p","p":"p","ṕ":"p","ṗ":"p","ƥ":"p","ᵽ":"p","ꝑ":"p","ꝓ":"p","ꝕ":"p","ⓠ":"q","q":"q","ɋ":"q","ꝗ":"q","ꝙ":"q","ⓡ":"r","r":"r","ŕ":"r","ṙ":"r","ř":"r","ȑ":"r","ȓ":"r","ṛ":"r","ṝ":"r","ŗ":"r","ṟ":"r","ɍ":"r","ɽ":"r","ꝛ":"r","ꞧ":"r","ꞃ":"r","ⓢ":"s","s":"s","ß":"s","ś":"s","ṥ":"s","ŝ":"s","ṡ":"s","š":"s","ṧ":"s","ṣ":"s","ṩ":"s","ș":"s","ş":"s","ȿ":"s","ꞩ":"s","ꞅ":"s","ẛ":"s","ⓣ":"t","t":"t","ṫ":"t","ẗ":"t","ť":"t","ṭ":"t","ț":"t","ţ":"t","ṱ":"t","ṯ":"t","ŧ":"t","ƭ":"t","ʈ":"t","ⱦ":"t","ꞇ":"t","ꜩ":"tz","ⓤ":"u","u":"u","ù":"u","ú":"u","û":"u","ũ":"u","ṹ":"u","ū":"u","ṻ":"u","ŭ":"u","ü":"u","ǜ":"u","ǘ":"u","ǖ":"u","ǚ":"u","ủ":"u","ů":"u","ű":"u","ǔ":"u","ȕ":"u","ȗ":"u","ư":"u","ừ":"u","ứ":"u","ữ":"u","ử":"u","ự":"u","ụ":"u","ṳ":"u","ų":"u","ṷ":"u","ṵ":"u","ʉ":"u","ⓥ":"v","v":"v","ṽ":"v","ṿ":"v","ʋ":"v","ꝟ":"v","ʌ":"v","ꝡ":"vy","ⓦ":"w","w":"w","ẁ":"w","ẃ":"w","ŵ":"w","ẇ":"w","ẅ":"w","ẘ":"w","ẉ":"w","ⱳ":"w","ⓧ":"x","x":"x","ẋ":"x","ẍ":"x","ⓨ":"y","y":"y","ỳ":"y","ý":"y","ŷ":"y","ỹ":"y","ȳ":"y","ẏ":"y","ÿ":"y","ỷ":"y","ẙ":"y","ỵ":"y","ƴ":"y","ɏ":"y","ỿ":"y","ⓩ":"z","z":"z","ź":"z","ẑ":"z","ż":"z","ž":"z","ẓ":"z","ẕ":"z","ƶ":"z","ȥ":"z","ɀ":"z","ⱬ":"z","ꝣ":"z","Ά":"Α","Έ":"Ε","Ή":"Η","Ί":"Ι","Ϊ":"Ι","Ό":"Ο","Ύ":"Υ","Ϋ":"Υ","Ώ":"Ω","ά":"α","έ":"ε","ή":"η","ί":"ι","ϊ":"ι","ΐ":"ι","ό":"ο","ύ":"υ","ϋ":"υ","ΰ":"υ","ω":"ω","ς":"σ"};K=a(document),I=function(){var a=1;return function(){return a++}}(),F=D(Object,{bind:function(a){var b=this;return function(){a.apply(b,arguments)}},init:function(c){var d,e,g=".select2-results";this.opts=c=this.prepareOpts(c),this.id=c.id,c.element.data("select2")!==b&&null!==c.element.data("select2")&&c.element.data("select2").destroy(),this.container=this.createContainer(),this.liveRegion=a("",{role:"status","aria-live":"polite"}).addClass("select2-hidden-accessible").appendTo(document.body),this.containerId="s2id_"+(c.element.attr("id")||"autogen"+I()),this.containerEventName=this.containerId.replace(/([.])/g,"_").replace(/([;&,\-\.\+\*\~':"\!\^#$%@\[\]\(\)=>\|])/g,"\\$1"),this.container.attr("id",this.containerId),this.container.attr("title",c.element.attr("title")),this.body=a("body"),s(this.container,this.opts.element,this.opts.adaptContainerCssClass),this.container.attr("style",c.element.attr("style")),this.container.css(z(c.containerCss,this.opts.element)),this.container.addClass(z(c.containerCssClass,this.opts.element)),this.elementTabIndex=this.opts.element.attr("tabindex"),this.opts.element.data("select2",this).attr("tabindex","-1").before(this.container).on("click.select2",p),this.container.data("select2",this),this.dropdown=this.container.find(".select2-drop"),s(this.dropdown,this.opts.element,this.opts.adaptDropdownCssClass),this.dropdown.addClass(z(c.dropdownCssClass,this.opts.element)),this.dropdown.data("select2",this),this.dropdown.on("click",p),this.results=d=this.container.find(g),this.search=e=this.container.find("input.select2-input"),this.queryCount=0,this.resultsPage=0,this.context=null,this.initContainer(),this.container.on("click",p),k(this.results),this.dropdown.on("mousemove-filtered",g,this.bind(this.highlightUnderEvent)),this.dropdown.on("touchstart touchmove touchend",g,this.bind(function(a){this._touchEvent=!0,this.highlightUnderEvent(a)})),this.dropdown.on("touchmove",g,this.bind(this.touchMoved)),this.dropdown.on("touchstart touchend",g,this.bind(this.clearTouchMoved)),this.dropdown.on("click",this.bind(function(){this._touchEvent&&(this._touchEvent=!1,this.selectHighlighted())})),m(80,this.results),this.dropdown.on("scroll-debounced",g,this.bind(this.loadMoreIfNeeded)),a(this.container).on("change",".select2-input",function(a){a.stopPropagation()}),a(this.dropdown).on("change",".select2-input",function(a){a.stopPropagation()}),a.fn.mousewheel&&d.mousewheel(function(a,b,c,e){var f=d.scrollTop();e>0&&0>=f-e?(d.scrollTop(0),p(a)):0>e&&d.get(0).scrollHeight-d.scrollTop()+e<=d.height()&&(d.scrollTop(d.get(0).scrollHeight-d.height()),p(a))}),j(e),e.on("keyup-change input paste",this.bind(this.updateResults)),e.on("focus",function(){e.addClass("select2-focused")}),e.on("blur",function(){e.removeClass("select2-focused")}),this.dropdown.on("mouseup",g,this.bind(function(b){a(b.target).closest(".select2-result-selectable").length>0&&(this.highlightUnderEvent(b),this.selectHighlighted(b))})),this.dropdown.on("click mouseup mousedown touchstart touchend focusin",function(a){a.stopPropagation()}),this.nextSearchTerm=b,a.isFunction(this.opts.initSelection)&&(this.initSelection(),this.monitorSource()),null!==c.maximumInputLength&&this.search.attr("maxlength",c.maximumInputLength);var h=c.element.prop("disabled");h===b&&(h=!1),this.enable(!h);var i=c.element.prop("readonly");i===b&&(i=!1),this.readonly(i),L=L||f(),this.autofocus=c.element.prop("autofocus"),c.element.prop("autofocus",!1),this.autofocus&&this.focus(),this.search.attr("placeholder",c.searchInputPlaceholder)},destroy:function(){var a=this.opts.element,c=a.data("select2"),d=this;this.close(),a.length&&a[0].detachEvent&&a.each(function(){this.detachEvent("onpropertychange",d._sync)}),this.propertyObserver&&(this.propertyObserver.disconnect(),this.propertyObserver=null),this._sync=null,c!==b&&(c.container.remove(),c.liveRegion.remove(),c.dropdown.remove(),a.removeClass("select2-offscreen").removeData("select2").off(".select2").prop("autofocus",this.autofocus||!1),this.elementTabIndex?a.attr({tabindex:this.elementTabIndex}):a.removeAttr("tabindex"),a.show()),C.call(this,"container","liveRegion","dropdown","results","search")},optionToData:function(a){return a.is("option")?{id:a.prop("value"),text:a.text(),element:a.get(),css:a.attr("class"),disabled:a.prop("disabled"),locked:g(a.attr("locked"),"locked")||g(a.data("locked"),!0)}:a.is("optgroup")?{text:a.attr("label"),children:[],element:a.get(),css:a.attr("class")}:void 0},prepareOpts:function(c){var d,e,f,i,j=this;if(d=c.element,"select"===d.get(0).tagName.toLowerCase()&&(this.select=e=c.element),e&&a.each(["id","multiple","ajax","query","createSearchChoice","initSelection","data","tags"],function(){if(this in c)throw new Error("Option '"+this+"' is not allowed for Select2 when attached to a element."); - } - }); - } - - opts = $.extend({}, { - populateResults: function(container, results, query) { - var populate, id=this.opts.id, liveRegion=this.liveRegion; - - populate=function(results, container, depth) { - - var i, l, result, selectable, disabled, compound, node, label, innerContainer, formatted; - - results = opts.sortResults(results, container, query); - - // collect the created nodes for bulk append - var nodes = []; - for (i = 0, l = results.length; i < l; i = i + 1) { - - result=results[i]; - - disabled = (result.disabled === true); - selectable = (!disabled) && (id(result) !== undefined); - - compound=result.children && result.children.length > 0; - - node=$("
      • "); - node.addClass("select2-results-dept-"+depth); - node.addClass("select2-result"); - node.addClass(selectable ? "select2-result-selectable" : "select2-result-unselectable"); - if (disabled) { node.addClass("select2-disabled"); } - if (compound) { node.addClass("select2-result-with-children"); } - node.addClass(self.opts.formatResultCssClass(result)); - node.attr("role", "presentation"); - - label=$(document.createElement("div")); - label.addClass("select2-result-label"); - label.attr("id", "select2-result-label-" + nextUid()); - label.attr("role", "option"); - - formatted=opts.formatResult(result, label, query, self.opts.escapeMarkup); - if (formatted!==undefined) { - label.html(formatted); - node.append(label); - } - - - if (compound) { - - innerContainer=$("
          "); - innerContainer.addClass("select2-result-sub"); - populate(result.children, innerContainer, depth+1); - node.append(innerContainer); - } - - node.data("select2-data", result); - nodes.push(node[0]); - } - - // bulk append the created nodes - container.append(nodes); - liveRegion.text(opts.formatMatches(results.length)); - }; - - populate(results, container, 0); - } - }, $.fn.select2.defaults, opts); - - if (typeof(opts.id) !== "function") { - idKey = opts.id; - opts.id = function (e) { return e[idKey]; }; - } - - if ($.isArray(opts.element.data("select2Tags"))) { - if ("tags" in opts) { - throw "tags specified as both an attribute 'data-select2-tags' and in options of Select2 " + opts.element.attr("id"); - } - opts.tags=opts.element.data("select2Tags"); - } - - if (select) { - opts.query = this.bind(function (query) { - var data = { results: [], more: false }, - term = query.term, - children, placeholderOption, process; - - process=function(element, collection) { - var group; - if (element.is("option")) { - if (query.matcher(term, element.text(), element)) { - collection.push(self.optionToData(element)); - } - } else if (element.is("optgroup")) { - group=self.optionToData(element); - element.children().each2(function(i, elm) { process(elm, group.children); }); - if (group.children.length>0) { - collection.push(group); - } - } - }; - - children=element.children(); - - // ignore the placeholder option if there is one - if (this.getPlaceholder() !== undefined && children.length > 0) { - placeholderOption = this.getPlaceholderOption(); - if (placeholderOption) { - children=children.not(placeholderOption); - } - } - - children.each2(function(i, elm) { process(elm, data.results); }); - - query.callback(data); - }); - // this is needed because inside val() we construct choices from options and their id is hardcoded - opts.id=function(e) { return e.id; }; - } else { - if (!("query" in opts)) { - - if ("ajax" in opts) { - ajaxUrl = opts.element.data("ajax-url"); - if (ajaxUrl && ajaxUrl.length > 0) { - opts.ajax.url = ajaxUrl; - } - opts.query = ajax.call(opts.element, opts.ajax); - } else if ("data" in opts) { - opts.query = local(opts.data); - } else if ("tags" in opts) { - opts.query = tags(opts.tags); - if (opts.createSearchChoice === undefined) { - opts.createSearchChoice = function (term) { return {id: $.trim(term), text: $.trim(term)}; }; - } - if (opts.initSelection === undefined) { - opts.initSelection = function (element, callback) { - var data = []; - $(splitVal(element.val(), opts.separator)).each(function () { - var obj = { id: this, text: this }, - tags = opts.tags; - if ($.isFunction(tags)) tags=tags(); - $(tags).each(function() { if (equal(this.id, obj.id)) { obj = this; return false; } }); - data.push(obj); - }); - - callback(data); - }; - } - } - } - } - if (typeof(opts.query) !== "function") { - throw "query function not defined for Select2 " + opts.element.attr("id"); - } - - if (opts.createSearchChoicePosition === 'top') { - opts.createSearchChoicePosition = function(list, item) { list.unshift(item); }; - } - else if (opts.createSearchChoicePosition === 'bottom') { - opts.createSearchChoicePosition = function(list, item) { list.push(item); }; - } - else if (typeof(opts.createSearchChoicePosition) !== "function") { - throw "invalid createSearchChoicePosition option must be 'top', 'bottom' or a custom function"; - } - - return opts; - }, - - /** - * Monitor the original element for changes and update select2 accordingly - */ - // abstract - monitorSource: function () { - var el = this.opts.element, observer, self = this; - - el.on("change.select2", this.bind(function (e) { - if (this.opts.element.data("select2-change-triggered") !== true) { - this.initSelection(); - } - })); - - this._sync = this.bind(function () { - - // sync enabled state - var disabled = el.prop("disabled"); - if (disabled === undefined) disabled = false; - this.enable(!disabled); - - var readonly = el.prop("readonly"); - if (readonly === undefined) readonly = false; - this.readonly(readonly); - - syncCssClasses(this.container, this.opts.element, this.opts.adaptContainerCssClass); - this.container.addClass(evaluate(this.opts.containerCssClass, this.opts.element)); - - syncCssClasses(this.dropdown, this.opts.element, this.opts.adaptDropdownCssClass); - this.dropdown.addClass(evaluate(this.opts.dropdownCssClass, this.opts.element)); - - }); - - // IE8-10 (IE9/10 won't fire propertyChange via attachEventListener) - if (el.length && el[0].attachEvent) { - el.each(function() { - this.attachEvent("onpropertychange", self._sync); - }); - } - - // safari, chrome, firefox, IE11 - observer = window.MutationObserver || window.WebKitMutationObserver|| window.MozMutationObserver; - if (observer !== undefined) { - if (this.propertyObserver) { delete this.propertyObserver; this.propertyObserver = null; } - this.propertyObserver = new observer(function (mutations) { - $.each(mutations, self._sync); - }); - this.propertyObserver.observe(el.get(0), { attributes:true, subtree:false }); - } - }, - - // abstract - triggerSelect: function(data) { - var evt = $.Event("select2-selecting", { val: this.id(data), object: data, choice: data }); - this.opts.element.trigger(evt); - return !evt.isDefaultPrevented(); - }, - - /** - * Triggers the change event on the source element - */ - // abstract - triggerChange: function (details) { - - details = details || {}; - details= $.extend({}, details, { type: "change", val: this.val() }); - // prevents recursive triggering - this.opts.element.data("select2-change-triggered", true); - this.opts.element.trigger(details); - this.opts.element.data("select2-change-triggered", false); - - // some validation frameworks ignore the change event and listen instead to keyup, click for selects - // so here we trigger the click event manually - this.opts.element.click(); - - // ValidationEngine ignores the change event and listens instead to blur - // so here we trigger the blur event manually if so desired - if (this.opts.blurOnChange) - this.opts.element.blur(); - }, - - //abstract - isInterfaceEnabled: function() - { - return this.enabledInterface === true; - }, - - // abstract - enableInterface: function() { - var enabled = this._enabled && !this._readonly, - disabled = !enabled; - - if (enabled === this.enabledInterface) return false; - - this.container.toggleClass("select2-container-disabled", disabled); - this.close(); - this.enabledInterface = enabled; - - return true; - }, - - // abstract - enable: function(enabled) { - if (enabled === undefined) enabled = true; - if (this._enabled === enabled) return; - this._enabled = enabled; - - this.opts.element.prop("disabled", !enabled); - this.enableInterface(); - }, - - // abstract - disable: function() { - this.enable(false); - }, - - // abstract - readonly: function(enabled) { - if (enabled === undefined) enabled = false; - if (this._readonly === enabled) return; - this._readonly = enabled; - - this.opts.element.prop("readonly", enabled); - this.enableInterface(); - }, - - // abstract - opened: function () { - return (this.container) ? this.container.hasClass("select2-dropdown-open") : false; - }, - - // abstract - positionDropdown: function() { - var $dropdown = this.dropdown, - offset = this.container.offset(), - height = this.container.outerHeight(false), - width = this.container.outerWidth(false), - dropHeight = $dropdown.outerHeight(false), - $window = $(window), - windowWidth = $window.width(), - windowHeight = $window.height(), - viewPortRight = $window.scrollLeft() + windowWidth, - viewportBottom = $window.scrollTop() + windowHeight, - dropTop = offset.top + height, - dropLeft = offset.left, - enoughRoomBelow = dropTop + dropHeight <= viewportBottom, - enoughRoomAbove = (offset.top - dropHeight) >= $window.scrollTop(), - dropWidth = $dropdown.outerWidth(false), - enoughRoomOnRight = dropLeft + dropWidth <= viewPortRight, - aboveNow = $dropdown.hasClass("select2-drop-above"), - bodyOffset, - above, - changeDirection, - css, - resultsListNode; - - // always prefer the current above/below alignment, unless there is not enough room - if (aboveNow) { - above = true; - if (!enoughRoomAbove && enoughRoomBelow) { - changeDirection = true; - above = false; - } - } else { - above = false; - if (!enoughRoomBelow && enoughRoomAbove) { - changeDirection = true; - above = true; - } - } - - //if we are changing direction we need to get positions when dropdown is hidden; - if (changeDirection) { - $dropdown.hide(); - offset = this.container.offset(); - height = this.container.outerHeight(false); - width = this.container.outerWidth(false); - dropHeight = $dropdown.outerHeight(false); - viewPortRight = $window.scrollLeft() + windowWidth; - viewportBottom = $window.scrollTop() + windowHeight; - dropTop = offset.top + height; - dropLeft = offset.left; - dropWidth = $dropdown.outerWidth(false); - enoughRoomOnRight = dropLeft + dropWidth <= viewPortRight; - $dropdown.show(); - - // fix so the cursor does not move to the left within the search-textbox in IE - this.focusSearch(); - } - - if (this.opts.dropdownAutoWidth) { - resultsListNode = $('.select2-results', $dropdown)[0]; - $dropdown.addClass('select2-drop-auto-width'); - $dropdown.css('width', ''); - // Add scrollbar width to dropdown if vertical scrollbar is present - dropWidth = $dropdown.outerWidth(false) + (resultsListNode.scrollHeight === resultsListNode.clientHeight ? 0 : scrollBarDimensions.width); - dropWidth > width ? width = dropWidth : dropWidth = width; - dropHeight = $dropdown.outerHeight(false); - enoughRoomOnRight = dropLeft + dropWidth <= viewPortRight; - } - else { - this.container.removeClass('select2-drop-auto-width'); - } - - //console.log("below/ droptop:", dropTop, "dropHeight", dropHeight, "sum", (dropTop+dropHeight)+" viewport bottom", viewportBottom, "enough?", enoughRoomBelow); - //console.log("above/ offset.top", offset.top, "dropHeight", dropHeight, "top", (offset.top-dropHeight), "scrollTop", this.body.scrollTop(), "enough?", enoughRoomAbove); - - // fix positioning when body has an offset and is not position: static - if (this.body.css('position') !== 'static') { - bodyOffset = this.body.offset(); - dropTop -= bodyOffset.top; - dropLeft -= bodyOffset.left; - } - - if (!enoughRoomOnRight) { - dropLeft = offset.left + this.container.outerWidth(false) - dropWidth; - } - - css = { - left: dropLeft, - width: width - }; - - if (above) { - css.top = offset.top - dropHeight; - css.bottom = 'auto'; - this.container.addClass("select2-drop-above"); - $dropdown.addClass("select2-drop-above"); - } - else { - css.top = dropTop; - css.bottom = 'auto'; - this.container.removeClass("select2-drop-above"); - $dropdown.removeClass("select2-drop-above"); - } - css = $.extend(css, evaluate(this.opts.dropdownCss, this.opts.element)); - - $dropdown.css(css); - }, - - // abstract - shouldOpen: function() { - var event; - - if (this.opened()) return false; - - if (this._enabled === false || this._readonly === true) return false; - - event = $.Event("select2-opening"); - this.opts.element.trigger(event); - return !event.isDefaultPrevented(); - }, - - // abstract - clearDropdownAlignmentPreference: function() { - // clear the classes used to figure out the preference of where the dropdown should be opened - this.container.removeClass("select2-drop-above"); - this.dropdown.removeClass("select2-drop-above"); - }, - - /** - * Opens the dropdown - * - * @return {Boolean} whether or not dropdown was opened. This method will return false if, for example, - * the dropdown is already open, or if the 'open' event listener on the element called preventDefault(). - */ - // abstract - open: function () { - - if (!this.shouldOpen()) return false; - - this.opening(); - - // Only bind the document mousemove when the dropdown is visible - $document.on("mousemove.select2Event", function (e) { - lastMousePosition.x = e.pageX; - lastMousePosition.y = e.pageY; - }); - - return true; - }, - - /** - * Performs the opening of the dropdown - */ - // abstract - opening: function() { - var cid = this.containerEventName, - scroll = "scroll." + cid, - resize = "resize."+cid, - orient = "orientationchange."+cid, - mask; - - this.container.addClass("select2-dropdown-open").addClass("select2-container-active"); - - this.clearDropdownAlignmentPreference(); - - if(this.dropdown[0] !== this.body.children().last()[0]) { - this.dropdown.detach().appendTo(this.body); - } - - // create the dropdown mask if doesn't already exist - mask = $("#select2-drop-mask"); - if (mask.length == 0) { - mask = $(document.createElement("div")); - mask.attr("id","select2-drop-mask").attr("class","select2-drop-mask"); - mask.hide(); - mask.appendTo(this.body); - mask.on("mousedown touchstart click", function (e) { - // Prevent IE from generating a click event on the body - reinsertElement(mask); - - var dropdown = $("#select2-drop"), self; - if (dropdown.length > 0) { - self=dropdown.data("select2"); - if (self.opts.selectOnBlur) { - self.selectHighlighted({noFocus: true}); - } - self.close(); - e.preventDefault(); - e.stopPropagation(); - } - }); - } - - // ensure the mask is always right before the dropdown - if (this.dropdown.prev()[0] !== mask[0]) { - this.dropdown.before(mask); - } - - // move the global id to the correct dropdown - $("#select2-drop").removeAttr("id"); - this.dropdown.attr("id", "select2-drop"); - - // show the elements - mask.show(); - - this.positionDropdown(); - this.dropdown.show(); - this.positionDropdown(); - - this.dropdown.addClass("select2-drop-active"); - - // attach listeners to events that can change the position of the container and thus require - // the position of the dropdown to be updated as well so it does not come unglued from the container - var that = this; - this.container.parents().add(window).each(function () { - $(this).on(resize+" "+scroll+" "+orient, function (e) { - if (that.opened()) that.positionDropdown(); - }); - }); - - - }, - - // abstract - close: function () { - if (!this.opened()) return; - - var cid = this.containerEventName, - scroll = "scroll." + cid, - resize = "resize."+cid, - orient = "orientationchange."+cid; - - // unbind event listeners - this.container.parents().add(window).each(function () { $(this).off(scroll).off(resize).off(orient); }); - - this.clearDropdownAlignmentPreference(); - - $("#select2-drop-mask").hide(); - this.dropdown.removeAttr("id"); // only the active dropdown has the select2-drop id - this.dropdown.hide(); - this.container.removeClass("select2-dropdown-open").removeClass("select2-container-active"); - this.results.empty(); - - // Now that the dropdown is closed, unbind the global document mousemove event - $document.off("mousemove.select2Event"); - - this.clearSearch(); - this.search.removeClass("select2-active"); - this.opts.element.trigger($.Event("select2-close")); - }, - - /** - * Opens control, sets input value, and updates results. - */ - // abstract - externalSearch: function (term) { - this.open(); - this.search.val(term); - this.updateResults(false); - }, - - // abstract - clearSearch: function () { - - }, - - //abstract - getMaximumSelectionSize: function() { - return evaluate(this.opts.maximumSelectionSize, this.opts.element); - }, - - // abstract - ensureHighlightVisible: function () { - var results = this.results, children, index, child, hb, rb, y, more, topOffset; - - index = this.highlight(); - - if (index < 0) return; - - if (index == 0) { - - // if the first element is highlighted scroll all the way to the top, - // that way any unselectable headers above it will also be scrolled - // into view - - results.scrollTop(0); - return; - } - - children = this.findHighlightableChoices().find('.select2-result-label'); - - child = $(children[index]); - - topOffset = (child.offset() || {}).top || 0; - - hb = topOffset + child.outerHeight(true); - - // if this is the last child lets also make sure select2-more-results is visible - if (index === children.length - 1) { - more = results.find("li.select2-more-results"); - if (more.length > 0) { - hb = more.offset().top + more.outerHeight(true); - } - } - - rb = results.offset().top + results.outerHeight(true); - if (hb > rb) { - results.scrollTop(results.scrollTop() + (hb - rb)); - } - y = topOffset - results.offset().top; - - // make sure the top of the element is visible - if (y < 0 && child.css('display') != 'none' ) { - results.scrollTop(results.scrollTop() + y); // y is negative - } - }, - - // abstract - findHighlightableChoices: function() { - return this.results.find(".select2-result-selectable:not(.select2-disabled):not(.select2-selected)"); - }, - - // abstract - moveHighlight: function (delta) { - var choices = this.findHighlightableChoices(), - index = this.highlight(); - - while (index > -1 && index < choices.length) { - index += delta; - var choice = $(choices[index]); - if (choice.hasClass("select2-result-selectable") && !choice.hasClass("select2-disabled") && !choice.hasClass("select2-selected")) { - this.highlight(index); - break; - } - } - }, - - // abstract - highlight: function (index) { - var choices = this.findHighlightableChoices(), - choice, - data; - - if (arguments.length === 0) { - return indexOf(choices.filter(".select2-highlighted")[0], choices.get()); - } - - if (index >= choices.length) index = choices.length - 1; - if (index < 0) index = 0; - - this.removeHighlight(); - - choice = $(choices[index]); - choice.addClass("select2-highlighted"); - - // ensure assistive technology can determine the active choice - this.search.attr("aria-activedescendant", choice.find(".select2-result-label").attr("id")); - - this.ensureHighlightVisible(); - - this.liveRegion.text(choice.text()); - - data = choice.data("select2-data"); - if (data) { - this.opts.element.trigger({ type: "select2-highlight", val: this.id(data), choice: data }); - } - }, - - removeHighlight: function() { - this.results.find(".select2-highlighted").removeClass("select2-highlighted"); - }, - - touchMoved: function() { - this._touchMoved = true; - }, - - clearTouchMoved: function() { - this._touchMoved = false; - }, - - // abstract - countSelectableResults: function() { - return this.findHighlightableChoices().length; - }, - - // abstract - highlightUnderEvent: function (event) { - var el = $(event.target).closest(".select2-result-selectable"); - if (el.length > 0 && !el.is(".select2-highlighted")) { - var choices = this.findHighlightableChoices(); - this.highlight(choices.index(el)); - } else if (el.length == 0) { - // if we are over an unselectable item remove all highlights - this.removeHighlight(); - } - }, - - // abstract - loadMoreIfNeeded: function () { - var results = this.results, - more = results.find("li.select2-more-results"), - below, // pixels the element is below the scroll fold, below==0 is when the element is starting to be visible - page = this.resultsPage + 1, - self=this, - term=this.search.val(), - context=this.context; - - if (more.length === 0) return; - below = more.offset().top - results.offset().top - results.height(); - - if (below <= this.opts.loadMorePadding) { - more.addClass("select2-active"); - this.opts.query({ - element: this.opts.element, - term: term, - page: page, - context: context, - matcher: this.opts.matcher, - callback: this.bind(function (data) { - - // ignore a response if the select2 has been closed before it was received - if (!self.opened()) return; - - - self.opts.populateResults.call(this, results, data.results, {term: term, page: page, context:context}); - self.postprocessResults(data, false, false); - - if (data.more===true) { - more.detach().appendTo(results).text(evaluate(self.opts.formatLoadMore, self.opts.element, page+1)); - window.setTimeout(function() { self.loadMoreIfNeeded(); }, 10); - } else { - more.remove(); - } - self.positionDropdown(); - self.resultsPage = page; - self.context = data.context; - this.opts.element.trigger({ type: "select2-loaded", items: data }); - })}); - } - }, - - /** - * Default tokenizer function which does nothing - */ - tokenize: function() { - - }, - - /** - * @param initial whether or not this is the call to this method right after the dropdown has been opened - */ - // abstract - updateResults: function (initial) { - var search = this.search, - results = this.results, - opts = this.opts, - data, - self = this, - input, - term = search.val(), - lastTerm = $.data(this.container, "select2-last-term"), - // sequence number used to drop out-of-order responses - queryNumber; - - // prevent duplicate queries against the same term - if (initial !== true && lastTerm && equal(term, lastTerm)) return; - - $.data(this.container, "select2-last-term", term); - - // if the search is currently hidden we do not alter the results - if (initial !== true && (this.showSearchInput === false || !this.opened())) { - return; - } - - function postRender() { - search.removeClass("select2-active"); - self.positionDropdown(); - if (results.find('.select2-no-results,.select2-selection-limit,.select2-searching').length) { - self.liveRegion.text(results.text()); - } - else { - self.liveRegion.text(self.opts.formatMatches(results.find('.select2-result-selectable').length)); - } - } - - function render(html) { - results.html(html); - postRender(); - } - - queryNumber = ++this.queryCount; - - var maxSelSize = this.getMaximumSelectionSize(); - if (maxSelSize >=1) { - data = this.data(); - if ($.isArray(data) && data.length >= maxSelSize && checkFormatter(opts.formatSelectionTooBig, "formatSelectionTooBig")) { - render("
        • " + evaluate(opts.formatSelectionTooBig, opts.element, maxSelSize) + "
        • "); - return; - } - } - - if (search.val().length < opts.minimumInputLength) { - if (checkFormatter(opts.formatInputTooShort, "formatInputTooShort")) { - render("
        • " + evaluate(opts.formatInputTooShort, opts.element, search.val(), opts.minimumInputLength) + "
        • "); - } else { - render(""); - } - if (initial && this.showSearch) this.showSearch(true); - return; - } - - if (opts.maximumInputLength && search.val().length > opts.maximumInputLength) { - if (checkFormatter(opts.formatInputTooLong, "formatInputTooLong")) { - render("
        • " + evaluate(opts.formatInputTooLong, opts.element, search.val(), opts.maximumInputLength) + "
        • "); - } else { - render(""); - } - return; - } - - if (opts.formatSearching && this.findHighlightableChoices().length === 0) { - render("
        • " + evaluate(opts.formatSearching, opts.element) + "
        • "); - } - - search.addClass("select2-active"); - - this.removeHighlight(); - - // give the tokenizer a chance to pre-process the input - input = this.tokenize(); - if (input != undefined && input != null) { - search.val(input); - } - - this.resultsPage = 1; - - opts.query({ - element: opts.element, - term: search.val(), - page: this.resultsPage, - context: null, - matcher: opts.matcher, - callback: this.bind(function (data) { - var def; // default choice - - // ignore old responses - if (queryNumber != this.queryCount) { - return; - } - - // ignore a response if the select2 has been closed before it was received - if (!this.opened()) { - this.search.removeClass("select2-active"); - return; - } - - // handle ajax error - if(data.hasError !== undefined && checkFormatter(opts.formatAjaxError, "formatAjaxError")) { - render("
        • " + evaluate(opts.formatAjaxError, opts.element, data.jqXHR, data.textStatus, data.errorThrown) + "
        • "); - return; - } - - // save context, if any - this.context = (data.context===undefined) ? null : data.context; - // create a default choice and prepend it to the list - if (this.opts.createSearchChoice && search.val() !== "") { - def = this.opts.createSearchChoice.call(self, search.val(), data.results); - if (def !== undefined && def !== null && self.id(def) !== undefined && self.id(def) !== null) { - if ($(data.results).filter( - function () { - return equal(self.id(this), self.id(def)); - }).length === 0) { - this.opts.createSearchChoicePosition(data.results, def); - } - } - } - - if (data.results.length === 0 && checkFormatter(opts.formatNoMatches, "formatNoMatches")) { - render("
        • " + evaluate(opts.formatNoMatches, opts.element, search.val()) + "
        • "); - return; - } - - results.empty(); - self.opts.populateResults.call(this, results, data.results, {term: search.val(), page: this.resultsPage, context:null}); - - if (data.more === true && checkFormatter(opts.formatLoadMore, "formatLoadMore")) { - results.append("
        • " + opts.escapeMarkup(evaluate(opts.formatLoadMore, opts.element, this.resultsPage)) + "
        • "); - window.setTimeout(function() { self.loadMoreIfNeeded(); }, 10); - } - - this.postprocessResults(data, initial); - - postRender(); - - this.opts.element.trigger({ type: "select2-loaded", items: data }); - })}); - }, - - // abstract - cancel: function () { - this.close(); - }, - - // abstract - blur: function () { - // if selectOnBlur == true, select the currently highlighted option - if (this.opts.selectOnBlur) - this.selectHighlighted({noFocus: true}); - - this.close(); - this.container.removeClass("select2-container-active"); - // synonymous to .is(':focus'), which is available in jquery >= 1.6 - if (this.search[0] === document.activeElement) { this.search.blur(); } - this.clearSearch(); - this.selection.find(".select2-search-choice-focus").removeClass("select2-search-choice-focus"); - }, - - // abstract - focusSearch: function () { - focus(this.search); - }, - - // abstract - selectHighlighted: function (options) { - if (this._touchMoved) { - this.clearTouchMoved(); - return; - } - var index=this.highlight(), - highlighted=this.results.find(".select2-highlighted"), - data = highlighted.closest('.select2-result').data("select2-data"); - - if (data) { - this.highlight(index); - this.onSelect(data, options); - } else if (options && options.noFocus) { - this.close(); - } - }, - - // abstract - getPlaceholder: function () { - var placeholderOption; - return this.opts.element.attr("placeholder") || - this.opts.element.attr("data-placeholder") || // jquery 1.4 compat - this.opts.element.data("placeholder") || - this.opts.placeholder || - ((placeholderOption = this.getPlaceholderOption()) !== undefined ? placeholderOption.text() : undefined); - }, - - // abstract - getPlaceholderOption: function() { - if (this.select) { - var firstOption = this.select.children('option').first(); - if (this.opts.placeholderOption !== undefined ) { - //Determine the placeholder option based on the specified placeholderOption setting - return (this.opts.placeholderOption === "first" && firstOption) || - (typeof this.opts.placeholderOption === "function" && this.opts.placeholderOption(this.select)); - } else if ($.trim(firstOption.text()) === "" && firstOption.val() === "") { - //No explicit placeholder option specified, use the first if it's blank - return firstOption; - } - } - }, - - /** - * Get the desired width for the container element. This is - * derived first from option `width` passed to select2, then - * the inline 'style' on the original element, and finally - * falls back to the jQuery calculated element width. - */ - // abstract - initContainerWidth: function () { - function resolveContainerWidth() { - var style, attrs, matches, i, l, attr; - - if (this.opts.width === "off") { - return null; - } else if (this.opts.width === "element"){ - return this.opts.element.outerWidth(false) === 0 ? 'auto' : this.opts.element.outerWidth(false) + 'px'; - } else if (this.opts.width === "copy" || this.opts.width === "resolve") { - // check if there is inline style on the element that contains width - style = this.opts.element.attr('style'); - if (style !== undefined) { - attrs = style.split(';'); - for (i = 0, l = attrs.length; i < l; i = i + 1) { - attr = attrs[i].replace(/\s/g, ''); - matches = attr.match(/^width:(([-+]?([0-9]*\.)?[0-9]+)(px|em|ex|%|in|cm|mm|pt|pc))/i); - if (matches !== null && matches.length >= 1) - return matches[1]; - } - } - - if (this.opts.width === "resolve") { - // next check if css('width') can resolve a width that is percent based, this is sometimes possible - // when attached to input type=hidden or elements hidden via css - style = this.opts.element.css('width'); - if (style.indexOf("%") > 0) return style; - - // finally, fallback on the calculated width of the element - return (this.opts.element.outerWidth(false) === 0 ? 'auto' : this.opts.element.outerWidth(false) + 'px'); - } - - return null; - } else if ($.isFunction(this.opts.width)) { - return this.opts.width(); - } else { - return this.opts.width; - } - }; - - var width = resolveContainerWidth.call(this); - if (width !== null) { - this.container.css("width", width); - } - } - }); - - SingleSelect2 = clazz(AbstractSelect2, { - - // single - - createContainer: function () { - var container = $(document.createElement("div")).attr({ - "class": "select2-container" - }).html([ - "", - "  ", - " ", - "", - "", - "", - "
          ", - " ", - "
            ", - "
          ", - "
          "].join("")); - return container; - }, - - // single - enableInterface: function() { - if (this.parent.enableInterface.apply(this, arguments)) { - this.focusser.prop("disabled", !this.isInterfaceEnabled()); - } - }, - - // single - opening: function () { - var el, range, len; - - if (this.opts.minimumResultsForSearch >= 0) { - this.showSearch(true); - } - - this.parent.opening.apply(this, arguments); - - if (this.showSearchInput !== false) { - // IE appends focusser.val() at the end of field :/ so we manually insert it at the beginning using a range - // all other browsers handle this just fine - - this.search.val(this.focusser.val()); - } - if (this.opts.shouldFocusInput(this)) { - this.search.focus(); - // move the cursor to the end after focussing, otherwise it will be at the beginning and - // new text will appear *before* focusser.val() - el = this.search.get(0); - if (el.createTextRange) { - range = el.createTextRange(); - range.collapse(false); - range.select(); - } else if (el.setSelectionRange) { - len = this.search.val().length; - el.setSelectionRange(len, len); - } - } - - // initializes search's value with nextSearchTerm (if defined by user) - // ignore nextSearchTerm if the dropdown is opened by the user pressing a letter - if(this.search.val() === "") { - if(this.nextSearchTerm != undefined){ - this.search.val(this.nextSearchTerm); - this.search.select(); - } - } - - this.focusser.prop("disabled", true).val(""); - this.updateResults(true); - this.opts.element.trigger($.Event("select2-open")); - }, - - // single - close: function () { - if (!this.opened()) return; - this.parent.close.apply(this, arguments); - - this.focusser.prop("disabled", false); - - if (this.opts.shouldFocusInput(this)) { - this.focusser.focus(); - } - }, - - // single - focus: function () { - if (this.opened()) { - this.close(); - } else { - this.focusser.prop("disabled", false); - if (this.opts.shouldFocusInput(this)) { - this.focusser.focus(); - } - } - }, - - // single - isFocused: function () { - return this.container.hasClass("select2-container-active"); - }, - - // single - cancel: function () { - this.parent.cancel.apply(this, arguments); - this.focusser.prop("disabled", false); - - if (this.opts.shouldFocusInput(this)) { - this.focusser.focus(); - } - }, - - // single - destroy: function() { - $("label[for='" + this.focusser.attr('id') + "']") - .attr('for', this.opts.element.attr("id")); - this.parent.destroy.apply(this, arguments); - - cleanupJQueryElements.call(this, - "selection", - "focusser" - ); - }, - - // single - initContainer: function () { - - var selection, - container = this.container, - dropdown = this.dropdown, - idSuffix = nextUid(), - elementLabel; - - if (this.opts.minimumResultsForSearch < 0) { - this.showSearch(false); - } else { - this.showSearch(true); - } - - this.selection = selection = container.find(".select2-choice"); - - this.focusser = container.find(".select2-focusser"); - - // add aria associations - selection.find(".select2-chosen").attr("id", "select2-chosen-"+idSuffix); - this.focusser.attr("aria-labelledby", "select2-chosen-"+idSuffix); - this.results.attr("id", "select2-results-"+idSuffix); - this.search.attr("aria-owns", "select2-results-"+idSuffix); - - // rewrite labels from original element to focusser - this.focusser.attr("id", "s2id_autogen"+idSuffix); - - elementLabel = $("label[for='" + this.opts.element.attr("id") + "']"); - - this.focusser.prev() - .text(elementLabel.text()) - .attr('for', this.focusser.attr('id')); - - // Ensure the original element retains an accessible name - var originalTitle = this.opts.element.attr("title"); - this.opts.element.attr("title", (originalTitle || elementLabel.text())); - - this.focusser.attr("tabindex", this.elementTabIndex); - - // write label for search field using the label from the focusser element - this.search.attr("id", this.focusser.attr('id') + '_search'); - - this.search.prev() - .text($("label[for='" + this.focusser.attr('id') + "']").text()) - .attr('for', this.search.attr('id')); - - this.search.on("keydown", this.bind(function (e) { - if (!this.isInterfaceEnabled()) return; - - // filter 229 keyCodes (input method editor is processing key input) - if (229 == e.keyCode) return; - - if (e.which === KEY.PAGE_UP || e.which === KEY.PAGE_DOWN) { - // prevent the page from scrolling - killEvent(e); - return; - } - - switch (e.which) { - case KEY.UP: - case KEY.DOWN: - this.moveHighlight((e.which === KEY.UP) ? -1 : 1); - killEvent(e); - return; - case KEY.ENTER: - this.selectHighlighted(); - killEvent(e); - return; - case KEY.TAB: - this.selectHighlighted({noFocus: true}); - return; - case KEY.ESC: - this.cancel(e); - killEvent(e); - return; - } - })); - - this.search.on("blur", this.bind(function(e) { - // a workaround for chrome to keep the search field focussed when the scroll bar is used to scroll the dropdown. - // without this the search field loses focus which is annoying - if (document.activeElement === this.body.get(0)) { - window.setTimeout(this.bind(function() { - if (this.opened()) { - this.search.focus(); - } - }), 0); - } - })); - - this.focusser.on("keydown", this.bind(function (e) { - if (!this.isInterfaceEnabled()) return; - - if (e.which === KEY.TAB || KEY.isControl(e) || KEY.isFunctionKey(e) || e.which === KEY.ESC) { - return; - } - - if (this.opts.openOnEnter === false && e.which === KEY.ENTER) { - killEvent(e); - return; - } - - if (e.which == KEY.DOWN || e.which == KEY.UP - || (e.which == KEY.ENTER && this.opts.openOnEnter)) { - - if (e.altKey || e.ctrlKey || e.shiftKey || e.metaKey) return; - - this.open(); - killEvent(e); - return; - } - - if (e.which == KEY.DELETE || e.which == KEY.BACKSPACE) { - if (this.opts.allowClear) { - this.clear(); - } - killEvent(e); - return; - } - })); - - - installKeyUpChangeEvent(this.focusser); - this.focusser.on("keyup-change input", this.bind(function(e) { - if (this.opts.minimumResultsForSearch >= 0) { - e.stopPropagation(); - if (this.opened()) return; - this.open(); - } - })); - - selection.on("mousedown touchstart", "abbr", this.bind(function (e) { - if (!this.isInterfaceEnabled()) return; - this.clear(); - killEventImmediately(e); - this.close(); - this.selection.focus(); - })); - - selection.on("mousedown touchstart", this.bind(function (e) { - // Prevent IE from generating a click event on the body - reinsertElement(selection); - - if (!this.container.hasClass("select2-container-active")) { - this.opts.element.trigger($.Event("select2-focus")); - } - - if (this.opened()) { - this.close(); - } else if (this.isInterfaceEnabled()) { - this.open(); - } - - killEvent(e); - })); - - dropdown.on("mousedown touchstart", this.bind(function() { - if (this.opts.shouldFocusInput(this)) { - this.search.focus(); - } - })); - - selection.on("focus", this.bind(function(e) { - killEvent(e); - })); - - this.focusser.on("focus", this.bind(function(){ - if (!this.container.hasClass("select2-container-active")) { - this.opts.element.trigger($.Event("select2-focus")); - } - this.container.addClass("select2-container-active"); - })).on("blur", this.bind(function() { - if (!this.opened()) { - this.container.removeClass("select2-container-active"); - this.opts.element.trigger($.Event("select2-blur")); - } - })); - this.search.on("focus", this.bind(function(){ - if (!this.container.hasClass("select2-container-active")) { - this.opts.element.trigger($.Event("select2-focus")); - } - this.container.addClass("select2-container-active"); - })); - - this.initContainerWidth(); - this.opts.element.addClass("select2-offscreen"); - this.setPlaceholder(); - - }, - - // single - clear: function(triggerChange) { - var data=this.selection.data("select2-data"); - if (data) { // guard against queued quick consecutive clicks - var evt = $.Event("select2-clearing"); - this.opts.element.trigger(evt); - if (evt.isDefaultPrevented()) { - return; - } - var placeholderOption = this.getPlaceholderOption(); - this.opts.element.val(placeholderOption ? placeholderOption.val() : ""); - this.selection.find(".select2-chosen").empty(); - this.selection.removeData("select2-data"); - this.setPlaceholder(); - - if (triggerChange !== false){ - this.opts.element.trigger({ type: "select2-removed", val: this.id(data), choice: data }); - this.triggerChange({removed:data}); - } - } - }, - - /** - * Sets selection based on source element's value - */ - // single - initSelection: function () { - var selected; - if (this.isPlaceholderOptionSelected()) { - this.updateSelection(null); - this.close(); - this.setPlaceholder(); - } else { - var self = this; - this.opts.initSelection.call(null, this.opts.element, function(selected){ - if (selected !== undefined && selected !== null) { - self.updateSelection(selected); - self.close(); - self.setPlaceholder(); - self.nextSearchTerm = self.opts.nextSearchTerm(selected, self.search.val()); - } - }); - } - }, - - isPlaceholderOptionSelected: function() { - var placeholderOption; - if (this.getPlaceholder() === undefined) return false; // no placeholder specified so no option should be considered - return ((placeholderOption = this.getPlaceholderOption()) !== undefined && placeholderOption.prop("selected")) - || (this.opts.element.val() === "") - || (this.opts.element.val() === undefined) - || (this.opts.element.val() === null); - }, - - // single - prepareOpts: function () { - var opts = this.parent.prepareOpts.apply(this, arguments), - self=this; - - if (opts.element.get(0).tagName.toLowerCase() === "select") { - // install the selection initializer - opts.initSelection = function (element, callback) { - var selected = element.find("option").filter(function() { return this.selected && !this.disabled }); - // a single select box always has a value, no need to null check 'selected' - callback(self.optionToData(selected)); - }; - } else if ("data" in opts) { - // install default initSelection when applied to hidden input and data is local - opts.initSelection = opts.initSelection || function (element, callback) { - var id = element.val(); - //search in data by id, storing the actual matching item - var match = null; - opts.query({ - matcher: function(term, text, el){ - var is_match = equal(id, opts.id(el)); - if (is_match) { - match = el; - } - return is_match; - }, - callback: !$.isFunction(callback) ? $.noop : function() { - callback(match); - } - }); - }; - } - - return opts; - }, - - // single - getPlaceholder: function() { - // if a placeholder is specified on a single select without a valid placeholder option ignore it - if (this.select) { - if (this.getPlaceholderOption() === undefined) { - return undefined; - } - } - - return this.parent.getPlaceholder.apply(this, arguments); - }, - - // single - setPlaceholder: function () { - var placeholder = this.getPlaceholder(); - - if (this.isPlaceholderOptionSelected() && placeholder !== undefined) { - - // check for a placeholder option if attached to a select - if (this.select && this.getPlaceholderOption() === undefined) return; - - this.selection.find(".select2-chosen").html(this.opts.escapeMarkup(placeholder)); - - this.selection.addClass("select2-default"); - - this.container.removeClass("select2-allowclear"); - } - }, - - // single - postprocessResults: function (data, initial, noHighlightUpdate) { - var selected = 0, self = this, showSearchInput = true; - - // find the selected element in the result list - - this.findHighlightableChoices().each2(function (i, elm) { - if (equal(self.id(elm.data("select2-data")), self.opts.element.val())) { - selected = i; - return false; - } - }); - - // and highlight it - if (noHighlightUpdate !== false) { - if (initial === true && selected >= 0) { - this.highlight(selected); - } else { - this.highlight(0); - } - } - - // hide the search box if this is the first we got the results and there are enough of them for search - - if (initial === true) { - var min = this.opts.minimumResultsForSearch; - if (min >= 0) { - this.showSearch(countResults(data.results) >= min); - } - } - }, - - // single - showSearch: function(showSearchInput) { - if (this.showSearchInput === showSearchInput) return; - - this.showSearchInput = showSearchInput; - - this.dropdown.find(".select2-search").toggleClass("select2-search-hidden", !showSearchInput); - this.dropdown.find(".select2-search").toggleClass("select2-offscreen", !showSearchInput); - //add "select2-with-searchbox" to the container if search box is shown - $(this.dropdown, this.container).toggleClass("select2-with-searchbox", showSearchInput); - }, - - // single - onSelect: function (data, options) { - - if (!this.triggerSelect(data)) { return; } - - var old = this.opts.element.val(), - oldData = this.data(); - - this.opts.element.val(this.id(data)); - this.updateSelection(data); - - this.opts.element.trigger({ type: "select2-selected", val: this.id(data), choice: data }); - - this.nextSearchTerm = this.opts.nextSearchTerm(data, this.search.val()); - this.close(); - - if ((!options || !options.noFocus) && this.opts.shouldFocusInput(this)) { - this.focusser.focus(); - } - - if (!equal(old, this.id(data))) { - this.triggerChange({ added: data, removed: oldData }); - } - }, - - // single - updateSelection: function (data) { - - var container=this.selection.find(".select2-chosen"), formatted, cssClass; - - this.selection.data("select2-data", data); - - container.empty(); - if (data !== null) { - formatted=this.opts.formatSelection(data, container, this.opts.escapeMarkup); - } - if (formatted !== undefined) { - container.append(formatted); - } - cssClass=this.opts.formatSelectionCssClass(data, container); - if (cssClass !== undefined) { - container.addClass(cssClass); - } - - this.selection.removeClass("select2-default"); - - if (this.opts.allowClear && this.getPlaceholder() !== undefined) { - this.container.addClass("select2-allowclear"); - } - }, - - // single - val: function () { - var val, - triggerChange = false, - data = null, - self = this, - oldData = this.data(); - - if (arguments.length === 0) { - return this.opts.element.val(); - } - - val = arguments[0]; - - if (arguments.length > 1) { - triggerChange = arguments[1]; - } - - if (this.select) { - this.select - .val(val) - .find("option").filter(function() { return this.selected }).each2(function (i, elm) { - data = self.optionToData(elm); - return false; - }); - this.updateSelection(data); - this.setPlaceholder(); - if (triggerChange) { - this.triggerChange({added: data, removed:oldData}); - } - } else { - // val is an id. !val is true for [undefined,null,'',0] - 0 is legal - if (!val && val !== 0) { - this.clear(triggerChange); - return; - } - if (this.opts.initSelection === undefined) { - throw new Error("cannot call val() if initSelection() is not defined"); - } - this.opts.element.val(val); - this.opts.initSelection(this.opts.element, function(data){ - self.opts.element.val(!data ? "" : self.id(data)); - self.updateSelection(data); - self.setPlaceholder(); - if (triggerChange) { - self.triggerChange({added: data, removed:oldData}); - } - }); - } - }, - - // single - clearSearch: function () { - this.search.val(""); - this.focusser.val(""); - }, - - // single - data: function(value) { - var data, - triggerChange = false; - - if (arguments.length === 0) { - data = this.selection.data("select2-data"); - if (data == undefined) data = null; - return data; - } else { - if (arguments.length > 1) { - triggerChange = arguments[1]; - } - if (!value) { - this.clear(triggerChange); - } else { - data = this.data(); - this.opts.element.val(!value ? "" : this.id(value)); - this.updateSelection(value); - if (triggerChange) { - this.triggerChange({added: value, removed:data}); - } - } - } - } - }); - - MultiSelect2 = clazz(AbstractSelect2, { - - // multi - createContainer: function () { - var container = $(document.createElement("div")).attr({ - "class": "select2-container select2-container-multi" - }).html([ - "
            ", - "
          • ", - " ", - " ", - "
          • ", - "
          ", - "
          ", - "
            ", - "
          ", - "
          "].join("")); - return container; - }, - - // multi - prepareOpts: function () { - var opts = this.parent.prepareOpts.apply(this, arguments), - self=this; - - // TODO validate placeholder is a string if specified - - if (opts.element.get(0).tagName.toLowerCase() === "select") { - // install the selection initializer - opts.initSelection = function (element, callback) { - - var data = []; - - element.find("option").filter(function() { return this.selected && !this.disabled }).each2(function (i, elm) { - data.push(self.optionToData(elm)); - }); - callback(data); - }; - } else if ("data" in opts) { - // install default initSelection when applied to hidden input and data is local - opts.initSelection = opts.initSelection || function (element, callback) { - var ids = splitVal(element.val(), opts.separator); - //search in data by array of ids, storing matching items in a list - var matches = []; - opts.query({ - matcher: function(term, text, el){ - var is_match = $.grep(ids, function(id) { - return equal(id, opts.id(el)); - }).length; - if (is_match) { - matches.push(el); - } - return is_match; - }, - callback: !$.isFunction(callback) ? $.noop : function() { - // reorder matches based on the order they appear in the ids array because right now - // they are in the order in which they appear in data array - var ordered = []; - for (var i = 0; i < ids.length; i++) { - var id = ids[i]; - for (var j = 0; j < matches.length; j++) { - var match = matches[j]; - if (equal(id, opts.id(match))) { - ordered.push(match); - matches.splice(j, 1); - break; - } - } - } - callback(ordered); - } - }); - }; - } - - return opts; - }, - - // multi - selectChoice: function (choice) { - - var selected = this.container.find(".select2-search-choice-focus"); - if (selected.length && choice && choice[0] == selected[0]) { - - } else { - if (selected.length) { - this.opts.element.trigger("choice-deselected", selected); - } - selected.removeClass("select2-search-choice-focus"); - if (choice && choice.length) { - this.close(); - choice.addClass("select2-search-choice-focus"); - this.opts.element.trigger("choice-selected", choice); - } - } - }, - - // multi - destroy: function() { - $("label[for='" + this.search.attr('id') + "']") - .attr('for', this.opts.element.attr("id")); - this.parent.destroy.apply(this, arguments); - - cleanupJQueryElements.call(this, - "searchContainer", - "selection" - ); - }, - - // multi - initContainer: function () { - - var selector = ".select2-choices", selection; - - this.searchContainer = this.container.find(".select2-search-field"); - this.selection = selection = this.container.find(selector); - - var _this = this; - this.selection.on("click", ".select2-search-choice:not(.select2-locked)", function (e) { - //killEvent(e); - _this.search[0].focus(); - _this.selectChoice($(this)); - }); - - // rewrite labels from original element to focusser - this.search.attr("id", "s2id_autogen"+nextUid()); - - this.search.prev() - .text($("label[for='" + this.opts.element.attr("id") + "']").text()) - .attr('for', this.search.attr('id')); - - this.search.on("input paste", this.bind(function() { - if (this.search.attr('placeholder') && this.search.val().length == 0) return; - if (!this.isInterfaceEnabled()) return; - if (!this.opened()) { - this.open(); - } - })); - - this.search.attr("tabindex", this.elementTabIndex); - - this.keydowns = 0; - this.search.on("keydown", this.bind(function (e) { - if (!this.isInterfaceEnabled()) return; - - ++this.keydowns; - var selected = selection.find(".select2-search-choice-focus"); - var prev = selected.prev(".select2-search-choice:not(.select2-locked)"); - var next = selected.next(".select2-search-choice:not(.select2-locked)"); - var pos = getCursorInfo(this.search); - - if (selected.length && - (e.which == KEY.LEFT || e.which == KEY.RIGHT || e.which == KEY.BACKSPACE || e.which == KEY.DELETE || e.which == KEY.ENTER)) { - var selectedChoice = selected; - if (e.which == KEY.LEFT && prev.length) { - selectedChoice = prev; - } - else if (e.which == KEY.RIGHT) { - selectedChoice = next.length ? next : null; - } - else if (e.which === KEY.BACKSPACE) { - if (this.unselect(selected.first())) { - this.search.width(10); - selectedChoice = prev.length ? prev : next; - } - } else if (e.which == KEY.DELETE) { - if (this.unselect(selected.first())) { - this.search.width(10); - selectedChoice = next.length ? next : null; - } - } else if (e.which == KEY.ENTER) { - selectedChoice = null; - } - - this.selectChoice(selectedChoice); - killEvent(e); - if (!selectedChoice || !selectedChoice.length) { - this.open(); - } - return; - } else if (((e.which === KEY.BACKSPACE && this.keydowns == 1) - || e.which == KEY.LEFT) && (pos.offset == 0 && !pos.length)) { - - this.selectChoice(selection.find(".select2-search-choice:not(.select2-locked)").last()); - killEvent(e); - return; - } else { - this.selectChoice(null); - } - - if (this.opened()) { - switch (e.which) { - case KEY.UP: - case KEY.DOWN: - this.moveHighlight((e.which === KEY.UP) ? -1 : 1); - killEvent(e); - return; - case KEY.ENTER: - this.selectHighlighted(); - killEvent(e); - return; - case KEY.TAB: - this.selectHighlighted({noFocus:true}); - this.close(); - return; - case KEY.ESC: - this.cancel(e); - killEvent(e); - return; - } - } - - if (e.which === KEY.TAB || KEY.isControl(e) || KEY.isFunctionKey(e) - || e.which === KEY.BACKSPACE || e.which === KEY.ESC) { - return; - } - - if (e.which === KEY.ENTER) { - if (this.opts.openOnEnter === false) { - return; - } else if (e.altKey || e.ctrlKey || e.shiftKey || e.metaKey) { - return; - } - } - - this.open(); - - if (e.which === KEY.PAGE_UP || e.which === KEY.PAGE_DOWN) { - // prevent the page from scrolling - killEvent(e); - } - - if (e.which === KEY.ENTER) { - // prevent form from being submitted - killEvent(e); - } - - })); - - this.search.on("keyup", this.bind(function (e) { - this.keydowns = 0; - this.resizeSearch(); - }) - ); - - this.search.on("blur", this.bind(function(e) { - this.container.removeClass("select2-container-active"); - this.search.removeClass("select2-focused"); - this.selectChoice(null); - if (!this.opened()) this.clearSearch(); - e.stopImmediatePropagation(); - this.opts.element.trigger($.Event("select2-blur")); - })); - - this.container.on("click", selector, this.bind(function (e) { - if (!this.isInterfaceEnabled()) return; - if ($(e.target).closest(".select2-search-choice").length > 0) { - // clicked inside a select2 search choice, do not open - return; - } - this.selectChoice(null); - this.clearPlaceholder(); - if (!this.container.hasClass("select2-container-active")) { - this.opts.element.trigger($.Event("select2-focus")); - } - this.open(); - this.focusSearch(); - e.preventDefault(); - })); - - this.container.on("focus", selector, this.bind(function () { - if (!this.isInterfaceEnabled()) return; - if (!this.container.hasClass("select2-container-active")) { - this.opts.element.trigger($.Event("select2-focus")); - } - this.container.addClass("select2-container-active"); - this.dropdown.addClass("select2-drop-active"); - this.clearPlaceholder(); - })); - - this.initContainerWidth(); - this.opts.element.addClass("select2-offscreen"); - - // set the placeholder if necessary - this.clearSearch(); - }, - - // multi - enableInterface: function() { - if (this.parent.enableInterface.apply(this, arguments)) { - this.search.prop("disabled", !this.isInterfaceEnabled()); - } - }, - - // multi - initSelection: function () { - var data; - if (this.opts.element.val() === "" && this.opts.element.text() === "") { - this.updateSelection([]); - this.close(); - // set the placeholder if necessary - this.clearSearch(); - } - if (this.select || this.opts.element.val() !== "") { - var self = this; - this.opts.initSelection.call(null, this.opts.element, function(data){ - if (data !== undefined && data !== null) { - self.updateSelection(data); - self.close(); - // set the placeholder if necessary - self.clearSearch(); - } - }); - } - }, - - // multi - clearSearch: function () { - var placeholder = this.getPlaceholder(), - maxWidth = this.getMaxSearchWidth(); - - if (placeholder !== undefined && this.getVal().length === 0 && this.search.hasClass("select2-focused") === false) { - this.search.val(placeholder).addClass("select2-default"); - // stretch the search box to full width of the container so as much of the placeholder is visible as possible - // we could call this.resizeSearch(), but we do not because that requires a sizer and we do not want to create one so early because of a firefox bug, see #944 - this.search.width(maxWidth > 0 ? maxWidth : this.container.css("width")); - } else { - this.search.val("").width(10); - } - }, - - // multi - clearPlaceholder: function () { - if (this.search.hasClass("select2-default")) { - this.search.val("").removeClass("select2-default"); - } - }, - - // multi - opening: function () { - this.clearPlaceholder(); // should be done before super so placeholder is not used to search - this.resizeSearch(); - - this.parent.opening.apply(this, arguments); - - this.focusSearch(); - - // initializes search's value with nextSearchTerm (if defined by user) - // ignore nextSearchTerm if the dropdown is opened by the user pressing a letter - if(this.search.val() === "") { - if(this.nextSearchTerm != undefined){ - this.search.val(this.nextSearchTerm); - this.search.select(); - } - } - - this.updateResults(true); - if (this.opts.shouldFocusInput(this)) { - this.search.focus(); - } - this.opts.element.trigger($.Event("select2-open")); - }, - - // multi - close: function () { - if (!this.opened()) return; - this.parent.close.apply(this, arguments); - }, - - // multi - focus: function () { - this.close(); - this.search.focus(); - }, - - // multi - isFocused: function () { - return this.search.hasClass("select2-focused"); - }, - - // multi - updateSelection: function (data) { - var ids = [], filtered = [], self = this; - - // filter out duplicates - $(data).each(function () { - if (indexOf(self.id(this), ids) < 0) { - ids.push(self.id(this)); - filtered.push(this); - } - }); - data = filtered; - - this.selection.find(".select2-search-choice").remove(); - $(data).each(function () { - self.addSelectedChoice(this); - }); - self.postprocessResults(); - }, - - // multi - tokenize: function() { - var input = this.search.val(); - input = this.opts.tokenizer.call(this, input, this.data(), this.bind(this.onSelect), this.opts); - if (input != null && input != undefined) { - this.search.val(input); - if (input.length > 0) { - this.open(); - } - } - - }, - - // multi - onSelect: function (data, options) { - - if (!this.triggerSelect(data) || data.text === "") { return; } - - this.addSelectedChoice(data); - - this.opts.element.trigger({ type: "selected", val: this.id(data), choice: data }); - - // keep track of the search's value before it gets cleared - this.nextSearchTerm = this.opts.nextSearchTerm(data, this.search.val()); - - this.clearSearch(); - this.updateResults(); - - if (this.select || !this.opts.closeOnSelect) this.postprocessResults(data, false, this.opts.closeOnSelect===true); - - if (this.opts.closeOnSelect) { - this.close(); - this.search.width(10); - } else { - if (this.countSelectableResults()>0) { - this.search.width(10); - this.resizeSearch(); - if (this.getMaximumSelectionSize() > 0 && this.val().length >= this.getMaximumSelectionSize()) { - // if we reached max selection size repaint the results so choices - // are replaced with the max selection reached message - this.updateResults(true); - } else { - // initializes search's value with nextSearchTerm and update search result - if(this.nextSearchTerm != undefined){ - this.search.val(this.nextSearchTerm); - this.updateResults(); - this.search.select(); - } - } - this.positionDropdown(); - } else { - // if nothing left to select close - this.close(); - this.search.width(10); - } - } - - // since its not possible to select an element that has already been - // added we do not need to check if this is a new element before firing change - this.triggerChange({ added: data }); - - if (!options || !options.noFocus) - this.focusSearch(); - }, - - // multi - cancel: function () { - this.close(); - this.focusSearch(); - }, - - addSelectedChoice: function (data) { - var enableChoice = !data.locked, - enabledItem = $( - "
        • " + - "
          " + - " " + - "
        • "), - disabledItem = $( - "
        • " + - "
          " + - "
        • "); - var choice = enableChoice ? enabledItem : disabledItem, - id = this.id(data), - val = this.getVal(), - formatted, - cssClass; - - formatted=this.opts.formatSelection(data, choice.find("div"), this.opts.escapeMarkup); - if (formatted != undefined) { - choice.find("div").replaceWith("
          "+formatted+"
          "); - } - cssClass=this.opts.formatSelectionCssClass(data, choice.find("div")); - if (cssClass != undefined) { - choice.addClass(cssClass); - } - - if(enableChoice){ - choice.find(".select2-search-choice-close") - .on("mousedown", killEvent) - .on("click dblclick", this.bind(function (e) { - if (!this.isInterfaceEnabled()) return; - - this.unselect($(e.target)); - this.selection.find(".select2-search-choice-focus").removeClass("select2-search-choice-focus"); - killEvent(e); - this.close(); - this.focusSearch(); - })).on("focus", this.bind(function () { - if (!this.isInterfaceEnabled()) return; - this.container.addClass("select2-container-active"); - this.dropdown.addClass("select2-drop-active"); - })); - } - - choice.data("select2-data", data); - choice.insertBefore(this.searchContainer); - - val.push(id); - this.setVal(val); - }, - - // multi - unselect: function (selected) { - var val = this.getVal(), - data, - index; - selected = selected.closest(".select2-search-choice"); - - if (selected.length === 0) { - throw "Invalid argument: " + selected + ". Must be .select2-search-choice"; - } - - data = selected.data("select2-data"); - - if (!data) { - // prevent a race condition when the 'x' is clicked really fast repeatedly the event can be queued - // and invoked on an element already removed - return; - } - - var evt = $.Event("select2-removing"); - evt.val = this.id(data); - evt.choice = data; - this.opts.element.trigger(evt); - - if (evt.isDefaultPrevented()) { - return false; - } - - while((index = indexOf(this.id(data), val)) >= 0) { - val.splice(index, 1); - this.setVal(val); - if (this.select) this.postprocessResults(); - } - - selected.remove(); - - this.opts.element.trigger({ type: "select2-removed", val: this.id(data), choice: data }); - this.triggerChange({ removed: data }); - - return true; - }, - - // multi - postprocessResults: function (data, initial, noHighlightUpdate) { - var val = this.getVal(), - choices = this.results.find(".select2-result"), - compound = this.results.find(".select2-result-with-children"), - self = this; - - choices.each2(function (i, choice) { - var id = self.id(choice.data("select2-data")); - if (indexOf(id, val) >= 0) { - choice.addClass("select2-selected"); - // mark all children of the selected parent as selected - choice.find(".select2-result-selectable").addClass("select2-selected"); - } - }); - - compound.each2(function(i, choice) { - // hide an optgroup if it doesn't have any selectable children - if (!choice.is('.select2-result-selectable') - && choice.find(".select2-result-selectable:not(.select2-selected)").length === 0) { - choice.addClass("select2-selected"); - } - }); - - if (this.highlight() == -1 && noHighlightUpdate !== false){ - self.highlight(0); - } - - //If all results are chosen render formatNoMatches - if(!this.opts.createSearchChoice && !choices.filter('.select2-result:not(.select2-selected)').length > 0){ - if(!data || data && !data.more && this.results.find(".select2-no-results").length === 0) { - if (checkFormatter(self.opts.formatNoMatches, "formatNoMatches")) { - this.results.append("
        • " + evaluate(self.opts.formatNoMatches, self.opts.element, self.search.val()) + "
        • "); - } - } - } - - }, - - // multi - getMaxSearchWidth: function() { - return this.selection.width() - getSideBorderPadding(this.search); - }, - - // multi - resizeSearch: function () { - var minimumWidth, left, maxWidth, containerLeft, searchWidth, - sideBorderPadding = getSideBorderPadding(this.search); - - minimumWidth = measureTextWidth(this.search) + 10; - - left = this.search.offset().left; - - maxWidth = this.selection.width(); - containerLeft = this.selection.offset().left; - - searchWidth = maxWidth - (left - containerLeft) - sideBorderPadding; - - if (searchWidth < minimumWidth) { - searchWidth = maxWidth - sideBorderPadding; - } - - if (searchWidth < 40) { - searchWidth = maxWidth - sideBorderPadding; - } - - if (searchWidth <= 0) { - searchWidth = minimumWidth; - } - - this.search.width(Math.floor(searchWidth)); - }, - - // multi - getVal: function () { - var val; - if (this.select) { - val = this.select.val(); - return val === null ? [] : val; - } else { - val = this.opts.element.val(); - return splitVal(val, this.opts.separator); - } - }, - - // multi - setVal: function (val) { - var unique; - if (this.select) { - this.select.val(val); - } else { - unique = []; - // filter out duplicates - $(val).each(function () { - if (indexOf(this, unique) < 0) unique.push(this); - }); - this.opts.element.val(unique.length === 0 ? "" : unique.join(this.opts.separator)); - } - }, - - // multi - buildChangeDetails: function (old, current) { - var current = current.slice(0), - old = old.slice(0); - - // remove intersection from each array - for (var i = 0; i < current.length; i++) { - for (var j = 0; j < old.length; j++) { - if (equal(this.opts.id(current[i]), this.opts.id(old[j]))) { - current.splice(i, 1); - if(i>0){ - i--; - } - old.splice(j, 1); - j--; - } - } - } - - return {added: current, removed: old}; - }, - - - // multi - val: function (val, triggerChange) { - var oldData, self=this; - - if (arguments.length === 0) { - return this.getVal(); - } - - oldData=this.data(); - if (!oldData.length) oldData=[]; - - // val is an id. !val is true for [undefined,null,'',0] - 0 is legal - if (!val && val !== 0) { - this.opts.element.val(""); - this.updateSelection([]); - this.clearSearch(); - if (triggerChange) { - this.triggerChange({added: this.data(), removed: oldData}); - } - return; - } - - // val is a list of ids - this.setVal(val); - - if (this.select) { - this.opts.initSelection(this.select, this.bind(this.updateSelection)); - if (triggerChange) { - this.triggerChange(this.buildChangeDetails(oldData, this.data())); - } - } else { - if (this.opts.initSelection === undefined) { - throw new Error("val() cannot be called if initSelection() is not defined"); - } - - this.opts.initSelection(this.opts.element, function(data){ - var ids=$.map(data, self.id); - self.setVal(ids); - self.updateSelection(data); - self.clearSearch(); - if (triggerChange) { - self.triggerChange(self.buildChangeDetails(oldData, self.data())); - } - }); - } - this.clearSearch(); - }, - - // multi - onSortStart: function() { - if (this.select) { - throw new Error("Sorting of elements is not supported when attached to instead."); - } - - // collapse search field into 0 width so its container can be collapsed as well - this.search.width(0); - // hide the container - this.searchContainer.hide(); - }, - - // multi - onSortEnd:function() { - - var val=[], self=this; - - // show search and move it to the end of the list - this.searchContainer.show(); - // make sure the search container is the last item in the list - this.searchContainer.appendTo(this.searchContainer.parent()); - // since we collapsed the width in dragStarted, we resize it here - this.resizeSearch(); - - // update selection - this.selection.find(".select2-search-choice").each(function() { - val.push(self.opts.id($(this).data("select2-data"))); - }); - this.setVal(val); - this.triggerChange(); - }, - - // multi - data: function(values, triggerChange) { - var self=this, ids, old; - if (arguments.length === 0) { - return this.selection - .children(".select2-search-choice") - .map(function() { return $(this).data("select2-data"); }) - .get(); - } else { - old = this.data(); - if (!values) { values = []; } - ids = $.map(values, function(e) { return self.opts.id(e); }); - this.setVal(ids); - this.updateSelection(values); - this.clearSearch(); - if (triggerChange) { - this.triggerChange(this.buildChangeDetails(old, this.data())); - } - } - } - }); - - $.fn.select2 = function () { - - var args = Array.prototype.slice.call(arguments, 0), - opts, - select2, - method, value, multiple, - allowedMethods = ["val", "destroy", "opened", "open", "close", "focus", "isFocused", "container", "dropdown", "onSortStart", "onSortEnd", "enable", "disable", "readonly", "positionDropdown", "data", "search"], - valueMethods = ["opened", "isFocused", "container", "dropdown"], - propertyMethods = ["val", "data"], - methodsMap = { search: "externalSearch" }; - - this.each(function () { - if (args.length === 0 || typeof(args[0]) === "object") { - opts = args.length === 0 ? {} : $.extend({}, args[0]); - opts.element = $(this); - - if (opts.element.get(0).tagName.toLowerCase() === "select") { - multiple = opts.element.prop("multiple"); - } else { - multiple = opts.multiple || false; - if ("tags" in opts) {opts.multiple = multiple = true;} - } - - select2 = multiple ? new window.Select2["class"].multi() : new window.Select2["class"].single(); - select2.init(opts); - } else if (typeof(args[0]) === "string") { - - if (indexOf(args[0], allowedMethods) < 0) { - throw "Unknown method: " + args[0]; - } - - value = undefined; - select2 = $(this).data("select2"); - if (select2 === undefined) return; - - method=args[0]; - - if (method === "container") { - value = select2.container; - } else if (method === "dropdown") { - value = select2.dropdown; - } else { - if (methodsMap[method]) method = methodsMap[method]; - - value = select2[method].apply(select2, args.slice(1)); - } - if (indexOf(args[0], valueMethods) >= 0 - || (indexOf(args[0], propertyMethods) >= 0 && args.length == 1)) { - return false; // abort the iteration, ready to return first matched value - } - } else { - throw "Invalid arguments to select2 plugin: " + args; - } - }); - return (value === undefined) ? this : value; - }; - - // plugin defaults, accessible to users - $.fn.select2.defaults = { - width: "copy", - loadMorePadding: 0, - closeOnSelect: true, - openOnEnter: true, - containerCss: {}, - dropdownCss: {}, - containerCssClass: "", - dropdownCssClass: "", - formatResult: function(result, container, query, escapeMarkup) { - var markup=[]; - markMatch(result.text, query.term, markup, escapeMarkup); - return markup.join(""); - }, - formatSelection: function (data, container, escapeMarkup) { - return data ? escapeMarkup(data.text) : undefined; - }, - sortResults: function (results, container, query) { - return results; - }, - formatResultCssClass: function(data) {return data.css;}, - formatSelectionCssClass: function(data, container) {return undefined;}, - minimumResultsForSearch: 0, - minimumInputLength: 0, - maximumInputLength: null, - maximumSelectionSize: 0, - id: function (e) { return e == undefined ? null : e.id; }, - matcher: function(term, text) { - return stripDiacritics(''+text).toUpperCase().indexOf(stripDiacritics(''+term).toUpperCase()) >= 0; - }, - separator: ",", - tokenSeparators: [], - tokenizer: defaultTokenizer, - escapeMarkup: defaultEscapeMarkup, - blurOnChange: false, - selectOnBlur: false, - adaptContainerCssClass: function(c) { return c; }, - adaptDropdownCssClass: function(c) { return null; }, - nextSearchTerm: function(selectedObject, currentSearchTerm) { return undefined; }, - searchInputPlaceholder: '', - createSearchChoicePosition: 'top', - shouldFocusInput: function (instance) { - // Attempt to detect touch devices - var supportsTouchEvents = (('ontouchstart' in window) || - (navigator.msMaxTouchPoints > 0)); - - // Only devices which support touch events should be special cased - if (!supportsTouchEvents) { - return true; - } - - // Never focus the input if search is disabled - if (instance.opts.minimumResultsForSearch < 0) { - return false; - } - - return true; - } - }; - - $.fn.select2.locales = []; - - $.fn.select2.locales['en'] = { - formatMatches: function (matches) { if (matches === 1) { return "One result is available, press enter to select it."; } return matches + " results are available, use up and down arrow keys to navigate."; }, - formatNoMatches: function () { return "No matches found"; }, - formatAjaxError: function (jqXHR, textStatus, errorThrown) { return "Loading failed"; }, - formatInputTooShort: function (input, min) { var n = min - input.length; return "Please enter " + n + " or more character" + (n == 1 ? "" : "s"); }, - formatInputTooLong: function (input, max) { var n = input.length - max; return "Please delete " + n + " character" + (n == 1 ? "" : "s"); }, - formatSelectionTooBig: function (limit) { return "You can only select " + limit + " item" + (limit == 1 ? "" : "s"); }, - formatLoadMore: function (pageNumber) { return "Loading more results…"; }, - formatSearching: function () { return "Searching…"; }, - }; - - $.extend($.fn.select2.defaults, $.fn.select2.locales['en']); - - $.fn.select2.ajaxDefaults = { - transport: $.ajax, - params: { - type: "GET", - cache: false, - dataType: "json" - } - }; - - // exports - window.Select2 = { - query: { - ajax: ajax, - local: local, - tags: tags - }, util: { - debounce: debounce, - markMatch: markMatch, - escapeMarkup: defaultEscapeMarkup, - stripDiacritics: stripDiacritics - }, "class": { - "abstract": AbstractSelect2, - "single": SingleSelect2, - "multi": MultiSelect2 - } - }; - -}(jQuery)); +k.empty(),m.opts.populateResults.call(this,k,f.results,{term:j.val(),page:this.resultsPage,context:null}),f.more===!0&&y(l.formatLoadMore,"formatLoadMore")&&(k.append("
        • "+l.escapeMarkup(z(l.formatLoadMore,l.element,this.resultsPage))+"
        • "),window.setTimeout(function(){m.loadMoreIfNeeded()},10)),this.postprocessResults(f,c),d(),this.opts.element.trigger({type:"select2-loaded",items:f})}})})}},cancel:function(){this.close()},blur:function(){this.opts.selectOnBlur&&this.selectHighlighted({noFocus:!0}),this.close(),this.container.removeClass("select2-container-active"),this.search[0]===document.activeElement&&this.search.blur(),this.clearSearch(),this.selection.find(".select2-search-choice-focus").removeClass("select2-search-choice-focus")},focusSearch:function(){n(this.search)},selectHighlighted:function(a){if(this._touchMoved)return void this.clearTouchMoved();var b=this.highlight(),c=this.results.find(".select2-highlighted"),d=c.closest(".select2-result").data("select2-data");d?(this.highlight(b),this.onSelect(d,a)):a&&a.noFocus&&this.close()},getPlaceholder:function(){var a;return this.opts.element.attr("placeholder")||this.opts.element.attr("data-placeholder")||this.opts.element.data("placeholder")||this.opts.placeholder||((a=this.getPlaceholderOption())!==b?a.text():b)},getPlaceholderOption:function(){if(this.select){var c=this.select.children("option").first();if(this.opts.placeholderOption!==b)return"first"===this.opts.placeholderOption&&c||"function"==typeof this.opts.placeholderOption&&this.opts.placeholderOption(this.select);if(""===a.trim(c.text())&&""===c.val())return c}},initContainerWidth:function(){function c(){var c,d,e,f,g,h;if("off"===this.opts.width)return null;if("element"===this.opts.width)return 0===this.opts.element.outerWidth(!1)?"auto":this.opts.element.outerWidth(!1)+"px";if("copy"===this.opts.width||"resolve"===this.opts.width){if(c=this.opts.element.attr("style"),c!==b)for(d=c.split(";"),f=0,g=d.length;g>f;f+=1)if(h=d[f].replace(/\s/g,""),e=h.match(/^width:(([-+]?([0-9]*\.)?[0-9]+)(px|em|ex|%|in|cm|mm|pt|pc))/i),null!==e&&e.length>=1)return e[1];return"resolve"===this.opts.width?(c=this.opts.element.css("width"),c.indexOf("%")>0?c:0===this.opts.element.outerWidth(!1)?"auto":this.opts.element.outerWidth(!1)+"px"):null}return a.isFunction(this.opts.width)?this.opts.width():this.opts.width}var d=c.call(this);null!==d&&this.container.css("width",d)}}),G=D(F,{createContainer:function(){var b=a(document.createElement("div")).attr({"class":"select2-container"}).html(["","  "," ","","","","
          "," ","
            ","
          ","
          "].join(""));return b},enableInterface:function(){this.parent.enableInterface.apply(this,arguments)&&this.focusser.prop("disabled",!this.isInterfaceEnabled())},opening:function(){var c,d,e;this.opts.minimumResultsForSearch>=0&&this.showSearch(!0),this.parent.opening.apply(this,arguments),this.showSearchInput!==!1&&this.search.val(this.focusser.val()),this.opts.shouldFocusInput(this)&&(this.search.focus(),c=this.search.get(0),c.createTextRange?(d=c.createTextRange(),d.collapse(!1),d.select()):c.setSelectionRange&&(e=this.search.val().length,c.setSelectionRange(e,e))),""===this.search.val()&&this.nextSearchTerm!=b&&(this.search.val(this.nextSearchTerm),this.search.select()),this.focusser.prop("disabled",!0).val(""),this.updateResults(!0),this.opts.element.trigger(a.Event("select2-open"))},close:function(){this.opened()&&(this.parent.close.apply(this,arguments),this.focusser.prop("disabled",!1),this.opts.shouldFocusInput(this)&&this.focusser.focus())},focus:function(){this.opened()?this.close():(this.focusser.prop("disabled",!1),this.opts.shouldFocusInput(this)&&this.focusser.focus())},isFocused:function(){return this.container.hasClass("select2-container-active")},cancel:function(){this.parent.cancel.apply(this,arguments),this.focusser.prop("disabled",!1),this.opts.shouldFocusInput(this)&&this.focusser.focus()},destroy:function(){a("label[for='"+this.focusser.attr("id")+"']").attr("for",this.opts.element.attr("id")),this.parent.destroy.apply(this,arguments),C.call(this,"selection","focusser")},initContainer:function(){var b,d,e=this.container,f=this.dropdown,g=I();this.showSearch(this.opts.minimumResultsForSearch<0?!1:!0),this.selection=b=e.find(".select2-choice"),this.focusser=e.find(".select2-focusser"),b.find(".select2-chosen").attr("id","select2-chosen-"+g),this.focusser.attr("aria-labelledby","select2-chosen-"+g),this.results.attr("id","select2-results-"+g),this.search.attr("aria-owns","select2-results-"+g),this.focusser.attr("id","s2id_autogen"+g),d=a("label[for='"+this.opts.element.attr("id")+"']"),this.focusser.prev().text(d.text()).attr("for",this.focusser.attr("id"));var h=this.opts.element.attr("title");this.opts.element.attr("title",h||d.text()),this.focusser.attr("tabindex",this.elementTabIndex),this.search.attr("id",this.focusser.attr("id")+"_search"),this.search.prev().text(a("label[for='"+this.focusser.attr("id")+"']").text()).attr("for",this.search.attr("id")),this.search.on("keydown",this.bind(function(a){if(this.isInterfaceEnabled()&&229!=a.keyCode){if(a.which===E.PAGE_UP||a.which===E.PAGE_DOWN)return void p(a);switch(a.which){case E.UP:case E.DOWN:return this.moveHighlight(a.which===E.UP?-1:1),void p(a);case E.ENTER:return this.selectHighlighted(),void p(a);case E.TAB:return void this.selectHighlighted({noFocus:!0});case E.ESC:return this.cancel(a),void p(a)}}})),this.search.on("blur",this.bind(function(){document.activeElement===this.body.get(0)&&window.setTimeout(this.bind(function(){this.opened()&&this.search.focus()}),0)})),this.focusser.on("keydown",this.bind(function(a){if(this.isInterfaceEnabled()&&a.which!==E.TAB&&!E.isControl(a)&&!E.isFunctionKey(a)&&a.which!==E.ESC){if(this.opts.openOnEnter===!1&&a.which===E.ENTER)return void p(a);if(a.which==E.DOWN||a.which==E.UP||a.which==E.ENTER&&this.opts.openOnEnter){if(a.altKey||a.ctrlKey||a.shiftKey||a.metaKey)return;return this.open(),void p(a)}return a.which==E.DELETE||a.which==E.BACKSPACE?(this.opts.allowClear&&this.clear(),void p(a)):void 0}})),j(this.focusser),this.focusser.on("keyup-change input",this.bind(function(a){if(this.opts.minimumResultsForSearch>=0){if(a.stopPropagation(),this.opened())return;this.open()}})),b.on("mousedown touchstart","abbr",this.bind(function(a){this.isInterfaceEnabled()&&(this.clear(),q(a),this.close(),this.selection.focus())})),b.on("mousedown touchstart",this.bind(function(d){c(b),this.container.hasClass("select2-container-active")||this.opts.element.trigger(a.Event("select2-focus")),this.opened()?this.close():this.isInterfaceEnabled()&&this.open(),p(d)})),f.on("mousedown touchstart",this.bind(function(){this.opts.shouldFocusInput(this)&&this.search.focus()})),b.on("focus",this.bind(function(a){p(a)})),this.focusser.on("focus",this.bind(function(){this.container.hasClass("select2-container-active")||this.opts.element.trigger(a.Event("select2-focus")),this.container.addClass("select2-container-active")})).on("blur",this.bind(function(){this.opened()||(this.container.removeClass("select2-container-active"),this.opts.element.trigger(a.Event("select2-blur")))})),this.search.on("focus",this.bind(function(){this.container.hasClass("select2-container-active")||this.opts.element.trigger(a.Event("select2-focus")),this.container.addClass("select2-container-active")})),this.initContainerWidth(),this.opts.element.addClass("select2-offscreen"),this.setPlaceholder()},clear:function(b){var c=this.selection.data("select2-data");if(c){var d=a.Event("select2-clearing");if(this.opts.element.trigger(d),d.isDefaultPrevented())return;var e=this.getPlaceholderOption();this.opts.element.val(e?e.val():""),this.selection.find(".select2-chosen").empty(),this.selection.removeData("select2-data"),this.setPlaceholder(),b!==!1&&(this.opts.element.trigger({type:"select2-removed",val:this.id(c),choice:c}),this.triggerChange({removed:c}))}},initSelection:function(){if(this.isPlaceholderOptionSelected())this.updateSelection(null),this.close(),this.setPlaceholder();else{var a=this;this.opts.initSelection.call(null,this.opts.element,function(c){c!==b&&null!==c&&(a.updateSelection(c),a.close(),a.setPlaceholder(),a.nextSearchTerm=a.opts.nextSearchTerm(c,a.search.val()))})}},isPlaceholderOptionSelected:function(){var a;return this.getPlaceholder()===b?!1:(a=this.getPlaceholderOption())!==b&&a.prop("selected")||""===this.opts.element.val()||this.opts.element.val()===b||null===this.opts.element.val()},prepareOpts:function(){var b=this.parent.prepareOpts.apply(this,arguments),c=this;return"select"===b.element.get(0).tagName.toLowerCase()?b.initSelection=function(a,b){var d=a.find("option").filter(function(){return this.selected&&!this.disabled});b(c.optionToData(d))}:"data"in b&&(b.initSelection=b.initSelection||function(c,d){var e=c.val(),f=null;b.query({matcher:function(a,c,d){var h=g(e,b.id(d));return h&&(f=d),h},callback:a.isFunction(d)?function(){d(f)}:a.noop})}),b},getPlaceholder:function(){return this.select&&this.getPlaceholderOption()===b?b:this.parent.getPlaceholder.apply(this,arguments)},setPlaceholder:function(){var a=this.getPlaceholder();if(this.isPlaceholderOptionSelected()&&a!==b){if(this.select&&this.getPlaceholderOption()===b)return;this.selection.find(".select2-chosen").html(this.opts.escapeMarkup(a)),this.selection.addClass("select2-default"),this.container.removeClass("select2-allowclear")}},postprocessResults:function(a,b,c){var d=0,e=this;if(this.findHighlightableChoices().each2(function(a,b){return g(e.id(b.data("select2-data")),e.opts.element.val())?(d=a,!1):void 0}),c!==!1&&this.highlight(b===!0&&d>=0?d:0),b===!0){var f=this.opts.minimumResultsForSearch;f>=0&&this.showSearch(A(a.results)>=f)}},showSearch:function(b){this.showSearchInput!==b&&(this.showSearchInput=b,this.dropdown.find(".select2-search").toggleClass("select2-search-hidden",!b),this.dropdown.find(".select2-search").toggleClass("select2-offscreen",!b),a(this.dropdown,this.container).toggleClass("select2-with-searchbox",b))},onSelect:function(a,b){if(this.triggerSelect(a)){var c=this.opts.element.val(),d=this.data();this.opts.element.val(this.id(a)),this.updateSelection(a),this.opts.element.trigger({type:"select2-selected",val:this.id(a),choice:a}),this.nextSearchTerm=this.opts.nextSearchTerm(a,this.search.val()),this.close(),b&&b.noFocus||!this.opts.shouldFocusInput(this)||this.focusser.focus(),g(c,this.id(a))||this.triggerChange({added:a,removed:d})}},updateSelection:function(a){var c,d,e=this.selection.find(".select2-chosen");this.selection.data("select2-data",a),e.empty(),null!==a&&(c=this.opts.formatSelection(a,e,this.opts.escapeMarkup)),c!==b&&e.append(c),d=this.opts.formatSelectionCssClass(a,e),d!==b&&e.addClass(d),this.selection.removeClass("select2-default"),this.opts.allowClear&&this.getPlaceholder()!==b&&this.container.addClass("select2-allowclear")},val:function(){var a,c=!1,d=null,e=this,f=this.data();if(0===arguments.length)return this.opts.element.val();if(a=arguments[0],arguments.length>1&&(c=arguments[1]),this.select)this.select.val(a).find("option").filter(function(){return this.selected}).each2(function(a,b){return d=e.optionToData(b),!1}),this.updateSelection(d),this.setPlaceholder(),c&&this.triggerChange({added:d,removed:f});else{if(!a&&0!==a)return void this.clear(c);if(this.opts.initSelection===b)throw new Error("cannot call val() if initSelection() is not defined");this.opts.element.val(a),this.opts.initSelection(this.opts.element,function(a){e.opts.element.val(a?e.id(a):""),e.updateSelection(a),e.setPlaceholder(),c&&e.triggerChange({added:a,removed:f})})}},clearSearch:function(){this.search.val(""),this.focusser.val("")},data:function(a){var c,d=!1;return 0===arguments.length?(c=this.selection.data("select2-data"),c==b&&(c=null),c):(arguments.length>1&&(d=arguments[1]),void(a?(c=this.data(),this.opts.element.val(a?this.id(a):""),this.updateSelection(a),d&&this.triggerChange({added:a,removed:c})):this.clear(d)))}}),H=D(F,{createContainer:function(){var b=a(document.createElement("div")).attr({"class":"select2-container select2-container-multi"}).html(["
            ","
          • "," "," ","
          • ","
          ","
          ","
            ","
          ","
          "].join(""));return b},prepareOpts:function(){var b=this.parent.prepareOpts.apply(this,arguments),c=this;return"select"===b.element.get(0).tagName.toLowerCase()?b.initSelection=function(a,b){var d=[];a.find("option").filter(function(){return this.selected&&!this.disabled}).each2(function(a,b){d.push(c.optionToData(b))}),b(d)}:"data"in b&&(b.initSelection=b.initSelection||function(c,d){var e=h(c.val(),b.separator),f=[];b.query({matcher:function(c,d,h){var i=a.grep(e,function(a){return g(a,b.id(h))}).length;return i&&f.push(h),i},callback:a.isFunction(d)?function(){for(var a=[],c=0;c0||(this.selectChoice(null),this.clearPlaceholder(),this.container.hasClass("select2-container-active")||this.opts.element.trigger(a.Event("select2-focus")),this.open(),this.focusSearch(),b.preventDefault()))})),this.container.on("focus",c,this.bind(function(){this.isInterfaceEnabled()&&(this.container.hasClass("select2-container-active")||this.opts.element.trigger(a.Event("select2-focus")),this.container.addClass("select2-container-active"),this.dropdown.addClass("select2-drop-active"),this.clearPlaceholder())})),this.initContainerWidth(),this.opts.element.addClass("select2-offscreen"),this.clearSearch()},enableInterface:function(){this.parent.enableInterface.apply(this,arguments)&&this.search.prop("disabled",!this.isInterfaceEnabled())},initSelection:function(){if(""===this.opts.element.val()&&""===this.opts.element.text()&&(this.updateSelection([]),this.close(),this.clearSearch()),this.select||""!==this.opts.element.val()){var a=this;this.opts.initSelection.call(null,this.opts.element,function(c){c!==b&&null!==c&&(a.updateSelection(c),a.close(),a.clearSearch())})}},clearSearch:function(){var a=this.getPlaceholder(),c=this.getMaxSearchWidth();a!==b&&0===this.getVal().length&&this.search.hasClass("select2-focused")===!1?(this.search.val(a).addClass("select2-default"),this.search.width(c>0?c:this.container.css("width"))):this.search.val("").width(10)},clearPlaceholder:function(){this.search.hasClass("select2-default")&&this.search.val("").removeClass("select2-default")},opening:function(){this.clearPlaceholder(),this.resizeSearch(),this.parent.opening.apply(this,arguments),this.focusSearch(),""===this.search.val()&&this.nextSearchTerm!=b&&(this.search.val(this.nextSearchTerm),this.search.select()),this.updateResults(!0),this.opts.shouldFocusInput(this)&&this.search.focus(),this.opts.element.trigger(a.Event("select2-open"))},close:function(){this.opened()&&this.parent.close.apply(this,arguments)},focus:function(){this.close(),this.search.focus()},isFocused:function(){return this.search.hasClass("select2-focused")},updateSelection:function(b){var c=[],d=[],f=this;a(b).each(function(){e(f.id(this),c)<0&&(c.push(f.id(this)),d.push(this))}),b=d,this.selection.find(".select2-search-choice").remove(),a(b).each(function(){f.addSelectedChoice(this)}),f.postprocessResults()},tokenize:function(){var a=this.search.val();a=this.opts.tokenizer.call(this,a,this.data(),this.bind(this.onSelect),this.opts),null!=a&&a!=b&&(this.search.val(a),a.length>0&&this.open())},onSelect:function(a,c){this.triggerSelect(a)&&""!==a.text&&(this.addSelectedChoice(a),this.opts.element.trigger({type:"selected",val:this.id(a),choice:a}),this.nextSearchTerm=this.opts.nextSearchTerm(a,this.search.val()),this.clearSearch(),this.updateResults(),(this.select||!this.opts.closeOnSelect)&&this.postprocessResults(a,!1,this.opts.closeOnSelect===!0),this.opts.closeOnSelect?(this.close(),this.search.width(10)):this.countSelectableResults()>0?(this.search.width(10),this.resizeSearch(),this.getMaximumSelectionSize()>0&&this.val().length>=this.getMaximumSelectionSize()?this.updateResults(!0):this.nextSearchTerm!=b&&(this.search.val(this.nextSearchTerm),this.updateResults(),this.search.select()),this.positionDropdown()):(this.close(),this.search.width(10)),this.triggerChange({added:a}),c&&c.noFocus||this.focusSearch())},cancel:function(){this.close(),this.focusSearch()},addSelectedChoice:function(c){var d,e,f=!c.locked,g=a("
        • "),h=a("
        • "),i=f?g:h,j=this.id(c),k=this.getVal();d=this.opts.formatSelection(c,i.find("div"),this.opts.escapeMarkup),d!=b&&i.find("div").replaceWith("
          "+d+"
          "),e=this.opts.formatSelectionCssClass(c,i.find("div")),e!=b&&i.addClass(e),f&&i.find(".select2-search-choice-close").on("mousedown",p).on("click dblclick",this.bind(function(b){this.isInterfaceEnabled()&&(this.unselect(a(b.target)),this.selection.find(".select2-search-choice-focus").removeClass("select2-search-choice-focus"),p(b),this.close(),this.focusSearch())})).on("focus",this.bind(function(){this.isInterfaceEnabled()&&(this.container.addClass("select2-container-active"),this.dropdown.addClass("select2-drop-active"))})),i.data("select2-data",c),i.insertBefore(this.searchContainer),k.push(j),this.setVal(k)},unselect:function(b){var c,d,f=this.getVal();if(b=b.closest(".select2-search-choice"),0===b.length)throw"Invalid argument: "+b+". Must be .select2-search-choice";if(c=b.data("select2-data")){var g=a.Event("select2-removing");if(g.val=this.id(c),g.choice=c,this.opts.element.trigger(g),g.isDefaultPrevented())return!1;for(;(d=e(this.id(c),f))>=0;)f.splice(d,1),this.setVal(f),this.select&&this.postprocessResults();return b.remove(),this.opts.element.trigger({type:"select2-removed",val:this.id(c),choice:c}),this.triggerChange({removed:c}),!0}},postprocessResults:function(a,b,c){var d=this.getVal(),f=this.results.find(".select2-result"),g=this.results.find(".select2-result-with-children"),h=this;f.each2(function(a,b){var c=h.id(b.data("select2-data"));e(c,d)>=0&&(b.addClass("select2-selected"),b.find(".select2-result-selectable").addClass("select2-selected"))}),g.each2(function(a,b){b.is(".select2-result-selectable")||0!==b.find(".select2-result-selectable:not(.select2-selected)").length||b.addClass("select2-selected")}),-1==this.highlight()&&c!==!1&&h.highlight(0),!this.opts.createSearchChoice&&!f.filter(".select2-result:not(.select2-selected)").length>0&&(!a||a&&!a.more&&0===this.results.find(".select2-no-results").length)&&y(h.opts.formatNoMatches,"formatNoMatches")&&this.results.append("
        • "+z(h.opts.formatNoMatches,h.opts.element,h.search.val())+"
        • ")},getMaxSearchWidth:function(){return this.selection.width()-i(this.search)},resizeSearch:function(){var a,b,c,d,e,f=i(this.search);a=r(this.search)+10,b=this.search.offset().left,c=this.selection.width(),d=this.selection.offset().left,e=c-(b-d)-f,a>e&&(e=c-f),40>e&&(e=c-f),0>=e&&(e=a),this.search.width(Math.floor(e))},getVal:function(){var a;return this.select?(a=this.select.val(),null===a?[]:a):(a=this.opts.element.val(),h(a,this.opts.separator))},setVal:function(b){var c;this.select?this.select.val(b):(c=[],a(b).each(function(){e(this,c)<0&&c.push(this)}),this.opts.element.val(0===c.length?"":c.join(this.opts.separator)))},buildChangeDetails:function(a,b){for(var b=b.slice(0),a=a.slice(0),c=0;c0&&c--,a.splice(d,1),d--);return{added:b,removed:a}},val:function(c,d){var e,f=this;if(0===arguments.length)return this.getVal();if(e=this.data(),e.length||(e=[]),!c&&0!==c)return this.opts.element.val(""),this.updateSelection([]),this.clearSearch(),void(d&&this.triggerChange({added:this.data(),removed:e}));if(this.setVal(c),this.select)this.opts.initSelection(this.select,this.bind(this.updateSelection)),d&&this.triggerChange(this.buildChangeDetails(e,this.data()));else{if(this.opts.initSelection===b)throw new Error("val() cannot be called if initSelection() is not defined");this.opts.initSelection(this.opts.element,function(b){var c=a.map(b,f.id);f.setVal(c),f.updateSelection(b),f.clearSearch(),d&&f.triggerChange(f.buildChangeDetails(e,f.data()))})}this.clearSearch()},onSortStart:function(){if(this.select)throw new Error("Sorting of elements is not supported when attached to instead.");this.search.width(0),this.searchContainer.hide()},onSortEnd:function(){var b=[],c=this;this.searchContainer.show(),this.searchContainer.appendTo(this.searchContainer.parent()),this.resizeSearch(),this.selection.find(".select2-search-choice").each(function(){b.push(c.opts.id(a(this).data("select2-data")))}),this.setVal(b),this.triggerChange()},data:function(b,c){var d,e,f=this;return 0===arguments.length?this.selection.children(".select2-search-choice").map(function(){return a(this).data("select2-data")}).get():(e=this.data(),b||(b=[]),d=a.map(b,function(a){return f.opts.id(a)}),this.setVal(d),this.updateSelection(b),this.clearSearch(),c&&this.triggerChange(this.buildChangeDetails(e,this.data())),void 0)}}),a.fn.select2=function(){var c,d,f,g,h,i=Array.prototype.slice.call(arguments,0),j=["val","destroy","opened","open","close","focus","isFocused","container","dropdown","onSortStart","onSortEnd","enable","disable","readonly","positionDropdown","data","search"],k=["opened","isFocused","container","dropdown"],l=["val","data"],m={search:"externalSearch"};return this.each(function(){if(0===i.length||"object"==typeof i[0])c=0===i.length?{}:a.extend({},i[0]),c.element=a(this),"select"===c.element.get(0).tagName.toLowerCase()?h=c.element.prop("multiple"):(h=c.multiple||!1,"tags"in c&&(c.multiple=h=!0)),d=h?new window.Select2.class.multi:new window.Select2.class.single,d.init(c);else{if("string"!=typeof i[0])throw"Invalid arguments to select2 plugin: "+i;if(e(i[0],j)<0)throw"Unknown method: "+i[0];if(g=b,d=a(this).data("select2"),d===b)return;if(f=i[0],"container"===f?g=d.container:"dropdown"===f?g=d.dropdown:(m[f]&&(f=m[f]),g=d[f].apply(d,i.slice(1))),e(i[0],k)>=0||e(i[0],l)>=0&&1==i.length)return!1}}),g===b?this:g},a.fn.select2.defaults={width:"copy",loadMorePadding:0,closeOnSelect:!0,openOnEnter:!0,containerCss:{},dropdownCss:{},containerCssClass:"",dropdownCssClass:"",formatResult:function(a,b,c,d){var e=[];return t(a.text,c.term,e,d),e.join("")},formatSelection:function(a,c,d){return a?d(a.text):b},sortResults:function(a){return a},formatResultCssClass:function(a){return a.css},formatSelectionCssClass:function(){return b},minimumResultsForSearch:0,minimumInputLength:0,maximumInputLength:null,maximumSelectionSize:0,id:function(a){return a==b?null:a.id},matcher:function(a,b){return d(""+b).toUpperCase().indexOf(d(""+a).toUpperCase())>=0},separator:",",tokenSeparators:[],tokenizer:B,escapeMarkup:u,blurOnChange:!1,selectOnBlur:!1,adaptContainerCssClass:function(a){return a},adaptDropdownCssClass:function(){return null},nextSearchTerm:function(){return b},searchInputPlaceholder:"",createSearchChoicePosition:"top",shouldFocusInput:function(a){var b="ontouchstart"in window||navigator.msMaxTouchPoints>0;return b&&a.opts.minimumResultsForSearch<0?!1:!0}},a.fn.select2.locales=[],a.fn.select2.locales.en={formatMatches:function(a){return 1===a?"One result is available, press enter to select it.":a+" results are available, use up and down arrow keys to navigate."},formatNoMatches:function(){return"No matches found"},formatAjaxError:function(){return"Loading failed"},formatInputTooShort:function(a,b){var c=b-a.length;return"Please enter "+c+" or more character"+(1==c?"":"s")},formatInputTooLong:function(a,b){var c=a.length-b;return"Please delete "+c+" character"+(1==c?"":"s")},formatSelectionTooBig:function(a){return"You can only select "+a+" item"+(1==a?"":"s")},formatLoadMore:function(){return"Loading more results…"},formatSearching:function(){return"Searching…"}},a.extend(a.fn.select2.defaults,a.fn.select2.locales.en),a.fn.select2.ajaxDefaults={transport:a.ajax,params:{type:"GET",cache:!1,dataType:"json"}},window.Select2={query:{ajax:v,local:w,tags:x},util:{debounce:l,markMatch:t,escapeMarkup:u,stripDiacritics:d},"class":{"abstract":F,single:G,multi:H}}}}(jQuery); +//# sourceMappingURL=../../../maps/libs/jquery/select2.js.map \ No newline at end of file diff --git a/static/scripts/libs/lunr.js b/static/scripts/libs/lunr.js index b5bacd97960..fdb74d9ef3d 100644 --- a/static/scripts/libs/lunr.js +++ b/static/scripts/libs/lunr.js @@ -1,1910 +1,2 @@ -/** - * lunr - http://lunrjs.com - A bit like Solr, but much smaller and not as bright - 0.5.7 - * Copyright (C) 2014 Oliver Nightingale - * MIT Licensed - * @license - */ - -(function(){ - -/** - * Convenience function for instantiating a new lunr index and configuring it - * with the default pipeline functions and the passed config function. - * - * When using this convenience function a new index will be created with the - * following functions already in the pipeline: - * - * lunr.StopWordFilter - filters out any stop words before they enter the - * index - * - * lunr.stemmer - stems the tokens before entering the index. - * - * Example: - * - * var idx = lunr(function () { - * this.field('title', 10) - * this.field('tags', 100) - * this.field('body') - * - * this.ref('cid') - * - * this.pipeline.add(function () { - * // some custom pipeline function - * }) - * - * }) - * - * @param {Function} config A function that will be called with the new instance - * of the lunr.Index as both its context and first parameter. It can be used to - * customize the instance of new lunr.Index. - * @namespace - * @module - * @returns {lunr.Index} - * - */ -var lunr = function (config) { - var idx = new lunr.Index - - idx.pipeline.add( - lunr.trimmer, - lunr.stopWordFilter, - lunr.stemmer - ) - - if (config) config.call(idx, idx) - - return idx -} - -lunr.version = "0.5.7" -/*! - * lunr.utils - * Copyright (C) 2014 Oliver Nightingale - */ - -/** - * A namespace containing utils for the rest of the lunr library - */ -lunr.utils = {} - -/** - * Print a warning message to the console. - * - * @param {String} message The message to be printed. - * @memberOf Utils - */ -lunr.utils.warn = (function (global) { - return function (message) { - if (global.console && console.warn) { - console.warn(message) - } - } -})(this) - -/*! - * lunr.EventEmitter - * Copyright (C) 2014 Oliver Nightingale - */ - -/** - * lunr.EventEmitter is an event emitter for lunr. It manages adding and removing event handlers and triggering events and their handlers. - * - * @constructor - */ -lunr.EventEmitter = function () { - this.events = {} -} - -/** - * Binds a handler function to a specific event(s). - * - * Can bind a single function to many different events in one call. - * - * @param {String} [eventName] The name(s) of events to bind this function to. - * @param {Function} handler The function to call when an event is fired. - * @memberOf EventEmitter - */ -lunr.EventEmitter.prototype.addListener = function () { - var args = Array.prototype.slice.call(arguments), - fn = args.pop(), - names = args - - if (typeof fn !== "function") throw new TypeError ("last argument must be a function") - - names.forEach(function (name) { - if (!this.hasHandler(name)) this.events[name] = [] - this.events[name].push(fn) - }, this) -} - -/** - * Removes a handler function from a specific event. - * - * @param {String} eventName The name of the event to remove this function from. - * @param {Function} handler The function to remove from an event. - * @memberOf EventEmitter - */ -lunr.EventEmitter.prototype.removeListener = function (name, fn) { - if (!this.hasHandler(name)) return - - var fnIndex = this.events[name].indexOf(fn) - this.events[name].splice(fnIndex, 1) - - if (!this.events[name].length) delete this.events[name] -} - -/** - * Calls all functions bound to the given event. - * - * Additional data can be passed to the event handler as arguments to `emit` - * after the event name. - * - * @param {String} eventName The name of the event to emit. - * @memberOf EventEmitter - */ -lunr.EventEmitter.prototype.emit = function (name) { - if (!this.hasHandler(name)) return - - var args = Array.prototype.slice.call(arguments, 1) - - this.events[name].forEach(function (fn) { - fn.apply(undefined, args) - }) -} - -/** - * Checks whether a handler has ever been stored against an event. - * - * @param {String} eventName The name of the event to check. - * @private - * @memberOf EventEmitter - */ -lunr.EventEmitter.prototype.hasHandler = function (name) { - return name in this.events -} - -/*! - * lunr.tokenizer - * Copyright (C) 2014 Oliver Nightingale - */ - -/** - * A function for splitting a string into tokens ready to be inserted into - * the search index. - * - * @module - * @param {String} obj The string to convert into tokens - * @returns {Array} - */ -lunr.tokenizer = function (obj) { - if (!arguments.length || obj == null || obj == undefined) return [] - if (Array.isArray(obj)) return obj.map(function (t) { return t.toLowerCase() }) - - var str = obj.toString().replace(/^\s+/, '') - - for (var i = str.length - 1; i >= 0; i--) { - if (/\S/.test(str.charAt(i))) { - str = str.substring(0, i + 1) - break - } - } - - return str - .split(/(?:\s+|\-)/) - .filter(function (token) { - return !!token - }) - .map(function (token) { - return token.toLowerCase() - }) -} -/*! - * lunr.Pipeline - * Copyright (C) 2014 Oliver Nightingale - */ - -/** - * lunr.Pipelines maintain an ordered list of functions to be applied to all - * tokens in documents entering the search index and queries being ran against - * the index. - * - * An instance of lunr.Index created with the lunr shortcut will contain a - * pipeline with a stop word filter and an English language stemmer. Extra - * functions can be added before or after either of these functions or these - * default functions can be removed. - * - * When run the pipeline will call each function in turn, passing a token, the - * index of that token in the original list of all tokens and finally a list of - * all the original tokens. - * - * The output of functions in the pipeline will be passed to the next function - * in the pipeline. To exclude a token from entering the index the function - * should return undefined, the rest of the pipeline will not be called with - * this token. - * - * For serialisation of pipelines to work, all functions used in an instance of - * a pipeline should be registered with lunr.Pipeline. Registered functions can - * then be loaded. If trying to load a serialised pipeline that uses functions - * that are not registered an error will be thrown. - * - * If not planning on serialising the pipeline then registering pipeline functions - * is not necessary. - * - * @constructor - */ -lunr.Pipeline = function () { - this._stack = [] -} - -lunr.Pipeline.registeredFunctions = {} - -/** - * Register a function with the pipeline. - * - * Functions that are used in the pipeline should be registered if the pipeline - * needs to be serialised, or a serialised pipeline needs to be loaded. - * - * Registering a function does not add it to a pipeline, functions must still be - * added to instances of the pipeline for them to be used when running a pipeline. - * - * @param {Function} fn The function to check for. - * @param {String} label The label to register this function with - * @memberOf Pipeline - */ -lunr.Pipeline.registerFunction = function (fn, label) { - if (label in this.registeredFunctions) { - lunr.utils.warn('Overwriting existing registered function: ' + label) - } - - fn.label = label - lunr.Pipeline.registeredFunctions[fn.label] = fn -} - -/** - * Warns if the function is not registered as a Pipeline function. - * - * @param {Function} fn The function to check for. - * @private - * @memberOf Pipeline - */ -lunr.Pipeline.warnIfFunctionNotRegistered = function (fn) { - var isRegistered = fn.label && (fn.label in this.registeredFunctions) - - if (!isRegistered) { - lunr.utils.warn('Function is not registered with pipeline. This may cause problems when serialising the index.\n', fn) - } -} - -/** - * Loads a previously serialised pipeline. - * - * All functions to be loaded must already be registered with lunr.Pipeline. - * If any function from the serialised data has not been registered then an - * error will be thrown. - * - * @param {Object} serialised The serialised pipeline to load. - * @returns {lunr.Pipeline} - * @memberOf Pipeline - */ -lunr.Pipeline.load = function (serialised) { - var pipeline = new lunr.Pipeline - - serialised.forEach(function (fnName) { - var fn = lunr.Pipeline.registeredFunctions[fnName] - - if (fn) { - pipeline.add(fn) - } else { - throw new Error ('Cannot load un-registered function: ' + fnName) - } - }) - - return pipeline -} - -/** - * Adds new functions to the end of the pipeline. - * - * Logs a warning if the function has not been registered. - * - * @param {Function} functions Any number of functions to add to the pipeline. - * @memberOf Pipeline - */ -lunr.Pipeline.prototype.add = function () { - var fns = Array.prototype.slice.call(arguments) - - fns.forEach(function (fn) { - lunr.Pipeline.warnIfFunctionNotRegistered(fn) - this._stack.push(fn) - }, this) -} - -/** - * Adds a single function after a function that already exists in the - * pipeline. - * - * Logs a warning if the function has not been registered. - * - * @param {Function} existingFn A function that already exists in the pipeline. - * @param {Function} newFn The new function to add to the pipeline. - * @memberOf Pipeline - */ -lunr.Pipeline.prototype.after = function (existingFn, newFn) { - lunr.Pipeline.warnIfFunctionNotRegistered(newFn) - - var pos = this._stack.indexOf(existingFn) + 1 - this._stack.splice(pos, 0, newFn) -} - -/** - * Adds a single function before a function that already exists in the - * pipeline. - * - * Logs a warning if the function has not been registered. - * - * @param {Function} existingFn A function that already exists in the pipeline. - * @param {Function} newFn The new function to add to the pipeline. - * @memberOf Pipeline - */ -lunr.Pipeline.prototype.before = function (existingFn, newFn) { - lunr.Pipeline.warnIfFunctionNotRegistered(newFn) - - var pos = this._stack.indexOf(existingFn) - this._stack.splice(pos, 0, newFn) -} - -/** - * Removes a function from the pipeline. - * - * @param {Function} fn The function to remove from the pipeline. - * @memberOf Pipeline - */ -lunr.Pipeline.prototype.remove = function (fn) { - var pos = this._stack.indexOf(fn) - this._stack.splice(pos, 1) -} - -/** - * Runs the current list of functions that make up the pipeline against the - * passed tokens. - * - * @param {Array} tokens The tokens to run through the pipeline. - * @returns {Array} - * @memberOf Pipeline - */ -lunr.Pipeline.prototype.run = function (tokens) { - var out = [], - tokenLength = tokens.length, - stackLength = this._stack.length - - for (var i = 0; i < tokenLength; i++) { - var token = tokens[i] - - for (var j = 0; j < stackLength; j++) { - token = this._stack[j](token, i, tokens) - if (token === void 0) break - }; - - if (token !== void 0) out.push(token) - }; - - return out -} - -/** - * Resets the pipeline by removing any existing processors. - * - * @memberOf Pipeline - */ -lunr.Pipeline.prototype.reset = function () { - this._stack = [] -} - -/** - * Returns a representation of the pipeline ready for serialisation. - * - * Logs a warning if the function has not been registered. - * - * @returns {Array} - * @memberOf Pipeline - */ -lunr.Pipeline.prototype.toJSON = function () { - return this._stack.map(function (fn) { - lunr.Pipeline.warnIfFunctionNotRegistered(fn) - - return fn.label - }) -} -/*! - * lunr.Vector - * Copyright (C) 2014 Oliver Nightingale - */ - -/** - * lunr.Vectors implement vector related operations for - * a series of elements. - * - * @constructor - */ -lunr.Vector = function () { - this._magnitude = null - this.list = undefined - this.length = 0 -} - -/** - * lunr.Vector.Node is a simple struct for each node - * in a lunr.Vector. - * - * @private - * @param {Number} The index of the node in the vector. - * @param {Object} The data at this node in the vector. - * @param {lunr.Vector.Node} The node directly after this node in the vector. - * @constructor - * @memberOf Vector - */ -lunr.Vector.Node = function (idx, val, next) { - this.idx = idx - this.val = val - this.next = next -} - -/** - * Inserts a new value at a position in a vector. - * - * @param {Number} The index at which to insert a value. - * @param {Object} The object to insert in the vector. - * @memberOf Vector. - */ -lunr.Vector.prototype.insert = function (idx, val) { - var list = this.list - - if (!list) { - this.list = new lunr.Vector.Node (idx, val, list) - return this.length++ - } - - var prev = list, - next = list.next - - while (next != undefined) { - if (idx < next.idx) { - prev.next = new lunr.Vector.Node (idx, val, next) - return this.length++ - } - - prev = next, next = next.next - } - - prev.next = new lunr.Vector.Node (idx, val, next) - return this.length++ -} - -/** - * Calculates the magnitude of this vector. - * - * @returns {Number} - * @memberOf Vector - */ -lunr.Vector.prototype.magnitude = function () { - if (this._magniture) return this._magnitude - var node = this.list, - sumOfSquares = 0, - val - - while (node) { - val = node.val - sumOfSquares += val * val - node = node.next - } - - return this._magnitude = Math.sqrt(sumOfSquares) -} - -/** - * Calculates the dot product of this vector and another vector. - * - * @param {lunr.Vector} otherVector The vector to compute the dot product with. - * @returns {Number} - * @memberOf Vector - */ -lunr.Vector.prototype.dot = function (otherVector) { - var node = this.list, - otherNode = otherVector.list, - dotProduct = 0 - - while (node && otherNode) { - if (node.idx < otherNode.idx) { - node = node.next - } else if (node.idx > otherNode.idx) { - otherNode = otherNode.next - } else { - dotProduct += node.val * otherNode.val - node = node.next - otherNode = otherNode.next - } - } - - return dotProduct -} - -/** - * Calculates the cosine similarity between this vector and another - * vector. - * - * @param {lunr.Vector} otherVector The other vector to calculate the - * similarity with. - * @returns {Number} - * @memberOf Vector - */ -lunr.Vector.prototype.similarity = function (otherVector) { - return this.dot(otherVector) / (this.magnitude() * otherVector.magnitude()) -} -/*! - * lunr.SortedSet - * Copyright (C) 2014 Oliver Nightingale - */ - -/** - * lunr.SortedSets are used to maintain an array of uniq values in a sorted - * order. - * - * @constructor - */ -lunr.SortedSet = function () { - this.length = 0 - this.elements = [] -} - -/** - * Loads a previously serialised sorted set. - * - * @param {Array} serialisedData The serialised set to load. - * @returns {lunr.SortedSet} - * @memberOf SortedSet - */ -lunr.SortedSet.load = function (serialisedData) { - var set = new this - - set.elements = serialisedData - set.length = serialisedData.length - - return set -} - -/** - * Inserts new items into the set in the correct position to maintain the - * order. - * - * @param {Object} The objects to add to this set. - * @memberOf SortedSet - */ -lunr.SortedSet.prototype.add = function () { - Array.prototype.slice.call(arguments).forEach(function (element) { - if (~this.indexOf(element)) return - this.elements.splice(this.locationFor(element), 0, element) - }, this) - - this.length = this.elements.length -} - -/** - * Converts this sorted set into an array. - * - * @returns {Array} - * @memberOf SortedSet - */ -lunr.SortedSet.prototype.toArray = function () { - return this.elements.slice() -} - -/** - * Creates a new array with the results of calling a provided function on every - * element in this sorted set. - * - * Delegates to Array.prototype.map and has the same signature. - * - * @param {Function} fn The function that is called on each element of the - * set. - * @param {Object} ctx An optional object that can be used as the context - * for the function fn. - * @returns {Array} - * @memberOf SortedSet - */ -lunr.SortedSet.prototype.map = function (fn, ctx) { - return this.elements.map(fn, ctx) -} - -/** - * Executes a provided function once per sorted set element. - * - * Delegates to Array.prototype.forEach and has the same signature. - * - * @param {Function} fn The function that is called on each element of the - * set. - * @param {Object} ctx An optional object that can be used as the context - * @memberOf SortedSet - * for the function fn. - */ -lunr.SortedSet.prototype.forEach = function (fn, ctx) { - return this.elements.forEach(fn, ctx) -} - -/** - * Returns the index at which a given element can be found in the - * sorted set, or -1 if it is not present. - * - * @param {Object} elem The object to locate in the sorted set. - * @param {Number} start An optional index at which to start searching from - * within the set. - * @param {Number} end An optional index at which to stop search from within - * the set. - * @returns {Number} - * @memberOf SortedSet - */ -lunr.SortedSet.prototype.indexOf = function (elem, start, end) { - var start = start || 0, - end = end || this.elements.length, - sectionLength = end - start, - pivot = start + Math.floor(sectionLength / 2), - pivotElem = this.elements[pivot] - - if (sectionLength <= 1) { - if (pivotElem === elem) { - return pivot - } else { - return -1 - } - } - - if (pivotElem < elem) return this.indexOf(elem, pivot, end) - if (pivotElem > elem) return this.indexOf(elem, start, pivot) - if (pivotElem === elem) return pivot -} - -/** - * Returns the position within the sorted set that an element should be - * inserted at to maintain the current order of the set. - * - * This function assumes that the element to search for does not already exist - * in the sorted set. - * - * @param {Object} elem The elem to find the position for in the set - * @param {Number} start An optional index at which to start searching from - * within the set. - * @param {Number} end An optional index at which to stop search from within - * the set. - * @returns {Number} - * @memberOf SortedSet - */ -lunr.SortedSet.prototype.locationFor = function (elem, start, end) { - var start = start || 0, - end = end || this.elements.length, - sectionLength = end - start, - pivot = start + Math.floor(sectionLength / 2), - pivotElem = this.elements[pivot] - - if (sectionLength <= 1) { - if (pivotElem > elem) return pivot - if (pivotElem < elem) return pivot + 1 - } - - if (pivotElem < elem) return this.locationFor(elem, pivot, end) - if (pivotElem > elem) return this.locationFor(elem, start, pivot) -} - -/** - * Creates a new lunr.SortedSet that contains the elements in the intersection - * of this set and the passed set. - * - * @param {lunr.SortedSet} otherSet The set to intersect with this set. - * @returns {lunr.SortedSet} - * @memberOf SortedSet - */ -lunr.SortedSet.prototype.intersect = function (otherSet) { - var intersectSet = new lunr.SortedSet, - i = 0, j = 0, - a_len = this.length, b_len = otherSet.length, - a = this.elements, b = otherSet.elements - - while (true) { - if (i > a_len - 1 || j > b_len - 1) break - - if (a[i] === b[j]) { - intersectSet.add(a[i]) - i++, j++ - continue - } - - if (a[i] < b[j]) { - i++ - continue - } - - if (a[i] > b[j]) { - j++ - continue - } - }; - - return intersectSet -} - -/** - * Makes a copy of this set - * - * @returns {lunr.SortedSet} - * @memberOf SortedSet - */ -lunr.SortedSet.prototype.clone = function () { - var clone = new lunr.SortedSet - - clone.elements = this.toArray() - clone.length = clone.elements.length - - return clone -} - -/** - * Creates a new lunr.SortedSet that contains the elements in the union - * of this set and the passed set. - * - * @param {lunr.SortedSet} otherSet The set to union with this set. - * @returns {lunr.SortedSet} - * @memberOf SortedSet - */ -lunr.SortedSet.prototype.union = function (otherSet) { - var longSet, shortSet, unionSet - - if (this.length >= otherSet.length) { - longSet = this, shortSet = otherSet - } else { - longSet = otherSet, shortSet = this - } - - unionSet = longSet.clone() - - unionSet.add.apply(unionSet, shortSet.toArray()) - - return unionSet -} - -/** - * Returns a representation of the sorted set ready for serialisation. - * - * @returns {Array} - * @memberOf SortedSet - */ -lunr.SortedSet.prototype.toJSON = function () { - return this.toArray() -} -/*! - * lunr.Index - * Copyright (C) 2014 Oliver Nightingale - */ - -/** - * lunr.Index is object that manages a search index. It contains the indexes - * and stores all the tokens and document lookups. It also provides the main - * user facing API for the library. - * - * @constructor - */ -lunr.Index = function () { - this._fields = [] - this._ref = 'id' - this.pipeline = new lunr.Pipeline - this.documentStore = new lunr.Store - this.tokenStore = new lunr.TokenStore - this.corpusTokens = new lunr.SortedSet - this.eventEmitter = new lunr.EventEmitter - - this._idfCache = {} - - this.on('add', 'remove', 'update', (function () { - this._idfCache = {} - }).bind(this)) -} - -/** - * Bind a handler to events being emitted by the index. - * - * The handler can be bound to many events at the same time. - * - * @param {String} [eventName] The name(s) of events to bind the function to. - * @param {Function} handler The serialised set to load. - * @memberOf Index - */ -lunr.Index.prototype.on = function () { - var args = Array.prototype.slice.call(arguments) - return this.eventEmitter.addListener.apply(this.eventEmitter, args) -} - -/** - * Removes a handler from an event being emitted by the index. - * - * @param {String} eventName The name of events to remove the function from. - * @param {Function} handler The serialised set to load. - * @memberOf Index - */ -lunr.Index.prototype.off = function (name, fn) { - return this.eventEmitter.removeListener(name, fn) -} - -/** - * Loads a previously serialised index. - * - * Issues a warning if the index being imported was serialised - * by a different version of lunr. - * - * @param {Object} serialisedData The serialised set to load. - * @returns {lunr.Index} - * @memberOf Index - */ -lunr.Index.load = function (serialisedData) { - if (serialisedData.version !== lunr.version) { - lunr.utils.warn('version mismatch: current ' + lunr.version + ' importing ' + serialisedData.version) - } - - var idx = new this - - idx._fields = serialisedData.fields - idx._ref = serialisedData.ref - - idx.documentStore = lunr.Store.load(serialisedData.documentStore) - idx.tokenStore = lunr.TokenStore.load(serialisedData.tokenStore) - idx.corpusTokens = lunr.SortedSet.load(serialisedData.corpusTokens) - idx.pipeline = lunr.Pipeline.load(serialisedData.pipeline) - - return idx -} - -/** - * Adds a field to the list of fields that will be searchable within documents - * in the index. - * - * An optional boost param can be passed to affect how much tokens in this field - * rank in search results, by default the boost value is 1. - * - * Fields should be added before any documents are added to the index, fields - * that are added after documents are added to the index will only apply to new - * documents added to the index. - * - * @param {String} fieldName The name of the field within the document that - * should be indexed - * @param {Number} boost An optional boost that can be applied to terms in this - * field. - * @returns {lunr.Index} - * @memberOf Index - */ -lunr.Index.prototype.field = function (fieldName, opts) { - var opts = opts || {}, - field = { name: fieldName, boost: opts.boost || 1 } - - this._fields.push(field) - return this -} - -/** - * Sets the property used to uniquely identify documents added to the index, - * by default this property is 'id'. - * - * This should only be changed before adding documents to the index, changing - * the ref property without resetting the index can lead to unexpected results. - * - * @param {String} refName The property to use to uniquely identify the - * documents in the index. - * @param {Boolean} emitEvent Whether to emit add events, defaults to true - * @returns {lunr.Index} - * @memberOf Index - */ -lunr.Index.prototype.ref = function (refName) { - this._ref = refName - return this -} - -/** - * Add a document to the index. - * - * This is the way new documents enter the index, this function will run the - * fields from the document through the index's pipeline and then add it to - * the index, it will then show up in search results. - * - * An 'add' event is emitted with the document that has been added and the index - * the document has been added to. This event can be silenced by passing false - * as the second argument to add. - * - * @param {Object} doc The document to add to the index. - * @param {Boolean} emitEvent Whether or not to emit events, default true. - * @memberOf Index - */ -lunr.Index.prototype.add = function (doc, emitEvent) { - var docTokens = {}, - allDocumentTokens = new lunr.SortedSet, - docRef = doc[this._ref], - emitEvent = emitEvent === undefined ? true : emitEvent - - this._fields.forEach(function (field) { - var fieldTokens = this.pipeline.run(lunr.tokenizer(doc[field.name])) - - docTokens[field.name] = fieldTokens - lunr.SortedSet.prototype.add.apply(allDocumentTokens, fieldTokens) - }, this) - - this.documentStore.set(docRef, allDocumentTokens) - lunr.SortedSet.prototype.add.apply(this.corpusTokens, allDocumentTokens.toArray()) - - for (var i = 0; i < allDocumentTokens.length; i++) { - var token = allDocumentTokens.elements[i] - var tf = this._fields.reduce(function (memo, field) { - var fieldLength = docTokens[field.name].length - - if (!fieldLength) return memo - - var tokenCount = docTokens[field.name].filter(function (t) { return t === token }).length - - return memo + (tokenCount / fieldLength * field.boost) - }, 0) - - this.tokenStore.add(token, { ref: docRef, tf: tf }) - }; - - if (emitEvent) this.eventEmitter.emit('add', doc, this) -} - -/** - * Removes a document from the index. - * - * To make sure documents no longer show up in search results they can be - * removed from the index using this method. - * - * The document passed only needs to have the same ref property value as the - * document that was added to the index, they could be completely different - * objects. - * - * A 'remove' event is emitted with the document that has been removed and the index - * the document has been removed from. This event can be silenced by passing false - * as the second argument to remove. - * - * @param {Object} doc The document to remove from the index. - * @param {Boolean} emitEvent Whether to emit remove events, defaults to true - * @memberOf Index - */ -lunr.Index.prototype.remove = function (doc, emitEvent) { - var docRef = doc[this._ref], - emitEvent = emitEvent === undefined ? true : emitEvent - - if (!this.documentStore.has(docRef)) return - - var docTokens = this.documentStore.get(docRef) - - this.documentStore.remove(docRef) - - docTokens.forEach(function (token) { - this.tokenStore.remove(token, docRef) - }, this) - - if (emitEvent) this.eventEmitter.emit('remove', doc, this) -} - -/** - * Updates a document in the index. - * - * When a document contained within the index gets updated, fields changed, - * added or removed, to make sure it correctly matched against search queries, - * it should be updated in the index. - * - * This method is just a wrapper around `remove` and `add` - * - * An 'update' event is emitted with the document that has been updated and the index. - * This event can be silenced by passing false as the second argument to update. Only - * an update event will be fired, the 'add' and 'remove' events of the underlying calls - * are silenced. - * - * @param {Object} doc The document to update in the index. - * @param {Boolean} emitEvent Whether to emit update events, defaults to true - * @see Index.prototype.remove - * @see Index.prototype.add - * @memberOf Index - */ -lunr.Index.prototype.update = function (doc, emitEvent) { - var emitEvent = emitEvent === undefined ? true : emitEvent - - this.remove(doc, false) - this.add(doc, false) - - if (emitEvent) this.eventEmitter.emit('update', doc, this) -} - -/** - * Calculates the inverse document frequency for a token within the index. - * - * @param {String} token The token to calculate the idf of. - * @see Index.prototype.idf - * @private - * @memberOf Index - */ -lunr.Index.prototype.idf = function (term) { - var cacheKey = "@" + term - if (Object.prototype.hasOwnProperty.call(this._idfCache, cacheKey)) return this._idfCache[cacheKey] - - var documentFrequency = this.tokenStore.count(term), - idf = 1 - - if (documentFrequency > 0) { - idf = 1 + Math.log(this.tokenStore.length / documentFrequency) - } - - return this._idfCache[cacheKey] = idf -} - -/** - * Searches the index using the passed query. - * - * Queries should be a string, multiple words are allowed and will lead to an - * AND based query, e.g. `idx.search('foo bar')` will run a search for - * documents containing both 'foo' and 'bar'. - * - * All query tokens are passed through the same pipeline that document tokens - * are passed through, so any language processing involved will be run on every - * query term. - * - * Each query term is expanded, so that the term 'he' might be expanded to - * 'hello' and 'help' if those terms were already included in the index. - * - * Matching documents are returned as an array of objects, each object contains - * the matching document ref, as set for this index, and the similarity score - * for this document against the query. - * - * @param {String} query The query to search the index with. - * @returns {Object} - * @see Index.prototype.idf - * @see Index.prototype.documentVector - * @memberOf Index - */ -lunr.Index.prototype.search = function (query) { - var queryTokens = this.pipeline.run(lunr.tokenizer(query)), - queryVector = new lunr.Vector, - documentSets = [], - fieldBoosts = this._fields.reduce(function (memo, f) { return memo + f.boost }, 0) - - var hasSomeToken = queryTokens.some(function (token) { - return this.tokenStore.has(token) - }, this) - - if (!hasSomeToken) return [] - - queryTokens - .forEach(function (token, i, tokens) { - var tf = 1 / tokens.length * this._fields.length * fieldBoosts, - self = this - - var set = this.tokenStore.expand(token).reduce(function (memo, key) { - var pos = self.corpusTokens.indexOf(key), - idf = self.idf(key), - similarityBoost = 1, - set = new lunr.SortedSet - - // if the expanded key is not an exact match to the token then - // penalise the score for this key by how different the key is - // to the token. - if (key !== token) { - var diff = Math.max(3, key.length - token.length) - similarityBoost = 1 / Math.log(diff) - } - - // calculate the query tf-idf score for this token - // applying an similarityBoost to ensure exact matches - // these rank higher than expanded terms - if (pos > -1) queryVector.insert(pos, tf * idf * similarityBoost) - - // add all the documents that have this key into a set - Object.keys(self.tokenStore.get(key)).forEach(function (ref) { set.add(ref) }) - - return memo.union(set) - }, new lunr.SortedSet) - - documentSets.push(set) - }, this) - - var documentSet = documentSets.reduce(function (memo, set) { - return memo.intersect(set) - }) - - return documentSet - .map(function (ref) { - return { ref: ref, score: queryVector.similarity(this.documentVector(ref)) } - }, this) - .sort(function (a, b) { - return b.score - a.score - }) -} - -/** - * Generates a vector containing all the tokens in the document matching the - * passed documentRef. - * - * The vector contains the tf-idf score for each token contained in the - * document with the passed documentRef. The vector will contain an element - * for every token in the indexes corpus, if the document does not contain that - * token the element will be 0. - * - * @param {Object} documentRef The ref to find the document with. - * @returns {lunr.Vector} - * @private - * @memberOf Index - */ -lunr.Index.prototype.documentVector = function (documentRef) { - var documentTokens = this.documentStore.get(documentRef), - documentTokensLength = documentTokens.length, - documentVector = new lunr.Vector - - for (var i = 0; i < documentTokensLength; i++) { - var token = documentTokens.elements[i], - tf = this.tokenStore.get(token)[documentRef].tf, - idf = this.idf(token) - - documentVector.insert(this.corpusTokens.indexOf(token), tf * idf) - }; - - return documentVector -} - -/** - * Returns a representation of the index ready for serialisation. - * - * @returns {Object} - * @memberOf Index - */ -lunr.Index.prototype.toJSON = function () { - return { - version: lunr.version, - fields: this._fields, - ref: this._ref, - documentStore: this.documentStore.toJSON(), - tokenStore: this.tokenStore.toJSON(), - corpusTokens: this.corpusTokens.toJSON(), - pipeline: this.pipeline.toJSON() - } -} - -/** - * Applies a plugin to the current index. - * - * A plugin is a function that is called with the index as its context. - * Plugins can be used to customise or extend the behaviour the index - * in some way. A plugin is just a function, that encapsulated the custom - * behaviour that should be applied to the index. - * - * The plugin function will be called with the index as its argument, additional - * arguments can also be passed when calling use. The function will be called - * with the index as its context. - * - * Example: - * - * var myPlugin = function (idx, arg1, arg2) { - * // `this` is the index to be extended - * // apply any extensions etc here. - * } - * - * var idx = lunr(function () { - * this.use(myPlugin, 'arg1', 'arg2') - * }) - * - * @param {Function} plugin The plugin to apply. - * @memberOf Index - */ -lunr.Index.prototype.use = function (plugin) { - var args = Array.prototype.slice.call(arguments, 1) - args.unshift(this) - plugin.apply(this, args) -} -/*! - * lunr.Store - * Copyright (C) 2014 Oliver Nightingale - */ - -/** - * lunr.Store is a simple key-value store used for storing sets of tokens for - * documents stored in index. - * - * @constructor - * @module - */ -lunr.Store = function () { - this.store = {} - this.length = 0 -} - -/** - * Loads a previously serialised store - * - * @param {Object} serialisedData The serialised store to load. - * @returns {lunr.Store} - * @memberOf Store - */ -lunr.Store.load = function (serialisedData) { - var store = new this - - store.length = serialisedData.length - store.store = Object.keys(serialisedData.store).reduce(function (memo, key) { - memo[key] = lunr.SortedSet.load(serialisedData.store[key]) - return memo - }, {}) - - return store -} - -/** - * Stores the given tokens in the store against the given id. - * - * @param {Object} id The key used to store the tokens against. - * @param {Object} tokens The tokens to store against the key. - * @memberOf Store - */ -lunr.Store.prototype.set = function (id, tokens) { - if (!this.has(id)) this.length++ - this.store[id] = tokens -} - -/** - * Retrieves the tokens from the store for a given key. - * - * @param {Object} id The key to lookup and retrieve from the store. - * @returns {Object} - * @memberOf Store - */ -lunr.Store.prototype.get = function (id) { - return this.store[id] -} - -/** - * Checks whether the store contains a key. - * - * @param {Object} id The id to look up in the store. - * @returns {Boolean} - * @memberOf Store - */ -lunr.Store.prototype.has = function (id) { - return id in this.store -} - -/** - * Removes the value for a key in the store. - * - * @param {Object} id The id to remove from the store. - * @memberOf Store - */ -lunr.Store.prototype.remove = function (id) { - if (!this.has(id)) return - - delete this.store[id] - this.length-- -} - -/** - * Returns a representation of the store ready for serialisation. - * - * @returns {Object} - * @memberOf Store - */ -lunr.Store.prototype.toJSON = function () { - return { - store: this.store, - length: this.length - } -} - -/*! - * lunr.stemmer - * Copyright (C) 2014 Oliver Nightingale - * Includes code from - http://tartarus.org/~martin/PorterStemmer/js.txt - */ - -/** - * lunr.stemmer is an english language stemmer, this is a JavaScript - * implementation of the PorterStemmer taken from http://tartaurs.org/~martin - * - * @module - * @param {String} str The string to stem - * @returns {String} - * @see lunr.Pipeline - */ -lunr.stemmer = (function(){ - var step2list = { - "ational" : "ate", - "tional" : "tion", - "enci" : "ence", - "anci" : "ance", - "izer" : "ize", - "bli" : "ble", - "alli" : "al", - "entli" : "ent", - "eli" : "e", - "ousli" : "ous", - "ization" : "ize", - "ation" : "ate", - "ator" : "ate", - "alism" : "al", - "iveness" : "ive", - "fulness" : "ful", - "ousness" : "ous", - "aliti" : "al", - "iviti" : "ive", - "biliti" : "ble", - "logi" : "log" - }, - - step3list = { - "icate" : "ic", - "ative" : "", - "alize" : "al", - "iciti" : "ic", - "ical" : "ic", - "ful" : "", - "ness" : "" - }, - - c = "[^aeiou]", // consonant - v = "[aeiouy]", // vowel - C = c + "[^aeiouy]*", // consonant sequence - V = v + "[aeiou]*", // vowel sequence - - mgr0 = "^(" + C + ")?" + V + C, // [C]VC... is m>0 - meq1 = "^(" + C + ")?" + V + C + "(" + V + ")?$", // [C]VC[V] is m=1 - mgr1 = "^(" + C + ")?" + V + C + V + C, // [C]VCVC... is m>1 - s_v = "^(" + C + ")?" + v; // vowel in stem - - var re_mgr0 = new RegExp(mgr0); - var re_mgr1 = new RegExp(mgr1); - var re_meq1 = new RegExp(meq1); - var re_s_v = new RegExp(s_v); - - var re_1a = /^(.+?)(ss|i)es$/; - var re2_1a = /^(.+?)([^s])s$/; - var re_1b = /^(.+?)eed$/; - var re2_1b = /^(.+?)(ed|ing)$/; - var re_1b_2 = /.$/; - var re2_1b_2 = /(at|bl|iz)$/; - var re3_1b_2 = new RegExp("([^aeiouylsz])\\1$"); - var re4_1b_2 = new RegExp("^" + C + v + "[^aeiouwxy]$"); - - var re_1c = /^(.+?[^aeiou])y$/; - var re_2 = /^(.+?)(ational|tional|enci|anci|izer|bli|alli|entli|eli|ousli|ization|ation|ator|alism|iveness|fulness|ousness|aliti|iviti|biliti|logi)$/; - - var re_3 = /^(.+?)(icate|ative|alize|iciti|ical|ful|ness)$/; - - var re_4 = /^(.+?)(al|ance|ence|er|ic|able|ible|ant|ement|ment|ent|ou|ism|ate|iti|ous|ive|ize)$/; - var re2_4 = /^(.+?)(s|t)(ion)$/; - - var re_5 = /^(.+?)e$/; - var re_5_1 = /ll$/; - var re3_5 = new RegExp("^" + C + v + "[^aeiouwxy]$"); - - var porterStemmer = function porterStemmer(w) { - var stem, - suffix, - firstch, - re, - re2, - re3, - re4; - - if (w.length < 3) { return w; } - - firstch = w.substr(0,1); - if (firstch == "y") { - w = firstch.toUpperCase() + w.substr(1); - } - - // Step 1a - re = re_1a - re2 = re2_1a; - - if (re.test(w)) { w = w.replace(re,"$1$2"); } - else if (re2.test(w)) { w = w.replace(re2,"$1$2"); } - - // Step 1b - re = re_1b; - re2 = re2_1b; - if (re.test(w)) { - var fp = re.exec(w); - re = re_mgr0; - if (re.test(fp[1])) { - re = re_1b_2; - w = w.replace(re,""); - } - } else if (re2.test(w)) { - var fp = re2.exec(w); - stem = fp[1]; - re2 = re_s_v; - if (re2.test(stem)) { - w = stem; - re2 = re2_1b_2; - re3 = re3_1b_2; - re4 = re4_1b_2; - if (re2.test(w)) { w = w + "e"; } - else if (re3.test(w)) { re = re_1b_2; w = w.replace(re,""); } - else if (re4.test(w)) { w = w + "e"; } - } - } - - // Step 1c - replace suffix y or Y by i if preceded by a non-vowel which is not the first letter of the word (so cry -> cri, by -> by, say -> say) - re = re_1c; - if (re.test(w)) { - var fp = re.exec(w); - stem = fp[1]; - w = stem + "i"; - } - - // Step 2 - re = re_2; - if (re.test(w)) { - var fp = re.exec(w); - stem = fp[1]; - suffix = fp[2]; - re = re_mgr0; - if (re.test(stem)) { - w = stem + step2list[suffix]; - } - } - - // Step 3 - re = re_3; - if (re.test(w)) { - var fp = re.exec(w); - stem = fp[1]; - suffix = fp[2]; - re = re_mgr0; - if (re.test(stem)) { - w = stem + step3list[suffix]; - } - } - - // Step 4 - re = re_4; - re2 = re2_4; - if (re.test(w)) { - var fp = re.exec(w); - stem = fp[1]; - re = re_mgr1; - if (re.test(stem)) { - w = stem; - } - } else if (re2.test(w)) { - var fp = re2.exec(w); - stem = fp[1] + fp[2]; - re2 = re_mgr1; - if (re2.test(stem)) { - w = stem; - } - } - - // Step 5 - re = re_5; - if (re.test(w)) { - var fp = re.exec(w); - stem = fp[1]; - re = re_mgr1; - re2 = re_meq1; - re3 = re3_5; - if (re.test(stem) || (re2.test(stem) && !(re3.test(stem)))) { - w = stem; - } - } - - re = re_5_1; - re2 = re_mgr1; - if (re.test(w) && re2.test(w)) { - re = re_1b_2; - w = w.replace(re,""); - } - - // and turn initial Y back to y - - if (firstch == "y") { - w = firstch.toLowerCase() + w.substr(1); - } - - return w; - }; - - return porterStemmer; -})(); - -lunr.Pipeline.registerFunction(lunr.stemmer, 'stemmer') -/*! - * lunr.stopWordFilter - * Copyright (C) 2014 Oliver Nightingale - */ - -/** - * lunr.stopWordFilter is an English language stop word list filter, any words - * contained in the list will not be passed through the filter. - * - * This is intended to be used in the Pipeline. If the token does not pass the - * filter then undefined will be returned. - * - * @module - * @param {String} token The token to pass through the filter - * @returns {String} - * @see lunr.Pipeline - */ -lunr.stopWordFilter = function (token) { - if (lunr.stopWordFilter.stopWords.indexOf(token) === -1) return token -} - -lunr.stopWordFilter.stopWords = new lunr.SortedSet -lunr.stopWordFilter.stopWords.length = 119 -lunr.stopWordFilter.stopWords.elements = [ - "", - "a", - "able", - "about", - "across", - "after", - "all", - "almost", - "also", - "am", - "among", - "an", - "and", - "any", - "are", - "as", - "at", - "be", - "because", - "been", - "but", - "by", - "can", - "cannot", - "could", - "dear", - "did", - "do", - "does", - "either", - "else", - "ever", - "every", - "for", - "from", - "get", - "got", - "had", - "has", - "have", - "he", - "her", - "hers", - "him", - "his", - "how", - "however", - "i", - "if", - "in", - "into", - "is", - "it", - "its", - "just", - "least", - "let", - "like", - "likely", - "may", - "me", - "might", - "most", - "must", - "my", - "neither", - "no", - "nor", - "not", - "of", - "off", - "often", - "on", - "only", - "or", - "other", - "our", - "own", - "rather", - "said", - "say", - "says", - "she", - "should", - "since", - "so", - "some", - "than", - "that", - "the", - "their", - "them", - "then", - "there", - "these", - "they", - "this", - "tis", - "to", - "too", - "twas", - "us", - "wants", - "was", - "we", - "were", - "what", - "when", - "where", - "which", - "while", - "who", - "whom", - "why", - "will", - "with", - "would", - "yet", - "you", - "your" -] - -lunr.Pipeline.registerFunction(lunr.stopWordFilter, 'stopWordFilter') -/*! - * lunr.trimmer - * Copyright (C) 2014 Oliver Nightingale - */ - -/** - * lunr.trimmer is a pipeline function for trimming non word - * characters from the begining and end of tokens before they - * enter the index. - * - * This implementation may not work correctly for non latin - * characters and should either be removed or adapted for use - * with languages with non-latin characters. - * - * @module - * @param {String} token The token to pass through the filter - * @returns {String} - * @see lunr.Pipeline - */ -lunr.trimmer = function (token) { - return token - .replace(/^\W+/, '') - .replace(/\W+$/, '') -} - -lunr.Pipeline.registerFunction(lunr.trimmer, 'trimmer') -/*! - * lunr.stemmer - * Copyright (C) 2014 Oliver Nightingale - * Includes code from - http://tartarus.org/~martin/PorterStemmer/js.txt - */ - -/** - * lunr.TokenStore is used for efficient storing and lookup of the reverse - * index of token to document ref. - * - * @constructor - */ -lunr.TokenStore = function () { - this.root = { docs: {} } - this.length = 0 -} - -/** - * Loads a previously serialised token store - * - * @param {Object} serialisedData The serialised token store to load. - * @returns {lunr.TokenStore} - * @memberOf TokenStore - */ -lunr.TokenStore.load = function (serialisedData) { - var store = new this - - store.root = serialisedData.root - store.length = serialisedData.length - - return store -} - -/** - * Adds a new token doc pair to the store. - * - * By default this function starts at the root of the current store, however - * it can start at any node of any token store if required. - * - * @param {String} token The token to store the doc under - * @param {Object} doc The doc to store against the token - * @param {Object} root An optional node at which to start looking for the - * correct place to enter the doc, by default the root of this lunr.TokenStore - * is used. - * @memberOf TokenStore - */ -lunr.TokenStore.prototype.add = function (token, doc, root) { - var root = root || this.root, - key = token[0], - rest = token.slice(1) - - if (!(key in root)) root[key] = {docs: {}} - - if (rest.length === 0) { - root[key].docs[doc.ref] = doc - this.length += 1 - return - } else { - return this.add(rest, doc, root[key]) - } -} - -/** - * Checks whether this key is contained within this lunr.TokenStore. - * - * By default this function starts at the root of the current store, however - * it can start at any node of any token store if required. - * - * @param {String} token The token to check for - * @param {Object} root An optional node at which to start - * @memberOf TokenStore - */ -lunr.TokenStore.prototype.has = function (token) { - if (!token) return false - - var node = this.root - - for (var i = 0; i < token.length; i++) { - if (!node[token[i]]) return false - - node = node[token[i]] - } - - return true -} - -/** - * Retrieve a node from the token store for a given token. - * - * By default this function starts at the root of the current store, however - * it can start at any node of any token store if required. - * - * @param {String} token The token to get the node for. - * @param {Object} root An optional node at which to start. - * @returns {Object} - * @see TokenStore.prototype.get - * @memberOf TokenStore - */ -lunr.TokenStore.prototype.getNode = function (token) { - if (!token) return {} - - var node = this.root - - for (var i = 0; i < token.length; i++) { - if (!node[token[i]]) return {} - - node = node[token[i]] - } - - return node -} - -/** - * Retrieve the documents for a node for the given token. - * - * By default this function starts at the root of the current store, however - * it can start at any node of any token store if required. - * - * @param {String} token The token to get the documents for. - * @param {Object} root An optional node at which to start. - * @returns {Object} - * @memberOf TokenStore - */ -lunr.TokenStore.prototype.get = function (token, root) { - return this.getNode(token, root).docs || {} -} - -lunr.TokenStore.prototype.count = function (token, root) { - return Object.keys(this.get(token, root)).length -} - -/** - * Remove the document identified by ref from the token in the store. - * - * By default this function starts at the root of the current store, however - * it can start at any node of any token store if required. - * - * @param {String} token The token to get the documents for. - * @param {String} ref The ref of the document to remove from this token. - * @param {Object} root An optional node at which to start. - * @returns {Object} - * @memberOf TokenStore - */ -lunr.TokenStore.prototype.remove = function (token, ref) { - if (!token) return - var node = this.root - - for (var i = 0; i < token.length; i++) { - if (!(token[i] in node)) return - node = node[token[i]] - } - - delete node.docs[ref] -} - -/** - * Find all the possible suffixes of the passed token using tokens - * currently in the store. - * - * @param {String} token The token to expand. - * @returns {Array} - * @memberOf TokenStore - */ -lunr.TokenStore.prototype.expand = function (token, memo) { - var root = this.getNode(token), - docs = root.docs || {}, - memo = memo || [] - - if (Object.keys(docs).length) memo.push(token) - - Object.keys(root) - .forEach(function (key) { - if (key === 'docs') return - - memo.concat(this.expand(token + key, memo)) - }, this) - - return memo -} - -/** - * Returns a representation of the token store ready for serialisation. - * - * @returns {Object} - * @memberOf TokenStore - */ -lunr.TokenStore.prototype.toJSON = function () { - return { - root: this.root, - length: this.length - } -} - - - /** - * export the module via AMD, CommonJS or as a browser global - * Export code from https://github.com/umdjs/umd/blob/master/returnExports.js - */ - ;(function (root, factory) { - if (typeof define === 'function' && define.amd) { - // AMD. Register as an anonymous module. - define(factory) - } else if (typeof exports === 'object') { - /** - * Node. Does not work with strict CommonJS, but - * only CommonJS-like enviroments that support module.exports, - * like Node. - */ - module.exports = factory() - } else { - // Browser globals (root is window) - root.lunr = factory() - } - }(this, function () { - /** - * Just return a value to define the module export. - * This example returns an object, but the module - * can return a function as the exported value. - */ - return lunr - })) -})() +!function(){var a=function(b){var c=new a.Index;return c.pipeline.add(a.trimmer,a.stopWordFilter,a.stemmer),b&&b.call(c,c),c};a.version="0.5.7",a.utils={},a.utils.warn=function(a){return function(b){a.console&&console.warn}}(this),a.EventEmitter=function(){this.events={}},a.EventEmitter.prototype.addListener=function(){var a=Array.prototype.slice.call(arguments),b=a.pop(),c=a;if("function"!=typeof b)throw new TypeError("last argument must be a function");c.forEach(function(a){this.hasHandler(a)||(this.events[a]=[]),this.events[a].push(b)},this)},a.EventEmitter.prototype.removeListener=function(a,b){if(this.hasHandler(a)){var c=this.events[a].indexOf(b);this.events[a].splice(c,1),this.events[a].length||delete this.events[a]}},a.EventEmitter.prototype.emit=function(a){if(this.hasHandler(a)){var b=Array.prototype.slice.call(arguments,1);this.events[a].forEach(function(a){a.apply(void 0,b)})}},a.EventEmitter.prototype.hasHandler=function(a){return a in this.events},a.tokenizer=function(a){if(!arguments.length||null==a||void 0==a)return[];if(Array.isArray(a))return a.map(function(a){return a.toLowerCase()});for(var b=a.toString().replace(/^\s+/,""),c=b.length-1;c>=0;c--)if(/\S/.test(b.charAt(c))){b=b.substring(0,c+1);break}return b.split(/(?:\s+|\-)/).filter(function(a){return!!a}).map(function(a){return a.toLowerCase()})},a.Pipeline=function(){this._stack=[]},a.Pipeline.registeredFunctions={},a.Pipeline.registerFunction=function(b,c){c in this.registeredFunctions&&a.utils.warn("Overwriting existing registered function: "+c),b.label=c,a.Pipeline.registeredFunctions[b.label]=b},a.Pipeline.warnIfFunctionNotRegistered=function(b){var c=b.label&&b.label in this.registeredFunctions;c||a.utils.warn("Function is not registered with pipeline. This may cause problems when serialising the index.\n",b)},a.Pipeline.load=function(b){var c=new a.Pipeline;return b.forEach(function(b){var d=a.Pipeline.registeredFunctions[b];if(!d)throw new Error("Cannot load un-registered function: "+b);c.add(d)}),c},a.Pipeline.prototype.add=function(){var b=Array.prototype.slice.call(arguments);b.forEach(function(b){a.Pipeline.warnIfFunctionNotRegistered(b),this._stack.push(b)},this)},a.Pipeline.prototype.after=function(b,c){a.Pipeline.warnIfFunctionNotRegistered(c);var d=this._stack.indexOf(b)+1;this._stack.splice(d,0,c)},a.Pipeline.prototype.before=function(b,c){a.Pipeline.warnIfFunctionNotRegistered(c);var d=this._stack.indexOf(b);this._stack.splice(d,0,c)},a.Pipeline.prototype.remove=function(a){var b=this._stack.indexOf(a);this._stack.splice(b,1)},a.Pipeline.prototype.run=function(a){for(var b=[],c=a.length,d=this._stack.length,e=0;c>e;e++){for(var f=a[e],g=0;d>g&&(f=this._stack[g](f,e,a),void 0!==f);g++);void 0!==f&&b.push(f)}return b},a.Pipeline.prototype.reset=function(){this._stack=[]},a.Pipeline.prototype.toJSON=function(){return this._stack.map(function(b){return a.Pipeline.warnIfFunctionNotRegistered(b),b.label})},a.Vector=function(){this._magnitude=null,this.list=void 0,this.length=0},a.Vector.Node=function(a,b,c){this.idx=a,this.val=b,this.next=c},a.Vector.prototype.insert=function(b,c){var d=this.list;if(!d)return this.list=new a.Vector.Node(b,c,d),this.length++;for(var e=d,f=d.next;void 0!=f;){if(bc.idx?c=c.next:(d+=b.val*c.val,b=b.next,c=c.next);return d},a.Vector.prototype.similarity=function(a){return this.dot(a)/(this.magnitude()*a.magnitude())},a.SortedSet=function(){this.length=0,this.elements=[]},a.SortedSet.load=function(a){var b=new this;return b.elements=a,b.length=a.length,b},a.SortedSet.prototype.add=function(){Array.prototype.slice.call(arguments).forEach(function(a){~this.indexOf(a)||this.elements.splice(this.locationFor(a),0,a)},this),this.length=this.elements.length},a.SortedSet.prototype.toArray=function(){return this.elements.slice()},a.SortedSet.prototype.map=function(a,b){return this.elements.map(a,b)},a.SortedSet.prototype.forEach=function(a,b){return this.elements.forEach(a,b)},a.SortedSet.prototype.indexOf=function(a,b,c){var b=b||0,c=c||this.elements.length,d=c-b,e=b+Math.floor(d/2),f=this.elements[e];return 1>=d?f===a?e:-1:a>f?this.indexOf(a,e,c):f>a?this.indexOf(a,b,e):f===a?e:void 0},a.SortedSet.prototype.locationFor=function(a,b,c){var b=b||0,c=c||this.elements.length,d=c-b,e=b+Math.floor(d/2),f=this.elements[e];if(1>=d){if(f>a)return e;if(a>f)return e+1}return a>f?this.locationFor(a,e,c):f>a?this.locationFor(a,b,e):void 0},a.SortedSet.prototype.intersect=function(b){for(var c=new a.SortedSet,d=0,e=0,f=this.length,g=b.length,h=this.elements,i=b.elements;;){if(d>f-1||e>g-1)break;h[d]!==i[e]?h[d]i[e]&&e++:(c.add(h[d]),d++,e++)}return c},a.SortedSet.prototype.clone=function(){var b=new a.SortedSet;return b.elements=this.toArray(),b.length=b.elements.length,b},a.SortedSet.prototype.union=function(a){var b,c,d;return this.length>=a.length?(b=this,c=a):(b=a,c=this),d=b.clone(),d.add.apply(d,c.toArray()),d},a.SortedSet.prototype.toJSON=function(){return this.toArray()},a.Index=function(){this._fields=[],this._ref="id",this.pipeline=new a.Pipeline,this.documentStore=new a.Store,this.tokenStore=new a.TokenStore,this.corpusTokens=new a.SortedSet,this.eventEmitter=new a.EventEmitter,this._idfCache={},this.on("add","remove","update",function(){this._idfCache={}}.bind(this))},a.Index.prototype.on=function(){var a=Array.prototype.slice.call(arguments);return this.eventEmitter.addListener.apply(this.eventEmitter,a)},a.Index.prototype.off=function(a,b){return this.eventEmitter.removeListener(a,b)},a.Index.load=function(b){b.version!==a.version&&a.utils.warn("version mismatch: current "+a.version+" importing "+b.version);var c=new this;return c._fields=b.fields,c._ref=b.ref,c.documentStore=a.Store.load(b.documentStore),c.tokenStore=a.TokenStore.load(b.tokenStore),c.corpusTokens=a.SortedSet.load(b.corpusTokens),c.pipeline=a.Pipeline.load(b.pipeline),c},a.Index.prototype.field=function(a,b){var b=b||{},c={name:a,boost:b.boost||1};return this._fields.push(c),this},a.Index.prototype.ref=function(a){return this._ref=a,this},a.Index.prototype.add=function(b,c){var d={},e=new a.SortedSet,f=b[this._ref],c=void 0===c?!0:c;this._fields.forEach(function(c){var f=this.pipeline.run(a.tokenizer(b[c.name]));d[c.name]=f,a.SortedSet.prototype.add.apply(e,f)},this),this.documentStore.set(f,e),a.SortedSet.prototype.add.apply(this.corpusTokens,e.toArray());for(var g=0;g0&&(d=1+Math.log(this.tokenStore.length/c)),this._idfCache[b]=d},a.Index.prototype.search=function(b){var c=this.pipeline.run(a.tokenizer(b)),d=new a.Vector,e=[],f=this._fields.reduce(function(a,b){return a+b.boost},0),g=c.some(function(a){return this.tokenStore.has(a)},this);if(!g)return[];c.forEach(function(b,c,g){var h=1/g.length*this._fields.length*f,i=this,j=this.tokenStore.expand(b).reduce(function(c,e){var f=i.corpusTokens.indexOf(e),g=i.idf(e),j=1,k=new a.SortedSet;if(e!==b){var l=Math.max(3,e.length-b.length);j=1/Math.log(l)}return f>-1&&d.insert(f,h*g*j),Object.keys(i.tokenStore.get(e)).forEach(function(a){k.add(a)}),c.union(k)},new a.SortedSet);e.push(j)},this);var h=e.reduce(function(a,b){return a.intersect(b)});return h.map(function(a){return{ref:a,score:d.similarity(this.documentVector(a))}},this).sort(function(a,b){return b.score-a.score})},a.Index.prototype.documentVector=function(b){for(var c=this.documentStore.get(b),d=c.length,e=new a.Vector,f=0;d>f;f++){var g=c.elements[f],h=this.tokenStore.get(g)[b].tf,i=this.idf(g);e.insert(this.corpusTokens.indexOf(g),h*i)}return e},a.Index.prototype.toJSON=function(){return{version:a.version,fields:this._fields,ref:this._ref,documentStore:this.documentStore.toJSON(),tokenStore:this.tokenStore.toJSON(),corpusTokens:this.corpusTokens.toJSON(),pipeline:this.pipeline.toJSON()}},a.Index.prototype.use=function(a){var b=Array.prototype.slice.call(arguments,1);b.unshift(this),a.apply(this,b)},a.Store=function(){this.store={},this.length=0},a.Store.load=function(b){var c=new this;return c.length=b.length,c.store=Object.keys(b.store).reduce(function(c,d){return c[d]=a.SortedSet.load(b.store[d]),c},{}),c},a.Store.prototype.set=function(a,b){this.has(a)||this.length++,this.store[a]=b},a.Store.prototype.get=function(a){return this.store[a]},a.Store.prototype.has=function(a){return a in this.store},a.Store.prototype.remove=function(a){this.has(a)&&(delete this.store[a],this.length--)},a.Store.prototype.toJSON=function(){return{store:this.store,length:this.length}},a.stemmer=function(){var a={ational:"ate",tional:"tion",enci:"ence",anci:"ance",izer:"ize",bli:"ble",alli:"al",entli:"ent",eli:"e",ousli:"ous",ization:"ize",ation:"ate",ator:"ate",alism:"al",iveness:"ive",fulness:"ful",ousness:"ous",aliti:"al",iviti:"ive",biliti:"ble",logi:"log"},b={icate:"ic",ative:"",alize:"al",iciti:"ic",ical:"ic",ful:"",ness:""},c="[^aeiou]",d="[aeiouy]",e=c+"[^aeiouy]*",f=d+"[aeiou]*",g="^("+e+")?"+f+e,h="^("+e+")?"+f+e+"("+f+")?$",i="^("+e+")?"+f+e+f+e,j="^("+e+")?"+d,k=new RegExp(g),l=new RegExp(i),m=new RegExp(h),n=new RegExp(j),o=/^(.+?)(ss|i)es$/,p=/^(.+?)([^s])s$/,q=/^(.+?)eed$/,r=/^(.+?)(ed|ing)$/,s=/.$/,t=/(at|bl|iz)$/,u=new RegExp("([^aeiouylsz])\\1$"),v=new RegExp("^"+e+d+"[^aeiouwxy]$"),w=/^(.+?[^aeiou])y$/,x=/^(.+?)(ational|tional|enci|anci|izer|bli|alli|entli|eli|ousli|ization|ation|ator|alism|iveness|fulness|ousness|aliti|iviti|biliti|logi)$/,y=/^(.+?)(icate|ative|alize|iciti|ical|ful|ness)$/,z=/^(.+?)(al|ance|ence|er|ic|able|ible|ant|ement|ment|ent|ou|ism|ate|iti|ous|ive|ize)$/,A=/^(.+?)(s|t)(ion)$/,B=/^(.+?)e$/,C=/ll$/,D=new RegExp("^"+e+d+"[^aeiouwxy]$"),E=function(c){var d,e,f,g,h,i,j;if(c.length<3)return c;if(f=c.substr(0,1),"y"==f&&(c=f.toUpperCase()+c.substr(1)),g=o,h=p,g.test(c)?c=c.replace(g,"$1$2"):h.test(c)&&(c=c.replace(h,"$1$2")),g=q,h=r,g.test(c)){var E=g.exec(c);g=k,g.test(E[1])&&(g=s,c=c.replace(g,""))}else if(h.test(c)){var E=h.exec(c);d=E[1],h=n,h.test(d)&&(c=d,h=t,i=u,j=v,h.test(c)?c+="e":i.test(c)?(g=s,c=c.replace(g,"")):j.test(c)&&(c+="e"))}if(g=w,g.test(c)){var E=g.exec(c);d=E[1],c=d+"i"}if(g=x,g.test(c)){var E=g.exec(c);d=E[1],e=E[2],g=k,g.test(d)&&(c=d+a[e])}if(g=y,g.test(c)){var E=g.exec(c);d=E[1],e=E[2],g=k,g.test(d)&&(c=d+b[e])}if(g=z,h=A,g.test(c)){var E=g.exec(c);d=E[1],g=l,g.test(d)&&(c=d)}else if(h.test(c)){var E=h.exec(c);d=E[1]+E[2],h=l,h.test(d)&&(c=d)}if(g=B,g.test(c)){var E=g.exec(c);d=E[1],g=l,h=m,i=D,(g.test(d)||h.test(d)&&!i.test(d))&&(c=d)}return g=C,h=l,g.test(c)&&h.test(c)&&(g=s,c=c.replace(g,"")),"y"==f&&(c=f.toLowerCase()+c.substr(1)),c};return E}(),a.Pipeline.registerFunction(a.stemmer,"stemmer"),a.stopWordFilter=function(b){return-1===a.stopWordFilter.stopWords.indexOf(b)?b:void 0},a.stopWordFilter.stopWords=new a.SortedSet,a.stopWordFilter.stopWords.length=119,a.stopWordFilter.stopWords.elements=["","a","able","about","across","after","all","almost","also","am","among","an","and","any","are","as","at","be","because","been","but","by","can","cannot","could","dear","did","do","does","either","else","ever","every","for","from","get","got","had","has","have","he","her","hers","him","his","how","however","i","if","in","into","is","it","its","just","least","let","like","likely","may","me","might","most","must","my","neither","no","nor","not","of","off","often","on","only","or","other","our","own","rather","said","say","says","she","should","since","so","some","than","that","the","their","them","then","there","these","they","this","tis","to","too","twas","us","wants","was","we","were","what","when","where","which","while","who","whom","why","will","with","would","yet","you","your"],a.Pipeline.registerFunction(a.stopWordFilter,"stopWordFilter"),a.trimmer=function(a){return a.replace(/^\W+/,"").replace(/\W+$/,"")},a.Pipeline.registerFunction(a.trimmer,"trimmer"),a.TokenStore=function(){this.root={docs:{}},this.length=0},a.TokenStore.load=function(a){var b=new this;return b.root=a.root,b.length=a.length,b},a.TokenStore.prototype.add=function(a,b,c){var c=c||this.root,d=a[0],e=a.slice(1);return d in c||(c[d]={docs:{}}),0===e.length?(c[d].docs[b.ref]=b,void(this.length+=1)):this.add(e,b,c[d])},a.TokenStore.prototype.has=function(a){if(!a)return!1;for(var b=this.root,c=0;c= 0; --i) { - if (handlers[i] === handler) { - handlers.splice(i, 1); - } - } - } - - /** - * Remove all crash handlers. - */ - function unsubscribeAll() { - uninstallGlobalHandler(); - handlers = []; - } - - /** - * Dispatch stack information to all handlers. - * @param {Object.} stack - */ - function notifyHandlers(stack, isWindowError) { - var exception = null; - if (isWindowError && !TraceKit.collectWindowErrors) { - return; - } - for (var i in handlers) { - if (hasKey(handlers, i)) { - try { - handlers[i].apply(null, [stack].concat(_slice.call(arguments, 2))); - } catch (inner) { - exception = inner; - } - } - } - - if (exception) { - throw exception; - } - } - - var _oldOnerrorHandler, _onErrorHandlerInstalled; - - /** - * Ensures all global unhandled exceptions are recorded. - * Supported by Gecko and IE. - * @param {string} message Error message. - * @param {string} url URL of script that generated the exception. - * @param {(number|string)} lineNo The line number at which the error - * occurred. - * @param {?(number|string)} colNo The column number at which the error - * occurred. - * @param {?Error} ex The actual Error object. - */ - function traceKitWindowOnError(message, url, lineNo, colNo, ex) { - var stack = null; - - if (lastExceptionStack) { - TraceKit.computeStackTrace.augmentStackTraceWithInitialElement(lastExceptionStack, url, lineNo, message); - processLastException(); - } else if (ex) { - // New chrome and blink send along a real error object - // Let's just report that like a normal error. - // See: https://mikewest.org/2013/08/debugging-runtime-errors-with-window-onerror - stack = TraceKit.computeStackTrace(ex); - notifyHandlers(stack, true); - } else { - var location = { - 'url': url, - 'line': lineNo, - 'column': colNo - }; - location.func = TraceKit.computeStackTrace.guessFunctionName(location.url, location.line); - location.context = TraceKit.computeStackTrace.gatherContext(location.url, location.line); - stack = { - 'message': message, - 'url': document.location.href, - 'stack': [location] - }; - notifyHandlers(stack, true); - } - - if (_oldOnerrorHandler) { - return _oldOnerrorHandler.apply(this, arguments); - } - - return false; - } - - function installGlobalHandler () - { - if (_onErrorHandlerInstalled) { - return; - } - _oldOnerrorHandler = window.onerror; - window.onerror = traceKitWindowOnError; - _onErrorHandlerInstalled = true; - } - - function uninstallGlobalHandler () - { - if (!_onErrorHandlerInstalled) { - return; - } - window.onerror = _oldOnerrorHandler; - _onErrorHandlerInstalled = false; - _oldOnerrorHandler = undefined; - } - - function processLastException() { - var _lastExceptionStack = lastExceptionStack, - _lastArgs = lastArgs; - lastArgs = null; - lastExceptionStack = null; - lastException = null; - notifyHandlers.apply(null, [_lastExceptionStack, false].concat(_lastArgs)); - } - - /** - * Reports an unhandled Error to TraceKit. - * @param {Error} ex - * @param {?boolean} rethrow If false, do not re-throw the exception. - * Only used for window.onerror to not cause an infinite loop of - * rethrowing. - */ - function report(ex, rethrow) { - var args = _slice.call(arguments, 1); - if (lastExceptionStack) { - if (lastException === ex) { - return; // already caught by an inner catch block, ignore - } else { - processLastException(); - } - } - - var stack = TraceKit.computeStackTrace(ex); - lastExceptionStack = stack; - lastException = ex; - lastArgs = args; - - // If the stack trace is incomplete, wait for 2 seconds for - // slow slow IE to see if onerror occurs or not before reporting - // this exception; otherwise, we will end up with an incomplete - // stack trace - window.setTimeout(function () { - if (lastException === ex) { - processLastException(); - } - }, (stack.incomplete ? 2000 : 0)); - - if (rethrow !== false) { - throw ex; // re-throw to propagate to the top level (and cause window.onerror) - } - } - - report.subscribe = subscribe; - report.unsubscribe = unsubscribe; - report.uninstall = unsubscribeAll; - return report; -}()); - -/** - * TraceKit.computeStackTrace: cross-browser stack traces in JavaScript - * - * Syntax: - * s = TraceKit.computeStackTrace.ofCaller([depth]) - * s = TraceKit.computeStackTrace(exception) // consider using TraceKit.report instead (see below) - * Returns: - * s.name - exception name - * s.message - exception message - * s.stack[i].url - JavaScript or HTML file URL - * s.stack[i].func - function name, or empty for anonymous functions (if guessing did not work) - * s.stack[i].args - arguments passed to the function, if known - * s.stack[i].line - line number, if known - * s.stack[i].column - column number, if known - * s.stack[i].context - an array of source code lines; the middle element corresponds to the correct line# - * - * Supports: - * - Firefox: full stack trace with line numbers and unreliable column - * number on top frame - * - Opera 10: full stack trace with line and column numbers - * - Opera 9-: full stack trace with line numbers - * - Chrome: full stack trace with line and column numbers - * - Safari: line and column number for the topmost stacktrace element - * only - * - IE: no line numbers whatsoever - * - * Tries to guess names of anonymous functions by looking for assignments - * in the source code. In IE and Safari, we have to guess source file names - * by searching for function bodies inside all page scripts. This will not - * work for scripts that are loaded cross-domain. - * Here be dragons: some function names may be guessed incorrectly, and - * duplicate functions may be mismatched. - * - * TraceKit.computeStackTrace should only be used for tracing purposes. - * Logging of unhandled exceptions should be done with TraceKit.report, - * which builds on top of TraceKit.computeStackTrace and provides better - * IE support by utilizing the window.onerror event to retrieve information - * about the top of the stack. - * - * Note: In IE and Safari, no stack trace is recorded on the Error object, - * so computeStackTrace instead walks its *own* chain of callers. - * This means that: - * * in Safari, some methods may be missing from the stack trace; - * * in IE, the topmost function in the stack trace will always be the - * caller of computeStackTrace. - * - * This is okay for tracing (because you are likely to be calling - * computeStackTrace from the function you want to be the topmost element - * of the stack trace anyway), but not okay for logging unhandled - * exceptions (because your catch block will likely be far away from the - * inner function that actually caused the exception). - * - * Tracing example: - * function trace(message) { - * var stackInfo = TraceKit.computeStackTrace.ofCaller(); - * var data = message + "\n"; - * for(var i in stackInfo.stack) { - * var item = stackInfo.stack[i]; - * data += (item.func || '[anonymous]') + "() in " + item.url + ":" + (item.line || '0') + "\n"; - * } - * if (window.console) - * console.info(data); - * else - * alert(data); - * } - */ -TraceKit.computeStackTrace = (function computeStackTraceWrapper() { - var debug = false, - sourceCache = {}; - - /** - * Attempts to retrieve source code via XMLHttpRequest, which is used - * to look up anonymous function names. - * @param {string} url URL of source code. - * @return {string} Source contents. - */ - function loadSource(url) { - if (!TraceKit.remoteFetching) { //Only attempt request if remoteFetching is on. - return ''; - } - try { - var getXHR = function() { - try { - return new window.XMLHttpRequest(); - } catch (e) { - // explicitly bubble up the exception if not found - return new window.ActiveXObject('Microsoft.XMLHTTP'); - } - }; - - var request = getXHR(); - request.open('GET', url, false); - request.send(''); - return request.responseText; - } catch (e) { - return ''; - } - } - - /** - * Retrieves source code from the source code cache. - * @param {string} url URL of source code. - * @return {Array.} Source contents. - */ - function getSource(url) { - if (!isString(url)) return []; - if (!hasKey(sourceCache, url)) { - // URL needs to be able to fetched within the acceptable domain. Otherwise, - // cross-domain errors will be triggered. - var source = ''; - if (url.indexOf(document.domain) !== -1) { - source = loadSource(url); - } - sourceCache[url] = source ? source.split('\n') : []; - } - - return sourceCache[url]; - } - - /** - * Tries to use an externally loaded copy of source code to determine - * the name of a function by looking at the name of the variable it was - * assigned to, if any. - * @param {string} url URL of source code. - * @param {(string|number)} lineNo Line number in source code. - * @return {string} The function name, if discoverable. - */ - function guessFunctionName(url, lineNo) { - var reFunctionArgNames = /function ([^(]*)\(([^)]*)\)/, - reGuessFunction = /['"]?([0-9A-Za-z$_]+)['"]?\s*[:=]\s*(function|eval|new Function)/, - line = '', - maxLines = 10, - source = getSource(url), - m; - - if (!source.length) { - return UNKNOWN_FUNCTION; - } - - // Walk backwards from the first line in the function until we find the line which - // matches the pattern above, which is the function definition - for (var i = 0; i < maxLines; ++i) { - line = source[lineNo - i] + line; - - if (!isUndefined(line)) { - if ((m = reGuessFunction.exec(line))) { - return m[1]; - } else if ((m = reFunctionArgNames.exec(line))) { - return m[1]; - } - } - } - - return UNKNOWN_FUNCTION; - } - - /** - * Retrieves the surrounding lines from where an exception occurred. - * @param {string} url URL of source code. - * @param {(string|number)} line Line number in source code to centre - * around for context. - * @return {?Array.} Lines of source code. - */ - function gatherContext(url, line) { - var source = getSource(url); - - if (!source.length) { - return null; - } - - var context = [], - // linesBefore & linesAfter are inclusive with the offending line. - // if linesOfContext is even, there will be one extra line - // *before* the offending line. - linesBefore = Math.floor(TraceKit.linesOfContext / 2), - // Add one extra line if linesOfContext is odd - linesAfter = linesBefore + (TraceKit.linesOfContext % 2), - start = Math.max(0, line - linesBefore - 1), - end = Math.min(source.length, line + linesAfter - 1); - - line -= 1; // convert to 0-based index - - for (var i = start; i < end; ++i) { - if (!isUndefined(source[i])) { - context.push(source[i]); - } - } - - return context.length > 0 ? context : null; - } - - /** - * Escapes special characters, except for whitespace, in a string to be - * used inside a regular expression as a string literal. - * @param {string} text The string. - * @return {string} The escaped string literal. - */ - function escapeRegExp(text) { - return text.replace(/[\-\[\]{}()*+?.,\\\^$|#]/g, '\\$&'); - } - - /** - * Escapes special characters in a string to be used inside a regular - * expression as a string literal. Also ensures that HTML entities will - * be matched the same as their literal friends. - * @param {string} body The string. - * @return {string} The escaped string. - */ - function escapeCodeAsRegExpForMatchingInsideHTML(body) { - return escapeRegExp(body).replace('<', '(?:<|<)').replace('>', '(?:>|>)').replace('&', '(?:&|&)').replace('"', '(?:"|")').replace(/\s+/g, '\\s+'); - } - - /** - * Determines where a code fragment occurs in the source code. - * @param {RegExp} re The function definition. - * @param {Array.} urls A list of URLs to search. - * @return {?Object.} An object containing - * the url, line, and column number of the defined function. - */ - function findSourceInUrls(re, urls) { - var source, m; - for (var i = 0, j = urls.length; i < j; ++i) { - // console.log('searching', urls[i]); - if ((source = getSource(urls[i])).length) { - source = source.join('\n'); - if ((m = re.exec(source))) { - // console.log('Found function in ' + urls[i]); - - return { - 'url': urls[i], - 'line': source.substring(0, m.index).split('\n').length, - 'column': m.index - source.lastIndexOf('\n', m.index) - 1 - }; - } - } - } - - // console.log('no match'); - - return null; - } - - /** - * Determines at which column a code fragment occurs on a line of the - * source code. - * @param {string} fragment The code fragment. - * @param {string} url The URL to search. - * @param {(string|number)} line The line number to examine. - * @return {?number} The column number. - */ - function findSourceInLine(fragment, url, line) { - var source = getSource(url), - re = new RegExp('\\b' + escapeRegExp(fragment) + '\\b'), - m; - - line -= 1; - - if (source && source.length > line && (m = re.exec(source[line]))) { - return m.index; - } - - return null; - } - - /** - * Determines where a function was defined within the source code. - * @param {(Function|string)} func A function reference or serialized - * function definition. - * @return {?Object.} An object containing - * the url, line, and column number of the defined function. - */ - function findSourceByFunctionBody(func) { - var urls = [window.location.href], - scripts = document.getElementsByTagName('script'), - body, - code = '' + func, - codeRE = /^function(?:\s+([\w$]+))?\s*\(([\w\s,]*)\)\s*\{\s*(\S[\s\S]*\S)\s*\}\s*$/, - eventRE = /^function on([\w$]+)\s*\(event\)\s*\{\s*(\S[\s\S]*\S)\s*\}\s*$/, - re, - parts, - result; - - for (var i = 0; i < scripts.length; ++i) { - var script = scripts[i]; - if (script.src) { - urls.push(script.src); - } - } - - if (!(parts = codeRE.exec(code))) { - re = new RegExp(escapeRegExp(code).replace(/\s+/g, '\\s+')); - } - - // not sure if this is really necessary, but I don’t have a test - // corpus large enough to confirm that and it was in the original. - else { - var name = parts[1] ? '\\s+' + parts[1] : '', - args = parts[2].split(',').join('\\s*,\\s*'); - - body = escapeRegExp(parts[3]).replace(/;$/, ';?'); // semicolon is inserted if the function ends with a comment.replace(/\s+/g, '\\s+'); - re = new RegExp('function' + name + '\\s*\\(\\s*' + args + '\\s*\\)\\s*{\\s*' + body + '\\s*}'); - } - - // look for a normal function definition - if ((result = findSourceInUrls(re, urls))) { - return result; - } - - // look for an old-school event handler function - if ((parts = eventRE.exec(code))) { - var event = parts[1]; - body = escapeCodeAsRegExpForMatchingInsideHTML(parts[2]); - - // look for a function defined in HTML as an onXXX handler - re = new RegExp('on' + event + '=[\\\'"]\\s*' + body + '\\s*[\\\'"]', 'i'); - - if ((result = findSourceInUrls(re, urls[0]))) { - return result; - } - - // look for ??? - re = new RegExp(body); - - if ((result = findSourceInUrls(re, urls))) { - return result; - } - } - - return null; - } - - // Contents of Exception in various browsers. - // - // SAFARI: - // ex.message = Can't find variable: qq - // ex.line = 59 - // ex.sourceId = 580238192 - // ex.sourceURL = http://... - // ex.expressionBeginOffset = 96 - // ex.expressionCaretOffset = 98 - // ex.expressionEndOffset = 98 - // ex.name = ReferenceError - // - // FIREFOX: - // ex.message = qq is not defined - // ex.fileName = http://... - // ex.lineNumber = 59 - // ex.columnNumber = 69 - // ex.stack = ...stack trace... (see the example below) - // ex.name = ReferenceError - // - // CHROME: - // ex.message = qq is not defined - // ex.name = ReferenceError - // ex.type = not_defined - // ex.arguments = ['aa'] - // ex.stack = ...stack trace... - // - // INTERNET EXPLORER: - // ex.message = ... - // ex.name = ReferenceError - // - // OPERA: - // ex.message = ...message... (see the example below) - // ex.name = ReferenceError - // ex.opera#sourceloc = 11 (pretty much useless, duplicates the info in ex.message) - // ex.stacktrace = n/a; see 'opera:config#UserPrefs|Exceptions Have Stacktrace' - - /** - * Computes stack trace information from the stack property. - * Chrome and Gecko use this property. - * @param {Error} ex - * @return {?Object.} Stack trace information. - */ - function computeStackTraceFromStackProp(ex) { - if (!ex.stack) { - return null; - } - - var chrome = /^\s*at (?:((?:\[object object\])?\S+(?: \[as \S+\])?) )?\(?((?:file|https?|chrome-extension):.*?):(\d+)(?::(\d+))?\)?\s*$/i, - gecko = /^\s*(\S*)(?:\((.*?)\))?@((?:file|https?|chrome).*?):(\d+)(?::(\d+))?\s*$/i, - lines = ex.stack.split('\n'), - stack = [], - parts, - element, - reference = /^(.*) is undefined$/.exec(ex.message); - - for (var i = 0, j = lines.length; i < j; ++i) { - if ((parts = gecko.exec(lines[i]))) { - element = { - 'url': parts[3], - 'func': parts[1] || UNKNOWN_FUNCTION, - 'args': parts[2] ? parts[2].split(',') : '', - 'line': +parts[4], - 'column': parts[5] ? +parts[5] : null - }; - } else if ((parts = chrome.exec(lines[i]))) { - element = { - 'url': parts[2], - 'func': parts[1] || UNKNOWN_FUNCTION, - 'line': +parts[3], - 'column': parts[4] ? +parts[4] : null - }; - } else { - continue; - } - - if (!element.func && element.line) { - element.func = guessFunctionName(element.url, element.line); - } - - if (element.line) { - element.context = gatherContext(element.url, element.line); - } - - stack.push(element); - } - - if (!stack.length) { - return null; - } - - if (stack[0].line && !stack[0].column && reference) { - stack[0].column = findSourceInLine(reference[1], stack[0].url, stack[0].line); - } else if (!stack[0].column && !isUndefined(ex.columnNumber)) { - // FireFox uses this awesome columnNumber property for its top frame - // Also note, Firefox's column number is 0-based and everything else expects 1-based, - // so adding 1 - stack[0].column = ex.columnNumber + 1; - } - - return { - 'name': ex.name, - 'message': ex.message, - 'url': document.location.href, - 'stack': stack - }; - } - - /** - * Computes stack trace information from the stacktrace property. - * Opera 10 uses this property. - * @param {Error} ex - * @return {?Object.} Stack trace information. - */ - function computeStackTraceFromStacktraceProp(ex) { - // Access and store the stacktrace property before doing ANYTHING - // else to it because Opera is not very good at providing it - // reliably in other circumstances. - var stacktrace = ex.stacktrace; - - var testRE = / line (\d+), column (\d+) in (?:]+)>|([^\)]+))\((.*)\) in (.*):\s*$/i, - lines = stacktrace.split('\n'), - stack = [], - parts; - - for (var i = 0, j = lines.length; i < j; i += 2) { - if ((parts = testRE.exec(lines[i]))) { - var element = { - 'line': +parts[1], - 'column': +parts[2], - 'func': parts[3] || parts[4], - 'args': parts[5] ? parts[5].split(',') : [], - 'url': parts[6] - }; - - if (!element.func && element.line) { - element.func = guessFunctionName(element.url, element.line); - } - if (element.line) { - try { - element.context = gatherContext(element.url, element.line); - } catch (exc) {} - } - - if (!element.context) { - element.context = [lines[i + 1]]; - } - - stack.push(element); - } - } - - if (!stack.length) { - return null; - } - - return { - 'name': ex.name, - 'message': ex.message, - 'url': document.location.href, - 'stack': stack - }; - } - - /** - * NOT TESTED. - * Computes stack trace information from an error message that includes - * the stack trace. - * Opera 9 and earlier use this method if the option to show stack - * traces is turned on in opera:config. - * @param {Error} ex - * @return {?Object.} Stack information. - */ - function computeStackTraceFromOperaMultiLineMessage(ex) { - // Opera includes a stack trace into the exception message. An example is: - // - // Statement on line 3: Undefined variable: undefinedFunc - // Backtrace: - // Line 3 of linked script file://localhost/Users/andreyvit/Projects/TraceKit/javascript-client/sample.js: In function zzz - // undefinedFunc(a); - // Line 7 of inline#1 script in file://localhost/Users/andreyvit/Projects/TraceKit/javascript-client/sample.html: In function yyy - // zzz(x, y, z); - // Line 3 of inline#1 script in file://localhost/Users/andreyvit/Projects/TraceKit/javascript-client/sample.html: In function xxx - // yyy(a, a, a); - // Line 1 of function script - // try { xxx('hi'); return false; } catch(ex) { TraceKit.report(ex); } - // ... - - var lines = ex.message.split('\n'); - if (lines.length < 4) { - return null; - } - - var lineRE1 = /^\s*Line (\d+) of linked script ((?:file|https?)\S+)(?:: in function (\S+))?\s*$/i, - lineRE2 = /^\s*Line (\d+) of inline#(\d+) script in ((?:file|https?)\S+)(?:: in function (\S+))?\s*$/i, - lineRE3 = /^\s*Line (\d+) of function script\s*$/i, - stack = [], - scripts = document.getElementsByTagName('script'), - inlineScriptBlocks = [], - parts, - i, - len, - source; - - for (i in scripts) { - if (hasKey(scripts, i) && !scripts[i].src) { - inlineScriptBlocks.push(scripts[i]); - } - } - - for (i = 2, len = lines.length; i < len; i += 2) { - var item = null; - if ((parts = lineRE1.exec(lines[i]))) { - item = { - 'url': parts[2], - 'func': parts[3], - 'line': +parts[1] - }; - } else if ((parts = lineRE2.exec(lines[i]))) { - item = { - 'url': parts[3], - 'func': parts[4] - }; - var relativeLine = (+parts[1]); // relative to the start of the