code
stringlengths
2
1.05M
repo_name
stringlengths
5
114
path
stringlengths
4
991
language
stringclasses
1 value
license
stringclasses
15 values
size
int32
2
1.05M
// dependencies define(['mvc/ui/ui-tabs', 'mvc/ui/ui-misc', 'mvc/ui/ui-portlet', 'utils/utils', 'plugin/models/chart', 'plugin/models/group', 'plugin/views/group', 'plugin/views/settings', 'plugin/views/types'], function(Tabs, Ui, Portlet, Utils, Chart, Group, GroupView, SettingsView, TypesView) { /** * The charts editor holds the tabs for selecting chart types, chart configuration * and data group selections. */ return Backbone.View.extend({ // initialize initialize: function(app, options){ // link this var self = this; // link application this.app = app; // get current chart object this.chart = this.app.chart; // message element this.message = new Ui.Message(); // create portlet this.portlet = new Portlet.View({ icon : 'fa-bar-chart-o', title: 'Editor', operations : { 'save' : new Ui.ButtonIcon({ icon : 'fa-save', tooltip : 'Draw Chart', title : 'Draw', onclick : function() { self._saveChart(); } }), 'back' : new Ui.ButtonIcon({ icon : 'fa-caret-left', tooltip : 'Return to Viewer', title : 'Cancel', onclick : function() { // show viewer/viewport self.app.go('viewer'); // reset chart self.app.storage.load(); } }) } }); // // grid with chart types // this.types = new TypesView(app, { onchange : function(chart_type) { // get chart definition var chart_definition = self.app.types.get(chart_type); if (!chart_definition) { console.debug('FAILED - Editor::onchange() - Chart type not supported.'); } // parse chart definition self.chart.definition = chart_definition; // reset type relevant chart content self.chart.settings.clear(); // update chart type self.chart.set({type: chart_type}); // set modified flag self.chart.set('modified', true); // log console.debug('Editor::onchange() - Switched chart type.'); }, ondblclick : function(chart_id) { self._saveChart(); } }); // // tabs // this.tabs = new Tabs.View({ title_new : 'Add Data', onnew : function() { var group = self._addGroupModel(); self.tabs.show(group.id); } }); // // main/default tab // // construct elements this.title = new Ui.Input({ placeholder: 'Chart title', onchange: function() { self.chart.set('title', self.title.value()); } }); // append element var $main = $('<div/>'); $main.append(Utils.wrap((new Ui.Label({ title : 'Provide a chart title:'})).$el)); $main.append(Utils.wrap(this.title.$el)); $main.append(Utils.wrap(this.types.$el)); // add tab this.tabs.add({ id : 'main', title : 'Start', $el : $main }); // // main settings tab // // create settings view this.settings = new SettingsView(this.app); // add tab this.tabs.add({ id : 'settings', title : 'Configuration', $el : this.settings.$el }); // append tabs this.portlet.append(this.message.$el); this.portlet.append(this.tabs.$el); // elements this.setElement(this.portlet.$el); // hide back button on startup this.tabs.hideOperation('back'); // chart events var self = this; this.chart.on('change:title', function(chart) { self._refreshTitle(); }); this.chart.on('change:type', function(chart) { self.types.value(chart.get('type')); }); this.chart.on('reset', function(chart) { self._resetChart(); }); this.app.chart.on('redraw', function(chart) { self.portlet.showOperation('back'); }); // groups events this.app.chart.groups.on('add', function(group) { self._addGroup(group); }); this.app.chart.groups.on('remove', function(group) { self._removeGroup(group); }); this.app.chart.groups.on('reset', function(group) { self._removeAllGroups(); }); this.app.chart.groups.on('change:key', function(group) { self._refreshGroupKey(); }); // reset this._resetChart(); }, // hide show: function() { this.$el.show(); }, // hide hide: function() { this.$el.hide(); }, // refresh title _refreshTitle: function() { var title = this.chart.get('title'); this.portlet.title(title); this.title.value(title); }, // refresh group _refreshGroupKey: function() { var self = this; var counter = 0; this.chart.groups.each(function(group) { var title = group.get('key', ''); if (title == '') { title = 'Data label'; } self.tabs.title(group.id, ++counter + ': ' + title); }); }, // add group model _addGroupModel: function() { var group = new Group({ id : Utils.uuid() }); this.chart.groups.add(group); return group; }, // add group tab _addGroup: function(group) { // link this var self = this; // create view var group_view = new GroupView(this.app, {group: group}); // add new tab this.tabs.add({ id : group.id, $el : group_view.$el, ondel : function() { self.chart.groups.remove(group.id); } }); // update titles this._refreshGroupKey(); // reset this.chart.set('modified', true); }, // remove group _removeGroup: function(group) { this.tabs.del(group.id); // update titles this._refreshGroupKey(); // reset this.chart.set('modified', true); }, // remove group _removeAllGroups: function(group) { this.tabs.delRemovable(); }, // reset _resetChart: function() { // reset chart details this.chart.set('id', Utils.uuid()); this.chart.set('type', 'nvd3_bar'); this.chart.set('dataset_id', this.app.options.config.dataset_id); this.chart.set('title', 'New Chart'); // reset back button this.portlet.hideOperation('back'); }, // create chart _saveChart: function() { // update chart data this.chart.set({ type : this.types.value(), title : this.title.value(), date : Utils.time() }); // make sure that at least one data group is available if (this.chart.groups.length == 0) { this.message.update({message: 'Please select data columns before drawing the chart.'}); var group = this._addGroupModel(); this.tabs.show(group.id); return; } // make sure that all necessary columns are assigned var self = this; var valid = true; var chart_def = this.chart.definition; this.chart.groups.each(function(group) { if (!valid) { return; } for (var key in chart_def.columns) { if (group.attributes[key] == 'null') { self.message.update({status: 'danger', message: 'This chart type requires column types not found in your tabular file.'}); self.tabs.show(group.id); valid = false; return; } } }); // validate if columns have been selected if (!valid) { return; } // show viewport this.app.go('viewer'); // wait until chart is ready var self = this; this.app.deferred.execute(function() { // save self.app.storage.save(); // trigger redraw self.chart.trigger('redraw'); }); } }); });
mikel-egana-aranguren/SADI-Galaxy-Docker
galaxy-dist/config/plugins/visualizations/charts/static/views/editor.js
JavaScript
gpl-3.0
9,412
jQuery(document).ready(function(){ if( $('.cd-stretchy-nav').length > 0 ) { var stretchyNavs = $('.cd-stretchy-nav'); stretchyNavs.each(function(){ var stretchyNav = $(this), stretchyNavTrigger = stretchyNav.find('.cd-nav-trigger'); stretchyNavTrigger.on('click', function(event){ event.preventDefault(); stretchyNav.toggleClass('nav-is-visible'); }); }); $(document).on('click', function(event){ ( !$(event.target).is('.cd-nav-trigger') && !$(event.target).is('.cd-nav-trigger span') ) && stretchyNavs.removeClass('nav-is-visible'); }); }; ///toggle en contenido $(".toggle-view li").on('click', function(e){ e.currentTarget.classList.toggle("active"); }); });
GobiernoFacil/agentes-v2
public/js/main.js
JavaScript
gpl-3.0
716
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = versionTransform; var _path2 = require('path'); var _path3 = _interopRequireDefault(_path2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var packagePath = _path3.default.resolve(process.cwd(), './package.json'); var _require = require(packagePath); var version = _require.version; function versionTransform() { return { visitor: { Identifier: function Identifier(path) { if (path.node.name === 'VERSION') { path.replaceWithSourceString('"' + version + '"'); } } } }; };
cassiane/KnowledgePlatform
Implementacao/nodejs-tcc/node_modules/babel-plugin-version-transform/lib/index.js
JavaScript
gpl-3.0
675
/* Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'image', 'eo', { alertUrl: 'Bonvolu tajpi la retadreson de la bildo', alt: 'Anstataŭiga Teksto', border: 'Bordero', btnUpload: 'Sendu al Servilo', button2Img: 'Ĉu vi volas transformi la selektitan bildbutonon en simplan bildon?', hSpace: 'Horizontala Spaco', img2Button: 'Ĉu vi volas transformi la selektitan bildon en bildbutonon?', infoTab: 'Informoj pri Bildo', linkTab: 'Ligilo', lockRatio: 'Konservi Proporcion', menu: 'Atributoj de Bildo', resetSize: 'Origina Grando', title: 'Atributoj de Bildo', titleButton: 'Bildbutonaj Atributoj', upload: 'Alŝuti', urlMissing: 'La fontretadreso de la bildo mankas.', vSpace: 'Vertikala Spaco', validateBorder: 'La bordero devas esti entjera nombro.', validateHSpace: 'La horizontala spaco devas esti entjera nombro.', validateVSpace: 'La vertikala spaco devas esti entjera nombro.' });
tsmaryka/hitc
public/javascripts/ckeditor/plugins/image/lang/eo.js
JavaScript
gpl-3.0
1,029
function drawChart(len){ var box = document.createElement('div'); box.setAttribute('style','width:500px;height:500px;border:1px solid black;display:flex;flex-direction:column'); for(var i=0; i<len; i++){ var row = document.createElement('div'); if(i<len-1){ row.setAttribute('style','border-bottom:1px solid black;display:flex;box-sizing: border-box; flex: 1;'); } else{ row.setAttribute('style','display:flex;box-sizing: border-box; flex: 1;'); } for(var j=0; j<len; j++){ var col = document.createElement('div'); if(i%2===0){ if(j%2===0){ col.setAttribute('style','background-color:white; flex: 1;'); } else{ col.setAttribute('style','background-color:black; flex: 1;'); } }else{ if(j%2===0){ col.setAttribute('style','background-color:black; flex: 1;'); } else{ col.setAttribute('style','background-color:white; flex: 1;'); } } row.appendChild(col); } box.appendChild(row); } document.body.appendChild(box); } drawChart(5);
shashankKeshava/effective-enigma
jobCrunch/chess.js
JavaScript
gpl-3.0
1,186
var path = require('path') module.exports = { // Webpack aliases aliases: { quasar: path.resolve(__dirname, '../node_modules/quasar-framework/'), src: path.resolve(__dirname, '../src'), assets: path.resolve(__dirname, '../src/assets'), components: path.resolve(__dirname, '../src/components') }, // Progress Bar Webpack plugin format // https://github.com/clessg/progress-bar-webpack-plugin#options progressFormat: ' [:bar] ' + ':percent'.bold + ' (:msg)', // Default theme to build with ('ios' or 'mat') defaultTheme: 'mat', build: { env: require('./prod.env'), index: path.resolve(__dirname, '../dist/index.html'), publicPath: '', productionSourceMap: false, // Gzip off by default as many popular static hosts such as // Surge or Netlify already gzip all static assets for you. // Before setting to `true`, make sure to: // npm install --save-dev compression-webpack-plugin productionGzip: false, productionGzipExtensions: ['js', 'css'] }, dev: { env: require('./dev.env'), cssSourceMap: true, // auto open browser or not openBrowser: true, publicPath: '/', port: 8081, // If for example you are using Quasar Play // to generate a QR code then on each dev (re)compilation // you need to avoid clearing out the console, so set this // to "false", otherwise you can set it to "true" to always // have only the messages regarding your last (re)compilation. clearConsoleOnRebuild: false, // Proxy your API if using any. // Also see /build/script.dev.js and search for "proxy api requests" // https://github.com/chimurai/http-proxy-middleware proxyTable: {} } } /* * proxyTable example: * proxyTable: { // proxy all requests starting with /api '/api': { target: 'https://some.address.com/api', changeOrigin: true, pathRewrite: { '^/api': '' } } } */
agustincl/AclBoilerplate
config/index.js
JavaScript
gpl-3.0
1,969
#!/usr/bin/env node 'use strict'; /*All Includes needed for the Bot Core*/ var isfile = function(name) { require('fs').exists(name, function(exists) { return exists; }); }; var jsonfile = require('jsonfile'); var configfile = 'config.json'; var Event = require('./modules/Events').eventBus; // One way Events from the Main Core System var DiscordProxy = require('./modules/DiscordProxy'); // Proxy between Core & Plugins var Discord = require('discord.io'); // Required for the Bot to do anything with Discord var Plugins = require('require-all')(__dirname + '/plugins');//Loads all Plugins into the Bot var express = require('express'); var app = express(); var bodyparser = require("body-parser"); var mongoose = require('mongoose'); /*System Related Variables & Checks*/ var SYSTEM = { CURRENT_VERSION: require('./package.json').version, LATEST_VERSION: null, NPM_URL: "https://registry.npmjs.org/devbot", HOMEPAGE_URL: require('./package.json').repository.url, BUGREPORT_URL: require('./package.json').bugs.url, AUTHOR: require('./package.json').author.name + " <" + require('./package.json').author.email + ">", WEB: { IP: "127.0.0.1", PORT: 1337, MONGODB: "mongodb://localhost" } CONFIG: null }; console.log(` ▓█████▄ ▓█████ ██▒ █▓ ▄▄▄▄ ▒█████ ▄▄▄█████▓ ▒██▀ ██▌▓█ ▀▓██░ █▒▓█████▄ ▒██▒ ██▒▓ ██▒ ▓▒ ░██ █▌▒███ ▓██ █▒░▒██▒ ▄██▒██░ ██▒▒ ▓██░ ▒░ ░▓█▄ ▌▒▓█ ▄ ▒██ █░░▒██░█▀ ▒██ ██░░ ▓██▓ ░ ░▒████▓ ░▒████▒ ▒▀█░ ░▓█ ▀█▓░ ████▓▒░ ▒██▒ ░ ▒▒▓ ▒ ░░ ▒░ ░ ░ ▐░ ░▒▓███▀▒░ ▒░▒░▒░ ▒ ░░ ░ ▒ ▒ ░ ░ ░ ░ ░░ ▒░▒ ░ ░ ▒ ▒░ ░ ░ ░ ░ ░ ░░ ░ ░ ░ ░ ░ ▒ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ `); console.log("Current Version: " + SYSTEM.CURRENT_VERSION); console.log("Created by: " SYSTEM.AUTHOR) require("request").get(SYSTEM.NPM_URL, function (err, res, body) { if (err) { console.log("[ERROR] There was a Error Checking the NPM Registry for Version Information!\nBot Shutting Down....."); process.exit(); } console.log("[UPDATE CHECK] Checking for Update...."); var data = JSON.parse((body)); var NPM_VERSION = data['dist-tags'].latest; if (require("semver").lt(SYSTEM.CURRENT_VERSION, NPM_VERSION)) { console.log("[UPDATE THE BOT]: This BOT is out of date! Your version is (" + SYSTEM.CURRENT_VERSION + ") but the latest version on NPM is (" + NPM_VERSION + ")\nWhen are you going to Update HUH!"); } else { console.log("[UPDATE CHECKED] No Updates Found!"); } if (isfile(configfile) == false) { console.log("[SETUP START] Seems like this is the first time the bot has been Launched. \n[CONFIG CREATION] Creating config.json and filling it up. Please wait a momment......"); var data = { TOKEN: null, TRIGGER: "!", OWNER: null }; jsonfile.writeFile(configfile,data, function(err) { if (err) { console.log("[ERROR] Error in creating the Config file.\n[ERROR] Please check the permissions. Application Terminating....."); process.exit(); } else { console.log("[SETUP COMPLETE] Seems to be all Set. Please edit the " + configfile + " adding the Discord Bot Token information.\nProcess will Close now!"); process.exit(); } }); } else { console.log("[INFORMATION] Config file found! Loading......."); jsonfile.readFile(configfile, function(err, data) { if (err) { console.log("Error in Parsing and Loading the Config file.\nPlease check the permissions.\nApplication Terminating....."); process.exit(); } else { SYSTEM.CONFIG = data; if (SYSTEM.CONFIG.TOKEN == null) { console.log("[SETUP REQUIRED] Please edit the " + configfile + " adding the Discord Bot Token information.\nProcess will Close now!"); process.exit(); } else if (SYSTEM.CONFIG.OWNER == null) { console.log("[SETUP REQUIRED] Please edit the " + configfile + " adding the Discord Bot Owner ID.\nProcess will Close now!"); process.exit(); } else { app.use(bodyparser.urlencoded({ extended: true })); app.use(bodyparser.json()); var Client = new Discord.Client({ token: SYSTEM.CONFIG.TOKEN }); DiscordProxy.addClient(Client); DiscordProxy.registerOwner(SYSTEM.CONFIG.OWNER); Client.on('ready', function(event) { console.log("[DISCORD] Connected!"); Event.emit("status", true); }); Client.on('disconnect', function(errMsg, code) { console.log("[DISCORD] Disconnected!"); Event.emit("status", false); Client.connect(); }); Client.on('message', function(user, userID, channelID, message, event) { if (Client.id == userID) return; Event.emit("message", user, userID, channelID, message, event); var arr = message.split(" "); if (arr[0].charAt(0) == SYSTEM.CONFIG.TRIGGER) { Event.emit("command", arr[0].slice(1), user, userID, channelID, message); } else if (arr[0].indexOf(Client.id.toString()) > 1) { Event.emit("direct_command", arr[1], user, userID, channelID, message); } }); Client.on('presence', function(user, userID, status, game, event) { Event.emit("presence", user, userID, status, game, event); }); app.post("/api/webhook/:webhook/:name", function(req, res) { console.log("[WEBHOOK RECEIVED] Received a webhook from " + req.params.webhook.toLowerCase() + " for " + req.params.name.toLowerCase()); Event.emit("webhook", req.params.webhook.toLowerCase(), req.params.name.toLowerCase(), req.headers, req.body); res.status(200).json({ success: true }); }); app.listen(SYSTEM.WEB.IP, SYSTEM.WEB.PORT, function() { mongoose.connect(SYSTEM.WEB.MONGODB); Client.connect(); console.log("[BOT] API Handling System Online!"); }); } } }); } });
Bioblaze/Devbot
bot.js
JavaScript
gpl-3.0
6,811
// Copyright (c) 2012-2014 Lotaris SA // // This file is part of ROX Center. // // ROX Center is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // ROX Center is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with ROX Center. If not, see <http://www.gnu.org/licenses/>. App.autoModule('globalSettings', function() { var Settings = Backbone.Model.extend({ url: LegacyApiPath.builder('settings') }); var SettingsForm = Marionette.ItemView.extend({ template: 'globalSettings', ui: { ticketingSystemUrl: '#settings_ticketing_system_url', reportsCacheSize: '#settings_reports_cache_size', tagCloudSize: '#settings_tag_cloud_size', testOutdatedDays: '#settings_test_outdated_days', testPayloadsLifespan: '#settings_test_payloads_lifespan', testRunsLifespan: '#settings_test_runs_lifespan', fields: 'form :input', saveButton: 'form button', formControls: 'form .form-controls' }, events: { 'submit form': 'save' }, modelEvents: { 'change': 'refresh' }, appEvents: { 'maintenance:changed': 'updateControls' }, model: new Settings(), initialize: function() { App.bindEvents(this); }, onRender: function() { this.$el.button(); this.model.fetch(this.requestOptions()); this.updateControls(); }, setBusy: function(busy) { this.busy = busy; this.updateControls(); }, updateControls: function() { this.ui.saveButton.attr('disabled', this.busy || !!App.maintenance); this.ui.fields.attr('disabled', !!App.maintenance); }, refresh: function() { this.ui.ticketingSystemUrl.val(this.model.get('ticketing_system_url')); this.ui.reportsCacheSize.val(this.model.get('reports_cache_size')); this.ui.tagCloudSize.val(this.model.get('tag_cloud_size')); this.ui.testOutdatedDays.val(this.model.get('test_outdated_days')); this.ui.testPayloadsLifespan.val(this.model.get('test_payloads_lifespan')); this.ui.testRunsLifespan.val(this.model.get('test_runs_lifespan')); }, save: function(e) { e.preventDefault(); this.setNotice(false); this.setBusy(true); var options = this.requestOptions(); options.type = 'PUT'; options.success = _.bind(this.onSaved, this, 'success'); options.error = _.bind(this.onSaved, this, 'error'); this.model.save({ ticketing_system_url: this.ui.ticketingSystemUrl.val(), reports_cache_size: this.ui.reportsCacheSize.val(), tag_cloud_size: this.ui.tagCloudSize.val(), test_outdated_days: this.ui.testOutdatedDays.val(), test_payloads_lifespan: this.ui.testPayloadsLifespan.val(), test_runs_lifespan: this.ui.testRunsLifespan.val() }, options).always(_.bind(this.setBusy, this, false)); }, onSaved: function(result) { this.setNotice(result); if (result == 'success') { this.refresh(); } }, setNotice: function(type) { this.ui.saveButton.next('.text-success,.text-danger').remove(); if (type == 'success') { $('<span class="text-success" />').text(I18n.t('jst.globalSettings.success')).insertAfter(this.ui.saveButton).hide().fadeIn('fast'); } else if (type == 'error') { $('<span class="text-danger" />').text(I18n.t('jst.globalSettings.error')).insertAfter(this.ui.saveButton).hide().fadeIn('fast'); } }, requestOptions: function() { return { dataType: 'json', accepts: { json: 'application/json' } }; } }); this.addAutoInitializer(function(options) { options.region.show(new SettingsForm()); }); });
lotaris/rox-center
app/assets/javascripts/modules/globalSettings.js
JavaScript
gpl-3.0
4,170
"use strict"; /* Copyright (C) 2013-2017 Bryan Hughes <[email protected]> Aquarium Control is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Aquarium Control is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Aquarium Control. If not, see <http://www.gnu.org/licenses/>. */ Object.defineProperty(exports, "__esModule", { value: true }); // Force to "any" type, otherwise TypeScript thinks the type is too strict exports.cleaningValidationSchema = { type: 'object', properties: { time: { required: true, type: 'number' }, bioFilterReplaced: { required: true, type: 'boolean' }, mechanicalFilterReplaced: { required: true, type: 'boolean' }, spongeReplaced: { required: true, type: 'boolean' } } }; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiSUNsZWFuaW5nLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vc3JjL2NvbW1vbi9zcmMvSUNsZWFuaW5nLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7QUFBQTs7Ozs7Ozs7Ozs7Ozs7O0VBZUU7O0FBYUYsMEVBQTBFO0FBQzdELFFBQUEsd0JBQXdCLEdBQVE7SUFDM0MsSUFBSSxFQUFFLFFBQVE7SUFDZCxVQUFVLEVBQUU7UUFDVixJQUFJLEVBQUU7WUFDSixRQUFRLEVBQUUsSUFBSTtZQUNkLElBQUksRUFBRSxRQUFRO1NBQ2Y7UUFDRCxpQkFBaUIsRUFBRTtZQUNqQixRQUFRLEVBQUUsSUFBSTtZQUNkLElBQUksRUFBRSxTQUFTO1NBQ2hCO1FBQ0Qsd0JBQXdCLEVBQUU7WUFDeEIsUUFBUSxFQUFFLElBQUk7WUFDZCxJQUFJLEVBQUUsU0FBUztTQUNoQjtRQUNELGNBQWMsRUFBRTtZQUNkLFFBQVEsRUFBRSxJQUFJO1lBQ2QsSUFBSSxFQUFFLFNBQVM7U0FDaEI7S0FDRjtDQUNGLENBQUMifQ==
nebrius/aquarium-control
server/dist/common/src/ICleaning.js
JavaScript
gpl-3.0
1,996
"use strict"; function HelpTutorial() { let _getText = function() { return "HelpTutorial_Base"; }; this.getName = function(){ return "HelpTutorial_Base"; }; this.getImageId = function(){ return "button_help"; }; this.getText = _getText; } function HelpTutorialBuilding(name, image) { this.getName = function(){ return name; }; this.getImageId = function(){ return image; }; } function HelpQueueData(colonyState) { let queue = [new HelpTutorial()]; let available = []; let discovery = colonyState.getDiscovery(); for(let i = 0; i < discovery.length; i++) { if(discovery[i].startsWith("Resource_")) { queue.push(new HelpTutorialBuilding(discovery[i], discovery[i])); } } let technology = colonyState.getTechnology(); for(let i = 0; i < technology.length; i++) { let item = PrototypeLib.get(technology[i]); available.push(new HelpTutorialBuilding(technology[i], item.getBuildingImageId())); } QueueData.call(this, queue, available); this.getInfo = function(item) { let text = ""; if(item != null) { let imgSize = GetImageSize(ImagesLib.getImage(item.getImageId())); text += '<div class="queueInfo">'; if(item.getText != undefined) { text += '<div class="queueInfoTitle" style="height: ' + (imgSize.height + 5) + 'px;">'; text += '<img class="queueInfoTitleImage" style="height: ' + imgSize.height + 'px;" src="' + ImagesLib.getFileName(item.getImageId()) + '">'; text += '<div class="queueInfoTitleData queueInfoTitleName">' + TextRepository.get(item.getName()) + '</div>'; text += '</div>'; text += '<div class="queueInfoDetails">' + TextRepository.get(item.getName() + "Description") + '</div>'; } else { let baseImgSize = GetImageSize(ImagesLib.getImage("baseTile")); text += '<div class="queueInfoTitle" style="height: ' + (imgSize.height + 5) + 'px;">'; text += '<div style="float: left; height: ' + imgSize.height + 'px; background: url(\'' + ImagesLib.getFileName("baseTile") + '\') no-repeat; background-position: 0 ' + (imgSize.height - baseImgSize.height) + 'px;">'; text += '<img style="height: ' + imgSize.height + 'px; border-size: 0;" src="' + ImagesLib.getFileName(item.getImageId()) + '">'; text += '</div>'; text += '<div class="queueInfoTitleData">'; text += '<div class="queueInfoTitleName">' + TextRepository.get(item.getName()) + '</div>'; text += '<div class="queueInfoTitleDescription">' + TextRepository.get(item.getName() + "Description") + '</div>'; text += '</div>'; text += '</div>'; text += '<div class="queueInfoDetails">'; let proto = PrototypeLib.get(item.getName()); text += '<table>'; text += '<tr><td class="tableMainColumn">' + TextRepository.get("TerrainLayer") + ':</td><td></td><td>' + TextRepository.get(proto.getTerrainLayer()) + '</td></tr>'; let list; let listItem; if(proto.getBuildingTime() > 0 || Object.keys(proto.getBuildingCost()).length > 0) { //text += '<tr><td>' + TextRepository.get("BuildingTitle") + '</td></tr>'; text += '<tr><td>' + TextRepository.get("BuildingTime") + ':</td><td class="tableDataRight">' + proto.getBuildingTime() + '</td><td>' + TextRepository.get("TimeUnit") + '</td></tr>'; list = proto.getBuildingCost(); if(Object.keys(list).length > 0) { text += '<tr><td>' + TextRepository.get("BuildingCost") + ':</td></tr>'; for (listItem in list) { if(list.hasOwnProperty(listItem)) { text += '<tr><td class="tableIndentation">' + TextRepository.get(listItem) + '</td><td class="tableDataRight">' + list[listItem] + '</td>'; if(list[listItem] > colonyState.getProduced(listItem)) { text += '<td class="colorError">' + TextRepository.get("unavailable") + '</td>'; } text += '</tr>'; } } } } if(proto.getRequiredResource() != null) { text += '<tr><td>' + TextRepository.get("Requirements") + ':</td><td>' + TextRepository.get(proto.getRequiredResource()) + '</td></tr>'; } list = proto.getCapacity(); if(Object.keys(list).length > 0) { text += '<tr><td>' + TextRepository.get("BuildingCapacity") + ':</td></tr>'; for (listItem in list) { if(list.hasOwnProperty(listItem)) { text += '<tr><td class="tableIndentation">' + TextRepository.get(listItem) + '</td><td class="tableDataRight">' + list[listItem] + '</td></tr>'; } } } if((Object.keys(proto.getConsumption()).length + Object.keys(proto.getProduction()).length + Object.keys(proto.getProductionWaste()).length) > 0) { //text += '<tr><td>' + TextRepository.get("ProductionTitle") + '</td></tr>'; list = proto.getConsumption(); if(Object.keys(list).length > 0) { text += '<tr><td>' + TextRepository.get("BuildingConsumption") + ':</td></tr>'; for (listItem in list) { if(list.hasOwnProperty(listItem)) { text += '<tr><td class="tableIndentation">' + TextRepository.get(listItem) + '</td><td class="tableDataRight">' + list[listItem] + '</td></tr>'; } } } list = proto.getProduction(); if(Object.keys(list).length > 0) { text += '<tr><td>' + TextRepository.get("BuildingProduction") + ':</td></tr>'; for (listItem in list) { if(list.hasOwnProperty(listItem)) { text += '<tr><td class="tableIndentation">' + TextRepository.get(listItem) + '</td><td class="tableDataRight">' + list[listItem] + '</td></tr>'; } } } list = proto.getProductionWaste(); if(Object.keys(list).length > 0) { text += '<tr><td>' + TextRepository.get("BuildingWaste") + ':</td></tr>'; for (listItem in list) { if(list.hasOwnProperty(listItem)) { text += '<tr><td class="tableIndentation">' + TextRepository.get(listItem) + '</td><td class="tableDataRight">' + list[listItem] + '</td></tr>'; } } } } text += '</table>'; text += '</div>'; } text += '</div>'; } return text; }; this.isSortable = function() { return false; }; this.getTitle = function() { return "HelpTitle"; }; this.getQueueTitle = function() { return "HelpBase"; }; this.getAvailableTitle = function() { return "Buildings"; }; } HelpQueueData.inherits(QueueData);
Hiperblade/OutpostTLH
script/ViewQueueHelp.js
JavaScript
gpl-3.0
6,371
var Util = require( 'findhit-util' ); // ----------------------------------------------------------------------------- // Data handles wizard data into session function Data ( route ) { var session = route.req[ route.router.options.reqSessionKey ]; // If there isn't a `wiz` object on session, just add it if( ! session.wiz ) { session.wiz = {}; } // Save route on this instance this.route = route; // Gather session from session, or just create a new one this.session = session.wiz[ route.id ] || ( session.wiz[ route.id ] = {} ); // Add a control variable for changed state this.changed = false; return this; }; // Export Data module.exports = Data; /* instance methods */ Data.prototype.currentStep = function ( step ) { // If there is no `step` provided, it means that we wan't to get! // Otherwise, lets set it! }; /* Data.prototype.save = function () { }; Data.prototype.destroy = function () { }; */ Data.prototype.getFromStep = function ( step ) { };
brunocasanova/emvici-router
lib/type/wizard/control.js
JavaScript
gpl-3.0
1,035
IWitness.ErrorsView = Ember.View.extend({ classNames: ["error-bubble"], classNameBindings: ["isError"], isError: function() { return !!this.get("error"); }.property("error") });
djacobs/iWitness
app/views/errors_view.js
JavaScript
gpl-3.0
198
#!/usr/bin/env node /*jshint -W100*/ 'use strict'; /** * ニコニコ動画ログインサンプル * * 以下のusernameとpasswordを書き換えてから実行してください */ var username = 'hogehoge'; var password = 'fugafuga'; var client = require('../index'); console.info('ニコニコTOPページにアクセスします'); client.fetch('http://nicovideo.jp/') .then(function (result) { console.info('ログインリンクをクリックします'); return result.$('#sideNav .loginBtn').click(); }) .then(function (result) { console.info('ログインフォームを送信します'); return result.$('#login_form').submit({ mail_tel: username, password: password }); }) .then(function (result) { console.info('ログイン可否をチェックします'); if (! result.response.headers['x-niconico-id']) { throw new Error('login failed'); } console.info('クッキー', result.response.cookies); console.info('マイページに移動します'); return client.fetch('http://www.nicovideo.jp/my/top'); }) .then(function (result) { console.info('マイページに表示されるアカウント名を取得します'); console.info(result.$('#siteHeaderUserNickNameContainer').text()); }) .catch(function (err) { console.error('エラーが発生しました', err.message); }) .finally(function () { console.info('終了します'); });
tohshige/test
express/example/niconico.js
JavaScript
gpl-3.0
1,404
Ext.define("Voyant.notebook.util.Embed", { transferable: ['embed'], embed: function() { // this is for instances embed.apply(this, arguments); }, constructor: function(config) { var me = this; }, statics: { i18n: {}, api: { embeddedParameters: undefined, embeddedConfig: undefined }, embed: function(cmp, config) { if (this.then) { this.then(function(embedded) { embed.call(embedded, cmp, config) }) } else if (Ext.isArray(cmp)) { Voyant.notebook.util.Show.SINGLE_LINE_MODE=true; show("<table><tr>"); cmp.forEach(function(embeddable) { show("<td>"); if (Ext.isArray(embeddable)) { if (embeddable[0].embeddable) { embeddable[0].embed.apply(embeddable[0], embeddable.slice(1)) } else { embed.apply(this, embeddable) } } else { embed.apply(this, embeddable); } show("</td>") }) // for (var i=0; i<arguments.length; i++) { // var unit = arguments[i]; // show("<td>") // unit[0].embed.call(unit[0], unit[1], unit[2]); // show("</td>") // } show("</tr></table>") Voyant.notebook.util.Show.SINGLE_LINE_MODE=false; return } else { // use the default (first) embeddable panel if no panel is specified if (this.embeddable && (!cmp || Ext.isObject(cmp))) { // if the first argument is an object, use it as config instead if (Ext.isObject(cmp)) {config = cmp;} cmp = this.embeddable[0]; } if (Ext.isString(cmp)) { cmp = Ext.ClassManager.getByAlias('widget.'+cmp.toLowerCase()) || Ext.ClassManager.get(cmp); } var isEmbedded = false; if (Ext.isFunction(cmp)) { var name = cmp.getName(); if (this.embeddable && Ext.Array.each(this.embeddable, function(item) { if (item==name) { config = config || {}; var embeddedParams = {}; for (key in Ext.ClassManager.get(Ext.getClassName(cmp)).api) { if (key in config) { embeddedParams[key] = config[key] } } if (!embeddedParams.corpus) { if (Ext.getClassName(this)=='Voyant.data.model.Corpus') { embeddedParams.corpus = this.getId(); } else if (this.getCorpus) { var corpus = this.getCorpus(); if (corpus) { embeddedParams.corpus = this.getCorpus().getId(); } } } Ext.applyIf(config, { style: 'width: '+(config.width || '90%') + (Ext.isNumber(config.width) ? 'px' : '')+ '; height: '+(config.height || '400px') + (Ext.isNumber(config.height) ? 'px' : '') }); delete config.width; delete config.height; var corpus = embeddedParams.corpus; delete embeddedParams.corpus; Ext.applyIf(embeddedParams, Voyant.application.getModifiedApiParams()); var embeddedConfigParamEncodded = Ext.encode(embeddedParams); var embeddedConfigParam = encodeURIComponent(embeddedConfigParamEncodded); var iframeId = Ext.id(); var url = Voyant.application.getBaseUrlFull()+"tool/"+name.substring(name.lastIndexOf(".")+1)+'/?'; if (true || embeddedConfigParam.length>1800) { show('<iframe style="'+config.style+'" id="'+iframeId+'" name="'+iframeId+'"></iframe>'); var dfd = Voyant.application.getDeferred(this); Ext.Ajax.request({ url: Voyant.application.getTromboneUrl(), params: { tool: 'resource.StoredResource', storeResource: embeddedConfigParam } }).then(function(response) { var json = Ext.util.JSON.decode(response.responseText); var params = { minimal: true, embeddedApiId: json.storedResource.id } if (corpus) { params.corpus = corpus; } Ext.applyIf(params, Voyant.application.getModifiedApiParams()); document.getElementById(iframeId).setAttribute("src",url+Ext.Object.toQueryString(params)); dfd.resolve(); }).otherwise(function(response) { showError(response); dfd.reject(); }) } else { show('<iframe src="'+url+embeddedConfigParam+'" style="'+config.style+'" id="'+iframeId+'" name="'+iframeId+'"></iframe>'); } isEmbedded = true; return false; } }, this)===true) { Voyant.notebook.util.Embed.showWidgetNotRecognized.call(this); } if (!isEmbedded) { var embedded = Ext.create(cmp, config); embedded.embed(config); isEmbedded = true; } } if (!isEmbedded) { Voyant.notebook.util.Embed.showWidgetNotRecognized.call(this); } } }, showWidgetNotRecognized: function() { var msg = Voyant.notebook.util.Embed.i18n.widgetNotRecognized; if (this.embeddable) { msg += Voyant.notebook.util.Embed.i18n.tryWidget+'<ul>'+this.embeddable.map(function(cmp) { var widget = cmp.substring(cmp.lastIndexOf(".")+1).toLowerCase() return "\"<a href='../../docs/#!/guide/"+widget+"' target='voyantdocs'>"+widget+"</a>\"" }).join(", ")+"</ul>" } showError(msg) } } }) embed = Voyant.notebook.util.Embed.embed
sgsinclair/Voyant
src/main/webapp/app/notebook/util/Embed.js
JavaScript
gpl-3.0
5,429
var Base = require("./../plugin"); module.exports = class extends Base { isDisableSelfAttackPriority(self, rival) { return true; } isDisableEnemyAttackPriority(self, rival) { return true; } }
ssac/feh-guide
src/models/seal/hardy_bearing_3.js
JavaScript
gpl-3.0
208
(function() { 'use strict'; angular .module('app.grid') .service('GridDemoModelSerivce', GridDemoModelSerivce) .service('GridUtils',GridUtils) .factory('GridFactory',GridFactory) ; GridFactory.$inject = ['modelNode','$q','$filter']; function GridFactory(modelNode,$q,$filter) { return { buildGrid: function (option) { return new Grid(option,modelNode,$q,$filter); } } } function Grid(option,modelNode,$q,$filter) { var self = this; this.page = angular.extend({size: 9, no: 1}, option.page); this.sort = { column: option.sortColumn || '_id', direction: option.sortDirection ||-1, toggle: function (column) { if (column.sortable) { if (this.column === column.name) { this.direction = -this.direction || -1; } else { this.column = column.name; this.direction = -1; } self.paging(); } } }; this.searchForm = option.searchForm; this.rows = []; this.rawData = []; this.modelling = false; //必须有的 this.model = option.model; if (angular.isString(this.model)) { this.model = modelNode.services[this.model]; } if (!this.model) this.model = angular.noop; var promise; if (angular.isFunction(this.model)) { this.model = this.model(); } promise = $q.when(this.model).then(function (ret) { if (angular.isArray(ret)) { self.rawData = ret; } else { self.modelling = true; } self.setData = setData; self.query = query; self.paging = paging; return self; }); return promise; function setData(data) { self.rawData = data; } function query(param) { var queryParam = angular.extend({}, self.searchForm, param); if (self.modelling) { self.rows = self.model.page(self.page, queryParam, null, (self.sort.direction > 0 ? '' : '-') + self.sort.column); //服务端totals在查询数据时计算 self.model.totals(queryParam).$promise.then(function (ret) { self.page.totals = ret.totals; }); } else { if (self.rawData) self.rows = $filter('filter')(self.rawData, queryParam); } } function paging() { if (this.modelling) { this.query(); } } } GridDemoModelSerivce.$inject = ['Utils']; function GridDemoModelSerivce(Utils) { this.query = query; this.find = find; this.one = one; this.save = save; this.update = update; this.remove = remove; this._demoData_ = []; function query(refresh) { refresh = this._demoData_.length == 0 || refresh; if (refresh) { this._demoData_.length = 0; var MAX_NUM = 10 * 50; for (var i = 0; i < MAX_NUM; ++i) { var id = Utils.rand(0, MAX_NUM); this._demoData_.push({ id: i + 1, name: 'Name' + id, // 字符串类型 followers: Utils.rand(0, 100 * 1000 * 1000), // 数字类型 birthday: moment().subtract(Utils.rand(365, 365 * 50), 'day').toDate(), // 日期类型 summary: '这是一个测试' + i, income: Utils.rand(1000, 100000) // 金额类型 }); } } return this._demoData_; } function one(properties) { return _.findWhere(this._demoData_, properties); } function find(id) { return _.find(this._demoData_, function (item) { return item.id == id; }); } ///为了保证何$resource中的save功能一样此方法用于添加 function save(data) { //添加 this._demoData_.push(_.defaults(data, {})); //if (id != 'new') { // //修改 // var dest = _.bind(find, this, id); // _.extend(dest, data); //} //else { // //} } function update(id,data){ var dest = _.bind(find, this, id); _.extend(dest, data); } function remove(ids) { console.log(this._demoData_.length); this._demoData_ = _.reject(this._demoData_, function (item) { return _.contains(ids, item.id); }); console.log(this._demoData_.length); } } GridUtils.$inject = ['$filter','ViewUtils']; function GridUtils($filter,ViewUtils) { return { paging: paging, totals: totals, hide: hide, width: width, toggleOrderClass: toggleOrderClass, noResultsColspan: noResultsColspan, revertNumber: revertNumber, calcAge: calcAge, formatter: formatter, populateFilter: populateFilter, boolFilter: boolFilter, diFilter: diFilter, repeatInfoCombo: repeatInfoCombo, orFilter: orFilter }; function paging(items, vm) { if (!items) return []; if(vm.serverPaging){ //服务端分页 vm.paged = items; } else{ //客户端分页 var offset = (vm.page.no - 1) * vm.page.size; vm.paged = items.slice(offset, offset + vm.page.size); ////客户端totals在分页数据时计算 vm.page.totals = items.length;//客户端分页是立即触发结果 } return vm.paged; } function totals(items,filter,vm) { if (!items) return 0; if (vm.serverPaging) { //服务端分页 return vm.page.totals; } else { //客户端分页 return items.length || 0 } } function hide(column) { if (!column) return true; return column.hidden === true; } function width(column) { if (!column) return 0; return column.width || 100; } function toggleOrderClass(direction) { if (direction === -1) return "glyphicon-chevron-down"; else return "glyphicon-chevron-up"; } function noResultsColspan(vm) { if (!vm || !vm.columns) return 1; return 1 + vm.columns.length - _.where(vm.columns, {hidden: true}).length; } function revertNumber(num,notConvert) { if (num && !notConvert) { return -num; } return num; } function calcAge(rowValue) { return ViewUtils.age(rowValue) } function formatter(rowValue, columnName, columns) { var one = _.findWhere(columns, {name: columnName}); if(one && !one.hidden) { if (one.formatterData) { if(_.isArray(rowValue)){ return _.map(rowValue,function(o){ return one.formatterData[o]; }); } else{ return one.formatterData[rowValue]; } } } return rowValue; } function populateFilter(rowValue, key) { key = key || 'name'; if(_.isArray(rowValue)){ return _.map(rowValue,function(o){ console.log(o); return ViewUtils.getPropery(o, key); }); } else{ return ViewUtils.getPropery(o, key); } return rowValue; } function boolFilter(rowValue){ return {"1": "是", "0": "否", "true": "是", "false": "否"}[rowValue]; } function diFilter(rowValue,di) { if (_.isArray(rowValue)) { return _.map(rowValue, function (o) { return di[o] || (_.findWhere(di, {value: rowValue}) || {}).name; }); } else { return di[rowValue] || (_.findWhere(di, {value: rowValue}) || {}).name; } } function repeatInfoCombo(repeatValues, repeat_start) { if (_.isArray(repeatValues) && repeatValues.length > 0) { return _.map(repeatValues, function (r) { return r + repeat_start; }).join('\r\n'); } else { return repeat_start; } } /** * AngularJS default filter with the following expression: * "person in people | filter: {name: $select.search, age: $select.search}" * performs a AND between 'name: $select.search' and 'age: $select.search'. * We want to perform a OR. */ function orFilter(items, props) { var out = []; if (_.isArray(items)) { _.each(items,function (item) { var itemMatches = false; var keys = Object.keys(props); for (var i = 0; i < keys.length; i++) { var prop = keys[i]; var text = props[prop].toLowerCase(); if (item[prop].toString().toLowerCase().indexOf(text) !== -1) { itemMatches = true; break; } } if (itemMatches) { out.push(item); } }); } else { // Let the output be the input untouched out = items; } return out; }; } })();
zppro/4gtour
src/vendor-1.x/js/modules/grid/grid.service.js
JavaScript
gpl-3.0
11,119
/** * Module dependencies. */ var express = require('express') , http = require('http') , path = require('path') , mongo = require('mongodb') , format = require('util').format; var app = express(); // all environments app.set('port', process.env.PORT || 3000); app.set('views', __dirname + '/views'); app.set('view engine', 'jade'); app.use(express.favicon()); app.use(express.logger('dev')); app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(app.router); app.use(express.static(path.join(__dirname, 'public'))); // development only if ('development' == app.get('env')) { app.use(express.errorHandler()); } var server = new mongo.Server("localhost", 27017, {auto_reconnect: true}); var dbManager = new mongo.Db("applique-web", server, {safe:true}); dbManager.open(function(err, db) { require('./routes/index')(app, db); app.listen(app.get('port'), function(){ console.log('Express server listening on port ' + app.get('port')); }); });
jkamga/INM5151-payGoStore
app.js
JavaScript
gpl-3.0
991
"use strict"; module.exports = function registerDefaultRoutes( baseUrl, app, opts ){ var controller = opts.controller; var listRouter = app.route( baseUrl ); if( opts.all ){ listRouter = listRouter.all( opts.all ); } if( opts.list ){ listRouter.get( opts.list ); } if( opts.create ){ listRouter.post( opts.create ); } listRouter.get( controller.list ) .post( controller.create ); var resourceRouter = app.route( baseUrl + "/:_id" ); if( opts.all ){ resourceRouter.all( opts.all ); } if( opts.retrieve ){ resourceRouter.get(opts.retrieve); } if(opts.update){ resourceRouter.patch(opts.update); } if(opts.remove){ resourceRouter.delete(opts.remove); } resourceRouter.get( controller.retrieve ) .patch( controller.update ) .delete( controller.remove ); return { list: listRouter, resources: resourceRouter }; };
beni55/d-pac.cms
app/routes/api/helpers/registerDefaultRoutes.js
JavaScript
gpl-3.0
999
/*** * Copyright (c) 2013 John Krauss. * * This file is part of Crashmapper. * * Crashmapper is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Crashmapper is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Crashmapper. If not, see <http://www.gnu.org/licenses/>. * ***/ /*jslint browser: true, nomen: true, sloppy: true*/ /*globals Backbone, Crashmapper */ /** * @param {Object} options * @constructor * @extends Backbone.View */ Crashmapper.AppView = Backbone.View.extend({ id: 'app', /** * @this {Crashmapper.AppView} */ initialize: function () { this.about = new Crashmapper.AboutView({}).render(); this.about.$el.appendTo(this.$el).hide(); this.map = new Crashmapper.MapView({}); this.map.$el.appendTo(this.$el); }, /** * @this {Crashmapper.AppView} */ render: function () { return this; } });
talos/nypd-crash-data-bandaid
map/src/views/app.js
JavaScript
gpl-3.0
1,396
import altConnect from 'higher-order-components/altConnect'; import { STATUS_OK } from 'app-constants'; import ItemStore from 'stores/ItemStore'; import ProgressBar from '../components/ProgressBar'; const mapStateToProps = ({ itemState }) => ({ progress: itemState.readingPercentage, hidden: itemState.status !== STATUS_OK, }); mapStateToProps.stores = { ItemStore }; export default altConnect(mapStateToProps)(ProgressBar); // WEBPACK FOOTER // // ./src/js/app/modules/item/containers/ProgressBarContainer.js
BramscoChill/BlendleParser
information/blendle-frontend-react-source/app/modules/item/containers/ProgressBarContainer.js
JavaScript
gpl-3.0
518
/// Copyright (c) 2012 Ecma International. All rights reserved. /// Ecma International makes this code available under the terms and conditions set /// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the /// "Use Terms"). Any redistribution of this code must retain the above /// copyright and this notice and otherwise comply with the Use Terms. /** * @path ch15/15.3/15.3.2/15.3.2.1/15.3.2.1-11-8-s.js * @description Strict Mode - SyntaxError is not thrown if a function is created using a Function constructor that has two identical parameters, which are separated by a unique parameter name and there is no explicit 'use strict' in the function constructor's body * @onlyStrict */ function testcase() { "use strict"; var foo = new Function("baz", "qux", "baz", "return 0;"); return true; } runTestCase(testcase);
geminy/aidear
oss/qt/qt-everywhere-opensource-src-5.9.0/qtdeclarative/tests/auto/qml/ecmascripttests/test262/test/suite/ch15/15.3/15.3.2/15.3.2.1/15.3.2.1-11-8-s.js
JavaScript
gpl-3.0
881
function createCategorySlider(selector) { $(document).ready(function(){ var checkforloadedcats = []; var firstImage = $(selector).find('img').filter(':first'); if(firstImage.length > 0){ checkforloadedcats[selector] = setInterval(function() { var image = firstImage.get(0); if (image.complete || image.readyState == 'complete' || image.readyState == 4) { clearInterval(checkforloadedcats[selector]); $(selector).flexslider({ namespace: "", animation: "slide", easing: "easeInQuart", slideshow: false, animationLoop: false, animationSpeed: 700, pauseOnHover: true, controlNav: false, itemWidth: 238, minItems: flexmin, maxItems: flexmax, move: 0 }); } }, 20); } $(window).resize(function() { try { $(selector).flexslider(0); if($('#center_column').width()<=280){ $(selector).data('flexslider').setOpts({minItems: 1, maxItems: 1}); } else if($('#center_column').width()<=440){ $(selector).data('flexslider').setOpts({minItems: grid_size_ms, maxItems: grid_size_ms});} else if($('#center_column').width()<963){ $(selector).data('flexslider').setOpts({minItems: grid_size_sm, maxItems: grid_size_sm});} else if($('#center_column').width()>=1240){ $(selector).data('flexslider').setOpts({minItems: grid_size_lg, maxItems: grid_size_lg});} else if($('#center_column').width()>=963){ $(selector).data('flexslider').setOpts({minItems: grid_size_md, maxItems: grid_size_md});} } catch(e) { // handle all your exceptions here } }); }); }
desarrollosimagos/puroextremo.com.ve
modules/categoryslider/categoryslider.js
JavaScript
gpl-3.0
1,648
(function (angular) { 'use strict'; var config = { githubApiUrl: 'https://api.github.com/', }; angular.module('myGithubApp').constant('config', config); })(angular);
PetrusStarken/MyGit
app/scripts/app-config.js
JavaScript
gpl-3.0
180
'use strict'; angular.module('aurea') .directive('d3Bars', function ($window, $timeout, d3Service) { return { restrict: 'EA', scope: { data: '=', onClick: '&' }, link: function (scope, ele, attrs) { d3Service.d3().then(function (d3) { var margin = parseInt(attrs.margin) || 20, barHeight = parseInt(attrs.barHeight) || 20, barPadding = parseInt(attrs.barPadding) || 5; var svg = d3.select(ele[0]) .append('svg') .style('width', '100%'); // Browser onresize event window.onresize = function () { scope.$apply(); }; // Watch for resize event scope.$watch(function () { return angular.element($window)[0].innerWidth; }, function () { scope.render(scope.data); }); scope.$watch('data', function (newData) { scope.render(newData); }, true); scope.render = function (data) { // remove all previous items before render svg.selectAll('*').remove(); // If we don't pass any data, return out of the element if (!data) return; // setup variables var width = d3.select(ele[0]).node().offsetWidth - margin, // calculate the height height = scope.data.length * (barHeight + barPadding), // Use the category20() scale function for multicolor support color = d3.scale.category20(), // our xScale xScale = d3.scale.linear() .domain([0, 31]) .range([0, width]); // set the height based on the calculations above svg.attr('height', height); //create the rectangles for the bar chart svg.selectAll('rect') .data(data).enter() .append('rect') .attr('height', barHeight) .attr('width', 140) .attr('x', 110) .attr('y', function (d, i) { return i * (barHeight + barPadding); }) .attr('fill', function (d) { return color(d.value); }) .attr('width', function (d) { return xScale(d.value); }); var baseSelection = svg.selectAll('text'); baseSelection .data(data) .enter() .append('text') .attr('font-family', 'monospace') .attr('fill', '#000') .attr('y', function (d, i) { return i * (barHeight + barPadding) + 15; }) .attr('x', 15) .text(function (d) { return d.name; }); baseSelection .data(data) .enter() .append('text') .attr('font-family', 'monospace') .attr('fill', '#fff') .attr('y', function (d, i) { return i * (barHeight + barPadding) + 15; }) .attr('x', 114) .text(function (d) { return d.value > 0 ? d.value : ''; }); }; }); } }; });
apuliasoft/aurea
public/js/directives/d3.js
JavaScript
gpl-3.0
4,457
define(['Scripts/App/CommentsScraper'], function(CommentsScraper) { describe('myFilter', function() { var failTest = function(error) { expect(error).toBeUndefined(); }; beforeEach(function(){ jasmine.addMatchers({ toBeEqualComment: function() { return { compare: function (actual, expected) { return { pass: actual.author === expected.author && actual.commentType === expected.commentType && actual.link === expected.link && actual.x === expected.x && actual.y === expected.y }; } }; } }); jasmine.getFixtures().fixturesPath = 'base/Tests/Fixtures/'; loadFixtures('sampleComments.html'); }); it('should give correct comment object when given correct comment html', function () { var expected = { author: 'Vaniver', commentType: 'Parent', link: 'http://lesswrong.com/lw/n93/open_thread_feb_01_feb_07_2016/d2us', x: 1454336014000, y: 2 }; //var employee = CommentsScraper.getCommentObj($('.comment')[0].outerHTML); //expect(employee.author).toBeEqualComment('ScottL'); }); // Our first test!!!! it('about greeting says "This is the about message2!"', function () { //console.log(CommentsScraper); //CommentsScraper.getCommentData($('.comment')[0].outerHTML).then(function(data) { // console.log(data); //}); }); }); });
srlee309/LessWrongKarma
Tests/Spec/testSpec.js
JavaScript
gpl-3.0
1,556
const actions = { // Video ended ended({dispatch,commit}, video) { video.isPlaying = false; dispatch('next', video); commit('PLAYING',video); }, // Add video to queue addToQueue({state, dispatch, commit }, obj) { var index = _.findIndex(state.queue, function(o) { return o.videoId == obj.videoId; }); if (index == -1) commit('ADD_TO_QUEUE', obj); }, // Play a video playVideo({ state, dispatch, commit }, video) { if (!state.playing || state.playing.videoId != video.videoId) { state.player.loadVideoById({ videoId: video.videoId, suggestedQuality: 'small' }); } else { state.player.playVideo(); } video.isPlaying = true; commit('PLAYING',video); dispatch('addToQueue', video); }, // Puase a video pauseVideo({ state, dispatch, commit }, video) { video.isPlaying = false; state.player.pauseVideo(); commit('PLAYING',video); }, // Play next song next({ state, dispatch, commit }) { if (state.queue && state.playing) { var index = _.findIndex(state.queue, function(o) { return o.videoId == state.playing.videoId; }); if (index != -1 && state.queue[index + 1]) { dispatch('playVideo', state.queue[index + 1]); } } }, // Play previous song previous({ state, dispatch, commit }) { if (state.queue && state.playing) { var index = _.findIndex(state.queue, function(o) { return o.videoId == state.playing.videoId; }); if (index && state.queue[index - 1]) { dispatch('playVideo', state.queue[index - 1]); } } }, addToFav({state,commit},video){ var index = _.findIndex(state.favs,function(o){ return o.videoId == video.videoId; }); // Add to favs if not exists if(index == -1) { commit('ADD_TO_FAVS',video); state.localStorage.setItem("favs", state.favs); } else if(index >= 0) { commit('REMOVE_FROM_FAVS',index); state.localStorage.setItem("favs", state.favs); } }, // Add localforge to state and load data from localStorage loadLocalStorage({state,commit},localStorage){ commit('LOAD_LOCAL_STORAGE',localStorage); state.localStorage.getItem('favs').then(function(list) { if(list) commit('ADD_TO_FAVS',list); }).catch(function(err) { console.log(err); }); } } export default actions;
iamspal/playtube
src/store/actions.js
JavaScript
gpl-3.0
2,955
// core import React from 'react'; import PropTypes from 'react'; // components import Loading from '../../components/loading/Loading'; // styles var style = require('./_index.scss'); // data var Timeline = require('react-twitter-widgets').Timeline; var Twitter = React.createClass({ getInitialState: function(){ return { isLoading: true } }, componentWillMount: function(){ this.setState({ isLoading: true }) }, componentDidMount: function(){ this.setState({ isLoading: false }) }, render: function(){ if(this.state.isLoading === true){ return ( <Loading /> ) } else { return ( <div className='twitter-container'> <Timeline className='twitter-component' dataSource={{ sourceType: 'widget', widgetId: '844245316706566144' }} /> </div> ) } } }); export default Twitter;
JoeDahle/fic
app/components/twitter/Twitter.js
JavaScript
gpl-3.0
946
function Greeter(person) { return "Hello, " + person; } var RandomGuy = "Random Dude"; alert(Greeter(RandomGuy)); //# sourceMappingURL=HelloWorld.js.map
LenardHessHAW/TypeScriptTesting
JavaScript/HelloWorld.js
JavaScript
gpl-3.0
156
/* _ _ _ _ ___| (_) ___| | __ (_)___ / __| | |/ __| |/ / | / __| \__ \ | | (__| < _ | \__ \ |___/_|_|\___|_|\_(_)/ |___/ |__/ Version: 1.8.1 Author: Ken Wheeler Website: http://kenwheeler.github.io Docs: http://kenwheeler.github.io/slick Repo: http://github.com/kenwheeler/slick Issues: http://github.com/kenwheeler/slick/issues */ /* global window, document, define, jQuery, setInterval, clearInterval */ ;(function(factory) { 'use strict'; if (typeof define === 'function' && define.amd) { define(['jquery'], factory); } else if (typeof exports !== 'undefined') { module.exports = factory(require('jquery')); } else { factory(jQuery); } }(function($) { 'use strict'; var Slick = window.Slick || {}; Slick = (function() { var instanceUid = 0; function Slick(element, settings) { var _ = this, dataSettings; _.defaults = { accessibility: true, adaptiveHeight: false, appendArrows: $(element), appendDots: $(element), arrows: true, asNavFor: null, prevArrow: '<button class="slick-prev" aria-label="Previous" type="button">Previous</button>', nextArrow: '<button class="slick-next" aria-label="Next" type="button">Next</button>', autoplay: false, autoplaySpeed: 3000, centerMode: false, centerPadding: '50px', cssEase: 'ease', customPaging: function(slider, i) { return $('<button type="button" />').text(i + 1); }, dots: false, dotsClass: 'slick-dots', draggable: true, easing: 'linear', edgeFriction: 0.35, fade: false, focusOnSelect: false, focusOnChange: false, infinite: true, initialSlide: 0, lazyLoad: 'ondemand', mobileFirst: false, pauseOnHover: true, pauseOnFocus: true, pauseOnDotsHover: false, respondTo: 'window', responsive: null, rows: 1, rtl: false, slide: '', slidesPerRow: 1, slidesToShow: 1, slidesToScroll: 1, speed: 500, swipe: true, swipeToSlide: false, touchMove: true, touchThreshold: 5, useCSS: true, useTransform: true, variableWidth: false, vertical: false, verticalSwiping: false, waitForAnimate: true, zIndex: 1000 }; _.initials = { animating: false, dragging: false, autoPlayTimer: null, currentDirection: 0, currentLeft: null, currentSlide: 0, direction: 1, $dots: null, listWidth: null, listHeight: null, loadIndex: 0, $nextArrow: null, $prevArrow: null, scrolling: false, slideCount: null, slideWidth: null, $slideTrack: null, $slides: null, sliding: false, slideOffset: 0, swipeLeft: null, swiping: false, $list: null, touchObject: {}, transformsEnabled: false, unslicked: false }; $.extend(_, _.initials); _.activeBreakpoint = null; _.animType = null; _.animProp = null; _.breakpoints = []; _.breakpointSettings = []; _.cssTransitions = false; _.focussed = false; _.interrupted = false; _.hidden = 'hidden'; _.paused = true; _.positionProp = null; _.respondTo = null; _.rowCount = 1; _.shouldClick = true; _.$slider = $(element); _.$slidesCache = null; _.transformType = null; _.transitionType = null; _.visibilityChange = 'visibilitychange'; _.windowWidth = 0; _.windowTimer = null; dataSettings = $(element).data('slick') || {}; _.options = $.extend({}, _.defaults, settings, dataSettings); _.currentSlide = _.options.initialSlide; _.originalSettings = _.options; if (typeof document.mozHidden !== 'undefined') { _.hidden = 'mozHidden'; _.visibilityChange = 'mozvisibilitychange'; } else if (typeof document.webkitHidden !== 'undefined') { _.hidden = 'webkitHidden'; _.visibilityChange = 'webkitvisibilitychange'; } _.autoPlay = $.proxy(_.autoPlay, _); _.autoPlayClear = $.proxy(_.autoPlayClear, _); _.autoPlayIterator = $.proxy(_.autoPlayIterator, _); _.changeSlide = $.proxy(_.changeSlide, _); _.clickHandler = $.proxy(_.clickHandler, _); _.selectHandler = $.proxy(_.selectHandler, _); _.setPosition = $.proxy(_.setPosition, _); _.swipeHandler = $.proxy(_.swipeHandler, _); _.dragHandler = $.proxy(_.dragHandler, _); _.keyHandler = $.proxy(_.keyHandler, _); _.instanceUid = instanceUid++; // A simple way to check for HTML strings // Strict HTML recognition (must start with <) // Extracted from jQuery v1.11 source _.htmlExpr = /^(?:\s*(<[\w\W]+>)[^>]*)$/; _.registerBreakpoints(); _.init(true); } return Slick; }()); Slick.prototype.activateADA = function() { var _ = this; _.$slideTrack.find('.slick-active').attr({ 'aria-hidden': 'false' }).find('a, input, button, select').attr({ 'tabindex': '0' }); }; Slick.prototype.addSlide = Slick.prototype.slickAdd = function(markup, index, addBefore) { var _ = this; if (typeof(index) === 'boolean') { addBefore = index; index = null; } else if (index < 0 || (index >= _.slideCount)) { return false; } _.unload(); if (typeof(index) === 'number') { if (index === 0 && _.$slides.length === 0) { $(markup).appendTo(_.$slideTrack); } else if (addBefore) { $(markup).insertBefore(_.$slides.eq(index)); } else { $(markup).insertAfter(_.$slides.eq(index)); } } else { if (addBefore === true) { $(markup).prependTo(_.$slideTrack); } else { $(markup).appendTo(_.$slideTrack); } } _.$slides = _.$slideTrack.children(this.options.slide); _.$slideTrack.children(this.options.slide).detach(); _.$slideTrack.append(_.$slides); _.$slides.each(function(index, element) { $(element).attr('data-slick-index', index); }); _.$slidesCache = _.$slides; _.reinit(); }; Slick.prototype.animateHeight = function() { var _ = this; if (_.options.slidesToShow === 1 && _.options.adaptiveHeight === true && _.options.vertical === false) { var targetHeight = _.$slides.eq(_.currentSlide).outerHeight(true); _.$list.animate({ height: targetHeight }, _.options.speed); } }; Slick.prototype.animateSlide = function(targetLeft, callback) { var animProps = {}, _ = this; _.animateHeight(); if (_.options.rtl === true && _.options.vertical === false) { targetLeft = -targetLeft; } if (_.transformsEnabled === false) { if (_.options.vertical === false) { _.$slideTrack.animate({ left: targetLeft }, _.options.speed, _.options.easing, callback); } else { _.$slideTrack.animate({ top: targetLeft }, _.options.speed, _.options.easing, callback); } } else { if (_.cssTransitions === false) { if (_.options.rtl === true) { _.currentLeft = -(_.currentLeft); } $({ animStart: _.currentLeft }).animate({ animStart: targetLeft }, { duration: _.options.speed, easing: _.options.easing, step: function(now) { now = Math.ceil(now); if (_.options.vertical === false) { animProps[_.animType] = 'translate(' + now + 'px, 0px)'; _.$slideTrack.css(animProps); } else { animProps[_.animType] = 'translate(0px,' + now + 'px)'; _.$slideTrack.css(animProps); } }, complete: function() { if (callback) { callback.call(); } } }); } else { _.applyTransition(); targetLeft = Math.ceil(targetLeft); if (_.options.vertical === false) { animProps[_.animType] = 'translate3d(' + targetLeft + 'px, 0px, 0px)'; } else { animProps[_.animType] = 'translate3d(0px,' + targetLeft + 'px, 0px)'; } _.$slideTrack.css(animProps); if (callback) { setTimeout(function() { _.disableTransition(); callback.call(); }, _.options.speed); } } } }; Slick.prototype.getNavTarget = function() { var _ = this, asNavFor = _.options.asNavFor; if ( asNavFor && asNavFor !== null ) { asNavFor = $(asNavFor).not(_.$slider); } return asNavFor; }; Slick.prototype.asNavFor = function(index) { var _ = this, asNavFor = _.getNavTarget(); if ( asNavFor !== null && typeof asNavFor === 'object' ) { asNavFor.each(function() { var target = $(this).slick('getSlick'); if(!target.unslicked) { target.slideHandler(index, true); } }); } }; Slick.prototype.applyTransition = function(slide) { var _ = this, transition = {}; if (_.options.fade === false) { transition[_.transitionType] = _.transformType + ' ' + _.options.speed + 'ms ' + _.options.cssEase; } else { transition[_.transitionType] = 'opacity ' + _.options.speed + 'ms ' + _.options.cssEase; } if (_.options.fade === false) { _.$slideTrack.css(transition); } else { _.$slides.eq(slide).css(transition); } }; Slick.prototype.autoPlay = function() { var _ = this; _.autoPlayClear(); if ( _.slideCount > _.options.slidesToShow ) { _.autoPlayTimer = setInterval( _.autoPlayIterator, _.options.autoplaySpeed ); } }; Slick.prototype.autoPlayClear = function() { var _ = this; if (_.autoPlayTimer) { clearInterval(_.autoPlayTimer); } }; Slick.prototype.autoPlayIterator = function() { var _ = this, slideTo = _.currentSlide + _.options.slidesToScroll; if ( !_.paused && !_.interrupted && !_.focussed ) { if ( _.options.infinite === false ) { if ( _.direction === 1 && ( _.currentSlide + 1 ) === ( _.slideCount - 1 )) { _.direction = 0; } else if ( _.direction === 0 ) { slideTo = _.currentSlide - _.options.slidesToScroll; if ( _.currentSlide - 1 === 0 ) { _.direction = 1; } } } _.slideHandler( slideTo ); } }; Slick.prototype.buildArrows = function() { var _ = this; if (_.options.arrows === true ) { _.$prevArrow = $(_.options.prevArrow).addClass('slick-arrow'); _.$nextArrow = $(_.options.nextArrow).addClass('slick-arrow'); if( _.slideCount > _.options.slidesToShow ) { _.$prevArrow.removeClass('slick-hidden').removeAttr('aria-hidden tabindex'); _.$nextArrow.removeClass('slick-hidden').removeAttr('aria-hidden tabindex'); if (_.htmlExpr.test(_.options.prevArrow)) { _.$prevArrow.prependTo(_.options.appendArrows); } if (_.htmlExpr.test(_.options.nextArrow)) { _.$nextArrow.appendTo(_.options.appendArrows); } if (_.options.infinite !== true) { _.$prevArrow .addClass('slick-disabled') .attr('aria-disabled', 'true'); } } else { _.$prevArrow.add( _.$nextArrow ) .addClass('slick-hidden') .attr({ 'aria-disabled': 'true', 'tabindex': '-1' }); } } }; Slick.prototype.buildDots = function() { var _ = this, i, dot; if (_.options.dots === true && _.slideCount > _.options.slidesToShow) { _.$slider.addClass('slick-dotted'); dot = $('<ul />').addClass(_.options.dotsClass); for (i = 0; i <= _.getDotCount(); i += 1) { dot.append($('<li />').append(_.options.customPaging.call(this, _, i))); } _.$dots = dot.appendTo(_.options.appendDots); _.$dots.find('li').first().addClass('slick-active'); } }; Slick.prototype.buildOut = function() { var _ = this; _.$slides = _.$slider .children( _.options.slide + ':not(.slick-cloned)') .addClass('slick-slide'); _.slideCount = _.$slides.length; _.$slides.each(function(index, element) { $(element) .attr('data-slick-index', index) .data('originalStyling', $(element).attr('style') || ''); }); _.$slider.addClass('slick-slider'); _.$slideTrack = (_.slideCount === 0) ? $('<div class="slick-track"/>').appendTo(_.$slider) : _.$slides.wrapAll('<div class="slick-track"/>').parent(); _.$list = _.$slideTrack.wrap( '<div class="slick-list"/>').parent(); _.$slideTrack.css('opacity', 0); if (_.options.centerMode === true || _.options.swipeToSlide === true) { _.options.slidesToScroll = 1; } $('img[data-lazy]', _.$slider).not('[src]').addClass('slick-loading'); _.setupInfinite(); _.buildArrows(); _.buildDots(); _.updateDots(); _.setSlideClasses(typeof _.currentSlide === 'number' ? _.currentSlide : 0); if (_.options.draggable === true) { _.$list.addClass('draggable'); } }; Slick.prototype.buildRows = function() { var _ = this, a, b, c, newSlides, numOfSlides, originalSlides,slidesPerSection; newSlides = document.createDocumentFragment(); originalSlides = _.$slider.children(); if(_.options.rows > 0) { slidesPerSection = _.options.slidesPerRow * _.options.rows; numOfSlides = Math.ceil( originalSlides.length / slidesPerSection ); for(a = 0; a < numOfSlides; a++){ var slide = document.createElement('div'); for(b = 0; b < _.options.rows; b++) { var row = document.createElement('div'); for(c = 0; c < _.options.slidesPerRow; c++) { var target = (a * slidesPerSection + ((b * _.options.slidesPerRow) + c)); if (originalSlides.get(target)) { row.appendChild(originalSlides.get(target)); } } slide.appendChild(row); } newSlides.appendChild(slide); } _.$slider.empty().append(newSlides); _.$slider.children().children().children() .css({ 'width':(100 / _.options.slidesPerRow) + '%', 'display': 'inline-block' }); } }; Slick.prototype.checkResponsive = function(initial, forceUpdate) { var _ = this, breakpoint, targetBreakpoint, respondToWidth, triggerBreakpoint = false; var sliderWidth = _.$slider.width(); var windowWidth = window.innerWidth || $(window).width(); if (_.respondTo === 'window') { respondToWidth = windowWidth; } else if (_.respondTo === 'slider') { respondToWidth = sliderWidth; } else if (_.respondTo === 'min') { respondToWidth = Math.min(windowWidth, sliderWidth); } if ( _.options.responsive && _.options.responsive.length && _.options.responsive !== null) { targetBreakpoint = null; for (breakpoint in _.breakpoints) { if (_.breakpoints.hasOwnProperty(breakpoint)) { if (_.originalSettings.mobileFirst === false) { if (respondToWidth < _.breakpoints[breakpoint]) { targetBreakpoint = _.breakpoints[breakpoint]; } } else { if (respondToWidth > _.breakpoints[breakpoint]) { targetBreakpoint = _.breakpoints[breakpoint]; } } } } if (targetBreakpoint !== null) { if (_.activeBreakpoint !== null) { if (targetBreakpoint !== _.activeBreakpoint || forceUpdate) { _.activeBreakpoint = targetBreakpoint; if (_.breakpointSettings[targetBreakpoint] === 'unslick') { _.unslick(targetBreakpoint); } else { _.options = $.extend({}, _.originalSettings, _.breakpointSettings[ targetBreakpoint]); if (initial === true) { _.currentSlide = _.options.initialSlide; } _.refresh(initial); } triggerBreakpoint = targetBreakpoint; } } else { _.activeBreakpoint = targetBreakpoint; if (_.breakpointSettings[targetBreakpoint] === 'unslick') { _.unslick(targetBreakpoint); } else { _.options = $.extend({}, _.originalSettings, _.breakpointSettings[ targetBreakpoint]); if (initial === true) { _.currentSlide = _.options.initialSlide; } _.refresh(initial); } triggerBreakpoint = targetBreakpoint; } } else { if (_.activeBreakpoint !== null) { _.activeBreakpoint = null; _.options = _.originalSettings; if (initial === true) { _.currentSlide = _.options.initialSlide; } _.refresh(initial); triggerBreakpoint = targetBreakpoint; } } // only trigger breakpoints during an actual break. not on initialize. if( !initial && triggerBreakpoint !== false ) { _.$slider.trigger('breakpoint', [_, triggerBreakpoint]); } } }; Slick.prototype.changeSlide = function(event, dontAnimate) { var _ = this, $target = $(event.currentTarget), indexOffset, slideOffset, unevenOffset; // If target is a link, prevent default action. if($target.is('a')) { event.preventDefault(); } // If target is not the <li> element (ie: a child), find the <li>. if(!$target.is('li')) { $target = $target.closest('li'); } unevenOffset = (_.slideCount % _.options.slidesToScroll !== 0); indexOffset = unevenOffset ? 0 : (_.slideCount - _.currentSlide) % _.options.slidesToScroll; switch (event.data.message) { case 'previous': slideOffset = indexOffset === 0 ? _.options.slidesToScroll : _.options.slidesToShow - indexOffset; if (_.slideCount > _.options.slidesToShow) { _.slideHandler(_.currentSlide - slideOffset, false, dontAnimate); } break; case 'next': slideOffset = indexOffset === 0 ? _.options.slidesToScroll : indexOffset; if (_.slideCount > _.options.slidesToShow) { _.slideHandler(_.currentSlide + slideOffset, false, dontAnimate); } break; case 'index': var index = event.data.index === 0 ? 0 : event.data.index || $target.index() * _.options.slidesToScroll; _.slideHandler(_.checkNavigable(index), false, dontAnimate); $target.children().trigger('focus'); break; default: return; } }; Slick.prototype.checkNavigable = function(index) { var _ = this, navigables, prevNavigable; navigables = _.getNavigableIndexes(); prevNavigable = 0; if (index > navigables[navigables.length - 1]) { index = navigables[navigables.length - 1]; } else { for (var n in navigables) { if (index < navigables[n]) { index = prevNavigable; break; } prevNavigable = navigables[n]; } } return index; }; Slick.prototype.cleanUpEvents = function() { var _ = this; if (_.options.dots && _.$dots !== null) { $('li', _.$dots) .off('click.slick', _.changeSlide) .off('mouseenter.slick', $.proxy(_.interrupt, _, true)) .off('mouseleave.slick', $.proxy(_.interrupt, _, false)); if (_.options.accessibility === true) { _.$dots.off('keydown.slick', _.keyHandler); } } _.$slider.off('focus.slick blur.slick'); if (_.options.arrows === true && _.slideCount > _.options.slidesToShow) { _.$prevArrow && _.$prevArrow.off('click.slick', _.changeSlide); _.$nextArrow && _.$nextArrow.off('click.slick', _.changeSlide); if (_.options.accessibility === true) { _.$prevArrow && _.$prevArrow.off('keydown.slick', _.keyHandler); _.$nextArrow && _.$nextArrow.off('keydown.slick', _.keyHandler); } } _.$list.off('touchstart.slick mousedown.slick', _.swipeHandler); _.$list.off('touchmove.slick mousemove.slick', _.swipeHandler); _.$list.off('touchend.slick mouseup.slick', _.swipeHandler); _.$list.off('touchcancel.slick mouseleave.slick', _.swipeHandler); _.$list.off('click.slick', _.clickHandler); $(document).off(_.visibilityChange, _.visibility); _.cleanUpSlideEvents(); if (_.options.accessibility === true) { _.$list.off('keydown.slick', _.keyHandler); } if (_.options.focusOnSelect === true) { $(_.$slideTrack).children().off('click.slick', _.selectHandler); } $(window).off('orientationchange.slick.slick-' + _.instanceUid, _.orientationChange); $(window).off('resize.slick.slick-' + _.instanceUid, _.resize); $('[draggable!=true]', _.$slideTrack).off('dragstart', _.preventDefault); $(window).off('load.slick.slick-' + _.instanceUid, _.setPosition); }; Slick.prototype.cleanUpSlideEvents = function() { var _ = this; _.$list.off('mouseenter.slick', $.proxy(_.interrupt, _, true)); _.$list.off('mouseleave.slick', $.proxy(_.interrupt, _, false)); }; Slick.prototype.cleanUpRows = function() { var _ = this, originalSlides; if(_.options.rows > 0) { originalSlides = _.$slides.children().children(); originalSlides.removeAttr('style'); _.$slider.empty().append(originalSlides); } }; Slick.prototype.clickHandler = function(event) { var _ = this; if (_.shouldClick === false) { event.stopImmediatePropagation(); event.stopPropagation(); event.preventDefault(); } }; Slick.prototype.destroy = function(refresh) { var _ = this; _.autoPlayClear(); _.touchObject = {}; _.cleanUpEvents(); $('.slick-cloned', _.$slider).detach(); if (_.$dots) { _.$dots.remove(); } if ( _.$prevArrow && _.$prevArrow.length ) { _.$prevArrow .removeClass('slick-disabled slick-arrow slick-hidden') .removeAttr('aria-hidden aria-disabled tabindex') .css('display',''); if ( _.htmlExpr.test( _.options.prevArrow )) { _.$prevArrow.remove(); } } if ( _.$nextArrow && _.$nextArrow.length ) { _.$nextArrow .removeClass('slick-disabled slick-arrow slick-hidden') .removeAttr('aria-hidden aria-disabled tabindex') .css('display',''); if ( _.htmlExpr.test( _.options.nextArrow )) { _.$nextArrow.remove(); } } if (_.$slides) { _.$slides .removeClass('slick-slide slick-active slick-center slick-visible slick-current') .removeAttr('aria-hidden') .removeAttr('data-slick-index') .each(function(){ $(this).attr('style', $(this).data('originalStyling')); }); _.$slideTrack.children(this.options.slide).detach(); _.$slideTrack.detach(); _.$list.detach(); _.$slider.append(_.$slides); } _.cleanUpRows(); _.$slider.removeClass('slick-slider'); _.$slider.removeClass('slick-initialized'); _.$slider.removeClass('slick-dotted'); _.unslicked = true; if(!refresh) { _.$slider.trigger('destroy', [_]); } }; Slick.prototype.disableTransition = function(slide) { var _ = this, transition = {}; transition[_.transitionType] = ''; if (_.options.fade === false) { _.$slideTrack.css(transition); } else { _.$slides.eq(slide).css(transition); } }; Slick.prototype.fadeSlide = function(slideIndex, callback) { var _ = this; if (_.cssTransitions === false) { _.$slides.eq(slideIndex).css({ zIndex: _.options.zIndex }); _.$slides.eq(slideIndex).animate({ opacity: 1 }, _.options.speed, _.options.easing, callback); } else { _.applyTransition(slideIndex); _.$slides.eq(slideIndex).css({ opacity: 1, zIndex: _.options.zIndex }); if (callback) { setTimeout(function() { _.disableTransition(slideIndex); callback.call(); }, _.options.speed); } } }; Slick.prototype.fadeSlideOut = function(slideIndex) { var _ = this; if (_.cssTransitions === false) { _.$slides.eq(slideIndex).animate({ opacity: 0, zIndex: _.options.zIndex - 2 }, _.options.speed, _.options.easing); } else { _.applyTransition(slideIndex); _.$slides.eq(slideIndex).css({ opacity: 0, zIndex: _.options.zIndex - 2 }); } }; Slick.prototype.filterSlides = Slick.prototype.slickFilter = function(filter) { var _ = this; if (filter !== null) { _.$slidesCache = _.$slides; _.unload(); _.$slideTrack.children(this.options.slide).detach(); _.$slidesCache.filter(filter).appendTo(_.$slideTrack); _.reinit(); } }; Slick.prototype.focusHandler = function() { var _ = this; _.$slider .off('focus.slick blur.slick') .on('focus.slick blur.slick', '*', function(event) { event.stopImmediatePropagation(); var $sf = $(this); setTimeout(function() { if( _.options.pauseOnFocus ) { _.focussed = $sf.is(':focus'); _.autoPlay(); } }, 0); }); }; Slick.prototype.getCurrent = Slick.prototype.slickCurrentSlide = function() { var _ = this; return _.currentSlide; }; Slick.prototype.getDotCount = function() { var _ = this; var breakPoint = 0; var counter = 0; var pagerQty = 0; if (_.options.infinite === true) { if (_.slideCount <= _.options.slidesToShow) { ++pagerQty; } else { while (breakPoint < _.slideCount) { ++pagerQty; breakPoint = counter + _.options.slidesToScroll; counter += _.options.slidesToScroll <= _.options.slidesToShow ? _.options.slidesToScroll : _.options.slidesToShow; } } } else if (_.options.centerMode === true) { pagerQty = _.slideCount; } else if(!_.options.asNavFor) { pagerQty = 1 + Math.ceil((_.slideCount - _.options.slidesToShow) / _.options.slidesToScroll); }else { while (breakPoint < _.slideCount) { ++pagerQty; breakPoint = counter + _.options.slidesToScroll; counter += _.options.slidesToScroll <= _.options.slidesToShow ? _.options.slidesToScroll : _.options.slidesToShow; } } return pagerQty - 1; }; Slick.prototype.getLeft = function(slideIndex) { var _ = this, targetLeft, verticalHeight, verticalOffset = 0, targetSlide, coef; _.slideOffset = 0; verticalHeight = _.$slides.first().outerHeight(true); if (_.options.infinite === true) { if (_.slideCount > _.options.slidesToShow) { _.slideOffset = (_.slideWidth * _.options.slidesToShow) * -1; coef = -1 if (_.options.vertical === true && _.options.centerMode === true) { if (_.options.slidesToShow === 2) { coef = -1.5; } else if (_.options.slidesToShow === 1) { coef = -2 } } verticalOffset = (verticalHeight * _.options.slidesToShow) * coef; } if (_.slideCount % _.options.slidesToScroll !== 0) { if (slideIndex + _.options.slidesToScroll > _.slideCount && _.slideCount > _.options.slidesToShow) { if (slideIndex > _.slideCount) { _.slideOffset = ((_.options.slidesToShow - (slideIndex - _.slideCount)) * _.slideWidth) * -1; verticalOffset = ((_.options.slidesToShow - (slideIndex - _.slideCount)) * verticalHeight) * -1; } else { _.slideOffset = ((_.slideCount % _.options.slidesToScroll) * _.slideWidth) * -1; verticalOffset = ((_.slideCount % _.options.slidesToScroll) * verticalHeight) * -1; } } } } else { if (slideIndex + _.options.slidesToShow > _.slideCount) { _.slideOffset = ((slideIndex + _.options.slidesToShow) - _.slideCount) * _.slideWidth; verticalOffset = ((slideIndex + _.options.slidesToShow) - _.slideCount) * verticalHeight; } } if (_.slideCount <= _.options.slidesToShow) { _.slideOffset = 0; verticalOffset = 0; } if (_.options.centerMode === true && _.slideCount <= _.options.slidesToShow) { _.slideOffset = ((_.slideWidth * Math.floor(_.options.slidesToShow)) / 2) - ((_.slideWidth * _.slideCount) / 2); } else if (_.options.centerMode === true && _.options.infinite === true) { _.slideOffset += _.slideWidth * Math.floor(_.options.slidesToShow / 2) - _.slideWidth; } else if (_.options.centerMode === true) { _.slideOffset = 0; _.slideOffset += _.slideWidth * Math.floor(_.options.slidesToShow / 2); } if (_.options.vertical === false) { targetLeft = ((slideIndex * _.slideWidth) * -1) + _.slideOffset; } else { targetLeft = ((slideIndex * verticalHeight) * -1) + verticalOffset; } if (_.options.variableWidth === true) { if (_.slideCount <= _.options.slidesToShow || _.options.infinite === false) { targetSlide = _.$slideTrack.children('.slick-slide').eq(slideIndex); } else { targetSlide = _.$slideTrack.children('.slick-slide').eq(slideIndex + _.options.slidesToShow); } if (_.options.rtl === true) { if (targetSlide[0]) { targetLeft = (_.$slideTrack.width() - targetSlide[0].offsetLeft - targetSlide.width()) * -1; } else { targetLeft = 0; } } else { targetLeft = targetSlide[0] ? targetSlide[0].offsetLeft * -1 : 0; } if (_.options.centerMode === true) { if (_.slideCount <= _.options.slidesToShow || _.options.infinite === false) { targetSlide = _.$slideTrack.children('.slick-slide').eq(slideIndex); } else { targetSlide = _.$slideTrack.children('.slick-slide').eq(slideIndex + _.options.slidesToShow + 1); } if (_.options.rtl === true) { if (targetSlide[0]) { targetLeft = (_.$slideTrack.width() - targetSlide[0].offsetLeft - targetSlide.width()) * -1; } else { targetLeft = 0; } } else { targetLeft = targetSlide[0] ? targetSlide[0].offsetLeft * -1 : 0; } targetLeft += (_.$list.width() - targetSlide.outerWidth()) / 2; } } return targetLeft; }; Slick.prototype.getOption = Slick.prototype.slickGetOption = function(option) { var _ = this; return _.options[option]; }; Slick.prototype.getNavigableIndexes = function() { var _ = this, breakPoint = 0, counter = 0, indexes = [], max; if (_.options.infinite === false) { max = _.slideCount; } else { breakPoint = _.options.slidesToScroll * -1; counter = _.options.slidesToScroll * -1; max = _.slideCount * 2; } var fs = 0; while (breakPoint < max) { indexes.push(breakPoint); breakPoint = counter + _.options.slidesToScroll; counter += _.options.slidesToScroll <= _.options.slidesToShow ? _.options.slidesToScroll : _.options.slidesToShow; fs++; if ( fs > 200 ) { console.log( 'WARNING! Infinite loop!' ); break; } } return indexes; }; Slick.prototype.getSlick = function() { return this; }; Slick.prototype.getSlideCount = function() { var _ = this, slidesTraversed, swipedSlide, centerOffset; centerOffset = _.options.centerMode === true ? _.slideWidth * Math.floor(_.options.slidesToShow / 2) : 0; if (_.options.swipeToSlide === true) { _.$slideTrack.find('.slick-slide').each(function(index, slide) { if (slide.offsetLeft - centerOffset + ($(slide).outerWidth() / 2) > (_.swipeLeft * -1)) { swipedSlide = slide; return false; } }); slidesTraversed = Math.abs($(swipedSlide).attr('data-slick-index') - _.currentSlide) || 1; return slidesTraversed; } else { return _.options.slidesToScroll; } }; Slick.prototype.goTo = Slick.prototype.slickGoTo = function(slide, dontAnimate) { var _ = this; _.changeSlide({ data: { message: 'index', index: parseInt(slide) } }, dontAnimate); }; Slick.prototype.init = function(creation) { var _ = this; if (!$(_.$slider).hasClass('slick-initialized')) { $(_.$slider).addClass('slick-initialized'); _.buildRows(); _.buildOut(); _.setProps(); _.startLoad(); _.loadSlider(); _.initializeEvents(); _.updateArrows(); _.updateDots(); _.checkResponsive(true); _.focusHandler(); } if (creation) { _.$slider.trigger('init', [_]); } if (_.options.accessibility === true) { _.initADA(); } if ( _.options.autoplay ) { _.paused = false; _.autoPlay(); } }; Slick.prototype.initADA = function() { var _ = this, numDotGroups = Math.ceil(_.slideCount / _.options.slidesToShow), tabControlIndexes = _.getNavigableIndexes().filter(function(val) { return (val >= 0) && (val < _.slideCount); }); _.$slides.add(_.$slideTrack.find('.slick-cloned')).attr({ 'aria-hidden': 'true', 'tabindex': '-1' }).find('a, input, button, select').attr({ 'tabindex': '-1' }); if (_.$dots !== null) { _.$slides.not(_.$slideTrack.find('.slick-cloned')).each(function(i) { var slideControlIndex = tabControlIndexes.indexOf(i); $(this).attr({ 'role': 'tabpanel', 'id': 'slick-slide' + _.instanceUid + i, 'tabindex': -1 }); if (slideControlIndex !== -1) { var ariaButtonControl = 'slick-slide-control' + _.instanceUid + slideControlIndex if ($('#' + ariaButtonControl).length) { $(this).attr({ 'aria-describedby': ariaButtonControl }); } } }); _.$dots.attr('role', 'tablist').find('li').each(function(i) { var mappedSlideIndex = tabControlIndexes[i]; $(this).attr({ 'role': 'presentation' }); $(this).find('button').first().attr({ 'role': 'tab', 'id': 'slick-slide-control' + _.instanceUid + i, 'aria-controls': 'slick-slide' + _.instanceUid + mappedSlideIndex, 'aria-label': (i + 1) + ' of ' + numDotGroups, 'aria-selected': null, 'tabindex': '-1' }); }).eq(_.currentSlide).find('button').attr({ 'aria-selected': 'true', 'tabindex': '0' }).end(); } for (var i=_.currentSlide, max=i+_.options.slidesToShow; i < max; i++) { if (_.options.focusOnChange) { _.$slides.eq(i).attr({'tabindex': '0'}); } else { _.$slides.eq(i).removeAttr('tabindex'); } } _.activateADA(); }; Slick.prototype.initArrowEvents = function() { var _ = this; if (_.options.arrows === true && _.slideCount > _.options.slidesToShow) { _.$prevArrow .off('click.slick') .on('click.slick', { message: 'previous' }, _.changeSlide); _.$nextArrow .off('click.slick') .on('click.slick', { message: 'next' }, _.changeSlide); if (_.options.accessibility === true) { _.$prevArrow.on('keydown.slick', _.keyHandler); _.$nextArrow.on('keydown.slick', _.keyHandler); } } }; Slick.prototype.initDotEvents = function() { var _ = this; if (_.options.dots === true && _.slideCount > _.options.slidesToShow) { $('li', _.$dots).on('click.slick', { message: 'index' }, _.changeSlide); if (_.options.accessibility === true) { _.$dots.on('keydown.slick', _.keyHandler); } } if (_.options.dots === true && _.options.pauseOnDotsHover === true && _.slideCount > _.options.slidesToShow) { $('li', _.$dots) .on('mouseenter.slick', $.proxy(_.interrupt, _, true)) .on('mouseleave.slick', $.proxy(_.interrupt, _, false)); } }; Slick.prototype.initSlideEvents = function() { var _ = this; if ( _.options.pauseOnHover ) { _.$list.on('mouseenter.slick', $.proxy(_.interrupt, _, true)); _.$list.on('mouseleave.slick', $.proxy(_.interrupt, _, false)); } }; Slick.prototype.initializeEvents = function() { var _ = this; _.initArrowEvents(); _.initDotEvents(); _.initSlideEvents(); _.$list.on('touchstart.slick mousedown.slick', { action: 'start' }, _.swipeHandler); _.$list.on('touchmove.slick mousemove.slick', { action: 'move' }, _.swipeHandler); _.$list.on('touchend.slick mouseup.slick', { action: 'end' }, _.swipeHandler); _.$list.on('touchcancel.slick mouseleave.slick', { action: 'end' }, _.swipeHandler); _.$list.on('click.slick', _.clickHandler); $(document).on(_.visibilityChange, $.proxy(_.visibility, _)); if (_.options.accessibility === true) { _.$list.on('keydown.slick', _.keyHandler); } if (_.options.focusOnSelect === true) { $(_.$slideTrack).children().on('click.slick', _.selectHandler); } $(window).on('orientationchange.slick.slick-' + _.instanceUid, $.proxy(_.orientationChange, _)); $(window).on('resize.slick.slick-' + _.instanceUid, $.proxy(_.resize, _)); $('[draggable!=true]', _.$slideTrack).on('dragstart', _.preventDefault); $(window).on('load.slick.slick-' + _.instanceUid, _.setPosition); $(_.setPosition); }; Slick.prototype.initUI = function() { var _ = this; if (_.options.arrows === true && _.slideCount > _.options.slidesToShow) { _.$prevArrow.show(); _.$nextArrow.show(); } if (_.options.dots === true && _.slideCount > _.options.slidesToShow) { _.$dots.show(); } }; Slick.prototype.keyHandler = function(event) { var _ = this; //Dont slide if the cursor is inside the form fields and arrow keys are pressed if(!event.target.tagName.match('TEXTAREA|INPUT|SELECT')) { if (event.keyCode === 37 && _.options.accessibility === true) { _.changeSlide({ data: { message: _.options.rtl === true ? 'next' : 'previous' } }); } else if (event.keyCode === 39 && _.options.accessibility === true) { _.changeSlide({ data: { message: _.options.rtl === true ? 'previous' : 'next' } }); } } }; Slick.prototype.lazyLoad = function() { var _ = this, loadRange, cloneRange, rangeStart, rangeEnd; function loadImages(imagesScope) { $('img[data-lazy]', imagesScope).each(function() { var image = $(this), imageSource = $(this).attr('data-lazy'), imageSrcSet = $(this).attr('data-srcset'), imageSizes = $(this).attr('data-sizes') || _.$slider.attr('data-sizes'), imageToLoad = document.createElement('img'); imageToLoad.onload = function() { image .animate({ opacity: 0 }, 100, function() { if (imageSrcSet) { image .attr('srcset', imageSrcSet ); if (imageSizes) { image .attr('sizes', imageSizes ); } } image .attr('src', imageSource) .animate({ opacity: 1 }, 200, function() { image .removeAttr('data-lazy data-srcset data-sizes') .removeClass('slick-loading'); }); _.$slider.trigger('lazyLoaded', [_, image, imageSource]); }); }; imageToLoad.onerror = function() { image .removeAttr( 'data-lazy' ) .removeClass( 'slick-loading' ) .addClass( 'slick-lazyload-error' ); _.$slider.trigger('lazyLoadError', [ _, image, imageSource ]); }; imageToLoad.src = imageSource; }); } if (_.options.centerMode === true) { if (_.options.infinite === true) { rangeStart = _.currentSlide + (_.options.slidesToShow / 2 + 1); rangeEnd = rangeStart + _.options.slidesToShow + 2; } else { rangeStart = Math.max(0, _.currentSlide - (_.options.slidesToShow / 2 + 1)); rangeEnd = 2 + (_.options.slidesToShow / 2 + 1) + _.currentSlide; } } else { rangeStart = _.options.infinite ? _.options.slidesToShow + _.currentSlide : _.currentSlide; rangeEnd = Math.ceil(rangeStart + _.options.slidesToShow); if (_.options.fade === true) { if (rangeStart > 0) rangeStart--; if (rangeEnd <= _.slideCount) rangeEnd++; } } loadRange = _.$slider.find('.slick-slide').slice(rangeStart, rangeEnd); if (_.options.lazyLoad === 'anticipated') { var prevSlide = rangeStart - 1, nextSlide = rangeEnd, $slides = _.$slider.find('.slick-slide'); for (var i = 0; i < _.options.slidesToScroll; i++) { if (prevSlide < 0) prevSlide = _.slideCount - 1; loadRange = loadRange.add($slides.eq(prevSlide)); loadRange = loadRange.add($slides.eq(nextSlide)); prevSlide--; nextSlide++; } } loadImages(loadRange); if (_.slideCount <= _.options.slidesToShow) { cloneRange = _.$slider.find('.slick-slide'); loadImages(cloneRange); } else if (_.currentSlide >= _.slideCount - _.options.slidesToShow) { cloneRange = _.$slider.find('.slick-cloned').slice(0, _.options.slidesToShow); loadImages(cloneRange); } else if (_.currentSlide === 0) { cloneRange = _.$slider.find('.slick-cloned').slice(_.options.slidesToShow * -1); loadImages(cloneRange); } }; Slick.prototype.loadSlider = function() { var _ = this; _.setPosition(); _.$slideTrack.css({ opacity: 1 }); _.$slider.removeClass('slick-loading'); _.initUI(); if (_.options.lazyLoad === 'progressive') { _.progressiveLazyLoad(); } }; Slick.prototype.next = Slick.prototype.slickNext = function() { var _ = this; _.changeSlide({ data: { message: 'next' } }); }; Slick.prototype.orientationChange = function() { var _ = this; _.checkResponsive(); _.setPosition(); }; Slick.prototype.pause = Slick.prototype.slickPause = function() { var _ = this; _.autoPlayClear(); _.paused = true; }; Slick.prototype.play = Slick.prototype.slickPlay = function() { var _ = this; _.autoPlay(); _.options.autoplay = true; _.paused = false; _.focussed = false; _.interrupted = false; }; Slick.prototype.postSlide = function(index) { var _ = this; if( !_.unslicked ) { _.$slider.trigger('afterChange', [_, index]); _.animating = false; if (_.slideCount > _.options.slidesToShow) { _.setPosition(); } _.swipeLeft = null; if ( _.options.autoplay ) { _.autoPlay(); } if (_.options.accessibility === true) { _.initADA(); if (_.options.focusOnChange) { var $currentSlide = $(_.$slides.get(_.currentSlide)); $currentSlide.attr('tabindex', 0).focus(); } } } }; Slick.prototype.prev = Slick.prototype.slickPrev = function() { var _ = this; _.changeSlide({ data: { message: 'previous' } }); }; Slick.prototype.preventDefault = function(event) { event.preventDefault(); }; Slick.prototype.progressiveLazyLoad = function( tryCount ) { tryCount = tryCount || 1; var _ = this, $imgsToLoad = $( 'img[data-lazy]', _.$slider ), image, imageSource, imageSrcSet, imageSizes, imageToLoad; if ( $imgsToLoad.length ) { image = $imgsToLoad.first(); imageSource = image.attr('data-lazy'); imageSrcSet = image.attr('data-srcset'); imageSizes = image.attr('data-sizes') || _.$slider.attr('data-sizes'); imageToLoad = document.createElement('img'); imageToLoad.onload = function() { if (imageSrcSet) { image .attr('srcset', imageSrcSet ); if (imageSizes) { image .attr('sizes', imageSizes ); } } image .attr( 'src', imageSource ) .removeAttr('data-lazy data-srcset data-sizes') .removeClass('slick-loading'); if ( _.options.adaptiveHeight === true ) { _.setPosition(); } _.$slider.trigger('lazyLoaded', [ _, image, imageSource ]); _.progressiveLazyLoad(); }; imageToLoad.onerror = function() { if ( tryCount < 3 ) { /** * try to load the image 3 times, * leave a slight delay so we don't get * servers blocking the request. */ setTimeout( function() { _.progressiveLazyLoad( tryCount + 1 ); }, 500 ); } else { image .removeAttr( 'data-lazy' ) .removeClass( 'slick-loading' ) .addClass( 'slick-lazyload-error' ); _.$slider.trigger('lazyLoadError', [ _, image, imageSource ]); _.progressiveLazyLoad(); } }; imageToLoad.src = imageSource; } else { _.$slider.trigger('allImagesLoaded', [ _ ]); } }; Slick.prototype.refresh = function( initializing ) { var _ = this, currentSlide, lastVisibleIndex; lastVisibleIndex = _.slideCount - _.options.slidesToShow; // in non-infinite sliders, we don't want to go past the // last visible index. if( !_.options.infinite && ( _.currentSlide > lastVisibleIndex )) { _.currentSlide = lastVisibleIndex; } // if less slides than to show, go to start. if ( _.slideCount <= _.options.slidesToShow ) { _.currentSlide = 0; } currentSlide = _.currentSlide; _.destroy(true); $.extend(_, _.initials, { currentSlide: currentSlide }); _.init(); if( !initializing ) { _.changeSlide({ data: { message: 'index', index: currentSlide } }, false); } }; Slick.prototype.registerBreakpoints = function() { var _ = this, breakpoint, currentBreakpoint, l, responsiveSettings = _.options.responsive || null; if ( $.type(responsiveSettings) === 'array' && responsiveSettings.length ) { _.respondTo = _.options.respondTo || 'window'; for ( breakpoint in responsiveSettings ) { l = _.breakpoints.length-1; if (responsiveSettings.hasOwnProperty(breakpoint)) { currentBreakpoint = responsiveSettings[breakpoint].breakpoint; // loop through the breakpoints and cut out any existing // ones with the same breakpoint number, we don't want dupes. while( l >= 0 ) { if( _.breakpoints[l] && _.breakpoints[l] === currentBreakpoint ) { _.breakpoints.splice(l,1); } l--; } _.breakpoints.push(currentBreakpoint); _.breakpointSettings[currentBreakpoint] = responsiveSettings[breakpoint].settings; } } _.breakpoints.sort(function(a, b) { return ( _.options.mobileFirst ) ? a-b : b-a; }); } }; Slick.prototype.reinit = function() { var _ = this; _.$slides = _.$slideTrack .children(_.options.slide) .addClass('slick-slide'); _.slideCount = _.$slides.length; if (_.currentSlide >= _.slideCount && _.currentSlide !== 0) { _.currentSlide = _.currentSlide - _.options.slidesToScroll; } if (_.slideCount <= _.options.slidesToShow) { _.currentSlide = 0; } _.registerBreakpoints(); _.setProps(); _.setupInfinite(); _.buildArrows(); _.updateArrows(); _.initArrowEvents(); _.buildDots(); _.updateDots(); _.initDotEvents(); _.cleanUpSlideEvents(); _.initSlideEvents(); _.checkResponsive(false, true); if (_.options.focusOnSelect === true) { $(_.$slideTrack).children().on('click.slick', _.selectHandler); } _.setSlideClasses(typeof _.currentSlide === 'number' ? _.currentSlide : 0); _.setPosition(); _.focusHandler(); _.paused = !_.options.autoplay; _.autoPlay(); _.$slider.trigger('reInit', [_]); }; Slick.prototype.resize = function() { var _ = this; if ($(window).width() !== _.windowWidth) { clearTimeout(_.windowDelay); _.windowDelay = window.setTimeout(function() { _.windowWidth = $(window).width(); _.checkResponsive(); if( !_.unslicked ) { _.setPosition(); } }, 50); } }; Slick.prototype.removeSlide = Slick.prototype.slickRemove = function(index, removeBefore, removeAll) { var _ = this; if (typeof(index) === 'boolean') { removeBefore = index; index = removeBefore === true ? 0 : _.slideCount - 1; } else { index = removeBefore === true ? --index : index; } if (_.slideCount < 1 || index < 0 || index > _.slideCount - 1) { return false; } _.unload(); if (removeAll === true) { _.$slideTrack.children().remove(); } else { _.$slideTrack.children(this.options.slide).eq(index).remove(); } _.$slides = _.$slideTrack.children(this.options.slide); _.$slideTrack.children(this.options.slide).detach(); _.$slideTrack.append(_.$slides); _.$slidesCache = _.$slides; _.reinit(); }; Slick.prototype.setCSS = function(position) { var _ = this, positionProps = {}, x, y; if (_.options.rtl === true) { position = -position; } x = _.positionProp == 'left' ? Math.ceil(position) + 'px' : '0px'; y = _.positionProp == 'top' ? Math.ceil(position) + 'px' : '0px'; positionProps[_.positionProp] = position; if (_.transformsEnabled === false) { _.$slideTrack.css(positionProps); } else { positionProps = {}; if (_.cssTransitions === false) { positionProps[_.animType] = 'translate(' + x + ', ' + y + ')'; _.$slideTrack.css(positionProps); } else { positionProps[_.animType] = 'translate3d(' + x + ', ' + y + ', 0px)'; _.$slideTrack.css(positionProps); } } }; Slick.prototype.setDimensions = function() { var _ = this; if (_.options.vertical === false) { if (_.options.centerMode === true) { _.$list.css({ padding: ('0px ' + _.options.centerPadding) }); } } else { _.$list.height(_.$slides.first().outerHeight(true) * _.options.slidesToShow); if (_.options.centerMode === true) { _.$list.css({ padding: (_.options.centerPadding + ' 0px') }); } } _.listWidth = _.$list.width(); _.listHeight = _.$list.height(); if (_.options.vertical === false && _.options.variableWidth === false) { _.slideWidth = Math.ceil(_.listWidth / _.options.slidesToShow); _.$slideTrack.width(Math.ceil((_.slideWidth * _.$slideTrack.children('.slick-slide').length))); } else if (_.options.variableWidth === true) { _.$slideTrack.width(5000 * _.slideCount); } else { _.slideWidth = Math.ceil(_.listWidth); _.$slideTrack.height(Math.ceil((_.$slides.first().outerHeight(true) * _.$slideTrack.children('.slick-slide').length))); } var offset = _.$slides.first().outerWidth(true) - _.$slides.first().width(); if (_.options.variableWidth === false) _.$slideTrack.children('.slick-slide').width(_.slideWidth - offset); }; Slick.prototype.setFade = function() { var _ = this, targetLeft; _.$slides.each(function(index, element) { targetLeft = (_.slideWidth * index) * -1; if (_.options.rtl === true) { $(element).css({ position: 'relative', right: targetLeft, top: 0, zIndex: _.options.zIndex - 2, opacity: 0 }); } else { $(element).css({ position: 'relative', left: targetLeft, top: 0, zIndex: _.options.zIndex - 2, opacity: 0 }); } }); _.$slides.eq(_.currentSlide).css({ zIndex: _.options.zIndex - 1, opacity: 1 }); }; Slick.prototype.setHeight = function() { var _ = this; if (_.options.slidesToShow === 1 && _.options.adaptiveHeight === true && _.options.vertical === false) { var targetHeight = _.$slides.eq(_.currentSlide).outerHeight(true); _.$list.css('height', targetHeight); } }; Slick.prototype.setOption = Slick.prototype.slickSetOption = function() { /** * accepts arguments in format of: * * - for changing a single option's value: * .slick("setOption", option, value, refresh ) * * - for changing a set of responsive options: * .slick("setOption", 'responsive', [{}, ...], refresh ) * * - for updating multiple values at once (not responsive) * .slick("setOption", { 'option': value, ... }, refresh ) */ var _ = this, l, item, option, value, refresh = false, type; if( $.type( arguments[0] ) === 'object' ) { option = arguments[0]; refresh = arguments[1]; type = 'multiple'; } else if ( $.type( arguments[0] ) === 'string' ) { option = arguments[0]; value = arguments[1]; refresh = arguments[2]; if ( arguments[0] === 'responsive' && $.type( arguments[1] ) === 'array' ) { type = 'responsive'; } else if ( typeof arguments[1] !== 'undefined' ) { type = 'single'; } } if ( type === 'single' ) { _.options[option] = value; } else if ( type === 'multiple' ) { $.each( option , function( opt, val ) { _.options[opt] = val; }); } else if ( type === 'responsive' ) { for ( item in value ) { if( $.type( _.options.responsive ) !== 'array' ) { _.options.responsive = [ value[item] ]; } else { l = _.options.responsive.length-1; // loop through the responsive object and splice out duplicates. while( l >= 0 ) { if( _.options.responsive[l].breakpoint === value[item].breakpoint ) { _.options.responsive.splice(l,1); } l--; } _.options.responsive.push( value[item] ); } } } if ( refresh ) { _.unload(); _.reinit(); } }; Slick.prototype.setPosition = function() { var _ = this; _.setDimensions(); _.setHeight(); if (_.options.fade === false) { _.setCSS(_.getLeft(_.currentSlide)); } else { _.setFade(); } _.$slider.trigger('setPosition', [_]); }; Slick.prototype.setProps = function() { var _ = this, bodyStyle = document.body.style; _.positionProp = _.options.vertical === true ? 'top' : 'left'; if (_.positionProp === 'top') { _.$slider.addClass('slick-vertical'); } else { _.$slider.removeClass('slick-vertical'); } if (bodyStyle.WebkitTransition !== undefined || bodyStyle.MozTransition !== undefined || bodyStyle.msTransition !== undefined) { if (_.options.useCSS === true) { _.cssTransitions = true; } } if ( _.options.fade ) { if ( typeof _.options.zIndex === 'number' ) { if( _.options.zIndex < 3 ) { _.options.zIndex = 3; } } else { _.options.zIndex = _.defaults.zIndex; } } if (bodyStyle.OTransform !== undefined) { _.animType = 'OTransform'; _.transformType = '-o-transform'; _.transitionType = 'OTransition'; if (bodyStyle.perspectiveProperty === undefined && bodyStyle.webkitPerspective === undefined) _.animType = false; } if (bodyStyle.MozTransform !== undefined) { _.animType = 'MozTransform'; _.transformType = '-moz-transform'; _.transitionType = 'MozTransition'; if (bodyStyle.perspectiveProperty === undefined && bodyStyle.MozPerspective === undefined) _.animType = false; } if (bodyStyle.webkitTransform !== undefined) { _.animType = 'webkitTransform'; _.transformType = '-webkit-transform'; _.transitionType = 'webkitTransition'; if (bodyStyle.perspectiveProperty === undefined && bodyStyle.webkitPerspective === undefined) _.animType = false; } if (bodyStyle.msTransform !== undefined) { _.animType = 'msTransform'; _.transformType = '-ms-transform'; _.transitionType = 'msTransition'; if (bodyStyle.msTransform === undefined) _.animType = false; } if (bodyStyle.transform !== undefined && _.animType !== false) { _.animType = 'transform'; _.transformType = 'transform'; _.transitionType = 'transition'; } _.transformsEnabled = _.options.useTransform && (_.animType !== null && _.animType !== false); }; Slick.prototype.setSlideClasses = function(index) { var _ = this, centerOffset, allSlides, indexOffset, remainder; allSlides = _.$slider .find('.slick-slide') .removeClass('slick-active slick-center slick-current') .attr('aria-hidden', 'true'); _.$slides .eq(index) .addClass('slick-current'); if (_.options.centerMode === true) { var evenCoef = _.options.slidesToShow % 2 === 0 ? 1 : 0; centerOffset = Math.floor(_.options.slidesToShow / 2); if (_.options.infinite === true) { if (index >= centerOffset && index <= (_.slideCount - 1) - centerOffset) { _.$slides .slice(index - centerOffset + evenCoef, index + centerOffset + 1) .addClass('slick-active') .attr('aria-hidden', 'false'); } else { indexOffset = _.options.slidesToShow + index; allSlides .slice(indexOffset - centerOffset + 1 + evenCoef, indexOffset + centerOffset + 2) .addClass('slick-active') .attr('aria-hidden', 'false'); } if (index === 0) { allSlides .eq(allSlides.length - 1 - _.options.slidesToShow) .addClass('slick-center'); } else if (index === _.slideCount - 1) { allSlides .eq(_.options.slidesToShow) .addClass('slick-center'); } } _.$slides .eq(index) .addClass('slick-center'); } else { if (index >= 0 && index <= (_.slideCount - _.options.slidesToShow)) { _.$slides .slice(index, index + _.options.slidesToShow) .addClass('slick-active') .attr('aria-hidden', 'false'); } else if (allSlides.length <= _.options.slidesToShow) { allSlides .addClass('slick-active') .attr('aria-hidden', 'false'); } else { remainder = _.slideCount % _.options.slidesToShow; indexOffset = _.options.infinite === true ? _.options.slidesToShow + index : index; if (_.options.slidesToShow == _.options.slidesToScroll && (_.slideCount - index) < _.options.slidesToShow) { allSlides .slice(indexOffset - (_.options.slidesToShow - remainder), indexOffset + remainder) .addClass('slick-active') .attr('aria-hidden', 'false'); } else { allSlides .slice(indexOffset, indexOffset + _.options.slidesToShow) .addClass('slick-active') .attr('aria-hidden', 'false'); } } } if (_.options.lazyLoad === 'ondemand' || _.options.lazyLoad === 'anticipated') { _.lazyLoad(); } }; Slick.prototype.setupInfinite = function() { var _ = this, i, slideIndex, infiniteCount; if (_.options.fade === true) { _.options.centerMode = false; } if (_.options.infinite === true && _.options.fade === false) { slideIndex = null; if (_.slideCount > _.options.slidesToShow) { if (_.options.centerMode === true) { infiniteCount = _.options.slidesToShow + 1; } else { infiniteCount = _.options.slidesToShow; } for (i = _.slideCount; i > (_.slideCount - infiniteCount); i -= 1) { slideIndex = i - 1; $(_.$slides[slideIndex]).clone(true).attr('id', '') .attr('data-slick-index', slideIndex - _.slideCount) .prependTo(_.$slideTrack).addClass('slick-cloned'); } for (i = 0; i < infiniteCount + _.slideCount; i += 1) { slideIndex = i; $(_.$slides[slideIndex]).clone(true).attr('id', '') .attr('data-slick-index', slideIndex + _.slideCount) .appendTo(_.$slideTrack).addClass('slick-cloned'); } _.$slideTrack.find('.slick-cloned').find('[id]').each(function() { $(this).attr('id', ''); }); } } }; Slick.prototype.interrupt = function( toggle ) { var _ = this; if( !toggle ) { _.autoPlay(); } _.interrupted = toggle; }; Slick.prototype.selectHandler = function(event) { var _ = this; var targetElement = $(event.target).is('.slick-slide') ? $(event.target) : $(event.target).parents('.slick-slide'); var index = parseInt(targetElement.attr('data-slick-index')); if (!index) index = 0; if (_.slideCount <= _.options.slidesToShow) { _.slideHandler(index, false, true); return; } _.slideHandler(index); }; Slick.prototype.slideHandler = function(index, sync, dontAnimate) { var targetSlide, animSlide, oldSlide, slideLeft, targetLeft = null, _ = this, navTarget; sync = sync || false; if (_.animating === true && _.options.waitForAnimate === true) { return; } if (_.options.fade === true && _.currentSlide === index) { return; } if (sync === false) { _.asNavFor(index); } targetSlide = index; targetLeft = _.getLeft(targetSlide); slideLeft = _.getLeft(_.currentSlide); _.currentLeft = _.swipeLeft === null ? slideLeft : _.swipeLeft; if (_.options.infinite === false && _.options.centerMode === false && (index < 0 || index > _.getDotCount() * _.options.slidesToScroll)) { if (_.options.fade === false) { targetSlide = _.currentSlide; if (dontAnimate !== true && _.slideCount > _.options.slidesToShow) { _.animateSlide(slideLeft, function() { _.postSlide(targetSlide); }); } else { _.postSlide(targetSlide); } } return; } else if (_.options.infinite === false && _.options.centerMode === true && (index < 0 || index > (_.slideCount - _.options.slidesToScroll))) { if (_.options.fade === false) { targetSlide = _.currentSlide; if (dontAnimate !== true && _.slideCount > _.options.slidesToShow) { _.animateSlide(slideLeft, function() { _.postSlide(targetSlide); }); } else { _.postSlide(targetSlide); } } return; } if ( _.options.autoplay ) { clearInterval(_.autoPlayTimer); } if (targetSlide < 0) { if (_.slideCount % _.options.slidesToScroll !== 0) { animSlide = _.slideCount - (_.slideCount % _.options.slidesToScroll); } else { animSlide = _.slideCount + targetSlide; } } else if (targetSlide >= _.slideCount) { if (_.slideCount % _.options.slidesToScroll !== 0) { animSlide = 0; } else { animSlide = targetSlide - _.slideCount; } } else { animSlide = targetSlide; } _.animating = true; _.$slider.trigger('beforeChange', [_, _.currentSlide, animSlide]); oldSlide = _.currentSlide; _.currentSlide = animSlide; _.setSlideClasses(_.currentSlide); if ( _.options.asNavFor ) { navTarget = _.getNavTarget(); navTarget = navTarget.slick('getSlick'); if ( navTarget.slideCount <= navTarget.options.slidesToShow ) { navTarget.setSlideClasses(_.currentSlide); } } _.updateDots(); _.updateArrows(); if (_.options.fade === true) { if (dontAnimate !== true) { _.fadeSlideOut(oldSlide); _.fadeSlide(animSlide, function() { _.postSlide(animSlide); }); } else { _.postSlide(animSlide); } _.animateHeight(); return; } if (dontAnimate !== true && _.slideCount > _.options.slidesToShow) { _.animateSlide(targetLeft, function() { _.postSlide(animSlide); }); } else { _.postSlide(animSlide); } }; Slick.prototype.startLoad = function() { var _ = this; if (_.options.arrows === true && _.slideCount > _.options.slidesToShow) { _.$prevArrow.hide(); _.$nextArrow.hide(); } if (_.options.dots === true && _.slideCount > _.options.slidesToShow) { _.$dots.hide(); } _.$slider.addClass('slick-loading'); }; Slick.prototype.swipeDirection = function() { var xDist, yDist, r, swipeAngle, _ = this; xDist = _.touchObject.startX - _.touchObject.curX; yDist = _.touchObject.startY - _.touchObject.curY; r = Math.atan2(yDist, xDist); swipeAngle = Math.round(r * 180 / Math.PI); if (swipeAngle < 0) { swipeAngle = 360 - Math.abs(swipeAngle); } if ((swipeAngle <= 45) && (swipeAngle >= 0)) { return (_.options.rtl === false ? 'left' : 'right'); } if ((swipeAngle <= 360) && (swipeAngle >= 315)) { return (_.options.rtl === false ? 'left' : 'right'); } if ((swipeAngle >= 135) && (swipeAngle <= 225)) { return (_.options.rtl === false ? 'right' : 'left'); } if (_.options.verticalSwiping === true) { if ((swipeAngle >= 35) && (swipeAngle <= 135)) { return 'down'; } else { return 'up'; } } return 'vertical'; }; Slick.prototype.swipeEnd = function(event) { var _ = this, slideCount, direction; _.dragging = false; _.swiping = false; if (_.scrolling) { _.scrolling = false; return false; } _.interrupted = false; _.shouldClick = ( _.touchObject.swipeLength > 10 ) ? false : true; if ( _.touchObject.curX === undefined ) { return false; } if ( _.touchObject.edgeHit === true ) { _.$slider.trigger('edge', [_, _.swipeDirection() ]); } if ( _.touchObject.swipeLength >= _.touchObject.minSwipe ) { direction = _.swipeDirection(); switch ( direction ) { case 'left': case 'down': slideCount = _.options.swipeToSlide ? _.checkNavigable( _.currentSlide + _.getSlideCount() ) : _.currentSlide + _.getSlideCount(); _.currentDirection = 0; break; case 'right': case 'up': slideCount = _.options.swipeToSlide ? _.checkNavigable( _.currentSlide - _.getSlideCount() ) : _.currentSlide - _.getSlideCount(); _.currentDirection = 1; break; default: } if( direction != 'vertical' ) { _.slideHandler( slideCount ); _.touchObject = {}; _.$slider.trigger('swipe', [_, direction ]); } } else { if ( _.touchObject.startX !== _.touchObject.curX ) { _.slideHandler( _.currentSlide ); _.touchObject = {}; } } }; Slick.prototype.swipeHandler = function(event) { var _ = this; if ((_.options.swipe === false) || ('ontouchend' in document && _.options.swipe === false)) { return; } else if (_.options.draggable === false && event.type.indexOf('mouse') !== -1) { return; } _.touchObject.fingerCount = event.originalEvent && event.originalEvent.touches !== undefined ? event.originalEvent.touches.length : 1; _.touchObject.minSwipe = _.listWidth / _.options .touchThreshold; if (_.options.verticalSwiping === true) { _.touchObject.minSwipe = _.listHeight / _.options .touchThreshold; } switch (event.data.action) { case 'start': _.swipeStart(event); break; case 'move': _.swipeMove(event); break; case 'end': _.swipeEnd(event); break; } }; Slick.prototype.swipeMove = function(event) { var _ = this, edgeWasHit = false, curLeft, swipeDirection, swipeLength, positionOffset, touches, verticalSwipeLength; touches = event.originalEvent !== undefined ? event.originalEvent.touches : null; if (!_.dragging || _.scrolling || touches && touches.length !== 1) { return false; } curLeft = _.getLeft(_.currentSlide); _.touchObject.curX = touches !== undefined ? touches[0].pageX : event.clientX; _.touchObject.curY = touches !== undefined ? touches[0].pageY : event.clientY; _.touchObject.swipeLength = Math.round(Math.sqrt( Math.pow(_.touchObject.curX - _.touchObject.startX, 2))); verticalSwipeLength = Math.round(Math.sqrt( Math.pow(_.touchObject.curY - _.touchObject.startY, 2))); if (!_.options.verticalSwiping && !_.swiping && verticalSwipeLength > 4) { _.scrolling = true; return false; } if (_.options.verticalSwiping === true) { _.touchObject.swipeLength = verticalSwipeLength; } swipeDirection = _.swipeDirection(); if (event.originalEvent !== undefined && _.touchObject.swipeLength > 4) { _.swiping = true; event.preventDefault(); } positionOffset = (_.options.rtl === false ? 1 : -1) * (_.touchObject.curX > _.touchObject.startX ? 1 : -1); if (_.options.verticalSwiping === true) { positionOffset = _.touchObject.curY > _.touchObject.startY ? 1 : -1; } swipeLength = _.touchObject.swipeLength; _.touchObject.edgeHit = false; if (_.options.infinite === false) { if ((_.currentSlide === 0 && swipeDirection === 'right') || (_.currentSlide >= _.getDotCount() && swipeDirection === 'left')) { swipeLength = _.touchObject.swipeLength * _.options.edgeFriction; _.touchObject.edgeHit = true; } } if (_.options.vertical === false) { _.swipeLeft = curLeft + swipeLength * positionOffset; } else { _.swipeLeft = curLeft + (swipeLength * (_.$list.height() / _.listWidth)) * positionOffset; } if (_.options.verticalSwiping === true) { _.swipeLeft = curLeft + swipeLength * positionOffset; } if (_.options.fade === true || _.options.touchMove === false) { return false; } if (_.animating === true) { _.swipeLeft = null; return false; } _.setCSS(_.swipeLeft); }; Slick.prototype.swipeStart = function(event) { var _ = this, touches; _.interrupted = true; if (_.touchObject.fingerCount !== 1 || _.slideCount <= _.options.slidesToShow) { _.touchObject = {}; return false; } if (event.originalEvent !== undefined && event.originalEvent.touches !== undefined) { touches = event.originalEvent.touches[0]; } _.touchObject.startX = _.touchObject.curX = touches !== undefined ? touches.pageX : event.clientX; _.touchObject.startY = _.touchObject.curY = touches !== undefined ? touches.pageY : event.clientY; _.dragging = true; }; Slick.prototype.unfilterSlides = Slick.prototype.slickUnfilter = function() { var _ = this; if (_.$slidesCache !== null) { _.unload(); _.$slideTrack.children(this.options.slide).detach(); _.$slidesCache.appendTo(_.$slideTrack); _.reinit(); } }; Slick.prototype.unload = function() { var _ = this; $('.slick-cloned', _.$slider).remove(); if (_.$dots) { _.$dots.remove(); } if (_.$prevArrow && _.htmlExpr.test(_.options.prevArrow)) { _.$prevArrow.remove(); } if (_.$nextArrow && _.htmlExpr.test(_.options.nextArrow)) { _.$nextArrow.remove(); } _.$slides .removeClass('slick-slide slick-active slick-visible slick-current') .attr('aria-hidden', 'true') .css('width', ''); }; Slick.prototype.unslick = function(fromBreakpoint) { var _ = this; _.$slider.trigger('unslick', [_, fromBreakpoint]); _.destroy(); }; Slick.prototype.updateArrows = function() { var _ = this, centerOffset; centerOffset = Math.floor(_.options.slidesToShow / 2); if ( _.options.arrows === true && _.slideCount > _.options.slidesToShow && !_.options.infinite ) { _.$prevArrow.removeClass('slick-disabled').attr('aria-disabled', 'false'); _.$nextArrow.removeClass('slick-disabled').attr('aria-disabled', 'false'); if (_.currentSlide === 0) { _.$prevArrow.addClass('slick-disabled').attr('aria-disabled', 'true'); _.$nextArrow.removeClass('slick-disabled').attr('aria-disabled', 'false'); } else if (_.currentSlide >= _.slideCount - _.options.slidesToShow && _.options.centerMode === false) { _.$nextArrow.addClass('slick-disabled').attr('aria-disabled', 'true'); _.$prevArrow.removeClass('slick-disabled').attr('aria-disabled', 'false'); } else if (_.currentSlide >= _.slideCount - 1 && _.options.centerMode === true) { _.$nextArrow.addClass('slick-disabled').attr('aria-disabled', 'true'); _.$prevArrow.removeClass('slick-disabled').attr('aria-disabled', 'false'); } } }; Slick.prototype.updateDots = function() { var _ = this; if (_.$dots !== null) { _.$dots .find('li') .removeClass('slick-active') .end(); _.$dots .find('li') .eq(Math.floor(_.currentSlide / _.options.slidesToScroll)) .addClass('slick-active'); } }; Slick.prototype.visibility = function() { var _ = this; if ( _.options.autoplay ) { if ( document[_.hidden] ) { _.interrupted = true; } else { _.interrupted = false; } } }; $.fn.slick = function() { var _ = this, opt = arguments[0], args = Array.prototype.slice.call(arguments, 1), l = _.length, i, ret; for (i = 0; i < l; i++) { if (typeof opt == 'object' || typeof opt == 'undefined') _[i].slick = new Slick(_[i], opt); else ret = _[i].slick[opt].apply(_[i].slick, args); if (typeof ret != 'undefined') return ret; } return _; }; $( document ).ready(function() { $( '.exopite-multifilter-items.slick-carousel' ).each(function ( idx, item ) { var carouselId = "slick-carousel" + idx; var data = $( this ).parent( '.exopite-multifilter-container' ).data( 'carousel' ); if ( typeof data !== "undefined" ) { this.id = carouselId; $( this ).slick({ autoplay: ( data.autoplay === 'false' ) ? false : true, arrows: ( data.arrows === 'false' ) ? false : true, autoplaySpeed: data.autoplay_speed, infinite: ( data.infinite === 'false' ) ? false : true, speed: parseInt( data.speed ), pauseOnHover: ( data.pause_on_hover === 'false' ) ? false : true, dots: ( data.dots === 'false' ) ? false : true, adaptiveHeight: ( data.adaptive_height === 'false' ) ? false : true, mobileFirst: ( data.mobile_first === 'false' ) ? false : true, slidesPerRow: parseInt( data.slides_per_row ), slidesToShow: parseInt( data.slides_to_show ), slidesToScroll: parseInt( data.slides_to_scroll ), useTransform: ( data.use_transform === 'false' ) ? false : true, }); } }); }); }));
JoeSz/exopite-multifilter
exopite-multifilter/public/js/slick.dev.js
JavaScript
gpl-3.0
90,524
HostCMS 6.7 = 9fdd2118a94f53ca1c411a7629edf565
gohdan/DFC
known_files/hashes/admin/wysiwyg/plugins/imagetools/plugin.min.js
JavaScript
gpl-3.0
47
import { DASHBOARD_ACTIVE_COIN_CHANGE, DASHBOARD_ACTIVE_COIN_BALANCE, DASHBOARD_ACTIVE_COIN_SEND_FORM, DASHBOARD_ACTIVE_COIN_RECEIVE_FORM, DASHBOARD_ACTIVE_COIN_RESET_FORMS, DASHBOARD_ACTIVE_SECTION, DASHBOARD_ACTIVE_TXINFO_MODAL, ACTIVE_COIN_GET_ADDRESSES, DASHBOARD_ACTIVE_COIN_NATIVE_BALANCE, DASHBOARD_ACTIVE_COIN_NATIVE_TXHISTORY, DASHBOARD_ACTIVE_COIN_NATIVE_OPIDS, DASHBOARD_ACTIVE_COIN_SENDTO, DASHBOARD_ACTIVE_ADDRESS, DASHBOARD_ACTIVE_COIN_GETINFO_FAILURE, SYNCING_NATIVE_MODE, DASHBOARD_UPDATE, DASHBOARD_ELECTRUM_BALANCE, DASHBOARD_ELECTRUM_TRANSACTIONS, DASHBOARD_REMOVE_COIN, DASHBOARD_ACTIVE_COIN_NET_PEERS, DASHBOARD_ACTIVE_COIN_NET_TOTALS, KV_HISTORY, DASHBOARD_ETHEREUM_BALANCE, DASHBOARD_ETHEREUM_TRANSACTIONS, DASHBOARD_CLEAR_ACTIVECOIN, } from '../actions/storeType'; // TODO: refactor current coin props copy on change const defaults = { native: { coin: null, mode: null, send: false, receive: false, balance: 0, addresses: null, activeSection: 'default', showTransactionInfo: false, showTransactionInfoTxIndex: null, txhistory: [], opids: null, lastSendToResponse: null, progress: null, rescanInProgress: false, getinfoFetchFailures: 0, net: { peers: null, totals: null, }, }, spv: { coin: null, mode: null, send: false, receive: false, balance: 0, addresses: null, activeSection: 'default', showTransactionInfo: false, showTransactionInfoTxIndex: null, txhistory: [], lastSendToResponse: null, }, eth: { coin: null, mode: null, send: false, receive: false, balance: 0, addresses: null, activeSection: 'default', showTransactionInfo: false, showTransactionInfoTxIndex: null, txhistory: [], lastSendToResponse: null, }, }; const checkCoinObjectKeys = (obj, mode) => { if (Object.keys(obj).length && mode) { for (let key in obj) { if (!defaults[mode].hasOwnProperty(key)) { delete obj[key]; } } } return obj; }; export const ActiveCoin = (state = { coins: { native: {}, spv: {}, eth: {}, }, coin: null, mode: null, send: false, receive: false, balance: 0, addresses: null, activeSection: 'default', showTransactionInfo: false, showTransactionInfoTxIndex: null, txhistory: [], opids: null, lastSendToResponse: null, activeAddress: null, progress: null, rescanInProgress: false, getinfoFetchFailures: 0, net: { peers: null, totals: null, }, }, action) => { switch (action.type) { case DASHBOARD_REMOVE_COIN: delete state.coins[action.mode][action.coin]; if (state.coin === action.coin) { return { ...state, ...defaults[action.mode], }; } else { return { ...state, }; } case DASHBOARD_ACTIVE_COIN_CHANGE: if (state.coins[action.mode] && state.coins[action.mode][action.coin]) { let _coins = state.coins; if (action.mode === state.mode) { const _coinData = state.coins[action.mode][action.coin]; const _coinDataToStore = checkCoinObjectKeys({ addresses: state.addresses, coin: state.coin, mode: state.mode, balance: state.balance, txhistory: state.txhistory, send: state.send, receive: state.receive, showTransactionInfo: state.showTransactionInfo, showTransactionInfoTxIndex: state.showTransactionInfoTxIndex, activeSection: state.activeSection, lastSendToResponse: state.lastSendToResponse, opids: state.mode === 'native' ? state.opids : null, activeAddress: state.activeAddress, progress: state.mode === 'native' ? state.progress : null, rescanInProgress: state.mode === 'native' ? state.rescanInProgress : false, getinfoFetchFailures: state.mode === 'native' ? state.getinfoFetchFailures : 0, net: state.mode === 'native' ? state.net : {}, }, action.mode); if (!action.skip) { _coins[action.mode][state.coin] = _coinDataToStore; } delete _coins.undefined; return { ...state, coins: _coins, ...checkCoinObjectKeys({ addresses: _coinData.addresses, coin: _coinData.coin, mode: _coinData.mode, balance: _coinData.balance, txhistory: _coinData.txhistory, send: _coinData.send, receive: _coinData.receive, showTransactionInfo: _coinData.showTransactionInfo, showTransactionInfoTxIndex: _coinData.showTransactionInfoTxIndex, activeSection: _coinData.activeSection, lastSendToResponse: _coinData.lastSendToResponse, opids: _coinData.mode === 'native' ? _coinData.opids : null, activeAddress: _coinData.activeAddress, progress: _coinData.mode === 'native' ? _coinData.progress : null, rescanInProgress: _coinData.mode === 'native' ? _coinData.rescanInProgress : false, getinfoFetchFailures: _coinData.mode === 'native' ? _coinData.getinfoFetchFailures : 0, net: _coinData.mode === 'native' ? _coinData.net : {}, }, _coinData.mode), }; } else { delete _coins.undefined; return { ...state, coins: state.coins, ...checkCoinObjectKeys({ coin: action.coin, mode: action.mode, balance: 0, addresses: null, txhistory: 'loading', send: false, receive: false, showTransactionInfo: false, showTransactionInfoTxIndex: null, activeSection: 'default', progress: null, rescanInProgress: false, net: { peers: null, totals: null, }, }, action.mode), }; } } else { if (state.coin) { const _coinData = checkCoinObjectKeys({ addresses: state.addresses, coin: state.coin, mode: state.mode, balance: state.balance, txhistory: state.txhistory, send: state.send, receive: state.receive, showTransactionInfo: state.showTransactionInfo, showTransactionInfoTxIndex: state.showTransactionInfoTxIndex, activeSection: state.activeSection, lastSendToResponse: state.lastSendToResponse, opids: state.mode === 'native' ? state.opids : null, activeAddress: state.activeAddress, progress: state.mode === 'native' ? state.progress : null, rescanInProgress: state.mode === 'native' ? state.rescanInProgress : false, getinfoFetchFailures: state.mode === 'native' ? state.getinfoFetchFailures : 0, net: state.mode === 'native' ? state.net : {}, }, state.mode); let _coins = state.coins; if (!action.skip && _coins[action.mode]) { _coins[action.mode][state.coin] = _coinData; } return { ...state, coins: _coins, ...checkCoinObjectKeys({ coin: action.coin, mode: action.mode, balance: 0, addresses: null, txhistory: 'loading', send: false, receive: false, showTransactionInfo: false, showTransactionInfoTxIndex: null, activeSection: 'default', progress: null, rescanInProgress: false, net: { peers: null, totals: null, }, }, action.mode), }; } else { return { ...state, ...checkCoinObjectKeys({ coin: action.coin, mode: action.mode, balance: 0, addresses: null, txhistory: 'loading', send: false, receive: false, showTransactionInfo: false, showTransactionInfoTxIndex: null, activeSection: 'default', progress: null, rescanInProgress: false, net: { peers: null, totals: null, }, }, action.mode), }; } } case DASHBOARD_ELECTRUM_BALANCE: return { ...state, balance: action.balance, }; case DASHBOARD_ELECTRUM_TRANSACTIONS: return { ...state, txhistory: action.txhistory, }; case DASHBOARD_ACTIVE_COIN_BALANCE: return { ...state, balance: action.balance, }; case DASHBOARD_ACTIVE_COIN_SEND_FORM: return { ...state, send: action.send, receive: false, }; case DASHBOARD_ACTIVE_COIN_RECEIVE_FORM: return { ...state, send: false, receive: action.receive, }; case DASHBOARD_ACTIVE_COIN_RESET_FORMS: return { ...state, send: false, receive: false, }; case ACTIVE_COIN_GET_ADDRESSES: return { ...state, addresses: action.addresses, }; case DASHBOARD_ACTIVE_SECTION: return { ...state, activeSection: action.section, }; case DASHBOARD_ACTIVE_TXINFO_MODAL: return { ...state, showTransactionInfo: action.showTransactionInfo, showTransactionInfoTxIndex: action.showTransactionInfoTxIndex, }; case DASHBOARD_ACTIVE_COIN_NATIVE_BALANCE: return { ...state, balance: action.balance, }; case DASHBOARD_ACTIVE_COIN_NATIVE_TXHISTORY: return { ...state, txhistory: action.txhistory, }; case DASHBOARD_ACTIVE_COIN_NATIVE_OPIDS: return { ...state, opids: action.opids, }; case DASHBOARD_ACTIVE_COIN_SENDTO: return { ...state, lastSendToResponse: action.lastSendToResponse, }; case DASHBOARD_ACTIVE_ADDRESS: return { ...state, activeAddress: action.address, }; case SYNCING_NATIVE_MODE: return { ...state, progress: state.mode === 'native' ? action.progress : null, getinfoFetchFailures: typeof action.progress === 'string' && action.progress.indexOf('"code":-777') ? state.getinfoFetchFailures + 1 : 0, }; case DASHBOARD_ACTIVE_COIN_GETINFO_FAILURE: return { ...state, getinfoFetchFailures: state.getinfoFetchFailures + 1, }; case DASHBOARD_UPDATE: if (state.coin === action.coin) { return { ...state, opids: action.opids, txhistory: action.txhistory, balance: action.balance, addresses: action.addresses, rescanInProgress: action.rescanInProgress, }; } case DASHBOARD_ACTIVE_COIN_NET_PEERS: return { ...state, net: { peers: action.peers, totals: state.net.totals, }, }; case DASHBOARD_ACTIVE_COIN_NET_TOTALS: return { ...state, net: { peers: state.net.peers, totals: action.totals, }, }; case DASHBOARD_ETHEREUM_BALANCE: return { ...state, balance: action.balance, }; case DASHBOARD_ETHEREUM_TRANSACTIONS: return { ...state, txhistory: action.txhistory, }; case DASHBOARD_CLEAR_ACTIVECOIN: return { coins: { native: {}, spv: {}, eth: {}, }, coin: null, mode: null, balance: 0, addresses: null, txhistory: 'loading', send: false, receive: false, showTransactionInfo: false, showTransactionInfoTxIndex: null, activeSection: 'default', progress: null, rescanInProgress: false, net: { peers: null, totals: null, }, getinfoFetchFailures: 0, }; default: return state; } } export default ActiveCoin;
pbca26/EasyDEX-GUI
react/src/reducers/activeCoin.js
JavaScript
gpl-3.0
12,574
// urlParams is null when used for embedding window.urlParams = window.urlParams || {}; // isLocalStorage controls access to local storage window.isLocalStorage = window.isLocalStorage || false; // Checks for SVG support window.isSvgBrowser = window.isSvgBrowser || (navigator.userAgent.indexOf('MSIE') < 0 || document.documentMode >= 9); // CUSTOM_PARAMETERS - URLs for save and export window.EXPORT_URL = window.EXPORT_URL || 'https://exp.draw.io/ImageExport4/export'; window.SAVE_URL = window.SAVE_URL || 'save'; window.OPEN_URL = window.OPEN_URL || 'open'; window.PROXY_URL = window.PROXY_URL || 'proxy'; // Paths and files window.SHAPES_PATH = window.SHAPES_PATH || 'shapes'; // Path for images inside the diagram window.GRAPH_IMAGE_PATH = window.GRAPH_IMAGE_PATH || 'img'; window.ICONSEARCH_PATH = window.ICONSEARCH_PATH || (navigator.userAgent.indexOf('MSIE') >= 0 || urlParams['dev']) ? 'iconSearch' : 'https://www.draw.io/iconSearch'; window.TEMPLATE_PATH = window.TEMPLATE_PATH || '/templates'; // Directory for i18 files and basename for main i18n file window.RESOURCES_PATH = window.RESOURCES_PATH || 'resources'; window.RESOURCE_BASE = window.RESOURCE_BASE || RESOURCES_PATH + '/dia'; // URL for logging window.DRAWIO_LOG_URL = window.DRAWIO_LOG_URL || ''; // Sets the base path, the UI language via URL param and configures the // supported languages to avoid 404s. The loading of all core language // resources is disabled as all required resources are in grapheditor. // properties. Note that in this example the loading of two resource // files (the special bundle and the default bundle) is disabled to // save a GET request. This requires that all resources be present in // the special bundle. window.mxLoadResources = window.mxLoadResources || false; window.mxLanguage = window.mxLanguage || (function() { var lang = (urlParams['offline'] == '1') ? 'en' : urlParams['lang']; // Known issue: No JSON object at this point in quirks in IE8 if (lang == null && typeof(JSON) != 'undefined') { // Cannot use mxSettings here if (isLocalStorage) { try { var value = localStorage.getItem('.drawio-config'); if (value != null) { lang = JSON.parse(value).language || null; } } catch (e) { // cookies are disabled, attempts to use local storage will cause // a DOM error at a minimum on Chrome isLocalStorage = false; } } } return lang; })(); // Add new languages here. First entry is translated to [Automatic] // in the menu defintion in Diagramly.js. window.mxLanguageMap = window.mxLanguageMap || { 'i18n': '', 'id' : 'Bahasa Indonesia', 'ms' : 'Bahasa Melayu', 'bs' : 'Bosanski', 'ca' : 'Català', 'cs' : 'Čeština', 'da' : 'Dansk', 'de' : 'Deutsch', 'et' : 'Eesti', 'en' : 'English', 'es' : 'Español', 'eo' : 'Esperanto', 'fil' : 'Filipino', 'fr' : 'Français', 'it' : 'Italiano', 'hu' : 'Magyar', 'nl' : 'Nederlands', 'no' : 'Norsk', 'pl' : 'Polski', 'pt-br' : 'Português (Brasil)', 'pt' : 'Português (Portugal)', 'ro' : 'Română', 'fi' : 'Suomi', 'sv' : 'Svenska', 'vi' : 'Tiếng Việt', 'tr' : 'Türkçe', 'el' : 'Ελληνικά', 'ru' : 'Русский', 'sr' : 'Српски', 'uk' : 'Українська', 'he' : 'עברית', 'ar' : 'العربية', 'th' : 'ไทย', 'ko' : '한국어', 'ja' : '日本語', 'zh' : '中文(中国)', 'zh-tw' : '中文(台灣)' }; if (typeof window.mxBasePath === 'undefined') { window.mxBasePath = 'mxgraph'; } if (window.mxLanguages == null) { window.mxLanguages = []; // Populates the list of supported special language bundles for (var lang in mxLanguageMap) { // Empty means default (ie. browser language), "en" means English (default for unsupported languages) // Since "en" uses no extension this must not be added to the array of supported language bundles. if (lang != 'en') { window.mxLanguages.push(lang); } } } /** * Returns the global UI setting before runngin static draw.io code */ window.uiTheme = window.uiTheme || (function() { var ui = urlParams['ui']; // Known issue: No JSON object at this point in quirks in IE8 if (ui == null && typeof JSON !== 'undefined') { // Cannot use mxSettings here if (isLocalStorage) { try { var value = localStorage.getItem('.drawio-config'); if (value != null) { ui = JSON.parse(value).ui || null; } } catch (e) { // cookies are disabled, attempts to use local storage will cause // a DOM error at a minimum on Chrome isLocalStorage = false; } } } return ui; })(); /** * Global function for loading local files via servlet */ function setCurrentXml(data, filename) { if (window.parent != null && window.parent.openFile != null) { window.parent.openFile.setData(data, filename); } }; /** * Overrides splash URL parameter via local storage */ (function() { // Known issue: No JSON object at this point in quirks in IE8 if (typeof JSON !== 'undefined') { // Cannot use mxSettings here if (isLocalStorage) { try { var value = localStorage.getItem('.drawio-config'); var showSplash = true; if (value != null) { showSplash = JSON.parse(value).showStartScreen; } // Undefined means true if (showSplash == false) { urlParams['splash'] = '0'; } } catch (e) { // ignore } } } })(); // Customizes export URL var ex = urlParams['export']; if (ex != null) { if (ex.substring(0, 7) != 'http://' && ex.substring(0, 8) != 'https://') { ex = 'http://' + ex; } EXPORT_URL = ex; } // Enables offline mode if (urlParams['offline'] == '1' || urlParams['demo'] == '1' || urlParams['stealth'] == '1' || urlParams['local'] == '1') { urlParams['analytics'] = '0'; urlParams['picker'] = '0'; urlParams['gapi'] = '0'; urlParams['db'] = '0'; urlParams['od'] = '0'; urlParams['gh'] = '0'; } // Disables math in offline mode if (urlParams['offline'] == '1' || urlParams['local'] == '1') { urlParams['math'] = '0'; } // Lightbox enabled chromeless mode if (urlParams['lightbox'] == '1') { urlParams['chrome'] = '0'; } // Adds hard-coded logging domain for draw.io domains var host = window.location.host; var searchString = 'draw.io'; var position = host.length - searchString.length; var lastIndex = host.lastIndexOf(searchString, position); if (lastIndex !== -1 && lastIndex === position && host != 'test.draw.io') { // endsWith polyfill window.DRAWIO_LOG_URL = 'https://log.draw.io'; }
crazykeyboard/draw.io
war/js/diagramly/Init.js
JavaScript
gpl-3.0
6,535
var chai = require('chai') , sinon = require('sinon') , sinonChai = require('sinon-chai') , expect = chai.expect , Promise = require('es6-promise').Promise , UpdateTemplatesController = require('../../../platypi-cli/controllers/cli/updatetemplates.controller'); chai.use(sinonChai); describe('TemplateUpdate controller', function () { it('should return a new controller', function (done) { try { var controller = new UpdateTemplatesController({ viewStuff: 'fakeview' }); expect(controller).to.be.an.object; expect(controller.model).to.be.an.object; expect(controller.view).to.be.an.object; expect(controller.view.model).to.equal(controller.model); done(); } catch (e) { done(e); } }); describe('getResponseView method', function () { var sandbox, controller, updateFunc; beforeEach(function (done) { sandbox = sinon.sandbox.create(); controller = new UpdateTemplatesController({ viewStuff: 'fakeview' }); updateFunc = sandbox.stub(controller.__provider, 'update'); done(); }); afterEach(function (done) { sandbox.restore(); done(); }); it('should call the clean method and return the view', function (done) { updateFunc.returns(Promise.resolve('')); controller.getResponseView().then(function (view) { try { expect(updateFunc).to.have.been.called; expect(controller.model.successMessage).not.to.equal(''); expect(view).to.exist; done(); } catch (e) { done(e); } }, function (err) { done(err); }); }); it('should call the update method and throw an error', function (done) { updateFunc.returns(Promise.reject('Err')); controller.getResponseView().then(function (view) { try { expect(updateFunc).to.have.been.called; expect(controller.model.errorMessage).not.to.equal(''); expect(view).to.exist; done(); } catch (e) { done(e); } }, function (err) { done(err); }); }); }); });
tonylegrone/platypi-cli
test/controllers/cli/updatetemplates.controller.test.js
JavaScript
gpl-3.0
2,558
var path = require('path'); var Q = require('q'); var fs = require('fs'); var mv = require('mv'); var Upload = require('./upload.model'); exports.upload = function (req, res) { var tmpPath = req.files[0].path; var newFileName = Math.random().toString(36).substring(7)+path.extname(tmpPath); var targetPath = path.resolve(process.env.UPLOAD_PATH, newFileName); var defer = Q.defer(); mv(tmpPath, targetPath, function (err) { if (err) { return nextIteration.reject(err); } targetPath = targetPath.substring(targetPath.indexOf('upload')); Upload.createUpload(targetPath).then(function(upload) { defer.resolve(upload); }, function(err) { defer.reject(err); }); }); defer.promise.then(function (upload) { res.json({ status: true, data: upload._id }); }, function(err) { console.log(err); res.json({ status: false, reason: err.toString() }); }); };
NishantDesai1306/lost-and-found
server/api/upload/upload.controller.js
JavaScript
gpl-3.0
1,066
// Karma configuration // Generated on Thu Jul 24 2014 18:11:41 GMT-0700 (PDT) module.exports = function(config) { config.set({ // base path that will be used to resolve all patterns (eg. files, exclude) basePath: '', // frameworks to use // available frameworks: https://npmjs.org/browse/keyword/karma-adapter frameworks: ['jasmine'], // list of files / patterns to load in the browser files: [ 'bower_components/angular/angular.js', 'bower_components/angular-mocks/angular-mocks.js', 'bower_components/angular-resource/angular-resource.js', 'src/*.js', 'test/*.js' ], // list of files to exclude exclude: [ ], // preprocess matching files before serving them to the browser // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor preprocessors: { }, // test results reporter to use // possible values: 'dots', 'progress' // available reporters: https://npmjs.org/browse/keyword/karma-reporter reporters: ['progress'], // web server port port: 9876, // enable / disable colors in the output (reporters and logs) colors: true, // level of logging // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG logLevel: config.LOG_INFO, // enable / disable watching file and executing tests whenever any file changes autoWatch: true, // start these browsers // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher browsers: [], // Continuous Integration mode // if true, Karma captures browsers, runs the tests and exits singleRun: false }); };
bthaase/DDWarden
html/lib/angular-abortable-requests/karma.conf.js
JavaScript
gpl-3.0
1,741
/*global require,module,console,angular */ require("angular/angular"); require("angular-route/angular-route"); angular.module("RegistrationApp", ["ngRoute"]); angular.module("RegistrationApp").controller("RegistrationCtrl", require("./components/registration/controller")); angular.module("RegistrationApp").directive("myRegistration", require("./components/registration/directive")); angular.module("MainApp", [ "RegistrationApp" ]); angular.module("MainApp").config(["$routeProvider", "$locationProvider", require("./app.routes")]);
gios/angular-modular-seed
app/app.modules.js
JavaScript
gpl-3.0
542
/* * jQuery JavaScript Library v1.10.1 * http://jquery.com/ * * Includes Sizzle.js * http://sizzlejs.com/ * * Copyright 2005, 2013 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2013-05-30T21:49Z */ (function( window, undefined ) { // Can't do this because several apps including ASP.NET trace // the stack via arguments.caller.callee and Firefox dies if // you try to trace through "use strict" call chains. (#13335) // Support: Firefox 18+ //"use strict"; var // The deferred used on DOM ready readyList, // A central reference to the root jQuery(document) rootjQuery, // Support: IE<10 // For `typeof xmlNode.method` instead of `xmlNode.method !== undefined` core_strundefined = typeof undefined, // Use the correct document accordingly with window argument (sandbox) location = window.location, document = window.document, docElem = document.documentElement, // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$, // [[Class]] -> type pairs class2type = {}, // List of deleted data cache ids, so we can reuse them core_deletedIds = [], core_version = "1.10.1", // Save a reference to some core methods core_concat = core_deletedIds.concat, core_push = core_deletedIds.push, core_slice = core_deletedIds.slice, core_indexOf = core_deletedIds.indexOf, core_toString = class2type.toString, core_hasOwn = class2type.hasOwnProperty, core_trim = core_version.trim, // Define a local copy of jQuery jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' return new jQuery.fn.init( selector, context, rootjQuery ); }, // Used for matching numbers core_pnum = /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source, // Used for splitting on whitespace core_rnotwhite = /\S+/g, // Make sure we trim BOM and NBSP (here's looking at you, Safari 5.0 and IE) rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, // A simple way to check for HTML strings // Prioritize #id over <tag> to avoid XSS via location.hash (#9521) // Strict HTML recognition (#11290: must start with <) rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/, // Match a standalone tag rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/, // JSON RegExp rvalidchars = /^[\],:{}\s]*$/, rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g, rvalidescape = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g, rvalidtokens = /"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g, // Matches dashed string for camelizing rmsPrefix = /^-ms-/, rdashAlpha = /-([\da-z])/gi, // Used by jQuery.camelCase as callback to replace() fcamelCase = function( all, letter ) { return letter.toUpperCase(); }, // The ready event handler completed = function( event ) { // readyState === "complete" is good enough for us to call the dom ready in oldIE if ( document.addEventListener || event.type === "load" || document.readyState === "complete" ) { detach(); jQuery.ready(); } }, // Clean-up method for dom ready events detach = function() { if ( document.addEventListener ) { document.removeEventListener( "DOMContentLoaded", completed, false ); window.removeEventListener( "load", completed, false ); } else { document.detachEvent( "onreadystatechange", completed ); window.detachEvent( "onload", completed ); } }; jQuery.fn = jQuery.prototype = { // The current version of jQuery being used jquery: core_version, constructor: jQuery, init: function( selector, context, rootjQuery ) { var match, elem; // HANDLE: $(""), $(null), $(undefined), $(false) if ( !selector ) { return this; } // Handle HTML strings if ( typeof selector === "string" ) { if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) { // Assume that strings that start and end with <> are HTML and skip the regex check match = [ null, selector, null ]; } else { match = rquickExpr.exec( selector ); } // Match html or make sure no context is specified for #id if ( match && (match[1] || !context) ) { // HANDLE: $(html) -> $(array) if ( match[1] ) { context = context instanceof jQuery ? context[0] : context; // scripts is true for back-compat jQuery.merge( this, jQuery.parseHTML( match[1], context && context.nodeType ? context.ownerDocument || context : document, true ) ); // HANDLE: $(html, props) if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) { for ( match in context ) { // Properties of context are called as methods if possible if ( jQuery.isFunction( this[ match ] ) ) { this[ match ]( context[ match ] ); // ...and otherwise set as attributes } else { this.attr( match, context[ match ] ); } } } return this; // HANDLE: $(#id) } else { elem = document.getElementById( match[2] ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE and Opera return items // by name instead of ID if ( elem.id !== match[2] ) { return rootjQuery.find( selector ); } // Otherwise, we inject the element directly into the jQuery object this.length = 1; this[0] = elem; } this.context = document; this.selector = selector; return this; } // HANDLE: $(expr, $(...)) } else if ( !context || context.jquery ) { return ( context || rootjQuery ).find( selector ); // HANDLE: $(expr, context) // (which is just equivalent to: $(context).find(expr) } else { return this.constructor( context ).find( selector ); } // HANDLE: $(DOMElement) } else if ( selector.nodeType ) { this.context = this[0] = selector; this.length = 1; return this; // HANDLE: $(function) // Shortcut for document ready } else if ( jQuery.isFunction( selector ) ) { return rootjQuery.ready( selector ); } if ( selector.selector !== undefined ) { this.selector = selector.selector; this.context = selector.context; } return jQuery.makeArray( selector, this ); }, // Start with an empty selector selector: "", // The default length of a jQuery object is 0 length: 0, toArray: function() { return core_slice.call( this ); }, // Get the Nth element in the matched element set OR // Get the whole matched element set as a clean array get: function( num ) { return num == null ? // Return a 'clean' array this.toArray() : // Return just the object ( num < 0 ? this[ this.length + num ] : this[ num ] ); }, // Take an array of elements and push it onto the stack // (returning the new matched element set) pushStack: function( elems ) { // Build a new jQuery matched element set var ret = jQuery.merge( this.constructor(), elems ); // Add the old object onto the stack (as a reference) ret.prevObject = this; ret.context = this.context; // Return the newly-formed element set return ret; }, // Execute a callback for every element in the matched set. // (You can seed the arguments with an array of args, but this is // only used internally.) each: function( callback, args ) { return jQuery.each( this, callback, args ); }, ready: function( fn ) { // Add the callback jQuery.ready.promise().done( fn ); return this; }, slice: function() { return this.pushStack( core_slice.apply( this, arguments ) ); }, first: function() { return this.eq( 0 ); }, last: function() { return this.eq( -1 ); }, eq: function( i ) { var len = this.length, j = +i + ( i < 0 ? len : 0 ); return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] ); }, map: function( callback ) { return this.pushStack( jQuery.map(this, function( elem, i ) { return callback.call( elem, i, elem ); })); }, end: function() { return this.prevObject || this.constructor(null); }, // For internal use only. // Behaves like an Array's method, not like a jQuery method. push: core_push, sort: [].sort, splice: [].splice }; // Give the init function the jQuery prototype for later instantiation jQuery.fn.init.prototype = jQuery.fn; jQuery.extend = jQuery.fn.extend = function() { var src, copyIsArray, copy, name, options, clone, target = arguments[0] || {}, i = 1, length = arguments.length, deep = false; // Handle a deep copy situation if ( typeof target === "boolean" ) { deep = target; target = arguments[1] || {}; // skip the boolean and the target i = 2; } // Handle case when target is a string or something (possible in deep copy) if ( typeof target !== "object" && !jQuery.isFunction(target) ) { target = {}; } // extend jQuery itself if only one argument is passed if ( length === i ) { target = this; --i; } for ( ; i < length; i++ ) { // Only deal with non-null/undefined values if ( (options = arguments[ i ]) != null ) { // Extend the base object for ( name in options ) { src = target[ name ]; copy = options[ name ]; // Prevent never-ending loop if ( target === copy ) { continue; } // Recurse if we're merging plain objects or arrays if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { if ( copyIsArray ) { copyIsArray = false; clone = src && jQuery.isArray(src) ? src : []; } else { clone = src && jQuery.isPlainObject(src) ? src : {}; } // Never move original objects, clone them target[ name ] = jQuery.extend( deep, clone, copy ); // Don't bring in undefined values } else if ( copy !== undefined ) { target[ name ] = copy; } } } } // Return the modified object return target; }; jQuery.extend({ // Unique for each copy of jQuery on the page // Non-digits removed to match rinlinejQuery expando: "jQuery" + ( core_version + Math.random() ).replace( /\D/g, "" ), noConflict: function( deep ) { if ( window.$ === jQuery ) { window.$ = _$; } if ( deep && window.jQuery === jQuery ) { window.jQuery = _jQuery; } return jQuery; }, // Is the DOM ready to be used? Set to true once it occurs. isReady: false, // A counter to track how many items to wait for before // the ready event fires. See #6781 readyWait: 1, // Hold (or release) the ready event holdReady: function( hold ) { if ( hold ) { jQuery.readyWait++; } else { jQuery.ready( true ); } }, // Handle when the DOM is ready ready: function( wait ) { // Abort if there are pending holds or we're already ready if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { return; } // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). if ( !document.body ) { return setTimeout( jQuery.ready ); } // Remember that the DOM is ready jQuery.isReady = true; // If a normal DOM Ready event fired, decrement, and wait if need be if ( wait !== true && --jQuery.readyWait > 0 ) { return; } // If there are functions bound, to execute readyList.resolveWith( document, [ jQuery ] ); // Trigger any bound ready events if ( jQuery.fn.trigger ) { jQuery( document ).trigger("ready").off("ready"); } }, // See test/unit/core.js for details concerning isFunction. // Since version 1.3, DOM methods and functions like alert // aren't supported. They return false on IE (#2968). isFunction: function( obj ) { return jQuery.type(obj) === "function"; }, isArray: Array.isArray || function( obj ) { return jQuery.type(obj) === "array"; }, isWindow: function( obj ) { /* jshint eqeqeq: false */ return obj != null && obj == obj.window; }, isNumeric: function( obj ) { return !isNaN( parseFloat(obj) ) && isFinite( obj ); }, type: function( obj ) { if ( obj == null ) { return String( obj ); } return typeof obj === "object" || typeof obj === "function" ? class2type[ core_toString.call(obj) ] || "object" : typeof obj; }, isPlainObject: function( obj ) { var key; // Must be an Object. // Because of IE, we also have to check the presence of the constructor property. // Make sure that DOM nodes and window objects don't pass through, as well if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { return false; } try { // Not own constructor property must be Object if ( obj.constructor && !core_hasOwn.call(obj, "constructor") && !core_hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) { return false; } } catch ( e ) { // IE8,9 Will throw exceptions on certain host objects #9897 return false; } // Support: IE<9 // Handle iteration over inherited properties before own properties. if ( jQuery.support.ownLast ) { for ( key in obj ) { return core_hasOwn.call( obj, key ); } } // Own properties are enumerated firstly, so to speed up, // if last one is own, then all properties are own. for ( key in obj ) {} return key === undefined || core_hasOwn.call( obj, key ); }, isEmptyObject: function( obj ) { var name; for ( name in obj ) { return false; } return true; }, error: function( msg ) { throw new Error( msg ); }, // data: string of html // context (optional): If specified, the fragment will be created in this context, defaults to document // keepScripts (optional): If true, will include scripts passed in the html string parseHTML: function( data, context, keepScripts ) { if ( !data || typeof data !== "string" ) { return null; } if ( typeof context === "boolean" ) { keepScripts = context; context = false; } context = context || document; var parsed = rsingleTag.exec( data ), scripts = !keepScripts && []; // Single tag if ( parsed ) { return [ context.createElement( parsed[1] ) ]; } parsed = jQuery.buildFragment( [ data ], context, scripts ); if ( scripts ) { jQuery( scripts ).remove(); } return jQuery.merge( [], parsed.childNodes ); }, parseJSON: function( data ) { // Attempt to parse using the native JSON parser first if ( window.JSON && window.JSON.parse ) { return window.JSON.parse( data ); } if ( data === null ) { return data; } if ( typeof data === "string" ) { // Make sure leading/trailing whitespace is removed (IE can't handle it) data = jQuery.trim( data ); if ( data ) { // Make sure the incoming data is actual JSON // Logic borrowed from http://json.org/json2.js if ( rvalidchars.test( data.replace( rvalidescape, "@" ) .replace( rvalidtokens, "]" ) .replace( rvalidbraces, "")) ) { return ( new Function( "return " + data ) )(); } } } jQuery.error( "Invalid JSON: " + data ); }, // Cross-browser xml parsing parseXML: function( data ) { var xml, tmp; if ( !data || typeof data !== "string" ) { return null; } try { if ( window.DOMParser ) { // Standard tmp = new DOMParser(); xml = tmp.parseFromString( data , "text/xml" ); } else { // IE xml = new ActiveXObject( "Microsoft.XMLDOM" ); xml.async = "false"; xml.loadXML( data ); } } catch( e ) { xml = undefined; } if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) { jQuery.error( "Invalid XML: " + data ); } return xml; }, noop: function() {}, // Evaluates a script in a global context // Workarounds based on findings by Jim Driscoll // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context globalEval: function( data ) { if ( data && jQuery.trim( data ) ) { // We use execScript on Internet Explorer // We use an anonymous function so that context is window // rather than jQuery in Firefox ( window.execScript || function( data ) { window[ "eval" ].call( window, data ); } )( data ); } }, // Convert dashed to camelCase; used by the css and data modules // Microsoft forgot to hump their vendor prefix (#9572) camelCase: function( string ) { return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); }, nodeName: function( elem, name ) { return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); }, // args is for internal usage only each: function( obj, callback, args ) { var value, i = 0, length = obj.length, isArray = isArraylike( obj ); if ( args ) { if ( isArray ) { for ( ; i < length; i++ ) { value = callback.apply( obj[ i ], args ); if ( value === false ) { break; } } } else { for ( i in obj ) { value = callback.apply( obj[ i ], args ); if ( value === false ) { break; } } } // A special, fast, case for the most common use of each } else { if ( isArray ) { for ( ; i < length; i++ ) { value = callback.call( obj[ i ], i, obj[ i ] ); if ( value === false ) { break; } } } else { for ( i in obj ) { value = callback.call( obj[ i ], i, obj[ i ] ); if ( value === false ) { break; } } } } return obj; }, // Use native String.trim function wherever possible trim: core_trim && !core_trim.call("\uFEFF\xA0") ? function( text ) { return text == null ? "" : core_trim.call( text ); } : // Otherwise use our own trimming functionality function( text ) { return text == null ? "" : ( text + "" ).replace( rtrim, "" ); }, // results is for internal usage only makeArray: function( arr, results ) { var ret = results || []; if ( arr != null ) { if ( isArraylike( Object(arr) ) ) { jQuery.merge( ret, typeof arr === "string" ? [ arr ] : arr ); } else { core_push.call( ret, arr ); } } return ret; }, inArray: function( elem, arr, i ) { var len; if ( arr ) { if ( core_indexOf ) { return core_indexOf.call( arr, elem, i ); } len = arr.length; i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0; for ( ; i < len; i++ ) { // Skip accessing in sparse arrays if ( i in arr && arr[ i ] === elem ) { return i; } } } return -1; }, merge: function( first, second ) { var l = second.length, i = first.length, j = 0; if ( typeof l === "number" ) { for ( ; j < l; j++ ) { first[ i++ ] = second[ j ]; } } else { while ( second[j] !== undefined ) { first[ i++ ] = second[ j++ ]; } } first.length = i; return first; }, grep: function( elems, callback, inv ) { var retVal, ret = [], i = 0, length = elems.length; inv = !!inv; // Go through the array, only saving the items // that pass the validator function for ( ; i < length; i++ ) { retVal = !!callback( elems[ i ], i ); if ( inv !== retVal ) { ret.push( elems[ i ] ); } } return ret; }, // arg is for internal usage only map: function( elems, callback, arg ) { var value, i = 0, length = elems.length, isArray = isArraylike( elems ), ret = []; // Go through the array, translating each of the items to their if ( isArray ) { for ( ; i < length; i++ ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret[ ret.length ] = value; } } // Go through every key on the object, } else { for ( i in elems ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret[ ret.length ] = value; } } } // Flatten any nested arrays return core_concat.apply( [], ret ); }, // A global GUID counter for objects guid: 1, // Bind a function to a context, optionally partially applying any // arguments. proxy: function( fn, context ) { var args, proxy, tmp; if ( typeof context === "string" ) { tmp = fn[ context ]; context = fn; fn = tmp; } // Quick check to determine if target is callable, in the spec // this throws a TypeError, but we will just return undefined. if ( !jQuery.isFunction( fn ) ) { return undefined; } // Simulated bind args = core_slice.call( arguments, 2 ); proxy = function() { return fn.apply( context || this, args.concat( core_slice.call( arguments ) ) ); }; // Set the guid of unique handler to the same of original handler, so it can be removed proxy.guid = fn.guid = fn.guid || jQuery.guid++; return proxy; }, // Multifunctional method to get and set values of a collection // The value/s can optionally be executed if it's a function access: function( elems, fn, key, value, chainable, emptyGet, raw ) { var i = 0, length = elems.length, bulk = key == null; // Sets many values if ( jQuery.type( key ) === "object" ) { chainable = true; for ( i in key ) { jQuery.access( elems, fn, i, key[i], true, emptyGet, raw ); } // Sets one value } else if ( value !== undefined ) { chainable = true; if ( !jQuery.isFunction( value ) ) { raw = true; } if ( bulk ) { // Bulk operations run against the entire set if ( raw ) { fn.call( elems, value ); fn = null; // ...except when executing function values } else { bulk = fn; fn = function( elem, key, value ) { return bulk.call( jQuery( elem ), value ); }; } } if ( fn ) { for ( ; i < length; i++ ) { fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) ); } } } return chainable ? elems : // Gets bulk ? fn.call( elems ) : length ? fn( elems[0], key ) : emptyGet; }, now: function() { return ( new Date() ).getTime(); }, // A method for quickly swapping in/out CSS properties to get correct calculations. // Note: this method belongs to the css module but it's needed here for the support module. // If support gets modularized, this method should be moved back to the css module. swap: function( elem, options, callback, args ) { var ret, name, old = {}; // Remember the old values, and insert the new ones for ( name in options ) { old[ name ] = elem.style[ name ]; elem.style[ name ] = options[ name ]; } ret = callback.apply( elem, args || [] ); // Revert the old values for ( name in options ) { elem.style[ name ] = old[ name ]; } return ret; } }); jQuery.ready.promise = function( obj ) { if ( !readyList ) { readyList = jQuery.Deferred(); // Catch cases where $(document).ready() is called after the browser event has already occurred. // we once tried to use readyState "interactive" here, but it caused issues like the one // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15 if ( document.readyState === "complete" ) { // Handle it asynchronously to allow scripts the opportunity to delay ready setTimeout( jQuery.ready ); // Standards-based browsers support DOMContentLoaded } else if ( document.addEventListener ) { // Use the handy event callback document.addEventListener( "DOMContentLoaded", completed, false ); // A fallback to window.onload, that will always work window.addEventListener( "load", completed, false ); // If IE event model is used } else { // Ensure firing before onload, maybe late but safe also for iframes document.attachEvent( "onreadystatechange", completed ); // A fallback to window.onload, that will always work window.attachEvent( "onload", completed ); // If IE and not a frame // continually check to see if the document is ready var top = false; try { top = window.frameElement == null && document.documentElement; } catch(e) {} if ( top && top.doScroll ) { (function doScrollCheck() { if ( !jQuery.isReady ) { try { // Use the trick by Diego Perini // http://javascript.nwbox.com/IEContentLoaded/ top.doScroll("left"); } catch(e) { return setTimeout( doScrollCheck, 50 ); } // detach all dom ready events detach(); // and execute any waiting functions jQuery.ready(); } })(); } } } return readyList.promise( obj ); }; // Populate the class2type map jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); }); function isArraylike( obj ) { var length = obj.length, type = jQuery.type( obj ); if ( jQuery.isWindow( obj ) ) { return false; } if ( obj.nodeType === 1 && length ) { return true; } return type === "array" || type !== "function" && ( length === 0 || typeof length === "number" && length > 0 && ( length - 1 ) in obj ); } // All jQuery objects should point back to these rootjQuery = jQuery(document); /*! * Sizzle CSS Selector Engine v1.9.4-pre * http://sizzlejs.com/ * * Copyright 2013 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2013-05-27 */ (function( window, undefined ) { var i, support, cachedruns, Expr, getText, isXML, compile, outermostContext, sortInput, // Local document vars setDocument, document, docElem, documentIsHTML, rbuggyQSA, rbuggyMatches, matches, contains, // Instance-specific data expando = "sizzle" + -(new Date()), preferredDoc = window.document, dirruns = 0, done = 0, classCache = createCache(), tokenCache = createCache(), compilerCache = createCache(), hasDuplicate = false, sortOrder = function() { return 0; }, // General-purpose constants strundefined = typeof undefined, MAX_NEGATIVE = 1 << 31, // Instance methods hasOwn = ({}).hasOwnProperty, arr = [], pop = arr.pop, push_native = arr.push, push = arr.push, slice = arr.slice, // Use a stripped-down indexOf if we can't use a native one indexOf = arr.indexOf || function( elem ) { var i = 0, len = this.length; for ( ; i < len; i++ ) { if ( this[i] === elem ) { return i; } } return -1; }, booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped", // Regular expressions // Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace whitespace = "[\\x20\\t\\r\\n\\f]", // http://www.w3.org/TR/css3-syntax/#characters characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+", // Loosely modeled on CSS identifier characters // An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors // Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier identifier = characterEncoding.replace( "w", "w#" ), // Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace + "*(?:([*^$|!~]?=)" + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]", // Prefer arguments quoted, // then not containing pseudos/brackets, // then attribute selectors/non-parenthetical expressions, // then anything else // These preferences are here to reduce the number of selectors // needing tokenize in the PSEUDO preFilter pseudos = ":(" + characterEncoding + ")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|" + attributes.replace( 3, 8 ) + ")*)|.*)\\)|)", // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ), rsibling = new RegExp( whitespace + "*[+~]" ), rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*)" + whitespace + "*\\]", "g" ), rpseudo = new RegExp( pseudos ), ridentifier = new RegExp( "^" + identifier + "$" ), matchExpr = { "ID": new RegExp( "^#(" + characterEncoding + ")" ), "CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ), "TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ), "ATTR": new RegExp( "^" + attributes ), "PSEUDO": new RegExp( "^" + pseudos ), "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), "bool": new RegExp( "^(?:" + booleans + ")$", "i" ), // For use in libraries implementing .is() // We use this for POS matching in `select` "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) }, rnative = /^[^{]+\{\s*\[native \w/, // Easily-parseable/retrievable ID or TAG or CLASS selectors rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, rinputs = /^(?:input|select|textarea|button)$/i, rheader = /^h\d$/i, rescape = /'|\\/g, // CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ), funescape = function( _, escaped, escapedWhitespace ) { var high = "0x" + escaped - 0x10000; // NaN means non-codepoint // Support: Firefox // Workaround erroneous numeric interpretation of +"0x" return high !== high || escapedWhitespace ? escaped : // BMP codepoint high < 0 ? String.fromCharCode( high + 0x10000 ) : // Supplemental Plane codepoint (surrogate pair) String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); }; // Optimize for push.apply( _, NodeList ) try { push.apply( (arr = slice.call( preferredDoc.childNodes )), preferredDoc.childNodes ); // Support: Android<4.0 // Detect silently failing push.apply arr[ preferredDoc.childNodes.length ].nodeType; } catch ( e ) { push = { apply: arr.length ? // Leverage slice if possible function( target, els ) { push_native.apply( target, slice.call(els) ); } : // Support: IE<9 // Otherwise append directly function( target, els ) { var j = target.length, i = 0; // Can't trust NodeList.length while ( (target[j++] = els[i++]) ) {} target.length = j - 1; } }; } function Sizzle( selector, context, results, seed ) { var match, elem, m, nodeType, // QSA vars i, groups, old, nid, newContext, newSelector; if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) { setDocument( context ); } context = context || document; results = results || []; if ( !selector || typeof selector !== "string" ) { return results; } if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) { return []; } if ( documentIsHTML && !seed ) { // Shortcuts if ( (match = rquickExpr.exec( selector )) ) { // Speed-up: Sizzle("#ID") if ( (m = match[1]) ) { if ( nodeType === 9 ) { elem = context.getElementById( m ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE, Opera, and Webkit return items // by name instead of ID if ( elem.id === m ) { results.push( elem ); return results; } } else { return results; } } else { // Context is not a document if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) && contains( context, elem ) && elem.id === m ) { results.push( elem ); return results; } } // Speed-up: Sizzle("TAG") } else if ( match[2] ) { push.apply( results, context.getElementsByTagName( selector ) ); return results; // Speed-up: Sizzle(".CLASS") } else if ( (m = match[3]) && support.getElementsByClassName && context.getElementsByClassName ) { push.apply( results, context.getElementsByClassName( m ) ); return results; } } // QSA path if ( support.qsa && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) { nid = old = expando; newContext = context; newSelector = nodeType === 9 && selector; // qSA works strangely on Element-rooted queries // We can work around this by specifying an extra ID on the root // and working up from there (Thanks to Andrew Dupont for the technique) // IE 8 doesn't work on object elements if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { groups = tokenize( selector ); if ( (old = context.getAttribute("id")) ) { nid = old.replace( rescape, "\\$&" ); } else { context.setAttribute( "id", nid ); } nid = "[id='" + nid + "'] "; i = groups.length; while ( i-- ) { groups[i] = nid + toSelector( groups[i] ); } newContext = rsibling.test( selector ) && context.parentNode || context; newSelector = groups.join(","); } if ( newSelector ) { try { push.apply( results, newContext.querySelectorAll( newSelector ) ); return results; } catch(qsaError) { } finally { if ( !old ) { context.removeAttribute("id"); } } } } } // All others return select( selector.replace( rtrim, "$1" ), context, results, seed ); } /** * For feature detection * @param {Function} fn The function to test for native support */ function isNative( fn ) { return rnative.test( fn + "" ); } /** * Create key-value caches of limited size * @returns {Function(string, Object)} Returns the Object data after storing it on itself with * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) * deleting the oldest entry */ function createCache() { var keys = []; function cache( key, value ) { // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) if ( keys.push( key += " " ) > Expr.cacheLength ) { // Only keep the most recent entries delete cache[ keys.shift() ]; } return (cache[ key ] = value); } return cache; } /** * Mark a function for special use by Sizzle * @param {Function} fn The function to mark */ function markFunction( fn ) { fn[ expando ] = true; return fn; } /** * Support testing using an element * @param {Function} fn Passed the created div and expects a boolean result */ function assert( fn ) { var div = document.createElement("div"); try { return !!fn( div ); } catch (e) { return false; } finally { // Remove from its parent by default if ( div.parentNode ) { div.parentNode.removeChild( div ); } // release memory in IE div = null; } } /** * Adds the same handler for all of the specified attrs * @param {String} attrs Pipe-separated list of attributes * @param {Function} handler The method that will be applied if the test fails * @param {Boolean} test The result of a test. If true, null will be set as the handler in leiu of the specified handler */ function addHandle( attrs, handler, test ) { attrs = attrs.split("|"); var current, i = attrs.length, setHandle = test ? null : handler; while ( i-- ) { // Don't override a user's handler if ( !(current = Expr.attrHandle[ attrs[i] ]) || current === handler ) { Expr.attrHandle[ attrs[i] ] = setHandle; } } } /** * Fetches boolean attributes by node * @param {Element} elem * @param {String} name */ function boolHandler( elem, name ) { // XML does not need to be checked as this will not be assigned for XML documents var val = elem.getAttributeNode( name ); return val && val.specified ? val.value : elem[ name ] === true ? name.toLowerCase() : null; } /** * Fetches attributes without interpolation * http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx * @param {Element} elem * @param {String} name */ function interpolationHandler( elem, name ) { // XML does not need to be checked as this will not be assigned for XML documents return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 ); } /** * Uses defaultValue to retrieve value in IE6/7 * @param {Element} elem * @param {String} name */ function valueHandler( elem ) { // Ignore the value *property* on inputs by using defaultValue // Fallback to Sizzle.attr by returning undefined where appropriate // XML does not need to be checked as this will not be assigned for XML documents if ( elem.nodeName.toLowerCase() === "input" ) { return elem.defaultValue; } } /** * Checks document order of two siblings * @param {Element} a * @param {Element} b * @returns Returns -1 if a precedes b, 1 if a follows b */ function siblingCheck( a, b ) { var cur = b && a, diff = cur && a.nodeType === 1 && b.nodeType === 1 && ( ~b.sourceIndex || MAX_NEGATIVE ) - ( ~a.sourceIndex || MAX_NEGATIVE ); // Use IE sourceIndex if available on both nodes if ( diff ) { return diff; } // Check if b follows a if ( cur ) { while ( (cur = cur.nextSibling) ) { if ( cur === b ) { return -1; } } } return a ? 1 : -1; } /** * Returns a function to use in pseudos for input types * @param {String} type */ function createInputPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === type; }; } /** * Returns a function to use in pseudos for buttons * @param {String} type */ function createButtonPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && elem.type === type; }; } /** * Returns a function to use in pseudos for positionals * @param {Function} fn */ function createPositionalPseudo( fn ) { return markFunction(function( argument ) { argument = +argument; return markFunction(function( seed, matches ) { var j, matchIndexes = fn( [], seed.length, argument ), i = matchIndexes.length; // Match elements found at the specified indexes while ( i-- ) { if ( seed[ (j = matchIndexes[i]) ] ) { seed[j] = !(matches[j] = seed[j]); } } }); }); } /** * Detect xml * @param {Element|Object} elem An element or a document */ isXML = Sizzle.isXML = function( elem ) { // documentElement is verified for cases where it doesn't yet exist // (such as loading iframes in IE - #4833) var documentElement = elem && (elem.ownerDocument || elem).documentElement; return documentElement ? documentElement.nodeName !== "HTML" : false; }; // Expose support vars for convenience support = Sizzle.support = {}; /** * Sets document-related variables once based on the current document * @param {Element|Object} [doc] An element or document object to use to set the document * @returns {Object} Returns the current document */ setDocument = Sizzle.setDocument = function( node ) { var doc = node ? node.ownerDocument || node : preferredDoc, parent = doc.parentWindow; // If no document and documentElement is available, return if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) { return document; } // Set our document document = doc; docElem = doc.documentElement; // Support tests documentIsHTML = !isXML( doc ); // Support: IE>8 // If iframe document is assigned to "document" variable and if iframe has been reloaded, // IE will throw "permission denied" error when accessing "document" variable, see jQuery #13936 if ( parent && parent.frameElement ) { parent.attachEvent( "onbeforeunload", function() { setDocument(); }); } /* Attributes ---------------------------------------------------------------------- */ // Support: IE<8 // Verify that getAttribute really returns attributes and not properties (excepting IE8 booleans) support.attributes = assert(function( div ) { // Support: IE<8 // Prevent attribute/property "interpolation" div.innerHTML = "<a href='#'></a>"; addHandle( "type|href|height|width", interpolationHandler, div.firstChild.getAttribute("href") === "#" ); // Support: IE<9 // Use getAttributeNode to fetch booleans when getAttribute lies addHandle( booleans, boolHandler, div.getAttribute("disabled") == null ); div.className = "i"; return !div.getAttribute("className"); }); // Support: IE<9 // Retrieving value should defer to defaultValue support.input = assert(function( div ) { div.innerHTML = "<input>"; div.firstChild.setAttribute( "value", "" ); return div.firstChild.getAttribute( "value" ) === ""; }); // IE6/7 still return empty string for value, // but are actually retrieving the property addHandle( "value", valueHandler, support.attributes && support.input ); /* getElement(s)By* ---------------------------------------------------------------------- */ // Check if getElementsByTagName("*") returns only elements support.getElementsByTagName = assert(function( div ) { div.appendChild( doc.createComment("") ); return !div.getElementsByTagName("*").length; }); // Check if getElementsByClassName can be trusted support.getElementsByClassName = assert(function( div ) { div.innerHTML = "<div class='a'></div><div class='a i'></div>"; // Support: Safari<4 // Catch class over-caching div.firstChild.className = "i"; // Support: Opera<10 // Catch gEBCN failure to find non-leading classes return div.getElementsByClassName("i").length === 2; }); // Support: IE<10 // Check if getElementById returns elements by name // The broken getElementById methods don't pick up programatically-set names, // so use a roundabout getElementsByName test support.getById = assert(function( div ) { docElem.appendChild( div ).id = expando; return !doc.getElementsByName || !doc.getElementsByName( expando ).length; }); // ID find and filter if ( support.getById ) { Expr.find["ID"] = function( id, context ) { if ( typeof context.getElementById !== strundefined && documentIsHTML ) { var m = context.getElementById( id ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 return m && m.parentNode ? [m] : []; } }; Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { return elem.getAttribute("id") === attrId; }; }; } else { // Support: IE6/7 // getElementById is not reliable as a find shortcut delete Expr.find["ID"]; Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id"); return node && node.value === attrId; }; }; } // Tag Expr.find["TAG"] = support.getElementsByTagName ? function( tag, context ) { if ( typeof context.getElementsByTagName !== strundefined ) { return context.getElementsByTagName( tag ); } } : function( tag, context ) { var elem, tmp = [], i = 0, results = context.getElementsByTagName( tag ); // Filter out possible comments if ( tag === "*" ) { while ( (elem = results[i++]) ) { if ( elem.nodeType === 1 ) { tmp.push( elem ); } } return tmp; } return results; }; // Class Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) { if ( typeof context.getElementsByClassName !== strundefined && documentIsHTML ) { return context.getElementsByClassName( className ); } }; /* QSA/matchesSelector ---------------------------------------------------------------------- */ // QSA and matchesSelector support // matchesSelector(:active) reports false when true (IE9/Opera 11.5) rbuggyMatches = []; // qSa(:focus) reports false when true (Chrome 21) // We allow this because of a bug in IE8/9 that throws an error // whenever `document.activeElement` is accessed on an iframe // So, we allow :focus to pass through QSA all the time to avoid the IE error // See http://bugs.jquery.com/ticket/13378 rbuggyQSA = []; if ( (support.qsa = isNative(doc.querySelectorAll)) ) { // Build QSA regex // Regex strategy adopted from Diego Perini assert(function( div ) { // Select is set to empty string on purpose // This is to test IE's treatment of not explicitly // setting a boolean content attribute, // since its presence should be enough // http://bugs.jquery.com/ticket/12359 div.innerHTML = "<select><option selected=''></option></select>"; // Support: IE8 // Boolean attributes and "value" are not treated correctly if ( !div.querySelectorAll("[selected]").length ) { rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" ); } // Webkit/Opera - :checked should return selected option elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked // IE8 throws error here and will not see later tests if ( !div.querySelectorAll(":checked").length ) { rbuggyQSA.push(":checked"); } }); assert(function( div ) { // Support: Opera 10-12/IE8 // ^= $= *= and empty values // Should not select anything // Support: Windows 8 Native Apps // The type attribute is restricted during .innerHTML assignment var input = doc.createElement("input"); input.setAttribute( "type", "hidden" ); div.appendChild( input ).setAttribute( "t", "" ); if ( div.querySelectorAll("[t^='']").length ) { rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" ); } // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) // IE8 throws error here and will not see later tests if ( !div.querySelectorAll(":enabled").length ) { rbuggyQSA.push( ":enabled", ":disabled" ); } // Opera 10-11 does not throw on post-comma invalid pseudos div.querySelectorAll("*,:x"); rbuggyQSA.push(",.*:"); }); } if ( (support.matchesSelector = isNative( (matches = docElem.webkitMatchesSelector || docElem.mozMatchesSelector || docElem.oMatchesSelector || docElem.msMatchesSelector) )) ) { assert(function( div ) { // Check to see if it's possible to do matchesSelector // on a disconnected node (IE 9) support.disconnectedMatch = matches.call( div, "div" ); // This should fail with an exception // Gecko does not error, returns false instead matches.call( div, "[s!='']:x" ); rbuggyMatches.push( "!=", pseudos ); }); } rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") ); rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") ); /* Contains ---------------------------------------------------------------------- */ // Element contains another // Purposefully does not implement inclusive descendent // As in, an element does not contain itself contains = isNative(docElem.contains) || docElem.compareDocumentPosition ? function( a, b ) { var adown = a.nodeType === 9 ? a.documentElement : a, bup = b && b.parentNode; return a === bup || !!( bup && bup.nodeType === 1 && ( adown.contains ? adown.contains( bup ) : a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 )); } : function( a, b ) { if ( b ) { while ( (b = b.parentNode) ) { if ( b === a ) { return true; } } } return false; }; /* Sorting ---------------------------------------------------------------------- */ // Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27) // Detached nodes confoundingly follow *each other* support.sortDetached = assert(function( div1 ) { // Should return 1, but returns 4 (following) return div1.compareDocumentPosition( doc.createElement("div") ) & 1; }); // Document order sorting sortOrder = docElem.compareDocumentPosition ? function( a, b ) { // Flag for duplicate removal if ( a === b ) { hasDuplicate = true; return 0; } var compare = b.compareDocumentPosition && a.compareDocumentPosition && a.compareDocumentPosition( b ); if ( compare ) { // Disconnected nodes if ( compare & 1 || (!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) { // Choose the first element that is related to our preferred document if ( a === doc || contains(preferredDoc, a) ) { return -1; } if ( b === doc || contains(preferredDoc, b) ) { return 1; } // Maintain original order return sortInput ? ( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) : 0; } return compare & 4 ? -1 : 1; } // Not directly comparable, sort on existence of method return a.compareDocumentPosition ? -1 : 1; } : function( a, b ) { var cur, i = 0, aup = a.parentNode, bup = b.parentNode, ap = [ a ], bp = [ b ]; // Exit early if the nodes are identical if ( a === b ) { hasDuplicate = true; return 0; // Parentless nodes are either documents or disconnected } else if ( !aup || !bup ) { return a === doc ? -1 : b === doc ? 1 : aup ? -1 : bup ? 1 : sortInput ? ( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) : 0; // If the nodes are siblings, we can do a quick check } else if ( aup === bup ) { return siblingCheck( a, b ); } // Otherwise we need full lists of their ancestors for comparison cur = a; while ( (cur = cur.parentNode) ) { ap.unshift( cur ); } cur = b; while ( (cur = cur.parentNode) ) { bp.unshift( cur ); } // Walk down the tree looking for a discrepancy while ( ap[i] === bp[i] ) { i++; } return i ? // Do a sibling check if the nodes have a common ancestor siblingCheck( ap[i], bp[i] ) : // Otherwise nodes in our document sort first ap[i] === preferredDoc ? -1 : bp[i] === preferredDoc ? 1 : 0; }; return doc; }; Sizzle.matches = function( expr, elements ) { return Sizzle( expr, null, null, elements ); }; Sizzle.matchesSelector = function( elem, expr ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } // Make sure that attribute selectors are quoted expr = expr.replace( rattributeQuotes, "='$1']" ); if ( support.matchesSelector && documentIsHTML && ( !rbuggyMatches || !rbuggyMatches.test( expr ) ) && ( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) { try { var ret = matches.call( elem, expr ); // IE 9's matchesSelector returns false on disconnected nodes if ( ret || support.disconnectedMatch || // As well, disconnected nodes are said to be in a document // fragment in IE 9 elem.document && elem.document.nodeType !== 11 ) { return ret; } } catch(e) {} } return Sizzle( expr, document, null, [elem] ).length > 0; }; Sizzle.contains = function( context, elem ) { // Set document vars if needed if ( ( context.ownerDocument || context ) !== document ) { setDocument( context ); } return contains( context, elem ); }; Sizzle.attr = function( elem, name ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } var fn = Expr.attrHandle[ name.toLowerCase() ], // Don't get fooled by Object.prototype properties (jQuery #13807) val = ( fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ? fn( elem, name, !documentIsHTML ) : undefined ); return val === undefined ? support.attributes || !documentIsHTML ? elem.getAttribute( name ) : (val = elem.getAttributeNode(name)) && val.specified ? val.value : null : val; }; Sizzle.error = function( msg ) { throw new Error( "Syntax error, unrecognized expression: " + msg ); }; /** * Document sorting and removing duplicates * @param {ArrayLike} results */ Sizzle.uniqueSort = function( results ) { var elem, duplicates = [], j = 0, i = 0; // Unless we *know* we can detect duplicates, assume their presence hasDuplicate = !support.detectDuplicates; sortInput = !support.sortStable && results.slice( 0 ); results.sort( sortOrder ); if ( hasDuplicate ) { while ( (elem = results[i++]) ) { if ( elem === results[ i ] ) { j = duplicates.push( i ); } } while ( j-- ) { results.splice( duplicates[ j ], 1 ); } } return results; }; /** * Utility function for retrieving the text value of an array of DOM nodes * @param {Array|Element} elem */ getText = Sizzle.getText = function( elem ) { var node, ret = "", i = 0, nodeType = elem.nodeType; if ( !nodeType ) { // If no nodeType, this is expected to be an array for ( ; (node = elem[i]); i++ ) { // Do not traverse comment nodes ret += getText( node ); } } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { // Use textContent for elements // innerText usage removed for consistency of new lines (see #11153) if ( typeof elem.textContent === "string" ) { return elem.textContent; } else { // Traverse its children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { ret += getText( elem ); } } } else if ( nodeType === 3 || nodeType === 4 ) { return elem.nodeValue; } // Do not include comment or processing instruction nodes return ret; }; Expr = Sizzle.selectors = { // Can be adjusted by the user cacheLength: 50, createPseudo: markFunction, match: matchExpr, attrHandle: {}, find: {}, relative: { ">": { dir: "parentNode", first: true }, " ": { dir: "parentNode" }, "+": { dir: "previousSibling", first: true }, "~": { dir: "previousSibling" } }, preFilter: { "ATTR": function( match ) { match[1] = match[1].replace( runescape, funescape ); // Move the given value to match[3] whether quoted or unquoted match[3] = ( match[4] || match[5] || "" ).replace( runescape, funescape ); if ( match[2] === "~=" ) { match[3] = " " + match[3] + " "; } return match.slice( 0, 4 ); }, "CHILD": function( match ) { /* matches from matchExpr["CHILD"] 1 type (only|nth|...) 2 what (child|of-type) 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) 4 xn-component of xn+y argument ([+-]?\d*n|) 5 sign of xn-component 6 x of xn-component 7 sign of y-component 8 y of y-component */ match[1] = match[1].toLowerCase(); if ( match[1].slice( 0, 3 ) === "nth" ) { // nth-* requires argument if ( !match[3] ) { Sizzle.error( match[0] ); } // numeric x and y parameters for Expr.filter.CHILD // remember that false/true cast respectively to 0/1 match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) ); match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" ); // other types prohibit arguments } else if ( match[3] ) { Sizzle.error( match[0] ); } return match; }, "PSEUDO": function( match ) { var excess, unquoted = !match[5] && match[2]; if ( matchExpr["CHILD"].test( match[0] ) ) { return null; } // Accept quoted arguments as-is if ( match[3] && match[4] !== undefined ) { match[2] = match[4]; // Strip excess characters from unquoted arguments } else if ( unquoted && rpseudo.test( unquoted ) && // Get excess from tokenize (recursively) (excess = tokenize( unquoted, true )) && // advance to the next closing parenthesis (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) { // excess is a negative index match[0] = match[0].slice( 0, excess ); match[2] = unquoted.slice( 0, excess ); } // Return only captures needed by the pseudo filter method (type and argument) return match.slice( 0, 3 ); } }, filter: { "TAG": function( nodeNameSelector ) { var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase(); return nodeNameSelector === "*" ? function() { return true; } : function( elem ) { return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; }; }, "CLASS": function( className ) { var pattern = classCache[ className + " " ]; return pattern || (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) && classCache( className, function( elem ) { return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== strundefined && elem.getAttribute("class") || "" ); }); }, "ATTR": function( name, operator, check ) { return function( elem ) { var result = Sizzle.attr( elem, name ); if ( result == null ) { return operator === "!="; } if ( !operator ) { return true; } result += ""; return operator === "=" ? result === check : operator === "!=" ? result !== check : operator === "^=" ? check && result.indexOf( check ) === 0 : operator === "*=" ? check && result.indexOf( check ) > -1 : operator === "$=" ? check && result.slice( -check.length ) === check : operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 : operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" : false; }; }, "CHILD": function( type, what, argument, first, last ) { var simple = type.slice( 0, 3 ) !== "nth", forward = type.slice( -4 ) !== "last", ofType = what === "of-type"; return first === 1 && last === 0 ? // Shortcut for :nth-*(n) function( elem ) { return !!elem.parentNode; } : function( elem, context, xml ) { var cache, outerCache, node, diff, nodeIndex, start, dir = simple !== forward ? "nextSibling" : "previousSibling", parent = elem.parentNode, name = ofType && elem.nodeName.toLowerCase(), useCache = !xml && !ofType; if ( parent ) { // :(first|last|only)-(child|of-type) if ( simple ) { while ( dir ) { node = elem; while ( (node = node[ dir ]) ) { if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) { return false; } } // Reverse direction for :only-* (if we haven't yet done so) start = dir = type === "only" && !start && "nextSibling"; } return true; } start = [ forward ? parent.firstChild : parent.lastChild ]; // non-xml :nth-child(...) stores cache data on `parent` if ( forward && useCache ) { // Seek `elem` from a previously-cached index outerCache = parent[ expando ] || (parent[ expando ] = {}); cache = outerCache[ type ] || []; nodeIndex = cache[0] === dirruns && cache[1]; diff = cache[0] === dirruns && cache[2]; node = nodeIndex && parent.childNodes[ nodeIndex ]; while ( (node = ++nodeIndex && node && node[ dir ] || // Fallback to seeking `elem` from the start (diff = nodeIndex = 0) || start.pop()) ) { // When found, cache indexes on `parent` and break if ( node.nodeType === 1 && ++diff && node === elem ) { outerCache[ type ] = [ dirruns, nodeIndex, diff ]; break; } } // Use previously-cached element index if available } else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) { diff = cache[1]; // xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...) } else { // Use the same loop as above to seek `elem` from the start while ( (node = ++nodeIndex && node && node[ dir ] || (diff = nodeIndex = 0) || start.pop()) ) { if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) { // Cache the index of each encountered element if ( useCache ) { (node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ]; } if ( node === elem ) { break; } } } } // Incorporate the offset, then check against cycle size diff -= last; return diff === first || ( diff % first === 0 && diff / first >= 0 ); } }; }, "PSEUDO": function( pseudo, argument ) { // pseudo-class names are case-insensitive // http://www.w3.org/TR/selectors/#pseudo-classes // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters // Remember that setFilters inherits from pseudos var args, fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || Sizzle.error( "unsupported pseudo: " + pseudo ); // The user may use createPseudo to indicate that // arguments are needed to create the filter function // just as Sizzle does if ( fn[ expando ] ) { return fn( argument ); } // But maintain support for old signatures if ( fn.length > 1 ) { args = [ pseudo, pseudo, "", argument ]; return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? markFunction(function( seed, matches ) { var idx, matched = fn( seed, argument ), i = matched.length; while ( i-- ) { idx = indexOf.call( seed, matched[i] ); seed[ idx ] = !( matches[ idx ] = matched[i] ); } }) : function( elem ) { return fn( elem, 0, args ); }; } return fn; } }, pseudos: { // Potentially complex pseudos "not": markFunction(function( selector ) { // Trim the selector passed to compile // to avoid treating leading and trailing // spaces as combinators var input = [], results = [], matcher = compile( selector.replace( rtrim, "$1" ) ); return matcher[ expando ] ? markFunction(function( seed, matches, context, xml ) { var elem, unmatched = matcher( seed, null, xml, [] ), i = seed.length; // Match elements unmatched by `matcher` while ( i-- ) { if ( (elem = unmatched[i]) ) { seed[i] = !(matches[i] = elem); } } }) : function( elem, context, xml ) { input[0] = elem; matcher( input, null, xml, results ); return !results.pop(); }; }), "has": markFunction(function( selector ) { return function( elem ) { return Sizzle( selector, elem ).length > 0; }; }), "contains": markFunction(function( text ) { return function( elem ) { return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; }; }), // "Whether an element is represented by a :lang() selector // is based solely on the element's language value // being equal to the identifier C, // or beginning with the identifier C immediately followed by "-". // The matching of C against the element's language value is performed case-insensitively. // The identifier C does not have to be a valid language name." // http://www.w3.org/TR/selectors/#lang-pseudo "lang": markFunction( function( lang ) { // lang value must be a valid identifier if ( !ridentifier.test(lang || "") ) { Sizzle.error( "unsupported lang: " + lang ); } lang = lang.replace( runescape, funescape ).toLowerCase(); return function( elem ) { var elemLang; do { if ( (elemLang = documentIsHTML ? elem.lang : elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) { elemLang = elemLang.toLowerCase(); return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; } } while ( (elem = elem.parentNode) && elem.nodeType === 1 ); return false; }; }), // Miscellaneous "target": function( elem ) { var hash = window.location && window.location.hash; return hash && hash.slice( 1 ) === elem.id; }, "root": function( elem ) { return elem === docElem; }, "focus": function( elem ) { return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex); }, // Boolean properties "enabled": function( elem ) { return elem.disabled === false; }, "disabled": function( elem ) { return elem.disabled === true; }, "checked": function( elem ) { // In CSS3, :checked should return both checked and selected elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked var nodeName = elem.nodeName.toLowerCase(); return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); }, "selected": function( elem ) { // Accessing this property makes selected-by-default // options in Safari work properly if ( elem.parentNode ) { elem.parentNode.selectedIndex; } return elem.selected === true; }, // Contents "empty": function( elem ) { // http://www.w3.org/TR/selectors/#empty-pseudo // :empty is only affected by element nodes and content nodes(including text(3), cdata(4)), // not comment, processing instructions, or others // Thanks to Diego Perini for the nodeName shortcut // Greater than "@" means alpha characters (specifically not starting with "#" or "?") for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { if ( elem.nodeName > "@" || elem.nodeType === 3 || elem.nodeType === 4 ) { return false; } } return true; }, "parent": function( elem ) { return !Expr.pseudos["empty"]( elem ); }, // Element/input types "header": function( elem ) { return rheader.test( elem.nodeName ); }, "input": function( elem ) { return rinputs.test( elem.nodeName ); }, "button": function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === "button" || name === "button"; }, "text": function( elem ) { var attr; // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc) // use getAttribute instead to test this case return elem.nodeName.toLowerCase() === "input" && elem.type === "text" && ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === elem.type ); }, // Position-in-collection "first": createPositionalPseudo(function() { return [ 0 ]; }), "last": createPositionalPseudo(function( matchIndexes, length ) { return [ length - 1 ]; }), "eq": createPositionalPseudo(function( matchIndexes, length, argument ) { return [ argument < 0 ? argument + length : argument ]; }), "even": createPositionalPseudo(function( matchIndexes, length ) { var i = 0; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "odd": createPositionalPseudo(function( matchIndexes, length ) { var i = 1; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "lt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; --i >= 0; ) { matchIndexes.push( i ); } return matchIndexes; }), "gt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; ++i < length; ) { matchIndexes.push( i ); } return matchIndexes; }) } }; // Add button/input type pseudos for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) { Expr.pseudos[ i ] = createInputPseudo( i ); } for ( i in { submit: true, reset: true } ) { Expr.pseudos[ i ] = createButtonPseudo( i ); } function tokenize( selector, parseOnly ) { var matched, match, tokens, type, soFar, groups, preFilters, cached = tokenCache[ selector + " " ]; if ( cached ) { return parseOnly ? 0 : cached.slice( 0 ); } soFar = selector; groups = []; preFilters = Expr.preFilter; while ( soFar ) { // Comma and first run if ( !matched || (match = rcomma.exec( soFar )) ) { if ( match ) { // Don't consume trailing commas as valid soFar = soFar.slice( match[0].length ) || soFar; } groups.push( tokens = [] ); } matched = false; // Combinators if ( (match = rcombinators.exec( soFar )) ) { matched = match.shift(); tokens.push({ value: matched, // Cast descendant combinators to space type: match[0].replace( rtrim, " " ) }); soFar = soFar.slice( matched.length ); } // Filters for ( type in Expr.filter ) { if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || (match = preFilters[ type ]( match ))) ) { matched = match.shift(); tokens.push({ value: matched, type: type, matches: match }); soFar = soFar.slice( matched.length ); } } if ( !matched ) { break; } } // Return the length of the invalid excess // if we're just parsing // Otherwise, throw an error or return tokens return parseOnly ? soFar.length : soFar ? Sizzle.error( selector ) : // Cache the tokens tokenCache( selector, groups ).slice( 0 ); } function toSelector( tokens ) { var i = 0, len = tokens.length, selector = ""; for ( ; i < len; i++ ) { selector += tokens[i].value; } return selector; } function addCombinator( matcher, combinator, base ) { var dir = combinator.dir, checkNonElements = base && dir === "parentNode", doneName = done++; return combinator.first ? // Check against closest ancestor/preceding element function( elem, context, xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { return matcher( elem, context, xml ); } } } : // Check against all ancestor/preceding elements function( elem, context, xml ) { var data, cache, outerCache, dirkey = dirruns + " " + doneName; // We can't set arbitrary data on XML nodes, so they don't benefit from dir caching if ( xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { if ( matcher( elem, context, xml ) ) { return true; } } } } else { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { outerCache = elem[ expando ] || (elem[ expando ] = {}); if ( (cache = outerCache[ dir ]) && cache[0] === dirkey ) { if ( (data = cache[1]) === true || data === cachedruns ) { return data === true; } } else { cache = outerCache[ dir ] = [ dirkey ]; cache[1] = matcher( elem, context, xml ) || cachedruns; if ( cache[1] === true ) { return true; } } } } } }; } function elementMatcher( matchers ) { return matchers.length > 1 ? function( elem, context, xml ) { var i = matchers.length; while ( i-- ) { if ( !matchers[i]( elem, context, xml ) ) { return false; } } return true; } : matchers[0]; } function condense( unmatched, map, filter, context, xml ) { var elem, newUnmatched = [], i = 0, len = unmatched.length, mapped = map != null; for ( ; i < len; i++ ) { if ( (elem = unmatched[i]) ) { if ( !filter || filter( elem, context, xml ) ) { newUnmatched.push( elem ); if ( mapped ) { map.push( i ); } } } } return newUnmatched; } function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { if ( postFilter && !postFilter[ expando ] ) { postFilter = setMatcher( postFilter ); } if ( postFinder && !postFinder[ expando ] ) { postFinder = setMatcher( postFinder, postSelector ); } return markFunction(function( seed, results, context, xml ) { var temp, i, elem, preMap = [], postMap = [], preexisting = results.length, // Get initial elements from seed or context elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ), // Prefilter to get matcher input, preserving a map for seed-results synchronization matcherIn = preFilter && ( seed || !selector ) ? condense( elems, preMap, preFilter, context, xml ) : elems, matcherOut = matcher ? // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, postFinder || ( seed ? preFilter : preexisting || postFilter ) ? // ...intermediate processing is necessary [] : // ...otherwise use results directly results : matcherIn; // Find primary matches if ( matcher ) { matcher( matcherIn, matcherOut, context, xml ); } // Apply postFilter if ( postFilter ) { temp = condense( matcherOut, postMap ); postFilter( temp, [], context, xml ); // Un-match failing elements by moving them back to matcherIn i = temp.length; while ( i-- ) { if ( (elem = temp[i]) ) { matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem); } } } if ( seed ) { if ( postFinder || preFilter ) { if ( postFinder ) { // Get the final matcherOut by condensing this intermediate into postFinder contexts temp = []; i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) ) { // Restore matcherIn since elem is not yet a final match temp.push( (matcherIn[i] = elem) ); } } postFinder( null, (matcherOut = []), temp, xml ); } // Move matched elements from seed to results to keep them synchronized i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) && (temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) { seed[temp] = !(results[temp] = elem); } } } // Add elements to results, through postFinder if defined } else { matcherOut = condense( matcherOut === results ? matcherOut.splice( preexisting, matcherOut.length ) : matcherOut ); if ( postFinder ) { postFinder( null, results, matcherOut, xml ); } else { push.apply( results, matcherOut ); } } }); } function matcherFromTokens( tokens ) { var checkContext, matcher, j, len = tokens.length, leadingRelative = Expr.relative[ tokens[0].type ], implicitRelative = leadingRelative || Expr.relative[" "], i = leadingRelative ? 1 : 0, // The foundational matcher ensures that elements are reachable from top-level context(s) matchContext = addCombinator( function( elem ) { return elem === checkContext; }, implicitRelative, true ), matchAnyContext = addCombinator( function( elem ) { return indexOf.call( checkContext, elem ) > -1; }, implicitRelative, true ), matchers = [ function( elem, context, xml ) { return ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( (checkContext = context).nodeType ? matchContext( elem, context, xml ) : matchAnyContext( elem, context, xml ) ); } ]; for ( ; i < len; i++ ) { if ( (matcher = Expr.relative[ tokens[i].type ]) ) { matchers = [ addCombinator(elementMatcher( matchers ), matcher) ]; } else { matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches ); // Return special upon seeing a positional matcher if ( matcher[ expando ] ) { // Find the next relative operator (if any) for proper handling j = ++i; for ( ; j < len; j++ ) { if ( Expr.relative[ tokens[j].type ] ) { break; } } return setMatcher( i > 1 && elementMatcher( matchers ), i > 1 && toSelector( // If the preceding token was a descendant combinator, insert an implicit any-element `*` tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" }) ).replace( rtrim, "$1" ), matcher, i < j && matcherFromTokens( tokens.slice( i, j ) ), j < len && matcherFromTokens( (tokens = tokens.slice( j )) ), j < len && toSelector( tokens ) ); } matchers.push( matcher ); } } return elementMatcher( matchers ); } function matcherFromGroupMatchers( elementMatchers, setMatchers ) { // A counter to specify which element is currently being matched var matcherCachedRuns = 0, bySet = setMatchers.length > 0, byElement = elementMatchers.length > 0, superMatcher = function( seed, context, xml, results, expandContext ) { var elem, j, matcher, setMatched = [], matchedCount = 0, i = "0", unmatched = seed && [], outermost = expandContext != null, contextBackup = outermostContext, // We must always have either seed elements or context elems = seed || byElement && Expr.find["TAG"]( "*", expandContext && context.parentNode || context ), // Use integer dirruns iff this is the outermost matcher dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1); if ( outermost ) { outermostContext = context !== document && context; cachedruns = matcherCachedRuns; } // Add elements passing elementMatchers directly to results // Keep `i` a string if there are no elements so `matchedCount` will be "00" below for ( ; (elem = elems[i]) != null; i++ ) { if ( byElement && elem ) { j = 0; while ( (matcher = elementMatchers[j++]) ) { if ( matcher( elem, context, xml ) ) { results.push( elem ); break; } } if ( outermost ) { dirruns = dirrunsUnique; cachedruns = ++matcherCachedRuns; } } // Track unmatched elements for set filters if ( bySet ) { // They will have gone through all possible matchers if ( (elem = !matcher && elem) ) { matchedCount--; } // Lengthen the array for every element, matched or not if ( seed ) { unmatched.push( elem ); } } } // Apply set filters to unmatched elements matchedCount += i; if ( bySet && i !== matchedCount ) { j = 0; while ( (matcher = setMatchers[j++]) ) { matcher( unmatched, setMatched, context, xml ); } if ( seed ) { // Reintegrate element matches to eliminate the need for sorting if ( matchedCount > 0 ) { while ( i-- ) { if ( !(unmatched[i] || setMatched[i]) ) { setMatched[i] = pop.call( results ); } } } // Discard index placeholder values to get only actual matches setMatched = condense( setMatched ); } // Add matches to results push.apply( results, setMatched ); // Seedless set matches succeeding multiple successful matchers stipulate sorting if ( outermost && !seed && setMatched.length > 0 && ( matchedCount + setMatchers.length ) > 1 ) { Sizzle.uniqueSort( results ); } } // Override manipulation of globals by nested matchers if ( outermost ) { dirruns = dirrunsUnique; outermostContext = contextBackup; } return unmatched; }; return bySet ? markFunction( superMatcher ) : superMatcher; } compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) { var i, setMatchers = [], elementMatchers = [], cached = compilerCache[ selector + " " ]; if ( !cached ) { // Generate a function of recursive functions that can be used to check each element if ( !group ) { group = tokenize( selector ); } i = group.length; while ( i-- ) { cached = matcherFromTokens( group[i] ); if ( cached[ expando ] ) { setMatchers.push( cached ); } else { elementMatchers.push( cached ); } } // Cache the compiled function cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); } return cached; }; function multipleContexts( selector, contexts, results ) { var i = 0, len = contexts.length; for ( ; i < len; i++ ) { Sizzle( selector, contexts[i], results ); } return results; } function select( selector, context, results, seed ) { var i, tokens, token, type, find, match = tokenize( selector ); if ( !seed ) { // Try to minimize operations if there is only one group if ( match.length === 1 ) { // Take a shortcut and set the context if the root selector is an ID tokens = match[0] = match[0].slice( 0 ); if ( tokens.length > 2 && (token = tokens[0]).type === "ID" && support.getById && context.nodeType === 9 && documentIsHTML && Expr.relative[ tokens[1].type ] ) { context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0]; if ( !context ) { return results; } selector = selector.slice( tokens.shift().value.length ); } // Fetch a seed set for right-to-left matching i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length; while ( i-- ) { token = tokens[i]; // Abort if we hit a combinator if ( Expr.relative[ (type = token.type) ] ) { break; } if ( (find = Expr.find[ type ]) ) { // Search, expanding context for leading sibling combinators if ( (seed = find( token.matches[0].replace( runescape, funescape ), rsibling.test( tokens[0].type ) && context.parentNode || context )) ) { // If seed is empty or no tokens remain, we can return early tokens.splice( i, 1 ); selector = seed.length && toSelector( tokens ); if ( !selector ) { push.apply( results, seed ); return results; } break; } } } } } // Compile and execute a filtering function // Provide `match` to avoid retokenization if we modified the selector above compile( selector, match )( seed, context, !documentIsHTML, results, rsibling.test( selector ) ); return results; } // Deprecated Expr.pseudos["nth"] = Expr.pseudos["eq"]; // Easy API for creating new setFilters function setFilters() {} setFilters.prototype = Expr.filters = Expr.pseudos; Expr.setFilters = new setFilters(); // One-time assignments // Sort stability support.sortStable = expando.split("").sort( sortOrder ).join("") === expando; // Initialize against the default document setDocument(); // Support: Chrome<<14 // Always assume duplicates if they aren't passed to the comparison function [0, 0].sort( sortOrder ); support.detectDuplicates = hasDuplicate; jQuery.find = Sizzle; jQuery.expr = Sizzle.selectors; jQuery.expr[":"] = jQuery.expr.pseudos; jQuery.unique = Sizzle.uniqueSort; jQuery.text = Sizzle.getText; jQuery.isXMLDoc = Sizzle.isXML; jQuery.contains = Sizzle.contains; })( window ); // String to Object options format cache var optionsCache = {}; // Convert String-formatted options into Object-formatted ones and store in cache function createOptions( options ) { var object = optionsCache[ options ] = {}; jQuery.each( options.match( core_rnotwhite ) || [], function( _, flag ) { object[ flag ] = true; }); return object; } /* * Create a callback list using the following parameters: * * options: an optional list of space-separated options that will change how * the callback list behaves or a more traditional option object * * By default a callback list will act like an event callback list and can be * "fired" multiple times. * * Possible options: * * once: will ensure the callback list can only be fired once (like a Deferred) * * memory: will keep track of previous values and will call any callback added * after the list has been fired right away with the latest "memorized" * values (like a Deferred) * * unique: will ensure a callback can only be added once (no duplicate in the list) * * stopOnFalse: interrupt callings when a callback returns false * */ jQuery.Callbacks = function( options ) { // Convert options from String-formatted to Object-formatted if needed // (we check in cache first) options = typeof options === "string" ? ( optionsCache[ options ] || createOptions( options ) ) : jQuery.extend( {}, options ); var // Flag to know if list is currently firing firing, // Last fire value (for non-forgettable lists) memory, // Flag to know if list was already fired fired, // End of the loop when firing firingLength, // Index of currently firing callback (modified by remove if needed) firingIndex, // First callback to fire (used internally by add and fireWith) firingStart, // Actual callback list list = [], // Stack of fire calls for repeatable lists stack = !options.once && [], // Fire callbacks fire = function( data ) { memory = options.memory && data; fired = true; firingIndex = firingStart || 0; firingStart = 0; firingLength = list.length; firing = true; for ( ; list && firingIndex < firingLength; firingIndex++ ) { if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) { memory = false; // To prevent further calls using add break; } } firing = false; if ( list ) { if ( stack ) { if ( stack.length ) { fire( stack.shift() ); } } else if ( memory ) { list = []; } else { self.disable(); } } }, // Actual Callbacks object self = { // Add a callback or a collection of callbacks to the list add: function() { if ( list ) { // First, we save the current length var start = list.length; (function add( args ) { jQuery.each( args, function( _, arg ) { var type = jQuery.type( arg ); if ( type === "function" ) { if ( !options.unique || !self.has( arg ) ) { list.push( arg ); } } else if ( arg && arg.length && type !== "string" ) { // Inspect recursively add( arg ); } }); })( arguments ); // Do we need to add the callbacks to the // current firing batch? if ( firing ) { firingLength = list.length; // With memory, if we're not firing then // we should call right away } else if ( memory ) { firingStart = start; fire( memory ); } } return this; }, // Remove a callback from the list remove: function() { if ( list ) { jQuery.each( arguments, function( _, arg ) { var index; while( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { list.splice( index, 1 ); // Handle firing indexes if ( firing ) { if ( index <= firingLength ) { firingLength--; } if ( index <= firingIndex ) { firingIndex--; } } } }); } return this; }, // Check if a given callback is in the list. // If no argument is given, return whether or not list has callbacks attached. has: function( fn ) { return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length ); }, // Remove all callbacks from the list empty: function() { list = []; firingLength = 0; return this; }, // Have the list do nothing anymore disable: function() { list = stack = memory = undefined; return this; }, // Is it disabled? disabled: function() { return !list; }, // Lock the list in its current state lock: function() { stack = undefined; if ( !memory ) { self.disable(); } return this; }, // Is it locked? locked: function() { return !stack; }, // Call all callbacks with the given context and arguments fireWith: function( context, args ) { args = args || []; args = [ context, args.slice ? args.slice() : args ]; if ( list && ( !fired || stack ) ) { if ( firing ) { stack.push( args ); } else { fire( args ); } } return this; }, // Call all the callbacks with the given arguments fire: function() { self.fireWith( this, arguments ); return this; }, // To know if the callbacks have already been called at least once fired: function() { return !!fired; } }; return self; }; jQuery.extend({ Deferred: function( func ) { var tuples = [ // action, add listener, listener list, final state [ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ], [ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ], [ "notify", "progress", jQuery.Callbacks("memory") ] ], state = "pending", promise = { state: function() { return state; }, always: function() { deferred.done( arguments ).fail( arguments ); return this; }, then: function( /* fnDone, fnFail, fnProgress */ ) { var fns = arguments; return jQuery.Deferred(function( newDefer ) { jQuery.each( tuples, function( i, tuple ) { var action = tuple[ 0 ], fn = jQuery.isFunction( fns[ i ] ) && fns[ i ]; // deferred[ done | fail | progress ] for forwarding actions to newDefer deferred[ tuple[1] ](function() { var returned = fn && fn.apply( this, arguments ); if ( returned && jQuery.isFunction( returned.promise ) ) { returned.promise() .done( newDefer.resolve ) .fail( newDefer.reject ) .progress( newDefer.notify ); } else { newDefer[ action + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments ); } }); }); fns = null; }).promise(); }, // Get a promise for this deferred // If obj is provided, the promise aspect is added to the object promise: function( obj ) { return obj != null ? jQuery.extend( obj, promise ) : promise; } }, deferred = {}; // Keep pipe for back-compat promise.pipe = promise.then; // Add list-specific methods jQuery.each( tuples, function( i, tuple ) { var list = tuple[ 2 ], stateString = tuple[ 3 ]; // promise[ done | fail | progress ] = list.add promise[ tuple[1] ] = list.add; // Handle state if ( stateString ) { list.add(function() { // state = [ resolved | rejected ] state = stateString; // [ reject_list | resolve_list ].disable; progress_list.lock }, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock ); } // deferred[ resolve | reject | notify ] deferred[ tuple[0] ] = function() { deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments ); return this; }; deferred[ tuple[0] + "With" ] = list.fireWith; }); // Make the deferred a promise promise.promise( deferred ); // Call given func if any if ( func ) { func.call( deferred, deferred ); } // All done! return deferred; }, // Deferred helper when: function( subordinate /* , ..., subordinateN */ ) { var i = 0, resolveValues = core_slice.call( arguments ), length = resolveValues.length, // the count of uncompleted subordinates remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0, // the master Deferred. If resolveValues consist of only a single Deferred, just use that. deferred = remaining === 1 ? subordinate : jQuery.Deferred(), // Update function for both resolve and progress values updateFunc = function( i, contexts, values ) { return function( value ) { contexts[ i ] = this; values[ i ] = arguments.length > 1 ? core_slice.call( arguments ) : value; if( values === progressValues ) { deferred.notifyWith( contexts, values ); } else if ( !( --remaining ) ) { deferred.resolveWith( contexts, values ); } }; }, progressValues, progressContexts, resolveContexts; // add listeners to Deferred subordinates; treat others as resolved if ( length > 1 ) { progressValues = new Array( length ); progressContexts = new Array( length ); resolveContexts = new Array( length ); for ( ; i < length; i++ ) { if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) { resolveValues[ i ].promise() .done( updateFunc( i, resolveContexts, resolveValues ) ) .fail( deferred.reject ) .progress( updateFunc( i, progressContexts, progressValues ) ); } else { --remaining; } } } // if we're not waiting on anything, resolve the master if ( !remaining ) { deferred.resolveWith( resolveContexts, resolveValues ); } return deferred.promise(); } }); jQuery.support = (function( support ) { var all, a, input, select, fragment, opt, eventName, isSupported, i, div = document.createElement("div"); // Setup div.setAttribute( "className", "t" ); div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>"; // Finish early in limited (non-browser) environments all = div.getElementsByTagName("*") || []; a = div.getElementsByTagName("a")[ 0 ]; if ( !a || !a.style || !all.length ) { return support; } // First batch of tests select = document.createElement("select"); opt = select.appendChild( document.createElement("option") ); input = div.getElementsByTagName("input")[ 0 ]; a.style.cssText = "top:1px;float:left;opacity:.5"; // Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7) support.getSetAttribute = div.className !== "t"; // IE strips leading whitespace when .innerHTML is used support.leadingWhitespace = div.firstChild.nodeType === 3; // Make sure that tbody elements aren't automatically inserted // IE will insert them into empty tables support.tbody = !div.getElementsByTagName("tbody").length; // Make sure that link elements get serialized correctly by innerHTML // This requires a wrapper element in IE support.htmlSerialize = !!div.getElementsByTagName("link").length; // Get the style information from getAttribute // (IE uses .cssText instead) support.style = /top/.test( a.getAttribute("style") ); // Make sure that URLs aren't manipulated // (IE normalizes it by default) support.hrefNormalized = a.getAttribute("href") === "/a"; // Make sure that element opacity exists // (IE uses filter instead) // Use a regex to work around a WebKit issue. See #5145 support.opacity = /^0.5/.test( a.style.opacity ); // Verify style float existence // (IE uses styleFloat instead of cssFloat) support.cssFloat = !!a.style.cssFloat; // Check the default checkbox/radio value ("" on WebKit; "on" elsewhere) support.checkOn = !!input.value; // Make sure that a selected-by-default option has a working selected property. // (WebKit defaults to false instead of true, IE too, if it's in an optgroup) support.optSelected = opt.selected; // Tests for enctype support on a form (#6743) support.enctype = !!document.createElement("form").enctype; // Makes sure cloning an html5 element does not cause problems // Where outerHTML is undefined, this still works support.html5Clone = document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav></:nav>"; // Will be defined later support.inlineBlockNeedsLayout = false; support.shrinkWrapBlocks = false; support.pixelPosition = false; support.deleteExpando = true; support.noCloneEvent = true; support.reliableMarginRight = true; support.boxSizingReliable = true; // Make sure checked status is properly cloned input.checked = true; support.noCloneChecked = input.cloneNode( true ).checked; // Make sure that the options inside disabled selects aren't marked as disabled // (WebKit marks them as disabled) select.disabled = true; support.optDisabled = !opt.disabled; // Support: IE<9 try { delete div.test; } catch( e ) { support.deleteExpando = false; } // Check if we can trust getAttribute("value") input = document.createElement("input"); input.setAttribute( "value", "" ); support.input = input.getAttribute( "value" ) === ""; // Check if an input maintains its value after becoming a radio input.value = "t"; input.setAttribute( "type", "radio" ); support.radioValue = input.value === "t"; // #11217 - WebKit loses check when the name is after the checked attribute input.setAttribute( "checked", "t" ); input.setAttribute( "name", "t" ); fragment = document.createDocumentFragment(); fragment.appendChild( input ); // Check if a disconnected checkbox will retain its checked // value of true after appended to the DOM (IE6/7) support.appendChecked = input.checked; // WebKit doesn't clone checked state correctly in fragments support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked; // Support: IE<9 // Opera does not clone events (and typeof div.attachEvent === undefined). // IE9-10 clones events bound via attachEvent, but they don't trigger with .click() if ( div.attachEvent ) { div.attachEvent( "onclick", function() { support.noCloneEvent = false; }); div.cloneNode( true ).click(); } // Support: IE<9 (lack submit/change bubble), Firefox 17+ (lack focusin event) // Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP) for ( i in { submit: true, change: true, focusin: true }) { div.setAttribute( eventName = "on" + i, "t" ); support[ i + "Bubbles" ] = eventName in window || div.attributes[ eventName ].expando === false; } div.style.backgroundClip = "content-box"; div.cloneNode( true ).style.backgroundClip = ""; support.clearCloneStyle = div.style.backgroundClip === "content-box"; // Support: IE<9 // Iteration over object's inherited properties before its own. for ( i in jQuery( support ) ) { break; } support.ownLast = i !== "0"; // Run tests that need a body at doc ready jQuery(function() { var container, marginDiv, tds, divReset = "padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;", body = document.getElementsByTagName("body")[0]; if ( !body ) { // Return for frameset docs that don't have a body return; } container = document.createElement("div"); container.style.cssText = "border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px"; body.appendChild( container ).appendChild( div ); // Support: IE8 // Check if table cells still have offsetWidth/Height when they are set // to display:none and there are still other visible table cells in a // table row; if so, offsetWidth/Height are not reliable for use when // determining if an element has been hidden directly using // display:none (it is still safe to use offsets if a parent element is // hidden; don safety goggles and see bug #4512 for more information). div.innerHTML = "<table><tr><td></td><td>t</td></tr></table>"; tds = div.getElementsByTagName("td"); tds[ 0 ].style.cssText = "padding:0;margin:0;border:0;display:none"; isSupported = ( tds[ 0 ].offsetHeight === 0 ); tds[ 0 ].style.display = ""; tds[ 1 ].style.display = "none"; // Support: IE8 // Check if empty table cells still have offsetWidth/Height support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 ); // Check box-sizing and margin behavior. div.innerHTML = ""; div.style.cssText = "box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;"; // Workaround failing boxSizing test due to offsetWidth returning wrong value // with some non-1 values of body zoom, ticket #13543 jQuery.swap( body, body.style.zoom != null ? { zoom: 1 } : {}, function() { support.boxSizing = div.offsetWidth === 4; }); // Use window.getComputedStyle because jsdom on node.js will break without it. if ( window.getComputedStyle ) { support.pixelPosition = ( window.getComputedStyle( div, null ) || {} ).top !== "1%"; support.boxSizingReliable = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px"; // Check if div with explicit width and no margin-right incorrectly // gets computed margin-right based on width of container. (#3333) // Fails in WebKit before Feb 2011 nightlies // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right marginDiv = div.appendChild( document.createElement("div") ); marginDiv.style.cssText = div.style.cssText = divReset; marginDiv.style.marginRight = marginDiv.style.width = "0"; div.style.width = "1px"; support.reliableMarginRight = !parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight ); } if ( typeof div.style.zoom !== core_strundefined ) { // Support: IE<8 // Check if natively block-level elements act like inline-block // elements when setting their display to 'inline' and giving // them layout div.innerHTML = ""; div.style.cssText = divReset + "width:1px;padding:1px;display:inline;zoom:1"; support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 ); // Support: IE6 // Check if elements with layout shrink-wrap their children div.style.display = "block"; div.innerHTML = "<div></div>"; div.firstChild.style.width = "5px"; support.shrinkWrapBlocks = ( div.offsetWidth !== 3 ); if ( support.inlineBlockNeedsLayout ) { // Prevent IE 6 from affecting layout for positioned elements #11048 // Prevent IE from shrinking the body in IE 7 mode #12869 // Support: IE<8 body.style.zoom = 1; } } body.removeChild( container ); // Null elements to avoid leaks in IE container = div = tds = marginDiv = null; }); // Null elements to avoid leaks in IE all = select = fragment = opt = a = input = null; return support; })({}); var rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/, rmultiDash = /([A-Z])/g; function internalData( elem, name, data, pvt /* Internal Use Only */ ){ if ( !jQuery.acceptData( elem ) ) { return; } var ret, thisCache, internalKey = jQuery.expando, // We have to handle DOM nodes and JS objects differently because IE6-7 // can't GC object references properly across the DOM-JS boundary isNode = elem.nodeType, // Only DOM nodes need the global jQuery cache; JS object data is // attached directly to the object so GC can occur automatically cache = isNode ? jQuery.cache : elem, // Only defining an ID for JS objects if its cache already exists allows // the code to shortcut on the same path as a DOM node with no cache id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey; // Avoid doing any more work than we need to when trying to get data on an // object that has no data at all if ( (!id || !cache[id] || (!pvt && !cache[id].data)) && data === undefined && typeof name === "string" ) { return; } if ( !id ) { // Only DOM nodes need a new unique ID for each element since their data // ends up in the global cache if ( isNode ) { id = elem[ internalKey ] = core_deletedIds.pop() || jQuery.guid++; } else { id = internalKey; } } if ( !cache[ id ] ) { // Avoid exposing jQuery metadata on plain JS objects when the object // is serialized using JSON.stringify cache[ id ] = isNode ? {} : { toJSON: jQuery.noop }; } // An object can be passed to jQuery.data instead of a key/value pair; this gets // shallow copied over onto the existing cache if ( typeof name === "object" || typeof name === "function" ) { if ( pvt ) { cache[ id ] = jQuery.extend( cache[ id ], name ); } else { cache[ id ].data = jQuery.extend( cache[ id ].data, name ); } } thisCache = cache[ id ]; // jQuery data() is stored in a separate object inside the object's internal data // cache in order to avoid key collisions between internal data and user-defined // data. if ( !pvt ) { if ( !thisCache.data ) { thisCache.data = {}; } thisCache = thisCache.data; } if ( data !== undefined ) { thisCache[ jQuery.camelCase( name ) ] = data; } // Check for both converted-to-camel and non-converted data property names // If a data property was specified if ( typeof name === "string" ) { // First Try to find as-is property data ret = thisCache[ name ]; // Test for null|undefined property data if ( ret == null ) { // Try to find the camelCased property ret = thisCache[ jQuery.camelCase( name ) ]; } } else { ret = thisCache; } return ret; } function internalRemoveData( elem, name, pvt ) { if ( !jQuery.acceptData( elem ) ) { return; } var thisCache, i, isNode = elem.nodeType, // See jQuery.data for more information cache = isNode ? jQuery.cache : elem, id = isNode ? elem[ jQuery.expando ] : jQuery.expando; // If there is already no cache entry for this object, there is no // purpose in continuing if ( !cache[ id ] ) { return; } if ( name ) { thisCache = pvt ? cache[ id ] : cache[ id ].data; if ( thisCache ) { // Support array or space separated string names for data keys if ( !jQuery.isArray( name ) ) { // try the string as a key before any manipulation if ( name in thisCache ) { name = [ name ]; } else { // split the camel cased version by spaces unless a key with the spaces exists name = jQuery.camelCase( name ); if ( name in thisCache ) { name = [ name ]; } else { name = name.split(" "); } } } else { // If "name" is an array of keys... // When data is initially created, via ("key", "val") signature, // keys will be converted to camelCase. // Since there is no way to tell _how_ a key was added, remove // both plain key and camelCase key. #12786 // This will only penalize the array argument path. name = name.concat( jQuery.map( name, jQuery.camelCase ) ); } i = name.length; while ( i-- ) { delete thisCache[ name[i] ]; } // If there is no data left in the cache, we want to continue // and let the cache object itself get destroyed if ( pvt ? !isEmptyDataObject(thisCache) : !jQuery.isEmptyObject(thisCache) ) { return; } } } // See jQuery.data for more information if ( !pvt ) { delete cache[ id ].data; // Don't destroy the parent cache unless the internal data object // had been the only thing left in it if ( !isEmptyDataObject( cache[ id ] ) ) { return; } } // Destroy the cache if ( isNode ) { jQuery.cleanData( [ elem ], true ); // Use delete when supported for expandos or `cache` is not a window per isWindow (#10080) /* jshint eqeqeq: false */ } else if ( jQuery.support.deleteExpando || cache != cache.window ) { /* jshint eqeqeq: true */ delete cache[ id ]; // When all else fails, null } else { cache[ id ] = null; } } jQuery.extend({ cache: {}, // The following elements throw uncatchable exceptions if you // attempt to add expando properties to them. noData: { "applet": true, "embed": true, // Ban all objects except for Flash (which handle expandos) "object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" }, hasData: function( elem ) { elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ]; return !!elem && !isEmptyDataObject( elem ); }, data: function( elem, name, data ) { return internalData( elem, name, data ); }, removeData: function( elem, name ) { return internalRemoveData( elem, name ); }, // For internal use only. _data: function( elem, name, data ) { return internalData( elem, name, data, true ); }, _removeData: function( elem, name ) { return internalRemoveData( elem, name, true ); }, // A method for determining if a DOM node can handle the data expando acceptData: function( elem ) { // Do not set data on non-element because it will not be cleared (#8335). if ( elem.nodeType && elem.nodeType !== 1 && elem.nodeType !== 9 ) { return false; } var noData = elem.nodeName && jQuery.noData[ elem.nodeName.toLowerCase() ]; // nodes accept data unless otherwise specified; rejection can be conditional return !noData || noData !== true && elem.getAttribute("classid") === noData; } }); jQuery.fn.extend({ data: function( key, value ) { var attrs, name, data = null, i = 0, elem = this[0]; // Special expections of .data basically thwart jQuery.access, // so implement the relevant behavior ourselves // Gets all values if ( key === undefined ) { if ( this.length ) { data = jQuery.data( elem ); if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) { attrs = elem.attributes; for ( ; i < attrs.length; i++ ) { name = attrs[i].name; if ( name.indexOf("data-") === 0 ) { name = jQuery.camelCase( name.slice(5) ); dataAttr( elem, name, data[ name ] ); } } jQuery._data( elem, "parsedAttrs", true ); } } return data; } // Sets multiple values if ( typeof key === "object" ) { return this.each(function() { jQuery.data( this, key ); }); } return arguments.length > 1 ? // Sets one value this.each(function() { jQuery.data( this, key, value ); }) : // Gets one value // Try to fetch any internally stored data first elem ? dataAttr( elem, key, jQuery.data( elem, key ) ) : null; }, removeData: function( key ) { return this.each(function() { jQuery.removeData( this, key ); }); } }); function dataAttr( elem, key, data ) { // If nothing was found internally, try to fetch any // data from the HTML5 data-* attribute if ( data === undefined && elem.nodeType === 1 ) { var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); data = elem.getAttribute( name ); if ( typeof data === "string" ) { try { data = data === "true" ? true : data === "false" ? false : data === "null" ? null : // Only convert to a number if it doesn't change the string +data + "" === data ? +data : rbrace.test( data ) ? jQuery.parseJSON( data ) : data; } catch( e ) {} // Make sure we set the data so it isn't changed later jQuery.data( elem, key, data ); } else { data = undefined; } } return data; } // checks a cache object for emptiness function isEmptyDataObject( obj ) { var name; for ( name in obj ) { // if the public data object is empty, the private is still empty if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) { continue; } if ( name !== "toJSON" ) { return false; } } return true; } jQuery.extend({ queue: function( elem, type, data ) { var queue; if ( elem ) { type = ( type || "fx" ) + "queue"; queue = jQuery._data( elem, type ); // Speed up dequeue by getting out quickly if this is just a lookup if ( data ) { if ( !queue || jQuery.isArray(data) ) { queue = jQuery._data( elem, type, jQuery.makeArray(data) ); } else { queue.push( data ); } } return queue || []; } }, dequeue: function( elem, type ) { type = type || "fx"; var queue = jQuery.queue( elem, type ), startLength = queue.length, fn = queue.shift(), hooks = jQuery._queueHooks( elem, type ), next = function() { jQuery.dequeue( elem, type ); }; // If the fx queue is dequeued, always remove the progress sentinel if ( fn === "inprogress" ) { fn = queue.shift(); startLength--; } if ( fn ) { // Add a progress sentinel to prevent the fx queue from being // automatically dequeued if ( type === "fx" ) { queue.unshift( "inprogress" ); } // clear up the last queue stop function delete hooks.stop; fn.call( elem, next, hooks ); } if ( !startLength && hooks ) { hooks.empty.fire(); } }, // not intended for public consumption - generates a queueHooks object, or returns the current one _queueHooks: function( elem, type ) { var key = type + "queueHooks"; return jQuery._data( elem, key ) || jQuery._data( elem, key, { empty: jQuery.Callbacks("once memory").add(function() { jQuery._removeData( elem, type + "queue" ); jQuery._removeData( elem, key ); }) }); } }); jQuery.fn.extend({ queue: function( type, data ) { var setter = 2; if ( typeof type !== "string" ) { data = type; type = "fx"; setter--; } if ( arguments.length < setter ) { return jQuery.queue( this[0], type ); } return data === undefined ? this : this.each(function() { var queue = jQuery.queue( this, type, data ); // ensure a hooks for this queue jQuery._queueHooks( this, type ); if ( type === "fx" && queue[0] !== "inprogress" ) { jQuery.dequeue( this, type ); } }); }, dequeue: function( type ) { return this.each(function() { jQuery.dequeue( this, type ); }); }, // Based off of the plugin by Clint Helfers, with permission. // http://blindsignals.com/index.php/2009/07/jquery-delay/ delay: function( time, type ) { time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; type = type || "fx"; return this.queue( type, function( next, hooks ) { var timeout = setTimeout( next, time ); hooks.stop = function() { clearTimeout( timeout ); }; }); }, clearQueue: function( type ) { return this.queue( type || "fx", [] ); }, // Get a promise resolved when queues of a certain type // are emptied (fx is the type by default) promise: function( type, obj ) { var tmp, count = 1, defer = jQuery.Deferred(), elements = this, i = this.length, resolve = function() { if ( !( --count ) ) { defer.resolveWith( elements, [ elements ] ); } }; if ( typeof type !== "string" ) { obj = type; type = undefined; } type = type || "fx"; while( i-- ) { tmp = jQuery._data( elements[ i ], type + "queueHooks" ); if ( tmp && tmp.empty ) { count++; tmp.empty.add( resolve ); } } resolve(); return defer.promise( obj ); } }); var nodeHook, boolHook, rclass = /[\t\r\n\f]/g, rreturn = /\r/g, rfocusable = /^(?:input|select|textarea|button|object)$/i, rclickable = /^(?:a|area)$/i, ruseDefault = /^(?:checked|selected)$/i, getSetAttribute = jQuery.support.getSetAttribute, getSetInput = jQuery.support.input; jQuery.fn.extend({ attr: function( name, value ) { return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 ); }, removeAttr: function( name ) { return this.each(function() { jQuery.removeAttr( this, name ); }); }, prop: function( name, value ) { return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 ); }, removeProp: function( name ) { name = jQuery.propFix[ name ] || name; return this.each(function() { // try/catch handles cases where IE balks (such as removing a property on window) try { this[ name ] = undefined; delete this[ name ]; } catch( e ) {} }); }, addClass: function( value ) { var classes, elem, cur, clazz, j, i = 0, len = this.length, proceed = typeof value === "string" && value; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).addClass( value.call( this, j, this.className ) ); }); } if ( proceed ) { // The disjunction here is for better compressibility (see removeClass) classes = ( value || "" ).match( core_rnotwhite ) || []; for ( ; i < len; i++ ) { elem = this[ i ]; cur = elem.nodeType === 1 && ( elem.className ? ( " " + elem.className + " " ).replace( rclass, " " ) : " " ); if ( cur ) { j = 0; while ( (clazz = classes[j++]) ) { if ( cur.indexOf( " " + clazz + " " ) < 0 ) { cur += clazz + " "; } } elem.className = jQuery.trim( cur ); } } } return this; }, removeClass: function( value ) { var classes, elem, cur, clazz, j, i = 0, len = this.length, proceed = arguments.length === 0 || typeof value === "string" && value; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).removeClass( value.call( this, j, this.className ) ); }); } if ( proceed ) { classes = ( value || "" ).match( core_rnotwhite ) || []; for ( ; i < len; i++ ) { elem = this[ i ]; // This expression is here for better compressibility (see addClass) cur = elem.nodeType === 1 && ( elem.className ? ( " " + elem.className + " " ).replace( rclass, " " ) : "" ); if ( cur ) { j = 0; while ( (clazz = classes[j++]) ) { // Remove *all* instances while ( cur.indexOf( " " + clazz + " " ) >= 0 ) { cur = cur.replace( " " + clazz + " ", " " ); } } elem.className = value ? jQuery.trim( cur ) : ""; } } } return this; }, toggleClass: function( value, stateVal ) { var type = typeof value, isBool = typeof stateVal === "boolean"; if ( jQuery.isFunction( value ) ) { return this.each(function( i ) { jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal ); }); } return this.each(function() { if ( type === "string" ) { // toggle individual class names var className, i = 0, self = jQuery( this ), state = stateVal, classNames = value.match( core_rnotwhite ) || []; while ( (className = classNames[ i++ ]) ) { // check each className given, space separated list state = isBool ? state : !self.hasClass( className ); self[ state ? "addClass" : "removeClass" ]( className ); } // Toggle whole class name } else if ( type === core_strundefined || type === "boolean" ) { if ( this.className ) { // store className if set jQuery._data( this, "__className__", this.className ); } // If the element has a class name or if we're passed "false", // then remove the whole classname (if there was one, the above saved it). // Otherwise bring back whatever was previously saved (if anything), // falling back to the empty string if nothing was stored. this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || ""; } }); }, hasClass: function( selector ) { var className = " " + selector + " ", i = 0, l = this.length; for ( ; i < l; i++ ) { if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) { return true; } } return false; }, val: function( value ) { var ret, hooks, isFunction, elem = this[0]; if ( !arguments.length ) { if ( elem ) { hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ]; if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) { return ret; } ret = elem.value; return typeof ret === "string" ? // handle most common string cases ret.replace(rreturn, "") : // handle cases where value is null/undef or number ret == null ? "" : ret; } return; } isFunction = jQuery.isFunction( value ); return this.each(function( i ) { var val; if ( this.nodeType !== 1 ) { return; } if ( isFunction ) { val = value.call( this, i, jQuery( this ).val() ); } else { val = value; } // Treat null/undefined as ""; convert numbers to string if ( val == null ) { val = ""; } else if ( typeof val === "number" ) { val += ""; } else if ( jQuery.isArray( val ) ) { val = jQuery.map(val, function ( value ) { return value == null ? "" : value + ""; }); } hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; // If set returns undefined, fall back to normal setting if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) { this.value = val; } }); } }); jQuery.extend({ valHooks: { option: { get: function( elem ) { // Use proper attribute retrieval(#6932, #12072) var val = jQuery.find.attr( elem, "value" ); return val != null ? val : elem.text; } }, select: { get: function( elem ) { var value, option, options = elem.options, index = elem.selectedIndex, one = elem.type === "select-one" || index < 0, values = one ? null : [], max = one ? index + 1 : options.length, i = index < 0 ? max : one ? index : 0; // Loop through all the selected options for ( ; i < max; i++ ) { option = options[ i ]; // oldIE doesn't update selected after form reset (#2551) if ( ( option.selected || i === index ) && // Don't return options that are disabled or in a disabled optgroup ( jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) && ( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) { // Get the specific value for the option value = jQuery( option ).val(); // We don't need an array for one selects if ( one ) { return value; } // Multi-Selects return an array values.push( value ); } } return values; }, set: function( elem, value ) { var optionSet, option, options = elem.options, values = jQuery.makeArray( value ), i = options.length; while ( i-- ) { option = options[ i ]; if ( (option.selected = jQuery.inArray( jQuery(option).val(), values ) >= 0) ) { optionSet = true; } } // force browsers to behave consistently when non-matching value is set if ( !optionSet ) { elem.selectedIndex = -1; } return values; } } }, attr: function( elem, name, value ) { var hooks, ret, nType = elem.nodeType; // don't get/set attributes on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } // Fallback to prop when attributes are not supported if ( typeof elem.getAttribute === core_strundefined ) { return jQuery.prop( elem, name, value ); } // All attributes are lowercase // Grab necessary hook if one is defined if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { name = name.toLowerCase(); hooks = jQuery.attrHooks[ name ] || ( jQuery.expr.match.bool.test( name ) ? boolHook : nodeHook ); } if ( value !== undefined ) { if ( value === null ) { jQuery.removeAttr( elem, name ); } else if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; } else { elem.setAttribute( name, value + "" ); return value; } } else if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { return ret; } else { ret = jQuery.find.attr( elem, name ); // Non-existent attributes return null, we normalize to undefined return ret == null ? undefined : ret; } }, removeAttr: function( elem, value ) { var name, propName, i = 0, attrNames = value && value.match( core_rnotwhite ); if ( attrNames && elem.nodeType === 1 ) { while ( (name = attrNames[i++]) ) { propName = jQuery.propFix[ name ] || name; // Boolean attributes get special treatment (#10870) if ( jQuery.expr.match.bool.test( name ) ) { // Set corresponding property to false if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) { elem[ propName ] = false; // Support: IE<9 // Also clear defaultChecked/defaultSelected (if appropriate) } else { elem[ jQuery.camelCase( "default-" + name ) ] = elem[ propName ] = false; } // See #9699 for explanation of this approach (setting first, then removal) } else { jQuery.attr( elem, name, "" ); } elem.removeAttribute( getSetAttribute ? name : propName ); } } }, attrHooks: { type: { set: function( elem, value ) { if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) { // Setting the type on a radio button after the value resets the value in IE6-9 // Reset value to default in case type is set after value during creation var val = elem.value; elem.setAttribute( "type", value ); if ( val ) { elem.value = val; } return value; } } } }, propFix: { "for": "htmlFor", "class": "className" }, prop: function( elem, name, value ) { var ret, hooks, notxml, nType = elem.nodeType; // don't get/set properties on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); if ( notxml ) { // Fix name and attach hooks name = jQuery.propFix[ name ] || name; hooks = jQuery.propHooks[ name ]; } if ( value !== undefined ) { return hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ? ret : ( elem[ name ] = value ); } else { return hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ? ret : elem[ name ]; } }, propHooks: { tabIndex: { get: function( elem ) { // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ // Use proper attribute retrieval(#12072) var tabindex = jQuery.find.attr( elem, "tabindex" ); return tabindex ? parseInt( tabindex, 10 ) : rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ? 0 : -1; } } } }); // Hooks for boolean attributes boolHook = { set: function( elem, value, name ) { if ( value === false ) { // Remove boolean attributes when set to false jQuery.removeAttr( elem, name ); } else if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) { // IE<8 needs the *property* name elem.setAttribute( !getSetAttribute && jQuery.propFix[ name ] || name, name ); // Use defaultChecked and defaultSelected for oldIE } else { elem[ jQuery.camelCase( "default-" + name ) ] = elem[ name ] = true; } return name; } }; jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) { var getter = jQuery.expr.attrHandle[ name ] || jQuery.find.attr; jQuery.expr.attrHandle[ name ] = getSetInput && getSetAttribute || !ruseDefault.test( name ) ? function( elem, name, isXML ) { var fn = jQuery.expr.attrHandle[ name ], ret = isXML ? undefined : /* jshint eqeqeq: false */ (jQuery.expr.attrHandle[ name ] = undefined) != getter( elem, name, isXML ) ? name.toLowerCase() : null; jQuery.expr.attrHandle[ name ] = fn; return ret; } : function( elem, name, isXML ) { return isXML ? undefined : elem[ jQuery.camelCase( "default-" + name ) ] ? name.toLowerCase() : null; }; }); // fix oldIE attroperties if ( !getSetInput || !getSetAttribute ) { jQuery.attrHooks.value = { set: function( elem, value, name ) { if ( jQuery.nodeName( elem, "input" ) ) { // Does not return so that setAttribute is also used elem.defaultValue = value; } else { // Use nodeHook if defined (#1954); otherwise setAttribute is fine return nodeHook && nodeHook.set( elem, value, name ); } } }; } // IE6/7 do not support getting/setting some attributes with get/setAttribute if ( !getSetAttribute ) { // Use this for any attribute in IE6/7 // This fixes almost every IE6/7 issue nodeHook = { set: function( elem, value, name ) { // Set the existing or create a new attribute node var ret = elem.getAttributeNode( name ); if ( !ret ) { elem.setAttributeNode( (ret = elem.ownerDocument.createAttribute( name )) ); } ret.value = value += ""; // Break association with cloned elements by also using setAttribute (#9646) return name === "value" || value === elem.getAttribute( name ) ? value : undefined; } }; jQuery.expr.attrHandle.id = jQuery.expr.attrHandle.name = jQuery.expr.attrHandle.coords = // Some attributes are constructed with empty-string values when not defined function( elem, name, isXML ) { var ret; return isXML ? undefined : (ret = elem.getAttributeNode( name )) && ret.value !== "" ? ret.value : null; }; jQuery.valHooks.button = { get: function( elem, name ) { var ret = elem.getAttributeNode( name ); return ret && ret.specified ? ret.value : undefined; }, set: nodeHook.set }; // Set contenteditable to false on removals(#10429) // Setting to empty string throws an error as an invalid value jQuery.attrHooks.contenteditable = { set: function( elem, value, name ) { nodeHook.set( elem, value === "" ? false : value, name ); } }; // Set width and height to auto instead of 0 on empty string( Bug #8150 ) // This is for removals jQuery.each([ "width", "height" ], function( i, name ) { jQuery.attrHooks[ name ] = { set: function( elem, value ) { if ( value === "" ) { elem.setAttribute( name, "auto" ); return value; } } }; }); } // Some attributes require a special call on IE // http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx if ( !jQuery.support.hrefNormalized ) { // href/src property should get the full normalized URL (#10299/#12915) jQuery.each([ "href", "src" ], function( i, name ) { jQuery.propHooks[ name ] = { get: function( elem ) { return elem.getAttribute( name, 4 ); } }; }); } if ( !jQuery.support.style ) { jQuery.attrHooks.style = { get: function( elem ) { // Return undefined in the case of empty string // Note: IE uppercases css property names, but if we were to .toLowerCase() // .cssText, that would destroy case senstitivity in URL's, like in "background" return elem.style.cssText || undefined; }, set: function( elem, value ) { return ( elem.style.cssText = value + "" ); } }; } // Safari mis-reports the default selected property of an option // Accessing the parent's selectedIndex property fixes it if ( !jQuery.support.optSelected ) { jQuery.propHooks.selected = { get: function( elem ) { var parent = elem.parentNode; if ( parent ) { parent.selectedIndex; // Make sure that it also works with optgroups, see #5701 if ( parent.parentNode ) { parent.parentNode.selectedIndex; } } return null; } }; } jQuery.each([ "tabIndex", "readOnly", "maxLength", "cellSpacing", "cellPadding", "rowSpan", "colSpan", "useMap", "frameBorder", "contentEditable" ], function() { jQuery.propFix[ this.toLowerCase() ] = this; }); // IE6/7 call enctype encoding if ( !jQuery.support.enctype ) { jQuery.propFix.enctype = "encoding"; } // Radios and checkboxes getter/setter jQuery.each([ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = { set: function( elem, value ) { if ( jQuery.isArray( value ) ) { return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 ); } } }; if ( !jQuery.support.checkOn ) { jQuery.valHooks[ this ].get = function( elem ) { // Support: Webkit // "" is returned instead of "on" if a value isn't specified return elem.getAttribute("value") === null ? "on" : elem.value; }; } }); var rformElems = /^(?:input|select|textarea)$/i, rkeyEvent = /^key/, rmouseEvent = /^(?:mouse|contextmenu)|click/, rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, rtypenamespace = /^([^.]*)(?:\.(.+)|)$/; function returnTrue() { return true; } function returnFalse() { return false; } function safeActiveElement() { try { return document.activeElement; } catch ( err ) { } } /* * Helper functions for managing events -- not part of the public interface. * Props to Dean Edwards' addEvent library for many of the ideas. */ jQuery.event = { global: {}, add: function( elem, types, handler, data, selector ) { var tmp, events, t, handleObjIn, special, eventHandle, handleObj, handlers, type, namespaces, origType, elemData = jQuery._data( elem ); // Don't attach events to noData or text/comment nodes (but allow plain objects) if ( !elemData ) { return; } // Caller can pass in an object of custom data in lieu of the handler if ( handler.handler ) { handleObjIn = handler; handler = handleObjIn.handler; selector = handleObjIn.selector; } // Make sure that the handler has a unique ID, used to find/remove it later if ( !handler.guid ) { handler.guid = jQuery.guid++; } // Init the element's event structure and main handler, if this is the first if ( !(events = elemData.events) ) { events = elemData.events = {}; } if ( !(eventHandle = elemData.handle) ) { eventHandle = elemData.handle = function( e ) { // Discard the second event of a jQuery.event.trigger() and // when an event is called after a page has unloaded return typeof jQuery !== core_strundefined && (!e || jQuery.event.triggered !== e.type) ? jQuery.event.dispatch.apply( eventHandle.elem, arguments ) : undefined; }; // Add elem as a property of the handle fn to prevent a memory leak with IE non-native events eventHandle.elem = elem; } // Handle multiple events separated by a space types = ( types || "" ).match( core_rnotwhite ) || [""]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[t] ) || []; type = origType = tmp[1]; namespaces = ( tmp[2] || "" ).split( "." ).sort(); // There *must* be a type, no attaching namespace-only handlers if ( !type ) { continue; } // If event changes its type, use the special event handlers for the changed type special = jQuery.event.special[ type ] || {}; // If selector defined, determine special event api type, otherwise given type type = ( selector ? special.delegateType : special.bindType ) || type; // Update special based on newly reset type special = jQuery.event.special[ type ] || {}; // handleObj is passed to all event handlers handleObj = jQuery.extend({ type: type, origType: origType, data: data, handler: handler, guid: handler.guid, selector: selector, needsContext: selector && jQuery.expr.match.needsContext.test( selector ), namespace: namespaces.join(".") }, handleObjIn ); // Init the event handler queue if we're the first if ( !(handlers = events[ type ]) ) { handlers = events[ type ] = []; handlers.delegateCount = 0; // Only use addEventListener/attachEvent if the special events handler returns false if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { // Bind the global event handler to the element if ( elem.addEventListener ) { elem.addEventListener( type, eventHandle, false ); } else if ( elem.attachEvent ) { elem.attachEvent( "on" + type, eventHandle ); } } } if ( special.add ) { special.add.call( elem, handleObj ); if ( !handleObj.handler.guid ) { handleObj.handler.guid = handler.guid; } } // Add to the element's handler list, delegates in front if ( selector ) { handlers.splice( handlers.delegateCount++, 0, handleObj ); } else { handlers.push( handleObj ); } // Keep track of which events have ever been used, for event optimization jQuery.event.global[ type ] = true; } // Nullify elem to prevent memory leaks in IE elem = null; }, // Detach an event or set of events from an element remove: function( elem, types, handler, selector, mappedTypes ) { var j, handleObj, tmp, origCount, t, events, special, handlers, type, namespaces, origType, elemData = jQuery.hasData( elem ) && jQuery._data( elem ); if ( !elemData || !(events = elemData.events) ) { return; } // Once for each type.namespace in types; type may be omitted types = ( types || "" ).match( core_rnotwhite ) || [""]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[t] ) || []; type = origType = tmp[1]; namespaces = ( tmp[2] || "" ).split( "." ).sort(); // Unbind all events (on this namespace, if provided) for the element if ( !type ) { for ( type in events ) { jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); } continue; } special = jQuery.event.special[ type ] || {}; type = ( selector ? special.delegateType : special.bindType ) || type; handlers = events[ type ] || []; tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ); // Remove matching events origCount = j = handlers.length; while ( j-- ) { handleObj = handlers[ j ]; if ( ( mappedTypes || origType === handleObj.origType ) && ( !handler || handler.guid === handleObj.guid ) && ( !tmp || tmp.test( handleObj.namespace ) ) && ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { handlers.splice( j, 1 ); if ( handleObj.selector ) { handlers.delegateCount--; } if ( special.remove ) { special.remove.call( elem, handleObj ); } } } // Remove generic event handler if we removed something and no more handlers exist // (avoids potential for endless recursion during removal of special event handlers) if ( origCount && !handlers.length ) { if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) { jQuery.removeEvent( elem, type, elemData.handle ); } delete events[ type ]; } } // Remove the expando if it's no longer used if ( jQuery.isEmptyObject( events ) ) { delete elemData.handle; // removeData also checks for emptiness and clears the expando if empty // so use it instead of delete jQuery._removeData( elem, "events" ); } }, trigger: function( event, data, elem, onlyHandlers ) { var handle, ontype, cur, bubbleType, special, tmp, i, eventPath = [ elem || document ], type = core_hasOwn.call( event, "type" ) ? event.type : event, namespaces = core_hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : []; cur = tmp = elem = elem || document; // Don't do events on text and comment nodes if ( elem.nodeType === 3 || elem.nodeType === 8 ) { return; } // focus/blur morphs to focusin/out; ensure we're not firing them right now if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { return; } if ( type.indexOf(".") >= 0 ) { // Namespaced trigger; create a regexp to match event type in handle() namespaces = type.split("."); type = namespaces.shift(); namespaces.sort(); } ontype = type.indexOf(":") < 0 && "on" + type; // Caller can pass in a jQuery.Event object, Object, or just an event type string event = event[ jQuery.expando ] ? event : new jQuery.Event( type, typeof event === "object" && event ); // Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true) event.isTrigger = onlyHandlers ? 2 : 3; event.namespace = namespaces.join("."); event.namespace_re = event.namespace ? new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) : null; // Clean up the event in case it is being reused event.result = undefined; if ( !event.target ) { event.target = elem; } // Clone any incoming data and prepend the event, creating the handler arg list data = data == null ? [ event ] : jQuery.makeArray( data, [ event ] ); // Allow special events to draw outside the lines special = jQuery.event.special[ type ] || {}; if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) { return; } // Determine event propagation path in advance, per W3C events spec (#9951) // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { bubbleType = special.delegateType || type; if ( !rfocusMorph.test( bubbleType + type ) ) { cur = cur.parentNode; } for ( ; cur; cur = cur.parentNode ) { eventPath.push( cur ); tmp = cur; } // Only add window if we got to document (e.g., not plain obj or detached DOM) if ( tmp === (elem.ownerDocument || document) ) { eventPath.push( tmp.defaultView || tmp.parentWindow || window ); } } // Fire handlers on the event path i = 0; while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) { event.type = i > 1 ? bubbleType : special.bindType || type; // jQuery handler handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" ); if ( handle ) { handle.apply( cur, data ); } // Native handler handle = ontype && cur[ ontype ]; if ( handle && jQuery.acceptData( cur ) && handle.apply && handle.apply( cur, data ) === false ) { event.preventDefault(); } } event.type = type; // If nobody prevented the default action, do it now if ( !onlyHandlers && !event.isDefaultPrevented() ) { if ( (!special._default || special._default.apply( eventPath.pop(), data ) === false) && jQuery.acceptData( elem ) ) { // Call a native DOM method on the target with the same name name as the event. // Can't use an .isFunction() check here because IE6/7 fails that test. // Don't do default actions on window, that's where global variables be (#6170) if ( ontype && elem[ type ] && !jQuery.isWindow( elem ) ) { // Don't re-trigger an onFOO event when we call its FOO() method tmp = elem[ ontype ]; if ( tmp ) { elem[ ontype ] = null; } // Prevent re-triggering of the same event, since we already bubbled it above jQuery.event.triggered = type; try { elem[ type ](); } catch ( e ) { // IE<9 dies on focus/blur to hidden element (#1486,#12518) // only reproducible on winXP IE8 native, not IE9 in IE8 mode } jQuery.event.triggered = undefined; if ( tmp ) { elem[ ontype ] = tmp; } } } } return event.result; }, dispatch: function( event ) { // Make a writable jQuery.Event from the native event object event = jQuery.event.fix( event ); var i, ret, handleObj, matched, j, handlerQueue = [], args = core_slice.call( arguments ), handlers = ( jQuery._data( this, "events" ) || {} )[ event.type ] || [], special = jQuery.event.special[ event.type ] || {}; // Use the fix-ed jQuery.Event rather than the (read-only) native event args[0] = event; event.delegateTarget = this; // Call the preDispatch hook for the mapped type, and let it bail if desired if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { return; } // Determine handlers handlerQueue = jQuery.event.handlers.call( this, event, handlers ); // Run delegates first; they may want to stop propagation beneath us i = 0; while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) { event.currentTarget = matched.elem; j = 0; while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) { // Triggered event must either 1) have no namespace, or // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) { event.handleObj = handleObj; event.data = handleObj.data; ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) .apply( matched.elem, args ); if ( ret !== undefined ) { if ( (event.result = ret) === false ) { event.preventDefault(); event.stopPropagation(); } } } } } // Call the postDispatch hook for the mapped type if ( special.postDispatch ) { special.postDispatch.call( this, event ); } return event.result; }, handlers: function( event, handlers ) { var sel, handleObj, matches, i, handlerQueue = [], delegateCount = handlers.delegateCount, cur = event.target; // Find delegate handlers // Black-hole SVG <use> instance trees (#13180) // Avoid non-left-click bubbling in Firefox (#3861) if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) { /* jshint eqeqeq: false */ for ( ; cur != this; cur = cur.parentNode || this ) { /* jshint eqeqeq: true */ // Don't check non-elements (#13208) // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) if ( cur.nodeType === 1 && (cur.disabled !== true || event.type !== "click") ) { matches = []; for ( i = 0; i < delegateCount; i++ ) { handleObj = handlers[ i ]; // Don't conflict with Object.prototype properties (#13203) sel = handleObj.selector + " "; if ( matches[ sel ] === undefined ) { matches[ sel ] = handleObj.needsContext ? jQuery( sel, this ).index( cur ) >= 0 : jQuery.find( sel, this, null, [ cur ] ).length; } if ( matches[ sel ] ) { matches.push( handleObj ); } } if ( matches.length ) { handlerQueue.push({ elem: cur, handlers: matches }); } } } } // Add the remaining (directly-bound) handlers if ( delegateCount < handlers.length ) { handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) }); } return handlerQueue; }, fix: function( event ) { if ( event[ jQuery.expando ] ) { return event; } // Create a writable copy of the event object and normalize some properties var i, prop, copy, type = event.type, originalEvent = event, fixHook = this.fixHooks[ type ]; if ( !fixHook ) { this.fixHooks[ type ] = fixHook = rmouseEvent.test( type ) ? this.mouseHooks : rkeyEvent.test( type ) ? this.keyHooks : {}; } copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; event = new jQuery.Event( originalEvent ); i = copy.length; while ( i-- ) { prop = copy[ i ]; event[ prop ] = originalEvent[ prop ]; } // Support: IE<9 // Fix target property (#1925) if ( !event.target ) { event.target = originalEvent.srcElement || document; } // Support: Chrome 23+, Safari? // Target should not be a text node (#504, #13143) if ( event.target.nodeType === 3 ) { event.target = event.target.parentNode; } // Support: IE<9 // For mouse/key events, metaKey==false if it's undefined (#3368, #11328) event.metaKey = !!event.metaKey; return fixHook.filter ? fixHook.filter( event, originalEvent ) : event; }, // Includes some event props shared by KeyEvent and MouseEvent props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "), fixHooks: {}, keyHooks: { props: "char charCode key keyCode".split(" "), filter: function( event, original ) { // Add which for key events if ( event.which == null ) { event.which = original.charCode != null ? original.charCode : original.keyCode; } return event; } }, mouseHooks: { props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "), filter: function( event, original ) { var body, eventDoc, doc, button = original.button, fromElement = original.fromElement; // Calculate pageX/Y if missing and clientX/Y available if ( event.pageX == null && original.clientX != null ) { eventDoc = event.target.ownerDocument || document; doc = eventDoc.documentElement; body = eventDoc.body; event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); } // Add relatedTarget, if necessary if ( !event.relatedTarget && fromElement ) { event.relatedTarget = fromElement === event.target ? original.toElement : fromElement; } // Add which for click: 1 === left; 2 === middle; 3 === right // Note: button is not normalized, so don't use it if ( !event.which && button !== undefined ) { event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); } return event; } }, special: { load: { // Prevent triggered image.load events from bubbling to window.load noBubble: true }, focus: { // Fire native event if possible so blur/focus sequence is correct trigger: function() { if ( this !== safeActiveElement() && this.focus ) { try { this.focus(); return false; } catch ( e ) { // Support: IE<9 // If we error on focus to hidden element (#1486, #12518), // let .trigger() run the handlers } } }, delegateType: "focusin" }, blur: { trigger: function() { if ( this === safeActiveElement() && this.blur ) { this.blur(); return false; } }, delegateType: "focusout" }, click: { // For checkbox, fire native event so checked state will be right trigger: function() { if ( jQuery.nodeName( this, "input" ) && this.type === "checkbox" && this.click ) { this.click(); return false; } }, // For cross-browser consistency, don't fire native .click() on links _default: function( event ) { return jQuery.nodeName( event.target, "a" ); } }, beforeunload: { postDispatch: function( event ) { // Even when returnValue equals to undefined Firefox will still show alert if ( event.result !== undefined ) { event.originalEvent.returnValue = event.result; } } } }, simulate: function( type, elem, event, bubble ) { // Piggyback on a donor event to simulate a different one. // Fake originalEvent to avoid donor's stopPropagation, but if the // simulated event prevents default then we do the same on the donor. var e = jQuery.extend( new jQuery.Event(), event, { type: type, isSimulated: true, originalEvent: {} } ); if ( bubble ) { jQuery.event.trigger( e, null, elem ); } else { jQuery.event.dispatch.call( elem, e ); } if ( e.isDefaultPrevented() ) { event.preventDefault(); } } }; jQuery.removeEvent = document.removeEventListener ? function( elem, type, handle ) { if ( elem.removeEventListener ) { elem.removeEventListener( type, handle, false ); } } : function( elem, type, handle ) { var name = "on" + type; if ( elem.detachEvent ) { // #8545, #7054, preventing memory leaks for custom events in IE6-8 // detachEvent needed property on element, by name of that event, to properly expose it to GC if ( typeof elem[ name ] === core_strundefined ) { elem[ name ] = null; } elem.detachEvent( name, handle ); } }; jQuery.Event = function( src, props ) { // Allow instantiation without the 'new' keyword if ( !(this instanceof jQuery.Event) ) { return new jQuery.Event( src, props ); } // Event object if ( src && src.type ) { this.originalEvent = src; this.type = src.type; // Events bubbling up the document may have been marked as prevented // by a handler lower down the tree; reflect the correct value. this.isDefaultPrevented = ( src.defaultPrevented || src.returnValue === false || src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse; // Event type } else { this.type = src; } // Put explicitly provided properties onto the event object if ( props ) { jQuery.extend( this, props ); } // Create a timestamp if incoming event doesn't have one this.timeStamp = src && src.timeStamp || jQuery.now(); // Mark it as fixed this[ jQuery.expando ] = true; }; // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding // http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html jQuery.Event.prototype = { isDefaultPrevented: returnFalse, isPropagationStopped: returnFalse, isImmediatePropagationStopped: returnFalse, preventDefault: function() { var e = this.originalEvent; this.isDefaultPrevented = returnTrue; if ( !e ) { return; } // If preventDefault exists, run it on the original event if ( e.preventDefault ) { e.preventDefault(); // Support: IE // Otherwise set the returnValue property of the original event to false } else { e.returnValue = false; } }, stopPropagation: function() { var e = this.originalEvent; this.isPropagationStopped = returnTrue; if ( !e ) { return; } // If stopPropagation exists, run it on the original event if ( e.stopPropagation ) { e.stopPropagation(); } // Support: IE // Set the cancelBubble property of the original event to true e.cancelBubble = true; }, stopImmediatePropagation: function() { this.isImmediatePropagationStopped = returnTrue; this.stopPropagation(); } }; // Create mouseenter/leave events using mouseover/out and event-time checks jQuery.each({ mouseenter: "mouseover", mouseleave: "mouseout" }, function( orig, fix ) { jQuery.event.special[ orig ] = { delegateType: fix, bindType: fix, handle: function( event ) { var ret, target = this, related = event.relatedTarget, handleObj = event.handleObj; // For mousenter/leave call the handler if related is outside the target. // NB: No relatedTarget if the mouse left/entered the browser window if ( !related || (related !== target && !jQuery.contains( target, related )) ) { event.type = handleObj.origType; ret = handleObj.handler.apply( this, arguments ); event.type = fix; } return ret; } }; }); // IE submit delegation if ( !jQuery.support.submitBubbles ) { jQuery.event.special.submit = { setup: function() { // Only need this for delegated form submit events if ( jQuery.nodeName( this, "form" ) ) { return false; } // Lazy-add a submit handler when a descendant form may potentially be submitted jQuery.event.add( this, "click._submit keypress._submit", function( e ) { // Node name check avoids a VML-related crash in IE (#9807) var elem = e.target, form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined; if ( form && !jQuery._data( form, "submitBubbles" ) ) { jQuery.event.add( form, "submit._submit", function( event ) { event._submit_bubble = true; }); jQuery._data( form, "submitBubbles", true ); } }); // return undefined since we don't need an event listener }, postDispatch: function( event ) { // If form was submitted by the user, bubble the event up the tree if ( event._submit_bubble ) { delete event._submit_bubble; if ( this.parentNode && !event.isTrigger ) { jQuery.event.simulate( "submit", this.parentNode, event, true ); } } }, teardown: function() { // Only need this for delegated form submit events if ( jQuery.nodeName( this, "form" ) ) { return false; } // Remove delegated handlers; cleanData eventually reaps submit handlers attached above jQuery.event.remove( this, "._submit" ); } }; } // IE change delegation and checkbox/radio fix if ( !jQuery.support.changeBubbles ) { jQuery.event.special.change = { setup: function() { if ( rformElems.test( this.nodeName ) ) { // IE doesn't fire change on a check/radio until blur; trigger it on click // after a propertychange. Eat the blur-change in special.change.handle. // This still fires onchange a second time for check/radio after blur. if ( this.type === "checkbox" || this.type === "radio" ) { jQuery.event.add( this, "propertychange._change", function( event ) { if ( event.originalEvent.propertyName === "checked" ) { this._just_changed = true; } }); jQuery.event.add( this, "click._change", function( event ) { if ( this._just_changed && !event.isTrigger ) { this._just_changed = false; } // Allow triggered, simulated change events (#11500) jQuery.event.simulate( "change", this, event, true ); }); } return false; } // Delegated event; lazy-add a change handler on descendant inputs jQuery.event.add( this, "beforeactivate._change", function( e ) { var elem = e.target; if ( rformElems.test( elem.nodeName ) && !jQuery._data( elem, "changeBubbles" ) ) { jQuery.event.add( elem, "change._change", function( event ) { if ( this.parentNode && !event.isSimulated && !event.isTrigger ) { jQuery.event.simulate( "change", this.parentNode, event, true ); } }); jQuery._data( elem, "changeBubbles", true ); } }); }, handle: function( event ) { var elem = event.target; // Swallow native change events from checkbox/radio, we already triggered them above if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) { return event.handleObj.handler.apply( this, arguments ); } }, teardown: function() { jQuery.event.remove( this, "._change" ); return !rformElems.test( this.nodeName ); } }; } // Create "bubbling" focus and blur events if ( !jQuery.support.focusinBubbles ) { jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { // Attach a single capturing handler while someone wants focusin/focusout var attaches = 0, handler = function( event ) { jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); }; jQuery.event.special[ fix ] = { setup: function() { if ( attaches++ === 0 ) { document.addEventListener( orig, handler, true ); } }, teardown: function() { if ( --attaches === 0 ) { document.removeEventListener( orig, handler, true ); } } }; }); } jQuery.fn.extend({ on: function( types, selector, data, fn, /*INTERNAL*/ one ) { var type, origFn; // Types can be a map of types/handlers if ( typeof types === "object" ) { // ( types-Object, selector, data ) if ( typeof selector !== "string" ) { // ( types-Object, data ) data = data || selector; selector = undefined; } for ( type in types ) { this.on( type, selector, data, types[ type ], one ); } return this; } if ( data == null && fn == null ) { // ( types, fn ) fn = selector; data = selector = undefined; } else if ( fn == null ) { if ( typeof selector === "string" ) { // ( types, selector, fn ) fn = data; data = undefined; } else { // ( types, data, fn ) fn = data; data = selector; selector = undefined; } } if ( fn === false ) { fn = returnFalse; } else if ( !fn ) { return this; } if ( one === 1 ) { origFn = fn; fn = function( event ) { // Can use an empty set, since event contains the info jQuery().off( event ); return origFn.apply( this, arguments ); }; // Use same guid so caller can remove using origFn fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); } return this.each( function() { jQuery.event.add( this, types, fn, data, selector ); }); }, one: function( types, selector, data, fn ) { return this.on( types, selector, data, fn, 1 ); }, off: function( types, selector, fn ) { var handleObj, type; if ( types && types.preventDefault && types.handleObj ) { // ( event ) dispatched jQuery.Event handleObj = types.handleObj; jQuery( types.delegateTarget ).off( handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, handleObj.selector, handleObj.handler ); return this; } if ( typeof types === "object" ) { // ( types-object [, selector] ) for ( type in types ) { this.off( type, selector, types[ type ] ); } return this; } if ( selector === false || typeof selector === "function" ) { // ( types [, fn] ) fn = selector; selector = undefined; } if ( fn === false ) { fn = returnFalse; } return this.each(function() { jQuery.event.remove( this, types, fn, selector ); }); }, trigger: function( type, data ) { return this.each(function() { jQuery.event.trigger( type, data, this ); }); }, triggerHandler: function( type, data ) { var elem = this[0]; if ( elem ) { return jQuery.event.trigger( type, data, elem, true ); } } }); var isSimple = /^.[^:#\[\.,]*$/, rparentsprev = /^(?:parents|prev(?:Until|All))/, rneedsContext = jQuery.expr.match.needsContext, // methods guaranteed to produce a unique set when starting from a unique set guaranteedUnique = { children: true, contents: true, next: true, prev: true }; jQuery.fn.extend({ find: function( selector ) { var i, ret = [], self = this, len = self.length; if ( typeof selector !== "string" ) { return this.pushStack( jQuery( selector ).filter(function() { for ( i = 0; i < len; i++ ) { if ( jQuery.contains( self[ i ], this ) ) { return true; } } }) ); } for ( i = 0; i < len; i++ ) { jQuery.find( selector, self[ i ], ret ); } // Needed because $( selector, context ) becomes $( context ).find( selector ) ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret ); ret.selector = this.selector ? this.selector + " " + selector : selector; return ret; }, has: function( target ) { var i, targets = jQuery( target, this ), len = targets.length; return this.filter(function() { for ( i = 0; i < len; i++ ) { if ( jQuery.contains( this, targets[i] ) ) { return true; } } }); }, not: function( selector ) { return this.pushStack( winnow(this, selector || [], true) ); }, filter: function( selector ) { return this.pushStack( winnow(this, selector || [], false) ); }, is: function( selector ) { return !!winnow( this, // If this is a positional/relative selector, check membership in the returned set // so $("p:first").is("p:last") won't return true for a doc with two "p". typeof selector === "string" && rneedsContext.test( selector ) ? jQuery( selector ) : selector || [], false ).length; }, closest: function( selectors, context ) { var cur, i = 0, l = this.length, ret = [], pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ? jQuery( selectors, context || this.context ) : 0; for ( ; i < l; i++ ) { for ( cur = this[i]; cur && cur !== context; cur = cur.parentNode ) { // Always skip document fragments if ( cur.nodeType < 11 && (pos ? pos.index(cur) > -1 : // Don't pass non-elements to Sizzle cur.nodeType === 1 && jQuery.find.matchesSelector(cur, selectors)) ) { cur = ret.push( cur ); break; } } } return this.pushStack( ret.length > 1 ? jQuery.unique( ret ) : ret ); }, // Determine the position of an element within // the matched set of elements index: function( elem ) { // No argument, return index in parent if ( !elem ) { return ( this[0] && this[0].parentNode ) ? this.first().prevAll().length : -1; } // index in selector if ( typeof elem === "string" ) { return jQuery.inArray( this[0], jQuery( elem ) ); } // Locate the position of the desired element return jQuery.inArray( // If it receives a jQuery object, the first element is used elem.jquery ? elem[0] : elem, this ); }, add: function( selector, context ) { var set = typeof selector === "string" ? jQuery( selector, context ) : jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ), all = jQuery.merge( this.get(), set ); return this.pushStack( jQuery.unique(all) ); }, addBack: function( selector ) { return this.add( selector == null ? this.prevObject : this.prevObject.filter(selector) ); } }); function sibling( cur, dir ) { do { cur = cur[ dir ]; } while ( cur && cur.nodeType !== 1 ); return cur; } jQuery.each({ parent: function( elem ) { var parent = elem.parentNode; return parent && parent.nodeType !== 11 ? parent : null; }, parents: function( elem ) { return jQuery.dir( elem, "parentNode" ); }, parentsUntil: function( elem, i, until ) { return jQuery.dir( elem, "parentNode", until ); }, next: function( elem ) { return sibling( elem, "nextSibling" ); }, prev: function( elem ) { return sibling( elem, "previousSibling" ); }, nextAll: function( elem ) { return jQuery.dir( elem, "nextSibling" ); }, prevAll: function( elem ) { return jQuery.dir( elem, "previousSibling" ); }, nextUntil: function( elem, i, until ) { return jQuery.dir( elem, "nextSibling", until ); }, prevUntil: function( elem, i, until ) { return jQuery.dir( elem, "previousSibling", until ); }, siblings: function( elem ) { return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem ); }, children: function( elem ) { return jQuery.sibling( elem.firstChild ); }, contents: function( elem ) { return jQuery.nodeName( elem, "iframe" ) ? elem.contentDocument || elem.contentWindow.document : jQuery.merge( [], elem.childNodes ); } }, function( name, fn ) { jQuery.fn[ name ] = function( until, selector ) { var ret = jQuery.map( this, fn, until ); if ( name.slice( -5 ) !== "Until" ) { selector = until; } if ( selector && typeof selector === "string" ) { ret = jQuery.filter( selector, ret ); } if ( this.length > 1 ) { // Remove duplicates if ( !guaranteedUnique[ name ] ) { ret = jQuery.unique( ret ); } // Reverse order for parents* and prev-derivatives if ( rparentsprev.test( name ) ) { ret = ret.reverse(); } } return this.pushStack( ret ); }; }); jQuery.extend({ filter: function( expr, elems, not ) { var elem = elems[ 0 ]; if ( not ) { expr = ":not(" + expr + ")"; } return elems.length === 1 && elem.nodeType === 1 ? jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] : jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) { return elem.nodeType === 1; })); }, dir: function( elem, dir, until ) { var matched = [], cur = elem[ dir ]; while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) { if ( cur.nodeType === 1 ) { matched.push( cur ); } cur = cur[dir]; } return matched; }, sibling: function( n, elem ) { var r = []; for ( ; n; n = n.nextSibling ) { if ( n.nodeType === 1 && n !== elem ) { r.push( n ); } } return r; } }); // Implement the identical functionality for filter and not function winnow( elements, qualifier, not ) { if ( jQuery.isFunction( qualifier ) ) { return jQuery.grep( elements, function( elem, i ) { /* jshint -W018 */ return !!qualifier.call( elem, i, elem ) !== not; }); } if ( qualifier.nodeType ) { return jQuery.grep( elements, function( elem ) { return ( elem === qualifier ) !== not; }); } if ( typeof qualifier === "string" ) { if ( isSimple.test( qualifier ) ) { return jQuery.filter( qualifier, elements, not ); } qualifier = jQuery.filter( qualifier, elements ); } return jQuery.grep( elements, function( elem ) { return ( jQuery.inArray( elem, qualifier ) >= 0 ) !== not; }); } function createSafeFragment( document ) { var list = nodeNames.split( "|" ), safeFrag = document.createDocumentFragment(); if ( safeFrag.createElement ) { while ( list.length ) { safeFrag.createElement( list.pop() ); } } return safeFrag; } var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" + "header|hgroup|mark|meter|nav|output|progress|section|summary|time|video", rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g, rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"), rleadingWhitespace = /^\s+/, rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, rtagName = /<([\w:]+)/, rtbody = /<tbody/i, rhtml = /<|&#?\w+;/, rnoInnerhtml = /<(?:script|style|link)/i, manipulation_rcheckableType = /^(?:checkbox|radio)$/i, // checked="checked" or checked rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, rscriptType = /^$|\/(?:java|ecma)script/i, rscriptTypeMasked = /^true\/(.*)/, rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g, // We have to close these tags to support XHTML (#13200) wrapMap = { option: [ 1, "<select multiple='multiple'>", "</select>" ], legend: [ 1, "<fieldset>", "</fieldset>" ], area: [ 1, "<map>", "</map>" ], param: [ 1, "<object>", "</object>" ], thead: [ 1, "<table>", "</table>" ], tr: [ 2, "<table><tbody>", "</tbody></table>" ], col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ], td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ], // IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags, // unless wrapped in a div with non-breaking characters in front of it. _default: jQuery.support.htmlSerialize ? [ 0, "", "" ] : [ 1, "X<div>", "</div>" ] }, safeFragment = createSafeFragment( document ), fragmentDiv = safeFragment.appendChild( document.createElement("div") ); wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; jQuery.fn.extend({ text: function( value ) { return jQuery.access( this, function( value ) { return value === undefined ? jQuery.text( this ) : this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) ); }, null, value, arguments.length ); }, append: function() { return this.domManip( arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.appendChild( elem ); } }); }, prepend: function() { return this.domManip( arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.insertBefore( elem, target.firstChild ); } }); }, before: function() { return this.domManip( arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this ); } }); }, after: function() { return this.domManip( arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this.nextSibling ); } }); }, // keepData is for internal use only--do not document remove: function( selector, keepData ) { var elem, elems = selector ? jQuery.filter( selector, this ) : this, i = 0; for ( ; (elem = elems[i]) != null; i++ ) { if ( !keepData && elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem ) ); } if ( elem.parentNode ) { if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) { setGlobalEval( getAll( elem, "script" ) ); } elem.parentNode.removeChild( elem ); } } return this; }, empty: function() { var elem, i = 0; for ( ; (elem = this[i]) != null; i++ ) { // Remove element nodes and prevent memory leaks if ( elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem, false ) ); } // Remove any remaining nodes while ( elem.firstChild ) { elem.removeChild( elem.firstChild ); } // If this is a select, ensure that it displays empty (#12336) // Support: IE<9 if ( elem.options && jQuery.nodeName( elem, "select" ) ) { elem.options.length = 0; } } return this; }, clone: function( dataAndEvents, deepDataAndEvents ) { dataAndEvents = dataAndEvents == null ? false : dataAndEvents; deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; return this.map( function () { return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); }); }, html: function( value ) { return jQuery.access( this, function( value ) { var elem = this[0] || {}, i = 0, l = this.length; if ( value === undefined ) { return elem.nodeType === 1 ? elem.innerHTML.replace( rinlinejQuery, "" ) : undefined; } // See if we can take a shortcut and just use innerHTML if ( typeof value === "string" && !rnoInnerhtml.test( value ) && ( jQuery.support.htmlSerialize || !rnoshimcache.test( value ) ) && ( jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value ) ) && !wrapMap[ ( rtagName.exec( value ) || ["", ""] )[1].toLowerCase() ] ) { value = value.replace( rxhtmlTag, "<$1></$2>" ); try { for (; i < l; i++ ) { // Remove element nodes and prevent memory leaks elem = this[i] || {}; if ( elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem, false ) ); elem.innerHTML = value; } } elem = 0; // If using innerHTML throws an exception, use the fallback method } catch(e) {} } if ( elem ) { this.empty().append( value ); } }, null, value, arguments.length ); }, replaceWith: function() { var // Snapshot the DOM in case .domManip sweeps something relevant into its fragment args = jQuery.map( this, function( elem ) { return [ elem.nextSibling, elem.parentNode ]; }), i = 0; // Make the changes, replacing each context element with the new content this.domManip( arguments, function( elem ) { var next = args[ i++ ], parent = args[ i++ ]; if ( parent ) { // Don't use the snapshot next if it has moved (#13810) if ( next && next.parentNode !== parent ) { next = this.nextSibling; } jQuery( this ).remove(); parent.insertBefore( elem, next ); } // Allow new content to include elements from the context set }, true ); // Force removal if there was no new content (e.g., from empty arguments) return i ? this : this.remove(); }, detach: function( selector ) { return this.remove( selector, true ); }, domManip: function( args, callback, allowIntersection ) { // Flatten any nested arrays args = core_concat.apply( [], args ); var first, node, hasScripts, scripts, doc, fragment, i = 0, l = this.length, set = this, iNoClone = l - 1, value = args[0], isFunction = jQuery.isFunction( value ); // We can't cloneNode fragments that contain checked, in WebKit if ( isFunction || !( l <= 1 || typeof value !== "string" || jQuery.support.checkClone || !rchecked.test( value ) ) ) { return this.each(function( index ) { var self = set.eq( index ); if ( isFunction ) { args[0] = value.call( this, index, self.html() ); } self.domManip( args, callback, allowIntersection ); }); } if ( l ) { fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, !allowIntersection && this ); first = fragment.firstChild; if ( fragment.childNodes.length === 1 ) { fragment = first; } if ( first ) { scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); hasScripts = scripts.length; // Use the original fragment for the last item instead of the first because it can end up // being emptied incorrectly in certain situations (#8070). for ( ; i < l; i++ ) { node = fragment; if ( i !== iNoClone ) { node = jQuery.clone( node, true, true ); // Keep references to cloned scripts for later restoration if ( hasScripts ) { jQuery.merge( scripts, getAll( node, "script" ) ); } } callback.call( this[i], node, i ); } if ( hasScripts ) { doc = scripts[ scripts.length - 1 ].ownerDocument; // Reenable scripts jQuery.map( scripts, restoreScript ); // Evaluate executable scripts on first document insertion for ( i = 0; i < hasScripts; i++ ) { node = scripts[ i ]; if ( rscriptType.test( node.type || "" ) && !jQuery._data( node, "globalEval" ) && jQuery.contains( doc, node ) ) { if ( node.src ) { // Hope ajax is available... jQuery._evalUrl( node.src ); } else { jQuery.globalEval( ( node.text || node.textContent || node.innerHTML || "" ).replace( rcleanScript, "" ) ); } } } } // Fix #11809: Avoid leaking memory fragment = first = null; } } return this; } }); // Support: IE<8 // Manipulating tables requires a tbody function manipulationTarget( elem, content ) { return jQuery.nodeName( elem, "table" ) && jQuery.nodeName( content.nodeType === 1 ? content : content.firstChild, "tr" ) ? elem.getElementsByTagName("tbody")[0] || elem.appendChild( elem.ownerDocument.createElement("tbody") ) : elem; } // Replace/restore the type attribute of script elements for safe DOM manipulation function disableScript( elem ) { elem.type = (jQuery.find.attr( elem, "type" ) !== null) + "/" + elem.type; return elem; } function restoreScript( elem ) { var match = rscriptTypeMasked.exec( elem.type ); if ( match ) { elem.type = match[1]; } else { elem.removeAttribute("type"); } return elem; } // Mark scripts as having already been evaluated function setGlobalEval( elems, refElements ) { var elem, i = 0; for ( ; (elem = elems[i]) != null; i++ ) { jQuery._data( elem, "globalEval", !refElements || jQuery._data( refElements[i], "globalEval" ) ); } } function cloneCopyEvent( src, dest ) { if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) { return; } var type, i, l, oldData = jQuery._data( src ), curData = jQuery._data( dest, oldData ), events = oldData.events; if ( events ) { delete curData.handle; curData.events = {}; for ( type in events ) { for ( i = 0, l = events[ type ].length; i < l; i++ ) { jQuery.event.add( dest, type, events[ type ][ i ] ); } } } // make the cloned public data object a copy from the original if ( curData.data ) { curData.data = jQuery.extend( {}, curData.data ); } } function fixCloneNodeIssues( src, dest ) { var nodeName, e, data; // We do not need to do anything for non-Elements if ( dest.nodeType !== 1 ) { return; } nodeName = dest.nodeName.toLowerCase(); // IE6-8 copies events bound via attachEvent when using cloneNode. if ( !jQuery.support.noCloneEvent && dest[ jQuery.expando ] ) { data = jQuery._data( dest ); for ( e in data.events ) { jQuery.removeEvent( dest, e, data.handle ); } // Event data gets referenced instead of copied if the expando gets copied too dest.removeAttribute( jQuery.expando ); } // IE blanks contents when cloning scripts, and tries to evaluate newly-set text if ( nodeName === "script" && dest.text !== src.text ) { disableScript( dest ).text = src.text; restoreScript( dest ); // IE6-10 improperly clones children of object elements using classid. // IE10 throws NoModificationAllowedError if parent is null, #12132. } else if ( nodeName === "object" ) { if ( dest.parentNode ) { dest.outerHTML = src.outerHTML; } // This path appears unavoidable for IE9. When cloning an object // element in IE9, the outerHTML strategy above is not sufficient. // If the src has innerHTML and the destination does not, // copy the src.innerHTML into the dest.innerHTML. #10324 if ( jQuery.support.html5Clone && ( src.innerHTML && !jQuery.trim(dest.innerHTML) ) ) { dest.innerHTML = src.innerHTML; } } else if ( nodeName === "input" && manipulation_rcheckableType.test( src.type ) ) { // IE6-8 fails to persist the checked state of a cloned checkbox // or radio button. Worse, IE6-7 fail to give the cloned element // a checked appearance if the defaultChecked value isn't also set dest.defaultChecked = dest.checked = src.checked; // IE6-7 get confused and end up setting the value of a cloned // checkbox/radio button to an empty string instead of "on" if ( dest.value !== src.value ) { dest.value = src.value; } // IE6-8 fails to return the selected option to the default selected // state when cloning options } else if ( nodeName === "option" ) { dest.defaultSelected = dest.selected = src.defaultSelected; // IE6-8 fails to set the defaultValue to the correct value when // cloning other types of input fields } else if ( nodeName === "input" || nodeName === "textarea" ) { dest.defaultValue = src.defaultValue; } } jQuery.each({ appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function( name, original ) { jQuery.fn[ name ] = function( selector ) { var elems, i = 0, ret = [], insert = jQuery( selector ), last = insert.length - 1; for ( ; i <= last; i++ ) { elems = i === last ? this : this.clone(true); jQuery( insert[i] )[ original ]( elems ); // Modern browsers can apply jQuery collections as arrays, but oldIE needs a .get() core_push.apply( ret, elems.get() ); } return this.pushStack( ret ); }; }); function getAll( context, tag ) { var elems, elem, i = 0, found = typeof context.getElementsByTagName !== core_strundefined ? context.getElementsByTagName( tag || "*" ) : typeof context.querySelectorAll !== core_strundefined ? context.querySelectorAll( tag || "*" ) : undefined; if ( !found ) { for ( found = [], elems = context.childNodes || context; (elem = elems[i]) != null; i++ ) { if ( !tag || jQuery.nodeName( elem, tag ) ) { found.push( elem ); } else { jQuery.merge( found, getAll( elem, tag ) ); } } } return tag === undefined || tag && jQuery.nodeName( context, tag ) ? jQuery.merge( [ context ], found ) : found; } // Used in buildFragment, fixes the defaultChecked property function fixDefaultChecked( elem ) { if ( manipulation_rcheckableType.test( elem.type ) ) { elem.defaultChecked = elem.checked; } } jQuery.extend({ clone: function( elem, dataAndEvents, deepDataAndEvents ) { var destElements, node, clone, i, srcElements, inPage = jQuery.contains( elem.ownerDocument, elem ); if ( jQuery.support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ) { clone = elem.cloneNode( true ); // IE<=8 does not properly clone detached, unknown element nodes } else { fragmentDiv.innerHTML = elem.outerHTML; fragmentDiv.removeChild( clone = fragmentDiv.firstChild ); } if ( (!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) && (elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) { // We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2 destElements = getAll( clone ); srcElements = getAll( elem ); // Fix all IE cloning issues for ( i = 0; (node = srcElements[i]) != null; ++i ) { // Ensure that the destination node is not null; Fixes #9587 if ( destElements[i] ) { fixCloneNodeIssues( node, destElements[i] ); } } } // Copy the events from the original to the clone if ( dataAndEvents ) { if ( deepDataAndEvents ) { srcElements = srcElements || getAll( elem ); destElements = destElements || getAll( clone ); for ( i = 0; (node = srcElements[i]) != null; i++ ) { cloneCopyEvent( node, destElements[i] ); } } else { cloneCopyEvent( elem, clone ); } } // Preserve script evaluation history destElements = getAll( clone, "script" ); if ( destElements.length > 0 ) { setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); } destElements = srcElements = node = null; // Return the cloned set return clone; }, buildFragment: function( elems, context, scripts, selection ) { var j, elem, contains, tmp, tag, tbody, wrap, l = elems.length, // Ensure a safe fragment safe = createSafeFragment( context ), nodes = [], i = 0; for ( ; i < l; i++ ) { elem = elems[ i ]; if ( elem || elem === 0 ) { // Add nodes directly if ( jQuery.type( elem ) === "object" ) { jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); // Convert non-html into a text node } else if ( !rhtml.test( elem ) ) { nodes.push( context.createTextNode( elem ) ); // Convert html into DOM nodes } else { tmp = tmp || safe.appendChild( context.createElement("div") ); // Deserialize a standard representation tag = ( rtagName.exec( elem ) || ["", ""] )[1].toLowerCase(); wrap = wrapMap[ tag ] || wrapMap._default; tmp.innerHTML = wrap[1] + elem.replace( rxhtmlTag, "<$1></$2>" ) + wrap[2]; // Descend through wrappers to the right content j = wrap[0]; while ( j-- ) { tmp = tmp.lastChild; } // Manually add leading whitespace removed by IE if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) { nodes.push( context.createTextNode( rleadingWhitespace.exec( elem )[0] ) ); } // Remove IE's autoinserted <tbody> from table fragments if ( !jQuery.support.tbody ) { // String was a <table>, *may* have spurious <tbody> elem = tag === "table" && !rtbody.test( elem ) ? tmp.firstChild : // String was a bare <thead> or <tfoot> wrap[1] === "<table>" && !rtbody.test( elem ) ? tmp : 0; j = elem && elem.childNodes.length; while ( j-- ) { if ( jQuery.nodeName( (tbody = elem.childNodes[j]), "tbody" ) && !tbody.childNodes.length ) { elem.removeChild( tbody ); } } } jQuery.merge( nodes, tmp.childNodes ); // Fix #12392 for WebKit and IE > 9 tmp.textContent = ""; // Fix #12392 for oldIE while ( tmp.firstChild ) { tmp.removeChild( tmp.firstChild ); } // Remember the top-level container for proper cleanup tmp = safe.lastChild; } } } // Fix #11356: Clear elements from fragment if ( tmp ) { safe.removeChild( tmp ); } // Reset defaultChecked for any radios and checkboxes // about to be appended to the DOM in IE 6/7 (#8060) if ( !jQuery.support.appendChecked ) { jQuery.grep( getAll( nodes, "input" ), fixDefaultChecked ); } i = 0; while ( (elem = nodes[ i++ ]) ) { // #4087 - If origin and destination elements are the same, and this is // that element, do not do anything if ( selection && jQuery.inArray( elem, selection ) !== -1 ) { continue; } contains = jQuery.contains( elem.ownerDocument, elem ); // Append to fragment tmp = getAll( safe.appendChild( elem ), "script" ); // Preserve script evaluation history if ( contains ) { setGlobalEval( tmp ); } // Capture executables if ( scripts ) { j = 0; while ( (elem = tmp[ j++ ]) ) { if ( rscriptType.test( elem.type || "" ) ) { scripts.push( elem ); } } } } tmp = null; return safe; }, cleanData: function( elems, /* internal */ acceptData ) { var elem, type, id, data, i = 0, internalKey = jQuery.expando, cache = jQuery.cache, deleteExpando = jQuery.support.deleteExpando, special = jQuery.event.special; for ( ; (elem = elems[i]) != null; i++ ) { if ( acceptData || jQuery.acceptData( elem ) ) { id = elem[ internalKey ]; data = id && cache[ id ]; if ( data ) { if ( data.events ) { for ( type in data.events ) { if ( special[ type ] ) { jQuery.event.remove( elem, type ); // This is a shortcut to avoid jQuery.event.remove's overhead } else { jQuery.removeEvent( elem, type, data.handle ); } } } // Remove cache only if it was not already removed by jQuery.event.remove if ( cache[ id ] ) { delete cache[ id ]; // IE does not allow us to delete expando properties from nodes, // nor does it have a removeAttribute function on Document nodes; // we must handle all of these cases if ( deleteExpando ) { delete elem[ internalKey ]; } else if ( typeof elem.removeAttribute !== core_strundefined ) { elem.removeAttribute( internalKey ); } else { elem[ internalKey ] = null; } core_deletedIds.push( id ); } } } } }, _evalUrl: function( url ) { return jQuery.ajax({ url: url, type: "GET", dataType: "script", async: false, global: false, "throws": true }); } }); jQuery.fn.extend({ wrapAll: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function(i) { jQuery(this).wrapAll( html.call(this, i) ); }); } if ( this[0] ) { // The elements to wrap the target around var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true); if ( this[0].parentNode ) { wrap.insertBefore( this[0] ); } wrap.map(function() { var elem = this; while ( elem.firstChild && elem.firstChild.nodeType === 1 ) { elem = elem.firstChild; } return elem; }).append( this ); } return this; }, wrapInner: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function(i) { jQuery(this).wrapInner( html.call(this, i) ); }); } return this.each(function() { var self = jQuery( this ), contents = self.contents(); if ( contents.length ) { contents.wrapAll( html ); } else { self.append( html ); } }); }, wrap: function( html ) { var isFunction = jQuery.isFunction( html ); return this.each(function(i) { jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html ); }); }, unwrap: function() { return this.parent().each(function() { if ( !jQuery.nodeName( this, "body" ) ) { jQuery( this ).replaceWith( this.childNodes ); } }).end(); } }); var iframe, getStyles, curCSS, ralpha = /alpha\([^)]*\)/i, ropacity = /opacity\s*=\s*([^)]*)/, rposition = /^(top|right|bottom|left)$/, // swappable if display is none or starts with table except "table", "table-cell", or "table-caption" // see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display rdisplayswap = /^(none|table(?!-c[ea]).+)/, rmargin = /^margin/, rnumsplit = new RegExp( "^(" + core_pnum + ")(.*)$", "i" ), rnumnonpx = new RegExp( "^(" + core_pnum + ")(?!px)[a-z%]+$", "i" ), rrelNum = new RegExp( "^([+-])=(" + core_pnum + ")", "i" ), elemdisplay = { BODY: "block" }, cssShow = { position: "absolute", visibility: "hidden", display: "block" }, cssNormalTransform = { letterSpacing: 0, fontWeight: 400 }, cssExpand = [ "Top", "Right", "Bottom", "Left" ], cssPrefixes = [ "Webkit", "O", "Moz", "ms" ]; // return a css property mapped to a potentially vendor prefixed property function vendorPropName( style, name ) { // shortcut for names that are not vendor prefixed if ( name in style ) { return name; } // check for vendor prefixed names var capName = name.charAt(0).toUpperCase() + name.slice(1), origName = name, i = cssPrefixes.length; while ( i-- ) { name = cssPrefixes[ i ] + capName; if ( name in style ) { return name; } } return origName; } function isHidden( elem, el ) { // isHidden might be called from jQuery#filter function; // in that case, element will be second argument elem = el || elem; return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem ); } function showHide( elements, show ) { var display, elem, hidden, values = [], index = 0, length = elements.length; for ( ; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } values[ index ] = jQuery._data( elem, "olddisplay" ); display = elem.style.display; if ( show ) { // Reset the inline display of this element to learn if it is // being hidden by cascaded rules or not if ( !values[ index ] && display === "none" ) { elem.style.display = ""; } // Set elements which have been overridden with display: none // in a stylesheet to whatever the default browser style is // for such an element if ( elem.style.display === "" && isHidden( elem ) ) { values[ index ] = jQuery._data( elem, "olddisplay", css_defaultDisplay(elem.nodeName) ); } } else { if ( !values[ index ] ) { hidden = isHidden( elem ); if ( display && display !== "none" || !hidden ) { jQuery._data( elem, "olddisplay", hidden ? display : jQuery.css( elem, "display" ) ); } } } } // Set the display of most of the elements in a second loop // to avoid the constant reflow for ( index = 0; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } if ( !show || elem.style.display === "none" || elem.style.display === "" ) { elem.style.display = show ? values[ index ] || "" : "none"; } } return elements; } jQuery.fn.extend({ css: function( name, value ) { return jQuery.access( this, function( elem, name, value ) { var len, styles, map = {}, i = 0; if ( jQuery.isArray( name ) ) { styles = getStyles( elem ); len = name.length; for ( ; i < len; i++ ) { map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles ); } return map; } return value !== undefined ? jQuery.style( elem, name, value ) : jQuery.css( elem, name ); }, name, value, arguments.length > 1 ); }, show: function() { return showHide( this, true ); }, hide: function() { return showHide( this ); }, toggle: function( state ) { var bool = typeof state === "boolean"; return this.each(function() { if ( bool ? state : isHidden( this ) ) { jQuery( this ).show(); } else { jQuery( this ).hide(); } }); } }); jQuery.extend({ // Add in style property hooks for overriding the default // behavior of getting and setting a style property cssHooks: { opacity: { get: function( elem, computed ) { if ( computed ) { // We should always get a number back from opacity var ret = curCSS( elem, "opacity" ); return ret === "" ? "1" : ret; } } } }, // Don't automatically add "px" to these possibly-unitless properties cssNumber: { "columnCount": true, "fillOpacity": true, "fontWeight": true, "lineHeight": true, "opacity": true, "orphans": true, "widows": true, "zIndex": true, "zoom": true }, // Add in properties whose names you wish to fix before // setting or getting the value cssProps: { // normalize float css property "float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat" }, // Get and set the style property on a DOM Node style: function( elem, name, value, extra ) { // Don't set styles on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { return; } // Make sure that we're working with the right name var ret, type, hooks, origName = jQuery.camelCase( name ), style = elem.style; name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) ); // gets hook for the prefixed version // followed by the unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // Check if we're setting a value if ( value !== undefined ) { type = typeof value; // convert relative number strings (+= or -=) to relative numbers. #7345 if ( type === "string" && (ret = rrelNum.exec( value )) ) { value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) ); // Fixes bug #9237 type = "number"; } // Make sure that NaN and null values aren't set. See: #7116 if ( value == null || type === "number" && isNaN( value ) ) { return; } // If a number was passed in, add 'px' to the (except for certain CSS properties) if ( type === "number" && !jQuery.cssNumber[ origName ] ) { value += "px"; } // Fixes #8908, it can be done more correctly by specifing setters in cssHooks, // but it would mean to define eight (for every problematic property) identical functions if ( !jQuery.support.clearCloneStyle && value === "" && name.indexOf("background") === 0 ) { style[ name ] = "inherit"; } // If a hook was provided, use that value, otherwise just set the specified value if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) { // Wrapped to prevent IE from throwing errors when 'invalid' values are provided // Fixes bug #5509 try { style[ name ] = value; } catch(e) {} } } else { // If a hook was provided get the non-computed value from there if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) { return ret; } // Otherwise just get the value from the style object return style[ name ]; } }, css: function( elem, name, extra, styles ) { var num, val, hooks, origName = jQuery.camelCase( name ); // Make sure that we're working with the right name name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) ); // gets hook for the prefixed version // followed by the unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // If a hook was provided get the computed value from there if ( hooks && "get" in hooks ) { val = hooks.get( elem, true, extra ); } // Otherwise, if a way to get the computed value exists, use that if ( val === undefined ) { val = curCSS( elem, name, styles ); } //convert "normal" to computed value if ( val === "normal" && name in cssNormalTransform ) { val = cssNormalTransform[ name ]; } // Return, converting to number if forced or a qualifier was provided and val looks numeric if ( extra === "" || extra ) { num = parseFloat( val ); return extra === true || jQuery.isNumeric( num ) ? num || 0 : val; } return val; } }); // NOTE: we've included the "window" in window.getComputedStyle // because jsdom on node.js will break without it. if ( window.getComputedStyle ) { getStyles = function( elem ) { return window.getComputedStyle( elem, null ); }; curCSS = function( elem, name, _computed ) { var width, minWidth, maxWidth, computed = _computed || getStyles( elem ), // getPropertyValue is only needed for .css('filter') in IE9, see #12537 ret = computed ? computed.getPropertyValue( name ) || computed[ name ] : undefined, style = elem.style; if ( computed ) { if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) { ret = jQuery.style( elem, name ); } // A tribute to the "awesome hack by Dean Edwards" // Chrome < 17 and Safari 5.0 uses "computed value" instead of "used value" for margin-right // Safari 5.1.7 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels // this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) { // Remember the original values width = style.width; minWidth = style.minWidth; maxWidth = style.maxWidth; // Put in the new values to get a computed value out style.minWidth = style.maxWidth = style.width = ret; ret = computed.width; // Revert the changed values style.width = width; style.minWidth = minWidth; style.maxWidth = maxWidth; } } return ret; }; } else if ( document.documentElement.currentStyle ) { getStyles = function( elem ) { return elem.currentStyle; }; curCSS = function( elem, name, _computed ) { var left, rs, rsLeft, computed = _computed || getStyles( elem ), ret = computed ? computed[ name ] : undefined, style = elem.style; // Avoid setting ret to empty string here // so we don't default to auto if ( ret == null && style && style[ name ] ) { ret = style[ name ]; } // From the awesome hack by Dean Edwards // http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291 // If we're not dealing with a regular pixel number // but a number that has a weird ending, we need to convert it to pixels // but not position css attributes, as those are proportional to the parent element instead // and we can't measure the parent instead because it might trigger a "stacking dolls" problem if ( rnumnonpx.test( ret ) && !rposition.test( name ) ) { // Remember the original values left = style.left; rs = elem.runtimeStyle; rsLeft = rs && rs.left; // Put in the new values to get a computed value out if ( rsLeft ) { rs.left = elem.currentStyle.left; } style.left = name === "fontSize" ? "1em" : ret; ret = style.pixelLeft + "px"; // Revert the changed values style.left = left; if ( rsLeft ) { rs.left = rsLeft; } } return ret === "" ? "auto" : ret; }; } function setPositiveNumber( elem, value, subtract ) { var matches = rnumsplit.exec( value ); return matches ? // Guard against undefined "subtract", e.g., when used as in cssHooks Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) : value; } function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) { var i = extra === ( isBorderBox ? "border" : "content" ) ? // If we already have the right measurement, avoid augmentation 4 : // Otherwise initialize for horizontal or vertical properties name === "width" ? 1 : 0, val = 0; for ( ; i < 4; i += 2 ) { // both box models exclude margin, so add it if we want it if ( extra === "margin" ) { val += jQuery.css( elem, extra + cssExpand[ i ], true, styles ); } if ( isBorderBox ) { // border-box includes padding, so remove it if we want content if ( extra === "content" ) { val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); } // at this point, extra isn't border nor margin, so remove border if ( extra !== "margin" ) { val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } else { // at this point, extra isn't content, so add padding val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); // at this point, extra isn't content nor padding, so add border if ( extra !== "padding" ) { val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } } return val; } function getWidthOrHeight( elem, name, extra ) { // Start with offset property, which is equivalent to the border-box value var valueIsBorderBox = true, val = name === "width" ? elem.offsetWidth : elem.offsetHeight, styles = getStyles( elem ), isBorderBox = jQuery.support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box"; // some non-html elements return undefined for offsetWidth, so check for null/undefined // svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285 // MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668 if ( val <= 0 || val == null ) { // Fall back to computed then uncomputed css if necessary val = curCSS( elem, name, styles ); if ( val < 0 || val == null ) { val = elem.style[ name ]; } // Computed unit is not pixels. Stop here and return. if ( rnumnonpx.test(val) ) { return val; } // we need the check for style in case a browser which returns unreliable values // for getComputedStyle silently falls back to the reliable elem.style valueIsBorderBox = isBorderBox && ( jQuery.support.boxSizingReliable || val === elem.style[ name ] ); // Normalize "", auto, and prepare for extra val = parseFloat( val ) || 0; } // use the active box-sizing model to add/subtract irrelevant styles return ( val + augmentWidthOrHeight( elem, name, extra || ( isBorderBox ? "border" : "content" ), valueIsBorderBox, styles ) ) + "px"; } // Try to determine the default display value of an element function css_defaultDisplay( nodeName ) { var doc = document, display = elemdisplay[ nodeName ]; if ( !display ) { display = actualDisplay( nodeName, doc ); // If the simple way fails, read from inside an iframe if ( display === "none" || !display ) { // Use the already-created iframe if possible iframe = ( iframe || jQuery("<iframe frameborder='0' width='0' height='0'/>") .css( "cssText", "display:block !important" ) ).appendTo( doc.documentElement ); // Always write a new HTML skeleton so Webkit and Firefox don't choke on reuse doc = ( iframe[0].contentWindow || iframe[0].contentDocument ).document; doc.write("<!doctype html><html><body>"); doc.close(); display = actualDisplay( nodeName, doc ); iframe.detach(); } // Store the correct default display elemdisplay[ nodeName ] = display; } return display; } // Called ONLY from within css_defaultDisplay function actualDisplay( name, doc ) { var elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ), display = jQuery.css( elem[0], "display" ); elem.remove(); return display; } jQuery.each([ "height", "width" ], function( i, name ) { jQuery.cssHooks[ name ] = { get: function( elem, computed, extra ) { if ( computed ) { // certain elements can have dimension info if we invisibly show them // however, it must have a current display style that would benefit from this return elem.offsetWidth === 0 && rdisplayswap.test( jQuery.css( elem, "display" ) ) ? jQuery.swap( elem, cssShow, function() { return getWidthOrHeight( elem, name, extra ); }) : getWidthOrHeight( elem, name, extra ); } }, set: function( elem, value, extra ) { var styles = extra && getStyles( elem ); return setPositiveNumber( elem, value, extra ? augmentWidthOrHeight( elem, name, extra, jQuery.support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box", styles ) : 0 ); } }; }); if ( !jQuery.support.opacity ) { jQuery.cssHooks.opacity = { get: function( elem, computed ) { // IE uses filters for opacity return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ? ( 0.01 * parseFloat( RegExp.$1 ) ) + "" : computed ? "1" : ""; }, set: function( elem, value ) { var style = elem.style, currentStyle = elem.currentStyle, opacity = jQuery.isNumeric( value ) ? "alpha(opacity=" + value * 100 + ")" : "", filter = currentStyle && currentStyle.filter || style.filter || ""; // IE has trouble with opacity if it does not have layout // Force it by setting the zoom level style.zoom = 1; // if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652 // if value === "", then remove inline opacity #12685 if ( ( value >= 1 || value === "" ) && jQuery.trim( filter.replace( ralpha, "" ) ) === "" && style.removeAttribute ) { // Setting style.filter to null, "" & " " still leave "filter:" in the cssText // if "filter:" is present at all, clearType is disabled, we want to avoid this // style.removeAttribute is IE Only, but so apparently is this code path... style.removeAttribute( "filter" ); // if there is no filter style applied in a css rule or unset inline opacity, we are done if ( value === "" || currentStyle && !currentStyle.filter ) { return; } } // otherwise, set new filter values style.filter = ralpha.test( filter ) ? filter.replace( ralpha, opacity ) : filter + " " + opacity; } }; } // These hooks cannot be added until DOM ready because the support test // for it is not run until after DOM ready jQuery(function() { if ( !jQuery.support.reliableMarginRight ) { jQuery.cssHooks.marginRight = { get: function( elem, computed ) { if ( computed ) { // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right // Work around by temporarily setting element display to inline-block return jQuery.swap( elem, { "display": "inline-block" }, curCSS, [ elem, "marginRight" ] ); } } }; } // Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084 // getComputedStyle returns percent when specified for top/left/bottom/right // rather than make the css module depend on the offset module, we just check for it here if ( !jQuery.support.pixelPosition && jQuery.fn.position ) { jQuery.each( [ "top", "left" ], function( i, prop ) { jQuery.cssHooks[ prop ] = { get: function( elem, computed ) { if ( computed ) { computed = curCSS( elem, prop ); // if curCSS returns percentage, fallback to offset return rnumnonpx.test( computed ) ? jQuery( elem ).position()[ prop ] + "px" : computed; } } }; }); } }); if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.hidden = function( elem ) { // Support: Opera <= 12.12 // Opera reports offsetWidths and offsetHeights less than zero on some elements return elem.offsetWidth <= 0 && elem.offsetHeight <= 0 || (!jQuery.support.reliableHiddenOffsets && ((elem.style && elem.style.display) || jQuery.css( elem, "display" )) === "none"); }; jQuery.expr.filters.visible = function( elem ) { return !jQuery.expr.filters.hidden( elem ); }; } // These hooks are used by animate to expand properties jQuery.each({ margin: "", padding: "", border: "Width" }, function( prefix, suffix ) { jQuery.cssHooks[ prefix + suffix ] = { expand: function( value ) { var i = 0, expanded = {}, // assumes a single number if not a string parts = typeof value === "string" ? value.split(" ") : [ value ]; for ( ; i < 4; i++ ) { expanded[ prefix + cssExpand[ i ] + suffix ] = parts[ i ] || parts[ i - 2 ] || parts[ 0 ]; } return expanded; } }; if ( !rmargin.test( prefix ) ) { jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber; } }); var r20 = /%20/g, rbracket = /\[\]$/, rCRLF = /\r?\n/g, rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i, rsubmittable = /^(?:input|select|textarea|keygen)/i; jQuery.fn.extend({ serialize: function() { return jQuery.param( this.serializeArray() ); }, serializeArray: function() { return this.map(function(){ // Can add propHook for "elements" to filter or add form elements var elements = jQuery.prop( this, "elements" ); return elements ? jQuery.makeArray( elements ) : this; }) .filter(function(){ var type = this.type; // Use .is(":disabled") so that fieldset[disabled] works return this.name && !jQuery( this ).is( ":disabled" ) && rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) && ( this.checked || !manipulation_rcheckableType.test( type ) ); }) .map(function( i, elem ){ var val = jQuery( this ).val(); return val == null ? null : jQuery.isArray( val ) ? jQuery.map( val, function( val ){ return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }) : { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }).get(); } }); //Serialize an array of form elements or a set of //key/values into a query string jQuery.param = function( a, traditional ) { var prefix, s = [], add = function( key, value ) { // If value is a function, invoke it and return its value value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value ); s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value ); }; // Set traditional to true for jQuery <= 1.3.2 behavior. if ( traditional === undefined ) { traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional; } // If an array was passed in, assume that it is an array of form elements. if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { // Serialize the form elements jQuery.each( a, function() { add( this.name, this.value ); }); } else { // If traditional, encode the "old" way (the way 1.3.2 or older // did it), otherwise encode params recursively. for ( prefix in a ) { buildParams( prefix, a[ prefix ], traditional, add ); } } // Return the resulting serialization return s.join( "&" ).replace( r20, "+" ); }; function buildParams( prefix, obj, traditional, add ) { var name; if ( jQuery.isArray( obj ) ) { // Serialize array item. jQuery.each( obj, function( i, v ) { if ( traditional || rbracket.test( prefix ) ) { // Treat each array item as a scalar. add( prefix, v ); } else { // Item is non-scalar (array or object), encode its numeric index. buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add ); } }); } else if ( !traditional && jQuery.type( obj ) === "object" ) { // Serialize object item. for ( name in obj ) { buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); } } else { // Serialize scalar item. add( prefix, obj ); } } jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " + "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + "change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) { // Handle event binding jQuery.fn[ name ] = function( data, fn ) { return arguments.length > 0 ? this.on( name, null, data, fn ) : this.trigger( name ); }; }); jQuery.fn.extend({ hover: function( fnOver, fnOut ) { return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); }, bind: function( types, data, fn ) { return this.on( types, null, data, fn ); }, unbind: function( types, fn ) { return this.off( types, null, fn ); }, delegate: function( selector, types, data, fn ) { return this.on( types, selector, data, fn ); }, undelegate: function( selector, types, fn ) { // ( namespace ) or ( selector, types [, fn] ) return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn ); } }); var // Document location ajaxLocParts, ajaxLocation, ajax_nonce = jQuery.now(), ajax_rquery = /\?/, rhash = /#.*$/, rts = /([?&])_=[^&]*/, rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL // #7653, #8125, #8152: local protocol detection rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/, rnoContent = /^(?:GET|HEAD)$/, rprotocol = /^\/\//, rurl = /^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/, // Keep a copy of the old load method _load = jQuery.fn.load, /* Prefilters * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example) * 2) These are called: * - BEFORE asking for a transport * - AFTER param serialization (s.data is a string if s.processData is true) * 3) key is the dataType * 4) the catchall symbol "*" can be used * 5) execution will start with transport dataType and THEN continue down to "*" if needed */ prefilters = {}, /* Transports bindings * 1) key is the dataType * 2) the catchall symbol "*" can be used * 3) selection will start with transport dataType and THEN go to "*" if needed */ transports = {}, // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression allTypes = "*/".concat("*"); // #8138, IE may throw an exception when accessing // a field from window.location if document.domain has been set try { ajaxLocation = location.href; } catch( e ) { // Use the href attribute of an A element // since IE will modify it given document.location ajaxLocation = document.createElement( "a" ); ajaxLocation.href = ""; ajaxLocation = ajaxLocation.href; } // Segment location into parts ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || []; // Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport function addToPrefiltersOrTransports( structure ) { // dataTypeExpression is optional and defaults to "*" return function( dataTypeExpression, func ) { if ( typeof dataTypeExpression !== "string" ) { func = dataTypeExpression; dataTypeExpression = "*"; } var dataType, i = 0, dataTypes = dataTypeExpression.toLowerCase().match( core_rnotwhite ) || []; if ( jQuery.isFunction( func ) ) { // For each dataType in the dataTypeExpression while ( (dataType = dataTypes[i++]) ) { // Prepend if requested if ( dataType[0] === "+" ) { dataType = dataType.slice( 1 ) || "*"; (structure[ dataType ] = structure[ dataType ] || []).unshift( func ); // Otherwise append } else { (structure[ dataType ] = structure[ dataType ] || []).push( func ); } } } }; } // Base inspection function for prefilters and transports function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) { var inspected = {}, seekingTransport = ( structure === transports ); function inspect( dataType ) { var selected; inspected[ dataType ] = true; jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) { var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR ); if( typeof dataTypeOrTransport === "string" && !seekingTransport && !inspected[ dataTypeOrTransport ] ) { options.dataTypes.unshift( dataTypeOrTransport ); inspect( dataTypeOrTransport ); return false; } else if ( seekingTransport ) { return !( selected = dataTypeOrTransport ); } }); return selected; } return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" ); } // A special extend for ajax options // that takes "flat" options (not to be deep extended) // Fixes #9887 function ajaxExtend( target, src ) { var deep, key, flatOptions = jQuery.ajaxSettings.flatOptions || {}; for ( key in src ) { if ( src[ key ] !== undefined ) { ( flatOptions[ key ] ? target : ( deep || (deep = {}) ) )[ key ] = src[ key ]; } } if ( deep ) { jQuery.extend( true, target, deep ); } return target; } jQuery.fn.load = function( url, params, callback ) { if ( typeof url !== "string" && _load ) { return _load.apply( this, arguments ); } var selector, response, type, self = this, off = url.indexOf(" "); if ( off >= 0 ) { selector = url.slice( off, url.length ); url = url.slice( 0, off ); } // If it's a function if ( jQuery.isFunction( params ) ) { // We assume that it's the callback callback = params; params = undefined; // Otherwise, build a param string } else if ( params && typeof params === "object" ) { type = "POST"; } // If we have elements to modify, make the request if ( self.length > 0 ) { jQuery.ajax({ url: url, // if "type" variable is undefined, then "GET" method will be used type: type, dataType: "html", data: params }).done(function( responseText ) { // Save response for use in complete callback response = arguments; self.html( selector ? // If a selector was specified, locate the right elements in a dummy div // Exclude scripts to avoid IE 'Permission Denied' errors jQuery("<div>").append( jQuery.parseHTML( responseText ) ).find( selector ) : // Otherwise use the full result responseText ); }).complete( callback && function( jqXHR, status ) { self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] ); }); } return this; }; // Attach a bunch of functions for handling common AJAX events jQuery.each( [ "ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend" ], function( i, type ){ jQuery.fn[ type ] = function( fn ){ return this.on( type, fn ); }; }); jQuery.extend({ // Counter for holding the number of active queries active: 0, // Last-Modified header cache for next request lastModified: {}, etag: {}, ajaxSettings: { url: ajaxLocation, type: "GET", isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ), global: true, processData: true, async: true, contentType: "application/x-www-form-urlencoded; charset=UTF-8", /* timeout: 0, data: null, dataType: null, username: null, password: null, cache: null, throws: false, traditional: false, headers: {}, */ accepts: { "*": allTypes, text: "text/plain", html: "text/html", xml: "application/xml, text/xml", json: "application/json, text/javascript" }, contents: { xml: /xml/, html: /html/, json: /json/ }, responseFields: { xml: "responseXML", text: "responseText", json: "responseJSON" }, // Data converters // Keys separate source (or catchall "*") and destination types with a single space converters: { // Convert anything to text "* text": String, // Text to html (true = no transformation) "text html": true, // Evaluate text as a json expression "text json": jQuery.parseJSON, // Parse text as xml "text xml": jQuery.parseXML }, // For options that shouldn't be deep extended: // you can add your own custom options here if // and when you create one that shouldn't be // deep extended (see ajaxExtend) flatOptions: { url: true, context: true } }, // Creates a full fledged settings object into target // with both ajaxSettings and settings fields. // If target is omitted, writes into ajaxSettings. ajaxSetup: function( target, settings ) { return settings ? // Building a settings object ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) : // Extending ajaxSettings ajaxExtend( jQuery.ajaxSettings, target ); }, ajaxPrefilter: addToPrefiltersOrTransports( prefilters ), ajaxTransport: addToPrefiltersOrTransports( transports ), // Main method ajax: function( url, options ) { // If url is an object, simulate pre-1.5 signature if ( typeof url === "object" ) { options = url; url = undefined; } // Force options to be an object options = options || {}; var // Cross-domain detection vars parts, // Loop variable i, // URL without anti-cache param cacheURL, // Response headers as string responseHeadersString, // timeout handle timeoutTimer, // To know if global events are to be dispatched fireGlobals, transport, // Response headers responseHeaders, // Create the final options object s = jQuery.ajaxSetup( {}, options ), // Callbacks context callbackContext = s.context || s, // Context for global events is callbackContext if it is a DOM node or jQuery collection globalEventContext = s.context && ( callbackContext.nodeType || callbackContext.jquery ) ? jQuery( callbackContext ) : jQuery.event, // Deferreds deferred = jQuery.Deferred(), completeDeferred = jQuery.Callbacks("once memory"), // Status-dependent callbacks statusCode = s.statusCode || {}, // Headers (they are sent all at once) requestHeaders = {}, requestHeadersNames = {}, // The jqXHR state state = 0, // Default abort message strAbort = "canceled", // Fake xhr jqXHR = { readyState: 0, // Builds headers hashtable if needed getResponseHeader: function( key ) { var match; if ( state === 2 ) { if ( !responseHeaders ) { responseHeaders = {}; while ( (match = rheaders.exec( responseHeadersString )) ) { responseHeaders[ match[1].toLowerCase() ] = match[ 2 ]; } } match = responseHeaders[ key.toLowerCase() ]; } return match == null ? null : match; }, // Raw string getAllResponseHeaders: function() { return state === 2 ? responseHeadersString : null; }, // Caches the header setRequestHeader: function( name, value ) { var lname = name.toLowerCase(); if ( !state ) { name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name; requestHeaders[ name ] = value; } return this; }, // Overrides response content-type header overrideMimeType: function( type ) { if ( !state ) { s.mimeType = type; } return this; }, // Status-dependent callbacks statusCode: function( map ) { var code; if ( map ) { if ( state < 2 ) { for ( code in map ) { // Lazy-add the new callback in a way that preserves old ones statusCode[ code ] = [ statusCode[ code ], map[ code ] ]; } } else { // Execute the appropriate callbacks jqXHR.always( map[ jqXHR.status ] ); } } return this; }, // Cancel the request abort: function( statusText ) { var finalText = statusText || strAbort; if ( transport ) { transport.abort( finalText ); } done( 0, finalText ); return this; } }; // Attach deferreds deferred.promise( jqXHR ).complete = completeDeferred.add; jqXHR.success = jqXHR.done; jqXHR.error = jqXHR.fail; // Remove hash character (#7531: and string promotion) // Add protocol if not provided (#5866: IE7 issue with protocol-less urls) // Handle falsy url in the settings object (#10093: consistency with old signature) // We also use the url parameter if available s.url = ( ( url || s.url || ajaxLocation ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" ); // Alias method option to type as per ticket #12004 s.type = options.method || options.type || s.method || s.type; // Extract dataTypes list s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().match( core_rnotwhite ) || [""]; // A cross-domain request is in order when we have a protocol:host:port mismatch if ( s.crossDomain == null ) { parts = rurl.exec( s.url.toLowerCase() ); s.crossDomain = !!( parts && ( parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] || ( parts[ 3 ] || ( parts[ 1 ] === "http:" ? "80" : "443" ) ) !== ( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? "80" : "443" ) ) ) ); } // Convert data if not already a string if ( s.data && s.processData && typeof s.data !== "string" ) { s.data = jQuery.param( s.data, s.traditional ); } // Apply prefilters inspectPrefiltersOrTransports( prefilters, s, options, jqXHR ); // If request was aborted inside a prefilter, stop there if ( state === 2 ) { return jqXHR; } // We can fire global events as of now if asked to fireGlobals = s.global; // Watch for a new set of requests if ( fireGlobals && jQuery.active++ === 0 ) { jQuery.event.trigger("ajaxStart"); } // Uppercase the type s.type = s.type.toUpperCase(); // Determine if request has content s.hasContent = !rnoContent.test( s.type ); // Save the URL in case we're toying with the If-Modified-Since // and/or If-None-Match header later on cacheURL = s.url; // More options handling for requests with no content if ( !s.hasContent ) { // If data is available, append data to url if ( s.data ) { cacheURL = ( s.url += ( ajax_rquery.test( cacheURL ) ? "&" : "?" ) + s.data ); // #9682: remove data so that it's not used in an eventual retry delete s.data; } // Add anti-cache in url if needed if ( s.cache === false ) { s.url = rts.test( cacheURL ) ? // If there is already a '_' parameter, set its value cacheURL.replace( rts, "$1_=" + ajax_nonce++ ) : // Otherwise add one to the end cacheURL + ( ajax_rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + ajax_nonce++; } } // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { if ( jQuery.lastModified[ cacheURL ] ) { jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] ); } if ( jQuery.etag[ cacheURL ] ) { jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] ); } } // Set the correct header, if data is being sent if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) { jqXHR.setRequestHeader( "Content-Type", s.contentType ); } // Set the Accepts header for the server, depending on the dataType jqXHR.setRequestHeader( "Accept", s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ? s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) : s.accepts[ "*" ] ); // Check for headers option for ( i in s.headers ) { jqXHR.setRequestHeader( i, s.headers[ i ] ); } // Allow custom headers/mimetypes and early abort if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) { // Abort if not done already and return return jqXHR.abort(); } // aborting is no longer a cancellation strAbort = "abort"; // Install callbacks on deferreds for ( i in { success: 1, error: 1, complete: 1 } ) { jqXHR[ i ]( s[ i ] ); } // Get transport transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR ); // If no transport, we auto-abort if ( !transport ) { done( -1, "No Transport" ); } else { jqXHR.readyState = 1; // Send global event if ( fireGlobals ) { globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] ); } // Timeout if ( s.async && s.timeout > 0 ) { timeoutTimer = setTimeout(function() { jqXHR.abort("timeout"); }, s.timeout ); } try { state = 1; transport.send( requestHeaders, done ); } catch ( e ) { // Propagate exception as error if not done if ( state < 2 ) { done( -1, e ); // Simply rethrow otherwise } else { throw e; } } } // Callback for when everything is done function done( status, nativeStatusText, responses, headers ) { var isSuccess, success, error, response, modified, statusText = nativeStatusText; // Called once if ( state === 2 ) { return; } // State is "done" now state = 2; // Clear timeout if it exists if ( timeoutTimer ) { clearTimeout( timeoutTimer ); } // Dereference transport for early garbage collection // (no matter how long the jqXHR object will be used) transport = undefined; // Cache response headers responseHeadersString = headers || ""; // Set readyState jqXHR.readyState = status > 0 ? 4 : 0; // Determine if successful isSuccess = status >= 200 && status < 300 || status === 304; // Get response data if ( responses ) { response = ajaxHandleResponses( s, jqXHR, responses ); } // Convert no matter what (that way responseXXX fields are always set) response = ajaxConvert( s, response, jqXHR, isSuccess ); // If successful, handle type chaining if ( isSuccess ) { // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { modified = jqXHR.getResponseHeader("Last-Modified"); if ( modified ) { jQuery.lastModified[ cacheURL ] = modified; } modified = jqXHR.getResponseHeader("etag"); if ( modified ) { jQuery.etag[ cacheURL ] = modified; } } // if no content if ( status === 204 || s.type === "HEAD" ) { statusText = "nocontent"; // if not modified } else if ( status === 304 ) { statusText = "notmodified"; // If we have data, let's convert it } else { statusText = response.state; success = response.data; error = response.error; isSuccess = !error; } } else { // We extract error from statusText // then normalize statusText and status for non-aborts error = statusText; if ( status || !statusText ) { statusText = "error"; if ( status < 0 ) { status = 0; } } } // Set data for the fake xhr object jqXHR.status = status; jqXHR.statusText = ( nativeStatusText || statusText ) + ""; // Success/Error if ( isSuccess ) { deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] ); } else { deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] ); } // Status-dependent callbacks jqXHR.statusCode( statusCode ); statusCode = undefined; if ( fireGlobals ) { globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError", [ jqXHR, s, isSuccess ? success : error ] ); } // Complete completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] ); if ( fireGlobals ) { globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] ); // Handle the global AJAX counter if ( !( --jQuery.active ) ) { jQuery.event.trigger("ajaxStop"); } } } return jqXHR; }, getJSON: function( url, data, callback ) { return jQuery.get( url, data, callback, "json" ); }, getScript: function( url, callback ) { return jQuery.get( url, undefined, callback, "script" ); } }); jQuery.each( [ "get", "post" ], function( i, method ) { jQuery[ method ] = function( url, data, callback, type ) { // shift arguments if data argument was omitted if ( jQuery.isFunction( data ) ) { type = type || callback; callback = data; data = undefined; } return jQuery.ajax({ url: url, type: method, dataType: type, data: data, success: callback }); }; }); /* Handles responses to an ajax request: * - finds the right dataType (mediates between content-type and expected dataType) * - returns the corresponding response */ function ajaxHandleResponses( s, jqXHR, responses ) { var firstDataType, ct, finalDataType, type, contents = s.contents, dataTypes = s.dataTypes; // Remove auto dataType and get content-type in the process while( dataTypes[ 0 ] === "*" ) { dataTypes.shift(); if ( ct === undefined ) { ct = s.mimeType || jqXHR.getResponseHeader("Content-Type"); } } // Check if we're dealing with a known content-type if ( ct ) { for ( type in contents ) { if ( contents[ type ] && contents[ type ].test( ct ) ) { dataTypes.unshift( type ); break; } } } // Check to see if we have a response for the expected dataType if ( dataTypes[ 0 ] in responses ) { finalDataType = dataTypes[ 0 ]; } else { // Try convertible dataTypes for ( type in responses ) { if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) { finalDataType = type; break; } if ( !firstDataType ) { firstDataType = type; } } // Or just use first one finalDataType = finalDataType || firstDataType; } // If we found a dataType // We add the dataType to the list if needed // and return the corresponding response if ( finalDataType ) { if ( finalDataType !== dataTypes[ 0 ] ) { dataTypes.unshift( finalDataType ); } return responses[ finalDataType ]; } } /* Chain conversions given the request and the original response * Also sets the responseXXX fields on the jqXHR instance */ function ajaxConvert( s, response, jqXHR, isSuccess ) { var conv2, current, conv, tmp, prev, converters = {}, // Work with a copy of dataTypes in case we need to modify it for conversion dataTypes = s.dataTypes.slice(); // Create converters map with lowercased keys if ( dataTypes[ 1 ] ) { for ( conv in s.converters ) { converters[ conv.toLowerCase() ] = s.converters[ conv ]; } } current = dataTypes.shift(); // Convert to each sequential dataType while ( current ) { if ( s.responseFields[ current ] ) { jqXHR[ s.responseFields[ current ] ] = response; } // Apply the dataFilter if provided if ( !prev && isSuccess && s.dataFilter ) { response = s.dataFilter( response, s.dataType ); } prev = current; current = dataTypes.shift(); if ( current ) { // There's only work to do if current dataType is non-auto if ( current === "*" ) { current = prev; // Convert response if prev dataType is non-auto and differs from current } else if ( prev !== "*" && prev !== current ) { // Seek a direct converter conv = converters[ prev + " " + current ] || converters[ "* " + current ]; // If none found, seek a pair if ( !conv ) { for ( conv2 in converters ) { // If conv2 outputs current tmp = conv2.split( " " ); if ( tmp[ 1 ] === current ) { // If prev can be converted to accepted input conv = converters[ prev + " " + tmp[ 0 ] ] || converters[ "* " + tmp[ 0 ] ]; if ( conv ) { // Condense equivalence converters if ( conv === true ) { conv = converters[ conv2 ]; // Otherwise, insert the intermediate dataType } else if ( converters[ conv2 ] !== true ) { current = tmp[ 0 ]; dataTypes.unshift( tmp[ 1 ] ); } break; } } } } // Apply converter (if not an equivalence) if ( conv !== true ) { // Unless errors are allowed to bubble, catch and return them if ( conv && s[ "throws" ] ) { response = conv( response ); } else { try { response = conv( response ); } catch ( e ) { return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current }; } } } } } } return { state: "success", data: response }; } // Install script dataType jQuery.ajaxSetup({ accepts: { script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript" }, contents: { script: /(?:java|ecma)script/ }, converters: { "text script": function( text ) { jQuery.globalEval( text ); return text; } } }); // Handle cache's special case and global jQuery.ajaxPrefilter( "script", function( s ) { if ( s.cache === undefined ) { s.cache = false; } if ( s.crossDomain ) { s.type = "GET"; s.global = false; } }); // Bind script tag hack transport jQuery.ajaxTransport( "script", function(s) { // This transport only deals with cross domain requests if ( s.crossDomain ) { var script, head = document.head || jQuery("head")[0] || document.documentElement; return { send: function( _, callback ) { script = document.createElement("script"); script.async = true; if ( s.scriptCharset ) { script.charset = s.scriptCharset; } script.src = s.url; // Attach handlers for all browsers script.onload = script.onreadystatechange = function( _, isAbort ) { if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) { // Handle memory leak in IE script.onload = script.onreadystatechange = null; // Remove the script if ( script.parentNode ) { script.parentNode.removeChild( script ); } // Dereference the script script = null; // Callback if not abort if ( !isAbort ) { callback( 200, "success" ); } } }; // Circumvent IE6 bugs with base elements (#2709 and #4378) by prepending // Use native DOM manipulation to avoid our domManip AJAX trickery head.insertBefore( script, head.firstChild ); }, abort: function() { if ( script ) { script.onload( undefined, true ); } } }; } }); var oldCallbacks = [], rjsonp = /(=)\?(?=&|$)|\?\?/; // Default jsonp settings jQuery.ajaxSetup({ jsonp: "callback", jsonpCallback: function() { var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( ajax_nonce++ ) ); this[ callback ] = true; return callback; } }); // Detect, normalize options and install callbacks for jsonp requests jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) { var callbackName, overwritten, responseContainer, jsonProp = s.jsonp !== false && ( rjsonp.test( s.url ) ? "url" : typeof s.data === "string" && !( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") && rjsonp.test( s.data ) && "data" ); // Handle iff the expected data type is "jsonp" or we have a parameter to set if ( jsonProp || s.dataTypes[ 0 ] === "jsonp" ) { // Get callback name, remembering preexisting value associated with it callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ? s.jsonpCallback() : s.jsonpCallback; // Insert callback into url or form data if ( jsonProp ) { s[ jsonProp ] = s[ jsonProp ].replace( rjsonp, "$1" + callbackName ); } else if ( s.jsonp !== false ) { s.url += ( ajax_rquery.test( s.url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName; } // Use data converter to retrieve json after script execution s.converters["script json"] = function() { if ( !responseContainer ) { jQuery.error( callbackName + " was not called" ); } return responseContainer[ 0 ]; }; // force json dataType s.dataTypes[ 0 ] = "json"; // Install callback overwritten = window[ callbackName ]; window[ callbackName ] = function() { responseContainer = arguments; }; // Clean-up function (fires after converters) jqXHR.always(function() { // Restore preexisting value window[ callbackName ] = overwritten; // Save back as free if ( s[ callbackName ] ) { // make sure that re-using the options doesn't screw things around s.jsonpCallback = originalSettings.jsonpCallback; // save the callback name for future use oldCallbacks.push( callbackName ); } // Call if it was a function and we have a response if ( responseContainer && jQuery.isFunction( overwritten ) ) { overwritten( responseContainer[ 0 ] ); } responseContainer = overwritten = undefined; }); // Delegate to script return "script"; } }); var xhrCallbacks, xhrSupported, xhrId = 0, // #5280: Internet Explorer will keep connections alive if we don't abort on unload xhrOnUnloadAbort = window.ActiveXObject && function() { // Abort all pending requests var key; for ( key in xhrCallbacks ) { xhrCallbacks[ key ]( undefined, true ); } }; // Functions to create xhrs function createStandardXHR() { try { return new window.XMLHttpRequest(); } catch( e ) {} } function createActiveXHR() { try { return new window.ActiveXObject("Microsoft.XMLHTTP"); } catch( e ) {} } // Create the request object // (This is still attached to ajaxSettings for backward compatibility) jQuery.ajaxSettings.xhr = window.ActiveXObject ? /* Microsoft failed to properly * implement the XMLHttpRequest in IE7 (can't request local files), * so we use the ActiveXObject when it is available * Additionally XMLHttpRequest can be disabled in IE7/IE8 so * we need a fallback. */ function() { return !this.isLocal && createStandardXHR() || createActiveXHR(); } : // For all other browsers, use the standard XMLHttpRequest object createStandardXHR; // Determine support properties xhrSupported = jQuery.ajaxSettings.xhr(); jQuery.support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported ); xhrSupported = jQuery.support.ajax = !!xhrSupported; // Create transport if the browser can provide an xhr if ( xhrSupported ) { jQuery.ajaxTransport(function( s ) { // Cross domain only allowed if supported through XMLHttpRequest if ( !s.crossDomain || jQuery.support.cors ) { var callback; return { send: function( headers, complete ) { // Get a new xhr var handle, i, xhr = s.xhr(); // Open the socket // Passing null username, generates a login popup on Opera (#2865) if ( s.username ) { xhr.open( s.type, s.url, s.async, s.username, s.password ); } else { xhr.open( s.type, s.url, s.async ); } // Apply custom fields if provided if ( s.xhrFields ) { for ( i in s.xhrFields ) { xhr[ i ] = s.xhrFields[ i ]; } } // Override mime type if needed if ( s.mimeType && xhr.overrideMimeType ) { xhr.overrideMimeType( s.mimeType ); } // X-Requested-With header // For cross-domain requests, seeing as conditions for a preflight are // akin to a jigsaw puzzle, we simply never set it to be sure. // (it can always be set on a per-request basis or even using ajaxSetup) // For same-domain requests, won't change header if already provided. if ( !s.crossDomain && !headers["X-Requested-With"] ) { headers["X-Requested-With"] = "XMLHttpRequest"; } // Need an extra try/catch for cross domain requests in Firefox 3 try { for ( i in headers ) { xhr.setRequestHeader( i, headers[ i ] ); } } catch( err ) {} // Do send the request // This may raise an exception which is actually // handled in jQuery.ajax (so no try/catch here) xhr.send( ( s.hasContent && s.data ) || null ); // Listener callback = function( _, isAbort ) { var status, responseHeaders, statusText, responses; // Firefox throws exceptions when accessing properties // of an xhr when a network error occurred // http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE) try { // Was never called and is aborted or complete if ( callback && ( isAbort || xhr.readyState === 4 ) ) { // Only called once callback = undefined; // Do not keep as active anymore if ( handle ) { xhr.onreadystatechange = jQuery.noop; if ( xhrOnUnloadAbort ) { delete xhrCallbacks[ handle ]; } } // If it's an abort if ( isAbort ) { // Abort it manually if needed if ( xhr.readyState !== 4 ) { xhr.abort(); } } else { responses = {}; status = xhr.status; responseHeaders = xhr.getAllResponseHeaders(); // When requesting binary data, IE6-9 will throw an exception // on any attempt to access responseText (#11426) if ( typeof xhr.responseText === "string" ) { responses.text = xhr.responseText; } // Firefox throws an exception when accessing // statusText for faulty cross-domain requests try { statusText = xhr.statusText; } catch( e ) { // We normalize with Webkit giving an empty statusText statusText = ""; } // Filter status for non standard behaviors // If the request is local and we have data: assume a success // (success with no data won't get notified, that's the best we // can do given current implementations) if ( !status && s.isLocal && !s.crossDomain ) { status = responses.text ? 200 : 404; // IE - #1450: sometimes returns 1223 when it should be 204 } else if ( status === 1223 ) { status = 204; } } } } catch( firefoxAccessException ) { if ( !isAbort ) { complete( -1, firefoxAccessException ); } } // Call complete if needed if ( responses ) { complete( status, statusText, responses, responseHeaders ); } }; if ( !s.async ) { // if we're in sync mode we fire the callback callback(); } else if ( xhr.readyState === 4 ) { // (IE6 & IE7) if it's in cache and has been // retrieved directly we need to fire the callback setTimeout( callback ); } else { handle = ++xhrId; if ( xhrOnUnloadAbort ) { // Create the active xhrs callbacks list if needed // and attach the unload handler if ( !xhrCallbacks ) { xhrCallbacks = {}; jQuery( window ).unload( xhrOnUnloadAbort ); } // Add to list of active xhrs callbacks xhrCallbacks[ handle ] = callback; } xhr.onreadystatechange = callback; } }, abort: function() { if ( callback ) { callback( undefined, true ); } } }; } }); } var fxNow, timerId, rfxtypes = /^(?:toggle|show|hide)$/, rfxnum = new RegExp( "^(?:([+-])=|)(" + core_pnum + ")([a-z%]*)$", "i" ), rrun = /queueHooks$/, animationPrefilters = [ defaultPrefilter ], tweeners = { "*": [function( prop, value ) { var tween = this.createTween( prop, value ), target = tween.cur(), parts = rfxnum.exec( value ), unit = parts && parts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ), // Starting value computation is required for potential unit mismatches start = ( jQuery.cssNumber[ prop ] || unit !== "px" && +target ) && rfxnum.exec( jQuery.css( tween.elem, prop ) ), scale = 1, maxIterations = 20; if ( start && start[ 3 ] !== unit ) { // Trust units reported by jQuery.css unit = unit || start[ 3 ]; // Make sure we update the tween properties later on parts = parts || []; // Iteratively approximate from a nonzero starting point start = +target || 1; do { // If previous iteration zeroed out, double until we get *something* // Use a string for doubling factor so we don't accidentally see scale as unchanged below scale = scale || ".5"; // Adjust and apply start = start / scale; jQuery.style( tween.elem, prop, start + unit ); // Update scale, tolerating zero or NaN from tween.cur() // And breaking the loop if scale is unchanged or perfect, or if we've just had enough } while ( scale !== (scale = tween.cur() / target) && scale !== 1 && --maxIterations ); } // Update tween properties if ( parts ) { start = tween.start = +start || +target || 0; tween.unit = unit; // If a +=/-= token was provided, we're doing a relative animation tween.end = parts[ 1 ] ? start + ( parts[ 1 ] + 1 ) * parts[ 2 ] : +parts[ 2 ]; } return tween; }] }; // Animations created synchronously will run synchronously function createFxNow() { setTimeout(function() { fxNow = undefined; }); return ( fxNow = jQuery.now() ); } function createTween( value, prop, animation ) { var tween, collection = ( tweeners[ prop ] || [] ).concat( tweeners[ "*" ] ), index = 0, length = collection.length; for ( ; index < length; index++ ) { if ( (tween = collection[ index ].call( animation, prop, value )) ) { // we're done with this property return tween; } } } function Animation( elem, properties, options ) { var result, stopped, index = 0, length = animationPrefilters.length, deferred = jQuery.Deferred().always( function() { // don't match elem in the :animated selector delete tick.elem; }), tick = function() { if ( stopped ) { return false; } var currentTime = fxNow || createFxNow(), remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ), // archaic crash bug won't allow us to use 1 - ( 0.5 || 0 ) (#12497) temp = remaining / animation.duration || 0, percent = 1 - temp, index = 0, length = animation.tweens.length; for ( ; index < length ; index++ ) { animation.tweens[ index ].run( percent ); } deferred.notifyWith( elem, [ animation, percent, remaining ]); if ( percent < 1 && length ) { return remaining; } else { deferred.resolveWith( elem, [ animation ] ); return false; } }, animation = deferred.promise({ elem: elem, props: jQuery.extend( {}, properties ), opts: jQuery.extend( true, { specialEasing: {} }, options ), originalProperties: properties, originalOptions: options, startTime: fxNow || createFxNow(), duration: options.duration, tweens: [], createTween: function( prop, end ) { var tween = jQuery.Tween( elem, animation.opts, prop, end, animation.opts.specialEasing[ prop ] || animation.opts.easing ); animation.tweens.push( tween ); return tween; }, stop: function( gotoEnd ) { var index = 0, // if we are going to the end, we want to run all the tweens // otherwise we skip this part length = gotoEnd ? animation.tweens.length : 0; if ( stopped ) { return this; } stopped = true; for ( ; index < length ; index++ ) { animation.tweens[ index ].run( 1 ); } // resolve when we played the last frame // otherwise, reject if ( gotoEnd ) { deferred.resolveWith( elem, [ animation, gotoEnd ] ); } else { deferred.rejectWith( elem, [ animation, gotoEnd ] ); } return this; } }), props = animation.props; propFilter( props, animation.opts.specialEasing ); for ( ; index < length ; index++ ) { result = animationPrefilters[ index ].call( animation, elem, props, animation.opts ); if ( result ) { return result; } } jQuery.map( props, createTween, animation ); if ( jQuery.isFunction( animation.opts.start ) ) { animation.opts.start.call( elem, animation ); } jQuery.fx.timer( jQuery.extend( tick, { elem: elem, anim: animation, queue: animation.opts.queue }) ); // attach callbacks from options return animation.progress( animation.opts.progress ) .done( animation.opts.done, animation.opts.complete ) .fail( animation.opts.fail ) .always( animation.opts.always ); } function propFilter( props, specialEasing ) { var index, name, easing, value, hooks; // camelCase, specialEasing and expand cssHook pass for ( index in props ) { name = jQuery.camelCase( index ); easing = specialEasing[ name ]; value = props[ index ]; if ( jQuery.isArray( value ) ) { easing = value[ 1 ]; value = props[ index ] = value[ 0 ]; } if ( index !== name ) { props[ name ] = value; delete props[ index ]; } hooks = jQuery.cssHooks[ name ]; if ( hooks && "expand" in hooks ) { value = hooks.expand( value ); delete props[ name ]; // not quite $.extend, this wont overwrite keys already present. // also - reusing 'index' from above because we have the correct "name" for ( index in value ) { if ( !( index in props ) ) { props[ index ] = value[ index ]; specialEasing[ index ] = easing; } } } else { specialEasing[ name ] = easing; } } } jQuery.Animation = jQuery.extend( Animation, { tweener: function( props, callback ) { if ( jQuery.isFunction( props ) ) { callback = props; props = [ "*" ]; } else { props = props.split(" "); } var prop, index = 0, length = props.length; for ( ; index < length ; index++ ) { prop = props[ index ]; tweeners[ prop ] = tweeners[ prop ] || []; tweeners[ prop ].unshift( callback ); } }, prefilter: function( callback, prepend ) { if ( prepend ) { animationPrefilters.unshift( callback ); } else { animationPrefilters.push( callback ); } } }); function defaultPrefilter( elem, props, opts ) { /* jshint validthis: true */ var prop, value, toggle, tween, hooks, oldfire, anim = this, orig = {}, style = elem.style, hidden = elem.nodeType && isHidden( elem ), dataShow = jQuery._data( elem, "fxshow" ); // handle queue: false promises if ( !opts.queue ) { hooks = jQuery._queueHooks( elem, "fx" ); if ( hooks.unqueued == null ) { hooks.unqueued = 0; oldfire = hooks.empty.fire; hooks.empty.fire = function() { if ( !hooks.unqueued ) { oldfire(); } }; } hooks.unqueued++; anim.always(function() { // doing this makes sure that the complete handler will be called // before this completes anim.always(function() { hooks.unqueued--; if ( !jQuery.queue( elem, "fx" ).length ) { hooks.empty.fire(); } }); }); } // height/width overflow pass if ( elem.nodeType === 1 && ( "height" in props || "width" in props ) ) { // Make sure that nothing sneaks out // Record all 3 overflow attributes because IE does not // change the overflow attribute when overflowX and // overflowY are set to the same value opts.overflow = [ style.overflow, style.overflowX, style.overflowY ]; // Set display property to inline-block for height/width // animations on inline elements that are having width/height animated if ( jQuery.css( elem, "display" ) === "inline" && jQuery.css( elem, "float" ) === "none" ) { // inline-level elements accept inline-block; // block-level elements need to be inline with layout if ( !jQuery.support.inlineBlockNeedsLayout || css_defaultDisplay( elem.nodeName ) === "inline" ) { style.display = "inline-block"; } else { style.zoom = 1; } } } if ( opts.overflow ) { style.overflow = "hidden"; if ( !jQuery.support.shrinkWrapBlocks ) { anim.always(function() { style.overflow = opts.overflow[ 0 ]; style.overflowX = opts.overflow[ 1 ]; style.overflowY = opts.overflow[ 2 ]; }); } } // show/hide pass for ( prop in props ) { value = props[ prop ]; if ( rfxtypes.exec( value ) ) { delete props[ prop ]; toggle = toggle || value === "toggle"; if ( value === ( hidden ? "hide" : "show" ) ) { continue; } orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop ); } } if ( !jQuery.isEmptyObject( orig ) ) { if ( dataShow ) { if ( "hidden" in dataShow ) { hidden = dataShow.hidden; } } else { dataShow = jQuery._data( elem, "fxshow", {} ); } // store state if its toggle - enables .stop().toggle() to "reverse" if ( toggle ) { dataShow.hidden = !hidden; } if ( hidden ) { jQuery( elem ).show(); } else { anim.done(function() { jQuery( elem ).hide(); }); } anim.done(function() { var prop; jQuery._removeData( elem, "fxshow" ); for ( prop in orig ) { jQuery.style( elem, prop, orig[ prop ] ); } }); for ( prop in orig ) { tween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim ); if ( !( prop in dataShow ) ) { dataShow[ prop ] = tween.start; if ( hidden ) { tween.end = tween.start; tween.start = prop === "width" || prop === "height" ? 1 : 0; } } } } } function Tween( elem, options, prop, end, easing ) { return new Tween.prototype.init( elem, options, prop, end, easing ); } jQuery.Tween = Tween; Tween.prototype = { constructor: Tween, init: function( elem, options, prop, end, easing, unit ) { this.elem = elem; this.prop = prop; this.easing = easing || "swing"; this.options = options; this.start = this.now = this.cur(); this.end = end; this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" ); }, cur: function() { var hooks = Tween.propHooks[ this.prop ]; return hooks && hooks.get ? hooks.get( this ) : Tween.propHooks._default.get( this ); }, run: function( percent ) { var eased, hooks = Tween.propHooks[ this.prop ]; if ( this.options.duration ) { this.pos = eased = jQuery.easing[ this.easing ]( percent, this.options.duration * percent, 0, 1, this.options.duration ); } else { this.pos = eased = percent; } this.now = ( this.end - this.start ) * eased + this.start; if ( this.options.step ) { this.options.step.call( this.elem, this.now, this ); } if ( hooks && hooks.set ) { hooks.set( this ); } else { Tween.propHooks._default.set( this ); } return this; } }; Tween.prototype.init.prototype = Tween.prototype; Tween.propHooks = { _default: { get: function( tween ) { var result; if ( tween.elem[ tween.prop ] != null && (!tween.elem.style || tween.elem.style[ tween.prop ] == null) ) { return tween.elem[ tween.prop ]; } // passing an empty string as a 3rd parameter to .css will automatically // attempt a parseFloat and fallback to a string if the parse fails // so, simple values such as "10px" are parsed to Float. // complex values such as "rotate(1rad)" are returned as is. result = jQuery.css( tween.elem, tween.prop, "" ); // Empty strings, null, undefined and "auto" are converted to 0. return !result || result === "auto" ? 0 : result; }, set: function( tween ) { // use step hook for back compat - use cssHook if its there - use .style if its // available and use plain properties where available if ( jQuery.fx.step[ tween.prop ] ) { jQuery.fx.step[ tween.prop ]( tween ); } else if ( tween.elem.style && ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || jQuery.cssHooks[ tween.prop ] ) ) { jQuery.style( tween.elem, tween.prop, tween.now + tween.unit ); } else { tween.elem[ tween.prop ] = tween.now; } } } }; // Support: IE <=9 // Panic based approach to setting things on disconnected nodes Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = { set: function( tween ) { if ( tween.elem.nodeType && tween.elem.parentNode ) { tween.elem[ tween.prop ] = tween.now; } } }; jQuery.each([ "toggle", "show", "hide" ], function( i, name ) { var cssFn = jQuery.fn[ name ]; jQuery.fn[ name ] = function( speed, easing, callback ) { return speed == null || typeof speed === "boolean" ? cssFn.apply( this, arguments ) : this.animate( genFx( name, true ), speed, easing, callback ); }; }); jQuery.fn.extend({ fadeTo: function( speed, to, easing, callback ) { // show any hidden elements after setting opacity to 0 return this.filter( isHidden ).css( "opacity", 0 ).show() // animate to the value specified .end().animate({ opacity: to }, speed, easing, callback ); }, animate: function( prop, speed, easing, callback ) { var empty = jQuery.isEmptyObject( prop ), optall = jQuery.speed( speed, easing, callback ), doAnimation = function() { // Operate on a copy of prop so per-property easing won't be lost var anim = Animation( this, jQuery.extend( {}, prop ), optall ); // Empty animations, or finishing resolves immediately if ( empty || jQuery._data( this, "finish" ) ) { anim.stop( true ); } }; doAnimation.finish = doAnimation; return empty || optall.queue === false ? this.each( doAnimation ) : this.queue( optall.queue, doAnimation ); }, stop: function( type, clearQueue, gotoEnd ) { var stopQueue = function( hooks ) { var stop = hooks.stop; delete hooks.stop; stop( gotoEnd ); }; if ( typeof type !== "string" ) { gotoEnd = clearQueue; clearQueue = type; type = undefined; } if ( clearQueue && type !== false ) { this.queue( type || "fx", [] ); } return this.each(function() { var dequeue = true, index = type != null && type + "queueHooks", timers = jQuery.timers, data = jQuery._data( this ); if ( index ) { if ( data[ index ] && data[ index ].stop ) { stopQueue( data[ index ] ); } } else { for ( index in data ) { if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) { stopQueue( data[ index ] ); } } } for ( index = timers.length; index--; ) { if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) { timers[ index ].anim.stop( gotoEnd ); dequeue = false; timers.splice( index, 1 ); } } // start the next in the queue if the last step wasn't forced // timers currently will call their complete callbacks, which will dequeue // but only if they were gotoEnd if ( dequeue || !gotoEnd ) { jQuery.dequeue( this, type ); } }); }, finish: function( type ) { if ( type !== false ) { type = type || "fx"; } return this.each(function() { var index, data = jQuery._data( this ), queue = data[ type + "queue" ], hooks = data[ type + "queueHooks" ], timers = jQuery.timers, length = queue ? queue.length : 0; // enable finishing flag on private data data.finish = true; // empty the queue first jQuery.queue( this, type, [] ); if ( hooks && hooks.stop ) { hooks.stop.call( this, true ); } // look for any active animations, and finish them for ( index = timers.length; index--; ) { if ( timers[ index ].elem === this && timers[ index ].queue === type ) { timers[ index ].anim.stop( true ); timers.splice( index, 1 ); } } // look for any animations in the old queue and finish them for ( index = 0; index < length; index++ ) { if ( queue[ index ] && queue[ index ].finish ) { queue[ index ].finish.call( this ); } } // turn off finishing flag delete data.finish; }); } }); // Generate parameters to create a standard animation function genFx( type, includeWidth ) { var which, attrs = { height: type }, i = 0; // if we include width, step value is 1 to do all cssExpand values, // if we don't include width, step value is 2 to skip over Left and Right includeWidth = includeWidth? 1 : 0; for( ; i < 4 ; i += 2 - includeWidth ) { which = cssExpand[ i ]; attrs[ "margin" + which ] = attrs[ "padding" + which ] = type; } if ( includeWidth ) { attrs.opacity = attrs.width = type; } return attrs; } // Generate shortcuts for custom animations jQuery.each({ slideDown: genFx("show"), slideUp: genFx("hide"), slideToggle: genFx("toggle"), fadeIn: { opacity: "show" }, fadeOut: { opacity: "hide" }, fadeToggle: { opacity: "toggle" } }, function( name, props ) { jQuery.fn[ name ] = function( speed, easing, callback ) { return this.animate( props, speed, easing, callback ); }; }); jQuery.speed = function( speed, easing, fn ) { var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : { complete: fn || !fn && easing || jQuery.isFunction( speed ) && speed, duration: speed, easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing }; opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration : opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default; // normalize opt.queue - true/undefined/null -> "fx" if ( opt.queue == null || opt.queue === true ) { opt.queue = "fx"; } // Queueing opt.old = opt.complete; opt.complete = function() { if ( jQuery.isFunction( opt.old ) ) { opt.old.call( this ); } if ( opt.queue ) { jQuery.dequeue( this, opt.queue ); } }; return opt; }; jQuery.easing = { linear: function( p ) { return p; }, swing: function( p ) { return 0.5 - Math.cos( p*Math.PI ) / 2; } }; jQuery.timers = []; jQuery.fx = Tween.prototype.init; jQuery.fx.tick = function() { var timer, timers = jQuery.timers, i = 0; fxNow = jQuery.now(); for ( ; i < timers.length; i++ ) { timer = timers[ i ]; // Checks the timer has not already been removed if ( !timer() && timers[ i ] === timer ) { timers.splice( i--, 1 ); } } if ( !timers.length ) { jQuery.fx.stop(); } fxNow = undefined; }; jQuery.fx.timer = function( timer ) { if ( timer() && jQuery.timers.push( timer ) ) { jQuery.fx.start(); } }; jQuery.fx.interval = 13; jQuery.fx.start = function() { if ( !timerId ) { timerId = setInterval( jQuery.fx.tick, jQuery.fx.interval ); } }; jQuery.fx.stop = function() { clearInterval( timerId ); timerId = null; }; jQuery.fx.speeds = { slow: 600, fast: 200, // Default speed _default: 400 }; // Back Compat <1.8 extension point jQuery.fx.step = {}; if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.animated = function( elem ) { return jQuery.grep(jQuery.timers, function( fn ) { return elem === fn.elem; }).length; }; } jQuery.fn.offset = function( options ) { if ( arguments.length ) { return options === undefined ? this : this.each(function( i ) { jQuery.offset.setOffset( this, options, i ); }); } var docElem, win, box = { top: 0, left: 0 }, elem = this[ 0 ], doc = elem && elem.ownerDocument; if ( !doc ) { return; } docElem = doc.documentElement; // Make sure it's not a disconnected DOM node if ( !jQuery.contains( docElem, elem ) ) { return box; } // If we don't have gBCR, just use 0,0 rather than error // BlackBerry 5, iOS 3 (original iPhone) if ( typeof elem.getBoundingClientRect !== core_strundefined ) { box = elem.getBoundingClientRect(); } win = getWindow( doc ); return { top: box.top + ( win.pageYOffset || docElem.scrollTop ) - ( docElem.clientTop || 0 ), left: box.left + ( win.pageXOffset || docElem.scrollLeft ) - ( docElem.clientLeft || 0 ) }; }; jQuery.offset = { setOffset: function( elem, options, i ) { var position = jQuery.css( elem, "position" ); // set position first, in-case top/left are set even on static elem if ( position === "static" ) { elem.style.position = "relative"; } var curElem = jQuery( elem ), curOffset = curElem.offset(), curCSSTop = jQuery.css( elem, "top" ), curCSSLeft = jQuery.css( elem, "left" ), calculatePosition = ( position === "absolute" || position === "fixed" ) && jQuery.inArray("auto", [curCSSTop, curCSSLeft]) > -1, props = {}, curPosition = {}, curTop, curLeft; // need to be able to calculate position if either top or left is auto and position is either absolute or fixed if ( calculatePosition ) { curPosition = curElem.position(); curTop = curPosition.top; curLeft = curPosition.left; } else { curTop = parseFloat( curCSSTop ) || 0; curLeft = parseFloat( curCSSLeft ) || 0; } if ( jQuery.isFunction( options ) ) { options = options.call( elem, i, curOffset ); } if ( options.top != null ) { props.top = ( options.top - curOffset.top ) + curTop; } if ( options.left != null ) { props.left = ( options.left - curOffset.left ) + curLeft; } if ( "using" in options ) { options.using.call( elem, props ); } else { curElem.css( props ); } } }; jQuery.fn.extend({ position: function() { if ( !this[ 0 ] ) { return; } var offsetParent, offset, parentOffset = { top: 0, left: 0 }, elem = this[ 0 ]; // fixed elements are offset from window (parentOffset = {top:0, left: 0}, because it is it's only offset parent if ( jQuery.css( elem, "position" ) === "fixed" ) { // we assume that getBoundingClientRect is available when computed position is fixed offset = elem.getBoundingClientRect(); } else { // Get *real* offsetParent offsetParent = this.offsetParent(); // Get correct offsets offset = this.offset(); if ( !jQuery.nodeName( offsetParent[ 0 ], "html" ) ) { parentOffset = offsetParent.offset(); } // Add offsetParent borders parentOffset.top += jQuery.css( offsetParent[ 0 ], "borderTopWidth", true ); parentOffset.left += jQuery.css( offsetParent[ 0 ], "borderLeftWidth", true ); } // Subtract parent offsets and element margins // note: when an element has margin: auto the offsetLeft and marginLeft // are the same in Safari causing offset.left to incorrectly be 0 return { top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ), left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true) }; }, offsetParent: function() { return this.map(function() { var offsetParent = this.offsetParent || docElem; while ( offsetParent && ( !jQuery.nodeName( offsetParent, "html" ) && jQuery.css( offsetParent, "position") === "static" ) ) { offsetParent = offsetParent.offsetParent; } return offsetParent || docElem; }); } }); // Create scrollLeft and scrollTop methods jQuery.each( {scrollLeft: "pageXOffset", scrollTop: "pageYOffset"}, function( method, prop ) { var top = /Y/.test( prop ); jQuery.fn[ method ] = function( val ) { return jQuery.access( this, function( elem, method, val ) { var win = getWindow( elem ); if ( val === undefined ) { return win ? (prop in win) ? win[ prop ] : win.document.documentElement[ method ] : elem[ method ]; } if ( win ) { win.scrollTo( !top ? val : jQuery( win ).scrollLeft(), top ? val : jQuery( win ).scrollTop() ); } else { elem[ method ] = val; } }, method, val, arguments.length, null ); }; }); function getWindow( elem ) { return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 ? elem.defaultView || elem.parentWindow : false; } // Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods jQuery.each( { Height: "height", Width: "width" }, function( name, type ) { jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name }, function( defaultExtra, funcName ) { // margin is only for outerHeight, outerWidth jQuery.fn[ funcName ] = function( margin, value ) { var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ), extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" ); return jQuery.access( this, function( elem, type, value ) { var doc; if ( jQuery.isWindow( elem ) ) { // As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there // isn't a whole lot we can do. See pull request at this URL for discussion: // https://github.com/jquery/jquery/pull/764 return elem.document.documentElement[ "client" + name ]; } // Get document width or height if ( elem.nodeType === 9 ) { doc = elem.documentElement; // Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], whichever is greatest // unfortunately, this causes bug #3838 in IE6/8 only, but there is currently no good, small way to fix it. return Math.max( elem.body[ "scroll" + name ], doc[ "scroll" + name ], elem.body[ "offset" + name ], doc[ "offset" + name ], doc[ "client" + name ] ); } return value === undefined ? // Get width or height on the element, requesting but not forcing parseFloat jQuery.css( elem, type, extra ) : // Set width or height on the element jQuery.style( elem, type, value, extra ); }, type, chainable ? margin : undefined, chainable, null ); }; }); }); // Limit scope pollution from any deprecated API // (function() { // The number of elements contained in the matched element set jQuery.fn.size = function() { return this.length; }; jQuery.fn.andSelf = jQuery.fn.addBack; // })(); if ( typeof module === "object" && module && typeof module.exports === "object" ) { // Expose jQuery as module.exports in loaders that implement the Node // module pattern (including browserify). Do not create the global, since // the user will be storing it themselves locally, and globals are frowned // upon in the Node module world. module.exports = jQuery; } else { // Otherwise expose jQuery to the global object as usual window.jQuery = window.$ = jQuery; // Register as a named AMD module, since jQuery can be concatenated with other // files that may use define, but not via a proper concatenation script that // understands anonymous AMD modules. A named AMD is safest and most robust // way to register. Lowercase jquery is used because AMD module names are // derived from file names, and jQuery is normally delivered in a lowercase // file name. Do this after creating the global so that if an AMD module wants // to call noConflict to hide this version of jQuery, it will work. if ( typeof define === "function" && define.amd ) { define( "jquery", [], function () { return jQuery; } ); } } })( window );
michaelBenin/raptor-editor
src/dependencies/jquery.js
JavaScript
gpl-3.0
274,078
'use strict'; var ParameterDef = function(object) { this.id = object.id; this.summary = object.summary; this.description = object.description; this.type = object.type; this.mandatory = object.mandatory; this.defaultValue = object.defaultValue; }; module.exports = ParameterDef;
linagora/mupee
backend/rules/parameter-definition.js
JavaScript
gpl-3.0
292
Fox.define('views/email/fields/from-email-address', 'views/fields/link', function (Dep) { return Dep.extend({ listTemplate: 'email/fields/from-email-address/detail', detailTemplate: 'email/fields/from-email-address/detail', }); });
ilovefox8/zhcrm
client/src/views/email/fields/from-email-address.js
JavaScript
gpl-3.0
261
export function Bounds(width, height) { this.width = width; this.height = height; } Bounds.prototype.equals = function(o) { return ((o != null) && (this.width == o.width) && (this.height == o.height)); };
elkonurbaev/nine-e
src/utils/Bounds.js
JavaScript
gpl-3.0
219
// The Vue build version to load with the `import` command // (runtime-only or standalone) has been set in webpack.base.conf with an alias. import Vue from 'vue'; import BootstrapVue from 'bootstrap-vue'; import 'bootstrap-vue/dist/bootstrap-vue.css'; import 'bootstrap/dist/css/bootstrap.css'; import { mapActions } from 'vuex'; import App from './App'; import websock from './websock'; import * as mtype from './store/mutation-types'; import store from './store'; Vue.config.productionTip = false; Vue.use(BootstrapVue); /* eslint-disable no-new */ new Vue({ el: '#app', template: '<App/>', store, components: { App }, created() { websock.connect(message => this.newMessage(message)); setInterval(() => { store.commit(mtype.UPDATE_CALLS_DUR); }, 1000); }, methods: mapActions(['newMessage']), });
staskobzar/amiws
web_root_vue/src/main.js
JavaScript
gpl-3.0
826
/** * Created by caimiao on 15-6-14. */ define(function(require, exports, module) { exports.hello= function (echo) { alert(echo); }; })
caimmy/prehistory
static/js/js_modules/archjs_tools.js
JavaScript
gpl-3.0
154
{"exchange_info":[{"onclick":null,"link":null,"value":"+34 943 018 705"},{"onclick":null,"link":"mailto:[email protected]","value":"[email protected]"},{"onclick":"window.open(this.href,'ix-new-window');return false;","link":"http://www.euskonix.com/principal.html","value":"Website"}],"address":["EuskoNIX (Bilbao, Spain)","\u003Caddress not available\u003E","Bilbao, Spain"],"name":"EuskoNIX (Bilbao, Spain)","id":"euskonix-bilbao-spain","buildings":[{"latitude":"43.268582","address":["\u003Caddress not available\u003E","Bilbao, Spain"],"longitude":"-2.946141","offset":"background:url('images/markers.png') no-repeat -22px 0;","id":18821}]}
brangerbriz/webroutes
nw-app/telegeography-data/internetexchanges/internet-exchanges/euskonix-bilbao-spain.js
JavaScript
gpl-3.0
641
'use strict' // untuk status uploader const STATUS_INITIAL = 0 const STATUS_SAVING = 1 const STATUS_SUCCESS = 2 const STATUS_FAILED = 3 // base url api const BASE_URL = 'http://localhost:3000' const app = new Vue({ el: '#app', data: { message: 'Hello', currentStatus: null, uploadError: null, uploadFieldName: 'image', uploadedFiles: [], files:[] }, computed: { isInitial() { return this.currentStatus === STATUS_INITIAL; }, isSaving() { return this.currentStatus === STATUS_SAVING; }, isSuccess() { return this.currentStatus === STATUS_SUCCESS; }, isFailed() { return this.currentStatus === STATUS_FAILED; } }, // computed methods: { // reset form to initial state getAllFile () { let self = this axios.get(`${BASE_URL}/files`) .then(response => { self.files = response.data }) }, // getAllFile() deleteFile (id) { axios.delete(`${BASE_URL}/files/${id}`) .then(r => { this.files.splice(id, 1) }) }, reset() { this.currentStatus = STATUS_INITIAL; this.uploadedFiles = []; this.uploadError = null; }, // reset() // upload data to the server save(formData) { console.log('save') console.log('form data', formData) this.currentStatus = STATUS_SAVING; axios.post(`${BASE_URL}/files/add`, formData) .then(up => { // console.log('up', up) this.uploadedFiles = [].concat(up) this.currentStatus = STATUS_SUCCESS }) .catch(e => { console.log(e.response.data) this.currentStatus = STATUS_FAILED }) }, // save() filesChange(fieldName, fileList) { // handle file changes const formData = new FormData(); formData.append('image', fileList[0]) console.log(formData) this.save(formData); } // filesChange() }, // methods mounted () { this.reset() }, created () { this.getAllFile() } })
hariantara/rapid-share-clone
client/assets/lib/upload.js
JavaScript
gpl-3.0
2,046
sap.ui.jsview(ui5nameSpace, { // define the (default) controller type for this View getControllerName: function() { return "my.own.controller"; }, // defines the UI of this View createContent: function(oController) { // button text is bound to Model, "press" action is bound to Controller's event handler return; } });
Ryan-Boyd/ui5-artisan
lib/stubs/views/PlainView.js
JavaScript
gpl-3.0
368
#pragma strict var playerFinalScore: int; var Users: List.< GameObject >; var userData: GameObject[]; var maxPlayers: int; var gameManager: GameObject; var currentPlayer: int; var currentName: String; function Awake () { //var users :GameObject = GameObject.Find("_UserControllerFB"); userData = GameObject.FindGameObjectsWithTag("Player"); } function Start() { gameManager = GameObject.Find("__GameManager"); NotificationCenter.DefaultCenter().AddObserver(this, "PlayerChanger"); } function Update () { if(Users.Count>0) playerFinalScore = Users[0].GetComponent(_GameManager).playerFinalScore; } function PlayerChanger() { currentPlayer++; for(var i: int; i<Users.Count; i++) { if(i!=currentPlayer)Users[i].SetActive(false); else Users[i].SetActive(true); } print("Change Player"); if(currentPlayer>maxPlayers) currentPlayer=0; } function OnLevelWasLoaded(level: int) { maxPlayers = userData.Length; gameManager = GameObject.Find("__GameManager"); for(var i: int; i< userData.Length; i++) { if(i!=0)Users[i].SetActive(false); Users[i].name = userData[i].name; currentName = Users[0].name; Users[i].transform.parent = gameManager.transform; } }
RomanKorchmenko/BowlingFX
BowlingFX/Assets/ScoreTransfer.js
JavaScript
gpl-3.0
1,210
'use strict'; /*global require, after, before*/ var async = require('async'), assert = require('assert'), db = require('../mocks/databasemock'); describe('Set methods', function() { describe('setAdd()', function() { it('should add to a set', function(done) { db.setAdd('testSet1', 5, function(err) { assert.equal(err, null); assert.equal(arguments.length, 1); done(); }); }); it('should add an array to a set', function(done) { db.setAdd('testSet1', [1, 2, 3, 4], function(err) { assert.equal(err, null); assert.equal(arguments.length, 1); done(); }); }); }); describe('getSetMembers()', function() { before(function(done) { db.setAdd('testSet2', [1,2,3,4,5], done); }); it('should return an empty set', function(done) { db.getSetMembers('doesnotexist', function(err, set) { assert.equal(err, null); assert.equal(arguments.length, 2); assert.equal(Array.isArray(set), true); assert.equal(set.length, 0); done(); }); }); it('should return a set with all elements', function(done) { db.getSetMembers('testSet2', function(err, set) { assert.equal(err, null); assert.equal(set.length, 5); set.forEach(function(value) { assert.notEqual(['1', '2', '3', '4', '5'].indexOf(value), -1); }); done(); }); }); }); describe('setsAdd()', function() { it('should add to multiple sets', function(done) { db.setsAdd(['set1', 'set2'], 'value', function(err) { assert.equal(err, null); assert.equal(arguments.length, 1); done(); }); }); }); describe('getSetsMembers()', function() { before(function(done) { db.setsAdd(['set3', 'set4'], 'value', done); }); it('should return members of two sets', function(done) { db.getSetsMembers(['set3', 'set4'], function(err, sets) { assert.equal(err, null); assert.equal(Array.isArray(sets), true); assert.equal(arguments.length, 2); assert.equal(Array.isArray(sets[0]) && Array.isArray(sets[1]), true); assert.strictEqual(sets[0][0], 'value'); assert.strictEqual(sets[1][0], 'value'); done(); }); }); }); describe('isSetMember()', function() { before(function(done) { db.setAdd('testSet3', 5, done); }); it('should return false if element is not member of set', function(done) { db.isSetMember('testSet3', 10, function(err, isMember) { assert.equal(err, null); assert.equal(arguments.length, 2); assert.equal(isMember, false); done(); }); }); it('should return true if element is a member of set', function(done) { db.isSetMember('testSet3', 5, function(err, isMember) { assert.equal(err, null); assert.equal(arguments.length, 2); assert.equal(isMember, true); done(); }); }); }); describe('isSetMembers()', function() { before(function(done) { db.setAdd('testSet4', [1, 2, 3, 4, 5], done); }); it('should return an array of booleans', function(done) { db.isSetMembers('testSet4', ['1', '2', '10', '3'], function(err, members) { assert.equal(err, null); assert.equal(arguments.length, 2); assert.equal(Array.isArray(members), true); assert.deepEqual(members, [true, true, false, true]); done(); }); }); }); describe('isMemberOfSets()', function() { before(function(done) { db.setsAdd(['set1', 'set2'], 'value', done); }); it('should return an array of booleans', function(done) { db.isMemberOfSets(['set1', 'testSet1', 'set2', 'doesnotexist'], 'value', function(err, members) { assert.equal(err, null); assert.equal(arguments.length, 2); assert.equal(Array.isArray(members), true); assert.deepEqual(members, [true, false, true, false]); done(); }); }); }); describe('setCount()', function() { before(function(done) { db.setAdd('testSet5', [1,2,3,4,5], done); }); it('should return the element count of set', function(done) { db.setCount('testSet5', function(err, count) { assert.equal(err, null); assert.equal(arguments.length, 2); assert.strictEqual(count, 5); done(); }); }); }); describe('setsCount()', function() { before(function(done) { async.parallel([ async.apply(db.setAdd, 'set5', [1,2,3,4,5]), async.apply(db.setAdd, 'set6', 1), async.apply(db.setAdd, 'set7', 2) ], done); }); it('should return the element count of sets', function(done) { db.setsCount(['set5', 'set6', 'set7', 'doesnotexist'], function(err, counts) { assert.equal(err, null); assert.equal(arguments.length, 2); assert.equal(Array.isArray(counts), true); assert.deepEqual(counts, [5, 1, 1, 0]); done(); }); }); }); describe('setRemove()', function() { before(function(done) { db.setAdd('testSet6', [1, 2], done); }); it('should remove a element from set', function(done) { db.setRemove('testSet6', '2', function(err) { assert.equal(err, null); assert.equal(arguments.length, 1); db.isSetMember('testSet6', '2', function(err, isMember) { assert.equal(err, null); assert.equal(isMember, false); done(); }); }); }); }); describe('setsRemove()', function() { before(function(done) { db.setsAdd(['set1', 'set2'], 'value', done); }); it('should remove a element from multiple sets', function(done) { db.setsRemove(['set1', 'set2'], 'value', function(err) { assert.equal(err, null); assert.equal(arguments.length, 1); db.isMemberOfSets(['set1', 'set2'], 'value', function(err, members) { assert.equal(err, null); assert.deepEqual(members, [false, false]); done(); }); }); }); }); describe('setRemoveRandom()', function() { before(function(done) { db.setAdd('testSet7', [1,2,3,4,5], done); }); it('should remove a random element from set', function(done) { db.setRemoveRandom('testSet7', function(err, element) { assert.equal(err, null); assert.equal(arguments.length, 2); db.isSetMember('testSet', element, function(err, ismember) { assert.equal(err, null); assert.equal(ismember, false); done(); }); }); }); }); after(function(done) { db.flushdb(done); }); });
seafruit/NodeBB
test/database/sets.js
JavaScript
gpl-3.0
6,160
/*jshint expr:true */ describe("Services: Core System Messages", function() { beforeEach(module("risevision.core.systemmessages")); beforeEach(module(function ($provide) { //stub services $provide.service("$q", function() {return Q;}); $provide.value("userState", { isRiseVisionUser: function () {return true; } }); })); it("should exist", function() { inject(function(getCoreSystemMessages) { expect(getCoreSystemMessages).be.defined; }); }); });
Rise-Vision/ng-core-api-client
test/unit/svc-system-messages-spec.js
JavaScript
gpl-3.0
499
// Copyright 2015, 2016 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. import React, { Component, PropTypes } from 'react'; import { observer } from 'mobx-react'; import { Button, GasPriceEditor } from '~/ui'; import TransactionMainDetails from '../TransactionMainDetails'; import TransactionPendingForm from '../TransactionPendingForm'; import styles from './transactionPending.css'; import * as tUtil from '../util/transaction'; @observer export default class TransactionPending extends Component { static contextTypes = { api: PropTypes.object.isRequired }; static propTypes = { className: PropTypes.string, date: PropTypes.instanceOf(Date).isRequired, focus: PropTypes.bool, gasLimit: PropTypes.object, id: PropTypes.object.isRequired, isSending: PropTypes.bool.isRequired, isTest: PropTypes.bool.isRequired, nonce: PropTypes.number, onConfirm: PropTypes.func.isRequired, onReject: PropTypes.func.isRequired, store: PropTypes.object.isRequired, transaction: PropTypes.shape({ data: PropTypes.string, from: PropTypes.string.isRequired, gas: PropTypes.object.isRequired, gasPrice: PropTypes.object.isRequired, to: PropTypes.string, value: PropTypes.object.isRequired }).isRequired }; static defaultProps = { focus: false }; gasStore = new GasPriceEditor.Store(this.context.api, { gas: this.props.transaction.gas.toFixed(), gasLimit: this.props.gasLimit, gasPrice: this.props.transaction.gasPrice.toFixed() }); componentWillMount () { const { store, transaction } = this.props; const { from, gas, gasPrice, to, value } = transaction; const fee = tUtil.getFee(gas, gasPrice); // BigNumber object const gasPriceEthmDisplay = tUtil.getEthmFromWeiDisplay(gasPrice); const gasToDisplay = tUtil.getGasDisplay(gas); const totalValue = tUtil.getTotalValue(fee, value); this.setState({ gasPriceEthmDisplay, totalValue, gasToDisplay }); this.gasStore.setEthValue(value); store.fetchBalances([from, to]); } render () { return this.gasStore.isEditing ? this.renderGasEditor() : this.renderTransaction(); } renderTransaction () { const { className, focus, id, isSending, isTest, store, transaction } = this.props; const { totalValue } = this.state; const { from, value } = transaction; const fromBalance = store.balances[from]; return ( <div className={ `${styles.container} ${className}` }> <TransactionMainDetails className={ styles.transactionDetails } from={ from } fromBalance={ fromBalance } gasStore={ this.gasStore } id={ id } isTest={ isTest } totalValue={ totalValue } transaction={ transaction } value={ value } /> <TransactionPendingForm address={ from } focus={ focus } isSending={ isSending } onConfirm={ this.onConfirm } onReject={ this.onReject } /> </div> ); } renderGasEditor () { const { className } = this.props; return ( <div className={ `${styles.container} ${className}` }> <GasPriceEditor store={ this.gasStore }> <Button label='view transaction' onClick={ this.toggleGasEditor } /> </GasPriceEditor> </div> ); } onConfirm = (data) => { const { id, transaction } = this.props; const { password, wallet } = data; const { gas, gasPrice } = this.gasStore.overrideTransaction(transaction); this.props.onConfirm({ gas, gasPrice, id, password, wallet }); } onReject = () => { this.props.onReject(this.props.id); } toggleGasEditor = () => { this.gasStore.setEditing(false); } }
jesuscript/parity
js/src/views/Signer/components/TransactionPending/transactionPending.js
JavaScript
gpl-3.0
4,499
import { useState } from "react"; import { PropTypes } from "prop-types"; import { SaveOutlined, WarningOutlined } from "@ant-design/icons"; import { Button, Col, Form, Input, InputNumber, Row, Select, Switch, Typography, Space, } from "@nextgisweb/gui/antd"; import i18n from "@nextgisweb/pyramid/i18n!"; import { AddressGeocoderOptions, DegreeFormatOptions, UnitsAreaOptions, UnitsLengthOptions, } from "./select-options"; const { Title } = Typography; const INPUT_DEFAULT_WIDTH = { width: "100%" }; export const SettingsForm = ({ onFinish, initialValues, srsOptions, status, }) => { const [geocoder, setGeocoder] = useState( initialValues.address_geocoder || "nominatim" ); const onValuesChange = (changedValues, allValues) => { setGeocoder(allValues.address_geocoder); }; return ( <Form name="webmap_settings" className="webmap-settings-form" initialValues={initialValues} onFinish={onFinish} onValuesChange={onValuesChange} layout="vertical" > <Title level={4}>{i18n.gettext("Identify popup")}</Title> <Row gutter={[16, 16]}> <Col span={8}> <Form.Item name="popup_width" label={i18n.gettext("Width, px")} rules={[ { required: true, }, ]} > <InputNumber min="100" style={INPUT_DEFAULT_WIDTH} /> </Form.Item> </Col> <Col span={8}> <Form.Item name="popup_height" label={i18n.gettext("Height, px")} rules={[ { required: true, }, ]} > <InputNumber min="100" style={INPUT_DEFAULT_WIDTH} /> </Form.Item> </Col> <Col span={8}> <Form.Item name="identify_radius" label={i18n.gettext("Radius, px")} rules={[ { required: true, }, ]} > <InputNumber min="1" style={INPUT_DEFAULT_WIDTH} /> </Form.Item> </Col> </Row> <Row gutter={[16, 16]}> <Col span={24}> <Form.Item> <Space direction="horizontal"> <Form.Item noStyle name="identify_attributes" valuePropName="checked" > <Switch /> </Form.Item> {i18n.gettext("Show feature attributes")} </Space> </Form.Item> </Col> </Row> <Title level={4}>{i18n.gettext("Measurement")}</Title> <Row gutter={[16, 16]}> <Col span={8}> <Form.Item name="units_length" label={i18n.gettext("Length units")} > <Select options={UnitsLengthOptions} style={INPUT_DEFAULT_WIDTH} /> </Form.Item> </Col> <Col span={8}> <Form.Item name="units_area" label={i18n.gettext("Area units")} > <Select options={UnitsAreaOptions} style={INPUT_DEFAULT_WIDTH} /> </Form.Item> </Col> <Col span={8}> <Form.Item name="degree_format" label={i18n.gettext("Degree format")} > <Select options={DegreeFormatOptions} style={INPUT_DEFAULT_WIDTH} /> </Form.Item> </Col> </Row> <Row gutter={[16, 16]}> <Col span={24}> <Form.Item name="measurement_srid" label={i18n.gettext("Measurement SRID")} > <Select options={srsOptions} style={INPUT_DEFAULT_WIDTH} /> </Form.Item> </Col> </Row> <Title level={4}>{i18n.gettext("Address search")}</Title> <Row gutter={[16, 16]}> <Col span={8}> <Form.Item> <Space direction="horizontal"> <Form.Item noStyle name="address_search_enabled" valuePropName="checked" > <Switch /> </Form.Item> {i18n.gettext("Enable")} </Space> </Form.Item> </Col> <Col span={16}> <Form.Item> <Space direction="horizontal"> <Form.Item noStyle name="address_search_extent" valuePropName="checked" > <Switch /> </Form.Item> {i18n.gettext("Limit by web map initial extent")} </Space> </Form.Item> </Col> </Row> <Row gutter={[16, 16]}> <Col span={8}> <Form.Item name="address_geocoder" label={i18n.gettext("Provider")} > <Select options={AddressGeocoderOptions} style={INPUT_DEFAULT_WIDTH} /> </Form.Item> </Col> <Col span={16}> {geocoder == "nominatim" ? ( <Form.Item name="nominatim_countrycodes" label={i18n.gettext( "Limit search results to countries" )} rules={[ { pattern: new RegExp( /^(?:(?:[A-Za-z]+)(?:-[A-Za-z]+)?(?:,|$))+(?<!,)$/ ), message: ( <div> {i18n.gettext( "Invalid countries. For example ru or gb,de" )} </div> ), }, ]} > <Input style={INPUT_DEFAULT_WIDTH} /> </Form.Item> ) : ( <Form.Item name="yandex_api_geocoder_key" label={i18n.gettext("Yandex.Maps API Geocoder Key")} > <Input style={INPUT_DEFAULT_WIDTH} /> </Form.Item> )} </Col> </Row> <Row className="row-submit"> <Col> <Button htmlType="submit" type={"primary"} danger={status === "saved-error"} icon={ status === "saved-error" ? ( <WarningOutlined /> ) : ( <SaveOutlined /> ) } loading={status === "saving"} > {i18n.gettext("Save")} </Button> </Col> </Row> </Form> ); }; SettingsForm.propTypes = { initialValues: PropTypes.object, onFinish: PropTypes.func, srsOptions: PropTypes.array, status: PropTypes.string, };
nextgis/nextgisweb
nextgisweb/webmap/nodepkg/settings/SettingsForm.js
JavaScript
gpl-3.0
9,428
var _ = require("lodash"); module.exports = { // ensure client accepts json json_request: function(req, res, next){ if(req.accepts("application/json")) return next(); res.stash.code = 406; _.last(req.route.stack).handle(req, res, next); }, // init response init_response: function(req, res, next){ res.stash = {}; res.response_start = new Date(); return next(); }, // respond to client handle_response: function(req, res, next){ res.setHeader("X-Navigator-Response-Time", new Date() - res.response_start); res.stash = _.defaults(res.stash, { code: 404 }); if(_.has(res.stash, "body")) res.status(res.stash.code).json(res.stash.body); else res.sendStatus(res.stash.code); } }
normanjoyner/containership.plugin.navigator
lib/middleware.js
JavaScript
gpl-3.0
854
var struct_m_s_vehicle_1_1_lane_q = [ [ "allowsContinuation", "d3/d89/struct_m_s_vehicle_1_1_lane_q.html#a1491a03d3e914ce9f78fe892c6f8594b", null ], [ "bestContinuations", "d3/d89/struct_m_s_vehicle_1_1_lane_q.html#a2fc7b1df76210eff08026dbd53c13312", null ], [ "bestLaneOffset", "d3/d89/struct_m_s_vehicle_1_1_lane_q.html#aa7f926a77c7d33c071c620ae7e9d0ac1", null ], [ "lane", "d3/d89/struct_m_s_vehicle_1_1_lane_q.html#a3df6bd9b94a7e3e4795547feddf68bf2", null ], [ "length", "d3/d89/struct_m_s_vehicle_1_1_lane_q.html#a637a05a2b120bacaf781181febc5b3bb", null ], [ "nextOccupation", "d3/d89/struct_m_s_vehicle_1_1_lane_q.html#acf8243e1febeb75b139a8b10bb679107", null ], [ "occupation", "d3/d89/struct_m_s_vehicle_1_1_lane_q.html#a51e793a9c0bfda3e315c62f579089f82", null ] ];
cathyyul/sumo-0.18
docs/doxygen/d3/d89/struct_m_s_vehicle_1_1_lane_q.js
JavaScript
gpl-3.0
801
jQuery(document).ready(function($) { $('#slide-left').flexslider({ animation: "slide", controlNav: "thumbnails", start: function(slider) { $('ol.flex-control-thumbs li img.flex-active').parent('li').addClass('active'); } }); }); jQuery(document).ready(function($) { $('#slide').flexslider({ animation: "slide", controlNav: false, directionNav: true }); });
vietnamframework/vietnamframework
app/view/newstreecolumn/js/jquery.flexslider.init.js
JavaScript
gpl-3.0
414
// NOTE: nbApp is defined in app.js nbApp.directive("languageContainerDirective", function() { return { restrict : 'E', templateUrl : 'js/templates/language-container.html', scope: { color: "@", language: "@", reading: "@", writing: "@", listening: "@", speaking: "@", flag: "@", }, link: function(scope, element, attrs) { scope.color = attrs.color; scope.language = attrs.language; scope.reading = attrs.reading; scope.writing = attrs.writing; scope.listening = attrs.listening; scope.speaking = attrs.speaking; scope.flag = attrs.flag; scope.$watch('language', function(nV, oV) { if(nV){ RadarChart.defaultConfig.color = function() {}; RadarChart.defaultConfig.radius = 3; RadarChart.defaultConfig.w = 250; RadarChart.defaultConfig.h = 250; /* * 0 - No Practical Proficiency * 1 - Elementary Proficiency * 2 - Limited Working Proficiency * 3 - Minimum Professional Proficiency * 4 - Full Professional Proficiency * 5 - Native or Bilingual Proficiency Read: the ability to read and understand texts written in the language Write: the ability to formulate written texts in the language Listen: the ability to follow and understand speech in the language Speak: the ability to produce speech in the language and be understood by its speakers. */ var data = [ { className: attrs.language, // optional can be used for styling axes: [ {axis: "Reading", value: attrs.reading}, {axis: "Writing", value: attrs.writing}, {axis: "Listening", value: attrs.listening}, {axis: "Speaking", value: attrs.speaking}, ] }, ]; function mapData() { return data.map(function(d) { return { className: d.className, axes: d.axes.map(function(axis) { return {axis: axis.axis, value: axis.value}; }) }; }); } // chart.config.w; // chart.config.h; // chart.config.axisText = true; // chart.config.levels = 5; // chart.config.maxValue = 5; // chart.config.circles = true; // chart.config.actorLegend = 1; var chart = RadarChart.chart(); var cfg = chart.config(); // retrieve default config cfg = chart.config({axisText: true, levels: 5, maxValue: 5, circles: true}); // retrieve default config var svg = d3.select('.' + attrs.language).append('svg') .attr('width', 250) .attr('height', 270); svg.append('g').classed('single', 1).datum(mapData()).call(chart); console.log('Rendering new language Radar Viz! --> ' + attrs.language); } }) } }; });
nbuechler/nb.com-v8
js/directives/language-container-directive.js
JavaScript
gpl-3.0
3,501
// app.photoGrid var Backbone = require("backbone"); // var _ = require("underscore"); var $ = require("jquery"); var ImageGridFuncs = require("./photo_grid_functions"); var ImageCollection = require("../models/photo_grid_image_collection"); var ImageView = require("./photo_grid_image"); module.exports = Backbone.View.extend({ el: '#photo-grid', initialize: function () { "use strict"; if (this.$el.length === 1) { var gridJSON = this.$(".hid"); if (gridJSON.length === 1) { this.funcs = new ImageGridFuncs(); this.template = this.funcs.slideTemplate(); // there is only one allowed div.hid gridJSON = JSON.parse(gridJSON[0].innerHTML); if (gridJSON.spacer_URL && gridJSON.image_URL) { this.model.set({ parentModel: this.model, // pass as reference spacerURL: gridJSON.spacer_URL, imageURL: gridJSON.image_URL, spacers: gridJSON.spacers, images: gridJSON.images, // shuffle image order: imagesShuffled: this.funcs.shuffleArray(gridJSON.images), }); this.setupGrid(); } this.model.on({ 'change:currentSlide': this.modelChange }, this); app.mindbodyModel.on({ 'change:popoverVisible': this.killSlides }, this); } } }, setupGrid: function () { "use strict"; var that = this, spacers = this.model.get("spacers"), randomInt, imageCollection = new ImageCollection(), i; for (i = 0; i < this.model.get("images").length; i += 1) { randomInt = that.funcs.getRandomInt(0, spacers.length); imageCollection.add({ // push some info to individual views: parentModel: this.model, order: i, spacerURL: this.model.get("spacerURL"), spacer: spacers[randomInt], imageURL: this.model.get("imageURL"), image: this.model.get("imagesShuffled")[i], }); } imageCollection.each(this.imageView, this); }, imageView: function (imageModel) { "use strict"; var imageView = new ImageView({model: imageModel}); this.$el.append(imageView.render().el); }, modelChange: function () { "use strict"; var currSlide = this.model.get("currentSlide"), allImages = this.model.get("imageURL"), imageInfo, imageViewer, imgWidth, slideDiv; if (currSlide !== false) { if (app.mindbodyModel.get("popoverVisible") !== true) { app.mindbodyModel.set({popoverVisible : true}); } // retrieve cached DOM object: imageViewer = app.mbBackGroundShader.openPopUp("imageViewer"); // set the stage: imageViewer.html(this.template(this.model.toJSON())); // select div.slide, the ugly way: slideDiv = imageViewer[0].getElementsByClassName("slide")[0]; // pull the array of info about the image: imageInfo = this.model.get("images")[currSlide]; // calculate the size of the image when it fits the slideshow: imgWidth = this.funcs.findSlideSize(imageInfo, slideDiv.offsetWidth, slideDiv.offsetHeight); slideDiv.innerHTML = '<img src="' + allImages + imageInfo.filename + '" style="width: ' + imgWidth + 'px;" />'; } }, killSlides: function () { "use strict"; if (app.mindbodyModel.get("popoverVisible") === false) { // popover is gone. No more slideshow. this.model.set({currentSlide : false}); } }, });
alexkademan/solful-2016-wp
_assets/js/views/photo_grid.js
JavaScript
gpl-3.0
4,143
// Remove the particular item function removeArr(arr , removeItem){ if(arr.indexOf(removeItem) > -1){ arr.splice(arr.indexOf(removeItem),1); } return arr; }
SCABER-Dev-Team/SCABER
client-service/js/user_defined_operator.js
JavaScript
gpl-3.0
177
const gal=[//731-62 '1@001/b4avsq1y2i', '1@002/50uvpeo7tb', '1@002/0ypu4wgjxm', '1@002/b61d80e9pf', '1@002/f1kb57t4ul', '1@002/swq38v49nz', '1@002/zeak367fw1', '1@003/nx1ld4j9pe', '1@003/yh0ub5rank', '1@004/j29uftobmh', '1@005/0asu1qo75n', '1@005/4c7bn1q5mx', '1@005/le3vrzbwfs', '1@006/ek0tq9wvny', '1@006/ax21m8tjos', '1@006/w2e3104dp6', '1@007/bsukxlv9j7', '1@007/w5cpl0uvy6', '1@007/l04q3wrucj', '2@007/s2hr6jv7nc', '2@009/31yrxp8waj', '2@009/8josfrbgwi', '2@009/rt4jie1fg8', '2@009/p0va85n4gf', '2@010/i9thzxn50q', '3@010/a6w84ltj02', '3@010/mfyevin3so', '3@010/wdy5qzflnv', '3@011/06wim8bjdp', '3@011/avtd46k9cx', '3@011/80915y2exz', '3@011/vkt4dalwhb', '3@011/znudscat9h', '3@012/18xg4h9s3i', '3@012/120sub86vt', '3@012/5gxj7u0om8', '3@012/95gzec2rsm', '3@012/dihoerqp40', '3@012/nif7secp8l', '3@012/q8awn1iplo', '3@012/ubzfcjte63', '3@013/b9atnq1les', '3@013/zof4tprh73', '3@013/lvdyctgefs', '4@013/c7fgqbsxkn', '4@013/ci9vg76yj5', '4@013/y3v8tjreas', '4@014/75krn9ifbp', '4@014/9tf7n5iexy', '4@014/boz3y1wauf', '4@014/ihqxma938n', '4@014/suxj4yv5w6', '4@014/o19tbsqjxe', '4@014/wy8tx24g0c', '4@015/302u7cs5nx', '4@015/4bo9c8053u', '4@015/8clxnh6eao', '4@015/hbi1d9grwz', '4@015/w8vmtnod7z', '5@016/0yeinjua6h', '5@016/rgpcwv4nym', '5@016/scxjm7ofar'];
Klanly/klanly.github.io
imh/az60.js
JavaScript
gpl-3.0
1,322
QUnit.test( "testGetIbanCheckDigits", function( assert ) { assert.equal(getIBANCheckDigits( 'GB00WEST12345698765432' ), '82', 'Get check digits of an IBAN' ); assert.equal(getIBANCheckDigits( '1234567890' ), '', 'If string isn\'t an IBAN, returns empty' ); assert.equal(getIBANCheckDigits( '' ), '', 'If string is empty, returns empty' ); } ); QUnit.test( "testGetGlobalIdentifier", function( assert ) { assert.equal(getGlobalIdentifier( 'G28667152', 'ES', '' ), 'ES55000G28667152', 'Obtain a global Id' ); } ); QUnit.test( "testReplaceCharactersNotInPattern", function( assert ) { assert.equal(replaceCharactersNotInPattern( 'ABC123-?:', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', '0' ), 'ABC123000', 'Remove unwanted characters' ); assert.equal(replaceCharactersNotInPattern( '12345', '0123456789', '0' ), '12345', 'If the string didn\'t have unwanted characters, returns it' ); } ); QUnit.test( "testReplaceLetterWithDigits", function( assert ) { assert.equal(replaceLetterWithDigits( '510007547061BE00' ), '510007547061111400', 'Replaces letters with digits' ); assert.equal(replaceLetterWithDigits( '1234567890' ), '1234567890', 'If we only receive digits, we return them' ); assert.equal(replaceLetterWithDigits( '' ), '', 'If we receive empty, we return empty' ); } ); QUnit.test( "testGetAccountLength", function( assert ) { assert.equal(getAccountLength( 'GB' ), 22, 'Returns tohe string th a SEPA country' ); assert.equal(getAccountLength( 'US' ), 0, 'If string isn\'t a SEPA country code, returns empty' ); assert.equal(getAccountLength( '' ), 0, 'If string is empty, returns empty' ); } ); QUnit.test( "testIsSepaCountry", function( assert ) { assert.equal(isSepaCountry( 'ES' ) , 1, 'Detects SEPA countries' ); assert.equal(isSepaCountry( 'US' ), 0, 'Rejects non SEPA countries' ); assert.equal(isSepaCountry( '' ) , 0, 'If string is empty, returns empty' ); } ); QUnit.test( "testIsValidIban", function( assert ) { assert.equal(isValidIBAN( 'GB82WEST12345698765432' ), 1, 'Accepts a good IBAN' ); assert.equal(isValidIBAN( 'GB00WEST12345698765432' ) , 0, 'Rejects a wrong IBAN' ); assert.equal(isValidIBAN( '' ), 0, 'Rejects empty strings' ); } );
amnesty/dataquality
test/javascript/iban.js
JavaScript
gpl-3.0
2,366
Bitrix 16.5 Business Demo = bf14f0c5bad016e66d0ed2d224b15630
gohdan/DFC
known_files/hashes/bitrix/modules/main/install/js/main/amcharts/3.11/lang/hr.min.js
JavaScript
gpl-3.0
61
function HistoryAssistant() { } HistoryAssistant.prototype.setup = function() { this.appMenuModel = { visible: true, items: [ { label: $L("About"), command: 'about' }, { label: $L("Help"), command: 'tutorial' }, ] }; this.controller.setupWidget(Mojo.Menu.appMenu, {omitDefaultItems: true}, this.appMenuModel); var attributes = {}; this.model = { //backgroundImage : 'images/glacier.png', background: 'black', onLeftFunction : this.wentLeft.bind(this), onRightFunction : this.wentRight.bind(this) } this.controller.setupWidget('historydiv', attributes, this.model); this.myPhotoDivElement = $('historydiv'); this.timestamp = new Date().getTime(); var env = Mojo.Environment.DeviceInfo; if (env.screenHeight <= 400) this.myPhotoDivElement.style.height = "372px"; } HistoryAssistant.prototype.wentLeft = function(event){ this.timestamp = this.timestamp - (1000*60*60*24); var timenow = new Date(this.timestamp); var timenowstring = ""; var Ayear = timenow.getUTCFullYear(); var Amonth = timenow.getUTCMonth()+1; if(Amonth.toString().length < 2) Amonth = "0" + Amonth; var Aday = timenow.getUTCDate(); if(Aday.toString().length < 2) Aday = "0" + Aday; /*var Ahours = timenow.getUTCHours(); if(Ahours.toString().length < 2) Ahours = "0" + Ahours;*/ Ahours = "00"; if (this.timestamp > 1276146000000) { if (this.timestamp > 1276146000000 + (1000 * 60 * 60 * 24)) { this.myPhotoDivElement.mojo.leftUrlProvided("http://100ps.omoco.de/100pixels/history/" + Ayear + Amonth + (Aday - 1) + Ahours + ".png"); } this.myPhotoDivElement.mojo.centerUrlProvided("http://100ps.omoco.de/100pixels/history/" + Ayear + Amonth + (Aday) + Ahours + ".png"); this.myPhotoDivElement.mojo.rightUrlProvided("http://100ps.omoco.de/100pixels/history/" + Ayear + Amonth + (Aday + 1) + Ahours + ".png"); } $('text').innerHTML = "<center>Histoy Of Pixels&nbsp;&nbsp;&nbsp;-&nbsp;&nbsp;&nbsp;" + Ayear + " / " + Amonth + " / " + Aday + "</center>"; } HistoryAssistant.prototype.wentRight = function(event){ this.timestamp = this.timestamp + (1000*60*60*24); var timenow = new Date(this.timestamp); var timenowstring = ""; var Ayear = timenow.getUTCFullYear(); var Amonth = timenow.getUTCMonth()+1; if(Amonth.toString().length < 2) Amonth = "0" + Amonth; var Aday = timenow.getUTCDate(); if(Aday.toString().length < 2) Aday = "0" + Aday; /*var Ahours = timenow.getUTCHours(); if(Ahours.toString().length < 2) Ahours = "0" + Ahours;*/ Ahours = "00"; if (this.timestamp < new Date().getTime()) { this.myPhotoDivElement.mojo.leftUrlProvided("http://100ps.omoco.de/100pixels/history/" + Ayear + Amonth + (Aday - 1) + Ahours + ".png"); this.myPhotoDivElement.mojo.centerUrlProvided("http://100ps.omoco.de/100pixels/history/" + Ayear + Amonth + (Aday) + Ahours + ".png"); if (this.timestamp + (1000*60*60*24) < new Date().getTime()) { this.myPhotoDivElement.mojo.rightUrlProvided("http://100ps.omoco.de/100pixels/history/" + Ayear + Amonth + (Aday + 1) + Ahours + ".png"); } } $('text').innerHTML = "<center>Histoy Of Pixels&nbsp;&nbsp;&nbsp;-&nbsp;&nbsp;&nbsp;" + Ayear + " / " + Amonth + " / " + Aday + "</center>"; } HistoryAssistant.prototype.activate = function(event) { var timenow = new Date(this.timestamp); var timenowstring = ""; var Ayear = timenow.getUTCFullYear(); var Amonth = timenow.getUTCMonth()+1; if(Amonth.toString().length < 2) Amonth = "0" + Amonth; var Aday = timenow.getUTCDate(); if(Aday.toString().length < 2) Aday = "0" + Aday; /*var Ahours = timenow.getUTCHours(); if(Ahours.toString().length < 2) Ahours = "0" + Ahours;*/ Ahours = "00"; this.myPhotoDivElement.mojo.leftUrlProvided("http://100ps.omoco.de/100pixels/history/" + Ayear + Amonth + (Aday-1) + Ahours + ".png"); this.myPhotoDivElement.mojo.centerUrlProvided("http://100ps.omoco.de/100pixels/history/" + Ayear + Amonth + (Aday) + Ahours + ".png"); //this.myPhotoDivElement.mojo.rightUrlProvided("http://100ps.omoco.de/100pixels/history/" + Ayear + Amonth + (Aday+1) + Ahours + ".png"); $('text').innerHTML = "<center>Histoy Of Pixels&nbsp;&nbsp;&nbsp;-&nbsp;&nbsp;&nbsp;" + Ayear + " / " + Amonth + " / " + Aday + "</center>"; } HistoryAssistant.prototype.deactivate = function(event) { } HistoryAssistant.prototype.cleanup = function(event) { } HistoryAssistant.prototype.handleCommand = function(event){ if(event.type == Mojo.Event.command) { switch (event.command) { case 'about': Mojo.Controller.stageController.pushScene("about"); break; case 'tutorial': this.controller.showAlertDialog({ onChoose: function(value) {}, title:"Help", message:"This is the history of all pixels user have every created. Every night there is made a new snapshot.<br><br>Flip the image left or right to go through the history. Zoom into the image for more details.", allowHTMLMessage: true, choices:[ {label:'OK', value:'OK', type:'color'} ] }); break; } } }
sebastianha/webos-app_de.omoco.100pixels
app/assistants/history-assistant.js
JavaScript
gpl-3.0
4,982
/* Copyright 2016 Devon Call, Zeke Hunter-Green, Paige Ormiston, Joe Renner, Jesse Sliter This file is part of Myrge. Myrge is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Myrge is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Myrge. If not, see <http://www.gnu.org/licenses/>. */ app.controller('NavCtrl', [ '$scope', '$state', 'auth', function($scope, $state, auth){ $scope.isLoggedIn = auth.isLoggedIn; $scope.currentUser = auth.currentUser; $scope.logOut = auth.logOut; $scope.loggedin = auth.isLoggedIn(); if($scope.loggedin){ auth.validate(auth.getToken()).success(function(data){ if(!data.valid){ auth.logOut(); $state.go("login"); } }); } }]);
Decision-Maker/sp
public/javascripts/Controllers/navController.js
JavaScript
gpl-3.0
1,136
'use strict'; angular.module('ldrWebApp') /** * @name pageSkipper * @param config * @param pages * @type element * @description Skip to page directive * @requires $scope */ .directive('pageSkipper', function () { return { restrict: 'E', templateUrl: 'components/page-skipper/page-skipper.template.html', scope: {'config': '=', 'pages': '='}, controller: function ($scope) { /** * @name pageSkipper#generateArray * @param {Number} start * @param {Number} end * @description generate an array in form {start} to {end} * @returns {Array} */ function generateArray(start, end) { var list = []; for (var i = start; i <= end; i++) { list.push(i); } return list; } /** * @name pageSkipper#skipToPage * @param {Number} item * @description get the desired page * @return {Undefined} */ $scope.skipToPage = function (item) { $scope.config.page = (item === undefined) ? 1 : item; }; $scope.selectedPage = 1; $scope.pagesList = generateArray(1, $scope.pages); } }; });
qualitance/ldir-web
client/components/page-skipper/page-skipper.directive.js
JavaScript
gpl-3.0
1,522
odoo.define('point_of_sale.DB', function (require) { "use strict"; var core = require('web.core'); var utils = require('web.utils'); /* The PosDB holds reference to data that is either * - static: does not change between pos reloads * - persistent : must stay between reloads ( orders ) */ var PosDB = core.Class.extend({ name: 'openerp_pos_db', //the prefix of the localstorage data limit: 100, // the maximum number of results returned by a search init: function(options){ options = options || {}; this.name = options.name || this.name; this.limit = options.limit || this.limit; if (options.uuid) { this.name = this.name + '_' + options.uuid; } //cache the data in memory to avoid roundtrips to the localstorage this.cache = {}; this.product_by_id = {}; this.product_by_barcode = {}; this.product_by_category_id = {}; this.product_packaging_by_barcode = {}; this.partner_sorted = []; this.partner_by_id = {}; this.partner_by_barcode = {}; this.partner_search_string = ""; this.partner_write_date = null; this.category_by_id = {}; this.root_category_id = 0; this.category_products = {}; this.category_ancestors = {}; this.category_childs = {}; this.category_parent = {}; this.category_search_string = {}; }, /** * sets an uuid to prevent conflict in locally stored data between multiple PoS Configs. By * using the uuid of the config the local storage from other configs will not get effected nor * loaded in sessions that don't belong to them. * * @param {string} uuid Unique identifier of the PoS Config linked to the current session. */ set_uuid: function(uuid){ this.name = this.name + '_' + uuid; }, /* returns the category object from its id. If you pass a list of id as parameters, you get * a list of category objects. */ get_category_by_id: function(categ_id){ if(categ_id instanceof Array){ var list = []; for(var i = 0, len = categ_id.length; i < len; i++){ var cat = this.category_by_id[categ_id[i]]; if(cat){ list.push(cat); }else{ console.error("get_category_by_id: no category has id:",categ_id[i]); } } return list; }else{ return this.category_by_id[categ_id]; } }, /* returns a list of the category's child categories ids, or an empty list * if a category has no childs */ get_category_childs_ids: function(categ_id){ return this.category_childs[categ_id] || []; }, /* returns a list of all ancestors (parent, grand-parent, etc) categories ids * starting from the root category to the direct parent */ get_category_ancestors_ids: function(categ_id){ return this.category_ancestors[categ_id] || []; }, /* returns the parent category's id of a category, or the root_category_id if no parent. * the root category is parent of itself. */ get_category_parent_id: function(categ_id){ return this.category_parent[categ_id] || this.root_category_id; }, /* adds categories definitions to the database. categories is a list of categories objects as * returned by the openerp server. Categories must be inserted before the products or the * product/ categories association may (will) not work properly */ add_categories: function(categories){ var self = this; if(!this.category_by_id[this.root_category_id]){ this.category_by_id[this.root_category_id] = { id : this.root_category_id, name : 'Root', }; } categories.forEach(function(cat){ self.category_by_id[cat.id] = cat; }); categories.forEach(function(cat){ var parent_id = cat.parent_id[0]; if(!(parent_id && self.category_by_id[parent_id])){ parent_id = self.root_category_id; } self.category_parent[cat.id] = parent_id; if(!self.category_childs[parent_id]){ self.category_childs[parent_id] = []; } self.category_childs[parent_id].push(cat.id); }); function make_ancestors(cat_id, ancestors){ self.category_ancestors[cat_id] = ancestors; ancestors = ancestors.slice(0); ancestors.push(cat_id); var childs = self.category_childs[cat_id] || []; for(var i=0, len = childs.length; i < len; i++){ make_ancestors(childs[i], ancestors); } } make_ancestors(this.root_category_id, []); }, category_contains: function(categ_id, product_id) { var product = this.product_by_id[product_id]; if (product) { var cid = product.pos_categ_id[0]; while (cid && cid !== categ_id){ cid = this.category_parent[cid]; } return !!cid; } return false; }, /* loads a record store from the database. returns default if nothing is found */ load: function(store,deft){ if(this.cache[store] !== undefined){ return this.cache[store]; } var data = localStorage[this.name + '_' + store]; if(data !== undefined && data !== ""){ data = JSON.parse(data); this.cache[store] = data; return data; }else{ return deft; } }, /* saves a record store to the database */ save: function(store,data){ localStorage[this.name + '_' + store] = JSON.stringify(data); this.cache[store] = data; }, _product_search_string: function(product){ var str = product.display_name; if (product.barcode) { str += '|' + product.barcode; } if (product.default_code) { str += '|' + product.default_code; } if (product.description) { str += '|' + product.description; } if (product.description_sale) { str += '|' + product.description_sale; } str = product.id + ':' + str.replace(/:/g,'') + '\n'; return str; }, add_products: function(products){ var stored_categories = this.product_by_category_id; if(!products instanceof Array){ products = [products]; } for(var i = 0, len = products.length; i < len; i++){ var product = products[i]; if (product.id in this.product_by_id) continue; if (product.available_in_pos){ var search_string = utils.unaccent(this._product_search_string(product)); var categ_id = product.pos_categ_id ? product.pos_categ_id[0] : this.root_category_id; product.product_tmpl_id = product.product_tmpl_id[0]; if(!stored_categories[categ_id]){ stored_categories[categ_id] = []; } stored_categories[categ_id].push(product.id); if(this.category_search_string[categ_id] === undefined){ this.category_search_string[categ_id] = ''; } this.category_search_string[categ_id] += search_string; var ancestors = this.get_category_ancestors_ids(categ_id) || []; for(var j = 0, jlen = ancestors.length; j < jlen; j++){ var ancestor = ancestors[j]; if(! stored_categories[ancestor]){ stored_categories[ancestor] = []; } stored_categories[ancestor].push(product.id); if( this.category_search_string[ancestor] === undefined){ this.category_search_string[ancestor] = ''; } this.category_search_string[ancestor] += search_string; } } this.product_by_id[product.id] = product; if(product.barcode){ this.product_by_barcode[product.barcode] = product; } } }, add_packagings: function(product_packagings){ var self = this; _.map(product_packagings, function (product_packaging) { if (_.find(self.product_by_id, {'id': product_packaging.product_id[0]})) { self.product_packaging_by_barcode[product_packaging.barcode] = product_packaging; } }); }, _partner_search_string: function(partner){ var str = partner.name || ''; if(partner.barcode){ str += '|' + partner.barcode; } if(partner.address){ str += '|' + partner.address; } if(partner.phone){ str += '|' + partner.phone.split(' ').join(''); } if(partner.mobile){ str += '|' + partner.mobile.split(' ').join(''); } if(partner.email){ str += '|' + partner.email; } if(partner.vat){ str += '|' + partner.vat; } str = '' + partner.id + ':' + str.replace(':', '').replace(/\n/g, ' ') + '\n'; return str; }, add_partners: function(partners){ var updated_count = 0; var new_write_date = ''; var partner; for(var i = 0, len = partners.length; i < len; i++){ partner = partners[i]; var local_partner_date = (this.partner_write_date || '').replace(/^(\d{4}-\d{2}-\d{2}) ((\d{2}:?){3})$/, '$1T$2Z'); var dist_partner_date = (partner.write_date || '').replace(/^(\d{4}-\d{2}-\d{2}) ((\d{2}:?){3})$/, '$1T$2Z'); if ( this.partner_write_date && this.partner_by_id[partner.id] && new Date(local_partner_date).getTime() + 1000 >= new Date(dist_partner_date).getTime() ) { // FIXME: The write_date is stored with milisec precision in the database // but the dates we get back are only precise to the second. This means when // you read partners modified strictly after time X, you get back partners that were // modified X - 1 sec ago. continue; } else if ( new_write_date < partner.write_date ) { new_write_date = partner.write_date; } if (!this.partner_by_id[partner.id]) { this.partner_sorted.push(partner.id); } this.partner_by_id[partner.id] = partner; updated_count += 1; } this.partner_write_date = new_write_date || this.partner_write_date; if (updated_count) { // If there were updates, we need to completely // rebuild the search string and the barcode indexing this.partner_search_string = ""; this.partner_by_barcode = {}; for (var id in this.partner_by_id) { partner = this.partner_by_id[id]; if(partner.barcode){ this.partner_by_barcode[partner.barcode] = partner; } partner.address = (partner.street ? partner.street + ', ': '') + (partner.zip ? partner.zip + ', ': '') + (partner.city ? partner.city + ', ': '') + (partner.state_id ? partner.state_id[1] + ', ': '') + (partner.country_id ? partner.country_id[1]: ''); this.partner_search_string += this._partner_search_string(partner); } this.partner_search_string = utils.unaccent(this.partner_search_string); } return updated_count; }, get_partner_write_date: function(){ return this.partner_write_date || "1970-01-01 00:00:00"; }, get_partner_by_id: function(id){ return this.partner_by_id[id]; }, get_partner_by_barcode: function(barcode){ return this.partner_by_barcode[barcode]; }, get_partners_sorted: function(max_count){ max_count = max_count ? Math.min(this.partner_sorted.length, max_count) : this.partner_sorted.length; var partners = []; for (var i = 0; i < max_count; i++) { partners.push(this.partner_by_id[this.partner_sorted[i]]); } return partners; }, search_partner: function(query){ try { query = query.replace(/[\[\]\(\)\+\*\?\.\-\!\&\^\$\|\~\_\{\}\:\,\\\/]/g,'.'); query = query.replace(/ /g,'.+'); var re = RegExp("([0-9]+):.*?"+utils.unaccent(query),"gi"); }catch(e){ return []; } var results = []; for(var i = 0; i < this.limit; i++){ var r = re.exec(this.partner_search_string); if(r){ var id = Number(r[1]); results.push(this.get_partner_by_id(id)); }else{ break; } } return results; }, /* removes all the data from the database. TODO : being able to selectively remove data */ clear: function(){ for(var i = 0, len = arguments.length; i < len; i++){ localStorage.removeItem(this.name + '_' + arguments[i]); } }, /* this internal methods returns the count of properties in an object. */ _count_props : function(obj){ var count = 0; for(var prop in obj){ if(obj.hasOwnProperty(prop)){ count++; } } return count; }, get_product_by_id: function(id){ return this.product_by_id[id]; }, get_product_by_barcode: function(barcode){ if(this.product_by_barcode[barcode]){ return this.product_by_barcode[barcode]; } else if (this.product_packaging_by_barcode[barcode]) { return this.product_by_id[this.product_packaging_by_barcode[barcode].product_id[0]]; } return undefined; }, get_product_by_category: function(category_id){ var product_ids = this.product_by_category_id[category_id]; var list = []; if (product_ids) { for (var i = 0, len = Math.min(product_ids.length, this.limit); i < len; i++) { const product = this.product_by_id[product_ids[i]]; if (!(product.active && product.available_in_pos)) continue; list.push(product); } } return list; }, /* returns a list of products with : * - a category that is or is a child of category_id, * - a name, package or barcode containing the query (case insensitive) */ search_product_in_category: function(category_id, query){ try { query = query.replace(/[\[\]\(\)\+\*\?\.\-\!\&\^\$\|\~\_\{\}\:\,\\\/]/g,'.'); query = query.replace(/ /g,'.+'); var re = RegExp("([0-9]+):.*?"+utils.unaccent(query),"gi"); }catch(e){ return []; } var results = []; for(var i = 0; i < this.limit; i++){ var r = re.exec(this.category_search_string[category_id]); if(r){ var id = Number(r[1]); const product = this.get_product_by_id(id); if (!(product.active && product.available_in_pos)) continue; results.push(product); }else{ break; } } return results; }, /* from a product id, and a list of category ids, returns * true if the product belongs to one of the provided category * or one of its child categories. */ is_product_in_category: function(category_ids, product_id) { if (!(category_ids instanceof Array)) { category_ids = [category_ids]; } var cat = this.get_product_by_id(product_id).pos_categ_id[0]; while (cat) { for (var i = 0; i < category_ids.length; i++) { if (cat == category_ids[i]) { // The == is important, ids may be strings return true; } } cat = this.get_category_parent_id(cat); } return false; }, /* paid orders */ add_order: function(order){ var order_id = order.uid; var orders = this.load('orders',[]); // if the order was already stored, we overwrite its data for(var i = 0, len = orders.length; i < len; i++){ if(orders[i].id === order_id){ orders[i].data = order; this.save('orders',orders); return order_id; } } // Only necessary when we store a new, validated order. Orders // that where already stored should already have been removed. this.remove_unpaid_order(order); orders.push({id: order_id, data: order}); this.save('orders',orders); return order_id; }, remove_order: function(order_id){ var orders = this.load('orders',[]); orders = _.filter(orders, function(order){ return order.id !== order_id; }); this.save('orders',orders); }, remove_all_orders: function(){ this.save('orders',[]); }, get_orders: function(){ return this.load('orders',[]); }, get_order: function(order_id){ var orders = this.get_orders(); for(var i = 0, len = orders.length; i < len; i++){ if(orders[i].id === order_id){ return orders[i]; } } return undefined; }, /* working orders */ save_unpaid_order: function(order){ var order_id = order.uid; var orders = this.load('unpaid_orders',[]); var serialized = order.export_as_JSON(); for (var i = 0; i < orders.length; i++) { if (orders[i].id === order_id){ orders[i].data = serialized; this.save('unpaid_orders',orders); return order_id; } } orders.push({id: order_id, data: serialized}); this.save('unpaid_orders',orders); return order_id; }, remove_unpaid_order: function(order){ var orders = this.load('unpaid_orders',[]); orders = _.filter(orders, function(o){ return o.id !== order.uid; }); this.save('unpaid_orders',orders); }, remove_all_unpaid_orders: function(){ this.save('unpaid_orders',[]); }, get_unpaid_orders: function(){ var saved = this.load('unpaid_orders',[]); var orders = []; for (var i = 0; i < saved.length; i++) { orders.push(saved[i].data); } return orders; }, /** * Return the orders with requested ids if they are unpaid. * @param {array<number>} ids order_ids. * @return {array<object>} list of orders. */ get_unpaid_orders_to_sync: function(ids){ var saved = this.load('unpaid_orders',[]); var orders = []; saved.forEach(function(o) { if (ids.includes(o.id)){ orders.push(o); } }); return orders; }, /** * Add a given order to the orders to be removed from the server. * * If an order is removed from a table it also has to be removed from the server to prevent it from reapearing * after syncing. This function will add the server_id of the order to a list of orders still to be removed. * @param {object} order object. */ set_order_to_remove_from_server: function(order){ if (order.server_id !== undefined) { var to_remove = this.load('unpaid_orders_to_remove',[]); to_remove.push(order.server_id); this.save('unpaid_orders_to_remove', to_remove); } }, /** * Get a list of server_ids of orders to be removed. * @return {array<number>} list of server_ids. */ get_ids_to_remove_from_server: function(){ return this.load('unpaid_orders_to_remove',[]); }, /** * Remove server_ids from the list of orders to be removed. * @param {array<number>} ids */ set_ids_removed_from_server: function(ids){ var to_remove = this.load('unpaid_orders_to_remove',[]); to_remove = _.filter(to_remove, function(id){ return !ids.includes(id); }); this.save('unpaid_orders_to_remove', to_remove); }, set_cashier: function(cashier) { // Always update if the user is the same as before this.save('cashier', cashier || null); }, get_cashier: function() { return this.load('cashier'); } }); return PosDB; });
jeremiahyan/odoo
addons/point_of_sale/static/src/js/db.js
JavaScript
gpl-3.0
21,089
var searchData= [ ['a',['a',['../structRREP.html#abe45cd7d5c14dc356ecab531b2176242',1,'RREP']]], ['ack_5ftimer',['ack_timer',['../structrt__table.html#a4b5c6baab186ae8733b48cf2d5172852',1,'rt_table']]], ['active',['active',['../classNA__NesgLog.html#a0ce1b63fe991dc4304cb30d703aadcd6',1,'NA_NesgLog']]], ['active_5froute_5ftimeout',['active_route_timeout',['../classNA__AODVUU.html#ae7108fca58788a241d1319cde34a7dde',1,'NA_AODVUU::active_route_timeout()'],['../main_8c.html#a1b01d3369a884952b1b133647b6f8972',1,'active_route_timeout():&#160;main.c'],['../NA__nl_8c.html#a1b01d3369a884952b1b133647b6f8972',1,'active_route_timeout():&#160;main.c']]], ['aodvnl',['aodvnl',['../NA__nl_8c.html#a1932512e3a0f6559a876627efde22cff',1,'NA_nl.c']]], ['aodvrttablemap',['aodvRtTableMap',['../classNA__AODVUU.html#ae0d6f9d77438a52f9c571a77e2151a48',1,'NA_AODVUU']]], ['aodvtimermap',['aodvTimerMap',['../classNA__AODVUU.html#ab1245e4e87b93a0416f42606da162489',1,'NA_AODVUU']]], ['attacktype',['attackType',['../classNA__Attack.html#ac4cf8ddfd1c47f348f057f49382f5323',1,'NA_Attack']]], ['avhopcount',['avHopCount',['../classNA__UDPBasicBurst.html#a8c9180eebb4ba6a44ab2ca3bc5052426',1,'NA_UDPBasicBurst']]] ];
robertomagan/neta_v1
doc/doxy/search/variables_61.js
JavaScript
gpl-3.0
1,214
/* This file is part of the OdinMS Maple Story Server Copyright (C) 2008 Patrick Huy <[email protected]> Matthias Butz <[email protected]> Jan Christian Meyer <[email protected]> This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License version 3 as published by the Free Software Foundation. You may not use, modify or distribute this program under any other version of the GNU Affero General Public License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** -- Odin JavaScript -------------------------------------------------------------------------------- Konpei - Showa Town(801000000) -- By --------------------------------------------------------------------------------------------- Information -- Version Info ----------------------------------------------------------------------------------- 1.1 - Fixed by Moogra 1.0 - First Version by Information --------------------------------------------------------------------------------------------------- **/ function start() { cm.sendSimple ("What do you want from me?\r #L0##bGather up some information on the hideout.#l\r\n#L1#Take me to the hideout#l\r\n#L2#Nothing#l#k"); } function action(mode, type, selection) { if (mode < 1) { cm.dispose(); } else { status++; if (status == 1) { if (selection == 0) { cm.sendNext("I can take you to the hideout, but the place is infested with thugs looking for trouble. You'll need to be both incredibly strong and brave to enter the premise. At the hideaway, you'll find the Boss that controls all the other bosses around this area. It's easy to get to the hideout, but the room on the top floor of the place can only be entered ONCE a day. The Boss's Room is not a place to mess around. I suggest you don't stay there for too long; you'll need to swiftly take care of the business once inside. The boss himself is a difficult foe, but you'll run into some incredibly powerful enemies on you way to meeting the boss! It ain't going to be easy."); cm.dispose(); } else if (selection == 1) cm.sendNext("Oh, the brave one. I've been awaiting your arrival. If these\r\nthugs are left unchecked, there's no telling what going to\r\nhappen in this neighborhood. Before that happens, I hope\r\nyou take care of all them and beat the boss, who resides\r\non the 5th floor. You'll need to be on alert at all times, since\r\nthe boss is too tough for even wisemen to handle.\r\nLooking at your eyes, however, I can see that eye of the\r\ntiger, the eyes that tell me you can do this. Let's go!"); else { cm.sendOk("I'm a busy person! Leave me alone if that's all you need!"); cm.dispose(); } } else { cm.warp(801040000); cm.dispose(); } } }
NovaStory/AeroStory
scripts/npc/world0/9120015.js
JavaScript
gpl-3.0
3,358
/* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * Copyright (c) 2015, Joyent, Inc. */ var test = require('./test-namer')('vm-to-zones'); var util = require('util'); var bunyan = require('bunyan'); var utils = require('../../lib/utils'); var buildZonesFromVm = require('../../lib/vm-to-zones'); var log = bunyan.createLogger({name: 'cns'}); test('basic single container', function (t) { var config = { forward_zones: { 'foo': {} }, reverse_zones: {} }; var vm = { uuid: 'abc123', services: [], listInstance: true, listServices: true, owner: { uuid: 'def432' }, nics: [ { ip: '1.2.3.4', zones: ['foo'] } ] }; var zones = buildZonesFromVm(vm, config, log); t.deepEqual(Object.keys(zones), ['foo', '3.2.1.in-addr.arpa']); t.deepEqual(Object.keys(zones['foo']), ['abc123.inst.def432']); t.deepEqual(Object.keys(zones['3.2.1.in-addr.arpa']), ['4']); var fwd = zones['foo']['abc123.inst.def432']; t.deepEqual(fwd, [ {constructor: 'A', args: ['1.2.3.4']}, {constructor: 'TXT', args: ['abc123']} ]); var rev = zones['3.2.1.in-addr.arpa']['4']; t.deepEqual(rev, [ {constructor: 'PTR', args: ['abc123.inst.def432.foo']} ]); t.end(); }); test('cloudapi instance', function (t) { var config = { forward_zones: { 'foo': {} }, reverse_zones: {} }; var vm = { uuid: 'abc123', services: [ { name: 'cloudapi', ports: [] } ], listInstance: true, listServices: true, owner: { uuid: 'def432', login: 'admin' }, nics: [ { ip: '1.2.3.4', zones: ['foo'] } ] }; var zones = buildZonesFromVm(vm, config, log); t.deepEqual(Object.keys(zones), ['foo', '3.2.1.in-addr.arpa']); t.deepEqual(Object.keys(zones['foo']), [ 'abc123.inst.def432', 'cloudapi.svc.def432', 'cloudapi']); t.deepEqual(Object.keys(zones['3.2.1.in-addr.arpa']), ['4']); var fwd = zones['foo']['cloudapi']; t.deepEqual(fwd, [ {constructor: 'A', args: ['1.2.3.4'], src: 'abc123'}, {constructor: 'TXT', args: ['abc123'], src: 'abc123'} ]); var rev = zones['3.2.1.in-addr.arpa']['4']; t.deepEqual(rev, [ {constructor: 'PTR', args: ['abc123.inst.def432.foo']} ]); t.end(); }); test('with use_alias', function (t) { var config = { use_alias: true, forward_zones: { 'foo': {} }, reverse_zones: {} }; var vm = { uuid: 'abc123', alias: 'test', services: [], listInstance: true, listServices: true, owner: { uuid: 'def432' }, nics: [ { ip: '1.2.3.4', zones: ['foo'] } ] }; var zones = buildZonesFromVm(vm, config, log); t.deepEqual(Object.keys(zones), ['foo', '3.2.1.in-addr.arpa']); t.deepEqual(Object.keys(zones['foo']), ['abc123.inst.def432', 'test.inst.def432']); t.deepEqual(Object.keys(zones['3.2.1.in-addr.arpa']), ['4']); var fwd = zones['foo']['test.inst.def432']; t.deepEqual(fwd, [ {constructor: 'A', args: ['1.2.3.4']}, {constructor: 'TXT', args: ['abc123']} ]); var rev = zones['3.2.1.in-addr.arpa']['4']; t.deepEqual(rev, [ {constructor: 'PTR', args: ['test.inst.def432.foo']} ]); t.end(); }); test('with use_login', function (t) { var config = { use_login: true, forward_zones: { 'foo': {} }, reverse_zones: {} }; var vm = { uuid: 'abc123', alias: 'test', services: [], listInstance: true, listServices: true, owner: { uuid: 'def432', login: 'bar' }, nics: [ { ip: '1.2.3.4', zones: ['foo'] } ] }; var zones = buildZonesFromVm(vm, config, log); t.deepEqual(Object.keys(zones), ['foo', '3.2.1.in-addr.arpa']); t.deepEqual(Object.keys(zones['foo']), ['abc123.inst.def432', 'abc123.inst.bar']); t.deepEqual(Object.keys(zones['3.2.1.in-addr.arpa']), ['4']); var fwd = zones['foo']['abc123.inst.bar']; t.deepEqual(fwd, [ {constructor: 'A', args: ['1.2.3.4']}, {constructor: 'TXT', args: ['abc123']} ]); var rev = zones['3.2.1.in-addr.arpa']['4']; t.deepEqual(rev, [ {constructor: 'PTR', args: ['abc123.inst.bar.foo']} ]); t.end(); }); test('with use_alias and use_login', function (t) { var config = { use_alias: true, use_login: true, forward_zones: { 'foo': {} }, reverse_zones: {} }; var vm = { uuid: 'abc123', alias: 'test', services: [], listInstance: true, listServices: true, owner: { uuid: 'def432', login: 'bar' }, nics: [ { ip: '1.2.3.4', zones: ['foo'] } ] }; var zones = buildZonesFromVm(vm, config, log); t.deepEqual(Object.keys(zones), ['foo', '3.2.1.in-addr.arpa']); t.deepEqual(Object.keys(zones['foo']), ['abc123.inst.def432', 'abc123.inst.bar', 'test.inst.def432', 'test.inst.bar']); t.deepEqual(Object.keys(zones['3.2.1.in-addr.arpa']), ['4']); var fwd = zones['foo']['test.inst.bar']; t.deepEqual(fwd, [ {constructor: 'A', args: ['1.2.3.4']}, {constructor: 'TXT', args: ['abc123']} ]); var rev = zones['3.2.1.in-addr.arpa']['4']; t.deepEqual(rev, [ {constructor: 'PTR', args: ['test.inst.bar.foo']} ]); t.end(); }); test('using a PTR name', function (t) { var config = { use_alias: true, use_login: true, forward_zones: { 'foo': {} }, reverse_zones: {} }; var vm = { uuid: 'abc123', alias: 'test', services: [], ptrname: 'test.something.com', listInstance: true, listServices: true, owner: { uuid: 'def432', login: 'bar' }, nics: [ { ip: '1.2.3.4', zones: ['foo'] } ] }; var zones = buildZonesFromVm(vm, config, log); t.deepEqual(Object.keys(zones), ['foo', '3.2.1.in-addr.arpa']); var rev = zones['3.2.1.in-addr.arpa']['4']; t.deepEqual(rev, [ {constructor: 'PTR', args: ['test.something.com']} ]); t.end(); }); test('multi-zone', function (t) { var config = { use_alias: true, use_login: true, forward_zones: { 'foo': {}, 'bar': {} }, reverse_zones: {} }; var vm = { uuid: 'abc123', alias: 'test', services: [], listInstance: true, listServices: true, owner: { uuid: 'def432', login: 'bar' }, nics: [ { ip: '1.2.3.4', zones: ['foo'] }, { ip: '3.2.1.4', zones: ['bar'] } ] }; var zones = buildZonesFromVm(vm, config, log); t.deepEqual(Object.keys(zones).sort(), ['1.2.3.in-addr.arpa', '3.2.1.in-addr.arpa', 'bar', 'foo']); t.deepEqual(Object.keys(zones['foo']).sort(), ['abc123.inst.bar', 'abc123.inst.def432', 'test.inst.bar', 'test.inst.def432']); t.deepEqual(Object.keys(zones['bar']).sort(), Object.keys(zones['foo']).sort()); t.deepEqual(Object.keys(zones['3.2.1.in-addr.arpa']), ['4']); t.deepEqual(Object.keys(zones['1.2.3.in-addr.arpa']), ['4']); var fwd = zones['foo']['test.inst.bar']; t.deepEqual(fwd, [ {constructor: 'A', args: ['1.2.3.4']}, {constructor: 'TXT', args: ['abc123']} ]); var rev = zones['3.2.1.in-addr.arpa']['4']; t.deepEqual(rev, [ {constructor: 'PTR', args: ['test.inst.bar.foo']} ]); var rev2 = zones['1.2.3.in-addr.arpa']['4']; t.deepEqual(rev2, [ {constructor: 'PTR', args: ['test.inst.bar.bar']} ]); t.end(); }); test('multi-zone, single PTRs', function (t) { var config = { use_alias: true, use_login: true, forward_zones: { 'foo': {}, 'bar': {}, 'baz': {} }, reverse_zones: {} }; var vm = { uuid: 'abc123', alias: 'test', services: [], listInstance: true, listServices: true, owner: { uuid: 'def432', login: 'bar' }, nics: [ { ip: '1.2.3.4', zones: ['foo', 'bar'] }, { ip: '3.2.1.4', zones: ['baz'] } ] }; var zones = buildZonesFromVm(vm, config, log); t.deepEqual(Object.keys(zones).sort(), ['1.2.3.in-addr.arpa', '3.2.1.in-addr.arpa', 'bar', 'baz', 'foo']); t.deepEqual(Object.keys(zones['foo']).sort(), ['abc123.inst.bar', 'abc123.inst.def432', 'test.inst.bar', 'test.inst.def432']); t.deepEqual(Object.keys(zones['bar']).sort(), Object.keys(zones['foo']).sort()); t.deepEqual(Object.keys(zones['3.2.1.in-addr.arpa']), ['4']); t.deepEqual(Object.keys(zones['1.2.3.in-addr.arpa']), ['4']); var fwd = zones['foo']['test.inst.bar']; t.deepEqual(fwd, [ {constructor: 'A', args: ['1.2.3.4']}, {constructor: 'TXT', args: ['abc123']} ]); var rev = zones['3.2.1.in-addr.arpa']['4']; t.deepEqual(rev, [ {constructor: 'PTR', args: ['test.inst.bar.foo']} ]); var rev2 = zones['1.2.3.in-addr.arpa']['4']; t.deepEqual(rev2, [ {constructor: 'PTR', args: ['test.inst.bar.baz']} ]); t.end(); }); test('multi-zone, shortest zone priority PTR', function (t) { var config = { use_alias: true, use_login: true, forward_zones: { 'foobarbaz': {}, 'foobar': {}, 'baz': {} }, reverse_zones: {} }; var vm = { uuid: 'abc123', alias: 'test', services: [], listInstance: true, listServices: true, owner: { uuid: 'def432', login: 'bar' }, nics: [ { ip: '1.2.3.4', zones: ['foobar', 'foobarbaz', 'baz'] } ] }; var zones = buildZonesFromVm(vm, config, log); var rev = zones['3.2.1.in-addr.arpa']['4']; t.deepEqual(rev, [ {constructor: 'PTR', args: ['test.inst.bar.baz']} ]); t.end(); }); test('service with srvs', function (t) { var config = { use_alias: true, forward_zones: { 'foo': {} }, reverse_zones: {} }; var vm = { uuid: 'abc123', alias: 'test', services: [ { name: 'svc1', ports: [1234, 1235] } ], listInstance: true, listServices: true, owner: { uuid: 'def432' }, nics: [ { ip: '1.2.3.4', zones: ['foo'] } ] }; var zones = buildZonesFromVm(vm, config, log); t.deepEqual(Object.keys(zones), ['foo', '3.2.1.in-addr.arpa']); t.deepEqual(Object.keys(zones['foo']), ['abc123.inst.def432', 'test.inst.def432', 'svc1.svc.def432']); var fwd = zones['foo']['test.inst.def432']; t.deepEqual(fwd, [ {constructor: 'A', args: ['1.2.3.4']}, {constructor: 'TXT', args: ['abc123']} ]); var svc = zones['foo']['svc1.svc.def432']; t.deepEqual(svc, [ {constructor: 'A', args: ['1.2.3.4'], src: 'abc123'}, {constructor: 'TXT', args: ['abc123'], src: 'abc123'}, {constructor: 'SRV', args: ['test.inst.def432.foo', 1234], src: 'abc123'}, {constructor: 'SRV', args: ['test.inst.def432.foo', 1235], src: 'abc123'} ]); t.end(); });
eait-itig/triton-cns
test/unit/vm-to-zones.test.js
JavaScript
mpl-2.0
10,814
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2008 Frederico Caldeira Knabben * * == BEGIN LICENSE == * * Licensed under the terms of any of the following licenses at your * choice: * * - GNU General Public License Version 2 or later (the "GPL") * http://www.gnu.org/licenses/gpl.html * * - GNU Lesser General Public License Version 2.1 or later (the "LGPL") * http://www.gnu.org/licenses/lgpl.html * * - Mozilla Public License Version 1.1 or later (the "MPL") * http://www.mozilla.org/MPL/MPL-1.1.html * * == END LICENSE == * * Editor configuration settings. * * Follow this link for more information: * http://docs.fckeditor.net/FCKeditor_2.x/Developers_Guide/Configuration/Configuration_Options */ FCKConfig.CustomConfigurationsPath = '' ; FCKConfig.EditorAreaCSS = FCKConfig.BasePath + 'css/fck_editorarea.css' ; FCKConfig.EditorAreaStyles = '' ; FCKConfig.ToolbarComboPreviewCSS = '' ; FCKConfig.DocType = '' ; FCKConfig.BaseHref = '' ; FCKConfig.FullPage = false ; // The following option determines whether the "Show Blocks" feature is enabled or not at startup. FCKConfig.StartupShowBlocks = false ; FCKConfig.Debug = false ; FCKConfig.AllowQueryStringDebug = true ; FCKConfig.SkinPath = FCKConfig.BasePath + 'skins/default/' ; FCKConfig.SkinEditorCSS = '' ; // FCKConfig.SkinPath + "|<minified css>" ; FCKConfig.SkinDialogCSS = '' ; // FCKConfig.SkinPath + "|<minified css>" ; FCKConfig.PreloadImages = [ FCKConfig.SkinPath + 'images/toolbar.start.gif', FCKConfig.SkinPath + 'images/toolbar.buttonarrow.gif' ] ; FCKConfig.PluginsPath = FCKConfig.BasePath + 'plugins/' ; // FCKConfig.Plugins.Add( 'autogrow' ) ; // FCKConfig.Plugins.Add( 'dragresizetable' ); FCKConfig.AutoGrowMax = 400 ; // FCKConfig.ProtectedSource.Add( /<%[\s\S]*?%>/g ) ; // ASP style server side code <%...%> // FCKConfig.ProtectedSource.Add( /<\?[\s\S]*?\?>/g ) ; // PHP style server side code // FCKConfig.ProtectedSource.Add( /(<asp:[^\>]+>[\s|\S]*?<\/asp:[^\>]+>)|(<asp:[^\>]+\/>)/gi ) ; // ASP.Net style tags <asp:control> FCKConfig.AutoDetectLanguage = true ; FCKConfig.DefaultLanguage = 'en' ; FCKConfig.ContentLangDirection = 'ltr' ; FCKConfig.ProcessHTMLEntities = true ; FCKConfig.IncludeLatinEntities = true ; FCKConfig.IncludeGreekEntities = true ; FCKConfig.ProcessNumericEntities = false ; FCKConfig.AdditionalNumericEntities = '' ; // Single Quote: "'" FCKConfig.FillEmptyBlocks = true ; FCKConfig.FormatSource = true ; FCKConfig.FormatOutput = true ; FCKConfig.FormatIndentator = ' ' ; FCKConfig.EMailProtection = 'encode' ; // none | encode | function FCKConfig.EMailProtectionFunction = 'mt(NAME,DOMAIN,SUBJECT,BODY)' ; FCKConfig.StartupFocus = false ; FCKConfig.ForcePasteAsPlainText = false ; FCKConfig.AutoDetectPasteFromWord = true ; // IE only. FCKConfig.ShowDropDialog = true ; FCKConfig.ForceSimpleAmpersand = false ; FCKConfig.TabSpaces = 0 ; FCKConfig.ShowBorders = true ; FCKConfig.SourcePopup = false ; FCKConfig.ToolbarStartExpanded = true ; FCKConfig.ToolbarCanCollapse = true ; FCKConfig.IgnoreEmptyParagraphValue = true ; FCKConfig.FloatingPanelsZIndex = 10000 ; FCKConfig.HtmlEncodeOutput = false ; FCKConfig.TemplateReplaceAll = true ; FCKConfig.TemplateReplaceCheckbox = true ; FCKConfig.ToolbarLocation = 'In' ; FCKConfig.ToolbarSets["Default"] = [ ['Source','DocProps','-','Save','NewPage','Preview','-','Templates'], ['Cut','Copy','Paste','PasteText','PasteWord','-','Print','SpellCheck'], ['Undo','Redo','-','Find','Replace','-','SelectAll','RemoveFormat'], ['Form','Checkbox','Radio','TextField','Textarea','Select','Button','ImageButton','HiddenField'], '/', ['Bold','Italic','Underline','StrikeThrough','-','Subscript','Superscript'], ['OrderedList','UnorderedList','-','Outdent','Indent','Blockquote','CreateDiv'], ['JustifyLeft','JustifyCenter','JustifyRight','JustifyFull'], ['Link','Unlink','Anchor'], ['Image','Flash','Table','Rule','Smiley','SpecialChar','PageBreak'], '/', ['Style','FontFormat','FontName','FontSize'], ['TextColor','BGColor'], ['FitWindow','ShowBlocks','-','About'] // No comma for the last row. ] ; FCKConfig.ToolbarSets["Basic"] = [ ['Bold','Italic','-','OrderedList','UnorderedList','-','Link','Unlink','-','About'] ] ; FCKConfig.EnterMode = 'p' ; // p | div | br FCKConfig.ShiftEnterMode = 'br' ; // p | div | br FCKConfig.Keystrokes = [ [ CTRL + 65 /*A*/, true ], [ CTRL + 67 /*C*/, true ], [ CTRL + 70 /*F*/, true ], [ CTRL + 83 /*S*/, true ], [ CTRL + 84 /*T*/, true ], [ CTRL + 88 /*X*/, true ], [ CTRL + 86 /*V*/, 'Paste' ], [ CTRL + 45 /*INS*/, true ], [ SHIFT + 45 /*INS*/, 'Paste' ], [ CTRL + 88 /*X*/, 'Cut' ], [ SHIFT + 46 /*DEL*/, 'Cut' ], [ CTRL + 90 /*Z*/, 'Undo' ], [ CTRL + 89 /*Y*/, 'Redo' ], [ CTRL + SHIFT + 90 /*Z*/, 'Redo' ], [ CTRL + 76 /*L*/, 'Link' ], [ CTRL + 66 /*B*/, 'Bold' ], [ CTRL + 73 /*I*/, 'Italic' ], [ CTRL + 85 /*U*/, 'Underline' ], [ CTRL + SHIFT + 83 /*S*/, 'Save' ], [ CTRL + ALT + 13 /*ENTER*/, 'FitWindow' ], [ SHIFT + 32 /*SPACE*/, 'Nbsp' ] ] ; FCKConfig.ContextMenu = ['Generic','Link','Anchor','Image','Flash','Select','Textarea','Checkbox','Radio','TextField','HiddenField','ImageButton','Button','BulletedList','NumberedList','Table','Form','DivContainer'] ; FCKConfig.BrowserContextMenuOnCtrl = false ; FCKConfig.BrowserContextMenu = false ; FCKConfig.EnableMoreFontColors = true ; FCKConfig.FontColors = '000000,993300,333300,003300,003366,000080,333399,333333,800000,FF6600,808000,808080,008080,0000FF,666699,808080,FF0000,FF9900,99CC00,339966,33CCCC,3366FF,800080,999999,FF00FF,FFCC00,FFFF00,00FF00,00FFFF,00CCFF,993366,C0C0C0,FF99CC,FFCC99,FFFF99,CCFFCC,CCFFFF,99CCFF,CC99FF,FFFFFF' ; FCKConfig.FontFormats = 'p;h1;h2;h3;h4;h5;h6;pre;address;div' ; FCKConfig.FontNames = 'Arial;Comic Sans MS;Courier New;Tahoma;Times New Roman;Verdana' ; FCKConfig.FontSizes = 'smaller;larger;xx-small;x-small;small;medium;large;x-large;xx-large' ; FCKConfig.StylesXmlPath = FCKConfig.EditorPath + 'fckstyles.xml' ; FCKConfig.TemplatesXmlPath = FCKConfig.EditorPath + 'fcktemplates.xml' ; FCKConfig.SpellChecker = 'ieSpell' ; // 'ieSpell' | 'SpellerPages' FCKConfig.IeSpellDownloadUrl = 'http://www.iespell.com/download.php' ; FCKConfig.SpellerPagesServerScript = 'server-scripts/spellchecker.php' ; // Available extension: .php .cfm .pl FCKConfig.FirefoxSpellChecker = false ; FCKConfig.MaxUndoLevels = 15 ; FCKConfig.DisableObjectResizing = false ; FCKConfig.DisableFFTableHandles = true ; FCKConfig.LinkDlgHideTarget = false ; FCKConfig.LinkDlgHideAdvanced = false ; FCKConfig.ImageDlgHideLink = false ; FCKConfig.ImageDlgHideAdvanced = false ; FCKConfig.FlashDlgHideAdvanced = false ; FCKConfig.ProtectedTags = '' ; // This will be applied to the body element of the editor FCKConfig.BodyId = '' ; FCKConfig.BodyClass = '' ; FCKConfig.DefaultStyleLabel = '' ; FCKConfig.DefaultFontFormatLabel = '' ; FCKConfig.DefaultFontLabel = '' ; FCKConfig.DefaultFontSizeLabel = '' ; FCKConfig.DefaultLinkTarget = '' ; // The option switches between trying to keep the html structure or do the changes so the content looks like it was in Word FCKConfig.CleanWordKeepsStructure = false ; // Only inline elements are valid. FCKConfig.RemoveFormatTags = 'b,big,code,del,dfn,em,font,i,ins,kbd,q,samp,small,span,strike,strong,sub,sup,tt,u,var' ; // Attributes that will be removed FCKConfig.RemoveAttributes = 'class,style,lang,width,height,align,hspace,valign' ; FCKConfig.CustomStyles = { 'Red Title' : { Element : 'h3', Styles : { 'color' : 'Red' } } }; // Do not add, rename or remove styles here. Only apply definition changes. FCKConfig.CoreStyles = { // Basic Inline Styles. 'Bold' : { Element : 'strong', Overrides : 'b' }, 'Italic' : { Element : 'em', Overrides : 'i' }, 'Underline' : { Element : 'u' }, 'StrikeThrough' : { Element : 'strike' }, 'Subscript' : { Element : 'sub' }, 'Superscript' : { Element : 'sup' }, // Basic Block Styles (Font Format Combo). 'p' : { Element : 'p' }, 'div' : { Element : 'div' }, 'pre' : { Element : 'pre' }, 'address' : { Element : 'address' }, 'h1' : { Element : 'h1' }, 'h2' : { Element : 'h2' }, 'h3' : { Element : 'h3' }, 'h4' : { Element : 'h4' }, 'h5' : { Element : 'h5' }, 'h6' : { Element : 'h6' }, // Other formatting features. 'FontFace' : { Element : 'span', Styles : { 'font-family' : '#("Font")' }, Overrides : [ { Element : 'font', Attributes : { 'face' : null } } ] }, 'Size' : { Element : 'span', Styles : { 'font-size' : '#("Size","fontSize")' }, Overrides : [ { Element : 'font', Attributes : { 'size' : null } } ] }, 'Color' : { Element : 'span', Styles : { 'color' : '#("Color","color")' }, Overrides : [ { Element : 'font', Attributes : { 'color' : null } } ] }, 'BackColor' : { Element : 'span', Styles : { 'background-color' : '#("Color","color")' } }, 'SelectionHighlight' : { Element : 'span', Styles : { 'background-color' : 'navy', 'color' : 'white' } } }; // The distance of an indentation step. FCKConfig.IndentLength = 40 ; FCKConfig.IndentUnit = 'px' ; // Alternatively, FCKeditor allows the use of CSS classes for block indentation. // This overrides the IndentLength/IndentUnit settings. FCKConfig.IndentClasses = [] ; // [ Left, Center, Right, Justified ] FCKConfig.JustifyClasses = [] ; // The following value defines which File Browser connector and Quick Upload // "uploader" to use. It is valid for the default implementaion and it is here // just to make this configuration file cleaner. // It is not possible to change this value using an external file or even // inline when creating the editor instance. In that cases you must set the // values of LinkBrowserURL, ImageBrowserURL and so on. // Custom implementations should just ignore it. var _FileBrowserLanguage = 'aspx' ; // asp | aspx | cfm | lasso | perl | php | py var _QuickUploadLanguage = 'aspx' ; // asp | aspx | cfm | lasso | perl | php | py // Don't care about the following two lines. It just calculates the correct connector // extension to use for the default File Browser (Perl uses "cgi"). var _FileBrowserExtension = _FileBrowserLanguage == 'perl' ? 'cgi' : _FileBrowserLanguage ; var _QuickUploadExtension = _QuickUploadLanguage == 'perl' ? 'cgi' : _QuickUploadLanguage ; FCKConfig.LinkBrowser = true ; FCKConfig.LinkBrowserURL = FCKConfig.BasePath + 'filemanager/browser/default/browser.html?Connector=' + encodeURIComponent( FCKConfig.BasePath + 'filemanager/connectors/' + _FileBrowserLanguage + '/connector.' + _FileBrowserExtension ) ; FCKConfig.LinkBrowserWindowWidth = FCKConfig.ScreenWidth * 0.7 ; // 70% FCKConfig.LinkBrowserWindowHeight = FCKConfig.ScreenHeight * 0.7 ; // 70% FCKConfig.ImageBrowser = true ; FCKConfig.ImageBrowserURL = FCKConfig.BasePath + 'filemanager/browser/default/browser.html?Type=Image&Connector=' + encodeURIComponent( FCKConfig.BasePath + 'filemanager/connectors/' + _FileBrowserLanguage + '/connector.' + _FileBrowserExtension ) ; FCKConfig.ImageBrowserWindowWidth = FCKConfig.ScreenWidth * 0.7 ; // 70% ; FCKConfig.ImageBrowserWindowHeight = FCKConfig.ScreenHeight * 0.7 ; // 70% ; FCKConfig.FlashBrowser = true ; FCKConfig.FlashBrowserURL = FCKConfig.BasePath + 'filemanager/browser/default/browser.html?Type=Flash&Connector=' + encodeURIComponent( FCKConfig.BasePath + 'filemanager/connectors/' + _FileBrowserLanguage + '/connector.' + _FileBrowserExtension ) ; FCKConfig.FlashBrowserWindowWidth = FCKConfig.ScreenWidth * 0.7 ; //70% ; FCKConfig.FlashBrowserWindowHeight = FCKConfig.ScreenHeight * 0.7 ; //70% ; FCKConfig.LinkUpload = true ; FCKConfig.LinkUploadURL = FCKConfig.BasePath + 'filemanager/connectors/' + _QuickUploadLanguage + '/upload.' + _QuickUploadExtension ; FCKConfig.LinkUploadAllowedExtensions = ".(7z|aiff|asf|avi|bmp|csv|doc|fla|flv|gif|gz|gzip|jpeg|jpg|mid|mov|mp3|mp4|mpc|mpeg|mpg|ods|odt|pdf|png|ppt|pxd|qt|ram|rar|rm|rmi|rmvb|rtf|sdc|sitd|swf|sxc|sxw|tar|tgz|tif|tiff|txt|vsd|wav|wma|wmv|xls|xml|zip)$" ; // empty for all FCKConfig.LinkUploadDeniedExtensions = "" ; // empty for no one FCKConfig.ImageUpload = true ; FCKConfig.ImageUploadURL = FCKConfig.BasePath + 'filemanager/connectors/' + _QuickUploadLanguage + '/upload.' + _QuickUploadExtension + '?Type=Image' ; FCKConfig.ImageUploadAllowedExtensions = ".(jpg|gif|jpeg|png|bmp)$" ; // empty for all FCKConfig.ImageUploadDeniedExtensions = "" ; // empty for no one FCKConfig.FlashUpload = true ; FCKConfig.FlashUploadURL = FCKConfig.BasePath + 'filemanager/connectors/' + _QuickUploadLanguage + '/upload.' + _QuickUploadExtension + '?Type=Flash' ; FCKConfig.FlashUploadAllowedExtensions = ".(swf|flv)$" ; // empty for all FCKConfig.FlashUploadDeniedExtensions = "" ; // empty for no one FCKConfig.SmileyPath = FCKConfig.BasePath + 'images/smiley/msn/' ; FCKConfig.SmileyImages = ['regular_smile.gif','sad_smile.gif','wink_smile.gif','teeth_smile.gif','confused_smile.gif','tounge_smile.gif','embaressed_smile.gif','omg_smile.gif','whatchutalkingabout_smile.gif','angry_smile.gif','angel_smile.gif','shades_smile.gif','devil_smile.gif','cry_smile.gif','lightbulb.gif','thumbs_down.gif','thumbs_up.gif','heart.gif','broken_heart.gif','kiss.gif','envelope.gif'] ; FCKConfig.SmileyColumns = 8 ; FCKConfig.SmileyWindowWidth = 320 ; FCKConfig.SmileyWindowHeight = 210 ; FCKConfig.BackgroundBlockerColor = '#ffffff' ; FCKConfig.BackgroundBlockerOpacity = 0.50 ; FCKConfig.MsWebBrowserControlCompat = false ; FCKConfig.PreventSubmitHandler = false ;
anam/abs
V1/fckeditor/fckconfig.js
JavaScript
mpl-2.0
13,602
"use strict"; add_task(setupPrefsAndRecentWindowBehavior); let testcases = [ /** * A portal is detected when there's no browser window, * then a browser window is opened, and the portal is logged into * and redirects to a different page. The portal tab should be added * and focused when the window is opened, and left open after login * since it redirected. */ function* test_detectedWithNoBrowserWindow_Redirect() { yield portalDetected(); let win = yield focusWindowAndWaitForPortalUI(); let browser = win.gBrowser.selectedTab.linkedBrowser; let loadPromise = BrowserTestUtils.browserLoaded(browser, false, CANONICAL_URL_REDIRECTED); BrowserTestUtils.loadURI(browser, CANONICAL_URL_REDIRECTED); yield loadPromise; yield freePortal(true); ensurePortalTab(win); ensureNoPortalNotification(win); yield closeWindowAndWaitForXulWindowVisible(win); }, /** * Test the various expected behaviors of the "Show Login Page" button * in the captive portal notification. The button should be visible for * all tabs except the captive portal tab, and when clicked, should * ensure a captive portal tab is open and select it. */ function* test_showLoginPageButton() { let win = yield openWindowAndWaitForFocus(); yield portalDetected(); let notification = ensurePortalNotification(win); testShowLoginPageButtonVisibility(notification, "visible"); function testPortalTabSelectedAndButtonNotVisible() { is(win.gBrowser.selectedTab, tab, "The captive portal tab should be selected."); testShowLoginPageButtonVisibility(notification, "hidden"); } let button = notification.querySelector("button.notification-button"); function* clickButtonAndExpectNewPortalTab() { let p = BrowserTestUtils.waitForNewTab(win.gBrowser, CANONICAL_URL); button.click(); let tab = yield p; is(win.gBrowser.selectedTab, tab, "The captive portal tab should be selected."); return tab; } // Simulate clicking the button. The portal tab should be opened and // selected and the button should hide. let tab = yield clickButtonAndExpectNewPortalTab(); testPortalTabSelectedAndButtonNotVisible(); // Close the tab. The button should become visible. yield BrowserTestUtils.removeTab(tab); ensureNoPortalTab(win); testShowLoginPageButtonVisibility(notification, "visible"); // When the button is clicked, a new portal tab should be opened and // selected. tab = yield clickButtonAndExpectNewPortalTab(); // Open another arbitrary tab. The button should become visible. When it's clicked, // the portal tab should be selected. let anotherTab = yield BrowserTestUtils.openNewForegroundTab(win.gBrowser); testShowLoginPageButtonVisibility(notification, "visible"); button.click(); is(win.gBrowser.selectedTab, tab, "The captive portal tab should be selected."); // Close the portal tab and select the arbitrary tab. The button should become // visible and when it's clicked, a new portal tab should be opened. yield BrowserTestUtils.removeTab(tab); win.gBrowser.selectedTab = anotherTab; testShowLoginPageButtonVisibility(notification, "visible"); tab = yield clickButtonAndExpectNewPortalTab(); yield BrowserTestUtils.removeTab(anotherTab); yield freePortal(true); ensureNoPortalTab(win); ensureNoPortalNotification(win); yield closeWindowAndWaitForXulWindowVisible(win); }, ]; for (let testcase of testcases) { add_task(testcase); }
Yukarumya/Yukarum-Redfoxes
browser/base/content/test/captivePortal/browser_CaptivePortalWatcher_1.js
JavaScript
mpl-2.0
3,581
/** * m59peacemaker's memoize * * See https://github.com/m59peacemaker/angular-pmkr-components/tree/master/src/memoize * Released under the MIT license */ angular.module('syncthing.core') .factory('pmkr.memoize', [ function() { function service() { return memoizeFactory.apply(this, arguments); } function memoizeFactory(fn) { var cache = {}; function memoized() { var args = [].slice.call(arguments); var key = JSON.stringify(args); if (cache.hasOwnProperty(key)) { return cache[key]; } cache[key] = fn.apply(this, arguments); return cache[key]; } return memoized; } return service; } ]);
atyenoria/syncthing
gui/syncthing/core/memoize.js
JavaScript
mpl-2.0
903
'use strict'; var LIVERELOAD_PORT = 35729; var lrSnippet = require('connect-livereload')({ port: LIVERELOAD_PORT }); var mountFolder = function (connect, dir) { return connect.static(require('path').resolve(dir)); }; var fs = require('fs'); var delayApiCalls = function (request, response, next) { if (request.url.indexOf('/api') !== -1) { setTimeout(function () { next(); }, 1000); } else { next(); } }; var httpMethods = function (request, response, next) { console.log("request method: " + JSON.stringify(request.method)); var rawpath = request.url.split('?')[0]; console.log("request url: " + JSON.stringify(request.url)); var path = require('path').resolve(__dirname, 'app/' + rawpath); console.log("request path : " + JSON.stringify(path)); console.log("request current dir : " + JSON.stringify(__dirname)); if ((request.method === 'PUT' || request.method === 'POST')) { console.log('inside put/post'); request.content = ''; request.addListener("data", function (chunk) { request.content += chunk; }); request.addListener("end", function () { console.log("request content: " + JSON.stringify(request.content)); if (fs.existsSync(path)) { if (request.method === 'POST') { response.statusCode = 403; response.end('Resource already exists.'); return; } fs.writeFile(path, request.content, function (err) { if (err) { response.statusCode(404); console.log('File not saved: ' + JSON.stringify(err)); response.end('Error writing to file.'); } else { console.log('File saved to: ' + path); response.end('File was saved.'); } }); return; } else { if (request.method === 'PUT') { response.statusCode = 404; response.end('Resource not found: ' + JSON.stringify(request.url)); return; } } if (request.url === '/log') { var filePath = 'server/log/server.log'; var logData = JSON.parse(request.content); fs.appendFile(filePath, logData.logUrl + '\n' + logData.logMessage + '\n', function (err) { if (err) { throw err; } console.log('log saved'); response.end('log was saved'); }); return; } }); return; } next(); }; // # Globbing // for performance reasons we're only matching one level down: // 'test/spec/{,*/}*.js' // use this if you want to recursively match all subfolders: // 'test/spec/**/*.js' module.exports = function (grunt) { require('load-grunt-tasks')(grunt); require('time-grunt')(grunt); // configurable paths var yeomanConfig = { app: 'app', dist: 'dist', doc: 'doc', test: 'test' }; try { yeomanConfig.app = require('./bower.json').appPath || yeomanConfig.app; } catch (e) {} grunt.initConfig({ yeoman: yeomanConfig, watch: { compass: { files: ['<%= yeoman.app %>/styles/**/*.{scss,sass}'], tasks: ['compass:server', 'autoprefixer:tmp'] }, styles: { files: ['<%= yeoman.app %>/styles/**/*.css'], tasks: ['autoprefixer:styles'] }, livereload: { options: { livereload: LIVERELOAD_PORT }, files: [ '<%= yeoman.app %>/**/*.html', '{.tmp,<%= yeoman.app %>}/styles/**/*.css', '{.tmp,<%= yeoman.app %>}/scripts/**/*.js', '{.tmp,<%= yeoman.app %>}/resources/**/*', '<%= yeoman.app %>/images/**/*.{png,jpg,jpeg,gif,webp,svg}' ] } // , // doc: { // files: ['{.tmp,<%= yeoman.app %>}/scripts/**/*.js'], // tasks: ['docular'] // } }, autoprefixer: { options: ['last 1 version'], tmp: { files: [{ expand: true, cwd: '.tmp/styles/', src: '**/*.css', dest: '.tmp/styles/' }] }, styles: { files: [{ expand: true, cwd: '<%= yeoman.app %>/styles/', src: '**/*.css', dest: '.tmp/styles/' }] } }, connect: { options: { protocol: 'http', port: 9000, // Change this to '0.0.0.0' to access the server from outside. hostname: 'localhost' }, livereload: { options: { middleware: function (connect) { return [ delayApiCalls, lrSnippet, mountFolder(connect, '.tmp'), mountFolder(connect, yeomanConfig.app), httpMethods ]; } } }, test: { options: { port: 9090, middleware: function (connect) { return [ mountFolder(connect, '.tmp'), mountFolder(connect, yeomanConfig.app), mountFolder(connect, '<%= yeoman.test %>'), httpMethods ]; } } }, dist: { options: { middleware: function (connect) { return [ delayApiCalls, mountFolder(connect, yeomanConfig.dist), httpMethods ]; } } }, doc: { options: { port: 3000, middleware: function (connect) { return [ mountFolder(connect, yeomanConfig.doc) ]; } } } }, open: { server: { url: '<%= connect.options.protocol %>://<%= connect.options.hostname %>:<%= connect.options.port %>' }, doc: { url: '<%= connect.options.protocol %>://<%= connect.options.hostname %>:9001' } }, clean: { dist: { files: [{ dot: true, src: [ '.tmp', '<%= yeoman.dist %>/*', '!<%= yeoman.dist %>/.git*' ] }] }, server: '.tmp' }, jshint: { options: { jshintrc: '.jshintrc' }, all: [ 'Gruntfile.js', '<%= yeoman.app %>/scripts/{,*/}*.js' ] }, compass: { options: { sassDir: '<%= yeoman.app %>/styles', cssDir: '.tmp/styles', generatedImagesDir: '.tmp/images/generated', imagesDir: '<%= yeoman.app %>/images', javascriptsDir: '<%= yeoman.app %>/scripts', fontsDir: '<%= yeoman.app %>/styles/fonts', importPath: '<%= yeoman.app %>/bower_components', httpImagesPath: '/images', httpGeneratedImagesPath: '/images/generated', httpFontsPath: '/styles/fonts', relativeAssets: false }, dist: { options: { debugInfo: false } }, server: { options: { debugInfo: true } } }, uglify: { dist: { files: { '<%= yeoman.dist %>/scripts/api/angular-jqm.js': ['<%= yeoman.app %>/scripts/api/angular-jqm.js'], '<%= yeoman.dist %>/bower_components/angular-animate/angular-animate.js': ['<%= yeoman.app %>/bower_components/angular-animate/angular-animate.js'], '<%= yeoman.dist %>/bower_components/angular-route/angular-route.js': ['<%= yeoman.app %>/bower_components/angular-route/angular-route.js'], '<%= yeoman.dist %>/bower_components/angular-touch/angular-touch.js': ['<%= yeoman.app %>/bower_components/angular-touch/angular-touch.js'] } } }, rev: { dist: { files: { src: [ '<%= yeoman.dist %>/scripts/*.js', '<%= yeoman.dist %>/styles/*.css', '<%= yeoman.dist %>/images/**/*.{png,jpg,jpeg,gif,webp,svg}', '!<%= yeoman.dist %>/images/glyphicons-*', '<%= yeoman.dist %>/styles/images/*.{gif,png}' ] } } }, useminPrepare: { html: '<%= yeoman.app %>/index.html', options: { dest: '<%= yeoman.dist %>' } }, usemin: { html: ['<%= yeoman.dist %>/*.html', '<%= yeoman.dist %>/views/**/*.html'], css: ['<%= yeoman.dist %>/styles/**/*.css'], options: { assetsDirs: ['<%= yeoman.dist %>/**'] } }, imagemin: { dist: { files: [{ expand: true, cwd: '<%= yeoman.app %>', src: [ 'styles/images/*.{jpg,jpeg,svg,gif}', 'images/*.{jpg,jpeg,svg,gif}' ], dest: '<%= yeoman.dist %>' }] } }, tinypng: { options: { apiKey: "l_QIDgceoKGF8PBNRr3cmYy_Nhfa9F1p", checkSigs: true, sigFile: '<%= yeoman.app %>/images/tinypng_sigs.json', summarize: true, showProgress: true, stopOnImageError: true }, dist: { expand: true, cwd: '<%= yeoman.app %>', src: 'images/**/*.png', dest: '<%= yeoman.app %>' } }, htmlmin: { dist: { options: { removeComments: true, removeCommentsFromCDATA: true, removeCDATASectionsFromCDATA: true, collapseWhitespace: true, // conservativeCollapse: true, collapseBooleanAttributes: true, removeAttributeQuotes: false, removeRedundantAttributes: true, useShortDoctype: true, removeEmptyAttributes: true, removeOptionalTags: true, keepClosingSlash: true, }, files: [{ expand: true, cwd: '<%= yeoman.dist %>', src: [ '*.html', 'views/**/*.html', 'template/**/*.html' ], dest: '<%= yeoman.dist %>' }] } }, // Put files not handled in other tasks here copy: { dist: { files: [{ expand: true, dot: true, cwd: '<%= yeoman.app %>', dest: '<%= yeoman.dist %>', src: [ '*.{ico,png,txt}', '.htaccess', 'api/**', 'images/{,*/}*.{gif,webp}', 'resources/**', 'styles/fonts/*', 'styles/images/*', '*.html', 'views/**/*.html', 'template/**/*.html' ] }, { expand: true, cwd: '.tmp/images', dest: '<%= yeoman.dist %>/images', src: [ 'generated/*' ] }, { expand: true, cwd: '<%= yeoman.app %>/bower_components/angular-i18n', dest: '<%= yeoman.dist %>/resources/i18n/angular', src: [ '*en-us.js', '*es-es.js', '*ja-jp.js', '*ar-eg.js' ] }] }, styles: { expand: true, cwd: '<%= yeoman.app %>/styles', dest: '.tmp/styles', src: '**/*.css' }, i18n: { expand: true, cwd: '<%= yeoman.app %>/bower_components/angular-i18n', dest: '.tmp/resources/i18n/angular', src: [ '*en-us.js', '*es-es.js', '*ja-jp.js', '*ar-eg.js' ] }, fonts: { expand: true, cwd: '<%= yeoman.app %>/bower_components/bootstrap-sass-official/assets/fonts', dest: '.tmp/fonts', src: '**/*' }, png: { expand: true, cwd: '<%= yeoman.app %>', dest: '<%= yeoman.dist %>', src: 'images/**/*.png' } }, concurrent: { server: [ 'compass:server', 'copy:i18n', 'copy:fonts' ], dist: [ 'compass:dist', 'imagemin' ] }, karma: { unit: { configFile: '<%= yeoman.test %>/karma-unit.conf.js', autoWatch: false, singleRun: true }, unit_auto: { configFile: '<%= yeoman.test %>/karma-unit.conf.js' }, midway: { configFile: '<%= yeoman.test %>/karma-midway.conf.js', autoWatch: false, singleRun: true }, midway_auto: { configFile: '<%= yeoman.test %>/karma-midway.conf.js' }, e2e: { configFile: '<%= yeoman.test %>/karma-e2e.conf.js', autoWatch: false, singleRun: true }, e2e_auto: { configFile: '<%= yeoman.test %>/karma-e2e.conf.js' } }, cdnify: { dist: { html: ['<%= yeoman.dist %>/*.html'] } }, ngAnnotate: { dist: { files: [{ expand: true, cwd: '.tmp/concat/scripts', src: '*.js', dest: '.tmp/concat/scripts' }] } }, docular: { showDocularDocs: false, showAngularDocs: true, docular_webapp_target: "doc", groups: [ { groupTitle: 'Appverse HTML5', groupId: 'appverse', groupIcon: 'icon-beer', sections: [ { id: "commonapi", title: "Common API", showSource: true, scripts: ["app/scripts/api/modules", "app/scripts/api/directives" ], docs: ["ngdocs/commonapi"], rank: {} } ] }, { groupTitle: 'Angular jQM', groupId: 'angular-jqm', groupIcon: 'icon-mobile-phone', sections: [ { id: "jqmapi", title: "API", showSource: true, scripts: ["app/scripts/api/angular-jqm.js" ], docs: ["ngdocs/jqmapi"], rank: {} } ] } ] } }); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-karma'); grunt.loadNpmTasks('grunt-docular'); grunt.registerTask('server', [ 'clean:server', 'concurrent:server', 'autoprefixer', 'connect:livereload', 'open:server', 'watch' ]); grunt.registerTask('testserver', [ 'clean:server', 'concurrent:server', 'autoprefixer', 'connect:test' ]); grunt.registerTask('test', [ 'karma:unit', 'testserver', 'karma:midway', 'karma:e2e' ]); grunt.registerTask('test:midway', [ 'testserver', 'karma:midway_auto' ]); grunt.registerTask('test:e2e', [ 'testserver', 'karma:e2e_auto' ]); grunt.registerTask('devmode', [ 'karma:unit_auto' ]); grunt.registerTask('doc', [ 'docular', 'connect:doc', 'open:doc', 'watch:doc' ]); grunt.registerTask('dist', [ 'clean:dist', 'useminPrepare', 'concurrent:dist', 'tinypng', 'copy:png', 'autoprefixer', 'concat', 'copy:dist', 'cdnify', 'ngAnnotate', 'cssmin', 'uglify', 'rev', 'usemin', 'htmlmin', 'connect:dist', // 'docular', // 'connect:doc', 'open:server', // 'open:doc', 'watch' ]); grunt.registerTask('default', [ 'server' ]); };
glarfs/training-unit-2
Gruntfile.js
JavaScript
mpl-2.0
19,182
const html = require('choo/html'); module.exports = function(name, url) { const dialog = function(state, emit, close) { return html` <send-share-dialog class="flex flex-col items-center text-center p-4 max-w-sm m-auto" > <h1 class="text-3xl font-bold my-4"> ${state.translate('notifyUploadEncryptDone')} </h1> <p class="font-normal leading-normal text-grey-80 dark:text-grey-40"> ${state.translate('shareLinkDescription')}<br /> <span class="word-break-all">${name}</span> </p> <input type="text" id="share-url" class="w-full my-4 border rounded-lg leading-loose h-12 px-2 py-1 dark:bg-grey-80" value="${url}" readonly="true" /> <button class="btn rounded-lg w-full flex-shrink-0 focus:outline" onclick="${share}" title="${state.translate('shareLinkButton')}" > ${state.translate('shareLinkButton')} </button> <button class="link-blue my-4 font-medium cursor-pointer focus:outline" onclick="${close}" title="${state.translate('okButton')}" > ${state.translate('okButton')} </button> </send-share-dialog> `; async function share(event) { event.stopPropagation(); try { await navigator.share({ title: state.translate('-send-brand'), text: state.translate('shareMessage', { name }), url }); } catch (e) { if (e.code === e.ABORT_ERR) { return; } console.error(e); } close(); } }; dialog.type = 'share'; return dialog; };
mozilla/send
app/ui/shareDialog.js
JavaScript
mpl-2.0
1,735
import { Mongo } from 'meteor/mongo'; const SurveyCaches = new Mongo.Collection('SurveyCaches'); SimpleSchema.debug = true; SurveyCaches.schema = new SimpleSchema({ title: { type: String, }, version: { type: Number, optional: true, autoValue() { return 2; }, }, createdAt: { type: Date, label: 'Created At', optional: true, autoValue() { let val; if (this.isInsert) { val = new Date(); } else if (this.isUpsert) { val = { $setOnInsert: new Date() }; } else { this.unset(); // Prevent user from supplying their own value } return val; }, }, updatedAt: { type: Date, label: 'Updated At', optional: true, autoValue() { let val; if (this.isUpdate) { val = new Date(); } return val; }, }, }); SurveyCaches.attachSchema(SurveyCaches.schema); export default SurveyCaches;
ctagroup/home-app
imports/api/surveys/surveyCaches.js
JavaScript
mpl-2.0
945
/*jslint unparam: true, browser: true, indent: 2 */ ;(function ($, window, document, undefined) { 'use strict'; Foundation.libs.dropdown = { name : 'dropdown', version : '4.3.2', settings : { activeClass: 'open', is_hover: false, opened: function(){}, closed: function(){} }, init : function (scope, method, options) { this.scope = scope || this.scope; Foundation.inherit(this, 'throttle scrollLeft data_options'); if (typeof method === 'object') { $.extend(true, this.settings, method); } if (typeof method !== 'string') { if (!this.settings.init) { this.events(); } return this.settings.init; } else { return this[method].call(this, options); } }, events : function () { var self = this; $(this.scope) .on('click.fndtn.dropdown', '[data-dropdown]', function (e) { var settings = $.extend({}, self.settings, self.data_options($(this))); e.preventDefault(); if (!settings.is_hover) self.toggle($(this)); }) .on('mouseenter', '[data-dropdown]', function (e) { var settings = $.extend({}, self.settings, self.data_options($(this))); if (settings.is_hover) self.toggle($(this)); }) .on('mouseleave', '[data-dropdown-content]', function (e) { var target = $('[data-dropdown="' + $(this).attr('id') + '"]'), settings = $.extend({}, self.settings, self.data_options(target)); if (settings.is_hover) self.close.call(self, $(this)); }) .on('opened.fndtn.dropdown', '[data-dropdown-content]', this.settings.opened) .on('closed.fndtn.dropdown', '[data-dropdown-content]', this.settings.closed); $(document).on('click.fndtn.dropdown touchstart.fndtn.dropdown', function (e) { var parent = $(e.target).closest('[data-dropdown-content]'); if ($(e.target).data('dropdown') || $(e.target).parent().data('dropdown')) { return; } if (!($(e.target).data('revealId')) && (parent.length > 0 && ($(e.target).is('[data-dropdown-content]') || $.contains(parent.first()[0], e.target)))) { e.stopPropagation(); return; } self.close.call(self, $('[data-dropdown-content]')); }); $(window).on('resize.fndtn.dropdown', self.throttle(function () { self.resize.call(self); }, 50)).trigger('resize'); this.settings.init = true; }, close: function (dropdown) { var self = this; dropdown.each(function () { if ($(this).hasClass(self.settings.activeClass)) { $(this) .css(Foundation.rtl ? 'right':'left', '-99999px') .removeClass(self.settings.activeClass) .prev('[data-dropdown]') .removeClass(self.settings.activeClass); $(this).trigger('closed'); } }); }, open: function (dropdown, target) { this .css(dropdown .addClass(this.settings.activeClass), target); dropdown.prev('[data-dropdown]').addClass(this.settings.activeClass); dropdown.trigger('opened'); }, toggle : function (target) { var dropdown = $('#' + target.data('dropdown')); if (dropdown.length === 0) { // No dropdown found, not continuing return; } this.close.call(this, $('[data-dropdown-content]').not(dropdown)); if (dropdown.hasClass(this.settings.activeClass)) { this.close.call(this, dropdown); } else { this.close.call(this, $('[data-dropdown-content]')) this.open.call(this, dropdown, target); } }, resize : function () { var dropdown = $('[data-dropdown-content].open'), target = $("[data-dropdown='" + dropdown.attr('id') + "']"); if (dropdown.length && target.length) { this.css(dropdown, target); } }, css : function (dropdown, target) { var offset_parent = dropdown.offsetParent(); // if (offset_parent.length > 0 && /body/i.test(dropdown.offsetParent()[0].nodeName)) { var position = target.offset(); position.top -= offset_parent.offset().top; position.left -= offset_parent.offset().left; // } else { // var position = target.position(); // } if (this.small()) { dropdown.css({ position : 'absolute', width: '95%', 'max-width': 'none', top: position.top + this.outerHeight(target) }); dropdown.css(Foundation.rtl ? 'right':'left', '2.5%'); } else { if (!Foundation.rtl && $(window).width() > this.outerWidth(dropdown) + target.offset().left && !this.data_options(target).align_right) { var left = position.left; if (dropdown.hasClass('right')) { dropdown.removeClass('right'); } } else { if (!dropdown.hasClass('right')) { dropdown.addClass('right'); } var left = position.left - (this.outerWidth(dropdown) - this.outerWidth(target)); } dropdown.attr('style', '').css({ position : 'absolute', top: position.top + this.outerHeight(target), left: left }); } return dropdown; }, small : function () { return $(window).width() < 768 || $('html').hasClass('lt-ie9'); }, off: function () { $(this.scope).off('.fndtn.dropdown'); $('html, body').off('.fndtn.dropdown'); $(window).off('.fndtn.dropdown'); $('[data-dropdown-content]').off('.fndtn.dropdown'); this.settings.init = false; }, reflow : function () {} }; }(Foundation.zj, this, this.document));
Elfhir/apero-imac
static/js/foundation/foundation.dropdown.js
JavaScript
mpl-2.0
5,841
'use strict'; var inheritance = require('./../../helpers/inheritance'), Field = require('./field'); var FilterField = function(){}; inheritance.inherits(Field,FilterField); FilterField.prototype.isOpen = function(){ return this.world.helper.elementGetter(this._root,this._data.elements.body).isDisplayed(); }; FilterField.prototype.accordionSelf = function(status){ var _this=this; switch(status){ case 'open': return _this.isOpen() .then(function(is){ if(!is){ return _this._root.scrollIntoView() .then(function(){ return _this._root.element(by.css('span.filter__sub-title')).click(); }) .then(function(){ return _this.world.helper.elementGetter(_this._root,_this._data.elements.body).waitToBeCompletelyVisibleAndStable(); }); } }); case 'close': return _this.isOpen() .then(function(is){ if(is){ return _this._root.scrollIntoView() .then(function(){ return _this._root.element(by.css('span.filter__sub-title')).click(); }) .then(function(){ return _this.world.helper.elementGetter(_this._root,_this._data.elements.body).waitToBeHidden(); }); } }); default: throw new Error('Wrong status of slider: '+status); } }; module.exports = FilterField;
Ivan-Katovich/cms-protractor-fw
test/e2e/support/ui_elements/fields/filterField.js
JavaScript
mpl-2.0
1,775
define([ 'jquery', 'underscore', 'backbone', 'text!template/login.html', 'models/campus' ], function ($, _, Backbone, LoginTemplate, CampusModel) { var LoginView = Backbone.View.extend({ tagName: 'section', className: 'container', template: _.template(LoginTemplate), events: { 'submit #frm-login': 'frmLoginOnSubmit', 'click #chk-password': 'chkPasswordOnCheck' }, render: function () { this.el.innerHTML = this.template(); return this; }, frmLoginOnSubmit: function (e) { e.preventDefault(); var self = this; var hostName = self.$('#txt-hostname').val().trim(); var username = self.$('#txt-username').val().trim(); var password = self.$('#txt-password').val().trim(); if (!hostName) { return; } if (!username) { return; } if (!password) { return; } self.$('#btn-submit').prop('disabled', true); var checkingLogin = $.post(hostName + '/main/webservices/rest.php', { action: 'loginNewMessages', username: username, password: password }); $.when(checkingLogin).done(function (response) { if (!response.status) { self.$('#btn-submit').prop('disabled', false); return; } var campusModel = new CampusModel({ url: hostName, username: username, apiKey: response.apiKey }); var savingCampus = campusModel.save(); $.when(savingCampus).done(function () { window.location.reload(); }); $.when(savingCampus).fail(function () { self.$('#btn-submit').prop('disabled', false); }); }); $.when(checkingLogin).fail(function () { self.$('#btn-submit').prop('disabled', false); }); }, chkPasswordOnCheck: function (e) { var inputType = e.target.checked ? 'text' : 'password'; this.$('#txt-password').attr('type', inputType); } }); return LoginView; });
AngelFQC/fx-dev-edition
app/js/views/login.js
JavaScript
mpl-2.0
2,454
const AWS = require('aws-sdk'); const s3 = new AWS.S3(); const conf = require('./config'); const { tmpdir } = require('os'); const fs = require('fs'); const path = require('path'); const mozlog = require('./log'); const log = mozlog('send.storage'); const redis = require('redis'); const redis_client = redis.createClient({ host: conf.redis_host, connect_timeout: 10000 }); redis_client.on('error', err => { log.error('Redis:', err); }); let tempDir = null; if (conf.s3_bucket) { module.exports = { filename: filename, exists: exists, ttl: ttl, length: awsLength, get: awsGet, set: awsSet, setField: setField, delete: awsDelete, forceDelete: awsForceDelete, ping: awsPing, flushall: flushall, quit: quit, metadata }; } else { tempDir = fs.mkdtempSync(`${tmpdir()}${path.sep}send-`); log.info('tempDir', tempDir); module.exports = { filename: filename, exists: exists, ttl: ttl, length: localLength, get: localGet, set: localSet, setField: setField, delete: localDelete, forceDelete: localForceDelete, ping: localPing, flushall: flushall, quit: quit, metadata }; } function flushall() { redis_client.flushdb(); } function quit() { redis_client.quit(); } function metadata(id) { return new Promise((resolve, reject) => { redis_client.hgetall(id, (err, reply) => { if (err || !reply) { return reject(err); } resolve(reply); }); }); } function ttl(id) { return new Promise((resolve, reject) => { redis_client.ttl(id, (err, reply) => { if (err || !reply) { return reject(err); } resolve(reply * 1000); }); }); } function filename(id) { return new Promise((resolve, reject) => { redis_client.hget(id, 'filename', (err, reply) => { if (err || !reply) { return reject(); } resolve(reply); }); }); } function exists(id) { return new Promise((resolve, reject) => { redis_client.exists(id, (rediserr, reply) => { if (reply === 1 && !rediserr) { resolve(); } else { reject(rediserr); } }); }); } function setField(id, key, value) { redis_client.hset(id, key, value); } function localLength(id) { return new Promise((resolve, reject) => { try { resolve(fs.statSync(path.join(tempDir, id)).size); } catch (err) { reject(); } }); } function localGet(id) { return fs.createReadStream(path.join(tempDir, id)); } function localSet(newId, file, filename, meta) { return new Promise((resolve, reject) => { const filepath = path.join(tempDir, newId); const fstream = fs.createWriteStream(filepath); file.pipe(fstream); file.on('limit', () => { file.unpipe(fstream); fstream.destroy(new Error('limit')); }); fstream.on('finish', () => { redis_client.hmset(newId, meta); redis_client.expire(newId, conf.expire_seconds); log.info('localSet:', 'Upload Finished of ' + newId); resolve(meta.delete); }); fstream.on('error', err => { log.error('localSet:', 'Failed upload of ' + newId); fs.unlinkSync(filepath); reject(err); }); }); } function localDelete(id, delete_token) { return new Promise((resolve, reject) => { redis_client.hget(id, 'delete', (err, reply) => { if (!reply || delete_token !== reply) { reject(); } else { redis_client.del(id); log.info('Deleted:', id); resolve(fs.unlinkSync(path.join(tempDir, id))); } }); }); } function localForceDelete(id) { return new Promise((resolve, reject) => { redis_client.del(id); resolve(fs.unlinkSync(path.join(tempDir, id))); }); } function localPing() { return new Promise((resolve, reject) => { redis_client.ping(err => { return err ? reject() : resolve(); }); }); } function awsLength(id) { const params = { Bucket: conf.s3_bucket, Key: id }; return new Promise((resolve, reject) => { s3.headObject(params, function(err, data) { if (!err) { resolve(data.ContentLength); } else { reject(); } }); }); } function awsGet(id) { const params = { Bucket: conf.s3_bucket, Key: id }; try { return s3.getObject(params).createReadStream(); } catch (err) { return null; } } function awsSet(newId, file, filename, meta) { const params = { Bucket: conf.s3_bucket, Key: newId, Body: file }; let hitLimit = false; const upload = s3.upload(params); file.on('limit', () => { hitLimit = true; upload.abort(); }); return upload.promise().then( () => { redis_client.hmset(newId, meta); redis_client.expire(newId, conf.expire_seconds); }, err => { if (hitLimit) { throw new Error('limit'); } else { throw err; } } ); } function awsDelete(id, delete_token) { return new Promise((resolve, reject) => { redis_client.hget(id, 'delete', (err, reply) => { if (!reply || delete_token !== reply) { reject(); } else { const params = { Bucket: conf.s3_bucket, Key: id }; s3.deleteObject(params, function(err, _data) { redis_client.del(id); err ? reject(err) : resolve(err); }); } }); }); } function awsForceDelete(id) { return new Promise((resolve, reject) => { const params = { Bucket: conf.s3_bucket, Key: id }; s3.deleteObject(params, function(err, _data) { redis_client.del(id); err ? reject(err) : resolve(); }); }); } function awsPing() { return localPing().then(() => s3.headBucket({ Bucket: conf.s3_bucket }).promise() ); }
dannycoates/chooloo
server/storage.js
JavaScript
mpl-2.0
5,806
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ "use strict"; var fs = require("fs"); var path = require("path"); var utils = require("../utils"); var chai = require("chai"); var expect = chai.expect; var exec = utils.exec; var simpleAddonPath = path.join(__dirname, "..", "fixtures", "simple-addon"); describe("jpm xpi", function () { beforeEach(utils.setup); afterEach(utils.tearDown); it("creates a xpi of the simple-addon", function (done) { var proc = exec("xpi", { addonDir: simpleAddonPath }); proc.on("close", function () { var xpiPath = path.join(simpleAddonPath, "@simple-addon-1.0.0.xpi"); utils.unzipTo(xpiPath, utils.tmpOutputDir).then(function () { utils.compareDirs(simpleAddonPath, utils.tmpOutputDir); fs.unlink(xpiPath); done(); }); }); }); });
matraska23/jpm
test/functional/test.xpi.js
JavaScript
mpl-2.0
987
import querystring from 'querystring' import SlackRTM from './SlackRTM' import FetchService from 'shared/FetchService' import userStore from 'stores/user/userStore' import accountStore from 'stores/account/accountStore' import { remote, ipcRenderer } from 'electron' import uuid from 'uuid' import { WB_WCFETCH_SERVICE_TEXT_CLEANUP } from 'shared/ipcEvents' const BASE_URL = 'https://slack.com/api/auth.test#sync-channel' class SlackHTTP { /* **************************************************************************/ // Utils /* **************************************************************************/ /** * Rejects a call because the service has no authentication info * @param info: any information we have * @return promise - rejected */ static _rejectWithNoAuth (info) { return Promise.reject(new Error('Service missing authentication information')) } static _fetch (serviceId, url, partitionId, opts) { return Promise.race([ this._fetchRaw(serviceId, url, partitionId, opts), new Promise((resolve, reject) => { setTimeout(() => { reject(new Error('timeout')) }, 30000) }) ]) } static _fetchRaw (serviceId, url, partitionId, opts) { if (userStore.getState().wceSlackHTTPWcThread()) { const wcId = accountStore.getState().getWebcontentTabId(serviceId) if (wcId) { const wc = remote.webContents.fromId(wcId) if (wc && !wc.isDestroyed()) { let isSlack try { isSlack = (new window.URL(wc.getURL())).hostname.endsWith('slack.com') } catch (ex) { isSlack = false } if (isSlack) { return Promise.resolve() .then(() => new Promise((resolve, reject) => { const channel = uuid.v4() let ipcMessageHandler let destroyedHandler let navigationHandler ipcMessageHandler = (evt, args) => { if (args[0] === channel) { wc.removeListener('ipc-message', ipcMessageHandler) wc.removeListener('destroyed', destroyedHandler) wc.removeListener('did-start-navigation', navigationHandler) resolve(args[1]) } } destroyedHandler = () => { wc.removeListener('ipc-message', ipcMessageHandler) wc.removeListener('did-start-navigation', navigationHandler) reject(new Error('inloaderror')) } navigationHandler = () => { wc.removeListener('ipc-message', ipcMessageHandler) wc.removeListener('destroyed', destroyedHandler) wc.removeListener('did-start-navigation', navigationHandler) reject(new Error('inloaderror')) } wc.on('ipc-message', ipcMessageHandler) wc.on('destroyed', destroyedHandler) wc.on('did-start-navigation', navigationHandler) wc.send('WB_WCFETCH_SERVICE_TEXT_RUNNER', channel, url, opts) })) .then( (res) => { ipcRenderer.send(WB_WCFETCH_SERVICE_TEXT_CLEANUP, BASE_URL, partitionId) return Promise.resolve({ status: res.status, ok: res.ok, text: () => Promise.resolve(res.body), json: () => Promise.resolve(JSON.parse(res.body)) }) }, (_err) => { return FetchService.wcRequest(BASE_URL, url, partitionId, opts) } ) } } } return FetchService.wcRequest(BASE_URL, url, partitionId, opts) } else { return FetchService.request(url, partitionId, opts) } } /* **************************************************************************/ // Profile /* **************************************************************************/ /** * Tests the auth * @param auth: the auth token * @return promise */ static testAuth (serviceId, auth, partitionId) { if (!auth) { return this._rejectWithNoAuth() } const query = querystring.stringify({ token: auth, '_x_gantry': true }) return Promise.resolve() .then(() => this._fetch(serviceId, 'https://slack.com/api/auth.test?' + query, partitionId, { credentials: 'include' })) .then((res) => res.ok ? Promise.resolve(res) : Promise.reject(res)) .then((res) => res.json()) .then((res) => res.ok ? Promise.resolve(res) : Promise.reject(res)) } /* **************************************************************************/ // RTM Start /* **************************************************************************/ /** * Starts the RTM sync service * @param auth: the auth token * @return promise */ static startRTM (serviceId, auth, partitionId) { if (!auth) { return this._rejectWithNoAuth() } const query = querystring.stringify({ token: auth, mpim_aware: true, '_x_gantry': true }) return Promise.resolve() .then(() => this._fetch(serviceId, 'https://slack.com/api/rtm.start?' + query, partitionId, { credentials: 'include' })) .then((res) => res.ok ? Promise.resolve(res) : Promise.reject(res)) .then((res) => res.json()) .then((res) => res.ok ? Promise.resolve(res) : Promise.reject(res)) .then((res) => { return { response: res, rtm: new SlackRTM(res.url) } }) } /* **************************************************************************/ // Unread /* **************************************************************************/ /** * Gets the unread info from the server * @param auth: the auth token * @param simpleUnreads = true: true to return the simple unread counts */ static fetchUnreadInfo (serviceId, auth, partitionId, simpleUnreads = true) { if (!auth) { return this._rejectWithNoAuth() } const query = querystring.stringify({ token: auth, simple_unreads: simpleUnreads, mpim_aware: true, include_threads: true, '_x_gantry': true }) return Promise.resolve() .then(() => this._fetch(serviceId, 'https://slack.com/api/users.counts?' + query, partitionId, { credentials: 'include' })) .then((res) => res.ok ? Promise.resolve(res) : Promise.reject(res)) .then((res) => res.json()) .then((res) => res.ok ? Promise.resolve(res) : Promise.reject(res)) } } export default SlackHTTP
wavebox/waveboxapp
classic/src/scenes/mailboxes/src/stores/slack/SlackHTTP.js
JavaScript
mpl-2.0
6,676
import React, { Fragment } from 'react'; import { compose, graphql } from 'react-apollo'; import { set } from 'react-redux-values'; import ReduxForm from 'declarative-redux-form'; import { Row, Col } from 'joyent-react-styled-flexboxgrid'; import { Margin } from 'styled-components-spacing'; import { change } from 'redux-form'; import { connect } from 'react-redux'; import intercept from 'apr-intercept'; import get from 'lodash.get'; import { NameIcon, H3, Button, H4, P } from 'joyent-ui-toolkit'; import Title from '@components/create-image/title'; import Details from '@components/create-image/details'; import Description from '@components/description'; import GetRandomName from '@graphql/get-random-name.gql'; import createClient from '@state/apollo-client'; import { instanceName as validateName } from '@state/validators'; import { Forms } from '@root/constants'; const NameContainer = ({ expanded, proceeded, name, version, description, placeholderName, randomizing, handleAsyncValidate, shouldAsyncValidate, handleNext, handleRandomize, handleEdit, step }) => ( <Fragment> <Title id={step} onClick={!expanded && !name && handleEdit} collapsed={!expanded && !proceeded} icon={<NameIcon />} > Image name and details </Title> {expanded ? ( <Description> Here you can name your custom image, version it, and give it a description so that you can identify it elsewhere in the Triton ecosystem. </Description> ) : null} <ReduxForm form={Forms.FORM_DETAILS} destroyOnUnmount={false} forceUnregisterOnUnmount={true} asyncValidate={handleAsyncValidate} shouldAsyncValidate={shouldAsyncValidate} onSubmit={handleNext} > {props => expanded ? ( <Details {...props} placeholderName={placeholderName} randomizing={randomizing} onRandomize={handleRandomize} /> ) : name ? ( <Margin top="3"> <H3 bold noMargin> {name} </H3> {version ? ( <Margin top="2"> <H4 bold noMargin> {version} </H4> </Margin> ) : null} {description ? ( <Row> <Col xs="12" sm="8"> <Margin top="1"> <P>{description}</P> </Margin> </Col> </Row> ) : null} </Margin> ) : null } </ReduxForm> {expanded ? ( <Margin top="4" bottom="7"> <Button type="button" disabled={!name} onClick={handleNext}> Next </Button> </Margin> ) : proceeded ? ( <Margin top="4" bottom="7"> <Button type="button" onClick={handleEdit} secondary> Edit </Button> </Margin> ) : null} </Fragment> ); export default compose( graphql(GetRandomName, { options: () => ({ fetchPolicy: 'network-only', ssr: false }), props: ({ data }) => ({ placeholderName: data.rndName || '' }) }), connect( ({ form, values }, ownProps) => { const name = get(form, `${Forms.FORM_DETAILS}.values.name`, ''); const version = get(form, `${Forms.FORM_DETAILS}.values.version`, ''); const description = get( form, `${Forms.FORM_DETAILS}.values.description`, '' ); const proceeded = get(values, `${Forms.FORM_DETAILS}-proceeded`, false); const randomizing = get(values, 'create-image-name-randomizing', false); return { ...ownProps, proceeded, randomizing, name, version, description }; }, (dispatch, { history, match }) => ({ handleNext: () => { dispatch(set({ name: `${Forms.FORM_DETAILS}-proceeded`, value: true })); return history.push(`/images/~create/${match.params.instance}/tag`); }, handleEdit: () => { dispatch(set({ name: `${Forms.FORM_DETAILS}-proceeded`, value: true })); return history.push(`/images/~create/${match.params.instance}/name`); }, shouldAsyncValidate: ({ trigger }) => { return trigger === 'change'; }, handleAsyncValidate: validateName, handleRandomize: async () => { dispatch(set({ name: 'create-image-name-randomizing', value: true })); const [err, res] = await intercept( createClient().query({ fetchPolicy: 'network-only', query: GetRandomName }) ); dispatch(set({ name: 'create-image-name-randomizing', value: false })); if (err) { // eslint-disable-next-line no-console console.error(err); return; } const { data } = res; const { rndName } = data; return dispatch(change(Forms.FORM_DETAILS, 'name', rndName)); } }) ) )(NameContainer);
yldio/joyent-portal
consoles/my-joy-images/src/containers/create-image/details.js
JavaScript
mpl-2.0
5,062
/* Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang("placeholder","pt",{title:"Propriedades dos marcadores",toolbar:"Símbolo",name:"Nome do marcador",invalidName:"O marcador não pode estar em branco e não pode conter qualquer dos seguintes carateres: [, ], <, >",pathName:"símbolo"});
crunchmail/dentifrice
dist/ckeditor/plugins/placeholder/lang/pt.js
JavaScript
mpl-2.0
406
$(function() { function FirmwareUpdaterViewModel(parameters) { var self = this; self.settingsViewModel = parameters[0]; self.loginState = parameters[1]; self.connection = parameters[2]; self.printerState = parameters[3]; self.configPathAvrdude = ko.observable(); self.hexFileName = ko.observable(undefined); self.hexFileURL = ko.observable(undefined); self.alertMessage = ko.observable(""); self.alertType = ko.observable("alert-warning"); self.showAlert = ko.observable(false); self.missingParamToFlash = ko.observable(false); self.progressBarText = ko.observable(); self.isBusy = ko.observable(false); self.updateAvailable = ko.observable(false); self.pathBroken = ko.observable(false); self.pathOk = ko.observable(false); self.pathText = ko.observable(); self.pathHelpVisible = ko.computed(function() { return self.pathBroken() || self.pathOk(); }); self.inSettingsDialog = false; self.selectHexPath = $("#settings_firmwareupdater_selectHexPath"); self.configurationDialog = $("#settings_plugin_firmwareupdater_configurationdialog"); self.selectHexPath.fileupload({ dataType: "hex", maxNumberOfFiles: 1, autoUpload: false, add: function(e, data) { if (data.files.length == 0) { return false; } self.hexData = data; self.hexFileName(data.files[0].name); } }) self.startFlashFromFile = function() { if (!self.loginState.isAdmin()){ self.alertType("alert-warning") self.alertMessage(gettext("Administrator privileges are needed to flash firmware.")); self.showAlert(true); return false; } if (self.printerState.isPrinting() || self.printerState.isPaused()){ self.alertType("alert-warning") self.alertMessage(gettext("Printer is printing. Please wait for the print to be finished.")); self.showAlert(true); return false; } if (!self.settingsViewModel.settings.plugins.firmwareupdater.avrdude_path()) { self.alertType("alert-warning") self.alertMessage(gettext("AVRDUDE path not configured")); self.showAlert(true); return false; } if (!self.hexFileName()) { self.alertType("alert-warning") self.alertMessage(gettext("Hex file path not specified")); self.showAlert(true); return false; } if (!self.connection.selectedPort()) { self.alertType("alert-warning") self.alertMessage(gettext("Port not selected")); self.showAlert(true); return false; } self.progressBarText("Flashing firmware..."); self.isBusy(true); self.showAlert(false); var form = { selected_port: self.connection.selectedPort() }; self.hexData.formData = form; self.hexData.submit(); } self.startFlashFromURL = function() { if (!self.loginState.isAdmin()){ self.alertType("alert-warning") self.alertMessage(gettext("Administrator privileges are needed to flash firmware.")); self.showAlert(true); return false; } if (self.printerState.isPrinting() || self.printerState.isPaused()){ self.alertType("alert-warning") self.alertMessage(gettext("Printer is printing. Please wait for the print to be finished.")); self.showAlert(true); return false; } if (!self.settingsViewModel.settings.plugins.firmwareupdater.avrdude_path()) { self.alertType("alert-warning") self.alertMessage(gettext("AVRDUDE path not configured")); self.showAlert(true); return false; } if (!self.hexFileURL()) { self.alertType("alert-warning") self.alertMessage(gettext("Hex file URL not specified")); self.showAlert(true); return false; } if (!self.connection.selectedPort()) { self.alertType("alert-warning") self.alertMessage(gettext("Port not selected")); self.showAlert(true); return false; } self.isBusy(true); self.showAlert(false); self.progressBarText("Flashing firmware..."); $.ajax({ url: PLUGIN_BASEURL + "firmwareupdater/flashFirmwareWithURL", type: "POST", dataType: "json", data: JSON.stringify({ selected_port: self.connection.selectedPort(), hex_url: self.hexFileURL() }), contentType: "application/json; charset=UTF-8" }) } self.checkForUpdates = function() { if (self.printerState.isPrinting() || self.printerState.isPaused()){ self.alertType("alert-warning") self.alertMessage(gettext("Printer is printing. Please wait for the print to be finished.")); self.showAlert(true); return false; } if (!self.connection.selectedPort()) { self.alertType("alert-warning") self.alertMessage(gettext("Port not selected")); self.showAlert(true); return false; } self.isBusy(true); self.showAlert(false); $.ajax({ url: PLUGIN_BASEURL + "firmwareupdater/checkForUpdates", type: "POST", dataType: "json", data: JSON.stringify({ selected_port: self.connection.selectedPort(), }), contentType: "application/json; charset=UTF-8" }); } self.flashUpdate = function() { if (self.printerState.isPrinting() || self.printerState.isPaused()){ self.alertType("alert-warning") self.alertMessage(gettext("Printer is printing. Please wait for the print to be finished.")); self.showAlert(true); return false; } if (!self.settingsViewModel.settings.plugins.firmwareupdater.avrdude_path()) { self.alertType("alert-warning") self.alertMessage(gettext("AVRDUDE path not configured")); self.showAlert(true); return false; } if (!self.connection.selectedPort()) { self.alertType("alert-warning") self.alertMessage(gettext("Port not selected")); self.showAlert(true); return false; } self.isBusy(true); self.showAlert(false); self.progressBarText("Flashing firmware..."); console.log(AJAX_BASEURL + "system"); $.ajax({ url: PLUGIN_BASEURL + "firmwareupdater/flashUpdate", type: "POST", dataType: "json", data: JSON.stringify({ selected_port: self.connection.selectedPort() }), contentType: "application/json; charset=UTF-8" }); } self.onDataUpdaterPluginMessage = function(plugin, data) { if (plugin != "firmwareupdater") { return; } if (data.type == "status" && data.status_type == "check_update_status") { if (data.status_value == "progress") { self.progressBarText(data.status_description); return; } if (data.status_value == "update_available") { if (!self.inSettingsDialog) { self.showUpdateAvailablePopup(data.status_description); } self.updateAvailable(true); self.isBusy(false); return; } if (data.status_value == "up_to_date") { self.updateAvailable(false); self.isBusy(false); self.showAlert(false); if (self.inSettingsDialog) { self.alertType("alert-success"); self.alertMessage(data.status_description); self.showAlert(true); } return; } if (data.status_value == "error") { self.updateAvailable(false); self.isBusy(false); self.alertType("alert-danger"); self.alertMessage(data.status_description); self.showAlert(true); return; } } if (data.type == "status" && data.status_type == "flashing_status") { if (data.status_value == "starting_flash") { self.isBusy(true); } else if (data.status_value == "progress") { self.progressBarText(data.status_description); } else if (data.status_value == "info") { self.alertType("alert-info"); self.alertMessage(data.status_description); self.showAlert(true); } else if (data.status_value == "successful") { self.showPopup("success", "Flashing Successful", ""); self.isBusy(false); self.showAlert(false); self.hexFileName(undefined); self.hexFileURL(undefined); } else if (data.status_value == "error") { self.showPopup("error", "Flashing Failed", data.status_description); self.isBusy(false); self.showAlert(false); } } } self.showPluginConfig = function() { self.configPathAvrdude(self.settingsViewModel.settings.plugins.firmwareupdater.avrdude_path()); self.configurationDialog.modal(); } self.onConfigClose = function() { self._saveAvrdudePath(); self.configurationDialog.modal("hide"); self.onConfigHidden(); if (self.configPathAvrdude()) { self.showAlert(false); } } self._saveAvrdudePath = function() { var data = { plugins: { firmwareupdater: { avrdude_path: self.configPathAvrdude(), } } } self.settingsViewModel.saveData(data); } self.onConfigHidden = function() { self.pathBroken(false); self.pathOk(false); self.pathText(""); } self.testAvrdudePath = function() { $.ajax({ url: API_BASEURL + "util/test", type: "POST", dataType: "json", data: JSON.stringify({ command: "path", path: self.configPathAvrdude(), check_type: "file", check_access: "x" }), contentType: "application/json; charset=UTF-8", success: function(response) { if (!response.result) { if (!response.exists) { self.pathText(gettext("The path doesn't exist")); } else if (!response.typeok) { self.pathText(gettext("The path is not a file")); } else if (!response.access) { self.pathText(gettext("The path is not an executable")); } } else { self.pathText(gettext("The path is valid")); } self.pathOk(response.result); self.pathBroken(!response.result); } }) } self.isReadyToFlashFromFile = function() { if (self.printerState.isPrinting() || self.printerState.isPaused()){ return false; } if (!self.settingsViewModel.settings.plugins.firmwareupdater.avrdude_path()) { return false; } if (!self.connection.selectedPort()) { return false; } if (!self.hexFileName()) { return false; } self.showAlert(false); return true; } self.isReadyToFlashFromURL = function() { if (self.printerState.isPrinting() || self.printerState.isPaused()){ return false; } if (!self.settingsViewModel.settings.plugins.firmwareupdater.avrdude_path()) { return false; } if (!self.connection.selectedPort()) { return false; } if (!self.hexFileURL()) { return false; } self.showAlert(false); return true; } self.isReadyToCheck = function() { if (self.printerState.isPrinting() || self.printerState.isPaused()){ return false; } if (!self.connection.selectedPort()) { return false; } return true; } self.isReadyToUpdate = function() { if (self.printerState.isPrinting() || self.printerState.isPaused()){ return false; } if (!self.settingsViewModel.settings.plugins.firmwareupdater.avrdude_path()) { return false; } if (!self.connection.selectedPort() || self.connection.selectedPort() == "AUTO") { return false; } return true; } self.onSettingsShown = function() { self.inSettingsDialog = true; } self.onSettingsHidden = function() { self.inSettingsDialog = false; self.showAlert(false); } // Popup Messages self.showUpdateAvailablePopup = function(new_fw_version) { self.updateAvailablePopup = new PNotify({ title: gettext('Firmware Update Available'), text: gettext('Version ') + new_fw_version, icon: true, hide: false, type: 'success', buttons: { closer: true, sticker: false, }, history: { history: false } }); }; self.showPopup = function(message_type, title, text){ if (self.popup !== undefined){ self.closePopup(); } self.popup = new PNotify({ title: gettext(title), text: text, type: message_type, hide: false }); } self.closePopup = function() { if (self.popup !== undefined) { self.popup.remove(); } }; } OCTOPRINT_VIEWMODELS.push([ FirmwareUpdaterViewModel, ["settingsViewModel", "loginStateViewModel", "connectionViewModel", "printerStateViewModel"], [document.getElementById("settings_plugin_firmwareupdater")] ]); });
mcecchi/SuperOcto
OctoPrint-FirmwareUpdater/octoprint_firmwareupdater/static/js/firmwareupdater.js
JavaScript
agpl-3.0
16,233
exports.main = function(env){ var capsule = env.capsule; var mtests = capsule.tests.modules; var thsocket = capsule.tests.modules.transport.http.socket_srv; // mtests.http_responder.test(capsule); // thsocket.test({ 'url' : 'http://localhost:8810/sockethh.js'}, capsule); var thttp = capsule.tests.modules.transport.http.server; thttp.test({ 'url' : 'http://localhost:8810/krevetk/o'}, capsule); }
ixdu/capsule
tests/deployer/nodejs_srv/capsulated.js
JavaScript
agpl-3.0
445
/* Copyright (c) 2006-2012 by OpenLayers Contributors (see authors.txt for * full list of contributors). Published under the 2-clause BSD license. * See license.txt in the OpenLayers distribution or repository for the * full text of the license. */ /** * @requires OpenLayers/Format/SLD/v1.js * @requires OpenLayers/Format/Filter/v1_0_0.js */ /** * Class: OpenLayers.Format.SLD.v1_0_0 * Write SLD version 1.0.0. * * Inherits from: * - <OpenLayers.Format.SLD.v1> */ OpenLayers.Format.SLD.v1_0_0 = OpenLayers.Class( OpenLayers.Format.SLD.v1, { /** * Constant: VERSION * {String} 1.0.0 */ VERSION: "1.0.0", /** * Property: schemaLocation * {String} http://www.opengis.net/sld * http://schemas.opengis.net/sld/1.0.0/StyledLayerDescriptor.xsd */ schemaLocation: "http://www.opengis.net/sld http://schemas.opengis.net/sld/1.0.0/StyledLayerDescriptor.xsd", /** * Constructor: OpenLayers.Format.SLD.v1_0_0 * Instances of this class are not created directly. Use the * <OpenLayers.Format.SLD> constructor instead. * * Parameters: * options - {Object} An optional object whose properties will be set on * this instance. */ CLASS_NAME: "OpenLayers.Format.SLD.v1_0_0" });
B3Partners/geo-ov
src/main/webapp/openlayers/lib/OpenLayers/Format/SLD/v1_0_0.js
JavaScript
agpl-3.0
1,351
'use strict'; angular.module('GO.Modules.GroupOffice.Contacts').factory('GO.Modules.GroupOffice.Contacts.Model.ContactGroup', [ 'GO.Core.Factories.Data.Model', function (Model) { var ContactGroup = GO.extend(Model, function () { //rename function because this record has a delete attribute on the server this.deleteRecord = this.delete; this.$parent.constructor.call(this, arguments); }); ContactGroup.prototype.getStoreRoute = function () { return 'contacts/'+this.contactId+'/permissions'; }; ContactGroup.prototype.$keys = ['groupId']; return ContactGroup; }]);
Intermesh/groupoffice-webclient
app/modules/groupoffice/contacts/model/contact-group.js
JavaScript
agpl-3.0
610
(function() { 'use strict'; var getModulesList = function(modules) { return modules.map(function(moduleName) { return {name: moduleName}; }); }; var jsOptimize = process.env.REQUIRE_BUILD_PROFILE_OPTIMIZE !== undefined ? process.env.REQUIRE_BUILD_PROFILE_OPTIMIZE : 'uglify2'; return { namespace: 'RequireJS', /** * List the modules that will be optimized. All their immediate and deep * dependencies will be included in the module's file when the build is * done. */ modules: getModulesList([ 'course_bookmarks/js/course_bookmarks_factory', 'course_search/js/course_search_factory', 'course_search/js/dashboard_search_factory', 'discussion/js/discussion_board_factory', 'discussion/js/discussion_profile_page_factory', 'js/api_admin/catalog_preview_factory', 'js/courseware/courseware_factory', 'js/discovery/discovery_factory', 'js/edxnotes/views/notes_visibility_factory', 'js/edxnotes/views/page_factory', 'js/financial-assistance/financial_assistance_form_factory', 'js/groups/views/cohorts_dashboard_factory', 'js/discussions_management/views/discussions_dashboard_factory', 'js/header_factory', 'js/learner_dashboard/course_entitlement_factory', 'js/learner_dashboard/unenrollment_factory', 'js/learner_dashboard/entitlement_unenrollment_factory', 'js/learner_dashboard/program_details_factory', 'js/learner_dashboard/program_list_factory', 'js/student_account/logistration_factory', 'js/student_account/views/account_settings_factory', 'js/student_account/views/finish_auth_factory', 'js/views/message_banner', 'learner_profile/js/learner_profile_factory', 'lms/js/preview/preview_factory', 'support/js/certificates_factory', 'support/js/enrollment_factory', 'support/js/manage_user_factory', 'teams/js/teams_tab_factory', 'js/dateutil_factory' ]), /** * By default all the configuration for optimization happens from the command * line or by properties in the config file, and configuration that was * passed to requirejs as part of the app's runtime "main" JS file is *not* * considered. However, if you prefer the "main" JS file configuration * to be read for the build so that you do not have to duplicate the values * in a separate configuration, set this property to the location of that * main JS file. The first requirejs({}), require({}), requirejs.config({}), * or require.config({}) call found in that file will be used. * As of 2.1.10, mainConfigFile can be an array of values, with the last * value's config take precedence over previous values in the array. */ mainConfigFile: 'require-config.js', /** * Set paths for modules. If relative paths, set relative to baseUrl above. * If a special value of "empty:" is used for the path value, then that * acts like mapping the path to an empty file. It allows the optimizer to * resolve the dependency to path, but then does not include it in the output. * Useful to map module names that are to resources on a CDN or other * http: URL when running in the browser and during an optimization that * file should be skipped because it has no dependencies. */ paths: { gettext: 'empty:', 'coffee/src/ajax_prefix': 'empty:', jquery: 'empty:', 'jquery-migrate': 'empty:', 'jquery.cookie': 'empty:', 'jquery.url': 'empty:', backbone: 'empty:', underscore: 'empty:', 'underscore.string': 'empty:', logger: 'empty:', utility: 'empty:', URI: 'empty:', 'common/js/discussion/views/discussion_inline_view': 'empty:', modernizr: 'empty', 'which-country': 'empty', // Don't bundle UI Toolkit helpers as they are loaded into the "edx" namespace 'edx-ui-toolkit/js/utils/html-utils': 'empty:', 'edx-ui-toolkit/js/utils/string-utils': 'empty:' }, /** * Inline requireJS text templates. */ inlineText: true, /** * Stub out requireJS text in the optimized file, but leave available for non-optimized development use. */ stubModules: ['text'], /** * If shim config is used in the app during runtime, duplicate the config * here. Necessary if shim config is used, so that the shim's dependencies * are included in the build. Using "mainConfigFile" is a better way to * pass this information though, so that it is only listed in one place. * However, if mainConfigFile is not an option, the shim config can be * inlined in the build config. */ shim: {}, /** * Introduced in 2.1.2: If using "dir" for an output directory, normally the * optimize setting is used to optimize the build bundles (the "modules" * section of the config) and any other JS file in the directory. However, if * the non-build bundle JS files will not be loaded after a build, you can * skip the optimization of those files, to speed up builds. Set this value * to true if you want to skip optimizing those other non-build bundle JS * files. */ skipDirOptimize: true, /** * When the optimizer copies files from the source location to the * destination directory, it will skip directories and files that start * with a ".". If you want to copy .directories or certain .files, for * instance if you keep some packages in a .packages directory, or copy * over .htaccess files, you can set this to null. If you want to change * the exclusion rules, change it to a different regexp. If the regexp * matches, it means the directory will be excluded. This used to be * called dirExclusionRegExp before the 1.0.2 release. * As of 1.0.3, this value can also be a string that is converted to a * RegExp via new RegExp(). */ fileExclusionRegExp: /^\.|spec|spec_helpers/, /** * Allow CSS optimizations. Allowed values: * - "standard": @import inlining and removal of comments, unnecessary * whitespace and line returns. * Removing line returns may have problems in IE, depending on the type * of CSS. * - "standard.keepLines": like "standard" but keeps line returns. * - "none": skip CSS optimizations. * - "standard.keepComments": keeps the file comments, but removes line * returns. (r.js 1.0.8+) * - "standard.keepComments.keepLines": keeps the file comments and line * returns. (r.js 1.0.8+) * - "standard.keepWhitespace": like "standard" but keeps unnecessary whitespace. */ optimizeCss: 'none', /** * How to optimize all the JS files in the build output directory. * Right now only the following values are supported: * - "uglify": Uses UglifyJS to minify the code. * - "uglify2": Uses UglifyJS2. * - "closure": Uses Google's Closure Compiler in simple optimization * mode to minify the code. Only available if REQUIRE_ENVIRONMENT is "rhino" (the default). * - "none": No minification will be done. */ optimize: jsOptimize, /** * Sets the logging level. It is a number: * TRACE: 0, * INFO: 1, * WARN: 2, * ERROR: 3, * SILENT: 4 * Default is 0. */ logLevel: 1 }; }());
TeachAtTUM/edx-platform
lms/static/lms/js/build.js
JavaScript
agpl-3.0
8,162
import React from 'react' import {intlEnzyme} from 'tocco-test-util' import MenuChildrenWrapper from './MenuChildrenWrapper' import {StyledMenuChildrenWrapper} from './StyledComponents' describe('admin', () => { describe('components', () => { describe('Navigation', () => { describe('menuType', () => { describe('MenuChildrenWrapper', () => { test('should render children when expanded', () => { const isOpen = true const canCollapse = true const children = <div id="child">Hallo</div> const props = { isOpen, canCollapse, menuTreePath: 'address', preferencesPrefix: '' } const wrapper = intlEnzyme.mountWithIntl(<MenuChildrenWrapper {...props}>{children}</MenuChildrenWrapper>) expect(wrapper.find(StyledMenuChildrenWrapper).prop('isOpen')).to.be.true }) test('should not render children when collapsed', () => { const isOpen = false const canCollapse = true const children = <div id="child">Hallo</div> const props = { isOpen, canCollapse, menuTreePath: 'address', preferencesPrefix: '' } const wrapper = intlEnzyme.mountWithIntl(<MenuChildrenWrapper {...props}>{children}</MenuChildrenWrapper>) expect(wrapper.find(StyledMenuChildrenWrapper).prop('isOpen')).to.be.false }) test('should render children when not collapsible', () => { const isOpen = false const canCollapse = false const children = <div id="child">Hallo</div> const props = { isOpen, canCollapse, menuTreePath: 'address', preferencesPrefix: '' } const wrapper = intlEnzyme.mountWithIntl(<MenuChildrenWrapper {...props}>{children}</MenuChildrenWrapper>) expect(wrapper.find(StyledMenuChildrenWrapper).prop('isOpen')).to.be.true }) }) }) }) }) })
tocco/tocco-client
packages/apps/admin/src/components/Navigation/menuType/MenuChildrenWrapper.spec.js
JavaScript
agpl-3.0
2,143
'use strict'; var phonetic = require('phonetic'); var socketio = require('socket.io'); var _ = require('underscore'); var load = function(http) { var io = socketio(http); var ioNamespace = '/'; var getEmptyRoomId = function() { var roomId = null; do { roomId = phonetic.generate().toLowerCase() } while (io.nsps[ioNamespace].adapter.rooms[roomId]); return roomId; }; var sendRoomInfo = function(socket, info) { if (!info.roomId) { return; } var clients = io.nsps[ioNamespace].adapter.rooms[info.roomId]; io.sockets.in(info.roomId).emit('room.info', { id: info.roomId, count: clients ? Object.keys(clients).length : 0 }); }; var onJoin = function(socket, info, data) { if (info.roomId) { return; } info.roomId = data && data.roomId ? data.roomId : null; if (!info.roomId || !io.nsps[ioNamespace].adapter.rooms[data.roomId]) { info.roomId = getEmptyRoomId(socket); console.log('[Socket] Assigning room id ' + info.roomId + ' to ip ' + socket.handshake.address); } else { console.log('[Socket] Assigning room id ' + info.roomId + ' to ip ' + socket.handshake.address + ' (from client)'); } socket.join(info.roomId); socket.emit('join', { roomId: info.roomId }); sendRoomInfo(socket, info); }; var onEvent = function(socket, info, event, data) { if (!info.roomId) { return; } socket.broadcast.to(info.roomId).emit(event, data); }; var onChunk = function(socket, info, data) { socket.emit('file.ack', { guid: data.guid }); onEvent(socket, info, 'file.chunk', data); }; var onConnection = function(socket) { console.log('[Socket] New connection from ip ' + socket.handshake.address); var info = { roomId: null }; socket.on('disconnect', function() { console.log('[Socket] Connection from ip ' + socket.handshake.address + ' disconnected'); sendRoomInfo(socket, info); }); socket.on('join', _.partial(onJoin, socket, info)); socket.on('file.start', _.partial(onEvent, socket, info, 'file.start')); socket.on('file.chunk', _.partial(onChunk, socket, info)); } io.on('connection', onConnection); }; module.exports = { load: load };
ryanpetris/droppy
socket.js
JavaScript
agpl-3.0
2,696
// //{block name="backend/create_backend_order/view/toolbar"} // Ext.define('Shopware.apps.SwagBackendOrder.view.main.Toolbar', { extend: 'Ext.toolbar.Toolbar', alternateClassName: 'SwagBackendOrder.view.main.Toolbar', alias: 'widget.createbackendorder-toolbar', dock: 'top', ui: 'shopware-ui', padding: '0 10 0 10', snippets: { buttons: { openCustomer: '{s namespace="backend/swag_backend_order/view/toolbar" name="swag_backend_order/toolbar/button/open_customer"}Open Customer{/s}', createCustomer: '{s namespace="backend/swag_backend_order/view/toolbar" name="swag_backend_order/toolbar/button/create_customer"}Create Customer{/s}', createGuest: '{s namespace="backend/swag_backend_order/view/toolbar" name="swag_backend_order/toolbar/button/create_guest"}Create Guest{/s}' }, shop: { noCustomer: '{s namespace="backend/swag_backend_order/view/toolbar" name="swag_backend_order/toolbar/shop/label/no_costumer"}Shop: No customer selected.{/s}', default: '{s namespace="backend/swag_backend_order/view/toolbar" name="swag_backend_order/toolbar/shop/label/default"}Shop: {/s}' }, currencyLabel: '{s namespace="backend/swag_backend_order/view/toolbar" name="swag_backend_order/toolbar/currency/label"}Choose currency{/s}', languageLabel: '{s namespace="backend/swag_backend_order/view/toolbar" name="swag_backend_order/toolbar/language/label"}Language{/s}' }, /** * */ initComponent: function () { var me = this; me.items = me.createToolbarItems(); me.languageStore = Ext.create('Ext.data.Store', { name: 'languageStore', fields: ['id', 'mainId', 'categoryId', 'name', 'title', 'default'] }); /** * automatically selects the standard currency */ me.currencyStore = me.subApplication.getStore('Currency'); me.currencyStore.on('load', function () { me.changeCurrencyComboBox.bindStore(me.currencyStore); var standardCurrency = me.currencyStore.findExact('default', 1); if (standardCurrency > -1) { me.currencyModel = me.currencyStore.getAt(standardCurrency); me.changeCurrencyComboBox.select(me.currencyModel); me.currencyModel.set('selected', 1); } else { me.changeCurrencyComboBox.select(me.currencyStore.first()); me.currencyStore.first().set('selected', 1); } }); me.customerSearchField.on('valueselect', function () { me.openCustomerButton.setDisabled(false); }); //selects and loads the language sub shops var customerStore = me.subApplication.getStore('Customer'); customerStore.on('load', function () { if (typeof customerStore.getAt(0) !== 'undefined') { var shopName = '', customerModel = customerStore.getAt(0); var languageId = customerModel.get('languageId'); var index = customerModel.languageSubShop().findExact('id', languageId); if (index >= 0) { shopName = customerModel.languageSubShop().getAt(index).get('name'); } else { index = customerModel.shop().findExact('id', languageId); shopName = customerModel.shop().getAt(index).get('name'); } me.shopLabel.setText(me.snippets.shop.default + shopName); me.fireEvent('changeCustomer'); me.getLanguageShops(customerModel.shop().getAt(0).get('id'), customerStore.getAt(0).get('languageId')); } }); me.callParent(arguments); }, /** * register the events */ registerEvents: function () { this.addEvents( 'changeSearchField' ) }, /** * creates the top toolbar items * * @returns [] */ createToolbarItems: function () { var me = this; me.customerSearchField = me.createCustomerSearch('customerName', 'id', 'email'); me.createCustomerButton = Ext.create('Ext.button.Button', { text: me.snippets.buttons.createCustomer, handler: function () { me.fireEvent('createCustomer', false); } }); me.createGuestButton = Ext.create('Ext.button.Button', { text: me.snippets.buttons.createGuest, handler: function () { me.fireEvent('createCustomer', true); } }); me.openCustomerButton = Ext.create('Ext.button.Button', { text: me.snippets.buttons.openCustomer, disabled: true, margin: '0 30 0 0', handler: function () { me.fireEvent('openCustomer'); } }); me.shopLabel = Ext.create('Ext.form.Label', { text: me.snippets.shop.noCustomer, style: { fontWeight: 'bold' } }); me.languageComboBox = Ext.create('Ext.form.field.ComboBox', { fieldLabel: me.snippets.languageLabel, labelWidth: 65, store: me.languageStore, queryMode: 'local', displayField: 'name', width: '20%', valueField: 'id', listeners: { change: { fn: function (comboBox, newValue, oldValue, eOpts) { me.fireEvent('changeLanguage', newValue); } } } }); me.changeCurrencyComboBox = Ext.create('Ext.form.field.ComboBox', { fieldLabel: me.snippets.currencyLabel, stores: me.currencyStore, queryMode: 'local', displayField: 'currency', width: '20%', valueField: 'id', listeners: { change: { fn: function (comboBox, newValue, oldValue, eOpts) { me.fireEvent('changeCurrency', comboBox, newValue, oldValue, eOpts); } } } }); return [ me.changeCurrencyComboBox, me.languageComboBox, me.shopLabel, '->', me.createCustomerButton, me.createGuestButton, me.openCustomerButton, me.customerSearchField ]; }, /** * * @param returnValue * @param hiddenReturnValue * @param name * @return Shopware.form.field.ArticleSearch */ createCustomerSearch: function (returnValue, hiddenReturnValue, name) { var me = this; me.customerStore = me.subApplication.getStore('Customer'); return Ext.create('Shopware.apps.SwagBackendOrder.view.main.CustomerSearch', { name: name, subApplication: me.subApplication, returnValue: returnValue, hiddenReturnValue: hiddenReturnValue, articleStore: me.customerStore, allowBlank: false, getValue: function () { me.store.getAt(me.record.rowIdx).set(name, this.getSearchField().getValue()); return this.getSearchField().getValue(); }, setValue: function (value) { this.getSearchField().setValue(value); } }); }, /** * @param mainShopId * @param languageId */ getLanguageShops: function (mainShopId, languageId) { var me = this; Ext.Ajax.request({ url: '{url action="getLanguageSubShops"}', params: { mainShopId: mainShopId }, success: function (response) { me.languageStore.removeAll(); var languageSubShops = Ext.JSON.decode(response.responseText); languageSubShops.data.forEach(function (record) { me.languageStore.add(record); }); me.languageComboBox.bindStore(me.languageStore); //selects the default language shop var languageIndex = me.languageStore.findExact('mainId', null); me.languageComboBox.setValue(languageId); } }); } }); // //{/block} //
GerDner/luck-docker
engine/Shopware/Plugins/Default/Backend/SwagBackendOrder/Views/backend/swag_backend_order/view/main/toolbar.js
JavaScript
agpl-3.0
8,411
/* uSquare 1.0 - Universal Responsive Grid Copyright (c) 2012 Br0 (shindiristudio.com) Project site: http://codecanyon.net/ Project demo: http://shindiristudio.com/usquare/ */ (function($) { function uSquareItem(element, options) { this.$item = $(element); this.$parent = options.$parent; this.options = options; this.$trigger = this.$(options.trigger); this.$close = this.$('.close'); this.$info = this.$(options.moreInfo); this.$trigger_text = this.$trigger.find('.usquare_square_text_wrapper'); this.$usquare_about = this.$info.find('.usquare_about'); this.$trigger.on('click', $.proxy(this.show, this)); this.$close.on('click', $.proxy(this.close, this)); options.$overlay.on('click', $.proxy(this.close, this)); }; uSquareItem.prototype = { show: function(e) { e.preventDefault(); if (!this.$parent.data('in_trans')) { if (!this.$item.data('showed')) { this.$parent.data('in_trans', 1); this.$item.data('showed', 1); if (this.options.before_item_opening_callback) this.options.before_item_opening_callback(this.$item); var item_position = this.$item.position(); var trigger_text_position; var this_backup=this; var moving=0; if (item_position.top>0) // && this.$parent.width()>=640) { var parent_position=this.$parent.offset(); var parent_top = parent_position.top; var non_visible_area=$(window).scrollTop()-parent_top; var going_to=item_position.top; if (non_visible_area>0) { var non_visible_row=Math.floor(non_visible_area/this.$item.height())+1; going_to=this.$item.height()*non_visible_row; going_to=item_position.top-going_to; } if (going_to>0) moving=1; if (moving) { this.$item.data('moved', going_to); var top_string='-'+going_to+'px'; var speed=this.options.opening_speed+(going_to/160)*100; this.$item.animate({top: top_string}, speed, this.options.easing, function(){ trigger_text_position = this_backup.$item.height() - this_backup.$trigger_text.height(); this_backup.$trigger_text.data('top', trigger_text_position); this_backup.$trigger_text.css('top', trigger_text_position); this_backup.$trigger_text.css('bottom', 'auto'); this_backup.$trigger_text.animate({'top': 0}, 'slow'); }); } } if (!moving) { trigger_text_position = this_backup.$item.height() - this_backup.$trigger_text.height(); this_backup.$trigger_text.data('top', trigger_text_position); this_backup.$trigger_text.css('top', trigger_text_position); this_backup.$trigger_text.css('bottom', 'auto'); this_backup.$trigger_text.animate({'top': 0}, 'slow'); } this.$item.addClass('usquare_block_selected'); var height_backup=this.$info.css('height'); this.$info.css('height', 0); this.$info.show(); this.$usquare_about.mCustomScrollbar("update"); if (this.options.before_info_rolling_callback) this.options.before_info_rolling_callback(this.$item); this.$info.animate({height:height_backup}, 'slow', this.options.easing, function() { this_backup.$parent.data('in_trans', 0); if (this_backup.options.after_info_rolling_callback) this_backup.options.after_info_rolling_callback(this_backup.$item); }); } } }, close: function(e) { e.preventDefault(); if (!this.$parent.data('in_trans')) { if (this.$item.data('showed')) { var this_backup=this; this.$info.hide(); var trigger_text_position_top = this_backup.$item.height() - this_backup.$trigger_text.height(); this_backup.$item.removeClass('usquare_block_selected'); if (this.$item.data('moved')) { var top_backup=this.$item.data('moved'); var speed=this.options.closing_speed+(top_backup/160)*100; this.$item.data('moved', 0); this.$item.animate({'top': 0}, speed, this.options.easing, function() { this_backup.$trigger_text.animate({'top': trigger_text_position_top}, 'slow'); }); } else { this_backup.$trigger_text.animate({'top': trigger_text_position_top}, 'slow'); } this.$item.data('showed', 0); } } }, $: function (selector) { return this.$item.find(selector); } }; function uSquare(element, options) { var self = this; this.options = $.extend({}, $.fn.uSquare.defaults, options); this.$element = $(element); this.$overlay = this.$('.usquare_module_shade'); this.$items = this.$(this.options.block); this.$triggers = this.$(this.options.trigger); this.$closes = this.$('.close'); this.$triggers.on('click', $.proxy(this.overlayShow, this)); this.$closes.on('click', $.proxy(this.overlayHide, this)); this.$overlay.on('click', $.proxy(this.overlayHide, this)); $.each( this.$items, function(i, element) { new uSquareItem(element, $.extend(self.options, {$overlay: self.$overlay, $parent: self.$element }) ); }); }; uSquare.prototype = { $: function (selector) { return this.$element.find(selector); }, overlayShow: function() { this.$overlay.fadeIn('slow', function(){ $(this).css({opacity : 0.5}); }) }, overlayHide: function() { if (!this.$element.data('in_trans')) { this.$overlay.fadeOut('slow'); } } }; $.fn.uSquare = function ( option ) { return this.each(function () { var $this = $(this), data = $this.data('tooltip'), options = typeof option == 'object' && option; data || $this.data('tooltip', (data = new uSquare(this, options))); (typeof option == 'string') && data[option](); }); }; $.fn.uSquare.Constructor = uSquare; $.fn.uSquare.defaults = { block: '.usquare_block', trigger: '.usquare_square', moreInfo: '.usquare_block_extended', opening_speed: 300, closing_speed: 500, easing: 'swing', before_item_opening_callback: null, before_info_rolling_callback: null, after_info_rolling_callback: null }; })(jQuery); $(window).load(function() { $(".usquare_about").mCustomScrollbar(); });
AhoraMadrid/ahoramadrid.org
js/vendor/jquery.usquare.js
JavaScript
agpl-3.0
6,490
var searchData= [ ['backtrace',['backtrace',['../class_logger.html#a5deb9b10c43285287a9113f280ee8fab',1,'Logger']]], ['baseexception',['BaseException',['../class_base_exception.html',1,'']]], ['baseexception_2ephp',['BaseException.php',['../_base_exception_8php.html',1,'']]], ['basic_2ephp',['Basic.php',['../_menu_2_basic_8php.html',1,'']]], ['basic_2ephp',['Basic.php',['../_paginator_2_basic_8php.html',1,'']]], ['basic_2ephp',['Basic.php',['../_auth_2_basic_8php.html',1,'']]], ['basic_2ephp',['Basic.php',['../_t_mail_2_basic_8php.html',1,'']]], ['basic_2ephp',['Basic.php',['../_form_2_basic_8php.html',1,'']]], ['basic_2ephp',['Basic.php',['../_grid_2_basic_8php.html',1,'']]], ['basicauth',['BasicAuth',['../class_basic_auth.html',1,'']]], ['basicauth_2ephp',['BasicAuth.php',['../_basic_auth_8php.html',1,'']]], ['beforedelete',['beforeDelete',['../class_s_q_l___relation.html#a44c9d7a3b22619b53d4f49f1070d5235',1,'SQL_Relation']]], ['beforefield',['beforeField',['../class_form___field.html#aa4bbfb40048e1c3fe939621179652be1',1,'Form_Field']]], ['beforeinsert',['beforeInsert',['../class_s_q_l___relation.html#ada6a7f2abf3ba1c19e4ba3711da1a61e',1,'SQL_Relation']]], ['beforeload',['beforeLoad',['../class_s_q_l___relation.html#a665492752f54f9cbc3fd2cae51ca4373',1,'SQL_Relation']]], ['beforemodify',['beforeModify',['../class_s_q_l___relation.html#a3ad587772d12f99af11a3db64d879210',1,'SQL_Relation']]], ['beforesave',['beforeSave',['../class_s_q_l___relation.html#ab9e4fb36c177d9633b81fc184f7bd933',1,'SQL_Relation']]], ['begintransaction',['beginTransaction',['../class_d_b.html#af3380f3b13931d581fa973a382946b32',1,'DB\beginTransaction()'],['../class_d_blite__mysql.html#a06fdc3063ff49b8de811683aae3483e6',1,'DBlite_mysql\beginTransaction()']]], ['belowfield',['belowField',['../class_form___field.html#a27cd7c6e75ed8c09aae8af32905a888d',1,'Form_Field']]], ['box_2ephp',['Box.php',['../_box_8php.html',1,'']]], ['breakhook',['breakHook',['../class_abstract_object.html#a446b3f8327b3272c838ae46f40a9da06',1,'AbstractObject']]], ['bt',['bt',['../class_d_b__dsql.html#aa374d1bfaabf3f546fe8862d09f4a096',1,'DB_dsql']]], ['button',['Button',['../class_button.html',1,'']]], ['button_2ephp',['Button.php',['../_button_8php.html',1,'']]], ['button_2ephp',['Button.php',['../_form_2_button_8php.html',1,'']]], ['button_2ephp',['Button.php',['../_view_2_button_8php.html',1,'']]], ['buttonset',['ButtonSet',['../class_button_set.html',1,'']]], ['buttonset_2ephp',['ButtonSet.php',['../_button_set_8php.html',1,'']]], ['buttonset_2ephp',['ButtonSet.php',['../_view_2_button_set_8php.html',1,'']]] ];
atk4/atk4-web
dox/html/search/all_62.js
JavaScript
agpl-3.0
2,662
ace.define("ace/mode/jsx", ["require", "exports", "module", "ace/lib/oop", "ace/mode/text", "ace/tokenizer", "ace/mode/jsx_highlight_rules", "ace/mode/matching_brace_outdent", "ace/mode/behaviour/cstyle", "ace/mode/folding/cstyle"], function (e, t, n) { function l() { this.HighlightRules = o, this.$outdent = new u, this.$behaviour = new a, this.foldingRules = new f } var r = e("../lib/oop"), i = e("./text").Mode, s = e("../tokenizer").Tokenizer, o = e("./jsx_highlight_rules").JsxHighlightRules, u = e("./matching_brace_outdent").MatchingBraceOutdent, a = e("./behaviour/cstyle").CstyleBehaviour, f = e("./folding/cstyle").FoldMode; r.inherits(l, i), function () { this.lineCommentStart = "//", this.blockComment = {start: "/*", end: "*/"}, this.getNextLineIndent = function (e, t, n) { var r = this.$getIndent(t), i = this.getTokenizer().getLineTokens(t, e), s = i.tokens; if (s.length && s[s.length - 1].type == "comment")return r; if (e == "start") { var o = t.match(/^.*[\{\(\[]\s*$/); o && (r += n) } return r }, this.checkOutdent = function (e, t, n) { return this.$outdent.checkOutdent(t, n) }, this.autoOutdent = function (e, t, n) { this.$outdent.autoOutdent(t, n) }, this.$id = "ace/mode/jsx" }.call(l.prototype), t.Mode = l }), ace.define("ace/mode/jsx_highlight_rules", ["require", "exports", "module", "ace/lib/oop", "ace/lib/lang", "ace/mode/doc_comment_highlight_rules", "ace/mode/text_highlight_rules"], function (e, t, n) { var r = e("../lib/oop"), i = e("../lib/lang"), s = e("./doc_comment_highlight_rules").DocCommentHighlightRules, o = e("./text_highlight_rules").TextHighlightRules, u = function () { var e = i.arrayToMap("break|do|instanceof|typeof|case|else|new|var|catch|finally|return|void|continue|for|switch|default|while|function|this|if|throw|delete|in|try|class|extends|super|import|from|into|implements|interface|static|mixin|override|abstract|final|number|int|string|boolean|variant|log|assert".split("|")), t = i.arrayToMap("null|true|false|NaN|Infinity|__FILE__|__LINE__|undefined".split("|")), n = i.arrayToMap("debugger|with|const|export|let|private|public|yield|protected|extern|native|as|operator|__fake__|__readonly__".split("|")), r = "[a-zA-Z_][a-zA-Z0-9_]*\\b"; this.$rules = {start: [ {token: "comment", regex: "\\/\\/.*$"}, s.getStartRule("doc-start"), {token: "comment", regex: "\\/\\*", next: "comment"}, {token: "string.regexp", regex: "[/](?:(?:\\[(?:\\\\]|[^\\]])+\\])|(?:\\\\/|[^\\]/]))*[/]\\w*\\s*(?=[).,;]|$)"}, {token: "string", regex: '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]'}, {token: "string", regex: "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']"}, {token: "constant.numeric", regex: "0[xX][0-9a-fA-F]+\\b"}, {token: "constant.numeric", regex: "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b"}, {token: "constant.language.boolean", regex: "(?:true|false)\\b"}, {token: ["storage.type", "text", "entity.name.function"], regex: "(function)(\\s+)(" + r + ")"}, {token: function (r) { return r == "this" ? "variable.language" : r == "function" ? "storage.type" : e.hasOwnProperty(r) || n.hasOwnProperty(r) ? "keyword" : t.hasOwnProperty(r) ? "constant.language" : /^_?[A-Z][a-zA-Z0-9_]*$/.test(r) ? "language.support.class" : "identifier" }, regex: r}, {token: "keyword.operator", regex: "!|%|&|\\*|\\-\\-|\\-|\\+\\+|\\+|~|==|=|!=|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\\|\\||\\?\\:|\\*=|%=|\\+=|\\-=|&=|\\^=|\\b(?:in|instanceof|new|delete|typeof|void)"}, {token: "punctuation.operator", regex: "\\?|\\:|\\,|\\;|\\."}, {token: "paren.lparen", regex: "[[({<]"}, {token: "paren.rparen", regex: "[\\])}>]"}, {token: "text", regex: "\\s+"} ], comment: [ {token: "comment", regex: ".*?\\*\\/", next: "start"}, {token: "comment", regex: ".+"} ]}, this.embedRules(s, "doc-", [s.getEndRule("start")]) }; r.inherits(u, o), t.JsxHighlightRules = u }), ace.define("ace/mode/doc_comment_highlight_rules", ["require", "exports", "module", "ace/lib/oop", "ace/mode/text_highlight_rules"], function (e, t, n) { var r = e("../lib/oop"), i = e("./text_highlight_rules").TextHighlightRules, s = function () { this.$rules = {start: [ {token: "comment.doc.tag", regex: "@[\\w\\d_]+"}, {token: "comment.doc.tag", regex: "\\bTODO\\b"}, {defaultToken: "comment.doc"} ]} }; r.inherits(s, i), s.getStartRule = function (e) { return{token: "comment.doc", regex: "\\/\\*(?=\\*)", next: e} }, s.getEndRule = function (e) { return{token: "comment.doc", regex: "\\*\\/", next: e} }, t.DocCommentHighlightRules = s }), ace.define("ace/mode/matching_brace_outdent", ["require", "exports", "module", "ace/range"], function (e, t, n) { var r = e("../range").Range, i = function () { }; (function () { this.checkOutdent = function (e, t) { return/^\s+$/.test(e) ? /^\s*\}/.test(t) : !1 }, this.autoOutdent = function (e, t) { var n = e.getLine(t), i = n.match(/^(\s*\})/); if (!i)return 0; var s = i[1].length, o = e.findMatchingBracket({row: t, column: s}); if (!o || o.row == t)return 0; var u = this.$getIndent(e.getLine(o.row)); e.replace(new r(t, 0, t, s - 1), u) }, this.$getIndent = function (e) { return e.match(/^\s*/)[0] } }).call(i.prototype), t.MatchingBraceOutdent = i }), ace.define("ace/mode/behaviour/cstyle", ["require", "exports", "module", "ace/lib/oop", "ace/mode/behaviour", "ace/token_iterator", "ace/lib/lang"], function (e, t, n) { var r = e("../../lib/oop"), i = e("../behaviour").Behaviour, s = e("../../token_iterator").TokenIterator, o = e("../../lib/lang"), u = ["text", "paren.rparen", "punctuation.operator"], a = ["text", "paren.rparen", "punctuation.operator", "comment"], f, l = {}, c = function (e) { var t = -1; e.multiSelect && (t = e.selection.id, l.rangeCount != e.multiSelect.rangeCount && (l = {rangeCount: e.multiSelect.rangeCount})); if (l[t])return f = l[t]; f = l[t] = {autoInsertedBrackets: 0, autoInsertedRow: -1, autoInsertedLineEnd: "", maybeInsertedBrackets: 0, maybeInsertedRow: -1, maybeInsertedLineStart: "", maybeInsertedLineEnd: ""} }, h = function () { this.add("braces", "insertion", function (e, t, n, r, i) { var s = n.getCursorPosition(), u = r.doc.getLine(s.row); if (i == "{") { c(n); var a = n.getSelectionRange(), l = r.doc.getTextRange(a); if (l !== "" && l !== "{" && n.getWrapBehavioursEnabled())return{text: "{" + l + "}", selection: !1}; if (h.isSaneInsertion(n, r))return/[\]\}\)]/.test(u[s.column]) || n.inMultiSelectMode ? (h.recordAutoInsert(n, r, "}"), {text: "{}", selection: [1, 1]}) : (h.recordMaybeInsert(n, r, "{"), {text: "{", selection: [1, 1]}) } else if (i == "}") { c(n); var p = u.substring(s.column, s.column + 1); if (p == "}") { var d = r.$findOpeningBracket("}", {column: s.column + 1, row: s.row}); if (d !== null && h.isAutoInsertedClosing(s, u, i))return h.popAutoInsertedClosing(), {text: "", selection: [1, 1]} } } else { if (i == "\n" || i == "\r\n") { c(n); var v = ""; h.isMaybeInsertedClosing(s, u) && (v = o.stringRepeat("}", f.maybeInsertedBrackets), h.clearMaybeInsertedClosing()); var p = u.substring(s.column, s.column + 1); if (p === "}") { var m = r.findMatchingBracket({row: s.row, column: s.column + 1}, "}"); if (!m)return null; var g = this.$getIndent(r.getLine(m.row)) } else { if (!v) { h.clearMaybeInsertedClosing(); return } var g = this.$getIndent(u) } var y = g + r.getTabString(); return{text: "\n" + y + "\n" + g + v, selection: [1, y.length, 1, y.length]} } h.clearMaybeInsertedClosing() } }), this.add("braces", "deletion", function (e, t, n, r, i) { var s = r.doc.getTextRange(i); if (!i.isMultiLine() && s == "{") { c(n); var o = r.doc.getLine(i.start.row), u = o.substring(i.end.column, i.end.column + 1); if (u == "}")return i.end.column++, i; f.maybeInsertedBrackets-- } }), this.add("parens", "insertion", function (e, t, n, r, i) { if (i == "(") { c(n); var s = n.getSelectionRange(), o = r.doc.getTextRange(s); if (o !== "" && n.getWrapBehavioursEnabled())return{text: "(" + o + ")", selection: !1}; if (h.isSaneInsertion(n, r))return h.recordAutoInsert(n, r, ")"), {text: "()", selection: [1, 1]} } else if (i == ")") { c(n); var u = n.getCursorPosition(), a = r.doc.getLine(u.row), f = a.substring(u.column, u.column + 1); if (f == ")") { var l = r.$findOpeningBracket(")", {column: u.column + 1, row: u.row}); if (l !== null && h.isAutoInsertedClosing(u, a, i))return h.popAutoInsertedClosing(), {text: "", selection: [1, 1]} } } }), this.add("parens", "deletion", function (e, t, n, r, i) { var s = r.doc.getTextRange(i); if (!i.isMultiLine() && s == "(") { c(n); var o = r.doc.getLine(i.start.row), u = o.substring(i.start.column + 1, i.start.column + 2); if (u == ")")return i.end.column++, i } }), this.add("brackets", "insertion", function (e, t, n, r, i) { if (i == "[") { c(n); var s = n.getSelectionRange(), o = r.doc.getTextRange(s); if (o !== "" && n.getWrapBehavioursEnabled())return{text: "[" + o + "]", selection: !1}; if (h.isSaneInsertion(n, r))return h.recordAutoInsert(n, r, "]"), {text: "[]", selection: [1, 1]} } else if (i == "]") { c(n); var u = n.getCursorPosition(), a = r.doc.getLine(u.row), f = a.substring(u.column, u.column + 1); if (f == "]") { var l = r.$findOpeningBracket("]", {column: u.column + 1, row: u.row}); if (l !== null && h.isAutoInsertedClosing(u, a, i))return h.popAutoInsertedClosing(), {text: "", selection: [1, 1]} } } }), this.add("brackets", "deletion", function (e, t, n, r, i) { var s = r.doc.getTextRange(i); if (!i.isMultiLine() && s == "[") { c(n); var o = r.doc.getLine(i.start.row), u = o.substring(i.start.column + 1, i.start.column + 2); if (u == "]")return i.end.column++, i } }), this.add("string_dquotes", "insertion", function (e, t, n, r, i) { if (i == '"' || i == "'") { c(n); var s = i, o = n.getSelectionRange(), u = r.doc.getTextRange(o); if (u !== "" && u !== "'" && u != '"' && n.getWrapBehavioursEnabled())return{text: s + u + s, selection: !1}; var a = n.getCursorPosition(), f = r.doc.getLine(a.row), l = f.substring(a.column - 1, a.column); if (l == "\\")return null; var p = r.getTokens(o.start.row), d = 0, v, m = -1; for (var g = 0; g < p.length; g++) { v = p[g], v.type == "string" ? m = -1 : m < 0 && (m = v.value.indexOf(s)); if (v.value.length + d > o.start.column)break; d += p[g].value.length } if (!v || m < 0 && v.type !== "comment" && (v.type !== "string" || o.start.column !== v.value.length + d - 1 && v.value.lastIndexOf(s) === v.value.length - 1)) { if (!h.isSaneInsertion(n, r))return; return{text: s + s, selection: [1, 1]} } if (v && v.type === "string") { var y = f.substring(a.column, a.column + 1); if (y == s)return{text: "", selection: [1, 1]} } } }), this.add("string_dquotes", "deletion", function (e, t, n, r, i) { var s = r.doc.getTextRange(i); if (!i.isMultiLine() && (s == '"' || s == "'")) { c(n); var o = r.doc.getLine(i.start.row), u = o.substring(i.start.column + 1, i.start.column + 2); if (u == s)return i.end.column++, i } }) }; h.isSaneInsertion = function (e, t) { var n = e.getCursorPosition(), r = new s(t, n.row, n.column); if (!this.$matchTokenType(r.getCurrentToken() || "text", u)) { var i = new s(t, n.row, n.column + 1); if (!this.$matchTokenType(i.getCurrentToken() || "text", u))return!1 } return r.stepForward(), r.getCurrentTokenRow() !== n.row || this.$matchTokenType(r.getCurrentToken() || "text", a) }, h.$matchTokenType = function (e, t) { return t.indexOf(e.type || e) > -1 }, h.recordAutoInsert = function (e, t, n) { var r = e.getCursorPosition(), i = t.doc.getLine(r.row); this.isAutoInsertedClosing(r, i, f.autoInsertedLineEnd[0]) || (f.autoInsertedBrackets = 0), f.autoInsertedRow = r.row, f.autoInsertedLineEnd = n + i.substr(r.column), f.autoInsertedBrackets++ }, h.recordMaybeInsert = function (e, t, n) { var r = e.getCursorPosition(), i = t.doc.getLine(r.row); this.isMaybeInsertedClosing(r, i) || (f.maybeInsertedBrackets = 0), f.maybeInsertedRow = r.row, f.maybeInsertedLineStart = i.substr(0, r.column) + n, f.maybeInsertedLineEnd = i.substr(r.column), f.maybeInsertedBrackets++ }, h.isAutoInsertedClosing = function (e, t, n) { return f.autoInsertedBrackets > 0 && e.row === f.autoInsertedRow && n === f.autoInsertedLineEnd[0] && t.substr(e.column) === f.autoInsertedLineEnd }, h.isMaybeInsertedClosing = function (e, t) { return f.maybeInsertedBrackets > 0 && e.row === f.maybeInsertedRow && t.substr(e.column) === f.maybeInsertedLineEnd && t.substr(0, e.column) == f.maybeInsertedLineStart }, h.popAutoInsertedClosing = function () { f.autoInsertedLineEnd = f.autoInsertedLineEnd.substr(1), f.autoInsertedBrackets-- }, h.clearMaybeInsertedClosing = function () { f && (f.maybeInsertedBrackets = 0, f.maybeInsertedRow = -1) }, r.inherits(h, i), t.CstyleBehaviour = h }), ace.define("ace/mode/folding/cstyle", ["require", "exports", "module", "ace/lib/oop", "ace/range", "ace/mode/folding/fold_mode"], function (e, t, n) { var r = e("../../lib/oop"), i = e("../../range").Range, s = e("./fold_mode").FoldMode, o = t.FoldMode = function (e) { e && (this.foldingStartMarker = new RegExp(this.foldingStartMarker.source.replace(/\|[^|]*?$/, "|" + e.start)), this.foldingStopMarker = new RegExp(this.foldingStopMarker.source.replace(/\|[^|]*?$/, "|" + e.end))) }; r.inherits(o, s), function () { this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/, this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/, this.getFoldWidgetRange = function (e, t, n, r) { var i = e.getLine(n), s = i.match(this.foldingStartMarker); if (s) { var o = s.index; if (s[1])return this.openingBracketBlock(e, s[1], n, o); var u = e.getCommentFoldRange(n, o + s[0].length, 1); return u && !u.isMultiLine() && (r ? u = this.getSectionRange(e, n) : t != "all" && (u = null)), u } if (t === "markbegin")return; var s = i.match(this.foldingStopMarker); if (s) { var o = s.index + s[0].length; return s[1] ? this.closingBracketBlock(e, s[1], n, o) : e.getCommentFoldRange(n, o, -1) } }, this.getSectionRange = function (e, t) { var n = e.getLine(t), r = n.search(/\S/), s = t, o = n.length; t += 1; var u = t, a = e.getLength(); while (++t < a) { n = e.getLine(t); var f = n.search(/\S/); if (f === -1)continue; if (r > f)break; var l = this.getFoldWidgetRange(e, "all", t); if (l) { if (l.start.row <= s)break; if (l.isMultiLine())t = l.end.row; else if (r == f)break } u = t } return new i(s, o, u, e.getLine(u).length) } }.call(o.prototype) })
ahammer/MySaasa
server/src/main/webapp/ace/src-min-noconflict/mode-jsx.js
JavaScript
agpl-3.0
17,411
import React from 'react'; import PropTypes from 'prop-types'; import ManaUsageGraph from './ManaUsageGraph'; class HealingDoneGraph extends React.PureComponent { static propTypes = { start: PropTypes.number.isRequired, end: PropTypes.number.isRequired, offset: PropTypes.number.isRequired, healingBySecond: PropTypes.object.isRequired, manaUpdates: PropTypes.array.isRequired, }; groupHealingBySeconds(healingBySecond, interval) { return Object.keys(healingBySecond) .reduce((obj, second) => { const healing = healingBySecond[second]; const index = Math.floor(second / interval); if (obj[index]) { obj[index] = obj[index].add(healing.regular, healing.absorbed, healing.overheal); } else { obj[index] = healing; } return obj; }, {}); } render() { const { start, end, offset, healingBySecond, manaUpdates } = this.props; // TODO: move this to vega-lite window transform // e.g. { window: [{op: 'mean', field: 'hps', as: 'hps'}], frame: [-2, 2] } const interval = 5; const healingPerFrame = this.groupHealingBySeconds(healingBySecond, interval); let max = 0; Object.keys(healingPerFrame) .map(k => healingPerFrame[k]) .forEach((healingDone) => { const current = healingDone.effective; if (current > max) { max = current; } }); max /= interval; const manaUsagePerFrame = { 0: 0, }; const manaLevelPerFrame = { 0: 1, }; manaUpdates.forEach((item) => { const frame = Math.floor((item.timestamp - start) / 1000 / interval); manaUsagePerFrame[frame] = (manaUsagePerFrame[frame] || 0) + item.used / item.max; manaLevelPerFrame[frame] = item.current / item.max; // use the lowest value of the frame; likely to be more accurate }); const fightDurationSec = Math.ceil((end - start) / 1000); const labels = []; for (let i = 0; i <= fightDurationSec / interval; i += 1) { labels.push(Math.ceil(offset/1000) + i * interval); healingPerFrame[i] = healingPerFrame[i] !== undefined ? healingPerFrame[i].effective : 0; manaUsagePerFrame[i] = manaUsagePerFrame[i] !== undefined ? manaUsagePerFrame[i] : 0; manaLevelPerFrame[i] = manaLevelPerFrame[i] !== undefined ? manaLevelPerFrame[i] : null; } let lastKnown = null; const mana = Object.values(manaLevelPerFrame).map((value, i) => { if (value !== null) { lastKnown = value; } return { x: labels[i], y: lastKnown * max, }; }); const healing = Object.values(healingPerFrame).map((value, i) => ({ x: labels[i], y: value / interval })); const manaUsed = Object.values(manaUsagePerFrame).map((value, i) => ({ x: labels[i], y: value * max })); return ( <div className="graph-container" style={{ marginBottom: 20 }}> <ManaUsageGraph mana={mana} healing={healing} manaUsed={manaUsed} /> </div> ); } } export default HealingDoneGraph;
yajinni/WoWAnalyzer
src/parser/shared/modules/resources/mana/ManaUsageChartComponent.js
JavaScript
agpl-3.0
3,101
odoo.define('web_editor.field_html_tests', function (require) { "use strict"; var ajax = require('web.ajax'); var FormView = require('web.FormView'); var testUtils = require('web.test_utils'); var weTestUtils = require('web_editor.test_utils'); var core = require('web.core'); var Wysiwyg = require('web_editor.wysiwyg'); var MediaDialog = require('wysiwyg.widgets.MediaDialog'); var _t = core._t; QUnit.module('web_editor', {}, function () { QUnit.module('field html', { beforeEach: function () { this.data = weTestUtils.wysiwygData({ 'note.note': { fields: { display_name: { string: "Displayed name", type: "char" }, header: { string: "Header", type: "html", required: true, }, body: { string: "Message", type: "html" }, }, records: [{ id: 1, display_name: "first record", header: "<p> &nbsp;&nbsp; <br> </p>", body: "<p>toto toto toto</p><p>tata</p>", }], }, 'mass.mailing': { fields: { display_name: { string: "Displayed name", type: "char" }, body_html: { string: "Message Body inline (to send)", type: "html" }, body_arch: { string: "Message Body for edition", type: "html" }, }, records: [{ id: 1, display_name: "first record", body_html: "<div class='field_body' style='background-color: red;'>yep</div>", body_arch: "<div class='field_body'>yep</div>", }], }, "ir.translation": { fields: { lang_code: {type: "char"}, value: {type: "char"}, res_id: {type: "integer"} }, records: [{ id: 99, res_id: 12, value: '', lang_code: 'en_US' }] }, }); testUtils.mock.patch(ajax, { loadAsset: function (xmlId) { if (xmlId === 'template.assets') { return Promise.resolve({ cssLibs: [], cssContents: ['body {background-color: red;}'] }); } if (xmlId === 'template.assets_all_style') { return Promise.resolve({ cssLibs: $('link[href]:not([type="image/x-icon"])').map(function () { return $(this).attr('href'); }).get(), cssContents: ['body {background-color: red;}'] }); } throw 'Wrong template'; }, }); }, afterEach: function () { testUtils.mock.unpatch(ajax); }, }, function () { QUnit.module('basic'); QUnit.test('simple rendering', async function (assert) { assert.expect(3); var form = await testUtils.createView({ View: FormView, model: 'note.note', data: this.data, arch: '<form>' + '<field name="body" widget="html" style="height: 100px"/>' + '</form>', res_id: 1, }); var $field = form.$('.oe_form_field[name="body"]'); assert.strictEqual($field.children('.o_readonly').html(), '<p>toto toto toto</p><p>tata</p>', "should have rendered a div with correct content in readonly"); assert.strictEqual($field.attr('style'), 'height: 100px', "should have applied the style correctly"); await testUtils.form.clickEdit(form); await testUtils.nextTick(); $field = form.$('.oe_form_field[name="body"]'); assert.strictEqual($field.find('.note-editable').html(), '<p>toto toto toto</p><p>tata</p>', "should have rendered the field correctly in edit"); form.destroy(); }); QUnit.test('check if required field is set', async function (assert) { assert.expect(1); var form = await testUtils.createView({ View: FormView, model: 'note.note', data: this.data, arch: '<form>' + '<field name="header" widget="html" style="height: 100px" />' + '</form>', res_id: 1, }); testUtils.mock.intercept(form, 'call_service', function (ev) { if (ev.data.service === 'notification') { assert.deepEqual(ev.data.args[0], { "className": undefined, "message": "<ul><li>Header</li></ul>", "sticky": undefined, "title": "Invalid fields:", "type": "danger" }); } }, true); await testUtils.form.clickEdit(form); await testUtils.nextTick(); await testUtils.dom.click(form.$('.o_form_button_save')); form.destroy(); }); QUnit.test('colorpicker', async function (assert) { assert.expect(6); var form = await testUtils.createView({ View: FormView, model: 'note.note', data: this.data, arch: '<form>' + '<field name="body" widget="html" style="height: 100px"/>' + '</form>', res_id: 1, }); // Summernote needs a RootWidget to set as parent of the ColorPaletteWidget. In the // tests, there is no RootWidget, so we set it here to the parent of the form view, which // can act as RootWidget, as it will honor rpc requests correctly (to the MockServer). const rootWidget = odoo.__DEBUG__.services['root.widget']; odoo.__DEBUG__.services['root.widget'] = form.getParent(); await testUtils.form.clickEdit(form); var $field = form.$('.oe_form_field[name="body"]'); // select the text var pText = $field.find('.note-editable p').first().contents()[0]; Wysiwyg.setRange(pText, 1, pText, 10); // text is selected var range = Wysiwyg.getRange($field[0]); assert.strictEqual(range.sc, pText, "should select the text"); async function openColorpicker(selector) { const $colorpicker = $field.find(selector); const openingProm = new Promise(resolve => { $colorpicker.one('shown.bs.dropdown', () => resolve()); }); await testUtils.dom.click($colorpicker.find('button:first')); return openingProm; } await openColorpicker('.note-toolbar .note-back-color-preview'); assert.ok($field.find('.note-back-color-preview').hasClass('show'), "should display the color picker"); await testUtils.dom.click($field.find('.note-toolbar .note-back-color-preview .o_we_color_btn[style="background-color:#00FFFF;"]')); assert.ok(!$field.find('.note-back-color-preview').hasClass('show'), "should close the color picker"); assert.strictEqual($field.find('.note-editable').html(), '<p>t<font style="background-color: rgb(0, 255, 255);">oto toto&nbsp;</font>toto</p><p>tata</p>', "should have rendered the field correctly in edit"); var fontContent = $field.find('.note-editable font').contents()[0]; var rangeControl = { sc: fontContent, so: 0, ec: fontContent, eo: fontContent.length, }; range = Wysiwyg.getRange($field[0]); assert.deepEqual(_.pick(range, 'sc', 'so', 'ec', 'eo'), rangeControl, "should select the text after color change"); // select the text pText = $field.find('.note-editable p').first().contents()[2]; Wysiwyg.setRange(fontContent, 5, pText, 2); // text is selected await openColorpicker('.note-toolbar .note-back-color-preview'); await testUtils.dom.click($field.find('.note-toolbar .note-back-color-preview .o_we_color_btn.bg-o-color-3')); assert.strictEqual($field.find('.note-editable').html(), '<p>t<font style="background-color: rgb(0, 255, 255);">oto t</font><font style="" class="bg-o-color-3">oto&nbsp;</font><font class="bg-o-color-3" style="">to</font>to</p><p>tata</p>', "should have rendered the field correctly in edit"); odoo.__DEBUG__.services['root.widget'] = rootWidget; form.destroy(); }); QUnit.test('media dialog: image', async function (assert) { assert.expect(1); var form = await testUtils.createView({ View: FormView, model: 'note.note', data: this.data, arch: '<form>' + '<field name="body" widget="html" style="height: 100px"/>' + '</form>', res_id: 1, mockRPC: function (route, args) { if (args.model === 'ir.attachment') { if (args.method === "generate_access_token") { return Promise.resolve(); } } if (route.indexOf('/web/image/123/transparent.png') === 0) { return Promise.resolve(); } if (route.indexOf('/web_unsplash/fetch_images') === 0) { return Promise.resolve(); } if (route.indexOf('/web_editor/media_library_search') === 0) { return Promise.resolve(); } return this._super(route, args); }, }); await testUtils.form.clickEdit(form); var $field = form.$('.oe_form_field[name="body"]'); // the dialog load some xml assets var defMediaDialog = testUtils.makeTestPromise(); testUtils.mock.patch(MediaDialog, { init: function () { this._super.apply(this, arguments); this.opened(defMediaDialog.resolve.bind(defMediaDialog)); } }); var pText = $field.find('.note-editable p').first().contents()[0]; Wysiwyg.setRange(pText, 1); await testUtils.dom.click($field.find('.note-toolbar .note-insert button:has(.fa-file-image-o)')); // load static xml file (dialog, media dialog, unsplash image widget) await defMediaDialog; await testUtils.dom.click($('.modal #editor-media-image .o_existing_attachment_cell:first').removeClass('d-none')); var $editable = form.$('.oe_form_field[name="body"] .note-editable'); assert.ok($editable.find('img')[0].dataset.src.includes('/web/image/123/transparent.png'), "should have the image in the dom"); testUtils.mock.unpatch(MediaDialog); form.destroy(); }); QUnit.test('media dialog: icon', async function (assert) { assert.expect(1); var form = await testUtils.createView({ View: FormView, model: 'note.note', data: this.data, arch: '<form>' + '<field name="body" widget="html" style="height: 100px"/>' + '</form>', res_id: 1, mockRPC: function (route, args) { if (args.model === 'ir.attachment') { return Promise.resolve([]); } if (route.indexOf('/web_unsplash/fetch_images') === 0) { return Promise.resolve(); } return this._super(route, args); }, }); await testUtils.form.clickEdit(form); var $field = form.$('.oe_form_field[name="body"]'); // the dialog load some xml assets var defMediaDialog = testUtils.makeTestPromise(); testUtils.mock.patch(MediaDialog, { init: function () { this._super.apply(this, arguments); this.opened(defMediaDialog.resolve.bind(defMediaDialog)); } }); var pText = $field.find('.note-editable p').first().contents()[0]; Wysiwyg.setRange(pText, 1); await testUtils.dom.click($field.find('.note-toolbar .note-insert button:has(.fa-file-image-o)')); // load static xml file (dialog, media dialog, unsplash image widget) await defMediaDialog; $('.modal .tab-content .tab-pane').removeClass('fade'); // to be sync in test await testUtils.dom.click($('.modal a[aria-controls="editor-media-icon"]')); await testUtils.dom.click($('.modal #editor-media-icon .font-icons-icon.fa-glass')); var $editable = form.$('.oe_form_field[name="body"] .note-editable'); assert.strictEqual($editable.data('wysiwyg').getValue(), '<p>t<span class="fa fa-glass"></span>oto toto toto</p><p>tata</p>', "should have the image in the dom"); testUtils.mock.unpatch(MediaDialog); form.destroy(); }); QUnit.test('save', async function (assert) { assert.expect(1); var form = await testUtils.createView({ View: FormView, model: 'note.note', data: this.data, arch: '<form>' + '<field name="body" widget="html" style="height: 100px"/>' + '</form>', res_id: 1, mockRPC: function (route, args) { if (args.method === "write") { assert.strictEqual(args.args[1].body, '<p>t<font class="bg-o-color-3">oto toto&nbsp;</font>toto</p><p>tata</p>', "should save the content"); } return this._super.apply(this, arguments); }, }); await testUtils.form.clickEdit(form); var $field = form.$('.oe_form_field[name="body"]'); // select the text var pText = $field.find('.note-editable p').first().contents()[0]; Wysiwyg.setRange(pText, 1, pText, 10); // text is selected async function openColorpicker(selector) { const $colorpicker = $field.find(selector); const openingProm = new Promise(resolve => { $colorpicker.one('shown.bs.dropdown', () => resolve()); }); await testUtils.dom.click($colorpicker.find('button:first')); return openingProm; } await openColorpicker('.note-toolbar .note-back-color-preview'); await testUtils.dom.click($field.find('.note-toolbar .note-back-color-preview .o_we_color_btn.bg-o-color-3')); await testUtils.form.clickSave(form); form.destroy(); }); QUnit.module('cssReadonly'); QUnit.test('rendering with iframe for readonly mode', async function (assert) { assert.expect(3); var form = await testUtils.createView({ View: FormView, model: 'note.note', data: this.data, arch: '<form>' + '<field name="body" widget="html" style="height: 100px" options="{\'cssReadonly\': \'template.assets\'}"/>' + '</form>', res_id: 1, }); var $field = form.$('.oe_form_field[name="body"]'); var $iframe = $field.find('iframe.o_readonly'); await $iframe.data('loadDef'); var doc = $iframe.contents()[0]; assert.strictEqual($(doc).find('#iframe_target').html(), '<p>toto toto toto</p><p>tata</p>', "should have rendered a div with correct content in readonly"); assert.strictEqual(doc.defaultView.getComputedStyle(doc.body).backgroundColor, 'rgb(255, 0, 0)', "should load the asset css"); await testUtils.form.clickEdit(form); $field = form.$('.oe_form_field[name="body"]'); assert.strictEqual($field.find('.note-editable').html(), '<p>toto toto toto</p><p>tata</p>', "should have rendered the field correctly in edit"); form.destroy(); }); QUnit.module('translation'); QUnit.test('field html translatable', async function (assert) { assert.expect(4); var multiLang = _t.database.multi_lang; _t.database.multi_lang = true; this.data['note.note'].fields.body.translate = true; var form = await testUtils.createView({ View: FormView, model: 'note.note', data: this.data, arch: '<form string="Partners">' + '<field name="body" widget="html"/>' + '</form>', res_id: 1, mockRPC: function (route, args) { if (route === '/web/dataset/call_button' && args.method === 'translate_fields') { assert.deepEqual(args.args, ['note.note', 1, 'body'], "should call 'call_button' route"); return Promise.resolve({ domain: [], context: {search_default_name: 'partnes,foo'}, }); } if (route === "/web/dataset/call_kw/res.lang/get_installed") { return Promise.resolve([["en_US"], ["fr_BE"]]); } return this._super.apply(this, arguments); }, }); assert.strictEqual(form.$('.oe_form_field_html .o_field_translate').length, 0, "should not have a translate button in readonly mode"); await testUtils.form.clickEdit(form); var $button = form.$('.oe_form_field_html .o_field_translate'); assert.strictEqual($button.length, 1, "should have a translate button"); await testUtils.dom.click($button); assert.containsOnce($(document), '.o_translation_dialog', 'should have a modal to translate'); form.destroy(); _t.database.multi_lang = multiLang; }); }); }); });
rven/odoo
addons/web_editor/static/tests/field_html_tests.js
JavaScript
agpl-3.0
20,217
"use strict"; require("./setup"); var exchange = require("../src/exchange"), assert = require("assert"), config = require("config"), async = require("async"); describe("Exchange", function () { describe("rounding", function () { it("should round as expected", function() { assert.equal( exchange.round("USD", 33.38 + 10.74), 44.12); }); }); describe("Load and keep fresh the exchange rates", function () { it("should be using test path", function () { // check it is faked out for tests var stubbedPath = "config/initial_exchange_rates.json"; assert.equal( exchange.pathToLatestJSON(), stubbedPath); // check it is normally correct exchange.pathToLatestJSON.restore(); assert.notEqual( exchange.pathToLatestJSON(), stubbedPath); }); it("fx object should convert correctly", function () { assert.equal(exchange.convert(100, "GBP", "USD"), 153.85 ); // 2 dp assert.equal(exchange.convert(100, "GBP", "JPY"), 15083 ); // 0 dp assert.equal(exchange.convert(100, "GBP", "LYD"), 195.385 ); // 3 dp assert.equal(exchange.convert(100, "GBP", "XAG"), 6.15 ); // null dp }); it("should reload exchange rates periodically", function (done) { var fx = exchange.fx; var clock = this.sandbox.clock; // change one of the exchange rates to test for the reload var originalGBP = fx.rates.GBP; fx.rates.GBP = 123.456; // start the delayAndReload exchange.initiateDelayAndReload(); // work out how long to wait var delay = exchange.calculateDelayUntilNextReload(); // go almost to the roll over and check no change clock.tick( delay-10 ); assert.equal(fx.rates.GBP, 123.456); async.series([ function (cb) { // go past rollover and check for change exchange.hub.once("reloaded", function () { assert.equal(fx.rates.GBP, originalGBP); cb(); }); clock.tick( 20 ); }, function (cb) { // reset it again and go ahead another interval and check for change fx.rates.GBP = 123.456; exchange.hub.once("reloaded", function () { assert.equal(fx.rates.GBP, originalGBP); cb(); }); clock.tick( config.exchangeReloadIntervalSeconds * 1000 ); } ], done); }); it.skip("should handle bad exchange rates JSON"); }); });
OpenBookPrices/openbookprices-api
test/exchange.js
JavaScript
agpl-3.0
2,486
window.WebServiceClientTest = new Class( { Implements : [Events, JsTestClass, Options], Binds : ['onDocumentReady', 'onDocumentError'], options : { testMethods : [ { method : 'initialize_', isAsynchron : false }] }, constants : { }, initialize : function( options ) { this.setOptions( options ); this.webServiceClient; }, beforeEachTest : function(){ this.webServiceClient = new WebServiceClient({ }); }, afterEachTest : function (){ this.webServiceClient = null; }, initialize_ : function() { assertThat( this.webServiceClient, JsHamcrest.Matchers.instanceOf( WebServiceClient )); } });
ZsZs/ProcessPuzzleUI
Implementation/WebTier/WebContent/JavaScript/ObjectTests/WebServiceClient/WebServiceClientTest.js
JavaScript
agpl-3.0
736
import { module, test } from 'qunit'; import { setupTest } from 'ember-qunit'; module('Unit | Model | partner partnerclient plan', function(hooks) { setupTest(hooks); // Replace this with your real tests. test('it exists', function(assert) { let store = this.owner.lookup('service:store'); let model = store.createRecord('partner/partnerclient-plan', {}); assert.ok(model); }); });
appknox/irene
tests/unit/models/partner/partnerclient-plan-test.js
JavaScript
agpl-3.0
404
OC.L10N.register( "files_external", { "Fetching request tokens failed. Verify that your app key and secret are correct." : "Ошибка получения токенов запроса. Проверьте корректность ключа и секрета приложения.", "Fetching access tokens failed. Verify that your app key and secret are correct." : "Ошибка получения токенов доступа. Проверьте корректность ключа и секрета приложения.", "Please provide a valid app key and secret." : "Пожалуйста укажите корректные ключ и секрет приложения.", "Step 1 failed. Exception: %s" : "Шаг 1 неудачен. Исключение: %s", "Step 2 failed. Exception: %s" : "Шаг 2 неудачен. Исключение: %s", "External storage" : "Внешнее хранилище", "Dropbox App Configuration" : "Настройка приложения Dropbox", "Google Drive App Configuration" : "Настройка приложения Google Drive", "Personal" : "Личное", "System" : "Система", "Grant access" : "Предоставить доступ", "Error configuring OAuth1" : "Ошибка настройки OAuth1", "Error configuring OAuth2" : "Ошибка настройки OAuth2", "Generate keys" : "Создать ключи", "Error generating key pair" : "Ошибка создания ключевой пары", "All users. Type to select user or group." : "Все пользователи. Для выбора введите имя пользователя или группы.", "(group)" : "(группа)", "Compatibility with Mac NFD encoding (slow)" : "Совместимость с кодировкой Mac NFD (медленно)", "Admin defined" : "Определено админом", "Saved" : "Сохранено", "Empty response from the server" : "Пустой ответ от сервера", "Couldn't access. Please logout and login to activate this mount point" : "Не удалось получить доступ. Пожалуйста, выйти и войдите чтобы активировать эту точку монтирования", "Couldn't get the information from the ownCloud server: {code} {type}" : "Не удалось получить информацию от сервера OwnCloud: {code} {type}", "Couldn't get the list of external mount points: {type}" : "Не удалось получить список внешних точек монтирования: {type}", "There was an error with message: " : "Обнаружена ошибка с сообщением:", "External mount error" : "Ошибка внешнего монтирования", "external-storage" : "внешнее-хранилище", "Couldn't get the list of Windows network drive mount points: empty response from the server" : "Не удалось получить список точек монтирования сетевых дисков Windows: пустой ответ от сервера", "Some of the configured external mount points are not connected. Please click on the red row(s) for more information" : "Некоторые из настроенных внешних точек монтирования не подключены. Для получения дополнительной информации пожалуйста нажмите на красную строку(и)", "Please enter the credentials for the {mount} mount" : "Пожалуйста укажите учетные данные для {mount}", "Username" : "Имя пользователя", "Password" : "Пароль", "Credentials saved" : "Учетные данные сохранены", "Credentials saving failed" : "Ошибка сохранения учетных данных", "Credentials required" : "Требуются учетные данные", "Save" : "Сохранить", "Storage with id \"%i\" not found" : "Хранилище с идентификатором \"%i\" не найдено", "Invalid backend or authentication mechanism class" : "Некорректный механизм авторизации или бэкенд", "Invalid mount point" : "Неправильная точка входа", "Objectstore forbidden" : "Хранение объектов запрещено", "Invalid storage backend \"%s\"" : "Неверный бэкенд хранилища \"%s\"", "Not permitted to use backend \"%s\"" : "Не допускается использование бэкенда \"%s\"", "Not permitted to use authentication mechanism \"%s\"" : "Не допускается использование механизма авторизации \"%s\"", "Unsatisfied backend parameters" : "Недопустимые настройки бэкенда", "Unsatisfied authentication mechanism parameters" : "Недопустимые настройки механизма авторизации", "Insufficient data: %s" : "Недостаточно данных: %s", "%s" : "%s", "Storage with id \"%i\" is not user editable" : "Пользователь не может редактировать хранилище \"%i\"", "Access key" : "Ключ доступа", "Secret key" : "Секретный ключ", "OAuth1" : "OAuth1", "App key" : "Ключ приложения", "App secret" : "Секретный ключ ", "OAuth2" : "OAuth2", "Client ID" : "Идентификатор клиента", "Client secret" : "Клиентский ключ ", "OpenStack" : "OpenStack", "Tenant name" : "Имя арендатора", "Identity endpoint URL" : "Удостоверение конечной точки URL", "Rackspace" : "Rackspace", "API key" : "Ключ API", "RSA public key" : "Открытый ключ RSA", "Public key" : "Открытый ключ", "Amazon S3" : "Amazon S3", "Bucket" : "Корзина", "Hostname" : "Имя хоста", "Port" : "Порт", "Region" : "Область", "Enable SSL" : "Включить SSL", "Enable Path Style" : "Включить стиль пути", "WebDAV" : "WebDAV", "URL" : "Ссылка", "Remote subfolder" : "Удаленный подкаталог", "Secure https://" : "Безопасный https://", "Dropbox" : "Dropbox", "Google Drive" : "Google Drive", "Local" : "Локально", "Location" : "Местоположение", "ownCloud" : "ownCloud", "SFTP" : "SFTP", "Host" : "Сервер", "Root" : "Корневой каталог", "SFTP with secret key login" : "SFTP с помощью секретного ключа", "SMB / CIFS" : "SMB / CIFS", "Share" : "Общий доступ", "Domain" : "Домен", "SMB / CIFS using OC login" : "SMB / CIFS с ипользованием логина OC", "Username as share" : "Имя пользователя в качестве имени общего ресурса", "OpenStack Object Storage" : "Хранилище объектов OpenStack", "Service name" : "Название сервиса", "Request timeout (seconds)" : "Таймаут запроса (секунды)", "<b>Note:</b> " : "<b>Примечание:</b> ", "<b>Note:</b> The cURL support in PHP is not enabled or installed. Mounting of %s is not possible. Please ask your system administrator to install it." : "<b>Примечание:</b> Поддержка cURL в PHP не включена или не установлена. Монтирование %s невозможно. Обратитесь к вашему системному администратору.", "<b>Note:</b> \"%s\" is not installed. Mounting of %s is not possible. Please ask your system administrator to install it." : "<b>Примечание:</b> \"%s\" не установлен. Монтирование %s невозможно. Пожалуйста, обратитесь к системному администратору.", "No external storage configured" : "Нет внешних хранилищ", "You can add external storages in the personal settings" : "Вы можете добавить внешние накопители в личных настройках", "Name" : "Имя", "Storage type" : "Тип хранилища", "Scope" : "Область", "Enable encryption" : "Включить шифрование", "Enable previews" : "Включить предпросмотр", "Enable sharing" : "Включить общий доступ", "Check for changes" : "Проверять изменения", "Never" : "Никогда", "Once every direct access" : "Один раз при прямом доступе", "External Storage" : "Внешнее хранилище", "Folder name" : "Имя каталога", "Authentication" : "Авторизация", "Configuration" : "Конфигурация", "Available for" : "Доступно для", "Add storage" : "Добавить хранилище", "Advanced settings" : "Расширенные настройки", "Delete" : "Удалить", "Allow users to mount external storage" : "Разрешить пользователями монтировать внешние накопители", "Allow users to mount the following external storage" : "Разрешить пользователям монтировать следующие сервисы хранения данных" }, "nplurals=4; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<12 || n%100>14) ? 1 : n%10==0 || (n%10>=5 && n%10<=9) || (n%100>=11 && n%100<=14)? 2 : 3);");
IljaN/core
apps/files_external/l10n/ru.js
JavaScript
agpl-3.0
10,010
'use strict'; /** * @ngdoc directive * @name GO.Core.CustomFields.goCustomFieldsEdit * * @description * Prints custom fields form fieldsets. * * * @param {string} ngModel The customFields model property of the model the customFields belong to * @param {string} serverModel The custom fields server model. * * @example * <go-custom-fields-edit ng-model="contact.customFields" server-model="GO\Modules\GroupOffice\Contacts\Model\ContactCustomFields"></go-custom-fields-edit> */ angular.module('GO.Core').directive('goCustomFieldsEdit', [ '$templateCache', '$compile', 'GO.Core.Directives.CustomFields', function ($templateCache, $compile, CustomFields) { var buildTemplate = function (customFieldSetStore) { var tpl = ''; for (var i = 0, l = customFieldSetStore.items.length; i < l; i++) { var fieldSet = customFieldSetStore.items[i]; tpl += '<fieldset><h3>{{::"' + fieldSet.name + '" | goT}}</h3>'; for (var n = 0, cl = fieldSet.fields.length; n < cl; n++) { var field = fieldSet.fields[n]; tpl += buildFunctions[field.type](field); } tpl += '</fieldset>'; } return tpl; }; var buildFunctions = { formName: null, text: function (field) { return '<md-input-container class="md-block">\ <md-icon>star</md-icon>\ <label>{{::"' + field.name + '" | goT}}</label>\ <input name="' + field.databaseName + '" type="text" maxlength="' + field.data.maxLength + '" ng-model="goModel[\'' + field.databaseName + '\']" ng-required="' + (field.required ? 'true' : 'false') + '" />\ <md-hint>{{::"'+field.hintText+'" | goT}}</md-hint>\ <div ng-messages="formController.' + field.databaseName + '.$error" role="alert">\ <div ng-message="required">\ {{::"This field is required" | goT}}\ </div>\ </div>\ </md-input-container>'; }, textarea: function (field) { return '<md-input-container class="md-block">\ <md-icon>star</md-icon>\ <label>{{::"' + field.name + '" | goT}}</label>\ <textarea id="' + field.databaseName + '" name="' + field.databaseName + '" maxlength="' + field.data.maxLength + '" ng-model="goModel[\'' + field.databaseName + '\']" ng-required="' + (field.required ? 'true' : 'false') + '"></textarea>\ <md-hint>{{::"'+field.hintText+'" | goT}}</md-hint>\ <div ng-messages="formController.' + field.databaseName + '.$error" role="alert">\ <div ng-message="required">\ {{::"This field is required" | goT}}\ </div>\ </div>\ </md-input-container>'; }, select: function (field) { var tpl = '<md-input-container class="md-block">\ <md-icon>star</md-icon>\ <label>{{::"' + field.name + '" | goT}}</label>\ <md-select name="' + field.databaseName + '" ng-model="goModel[\'' + field.databaseName + '\']" ng-required="' + (field.required ? 'true' : 'false') + '">'; for (var i = 0, l = field.data.options.length; i < l; i++) { tpl += '<md-option value="' + field.data.options[i] + '">{{::"' + field.data.options[i] + '" | goT}}</md-option>'; } tpl += '</md-select>\ <md-hint>{{::"'+field.hintText+'" | goT}}</md-hint>\ <div class="md-errors-spacer"></div>\ <div ng-messages="formController.' + field.databaseName + '.$error" role="alert">\ <div ng-message="required">\ {{::"This field is required" | goT}}\ </div>\ </div>'; tpl += '</md-input-container>'; return tpl; }, checkbox: function (field) { return '<md-input-container class="md-block">\ <md-checkbox id="cf_{{field.id}}" ng-model="goModel[\'' + field.databaseName + '\']" ng-required="' + (field.required ? 'true' : 'false') + '"> {{::"' + field.name + '" | goT}}</md-checkbox>\ <md-hint>{{::"'+field.hintText+'" | goT}}</md-hint>\ </md-input-container>'; }, date: function (field) { return '<go-date-picker id="cf_{{field.id}}" name="dateOfBirth" hint="{{::\''+field.hintText+'\' | goT }}" label="' + field.name + '" ng-model="goModel[\'' + field.databaseName + '\']" ng-required="' + (field.required ? 'true' : 'false') + '"></go-date-picker>'; }, number: function (field) { return '<md-input-container class="md-block">\ <md-icon>star</md-icon>\ <label>{{::"' + field.name + '" | goT}}</label>\ <input go-number id="cf_{{field.id}}" name="' + field.databaseName + '" type="text" ng-model="goModel[\'' + field.databaseName + '\']" ng-required="' + (field.required ? 'true' : 'false') + '" />\ <md-hint>{{::"'+field.hintText+'" | goT}}</md-hint>\ <div ng-messages="formController.' + field.databaseName + '.$error" role="alert">\ <div ng-message="required">\ {{::"This field is required" | goT}}\ </div>\ </div>\ </md-input-container>'; } }; return { restrict: 'E', scope: { goModel: '=ngModel', serverModel: '@', formController: '=' }, link: function (scope, element, attrs) { var customFieldSetStore = CustomFields.getFieldSetStore(attrs.serverModel); //TODO load is called twice now customFieldSetStore.promise.then(function () { var tpl = buildTemplate(customFieldSetStore); element.html(tpl); $compile(element.contents())(scope); }); } }; }]);
Intermesh/groupoffice-webclient
app/core/directives/custom-fields/custom-fields-edit-directive.js
JavaScript
agpl-3.0
5,358
'use strict' var config = {} config.facebook = { 'appID': '261938654297222', 'appSecret': 'cd8d0bf4ce75ae5e24be29970b79876f', 'callbackUrl': '/login/facebook/callback/' } config.server = { 'port': process.env.PORT || 3000, 'env': process.env.NODE_ENV || 'dev', 'dbUrl': process.env.MONGODB_URI || 'mongodb://localhost:27017/minihero', 'sessionSecret': 'Minihero FTW!' } config.defaultLocation = { // The default location shown to signed out users on /missions is Amsterdam! latitude: 52.370216, longitude: 4.895168 } config.apiKeys = { google: 'AIzaSyA4vKjKRLNIZ829rfFvz9m_-OFhiORB5Q8' } module.exports = config
damirkotoric/minihero.org
config.js
JavaScript
agpl-3.0
640
/* * _ _ _ * | | | | | | * | | __ _| |__ ___ ___ __ _| |_ Labcoat (R) * | |/ _` | '_ \ / __/ _ \ / _` | __| Powerful development environment for Quirrel. * | | (_| | |_) | (_| (_) | (_| | |_ Copyright (C) 2010 - 2013 SlamData, Inc. * |_|\__,_|_.__/ \___\___/ \__,_|\__| All Rights Reserved. * * * This program is free software: you can redistribute it and/or modify it under the terms of the * GNU Affero General Public License as published by the Free Software Foundation, either version * 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See * the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this * program. If not, see <http://www.gnu.org/licenses/>. * */ define(function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var CSharpHighlightRules = require("./csharp_highlight_rules").CSharpHighlightRules; var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent; var CstyleBehaviour = require("./behaviour/cstyle").CstyleBehaviour; var CStyleFoldMode = require("./folding/cstyle").FoldMode; var Mode = function() { this.$tokenizer = new Tokenizer(new CSharpHighlightRules().getRules()); this.$outdent = new MatchingBraceOutdent(); this.$behaviour = new CstyleBehaviour(); this.foldingRules = new CStyleFoldMode(); }; oop.inherits(Mode, TextMode); (function() { this.lineCommentStart = "//"; this.blockComment = {start: "/*", end: "*/"}; this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); var tokenizedLine = this.$tokenizer.getLineTokens(line, state); var tokens = tokenizedLine.tokens; if (tokens.length && tokens[tokens.length-1].type == "comment") { return indent; } if (state == "start") { var match = line.match(/^.*[\{\(\[]\s*$/); if (match) { indent += tab; } } return indent; }; this.checkOutdent = function(state, line, input) { return this.$outdent.checkOutdent(line, input); }; this.autoOutdent = function(state, doc, row) { this.$outdent.autoOutdent(doc, row); }; this.createWorker = function(session) { return null; }; }).call(Mode.prototype); exports.Mode = Mode; });
precog/labcoat-legacy
js/ace/mode/csharp.js
JavaScript
agpl-3.0
2,838