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 |
|---|---|---|---|---|---|
'use strict';
const db = requireDb();
const exceptions = require('dumonda-me-server-lib').exceptions;
const moreResults = require('../util/moreSearchResults');
const cdn = require('dumonda-me-server-lib').cdn;
const slug = require('limax');
const PAGE_SIZE = 20;
const getSuggestionResponse = async function (suggestions, userId) {
for (let suggestion of suggestions) {
suggestion.creator = {
name: suggestion.user.name,
userId: suggestion.user.userId,
slug: slug(suggestion.user.name),
userImage: await cdn.getSignedUrl(`profileImage/${suggestion.user.userId}/thumbnail.jpg`),
userImagePreview: await cdn.getSignedUrl(`profileImage/${suggestion.user.userId}/profilePreview.jpg`),
isLoggedInUser: suggestion.user.userId === userId,
isTrustUser: suggestion.isTrustUser,
};
delete suggestion.user;
delete suggestion.isTrustUser;
}
return suggestions;
};
const isAllowedToWatchSuggestions = async function (questionId, userId, superUser) {
let response = await db.cypher()
.match(`(question:Question {questionId: {questionId}})<-[:IS_CREATOR]-(:User {userId: {userId}})`)
.return(`question`).end({questionId, userId}).send();
if (response.length === 0 && !superUser) {
throw new exceptions.InvalidOperation(`User ${userId} is not admin of question ${questionId} or super user`);
}
};
const getSuggestions = async function (questionId, page, userId, superUser) {
await isAllowedToWatchSuggestions(questionId, userId, superUser);
page = PAGE_SIZE * page;
let dbResponse = await db.cypher()
.match(`(:Question {questionId: {questionId}})<-[:SUGGESTION]-(s:QuestionSuggestion)
<-[:IS_CREATOR]-(user:User)`)
.return(`s.open AS open, s.title AS title, s.description AS description, s.explanation AS explanation,
s.created AS created, s.suggestionId AS suggestionId, user,
exists((:User {userId: {userId}})-[:IS_CONTACT]->(user)) AS isTrustUser`)
.orderBy(`open DESC, created DESC`)
.skip(`{page}`)
.limit(`${PAGE_SIZE + 1}`)
.end({questionId, page, userId}).send();
let hasMoreSuggestions = moreResults.getHasMoreResults(dbResponse, PAGE_SIZE);
return {hasMoreSuggestions, suggestions: await getSuggestionResponse(dbResponse, userId)};
};
module.exports = {
getSuggestions
};
| Elyoos/Elyoos | dumondaMe/api/models/question/suggestion.js | JavaScript | agpl-3.0 | 2,463 |
import Ember from 'ember';
import { expect } from 'chai';
import { describeComponent, it } from 'ember-mocha';
import { beforeEach } from 'mocha';
import hbs from 'htmlbars-inline-precompile';
import instanceInitializer from '../../../../instance-initializers/ember-intl';
let options = { integration: true };
describeComponent('timeline-events/club-join', 'Integration: ClubJoinTimelineEventComponent', options, function() {
beforeEach(function() {
instanceInitializer.initialize(this);
this.register('service:account', Ember.Service.extend({
user: null,
club: null,
}));
this.inject.service('intl', { as: 'intl' });
this.inject.service('account', { as: 'account' });
this.get('intl').setLocale('en');
this.set('event', {
time: '2016-06-24T12:34:56Z',
actor: {
id: 1,
name: 'John Doe',
},
club: {
id: 42,
name: 'SFN',
},
});
});
it('renders default text', function() {
this.render(hbs`{{timeline-events/club-join event=event}}`);
expect(this.$('td:nth-of-type(2) p:nth-of-type(2)').text().trim())
.to.equal('John Doe joined SFN.');
});
it('renders alternate text if actor is current user', function() {
this.set('account.user', { id: 1, name: 'John Doe' });
this.render(hbs`{{timeline-events/club-join event=event}}`);
expect(this.$('td:nth-of-type(2) p:nth-of-type(2)').text().trim())
.to.equal('You joined SFN.');
});
});
| kerel-fs/skylines | ember/tests/integration/components/timeline-events/club-join-test.js | JavaScript | agpl-3.0 | 1,488 |
// Módulos
var fs = require('fs') // IO ficheros
, parser = require('csv-parse') // carga CSV en array
, slug = require('slug') // genera slug
, _ = require ('lodash') // funciones manipulación de colecciones
, ejs = require ('ejs') // motor de plantillas
, minify = require('html-minifier').minify; // reducir html
// CONFIGURACIÓN
var FICH_DATA = __dirname + '/data/programa.csv';
var DELIMITER = '\t';
var PLANTILLA = __dirname + '/plantilla-wp.ejs';
var etiquetas = require(__dirname + '/data/etiquetas.json');
//añadimos slugs
etiquetas.forEach(function(etiqueta) {
etiqueta["slug"] = slug(etiqueta.nombre).toLowerCase();
});
function dame_etiquetas(num_medida) {
var categorias = [];
etiquetas.forEach(function(etiqueta) {
if (etiqueta.medidas.indexOf(num_medida)>=0) categorias.push(etiqueta);
});
return categorias;
}
// MAIN
// Leemos el fichero con las medidas
parser(fs.readFileSync(FICH_DATA, "utf8"),
{comment: '#', delimiter: DELIMITER, quote: '"'},
function(err, medidas_csv) {
if (err) return;
var medidas = [];
var total_medidas = medidas_csv.length;
for (var i=1; i<total_medidas; i++) {
var num = parseInt(medidas_csv[i][0]);
if (num) {
var medida = {
num: num,
eje: (medidas_csv[i][1])?medidas_csv[i][1]:"",
titulo: (medidas_csv[i][2])?medidas_csv[i][2]:"",
descripcion: (medidas_csv[i][3])?medidas_csv[i][3]:"",
etiquetas: dame_etiquetas(num)
};
medidas.push(medida);
}
}
var ejes = _.uniq(_.pluck(medidas, 'eje'));
//ejes = _.zipObject(ejes, [30, 40]);
ejes = _.map (ejes, function(eje) {
return {
nombre: eje,
slug: slug(eje).toLowerCase()
};
});
var pagina = ejs.render(fs.readFileSync(PLANTILLA, "utf8"), {medidas: medidas, etiquetas: etiquetas, ejes: ejes});
fs.writeFileSync(__dirname+'/web/index.html', pagina);
fs.writeFileSync(__dirname+'/web/index.min.html', minify(pagina, {
collapseWhitespace: true,
removeAttributeQuotes: true }));
/*
filtros por ejes
_.each(ejes, function(eje){
var medidas_por_eje = _.filter(medidas, function(medida) {
return (medida.eje == eje.nombre)
});
var pagina = ejs.render(fs.readFileSync(PLANTILLA, "utf8"), {medidas: medidas_por_eje, etiquetas: etiquetas, ejes: ejes});
fs.writeFileSync(__dirname+'/web/'+eje.slug+'.htm', pagina);
});
*/
});
| joker-x/programa-podemos-2015 | index.js | JavaScript | agpl-3.0 | 2,313 |
'use strict';
/*global _*/
/**
* @ngdoc directive
* @name ngPasswordStrengthApp.directive:ngPasswordStrength
* @description
* # ngPasswordStrength HEAVILY CUSTOMISED DO NOT UPDATE
*/
angular.module('ngPasswordStrength', []).directive('ngPasswordStrength', ['$compile', '$rootScope', function($compile, $rootScope) {
return {
restrict: 'A',
require: 'ngModel',
scope: {
pwd: '=ngModel'
},
link: function(scope, elem, attrs, ngModel) {
var mesureStrength = function(p) {
var matches = {
pos: {},
neg: {}
},
counts = {
pos: {},
neg: {
seqLetter: 0,
seqNumber: 0,
seqSymbol: 0
}
},
tmp,
strength = 0,
letters = 'abcdefghijklmnopqrstuvwxyz',
numbers = '01234567890',
symbols = '\\!@#$%&/()=?¿',
back,
forth,
i;
if (p) {
// Benefits
matches.pos.lower = p.match(/[a-z]/g);
matches.pos.upper = p.match(/[A-Z]/g);
matches.pos.numbers = p.match(/\d/g);
matches.pos.symbols = p.match(/[$-/:-?{-~!^_`\[\]]/g);
matches.pos.middleNumber = p.slice(1, -1).match(/\d/g);
matches.pos.middleSymbol = p.slice(1, -1).match(/[$-/:-?{-~!^_`\[\]]/g);
counts.pos.lower = matches.pos.lower ? matches.pos.lower.length : 0;
counts.pos.upper = matches.pos.upper ? matches.pos.upper.length : 0;
counts.pos.numbers = matches.pos.numbers ? matches.pos.numbers.length : 0;
counts.pos.symbols = matches.pos.symbols ? matches.pos.symbols.length : 0;
tmp = _.reduce(counts.pos, function(memo, val) {
// if has count will add 1
return memo + Math.min(1, val);
}, 0);
counts.pos.numChars = p.length;
tmp += (counts.pos.numChars >= 8) ? 1 : 0;
counts.pos.requirements = (tmp >= 3) ? tmp : 0;
counts.pos.middleNumber = matches.pos.middleNumber ? matches.pos.middleNumber.length : 0;
counts.pos.middleSymbol = matches.pos.middleSymbol ? matches.pos.middleSymbol.length : 0;
// Deductions
matches.neg.consecLower = p.match(/(?=([a-z]{2}))/g);
matches.neg.consecUpper = p.match(/(?=([A-Z]{2}))/g);
matches.neg.consecNumbers = p.match(/(?=(\d{2}))/g);
matches.neg.onlyNumbers = p.match(/^[0-9]*$/g);
matches.neg.onlyLetters = p.match(/^([a-z]|[A-Z])*$/g);
counts.neg.consecLower = matches.neg.consecLower ? matches.neg.consecLower.length : 0;
counts.neg.consecUpper = matches.neg.consecUpper ? matches.neg.consecUpper.length : 0;
counts.neg.consecNumbers = matches.neg.consecNumbers ? matches.neg.consecNumbers.length : 0;
var reverse = function(str) {
return str == null ? '' : str.split('').reverse().join('');
};
// sequential letters (back and forth)
for (i = 0; i < letters.length - 2; i++) {
var p2 = p.toLowerCase();
forth = letters.substring(i, parseInt(i + 3));
back = reverse(forth);
if (p2.indexOf(forth) !== -1 || p2.indexOf(back) !== -1) {
counts.neg.seqLetter++;
}
}
// sequential numbers (back and forth)
for (i = 0; i < numbers.length - 2; i++) {
forth = numbers.substring(i, parseInt(i + 3));
back = reverse(forth);
if (p.indexOf(forth) !== -1 || p.toLowerCase().indexOf(back) !== -1) {
counts.neg.seqNumber++;
}
}
// sequential symbols (back and forth)
for (i = 0; i < symbols.length - 2; i++) {
forth = symbols.substring(i, parseInt(i + 3));
back = reverse(forth);
if (p.indexOf(forth) !== -1 || p.toLowerCase().indexOf(back) !== -1) {
counts.neg.seqSymbol++;
}
}
// repeated chars
counts.neg.repeated = _.chain(p.toLowerCase().split('')).
countBy(function(val) {
return val;
})
.reject(function(val) {
return val === 1;
})
.reduce(function(memo, val) {
return memo + val;
}, 0)
.value();
// Calculations
strength += counts.pos.numChars * 4;
if (counts.pos.upper) {
strength += (counts.pos.numChars - counts.pos.upper) * 2;
}
if (counts.pos.lower) {
strength += (counts.pos.numChars - counts.pos.lower) * 2;
}
if (counts.pos.upper || counts.pos.lower) {
strength += counts.pos.numbers * 4;
}
strength += counts.pos.symbols * 6;
strength += (counts.pos.middleSymbol + counts.pos.middleNumber) * 2;
strength += counts.pos.requirements * 2;
strength -= counts.neg.consecLower * 2;
strength -= counts.neg.consecUpper * 2;
strength -= counts.neg.consecNumbers * 2;
strength -= counts.neg.seqNumber * 3;
strength -= counts.neg.seqLetter * 3;
strength -= counts.neg.seqSymbol * 3;
if (matches.neg.onlyNumbers) {
strength -= counts.pos.numChars;
}
if (matches.neg.onlyLetters) {
strength -= counts.pos.numChars;
}
if (counts.neg.repeated) {
strength -= (counts.neg.repeated / counts.pos.numChars) * 10;
}
}
return Math.max(0, Math.min(100, Math.round(strength)));
},
getClass = function(score) {
if (score < 40) {
return "danger";
} else {
return "success";
}
},
getLabel = function(score) {
if (score < 20) {
return 'veryweak'
} else if (score < 40) {
return 'weak'
} else if (score < 60) {
return 'good'
} else {
return 'strong'
}
};
var template = '<div id="password-strength-result" class="form-text validation-error text-{{class}}">{{ label }}</div>';
scope.$watch('pwd', function() {
if (!ngModel.$pristine) {
scope.value = mesureStrength(scope.pwd);
scope.label = $rootScope.message("todo.is.ui.password.strength." + getLabel(scope.value));
scope.class = getClass(scope.value);
var compiledTemplate = angular.element($compile(template)(scope));
elem.parent().find('#password-strength-result').remove();
if(scope.pwd) {
elem.after(compiledTemplate);
}
}
});
}
};
}]); | icescrum/iceScrum | grails-app/assets/javascripts/vendors/angular/plugins/angular-password-strength.js | JavaScript | agpl-3.0 | 8,396 |
// Usage: node gen_dao.js exec <source folder name> <target folder name>
// <source folder name>: Include files each for a table.
// <target folder name>: To store generated java class files.
// 映射文件格式:
// 1# DB表名
// 2# 第一个字段名 + 空格 + 如果后面跟一个 # 号表示字段非空,跟一个 * 号表示字段唯一
// 3# 第一个字段类型和长度
// 4# 第一个字段的说明
// 5# 重复2-3的内容
var fs = require('fs');
var util = require('util');
var StringDecoder = require('string_decoder').StringDecoder;
var ejs = require('ejs');
var program = require('commander');
var decoder = new StringDecoder('utf8');
console.log('DAO generator for Java persistence ')
// 换行符
var LINE_SEP = '\n';
var arg_src_folder = process.argv[2];
var arg_target_folder = process.argv[3];
var is_verbose = false;
program.version('1.0')
.option('-v, --verbose', 'show verbose log')
.command('exec <src> <dst>')
.action(function(src, dst) {
console.log(program.verbose);
if (program.verbose) {
console.log("verbose mode");
}
else {
console.log("silent mode");
}
console.log(src);
console.log(dst);
arg_src_folder = src;
arg_target_folder = dst;
is_verbose = program.verbose;
console.log(arg_src_folder);
execGeneration();
});
program.parse(process.argv);
// if (process.argv.length < 4) {
// console.log('Usage: node gen_dao.js <source folder name> <target folder name>');
// return;
// }
//
// var arg_src_folder = process.argv[2];
// var arg_target_folder = process.argv[3];
var mapping;
function execGeneration() {
console.log('Starting generator');
info(arg_src_folder);
info(arg_target_folder);
var mappingSrc = readFileToString('template/mapping');
mapping = JSON.parse(mappingSrc);
info(mapping);
fs.readdir(arg_src_folder, function (err, files) {
if (err || !files || files.length == 0) {
info('No mapping files for DB');
return;
}
for (var i = 0; i < files.length; i++) {
var fileName = files[i];
if (fileName.indexOf('.') == 0) {
continue;
}
var className = fileName;
info('Read definition file: ' + fileName);
var fileData = fs.readFileSync(arg_src_folder + '/' + fileName);
handleMapping(className, fileData);
}
});
}
/**
* 处理一个映射文件中的元数据,生成实体类文件
* @param className
* @param data
*/
function handleMapping(className, data) {
if (!data) {
info(' failed to load file');
}
else {
var bytes = new Buffer(data);
var str = decoder.write(bytes).trim();
//console.log(str);
var lines = str.split(LINE_SEP);
debug('### ' + lines.length % 3 == 2); // 必须是 3*n+2 行
if (!lines || lines.length == 0 || lines.length % 3 != 2) {
info(' column definition invalid');
return;
}
var colDefs = []; // 字段定义
var tableName = lines[0];
var entityDesc = lines[1];
for (var j = 2; j < lines.length; j++) {
var colDef = {};
debug(colDef);
colDef.name = getColName(lines[j]);
colDef.unique = lines[j].indexOf('*') > 0;
colDef.notnull = lines[j++].indexOf('#') > 0;
colDef.type = getType(lines[j]);
colDef.length = getLength(lines[j++], colDef.type);
colDef.comment = lines[j];
debug(colDef);
colDefs.push(colDef);
}
genJpaEntity(className, tableName, colDefs, entityDesc);
genJpaDaoInterfaceAndImpl(className, entityDesc);
}
}
function getColName(str) {
if (str.indexOf(' ') <= 0) {
return str;
}
else {
return str.substring(0, str.indexOf(' '));
}
}
function getType(str) {
var idx = str.indexOf('(');
return str.substring(0, idx <= 0 ? str.length : idx);
}
function getLength(str, type) {
if (str.indexOf('(') <= 0) {
return 0;// 无长度
}
// decimal 特殊处理
if (type == 'DECIMAL') {
var idx1 = str.indexOf('(');
var idx2 = str.indexOf(')');
return str.substring(idx1 + 1, idx2);
//return 12; // TODO 暂时固定为14,将来重构成可以自动计算长度
}
else {
return str.substring(str.indexOf('(') + 1, str.indexOf(')'));
}
}
/**
* 生成 JPA 定义的实体类
* @param className 实体类名
* @param tbName 表名
* @param columns 字段定义
* @param entityDesc
*/
function genJpaEntity(entityClassName, tbName, columns, entityDesc) {
info();
info('==== Create JPA Entity Class for Table "%s" ====', tbName);
var colValues = {};
colValues = Object.assign(colValues, mapping);
// colValues.entity_pkg_name = arg_pkg_name_entity;
colValues.entity_class_name = entityClassName;
colValues.table_name = tbName;
colValues.entity_desc = entityDesc;
colValues.col_defs = [];// init
for (var j = 0; j < columns.length; j++) {
var colDef = columns[j];
var colValue = {};
colValue.name = colDef.name;
// 注释
if (colDef.comment) {
colValue.comment = util.format('%s', colDef.comment);
}
// 注解
colValue.annotations = [];
if (colDef.name == 'ID') {
colValue.annotations.push('@Id()');
}
var content = '';
content += util.format('@Column(name = COL_NAME_%s', colDef.name);
if (colDef.type == 'DECIMAL') {
var iSeperator = colDef.length.indexOf(',');
console.log(colDef.length);
var precise = colDef.length.substring(0, iSeperator);
var scale = colDef.length.substring(iSeperator + 1, colDef.length.length);
content += ', precision = ' + precise + ', scale = ' + scale;
}
else if(colDef.type != 'INT' && colDef.type != 'LONG' && colDef.type != 'SMALLINT') {
content += ', length = ' + colDef.length;
if (colDef.type == 'CHAR') {
content += ', columnDefinition = "char(' + colDef.length + ')"';
}
}
if (colDef.unique) {
content += ', unique = true';
}
if (colDef.notnull) {
content += ', nullable = false';
}
content += ')';
colValue.annotations.push(content);
// 成员变量定义
var type = 'String';
if (colDef.type == 'INT' || colDef.type == 'SMALLINT') {
type = 'int';
}
else if (colDef.type == 'LONG') {
type = 'long';
}
else if (colDef.type == 'DECIMAL') {
type = 'BigDecimal';
}
else if(colDef.type == 'CHAR' || colDef.type == 'VARCHAR') {
type = 'String';
}
else {
info(' WARN: Unrecognizable column type: %s, treat as String', colDef.type);
}
colValue.type = type;
colValue.property_name = convertUnderLineToCamelSentence(colDef.name, true);
colValue.property_method_name = convertUnderLineToCamelSentence(colDef.name, false);
debug(colValue);
colValues.col_defs.push(colValue);
}
debug('转换结果:');
debug(colValues);
for(var i=0; i<colValues.length; i++) {
debug(colValues[i]);
}
var javaCode;
var templateSrc = readFileToString('template/entity_template.java');
if (!templateSrc || templateSrc.length == 0) {
info('实体类模版没有找到');
return;
}
var template = ejs.compile(templateSrc, {compileDebug: true, rmWhitespace: false});
javaCode = template(colValues);
var dstDir = arg_target_folder + '/entity/';
if (!fs.existsSync(dstDir)) {
fs.mkdirSync(dstDir);
}
var dstFilePath = dstDir + entityClassName + '.java';
fs.writeFile(dstFilePath, javaCode);
info('==== Done with file %s created ====', dstFilePath);
}
/**
* 读取文本文件内容
*/
function readFileToString(filePath) {
var data = fs.readFileSync(filePath);
var bytes = new Buffer(data);
return decoder.write(bytes).trim();
}
/**
* 生成 DAO 接口和实现类
* @param entityName 必须以’Entity‘结尾
* @param entityDesc
*/
function genJpaDaoInterfaceAndImpl(entityClassName, entityDesc) {
info();
info('==== Create JPA Dao Interface for Entity "%s" ====', entityName);
var daoName = replaceTail(entityClassName, 'Entity', 'Dao');
var entityName = replaceTail(entityClassName, 'Entity', '');
var params = {};
params = Object.assign(params, mapping);
// params.dao_pkg_name = arg_pkg_name_dao;
// params.entity_pkg_name = arg_pkg_name_entity;
params.dao_name = daoName;
params.entity_class_name = entityClassName;
params.entity_name = entityName;
params.dao_desc = entityDesc;
var templateSrc = readFileToString('template/dao_template.java');
var template = ejs.compile(templateSrc, {compileDebug: true, rmWhitespace: false});
javaCode = template(params);
// var template2 = ejs.compile(javaCode, {compileDebug: true, rmWhitespace: false});
// var javaCode2 = template2(mapping);
var dstDir = arg_target_folder;
if (!fs.existsSync(dstDir)) {
fs.mkdirSync(dstDir);
}
var dstDaoFilePath = arg_target_folder + daoName + '.java';
fs.writeFile(dstDaoFilePath, javaCode);
info('==== Done with file %s created ====', dstDaoFilePath);
// 生成 DAO 实现类
info();
info('==== Create JPA Dao Interface for Entity "%s" ====', entityName);
// var daoImplName = replaceTail(entityName, 'Entity', 'DaoImpl');
var templateSrc = readFileToString('template/dao_impl_template.java');
var template = ejs.compile(templateSrc, {compileDebug: true, rmWhitespace: false});
javaCode = template(params);
var dstDir = arg_target_folder + 'impl/';
if (!fs.existsSync(dstDir)) {
fs.mkdirSync(dstDir);
}
var dstDaoImplFilePath = arg_target_folder + 'impl/' + daoName + 'Impl.java';
fs.writeFile(dstDaoImplFilePath, javaCode);
info('==== Done with file %s created ====', dstDaoImplFilePath);
}
/**
* 将字符串尾部的内容替换掉
*
*/
function replaceTail(str, old, replacement) {
var n = str.lastIndexOf(old);
if (n <=0 ) {
debug('No specified tail found');
return str;
}
debug(n);
debug(str.substring(0, n) );
return str.substring(0, n) + replacement;
}
/**
* 将下划线句子转换为驼峰
* @param sentence
* @param firstLowerCase 第一个字母是否小写,默认为false
*/
function convertUnderLineToCamelSentence(sentence, firstLowerCase) {
var words = sentence.split('_');
if (!words || words.length == 0) {
return sentence;
}
var ret = '';
var start = 0;
if (firstLowerCase) {
ret = words[0].toLowerCase(); // 第一个特殊处理
start = 1; // 从第二个开始
}
for (var i = start; i < words.length; i++) {
ret += words[i].charAt(0).toUpperCase(); // 第一个大写
ret += words[i].substring(1).toLowerCase(); // 后面全部小写
}
return ret;
}
function debug(str) {
if (is_verbose && str) {
console.log(str);
}
}
function info(str) {
if (str) {
console.log(str);
}
}
function info(str, value) {
if (str) {
console.log(str, value);
}
}
| swiftech/DaoGen | gen_dao.js | JavaScript | agpl-3.0 | 10,786 |
var appoAPIClient = {
hints: ["Questa settimana ti sei spostato per 100 km in auto, per 5 in bus ed hai camminato per 2 km bruciando 50 calorie"],
healthOptions: [{"key": "lose_weight", "value": "Perdere peso"},
{"key": "walk_more", "value": "Camminare di piu'"}],
executeQuery: function(actionQuery, successQueryAction, errorQuery) {
console.log("actionQuery: " + actionQuery);
var action;
var params = null;
if (actionQuery.indexOf("?") > -1) {
var sections = actionQuery.split("?");
action = sections[0];
params = sections[1];
}
else {
action = actionQuery;
}
var response = {};
response.status = {};
response.status.error_message = "successful";
response.status.current_operation = action;
response.status.error_code = 0;
response.data = {};
var initialTime = new Date();
if (action === "/recommender/health/") {
var randomHintIndex = Math.floor((Math.random() * this.hints.length));
response.data.hint = this.hints[randomHintIndex];
}
else if (action === "/recommender/healthgoals_all") {
response.data.options = this.healthOptions;
}
else if (action === "/recommender/healthgoals/") {
//console.log("params: " + params);
//console.log("healthGoal: " + healthGoal);
var healthGoal = appoAPIClient.getParameterFromPath(params, "goal");
//console.log("healthGoal: " + healthGoal);
if (healthGoal === "lose_weight") {
var sex = appoAPIClient.getParameterFromPath(params, "sex");
//console.log("sex: " + sex);
if (sex === "M") {
response.data.hint = "Porta fuori il cane";
}
else {
response.data.hint = "Porta fuori la cagna";
}
}
else if (healthGoal === "walk_more") {
var walking_minutes = 20;
var weight = appoAPIClient.getParameterFromPath(params, "weight");
var kilocalories;
if (weight) {
kilocalories = Math.floor(.6 * weight * walking_minutes / 60);
}
var hint = "Invece di prendere l'auto per andare a lavoro, ";
hint += "prendi l'autobus a soli 800 metri da casa. ";
hint += "La linea 6 ti porta a 500 metri dal lavoro e camminerai per " + walking_minutes + " minuti al giorno.";
if (kilocalories) {
hint += "\nConsumo calorie: " + kilocalories;
}
var journey = {};
journey.wkt = 'LINESTRING(11.248197799999955 43.77360880000041,' +
'11.248243299999997 43.77364769999992,11.248776499999991 43.7732725,11.248813200000027 43.773246700000236,' +
'11.248888499999957 43.7732941000004,11.249025699999956 43.77327530000041,11.249024899999958 43.7732369000004)';
response.data.hint = hint;
response.data.journey = journey;
}
else {
errorQuery("Unknown goal: " + healthGoal);
return;
}
}
else {
errorQuery("Unknown action");
return;
}
response.elapsed_ms = (new Date() - initialTime) / 1000;
successQueryAction(JSON.stringify(response));
},
getParameterFromPath: function(params, paramName) {
var value = null;
if (params) {
var paramsPairs = params.split("&");
var paramsPair;
for (var indx = 0; indx < paramsPairs.length; indx++) {
if (paramsPairs[indx].indexOf("=") > -1) {
paramsPair = paramsPairs[indx].split("=");
if (paramsPair[0] == paramName) {
value = paramsPair[1];
}
}
}
}
return value;
}
} | sPaolettiGeoin/siiMobilityAppKit | www/js/modules/healthCare/AppoAPIClient.js | JavaScript | agpl-3.0 | 3,320 |
//객체얻기
function getId(id)
{
return document.getElementById(id);
}
//리다이렉트
function goHref(url)
{
location.href = url;
}
//아이디형식체크
function chkIdValue(id)
{
if (id == '') return false;
if (!getTypeCheck(id,"abcdefghijklmnopqrstuvwxyz1234567890_-")) return false;
return true;
}
//파일명형식체크
function chkFnameValue(file)
{
if (file == '') return false;
if (!getTypeCheck(file,"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890_-")) return false;
return true;
}
//이메일체크
function chkEmailAddr(email)
{
if (email == '') return false;
if (email.indexOf('\@') == -1 || email.indexOf('.') == -1) return false;
return true;
}
//오픈윈도우
function OpenWindow(url)
{
setCookie('TmpCode','',1);
window.open(url,'','width=100px,height=100px,status=no,scrollbars=no,toolbar=no');
}
//이미지보기
function imgOrignWin(url)
{
setCookie('TmpImg',url,1);
OpenWindow(rooturl+'/_core/lib/zoom.php','','width=10px,height=10px,status=yes,resizable=yes,scrollbars=yes');
}
//로그인체크
function isLogin()
{
if (memberid == '')
{
alert(needlog+' ');
return false;
}
return true;
}
/*쿠키세팅*/
function setCookie(name,value,expiredays)
{
var todayDate = new Date();
todayDate.setDate( todayDate.getDate() + expiredays );
document.cookie = name + "=" + escape( value ) + "; path=/; expires=" + todayDate.toGMTString() + ";"
}
/*쿠키추출*/
function getCookie( name )
{
var nameOfCookie = name + "=";
var x = 0;
while ( x <= document.cookie.length )
{
var y = (x+nameOfCookie.length);
if ( document.cookie.substring( x, y ) == nameOfCookie )
{
if ( (endOfCookie=document.cookie.indexOf( ";", y )) == -1 ) endOfCookie = document.cookie.length;
return unescape( document.cookie.substring( y, endOfCookie ) );
}
x = document.cookie.indexOf( " ", x ) + 1;
if ( x == 0 ) break;
}
return "";
}
/*이벤트좌표값*/
function getEventXY(e)
{
var obj = new Object();
obj.x = e.clientX + (document.documentElement.scrollLeft || document.body.scrollLeft) - (document.documentElement.clientLeft || document.body.clientLeft);
obj.y = e.clientY + (document.documentElement.scrollTop || document.body.scrollTop) - (document.documentElement.clientTop || document.body.clientTop);
return obj;
}
/*파일확장자*/
function getFileExt(file)
{
var arr = file.split('.');
return arr[arr.length-1];
}
/*객체의위치/크기*/
function getDivWidth(width,div)
{
var maxsize = parseInt(width);
var content = getId(div);
var img = content.getElementsByTagName('img');
var len = img.length;
for(i=0;i<len;i++)
{
if (img[i].width > maxsize) img[i].width=maxsize;
if (img[i].style.display == 'none') img[i].style.display = 'block';
}
}
function getOfs(id)
{
var obj = new Object();
var box = id.getBoundingClientRect();
obj.left = box.left + (document.documentElement.scrollLeft || document.body.scrollLeft);
obj.top = box.top + (document.documentElement.scrollTop || document.body.scrollTop);
obj.width = box.right - box.left;
obj.height = box.bottom - box.top;
return obj;
}
/*조사처리*/
/*은,는,이,가 - getJosa(str,"은는")*/
function getJosa(str, tail)
{
strTemp = str.substr(str.length - 1);
return ((strTemp.charCodeAt(0) - 16) % 28 != 0) ? str + tail.substr(0, 1) : str + tail.substr(1, 1);
}
/*타입비교 (비교문자 , 비교형식 ; ex: getTypeCheck(string , "1234567890") ) */
function getTypeCheck(s, spc)
{
var i;
for(i=0; i< s.length; i++)
{
if (spc.indexOf(s.substring(i, i+1)) < 0)
{
return false;
}
}
return true;
}
/*콤마삽입 (number_format)*/
function commaSplit(srcNumber)
{
var txtNumber = '' + srcNumber;
var rxSplit = new RegExp('([0-9])([0-9][0-9][0-9][,.])');
var arrNumber = txtNumber.split('.');
arrNumber[0] += '.';
do {
arrNumber[0] = arrNumber[0].replace(rxSplit, '$1,$2');
}
while (rxSplit.test(arrNumber[0]));
if (arrNumber.length > 1) {
return arrNumber.join('');
}
else {
return arrNumber[0].split('.')[0];
}
}
function priceFormat(obj)
{
if (!getTypeCheck(filterNum(obj.value),'0123456789'))
{
alert(neednum);
obj.value = obj.defaultValue;
obj.focus();
return false;
}
else {
obj.value = commaSplit(filterNum(obj.value));
}
}
function numFormat(obj)
{
if (!getTypeCheck(obj.value,'0123456789'))
{
alert(neednum);
obj.value = obj.defaultValue;
obj.focus();
return false;
}
}
function getJeolsa(price,_round)
{
return price - (price%(_round*10));
}
/*콤마제거*/
function filterNum(str)
{
return str.replace(/^\$|,/g, "");
}
/*페이징처리*/
function getPageLink(lnum,p,tpage,img)
{
var g_hi = img.split('|');
var imgpath = g_hi[0];
var wp = g_hi[1] ? g_hi[1] : '';
var g_p1 = '<img src="'+imgpath+'/p1.gif" alt="Prev '+lnum+' pages" />';
var g_p2 = '<img src="'+imgpath+'/p2.gif" alt="Prev '+lnum+' pages" />';
var g_n1 = '<img src="'+imgpath+'/n1.gif" alt="Next '+lnum+' pages" />';
var g_n2 = '<img src="'+imgpath+'/n2.gif" alt="Next '+lnum+' pages" />';
var g_cn = '<img src="'+imgpath+'/l.gif" class="split" alt="" />';
var g_q = p > 1 ? '<a href="'+getPageGo(1,wp)+'"><img src="'+imgpath+'/fp.gif" alt="First page" class="phidden" /></a>' : '<img src="'+imgpath+'/fp1.gif" alt="First page" class="phidden" />';
if(p < lnum+1) { g_q += g_p1; }
else{ var pp = parseInt((p-1)/lnum)*lnum; g_q += '<a href="'+getPageGo(pp,wp)+'">'+g_p2+'</a>';} g_q += g_cn;
var st1 = parseInt((p-1)/lnum)*lnum + 1;
var st2 = st1 + lnum;
for(var jn = st1; jn < st2; jn++)
if ( jn <= tpage)
(jn == p)? g_q += '<span class="selected" title="'+jn+' page">'+jn+'</span>'+g_cn : g_q += '<a href="'+getPageGo(jn,wp)+'" class="notselected" title="'+jn+' page">'+jn+'</a>'+g_cn;
if(tpage < lnum || tpage < jn) { g_q += g_n1; }
else{var np = jn; g_q += '<a href="'+getPageGo(np,wp)+'">'+g_n2+'</a>'; }
g_q += tpage > p ? '<a href="'+getPageGo(tpage,wp)+'"><img src="'+imgpath+'/lp.gif" alt="Last page" class="phidden" /></a>' : '<img src="'+imgpath+'/lp1.gif" alt="Last page" class="phidden" />';
document.write(g_q);
}
/*페이지클릭*/
function getPageGo(n,wp)
{
var v = wp != '' ? wp : 'p';
var p = getUriString(v);
var que = location.href.replace('&'+v+'='+p,'');
que = que.indexOf('?') != -1 ? que : que + '?';
que = que.replace('&mod=view&uid=' + getUriString('uid') , '');
var xurl = que.split('#');
return xurl[0].indexOf('?') != -1 ? xurl[0] + '&'+v+'=' + n : xurl[0] + '?'+v+'=' + n;
}
/*파라미터값*/
function getUriString(param)
{
var QuerySplit = location.href.split('?');
var ResultQuer = QuerySplit[1] ? QuerySplit[1].split('&') : '';
for (var i = 0; i < ResultQuer.length; i++)
{
var keyval = ResultQuer[i].split('=');
if (param == keyval[0]) return keyval[1];
}
return '';
}
function getUrlParam(url,param)
{
var QuerySplit = url.split('&');
for (var i = 0; i < QuerySplit.length; i++)
{
var keyval = QuerySplit[i].split('=');
if (param == keyval[0]) return keyval[1];
}
return '';
}
/* 날짜출력포맷 */
/* getDateFormat('yyyymmddhhiiss','xxxx.xx.xx xx:xx:xx')*/
var dateFormat = 0;
function getDateFormat(date , type)
{
var ck;
var rtstr = "";
var j = 0;
for(var i = 0; i < type.length; i++)
{
if(type.substring(i,i+1) == 'x')
{
rtstr += date.substring(j,j+1);
}
else {
j--;
rtstr += type.substring(i,i+1);
}
j++;
}
if(dateFormat == 0)
{
document.write(rtstr);
}
else {
dateFormat = 0;
return rtstr;
}
}
//선택반전
function chkFlag(f)
{
var l = document.getElementsByName(f);
var n = l.length;
var i;
for (i = 0; i < n; i++) l[i].checked = !l[i].checked;
}
/*문자열카피*/
function copyStr(str)
{
if(myagent == 'ie')
{
window.clipboardData.setData('Text',str);
}
else {
window.execCommand('copy',str);
}
}
//레이어show/hide
function layerShowHide(layer,show,hide)
{
if(getId(layer).style.display != show) getId(layer).style.display = show;
else getId(layer).style.display = hide;
}
//keycode
function checkKeycode(e)
{
if (window.event) return window.event.keyCode;
else if (e) return e.which;
}
//AJAX-Request
function getHttprequest(URL,f)
{
var xmlhttp = null;
if(window.XMLHttpRequest) xmlhttp = new XMLHttpRequest();
else {try{xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");}catch(e1){try{xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");}catch(e2){return false;}}}
if (xmlhttp)
{
if (f)
{
var i;
var iParam = "";
for (i=1;i<f.length;i++)
{
if ((f[i].type=='radio'||f[i].type=='checkbox')&&f[i].checked==false) continue;
iParam += '&' + f[i].name + '=' + encodeURIComponent(f[i].value);
}
xmlhttp.open("POST", URL, false);
xmlhttp.setRequestHeader("Content-Type","multipart/form-data;application/x-www-form-urlencoded;charset=utf-8");
xmlhttp.send(iParam);
}
else {
xmlhttp.open("GET", URL, false);
xmlhttp.send(null);
}
if (xmlhttp.readyState==4 && xmlhttp.status == 200 && xmlhttp.statusText=='OK') return xmlhttp.responseText;
xmlhttp = null;
}
}
function getAjaxFilterString(str,code)
{
var arr1 = str.split('['+code+':');
var arr2 = arr1[1].split(':'+code+']');
return arr2[0];
}
//iframe_for_action
function getIframeForAction(f)
{
getId('_hidden_layer_').style.display = 'none';
getId('_hidden_layer_').innerHTML = '<iframe name="__iframe_for_action__"></iframe>';
if(f) f.target = '__iframe_for_action__';
}
function hrefCheck(obj,target,msg)
{
if(target) getIframeForAction(obj);
if(msg) return confirm(msg);
}
function getEventBoxPos(e)
{
var gtop = 0;
var gleft = 0;
var ele = e.srcElement || e.target;
if (parseInt(document.body.offsetWidth) > parseInt(document.body.scrollWidth))
{
if ((e.clientX == e.offsetX||ele.alt=='.')&&ele.alt!='..')
{
var box = getId('commentFrame').getBoundingClientRect();
gleft = box.left;
gtop = box.top;
}
}
var clk = ele.getBoundingClientRect();
var obj = new Object();
var lt = (document.documentElement.scrollLeft || document.body.scrollLeft) - (document.documentElement.clientLeft || document.body.clientLeft);
var tp = (document.documentElement.scrollTop || document.body.scrollTop) - (document.documentElement.clientTop || document.body.clientTop);
obj.x = clk.right + lt + gleft;
obj.y = clk.bottom + tp + gtop;
obj.left = clk.left + lt + gleft;
obj.top = clk.top + tp + gtop;
return obj;
}
//회원레이어
var selPos;
function getMemberLayer(uid,e)
{
var ly = getId('_action_layer_');
ly.className = 'mbrLayerBlock';
ly.style.display = 'block';
ly.style.zIndex = '1';
var xy = getEventBoxPos(e);
var bx = getOfs(ly);
var nowPos = parseInt(xy.x);
var nowWidth = parseInt(document.body.offsetWidth);
selPos = nowWidth - nowPos > 330 ? 'r' : 'l';
var tags = '';
if (selPos=='r')
{
ly.style.top = (parseInt(xy.y) - 61) + 'px';
ly.style.left = (parseInt(xy.x) + 10) + 'px';
}
else {
ly.style.top = (parseInt(xy.y) - 61) + 'px';
ly.style.left = (parseInt(xy.x) - 370) + 'px';
}
tags += '<div style="height:100%;text-align:center;" onmousedown="showMemberLayer();"><img src="'+rooturl+'/_core/image/loading/white_big.gif" alt="" style="margin-top:'+((bx.height/2)-30)+'px;" /></div>';
ly.innerHTML = tags;
mbrclick = true;
setTimeout("mbrclick=false;",200);
setTimeout("getMemberLayerLoad('"+uid+"');",1);
//getMemberLayerLoad(uid);
}
function getMemberLayerLoad(uid)
{
var result = getHttprequest(rooturl+'/?r='+raccount+'&iframe=Y&system=layer.member&uid='+uid+'&selPos='+selPos,'');
getId('_action_layer_').innerHTML=getAjaxFilterString(result,'RESULT');
}
function showMemberLayer()
{
mbrclick=true;
setTimeout("mbrclick=false;",200);
}
function closeMemberLayer()
{
if(mbrclick==false) if(getId('_box_layer_').style.display!='block') getId('_action_layer_').style.display = 'none';
if(parent.mbrclick==false) if(parent.getId('_box_layer_').style.display!='block') parent.getId('_action_layer_').style.display = 'none';
}
var startTop = 0;
var startLeft = 0;
function getLayerBox(url,title,w,h,e,ar,direction)
{
var ly = getId('_box_layer_');
ly.className = 'mbrLayerBlock';
ly.style.width = w+'px';
ly.style.height = h+'px';
ly.style.display = 'block';
ly.style.zIndex = '100';
if (e)
{
var xy = getEventBoxPos(e);
}
else {
var xy = new Object();
xy.x = parseInt(document.body.clientWidth/2) - parseInt(w/2);
xy.y = parseInt(screen.availHeight/2) - parseInt(h/2);
}
var bx = getOfs(ly);
direction = direction ? direction : 'r';
if (direction=='r')
{
ly.style.top = (xy.y - 50) + 'px';
ly.style.left = (xy.x + 10) + 'px';
}
if (direction=='l')
{
ly.style.top = (xy.y - 50) + 'px';
ly.style.left = (xy.left - 12 - w) + 'px';
}
if (direction=='b')
{
ly.style.top = (xy.y + 10) + 'px';
ly.style.left = (xy.left+parseInt((xy.x-xy.left)/2)-parseInt(w/2)) - 7 + 'px';
}
if (direction=='t')
{
ly.style.top = (xy.top - h - 11) + 'px';
ly.style.left = (xy.left+parseInt((xy.x-xy.left)/2)-parseInt(w/2)) - 7 + 'px';
}
if(parseInt(ly.style.top) < 0) ly.style.top = '10px';
var tags = '';
if (ar==true)
{
if(direction=='r')tags += '<div style="width:1px;height:1px;position:absolute;"><img src="'+rooturl+'/_core/image/_public/arr_left.gif" alt="" style="position:relative;top:30px;left:-8px;" /></div>';
if(direction=='l')tags += '<div style="width:1px;height:1px;position:absolute;"><img src="'+rooturl+'/_core/image/_public/arr_right.gif" alt="" style="position:relative;top:30px;left:'+(w)+'px;" /></div>';
if(direction=='b')tags += '<div style="width:1px;height:1px;position:absolute;"><img src="'+rooturl+'/_core/image/_public/arr_top.gif" alt="" style="position:relative;top:-8px;left:'+parseInt(w/2)+'px;" /></div>';
if(direction=='t')tags += '<div style="width:1px;height:1px;position:absolute;"><img src="'+rooturl+'/_core/image/_public/arr_bottom.gif" alt="" style="position:relative;top:'+(h)+'px;left:'+parseInt(w/2)+'px;" /></div>';
}
tags += '<div style="height:30px;background:#efefef;">';
tags += '<div style="float:left;"><span id="_layer_title_" style="display:block;padding:9px 0 0 10px;font-weight:bold;color:#202020;">'+title+'</span></div>';
tags += '<div style="float:right;"><img src="'+rooturl+'/_core/image/_public/ico_x_01.gif" style="padding:8px 8px 8px 8px;cursor:pointer;" alt="" title="닫기(단축키:ESC)" onclick="getLayerBoxHide();" /></div>';
tags += '<div class="clear"></div>';
tags +='</div>';
tags += '<iframe id="_box_frame_" src="'+url+'" width="100%" height="'+(h-30)+'" frameborder="0"></iframe>';
ly.innerHTML = tags;
if (e=='')
{
startTop = parseInt(ly.style.top);
startLeft = parseInt(ly.style.left);
getLayerBoxMove();
//setInterval('getLayerBoxMove();',100);
}
}
function getLayerBoxMove()
{
var ly = getId('_box_layer_');
var lt = (document.documentElement.scrollLeft || document.body.scrollLeft);
var tp = (document.documentElement.scrollTop || document.body.scrollTop);
ly.style.left = (startLeft+lt) + 'px';
ly.style.top = (startTop+tp) + 'px';
}
function getLayerBoxHide()
{
showMemberLayer();
getId('_box_layer_').innerHTML = '';
getId('_box_layer_').style.display = 'none';
$('#_modal_bg_').remove();
$('body').unbind('mousewheel');
}
function getLayerBoxModal(url,title,w,h,e,ar,direction) {
var hWin = $(window).height();
var hBody = $('body').height();
hBody = hBody > hWin ? hBody : hWin;
$('body').append('<div id="_modal_bg_" style="height:'+hBody+'px;" onclick="hideImgLayer()"></div>');
var height = h>0 ? h : hWin-200;
getLayerBox(url,title,w,height,e,ar,direction);
$('#_box_layer_').css('position', 'fixed');
$('#_box_layer_').css('top', '100px');
$('body').bind('mousewheel', function(event, delta, deltaX, deltaY){event.preventDefault();});
}
function hideImgLayer()
{
if(getId('_box_layer_').innerHTML == '') closeMemberLayer();
getId('_box_layer_').style.display = 'none';
getId('_box_layer_').innerHTML = '';
$('#_modal_bg_').remove();
$('body').unbind('mousewheel');
}
function closeImgLayer(e)
{
var k = checkKeycode(e);
if (parent.getId('_box_layer_'))
{
switch (k)
{
case 27 : parent.hideImgLayer(); break;
}
}
else {
switch (k)
{
case 27 : hideImgLayer(); break;
}
}
}
function hubTab(mod,layer,option,obj)
{
var i;
var xy = getOfs(getId(layer));
if(obj)
{
for (i = 0; i < obj.parentNode.children.length; i++)
if(obj.parentNode.children[i].className != 'more') obj.parentNode.children[i].className = obj.parentNode.children[i].className.replace('on','');
obj.className = obj.className.indexOf('ls') != -1 ? 'ls on' : 'on';
}
getId(layer).innerHTML = '<div style="text-align:center;padding-top:'+(parseInt(xy.height/2)-30)+'px;"><img src="'+rooturl+'/_core/image/loading/white_big.gif" alt="" /></div>';
setTimeout("hubTabLoad('"+mod+"','"+layer+"','"+option+"');",1);
//hubTabLoad(mod,layer,option);
}
function hubTabLoad(type,layer,option)
{
var result = getHttprequest(rooturl+'/?r='+raccount+'&system=layer.member1&iframe=Y&type='+type+'&option='+option);
getId(layer).innerHTML=getAjaxFilterString(result,'RESULT');
}
function iPopup(url,iframe,w,h,scroll,st)
{
var ow = (parseInt(document.body.clientWidth/2) - parseInt(w/2)) + 'px';
var nw = window.open(url+(iframe?'&iframe='+iframe:'')+(st?'&_style_='+escape(st):''),'_iPopup_','left='+ow+'px,top=100px,width='+w+'px,height='+h+'px,status=yes,scrollbars='+scroll+',toolbar=no');
}
function copyToClipboard(str)
{
if(window.clipboardData)
{
window.clipboardData.setData('text', str);
alert('복사되었습니다. ');
}
else window.prompt("Ctrl+C 를 누른다음 Enter를 치시면 복사됩니다.", str);
}
function crLayer(title,msg,flag,w,h,t)
{
scrollTo(0,0);
var ow = (parseInt(document.body.clientWidth/2) - parseInt(w/2)) + 'px';
var html = '';
html += '<div id="_modal_bg_" style="position:absolute;z-index:10000;top:0;left:0;width:100%;height:100%;background:#000000;filter:alpha(opacity=80);opacity:0.8;"></div>';
html += '<div id="_modal_on_" style="position:absolute;z-index:10001;top:'+t+';left:'+ow+';width:'+w+'px;'+(h?'height:'+h+'px;':'')+'background:#ffffff;border:#333333 solid 2px;">';
html += ' <div style="background:#F4F4F4;font-weight:bold;padding:10px 0 10px 20px;">'+title;
if(flag=='wait') html += ' <img src="'+rooturl+'/_core/image/loading/white_small.gif" alt="" style="float:right;position:relative;left:-13px;" />';
else html += ' <img src="'+rooturl+'/_core/image/_public/ico_x_01.gif" alt="" onclick="crLayerClose();" style="float:right;position:relative;left:-10px;cursor:pointer;" />';
html += '</div>';
html += ' <div style="'+(flag=='iframe'?'padding:0;':'padding:20px 20px 20px 20px;line-height:140%;color:#555555;')+'">';
html += flag=='iframe'?'<iframe src="'+msg+'" width="100%" frameborder="0" style="border-top:#dfdfdf solid 1px;'+(h?'height:'+(h-35)+'px;':'')+'"></iframe>':msg;
if(flag=='close') html += '<div style="border-top:#dfdfdf solid 1px;padding-top:15px;margin-top:15px;"><a href="#." onclick="crLayerClose();" class="btnGray01 noIcon txtCenter" style="width:80px;margin-left:'+(parseInt(w/2)-65)+'px;cursor:pointer;"><i><s> 확인 </s></i></a></div>';
html += ' </div>';
html += '</div>';
getId('_overLayer_').innerHTML = html;
getId('_overLayer_').className = '';
document.body.style.overflow = 'hidden';
}
function crLayerClose()
{
getId('_overLayer_').className = 'hide';
document.body.style.overflow = 'auto';
}
//
// 이미지 페이드 처리
function fadeImage(prm){
var isfade = false;
var iswrap = prm.wrap ? prm.wrap : false;
var id = prm.id;
var navi_use = prm.navi_use;
var navi_pos = prm.navi_pos;
var interval = prm.interval ? prm.interval : 4000;
var $first = $('#'+id).find('.first >img');
var $items = $('#'+id).find('.bg');
var $navi = $('#'+id).find('.navi>ul>li');
// member function
this.moveTo = function(idx){_moveTo(idx);}
// overide
$(window).load(function(){
if(!$first.height())
$first = $('#'+id).find('.first>a>img');
$('#'+id).css('height',$first.height()+'px');
$items.css('position','absolute');
$items.css('width',$('#'+id).width()+'px');
if(navi_use)
_addNavi();
setTimeout(function(){_fade(id);},interval);
});
function _moveTo(idx) {
if(idx < 0) return;
var _idx = idx;
$('#'+id).attr('_idx',_idx);
$($items).hide();
$($items[_idx]).show();
if($navi.length){
$($navi).removeClass('on');
$($navi[_idx]).addClass('on');
}
isfade = true;
$navi.mouseout(function(){isfade = false;});
}
function _addNavi() {
var style = '';
switch(navi_pos) {
case 'br':
style = 'float:right; padding:'+($first.height()-40)+'px 10px 0px 0px;';
break;
case 'bl':
style = 'padding:'+($first.height()-40)+'px 0px 0px 10px;';
break;
case 'tr':
style = 'float:right; padding:10px 10px 0px 0px;';
break;
case 'tl':
default:
style = 'padding-top:10px 0px 0px 10px;';
break;
}
var li = '<div class="navi'+ (iswrap ? ' wrap' : '') +'"><ul style="'+ style +'">';
for(i=0; i<$items.length; i++) {
li += '<li '+ (i ? '' : 'class="on" ') +' onmouseover="'+id+'.moveTo('+i+');"><span class="glyphicon glyphicon-stop"></span></li>'
}
li += '</ul><div class="clear"></div></div>';
$('#'+id).append(li);
$navi = $('#'+id).find('.navi>ul>li');
}
function _fade(id){
if(isfade){
setTimeout(function(){_fade(id);},interval);
return;
}
if($items.length <= 1) return;
var _idx = $('#'+id).attr('_idx');
_idx = _idx ? Number(_idx)+1 : 1;
_idx = _idx >= $items.length ? 0 : _idx;
$('#'+id).attr('_idx',_idx);
$($items).fadeOut(1000);
$($items[_idx]).fadeIn(1000);
if($navi.length){
$($navi).removeClass('on');
$($navi[_idx]).addClass('on');
}
setTimeout(function(){_fade(id);},interval);
}
}
// 엔터값 체크
function skipEnter() {
var code = window.event.keyCode
if(code == 13)
return false;
} | gitkhs/cms-kq | _core/js/sys.js | JavaScript | lgpl-2.1 | 21,910 |
/*
* Copyright (C) 2011 JTalks.org Team
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
* This library 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
* Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* This is a central class for creation dialog windows in the project. Each dialog consists of three parts: header, body, footer.
* For each of these parts there is a function that generates the content: rootPanelFunc, bodyContentFunc, footerContentFunc,
* you can override them for your particular dialog. The main method of creating the Dialog is 'createDialog' where you can
* specify your custom configuration parameters. Note, that each parameter has a default option and if you don't override it, then default will be taken.
* Also, there are 3 types of dialogs: alert, info, confirm with predefined markup and functions. E.g. to create an alert, write this:
* jDialog.createDialog({
* type: jDialog.alertType,
* bodyMessage: 'some message'
* });
*
* Options.
* tabNavigation - this option sets the order of elements that get focused when user presses TAB, you just need to specify a list of selectors here
* Example:
* jDialog.createDialog({
* ...
* tabNavigation : ['#fieldId', '.className', 'input[name="fieldName"]', etc.]
* ...
* })
* handlers - a list of objects to configure a UI event and the function to process this event. Instead of passing actual functions, you can use mnemonics
* (predefined names functions). Example of both:
* handlers: {
* '#signin-submit-button': {'click': sendLoginPost, 'keydown': someFunc, ...}
* '#signin-cancel-button': 'close'
* }
* handlersDelegate & handlersLive - same purpose as 'handlers', but instead of 'onSomeEvent' functions JQuery uses 'delegate' and 'live' functions.
* This is needed when while dialog creation
* you don't yet have elements to describe events for (these elements are dynamically created after the dialog is already in place)
*/
var jDialog = {};
$(function () {
//types of dialog
jDialog.confirmType = 'confirm';
jDialog.alertType = 'alert';
jDialog.infoType = 'info';
jDialog.options = {};
jDialog.dialog;
jDialog.rootPanelFunc = function () {
var dialog = $(' \
<form style="display: none" method="post" class="modal" id="' + jDialog.options.dialogId + '" tabindex="-1" role="dialog" \
aria-hidden="true"> \
<div class="modal-header"> \
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button> \
<h3>' + jDialog.options.title + '</h3> \
</div> \
' + jDialog.bodyContentFunc() + ' \
' + jDialog.footerContentFunc() + ' \
</form> \
');
return dialog;
};
jDialog.bodyContentFunc = function () {
var body = '<div class="modal-body">';
switch (jDialog.options.type) {
case jDialog.alertType :
case jDialog.confirmType :
{
body += '<div class="dialog-message"><h4>' + jDialog.options.bodyMessage + '</h4></div>';
break;
}
default :
{
body += jDialog.options.bodyContent;
break;
}
}
return body + '</div>';
};
jDialog.footerContentFunc = function () {
var footer = '<div class="modal-footer">';
switch (jDialog.options.type) {
case jDialog.alertType :
{
footer += '<button id="' + jDialog.options.alertDefaultBut + '" class="btn btn-primary">' + $labelOk
+ '</button>';
break;
}
default :
{
footer += jDialog.options.footerContent;
break;
}
}
return footer + '</div>';
};
var body = $('body');
jDialog.closeDialog = function () {
jDialog.dialog.modal('hide');
jDialog.dialog.remove();
body.css('overflow','auto');
};
//if user sets options with name which exists in default then default option overridden, else adds
jDialog.defaultOptions = {
'type': jDialog.infoType,
'dialogId': '',
//for header height
'title': ' ',
'rootPanelFunc': jDialog.rootPanelFunc,
'bodyContentFunc': jDialog.bodyContentFunc,
'footerContentFunc': jDialog.footerContentFunc,
'closeDialog': jDialog.closeDialog,
'bodyContent': '',
//for confirm, alert types
'bodyMessage': '',
'footerContent': '',
'maxWidth': 300,
'maxHeight': 400,
'overflow': 'auto', //The "overflow: auto" fixes the problem of small screens for other dialogs.
'overflowBody': 'hidden',
'modal' : true,
//first element focus
'firstFocus': true,
'tabNavigation': [],
//contained selector of object (key of object), handler to object (value of object)
'handlers': {},
'handlersDelegate': {},
'handlersLive': {},
'dialogKeydown': Keymaps.defaultDialog,
'alertDefaultBut': 'alert-ok',
'backdrop': 'static'
};
jDialog.createDialog = function (opts) {
if (jDialog.dialog) {
jDialog.closeDialog();
}
body.css('overflow','hidden');
//merge default options and users option
jDialog.options = $.extend({}, jDialog.defaultOptions, opts);
jDialog.dialog = jDialog.rootPanelFunc();
var enforceModalFocusFn = $.fn.modal.Constructor.prototype.enforceFocus;
if (jDialog.options.modal == false) {
jDialog.options.backdrop = false;
// this code removes "enforce focus" mechanism when user can't select any input outside the dialog
// Dialog becomes non-modal
$.fn.modal.Constructor.prototype.enforceFocus = function() {};
}
//modal function is bootstrap
jDialog.dialog.modal({
'backdrop' : jDialog.options.backdrop,
'keyboard': false,
'show': false
}).css(
{'max-width': jDialog.options.maxWidth,
'max-height': jDialog.options.maxHeight,
'overflow': jDialog.options.overflow}
);
//we need add element to calculate width and height
body.append(jDialog.dialog);
jDialog.resizeDialog(jDialog.dialog);
jDialog.dialog.modal('show');
addHandlers();
if (jDialog.options.firstFocus && jDialog.options.type == jDialog.infoType) {
jDialog.focusFirstElement();
}
// html5 placeholder emulation for old IE
jDialog.dialog.find('input[placeholder]').placeholder();
$(jDialog.dialog).on('hidden', function() {
$.fn.modal.Constructor.prototype.enforceFocus = enforceModalFocusFn;
});
return jDialog.dialog;
};
/*
* first elemnts it is element which have class "first",
* or first "input" element, or first "button"
*/
jDialog.focusFirstElement = function () {
var firsts = ['.first', 'input:first', 'button:first'];
var first;
$.each(firsts, function (idx, v) {
first = jDialog.dialog.find(v);
if (first.length != 0) {
first.focus();
return false;
}
});
};
//methods to dialogs
jDialog.resizeDialog = function (dialog) {
if (dialog) {
dialog.css("top","50%");
dialog.css("margin-top", function () {
return $(this).outerHeight() / 2 * (-1)
});
// Starting from 480px class "modal" has new properties (see details in bootstrap-responsive.css).
// In this case when we call the resizeDialog function right after the dialog creation
// actually size of the dialog is not calculated yet so we should just leave
// default value for the "left" = 10px. New value will be calculated
// during the next window resize event.
if ($(window).width() > 480) { //The bootstrup .modal class has this styles, but ...
dialog.css("left","50%"); //... has not correct behavior when the screen is small.
dialog.css("margin-left", function () {
return $(this).outerWidth() / 2 * (-1)
});
}
}
};
/**
* Enable all disabled elements
* Remove previous errors
* Show hidden hel text
*/
jDialog.prepareDialog = function (dialog) {
dialog.find('*').attr('disabled', false);
dialog.find('._error').remove();
dialog.find(".help-block").show();
dialog.find('.control-group').removeClass('error');
};
var capitaliseFirstLetter = function (string)
{
return string.charAt(0).toUpperCase() + string.slice(1);
};
/**
* Show errors under fields with errors
* Errors overrides help text (help text will be hidden)
*/
jDialog.showErrors = function (dialog, errors, idPrefix, idPostfix) {
ErrorUtils.removeAllErrorMessages();
for (var i = 0; i < errors.length; i++) {
var idField = '#' + idPrefix + errors[i].field + idPostfix;
if (idPrefix.length > 0 && $(idField).length == 0) {
idField = '#' + idPrefix + capitaliseFirstLetter(errors[i].field) + idPostfix;
}
ErrorUtils.addErrorMessage(idField, errors[i].defaultMessage);
}
jDialog.resizeDialog(dialog);
};
var addHandlers = function () {
$('.modal-backdrop').live('click', function (e) {
jDialog.options.closeDialog();
});
jDialog.dialog.find('.close').bind('click', function (e) {
jDialog.options.closeDialog();
});
jDialog.dialog.on('keydown', jDialog.options.dialogKeydown);
if (jDialog.options.type == jDialog.alertType) {
tabNavigation([jDialog.options.alertDefaultBut]);
$('#' + jDialog.options.alertDefaultBut).on('click', getStaticHandler('close'))
}
$.each(jDialog.options.handlers, function (k, v) {
$.each(v, function (ke, ve) {
if (ke == 'static') {
$(k).on('click', getStaticHandler(ve))
} else {
$(k).on(ke, ve);
}
})
});
$.each(jDialog.options.handlersDelegate, function (k, v) {
$.each(v, function (ke, ve) {
if (ke == 'static') {
$(document).delegate(k, 'click', getStaticHandler(ve));
} else {
$(document).delegate(k, ke, ve);
}
}
)
});
$.each(jDialog.options.handlersLive, function (k, v) {
$.each(v, function (ke, ve) {
if (ke == 'static') {
$(document).live(k, 'click', getStaticHandler(ve));
} else {
$(document).live(k, ke, ve);
}
})
});
tabNavigation(jDialog.options.tabNavigation);
};
var tabNavigation = function (selectors) {
$.each(selectors, function (idx, v) {
var func = function (e) {
if ((e.keyCode || e.charCode) == tabCode) {
e.preventDefault();
nextTabElm(selectors, idx).focus();
}
};
$(v).on('keydown', func);
});
};
var getStaticHandler = function (key) {
switch (key) {
case 'close':
return function(e) {
e.preventDefault();
jDialog.options.closeDialog();
};
break;
}
};
var nextTabElm = function (els, curIdx) {
if (els.length == curIdx + 1) {
return jDialog.dialog.find(els[0]);
} else {
return jDialog.dialog.find(els[curIdx + 1])
}
}
}
)
;
| a-nigredo/jcommune | jcommune-view/jcommune-web-view/src/main/webapp/resources/javascript/app/dialog.js | JavaScript | lgpl-2.1 | 13,856 |
/*!
* TableDnD plug-in for JQuery, allows you to drag and drop table rows
* You can set up various options to control how the system will work
* Copyright (c) Denis Howlett <denish@isocra.com>
* Licensed like jQuery, see http://docs.jquery.com/License.
*/
/**
* Configuration options:
*
* onDragStyle
* This is the style that is assigned to the row during drag. There are limitations to the styles that can be
* associated with a row (such as you can't assign a border--well you can, but it won't be
* displayed). (So instead consider using onDragClass.) The CSS style to apply is specified as
* a map (as used in the jQuery css(...) function).
* onDropStyle
* This is the style that is assigned to the row when it is dropped. As for onDragStyle, there are limitations
* to what you can do. Also this replaces the original style, so again consider using onDragClass which
* is simply added and then removed on drop.
* onDragClass
* This class is added for the duration of the drag and then removed when the row is dropped. It is more
* flexible than using onDragStyle since it can be inherited by the row cells and other content. The default
* is class is tDnD_whileDrag. So to use the default, simply customise this CSS class in your
* stylesheet.
* onDrop
* Pass a function that will be called when the row is dropped. The function takes 2 parameters: the table
* and the row that was dropped. You can work out the new order of the rows by using
* table.rows.
* onDragStart
* Pass a function that will be called when the user starts dragging. The function takes 2 parameters: the
* table and the row which the user has started to drag.
* onAllowDrop
* Pass a function that will be called as a row is over another row. If the function returns true, allow
* dropping on that row, otherwise not. The function takes 2 parameters: the dragged row and the row under
* the cursor. It returns a boolean: true allows the drop, false doesn't allow it.
* scrollAmount
* This is the number of pixels to scroll if the user moves the mouse cursor to the top or bottom of the
* window. The page should automatically scroll up or down as appropriate (tested in IE6, IE7, Safari, FF2,
* FF3 beta
* dragHandle
* This is the name of a class that you assign to one or more cells in each row that is draggable. If you
* specify this class, then you are responsible for setting cursor: move in the CSS and only these cells
* will have the drag behaviour. If you do not specify a dragHandle, then you get the old behaviour where
* the whole row is draggable.
*
* Other ways to control behaviour:
*
* Add class="nodrop" to any rows for which you don't want to allow dropping, and class="nodrag" to any rows
* that you don't want to be draggable.
*
* Inside the onDrop method you can also call $.tableDnD.serialize() this returns a string of the form
* <tableID>[]=<rowID1>&<tableID>[]=<rowID2> so that you can send this back to the server. The table must have
* an ID as must all the rows.
*
* Other methods:
*
* $("...").tableDnDUpdate()
* Will update all the matching tables, that is it will reapply the mousedown method to the rows (or handle cells).
* This is useful if you have updated the table rows using Ajax and you want to make the table draggable again.
* The table maintains the original configuration (so you don't have to specify it again).
*
* $("...").tableDnDSerialize()
* Will serialize and return the serialized string as above, but for each of the matching tables--so it can be
* called from anywhere and isn't dependent on the currentTable being set up correctly before calling
*
* Known problems:
* - Auto-scoll has some problems with IE7 (it scrolls even when it shouldn't), work-around: set scrollAmount to 0
*
* Version 0.2: 2008-02-20 First public version
* Version 0.3: 2008-02-07 Added onDragStart option
* Made the scroll amount configurable (default is 5 as before)
* Version 0.4: 2008-03-15 Changed the noDrag/noDrop attributes to nodrag/nodrop classes
* Added onAllowDrop to control dropping
* Fixed a bug which meant that you couldn't set the scroll amount in both directions
* Added serialize method
* Version 0.5: 2008-05-16 Changed so that if you specify a dragHandle class it doesn't make the whole row
* draggable
* Improved the serialize method to use a default (and settable) regular expression.
* Added tableDnDupate() and tableDnDSerialize() to be called when you are outside the table
*/
jQuery.tableDnD = {
/** Keep hold of the current table being dragged */
currentTable : null,
/** Keep hold of the current drag object if any */
dragObject: null,
/** The current mouse offset */
mouseOffset: null,
/** Remember the old value of Y so that we don't do too much processing */
oldY: 0,
/** Actually build the structure */
build: function(options) {
// Set up the defaults if any
this.each(function() {
// This is bound to each matching table, set up the defaults and override with user options
this.tableDnDConfig = jQuery.extend({
onDragStyle: null,
onDropStyle: null,
// Add in the default class for whileDragging
onDragClass: "tDnD_whileDrag",
onDrop: null,
onDragStart: null,
scrollAmount: 5,
serializeRegexp: /[^\-]*$/, // The regular expression to use to trim row IDs
serializeParamName: null, // If you want to specify another parameter name instead of the table ID
dragHandle: null // If you give the name of a class here, then only Cells with this class will be draggable
}, options || {});
// Now make the rows draggable
jQuery.tableDnD.makeDraggable(this);
});
// Now we need to capture the mouse up and mouse move event
// We can use bind so that we don't interfere with other event handlers
jQuery(document)
.bind('mousemove', jQuery.tableDnD.mousemove)
.bind('mouseup', jQuery.tableDnD.mouseup);
// Don't break the chain
return this;
},
/** This function makes all the rows on the table draggable apart from those marked as "NoDrag" */
makeDraggable: function(table) {
var config = table.tableDnDConfig;
if (table.tableDnDConfig.dragHandle) {
// We only need to add the event to the specified cells
var cells = jQuery("td."+table.tableDnDConfig.dragHandle, table);
cells.each(function() {
// The cell is bound to "this"
jQuery(this).mousedown(function(ev) {
jQuery.tableDnD.dragObject = this.parentNode;
jQuery.tableDnD.currentTable = table;
jQuery.tableDnD.mouseOffset = jQuery.tableDnD.getMouseOffset(this, ev);
if (config.onDragStart) {
// Call the onDrop method if there is one
config.onDragStart(table, this);
}
return false;
});
})
} else {
// For backwards compatibility, we add the event to the whole row
var rows = jQuery("tr", table); // get all the rows as a wrapped set
rows.each(function() {
// Iterate through each row, the row is bound to "this"
var row = jQuery(this);
if (! row.hasClass("nodrag")) {
row.mousedown(function(ev) {
if (ev.target.tagName == "TD") {
jQuery.tableDnD.dragObject = this;
jQuery.tableDnD.currentTable = table;
jQuery.tableDnD.mouseOffset = jQuery.tableDnD.getMouseOffset(this, ev);
if (config.onDragStart) {
// Call the onDrop method if there is one
config.onDragStart(table, this);
}
return false;
}
}).css("cursor", "move"); // Store the tableDnD object
}
});
}
},
updateTables: function() {
this.each(function() {
// this is now bound to each matching table
if (this.tableDnDConfig) {
jQuery.tableDnD.makeDraggable(this);
}
})
},
/** Get the mouse coordinates from the event (allowing for browser differences) */
mouseCoords: function(ev){
if(ev.pageX || ev.pageY){
return {x:ev.pageX, y:ev.pageY};
}
return {
x:ev.clientX + document.body.scrollLeft - document.body.clientLeft,
y:ev.clientY + document.body.scrollTop - document.body.clientTop
};
},
/** Given a target element and a mouse event, get the mouse offset from that element.
To do this we need the element's position and the mouse position */
getMouseOffset: function(target, ev) {
ev = ev || window.event;
var docPos = this.getPosition(target);
var mousePos = this.mouseCoords(ev);
return {x:mousePos.x - docPos.x, y:mousePos.y - docPos.y};
},
/** Get the position of an element by going up the DOM tree and adding up all the offsets */
getPosition: function(e){
var left = 0;
var top = 0;
/** Safari fix -- thanks to Luis Chato for this! */
if (e.offsetHeight == 0) {
/** Safari 2 doesn't correctly grab the offsetTop of a table row
this is detailed here:
http://jacob.peargrove.com/blog/2006/technical/table-row-offsettop-bug-in-safari/
the solution is likewise noted there, grab the offset of a table cell in the row - the firstChild.
note that firefox will return a text node as a first child, so designing a more thorough
solution may need to take that into account, for now this seems to work in firefox, safari, ie */
e = e.firstChild; // a table cell
}
while (e.offsetParent){
left += e.offsetLeft;
top += e.offsetTop;
e = e.offsetParent;
}
left += e.offsetLeft;
top += e.offsetTop;
return {x:left, y:top};
},
mousemove: function(ev) {
if (jQuery.tableDnD.dragObject == null) {
return;
}
var dragObj = jQuery(jQuery.tableDnD.dragObject);
var config = jQuery.tableDnD.currentTable.tableDnDConfig;
var mousePos = jQuery.tableDnD.mouseCoords(ev);
var y = mousePos.y - jQuery.tableDnD.mouseOffset.y;
//auto scroll the window
var yOffset = window.pageYOffset;
if (document.all) {
// Windows version
//yOffset=document.body.scrollTop;
if (typeof document.compatMode != 'undefined' &&
document.compatMode != 'BackCompat' ) {
yOffset = document.documentElement.scrollTop;
}
else if (typeof document.body != 'undefined' ) {
yOffset=document.body.scrollTop;
}
}
if (mousePos.y-yOffset < config.scrollAmount) {
window.scrollBy(0, -config.scrollAmount);
} else {
var windowHeight = window.innerHeight ? window.innerHeight
: document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.clientHeight;
if (windowHeight-(mousePos.y-yOffset) < config.scrollAmount) {
window.scrollBy(0, config.scrollAmount);
}
}
if (y != jQuery.tableDnD.oldY) {
// work out if we're going up or down...
var movingDown = y > jQuery.tableDnD.oldY;
// update the old value
jQuery.tableDnD.oldY = y;
// update the style to show we're dragging
if (config.onDragClass) {
dragObj.addClass(config.onDragClass);
} else {
dragObj.css(config.onDragStyle);
}
// If we're over a row then move the dragged row to there so that the user sees the
// effect dynamically
var currentRow = jQuery.tableDnD.findDropTargetRow(dragObj, y);
if (currentRow) {
// TODO worry about what happens when there are multiple TBODIES
if (movingDown && jQuery.tableDnD.dragObject != currentRow) {
jQuery.tableDnD.dragObject.parentNode.insertBefore(jQuery.tableDnD.dragObject, currentRow.nextSibling);
} else if (! movingDown && jQuery.tableDnD.dragObject != currentRow) {
jQuery.tableDnD.dragObject.parentNode.insertBefore(jQuery.tableDnD.dragObject, currentRow);
}
}
}
return false;
},
/** We're only worried about the y position really, because we can only move rows up and down */
findDropTargetRow: function(draggedRow, y) {
var rows = jQuery.tableDnD.currentTable.rows;
for (var i=0; i<rows.length; i++) {
var row = rows[i];
var rowY = this.getPosition(row).y;
var rowHeight = parseInt(row.offsetHeight)/2;
if (row.offsetHeight == 0) {
rowY = this.getPosition(row.firstChild).y;
rowHeight = parseInt(row.firstChild.offsetHeight)/2;
}
// Because we always have to insert before, we need to offset the height a bit
if ((y > rowY - rowHeight) && (y < (rowY + rowHeight))) {
// that's the row we're over
// If it's the same as the current row, ignore it
if (row == draggedRow) {return null;}
var config = jQuery.tableDnD.currentTable.tableDnDConfig;
if (config.onAllowDrop) {
if (config.onAllowDrop(draggedRow, row)) {
return row;
} else {
return null;
}
} else {
// If a row has nodrop class, then don't allow dropping (inspired by John Tarr and Famic)
var nodrop = jQuery(row).hasClass("nodrop");
if (! nodrop) {
return row;
} else {
return null;
}
}
return row;
}
}
return null;
},
mouseup: function(e) {
if (jQuery.tableDnD.currentTable && jQuery.tableDnD.dragObject) {
var droppedRow = jQuery.tableDnD.dragObject;
var config = jQuery.tableDnD.currentTable.tableDnDConfig;
// If we have a dragObject, then we need to release it,
// The row will already have been moved to the right place so we just reset stuff
if (config.onDragClass) {
jQuery(droppedRow).removeClass(config.onDragClass);
} else {
jQuery(droppedRow).css(config.onDropStyle);
}
jQuery.tableDnD.dragObject = null;
if (config.onDrop) {
// Call the onDrop method if there is one
config.onDrop(jQuery.tableDnD.currentTable, droppedRow);
}
jQuery.tableDnD.currentTable = null; // let go of the table too
}
},
serialize: function() {
if (jQuery.tableDnD.currentTable) {
return jQuery.tableDnD.serializeTable(jQuery.tableDnD.currentTable);
} else {
return "Error: No Table id set, you need to set an id on your table and every row";
}
},
serializeTable: function(table) {
var result = "";
var tableId = table.id;
var rows = table.rows;
for (var i=0; i<rows.length; i++) {
if (result.length > 0) result += "&";
var rowId = rows[i].id;
if (rowId && rowId && table.tableDnDConfig && table.tableDnDConfig.serializeRegexp) {
rowId = rowId.match(table.tableDnDConfig.serializeRegexp)[0];
}
result += tableId + '[]=' + rowId;
}
return result;
},
serializeTables: function() {
var result = "";
this.each(function() {
// this is now bound to each matching table
result += jQuery.tableDnD.serializeTable(this);
});
return result;
}
}
jQuery.fn.extend(
{
tableDnD : jQuery.tableDnD.build,
tableDnDUpdate : jQuery.tableDnD.updateTables,
tableDnDSerialize: jQuery.tableDnD.serializeTables
}
);
| jinshana/tangocms | assets/js/jQuery/plugins/dnd.src.js | JavaScript | lgpl-2.1 | 16,674 |
(function(){var __modFun = function(__require, promiseland){ __modFun = undefined;
var classSystem = promiseland.classSystem;
if (promiseland._hasModule({ hashStr: "b9f8ed0c9d353bb6c2c3688ec475e4a8" })){ return promiseland._getModule("b9f8ed0c9d353bb6c2c3688ec475e4a8"); };
var PL$1 = (function(){
"use strict";
var PL$3/*C2*/;
var PL$8/*b*/;
var PL$6/*C1*/;
var PL$9/*v1*/;
/* ---------------------------- */
/* type C2 */
var PL$2/*type:C2*/ = classSystem._createProvisionalClass();
PL$3/*C2*/ = PL$2/*type:C2*/
var PL$4/*C2-constructor*/ = undefined;
classSystem.readyPromise(PL$2/*type:C2*/).then(function(parType){
PL$2/*type:C2*/ = parType;
PL$4/*C2-constructor*/ = classSystem.getTypeConstructor(PL$2/*type:C2*/);
});
/* ---------------------------- */
/* ---------------------------- */
/* type C1 */
var PL$5/*type:C1*/ = classSystem._createProvisionalClass();
PL$6/*C1*/ = PL$5/*type:C1*/
var PL$7/*C1-constructor*/ = undefined;
classSystem.readyPromise(PL$5/*type:C1*/).then(function(parType){
PL$5/*type:C1*/ = parType;
PL$7/*C1-constructor*/ = classSystem.getTypeConstructor(PL$5/*type:C1*/);
});
/* ---------------------------- */
;
classSystem._resolveProvisional(PL$2/*type:C2*/, classSystem.createClass({className: "C2",members: [{"name":"a","type":classSystem.getBuiltinType("var")}], "extends": [], "hasFreePart": true, "hashStr": "b9f8ed0c9d353bb6c2c3688ec475e4a8", "name": "C2"}, {"a": 2}));PL$3/*C2*/;
PL$8/*b*/ = new PL$4/*C2-constructor*/();
PL$8/*b*/[3] = 3;
classSystem._resolveProvisional(PL$5/*type:C1*/, classSystem.createClass({className: "C1",members: [{"name":"a","type":PL$2/*type:C2*/},{"name":"b","type":classSystem.getBuiltinType("var")}], "extends": [], "hasFreePart": true, "hashStr": "b9f8ed0c9d353bb6c2c3688ec475e4a8", "name": "C1"}, {"a": new PL$4/*C2-constructor*/(), "b": (function(){
;
this[3] = PL$8/*b*/;
;})}));PL$6/*C1*/;
PL$9/*v1*/ = new PL$7/*C1-constructor*/();
PL$9/*v1*/[4]();
if((PL$9/*v1*/[3][3] == 3)){
return {
"success": true
};
};
;
return {
"success": false
};
;})();
;return PL$1;
};
if (typeof exports == "object" && typeof module == "object"){ // CommonJS
module.exports = __modFun(function(modulesAr, callback, errBack){
// the require function for CommonJs
var args = [];
try{
var i = 0;
var l = modulesAr.length;
for (i; i < l; ++i){
args.push(require(modulesAr[i]));
};
}catch(e){
errBack(e);
return;
};
callback.apply(callback, args);
}, require("promiseland"));
}else if (typeof define == "function" && define.amd){ // AMD
define(["require", "promiseland"], __modFun);
}else{ // Plain browser env
__modFun(function(){ throw { msg: "require not possible in non loader mode" }; });
};
})();
| soliton4/promiseland | test/test/typesafetyMemberFunction2.js | JavaScript | lgpl-3.0 | 2,861 |
// Monkey patching in Date.now in case it's not here already
// This is for IE8-. In IE9+ ( even IE9 w/ IE8 compatability mode on ) this works
// just fine.
Date.now = Date.now || function() { return +new Date; };
// JavaScript Document
Ext.namespace('CCR', 'CCR.xdmod', 'CCR.xdmod.ui', 'CCR.xdmod.ui.dd', 'XDMoD', 'XDMoD.constants', 'XDMoD.Module', 'XDMoD.regex', 'XDMoD.validator', 'XDMoD.utils', 'CCR.xdmod.reporting');
// ==============================================================
XDMoD.Tracking = {
sequence_index: 0,
timestamp: new Date().getTime(),
suppress_close_handler: false
};
XDMoD.TrackEvent = function (category, action, details, suppress_close_handler) {
// Tracking is not implemented outside of the XSEDE XDMoD instance.
if (!CCR.xdmod.features) {
return;
}
if (!CCR.xdmod.features.xsede) {
return;
}
details = details || '';
suppress_close_handler = suppress_close_handler || false;
XDMoD.Tracking.suppress_close_handler = suppress_close_handler;
if (typeof details !== 'string') {
details = JSON.stringify(details);
}
//console.log("[TrackEvent]: " + [XDMoD.REST.token,XDMoD.Tracking.sequence_index,CCR.xdmod.ui.username,category,action,details,details.length].join(' -- '));
var dimension_limit = 150; // dimension limit imposed by Google
var action_dimension_slots = 3; // how many custom dimensions are dedicated to storing action details
var action_details = [];
var i = 0;
for (i = 0; i < action_dimension_slots; i++) {
action_details.push((details.substr(0, dimension_limit).length > 0) ? details.substr(0, dimension_limit) : '-');
details = details.substr(dimension_limit);
}
XDMoD.Tracking.sequence_index++;
var current_date = new Date();
var current_timestamp = current_date.getTime();
var timezone_offset = current_date.getTimezoneOffset();
var time_delta = current_timestamp - XDMoD.Tracking.timestamp;
ga('send', 'event', category, action, {
'dimension1': XDMoD.Tracking.sequence_index,
'dimension2': CCR.xdmod.ui.username,
'dimension3': current_timestamp.toString(),
'dimension4': XDMoD.REST.token,
'dimension5': (timezone_offset / 60).toString(),
'dimension6': action_details[0],
'dimension7': action_details[1],
'dimension8': action_details[2],
'metric1': time_delta.toString()
});
XDMoD.Tracking.timestamp = current_timestamp;
_gaq.push(['_trackEvent', CCR.xdmod.ui.username, category, action]);
}; //XDMoD.TrackEvent
// ==============================================================
XDMoD.GeneralOperations = {
disableButton: function (button_id) {
Ext.getCmp(button_id).setDisabled(true);
}, //disableButton
contactSuccessHandler: function (window_id) {
var w = Ext.getCmp(window_id);
w.hide();
CCR.xdmod.ui.generalMessage('Message Sent', 'Thank you for contacting us.<br>We will get back to you as soon as possible.', true);
} //contactSuccessHandler
}; //XDMoD.GeneralOperations
// ==============================================================
XDMoD.GlobalToolbar = {};
XDMoD.GlobalToolbar.Logo = {
xtype: 'tbtext',
cls: 'logo93',
id: 'logo',
width: 93,
height: 32,
border: false
}; //XDMoD.GlobalToolbar.Logo
// -------------------------------------------------
XDMoD.GlobalToolbar.CustomCenterLogo = {
xtype: 'tbtext',
cls: 'custom_center_logo',
height: 32,
border: false
}; //XDMoD.GlobalToolbar.CustomCenterLogo
// -------------------------------------------------
XDMoD.GlobalToolbar.Profile = {
text: 'My Profile',
scale: 'small',
iconCls: 'user_profile_16',
id: 'global-toolbar-profile',
tooltip: 'Profile Editor',
handler: function () {
XDMoD.TrackEvent("Portal", "My Profile Button Clicked");
var profileEditor = new XDMoD.ProfileEditor();
profileEditor.init();
}
}; //XDMoD.GlobalToolbar.Profile
// -------------------------------------------------
XDMoD.GlobalToolbar.Dashboard = {
text: 'Dashboard',
scale: 'small',
iconCls: 'btn_dashboard',
id: 'global-toolbar-dashboard',
tooltip: 'Internal Dashboard',
handler: function () {
XDMoD.TrackEvent("Portal", "Dashboard Button Clicked");
CCR.xdmod.initDashboard();
} //handler
}; //XDMoD.GlobalToolbar.Dashboard
// -------------------------------------------------
XDMoD.GlobalToolbar.SignUp = {
text: 'Sign Up',
tooltip: 'New User? Sign Up Today',
scale: 'small',
iconCls: 'signup_16',
id: 'global-toolbar-signup',
handler: function () {
XDMoD.TrackEvent("Portal", "Sign Up Button Clicked");
CCR.xdmod.ui.actionSignUp();
}
}; //XDMoD.GlobalToolbar.SignUp
// -------------------------------------------------
XDMoD.GlobalToolbar.About = function (tabPanel) {
return {
text: 'About',
tooltip: 'About',
scale: 'small',
iconCls: 'about_16',
id: 'global-toolbar-about',
handler: function () {
XDMoD.TrackEvent("Portal", "About Button Clicked");
Ext.History.add('#main_tab_panel:about_xdmod?XDMoD');
}
};
}; //XDMoD.GlobalToolbar.About
// -------------------------------------------------
XDMoD.GlobalToolbar.Roadmap = {
text: 'Roadmap',
iconCls: 'roadmap',
id: 'global-toolbar-roadmap',
handler: function() {
Ext.History.add('#main_tab_panel:about_xdmod?Roadmap');
}
};
XDMoD.GlobalToolbar.Contact = function () {
var contactHandler = function(){
XDMoD.TrackEvent('Portal', 'Contact Us -> ' + this.text + ' Button Clicked');
switch(this.text){
case 'Send Message':
new XDMoD.ContactDialog().show();
break;
case 'Request Feature':
new XDMoD.WishlistDialog().show();
break;
case 'Submit Support Request':
new XDMoD.SupportDialog().show();
break;
}
};
return {
text: 'Contact Us',
tooltip: 'Contact Us',
scale: 'small',
iconCls: 'contact_16',
id: 'global-toolbar-contact-us',
menu: new Ext.menu.Menu({
items: [{
text: 'Send Message',
iconCls: 'contact_16',
id: 'global-toolbar-contact-us-send-message',
handler: contactHandler
},
{
text: 'Request Feature',
iconCls: 'bulb_16',
id: 'global-toolbar-contact-us-request-feature',
handler: contactHandler
},
{
text: 'Submit Support Request',
iconCls: 'help_16',
id: 'global-toolbar-contact-us-submit-support-request',
handler: contactHandler
}]
}) //menu
};
}; //XDMoD.GlobalToolbar.Contact
// -------------------------------------------------
XDMoD.GlobalToolbar.Help = function (tabPanel) {
var menuItems = [
{
text: 'User Manual',
iconCls: 'user_manual_16',
id: 'global-toolbar-help-user-manual',
handler: function () {
if (tabPanel === undefined) {
window.open("user_manual.php");
return;
}
var searchTerms = tabPanel.getActiveTab().userManualSectionName;
XDMoD.TrackEvent("Portal", "Help -> User Manual Button Clicked with " + searchTerms || "no" + " tab selected");
window.open('user_manual.php?t=' + encodeURIComponent(searchTerms));
}
},
{
text: 'YouTube Channel',
iconCls: 'youtube_16',
id: 'global-toolbar-help-youtube',
handler: function () {
XDMoD.TrackEvent("Portal", "Help -> YouTube Channel Button Clicked");
window.open('https://www.youtube.com/channel/UChm_AbEcBryCdIfebN5Kkrg');
}
}
];
if (CCR.xdmod.features.xsede) {
menuItems.splice(1, 0, {
text: 'FAQ',
iconCls: 'help_16',
id: 'global-toolbar-help-faq',
handler: function () {
XDMoD.TrackEvent("Portal", "Help -> FAQ Button Clicked");
window.open('faq');
}
});
}
return {
text: 'Help',
tooltip: 'Help',
scale: 'small',
id: 'help_button',
iconCls: 'help_16',
menu: new Ext.menu.Menu({
items: menuItems
}) //menu
};
}; //XDMoD.GlobalToolbar.Help
// =====================================================================
// XDMoD.constants
//
// A namespace containing constants used across various components.
// Ideally, some of these should be defined in one place, as they are used
// by both the browser client and the server.
/**
* The maximum length of a full name.
*/
XDMoD.constants.maxNameLength = 100;
/**
* The maximum length of a first name.
*/
XDMoD.constants.maxFirstNameLength = 50;
/**
* The maximum length of a last name.
*/
XDMoD.constants.maxLastNameLength = 50;
/**
* The minimum length of an email address.
*/
XDMoD.constants.minEmailLength = 6;
/**
* The maximum length of an email address.
*/
XDMoD.constants.maxEmailLength = 200;
/**
* The minimum length of a username.
*/
XDMoD.constants.minUsernameLength = 5;
/**
* The maximum length of a username.
*/
XDMoD.constants.maxUsernameLength = 200;
/**
* The minimum length of a password.
*/
XDMoD.constants.minPasswordLength = 5;
/**
* The maximum length of a password.
*/
XDMoD.constants.maxPasswordLength = 20;
/**
* The maximum length of a report name.
*/
XDMoD.constants.maxReportNameLength = 50;
/**
* The maximum length of a report title.
*/
XDMoD.constants.maxReportTitleLength = 50;
/**
* The maximum length of a report header.
*/
XDMoD.constants.maxReportHeaderLength = 40;
/**
* The maximum length of a report footer.
*/
XDMoD.constants.maxReportFooterLength = 40;
/**
* The maximum length of a user's position (job title).
*/
XDMoD.constants.maxUserPositionLength = 200;
/**
* The maximum length of a user's organization.
*/
XDMoD.constants.maxUserOrganizationLength = 200;
// =====================================================================
// XDMoD.regex
//
// A namespace containing commonly-used regular expressions.
/**
* Regular expression that matches if a string contains no reserved characters.
*/
XDMoD.regex.noReservedCharacters = /^[^$^#<>":\/\\!]*$/;
/**
* Regular expression that matches allowed username characters.
*/
XDMoD.regex.usernameCharacters = /^[a-zA-Z0-9@.\-_+\']*$/;
// XDMoD.validator
//
// A namespace for form field validator functions.
/**
* Validate an email address.
*
* @param {String} email The email address to validate.
*
* @return {Boolean|String} True if the email is valid. An error message if
* it is not valid.
*/
XDMoD.validator.email = function (email) {
return Ext.form.VTypes.email(email) || 'You must specify a valid email address. (e.g. user@domain.com)';
}
// =====================================================================
// XDMoD.utils
//
// A namespace containing commonly-used utility functions.
/**
* A listener for input fields that will trim white space from their values
* before they lose focus.
*
* @param Ext.form.field thisField The field being operated on.
*/
XDMoD.utils.trimOnBlur = function (thisField) {
thisField.setValue(Ext.util.Format.trim(thisField.getValue()));
};
/**
* Calls the syncShadow function on a component's containing window.
*
* This can be attached as a listener to window components that change their
* height in a window where at least one component is using autoHeight in order
* to fix the shadow not being redrawn on height change.
*
* Based on: http://www.sencha.com/forum/showthread.php?49200-How-to-invoke-panel-syncShadow-with-autoHeight-true&p=234394&viewfull=1#post234394
*
* @param Ext.Component thisComponent The component requesting its window sync.
*/
XDMoD.utils.syncWindowShadow = function (thisComponent) {
thisComponent.bubble(function (currentComponent) {
if (currentComponent instanceof Ext.Window) {
currentComponent.syncShadow();
return false;
}
return true;
});
};
// =====================================================================
Ext.Ajax.timeout = 86400000;
CCR.xdmod.ui.tokenDelimiter = ':';
CCR.xdmod.ui.minChartScale = 0.5;
CCR.xdmod.ui.maxChartScale = 5;
CCR.xdmod.ui.deltaChartScale = 0.2;
CCR.xdmod.ui.thumbChartScale = 0.76;
CCR.xdmod.ui.thumbAspect = 3.0 / 5.0;
CCR.xdmod.ui.thumbPadding = 15.0;
CCR.xdmod.ui.scrollBarWidth = 15;
CCR.xdmod.ui.deltaThumbChartScale = 0.3;
CCR.xdmod.ui.highResScale = 2.594594594594595;
CCR.xdmod.ui.hd1280Scale = 1.72972972972973;
CCR.xdmod.ui.hd1920cale = 2.594594594594595;
CCR.xdmod.ui.print300dpiScale = 4.662162162162162;
CCR.xdmod.ui.smallChartScale = 0.61;
CCR.xdmod.ui.thumbWidth = 400;
CCR.xdmod.ui.thumbHeight = CCR.xdmod.ui.thumbWidth * CCR.xdmod.ui.thumbAspect;
CCR.xdmod.XSEDE_USER_TYPE = 700;
CCR.xdmod.UserTypes = {
ProgramOfficer: 'po',
CenterDirector: 'cd',
CenterStaff: 'cs',
CampusChampion: 'cc',
PrincipalInvestigator: 'pi',
User: 'usr'
};
CCR.xdmod.reporting.dirtyState = false;
CCR.xdmod.catalog = {
metric_explorer: {},
report_generator: {}
};
CCR.xdmod.ui.invertColor = function (hexTripletColor) {
var color = hexTripletColor;
color = parseInt(color, 16); // convert to integer
color = 0xFFFFFF ^ color; // invert three bytes
color = color.toString(16); // convert to hex
color = ("000000" + color).slice(-6); // pad with leading zeros
return color;
};
// ------------------------------------
// Global reference to login prompt
CCR.xdmod.ui.login_prompt = null;
// ------------------------------------
CCR.xdmod.ui.createUserManualLink = function (tags) {
return '<div style="background-image: url(\'gui/images/user_manual.png\'); background-repeat: no-repeat; height: 36px; padding-left: 40px; padding-top: 10px">' +
'For more information, please refer to the <a href="javascript:void(0)" onClick="CCR.xdmod.ui.userManualNav(\'' + tags + '\')">User Manual</a>' +
'</div>';
}; //CCR.xdmod.ui.createUserManualLink
CCR.xdmod.ui.userManualNav = function (tags) {
window.open('user_manual.php?t=' + tags);
};
CCR.xdmod.ui.shortTitle = function (name) {
if (name.length > 50) {
return name.substr(0, 47) + '...';
}
return name;
};
CCR.xdmod.ui.randomBuffer = function () {
return 300 * Math.random();
};
CCR.ucfirst = function (str) {
return str.toLowerCase().replace(/\b([a-z])/gi, function (c) {
return c.toUpperCase();
});
};
CCR.xdmod.ui.userAssumedCenterRole = function () {
var role_id = CCR.xdmod.ui.activeRole.split(';')[0];
return (role_id == CCR.xdmod.UserTypes.CenterDirector || role_id == CCR.xdmod.UserTypes.CenterStaff);
}; //CCR.xdmod.ui.userAssumedCenterRole
CCR.xdmod.enumAssignedResourceProviders = function () {
var assignedResourceProviders = {};
for (var x = 0; x < CCR.xdmod.ui.allRoles.length; x++) {
var role_data = CCR.xdmod.ui.allRoles[x].param_value.split(':');
var role_id = role_data[0];
if (role_id == CCR.xdmod.UserTypes.CenterDirector || role_id == CCR.xdmod.UserTypes.CenterStaff) {
assignedResourceProviders[role_data[1]] = CCR.xdmod.ui.allRoles[x].description.split(' - ')[1];
}
} //for
return assignedResourceProviders;
}; //enumAssignedResourceProviders
CCR.xdmod.ui.createMenuCategory = function (text) {
return new Ext.menu.TextItem({
html: '<div style="height: 20px; vertical-align: middle; background-color: #ddd; font-weight: bold"><span style="color: #00f; position: relative; top: 4px; left: 3px">' + text + '</span></div>'
});
}; //CCR.xdmod.ui.createMenuCategory
// -----------------------------------
/**
* Safely decode the JSON contents of a request response.
*
* @param object response A response passed to a request callback.
* @returns The decoded contents of the response, or null if unable to decode.
*/
CCR.safelyDecodeJSONResponse = function (response) {
var responseObject = null;
try {
responseObject = Ext.decode(response.responseText);
}
catch (e) {}
return responseObject;
};
/**
* Check if the value returned by CCR.safelyDecodeJSONResponse indicates
* that the request was successful.
*
* @param responseObject Decoded response contents.
* @returns boolean True if response indicates success, otherwise false.
*/
CCR.checkDecodedJSONResponseSuccess = function (responseObject) {
var responseSuccessful = false;
try {
responseSuccessful = responseObject.success === true;
}
catch (e) {}
return responseSuccessful;
};
/**
* Check if a request response containing JSON indicates success. (This is a
* shortcut for calling CCR.safelyDecodeJSONResponse followed by
* CCR.checkDecodedJSONResponseSuccess. If you wish to use contents of the
* response other than the success indicator, use those functions directly.)
*
* @param object response A response passed to a request callback.
* @returns boolean True if response indicates success, otherwise false.
*/
CCR.checkJSONResponseSuccess = function (response) {
return CCR.checkDecodedJSONResponseSuccess(CCR.safelyDecodeJSONResponse(response));
};
// -----------------------------------
/**
* Send a request by creating a temporary form and submitting the
* provided values. This function will not check if the client's session
* is alive first.
*
* @param string url The URL to submit the request to.
* @param string method The request method to use.
* @param object params A set of parameters to submit with the request.
*/
CCR.submitHiddenFormImmediately = function (url, method, params) {
var temp = document.createElement("form");
temp.action = url;
temp.method = method;
temp.style.display = "none";
for (var param in params) {
if(params.hasOwnProperty(param)){
var opt = document.createElement("textarea");
opt.name = param;
opt.value = params[param];
temp.appendChild(opt);
}
}
document.body.appendChild(temp);
temp.submit();
document.body.removeChild(temp);
}; //CCR.invokePostImmediately
// -----------------------------------
/**
* Send a POST request by creating a temporary form and submitting the
* provided values. This function will not check if the client's session
* is alive first.
*
* @param string url The URL to submit the request to.
* @param object params A set of parameters to submit with the request.
*/
CCR.invokePostImmediately = function (url, params) {
CCR.submitHiddenFormImmediately(url, "POST", params);
};
// -----------------------------------
/**
* Send a request by creating a temporary form and submitting the
* provided values. This function will first check if the client's
* session is alive and will only submit the form if it is.
*
* @param string url The URL to submit the request to.
* @param string method The request method to use.
* @param object params A set of parameters to submit with the request.
* @param object options (Optional) A set of options, including:
* boolean checkDashboardUser Check the dashboard user session instead
* of the main user session. (Default: false)
*/
CCR.submitHiddenForm = function (url, method, params, options) {
options = options || {};
var checkDashboardUser = typeof options.checkDashboardUser === "undefined" ? false : options.checkDashboardUser;
var checkUrlPrefix = checkDashboardUser ? "../" : "";
Ext.Ajax.request({
url: checkUrlPrefix + "controllers/user_auth.php",
params: {
operation: "session_check",
public_user: typeof params.public_user === "undefined" ? false : params.public_user,
session_user_id_type: checkDashboardUser ? "Dashboard" : ""
},
callback: function (options, success, response) {
if (success) {
success = CCR.checkJSONResponseSuccess(response);
}
if (success) {
CCR.submitHiddenFormImmediately(url, method, params);
} else {
CCR.xdmod.ui.presentFailureResponse(response);
}
}
});
}; //CCR.invokePost
// -----------------------------------
/**
* Send a POST request by creating a temporary form and submitting the
* provided values. This function will first check if the client's
* session is alive and will only submit the form if it is.
*
* @param string url The URL to submit the request to.
* @param object params A set of parameters to submit with the request.
* @param object options (Optional) A set of options, including:
* boolean checkDashboardUser Check the dashboard user session instead
* of the main user session. (Default: false)
*/
CCR.invokePost = function (url, params, options) {
CCR.submitHiddenForm(url, "POST", params, options);
};
// -----------------------------------
CCR.xdmod.ui.AssistPanel = Ext.extend(Ext.Panel, {
layout: 'fit',
margins: '2 2 2 0',
bodyStyle: {
overflow: 'auto'
},
initComponent: function () {
var self = this;
self.html = '<div class="x-grid-empty">';
if (self.headerText) {
self.html += '<b style="font-size: 150%">' + self.headerText + '</b><br/><br/>';
}
if (self.subHeaderText) {
self.html += self.subHeaderText + '<br/><br/>';
}
if (self.graphic) {
self.html += '<img src="' + self.graphic + '"><br/><br/>';
}
if (self.userManualRef) {
self.html += CCR.xdmod.ui.createUserManualLink(self.userManualRef);
}
self.html += '</div>';
CCR.xdmod.ui.AssistPanel.superclass.initComponent.call(this);
} //initComponent
}); //CCR.xdmod.ui.AssistPanel
// -----------------------------------
CCR.WebPanel = Ext.extend(Ext.Window, {
onRender: function () {
this.bodyCfg = {
tag: 'iframe',
src: this.src,
cls: this.bodyCls,
style: {
border: '0px none'
}
};
if (this.frameid) {
this.bodyCfg.id = this.frameid;
}
CCR.WebPanel.superclass.onRender.apply(this, arguments);
}, //onRender
// -----------------------------
initComponent: function () {
CCR.WebPanel.superclass.initComponent.call(this);
} //initComponent
}); //CCR.WebPanel
// -----------------------------------
CCR.xdmod.sponsor_message = 'This work was sponsored by NSF under grant number OCI 1025159';
//Used in html/gui/general/login.php
var toggle_about_footer = function (o) {
o.innerHTML = (o.innerHTML == CCR.xdmod.version) ? CCR.xdmod.sponsor_message : CCR.xdmod.version;
}; //toggle_about_footer
CCR.BrowserWindow = Ext.extend(Ext.Window, {
modal: true,
resizable: false,
closeAction: 'hide',
versionStamp: false, // Set to 'true' during instantiation to display version stamp
// in lower-left region of window (left of bbar)
onRender: function () {
this.bodyCfg = {
tag: 'iframe',
src: this.src,
cls: this.bodyCls,
style: {
border: '0px none'
}
};
if (this.frameid) {
this.bodyCfg.id = this.frameid;
}
CCR.BrowserWindow.superclass.onRender.apply(this, arguments);
}, //onRender
initComponent: function () {
var self = this;
var window_items = [];
if (self.nbutton) {
window_items.push(self.nbutton);
}
if (self.versionStamp) {
window_items.push({
xtype: 'tbtext',
html: '<span style="color: #000; cursor: default" onClick="toggle_about_footer(this)">' + CCR.xdmod.sponsor_message + '</span>'
});
}
window_items.push('->');
window_items.push(
new Ext.Button({
text: 'Close',
iconCls: 'general_btn_close',
handler: function () {
if (self.closeAction == 'close'){
self.close();
}
else {
self.hide();
}
}
})
);
Ext.apply(this, {
bbar: {
items: window_items
}
});
CCR.BrowserWindow.superclass.initComponent.call(this);
} //initComponent
}); //CCR.BrowserWindow
// -----------------------------------
var logoutCallback = function () {
location.href = 'index.php';
};
CCR.xdmod.ui.actionLogout = function () {
XDMoD.TrackEvent("Portal", "logout link clicked");
XDMoD.REST.Call({
action: 'auth/logout',
method: 'POST',
callback: logoutCallback
});
}; //actionLogout
// Used in html/gui/general/login.php
var presentLoginResponse = function (message, status, target, cb) {
var messageColor = status ? '#080' : '#f00';
var targetCmp = Ext.getCmp(target);
targetCmp.update('<p style="color:' + messageColor + '">' + message + '</p>');
targetCmp.show();
if (cb) {
cb();
}
}; //presentLoginResponse
// Used in html/gui/general/login.php
var clearLoginResponse = function (target) {
var targetCmp = Ext.getCmp(target);
targetCmp.hide();
}; //clearLoginResponse
// Used in html/gui/general/login.php
var presentContactFormViaLoginError = function () {
XDMoD.TrackEvent('Login Window', 'Clicked on Conact Us');
CCR.xdmod.ui.login_prompt.close();
var contact = new XDMoD.ContactDialog();
contact.show();
}; //presentContactFormViaLoginError
// Used in html/gui/general/login.php
var presentSignUpViaLoginPrompt = function () {
XDMoD.TrackEvent('Login Window', 'Clicked on Sign Up button');
CCR.xdmod.ui.login_prompt.close();
CCR.xdmod.ui.actionSignUp();
}; //presentSignUpViaLoginPrompt
// -----------------------------------
CCR.xdmod.ui.actionSignUp = function () {
var wndSignup = new XDMoD.SignUpDialog();
wndSignup.show();
}; //CCR.xdmod.ui.actionSignUp
// -----------------------------------
CCR.xdmod.ui.FadeInWindow = Ext.extend(Ext.Window, { //experimental
animateTarget: true,
setAnimateTarget: Ext.emptyFn,
animShow: function () {
this.el.fadeIn({
duration: 0.55,
callback: this.afterShow.createDelegate(this, [true], false),
scope: this
});
},
animHide: function () {
if (this.el.shadow) {
this.el.shadow.hide();
}
this.el.fadeOut({
duration: 0.55,
callback: this.afterHide,
scope: this
});
}
});
CCR.xdmod.ui.actionLogin = function (config, animateTarget) {
XDMoD.TrackEvent("Portal", "Sign In link clicked");
var width = 280,
promptHeight = 348,
iframeHeight = 318;
// Adjsut window size depending on if the XSEDE login is enabled.
if (CCR.xdmod.features.xsede || CCR.xdmod.isFederationConfigured) {
width = 540;
promptHeight = 486;
iframeHeight = 500;
}
//reset referer
XDMoD.referer = document.location.hash;
CCR.xdmod.ui.login_prompt = new Ext.Window({
title: "Welcome To XDMoD",
width: width,
height: promptHeight,
modal: true,
animate: true,
resizable: false,
tbar: {
items: [{
xtype: 'tbtext',
html: '<span style="color: #000">Close this window to view public information</span>'
}]
},
items: [
new Ext.Panel({
id: 'wnd_login',
layout: 'fit',
html: '<iframe src="gui/general/login.php" frameborder=0 width=100% height=' + iframeHeight + '></iframe>'
})
],
listeners: {
close: function () {
XDMoD.TrackEvent('Login Window', 'Closed Window');
} //close
} //listeners
}); //CCR.xdmod.ui.login_prompt
CCR.xdmod.ui.login_prompt.show(animateTarget);
CCR.xdmod.ui.login_prompt.center();
}; //actionLogin
// -----------------------------------
CCR.xdmod.ControllerBase = "controllers/";
// -----------------------------------
// For handling the cases where a UI element is bound to a datastore, and usage of that UI element alone determines when
// that data store reloads
CCR.xdmod.ControllerUIDataStoreHandler = function (activeStore) {
CCR.xdmod.ControllerResponseHandler('{"status" : "' + activeStore.reader.jsonData.status + '"}', null);
};
// -----------------------------------
CCR.xdmod.ControllerResponseHandler = function (responseText, targetStore) {
var responseData = Ext.decode(responseText);
if (responseData.status == 'not_logged_in') {
var newPanel = new XDMoD.LoginPrompt();
newPanel.show();
return false;
}
if (targetStore == null) {
return true;
}
targetStore.loadData(responseData);
}; //CCR.xdmod.ControllerResponseHandler
// -----------------------------------
CCR.xdmod.ControllerProxy = function (targetStore, parameters) {
if (parameters.operation == null) {
Ext.MessageBox.alert('Controller Proxy', 'An operation must be specified');
return;
}
Ext.Ajax.request({
url: targetStore.url,
method: 'POST',
params: parameters,
timeout: 60000, // 1 Minute,
async: false,
success: function (response) {
CCR.xdmod.ControllerResponseHandler(response.responseText, targetStore);
},
failure: function () {
Ext.MessageBox.alert('Error', 'There has been a request error');
}
});
}; //CCR.xdmod.ControllerProxy
// -----------------------------------
CCR.xdmod.initDashboard = function () {
// Opening the window before the AJAX request is necessary to prevent
// it being treated as a popup. Solution from: http://stackoverflow.com/a/20822754
var dashboardWindow = window.open("", "_blank");
dashboardWindow.focus();
Ext.Ajax.request({
url: 'controllers/dashboard_launch.php',
method: 'POST',
callback: function (options, success, response) {
if (success && CCR.checkJSONResponseSuccess(response)) {
dashboardWindow.location.href = 'internal_dashboard';
}
else {
dashboardWindow.close();
window.focus();
CCR.xdmod.ui.presentFailureResponse(response, {
title: 'XDMoD Dashboard'
});
}
}
});
}; //CCR.xdmod.initDashboard
// -----------------------------------
CCR.xdmod.ui.generalMessage = function (msg_title, msg, success, show_delay) {
show_delay = show_delay || 2000;
var styleColor = success ? '#080' : '#f00';
var x_offset = -1 * ((Ext.getBody().getViewSize().width - 300) / 2);
var y_offset = -1 * ((Ext.getBody().getViewSize().height - 40) / 2);
new Ext.ux.window.MessageWindow({
title: msg_title,
width: 300,
html: '<b style="color: ' + styleColor + '">' + msg + '</b>' || 'No information available',
origin: {
offY: y_offset,
offX: x_offset
},
iconCls: '',
autoHeight: true,
draggable: false,
help: false,
hideFx: {
delay: show_delay,
mode: 'standard'
}
}).show(Ext.getDoc());
}; //CCR.xdmod.ui.generalMessage
// -----------------------------------
CCR.xdmod.ui.userManagementMessage = function (msg, success) {
var styleColor = success ? '#080' : '#f00';
var x_offset = -1 * ((Ext.getBody().getViewSize().width - 300) / 2);
var y_offset = -1 * ((Ext.getBody().getViewSize().height - 40) / 2);
new Ext.ux.window.MessageWindow({
title: 'User Management',
width: 300,
html: '<b style="color: ' + styleColor + '">' + msg + '</b>' || 'No information available',
origin: {
offY: y_offset,
offX: x_offset
},
iconCls: 'user_management_message_prompt',
autoHeight: true,
draggable: false,
help: false,
hideFx: {
delay: 2000,
mode: 'standard'
}
}).show(Ext.getDoc());
}; //CCR.xdmod.ui.userManagementMessage
// -----------------------------------
CCR.xdmod.ui.reportGeneratorMessage = function (title, msg, success, callback) {
var styleColor = success ? '#080' : '#f00';
var x_offset = -1 * ((Ext.getBody().getViewSize().width - 200) / 2);
var y_offset = -1 * ((Ext.getBody().getViewSize().height - 40) / 2);
new Ext.ux.window.MessageWindow({
title: title || 'You have clicked:',
id: 'report_generator_message',
html: '<b style="color: ' + styleColor + '">' + msg + '</b>' || 'No information available',
origin: {
offY: y_offset,
offX: x_offset
},
iconCls: 'report_generator_message_prompt',
autoHeight: true,
draggable: false,
help: false,
hideFx: {
delay: 3000,
mode: 'standard'
},
listeners: {
hide: function () {
if (callback) {
callback();
}
}
}
}).show(Ext.getDoc());
}; //CCR.xdmod.ui.reportGeneratorMessage
// -----------------------------------
CCR.xdmod.ui.toastMessage = function (title, msg) {
if (CCR.xdmod.ui.isDeveloper) {
new Ext.ux.window.MessageWindow({
title: title || 'You have clicked:',
html: msg || 'No information available',
origin: {
offY: -5,
offX: -5
},
autoHeight: true,
iconCls: 'load_time_message_prompt',
help: false,
hideFx: {
delay: 1000,
mode: 'standard'
}
}).show(Ext.getDoc());
}
};
// -----------------------------------
/**
* Attempt to extract an error message from a response object.
*
* @param {object} response A response object that was passed to a callback of
* an Ext.data.Connection (Ext.AJAX, etc.) request.
* @param {object} options (Optional) A set of optional options, including:
* {boolean} htmlEncode HTML encode the response message for safe
* display on a page. (Default: true)
* @return {mixed} The message contained in the response, or null if
* not found.
*/
CCR.xdmod.ui.extractErrorMessageFromResponse = function (response, options) {
// Set default values for unused, optional parameters.
options = typeof options === "undefined" ? {} : options;
options.htmlEncode = typeof options.htmlEncode === "undefined" ? true : options.htmlEncode;
var responseMessage = null;
var responseObject = response;
try {
if (response.responseText) {
responseObject = Ext.decode(response.responseText);
}
}
catch (e) {}
try {
responseMessage = responseObject.message || responseObject.status || responseMessage;
}
catch (e) {}
if (options.htmlEncode) {
responseMessage = Ext.util.Format.htmlEncode(responseMessage);
}
return responseMessage;
};
// -----------------------------------
/**
* Display a generic alert box using the contents of a response object.
* A box will not be displayed if the response represents an exception and
* that exception has been handled globally.
*
* @param object response A response object that was passed to a callback of
* an Ext.data.Connection (Ext.AJAX, etc.) request.
* @param object options (Optional) A set of optional settings, including:
* string title A title to use in the alert box.
* string wrapperMessage A user-friendly message to precede the
* contents of the response.
*/
CCR.xdmod.ui.presentFailureResponse = function (response, options) {
// Set default values for unused, optional parameters.
options = typeof options === "undefined" ? {} : options;
var title = typeof options.title === "undefined" ? "Error" : options.title;
// If this response was already handled globally, stop and do nothing.
if (response.exceptionHandledGlobally) {
return;
}
// Attempt to extract an error message from the response object.
var responseMessage = CCR.xdmod.ui.extractErrorMessageFromResponse(response);
if (responseMessage === null) {
responseMessage = "Unknown Error";
}
// If a user-friendly message was given, add it to the displayed message.
var outputMessage;
if (options.wrapperMessage) {
outputMessage = options.wrapperMessage + " (" + responseMessage + ")";
} else {
outputMessage = responseMessage;
}
// Display the message in an Ext message box.
Ext.MessageBox.alert(title, outputMessage);
};
// -----------------------------------
CCR.xdmod.ui.intersect = function (a, b) {
var result = [];
for (var i = 0; i < a.length; i++) {
for (var j = 0; j < b.length; j++) {
if (a[i] == b[j]) {
result.push(a[i]);
}
}
}
return result;
};
CCR.xdmod.ui.getComboBox = function (data, fields, valueField, displayField, editable, emptyText) {
return new Ext.form.ComboBox({
typeAhead: true,
triggerAction: 'all',
lazyRender: true,
mode: 'local',
emptyText: emptyText,
editable: editable,
store: new Ext.data.ArrayStore({
id: 0,
fields: fields,
data: data
}),
valueField: valueField,
displayField: displayField
});
};
CCR.xdmod.ui.gridComboRenderer = function (combo) {
return function (value) {
var idx = combo.store.find(combo.valueField, value);
var rec = combo.store.getAt(idx);
if (!rec) {
return combo.emptyText;
}
return rec.get(combo.displayField);
};
};
CCR.isBlank = function (value) {
return !value || value === 'undefined' || !value.trim() ? true: false;
};
CCR.Types = {};
CCR.Types.String = '[object String]';
CCR.Types.Number = '[object Number]';
CCR.Types.Array = '[object Array]';
CCR.Types.Object = '[object Object]';
CCR.Types.Null = '[object Null]';
CCR.Types.Undefined = '[object Undefined]';
CCR.Types.Function = '[object Function]';
CCR.isType = function (value, type) {
if (typeof type === 'string') {
return Object.prototype.toString.call(value) === type;
} else {
return Object.prototype.toString.call(value) ===
Object.prototype.toString.call(type);
}
};
CCR.exists = function (value) {
if (CCR.isType(value, '[object String]') && value === '') {
return false;
}
if (value === undefined || value === null) {
return false;
}
return true;
};
CCR.merge = function (obj1, obj2) {
var obj3 = {};
for (var attrname1 in obj1) {
if(obj1.hasOwnProperty(attrname1)){
obj3[attrname1] = obj1[attrname1];
}
}
for (var attrname in obj2) {
if(obj2.hasOwnProperty(attrname)){
obj3[attrname] = obj2[attrname];
}
}
return obj3;
};
CCR.getParameter = function (name, source) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(source);
return results === null
? ""
: decodeURIComponent(results[1].replace(/\+/g, " "));
};
CCR.tokenize = function (hash) {
var exists = CCR.exists;
var root, tab, params;
function select(value, delimiter, index) {
if (exists(value) && exists(delimiter) && exists(index) &&
exists(value.indexOf) && typeof index === 'number' &&
index >= 0 && value.indexOf(delimiter) >= 0) {
return value.split(delimiter)[index];
} else {
return value;
}
}
function first(value, delimiter) {
return select(value, delimiter, 0);
}
function second(value, delimiter) {
return select(value, delimiter, 1);
}
if (exists(hash)) {
var tabDelimIndex = hash.indexOf(CCR.xdmod.ui.tokenDelimiter);
var paramDelimIndex = hash.indexOf('?');
var equalIndex = hash.indexOf('=');
var result = {
raw: hash,
content: second(hash, '#')
};
if (tabDelimIndex >= 0 && paramDelimIndex >= 0) {
// We have a well formed hash: parent:child?name=value...
root = first(
first(result.content, CCR.xdmod.ui.tokenDelimiter)
, '?'
);
tab = first(
second(result.content, CCR.xdmod.ui.tokenDelimiter),
'?'
);
params = second(result.content, '?');
if (params === result.content) {
params = '';
}
result['root'] = root;
result['tab'] = tab;
result['params'] = params;
} else if (tabDelimIndex < 0 && paramDelimIndex < 0 && equalIndex >= 0) {
// We have a hash that looks like: name=value
result['root'] = '';
result['tab'] = '';
result['params'] = result.content;
} else if (tabDelimIndex < 0 && paramDelimIndex < 0) {
result['root'] = '';
result['tab'] = result.content;
result['params'] = '';
} else if (tabDelimIndex >= 0 && paramDelimIndex < 0) {
// We have a hash that looks like: parent:child
root = first(result.content, CCR.xdmod.ui.tokenDelimiter);
tab = second(result.content, CCR.xdmod.ui.tokenDelimiter);
params = '';
result['root'] = root;
result['tab'] = tab;
result['params'] = params;
} else if (tabDelimIndex < 0 && paramDelimIndex >= 0) {
// We have a hash that looks like: child?name=value
root = '';
tab = first(result.content, '?');
params = second(result.content, '?');
result['root'] = root;
result['tab'] = tab;
result['params'] = params;
}
return result;
}
return {};
};
/**
* Helper function that converts a string to an array of items. It does this
* based on the provided delims array. For each delimiter provided there will be
* one level of arrays in the result. So for example:
* value = "key1=value1&key2=value2",
* delims = ['&', '=']
*
* would result in:
* [
* ["key1", "value1"],
* ["key2", "value2"]
* ];
*
* @param {String} value
* @param {Array} delims
* @returns {Array}
*/
CCR.toArray = function(value, delims) {
if (!CCR.exists(value) || !CCR.isType(value, CCR.Types.String) || value.length < 1) {
return [];
}
delims = delims || ['&', '='];
if (delims.length < 1) {
return [value];
}
var results = [];
var temp = value.split(delims[0]);
if (delims.length > 1) {
for (var i = 1; i < delims.length; i++) {
var delim = delims[i];
for (var j = 0; j < temp.length; j++) {
var entry = temp[j];
if (entry && entry.indexOf(delim) >= 0) {
results.push(entry.split(delim));
}
}
}
}
return results;
};
CCR.objectToArray = function(object) {
if (!CCR.exists(object)) {
return [];
}
var results;
for (var property in object) {
if(object.hasOwnProperty(property)) {
results = [property, object[property]];
}
}
return results;
};
CCR.join = function(values, joiners) {
if (!CCR.exists(values) || !CCR.isType(values, CCR.Types.Array)) {
return "";
}
joiners = joiners || ['&', '='];
if (values.length < 1) {
return "";
}
if (joiners.length < 1) {
return values.join('');
}
var joinerIndex = 0;
var result;
var joinValue = function(value, joiners, joinerIndex) {
var isArray = CCR.isType(value, CCR.Types.Array);
var holdsArrays = isArray && value.length > 0 && CCR.isType(value[0], CCR.Types.Array);
var result = [];
if (isArray && holdsArrays) {
for (var i = 0; i < value.length; i++) {
result.push(joinValue(value[i], joiners, joinerIndex + 1));
}
} else if (isArray && !holdsArrays) {
result = value;
} else {
result.push(value, joiners[joinerIndex]);
}
return result.join(joiners[joinerIndex]);
};
result = joinValue(values, joiners, joinerIndex);
return result;
};
CCR.STR_PAD_LEFT = 1;
CCR.STR_PAD_RIGHT = 2;
CCR.STR_PAD_BOTH = 3;
CCR.pad = function (str, len, pad, dir) {
len = len || 0;
pad = pad || ' ';
dir = dir || CCR.STR_PAD_RIGHT;
if (len + 1 >= str.length) {
switch (dir) {
case CCR.STR_PAD_LEFT:
str = Array(len + 1 - str.length).join(pad) + str;
break;
case CCR.STR_PAD_BOTH:
var right = Math.ceil((len = len - str.length) / 2);
var left = len - right;
str = Array(left + 1).join(pad) + str + Array(right + 1).join(pad);
break;
default:
str = str + Array(len + 1 - str.length).join(pad);
break;
} // switch
}
return str;
};
CCR.deepEncode = function(values, options) {
if (!CCR.exists(values)) {
return '';
}
options = options || {};
var delim = options.delim || '&';
var left = options.left || '';
var right = options.right || '';
if (CCR.isType(values, CCR.Types.Array)) {
return CCR._encodeArray(values, {
delim: delim,
left: left,
right: right
});
} else if (CCR.isType(values, CCR.Types.Object)) {
return CCR._encodeObject(values, {
delim: delim,
left: left,
right: right
});
} else {
return '';
}
};
CCR._encodeArray = function(values, options) {
if (!CCR.exists(values)) {
return JSON.stringify([]);
}
options = options || {};
var delim = options.delim || ',';
var left = options.left || '[';
var right = options.right || ']';
var results = [];
for (var i = 0; i < values.length; i++) {
var value = values[i];
if (CCR.isType(value, CCR.Types.Array)) {
results.push(CCR._encodeArray(value, options));
} else if (CCR.isType(value, CCR.Types.Object)) {
results.push(CCR._encodeObject(value, options));
} else {
var isNumber = CCR.isType(value, CCR.Types.Number);
var encoded = isNumber ? value : '"' + value + '"';
results.push(encoded);
}
}
return (left + results.join(delim) + right).trim();
};
CCR._encodeObject = function(value, options) {
if (!CCR.exists(value)){
return JSON.stringify({});
}
options = options || {};
var delim = options.delim || ',';
var left = options.left || '{';
var right = options.right || '}';
var wrap = options.wrap || false;
var separator = options.seperator || '=';
var results = [];
for (var property in value ) {
if(value.hasOwnProperty(property)){
var propertyValue = value[property];
if (CCR.isType(propertyValue, CCR.Types.Array)) {
results.push(property + '=' + encodeURIComponent(CCR._encodeArray(propertyValue, {
wrap: true,
seperator: ':'
})));
} else if (CCR.isType(propertyValue, CCR.Types.Object)) {
results.push(property + '=' + encodeURIComponent(CCR._encodeObject(propertyValue, {
wrap: true
})));
} else {
var key = wrap ? '"' + property + '"' : property;
results.push(key + separator + propertyValue);
}
}
}
return (left + results.join(delim) + right).trim();
};
/**
* Encode the provided Array of values for inclusion as query parameters.
*
* @param {Object} values
*/
CCR.encode = function (values) {
if (CCR.exists(values)) {
var parameters = [];
for (var property in values) {
if (values.hasOwnProperty(property)) {
var isArray = CCR.isType(values[property], CCR.Types.Array);
var isObject = CCR.isType(values[property], CCR.Types.Object);
var value = isArray || isObject
? encodeURIComponent(CCR.deepEncode(values[property]))
: values[property];
parameters.push(property + '=' + value);
}
}
return parameters.join('&');
}
return undefined;
};
/**
* Apply implements an immutable merge (ie. returns a new object containing
* the properties of both objects.) of two javascript objects,
* lhs ( left hand side) and rhs ( right hand side). A property that exists
* in both lhs and rhs will default to the value of rhs.
*
* @param {Object} lhs Left hand side of the merge.
* @param {Object} rhs Right hand side of the merge.
*
**/
CCR.apply = function (lhs, rhs) {
if (typeof lhs === 'object' && typeof rhs === 'object') {
var results = {};
for (var property in lhs) {
if (lhs.hasOwnProperty(property)) {
results[property] = lhs[property];
}
}
for (property in rhs) {
if (rhs.hasOwnProperty(property)) {
var rhsExists = rhs[property] !== undefined
&& rhs[property] !== null;
if (rhsExists) {
results[property] = rhs[property];
}
}
}
return results;
}
return lhs;
};
CCR.toInt = function (value) {
var isType = CCR.isType;
var result;
if (isType(value, CCR.Types.Number)) {
result = value;
} else if (isType(value, CCR.Types.String)) {
result = parseInt(value);
} else {
result = value;
}
return result;
};
/**
* Displays a MessageBox to the user with the error styling.
*
* @param {String} title of the Error Dialog Box.
* @param {String} message that will be displayed to the user.
* @param {Function} success function that will be executed if the user does not
* click 'no' or 'cancel'.
* @param {Function} failure function that will be executed if the user does
* click 'no' or 'cancel'.
* @param {Object} buttons the buttons that will
*/
CCR.error = function (title, message, success, failure, buttons) {
buttons = buttons || Ext.MessageBox.OK;
success = success || function(){};
failure = failure || function(){};
Ext.MessageBox.show({
title: title,
msg: message,
buttons: buttons,
icon: Ext.MessageBox.ERROR,
fn: function(buttonId, text, options) {
var compare = CCR.compare;
if (compare.strings(buttonId, Ext.MessageBox.buttonText['no'])
|| compare.strings(buttonId, Ext.MessageBox.buttonText['cancel'])) {
failure(buttonId, text, options);
} else {
success(buttonId, text, options);
}
}
});
};
CCR.compare = {
method: {
String: {
LowerCase: 'toLowerCase',
UpperCase: 'toUpperCase',
None: 'toString'
}
},
strings: function(left, right, method) {
if (!CCR.exists(left) || !CCR.exists(right)) {
return false;
}
method = method || CCR.compare.method.String.LowerCase;
return left[method]() === right[method]();
}
};
/**
* Retrieve a reference to the static ( namespaced ) JavaScript property
* identified by the 'instancePath' argument that will be an instance of the class
* identified by the 'classPath' argument constructed with 'config' as a
* constructor argument, if provided.
* Example:
* CCR.getInstance(
* 'CCR.xdmod.ui.jobViewer', // <- static namespace where an instance of 'classPath' should live.
* 'XDMoD.Module.JobViewer', // <- if nothing is found @ 'instancePath' then use this so there is.
* {
* id: 'job_viewer',
* title: 'Job Viewer', // <- If we're invoking 'classPath' then use this as a configuration object.
* ... etc. etc.
* });
*
* @param {String} instancePath the namespace to retrieve / assign the newly
* created instance of classPath to.
* @param {String} classPath the namespace path of the class to
* create should the 'create' parameter be set
* to true.
* @param {Object} [config=null] the configuration constructor param used
* when instantiating 'classPath'.
* @return {*} either the value reference by 'instancePath' if it exists
* or an instance of 'classPath' instantiated with 'config'
* as a constructor argument.
**/
CCR.getInstance = function(instancePath, classPath, config) {
if ( !instancePath || typeof instancePath !== 'string' ) {
return;
}
if ( !classPath || typeof classPath !== 'string' ) {
return;
}
/**
* Walk the provided 'path' parameter, executing the provided callback
* at each index. The callback has the following parameters:
* - previousValue: The value previously returned in the last invocation
* of the callback, or if this is the first invocation, 'window'.
* - currentValue: The current element being processed.
*
* @param {String} path the '.' delimited string to be walked.
* @param {Function} callback the function to be executed for each split
* item.
*
* @return {*} the result of walking the provided 'path'.
**/
var getReference = function(path, callback) {
callback = callback !== undefined
? callback
: function(previous, current) {
return previous[current];
};
return path.split('.').reduce( callback, window );
};
/**
* Attempt to invoke the result of walking the provided 'classPath'.
* 'config' is passed as a parameter to this invocation. If the result of
* walking the 'classPath' is not a function then instead of invoking it
* it is itself, returned.
*
* @param {String} classPath the '.' delimited string of the
* 'class' that is to be instantiated.
* @param {Object} [config=undefined] an object that will be passed to the
* invocation of 'classPath' should it
* be found.
*
* @return {*} The return value of invoking 'classPath' or, failing that,
* the value of 'classPath'.
**/
var instantiateClass = function(classPath, config) {
var Class = getReference(classPath);
return typeof Class === 'function' ? new Class(config) : Class;
};
var result = getReference(instancePath);
if (!result) {
result = getReference(
instancePath,
function(previous, current) {
if ( previous[current] === undefined ) {
return previous[current] = instantiateClass(classPath, config);
} else {
return previous[current];
}
}
);
}
return result;
};
// override 3.4.0 to be able to restore column state
Ext.override(Ext.grid.ColumnModel, {
setState: function (col, state) {
state = Ext.applyIf(state, this.defaults);
if (this.columns && this.columns[col]) {
Ext.apply(this.columns[col], state);
} else if (this.config && this.config[col]) {
Ext.apply(this.config[col], state);
}
}
});
// override 3.4.0 to fix layout bug with composite fields (field width too narrow)
Ext.override(Ext.form.TriggerField, {
onResize: function (w, h) {
Ext.form.TriggerField.superclass.onResize.call(this, w, h);
var tw = this.getTriggerWidth();
if (Ext.isNumber(w)) {
this.el.setWidth(w - tw);
}
if (this.rendered && !this.readOnly && this.editable && !this.el.getWidth()) {
this.wrap.setWidth(w);
}
else {
this.wrap.setWidth(this.el.getWidth() + tw);
}
}
});
// override 3.4.0 to:
// * fix issue with tooltip text wrapping in IE9 (tooltip 1 pixel too narrow)
// JS: I suspect this issue is caused by subpixel rendering in IE9 causing bad measurements
// * allow beforeshow to cancel a tooltip
Ext.override(Ext.Tip, {
doAutoWidth: function (adjust) {
// next line added to allow beforeshow to cancel tooltip (see below)
if (!this.body) {
return;
}
adjust = adjust || 0;
var bw = this.body.getTextWidth();
if (this.title) {
bw = Math.max(bw, this.header.child('span').getTextWidth(this.title));
}
bw += this.getFrameWidth() + (this.closable ? 20 : 0) + this.body.getPadding("lr") + adjust;
// added this line:
if (Ext.isIE9) {
bw += 1;
}
this.setWidth(bw.constrain(this.minWidth, this.maxWidth));
if (Ext.isIE7 && !this.repainted) {
this.el.repaint();
this.repainted = true;
}
}
});
// override 3.4.0 to allow beforeshow to cancel the tooltip
Ext.override(Ext.ToolTip, {
show: function () {
if (this.anchor) {
this.showAt([-1000, -1000]);
this.origConstrainPosition = this.constrainPosition;
this.constrainPosition = false;
this.anchor = this.origAnchor;
}
this.showAt(this.getTargetXY());
if (this.anchor) {
this.anchorEl.show();
this.syncAnchor();
this.constrainPosition = this.origConstrainPosition;
// added "if (this.anchorEl)"
} else if (this.anchorEl) {
this.anchorEl.hide();
}
},
showAt: function (xy) {
this.lastActive = new Date();
this.clearTimers();
Ext.ToolTip.superclass.showAt.call(this, xy);
if (this.dismissDelay && this.autoHide !== false) {
this.dismissTimer = this.hide.defer(this.dismissDelay, this);
}
if (this.anchor && !this.anchorEl.isVisible()) {
this.syncAnchor();
this.anchorEl.show();
// added "if (this.anchorEl)"
} else if (this.anchorEl) {
this.anchorEl.hide();
}
}
});
// override 3.4.0 to ensure that the grid stops editing if the view is refreshed
// actual bug: removing grid lines with active lookup editor didn't hide editor
Ext.grid.GridView.prototype.processRows =
Ext.grid.GridView.prototype.processRows.createInterceptor(function () {
if (this.grid) {
this.grid.stopEditing(true);
}
});
// override 3.4.0 to fix issue with chart labels losing their labelRenderer after hide/show
Ext.override(Ext.chart.CartesianChart, {
createAxis: function (axis, value) {
var o = Ext.apply({}, value),
ref,
old;
if (this[axis]) {
old = this[axis].labelFunction;
this.removeFnProxy(old);
this.labelFn.remove(old);
}
if (o.labelRenderer) {
ref = this.getFunctionRef(o.labelRenderer);
o.labelFunction = this.createFnProxy(function (v) {
return ref.fn.call(ref.scope, v);
});
// delete o.labelRenderer; // <-- commented out this line
this.labelFn.push(o.labelFunction);
}
if (axis.indexOf('xAxis') > -1 && o.position == 'left') {
o.position = 'bottom';
}
return o;
}
});
// override 3.4.0 to allow tabbing between editable grid cells to work correctly
Ext.override(Ext.grid.RowSelectionModel, {
acceptsNav: function (row, col, cm) {
if (!cm.isHidden(col) && cm.isCellEditable(col, row)) {
// check that there is actually an editor
if (cm.getCellEditor) {
return !!cm.getCellEditor(col, row);
}
return true;
}
return false;
}
});
// override to allow menu items to have a tooltip property
Ext.override(Ext.menu.Item, {
onRender : function(container, position){
if (!this.itemTpl) {
this.itemTpl = Ext.menu.Item.prototype.itemTpl = new Ext.XTemplate(
'<a id="{id}" class="{cls} x-unselectable" hidefocus="true" unselectable="on" href="{href}"',
'<tpl if="hrefTarget">',
' target="{hrefTarget}"',
'</tpl>',
'>',
'<img src="{icon}" class="x-menu-item-icon {iconCls}"/>',
'<span class="x-menu-item-text">{text}</span>',
'</a>'
);
}
var a = this.getTemplateArgs();
this.el = position ? this.itemTpl.insertBefore(position, a, true) : this.itemTpl.append(container, a, true);
this.iconEl = this.el.child('img.x-menu-item-icon');
this.textEl = this.el.child('.x-menu-item-text');
if (this.tooltip) {
this.tooltip = new Ext.ToolTip(Ext.apply({
target: this.el
}, Ext.isObject(this.tooltip) ? this.toolTip : { html: this.tooltip }));
}
Ext.menu.Item.superclass.onRender.call(this, container, position);
}
});
| smgallo/xdmod | html/gui/js/CCR.js | JavaScript | lgpl-3.0 | 63,227 |
/**
* This file is part of ComilaJS.
*
* ComilaJS is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* ComilaJS 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with ComilaJS. If not, see <http://www.gnu.org/licenses/>.
*/
var RowReference = require('./../Reference/RowReference');
var TableIndexes = require('./../Constant/TableIndexes');
/**
* Class ConstantRow.
*
* @param {CILParser} reader
* The CIL reader.
*
* @constructor
* @struct
*/
function CustomAttributeRow (reader) {
'use strict';
/**
* The reference to the parent row.
*
* @type {RowReference}
*/
this.parent = new RowReference(reader, [
TableIndexes.METHOD_DEF,
TableIndexes.FIELD,
TableIndexes.TYPE_REF,
TableIndexes.TYPE_DEF,
TableIndexes.PARAM,
TableIndexes.INTERFACE_IMPL,
TableIndexes.MEMBER_REF,
TableIndexes.MODULE,
-1,
TableIndexes.PROPERTY,
TableIndexes.EVENT,
TableIndexes.STAND_ALONE_SIG,
TableIndexes.MODULE_REF,
TableIndexes.TYPE_SPEC,
TableIndexes.ASSEMBLY,
TableIndexes.ASSEMBLY_REF,
TableIndexes.FILE,
TableIndexes.EXPORTED_TYPE,
TableIndexes.MANIFEST_RESOURCE
]);
/**
* The reference to the type row.
*
* @type {RowReference}
*/
this.type = new RowReference(reader, [
-1,
-1,
TableIndexes.METHOD_DEF,
TableIndexes.MEMBER_REF,
-1
]);
/**
* The value as an index into the blob heap.
*
* @type {number}
*/
this.value = reader.readBlobIndex();
}
module.exports = CustomAttributeRow;
| danitso/comlajs | src/Parser/Row/CustomAttributeRow.js | JavaScript | lgpl-3.0 | 2,006 |
function TextNodeAnchorProvider(){
this._selector;
this._anchor;
}
TextNodeAnchorProvider.prototype = new AnchorProvider();
TextNodeAnchorProvider.prototype.constructor = TextNodeAnchorProvider;
TextNodeAnchorProvider.prototype.getAnchor = function(template, selector){
checkType(template, MbaDom);
checkType(selector, 'string');
this._selector = selector;
this._anchor = template.find(this._selector);
var textNodeElements = [];
if(this.anchorContainsOneAndOnlyOneTextNode()){
for(var i=0 ; i<this._anchor.getLength() ; i++){
textNodeElements.push(this._anchor.getElement(i).childNodes[0]);
}
}
else
this.throwAnError();
return new MbaAnchor(textNodeElements);
};
TextNodeAnchorProvider.prototype.anchorElementHasNotOnlyOneChild = function(anchorElement){
checkType(anchorElement, 'dom');
var children = anchorElement.childNodes;
return children.length != 1;
};
TextNodeAnchorProvider.prototype.theOnlyChildIsNotATextNode = function(anchorElement){
checkType(anchorElement, 'dom');
return !isATextNode(anchorElement.childNodes[0]);
};
TextNodeAnchorProvider.prototype.anchorContainsOneAndOnlyOneTextNode = function(){
for(var i=0 ; i<this._anchor.getLength() ; i++){
var anchorElement = this._anchor.getElement(i);
if(this.anchorElementHasNotOnlyOneChild(anchorElement)
|| this.theOnlyChildIsNotATextNode(anchorElement))
return false;
}
return true;
};
TextNodeAnchorProvider.prototype.throwAnError = function(){
throw new Error('The elements found with \''+this._selector+'\' css selector are not empty.\n'
+'You can\'t bind into their innerHTML, did you want to bind into an HTML attribute '
+'('+this._selector+'@value) or a dom property ('+this._selector+'$value) ?');
}; | amoissant/mambajs | Mamba/js/TextNodeAnchorProvider.js | JavaScript | lgpl-3.0 | 1,901 |
// onblur事件
// 如果用户试图让这个页面退到后面(这会触发onblur 处理程
// 序),脚本会迫使它再次回到前面。
window.onblur = moveUp; // 没能看到效果,可能有特别的设置吧
function moveUp() {
self.focus();
}
// onblur 事件的另一种更讨厌的用途:广告发布者在你浏览的当前网页后面悄
// 悄地打开一个广告窗口,直到你关闭了当前窗口,才发现后面已经堆了很多窗口。人们往
// 往把这归罪于他们打开的最后一个Web 站点,但是实际上广告可能是更早之前浏览的页面
// 所创建的。
// onblur还有其他的用法
| Litfeature/litfeature.github.io | demo/Origin JavaScript/JavaScript基础教程(第8版)/Chapter 08/js/08-04.js | JavaScript | lgpl-3.0 | 707 |
//////////////////////////////////////////////
// Mapa Digital de México v6.0 //
// //
//////////////////////////////////////////////
eval((function(x){var d="";var p=0;while(p<x.length){if(x.charAt(p)!="`")d+=x.charAt(p++);else{var l=x.charCodeAt(p+3)-28;if(l>4)d+=d.substr(d.length-x.charCodeAt(p+1)*96-x.charCodeAt(p+2)+3104-l,l);else d+="`";p+=4}}return d})("define(function () {amplify.subscribe(\"mapBeforeLoad\", ` C)});amplify.subscribe(\"mapBe` \"MAfter` %IRel` #HFeatureAdde` G*data` S\"return;});")) | MxSIG/mxsig | mxsig/js/core/events.js | JavaScript | lgpl-3.0 | 520 |
/*!
* Copyright (c) Metaways Infosystems GmbH, 2011
* LGPLv3, http://www.arcavias.com/en/license
*/
Ext.ns('Ext.ux.AdvancedSearch');
/**
* operator and value part of a search criteria
*
* @namespace Ext.ux.AdvancedSearch
* @class Ext.ux.AdvancedSearch.Filter
* @extends Ext.Container
*/
Ext.ux.AdvancedSearch.Filter = Ext.extend(Ext.Container, {
defaultOperator : null,
defaultValue : null,
operator : null,
operatorFieldConfig : null,
value : null,
valueFieldConfig : null,
layout : 'hbox',
layoutConfig : {
pack : 'start'
},
getOperator : function() {
return this.operatorField.getValue();
},
getValue : function() {
return this.valueField.getValue();
},
initComponent : function() {
this.initOperatorField();
this.initValueField();
this.items = [Ext.applyIf(this.operatorField, {
flex : 1
}), Ext.applyIf(this.valueField, {
flex : 2
})];
Ext.ux.AdvancedSearch.Filter.superclass.initComponent.call(this);
},
initOperatorField : function() {
this.operatorStore = new Ext.data.ArrayStore({
fields : ['operator', 'displayText']
});
Ext.each(this.operators, function(operator) {
this.operatorStore.loadData([[operator, _(operator)]], true);
}, this);
this.operatorField = Ext.ComponentMgr.create(Ext.apply({
xtype : 'combo',
typeAhead : true,
triggerAction : 'all',
lazyRender : true,
forceSelection : true,
mode : 'local',
store : this.operatorStore,
valueField : 'operator',
displayField : 'displayText',
isValid : function(preventMark) {
var val = this.getRawValue();
var rec = this.findRecord(this.valueField, val);
var isValid = Ext.form.ComboBox.prototype.isValid.apply(this, arguments);
if(!isValid || !rec) {
if(!preventMark) {
this.markInvalid(this.blankText);
}
return false;
}
return true;
},
value : this.operator ? this.operator : this.defaultOperator,
listeners : {
scope : this,
select : this.onOperatorSelect
}
}, this.operatorFieldConfig));
},
initValueField : function() {
this.valueField = Ext.ComponentMgr.create(Ext.apply({
xtype : 'textfield',
selectOnFocus : true,
listeners : {
scope : this,
specialkey : function(field, e) {
if(e.getKey() == e.ENTER) {
this.fireEvent('filtertrigger', this);
}
}
},
isValid : function(preventMark) {
var isValid = Ext.form.TextField.prototype.isValid.apply(this, arguments), val = this.getRawValue();
if(!isValid || !Ext.isString(val)) {
if(!preventMark) {
this.markInvalid();
}
return false;
}
return true;
}
}, this.valueFieldConfig));
},
isValid : function(preventMark) {
return this.isValidOperator(preventMark) && this.isValidValue(preventMark);
},
isValidOperator : function(preventMark) {
return this.operatorField.isValid(preventMark);
},
isValidValue : function(preventMark) {
return this.valueField.isValid(preventMark);
},
onOperatorSelect : function(combo, newRecord, newKey) {
},
setOperator : function(operator) {
this.operatorField.setValue(operator);
return this;
},
setValue : function(value) {
this.valueField.setValue(value);
return this;
}
});
| Arcavias/arcavias-core | client/extjs/lib/ext.ux/AdvancedSearch/Filter.js | JavaScript | lgpl-3.0 | 4,034 |
export const VALID_ORG_RESOURCE_NO_ID = {
"type": "organizations",
"attributes": {
"name": "Test Organization"
},
"relationships": {
"liaisons": {
"data": [{"type": "people", "id": "53f54dd98d1e62ff12539db3"}]
}
}
};
export const VALID_ORG_RESOURCE_NO_ID_EXTRA_MEMBER = Object.assign(
{"extraMember": true}, VALID_ORG_RESOURCE_NO_ID
);
export const ORG_RESOURCE_CLIENT_ID = Object.assign(
{"id": "53f54dd98d1e62ff12539db3"}, VALID_ORG_RESOURCE_NO_ID
);
export const VALID_SCHOOL_RESOURCE_NO_ID = {
"type": "schools",
"attributes": {
"name": "Test School"
}
};
export const INVALID_ORG_RESOURCE_NO_DATA_IN_RELATIONSHIP = {
"type": "organizations",
"relationships": {
"liaisons": {
"type": "people", "id": "53f54dd98d1e62ff12539db3"
}
}
};
| beni55/json-api | test/integration/fixtures/creation.js | JavaScript | lgpl-3.0 | 804 |
var searchData=
[
['thermalbody',['ThermalBody',['../d2/d2b/classmknix_1_1_thermal_body.html#a41c675feaab004c04ff4f5ae0fb8a27e',1,'mknix::ThermalBody::ThermalBody()'],['../d2/d2b/classmknix_1_1_thermal_body.html#ac80f8070e47d8467ff2818a9d9095a8c',1,'mknix::ThermalBody::ThermalBody(std::string)']]],
['translate',['translate',['../dd/de3/classmknix_1_1_body.html#a5f58f8e5398bbacc973b046be600eb5f',1,'mknix::Body']]],
['type',['type',['../df/d86/classmknix_1_1_analysis.html#a6dd7026a22ae11f3eef3dad3be370e70',1,'mknix::Analysis::type()'],['../d4/d8c/classmknix_1_1_analysis_dynamic.html#a10045ff80be02d24dc08ad7da248844f',1,'mknix::AnalysisDynamic::type()'],['../db/d8f/classmknix_1_1_analysis_static.html#a14ab31bf7d144b576cbc7ea8de0d4fd9',1,'mknix::AnalysisStatic::type()'],['../d5/dd9/classmknix_1_1_analysis_thermal_dynamic.html#ae1d271bfca189706a101259cff192ec9',1,'mknix::AnalysisThermalDynamic::type()'],['../d4/d3e/classmknix_1_1_analysis_thermal_static.html#a14a7b53403f7523ccb783129e928241b',1,'mknix::AnalysisThermalStatic::type()'],['../da/df3/classmknix_1_1_analysis_thermo_mechanical_dynamic.html#ad6a3d20e5522565eaa53854f1f65e808',1,'mknix::AnalysisThermoMechanicalDynamic::type()']]]
];
| daniel-iglesias/mknix | doc/html/search/functions_f.js | JavaScript | lgpl-3.0 | 1,210 |
/*!
* Copyright(c) 2018 Jan Blaha
*/
class Resources {
constructor (reporter, definition) {
this.reporter = reporter
this.definition = definition
if (!this.reporter.documentStore.model.entityTypes.TemplateType) {
throw new Error('resources extension depends on templates extension')
}
this.reporter.beforeRenderListeners.insert({
after: 'data',
before: 'scripts'
}, definition.name, this, this.handleBeforeRender.bind(this))
this.reporter.documentStore.registerComplexType('ResourceRefType', {
shortid: {type: 'Edm.String', referenceTo: 'data'},
entitySet: {type: 'Edm.String'}
})
this.reporter.documentStore.registerComplexType('ResourcesType', {
items: {type: 'Collection(jsreport.ResourceRefType)'},
defaultLanguage: {type: 'Edm.String'}
})
this.reporter.documentStore.model.entityTypes['TemplateType'].resources = {type: 'jsreport.ResourcesType'}
}
async handleBeforeRender (request, response) {
if (!request.template.resources || !request.template.resources.items || request.template.resources.items.length < 1) {
this.reporter.logger.debug('Resources not defined for this template.', request)
return
}
const resources = await Promise.all(request.template.resources.items.map(async (r) => {
const res = await this.reporter.documentStore.collection(r.entitySet).find({shortid: r.shortid}, request)
if (res.length < 1) {
throw this.reporter.createError(`Data item with shortid ${r.shortid} was not found (resource lookup)`, {
statusCode: 404
})
}
return res[0]
}))
resources.forEach((r) => (r.data = JSON.parse(r.dataJson)))
request.options.resources = resources
request.data['$resources'] = resources
const resourcesByName = {}
resources.forEach((r) => (resourcesByName[r.name] = r.data))
request.options.resource = resourcesByName
request.data['$resource'] = resourcesByName
if (request.options.language || (request.template.resources && request.template.resources.defaultLanguage)) {
let languageUsed
let applicableResources = []
if (request.options.language) {
languageUsed = request.options.language
applicableResources = resources.filter((r) => r.name.startsWith(`${languageUsed}-`))
}
if (!applicableResources.length && request.template.resources && request.template.resources.defaultLanguage) {
languageUsed = request.template.resources.defaultLanguage
applicableResources = resources.filter((r) => r.name.startsWith(`${languageUsed}-`))
}
this.reporter.logger.debug(`Found ${applicableResources.length} resources for language "${languageUsed}"`, request)
request.options.localizedResources = applicableResources
request.data['$localizedResources'] = applicableResources
const localizedResourceByName = {}
applicableResources.forEach((r) => {
localizedResourceByName[r.name.substring(`${languageUsed}-`.length)] = r.data
})
request.options.localizedResource = applicableResources.length === 1 ? applicableResources[0].data : localizedResourceByName
request.data['$localizedResource'] = request.options.localizedResource
}
}
}
module.exports = function (reporter, definition) {
reporter.resources = new Resources(reporter, definition)
}
| jsreport/jsreport-resources | lib/resources.js | JavaScript | lgpl-3.0 | 3,404 |
// Written by Jürgen Moßgraber - mossgrabers.de
// Michael Schmalle - teotigraphix.com
// (c) 2014-2016
// Licensed under LGPLv3 - http://www.gnu.org/licenses/lgpl-3.0.txt
function CursorDeviceProxy (cursorDevice, numSends, numParams, numDevicesInBank, numDeviceLayers, numDrumPadLayers)
{
this.cursorDevice = cursorDevice;
this.numSends = numSends;
this.numParams = numParams ? numParams : 8;
this.numDevicesInBank = numDevicesInBank ? numDevicesInBank : 8;
this.numDeviceLayers = numDeviceLayers ? numDeviceLayers : 8;
this.numDrumPadLayers = numDrumPadLayers ? numDrumPadLayers : 16;
this.canSelectPrevious = true;
this.canSelectNext = true;
this.hasNextParamPage = true;
this.hasPreviousParamPage = true;
this.canScrollLayersUpValue = true;
this.canScrollLayersDownValue = true;
this.textLength = GlobalConfig.CURSOR_DEVICE_TEXT_LENGTH;
this.isWindowOpenValue = false;
this.hasDrumPadsValue = false;
this.isNestedValue = false;
this.hasLayersValue = false;
this.hasSlotsValue = false;
this.isExpandedValue = false;
this.isMacroSectionVisibleValue = false;
this.isParameterPageSectionVisibleValue = false;
this.selectedParameterPage = -1;
this.parameterPageNames = null;
this.fxparams = this.createFXParams (this.numParams);
this.commonParams = this.createFXParams (this.numParams);
this.envelopeParams = this.createFXParams (this.numParams);
// There are only 8 macro parameters
this.macroParams = this.createFXParams (Math.min (8, this.numParams));
this.modulationParams = this.createFXParams (this.numParams);
this.selectedDevice =
{
name: 'None',
enabled: false
};
this.directParameters = [];
this.numDirectPageBank = 0;
this.directParameterPageNames = [];
this.currentDirectParameterPage = 0;
this.directParameterObservationEnabled = false;
this.deviceBanks = [];
this.drumPadBanks = [];
this.position = 0;
this.siblingDevices = initArray ("", this.numDevicesInBank);
this.isMacroMappings = initArray (false, this.numParams);
this.cursorDevice.addIsEnabledObserver (doObject (this, CursorDeviceProxy.prototype.handleIsEnabled));
this.cursorDevice.addIsPluginObserver (doObject (this, CursorDeviceProxy.prototype.handleIsPlugin));
this.cursorDevice.addPositionObserver (doObject (this, CursorDeviceProxy.prototype.handlePosition));
this.cursorDevice.addNameObserver (34, 'None', doObject (this, CursorDeviceProxy.prototype.handleName));
this.cursorDevice.addCanSelectPreviousObserver (doObject (this, CursorDeviceProxy.prototype.handleCanSelectPrevious));
this.cursorDevice.addCanSelectNextObserver (doObject (this, CursorDeviceProxy.prototype.handleCanSelectNext));
this.cursorDevice.addPreviousParameterPageEnabledObserver (doObject (this, CursorDeviceProxy.prototype.handlePreviousParameterPageEnabled));
this.cursorDevice.addNextParameterPageEnabledObserver (doObject (this, CursorDeviceProxy.prototype.handleNextParameterPageEnabled));
this.cursorDevice.addSelectedPageObserver (-1, doObject (this, CursorDeviceProxy.prototype.handleSelectedPage));
this.cursorDevice.addPageNamesObserver(doObject (this, CursorDeviceProxy.prototype.handlePageNames));
this.cursorDevice.isExpanded ().addValueObserver (doObject (this, CursorDeviceProxy.prototype.handleIsExpanded));
this.cursorDevice.isMacroSectionVisible ().addValueObserver (doObject (this, CursorDeviceProxy.prototype.handleIsMacroSectionVisible));
this.cursorDevice.isParameterPageSectionVisible ().addValueObserver (doObject (this, CursorDeviceProxy.prototype.handleIsParameterPageSectionVisible));
var i;
var p;
for (i = 0; i < this.numParams; i++)
{
p = this.getParameter (i);
p.addNameObserver (this.textLength, '', doObjectIndex (this, i, CursorDeviceProxy.prototype.handleParameterName));
p.addValueObserver (Config.maxParameterValue, doObjectIndex (this, i, CursorDeviceProxy.prototype.handleValue));
p.addValueDisplayObserver (this.textLength, '', doObjectIndex (this, i, CursorDeviceProxy.prototype.handleValueDisplay));
p = this.getCommonParameter (i);
p.addNameObserver (this.textLength, '', doObjectIndex (this, i, CursorDeviceProxy.prototype.handleCommonParameterName));
p.addValueObserver (Config.maxParameterValue, doObjectIndex (this, i, CursorDeviceProxy.prototype.handleCommonValue));
p.addValueDisplayObserver (this.textLength, '', doObjectIndex (this, i, CursorDeviceProxy.prototype.handleCommonValueDisplay));
p = this.getEnvelopeParameter (i);
p.addNameObserver (this.textLength, '', doObjectIndex (this, i, CursorDeviceProxy.prototype.handleEnvelopeParameterName));
p.addValueObserver (Config.maxParameterValue, doObjectIndex (this, i, CursorDeviceProxy.prototype.handleEnvelopeValue));
p.addValueDisplayObserver (this.textLength, '', doObjectIndex (this, i, CursorDeviceProxy.prototype.handleEnvelopeValueDisplay));
p = this.getMacro (i);
p.addLabelObserver (this.textLength, '', doObjectIndex (this, i, CursorDeviceProxy.prototype.handleMacroParameterName));
var amount = p.getAmount ();
amount.addValueObserver (Config.maxParameterValue, doObjectIndex (this, i, CursorDeviceProxy.prototype.handleMacroValue));
amount.addValueDisplayObserver (this.textLength, '', doObjectIndex (this, i, CursorDeviceProxy.prototype.handleMacroValueDisplay));
var mod = p.getModulationSource ();
mod.addIsMappingObserver (doObjectIndex (this, i, CursorDeviceProxy.prototype.handleIsMapping));
p = this.getModulationSource (i);
p.addNameObserver (this.textLength, '', doObjectIndex (this, i, CursorDeviceProxy.prototype.handleModulationSourceName));
p.addIsMappingObserver (doObjectIndex (this, i, CursorDeviceProxy.prototype.handleModulationSourceIsMapping));
}
this.cursorDevice.addDirectParameterIdObserver (doObject (this, CursorDeviceProxy.prototype.handleDirectParameterIds));
this.cursorDevice.addDirectParameterNameObserver (this.textLength, doObject (this, CursorDeviceProxy.prototype.handleDirectParameterNames));
this.directParameterValueDisplayObserver = this.cursorDevice.addDirectParameterValueDisplayObserver (this.textLength, doObject (this, CursorDeviceProxy.prototype.handleDirectParameterValueDisplay));
this.cursorDevice.addDirectParameterNormalizedValueObserver (doObject (this, CursorDeviceProxy.prototype.handleDirectParameterValue));
this.cursorDevice.isWindowOpen ().addValueObserver (doObject (this, CursorDeviceProxy.prototype.handleIsWindowOpen));
this.cursorDevice.isNested ().addValueObserver (doObject (this, CursorDeviceProxy.prototype.handleIsNested));
this.cursorDevice.hasDrumPads ().addValueObserver (doObject (this, CursorDeviceProxy.prototype.handleHasDrumPads));
this.cursorDevice.hasLayers ().addValueObserver (doObject (this, CursorDeviceProxy.prototype.handleHasLayers));
this.cursorDevice.hasSlots ().addValueObserver (doObject (this, CursorDeviceProxy.prototype.handleHasSlots));
// Monitor the sibling devices of the cursor device
this.siblings = this.cursorDevice.createSiblingsDeviceBank (this.numDevicesInBank);
for (i = 0; i < this.numDevicesInBank; i++)
{
var sibling = this.siblings.getDevice (i);
sibling.addNameObserver (this.textLength, '', doObjectIndex (this, i, CursorDeviceProxy.prototype.handleSiblingName));
}
// Monitor the layers of a container device (if any)
this.cursorDeviceLayer = this.cursorDevice.createCursorLayer ();
this.cursorDeviceLayer.addCanSelectPreviousObserver (doObject (this, CursorDeviceProxy.prototype.handleCanScrollLayerDown));
this.cursorDeviceLayer.addCanSelectNextObserver (doObject (this, CursorDeviceProxy.prototype.handleCanScrollLayerUp));
this.layerBank = this.cursorDevice.createLayerBank (this.numDeviceLayers);
this.deviceLayers = this.createDeviceLayers (this.numDeviceLayers);
var layer;
var v;
var j;
var s;
for (i = 0; i < this.numDeviceLayers; i++)
{
layer = this.layerBank.getChannel (i);
layer.exists ().addValueObserver (doObjectIndex (this, i, CursorDeviceProxy.prototype.handleLayerExists));
layer.isActivated ().addValueObserver (doObjectIndex (this, i, CursorDeviceProxy.prototype.handleLayerActivated));
layer.addIsSelectedObserver (doObjectIndex (this, i, CursorDeviceProxy.prototype.handleLayerSelection));
layer.addNameObserver (this.textLength, '', doObjectIndex (this, i, CursorDeviceProxy.prototype.handleLayerName));
v = layer.getVolume ();
v.addValueObserver (Config.maxParameterValue, doObjectIndex (this, i, CursorDeviceProxy.prototype.handleLayerVolume));
v.addValueDisplayObserver (this.textLength, '', doObjectIndex (this, i, CursorDeviceProxy.prototype.handleLayerVolumeStr));
p = layer.getPan ();
p.addValueObserver (Config.maxParameterValue, doObjectIndex (this, i, CursorDeviceProxy.prototype.handleLayerPan));
p.addValueDisplayObserver (this.textLength, '', doObjectIndex (this, i, CursorDeviceProxy.prototype.handleLayerPanStr));
layer.addVuMeterObserver (Config.maxParameterValue, -1, true, doObjectIndex (this, i, CursorDeviceProxy.prototype.handleLayerVUMeters));
layer.getMute ().addValueObserver (doObjectIndex (this, i, CursorDeviceProxy.prototype.handleLayerMute));
layer.getSolo ().addValueObserver (doObjectIndex (this, i, CursorDeviceProxy.prototype.handleLayerSolo));
layer.addColorObserver (doObjectIndex (this, i, CursorDeviceProxy.prototype.handleLayerColor));
// Sends values & texts
for (j = 0; j < this.numSends; j++)
{
s = layer.getSend (j);
if (s == null)
continue;
s.addNameObserver (this.textLength, '', doObjectDoubleIndex (this, i, j, CursorDeviceProxy.prototype.handleLayerSendName));
s.addValueObserver (Config.maxParameterValue, doObjectDoubleIndex (this, i, j, CursorDeviceProxy.prototype.handleLayerSendVolume));
s.addValueDisplayObserver (this.textLength, '', doObjectDoubleIndex (this, i, j, CursorDeviceProxy.prototype.handleLayerSendVolumeStr));
}
this.deviceBanks[i] = layer.createDeviceBank (this.numDevicesInBank);
}
// Monitor the drum pad layers of a container device (if any)
this.drumPadBank = this.cursorDevice.createDrumPadBank (this.numDrumPadLayers);
this.drumPadLayers = this.createDeviceLayers (this.numDrumPadLayers);
for (i = 0; i < this.numDrumPadLayers; i++)
{
layer = this.drumPadBank.getChannel (i);
layer.exists ().addValueObserver (doObjectIndex (this, i, CursorDeviceProxy.prototype.handleDrumPadExists));
layer.isActivated ().addValueObserver (doObjectIndex (this, i, CursorDeviceProxy.prototype.handleDrumPadActivated));
layer.addIsSelectedObserver (doObjectIndex (this, i, CursorDeviceProxy.prototype.handleDrumPadSelection));
layer.addNameObserver (this.textLength, '', doObjectIndex (this, i, CursorDeviceProxy.prototype.handleDrumPadName));
v = layer.getVolume ();
v.addValueObserver (Config.maxParameterValue, doObjectIndex (this, i, CursorDeviceProxy.prototype.handleDrumPadVolume));
v.addValueDisplayObserver (this.textLength, '', doObjectIndex (this, i, CursorDeviceProxy.prototype.handleDrumPadVolumeStr));
p = layer.getPan ();
p.addValueObserver (Config.maxParameterValue, doObjectIndex (this, i, CursorDeviceProxy.prototype.handleDrumPadPan));
p.addValueDisplayObserver (this.textLength, '', doObjectIndex (this, i, CursorDeviceProxy.prototype.handleDrumPadPanStr));
layer.addVuMeterObserver (Config.maxParameterValue, -1, true, doObjectIndex (this, i, CursorDeviceProxy.prototype.handleDrumPadVUMeters));
layer.getMute ().addValueObserver (doObjectIndex (this, i, CursorDeviceProxy.prototype.handleDrumPadMute));
layer.getSolo ().addValueObserver (doObjectIndex (this, i, CursorDeviceProxy.prototype.handleDrumPadSolo));
layer.addColorObserver (doObjectIndex (this, i, CursorDeviceProxy.prototype.handleDrumPadColor));
// Sends values & texts
for (j = 0; j < this.numSends; j++)
{
s = layer.getSend (j);
if (s == null)
continue;
s.addNameObserver (this.textLength, '', doObjectDoubleIndex (this, i, j, CursorDeviceProxy.prototype.handleDrumPadSendName));
s.addValueObserver (Config.maxParameterValue, doObjectDoubleIndex (this, i, j, CursorDeviceProxy.prototype.handleDrumPadSendVolume));
s.addValueDisplayObserver (this.textLength, '', doObjectDoubleIndex (this, i, j, CursorDeviceProxy.prototype.handleDrumPadSendVolumeStr));
}
this.drumPadBanks[i] = layer.createDeviceBank (this.numDevicesInBank);
}
}
//--------------------------------------
// Bitwig Device API
//--------------------------------------
CursorDeviceProxy.prototype.getSiblingDeviceName = function (index)
{
return this.siblingDevices[index];
};
CursorDeviceProxy.prototype.getPositionInChain = function ()
{
return this.position;
};
CursorDeviceProxy.prototype.getPositionInBank = function ()
{
return this.position % this.numDevicesInBank;
};
CursorDeviceProxy.prototype.getCommonParameter = function (index)
{
return this.cursorDevice.getCommonParameter (index);
};
CursorDeviceProxy.prototype.getEnvelopeParameter = function (index)
{
return this.cursorDevice.getEnvelopeParameter (index);
};
CursorDeviceProxy.prototype.getMacro = function (index)
{
return this.cursorDevice.getMacro (index);
};
CursorDeviceProxy.prototype.getModulationSource = function (index)
{
return this.cursorDevice.getModulationSource (index);
};
CursorDeviceProxy.prototype.getParameter = function (indexInPage)
{
return this.cursorDevice.getParameter (indexInPage);
};
CursorDeviceProxy.prototype.setParameter = function (index, value)
{
this.getParameter (index).set (value, Config.maxParameterValue);
};
CursorDeviceProxy.prototype.resetParameter = function (index)
{
this.getParameter (index).reset ();
};
CursorDeviceProxy.prototype.nextParameterPage = function ()
{
return this.cursorDevice.nextParameterPage ();
};
CursorDeviceProxy.prototype.previousParameterPage = function ()
{
return this.cursorDevice.previousParameterPage ();
};
CursorDeviceProxy.prototype.hasPreviousParameterPage = function ()
{
return this.hasPreviousParamPage;
};
CursorDeviceProxy.prototype.hasNextParameterPage = function ()
{
return this.hasNextParamPage;
};
CursorDeviceProxy.prototype.getParameterPageNames = function ()
{
return this.parameterPageNames;
};
CursorDeviceProxy.prototype.getSelectedParameterPageName = function ()
{
return this.selectedParameterPage >= 0 ? this.parameterPageNames[this.selectedParameterPage] : "";
};
CursorDeviceProxy.prototype.getSelectedParameterPage = function ()
{
return this.selectedParameterPage;
};
CursorDeviceProxy.prototype.setSelectedParameterPage = function (index)
{
this.cursorDevice.setParameterPage (index);
};
CursorDeviceProxy.prototype.toggleEnabledState = function ()
{
this.cursorDevice.toggleEnabledState ();
};
CursorDeviceProxy.prototype.canSelectPreviousFX = function ()
{
return this.canSelectPrevious;
};
CursorDeviceProxy.prototype.canSelectNextFX = function ()
{
return this.canSelectNext;
};
CursorDeviceProxy.prototype.selectNext = function ()
{
var moveBank = this.getPositionInBank () == 7;
this.cursorDevice.selectNext ();
if (moveBank)
this.selectNextBank ();
};
CursorDeviceProxy.prototype.selectPrevious = function ()
{
var moveBank = this.getPositionInBank () == 0;
this.cursorDevice.selectPrevious ();
if (moveBank)
this.selectPreviousBank ();
};
CursorDeviceProxy.prototype.selectSibling = function (index)
{
this.cursorDevice.selectDevice (this.siblings.getDevice (index));
};
CursorDeviceProxy.prototype.selectNextBank = function ()
{
this.siblings.scrollPageDown ();
};
CursorDeviceProxy.prototype.selectPreviousBank = function ()
{
this.siblings.scrollPageUp ();
};
CursorDeviceProxy.prototype.hasSelectedDevice = function ()
{
return this.selectedDevice.name != 'None';
};
CursorDeviceProxy.prototype.getSelectedDevice = function ()
{
return this.selectedDevice;
};
CursorDeviceProxy.prototype.getFXParam = function (index)
{
return this.fxparams[index];
};
CursorDeviceProxy.prototype.getCommonParam = function (index)
{
return this.commonParams[index];
};
CursorDeviceProxy.prototype.getEnvelopeParam = function (index)
{
return this.envelopeParams[index];
};
CursorDeviceProxy.prototype.getMacroParam = function (index)
{
return this.macroParams[index];
};
CursorDeviceProxy.prototype.getModulationParam = function (index)
{
return this.modulationParams[index];
};
CursorDeviceProxy.prototype.isWindowOpen = function ()
{
return this.isWindowOpenValue;
};
CursorDeviceProxy.prototype.toggleWindowOpen = function ()
{
this.cursorDevice.isWindowOpen ().toggle ();
};
CursorDeviceProxy.prototype.isExpanded = function ()
{
return this.isExpandedValue;
};
CursorDeviceProxy.prototype.toggleExpanded = function ()
{
this.cursorDevice.isExpanded ().toggle ();
};
CursorDeviceProxy.prototype.isMacroSectionVisible = function ()
{
return this.isMacroSectionVisibleValue;
};
CursorDeviceProxy.prototype.toggleMacroSectionVisible = function ()
{
this.cursorDevice.isMacroSectionVisible ().toggle ();
};
CursorDeviceProxy.prototype.isParameterPageSectionVisible = function ()
{
return this.isParameterPageSectionVisibleValue;
};
CursorDeviceProxy.prototype.toggleParameterPageSectionVisible = function ()
{
this.cursorDevice.isParameterPageSectionVisible ().toggle ();
};
CursorDeviceProxy.prototype.isNested = function ()
{
return this.isNestedValue;
};
CursorDeviceProxy.prototype.hasSlots = function ()
{
return this.hasSlotsValue;
};
CursorDeviceProxy.prototype.isMacroMapping = function (index)
{
return this.isMacroMappings[index];
};
//--------------------------------------
// Layer & Drum Pad Abstraction
//--------------------------------------
CursorDeviceProxy.prototype.getLayerOrDrumPad = function (index)
{
return this.hasDrumPads () ? this.getDrumPad (index) : this.getLayer (index);
};
CursorDeviceProxy.prototype.getSelectedLayerOrDrumPad = function ()
{
return this.hasDrumPads () ? this.getSelectedDrumPad () : this.getSelectedLayer ();
};
CursorDeviceProxy.prototype.selectLayerOrDrumPad = function (index)
{
if (this.hasDrumPads ())
this.selectDrumPad (index);
else
this.selectLayer (index);
};
CursorDeviceProxy.prototype.previousLayerOrDrumPad = function ()
{
if (this.hasDrumPads ())
this.previousDrumPad ();
else
this.previousLayer ();
};
CursorDeviceProxy.prototype.previousLayerOrDrumPadBank = function ()
{
if (this.hasDrumPads ())
this.previousDrumPadBank ();
else
this.previousLayerBank ();
};
CursorDeviceProxy.prototype.nextLayerOrDrumPad = function ()
{
if (this.hasDrumPads ())
this.nextDrumPad ();
else
this.nextLayer ();
};
CursorDeviceProxy.prototype.nextLayerOrDrumPadBank = function ()
{
if (this.hasDrumPads ())
this.nextDrumPadBank ();
else
this.nextLayerBank ();
};
CursorDeviceProxy.prototype.enterLayerOrDrumPad = function (index)
{
if (this.hasDrumPads ())
this.enterDrumPad (index);
else
this.enterLayer (index);
};
CursorDeviceProxy.prototype.selectFirstDeviceInLayerOrDrumPad = function (index)
{
if (this.hasDrumPads ())
this.selectFirstDeviceInDrumPad (index);
else
this.selectFirstDeviceInLayer (index);
};
CursorDeviceProxy.prototype.canScrollLayersOrDrumPadsUp = function ()
{
return this.hasDrumPads () ? this.canScrollDrumPadsUp () : this.canScrollLayersUp ();
};
CursorDeviceProxy.prototype.canScrollLayersOrDrumPadsDown = function ()
{
return this.hasDrumPads () ? this.canScrollDrumPadsDown () : this.canScrollLayersDown ();
};
CursorDeviceProxy.prototype.scrollLayersOrDrumPadsPageUp = function ()
{
this.hasDrumPads () ? this.scrollDrumPadsPageUp () : this.scrollLayersPageUp ();
};
CursorDeviceProxy.prototype.scrollLayersOrDrumPadsPageDown = function ()
{
this.hasDrumPads () ? this.scrollDrumPadsPageDown () : this.scrollLayersPageDown ();
};
CursorDeviceProxy.prototype.changeLayerOrDrumPadVolume = function (index, value, fractionValue)
{
if (this.hasDrumPads ())
this.changeDrumPadVolume (index, value, fractionValue);
else
this.changeLayerVolume (index, value, fractionValue);
};
CursorDeviceProxy.prototype.setLayerOrDrumPadVolume = function (index, value)
{
if (this.hasDrumPads ())
this.setDrumPadVolume (index, value);
else
this.setLayerVolume (index, value);
};
CursorDeviceProxy.prototype.resetLayerOrDrumPadVolume = function (index)
{
if (this.hasDrumPads ())
this.resetDrumPadVolume (index);
else
this.resetLayerVolume (index);
};
CursorDeviceProxy.prototype.touchLayerOrDrumPadVolume = function (index, isBeingTouched)
{
if (this.hasDrumPads ())
this.touchDrumPadVolume (index, isBeingTouched);
else
this.touchLayerVolume (index, isBeingTouched);
};
CursorDeviceProxy.prototype.changeLayerOrDrumPadPan = function (index, value, fractionValue)
{
if (this.hasDrumPads ())
this.changeDrumPadPan (index, value, fractionValue);
else
this.changeLayerPan (index, value, fractionValue);
};
CursorDeviceProxy.prototype.setLayerOrDrumPadPan = function (index, value)
{
if (this.hasDrumPads ())
this.setDrumPadPan (index, value);
else
this.setLayerPan (index, value);
};
CursorDeviceProxy.prototype.resetLayerOrDrumPadPan = function (index)
{
if (this.hasDrumPads ())
this.resetDrumPadPan (index);
else
this.resetLayerPan (index);
};
CursorDeviceProxy.prototype.touchLayerOrDrumPadPan = function (index, isBeingTouched)
{
if (this.hasDrumPads ())
this.touchDrumPadPan (index, isBeingTouched);
else
this.touchLayerPan (index, isBeingTouched);
};
CursorDeviceProxy.prototype.changeLayerOrDrumPadSend = function (index, send, value, fractionValue)
{
if (this.hasDrumPads ())
this.changeDrumPadSend (index, send, value, fractionValue);
else
this.changeLayerSend (index, send, value, fractionValue);
};
CursorDeviceProxy.prototype.setLayerOrDrumPadSend = function (index, send, value)
{
if (this.hasDrumPads ())
this.setDrumPadSend (index, send, value);
else
this.setLayerSend (index, send, value);
};
CursorDeviceProxy.prototype.resetLayerOrDrumPadSend = function (index, send)
{
if (this.hasDrumPads ())
this.resetDrumPadSend (index, send);
else
this.resetLayerSend (index, send);
};
CursorDeviceProxy.prototype.touchLayerOrDrumPadSend = function (index, send, isBeingTouched)
{
if (this.hasDrumPads ())
this.touchDrumPadSend (index, send, isBeingTouched);
else
this.touchLayerSend (index, send, isBeingTouched);
};
CursorDeviceProxy.prototype.toggleLayerOrDrumPadMute = function (index)
{
if (this.hasDrumPads ())
this.toggleDrumPadMute (index);
else
this.toggleLayerMute (index);
};
CursorDeviceProxy.prototype.setLayerOrDrumPadMute = function (index, value)
{
if (this.hasDrumPads ())
this.setDrumPadMute (index, value);
else
this.setLayerMute (index, value);
};
CursorDeviceProxy.prototype.toggleLayerOrDrumPadSolo = function (index)
{
if (this.hasDrumPads ())
this.toggleDrumPadSolo (index);
else
this.toggleLayerSolo (index);
};
CursorDeviceProxy.prototype.setLayerOrDrumPadSolo = function (index, value)
{
if (this.hasDrumPads ())
this.setDrumPadSolo (index, value);
else
this.setLayerSolo (index, value);
};
CursorDeviceProxy.prototype.getLayerOrDrumPadColorEntry = function (index)
{
var layer = this.getLayerOrDrumPad (index);
return AbstractTrackBankProxy.getColorEntry (layer.color);
};
//--------------------------------------
// Layers
//--------------------------------------
CursorDeviceProxy.prototype.hasLayers = function ()
{
return this.hasLayersValue;
};
// The device can have layers but none exist
CursorDeviceProxy.prototype.hasZeroLayers = function ()
{
for (var i = 0; i < this.numDeviceLayers; i++)
if (this.deviceLayers[i].exists)
return false;
return true;
};
CursorDeviceProxy.prototype.getLayer = function (index)
{
return this.deviceLayers[index];
};
CursorDeviceProxy.prototype.getSelectedLayer = function ()
{
for (var i = 0; i < this.deviceLayers.length; i++)
{
if (this.deviceLayers[i].selected)
return this.deviceLayers[i];
}
return null;
};
CursorDeviceProxy.prototype.selectLayer = function (index)
{
this.layerBank.getChannel (index).selectInEditor ();
};
CursorDeviceProxy.prototype.previousLayer = function ()
{
var sel = this.getSelectedLayer ();
var index = sel == null ? 0 : sel.index - 1;
if (index == -1)
this.previousLayerBank ();
else
this.selectLayer (index);
};
CursorDeviceProxy.prototype.previousLayerBank = function ()
{
if (!this.canScrollLayersUp ())
return;
this.scrollLayersPageUp ();
scheduleTask (doObject (this, this.selectLayer), [ this.numDeviceLayers - 1 ], 75);
};
CursorDeviceProxy.prototype.nextLayer = function ()
{
var sel = this.getSelectedLayer ();
var index = sel == null ? 0 : sel.index + 1;
if (index == this.numDeviceLayers)
this.nextLayerBank ();
else
this.selectLayer (index);
};
CursorDeviceProxy.prototype.nextLayerBank = function ()
{
if (!this.canScrollLayersDown ())
return;
this.scrollLayersPageDown ();
scheduleTask (doObject (this, this.selectLayer), [ 0 ], 75);
};
CursorDeviceProxy.prototype.enterLayer = function (index)
{
this.layerBank.getChannel (index).selectInMixer ();
};
CursorDeviceProxy.prototype.selectParent = function ()
{
this.cursorDevice.selectParent ();
};
CursorDeviceProxy.prototype.selectChannel = function ()
{
this.cursorDevice.getChannel ().selectInEditor ();
};
CursorDeviceProxy.prototype.selectFirstDeviceInLayer = function (index)
{
this.cursorDevice.selectDevice (this.deviceBanks[index].getDevice (0));
};
CursorDeviceProxy.prototype.canScrollLayersUp = function ()
{
// TODO Bugfix required - up and down are flipped
return this.canScrollLayersDownValue;
};
CursorDeviceProxy.prototype.canScrollLayersDown = function ()
{
// TODO Bugfix required - up and down are flipped
return this.canScrollLayersUpValue;
};
CursorDeviceProxy.prototype.scrollLayersPageUp = function ()
{
this.layerBank.scrollChannelsPageUp ();
};
CursorDeviceProxy.prototype.scrollLayersPageDown = function ()
{
this.layerBank.scrollChannelsPageDown ();
};
CursorDeviceProxy.prototype.changeLayerVolume = function (index, value, fractionValue)
{
var t = this.getLayer (index);
t.volume = changeValue (value, t.volume, fractionValue, Config.maxParameterValue);
this.layerBank.getChannel (index).getVolume ().set (t.volume, Config.maxParameterValue);
};
CursorDeviceProxy.prototype.setLayerVolume = function (index, value)
{
var t = this.getLayer (index);
t.volume = value;
this.layerBank.getChannel (index).getVolume ().set (t.volume, Config.maxParameterValue);
};
CursorDeviceProxy.prototype.resetLayerVolume = function (index)
{
this.layerBank.getChannel (index).getVolume ().reset ();
};
CursorDeviceProxy.prototype.touchLayerVolume = function (index, isBeingTouched)
{
this.layerBank.getChannel (index).getVolume ().touch (isBeingTouched);
};
CursorDeviceProxy.prototype.changeLayerPan = function (index, value, fractionValue)
{
var t = this.getLayer (index);
t.pan = changeValue (value, t.pan, fractionValue, Config.maxParameterValue);
this.layerBank.getChannel (index).getPan ().set (t.pan, Config.maxParameterValue);
};
CursorDeviceProxy.prototype.setLayerPan = function (index, value)
{
var t = this.getLayer (index);
t.pan = value;
this.layerBank.getChannel (index).getPan ().set (t.pan, Config.maxParameterValue);
};
CursorDeviceProxy.prototype.resetLayerPan = function (index)
{
this.layerBank.getChannel (index).getPan ().reset ();
};
CursorDeviceProxy.prototype.touchLayerPan = function (index, isBeingTouched)
{
this.layerBank.getChannel (index).getPan ().touch (isBeingTouched);
};
CursorDeviceProxy.prototype.changeLayerSend = function (index, sendIndex, value, fractionValue)
{
var s = this.getLayer (index).sends[sendIndex];
s.volume = changeValue (value, s.volume, fractionValue, Config.maxParameterValue);
var send = this.layerBank.getChannel (index).getSend (sendIndex);
send.set (s.volume, Config.maxParameterValue);
};
CursorDeviceProxy.prototype.setLayerSend = function (index, sendIndex, value)
{
var t = this.getLayer (index);
var send = t.sends[sendIndex];
send.volume = value;
this.layerBank.getChannel (t.index).getSend (sendIndex).set (send.volume, Config.maxParameterValue);
};
CursorDeviceProxy.prototype.resetLayerSend = function (index, sendIndex)
{
this.layerBank.getChannel (index).getSend (sendIndex).reset ();
};
CursorDeviceProxy.prototype.touchLayerSend = function (index, sendIndex, isBeingTouched)
{
this.layerBank.getChannel (index).getSend (sendIndex).touch (isBeingTouched);
};
CursorDeviceProxy.prototype.toggleLayerMute = function (index)
{
this.layerBank.getChannel (index).getMute ().set (!this.getLayer (index).mute);
};
CursorDeviceProxy.prototype.setLayerMute = function (index, value)
{
this.layerBank.getChannel (index).getMute ().set (value);
};
CursorDeviceProxy.prototype.toggleLayerSolo = function (index)
{
this.layerBank.getChannel (index).getSolo ().set (!this.getLayer (index).solo);
};
CursorDeviceProxy.prototype.setLayerSolo = function (index, value)
{
this.layerBank.getChannel (index).getSolo ().set (value);
};
//--------------------------------------
// Drum Pads
//--------------------------------------
CursorDeviceProxy.prototype.hasDrumPads = function ()
{
return this.hasDrumPadsValue;
};
CursorDeviceProxy.prototype.getDrumPad = function (index)
{
return this.drumPadLayers[index];
};
CursorDeviceProxy.prototype.getSelectedDrumPad = function ()
{
for (var i = 0; i < this.drumPadLayers.length; i++)
{
if (this.drumPadLayers[i].selected)
return this.drumPadLayers[i];
}
return null;
};
CursorDeviceProxy.prototype.selectDrumPad = function (index)
{
var channel = this.drumPadBank.getChannel (index);
if (channel != null)
channel.selectInEditor ();
};
CursorDeviceProxy.prototype.previousDrumPad = function ()
{
var sel = this.getSelectedDrumPad ();
var index = sel == null ? 0 : sel.index - 1;
while (index > 0 && !this.getDrumPad (index).exists)
index--;
if (index == -1)
this.previousDrumPadBank ();
else
this.selectDrumPad (index);
};
CursorDeviceProxy.prototype.previousDrumPadBank = function ()
{
if (!this.canScrollDrumPadsUp ())
return;
this.scrollDrumPadsPageUp ();
scheduleTask (doObject (this, this.selectDrumPad), [ this.numDrumPadLayers - 1 ], 75);
};
CursorDeviceProxy.prototype.nextDrumPad = function ()
{
var sel = this.getSelectedDrumPad ();
var index = sel == null ? 0 : sel.index + 1;
while (index < this.numDrumPadLayers - 1 && !this.getDrumPad (index).exists)
index++;
if (index == this.numDrumPadLayers)
this.nextDrumPadBank ();
else
this.selectDrumPad (index);
};
CursorDeviceProxy.prototype.nextDrumPadBank = function ()
{
if (!this.canScrollDrumPadsDown ())
return;
this.scrollDrumPadsPageDown ();
scheduleTask (doObject (this, this.selectDrumPad), [ 0 ], 75);
};
CursorDeviceProxy.prototype.enterDrumPad = function (index)
{
this.drumPadBank.getChannel (index).selectInMixer ();
};
CursorDeviceProxy.prototype.changeDrumPadVolume = function (index, value, fractionValue)
{
var t = this.getDrumPad (index);
t.volume = changeValue (value, t.volume, fractionValue, Config.maxParameterValue);
this.drumPadBank.getChannel (index).getVolume ().set (t.volume, Config.maxParameterValue);
};
CursorDeviceProxy.prototype.setDrumPadVolume = function (index, value)
{
var t = this.getDrumPad (index);
t.volume = value;
this.drumPadBank.getChannel (index).getVolume ().set (t.volume, Config.maxParameterValue);
};
CursorDeviceProxy.prototype.resetDrumPadVolume = function (index)
{
this.drumPadBank.getChannel (index).getVolume ().reset ();
};
CursorDeviceProxy.prototype.touchDrumPadVolume = function (index, isBeingTouched)
{
this.drumPadBank.getChannel (index).getVolume ().touch (isBeingTouched);
};
CursorDeviceProxy.prototype.changeDrumPadPan = function (index, value, fractionValue)
{
var t = this.getDrumPad (index);
t.pan = changeValue (value, t.pan, fractionValue, Config.maxParameterValue);
this.drumPadBank.getChannel (index).getPan ().set (t.pan, Config.maxParameterValue);
};
CursorDeviceProxy.prototype.setDrumPadPan = function (index, value)
{
var t = this.getDrumPad (index);
t.pan = value;
this.drumPadBank.getChannel (index).getPan ().set (t.pan, Config.maxParameterValue);
};
CursorDeviceProxy.prototype.resetDrumPadPan = function (index)
{
this.drumPadBank.getChannel (index).getPan ().reset ();
};
CursorDeviceProxy.prototype.touchDrumPadPan = function (index, isBeingTouched)
{
this.drumPadBank.getChannel (index).getPan ().touch (isBeingTouched);
};
CursorDeviceProxy.prototype.changeDrumPadSend = function (index, sendIndex, value, fractionValue)
{
var s = this.getDrumPad (index).sends[sendIndex];
s.volume = changeValue (value, s.volume, fractionValue, Config.maxParameterValue);
var send = this.drumPadBank.getChannel (index).getSend (sendIndex);
send.set (s.volume, Config.maxParameterValue);
};
CursorDeviceProxy.prototype.setDrumPadSend = function (index, sendIndex, value)
{
var t = this.getDrumPad (index);
var send = t.sends[sendIndex];
send.volume = value;
this.drumPadBank.getChannel (t.index).getSend (sendIndex).set (send.volume, Config.maxParameterValue);
};
CursorDeviceProxy.prototype.resetDrumPadSend = function (index, sendIndex)
{
this.drumPadBank.getChannel (index).getSend (sendIndex).reset ();
};
CursorDeviceProxy.prototype.touchDrumPadSend = function (index, sendIndex, isBeingTouched)
{
this.drumPadBank.getChannel (index).getSend (sendIndex).touch (isBeingTouched);
};
CursorDeviceProxy.prototype.toggleDrumPadMute = function (index)
{
this.drumPadBank.getChannel (index).getMute ().set (!this.getDrumPad (index).mute);
};
CursorDeviceProxy.prototype.setDrumPadMute = function (index, value)
{
this.drumPadBank.getChannel (index).getMute ().set (value);
};
CursorDeviceProxy.prototype.toggleDrumPadSolo = function (index)
{
this.drumPadBank.getChannel (index).getSolo ().set (!this.getDrumPad (index).solo);
};
CursorDeviceProxy.prototype.setDrumPadSolo = function (index, value)
{
this.drumPadBank.getChannel (index).getSolo ().set (value);
};
CursorDeviceProxy.prototype.selectFirstDeviceInDrumPad = function (index)
{
this.cursorDevice.selectDevice (this.drumPadBanks[index].getDevice (0));
};
CursorDeviceProxy.prototype.canScrollDrumPadsUp = function ()
{
// TODO API extension required, use the layer info instead which works too
return this.canScrollLayersUp ();
};
CursorDeviceProxy.prototype.canScrollDrumPadsDown = function ()
{
// TODO API extension required, use the layer info instead which works too
return this.canScrollLayersDown ();
};
CursorDeviceProxy.prototype.scrollDrumPadsPageUp = function ()
{
this.drumPadBank.scrollChannelsPageUp ();
};
CursorDeviceProxy.prototype.scrollDrumPadsPageDown = function ()
{
this.drumPadBank.scrollChannelsPageDown ();
};
//--------------------------------------
// Direct Parameters
//--------------------------------------
CursorDeviceProxy.prototype.getDirectParameters = function ()
{
return this.directParameters;
};
CursorDeviceProxy.prototype.getDirectParameter = function (id)
{
for (var i = 0; i < this.directParameters.length; i++)
{
if (this.directParameters[i].id == id)
return this.directParameters[i];
}
return null;
};
CursorDeviceProxy.prototype.changeDirectParameter = function (index, value, fractionValue)
{
// Scale up from [0..1] to [0..1000000000000] to prevent rounding errors
var UP_SCALE = 1000000000000;
var frac = fractionValue / Config.maxParameterValue * UP_SCALE;
var newvalue = changeValue (value, Math.floor (this.directParameters[index].value * UP_SCALE), frac, UP_SCALE);
this.cursorDevice.setDirectParameterValueNormalized (this.directParameters[index].id, newvalue, UP_SCALE);
};
CursorDeviceProxy.prototype.hasPreviousDirectParameterPage = function ()
{
return this.directParameters.length > 0 && this.currentDirectParameterPage > 0;
};
CursorDeviceProxy.prototype.hasNextDirectParameterPage = function ()
{
return this.directParameters.length > 0 && this.currentDirectParameterPage < this.getDirectParameterPagesLength () - 1;
};
CursorDeviceProxy.prototype.previousDirectParameterPage = function ()
{
this.setSelectedDirectParameterPage (this.currentDirectParameterPage - 1);
};
CursorDeviceProxy.prototype.nextDirectParameterPage = function ()
{
this.setSelectedDirectParameterPage (this.currentDirectParameterPage + 1);
};
CursorDeviceProxy.prototype.previousDirectParameterPageBank = function ()
{
this.setSelectedDirectParameterPage (this.currentDirectParameterPage - 8);
};
CursorDeviceProxy.prototype.nextDirectParameterPageBank = function ()
{
this.setSelectedDirectParameterPage (this.currentDirectParameterPage + 8);
};
CursorDeviceProxy.prototype.getSelectedDirectParameterPageName = function (page)
{
return this.directParameterPageNames[page];
};
CursorDeviceProxy.prototype.getSelectedDirectParameterPage = function ()
{
return this.currentDirectParameterPage;
};
CursorDeviceProxy.prototype.setSelectedDirectParameterPage = function (index)
{
this.currentDirectParameterPage = Math.max (0, Math.min (index, this.getDirectParameterPagesLength () - 1));
this.enableDirectParameterObservation (this.directParameterObservationEnabled);
};
CursorDeviceProxy.prototype.enableDirectParameterObservation = function (enable)
{
this.directParameterObservationEnabled = enable;
// Disable / clear old observers
this.directParameterValueDisplayObserver.setObservedParameterIds (null);
if (!enable)
return;
var paramIds = [];
for (var i = 0; i < 8; i++)
{
var index = this.currentDirectParameterPage * 8 + i;
if (index >= this.directParameters.length)
break;
paramIds.push (this.directParameters[index].id);
}
this.directParameterValueDisplayObserver.setObservedParameterIds (paramIds);
};
// Get the number of pages with direct parameters
CursorDeviceProxy.prototype.getDirectParameterPagesLength = function ()
{
return this.numDirectPageBank;
};
CursorDeviceProxy.prototype.changeDirectPageParameter = function (index, value, fractionValue)
{
var pos = this.currentDirectParameterPage * 8 + index;
if (pos < this.directParameters.length)
this.changeDirectParameter (pos, value, fractionValue);
};
//--------------------------------------
// Callback Handlers
//--------------------------------------
CursorDeviceProxy.prototype.handleIsEnabled = function (isEnabled)
{
this.selectedDevice.enabled = isEnabled;
};
CursorDeviceProxy.prototype.handleIsPlugin = function (isPlugin)
{
this.selectedDevice.isPlugin = isPlugin;
};
CursorDeviceProxy.prototype.handlePosition = function (pos)
{
this.position = pos;
};
CursorDeviceProxy.prototype.handleName = function (name)
{
this.selectedDevice.name = name;
};
CursorDeviceProxy.prototype.handleCanSelectPrevious = function (isEnabled)
{
this.canSelectPrevious = isEnabled;
};
CursorDeviceProxy.prototype.handleCanSelectNext = function (isEnabled)
{
this.canSelectNext = isEnabled;
};
CursorDeviceProxy.prototype.handlePreviousParameterPageEnabled = function (isEnabled)
{
this.hasPreviousParamPage = isEnabled;
};
CursorDeviceProxy.prototype.handleNextParameterPageEnabled = function (isEnabled)
{
this.hasNextParamPage = isEnabled;
};
CursorDeviceProxy.prototype.handleSelectedPage = function (page)
{
this.selectedParameterPage = page;
};
CursorDeviceProxy.prototype.handlePageNames = function ()
{
this.parameterPageNames = arguments;
};
CursorDeviceProxy.prototype.handleIsExpanded = function (expanded)
{
this.isExpandedValue = expanded;
};
CursorDeviceProxy.prototype.handleIsMacroSectionVisible = function (isVisible)
{
this.isMacroSectionVisibleValue = isVisible;
};
CursorDeviceProxy.prototype.handleIsParameterPageSectionVisible = function (isVisible)
{
this.isParameterPageSectionVisibleValue = isVisible;
};
CursorDeviceProxy.prototype.handleDirectParameterIds = function (ids)
{
this.directParameters.length = 0;
for (var i = 0; i < ids.length; i++)
this.directParameters.push ({ id: ids[i], name: '', valueStr: '', value: '' });
this.numDirectPageBank = Math.floor (this.directParameters.length / 8) + (this.directParameters.length % 8 > 0 ? 1 : 0);
this.directParameterPageNames.length = 0;
for (var i = 0; i < this.numDirectPageBank; i++)
this.directParameterPageNames.push ("Page " + (i + 1));
// Reset page to check for new range of pages
this.setSelectedDirectParameterPage (this.currentDirectParameterPage);
};
CursorDeviceProxy.prototype.handleDirectParameterNames = function (id, name)
{
var dp = this.getDirectParameter (id);
if (dp == null)
host.errorln ("Direct parameter '" + id + "' not found.");
else
dp.name = name;
};
CursorDeviceProxy.prototype.handleDirectParameterValueDisplay = function (id, value)
{
var dp = this.getDirectParameter (id);
if (dp == null)
host.errorln ("Direct parameter '" + id + "' not found.");
else
dp.valueStr = value;
};
CursorDeviceProxy.prototype.handleDirectParameterValue = function (id, value)
{
var dp = this.getDirectParameter (id);
if (dp == null)
host.errorln ("Direct parameter '" + id + "' not found.");
else
dp.value = value;
};
CursorDeviceProxy.prototype.handleParameterName = function (index, name)
{
this.fxparams[index].name = name;
};
CursorDeviceProxy.prototype.handleValue = function (index, value)
{
this.fxparams[index].value = value;
};
CursorDeviceProxy.prototype.handleValueDisplay = function (index, value)
{
this.fxparams[index].valueStr = value;
};
CursorDeviceProxy.prototype.handleCommonParameterName = function (index, name)
{
this.commonParams[index].name = name;
};
CursorDeviceProxy.prototype.handleCommonValue = function (index, value)
{
this.commonParams[index].value = value;
};
CursorDeviceProxy.prototype.handleCommonValueDisplay = function (index, value)
{
this.commonParams[index].valueStr = value;
};
CursorDeviceProxy.prototype.handleEnvelopeParameterName = function (index, name)
{
this.envelopeParams[index].name = name;
};
CursorDeviceProxy.prototype.handleEnvelopeValue = function (index, value)
{
this.envelopeParams[index].value = value;
};
CursorDeviceProxy.prototype.handleEnvelopeValueDisplay = function (index, value)
{
this.envelopeParams[index].valueStr = value;
};
CursorDeviceProxy.prototype.handleMacroParameterName = function (index, name)
{
this.macroParams[index].name = name;
};
CursorDeviceProxy.prototype.handleMacroValue = function (index, value)
{
this.macroParams[index].value = value;
};
CursorDeviceProxy.prototype.handleMacroValueDisplay = function (index, value)
{
this.macroParams[index].valueStr = value;
};
CursorDeviceProxy.prototype.handleIsMapping = function (index, value)
{
this.isMacroMappings[index] = value;
};
CursorDeviceProxy.prototype.handleModulationSourceName = function (index, name)
{
this.modulationParams[index].name = name;
};
CursorDeviceProxy.prototype.handleModulationSourceIsMapping = function (index, isMapping)
{
this.modulationParams[index].value = isMapping;
this.modulationParams[index].valueStr = isMapping ? 'On' : 'Off';
};
CursorDeviceProxy.prototype.handleIsWindowOpen = function (value)
{
this.isWindowOpenValue = value;
};
CursorDeviceProxy.prototype.handleIsNested = function (value)
{
this.isNestedValue = value;
};
CursorDeviceProxy.prototype.handleHasDrumPads = function (value)
{
this.hasDrumPadsValue = value;
};
CursorDeviceProxy.prototype.handleHasLayers = function (value)
{
this.hasLayersValue = value;
};
CursorDeviceProxy.prototype.handleHasSlots = function (value)
{
this.hasSlotsValue = value;
};
CursorDeviceProxy.prototype.handleSiblingName = function (index, name)
{
this.siblingDevices[index] = name;
};
CursorDeviceProxy.prototype.handleLayerExists = function (index, exists)
{
this.deviceLayers[index].exists = exists;
};
CursorDeviceProxy.prototype.handleLayerActivated = function (index, activated)
{
this.deviceLayers[index].activated = activated;
};
CursorDeviceProxy.prototype.handleLayerSelection = function (index, isSelected)
{
this.deviceLayers[index].selected = isSelected;
};
CursorDeviceProxy.prototype.handleLayerName = function (index, name)
{
this.deviceLayers[index].name = name;
};
CursorDeviceProxy.prototype.handleLayerVolume = function (index, value)
{
this.deviceLayers[index].volume = value;
};
CursorDeviceProxy.prototype.handleLayerVolumeStr = function (index, text)
{
this.deviceLayers[index].volumeStr = text;
};
CursorDeviceProxy.prototype.handleLayerPan = function (index, value)
{
this.deviceLayers[index].pan = value;
};
CursorDeviceProxy.prototype.handleLayerPanStr = function (index, text)
{
this.deviceLayers[index].panStr = text;
};
CursorDeviceProxy.prototype.handleLayerVUMeters = function (index, value)
{
this.deviceLayers[index].vu = value;
};
CursorDeviceProxy.prototype.handleLayerMute = function (index, isMuted)
{
this.deviceLayers[index].mute = isMuted;
};
CursorDeviceProxy.prototype.handleLayerSolo = function (index, isSoloed)
{
this.deviceLayers[index].solo = isSoloed;
};
CursorDeviceProxy.prototype.handleLayerColor = function (index, red, green, blue)
{
this.deviceLayers[index].color = AbstractTrackBankProxy.getColorIndex (red, green, blue);
};
CursorDeviceProxy.prototype.handleLayerSendName = function (index, index2, text)
{
this.deviceLayers[index].sends[index2].name = text;
};
CursorDeviceProxy.prototype.handleLayerSendVolume = function (index, index2, value)
{
this.deviceLayers[index].sends[index2].volume = value;
};
CursorDeviceProxy.prototype.handleLayerSendVolumeStr = function (index, index2, text)
{
this.deviceLayers[index].sends[index2].volumeStr = text;
};
CursorDeviceProxy.prototype.handleCanScrollLayerUp = function (canScroll)
{
this.canScrollLayersUpValue = canScroll;
};
CursorDeviceProxy.prototype.handleCanScrollLayerDown = function (canScroll)
{
this.canScrollLayersDownValue = canScroll;
};
CursorDeviceProxy.prototype.handleDrumPadExists = function (index, exists)
{
this.drumPadLayers[index].exists = exists;
};
CursorDeviceProxy.prototype.handleDrumPadActivated = function (index, activated)
{
this.drumPadLayers[index].activated = activated;
};
CursorDeviceProxy.prototype.handleDrumPadSelection = function (index, isSelected)
{
this.drumPadLayers[index].selected = isSelected;
};
CursorDeviceProxy.prototype.handleDrumPadName = function (index, name)
{
this.drumPadLayers[index].name = name;
};
CursorDeviceProxy.prototype.handleDrumPadVolume = function (index, value)
{
this.drumPadLayers[index].volume = value;
};
CursorDeviceProxy.prototype.handleDrumPadVolumeStr = function (index, text)
{
this.drumPadLayers[index].volumeStr = text;
};
CursorDeviceProxy.prototype.handleDrumPadPan = function (index, value)
{
this.drumPadLayers[index].pan = value;
};
CursorDeviceProxy.prototype.handleDrumPadPanStr = function (index, text)
{
this.drumPadLayers[index].panStr = text;
};
CursorDeviceProxy.prototype.handleDrumPadVUMeters = function (index, value)
{
this.drumPadLayers[index].vu = value;
};
CursorDeviceProxy.prototype.handleDrumPadMute = function (index, isMuted)
{
this.drumPadLayers[index].mute = isMuted;
};
CursorDeviceProxy.prototype.handleDrumPadSolo = function (index, isSoloed)
{
this.drumPadLayers[index].solo = isSoloed;
};
CursorDeviceProxy.prototype.handleDrumPadColor = function (index, red, green, blue)
{
this.drumPadLayers[index].color = AbstractTrackBankProxy.getColorIndex (red, green, blue);
};
CursorDeviceProxy.prototype.handleDrumPadSendName = function (index, index2, text)
{
this.drumPadLayers[index].sends[index2].name = text;
};
CursorDeviceProxy.prototype.handleDrumPadSendVolume = function (index, index2, value)
{
this.drumPadLayers[index].sends[index2].volume = value;
};
CursorDeviceProxy.prototype.handleDrumPadSendVolumeStr = function (index, index2, text)
{
this.drumPadLayers[index].sends[index2].volumeStr = text;
};
//--------------------------------------
// Private
//--------------------------------------
CursorDeviceProxy.prototype.createFXParams = function (count)
{
var fxparams = [];
for (var i = 0; i < count; i++)
{
fxparams.push (
{
index: i,
name: '',
valueStr: '',
value: 0
});
}
return fxparams;
};
CursorDeviceProxy.prototype.createDeviceLayers = function (count)
{
var layers = [];
for (var i = 0; i < count; i++)
{
var l =
{
index: i,
exists: false,
activated: true,
selected: false,
name: '',
volumeStr: '',
volume: 0,
panStr: '',
pan: 0,
vu: 0,
mute: false,
solo: false,
color: 0,
sends: []
};
for (var j = 0; j < this.numSends; j++)
l.sends.push ({ index: j, volume: 0 });
layers.push (l);
}
return layers;
};
| teotigraphix/Touch4BitwigOSC | framework/daw/CursorDeviceProxy.js | JavaScript | lgpl-3.0 | 52,741 |
/**
* Start Command
*
* @module greppy/cli/start
* @author Hermann Mayer <hermann.mayer92@gmail.com>
*/
exports.run = function(contexts, debug)
{
// Find a Greppy project recursivly
var appPath = commandHelper.findProjectOrDie();
contexts = commandHelper.checkContexts(contexts || []);
var startScript = projectHelper.findStartScript(process.cwd());
if (false === startScript) {
console.log('No start script was found in the current project.');
console.log('You should have an app/worker.js or an app/master.js');
process.exit(1);
return;
}
// A normal un-debugged start process
if (!debug) {
// Start all contexts with the found start script
contexts.contexts.forEach(function(context) {
var state = processHelper.getContextState(process.cwd(), context);
var isRunning = commandHelper.checkForRunningContextState(state);
if (isRunning) {
return;
}
// Start the daemon process
var args = ['--context', context];
var stderr = fs.openSync(appPath + 'var/log/' + context + '.master.stderr.log', 'a');
var child = daemon.daemon(startScript, args, {
cwd : appPath,
stderr : stderr
});
fs.writeFileSync(state.file, child.pid);
global.table.writeRow([
'start'.bold.green,
(context + ' -- started (' + child.pid + ')').white
]);
});
// We are done with this starting process
return;
}
// A debugged start process for only one context
// We only start the one process in foreground
if (1 === contexts.contexts.length) {
// Remap the context variable to fit the situation
var context = contexts.contexts[0];
var state = processHelper.getContextState(process.cwd(), context);
var isRunning = commandHelper.checkForRunningContextState(state);
if (isRunning) {
return;
}
var print = function (data) {
console.log(data.toString().replace(/\n$/, ''));
};
if (process.stdin.setRawMode) {
process.stdin.resume();
process.stdin.setRawMode(true);
process.stdin.on('data', function (data) {
// Ctrl+C or Ctrl+D
if ('\3' == data || '\4' == data) {
process.stdin.pause();
emitExitToChild();
}
// F5 was pressed
if (String.fromCharCode(0x1b,0x5b,0x31,0x35,0x7e) == data) {
console.log();
child.kill('SIGHUP');
}
});
}
var child = require('child_process').spawn(process.execPath, [
startScript, '--context', context, '--debug'
], {
stdio: ['pipe', 'pipe', 'pipe']
});
var emitExitToChild = function() {
console.log();
child.kill('SIGINT');
};
process.on('SIGINT', emitExitToChild);
process.on('SIGTERM ', emitExitToChild);
child.stdout.on('data', print);
child.stderr.on('data', print);
child.on('close', function() {
process.stdin.pause();
});
fs.writeFileSync(state.file, child.pid);
// We are done with this starting process
return;
}
// A debugged start process for more than one context
// We start a GNU Screen session for the given contexts
if (1 < contexts.contexts.length) {
var conf = fs.readFileSync(__dirname + '/../template/screen.conf.tmpl', 'utf8');
var tabs = [];
var projectName = require(process.cwd() + '/package').name;
// Build the configuration for all contexts
// So every context became a tab on the screen session
contexts.contexts.forEach(function(context) {
tabs.push(
'screen -t ' + context + ' ' + (tabs.length + 1) +
' greppy -s ' + context + ' -d'
);
});
// Replace all template tokens
conf = conf.replace('{{tabs}}', tabs.join('\n'))
.replace('{{projectName}}', projectName)
.replace('{{contextList}}', contexts.contexts.join(','));
var tmpConfPath = '/tmp/.' + projectName + '.screenrc';
fs.writeFileSync(tmpConfPath, conf);
var screen = new (require('screen-init'))({
args: ['-c', tmpConfPath]
});
// We are done with this starting process
return;
}
};
| Jack12816/greppy | bin/command/start.js | JavaScript | lgpl-3.0 | 4,709 |
/**
* Copyright (C) 2005-2015 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @author Dave Draper
*/
define(["intern!object",
"intern/chai!assert",
"require",
"alfresco/TestCommon",
"intern/dojo/node!leadfoot/keys"],
function (registerSuite, assert, require, TestCommon, keys) {
var pause = 150;
var browser;
registerSuite({
name: "Form Creation DND tests",
setup: function() {
browser = this.remote;
return TestCommon.loadTestWebScript(this.remote, "/form-dnd", "Form Creation DND tests")
.end();
},
beforeEach: function() {
browser.end();
},
"Drag form onto target": function () {
return browser.findByCssSelector("#dojoUnique2 .title")
.moveMouseTo()
.click()
.pressMouseButton()
.moveMouseTo(1, 1)
.end()
.findByCssSelector(".alfresco-dnd-DragAndDropTarget > div")
.then(function(element) {
return browser.moveMouseTo(element)
.sleep(500) // The drag is 'elastic' and this sleep allows the item to catch up with the mouse movement
.releaseMouseButton();
})
.end()
.findAllByCssSelector("#ROOT_DROPPED_ITEMS1 .alfresco-dnd-DragAndDropTarget > div.previewPanel > .alfresco-dnd-DroppedItemWrapper")
.then(function(elements) {
assert.lengthOf(elements, 1, "The dropped item was found");
});
},
"Add two controls to form": function() {
// Select form control
return browser.pressKeys(keys.TAB)
.sleep(pause)
.pressKeys(keys.ENTER)
// Add to form (select the preview panel with the mouse and use enter to add the selected item)...
.findByCssSelector(".alfresco-dnd-DragAndDropTarget .alfresco-dnd-DragAndDropTarget .previewPanel")
.click()
.end()
.pressKeys(keys.ENTER)
.pressKeys(keys.ENTER)
.findAllByCssSelector("#ROOT_DROPPED_ITEMS1 .alfresco-dnd-DragAndDropTarget .alfresco-dnd-DragAndDropTarget > div.previewPanel > .alfresco-dnd-DroppedItemWrapper")
.then(function(elements) {
assert.lengthOf(elements, 2, "There should be two form controls added now");
});
},
"Set a field id": function() {
// Click to edit the form control...
return browser.findByCssSelector(".alfresco-dnd-DragAndDropTarget .alfresco-dnd-DragAndDropTarget .previewPanel .action.edit img")
.click()
.end()
.findByCssSelector("#ALF_DROPPED_ITEM_CONFIGURATION_DIALOG #FIELD_ID .dijitInputContainer input")
.clearValue()
.type("field1")
.end()
.findByCssSelector("#ALF_DROPPED_ITEM_CONFIGURATION_DIALOG .confirmationButton > span")
.click()
.end()
.waitForDeletedByCssSelector(".dialogDisplayed");
// TODO: Test something?
},
"Edit the form": function() {
// We want to make sure that editing the form won't hide the nested form control...
return browser.findByCssSelector(".alfresco-dnd-DragAndDropTarget .previewPanel .action.edit img")
.click()
.end()
.sleep(1000) // Wait for dialog to render...
.findByCssSelector("#ALF_DROPPED_ITEM_CONFIGURATION_DIALOG .confirmationButton > span")
.click()
.end()
.findAllByCssSelector(".alfresco-dnd-DragAndDropTarget .alfresco-dnd-DragAndDropTarget .previewPanel .action.edit img")
.then(function(elements) {
assert.lengthOf(elements, 2, "The form control edit button couldn't be found which indicates that the control wasn't re-rendered");
});
},
"Edit the second form control to check form control information is available": function() {
// Edit the second control...
return browser.findByCssSelector(".alfresco-dnd-DroppedItemWrapper:nth-child(2) .action.edit img")
.click()
.end()
.sleep(1000)
// Reveal the dynamic visibility controls...
.pressKeys(keys.TAB)
.sleep(pause)
.pressKeys(keys.TAB)
.sleep(pause)
.pressKeys(keys.TAB)
.sleep(pause)
.pressKeys(keys.TAB)
.sleep(pause)
.pressKeys(keys.TAB)
.sleep(pause)
.pressKeys(keys.TAB)
.sleep(pause)
.pressKeys(keys.TAB)
.sleep(pause)
.pressKeys(keys.SPACE)
.sleep(pause)
// Reveal the dynamic visibility controls...
// .findByCssSelector("#ALF_DROPPED_ITEM_CONFIGURATION_DIALOG #DYNAMIC_BEHAVIOUR_TOGGLE input")
// .click()
// .end()
// Add a new visibility rule...
.pressKeys(keys.TAB)
.sleep(pause)
.pressKeys(keys.TAB)
.sleep(pause)
.pressKeys(keys.SPACE)
.sleep(pause)
.sleep(1000)
// Add a new visibility rule...
// .findByCssSelector("#ALF_DROPPED_ITEM_CONFIGURATION_DIALOG #DYNAMIC_VISIBILITY_RULES .button.add")
// .click()
// .end()
// Count the numnber of fields that can be referenced...
.findAllByCssSelector("#ALF_DROPPED_ITEM_CONFIGURATION_DIALOG #DYNAMIC_VISIBILITY_RULES .alfresco-forms-controls-Select tr")
.then(function(elements) {
assert.lengthOf(elements, 1, "An unexpected number of other field options was found");
});
},
"Preview the form": function() {
return browser.findByCssSelector("#ALF_DROPPED_ITEM_CONFIGURATION_DIALOG .cancellationButton > span")
.click()
.end()
.sleep(1000)
.findByCssSelector("#FORM1 .buttons > span:nth-child(2) > span")
.click()
.end()
.sleep(5000) // Give the preview time to render
.findAllByCssSelector(".alfresco-prototyping-Preview .alfresco-forms-controls-TextBox")
.then(function(elements) {
assert.lengthOf(elements, 2, "Text boxes not found in the preview panel");
});
},
"Post Coverage Results": function() {
TestCommon.alfPostCoverageResults(this, browser);
}
});
}); | nzheyuti/Aikau | aikau/src/test/resources/alfresco/dnd/FormCreationTest.js | JavaScript | lgpl-3.0 | 7,160 |
/*
* SonarQube
* Copyright (C) 2009-2016 SonarSource SA
* mailto:contact AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
import React from 'react';
import { DetailedMeasure } from './detailed-measure';
import { DonutChart } from '../../../components/charts/donut-chart';
import { DrilldownLink } from '../../../components/shared/drilldown-link';
import { formatMeasure, formatMeasureVariation } from '../../../helpers/measures';
import { translate } from '../../../helpers/l10n';
export const CoverageMeasures = React.createClass({
propTypes: {
measures: React.PropTypes.object.isRequired,
leak: React.PropTypes.object.isRequired,
prefix: React.PropTypes.string.isRequired
},
getMetricName(metric) {
const { prefix } = this.props;
return prefix + metric;
},
getNewCoverageMetricName () {
const { prefix } = this.props;
return 'new_' + prefix + 'coverage';
},
getCoverageMeasure() {
const coverageMetricName = this.getMetricName('coverage');
return this.props.measures[coverageMetricName];
},
getCoverageLeak() {
const coverageMetricName = this.getMetricName('coverage');
return this.props.leak[coverageMetricName];
},
getNewCoverageMeasure() {
const newCoverageMetricName = this.getNewCoverageMetricName();
return this.props.leak[newCoverageMetricName];
},
renderCoverageLeak () {
if (!this.props.leakPeriodDate) {
return null;
}
const coverageLeak = this.getCoverageLeak();
return <div className="overview-detailed-measure-leak">
<span className="overview-detailed-measure-value">
{formatMeasureVariation(coverageLeak, 'PERCENT')}
</span>
</div>;
},
renderCoverageOnNewCode() {
const newCoverageMetricName = this.getNewCoverageMetricName();
const newCoverage = this.getNewCoverageMeasure();
if (!this.props.leakPeriodDate || newCoverage == null) {
return null;
}
const donutData = [
{ value: newCoverage, fill: '#85bb43' },
{ value: 100 - newCoverage, fill: '#d4333f' }
];
return <div className="overview-detailed-measure" style={{ lineHeight: '30px' }}>
<div className="overview-detailed-measure-nutshell overview-leak">
<span className="overview-detailed-measure-name">
{translate('metric', newCoverageMetricName, 'name')}
</span>
</div>
<div className="overview-detailed-measure-leak">
<span className="overview-detailed-measure-value">
<span className="spacer-right">
<DonutChart width="30"
height="30"
thickness="4"
data={donutData}/>
</span>
<DrilldownLink component={this.props.component.key}
metric={newCoverageMetricName}
period={this.props.leakPeriodIndex}>
{formatMeasure(newCoverage, 'PERCENT')}
</DrilldownLink>
</span>
</div>
</div>;
},
renderDonut() {
const coverage = this.getCoverageMeasure();
const donutData = [
{ value: coverage, fill: '#85bb43' },
{ value: 100 - coverage, fill: '#d4333f' }
];
return <DonutChart width="30"
height="30"
thickness="4"
data={donutData}/>;
},
render() {
const coverageMetricName = this.getMetricName('coverage');
const coverage = this.getCoverageMeasure();
return (
<div className="overview-detailed-measures-list">
<div className="overview-detailed-measure" style={{ lineHeight: '30px' }}>
<div className="overview-detailed-measure-nutshell">
<span className="overview-detailed-measure-name big">
{translate('metric', coverageMetricName, 'name')}
</span>
<span className="overview-detailed-measure-value">
<span className="spacer-right">{this.renderDonut()}</span>
<DrilldownLink component={this.props.component.key} metric={coverageMetricName}>
{formatMeasure(coverage, 'PERCENT')}
</DrilldownLink>
</span>
</div>
{this.renderCoverageLeak()}
</div>
<DetailedMeasure {...this.props} {...this.props}
metric={this.getMetricName('line_coverage')}
type="PERCENT"/>
<DetailedMeasure {...this.props} {...this.props}
metric={this.getMetricName('uncovered_lines')}
type="INT"/>
<DetailedMeasure {...this.props} {...this.props}
metric="lines_to_cover"
type="INT"/>
<DetailedMeasure {...this.props} {...this.props}
metric={this.getMetricName('branch_coverage')}
type="PERCENT"/>
<DetailedMeasure {...this.props} {...this.props}
metric={this.getMetricName('uncovered_conditions')}
type="INT"/>
<DetailedMeasure {...this.props} {...this.props}
metric="conditions_to_cover"
type="INT"/>
{this.renderCoverageOnNewCode()}
</div>
);
}
});
| joansmith/sonarqube | server/sonar-web/src/main/js/apps/overview/components/coverage-measures.js | JavaScript | lgpl-3.0 | 5,926 |
var class_catharsis_1_1_web_1_1_widgets_1_1_i_yandex_analytics_widget_extensions =
[
[ "Language", "class_catharsis_1_1_web_1_1_widgets_1_1_i_yandex_analytics_widget_extensions.html#ae852a90ce1030b834ba7e3a03e730c69", null ]
]; | prokhor-ozornin/Catharsis.NET.Web.Widgets | doc/html/class_catharsis_1_1_web_1_1_widgets_1_1_i_yandex_analytics_widget_extensions.js | JavaScript | lgpl-3.0 | 231 |
import React from "react"
export default function Home() {
return <div>404</div>
}
| pinoytech/react-playground | gatsby-source-plugin-rest-with-images/src/pages/404.js | JavaScript | unlicense | 86 |
"use strict";
const conversions = require("webidl-conversions");
const utils = require("./utils.js");
const convertStorageEventInit = require("./StorageEventInit.js").convert;
const convertStorage = require("./Storage.js").convert;
const impl = utils.implSymbol;
const ctorRegistry = utils.ctorRegistrySymbol;
const Event = require("./Event.js");
const interfaceName = "StorageEvent";
/**
* When an interface-module that implements this interface as a mixin is loaded, it will append its own `.is()`
* method into this array. It allows objects that directly implements *those* interfaces to be recognized as
* implementing this mixin interface.
*/
exports._mixedIntoPredicates = [];
exports.is = function is(obj) {
if (obj) {
if (utils.hasOwn(obj, impl) && obj[impl] instanceof Impl.implementation) {
return true;
}
for (const isMixedInto of exports._mixedIntoPredicates) {
if (isMixedInto(obj)) {
return true;
}
}
}
return false;
};
exports.isImpl = function isImpl(obj) {
if (obj) {
if (obj instanceof Impl.implementation) {
return true;
}
const wrapper = utils.wrapperForImpl(obj);
for (const isMixedInto of exports._mixedIntoPredicates) {
if (isMixedInto(wrapper)) {
return true;
}
}
}
return false;
};
exports.convert = function convert(obj, { context = "The provided value" } = {}) {
if (exports.is(obj)) {
return utils.implForWrapper(obj);
}
throw new TypeError(`${context} is not of type 'StorageEvent'.`);
};
exports.create = function create(globalObject, constructorArgs, privateData) {
if (globalObject[ctorRegistry] === undefined) {
throw new Error("Internal error: invalid global object");
}
const ctor = globalObject[ctorRegistry]["StorageEvent"];
if (ctor === undefined) {
throw new Error("Internal error: constructor StorageEvent is not installed on the passed global object");
}
let obj = Object.create(ctor.prototype);
obj = exports.setup(obj, globalObject, constructorArgs, privateData);
return obj;
};
exports.createImpl = function createImpl(globalObject, constructorArgs, privateData) {
const obj = exports.create(globalObject, constructorArgs, privateData);
return utils.implForWrapper(obj);
};
exports._internalSetup = function _internalSetup(obj) {
Event._internalSetup(obj);
};
exports.setup = function setup(obj, globalObject, constructorArgs = [], privateData = {}) {
privateData.wrapper = obj;
exports._internalSetup(obj);
Object.defineProperty(obj, impl, {
value: new Impl.implementation(globalObject, constructorArgs, privateData),
configurable: true
});
obj[impl][utils.wrapperSymbol] = obj;
if (Impl.init) {
Impl.init(obj[impl], privateData);
}
return obj;
};
exports.install = function install(globalObject) {
if (globalObject.Event === undefined) {
throw new Error("Internal error: attempting to evaluate StorageEvent before Event");
}
class StorageEvent extends globalObject.Event {
constructor(type) {
if (arguments.length < 1) {
throw new TypeError(
"Failed to construct 'StorageEvent': 1 argument required, but only " + arguments.length + " present."
);
}
const args = [];
{
let curArg = arguments[0];
curArg = conversions["DOMString"](curArg, { context: "Failed to construct 'StorageEvent': parameter 1" });
args.push(curArg);
}
{
let curArg = arguments[1];
curArg = convertStorageEventInit(curArg, { context: "Failed to construct 'StorageEvent': parameter 2" });
args.push(curArg);
}
return exports.setup(Object.create(new.target.prototype), globalObject, args);
}
initStorageEvent(type) {
if (!this || !exports.is(this)) {
throw new TypeError("Illegal invocation");
}
if (arguments.length < 1) {
throw new TypeError(
"Failed to execute 'initStorageEvent' on 'StorageEvent': 1 argument required, but only " +
arguments.length +
" present."
);
}
const args = [];
{
let curArg = arguments[0];
curArg = conversions["DOMString"](curArg, {
context: "Failed to execute 'initStorageEvent' on 'StorageEvent': parameter 1"
});
args.push(curArg);
}
{
let curArg = arguments[1];
if (curArg !== undefined) {
curArg = conversions["boolean"](curArg, {
context: "Failed to execute 'initStorageEvent' on 'StorageEvent': parameter 2"
});
} else {
curArg = false;
}
args.push(curArg);
}
{
let curArg = arguments[2];
if (curArg !== undefined) {
curArg = conversions["boolean"](curArg, {
context: "Failed to execute 'initStorageEvent' on 'StorageEvent': parameter 3"
});
} else {
curArg = false;
}
args.push(curArg);
}
{
let curArg = arguments[3];
if (curArg !== undefined) {
if (curArg === null || curArg === undefined) {
curArg = null;
} else {
curArg = conversions["DOMString"](curArg, {
context: "Failed to execute 'initStorageEvent' on 'StorageEvent': parameter 4"
});
}
} else {
curArg = null;
}
args.push(curArg);
}
{
let curArg = arguments[4];
if (curArg !== undefined) {
if (curArg === null || curArg === undefined) {
curArg = null;
} else {
curArg = conversions["DOMString"](curArg, {
context: "Failed to execute 'initStorageEvent' on 'StorageEvent': parameter 5"
});
}
} else {
curArg = null;
}
args.push(curArg);
}
{
let curArg = arguments[5];
if (curArg !== undefined) {
if (curArg === null || curArg === undefined) {
curArg = null;
} else {
curArg = conversions["DOMString"](curArg, {
context: "Failed to execute 'initStorageEvent' on 'StorageEvent': parameter 6"
});
}
} else {
curArg = null;
}
args.push(curArg);
}
{
let curArg = arguments[6];
if (curArg !== undefined) {
curArg = conversions["USVString"](curArg, {
context: "Failed to execute 'initStorageEvent' on 'StorageEvent': parameter 7"
});
} else {
curArg = "";
}
args.push(curArg);
}
{
let curArg = arguments[7];
if (curArg !== undefined) {
if (curArg === null || curArg === undefined) {
curArg = null;
} else {
curArg = convertStorage(curArg, {
context: "Failed to execute 'initStorageEvent' on 'StorageEvent': parameter 8"
});
}
} else {
curArg = null;
}
args.push(curArg);
}
return this[impl].initStorageEvent(...args);
}
get key() {
if (!this || !exports.is(this)) {
throw new TypeError("Illegal invocation");
}
return this[impl]["key"];
}
get oldValue() {
if (!this || !exports.is(this)) {
throw new TypeError("Illegal invocation");
}
return this[impl]["oldValue"];
}
get newValue() {
if (!this || !exports.is(this)) {
throw new TypeError("Illegal invocation");
}
return this[impl]["newValue"];
}
get url() {
if (!this || !exports.is(this)) {
throw new TypeError("Illegal invocation");
}
return this[impl]["url"];
}
get storageArea() {
if (!this || !exports.is(this)) {
throw new TypeError("Illegal invocation");
}
return utils.tryWrapperForImpl(this[impl]["storageArea"]);
}
}
Object.defineProperties(StorageEvent.prototype, {
initStorageEvent: { enumerable: true },
key: { enumerable: true },
oldValue: { enumerable: true },
newValue: { enumerable: true },
url: { enumerable: true },
storageArea: { enumerable: true },
[Symbol.toStringTag]: { value: "StorageEvent", configurable: true }
});
if (globalObject[ctorRegistry] === undefined) {
globalObject[ctorRegistry] = Object.create(null);
}
globalObject[ctorRegistry][interfaceName] = StorageEvent;
Object.defineProperty(globalObject, interfaceName, {
configurable: true,
writable: true,
value: StorageEvent
});
};
const Impl = require("../events/StorageEvent-impl.js");
| diegopacheco/scala-playground | scala-js-1.0-fun/node_modules/jsdom/lib/jsdom/living/generated/StorageEvent.js | JavaScript | unlicense | 8,698 |
import React from 'react';
import ReactDOM from 'react-dom';
import baconipsum from 'baconipsum';
import { ThemeProvider } from 'styled-components';
import Button
from './vanilla/Button';
// from './inline/Button';
// from './css-modules/Button';
// from './radium/Button';
// from './aphrodite/Button';
// from './styled-components/Button';
import './styled-components/global';
import Logo from './styled-components/Logo';
import Post from './styled-components/Post';
import FancyLink from './styled-components/FancyLink';
import theme from './styled-components/theme';
const App = () => (
<div>
{/* Can be styled by each included styling library (change imports above): */}
<Button>Styled Button</Button>
<hr/>
{/* Try adding 'alternate' attribute: */}
<Logo spin/>
<hr/>
{/* Try changing the 'theme' attribute to 'theme.light': */}
<ThemeProvider theme={theme.dark}>
<Post>
{baconipsum(50)}
</Post>
</ThemeProvider>
<hr/>
{/* Won't actually work (see console error on click): */}
<FancyLink to="">Home</FancyLink>
<hr/>
</div>
);
ReactDOM.render(<App/>, document.getElementById('root'));
| ReactCLT/styling-react-components | index.js | JavaScript | unlicense | 1,184 |
import isomorphic from './isomorphic'
import * as styles from './styles'
import assetsLoaders from './assetsLoaders'
import babelLoader from './babelLoader'
import polyfills from './polyfills'
import * as devtools from './devtools'
import globals from './globals'
import optimize from './optimize'
import output from './output'
export default function makeConfig(options) {
return {
// the cache seems to be in-memory only: https://webpack.github.io/docs/configuration.html#cache
cache: options.useDevServer,
// cheap-module-eval-source-map, because we want original source, but we don't
// care about columns, which makes this devtool faster than eval-source-map.
// http://webpack.github.io/docs/configuration.html#devtool
devtool: options.env === 'development' ? 'cheap-module-eval-source-map' : '',
entry: {
app: [
...polyfills,
...devtools.entry(options),
options.entry,
],
},
module: {
rules: [
...assetsLoaders,
babelLoader(options),
...devtools.loaders(options),
...styles.loaders(options),
],
},
output: output(options),
plugins: [
...globals(options),
...devtools.plugins(options),
...styles.plugins(options),
...optimize(options),
...isomorphic(options),
],
}
}
| vacuumlabs/webpack-config-vacuumlabs | src/makeConfig.js | JavaScript | unlicense | 1,343 |
mycallback( {"_record_type": "fec.version.v7_0.TEXT", "FILER COMMITTEE ID NUMBER": "C00441410", "REC TYPE": "TEXT", "TEXT4000": "8110 La Jolla Shores", "TRANSACTION ID NUMBER": "TINCA492", "_src_file": "2011/20110504/727399.fec_1.yml", "BACK REFERENCE TRAN ID NUMBER": "INCA492", "BACK REFERENCE SCHED / FORM NAME": "SA11AI"});
| h4ck3rm1k3/federal-election-commission-aggregation-json-2011 | objects/81/b02ffab62f9e64227debb676f18f4a7be31103.js | JavaScript | unlicense | 328 |
// var assert = require('assert');
// describe('Array', function() {
// describe('#indexOf()', function () {
// it('should return -1 when the value is not present', function () {
// assert.equal(-1, [1,2,3].indexOf(5));
// assert.equal(-1, [1,2,3].indexOf(1)); // ここが失敗する
// });
// });
// });
| katsut/sls_apps | test/handlers/cleaning.test.js | JavaScript | unlicense | 331 |
// root.part1.js | danatcofo/VS.NET-Javascript-Include | Javascipt-Include/JavascriptInclude.Tests.Src/src/root.part1.js | JavaScript | unlicense | 19 |
// Load our dependencies
var quote = require('shell-quote').quote;
var SemVer = require('semver').SemVer;
var shell = require('shelljs');
// Define our release process
exports.publish = function (params, cb) {
// Calculate the semver branches (e.g. `1.2.3` -> `1.2.x`, `1.x.x`)
var semver = new SemVer(params.version);
var minorBranch = [semver.major, 'x', 'x'].join('.'); // 1.x.x
var patchBranch = [semver.major, semver.minor, 'x'].join('.'); // 1.2.x
// Update the branches, push the branches, and go back to the original branch
// DEV: We should force push but based on some configs that could push all branches
shell.exec(quote(['git', 'checkout', '-B', minorBranch]));
shell.exec('git push');
shell.exec('git checkout -');
shell.exec(quote(['git', 'checkout', '-B', patchBranch]));
shell.exec('git push');
shell.exec('git checkout -');
process.nextTick(cb);
};
| twolfson/foundry-release-git-semver-branches | lib/foundry-release-git-semver-branches.js | JavaScript | unlicense | 895 |
/**
* pseries - a JavaScript micro-library for handling asynchronous flow control
* https://github.com/rBurgett/pseries
*
* Copyright (c) 2016 by Ryan Burgett.
* Licensed under Apache License Version 2.0
* https://github.com/rBurgett/pseries/blob/master/LICENSE
**/
const pseries = arr => {
return new Promise((resolve, reject) => {
if(!Array.isArray(arr) || arr.length === 0) {
reject(new Error('You must pass in an array of promise-returning functions.'));
}
const runFuncs = (funcArr, i = 0, resArray = []) => {
const func = funcArr[i];
if(typeof func !== 'function') {
reject(new Error('The passed-in array must only contain promise-returning functions.'));
}
func().then(
res => {
const newResArray = resArray.concat([res]);
if(i === funcArr.length - 1) {
resolve(newResArray);
} else {
runFuncs(funcArr, i + 1, newResArray);
}
},
err => reject(err)
);
};
runFuncs(arr);
});
};
if (typeof exports !== 'undefined') {
if (typeof module !== 'undefined' && module.exports) {
module.exports = pseries;
}
exports.pseries = pseries;
} else if (typeof define !== 'undefined' && define.amd) {
define([], function () { return pseries; });
} else {
global.pseries = pseries;
}
| rBurgett/pseries | src/pseries.js | JavaScript | apache-2.0 | 1,528 |
/**
* Created by plter on 6/29/16.
*/
(function () {
function Main() {
this._MAX_VALUE = 100;
this._data = [10, 11, 13, 20, 16, 18, 23, 20, 30, 25, 20, 35];
this._context2d = document.getElementById("canvas").getContext("2d");
this.drawData();
}
Main.prototype.drawData = function () {
//绘制折线图
// var p = this.getPositionByIndex(0);
// this._context2d.moveTo(p.x, p.y);
//
// for (var i = 1; i < this._data.length; i++) {
// p = this.getPositionByIndex(i);
// this._context2d.lineTo(p.x, p.y);
// }
// this._context2d.stroke();
//绘制柱状图
this.drawRect(this.getPositionByIndex(0));
for (var i = 1; i < this._data.length; i++) {
this.drawRect(this.getPositionByIndex(i));
}
this._context2d.stroke();
};
Main.prototype.drawRect = function (p) {
this._context2d.fillRect(p.x, p.y, 10, 400 - p.y);
};
Main.prototype.getPositionByIndex = function (index) {
var y = 400 * (1 - this._data[index] / this._MAX_VALUE);
var x = (400 / 12) * index + 10;
return {x: x, y: y};
};
new Main();
})(); | plter/HTML5Course20160612 | 20160629/Chart/app.js | JavaScript | apache-2.0 | 1,244 |
sap.ui.define(['sap/ui/core/UIComponent'],
function (UIComponent) {
"use strict";
return UIComponent.extend("sap.m.sample.WizardCurrentStep.Component", {
metadata: {
manifest: "json"
}
});
});
| SAP/openui5 | src/sap.m/test/sap/m/demokit/sample/WizardCurrentStep/Component.js | JavaScript | apache-2.0 | 213 |
var fs=require("fs"),path=require("path"),util=require("util"),npmlog=require("npmlog"),async=require("async"),streamBuffers=require("stream-buffers"),crypto=require("crypto"),luna=require("./luna"),novacom=require("./novacom"),errMsgHndl=require("./error-handler");
(function(){var c=npmlog;c.heading="installer";c.level="warn";var r={log:c,install:function(a,e,g){if("function"!==typeof g)throw Error("Missing completion callback (next="+util.inspect(g)+")");var d=path.basename(e);if(d){var k="/media/developer/temp/"+d,m=new streamBuffers.ReadableStreamBuffer,p=new streamBuffers.WritableStreamBuffer,q=a.appId,b,f,l=200;c.info("installer#install():","installing "+e);m.pause();a=a||{};async.waterfall([function(h){a.nReplies=0;new novacom.Session(a.device,h)},function(h,
c){a.session=h;if(a.opkg&&"root"!=a.session.getDevice().username)return setImmediate(c,Error("opkg-install is only available for the device allowing root-connection"));var b="/bin/rm -rf /media/developer/temp/ && /bin/mkdir -p /media/developer/temp/";"root"===a.session.getDevice().username&&(b+=" && /bin/chmod 777 /media/developer/temp/");a.op=(h.target.files||"stream")+"Put";a.session.run(b,null,null,null,c)},function(h){console.log("Installing package "+e);var b=a.op;if("streamPut"===b)fs.readFile(e,
function(f,n){if(f)return h(f);m.put(n);c.verbose("installer#type:",b);a.session[b](k,m,h)});else if("sftpPut"===b)c.verbose("installer#type:",b),a.session[b](e,k,h);else return c.verbose("installer#type:","unknown files type for installation"),h(Error("unknown files type for installtaion"))},function(h){a.session.run("/bin/ls -l "+k,null,p,null,h)},function(a){c.verbose("installer#install():","ls -l:",p.getContents().toString());a()},function(a){var f=crypto.createHash("md5"),d=new Buffer(l),n=0;
async.waterfall([fs.lstat.bind(fs,e),function(a,b){a.size>l?n=a.size-l:(n=0,l=a.size);b()},fs.open.bind(fs,e,"r"),function(a,b){fs.read(a,d,0,l,n,function(a,h){f.update(d);b()})},function(){(b=f.digest("hex"))||c.warn("installer#install():","Failed to get md5sum from the ipk file");c.verbose("installer#install():","srcMd5:",b);a()}],function(b){a(b)})},function(b){function d(a){if(a=Buffer.isBuffer(a)?a.toString().trim():a.trim())f=a.split("-")[0].trim(),c.verbose("installer#install():","dstMd5:",
f);f||c.warn("installer#install():","Failed to get md5sum from the transmitted file");b()}var e="/usr/bin/tail -c "+l+" "+k+" | /usr/bin/md5sum";async.series([function(b){a.session.run(e,null,d,null,b)}],function(a){if(a)return b(a)})},function(a){if(b&&f){if(c.verbose("installer#install():","srcMd5:",b,", dstMd5:",f),b!==f)return a(Error("File transmission error, please try again."))}else c.warn("installer#install():","Cannot verify transmitted file");a()},function(b){function f(b){function c(a){a=
Buffer.isBuffer(a)?a.toString():a;console.log(a)}var h="/usr/bin/opkg install "+k,h=h.concat(a.opkg_param?" "+a.opkg_param:"");async.series([a.session.run.bind(a.session,h,null,c,c),a.session.run.bind(a.session,"/usr/sbin/ls-control scan-services ",null,null,c)],function(a){if(a)return b(a);b(null,null)})}function d(b){var f=a.session.getDevice(),h=f.lunaResult.install;luna.send(a,f.lunaAddr.install,"webos3"===f.type?{target:k,subscribe:!0}:{id:q,ipkUrl:k,subscribe:!0},function(a,b){c.verbose("installer#install():",
"lineObj: %j",a);var f=h.getResultValue(a);f.match(/FAILED/i)?(c.verbose("installer#install():","failure"),b(errMsgHndl.changeErrMsg(f))):f.match(/installed|^SUCCESS/i)?(c.verbose("installer#install():","success"),b(null,f)):(c.verbose("installer#install():","waiting"),b(null,null))},b)}op=a.opkg?f:d;op(b)},function(b,f){"function"===typeof b&&(f=b);a.session.run("/bin/rm -f "+k,null,null,null,f)},function(){a.session.end();a.session=null;g(null,{msg:"Success"})}],function(a){c.verbose("installer#waterfall callback err:",
a);g(a)})}else g(Error("Invalid package: '"+e+"'"))},remove:function(a,e,g){if("function"!==typeof g)throw Error("Missing completion callback (next="+util.inspect(g)+")");a=a||{};async.waterfall([function(c){a.nReplies=void 0;a.session=new novacom.Session(a.device,c)},function(c,e){a.session=c;if(a.opkg&&"root"!=a.session.getDevice().username)return setImmediate(e,Error("opkg-remove is only available for the device allowing root-connection"));setImmediate(e)},function(d){function g(c){function d(a){a=
Buffer.isBuffer(a)?a.toString():a;return c(Error(a))}var b="/usr/bin/opkg remove "+e,b=b.concat(a.opkg_param?" "+a.opkg_param:"");async.series([a.session.run.bind(a.session,b,null,function(a){a=Buffer.isBuffer(a)?a.toString():a;console.log(a);if(a.match(/No packages removed/g))return c(Error("[package Name: "+e+"] "+a))},d),a.session.run.bind(a.session,"/usr/sbin/ls-control scan-services ",null,null,d)],function(a){if(a)return c(a);c(null,{})})}function m(d){var g=a.session.getDevice(),b=g.lunaResult.remove,
f=0;luna.send(a,g.lunaAddr.remove,"webos3"===g.type?{subscribe:!0,packageName:e}:{id:e,subscribe:!0},function(a,d){c.verbose("installer#remove():","lineObj: %j",a);var g=b.getResultValue(a);g.match(/FAILED/i)?(c.verbose("installer#remove():","failure"),f++||d(Error(g))):g.match(/removed|^SUCCESS/i)?(c.verbose("installer#remove():","success"),d(null,{status:g})):(c.verbose("installer#remove():","waiting"),d())},d)}op=a.opkg?g:m;op(d)}],function(a,k){c.verbose("installer#remove():","err:",a,"result:",
k);a||(k.msg="Removed package "+e);g(a,k)})},list:function(a,e){if("function"!==typeof e)throw Error("Missing completion callback (next="+util.inspect(e)+")");a=a||{};async.waterfall([function(c){a.nReplies=1;a.session=new novacom.Session(a.device,c)},function(c,d){a.session=c;if(a.opkg&&"root"!=a.session.getDevice().username)return setImmediate(d,Error("opkg-list is only available for the device allowing root-connection"));setImmediate(d)},function(g){function d(c){function d(a){a=Buffer.isBuffer(a)?
a.toString():a;console.log(a)}var e;e="/usr/bin/opkg list".concat(a.opkg_param?" "+a.opkg_param:"");async.series([a.session.run.bind(a.session,e,null,d,d)],function(a){if(a)return c(a);c(null,{})})}function e(d){var g=a.session.getDevice().lunaAddr.list,k=a.session.getDevice().lunaResult.list,b;luna.send(a,g,{subscribe:!1},function(a,d){b=k.getResultValue(a);if(Array.isArray(b)){for(var e=0;e<b.length;e++)b[e].visible||(b.splice(e,1),e--);c.verbose("installer#list():","success");d(null,b)}else c.verbose("installer#list():",
"failure"),d(Error("object format error"))},d)}op=a.opkg?d:e;op(g)}],function(a,d){c.verbose("installer#list():","err:",a,"results:",d);e(a,d)})}};"undefined"!==typeof module&&module.exports&&(module.exports=r)})();
| recurve/ares-ecosystem | node_modules/ares-webos-sdk/lib/installer.js | JavaScript | apache-2.0 | 6,625 |
$(function () {
$("#jqGrid").jqGrid({
url: '../sys/log/list',
datatype: "json",
colModel: [
{ label: 'id', name: 'id', width: 30, key: true,hidden : true },
{ label: '用户名', name: 'username', width: 50 },
{ label: '用户操作', name: 'operation', width: 70 },
{ label: '请求方法', name: 'method', width: 150 },
{ label: '请求参数', name: 'params', width: 80 },
{ label: 'IP地址', name: 'ip', width: 70 },
{ label: '创建时间', name: 'createDate', width: 90 }
],
viewrecords: true,
height: 385,
rowNum: 20,
rowList : [20,30,50,100,200],
rownumbers: true,
rownumWidth: 25,
autowidth:true,
multiselect: false,
pager: "#jqGridPager",
jsonReader : {
root: "page.list",
page: "page.currPage",
total: "page.totalPage",
records: "page.totalCount"
},
prmNames : {
page:"page",
rows:"limit",
order: "order"
},
gridComplete:function(){
//隐藏grid底部滚动条
$("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" });
}
});
});
var vm = new Vue({
el:'#rrapp',
data:{
q:{
key: null
},
},
methods: {
query: function () {
vm.reload();
},
reload: function (event) {
var page = $("#jqGrid").jqGrid('getGridParam','page');
$("#jqGrid").jqGrid('setGridParam',{
postData:{'key': vm.q.key},
page:page
}).trigger("reloadGrid");
}
}
}); | oyhf521/school | school-web/src/main/webapp/js/sys/log.js | JavaScript | apache-2.0 | 1,678 |
var fs = require('fs'),
isCompressibleFile = require('../src/compressor')
._isCompressibleFile,
path = require('path');
var compressibleFiles = [
'file.js',
'file.css',
'file.html',
'uppercase.HTML'
];
describe( 'compressor', function() {
describe( 'isCompressibleFile', function() {
compressibleFiles.forEach( function( filename ) {
it( 'should compress ' + filename, function() {
var filePath = path.join( './test/support', filename );
var stream = fs.createReadStream( filePath );
var isCompressible = isCompressibleFile( stream );
expect( isCompressible ).to.equal( true );
} );
} );
it( 'should not compress GIF files', function() {
var stream = fs.createReadStream( './test/support/file.gif' );
var isCompressible = isCompressibleFile( stream );
expect( isCompressible ).to.equal( false );
} );
} );
} );
| omsmith/gulp-frau-publisher | test/isCompressibleFile.js | JavaScript | apache-2.0 | 869 |
'use strict';
const chai = require('chai');
const assert = chai.assert;
const EventEmitterEnhancer = require('event-emitter-enhancer');
const ResultSetReadStream = require('../../lib/resultset-read-stream');
describe('ResultSetReadStream Tests', function () {
const failListener = function (eventName) {
return function () {
assert.fail(eventName);
};
};
describe('read tests', function () {
it('no data', function (done) {
const stream = new ResultSetReadStream();
EventEmitterEnhancer.modifyInstance(stream);
stream.nextRow = function (callback) {
process.nextTick(function () {
callback();
});
};
['data', 'error'].forEach(function (eventName) {
stream.on(eventName, failListener(eventName));
});
const remove = stream.onAny(['end', 'close'], function () {
remove();
done();
});
});
it('null data', function (done) {
const stream = new ResultSetReadStream();
EventEmitterEnhancer.modifyInstance(stream);
stream.nextRow = function (callback) {
process.nextTick(function () {
callback(null, null);
});
};
['data', 'error'].forEach(function (eventName) {
stream.on(eventName, failListener(eventName));
});
const remove = stream.onAny(['end', 'close'], function () {
remove();
done();
});
});
it('multiple rows', function (done) {
const stream = new ResultSetReadStream();
EventEmitterEnhancer.modifyInstance(stream);
let nextCounter = 0;
stream.nextRow = function (callback) {
if (nextCounter >= 5) {
process.nextTick(function () {
callback();
});
} else {
process.nextTick(function () {
nextCounter++;
callback(null, {
row: nextCounter
});
});
}
};
stream.on('error', failListener('error'));
let dataFound = 0;
stream.on('data', function (data) {
dataFound++;
assert.deepEqual(data, {
row: dataFound
});
});
const remove = stream.onAny(['end', 'close'], function () {
assert.equal(dataFound, 5);
remove();
done();
});
});
it('error on start', function (done) {
const stream = new ResultSetReadStream();
stream.nextRow = function (callback) {
process.nextTick(function () {
callback(new Error('test'));
});
};
stream.on('data', failListener('data'));
stream.on('error', function (error) {
assert.equal(error.message, 'test');
done();
});
});
it('error after few data events', function (done) {
let counter = 0;
const stream = new ResultSetReadStream();
stream.nextRow = function (callback) {
counter++;
if (counter < 5) {
process.nextTick(function () {
callback(null, {
id: counter
});
});
} else if (counter === 5) {
process.nextTick(function () {
callback(new Error('test'));
});
} else {
process.nextTick(function () {
callback(new Error('fail'));
});
}
};
['end', 'close'].forEach(function (eventName) {
stream.on(eventName, failListener(eventName));
});
stream.on('data', function (data) {
assert.isTrue(data.id < 5);
});
stream.on('error', function (error) {
assert.equal(error.message, 'test');
done();
});
});
it('all data read', function (done) {
let counter = 0;
const stream = new ResultSetReadStream();
EventEmitterEnhancer.modifyInstance(stream);
stream.nextRow = function (callback) {
counter++;
if (counter < 5) {
process.nextTick(function () {
callback(null, {
id: counter
});
});
} else if (counter === 5) {
process.nextTick(function () {
callback();
});
} else {
process.nextTick(function () {
callback(new Error('fail'));
});
}
};
stream.on('error', failListener('error'));
let dataFound = 0;
stream.on('data', function (data) {
dataFound++;
assert.isTrue(data.id < 5);
});
const remove = stream.onAny(['end', 'close'], function () {
assert.equal(dataFound, 4);
remove();
done();
});
});
});
});
| sagiegurari/simple-oracledb | test/spec/resultset-read-stream-spec.js | JavaScript | apache-2.0 | 5,779 |
/**
* JS for MaIOMan App UI Config
*
* @author: manu.martor@gmail.com
* @version: 1.0.0
**/
angular.module('app.ui')
.config(function ($routeProvider) {
//set routes
$routeProvider
.when("/myprofile", {
templateUrl: "js/core/ui/views/myprofile.html",
controller: "appMyProfileController"})
.when("/myconfig", {
templateUrl: "js/core/ui/views/myconfig.html",
controller: "appMyConfigController"})
}); | manumartor/app-dashboard-skeleton | public/js/core/ui/app-ui.config.js | JavaScript | apache-2.0 | 431 |
/**
* Copyright 2017 dialog LLC <info@dlg.im>
* @flow
*/
import type { Props } from './types';
import type { ProviderContext } from '@dlghq/react-l10n';
import React, { PureComponent } from 'react';
import { LocalizationContextType } from '@dlghq/react-l10n';
import styles from './ContextMenu.css';
import Trigger from '../Trigger/Trigger';
import Dropdown from '../Dropdown/Dropdown';
import DropdownItem from '../Dropdown/DropdownItem';
export type Context = ProviderContext;
class ContextMenu extends PureComponent {
props: Props;
context: Context;
static contextTypes = {
l10n: LocalizationContextType
};
renderMenuItems() {
const items = this.props.getMenu();
return items.map(({ title, handler }, index) => {
return (
<DropdownItem key={index} onClick={handler}>
{this.context.l10n.formatText(title)}
</DropdownItem>
);
});
}
renderMenu = (position: Object) => {
return (
<Dropdown
className={styles.container}
style={{ left: window.pageXOffset + position.x, top: window.pageYOffset + position.y }}
>
{this.renderMenuItems()}
</Dropdown>
);
};
renderTrigger = (newProps: Object) => {
return (
<span {...newProps}>{this.props.children}</span>
);
};
render() {
const options = {
attachment: 'top left',
targetAttachment: 'top left',
target: document.body,
constraints: [
{
to: 'window',
attachment: 'together'
}
]
};
return (
<Trigger
openHandler={['onContextMenu']}
closeHandler={['onClick']}
closeOnDocumentClick
preventDefault
renderTrigger={this.renderTrigger}
renderChild={this.renderMenu}
options={options}
/>
);
}
}
export default ContextMenu;
| nolawi/champs-dialog-sg | src/components/ContextMenu/ContextMenu.js | JavaScript | apache-2.0 | 1,862 |
var a=20, b= 9, c=1, d=null;
var dag1 = 'maandag';
var dag2 = 'dinsdag';
var dag3 = 'Dinsdag';
var score = 100;
console.log(score === 100); //true
console.log(score !==100); //false
console.log(score < 20 || score >50); //true
console.log(score > 0 && score > 99); //true
console.log(score < 30 || score > 100 || 1==1); //true
console.log(a === 20 && b<8 && c<3); //false
console.log(a === 20 && b>8 || c<3); //true
console.log(a == d);//false
console.log(dag1 != dag2); //true
console.log(dag3 == dag2); //false | wesleyvano/KW1C_Javascript-L1P3 | Hoofdstuk 3/314/scripts/Script.js | JavaScript | apache-2.0 | 518 |
/**
* @copyright Copyright (c) 2014 X.commerce, Inc. (http://www.magentocommerce.com)
*/
/*jshint browser:true jquery:true */
/*global console:true*/
define([
"jquery",
"handlebars",
"jquery/ui",
"jquery/template",
"mage/translate"
], function($){
$.widget("mage.loader", {
loaderStarted: 0,
spinnerTemplate: $(undefined),
options: {
icon: '',
texts: {
loaderText: $.mage.__('Please wait...'),
imgAlt: $.mage.__('Loading...')
},
template: '<script id="loader-template" type="text/x-handlebars-template">' +
'<div class="loading-mask" data-role="loader">' +
'<div class="loader">' +
'<img alt="{{imgAlt}}" src="{{icon}}">' +
'<p>{{loaderText}}</p>' +
'</div>' +
'</div>' +
'</script>'
},
/**
* Loader creation
* @protected
*/
_create: function() {
this._bind();
},
/**
* Bind on ajax events
* @protected
*/
_bind: function() {
this._on({
'processStop': 'hide',
'processStart': 'show',
'show.loader': 'show',
'hide.loader': 'hide',
'contentUpdated.loader': '_contentUpdated'
});
},
/**
* Verify loader present after content updated
*
* This will be cleaned up by the task MAGETWO-11070
*
* @param event
* @private
*/
_contentUpdated: function(e) {
this.show(e);
},
/**
* Show loader
*/
show: function(e, ctx) {
this._render();
this.loaderStarted++;
this.spinner.show();
if (ctx) {
this.spinner
.css({width: ctx.outerWidth(), height: ctx.outerHeight(), position: 'absolute'})
.position({
my: 'top left',
at: 'top left',
of: ctx
});
}
return false;
},
/**
* Hide loader
*/
hide: function() {
if (this.loaderStarted > 0) {
this.loaderStarted--;
if (this.loaderStarted === 0) {
this.spinner.hide();
}
}
return false;
},
/**
* Render loader
* @protected
*/
_render: function() {
if (this.spinnerTemplate.length === 0) {
this.spinnerTemplate = $(this.options.template)/*.css(this._getCssObj())*/;
var source = this.spinnerTemplate.html();
var template = Handlebars.compile(source);
var content = {
imgAlt: this.options.texts.imgAlt,
icon: this.options.icon,
loaderText: this.options.texts.loaderText
};
var html = $(template(content));
html.prependTo(this.element);
this.spinner = html;
}
},
/**
* Destroy loader
*/
_destroy: function() {
this.spinner.remove();
}
});
/**
* This widget takes care of registering the needed loader listeners on the body
*/
$.widget("mage.loaderAjax", {
options: {
defaultContainer: '[data-container=body]',
loadingClass: 'ajax-loading'
},
_create: function() {
this._bind();
// There should only be one instance of this widget, and it should be attached
// to the body only. Having it on the page twice will trigger multiple processStarts.
if (window.console && !this.element.is(this.options.defaultContainer) && $.mage.isDevMode(undefined)) {
console.warn("This widget is intended to be attached to the body, not below.");
}
},
_bind: function() {
$(document).on({
'ajaxSend': this._onAjaxSend.bind(this),
'ajaxComplete': this._onAjaxComplete.bind(this)
});
},
_getJqueryObj: function(loaderContext) {
var ctx;
// Check to see if context is jQuery object or not.
if (loaderContext) {
if (loaderContext.jquery) {
ctx = loaderContext;
} else {
ctx = $(loaderContext);
}
} else {
ctx = $('[data-container="body"]');
}
return ctx;
},
_onAjaxSend: function(e, jqxhr, settings) {
$(this.options.defaultContainer).addClass(this.options.loadingClass);
if (settings && settings.showLoader) {
var ctx = this._getJqueryObj(settings.loaderContext);
ctx.trigger('processStart');
// Check to make sure the loader is there on the page if not report it on the console.
// NOTE that this check should be removed before going live. It is just an aid to help
// in finding the uses of the loader that maybe broken.
if (window.console && !ctx.parents('[data-role="loader"]').length) {
console.warn('Expected to start loader but did not find one in the dom');
}
}
},
_onAjaxComplete: function(e, jqxhr, settings) {
$(this.options.defaultContainer).removeClass(this.options.loadingClass);
if (settings && settings.showLoader) {
this._getJqueryObj(settings.loaderContext).trigger('processStop');
}
}
});
return {
loader: $.mage.loader,
loaderAjax: $.mage.loaderAjax
};
});
| webadvancedservicescom/magento | lib/web/mage/loader.js | JavaScript | apache-2.0 | 6,134 |
var args = arguments[0] || {};
var tabindex = args.tab;
$.tabGroup.setActiveTab(tabindex);
activateIcon(tabindex);
function activateIcon(tabindex) {
activate($.tabGroup.getTabs()[tabindex]);
}
function activate(tab) {
$.watch.icon = "/images/tabIconWatchDisable.png";
$.park.icon = "/images/tabIconParkDisable.png";
$.crossing.icon = "/images/tabIconCrossingDisable.png";
if ($.watch.active) {
$.watch.icon = "/images/tabIconWatch.png";
return;
}
if ($.park.active) {
$.park.icon = "/images/tabIconPark.png";
return;
}
if ($.crossing.active) {
$.crossing.icon = "/images/tabIconCrossing.png";
return;
}
}
function activateIcon(e) {
activate($.tabGroup.activeTab);
}
| mix-juice001/MobileAgentPilot | app/controllers/safetyDrive4Veteran.js | JavaScript | apache-2.0 | 695 |
/*
* ../../../..//localization/sco/HelpDialog.js
*
* Copyright (c) 2009-2018 The MathJax Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*************************************************************
*
* MathJax/localization/sco/HelpDialog.js
*
* Copyright (c) 2009-2018 The MathJax Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
MathJax.Localization.addTranslation("sco", "HelpDialog", {
version: "2.7.5",
isLoaded: true,
strings: {
Help: "MathJax Heelp",
MathJax:
"*MathJax* is ae JavaScreept librairie that allous page authers tae incluid mathematics wiin thair wab pages. Aes ae reader, ye dinna need tae dae oniething tae mak that happen.",
Browsers:
"*Brousers*: MathJax warks wi aw modern brousers incluidin IE6+, Firefox 3+, Chrome 0.2+, Safari 2+, Opera 9.6+ n maist mobile brousers.",
Menu:
"*Maths menu*: MathJax adds ae contextual menu til equations. Richt-clap or Ctrl-clap oan onie mathematics tae access the menu.",
ShowMath:
"*Shaw maths aes* Permits ye tae view the formula's soorce maurkup fer copie \u0026 paste (aes MathML or in its oreeginal format).",
Settings:
"*Settins* gies ye control ower features o MathJax, lik the size o the mathematics, n the mechanism uised tae displey equations.",
Language: "*Leid* lets ye select the leid uised bi MathJax fer its menus n warnishment messages.",
Zoom:
"*Maths zuim*: Gif ye'r haein difficultie readin aen equation, MathJax can mak it mair muckle tae heelp ye see it better.",
Accessibilty:
"*Accessibeelitie*: MathJax will aut\u00E6maticlie wark wi screen readers tae mak mathematics accessible til the veesuallie impaired.",
Fonts:
"*Fonts*: MathJax will uise certain maths fonts gif thay ar installed oan yer computer; itherwise, it will uise wab-based fonts. Awthough no needit, locallie installed fonts will speed up typesettin. We suggest installin the [STIX fonts](%1)."
}
});
MathJax.Ajax.loadComplete("[MathJax]/localization/sco/HelpDialog.js");
| GerHobbelt/MathJax | localization/sco/HelpDialog.js | JavaScript | apache-2.0 | 3,102 |
/**
* Copyright 2017 Goldman Sachs.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/* Display a stock ticker that provides typeahead (aka autocomplete) capability.
* This requires making an AJAX HTTP request (asynchronous JavaScript and XML request) to
* your service and prefetching the list of all available stock tickers or making an async
* query every time the input changes (AsyncTypeahead). If you don't have a route defined
* in your services/API that returns all stock tickers as a JSON object, create one!
*
* You can use promises(axios),
* fetch, jQuery...there are many libraries to help you do this. The data you will
* receive will be in a JSON format.
* https://hashnode.com/post/5-best-libraries-for-making-ajax-calls-in-react-cis8x5f7k0jl7th53z68s41k1
* fetch: https://davidwalsh.name/fetch
* axios: https://github.com/mzabriskie/axios (you will need to install this package)
* jquery: http://api.jquery.com/jquery.getjson/ (you will need to install the jquery package)
*
* Feel free to choose among of the many open source options for your typeahead select box.
* We recommend react-select or react-bootstrap-typeahead. react-boostrap-typeahead is included
* in your package.json.
*
* react-select:
* https://www.npmjs.com/package/react-select
* http://jedwatson.github.io/react-select/
* https://github.com/JedWatson/react-select
*
* react-boostrap-typeahead
* https://www.npmjs.com/package/react-bootstrap-typeahead
* http://ericgio.github.io/react-bootstrap-typeahead/
* https://github.com/ericgio/react-bootstrap-typeahead/blob/master/example/examples/BasicBehaviorsExample.react.js (note this is not ES2015)
*/
import React from 'react';
//import {Typeahead} from 'react-bootstrap-typeahead'; UNCOMMENT this line if you are using the react-bootstrap-typeeahead component
/* If you chose to use react-boostrap-typeahead, look at AsyncTypeahead for a component that
* provides auto-complete suggestions as you type. This would require adding a search handler
* method for an onSearch prop.
* https://github.com/ericgio/react-bootstrap-typeahead/blob/master/example/examples/AsyncExample.react.js
*/
class StockTicker extends React.Component {
/**
* TODO
* Prefetch the data required to display options fo the typeahead component. Initialize a state array with
* this data and pass it via props to the typeahead component that will be rendered.
* https://github.com/ericgio/react-bootstrap-typeahead/blob/master/docs/Data.md
* e.g.
* options : [
* GS,
* AAPL,
* FB,
* ]
* If you are having difficulty with this, you may hard code the options array from the company data provided for the
* services.
*/
constructor(props) {
super(props);
this.state = {
showcompanyinfo: false, //TODO: Use this boolean to determine if the company information should be rendered
company : {
symbol: '',
name: '',
city: '',
state: '',
sector: '',
industry: ''
}
/**
* TODO
* Add any additional state to pass via props to the typeahead component.
*/
};
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
if (event.length > 0) {
/**
* TODO
* Make a request to your service to GET company information for the selected company and set it in state.
* The information you will need to determine the URL will be contained in the 'event[0]' object,
* e.g. event[0] (event[0].symbol if your options are an array of objects) provides you the symbol selected.
* The URL will be on your localhost (e.g. http://localhost:8000/service_path/some_param) where
* your service is running. Your service MUST be running for the request to work (you can add a catch function
* to handle errors). If you successfully retrieve this information, you can set the state objects
* and render it.
*/
this.setState({showinfo: true});
//this.props.onChange(..); Call this.props.onChange with the selected symbol to propagate it
// to the App component, which will handle it via its own onChane prop,
// ultimately used to fetch the data for the LineChart component.
}
else {
this.setState({showinfo: false});
this.props.onChange(undefined);
}
}
render() {
/**
* TODO
* Render a typeahead component that uses the data prefetched from your service to display a list of companies or
* ticker symbols. The props you use can be stored as state objects.
* On change should fetch the company information and display Company, Ticker Symbol, City, State/Country, Sector, and Industry information.
* https://github.com/ericgio/react-bootstrap-typeahead/blob/master/docs/Props.md
*/
return (
<div className="stockticker">
<div className="ticker-input">
<p>Stock Ticker: </p>
<input type = 'text' className = 'ticker-input' name="StockTicker" value={this.props.value} onChange={this.handleChange}/>
<div className="stockticker-typeahead">
{/* useful props if you decide to use react-bootstrap-typeahead
<Typeahead
align=
filterBy=
labelKey=
onChange={this.handleChange}
minLength=
placeholder="Company Name/Ticker"
options=
/>
*/}
</div>
</div>
{
/**
* TODO
* Create a div element that shows a company information when the ticker changes. You will need to use a conditional here
* to help control rendering and pass these states as props to the component. This conditional can
* be maintained as a state object.
* http://reactpatterns.com/#conditional-rendering
*/
}
</div>
);
}
}
export default StockTicker; | jennybkim/engineeringessentials | caseStudy/ui/src/components/StockTicker.js | JavaScript | apache-2.0 | 7,265 |
'use strict';
angular.module("openshiftConsole")
.factory("AppsService", function() {
var appLabel = function(apiObject) {
return _.get(apiObject, 'metadata.labels.app', '');
};
// Place empty app labels last.
var compareAppNames = function(left, right) {
if (!left && !right) {
return 0;
}
if (!left) {
return 1;
}
if (!right) {
return -1;
}
return left.toLowerCase().localeCompare(right.toLowerCase());
};
return {
groupByApp: function(collection, sortBy) {
var byApp = _.groupBy(collection, appLabel);
if (sortBy) {
_.mapValues(byApp, function(items) {
return _.sortBy(items, sortBy);
});
}
return byApp;
},
// Sort an array of app names.
sortAppNames: function(appNames) {
appNames.sort(compareAppNames);
}
};
});
| openshift/origin-web-console | app/scripts/services/apps.js | JavaScript | apache-2.0 | 930 |
Handlebars.registerPartial("errorDiv", window.HandlebarsTemplates["components/error_div"]);
Handlebars.registerPartial("itemTags", window.HandlebarsTemplates["item_tags"]);
Handlebars.registerPartial("workspaceItemDetails", window.HandlebarsTemplates["workspace_item_details"]);
Handlebars.registerPartial("itemLastComment", window.HandlebarsTemplates["item_last_comment"]);
Handlebars.registerPartial("multipleSelectionHeader", window.HandlebarsTemplates["multiple_selection_header"]);
Handlebars.registerPartial("listItemText", window.HandlebarsTemplates["list_item_text"]);
Handlebars.registerPartial("formControls", window.HandlebarsTemplates["components/form_controls"]);
Handlebars.registerPartial("csvImportConsole", window.HandlebarsTemplates["csv_import_console"]);
Handlebars.registerPartial("closeWindowFormControls", window.HandlebarsTemplates["components/close_window_form_controls"]);
Handlebars.registerPartial("timeZoneSelector", window.HandlebarsTemplates["time_zone_selector"]);
Handlebars.registerPartial("activity", window.HandlebarsTemplates["activity"]);
Handlebars.registerPartial("adminBadge", window.HandlebarsTemplates["components/admin_badge"]);
Handlebars.registerPartial("developerBadge", window.HandlebarsTemplates["components/developer_badge"]);
Handlebars.registerPartial("drawerMenu", window.HandlebarsTemplates["components/drawer_menu"]);
Handlebars.registerPartial("usernameMenu", window.HandlebarsTemplates["components/username_menu"]);
Handlebars.registerPartial("notificationsMenu", window.HandlebarsTemplates["components/notifications_menu"]);
Handlebars.registerPartial("headerLeft", window.HandlebarsTemplates["components/header_left"]);
Handlebars.registerPartial("headerSearchbar", window.HandlebarsTemplates["components/header_searchbar"]);
Handlebars.registerPartial("headerRight", window.HandlebarsTemplates["components/header_right"]);
| nvoron23/chorus | app/assets/javascripts/utilities/handlebars_partials.js | JavaScript | apache-2.0 | 1,886 |
// @flow
const ExtractTextPlugin = require("extract-text-webpack-plugin");
function wrapExtract(
{ platform, use } /* { platform: Platform, use: Array<Object> } */
) {
const wrapped = ExtractTextPlugin.extract({
use
});
return platform === "browser" || platform === "desktop" ? wrapped : use;
}
function getRule(
{
fileType,
platform,
modules,
NODE_ENV
} /* {
* fileType: Function,
* platform: Platform,
* modules: boolean,
* NODE_ENV: 'development' | 'production',
* } */
) {
const test = modules ? fileType("text/css") : fileType("text/x-css-vendor");
const exclude = modules ? /node_modules/ : undefined;
const loader = platform === "server" ? "css-loader/locals" : "css-loader";
const localIdentName =
NODE_ENV === "production"
? "[hash:base64:8]"
: "[path][name]__[local]__[hash:base64:3]";
const importLoaders = platform === "server" ? 0 : 1;
const use = [
{
loader,
options: {
importLoaders,
minimize: NODE_ENV === "production",
modules,
localIdentName
}
},
"postcss-loader"
];
return {
test,
use: wrapExtract({ platform, use }),
exclude
};
}
function cssModules() {
return (
{
fileType,
platform,
webpack
} /* : { fileType: Function, platform: Platform, webpack: Object } */
) => {
const { NODE_ENV } = process.env;
fileType.add({
"text/x-css-vendor": /node_modules.*\.css$/
});
const config = {
module: {
rules: [
getRule({ fileType, platform, NODE_ENV, modules: true }),
getRule({ fileType, platform, NODE_ENV, modules: false })
]
}
};
if (platform === "browser" || platform === "desktop") {
return Object.assign({}, config, {
plugins: [
new ExtractTextPlugin({
filename: "styles.css",
allChunks: true
})
]
});
}
return config;
};
}
module.exports = cssModules;
| tribou/react-template | config/webpack/blocks/cssModules.js | JavaScript | apache-2.0 | 2,032 |
/*!@license
* Infragistics.Web.ClientUI utilities localization resources 13.1.20131.1012
*
* Copyright (c) 2011-2013 Infragistics Inc.
*
* http://www.infragistics.com/
*
*/
$.ig = $.ig || {};
if (!$.ig.util) {
$.ig.util = {};
$.extend($.ig.util, {
locale: {
unsupportedBrowser: "Der aktuelle Browser unterstützt HTML5 Canvas Element nicht. <br/>Führen Sie ein Upgrade auf eine der folgenden Versionen durch:",
currentBrowser: "Aktueller Browser: {0}",
ie9: "Microsoft Internet Explorer V 9+",
chrome8: "Google Chrome V 8+",
firefox36: "Mozilla Firefox V 3.6+",
safari5: "Apple Safari V 5+",
opera11: "Opera V 11+",
ieDownload: "http://www.microsoft.com/windows/internet-explorer/default.aspx",
operaDownload: "http://www.opera.com/download/",
chromeDownload: "http://www.google.com/chrome",
firefoxDownload: "http://www.mozilla.com/",
safariDownload: "http://www.apple.com/safari/download/"
}
});
}
| mikeleishen/bacosys | frame/frame-web/src/main/webapp/script/ig/modules/i18n/infragistics.util-de.js | JavaScript | apache-2.0 | 952 |
import $ from 'jquery';
import React from 'react';
import ReactDOM from 'react-dom';
import Promise from 'bluebird';
Promise.config({
cancellation: true,
});
import App from './app.jsx';
import * as Api from './api';
import { ApiError } from './utils/http';
var initializationEl = document.querySelector('#initialization');
var progressBarEl = initializationEl.querySelector('.progress-bar');
var progress = +progressBarEl.getAttribute('aria-valuenow');
function incrementProgressBar(gotoPercent) {
progress = Math.min(gotoPercent || (progress + 20), 100); // cap to 100%
progressBarEl.style.width = `${progress}%`;
progressBarEl.setAttribute('aria-valuenow', progress);
progressBarEl.querySelector('span').textContent = `${progress}% Complete`;
}
function renderApp() {
incrementProgressBar(100);
initializationEl.classList.add('done');
initializationEl.addEventListener('transitionend', function() { initializationEl.remove(); });
const appElement = document.querySelector('#app');
ReactDOM.render(App, appElement);
$('#screen').css('padding-top', $('#header-main').height() + 10);
}
export default function startApp() {
incrementProgressBar(25);
// Load user.
var userPromise = Api.getCurrentUser();
userPromise.then(() => {
incrementProgressBar(50);
// Check permissions?
// Get lookups.
var citiesPromise = Api.getCities();
var districtsPromise = Api.getDistricts();
var regionsPromise = Api.getRegions();
var schoolDistrictsPromise = Api.getSchoolDistricts();
var serviceAreasPromise = Api.getServiceAreas();
return Promise.all([citiesPromise, districtsPromise, regionsPromise, schoolDistrictsPromise, serviceAreasPromise]).then(() => {
incrementProgressBar(75);
// Wrapping in a setTimeout to silence an error from Bluebird's promise lib about API requests
// made inside of component{Will,Did}Mount.
setTimeout(renderApp, 0);
});
}).catch(err => {
showError(err);
});
}
function showError(err) {
progressBarEl.classList.add('progress-bar-danger');
progressBarEl.classList.remove('active');
console.error(err);
var errorMessage = String(err);
if (err instanceof ApiError) {
errorMessage = err.message;
}
ReactDOM.render((
<div id="loading-error-message">
<h4>Error loading application</h4>
<p>{errorMessage}</p>
</div>
), document.getElementById('init-error'));
}
window.onload = startApp;
| GeorgeWalker/schoolbus | Client/src/js/init.js | JavaScript | apache-2.0 | 2,457 |
/**
* Cube3D
* http://www.joelambert.co.uk/cube3d
*
* Copyright 2011, Joe Lambert. All rights reserved
* Free to use under the MIT license.
* http://www.opensource.org/licenses/mit-license.php
*/
var Cube = function(elem, opts) {
var _this = this;
this.options = $.extend({
size: 400,
delay: 800,
faceCSS: {
background: 'red'
}
}, opts);
this.element = $(elem);
// This represents the camera/viewport
this.surface = $('<div class="cubeviewport"></div>').css3({
'transform-style': 'preserve-3d',
'perspective': 600,
'perspective-origin': '50% 50%'
});
this.element.append(this.surface);
// This is the container for the cube sides
this.container = $('<div class="cube"></div>').css({
width: this.options.size+'px',
height: this.options.size+'px',
position: 'relative'
}).css3({
'transform': flux.browser.translate(0,0,-this.options.size/2)
});
this.surface.append(this.container);
this.drawCube();
this.container.css3({
'transition-duration': '4000ms',
'transition-timing-function': 'linear',
'transition-property': 'all',
'transform-style': 'preserve-3d'
});
};
Cube.prototype = {
sides: [],
constructor: Cube,
// Perform set rotations
up: function() {
this.applyRotation(new Vector(1,0,0), 90);
},
down: function() {
this.applyRotation(new Vector(1,0,0), -90);
},
left: function() {
this.applyRotation(new Vector(0,1,0), -90);
},
right: function() {
this.applyRotation(new Vector(0,1,0), 90);
},
// Perform matrix transformations
applyRotation: function(vector, angle) {
var _this = this;
// Get the current Matrix
var m = new WebKitCSSMatrix(this.container.css('webkitTransform'));
// Work out what the vector looks like under the current Matrix
vector = m.transformVector(vector);
// Rotate the Matrix around the transformed vector
var newMatrix = m.rotateAxisAngle(vector.x, vector.y, vector.z, angle);
this.container.css3({
'transition-duration': this.options.delay+'ms',
'transition-timing-function': 'linear'
});
setTimeout(function(){
_this.container.get(0).style.webkitTransform = newMatrix;
}, 5);
},
// Render the 6 sides of the Cube and position them in 3D space
drawCube: function() {
// Add the 6 sides of the cube
var defaultCSS = $.extend(this.options.faceCSS, {
position: 'absolute',
top: '0px',
left: '0px',
width: this.options.size+'px',
height: this.options.size+'px'
});
var side1 = $('<div></div>').css3({
'transform': flux.browser.translate(0, 0, this.options.size/2)
}).css(defaultCSS);
var side2 = $('<div></div>').css3({
'transform': flux.browser.rotateX(90) + ' ' + flux.browser.translate(0, 0, this.options.size/2)
}).css(defaultCSS);
var side3 = $('<div></div>').css3({
'transform': flux.browser.rotateY(90) + ' ' + flux.browser.translate(0, 0, this.options.size/2)
}).css(defaultCSS);
var side4 = $('<div></div>').css3({
'transform': flux.browser.rotateX(-90) + ' ' + flux.browser.translate(0, 0, this.options.size/2)
}).css(defaultCSS);
var side5 = $('<div></div>').css3({
'transform': flux.browser.rotateY(-90) + ' ' + flux.browser.translate(0, 0, this.options.size/2)
}).css(defaultCSS);
var side6 = $('<div></div>').css3({
'transform': flux.browser.translate(0, 0, -this.options.size/2)
}).css(defaultCSS);
this.sides.push(side1);
this.sides.push(side2);
this.sides.push(side3);
this.sides.push(side4);
this.sides.push(side5);
this.sides.push(side6);
for(var i=0; i<this.sides.length; i++)
this.container.append(this.sides[i]);
},
// Accessor function
getSide: function(index) {
index = index % this.sides.length;
return this.sides[index];
}
};
| danja/thoughtcatchers.org | www/cube/js/cube.js | JavaScript | apache-2.0 | 3,704 |
//// [couldNotSelectGenericOverload.js]
function makeArray(items) {
return items;
}
var b = [1, ""];
var b1G = makeArray(1, "");
var b2G = makeArray(b);
function makeArray2(items) {
return items;
}
var b3G = makeArray2(1, "");
| fdecampredon/jsx-typescript-old-version | tests/baselines/reference/couldNotSelectGenericOverload.js | JavaScript | apache-2.0 | 248 |
/**
* @license Apache-2.0
*
* Copyright (c) 2020 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
// MODULES //
var bench = require( '@stdlib/bench' );
var discreteUniform = require( '@stdlib/random/base/discrete-uniform' ).factory;
var isnanf = require( '@stdlib/math/base/assert/is-nanf' );
var pow = require( '@stdlib/math/base/special/pow' );
var floor = require( '@stdlib/math/base/special/floor' );
var Float32Array = require( '@stdlib/array/float32' );
var scopy = require( '@stdlib/blas/base/scopy' );
var pkg = require( './../package.json' ).name;
var ssort2hp = require( './../lib/ndarray.js' );
// FUNCTIONS //
/**
* Create a benchmark function.
*
* @private
* @param {PositiveInteger} iter - number of iterations
* @param {PositiveInteger} len - array length
* @returns {Function} benchmark function
*/
function createBenchmark( iter, len ) {
var randi;
var tmp;
var out;
var M;
var x;
var v;
var i;
var j;
randi = discreteUniform( 1, 10 );
M = floor( len*0.333 );
x = [];
for ( i = 0; i < iter; i++ ) {
tmp = new Float32Array( len );
v = randi();
for ( j = 0; j < len; j++ ) {
if ( i % M === 0 ) {
v -= randi();
}
tmp[ j ] = v;
}
x.push( tmp );
}
out = new Float32Array( len );
return benchmark;
function benchmark( b ) {
var xc;
var y;
var i;
xc = x.slice();
for ( i = 0; i < iter; i++ ) {
xc[ i ] = scopy( len, x[ i ], 1, new Float32Array( len ), 1 );
}
b.tic();
for ( i = 0; i < b.iterations; i++ ) {
y = ssort2hp( len, 1, xc[ i ], 1, 0, out, 1, 0 );
if ( isnanf( y[ i%len ] ) ) {
b.fail( 'should not return NaN' );
}
}
b.toc();
if ( isnanf( y[ i%len ] ) ) {
b.fail( 'should not return NaN' );
}
b.pass( 'benchmark finished' );
b.end();
}
}
// MAIN //
function main() {
var opts;
var iter;
var len;
var min;
var max;
var f;
var i;
iter = 1e6;
min = 1; // 10^min
max = 4; // 10^max
for ( i = min; i <= max; i++ ) {
len = pow( 10, i );
f = createBenchmark( iter, len );
opts = {
'iterations': iter
};
bench( pkg+'::reverse_sorted,few_uniques:ndarray:len='+len, opts, f );
iter = floor( pow( iter, 3.0/4.0 ) );
}
}
main();
| stdlib-js/stdlib | lib/node_modules/@stdlib/blas/ext/base/ssort2hp/benchmark/benchmark.rev_sorted_few_uniques.ndarray.js | JavaScript | apache-2.0 | 2,700 |
/* Play [State]
- Everything already loaded
- When player dies go back to menu
*/
// init states
var playState = {
create: function() {
// avoid broweser keyinputs
game.input.keyboard.addKeyCapture(
[Phaser.Keyboard.UP, Phaser.Keyboard.DOWN, Phaser.Keyboard.LEFT, Phaser.Keyboard.RIGHT]
);
this.music = game.add.audio('music');
this.music.loop = true;
this.music.play();
this.music.volume = 0.6;
this.createWorld();
this.cursor = game.input.keyboard.createCursorKeys();
this.player = game.add.sprite(game.world.centerX, game.world.centerY, 'player');
this.player.anchor.setTo(0.5, 0.5);
game.physics.arcade.enable(this.player);
this.player.body.gravity.y = 600;
this.player.animations.add('right', [1, 2], 8, true);
this.player.animations.add('left', [3, 4], 8, true);
this.enemies = game.add.group();
this.enemies.enableBody = true;
this.enemies.createMultiple(15, 'enemy');
this.coin = game.add.sprite(60, 140, 'coin');
game.physics.arcade.enable(this.coin);
this.coin.anchor.setTo(0.5, 0.5);
this.scoreLabel = game.add.text(30, 30, 'score: 0', {
font: '20px Geo',
fill: '#fff'
});
game.global.score = 0;
// game.time.events.loop(2000, this.addEnemy, this);
this.nextEnemy = 0;
this.jumpSound = game.add.audio('jump');
this.coinSound = game.add.audio('coin');
this.deadSound = game.add.audio('dead');
this.emitter = game.add.emitter(0, 0, 15);
this.emitter.makeParticles('pixel');
this.emitter.setYSpeed(-150, 150);
this.emitter.setXSpeed(-150, 150);
this.emitter.gravity = 0;
},
update: function() {
// init collision detection
// listen for collisions between player and walls
game.physics.arcade.collide(this.player, this.walls);
// listen for overlap between player and coin
game.physics.arcade.overlap(this.player, this.coin, this.takeCoin, null, this);
// listen for walls => enemy collision
game.physics.arcade.collide(this.enemies, this.walls);
// listen for player => enemy collision
game.physics.arcade.collide(this.player, this.enemies, this.playerDie, null, this);
if (this.nextEnemy < game.time.now) {
var start = 4000,
end = 1000,
score = 100;
// ! - formula to decrease the delay between spawned enemies over time
var delay = Math.max(start - (start - end) * game.global.score / score, end);
this.addEnemy();
this.nextEnemy = game.time.now + delay;
}
//init movePlayer
this.movePlayer();
// listen if player is dead
if (!this.player.inWorld) {
this.playerDie();
}
},
////// CUSTOM FUNCTIONS
// player moving
movePlayer: function() {
if (this.cursor.left.isDown) {
this.player.body.velocity.x = -200;
this.player.animations.play('left');
} else if (this.cursor.right.isDown) {
this.player.body.velocity.x = 200;
this.player.animations.play('right');
} else {
this.player.body.velocity.x = 0;
this.player.animations.stop();
this.player.frame = 0;
}
if (this.cursor.up.isDown && this.player.body.touching.down) {
this.player.body.velocity.y = -320;
this.jumpSound.play();
}
},
// create walls
createWorld: function() {
this.walls = game.add.group();
this.walls.enableBody = true;
game.add.sprite(0, 0, 'wallV', 0, this.walls);
game.add.sprite(480, 0, 'wallV', 0, this.walls);
game.add.sprite(0, 0, 'wallH', 0, this.walls);
game.add.sprite(300, 0, 'wallH', 0, this.walls);
game.add.sprite(0, 320, 'wallH', 0, this.walls);
game.add.sprite(300, 320, 'wallH', 0, this.walls);
game.add.sprite(-100, 160, 'wallH', 0, this.walls);
game.add.sprite(300, 160, 'wallH', 0, this.walls);
var middleTop = game.add.sprite(100, 80, 'wallH', 0, this.walls);
middleTop.scale.setTo(1.5, 1);
var middleBottom = game.add.sprite(100, 240, 'wallH', 0, this.walls);
middleBottom.scale.setTo(1.5, 1);
// make walls static
this.walls.setAll('body.immovable', true);
},
// update the score on coin taken
takeCoin: function(player, coin) {
this.coin.scale.setTo(0, 0);
game.add.tween(this.coin.scale).to({
x: 1,
y: 1
}, 300).start();
game.add.tween(this.player.scale).to({
x: 1.3,
y: 1.3
}, 50).to({
x: 1,
y: 1
}, 150).start();
this.coinSound.play();
game.global.score += 5;
this.scoreLabel.text = 'score: ' + game.global.score;
this.updateCoinPosition();
},
// on taken coin re-use it and change position
updateCoinPosition: function() {
var coinPosition = [{
x: 140,
y: 60
}, {
x: 360,
y: 60
}, {
x: 60,
y: 140
}, {
x: 440,
y: 140
}, {
x: 440,
y: 60
}, {
x: 60,
y: 60
}, {
x: 130,
y: 300
}, {
x: 370,
y: 300
}];
for (var i = coinPosition.length - 1; i >= 0; i--) {
if (coinPosition[i].x === this.coin.x) {
coinPosition.splice(i, 1);
};
};
var newPosition = coinPosition[game.rnd.integerInRange(0, coinPosition.length - 1)];
this.coin.reset(newPosition.x, newPosition.y);
},
// add enemies
addEnemy: function() {
var enemy = this.enemies.getFirstDead();
if (!enemy) {
return;
}
enemy.anchor.setTo(0.5, 1);
enemy.reset(game.world.centerX, 0);
enemy.body.gravity.y = 700;
enemy.body.velocity.x = 200 * Phaser.Math.randomSign();
enemy.body.bounce.x = 1;
enemy.checkWorldBounds = true;
enemy.outOfBoundsKill = true;
},
// restart when player dies
playerDie: function() {
if (!this.player.alive) {
return;
}
this.player.kill();
this.deadSound.play();
this.emitter.x = this.player.x;
this.emitter.y = this.player.y;
this.emitter.start(true, 600, null, 15);
game.time.events.add(1000, this.startMenu, this);
this.music.stop();
},
startMenu: function() {
game.state.start('menu');
}
};
| arekom/supercoinbox | states/play.js | JavaScript | apache-2.0 | 6,937 |
// @ts-nocheck
'use strict';
const _ = require('lodash');
const containsString = require('../../utils/containsString');
const matchesStringOrRegExp = require('../../utils/matchesStringOrRegExp');
const report = require('../../utils/report');
const ruleMessages = require('../../utils/ruleMessages');
const validateOptions = require('../../utils/validateOptions');
const ruleName = 'comment-word-blacklist';
const messages = ruleMessages(ruleName, {
rejected: (pattern) => `Unexpected word matching pattern "${pattern}"`,
});
function rule(list) {
return (root, result) => {
const validOptions = validateOptions(result, ruleName, {
actual: list,
possible: [_.isString, _.isRegExp],
});
if (!validOptions) {
return;
}
result.warn(`'${ruleName}' has been deprecated. Instead use 'comment-word-disallowed-list'.`, {
stylelintType: 'deprecation',
stylelintReference: `https://github.com/stylelint/stylelint/blob/13.7.0/lib/rules/${ruleName}/README.md`,
});
root.walkComments((comment) => {
const text = comment.text;
const rawComment = comment.toString();
const firstFourChars = rawComment.substr(0, 4);
// Return early if sourcemap
if (firstFourChars === '/*# ') {
return;
}
const matchesWord = matchesStringOrRegExp(text, list) || containsString(text, list);
if (!matchesWord) {
return;
}
report({
message: messages.rejected(matchesWord.pattern),
node: comment,
result,
ruleName,
});
});
};
}
rule.primaryOptionArray = true;
rule.ruleName = ruleName;
rule.messages = messages;
rule.meta = { deprecated: true };
module.exports = rule;
| kyleterry/sufr | pkg/ui/node_modules/stylelint/lib/rules/comment-word-blacklist/index.js | JavaScript | apache-2.0 | 1,637 |
var pagePromptText = {
Summary_QTileMaximum:"您最多可以输入100个字符。",//10001
Summary_QDescribeMaximum:"您最多可以输入200个字符。",//10002
Summary_QFacePpicture:"请上传问卷封面图片,这个图片将显示在您的问卷封面上。(上传图片不大于5M)",//10003
Summary_QCommitment:"众研承诺您的隐私信息只会以加密的形式记录在我们的数据库内,不会出现在任何除此之外的地方。",//10004
Publish_publishCount:"请设置问卷的发行总数,默认为100份。或者在下拉列表中选取配额,从配额设定中直接设定问卷发行总数。",//10005
Publish_publishDays: "请设置问卷的收集时限。默认为30天。勾选“无期限直至集满配额”选项将不为问卷设定时限,当集满问卷发行数后问卷自动下线。",//10006
Publish_publishTime:"请设置问卷的发布时间。",//10007
Publish_publishIntervieweeInfo: "收集微信用户的基本信息(昵称、性别、城市信息),回答前需要微信号授权登录。",//10008
Publish_publishWeiXinInfo: "微信号和名称可在“微信公众平台>公众号设置”里查询,AppID和AppSecret可在“微信公众平台>开发者中心”下查看,点击“验证并保存”按钮确认信息是否绑定正确",//10009
Publish_publishAppInfo:"AppID和AppSecret可在“微信公众平台>开发者中心”下查看",//10010
Publish_publishValidateSave:"点击“验证并保存”按钮确认信息是否绑定正确",//10011
Publish_publishOauthConfig: "复制左侧域名,登录微信公众平台,进入开发者中心>接口权限表>网页服务>网页账号>网页授权获取用户基本信息>修改,在授权回调页面域名中粘贴左侧域名地址,点击确认。",//10012
Publish_publishImmediatelyVerify :"设置完毕后,可以通过“立即验证”按钮验证操作是否成功。",//10013
Quota_PromptMessage:"请在下方单元格中输入需要收集的问卷数量,不输入代表问卷数量为0",//10014
UserInfo_UserPicForm: "图片格式:JPG | PNG | JPEG | BMP",//10015
UserInfo_UserPicSize: "文件尺寸:小于2M",//10015
UserInfo_UserName:"您最多可以输入20个字符。",//10016
UserInfo_Email:"您最多可以输入50个字符。",//10017
Password_CurrentPwd:"请输入当前密码。",//10018
Password_NewPwd:"请输入新密码(6-20个字符)。",//10019
Password_NewPwdAgain:"请再次输入新的密码(6-20个字符)。",//10020
LoginAndRegister_Register:"注册成功,正在转到登录页面…",//10021
} | emksaz/choicefrom | development/common/script/pagePromptText.js | JavaScript | apache-2.0 | 2,752 |
jQuery.webshims.register("dom-extend",function(c,g,u,i,n){var l=g.modules,h=/\s*,\s*/,p={},v={},q={},k={},x={},B=c.fn.val,y=function(b,a,d,f,e){return e?B.call(c(b)):B.call(c(b),d)};c.fn.val=function(b){var a=this[0];arguments.length&&null==b&&(b="");if(!arguments.length)return!a||1!==a.nodeType?B.call(this):c.prop(a,"value",b,"val",!0);if(c.isArray(b))return B.apply(this,arguments);var d=c.isFunction(b);return this.each(function(f){a=this;1===a.nodeType&&(d?(f=b.call(a,f,c.prop(a,"value",n,"val",
!0)),null==f&&(f=""),c.prop(a,"value",f,"val")):c.prop(a,"value",b,"val"))})};var o="_webshimsLib"+Math.round(1E3*Math.random()),t=function(b,a,d){b=b.jquery?b[0]:b;if(!b)return d||{};var f=c.data(b,o);d!==n&&(f||(f=c.data(b,o,{})),a&&(f[a]=d));return a?f&&f[a]:f};[{name:"getNativeElement",prop:"nativeElement"},{name:"getShadowElement",prop:"shadowElement"},{name:"getShadowFocusElement",prop:"shadowFocusElement"}].forEach(function(b){c.fn[b.name]=function(){return this.map(function(){var a=t(this,
"shadowData");return a&&a[b.prop]||this})}});["removeAttr","prop","attr"].forEach(function(b){p[b]=c[b];c[b]=function(a,d,f,e,m){var w="val"==e,C=!w?p[b]:y;if(!a||!v[d]||1!==a.nodeType||!w&&e&&"attr"==b&&c.attrFn[d])return C(a,d,f,e,m);var D=(a.nodeName||"").toLowerCase(),g=q[D],l="attr"==b&&(!1===f||null===f)?"removeAttr":b,h,k,j;g||(g=q["*"]);g&&(g=g[d]);g&&(h=g[l]);if(h){if("value"==d)k=h.isVal,h.isVal=w;if("removeAttr"===l)return h.value.call(a);if(f===n)return h.get?h.get.call(a):h.value;h.set&&
("attr"==b&&!0===f&&(f=d),j=h.set.call(a,f));if("value"==d)h.isVal=k}else j=C(a,d,f,e,m);if((f!==n||"removeAttr"===l)&&x[D]&&x[D][d]){var i;i="removeAttr"==l?!1:"prop"==l?!!f:!0;x[D][d].forEach(function(e){if(!e.only||(e.only="prop"==b)||"attr"==e.only&&"prop"!=b)e.call(a,f,i,w?"val":l,b)})}return j};k[b]=function(a,d,f){q[a]||(q[a]={});q[a][d]||(q[a][d]={});var e=q[a][d][b],m=function(e,a,c){return a&&a[e]?a[e]:c&&c[e]?c[e]:"prop"==b&&"value"==d?function(e){return f.isVal?y(this,d,e,!1,0===arguments.length):
p[b](this,d,e)}:"prop"==b&&"value"==e&&f.value.apply?function(e){var a=p[b](this,d);a&&a.apply&&(a=a.apply(this,arguments));return a}:function(e){return p[b](this,d,e)}};q[a][d][b]=f;if(f.value===n){if(!f.set)f.set=f.writeable?m("set",f,e):g.cfg.useStrict&&"prop"==d?function(){throw d+" is readonly on "+a;}:c.noop;if(!f.get)f.get=m("get",f,e)}["value","get","set"].forEach(function(a){f[a]&&(f["_sup"+a]=m(a,e))})}});var z=!c.browser.msie||8<parseInt(c.browser.version,10),j=function(){var b=g.getPrototypeOf(i.createElement("foobar")),
a=Object.prototype.hasOwnProperty;return function(c,f,e){var m=i.createElement(c),w=g.getPrototypeOf(m);if(z&&w&&b!==w&&(!m[f]||!a.call(m,f))){var l=m[f];e._supvalue=function(){return l&&l.apply?l.apply(this,arguments):l};w[f]=e.value}else e._supvalue=function(){var e=t(this,"propValue");return e&&e[f]&&e[f].apply?e[f].apply(this,arguments):e&&e[f]},r.extendValue(c,f,e.value);e.value._supvalue=e._supvalue}}(),r=function(){var b={};g.addReady(function(e,a){var d={},f=function(b){d[b]||(d[b]=c(e.getElementsByTagName(b)),
a[0]&&c.nodeName(a[0],b)&&(d[b]=d[b].add(a)))};c.each(b,function(e,a){f(e);!a||!a.forEach?g.warn("Error: with "+e+"-property. methods: "+a):a.forEach(function(a){d[e].each(a)})});d=null});var a,d=c([]),f=function(e,d){b[e]?b[e].push(d):b[e]=[d];c.isDOMReady&&(a||c(i.getElementsByTagName(e))).each(d)};return{createTmpCache:function(e){c.isDOMReady&&(a=a||c(i.getElementsByTagName(e)));return a||d},flushTmpCache:function(){a=null},content:function(e,a){f(e,function(){var e=c.attr(this,a);null!=e&&c.attr(this,
a,e)})},createElement:function(e,a){f(e,a)},extendValue:function(e,a,b){f(e,function(){c(this).each(function(){t(this,"propValue",{})[a]=this[a];this[a]=b})})}}}(),A=function(b,a){if(b.defaultValue===n)b.defaultValue="";if(!b.removeAttr)b.removeAttr={value:function(){b[a||"prop"].set.call(this,b.defaultValue);b.removeAttr._supvalue.call(this)}};if(!b.attr)b.attr={}};c.extend(g,{getID:function(){var b=(new Date).getTime();return function(a){var a=c(a),d=a.attr("id");d||(b++,d="ID-"+b,a.attr("id",d));
return d}}(),extendUNDEFProp:function(b,a){c.each(a,function(a,c){a in b||(b[a]=c)})},createPropDefault:A,data:t,moveToFirstEvent:function(){var b=c._data?"_data":"data";return function(a,d,f){if((a=(c[b](a,"events")||{})[d])&&1<a.length)d=a.pop(),f||(f="bind"),"bind"==f&&a.delegateCount?a.splice(a.delegateCount,0,d):a.unshift(d)}}(),addShadowDom:function(b,a,d){d=d||{};b.jquery&&(b=b[0]);a.jquery&&(a=a[0]);var f=c.data(b,o)||c.data(b,o,{}),e=c.data(a,o)||c.data(a,o,{}),m={};if(d.shadowFocusElement){if(d.shadowFocusElement){if(d.shadowFocusElement.jquery)d.shadowFocusElement=
d.shadowFocusElement[0];m=c.data(d.shadowFocusElement,o)||c.data(d.shadowFocusElement,o,m)}}else d.shadowFocusElement=a;f.hasShadow=a;m.nativeElement=e.nativeElement=b;m.shadowData=e.shadowData=f.shadowData={nativeElement:b,shadowElement:a,shadowFocusElement:d.shadowFocusElement};d.shadowChilds&&d.shadowChilds.each(function(){t(this,"shadowData",e.shadowData)});if(d.data)m.shadowData.data=e.shadowData.data=f.shadowData.data=d.data;d=null},propTypes:{standard:function(b){A(b);if(!b.prop)b.prop={set:function(a){b.attr.set.call(this,
""+a)},get:function(){return b.attr.get.call(this)||b.defaultValue}}},"boolean":function(b){A(b);if(!b.prop)b.prop={set:function(a){a?b.attr.set.call(this,""):b.removeAttr.value.call(this)},get:function(){return null!=b.attr.get.call(this)}}},src:function(){var b=i.createElement("a");b.style.display="none";return function(a,d){A(a);if(!a.prop)a.prop={set:function(b){a.attr.set.call(this,b)},get:function(){var a=this.getAttribute(d),e;if(null==a)return"";b.setAttribute("href",a+"");if(!c.support.hrefNormalized){try{c(b).insertAfterTo(this),
e=b.getAttribute("href",4)}catch(m){e=b.getAttribute("href",4)}c(b).detach()}return e||b.href}}}}(),enumarated:function(b){A(b);if(!b.prop)b.prop={set:function(a){b.attr.set.call(this,a)},get:function(){var a=(b.attr.get.call(this)||"").toLowerCase();if(!a||-1==b.limitedTo.indexOf(a))a=b.defaultValue;return a}}}},reflectProperties:function(b,a){"string"==typeof a&&(a=a.split(h));a.forEach(function(a){g.defineNodeNamesProperty(b,a,{prop:{set:function(b){c.attr(this,a,b)},get:function(){return c.attr(this,
a)||""}}})})},defineNodeNameProperty:function(b,a,d){v[a]=!0;if(d.reflect)g.propTypes[d.propType||"standard"](d,a);["prop","attr","removeAttr"].forEach(function(f){var e=d[f];e&&(e="prop"===f?c.extend({writeable:!0},e):c.extend({},e,{writeable:!0}),k[f](b,a,e),"*"!=b&&g.cfg.extendNative&&"prop"==f&&e.value&&c.isFunction(e.value)&&j(b,a,e),d[f]=e)});d.initAttr&&r.content(b,a);return d},defineNodeNameProperties:function(b,a,c,f){for(var e in a)!f&&a[e].initAttr&&r.createTmpCache(b),c&&(a[e][c]?g.log("override: "+
b+"["+e+"] for "+c):(a[e][c]={},["value","set","get"].forEach(function(b){b in a[e]&&(a[e][c][b]=a[e][b],delete a[e][b])}))),a[e]=g.defineNodeNameProperty(b,e,a[e]);f||r.flushTmpCache();return a},createElement:function(b,a,d){var f;c.isFunction(a)&&(a={after:a});r.createTmpCache(b);a.before&&r.createElement(b,a.before);d&&(f=g.defineNodeNameProperties(b,d,!1,!0));a.after&&r.createElement(b,a.after);r.flushTmpCache();return f},onNodeNamesPropertyModify:function(b,a,d,f){"string"==typeof b&&(b=b.split(h));
c.isFunction(d)&&(d={set:d});b.forEach(function(e){x[e]||(x[e]={});"string"==typeof a&&(a=a.split(h));d.initAttr&&r.createTmpCache(e);a.forEach(function(a){x[e][a]||(x[e][a]=[],v[a]=!0);if(d.set){if(f)d.set.only=f;x[e][a].push(d.set)}d.initAttr&&r.content(e,a)});r.flushTmpCache()})},defineNodeNamesBooleanProperty:function(b,a,d){d||(d={});if(c.isFunction(d))d.set=d;g.defineNodeNamesProperty(b,a,{attr:{set:function(b){this.setAttribute(a,b);d.set&&d.set.call(this,!0)},get:function(){return null==this.getAttribute(a)?
n:a}},removeAttr:{value:function(){this.removeAttribute(a);d.set&&d.set.call(this,!1)}},reflect:!0,propType:"boolean",initAttr:d.initAttr||!1})},contentAttr:function(b,a,c){if(b.nodeName){if(c===n)return c=(b.attributes[a]||{}).value,null==c?n:c;"boolean"==typeof c?c?b.setAttribute(a,a):b.removeAttribute(a):b.setAttribute(a,c)}},activeLang:function(){var b=[],a={},d,f,e=/:\/\/|^\.*\//,m=function(a,b,d){return b&&d&&-1!==c.inArray(b,d.availabeLangs||[])?(a.loading=!0,d=d.langSrc,e.test(d)||(d=g.cfg.basePath+
d),g.loader.loadScript(d+b+".js",function(){a.langObj[b]?(a.loading=!1,h(a,!0)):c(function(){a.langObj[b]&&h(a,!0);a.loading=!1})}),!0):!1},w=function(e){a[e]&&a[e].forEach(function(a){a.callback()})},h=function(a,e){if(a.activeLang!=d&&a.activeLang!==f){var b=l[a.module].options;if(a.langObj[d]||f&&a.langObj[f])a.activeLang=d,a.callback(a.langObj[d]||a.langObj[f],d),w(a.module);else if(!e&&!m(a,d,b)&&!m(a,f,b)&&a.langObj[""]&&""!==a.activeLang)a.activeLang="",a.callback(a.langObj[""],d),w(a.module)}};
return function(e){if("string"==typeof e&&e!==d)d=e,f=d.split("-")[0],d==f&&(f=!1),c.each(b,function(a,e){h(e)});else if("object"==typeof e)if(e.register)a[e.register]||(a[e.register]=[]),a[e.register].push(e),e.callback();else{if(!e.activeLang)e.activeLang="";b.push(e);h(e)}return d}}()});c.each({defineNodeNamesProperty:"defineNodeNameProperty",defineNodeNamesProperties:"defineNodeNameProperties",createElements:"createElement"},function(b,a){g[b]=function(b,c,e,m){"string"==typeof b&&(b=b.split(h));
var l={};b.forEach(function(b){l[b]=g[a](b,c,e,m)});return l}});g.isReady("webshimLocalization",!0)});
(function(c,g){var u=c.webshims.browserVersion;if(!(c.browser.mozilla&&5<u)&&(!c.browser.msie||12>u&&7<u)){var i={article:"article",aside:"complementary",section:"region",nav:"navigation",address:"contentinfo"},n=function(c,g){c.getAttribute("role")||c.setAttribute("role",g)};c.webshims.addReady(function(l,h){c.each(i,function(g,i){for(var p=c(g,l).add(h.filter(g)),q=0,o=p.length;q<o;q++)n(p[q],i)});if(l===g){var p=g.getElementsByTagName("header")[0],v=g.getElementsByTagName("footer"),q=v.length;
p&&!c(p).closest("section, article")[0]&&n(p,"banner");q&&(p=v[q-1],c(p).closest("section, article")[0]||n(p,"contentinfo"))}})}})(jQuery,document);
(function(c,g,u){var i=g.audio&&g.video,n=!1;if(i)c=document.createElement("video"),g.videoBuffered="buffered"in c,n="loop"in c,u.capturingEvents("play,playing,waiting,paused,ended,durationchange,loadedmetadata,canplay,volumechange".split(",")),g.videoBuffered||(u.addPolyfill("mediaelement-native-fix",{f:"mediaelement",test:g.videoBuffered,d:["dom-support"]}),u.reTest("mediaelement-native-fix"));jQuery.webshims.register("mediaelement-core",function(c,h,p,v,q){var k=h.mediaelement,x=h.cfg.mediaelement,
u=function(a,b){var a=c(a),d={src:a.attr("src")||"",elem:a,srcProp:a.prop("src")};if(!d.src)return d;var f=a.attr("type");if(f)d.type=f,d.container=c.trim(f.split(";")[0]);else if(b||(b=a[0].nodeName.toLowerCase(),"source"==b&&(b=(a.closest("video, audio")[0]||{nodeName:"video"}).nodeName.toLowerCase())),f=k.getTypeForSrc(d.src,b))d.type=f,d.container=f;if(f=a.attr("media"))d.media=f;return d},y=swfobject.hasFlashPlayerVersion("9.0.115"),o=!y&&"postMessage"in p&&i,t=function(){h.ready("mediaelement-swf",
function(){if(!k.createSWF)h.modules["mediaelement-swf"].test=c.noop,h.reTest(["mediaelement-swf"],i)})},z=function(){var a;return function(){!a&&o&&(a=!0,h.loader.loadScript("https://www.youtube.com/player_api"),c(function(){h.polyfill("mediaelement-yt")}))}}(),j=function(){y?t():z();c(function(){h.loader.loadList(["track-ui"])})};h.addPolyfill("mediaelement-yt",{test:!o,d:["dom-support"]});k.mimeTypes={audio:{"audio/ogg":["ogg","oga","ogm"],'audio/ogg;codecs="opus"':"opus","audio/mpeg":["mp2","mp3",
"mpga","mpega"],"audio/mp4":"mp4,mpg4,m4r,m4a,m4p,m4b,aac".split(","),"audio/wav":["wav"],"audio/3gpp":["3gp","3gpp"],"audio/webm":["webm"],"audio/fla":["flv","f4a","fla"],"application/x-mpegURL":["m3u8","m3u"]},video:{"video/ogg":["ogg","ogv","ogm"],"video/mpeg":["mpg","mpeg","mpe"],"video/mp4":["mp4","mpg4","m4v"],"video/quicktime":["mov","qt"],"video/x-msvideo":["avi"],"video/x-ms-asf":["asf","asx"],"video/flv":["flv","f4v"],"video/3gpp":["3gp","3gpp"],"video/webm":["webm"],"application/x-mpegURL":["m3u8",
"m3u"],"video/MP2T":["ts"]}};k.mimeTypes.source=c.extend({},k.mimeTypes.audio,k.mimeTypes.video);k.getTypeForSrc=function(a,b){if(-1!=a.indexOf("youtube.com/watch?")||-1!=a.indexOf("youtube.com/v/"))return"video/youtube";var a=a.split("?")[0].split("."),a=a[a.length-1],d;c.each(k.mimeTypes[b],function(c,b){if(-1!==b.indexOf(a))return d=c,!1});return d};k.srces=function(a,b){a=c(a);if(b)a.removeAttr("src").removeAttr("type").find("source").remove(),c.isArray(b)||(b=[b]),b.forEach(function(c){var b=
v.createElement("source");"string"==typeof c&&(c={src:c});b.setAttribute("src",c.src);c.type&&b.setAttribute("type",c.type);c.media&&b.setAttribute("media",c.media);a.append(b)});else{var b=[],d=a[0].nodeName.toLowerCase(),f=u(a,d);f.src?b.push(f):c("source",a).each(function(){f=u(this,d);f.src&&b.push(f)});return b}};c.fn.loadMediaSrc=function(a,b){return this.each(function(){b!==q&&(c(this).removeAttr("poster"),b&&c.attr(this,"poster",b));k.srces(this,a);c(this).mediaLoad()})};k.swfMimeTypes="video/3gpp,video/x-msvideo,video/quicktime,video/x-m4v,video/mp4,video/m4p,video/x-flv,video/flv,audio/mpeg,audio/aac,audio/mp4,audio/x-m4a,audio/m4a,audio/mp3,audio/x-fla,audio/fla,youtube/flv,jwplayer/jwplayer,video/youtube".split(",");
k.canThirdPlaySrces=function(a,b){var d="";if(y||o)a=c(a),b=b||k.srces(a),c.each(b,function(a,c){if(c.container&&c.src&&(y&&-1!=k.swfMimeTypes.indexOf(c.container)||o&&"video/youtube"==c.container))return d=c,!1});return d};var r={};k.canNativePlaySrces=function(a,b){var d="";if(i){var a=c(a),f=(a[0].nodeName||"").toLowerCase();if(!r[f])return d;b=b||k.srces(a);c.each(b,function(c,b){if(b.type&&r[f].prop._supvalue.call(a[0],b.type))return d=b,!1})}return d};if(i&&y&&!x.preferFlash){var A=function(a){var b=
a.target.parentNode;!x.preferFlash&&(c(a.target).is("audio, video")||b&&c("source:last",b)[0]==a.target)&&h.ready("mediaelement-swf",function(){setTimeout(function(){if(!c(a.target).closest("audio, video").is(".nonnative-api-active"))x.preferFlash=!0,v.removeEventListener("error",A,!0),c("audio, video").mediaLoad()},20)})};v.addEventListener("error",A,!0);c.webshims.ready("DOM",function(){c("audio, video").each(function(){this.error&&A({target:this})})})}k.setError=function(a,b){b||(b="can't play sources");
c(a).pause().data("mediaerror",b);h.warn("mediaelementError: "+b);setTimeout(function(){c(a).data("mediaerror")&&c(a).trigger("mediaerror")},1)};var b=function(){var a;return function(c,d,f){h.ready(y?"mediaelement-swf":"mediaelement-yt",function(){k.createSWF?k.createSWF(c,d,f):a||(a=!0,j(),b(c,d,f))});!a&&o&&!k.createSWF&&z()}}(),a=function(c,d,f,g,h){f||!1!==f&&d&&"third"==d.isActive?(f=k.canThirdPlaySrces(c,g))?b(c,f,d):h?k.setError(c,!1):a(c,d,!1,g,!0):(f=k.canNativePlaySrces(c,g))?d&&"third"==
d.isActive&&k.setActive(c,"html5",d):h?(k.setError(c,!1),d&&"third"==d.isActive&&k.setActive(c,"html5",d)):a(c,d,!0,g,!0)},d=/^(?:embed|object|datalist)$/i,f=function(b,f){var g=h.data(b,"mediaelementBase")||h.data(b,"mediaelementBase",{}),j=k.srces(b),i=b.parentNode;clearTimeout(g.loadTimer);c.data(b,"mediaerror",!1);if(j.length&&i&&!(1!=i.nodeType||d.test(i.nodeName||"")))f=f||h.data(b,"mediaelement"),a(b,f,x.preferFlash||q,j)};c(v).bind("ended",function(a){var b=h.data(a.target,"mediaelement");
(!n||b&&"html5"!=b.isActive||c.prop(a.target,"loop"))&&setTimeout(function(){!c.prop(a.target,"paused")&&c.prop(a.target,"loop")&&c(a.target).prop("currentTime",0).play()},1)});n||h.defineNodeNamesBooleanProperty(["audio","video"],"loop");["audio","video"].forEach(function(a){var b=h.defineNodeNameProperty(a,"load",{prop:{value:function(){var a=h.data(this,"mediaelement");f(this,a);i&&(!a||"html5"==a.isActive)&&b.prop._supvalue&&b.prop._supvalue.apply(this,arguments)}}});r[a]=h.defineNodeNameProperty(a,
"canPlayType",{prop:{value:function(b){var d="";i&&r[a].prop._supvalue&&(d=r[a].prop._supvalue.call(this,b),"no"==d&&(d=""));!d&&y&&(b=c.trim((b||"").split(";")[0]),-1!=k.swfMimeTypes.indexOf(b)&&(d="maybe"));return d}}})});h.onNodeNamesPropertyModify(["audio","video"],["src","poster"],{set:function(){var a=this,b=h.data(a,"mediaelementBase")||h.data(a,"mediaelementBase",{});clearTimeout(b.loadTimer);b.loadTimer=setTimeout(function(){f(a);a=null},9)}});p=function(){h.addReady(function(a,b){c("video, audio",
a).add(b.filter("video, audio")).each(function(){c.browser.msie&&8<h.browserVersion&&c.prop(this,"paused")&&!c.prop(this,"readyState")&&c(this).is('audio[preload="none"][controls]:not([autoplay])')?c(this).prop("preload","metadata").mediaLoad():f(this);if(i){var a,b,d=this,e=function(){var a=c.prop(d,"buffered");if(a){for(var b="",e=0,f=a.length;e<f;e++)b+=a.end(e);return b}},g=function(){var a=e();a!=b&&(b=a,c(d).triggerHandler("progress"))};c(this).bind("play loadstart progress",function(c){"progress"==
c.type&&(b=e());clearTimeout(a);a=setTimeout(g,999)}).bind("emptied stalled mediaerror abort suspend",function(c){"emptied"==c.type&&(b=!1);clearTimeout(a)})}})})};g.track?h.defineProperty(TextTrack.prototype,"shimActiveCues",{get:function(){return this._shimActiveCues||this.activeCues}}):c(function(){h.loader.loadList(["track-ui"])});i?(h.isReady("mediaelement-core",!0),p(),h.ready("WINDOWLOAD mediaelement",j)):h.ready("mediaelement-swf",p)})})(jQuery,Modernizr,jQuery.webshims);
jQuery.webshims.register("mediaelement-swf",function(c,g,u,i,n,l){var h=g.mediaelement,p=u.swfobject,v=Modernizr.audio&&Modernizr.video,q=p.hasFlashPlayerVersion("9.0.115"),k=0,u={paused:!0,ended:!1,currentSrc:"",duration:u.NaN,readyState:0,networkState:0,videoHeight:0,videoWidth:0,error:null,buffered:{start:function(a){if(a)g.error("buffered index size error");else return 0},end:function(a){if(a)g.error("buffered index size error");else return 0},length:0}},x=Object.keys(u),B={currentTime:0,volume:1,
muted:!1};Object.keys(B);var y=c.extend({isActive:"html5",activating:"html5",wasSwfReady:!1,_bufferedEnd:0,_bufferedStart:0,_metadata:!1,_durationCalcs:-1,_callMeta:!1,currentTime:0,_ppFlag:n},u,B),o=/^jwplayer-/,t=function(a){if(a=i.getElementById(a.replace(o,"")))return a=g.data(a,"mediaelement"),"third"==a.isActive?a:null},z=function(a){return(a=g.data(a,"mediaelement"))&&"third"==a.isActive?a:null},j=function(a,b){b=c.Event(b);b.preventDefault();c.event.trigger(b,n,a)},r=l.playerPath||g.cfg.basePath+
"jwplayer/"+(l.playerName||"player.swf"),A=l.pluginPath||g.cfg.basePath+"swf/jwwebshims.swf";g.extendUNDEFProp(l.jwParams,{allowscriptaccess:"always",allowfullscreen:"true",wmode:"transparent"});g.extendUNDEFProp(l.jwVars,{screencolor:"ffffffff"});g.extendUNDEFProp(l.jwAttrs,{bgcolor:"#000000"});var b=function(a,b){var d=a.duration;if(!(d&&0<a._durationCalcs)){try{if(a.duration=a.jwapi.getPlaylist()[0].duration,!a.duration||0>=a.duration||a.duration===a._lastDuration)a.duration=d}catch(e){}a.duration&&
a.duration!=a._lastDuration?(j(a._elem,"durationchange"),("audio"==a._elemNodeName||a._callMeta)&&h.jwEvents.Model.META(c.extend({duration:a.duration},b),a),a._durationCalcs--):a._durationCalcs++}},a=function(b,c){3>b&&clearTimeout(c._canplaythroughTimer);if(3<=b&&3>c.readyState)c.readyState=b,j(c._elem,"canplay"),clearTimeout(c._canplaythroughTimer),c._canplaythroughTimer=setTimeout(function(){a(4,c)},4E3);if(4<=b&&4>c.readyState)c.readyState=b,j(c._elem,"canplaythrough");c.readyState=b};h.jwEvents=
{View:{PLAY:function(a){var b=t(a.id);if(b&&!b.stopPlayPause&&(b._ppFlag=!0,b.paused==a.state)){b.paused=!a.state;if(b.ended)b.ended=!1;j(b._elem,a.state?"play":"pause")}}},Model:{BUFFER:function(d){var s=t(d.id);if(s&&"percentage"in d&&s._bufferedEnd!=d.percentage){s.networkState=100==d.percentage?1:2;(isNaN(s.duration)||5<d.percentage&&25>d.percentage||100===d.percentage)&&b(s,d);if(s.ended)s.ended=!1;if(s.duration){2<d.percentage&&20>d.percentage?a(3,s):20<d.percentage&&a(4,s);if(s._bufferedEnd&&
s._bufferedEnd>d.percentage)s._bufferedStart=s.currentTime||0;s._bufferedEnd=d.percentage;s.buffered.length=1;if(100==d.percentage)s.networkState=1,a(4,s);c.event.trigger("progress",n,s._elem,!0)}}},META:function(b,c){if(c=c&&c.networkState?c:t(b.id))if("duration"in b){if(!c._metadata||!((!b.height||c.videoHeight==b.height)&&b.duration===c.duration)){c._metadata=!0;var d=c.duration;if(b.duration)c.duration=b.duration;c._lastDuration=c.duration;if(b.height||b.width)c.videoHeight=b.height||0,c.videoWidth=
b.width||0;if(!c.networkState)c.networkState=2;1>c.readyState&&a(1,c);c.duration&&d!==c.duration&&j(c._elem,"durationchange");j(c._elem,"loadedmetadata")}}else c._callMeta=!0},TIME:function(c){var d=t(c.id);if(d&&d.currentTime!==c.position){d.currentTime=c.position;d.duration&&d.duration<d.currentTime&&b(d,c);2>d.readyState&&a(2,d);if(d.ended)d.ended=!1;j(d._elem,"timeupdate")}},STATE:function(c){var d=t(c.id);if(d)switch(c.newstate){case "BUFFERING":if(d.ended)d.ended=!1;a(1,d);j(d._elem,"waiting");
break;case "PLAYING":d.paused=!1;d._ppFlag=!0;d.duration||b(d,c);3>d.readyState&&a(3,d);if(d.ended)d.ended=!1;j(d._elem,"playing");break;case "PAUSED":if(!d.paused&&!d.stopPlayPause)d.paused=!0,d._ppFlag=!0,j(d._elem,"pause");break;case "COMPLETED":4>d.readyState&&a(4,d),d.ended=!0,j(d._elem,"ended")}}},Controller:{ERROR:function(a){var b=t(a.id);b&&h.setError(b._elem,a.message)},SEEK:function(a){var b=t(a.id);if(b){if(b.ended)b.ended=!1;if(b.paused)try{b.jwapi.sendEvent("play","false")}catch(c){}if(b.currentTime!=
a.position)b.currentTime=a.position,j(b._elem,"timeupdate")}},VOLUME:function(a){var b=t(a.id);if(b&&(a=a.percentage/100,b.volume!=a))b.volume=a,j(b._elem,"volumechange")},MUTE:function(a){if(!a.state){var b=t(a.id);if(b&&b.muted!=a.state)b.muted=a.state,j(b._elem,"volumechange")}}}};var d=function(a){var b=!0;c.each(h.jwEvents,function(d,e){c.each(e,function(c){try{a.jwapi["add"+d+"Listener"](c,"jQuery.webshims.mediaelement.jwEvents."+d+"."+c)}catch(e){return b=!1}})});return b},f=function(a){var b=
a.actionQueue.length,c=0,d;if(b&&"third"==a.isActive)for(;a.actionQueue.length&&b>c;)c++,d=a.actionQueue.shift(),a.jwapi[d.fn].apply(a.jwapi,d.args);if(a.actionQueue.length)a.actionQueue=[]},e=function(a){a&&(a._ppFlag===n&&c.prop(a._elem,"autoplay")||!a.paused)&&setTimeout(function(){if("third"==a.isActive&&(a._ppFlag===n||!a.paused))try{c(a._elem).play()}catch(b){}},1)},m=function(a){if(a&&"video"==a._elemNodeName){var b,d,e,f,g,h,k,l,i=function(i,j){if(j&&i&&!(1>j||1>i||"third"!=a.isActive))if(b&&
(b.remove(),b=!1),f=i,g=j,clearTimeout(k),d="auto"==a._elem.style.width,e="auto"==a._elem.style.height,d||e){h=h||c(a._elem).getShadowElement();var m;d&&!e?(m=h.height(),i*=m/j,j=m):!d&&e&&(m=h.width(),j*=m/i,i=m);l=!0;setTimeout(function(){l=!1},9);h.css({width:i,height:j})}},j=function(){if(!("third"!=a.isActive||c.prop(a._elem,"readyState")&&c.prop(this,"videoWidth"))){var f=c.prop(a._elem,"poster");if(f&&(d="auto"==a._elem.style.width,e="auto"==a._elem.style.height,d||e))b&&(b.remove(),b=!1),
b=c('<img style="position: absolute; height: auto; width: auto; top: 0px; left: 0px; visibility: hidden;" />'),b.bind("load error alreadycomplete",function(){clearTimeout(k);var a=this,d=a.naturalWidth||a.width||a.offsetWidth,e=a.naturalHeight||a.height||a.offsetHeight;e&&d?(i(d,e),a=null):setTimeout(function(){d=a.naturalWidth||a.width||a.offsetWidth;e=a.naturalHeight||a.height||a.offsetHeight;i(d,e);b&&(b.remove(),b=!1);a=null},9);c(this).unbind()}).prop("src",f).appendTo("body").each(function(){this.complete||
this.error?c(this).triggerHandler("alreadycomplete"):(clearTimeout(k),k=setTimeout(function(){c(a._elem).triggerHandler("error")},9999))})}};c(a._elem).bind("loadedmetadata",function(){i(c.prop(this,"videoWidth"),c.prop(this,"videoHeight"))}).bind("emptied",j).bind("swfstageresize updatemediaelementdimensions",function(){l||i(f,g)}).bind("emptied",function(){f=void 0;g=void 0}).triggerHandler("swfstageresize");j();c.prop(a._elem,"readyState")&&i(c.prop(a._elem,"videoWidth"),c.prop(a._elem,"videoHeight"))}};
h.playerResize=function(a){a&&(a=i.getElementById(a.replace(o,"")))&&c(a).triggerHandler("swfstageresize")};c(i).bind("emptied",function(a){a=z(a.target);e(a)});var w;h.jwPlayerReady=function(a){var b=t(a.id),h=0,i=function(){if(!(9<h))if(h++,d(b)){if(b.wasSwfReady)c(b._elem).mediaLoad();else{var k=parseFloat(a.version,10);(5.6>k||6<=k)&&g.warn("mediaelement-swf is only testet with jwplayer 5.6+")}b.wasSwfReady=!0;b.tryedReframeing=0;f(b);e(b)}else clearTimeout(b.reframeTimer),b.reframeTimer=setTimeout(i,
9*h),2<h&&9>b.tryedReframeing&&(b.tryedReframeing++,b.shadowElem.css({overflow:"visible"}),setTimeout(function(){b.shadowElem.css({overflow:"hidden"})},16))};if(b&&b.jwapi){if(!b.tryedReframeing)b.tryedReframeing=0;clearTimeout(w);b.jwData=a;b.shadowElem.removeClass("flashblocker-assumed");c.prop(b._elem,"volume",b.volume);c.prop(b._elem,"muted",b.muted);i()}};var C=c.noop;if(v){var D={play:1,playing:1},I="play,pause,playing,canplay,progress,waiting,ended,loadedmetadata,durationchange,emptied".split(","),
J=I.map(function(a){return a+".webshimspolyfill"}).join(" "),K=function(a){var b=g.data(a.target,"mediaelement");b&&(a.originalEvent&&a.originalEvent.type===a.type)==("third"==b.activating)&&(a.stopImmediatePropagation(),D[a.type]&&b.isActive!=b.activating&&c(a.target).pause())},C=function(a){c(a).unbind(J).bind(J,K);I.forEach(function(b){g.moveToFirstEvent(a,b)})};C(i)}h.setActive=function(a,b,d){d||(d=g.data(a,"mediaelement"));if(d&&d.isActive!=b){"html5"!=b&&"third"!=b&&g.warn("wrong type for mediaelement activating: "+
b);var e=g.data(a,"shadowData");d.activating=b;c(a).pause();d.isActive=b;"third"==b?(e.shadowElement=e.shadowFocusElement=d.shadowElem[0],c(a).addClass("swf-api-active nonnative-api-active").hide().getShadowElement().show()):(c(a).removeClass("swf-api-active nonnative-api-active").show().getShadowElement().hide(),e.shadowElement=e.shadowFocusElement=!1);c(a).trigger("mediaelementapichange")}};var L=function(){var b="_bufferedEnd,_bufferedStart,_metadata,_ppFlag,currentSrc,currentTime,duration,ended,networkState,paused,videoHeight,videoWidth,_callMeta,_durationCalcs".split(","),
c=b.length;return function(d){if(d){var e=c,f=d.networkState;for(a(0,d);--e;)delete d[b[e]];d.actionQueue=[];d.buffered.length=0;f&&j(d._elem,"emptied")}}}(),H=function(a,b){var d=a._elem,e=a.shadowElem;c(d)[b?"addClass":"removeClass"]("webshims-controls");"audio"==a._elemNodeName&&!b?e.css({width:0,height:0}):e.css({width:d.style.width||c(d).width(),height:d.style.height||c(d).height()})};h.createSWF=function(a,b,d){if(q){1>k?k=1:k++;var e=c.extend({},l.jwVars,{image:c.prop(a,"poster")||"",file:b.srcProp}),
f=c(a).data("jwvars")||{};d||(d=g.data(a,"mediaelement"));if(d&&d.swfCreated)h.setActive(a,"third",d),L(d),d.currentSrc=b.srcProp,c.extend(e,f),l.changeJW(e,a,b,d,"load"),E(a,"sendEvent",["LOAD",e]);else{var G=c.prop(a,"controls"),F="jwplayer-"+g.getID(a),i=c.extend({},l.jwParams,c(a).data("jwparams")),j=a.nodeName.toLowerCase(),n=c.extend({},l.jwAttrs,{name:F,id:F},c(a).data("jwattrs")),o=c('<div class="polyfill-'+j+' polyfill-mediaelement" id="wrapper-'+F+'"><div id="'+F+'"></div>').css({position:"relative",
overflow:"hidden"}),d=g.data(a,"mediaelement",g.objectCreate(y,{actionQueue:{value:[]},shadowElem:{value:o},_elemNodeName:{value:j},_elem:{value:a},currentSrc:{value:b.srcProp},swfCreated:{value:!0},buffered:{value:{start:function(a){if(a>=d.buffered.length)g.error("buffered index size error");else return 0},end:function(a){if(a>=d.buffered.length)g.error("buffered index size error");else return(d.duration-d._bufferedStart)*d._bufferedEnd/100+d._bufferedStart},length:0}}}));H(d,G);o.insertBefore(a);
v&&c.extend(d,{volume:c.prop(a,"volume"),muted:c.prop(a,"muted")});c.extend(e,{id:F,controlbar:G?l.jwVars.controlbar||("video"==j?"over":"bottom"):"video"==j?"none":"bottom",icons:""+(G&&"video"==j)},f,{playerready:"jQuery.webshims.mediaelement.jwPlayerReady"});e.plugins=e.plugins?e.plugins+(","+A):A;g.addShadowDom(a,o);C(a);h.setActive(a,"third",d);l.changeJW(e,a,b,d,"embed");c(a).bind("updatemediaelementdimensions",function(){H(d,c.prop(a,"controls"))});m(d);p.embedSWF(r,F,"100%","100%","9.0.0",
!1,e,i,n,function(b){if(b.success)d.jwapi=b.ref,G||c(b.ref).attr("tabindex","-1").css("outline","none"),setTimeout(function(){if(!b.ref.parentNode&&o[0].parentNode||"none"==b.ref.style.display)o.addClass("flashblocker-assumed"),c(a).trigger("flashblocker"),g.warn("flashblocker assumed");c(b.ref).css({minHeight:"2px",minWidth:"2px",display:"block"})},9),w||(clearTimeout(w),w=setTimeout(function(){var a=c(b.ref);1<a[0].offsetWidth&&1<a[0].offsetHeight&&0===location.protocol.indexOf("file:")?g.error("Add your local development-directory to the local-trusted security sandbox: http://www.macromedia.com/support/documentation/en/flashplayer/help/settings_manager04.html"):
(2>a[0].offsetWidth||2>a[0].offsetHeight)&&g.info("JS-SWF connection can't be established on hidden or unconnected flash objects")},8E3))})}}else setTimeout(function(){c(a).mediaLoad()},1)};var E=function(a,b,d,c){return(c=c||z(a))?(c.jwapi&&c.jwapi[b]?c.jwapi[b].apply(c.jwapi,d||[]):(c.actionQueue.push({fn:b,args:d}),10<c.actionQueue.length&&setTimeout(function(){5<c.actionQueue.length&&c.actionQueue.shift()},99)),c):!1};["audio","video"].forEach(function(a){var b={},d,e=function(c){"audio"==a&&
("videoHeight"==c||"videoWidth"==c)||(b[c]={get:function(){var a=z(this);return a?a[c]:v&&d[c].prop._supget?d[c].prop._supget.apply(this):y[c]},writeable:!1})},f=function(a,c){e(a);delete b[a].writeable;b[a].set=c};f("volume",function(a){var b=z(this);if(b){if(a*=100,!isNaN(a)){var c=b.muted;(0>a||100<a)&&g.error("volume greater or less than allowed "+a/100);E(this,"sendEvent",["VOLUME",a],b);if(c)try{b.jwapi.sendEvent("mute","true")}catch(e){}a/=100;if(!(b.volume==a||"third"!=b.isActive))b.volume=
a,j(b._elem,"volumechange")}}else if(d.volume.prop._supset)return d.volume.prop._supset.apply(this,arguments)});f("muted",function(a){var b=z(this);if(b){if(a=!!a,E(this,"sendEvent",["mute",""+a],b),!(b.muted==a||"third"!=b.isActive))b.muted=a,j(b._elem,"volumechange")}else if(d.muted.prop._supset)return d.muted.prop._supset.apply(this,arguments)});f("currentTime",function(a){var b=z(this);if(b){if(a*=1,!isNaN(a)){if(b.paused)clearTimeout(b.stopPlayPause),b.stopPlayPause=setTimeout(function(){b.paused=
!0;b.stopPlayPause=!1},50);E(this,"sendEvent",["SEEK",""+a],b);if(b.paused){if(0<b.readyState)b.currentTime=a,j(b._elem,"timeupdate");try{b.jwapi.sendEvent("play","false")}catch(c){}}}}else if(d.currentTime.prop._supset)return d.currentTime.prop._supset.apply(this,arguments)});["play","pause"].forEach(function(a){b[a]={value:function(){var b=z(this);if(b)b.stopPlayPause&&clearTimeout(b.stopPlayPause),E(this,"sendEvent",["play","play"==a],b),setTimeout(function(){if("third"==b.isActive&&(b._ppFlag=
!0,b.paused!=("play"!=a)))b.paused="play"!=a,j(b._elem,a)},1);else if(d[a].prop._supvalue)return d[a].prop._supvalue.apply(this,arguments)}}});x.forEach(e);g.onNodeNamesPropertyModify(a,"controls",function(b,d){var e=z(this);c(this)[d?"addClass":"removeClass"]("webshims-controls");if(e){try{E(this,d?"showControls":"hideControls",[a],e)}catch(f){g.warn("you need to generate a crossdomain.xml")}"audio"==a&&H(e,d);c(e.jwapi).attr("tabindex",d?"0":"-1")}});d=g.defineNodeNameProperties(a,b,"prop")});if(q){var M=
c.cleanData,N=c.browser.msie&&9>g.browserVersion,O={object:1,OBJECT:1};c.cleanData=function(a){var b,c,d;if(a&&(c=a.length)&&k)for(b=0;b<c;b++)if(O[a[b].nodeName]){if("sendEvent"in a[b]){k--;try{a[b].sendEvent("play",!1)}catch(e){}}if(N)try{for(d in a[b])"function"==typeof a[b][d]&&(a[b][d]=null)}catch(f){}}return M.apply(this,arguments)}}v||(["poster","src"].forEach(function(a){g.defineNodeNameProperty("src"==a?["audio","video","source"]:["video"],a,{reflect:!0,propType:"src"})}),["autoplay","controls"].forEach(function(a){g.defineNodeNamesBooleanProperty(["audio",
"video"],a)}),g.defineNodeNamesProperties(["audio","video"],{HAVE_CURRENT_DATA:{value:2},HAVE_ENOUGH_DATA:{value:4},HAVE_FUTURE_DATA:{value:3},HAVE_METADATA:{value:1},HAVE_NOTHING:{value:0},NETWORK_EMPTY:{value:0},NETWORK_IDLE:{value:1},NETWORK_LOADING:{value:2},NETWORK_NO_SOURCE:{value:3}},"prop"))});
| mdia/OneCalendar | public/javascripts/lib/js-webshim/minified/shims/combos/9.js | JavaScript | apache-2.0 | 32,320 |
/*
Copyright © 2011, Doron Rosenberg
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
Neither the name of the Google Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
enyo.kind({
name: "enyoextras.ScrollBarsScroller",
kind: enyo.Scroller,
published: {
scrollbarColor: "black",
scrollbarOpacity: 0.4,
alwaysShowScrollbars: false,
},
initComponents: function() {
if(this.scrollbarOpacity == 0) {
this.scrollbarOpacity = 0.1;
}
this.createChrome([{kind: "enyoextras.ScrollBarsScrollerBar", name: "scrollbars", scrollbarColor: this.scrollbarColor, scrollbarOpacity: this.scrollbarOpacity, alwaysShowScrollbars: this.alwaysShowScrollbars}]);
this.inherited(arguments);
},
scroll: function(inSender) {
this.inherited(arguments);
this.$.scrollbars.scrollUpdate(this);
},
scrollStart: function() {
this.inherited(arguments);
this.$.scrollbars.scrollStart(this);
},
scrollStop: function() {
this.inherited(arguments);
this.$.scrollbars.scrollStop(this);
}
});
enyo.kind({
name: "enyoextras.ScrollBarsScrollerBar",
kind: enyo.Control,
published: {
scrollbarColor: "black",
alwaysShowScrollbars: false,
scrollbarOpacity: 0.1
},
started: false,
duration: "1200ms",
components: [],
initComponents: function() {
var style = "width: 8px; border-radius: 5px; position: absolute; top: 0px; right: 2px; opacity: 0; z-index: 100; -webkit-transition-property: opacity; background-color:" + this.scrollbarColor;
this.createChrome([{name: "scrollBars", showing: false, style: style}]);
this.inherited(arguments);
// build the binding
this._transitionEndBinding = enyo.bind(this, this._transitionEnd);
},
scrollUpdate: function(inScroller) {
if (inScroller.vertical) {
var bs = inScroller.getBoundaries();
// lets calculate the height of the entire content
var scrollee = inScroller.scrollee.hasNode();
var cheight = scrollee.offsetHeight + scrollee.offsetTop;
// lets calculate the visible height
var height = inScroller.hasNode().offsetHeight;
// calculate the scrollbar height, first calculate the percentage of
// visible height compared to content height.
var hperc = Math.floor((height / (cheight))*100)/100;
var sheight = Math.max(Math.floor(height * hperc), 15);
// 10 is for bottom/top padding (5px each)
this.$.scrollBars.hasNode().style.height = sheight-10+"px";
// now calculate the scrollbar position
var perc = inScroller.scrollTop / (bs.bottom);
// take scrollbar height into consideration
var h = ((height-sheight) * perc);
// 5 is for top padding
this.$.scrollBars.hasNode().style.top = h+5+"px";
}
},
scrollStart: function(inScroller) {
// don't show first time as this is the initial render or there is no overflow
if ((this.started || this.alwaysShowScrollbars) && this._hasOverflow(inScroller)) {
this.$.scrollBars.hasNode().style.webkitTransitionDuration = "";
this.$.scrollBars.hasNode().style.webkitTransitionDelay = "";
this.$.scrollBars.setShowing(true);
this.$.scrollBars.hasNode().style.opacity = this.scrollbarOpacity;
} else {
this.started = true;
}
},
scrollStop: function(inScroller) {
if (!this.alwaysShowScrollbars) {
// listen for end event
this.$.scrollBars.hasNode().addEventListener("webkitTransitionEnd", this._transitionEndBinding, false);
this.$.scrollBars.hasNode().style.webkitTransitionDuration = this.duration;
this.$.scrollBars.hasNode().style.opacity = 0;
}
},
_transitionEnd: function(inEvent) {
this.$.scrollBars.hasNode().removeEventListener("webkitTransitionEnd", this._transitionEndBinding, false);
this.$.scrollBars.setShowing(false);
},
scrollBarColorChanged: function() {
if (this.$.scrollBars.hasNode()) {
this.$.scrollBars.hasNode().style.backgroundColor = this.scrollbarColor;
}
},
scrollBarOpacityChanged: function() {
if(this.scrollbarOpacity < 0.1) {
this.scrollbarOpacity = 0.1;
}
if (this.$.scrollBars.hasNode()) {
this.$.scrollBars.hasNode().style.opacity = this.scrollbarOpacity;
}
},
alwaysShowScrollbarsChanged: function() {
if (this.alwaysShowScrollbars) {
this.$.scrollBars.setShowing(true);
this.$.scrollBars.hasNode().style.opacity = this.scrollbarOpacity;
} else {
this.$.scrollBars.setShowing(false);
this.$.scrollBars.hasNode().style.opacity = this.scrollbarOpacity;
}
},
_hasOverflow: function(inScroller) {
var bs = inScroller.getBoundaries();
var scrollee = inScroller.scrollee.hasNode();
return (scrollee.offsetHeight > inScroller.hasNode().offsetHeight);
}
});
| nils-werner/Typewriter | application/source/kinds/ScrollBarsScroller.js | JavaScript | apache-2.0 | 6,121 |
var should = require('should');
var assert = require('assert');
var request = require('supertest');
var rewire = require('rewire');
var sinon = require('sinon');
describe('Endpoints: Jira Webhooks', function() {
var url = 'http://localhost:9000';
var server;
beforeEach(function() {
server = rewire('esn-notification-server');
server.setElectronSupport(false);
this.notifier = {
notify: sinon.spy()
}
server.__set__("notifier", this.notifier);
server.listen(9000);
});
afterEach(function() {
server.close();
});
it('should send a notification (webhook: jira:issue_created)', function(done) {
request(url)
.post('/notification/jira/webhook')
.send(bodyCreated)
.expect(200)
.end(function(err, res) {
if (err) {
throw err;
}
res.body.should.have.property('message');
res.should.have.property('status', 200);
done();
});
});
it('should send a notification (webhook: jira:issue_updated)', function(done) {
request(url)
.post('/notification/jira/webhook')
.send(bodyUpdated)
.expect(200)
.end(function(err, res) {
if (err) {
throw err;
}
res.body.should.have.property('message');
res.should.have.property('status', 200);
done();
});
});
it('should send a notification (webhook: jira:issue_deleted)', function(done) {
request(url)
.post('/notification/jira/webhook')
.send(bodyDeleted)
.expect(200)
.end(function(err, res) {
if (err) {
throw err;
}
res.body.should.have.property('message');
res.should.have.property('status', 200);
done();
});
});
it('should fail since invalid jira webhook is provided', function(done) {
request(url)
.post('/notification/jira/webhook')
.send(bodyInvalidWebhook)
.expect(400)
.end(function(err, res) {
if (err) {
throw err;
}
res.body.should.have.property('message');
res.should.have.property('status', 400);
done();
});
});
});
var bodyCreated = {
"id": 2,
"timestamp": "2009-09-09T00:08:36.796-0500",
"issue": {
"expand":"renderedFields,names,schema,transitions,operations,editmeta,changelog",
"id":"99291",
"self":"https://jira.atlassian.com/rest/api/2/issue/99291",
"key":"JRA-20002",
"fields":{
"summary":"I feel the need for speed",
"created":"2009-12-16T23:46:10.612-0600",
"description":"Make the issue nav load 10x faster",
"labels":["UI", "dialogue", "move"],
"priority": "Minor"
}
},
"user": {
"self":"https://jira.atlassian.com/rest/api/2/user?username=brollins",
"name":"brollins",
"emailAddress":"bryansemail at atlassian dot com",
"avatarUrls":{
"16x16":"https://jira.atlassian.com/secure/useravatar?size=small&avatarId=10605",
"48x48":"https://jira.atlassian.com/secure/useravatar?avatarId=10605"
},
"displayName":"Bryan Rollins [Atlassian]",
"active" : "true"
},
"changelog": {
"items": [
{
"toString": "A new summary.",
"to": null,
"fromString": "What is going on here?????",
"from": null,
"fieldtype": "jira",
"field": "summary"
},
{
"toString": "New Feature",
"to": "2",
"fromString": "Improvement",
"from": "4",
"fieldtype": "jira",
"field": "issuetype"
}
],
"id": 10124
},
"comment" : {
"self":"https://jira.atlassian.com/rest/api/2/issue/10148/comment/252789",
"id":"252789",
"author":{
"self":"https://jira.atlassian.com/rest/api/2/user?username=brollins",
"name":"brollins",
"emailAddress":"bryansemail@atlassian.com",
"avatarUrls":{
"16x16":"https://jira.atlassian.com/secure/useravatar?size=small&avatarId=10605",
"48x48":"https://jira.atlassian.com/secure/useravatar?avatarId=10605"
},
"displayName":"Bryan Rollins [Atlassian]",
"active":true
},
"body":"Just in time for AtlasCamp!",
"updateAuthor":{
"self":"https://jira.atlassian.com/rest/api/2/user?username=brollins",
"name":"brollins",
"emailAddress":"brollins@atlassian.com",
"avatarUrls":{
"16x16":"https://jira.atlassian.com/secure/useravatar?size=small&avatarId=10605",
"48x48":"https://jira.atlassian.com/secure/useravatar?avatarId=10605"
},
"displayName":"Bryan Rollins [Atlassian]",
"active":true
},
"created":"2011-06-07T10:31:26.805-0500",
"updated":"2011-06-07T10:31:26.805-0500"
},
"timestamp": "2011-06-07T10:31:26.805-0500",
"webhookEvent": "jira:issue_created"
};
var bodyUpdated = {
"id": 2,
"timestamp": "2009-09-09T00:08:36.796-0500",
"issue": {
"expand":"renderedFields,names,schema,transitions,operations,editmeta,changelog",
"id":"99291",
"self":"https://jira.atlassian.com/rest/api/2/issue/99291",
"key":"JRA-20002",
"fields":{
"summary":"I feel the need for speed",
"created":"2009-12-16T23:46:10.612-0600",
"description":"Make the issue nav load 10x faster",
"labels":["UI", "dialogue", "move"],
"priority": "Minor"
}
},
"user": {
"self":"https://jira.atlassian.com/rest/api/2/user?username=brollins",
"name":"brollins",
"emailAddress":"bryansemail at atlassian dot com",
"avatarUrls":{
"16x16":"https://jira.atlassian.com/secure/useravatar?size=small&avatarId=10605",
"48x48":"https://jira.atlassian.com/secure/useravatar?avatarId=10605"
},
"displayName":"Bryan Rollins [Atlassian]",
"active" : "true"
},
"changelog": {
"items": [
{
"toString": "A new summary.",
"to": null,
"fromString": "What is going on here?????",
"from": null,
"fieldtype": "jira",
"field": "summary"
},
{
"toString": "New Feature",
"to": "2",
"fromString": "Improvement",
"from": "4",
"fieldtype": "jira",
"field": "issuetype"
}
],
"id": 10124
},
"comment" : {
"self":"https://jira.atlassian.com/rest/api/2/issue/10148/comment/252789",
"id":"252789",
"author":{
"self":"https://jira.atlassian.com/rest/api/2/user?username=brollins",
"name":"brollins",
"emailAddress":"bryansemail@atlassian.com",
"avatarUrls":{
"16x16":"https://jira.atlassian.com/secure/useravatar?size=small&avatarId=10605",
"48x48":"https://jira.atlassian.com/secure/useravatar?avatarId=10605"
},
"displayName":"Bryan Rollins [Atlassian]",
"active":true
},
"body":"Just in time for AtlasCamp!",
"updateAuthor":{
"self":"https://jira.atlassian.com/rest/api/2/user?username=brollins",
"name":"brollins",
"emailAddress":"brollins@atlassian.com",
"avatarUrls":{
"16x16":"https://jira.atlassian.com/secure/useravatar?size=small&avatarId=10605",
"48x48":"https://jira.atlassian.com/secure/useravatar?avatarId=10605"
},
"displayName":"Bryan Rollins [Atlassian]",
"active":true
},
"created":"2011-06-07T10:31:26.805-0500",
"updated":"2011-06-07T10:31:26.805-0500"
},
"timestamp": "2011-06-07T10:31:26.805-0500",
"webhookEvent": "jira:issue_updated"
};
var bodyDeleted = {
"id": 2,
"timestamp": "2009-09-09T00:08:36.796-0500",
"issue": {
"expand":"renderedFields,names,schema,transitions,operations,editmeta,changelog",
"id":"99291",
"self":"https://jira.atlassian.com/rest/api/2/issue/99291",
"key":"JRA-20002",
"fields":{
"summary":"I feel the need for speed",
"created":"2009-12-16T23:46:10.612-0600",
"description":"Make the issue nav load 10x faster",
"labels":["UI", "dialogue", "move"],
"priority": "Minor"
}
},
"user": {
"self":"https://jira.atlassian.com/rest/api/2/user?username=brollins",
"name":"brollins",
"emailAddress":"bryansemail at atlassian dot com",
"avatarUrls":{
"16x16":"https://jira.atlassian.com/secure/useravatar?size=small&avatarId=10605",
"48x48":"https://jira.atlassian.com/secure/useravatar?avatarId=10605"
},
"displayName":"Bryan Rollins [Atlassian]",
"active" : "true"
},
"changelog": {
"items": [
{
"toString": "A new summary.",
"to": null,
"fromString": "What is going on here?????",
"from": null,
"fieldtype": "jira",
"field": "summary"
},
{
"toString": "New Feature",
"to": "2",
"fromString": "Improvement",
"from": "4",
"fieldtype": "jira",
"field": "issuetype"
}
],
"id": 10124
},
"comment" : {
"self":"https://jira.atlassian.com/rest/api/2/issue/10148/comment/252789",
"id":"252789",
"author":{
"self":"https://jira.atlassian.com/rest/api/2/user?username=brollins",
"name":"brollins",
"emailAddress":"bryansemail@atlassian.com",
"avatarUrls":{
"16x16":"https://jira.atlassian.com/secure/useravatar?size=small&avatarId=10605",
"48x48":"https://jira.atlassian.com/secure/useravatar?avatarId=10605"
},
"displayName":"Bryan Rollins [Atlassian]",
"active":true
},
"body":"Just in time for AtlasCamp!",
"updateAuthor":{
"self":"https://jira.atlassian.com/rest/api/2/user?username=brollins",
"name":"brollins",
"emailAddress":"brollins@atlassian.com",
"avatarUrls":{
"16x16":"https://jira.atlassian.com/secure/useravatar?size=small&avatarId=10605",
"48x48":"https://jira.atlassian.com/secure/useravatar?avatarId=10605"
},
"displayName":"Bryan Rollins [Atlassian]",
"active":true
},
"created":"2011-06-07T10:31:26.805-0500",
"updated":"2011-06-07T10:31:26.805-0500"
},
"timestamp": "2011-06-07T10:31:26.805-0500",
"webhookEvent": "jira:issue_deleted"
};
var bodyInvalidWebhook = {
"id": 2,
"timestamp": "2009-09-09T00:08:36.796-0500",
"issue": {
"expand":"renderedFields,names,schema,transitions,operations,editmeta,changelog",
"id":"99291",
"self":"https://jira.atlassian.com/rest/api/2/issue/99291",
"key":"JRA-20002",
"fields":{
"summary":"I feel the need for speed",
"created":"2009-12-16T23:46:10.612-0600",
"description":"Make the issue nav load 10x faster",
"labels":["UI", "dialogue", "move"],
"priority": "Minor"
}
},
"user": {
"self":"https://jira.atlassian.com/rest/api/2/user?username=brollins",
"name":"brollins",
"emailAddress":"bryansemail at atlassian dot com",
"avatarUrls":{
"16x16":"https://jira.atlassian.com/secure/useravatar?size=small&avatarId=10605",
"48x48":"https://jira.atlassian.com/secure/useravatar?avatarId=10605"
},
"displayName":"Bryan Rollins [Atlassian]",
"active" : "true"
},
"changelog": {
"items": [
{
"toString": "A new summary.",
"to": null,
"fromString": "What is going on here?????",
"from": null,
"fieldtype": "jira",
"field": "summary"
},
{
"toString": "New Feature",
"to": "2",
"fromString": "Improvement",
"from": "4",
"fieldtype": "jira",
"field": "issuetype"
}
],
"id": 10124
},
"comment" : {
"self":"https://jira.atlassian.com/rest/api/2/issue/10148/comment/252789",
"id":"252789",
"author":{
"self":"https://jira.atlassian.com/rest/api/2/user?username=brollins",
"name":"brollins",
"emailAddress":"bryansemail@atlassian.com",
"avatarUrls":{
"16x16":"https://jira.atlassian.com/secure/useravatar?size=small&avatarId=10605",
"48x48":"https://jira.atlassian.com/secure/useravatar?avatarId=10605"
},
"displayName":"Bryan Rollins [Atlassian]",
"active":true
},
"body":"Just in time for AtlasCamp!",
"updateAuthor":{
"self":"https://jira.atlassian.com/rest/api/2/user?username=brollins",
"name":"brollins",
"emailAddress":"brollins@atlassian.com",
"avatarUrls":{
"16x16":"https://jira.atlassian.com/secure/useravatar?size=small&avatarId=10605",
"48x48":"https://jira.atlassian.com/secure/useravatar?avatarId=10605"
},
"displayName":"Bryan Rollins [Atlassian]",
"active":true
},
"created":"2011-06-07T10:31:26.805-0500",
"updated":"2011-06-07T10:31:26.805-0500"
},
"timestamp": "2011-06-07T10:31:26.805-0500",
"webhookEvent": "jira:invalid_webhook_sandwiches"
};
| JonathanBlood/Electron-Desktop-Notifier | test/endpoints-jira-webhooks-test.js | JavaScript | apache-2.0 | 13,106 |
import DS from 'ember-data';
var Todo = DS.Model.extend({
title: DS.attr('string'),
isCompleted: DS.attr('boolean')
});
Todo.reopenClass({
FIXTURES: [
{
id: 1,
title: "Complete Ember.js Tutorial",
isCompleted: false
},
{
id: 2,
title: "Checkout some more ember stuff",
isCompleted: true
},
{
id: 3,
title: "Solve world hunger (with Ember)",
isCompleted: false
}
]
})
export default Todo;
| Allyooop/ember-todo | todo-mvc/app/models/todo.js | JavaScript | apache-2.0 | 563 |
/**
*
* Copyright 2014-present Basho Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
var rpb = require('../../../lib/protobuf/riakprotobuf');
var FetchValue = require('../../../lib/commands/kv/fetchvalue');
var RpbGetResp = rpb.getProtoFor('RpbGetResp');
var RpbContent = rpb.getProtoFor('RpbContent');
var RpbPair = rpb.getProtoFor('RpbPair');
var RpbLink = rpb.getProtoFor('RpbLink');
var RpbErrorResp = rpb.getProtoFor('RpbErrorResp');
var assert = require('assert');
var crypto = require('crypto');
function generateTestRpbContent(value, contentType) {
var rpbContent = new RpbContent();
rpbContent.setValue(new Buffer(value));
rpbContent.setContentType(new Buffer(contentType));
var pair = new RpbPair();
pair.setKey(new Buffer('email_bin'));
pair.setValue(new Buffer('roach@basho.com'));
rpbContent.indexes.push(pair);
pair = new RpbPair();
pair.setKey(new Buffer('metaKey1'));
pair.setValue(new Buffer('metaValue1'));
rpbContent.usermeta.push(pair);
var link = new RpbLink();
link.setBucket(new Buffer('b'));
link.setKey(new Buffer('k'));
link.setTag(new Buffer('t'));
rpbContent.links.push(link);
link = new RpbLink();
link.setBucket(new Buffer('b'));
link.setKey(new Buffer('k2'));
link.setTag(new Buffer('t2'));
rpbContent.links.push(link);
return rpbContent;
}
describe('FetchValue', function() {
describe('Build', function() {
it('should build a RpbGetReq correctly', function(done) {
var vclock = new Buffer(0);
var fetchCommand = new FetchValue.Builder()
.withBucketType('bucket_type')
.withBucket('bucket_name')
.withKey('key')
.withR(3)
.withPr(1)
.withNotFoundOk(true)
.withBasicQuorum(true)
.withReturnDeletedVClock(true)
.withHeadOnly(true)
.withIfModified(vclock)
.withTimeout(20000)
.withCallback(function(){})
.build();
var protobuf = fetchCommand.constructPbRequest();
assert.equal(protobuf.getType().toString('utf8'), 'bucket_type');
assert.equal(protobuf.getBucket().toString('utf8'), 'bucket_name');
assert.equal(protobuf.getKey().toString('utf8'), 'key');
assert.equal(protobuf.getR(), 3);
assert.equal(protobuf.getPr(), 1);
assert.equal(protobuf.getNotfoundOk(), true);
assert.equal(protobuf.getBasicQuorum(), true);
assert.equal(protobuf.getDeletedvclock(), true);
assert.equal(protobuf.getHead(), true);
assert(protobuf.getIfModified().toBuffer() !== null);
assert.equal(protobuf.getTimeout(), 20000);
done();
});
it('should build a RpbGetReq correctly with a binary key', function(done) {
var binaryKey = crypto.randomBytes(128);
var cmd = new FetchValue.Builder()
.withBucketType('bucket_type')
.withBucket('bucket_name')
.withKey(binaryKey)
.withCallback(function(){})
.build();
var protobuf = cmd.constructPbRequest();
var keyBuf = protobuf.getKey().toBuffer();
assert(binaryKey.equals(keyBuf));
done();
});
it('should take a RpbGetResp and call the users callback with the response', function(done) {
var rpbContent = generateTestRpbContent('this is a value', "application/json");
var rpbGetResp = new RpbGetResp();
rpbGetResp.setContent(rpbContent);
rpbGetResp.setVclock(new Buffer('1234'));
var callback = function(err, response) {
assert(!err, err);
assert(response, 'expected a response!');
assert.equal(response.values.length, 1);
var riakObject = response.values[0];
assert.equal(riakObject.getBucketType(), 'bucket_type');
assert.equal(riakObject.getBucket(), 'bucket_name');
assert.equal(riakObject.getKey(), 'key');
assert.equal(riakObject.getContentType(), 'application/json');
assert.equal(riakObject.hasIndexes(), true);
assert.equal(riakObject.getIndex('email_bin')[0], 'roach@basho.com');
assert.equal(riakObject.hasUserMeta(), true);
assert.equal(riakObject.getUserMeta()[0].key, 'metaKey1');
assert.equal(riakObject.getUserMeta()[0].value, 'metaValue1');
assert.equal(riakObject.getLinks()[0].bucket, 'b');
assert.equal(riakObject.getLinks()[0].key, 'k');
assert.equal(riakObject.getLinks()[0].tag, 't');
assert.equal(riakObject.getLinks()[1].bucket, 'b');
assert.equal(riakObject.getLinks()[1].key, 'k2');
assert.equal(riakObject.getLinks()[1].tag, 't2');
assert.equal(riakObject.getVClock().toString('utf8'), '1234');
done();
};
var fetchCommand = new FetchValue.Builder()
.withBucketType('bucket_type')
.withBucket('bucket_name')
.withKey('key')
.withCallback(callback)
.build();
fetchCommand.onSuccess(rpbGetResp);
});
it('should take a RpbGetResp and create a tombstone RiakObject correctly', function(done) {
var rpbGetResp = new RpbGetResp();
rpbGetResp.setUnchanged(true);
rpbGetResp.setVclock(new Buffer('1234'));
var callback = function(err, response) {
assert(!err, err);
assert(response, 'expected a response!');
assert.equal(response.values.length, 1);
var riakObject = response.values[0];
assert(riakObject.getIsTombstone());
assert.equal(riakObject.getBucketType(), 'bucket_type');
assert.equal(riakObject.getBucket(), 'bucket_name');
assert.equal(riakObject.getKey(), 'key');
done();
};
var fetchCommand = new FetchValue.Builder()
.withBucketType('bucket_type')
.withBucket('bucket_name')
.withKey('key')
.withCallback(callback)
.build();
fetchCommand.onSuccess(rpbGetResp);
});
describe('when convertToJs provided as true', function(){
it('should take a RpbGetResp and call the users callback with the error when unable to parse', function(done) {
var rpbContent = generateTestRpbContent('this is a value', "text/plain");
var rpbGetResp = new RpbGetResp();
rpbGetResp.setContent(rpbContent);
rpbGetResp.setVclock(new Buffer('1234'));
var callback = function(err, response) {
assert(err, 'expected an error!');
assert(!response, 'did NOT expect a response!');
done();
};
var fetchCommand = new FetchValue.Builder()
.withBucketType('bucket_type')
.withBucket('bucket_name')
.withKey('key')
.withConvertValueToJs(true)
.withCallback(callback)
.build();
fetchCommand.onSuccess(rpbGetResp);
});
it('should take a RpbGetResp and call the users callback with the parsed body if able to parse', function(done) {
var rpbContent = generateTestRpbContent('{"key":"value"}', "application/json");
var rpbGetResp = new RpbGetResp();
rpbGetResp.setContent(rpbContent);
rpbGetResp.setVclock(new Buffer('1234'));
var callback = function(err, response) {
assert(!err, err);
assert.equal(response.values.length, 1);
var riakObject = response.values[0];
var parsedValue = riakObject.getValue();
assert(typeof parsedValue === "object");
assert.equal(parsedValue.key, "value");
done();
};
var fetchCommand = new FetchValue.Builder()
.withBucketType('bucket_type')
.withBucket('bucket_name')
.withKey('key')
.withConvertValueToJs(true)
.withCallback(callback)
.build();
fetchCommand.onSuccess(rpbGetResp);
});
});
it ('should take a RpbErrorResp and call the users callback with the error message', function(done) {
var rpbErrorResp = new RpbErrorResp();
rpbErrorResp.setErrmsg(new Buffer('this is an error'));
var callback = function(err, response) {
if (err) {
assert.equal(err,'this is an error');
done();
}
};
var fetchCommand = new FetchValue.Builder()
.withBucketType('bucket_type')
.withBucket('bucket_name')
.withKey('key')
.withCallback(callback)
.build();
fetchCommand.onRiakError(rpbErrorResp);
});
});
});
| basho/riak-nodejs-client | test/unit/kv/fetchvalue.js | JavaScript | apache-2.0 | 10,139 |
for(var i = 0; i < 5; i++) { var scriptId = 'u' + i; window[scriptId] = document.getElementById(scriptId); }
$axure.eventManager.pageLoad(
function (e) {
});
gv_vAlignTable['u4'] = 'center';gv_vAlignTable['u1'] = 'center'; | bpigg/WFMMobile | www/iPhone_Frame_for_Desktop_View_files/axurerp_pagespecificscript.js | JavaScript | apache-2.0 | 227 |
(function(){
/*
* jQuery 1.1.4 - New Wave Javascript
*
* Copyright (c) 2007 John Resig (jquery.com)
* Dual licensed under the MIT (MIT-LICENSE.txt)
* and GPL (GPL-LICENSE.txt) licenses.
*
* $Date: 2007-08-23 21:49:27 -0400 (Thu, 23 Aug 2007) $
* $Rev: 2862 $
*/
// Map over jQuery in case of overwrite
if ( typeof jQuery != "undefined" )
var _jQuery = jQuery;
var jQuery = window.jQuery = function(a,c) {
// If the context is global, return a new object
if ( window == this || !this.init )
return new jQuery(a,c);
return this.init(a,c);
};
// Map over the $ in case of overwrite
if ( typeof $ != "undefined" )
var _$ = $;
// Map the jQuery namespace to the '$' one
window.$ = jQuery;
var quickExpr = /^[^<]*(<(.|\s)+>)[^>]*$|^#(\w+)$/;
jQuery.fn = jQuery.prototype = {
init: function(a,c) {
// Make sure that a selection was provided
a = a || document;
// Handle HTML strings
if ( typeof a == "string" ) {
var m = quickExpr.exec(a);
if ( m && (m[1] || !c) ) {
// HANDLE: $(html) -> $(array)
if ( m[1] )
a = jQuery.clean( [ m[1] ] );
// HANDLE: $("#id")
else {
var tmp = document.getElementById( m[3] );
if ( tmp )
// Handle the case where IE and Opera return items
// by name instead of ID
if ( tmp.id != m[3] )
return jQuery().find( a );
else {
this[0] = tmp;
this.length = 1;
return this;
}
else
a = [];
}
// HANDLE: $(expr)
} else
return new jQuery( c ).find( a );
// HANDLE: $(function)
// Shortcut for document ready
} else if ( jQuery.isFunction(a) )
return new jQuery(document)[ jQuery.fn.ready ? "ready" : "load" ]( a );
return this.setArray(
// HANDLE: $(array)
a.constructor == Array && a ||
// HANDLE: $(arraylike)
// Watch for when an array-like object is passed as the selector
(a.jquery || a.length && a != window && !a.nodeType && a[0] != undefined && a[0].nodeType) && jQuery.makeArray( a ) ||
// HANDLE: $(*)
[ a ] );
},
jquery: "1.1.4",
size: function() {
return this.length;
},
length: 0,
get: function( num ) {
return num == undefined ?
// Return a 'clean' array
jQuery.makeArray( this ) :
// Return just the object
this[num];
},
pushStack: function( a ) {
var ret = jQuery(a);
ret.prevObject = this;
return ret;
},
setArray: function( a ) {
this.length = 0;
Array.prototype.push.apply( this, a );
return this;
},
each: function( fn, args ) {
return jQuery.each( this, fn, args );
},
index: function( obj ) {
var pos = -1;
this.each(function(i){
if ( this == obj ) pos = i;
});
return pos;
},
attr: function( key, value, type ) {
var obj = key;
// Look for the case where we're accessing a style value
if ( key.constructor == String )
if ( value == undefined )
return this.length && jQuery[ type || "attr" ]( this[0], key ) || undefined;
else {
obj = {};
obj[ key ] = value;
}
// Check to see if we're setting style values
return this.each(function(index){
// Set all the styles
for ( var prop in obj )
jQuery.attr(
type ? this.style : this,
prop, jQuery.prop(this, obj[prop], type, index, prop)
);
});
},
css: function( key, value ) {
return this.attr( key, value, "curCSS" );
},
text: function(e) {
if ( typeof e != "object" && e != null )
return this.empty().append( document.createTextNode( e ) );
var t = "";
jQuery.each( e || this, function(){
jQuery.each( this.childNodes, function(){
if ( this.nodeType != 8 )
t += this.nodeType != 1 ?
this.nodeValue : jQuery.fn.text([ this ]);
});
});
return t;
},
wrap: function() {
// The elements to wrap the target around
var a, args = arguments;
// Wrap each of the matched elements individually
return this.each(function(){
if ( !a )
a = jQuery.clean(args, this.ownerDocument);
// Clone the structure that we're using to wrap
var b = a[0].cloneNode(true);
// Insert it before the element to be wrapped
this.parentNode.insertBefore( b, this );
// Find the deepest point in the wrap structure
while ( b.firstChild )
b = b.firstChild;
// Move the matched element to within the wrap structure
b.appendChild( this );
});
},
append: function() {
return this.domManip(arguments, true, 1, function(a){
this.appendChild( a );
});
},
prepend: function() {
return this.domManip(arguments, true, -1, function(a){
this.insertBefore( a, this.firstChild );
});
},
before: function() {
return this.domManip(arguments, false, 1, function(a){
this.parentNode.insertBefore( a, this );
});
},
after: function() {
return this.domManip(arguments, false, -1, function(a){
this.parentNode.insertBefore( a, this.nextSibling );
});
},
end: function() {
return this.prevObject || jQuery([]);
},
find: function(t) {
var data = jQuery.map(this, function(a){ return jQuery.find(t,a); });
return this.pushStack( /[^+>] [^+>]/.test( t ) || t.indexOf("..") > -1 ?
jQuery.unique( data ) : data );
},
clone: function(deep) {
deep = deep != undefined ? deep : true;
var $this = this.add(this.find("*"));
if (jQuery.browser.msie) {
// Need to remove events on the element and its descendants
$this.each(function() {
this._$events = {};
for (var type in this.$events)
this._$events[type] = jQuery.extend({},this.$events[type]);
}).unbind();
}
// Do the clone
var r = this.pushStack( jQuery.map( this, function(a){
return a.cloneNode( deep );
}) );
if (jQuery.browser.msie) {
$this.each(function() {
// Add the events back to the original and its descendants
var events = this._$events;
for (var type in events)
for (var handler in events[type])
jQuery.event.add(this, type, events[type][handler], events[type][handler].data);
this._$events = null;
});
}
// copy form values over
if (deep) {
var inputs = r.add(r.find('*')).filter('select,input[@type=checkbox]');
$this.filter('select,input[@type=checkbox]').each(function(i) {
if (this.selectedIndex)
inputs[i].selectedIndex = this.selectedIndex;
if (this.checked)
inputs[i].checked = true;
});
}
// Return the cloned set
return r;
},
filter: function(t) {
return this.pushStack(
jQuery.isFunction( t ) &&
jQuery.grep(this, function(el, index){
return t.apply(el, [index]);
}) ||
jQuery.multiFilter(t,this) );
},
not: function(t) {
return this.pushStack(
t.constructor == String &&
jQuery.multiFilter(t, this, true) ||
jQuery.grep(this, function(a) {
return ( t.constructor == Array || t.jquery )
? jQuery.inArray( a, t ) < 0
: a != t;
})
);
},
add: function(t) {
return this.pushStack( jQuery.merge(
this.get(),
t.constructor == String ?
jQuery(t).get() :
t.length != undefined && (!t.nodeName || t.nodeName == "FORM") ?
t : [t] )
);
},
is: function(expr) {
return expr ? jQuery.multiFilter(expr,this).length > 0 : false;
},
val: function( val ) {
return val == undefined ?
( this.length ? this[0].value : null ) :
this.attr( "value", val );
},
html: function( val ) {
return val == undefined ?
( this.length ? this[0].innerHTML : null ) :
this.empty().append( val );
},
slice: function() {
return this.pushStack( Array.prototype.slice.apply( this, arguments ) );
},
domManip: function(args, table, dir, fn){
var clone = this.length > 1, a;
return this.each(function(){
if ( !a ) {
a = jQuery.clean(args, this.ownerDocument);
if ( dir < 0 )
a.reverse();
}
var obj = this;
if ( table && jQuery.nodeName(this, "table") && jQuery.nodeName(a[0], "tr") )
obj = this.getElementsByTagName("tbody")[0] || this.appendChild(document.createElement("tbody"));
jQuery.each( a, function(){
if ( jQuery.nodeName(this, "script") ) {
if ( this.src )
jQuery.ajax({ url: this.src, async: false, dataType: "script" });
else
jQuery.globalEval( this.text || this.textContent || this.innerHTML || "" );
} else
fn.apply( obj, [ clone ? this.cloneNode(true) : this ] );
});
});
}
};
jQuery.extend = jQuery.fn.extend = function() {
// copy reference to target object
var target = arguments[0] || {}, a = 1, al = arguments.length, deep = false;
// Handle a deep copy situation
if ( target.constructor == Boolean ) {
deep = target;
target = arguments[1] || {};
}
// extend jQuery itself if only one argument is passed
if ( al == 1 ) {
target = this;
a = 0;
}
var prop;
for ( ; a < al; a++ )
// Only deal with non-null/undefined values
if ( (prop = arguments[a]) != null )
// Extend the base object
for ( var i in prop ) {
// Prevent never-ending loop
if ( target == prop[i] )
continue;
// Recurse if we're merging object values
if ( deep && typeof prop[i] == 'object' && target[i] )
jQuery.extend( target[i], prop[i] );
// Don't bring in undefined values
else if ( prop[i] != undefined )
target[i] = prop[i];
}
// Return the modified object
return target;
};
jQuery.extend({
noConflict: function(deep) {
window.$ = _$;
if ( deep )
window.jQuery = _jQuery;
return jQuery;
},
// This may seem like some crazy code, but trust me when I say that this
// is the only cross-browser way to do this. --John
isFunction: function( fn ) {
return !!fn && typeof fn != "string" && !fn.nodeName &&
fn.constructor != Array && /function/i.test( fn + "" );
},
// check if an element is in a XML document
isXMLDoc: function(elem) {
return elem.documentElement && !elem.body ||
elem.tagName && elem.ownerDocument && !elem.ownerDocument.body;
},
// Evalulates a script in a global context
// Evaluates Async. in Safari 2 :-(
globalEval: function( data ) {
data = jQuery.trim( data );
if ( data ) {
if ( window.execScript )
window.execScript( data );
else if ( jQuery.browser.safari )
// safari doesn't provide a synchronous global eval
window.setTimeout( data, 0 );
else
eval.call( window, data );
}
},
nodeName: function( elem, name ) {
return elem.nodeName && elem.nodeName.toUpperCase() == name.toUpperCase();
},
// args is for internal usage only
each: function( obj, fn, args ) {
if ( args ) {
if ( obj.length == undefined )
for ( var i in obj )
fn.apply( obj[i], args );
else
for ( var i = 0, ol = obj.length; i < ol; i++ )
if ( fn.apply( obj[i], args ) === false ) break;
// A special, fast, case for the most common use of each
} else {
if ( obj.length == undefined )
for ( var i in obj )
fn.call( obj[i], i, obj[i] );
else
for ( var i = 0, ol = obj.length, val = obj[0];
i < ol && fn.call(val,i,val) !== false; val = obj[++i] ){}
}
return obj;
},
prop: function(elem, value, type, index, prop){
// Handle executable functions
if ( jQuery.isFunction( value ) )
value = value.call( elem, [index] );
// exclude the following css properties to add px
var exclude = /z-?index|font-?weight|opacity|zoom|line-?height/i;
// Handle passing in a number to a CSS property
return value && value.constructor == Number && type == "curCSS" && !exclude.test(prop) ?
value + "px" :
value;
},
className: {
// internal only, use addClass("class")
add: function( elem, c ){
jQuery.each( (c || "").split(/\s+/), function(i, cur){
if ( !jQuery.className.has( elem.className, cur ) )
elem.className += ( elem.className ? " " : "" ) + cur;
});
},
// internal only, use removeClass("class")
remove: function( elem, c ){
elem.className = c != undefined ?
jQuery.grep( elem.className.split(/\s+/), function(cur){
return !jQuery.className.has( c, cur );
}).join(" ") : "";
},
// internal only, use is(".class")
has: function( t, c ) {
return jQuery.inArray( c, (t.className || t).toString().split(/\s+/) ) > -1;
}
},
swap: function(e,o,f) {
for ( var i in o ) {
e.style["old"+i] = e.style[i];
e.style[i] = o[i];
}
f.apply( e, [] );
for ( var i in o )
e.style[i] = e.style["old"+i];
},
css: function(e,p) {
if ( p == "height" || p == "width" ) {
var old = {}, oHeight, oWidth, d = ["Top","Bottom","Right","Left"];
jQuery.each( d, function(){
old["padding" + this] = 0;
old["border" + this + "Width"] = 0;
});
jQuery.swap( e, old, function() {
if ( jQuery(e).is(':visible') ) {
oHeight = e.offsetHeight;
oWidth = e.offsetWidth;
} else {
e = jQuery(e.cloneNode(true))
.find(":radio").removeAttr("checked").end()
.css({
visibility: "hidden", position: "absolute", display: "block", right: "0", left: "0"
}).appendTo(e.parentNode)[0];
var parPos = jQuery.css(e.parentNode,"position") || "static";
if ( parPos == "static" )
e.parentNode.style.position = "relative";
oHeight = e.clientHeight;
oWidth = e.clientWidth;
if ( parPos == "static" )
e.parentNode.style.position = "static";
e.parentNode.removeChild(e);
}
});
return p == "height" ? oHeight : oWidth;
}
return jQuery.curCSS( e, p );
},
curCSS: function(elem, prop, force) {
var ret, stack = [], swap = [];
// A helper method for determining if an element's values are broken
function color(a){
if ( !jQuery.browser.safari )
return false;
var ret = document.defaultView.getComputedStyle(a,null);
return !ret || ret.getPropertyValue("color") == "";
}
if (prop == "opacity" && jQuery.browser.msie) {
ret = jQuery.attr(elem.style, "opacity");
return ret == "" ? "1" : ret;
}
if (prop.match(/float/i))
prop = styleFloat;
if (!force && elem.style[prop])
ret = elem.style[prop];
else if (document.defaultView && document.defaultView.getComputedStyle) {
if (prop.match(/float/i))
prop = "float";
prop = prop.replace(/([A-Z])/g,"-$1").toLowerCase();
var cur = document.defaultView.getComputedStyle(elem, null);
if ( cur && !color(elem) )
ret = cur.getPropertyValue(prop);
// If the element isn't reporting its values properly in Safari
// then some display: none elements are involved
else {
// Locate all of the parent display: none elements
for ( var a = elem; a && color(a); a = a.parentNode )
stack.unshift(a);
// Go through and make them visible, but in reverse
// (It would be better if we knew the exact display type that they had)
for ( a = 0; a < stack.length; a++ )
if ( color(stack[a]) ) {
swap[a] = stack[a].style.display;
stack[a].style.display = "block";
}
// Since we flip the display style, we have to handle that
// one special, otherwise get the value
ret = prop == "display" && swap[stack.length-1] != null ?
"none" :
document.defaultView.getComputedStyle(elem,null).getPropertyValue(prop) || "";
// Finally, revert the display styles back
for ( a = 0; a < swap.length; a++ )
if ( swap[a] != null )
stack[a].style.display = swap[a];
}
if ( prop == "opacity" && ret == "" )
ret = "1";
} else if (elem.currentStyle) {
var newProp = prop.replace(/\-(\w)/g,function(m,c){return c.toUpperCase();});
ret = elem.currentStyle[prop] || elem.currentStyle[newProp];
}
return ret;
},
clean: function(a, doc) {
var r = [];
doc = doc || document;
jQuery.each( a, function(i,arg){
if ( !arg ) return;
if ( arg.constructor == Number )
arg = arg.toString();
// Convert html string into DOM nodes
if ( typeof arg == "string" ) {
// Trim whitespace, otherwise indexOf won't work as expected
var s = jQuery.trim(arg).toLowerCase(), div = doc.createElement("div"), tb = [];
var wrap =
// option or optgroup
!s.indexOf("<opt") &&
[1, "<select>", "</select>"] ||
!s.indexOf("<leg") &&
[1, "<fieldset>", "</fieldset>"] ||
s.match(/^<(thead|tbody|tfoot|colg|cap)/) &&
[1, "<table>", "</table>"] ||
!s.indexOf("<tr") &&
[2, "<table><tbody>", "</tbody></table>"] ||
// <thead> matched above
(!s.indexOf("<td") || !s.indexOf("<th")) &&
[3, "<table><tbody><tr>", "</tr></tbody></table>"] ||
!s.indexOf("<col") &&
[2, "<table><tbody></tbody><colgroup>", "</colgroup></table>"] ||
// IE can't serialize <link> and <script> tags normally
jQuery.browser.msie &&
[1, "div<div>", "</div>"] ||
[0,"",""];
// Go to html and back, then peel off extra wrappers
div.innerHTML = wrap[1] + arg + wrap[2];
// Move to the right depth
while ( wrap[0]-- )
div = div.lastChild;
// Remove IE's autoinserted <tbody> from table fragments
if ( jQuery.browser.msie ) {
// String was a <table>, *may* have spurious <tbody>
if ( !s.indexOf("<table") && s.indexOf("<tbody") < 0 )
tb = div.firstChild && div.firstChild.childNodes;
// String was a bare <thead> or <tfoot>
else if ( wrap[1] == "<table>" && s.indexOf("<tbody") < 0 )
tb = div.childNodes;
for ( var n = tb.length-1; n >= 0 ; --n )
if ( jQuery.nodeName(tb[n], "tbody") && !tb[n].childNodes.length )
tb[n].parentNode.removeChild(tb[n]);
// IE completely kills leading whitespace when innerHTML is used
if ( /^\s/.test(arg) )
div.insertBefore( doc.createTextNode( arg.match(/^\s*/)[0] ), div.firstChild );
}
arg = jQuery.makeArray( div.childNodes );
}
if ( 0 === arg.length && (!jQuery.nodeName(arg, "form") && !jQuery.nodeName(arg, "select")) )
return;
if ( arg[0] == undefined || jQuery.nodeName(arg, "form") || arg.options )
r.push( arg );
else
r = jQuery.merge( r, arg );
});
return r;
},
attr: function(elem, name, value){
var fix = jQuery.isXMLDoc(elem) ? {} : jQuery.props;
// Safari mis-reports the default selected property of a hidden option
// Accessing the parent's selectedIndex property fixes it
if ( name == "selected" && jQuery.browser.safari )
elem.parentNode.selectedIndex;
// Certain attributes only work when accessed via the old DOM 0 way
if ( fix[name] ) {
if ( value != undefined ) elem[fix[name]] = value;
return elem[fix[name]];
} else if ( jQuery.browser.msie && name == "style" )
return jQuery.attr( elem.style, "cssText", value );
else if ( value == undefined && jQuery.browser.msie && jQuery.nodeName(elem, "form") && (name == "action" || name == "method") )
return elem.getAttributeNode(name).nodeValue;
// IE elem.getAttribute passes even for style
else if ( elem.tagName ) {
if ( value != undefined ) elem.setAttribute( name, value );
if ( jQuery.browser.msie && /href|src/.test(name) && !jQuery.isXMLDoc(elem) )
return elem.getAttribute( name, 2 );
return elem.getAttribute( name );
// elem is actually elem.style ... set the style
} else {
// IE actually uses filters for opacity
if ( name == "opacity" && jQuery.browser.msie ) {
if ( value != undefined ) {
// IE has trouble with opacity if it does not have layout
// Force it by setting the zoom level
elem.zoom = 1;
// Set the alpha filter to set the opacity
elem.filter = (elem.filter || "").replace(/alpha\([^)]*\)/,"") +
(parseFloat(value).toString() == "NaN" ? "" : "alpha(opacity=" + value * 100 + ")");
}
return elem.filter ?
(parseFloat( elem.filter.match(/opacity=([^)]*)/)[1] ) / 100).toString() : "";
}
name = name.replace(/-([a-z])/ig,function(z,b){return b.toUpperCase();});
if ( value != undefined ) elem[name] = value;
return elem[name];
}
},
trim: function(t){
return (t||"").replace(/^\s+|\s+$/g, "");
},
makeArray: function( a ) {
var r = [];
// Need to use typeof to fight Safari childNodes crashes
if ( typeof a != "array" )
for ( var i = 0, al = a.length; i < al; i++ )
r.push( a[i] );
else
r = a.slice( 0 );
return r;
},
inArray: function( b, a ) {
for ( var i = 0, al = a.length; i < al; i++ )
if ( a[i] == b )
return i;
return -1;
},
merge: function(first, second) {
// We have to loop this way because IE & Opera overwrite the length
// expando of getElementsByTagName
// Also, we need to make sure that the correct elements are being returned
// (IE returns comment nodes in a '*' query)
if ( jQuery.browser.msie ) {
for ( var i = 0; second[i]; i++ )
if ( second[i].nodeType != 8 )
first.push(second[i]);
} else
for ( var i = 0; second[i]; i++ )
first.push(second[i]);
return first;
},
unique: function(first) {
var r = [], num = jQuery.mergeNum++;
try {
for ( var i = 0, fl = first.length; i < fl; i++ )
if ( num != first[i].mergeNum ) {
first[i].mergeNum = num;
r.push(first[i]);
}
} catch(e) {
r = first;
}
return r;
},
mergeNum: 0,
grep: function(elems, fn, inv) {
// If a string is passed in for the function, make a function
// for it (a handy shortcut)
if ( typeof fn == "string" )
fn = eval("false||function(a,i){return " + fn + "}");
var result = [];
// Go through the array, only saving the items
// that pass the validator function
for ( var i = 0, el = elems.length; i < el; i++ )
if ( !inv && fn(elems[i],i) || inv && !fn(elems[i],i) )
result.push( elems[i] );
return result;
},
map: function(elems, fn) {
// If a string is passed in for the function, make a function
// for it (a handy shortcut)
if ( typeof fn == "string" )
fn = eval("false||function(a){return " + fn + "}");
var result = [];
// Go through the array, translating each of the items to their
// new value (or values).
for ( var i = 0, el = elems.length; i < el; i++ ) {
var val = fn(elems[i],i);
if ( val !== null && val != undefined ) {
if ( val.constructor != Array ) val = [val];
result = result.concat( val );
}
}
return result;
}
});
/*
* Whether the W3C compliant box model is being used.
*
* @property
* @name $.boxModel
* @type Boolean
* @cat JavaScript
*/
var userAgent = navigator.userAgent.toLowerCase();
// Figure out what browser is being used
jQuery.browser = {
version: (userAgent.match(/.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/) || [])[1],
safari: /webkit/.test(userAgent),
opera: /opera/.test(userAgent),
msie: /msie/.test(userAgent) && !/opera/.test(userAgent),
mozilla: /mozilla/.test(userAgent) && !/(compatible|webkit)/.test(userAgent)
};
var styleFloat = jQuery.browser.msie ? "styleFloat" : "cssFloat";
jQuery.extend({
// Check to see if the W3C box model is being used
boxModel: !jQuery.browser.msie || document.compatMode == "CSS1Compat",
styleFloat: jQuery.browser.msie ? "styleFloat" : "cssFloat",
props: {
"for": "htmlFor",
"class": "className",
"float": styleFloat,
cssFloat: styleFloat,
styleFloat: styleFloat,
innerHTML: "innerHTML",
className: "className",
value: "value",
disabled: "disabled",
checked: "checked",
readonly: "readOnly",
selected: "selected",
maxlength: "maxLength"
}
});
jQuery.each({
parent: "a.parentNode",
parents: "jQuery.parents(a)",
next: "jQuery.nth(a,2,'nextSibling')",
prev: "jQuery.nth(a,2,'previousSibling')",
siblings: "jQuery.sibling(a.parentNode.firstChild,a)",
children: "jQuery.sibling(a.firstChild)"
}, function(i,n){
jQuery.fn[ i ] = function(a) {
var ret = jQuery.map(this,n);
if ( a && typeof a == "string" )
ret = jQuery.multiFilter(a,ret);
return this.pushStack( jQuery.unique(ret) );
};
});
jQuery.each({
appendTo: "append",
prependTo: "prepend",
insertBefore: "before",
insertAfter: "after"
}, function(i,n){
jQuery.fn[ i ] = function(){
var a = arguments;
return this.each(function(){
for ( var j = 0, al = a.length; j < al; j++ )
jQuery(a[j])[n]( this );
});
};
});
jQuery.each( {
removeAttr: function( key ) {
jQuery.attr( this, key, "" );
this.removeAttribute( key );
},
addClass: function(c){
jQuery.className.add(this,c);
},
removeClass: function(c){
jQuery.className.remove(this,c);
},
toggleClass: function( c ){
jQuery.className[ jQuery.className.has(this,c) ? "remove" : "add" ](this, c);
},
remove: function(a){
if ( !a || jQuery.filter( a, [this] ).r.length )
this.parentNode.removeChild( this );
},
empty: function() {
while ( this.firstChild )
this.removeChild( this.firstChild );
}
}, function(i,n){
jQuery.fn[ i ] = function() {
return this.each( n, arguments );
};
});
// DEPRECATED
jQuery.each( [ "eq", "lt", "gt", "contains" ], function(i,n){
jQuery.fn[ n ] = function(num,fn) {
return this.filter( ":" + n + "(" + num + ")", fn );
};
});
jQuery.each( [ "height", "width" ], function(i,n){
jQuery.fn[ n ] = function(h) {
return h == undefined ?
( this.length ? jQuery.css( this[0], n ) : null ) :
this.css( n, h.constructor == String ? h : h + "px" );
};
});
var chars = jQuery.browser.safari && parseInt(jQuery.browser.version) < 417 ?
"(?:[\\w*_-]|\\\\.)" :
"(?:[\\w\u0128-\uFFFF*_-]|\\\\.)",
quickChild = new RegExp("^[/>]\\s*(" + chars + "+)"),
quickID = new RegExp("^(" + chars + "+)(#)(" + chars + "+)"),
quickClass = new RegExp("^([#.]?)(" + chars + "*)");
jQuery.extend({
expr: {
"": "m[2]=='*'||jQuery.nodeName(a,m[2])",
"#": "a.getAttribute('id')==m[2]",
":": {
// Position Checks
lt: "i<m[3]-0",
gt: "i>m[3]-0",
nth: "m[3]-0==i",
eq: "m[3]-0==i",
first: "i==0",
last: "i==r.length-1",
even: "i%2==0",
odd: "i%2",
// Child Checks
"first-child": "a.parentNode.getElementsByTagName('*')[0]==a",
"last-child": "jQuery.nth(a.parentNode.lastChild,1,'previousSibling')==a",
"only-child": "!jQuery.nth(a.parentNode.lastChild,2,'previousSibling')",
// Parent Checks
parent: "a.firstChild",
empty: "!a.firstChild",
// Text Check
contains: "(a.textContent||a.innerText||'').indexOf(m[3])>=0",
// Visibility
visible: '"hidden"!=a.type&&jQuery.css(a,"display")!="none"&&jQuery.css(a,"visibility")!="hidden"',
hidden: '"hidden"==a.type||jQuery.css(a,"display")=="none"||jQuery.css(a,"visibility")=="hidden"',
// Form attributes
enabled: "!a.disabled",
disabled: "a.disabled",
checked: "a.checked",
selected: "a.selected||jQuery.attr(a,'selected')",
// Form elements
text: "'text'==a.type",
radio: "'radio'==a.type",
checkbox: "'checkbox'==a.type",
file: "'file'==a.type",
password: "'password'==a.type",
submit: "'submit'==a.type",
image: "'image'==a.type",
reset: "'reset'==a.type",
button: '"button"==a.type||jQuery.nodeName(a,"button")',
input: "/input|select|textarea|button/i.test(a.nodeName)",
// :has()
has: "jQuery.find(m[3],a).length"
},
// DEPRECATED
"[": "jQuery.find(m[2],a).length"
},
// The regular expressions that power the parsing engine
parse: [
// Match: [@value='test'], [@foo]
/^\[ *(@)([\w-]+) *([!*$^~=]*) *('?"?)(.*?)\4 *\]/,
// DEPRECATED
// Match: [div], [div p]
/^(\[)\s*(.*?(\[.*?\])?[^[]*?)\s*\]/,
// Match: :contains('foo')
/^(:)([\w-]+)\("?'?(.*?(\(.*?\))?[^(]*?)"?'?\)/,
// Match: :even, :last-chlid, #id, .class
new RegExp("^([:.#]*)(" + chars + "+)")
],
multiFilter: function( expr, elems, not ) {
var old, cur = [];
while ( expr && expr != old ) {
old = expr;
var f = jQuery.filter( expr, elems, not );
expr = f.t.replace(/^\s*,\s*/, "" );
cur = not ? elems = f.r : jQuery.merge( cur, f.r );
}
return cur;
},
find: function( t, context ) {
// Quickly handle non-string expressions
if ( typeof t != "string" )
return [ t ];
// Make sure that the context is a DOM Element
if ( context && !context.nodeType )
context = null;
// Set the correct context (if none is provided)
context = context || document;
// DEPRECATED
// Handle the common XPath // expression
if ( !t.indexOf("//") ) {
//context = context.documentElement;
t = t.substr(2,t.length);
// DEPRECATED
// And the / root expression
} else if ( !t.indexOf("/") && !context.ownerDocument ) {
context = context.documentElement;
t = t.substr(1,t.length);
if ( t.indexOf("/") >= 1 )
t = t.substr(t.indexOf("/"),t.length);
}
// Initialize the search
var ret = [context], done = [], last;
// Continue while a selector expression exists, and while
// we're no longer looping upon ourselves
while ( t && last != t ) {
var r = [];
last = t;
// DEPRECATED
t = jQuery.trim(t).replace( /^\/\//, "" );
var foundToken = false;
// An attempt at speeding up child selectors that
// point to a specific element tag
var re = quickChild;
var m = re.exec(t);
if ( m ) {
var nodeName = m[1].toUpperCase();
// Perform our own iteration and filter
for ( var i = 0; ret[i]; i++ )
for ( var c = ret[i].firstChild; c; c = c.nextSibling )
if ( c.nodeType == 1 && (nodeName == "*" || c.nodeName.toUpperCase() == nodeName.toUpperCase()) )
r.push( c );
ret = r;
t = t.replace( re, "" );
if ( t.indexOf(" ") == 0 ) continue;
foundToken = true;
} else {
// (.. and /) DEPRECATED
re = /^((\/?\.\.)|([>\/+~]))\s*(\w*)/i;
if ( (m = re.exec(t)) != null ) {
r = [];
var nodeName = m[4], mergeNum = jQuery.mergeNum++;
m = m[1];
for ( var j = 0, rl = ret.length; j < rl; j++ )
if ( m.indexOf("..") < 0 ) {
var n = m == "~" || m == "+" ? ret[j].nextSibling : ret[j].firstChild;
for ( ; n; n = n.nextSibling )
if ( n.nodeType == 1 ) {
if ( m == "~" && n.mergeNum == mergeNum ) break;
if (!nodeName || n.nodeName.toUpperCase() == nodeName.toUpperCase() ) {
if ( m == "~" ) n.mergeNum = mergeNum;
r.push( n );
}
if ( m == "+" ) break;
}
// DEPRECATED
} else
r.push( ret[j].parentNode );
ret = r;
// And remove the token
t = jQuery.trim( t.replace( re, "" ) );
foundToken = true;
}
}
// See if there's still an expression, and that we haven't already
// matched a token
if ( t && !foundToken ) {
// Handle multiple expressions
if ( !t.indexOf(",") ) {
// Clean the result set
if ( context == ret[0] ) ret.shift();
// Merge the result sets
done = jQuery.merge( done, ret );
// Reset the context
r = ret = [context];
// Touch up the selector string
t = " " + t.substr(1,t.length);
} else {
// Optimize for the case nodeName#idName
var re2 = quickID;
var m = re2.exec(t);
// Re-organize the results, so that they're consistent
if ( m ) {
m = [ 0, m[2], m[3], m[1] ];
} else {
// Otherwise, do a traditional filter check for
// ID, class, and element selectors
re2 = quickClass;
m = re2.exec(t);
}
m[2] = m[2].replace(/\\/g, "");
var elem = ret[ret.length-1];
// Try to do a global search by ID, where we can
if ( m[1] == "#" && elem && elem.getElementById && !jQuery.isXMLDoc(elem) ) {
// Optimization for HTML document case
var oid = elem.getElementById(m[2]);
// Do a quick check for the existence of the actual ID attribute
// to avoid selecting by the name attribute in IE
// also check to insure id is a string to avoid selecting an element with the name of 'id' inside a form
if ( (jQuery.browser.msie||jQuery.browser.opera) && oid && typeof oid.id == "string" && oid.id != m[2] )
oid = jQuery('[@id="'+m[2]+'"]', elem)[0];
// Do a quick check for node name (where applicable) so
// that div#foo searches will be really fast
ret = r = oid && (!m[3] || jQuery.nodeName(oid, m[3])) ? [oid] : [];
} else {
// We need to find all descendant elements
for ( var i = 0; ret[i]; i++ ) {
// Grab the tag name being searched for
var tag = m[1] != "" || m[0] == "" ? "*" : m[2];
// Handle IE7 being really dumb about <object>s
if ( tag == "*" && ret[i].nodeName.toLowerCase() == "object" )
tag = "param";
r = jQuery.merge( r, ret[i].getElementsByTagName( tag ));
}
// It's faster to filter by class and be done with it
if ( m[1] == "." )
r = jQuery.classFilter( r, m[2] );
// Same with ID filtering
if ( m[1] == "#" ) {
var tmp = [];
// Try to find the element with the ID
for ( var i = 0; r[i]; i++ )
if ( r[i].getAttribute("id") == m[2] ) {
tmp = [ r[i] ];
break;
}
r = tmp;
}
ret = r;
}
t = t.replace( re2, "" );
}
}
// If a selector string still exists
if ( t ) {
// Attempt to filter it
var val = jQuery.filter(t,r);
ret = r = val.r;
t = jQuery.trim(val.t);
}
}
// An error occurred with the selector;
// just return an empty set instead
if ( t )
ret = [];
// Remove the root context
if ( ret && context == ret[0] )
ret.shift();
// And combine the results
done = jQuery.merge( done, ret );
return done;
},
classFilter: function(r,m,not){
m = " " + m + " ";
var tmp = [];
for ( var i = 0; r[i]; i++ ) {
var pass = (" " + r[i].className + " ").indexOf( m ) >= 0;
if ( !not && pass || not && !pass )
tmp.push( r[i] );
}
return tmp;
},
filter: function(t,r,not) {
var last;
// Look for common filter expressions
while ( t && t != last ) {
last = t;
var p = jQuery.parse, m;
for ( var i = 0; p[i]; i++ ) {
m = p[i].exec( t );
if ( m ) {
// Remove what we just matched
t = t.substring( m[0].length );
m[2] = m[2].replace(/\\/g, "");
break;
}
}
if ( !m )
break;
// :not() is a special case that can be optimized by
// keeping it out of the expression list
if ( m[1] == ":" && m[2] == "not" )
r = jQuery.filter(m[3], r, true).r;
// We can get a big speed boost by filtering by class here
else if ( m[1] == "." )
r = jQuery.classFilter(r, m[2], not);
else if ( m[1] == "@" ) {
var tmp = [], type = m[3];
for ( var i = 0, rl = r.length; i < rl; i++ ) {
var a = r[i], z = a[ jQuery.props[m[2]] || m[2] ];
if ( z == null || /href|src|selected/.test(m[2]) )
z = jQuery.attr(a,m[2]);// || '';
if ( (type == "" && !!z ||
type == "=" && z == m[5] ||
type == "!=" && z != m[5] ||
type == "^=" && z && !z.indexOf(m[5]) ||
type == "$=" && z.substr(z.length - m[5].length) == m[5] ||
(type == "*=" || type == "~=") && z.indexOf(m[5]) >= 0) ^ not )
tmp.push( a );
}
r = tmp;
// We can get a speed boost by handling nth-child here
} else if ( m[1] == ":" && m[2] == "nth-child" ) {
var num = jQuery.mergeNum++, tmp = [],
test = /(\d*)n\+?(\d*)/.exec(
m[3] == "even" && "2n" || m[3] == "odd" && "2n+1" ||
!/\D/.test(m[3]) && "n+" + m[3] || m[3]),
first = (test[1] || 1) - 0, last = test[2] - 0;
for ( var i = 0, rl = r.length; i < rl; i++ ) {
var node = r[i], parentNode = node.parentNode;
if ( num != parentNode.mergeNum ) {
var c = 1;
for ( var n = parentNode.firstChild; n; n = n.nextSibling )
if ( n.nodeType == 1 )
n.nodeIndex = c++;
parentNode.mergeNum = num;
}
var add = false;
if ( first == 1 ) {
if ( last == 0 || node.nodeIndex == last )
add = true;
} else if ( (node.nodeIndex + last) % first == 0 )
add = true;
if ( add ^ not )
tmp.push( node );
}
r = tmp;
// Otherwise, find the expression to execute
} else {
var f = jQuery.expr[m[1]];
if ( typeof f != "string" )
f = jQuery.expr[m[1]][m[2]];
// Build a custom macro to enclose it
f = eval("false||function(a,i){return " + f + "}");
// Execute it against the current filter
r = jQuery.grep( r, f, not );
}
}
// Return an array of filtered elements (r)
// and the modified expression string (t)
return { r: r, t: t };
},
parents: function( elem ){
var matched = [];
var cur = elem.parentNode;
while ( cur && cur != document ) {
matched.push( cur );
cur = cur.parentNode;
}
return matched;
},
nth: function(cur,result,dir,elem){
result = result || 1;
var num = 0;
for ( ; cur; cur = cur[dir] )
if ( cur.nodeType == 1 && ++num == result )
break;
return cur;
},
sibling: function( n, elem ) {
var r = [];
for ( ; n; n = n.nextSibling ) {
if ( n.nodeType == 1 && (!elem || n != elem) )
r.push( n );
}
return r;
}
});
/*
* A number of helper functions used for managing events.
* Many of the ideas behind this code orignated from
* Dean Edwards' addEvent library.
*/
jQuery.event = {
// Bind an event to an element
// Original by Dean Edwards
add: function(element, type, handler, data) {
// For whatever reason, IE has trouble passing the window object
// around, causing it to be cloned in the process
if ( jQuery.browser.msie && element.setInterval != undefined )
element = window;
// Make sure that the function being executed has a unique ID
if ( !handler.guid )
handler.guid = this.guid++;
// if data is passed, bind to handler
if( data != undefined ) {
// Create temporary function pointer to original handler
var fn = handler;
// Create unique handler function, wrapped around original handler
handler = function() {
// Pass arguments and context to original handler
return fn.apply(this, arguments);
};
// Store data in unique handler
handler.data = data;
// Set the guid of unique handler to the same of original handler, so it can be removed
handler.guid = fn.guid;
}
// Init the element's event structure
if (!element.$events)
element.$events = {};
if (!element.$handle)
element.$handle = function() {
// returned undefined or false
var val;
// Handle the second event of a trigger and when
// an event is called after a page has unloaded
if ( typeof jQuery == "undefined" || jQuery.event.triggered )
return val;
val = jQuery.event.handle.apply(element, arguments);
return val;
};
// Get the current list of functions bound to this event
var handlers = element.$events[type];
// Init the event handler queue
if (!handlers) {
handlers = element.$events[type] = {};
// And bind the global event handler to the element
if (element.addEventListener)
element.addEventListener(type, element.$handle, false);
else
element.attachEvent("on" + type, element.$handle);
}
// Add the function to the element's handler list
handlers[handler.guid] = handler;
// Keep track of which events have been used, for global triggering
if (element==window||element==document) // Added by fanguozhu
this.global[type] = true;
},
guid: 1,
global: {},
// Detach an event or set of events from an element
remove: function(element, type, handler) {
var events = element.$events, ret, index;
if ( events ) {
// type is actually an event object here
if ( type && type.type ) {
handler = type.handler;
type = type.type;
}
if ( !type ) {
for ( type in events )
this.remove( element, type );
} else if ( events[type] ) {
// remove the given handler for the given type
if ( handler )
delete events[type][handler.guid];
// remove all handlers for the given type
else
for ( handler in element.$events[type] )
delete events[type][handler];
// remove generic event handler if no more handlers exist
for ( ret in events[type] ) break;
if ( !ret ) {
if (element.removeEventListener)
element.removeEventListener(type, element.$handle, false);
else
element.detachEvent("on" + type, element.$handle);
ret = null;
delete events[type];
}
}
// Remove the expando if it's no longer used
for ( ret in events ) break;
if ( !ret )
element.$handle = element.$events = null;
}
},
trigger: function(type, data, element) {
// Clone the incoming data, if any
data = jQuery.makeArray(data || []);
// Handle a global trigger
if ( !element ) {
// Only trigger if we've ever bound an event for it
if ( this.global[type] )
$([window, document]).trigger(type, data);
//jQuery("*").add([window, document]).trigger(type, data);
// Handle triggering a single element
} else {
var val, ret, fn = jQuery.isFunction( element[ type ] || null );
// Pass along a fake event
data.unshift( this.fix({ type: type, target: element }) );
// Trigger the event
if ( jQuery.isFunction( element.$handle ) )
val = element.$handle.apply( element, data );
if ( !fn && element["on"+type] && element["on"+type].apply( element, data ) === false )
val = false;
if ( fn && val !== false && !(jQuery.nodeName(element, 'a') && type == "click") ) {
this.triggered = true;
element[ type ]();
}
this.triggered = false;
}
},
handle: function(event) {
// returned undefined or false
var val;
// Empty object is for triggered events with no data
event = jQuery.event.fix( event || window.event || {} );
var c = this.$events && this.$events[event.type], args = Array.prototype.slice.call( arguments, 1 );
args.unshift( event );
for ( var j in c ) {
// Pass in a reference to the handler function itself
// So that we can later remove it
args[0].handler = c[j];
args[0].data = c[j].data;
if ( c[j].apply( this, args ) === false ) {
event.preventDefault();
event.stopPropagation();
val = false;
}
}
// Clean up added properties in IE to prevent memory leak
if (jQuery.browser.msie)
event.target = event.preventDefault = event.stopPropagation =
event.handler = event.data = null;
return val;
},
fix: function(event) {
// store a copy of the original event object
// and clone to set read-only properties
var originalEvent = event;
event = jQuery.extend({}, originalEvent);
// add preventDefault and stopPropagation since
// they will not work on the clone
event.preventDefault = function() {
// if preventDefault exists run it on the original event
if (originalEvent.preventDefault)
originalEvent.preventDefault();
// otherwise set the returnValue property of the original event to false (IE)
originalEvent.returnValue = false;
};
event.stopPropagation = function() {
// if stopPropagation exists run it on the original event
if (originalEvent.stopPropagation)
originalEvent.stopPropagation();
// otherwise set the cancelBubble property of the original event to true (IE)
originalEvent.cancelBubble = true;
};
// Fix target property, if necessary
if ( !event.target && event.srcElement )
event.target = event.srcElement;
// check if target is a textnode (safari)
if (jQuery.browser.safari && event.target.nodeType == 3)
event.target = originalEvent.target.parentNode;
// Add relatedTarget, if necessary
if ( !event.relatedTarget && event.fromElement )
event.relatedTarget = event.fromElement == event.target ? event.toElement : event.fromElement;
// Calculate pageX/Y if missing and clientX/Y available
if ( event.pageX == null && event.clientX != null ) {
var e = document.documentElement, b = document.body;
event.pageX = event.clientX + (e && e.scrollLeft || b.scrollLeft || 0);
event.pageY = event.clientY + (e && e.scrollTop || b.scrollTop || 0);
}
// Add which for key events
if ( !event.which && (event.charCode || event.keyCode) )
event.which = event.charCode || event.keyCode;
// Add metaKey to non-Mac browsers (use ctrl for PC's and Meta for Macs)
if ( !event.metaKey && event.ctrlKey )
event.metaKey = event.ctrlKey;
// Add which for click: 1 == left; 2 == middle; 3 == right
// Note: button is not normalized, so don't use it
if ( !event.which && event.button )
event.which = (event.button & 1 ? 1 : ( event.button & 2 ? 3 : ( event.button & 4 ? 2 : 0 ) ));
return event;
}
};
jQuery.fn.extend({
bind: function( type, data, fn ) {
return type == "unload" ? this.one(type, data, fn) : this.each(function(){
jQuery.event.add( this, type, fn || data, fn && data );
});
},
one: function( type, data, fn ) {
return this.each(function(){
jQuery.event.add( this, type, function(event) {
jQuery(this).unbind(event);
return (fn || data).apply( this, arguments);
}, fn && data);
});
},
unbind: function( type, fn ) {
return this.each(function(){
jQuery.event.remove( this, type, fn );
});
},
trigger: function( type, data ) {
return this.each(function(){
jQuery.event.trigger( type, data, this );
});
},
toggle: function() {
// Save reference to arguments for access in closure
var a = arguments;
return this.click(function(e) {
// Figure out which function to execute
this.lastToggle = 0 == this.lastToggle ? 1 : 0;
// Make sure that clicks stop
e.preventDefault();
// and execute the function
return a[this.lastToggle].apply( this, [e] ) || false;
});
},
hover: function(f,g) {
// A private function for handling mouse 'hovering'
function handleHover(e) {
// Check if mouse(over|out) are still within the same parent element
var p = e.relatedTarget;
// Traverse up the tree
while ( p && p != this ) try { p = p.parentNode; } catch(e) { p = this; };
// If we actually just moused on to a sub-element, ignore it
if ( p == this ) return false;
// Execute the right function
return (e.type == "mouseover" ? f : g).apply(this, [e]);
}
// Bind the function to the two event listeners
return this.mouseover(handleHover).mouseout(handleHover);
},
ready: function(f) {
// Attach the listeners
bindReady();
// If the DOM is already ready
if ( jQuery.isReady )
// Execute the function immediately
f.apply( document, [jQuery] );
// Otherwise, remember the function for later
else
// Add the function to the wait list
jQuery.readyList.push( function() { return f.apply(this, [jQuery]); } );
return this;
}
});
jQuery.extend({
/*
* All the code that makes DOM Ready work nicely.
*/
isReady: false,
readyList: [],
// Handle when the DOM is ready
ready: function() {
// Make sure that the DOM is not already loaded
if ( !jQuery.isReady ) {
// Remember that the DOM is ready
jQuery.isReady = true;
// If there are functions bound, to execute
if ( jQuery.readyList ) {
// Execute all of them
jQuery.each( jQuery.readyList, function(){
this.apply( document );
});
// Reset the list of functions
jQuery.readyList = null;
}
// Remove event listener to avoid memory leak
if ( jQuery.browser.mozilla || jQuery.browser.opera )
document.removeEventListener( "DOMContentLoaded", jQuery.ready, false );
// Remove script element used by IE hack
if( !window.frames.length ) // don't remove if frames are present (#1187)
jQuery(window).load(function(){ jQuery("#__ie_init").remove(); });
}
}
});
jQuery.each( ("blur,focus,load,resize,scroll,unload,click,dblclick," +
"mousedown,mouseup,mousemove,mouseover,mouseout,change,select," +
"submit,keydown,keypress,keyup,error").split(","), function(i,o){
// Handle event binding
jQuery.fn[o] = function(f){
return f ? this.bind(o, f) : this.trigger(o);
};
});
var readyBound = false;
function bindReady(){
if ( readyBound ) return;
readyBound = true;
// If Mozilla is used
if ( jQuery.browser.mozilla || jQuery.browser.opera )
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", jQuery.ready, false );
// If IE is used, use the excellent hack by Matthias Miller
// http://www.outofhanwell.com/blog/index.php?title=the_window_onload_problem_revisited
else if ( jQuery.browser.msie ) {
// Only works if you document.write() it
document.write("<scr" + "ipt id=__ie_init defer=true " +
"src=//:><\/script>");
// Use the defer script hack
var script = document.getElementById("__ie_init");
// script does not exist if jQuery is loaded dynamically
if ( script )
script.onreadystatechange = function() {
if ( document.readyState != "complete" ) return;
jQuery.ready();
};
// Clear from memory
script = null;
// If Safari is used
} else if ( jQuery.browser.safari )
// Continually check to see if the document.readyState is valid
jQuery.safariTimer = setInterval(function(){
// loaded and complete are both valid states
if ( document.readyState == "loaded" ||
document.readyState == "complete" ) {
// If either one are found, remove the timer
clearInterval( jQuery.safariTimer );
jQuery.safariTimer = null;
// and execute any waiting functions
jQuery.ready();
}
}, 10);
// A fallback to window.onload, that will always work
jQuery.event.add( window, "load", jQuery.ready );
}
jQuery.fn.extend({
// DEPRECATED
loadIfModified: function( url, params, callback ) {
this.load( url, params, callback, 1 );
},
load: function( url, params, callback, ifModified ) {
if ( jQuery.isFunction( url ) )
return this.bind("load", url);
callback = callback || function(){};
// Default to a GET request
var type = "GET";
// If the second parameter was provided
if ( params )
// If it's a function
if ( jQuery.isFunction( params ) ) {
// We assume that it's the callback
callback = params;
params = null;
// Otherwise, build a param string
} else {
params = jQuery.param( params );
type = "POST";
}
var self = this;
// Request the remote document
jQuery.ajax({
url: url,
type: type,
data: params,
ifModified: ifModified,
complete: function(res, status){
// If successful, inject the HTML into all the matched elements
if ( status == "success" || !ifModified && status == "notmodified" )
self.html(res.responseText);
// Add delay to account for Safari's delay in globalEval
setTimeout(function(){
self.each( callback, [res.responseText, status, res] );
}, 13);
}
});
return this;
},
serialize: function() {
return jQuery.param( this );
},
// DEPRECATED
// This method no longer does anything - all script evaluation is
// taken care of within the HTML injection methods.
evalScripts: function(){}
});
// Attach a bunch of functions for handling common AJAX events
jQuery.each( "ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess,ajaxSend".split(","), function(i,o){
jQuery.fn[o] = function(f){
return this.bind(o, f);
};
});
jQuery.extend({
get: function( url, data, callback, type, ifModified ) {
// shift arguments if data argument was ommited
if ( jQuery.isFunction( data ) ) {
callback = data;
data = null;
}
return jQuery.ajax({
type: "GET",
url: url,
data: data,
success: callback,
dataType: type,
ifModified: ifModified
});
},
// DEPRECATED
getIfModified: function( url, data, callback, type ) {
return jQuery.get(url, data, callback, type, 1);
},
getScript: function( url, callback ) {
return jQuery.get(url, null, callback, "script");
},
getJSON: function( url, data, callback ) {
return jQuery.get(url, data, callback, "json");
},
post: function( url, data, callback, type ) {
if ( jQuery.isFunction( data ) ) {
callback = data;
data = {};
}
return jQuery.ajax({
type: "POST",
url: url,
data: data,
success: callback,
dataType: type
});
},
// DEPRECATED
ajaxTimeout: function( timeout ) {
jQuery.ajaxSettings.timeout = timeout;
},
ajaxSetup: function( settings ) {
jQuery.extend( jQuery.ajaxSettings, settings );
},
ajaxSettings: {
global: true,
type: "GET",
timeout: 0,
contentType: "application/x-www-form-urlencoded",
processData: true,
async: true,
data: null
},
// Last-Modified header cache for next request
lastModified: {},
ajax: function( s ) {
// Extend the settings, but re-extend 's' so that it can be
// checked again later (in the test suite, specifically)
s = jQuery.extend(true, s, jQuery.extend(true, {}, jQuery.ajaxSettings, s));
// if data available
if ( s.data ) {
// convert data if not already a string
if ( s.processData && typeof s.data != "string" )
s.data = jQuery.param(s.data);
// append data to url for get requests
if ( s.type.toLowerCase() == "get" ) {
// "?" + data or "&" + data (in case there are already params)
s.url += (s.url.indexOf("?") > -1 ? "&" : "?") + s.data;
// IE likes to send both get and post data, prevent this
s.data = null;
}
}
// Watch for a new set of requests
if ( s.global && ! jQuery.active++ )
jQuery.event.trigger( "ajaxStart" );
var requestDone = false;
// Create the request object; Microsoft failed to properly
// implement the XMLHttpRequest in IE7, so we use the ActiveXObject when it is available
var xml = window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
// Open the socket
xml.open(s.type, s.url, s.async);
// Set the correct header, if data is being sent
if ( s.data )
xml.setRequestHeader("Content-Type", s.contentType);
// Set the If-Modified-Since header, if ifModified mode.
if ( s.ifModified )
xml.setRequestHeader("If-Modified-Since",
jQuery.lastModified[s.url] || "Thu, 01 Jan 1970 00:00:00 GMT" );
// Set header so the called script knows that it's an XMLHttpRequest
xml.setRequestHeader("X-Requested-With", "XMLHttpRequest");
// Allow custom headers/mimetypes
if( s.beforeSend )
s.beforeSend(xml);
if ( s.global )
jQuery.event.trigger("ajaxSend", [xml, s]);
// Wait for a response to come back
var onreadystatechange = function(isTimeout){
// The transfer is complete and the data is available, or the request timed out
if ( !requestDone && xml && (xml.readyState == 4 || isTimeout == "timeout") ) {
requestDone = true;
// clear poll interval
if (ival) {
clearInterval(ival);
ival = null;
}
var status = isTimeout == "timeout" && "timeout" ||
!jQuery.httpSuccess( xml ) && "error" ||
s.ifModified && jQuery.httpNotModified( xml, s.url ) && "notmodified" ||
"success";
if ( status == "success" ) {
// Watch for, and catch, XML document parse errors
try {
// process the data (runs the xml through httpData regardless of callback)
var data = jQuery.httpData( xml, s.dataType );
} catch(e) {
status = "parsererror";
}
}
// Make sure that the request was successful or notmodified
if ( status == "success" ) {
// Cache Last-Modified header, if ifModified mode.
var modRes;
try {
modRes = xml.getResponseHeader("Last-Modified");
} catch(e) {} // swallow exception thrown by FF if header is not available
if ( s.ifModified && modRes )
jQuery.lastModified[s.url] = modRes;
// If a local callback was specified, fire it and pass it the data
if ( s.success )
s.success( data, status );
// Fire the global callback
if ( s.global )
jQuery.event.trigger( "ajaxSuccess", [xml, s] );
} else
jQuery.handleError(s, xml, status);
// The request was completed
if( s.global )
jQuery.event.trigger( "ajaxComplete", [xml, s] );
// Handle the global AJAX counter
if ( s.global && ! --jQuery.active )
jQuery.event.trigger( "ajaxStop" );
// Process result
if ( s.complete )
s.complete(xml, status);
// Stop memory leaks
if(s.async)
xml = null;
}
};
if ( s.async ) {
// don't attach the handler to the request, just poll it instead
var ival = setInterval(onreadystatechange, 13);
// Timeout checker
if ( s.timeout > 0 )
setTimeout(function(){
// Check to see if the request is still happening
if ( xml ) {
// Cancel the request
xml.abort();
if( !requestDone )
onreadystatechange( "timeout" );
}
}, s.timeout);
}
// Send the data
try {
xml.send(s.data);
} catch(e) {
jQuery.handleError(s, xml, null, e);
}
// firefox 1.5 doesn't fire statechange for sync requests
if ( !s.async )
onreadystatechange();
// return XMLHttpRequest to allow aborting the request etc.
return xml;
},
handleError: function( s, xml, status, e ) {
// If a local callback was specified, fire it
if ( s.error ) s.error( xml, status, e );
// Fire the global callback
if ( s.global )
jQuery.event.trigger( "ajaxError", [xml, s, e] );
},
// Counter for holding the number of active queries
active: 0,
// Determines if an XMLHttpRequest was successful or not
httpSuccess: function( r ) {
try {
return !r.status && location.protocol == "file:" ||
( r.status >= 200 && r.status < 300 ) || r.status == 304 ||
jQuery.browser.safari && r.status == undefined;
} catch(e){}
return false;
},
// Determines if an XMLHttpRequest returns NotModified
httpNotModified: function( xml, url ) {
try {
var xmlRes = xml.getResponseHeader("Last-Modified");
// Firefox always returns 200. check Last-Modified date
return xml.status == 304 || xmlRes == jQuery.lastModified[url] ||
jQuery.browser.safari && xml.status == undefined;
} catch(e){}
return false;
},
/* Get the data out of an XMLHttpRequest.
* Return parsed XML if content-type header is "xml" and type is "xml" or omitted,
* otherwise return plain text.
* (String) data - The type of data that you're expecting back,
* (e.g. "xml", "html", "script")
*/
httpData: function( r, type ) {
var ct = r.getResponseHeader("content-type");
var xml = type == "xml" || !type && ct && ct.indexOf("xml") >= 0;
data = xml ? r.responseXML : r.responseText;
if ( xml && data.documentElement.tagName == "parsererror" )
throw "parsererror";
// If the type is "script", eval it in global context
if ( type == "script" )
jQuery.globalEval( data );
// Get the JavaScript object, if JSON is used.
if ( type == "json" )
data = eval("(" + data + ")");
return data;
},
// Serialize an array of form elements or a set of
// key/values into a query string
param: function( a ) {
var s = [];
// If an array was passed in, assume that it is an array
// of form elements
if ( a.constructor == Array || a.jquery )
// Serialize the form elements
jQuery.each( a, function(){
s.push( encodeURIComponent(this.name) + "=" + encodeURIComponent( this.value ) );
});
// Otherwise, assume that it's an object of key/value pairs
else
// Serialize the key/values
for ( var j in a )
// If the value is an array then the key names need to be repeated
if ( a[j] && a[j].constructor == Array )
jQuery.each( a[j], function(){
s.push( encodeURIComponent(j) + "=" + encodeURIComponent( this ) );
});
else
s.push( encodeURIComponent(j) + "=" + encodeURIComponent( a[j] ) );
// Return the resulting serialization
return s.join("&");
}
});
jQuery.fn.extend({
show: function(speed,callback){
return speed ?
this.animate({
height: "show", width: "show", opacity: "show"
}, speed, callback) :
this.filter(":hidden").each(function(){
this.style.display = this.oldblock ? this.oldblock : "";
if ( jQuery.css(this,"display") == "none" )
this.style.display = "block";
}).end();
},
hide: function(speed,callback){
return speed ?
this.animate({
height: "hide", width: "hide", opacity: "hide"
}, speed, callback) :
this.filter(":visible").each(function(){
this.oldblock = this.oldblock || jQuery.css(this,"display");
if ( this.oldblock == "none" )
this.oldblock = "block";
this.style.display = "none";
}).end();
},
// Save the old toggle function
_toggle: jQuery.fn.toggle,
toggle: function( fn, fn2 ){
return jQuery.isFunction(fn) && jQuery.isFunction(fn2) ?
this._toggle( fn, fn2 ) :
fn ?
this.animate({
height: "toggle", width: "toggle", opacity: "toggle"
}, fn, fn2) :
this.each(function(){
jQuery(this)[ jQuery(this).is(":hidden") ? "show" : "hide" ]();
});
},
slideDown: function(speed,callback){
return this.animate({height: "show"}, speed, callback);
},
slideUp: function(speed,callback){
return this.animate({height: "hide"}, speed, callback);
},
slideToggle: function(speed, callback){
return this.animate({height: "toggle"}, speed, callback);
},
fadeIn: function(speed, callback){
return this.animate({opacity: "show"}, speed, callback);
},
fadeOut: function(speed, callback){
return this.animate({opacity: "hide"}, speed, callback);
},
fadeTo: function(speed,to,callback){
return this.animate({opacity: to}, speed, callback);
},
animate: function( prop, speed, easing, callback ) {
return this.queue(function(){
var hidden = jQuery(this).is(":hidden"),
opt = jQuery.speed(speed, easing, callback),
self = this;
for ( var p in prop ) {
if ( prop[p] == "hide" && hidden || prop[p] == "show" && !hidden )
return jQuery.isFunction(opt.complete) && opt.complete.apply(this);
if ( p == "height" || p == "width" ) {
// Store display property
opt.display = jQuery.css(this, "display");
// Make sure that nothing sneaks out
opt.overflow = this.style.overflow;
}
}
if ( opt.overflow != null )
this.style.overflow = "hidden";
this.curAnim = jQuery.extend({}, prop);
jQuery.each( prop, function(name, val){
var e = new jQuery.fx( self, opt, name );
if ( val.constructor == Number )
e.custom( e.cur() || 0, val );
else
e[ val == "toggle" ? hidden ? "show" : "hide" : val ]( prop );
});
// For JS strict compliance
return true;
});
},
queue: function(type,fn){
if ( !fn ) {
fn = type;
type = "fx";
}
return this.each(function(){
if ( !this.queue )
this.queue = {};
if ( !this.queue[type] )
this.queue[type] = [];
this.queue[type].push( fn );
if ( this.queue[type].length == 1 )
fn.apply(this);
});
}
});
jQuery.extend({
speed: function(speed, easing, fn) {
var opt = speed && speed.constructor == Object ? speed : {
complete: fn || !fn && easing ||
jQuery.isFunction( speed ) && speed,
duration: speed,
easing: fn && easing || easing && easing.constructor != Function && easing
};
opt.duration = (opt.duration && opt.duration.constructor == Number ?
opt.duration :
{ slow: 600, fast: 200 }[opt.duration]) || 400;
// Queueing
opt.old = opt.complete;
opt.complete = function(){
jQuery.dequeue(this, "fx");
if ( jQuery.isFunction( opt.old ) )
opt.old.apply( this );
};
return opt;
},
easing: {
linear: function( p, n, firstNum, diff ) {
return firstNum + diff * p;
},
swing: function( p, n, firstNum, diff ) {
return ((-Math.cos(p*Math.PI)/2) + 0.5) * diff + firstNum;
}
},
queue: {},
dequeue: function(elem,type){
type = type || "fx";
if ( elem.queue && elem.queue[type] ) {
// Remove self
elem.queue[type].shift();
// Get next function
var f = elem.queue[type][0];
if ( f ) f.apply( elem );
}
},
timers: [],
/*
* I originally wrote fx() as a clone of moo.fx and in the process
* of making it small in size the code became illegible to sane
* people. You've been warned.
*/
fx: function( elem, options, prop ){
var z = this;
// The styles
var y = elem.style;
// Simple function for setting a style value
z.a = function(){
if ( options.step )
options.step.apply( elem, [ z.now ] );
if ( prop == "opacity" )
jQuery.attr(y, "opacity", z.now); // Let attr handle opacity
else {
y[prop] = parseInt(z.now) + "px";
// Set display property to block for height/width animations
if ( prop == "height" || prop == "width" )
y.display = "block";
}
};
// Figure out the maximum number to run to
z.max = function(){
return parseFloat( jQuery.css(elem,prop) );
};
// Get the current size
z.cur = function(){
var r = parseFloat( jQuery.curCSS(elem, prop) );
return r && r > -10000 ? r : z.max();
};
// Start an animation from one number to another
z.custom = function(from,to){
z.startTime = (new Date()).getTime();
z.now = from;
z.a();
jQuery.timers.push(function(){
return z.step(from, to);
});
if ( jQuery.timers.length == 1 ) {
var timer = setInterval(function(){
var timers = jQuery.timers;
for ( var i = 0; i < timers.length; i++ )
if ( !timers[i]() )
timers.splice(i--, 1);
if ( !timers.length )
clearInterval( timer );
}, 13);
}
};
// Simple 'show' function
z.show = function(){
if ( !elem.orig ) elem.orig = {};
// Remember where we started, so that we can go back to it later
elem.orig[prop] = jQuery.attr( elem.style, prop );
options.show = true;
// Begin the animation
z.custom(0, this.cur());
// Make sure that we start at a small width/height to avoid any
// flash of content
if ( prop != "opacity" )
y[prop] = "1px";
// Start by showing the element
jQuery(elem).show();
};
// Simple 'hide' function
z.hide = function(){
if ( !elem.orig ) elem.orig = {};
// Remember where we started, so that we can go back to it later
elem.orig[prop] = jQuery.attr( elem.style, prop );
options.hide = true;
// Begin the animation
z.custom(this.cur(), 0);
};
// Each step of an animation
z.step = function(firstNum, lastNum){
var t = (new Date()).getTime();
if (t > options.duration + z.startTime) {
z.now = lastNum;
z.a();
if (elem.curAnim) elem.curAnim[ prop ] = true;
var done = true;
for ( var i in elem.curAnim )
if ( elem.curAnim[i] !== true )
done = false;
if ( done ) {
if ( options.display != null ) {
// Reset the overflow
y.overflow = options.overflow;
// Reset the display
y.display = options.display;
if ( jQuery.css(elem, "display") == "none" )
y.display = "block";
}
// Hide the element if the "hide" operation was done
if ( options.hide )
y.display = "none";
// Reset the properties, if the item has been hidden or shown
if ( options.hide || options.show )
for ( var p in elem.curAnim )
jQuery.attr(y, p, elem.orig[p]);
}
// If a callback was provided, execute it
if ( done && jQuery.isFunction( options.complete ) )
// Execute the complete function
options.complete.apply( elem );
return false;
} else {
var n = t - this.startTime;
// Figure out where in the animation we are and set the number
var p = n / options.duration;
// Perform the easing function, defaults to swing
z.now = jQuery.easing[options.easing || (jQuery.easing.swing ? "swing" : "linear")](p, n, firstNum, (lastNum-firstNum), options.duration);
// Perform the next step of the animation
z.a();
}
return true;
};
}
});
})();
| stserp/erp1 | source/web/por2/js/jquery.js | JavaScript | apache-2.0 | 67,358 |
/* jshint
funcscope: true,
newcap: true,
nonew: true,
shadow: false,
unused: true,
maxlen: 90,
maxstatements: 200
*/
/* global $ */
'use strict';
var markup = require('./NetSimDnsModeControl.html');
/**
* Generator and controller for DNS mode selector
* @param {jQuery} rootDiv
* @param {function} dnsModeChangeCallback
* @constructor
*/
var NetSimDnsModeControl = module.exports = function (rootDiv,
dnsModeChangeCallback) {
/**
* Component root, which we fill whenever we call render()
* @type {jQuery}
* @private
*/
this.rootDiv_ = rootDiv;
/**
* @type {function}
* @private
*/
this.dnsModeChangeCallback_ = dnsModeChangeCallback;
/**
* Set of all DNS mode radio buttons
* @type {jQuery}
* @private
*/
this.dnsModeRadios_ = null;
/**
* Internal state: Current DNS mode.
* @type {string}
* @private
*/
this.currentDnsMode_ = 'none';
this.render();
};
/**
* Fill the root div with new elements reflecting the current state
*/
NetSimDnsModeControl.prototype.render = function () {
var renderedMarkup = $(markup({}));
this.rootDiv_.html(renderedMarkup);
this.dnsModeRadios_ = this.rootDiv_.find('input[type="radio"][name="dns_mode"]');
this.dnsModeRadios_.change(this.onDnsModeChange_.bind(this));
this.setDnsMode(this.currentDnsMode_);
};
/**
* Handler for a new radio button being selected.
* @private
*/
NetSimDnsModeControl.prototype.onDnsModeChange_ = function () {
var newDnsMode = this.dnsModeRadios_.siblings(':checked').val();
this.dnsModeChangeCallback_(newDnsMode);
};
/**
* @param {string} newDnsMode
*/
NetSimDnsModeControl.prototype.setDnsMode = function (newDnsMode) {
this.currentDnsMode_ = newDnsMode;
this.dnsModeRadios_
.siblings('[value="' + newDnsMode + '"]')
.prop('checked', true);
};
| bakerfranke/code-dot-org | apps/src/netsim/NetSimDnsModeControl.js | JavaScript | apache-2.0 | 1,835 |
/*
* @flow
*/
import type { Child } from '../../stats/getEntryHierarchy';
import * as React from 'react';
export type Props = {|
parentChunks: Array<Child>,
totalModules: number,
|};
export default function ChunkBreadcrumb(props: Props) {
if (props.parentChunks.length === 0) {
return null;
}
return (
<ol className="breadcrumb">
{props.parentChunks.map((chunk) => (
<li className="breadcrumb-item" key={chunk.id}>
{chunk.name} ({String(chunk.id)})
</li>
))}
{props.totalModules
? <li className="breadcrumb-item active">
{props.totalModules} modules
</li>
: null}
</ol>
);
}
| pinterest/bonsai | src/components/stats/ChunkBreadcrumb.js | JavaScript | apache-2.0 | 683 |
/*describe ('UI testing with mockup', function() {
beforeEach(function() {
});
});*/
(function() {
'use strict';
describe('initial tests', function() {
beforeEach(function() {
browser.get('http://pipeline-dev.deleidos.com');
});
it('Title present: indicates website is functional', function() {
/*var page = require('webpage').create();
page.open('http://pipeline-dev.deleidos.com', function () {
var title = page.evaluate(function () {
return document.title;
});
expect(title).toEqual('DigitalEdge Pipeline Tool');*/
expect(browser.getTitle()).toEqual('DigitalEdge Pipeline Tool');
//});
});
it('Operators present: indicates data service and Mongo are functional', function() {
var opList = element.all(by.repeater('opType in displayList'));
expect(opList.count()).toBeGreaterThan(0);
});
it('Systems present: indicates Hadoop is working right', function() {
var sysList = element.all(by.repeater('(index, system) in systems'));
expect(sysList.count()).toBeGreaterThan(0);
});
/* it('operators should be present', function() {
var ops = element.all(by.repeater('operator in opType.operators'));
expect(ops.count()).toBeGreaterThan(0);
});
*/
//element(by.model('searchOp.display_name')).sendKeys('output');
//element(by.operatorButton('Input')).click();
//element(by.cssContainingText('.ng-binding', 'Input')).click();
/*element.all(by.css('md-select')).each(function (eachElement, index) {
eachElement.click(); //select the select
browser.driver.sleep(500); //wait for the renderings to take effect
element(by.css('md-option')).click(); //select the first md-option
browser.driver.sleep(500); //wait for the renderings to take effect
});*/
//expect(ops.count()).toBe(4);
/*var button = browser.findElement(by.cssContainingText('.md-tab', 'Input'));
button.click();*/
});
/*
describe('Protractor Demo App', function() {
var firstNumber = element(by.model('first'));
var secondNumber = element(by.model('second'));
var goButton = element(by.id('gobutton'));
var latestResult = element(by.binding('latest'));
var history = element.all(by.repeater('result in memory'));
function add(a, b) {
firstNumber.sendKeys(a);
secondNumber.sendKeys(b);
goButton.click();
}
beforeEach(function() {
browser.get('http://juliemr.github.io/protractor-demo/');
});
it('should have a history', function() {
add(1, 2);
add(3, 4);
expect(history.count()).toEqual(2);
add(5, 6);
console.log(history.count());
expect(history.count()).toEqual(0); // This is wrong!
});
});
*/
}());
| deleidos/de-pipeline-tool | de-ui-system-tools/app/tests/test.js | JavaScript | apache-2.0 | 3,052 |
/**
* @license Copyright 2017 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
'use strict';
const MultiCheckAudit = require('./multi-check-audit.js');
const ManifestValues = require('../computed/manifest-values.js');
const i18n = require('../lib/i18n/i18n.js');
const UIStrings = {
/** Title of a Lighthouse audit that provides detail on splash screens. This descriptive title is shown to users when the site has a custom splash screen. */
title: 'Configured for a custom splash screen',
/** Title of a Lighthouse audit that provides detail on splash screens. This descriptive title is shown to users when the site does not have a custom splash screen. */
failureTitle: 'Is not configured for a custom splash screen',
/** Description of a Lighthouse audit that tells the user why they should configure a custom splash screen. This is displayed after a user expands the section to see more. No character length limits. 'Learn More' becomes link text to additional documentation. */
description: 'A themed splash screen ensures a high-quality experience when ' +
'users launch your app from their homescreens. [Learn ' +
'more](https://web.dev/splash-screen).',
};
const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings);
/**
* @fileoverview
* Audits if a page is configured for a custom splash screen when launched
* https://github.com/GoogleChrome/lighthouse/issues/24
*
* Requirements:
* * manifest is not empty
* * manifest has a valid name
* * manifest has a valid background_color
* * manifest has a valid theme_color
* * manifest contains icon that's a png and size >= 512px
*/
class SplashScreen extends MultiCheckAudit {
/**
* @return {LH.Audit.Meta}
*/
static get meta() {
return {
id: 'splash-screen',
title: str_(UIStrings.title),
failureTitle: str_(UIStrings.failureTitle),
description: str_(UIStrings.description),
requiredArtifacts: ['WebAppManifest'],
};
}
/**
* @param {LH.Artifacts.ManifestValues} manifestValues
* @param {Array<string>} failures
*/
static assessManifest(manifestValues, failures) {
if (manifestValues.isParseFailure && manifestValues.parseFailureReason) {
failures.push(manifestValues.parseFailureReason);
return;
}
const splashScreenCheckIds = [
'hasName',
'hasBackgroundColor',
'hasThemeColor',
'hasIconsAtLeast512px',
];
manifestValues.allChecks
.filter(item => splashScreenCheckIds.includes(item.id))
.forEach(item => {
if (!item.passing) {
failures.push(item.failureText);
}
});
}
/**
* @param {LH.Artifacts} artifacts
* @param {LH.Audit.Context} context
* @return {Promise<{failures: Array<string>, manifestValues: LH.Artifacts.ManifestValues}>}
*/
static async audit_(artifacts, context) {
/** @type {Array<string>} */
const failures = [];
const manifestValues = await ManifestValues.request(artifacts.WebAppManifest, context);
SplashScreen.assessManifest(manifestValues, failures);
return {
failures,
manifestValues,
};
}
}
module.exports = SplashScreen;
module.exports.UIStrings = UIStrings;
| wardpeet/lighthouse | lighthouse-core/audits/splash-screen.js | JavaScript | apache-2.0 | 3,732 |
import React from "react";
import Router from "react-router";
import routes from "./routes.js";
var Application = {};
Application.run = function runApplication() {
Router.run(routes, function (Handler) {
React.render(<Handler/>, document.body);
});
};
export default Application;
| manuel-woelker/agendarium | ui/src/chrome/Application.js | JavaScript | apache-2.0 | 288 |
// test the main app file
//
// Copyright 2017 AJ Jordan
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
require("./lib/hostname");
var vows = require("perjury"),
assert = vows.assert,
_ = require("underscore"),
defaults = require("../lib/defaults");
vows.describe("app module").addBatch({
"When we require the module": {
topic: function() {
return require("../lib/app");
},
"it works": function(err) {
assert.ifError(err);
},
"it exports a makeApp() function": function(err, makeApp) {
assert.isFunction(makeApp);
},
"and we call makeApp()": {
topic: function(makeApp) {
return makeApp(_.defaults({port: 15180}, defaults));
},
"it works": function(err) {
assert.ifError(err);
},
"we get back an Express app": function(err, app) {
assert.isObject(app);
},
"the Express app has a start() method": function(err, app) {
assert.isFunction(app.start);
},
"and we call app.start()": {
topic: function(app) {
app.start(this.callback);
},
teardown: function(app) {
if (app.server && app.server.close) {
app.server.close(this.callback);
}
},
"it works": function(err) {
assert.ifError(err);
},
"we get back an app server object": function(err, appServer) {
assert.isObject(appServer);
assert.isFunction(appServer.listen);
}
}
}
}
}).export(module);
| e14n/ofirehose | test/app-test.js | JavaScript | apache-2.0 | 1,906 |
'use strict';
/* Some browsers and PhantomJS don't support bind, mozilla provides
* this implementation as a monkey patch on Function.prototype
*
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FFunction%2Fbind
*/
if (!Function.prototype.bind) {
Function.prototype.bind = function (oThis) {
if (typeof this !== 'function') {
// closest thing possible to the ECMAScript 5 internal IsCallable function
throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable');
}
var aArgs = Array.prototype.slice.call(arguments, 1),
fToBind = this,
FNOP = function () {},
fBound = function () {
return fToBind.apply(this instanceof FNOP && oThis ? this
: oThis,
aArgs.concat(Array.prototype.slice.call(arguments)));
};
FNOP.prototype = this.prototype;
fBound.prototype = new FNOP();
return fBound;
};
}
| o19s/splainer-search | services/bind.js | JavaScript | apache-2.0 | 1,095 |
function Ranger(pin) {
var self = this;
self.signal = pin;
return {
getDistance: function(callback) {
self.signal.output(1);
setTimeout(function() {
self.signal.rawWrite(0);
}, 10);
self.signal.readPulse('high', 1000, function(err, duration) {
if (err) {
callback(err, 0);
return;
}
var distance = ((duration * 1000) / 2) / 29.1;
callback(null, distance);
});
}
};
}
function use(pin) {
var ranger = new Ranger(pin);
return ranger;
}
exports.use = use;
| mitchdenny/tessel-sen10737p | index.js | JavaScript | apache-2.0 | 570 |
/**
* @license
* Copyright 2013 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
/**
* @fileoverview Common support code for games that embed Ace.
* @author fraser@google.com (Neil Fraser)
*/
'use strict';
goog.provide('BlocklyAce');
goog.require('BlocklyInterface');
/**
* Load the Babel transpiler.
* Defer loading until page is loaded and responsive.
*/
BlocklyAce.importBabel = function() {
function load() {
//<script type="text/javascript"
// src="third-party/babel.min.js"></script>
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'third-party/babel.min.js';
document.head.appendChild(script);
}
setTimeout(load, 1);
};
/**
* Attempt to transpile user code to ES5.
* @param {string} code User code that may contain ES6+ syntax.
* @return {string|undefined} ES5 code, or undefined if Babel not loaded.
* @throws SyntaxError if code is unparsable.
*/
BlocklyAce.transpileToEs5 = function(code) {
if (typeof Babel != 'object') {
return undefined;
}
var options = {
'presets': ['es2015']
};
var fish = Babel.transform(code, options);
return fish.code;
};
/**
* Create an ACE editor, and return the session object.
* @return {!Object} ACE session object
*/
BlocklyAce.makeAceSession = function() {
var ace = window['ace'];
ace['require']('ace/ext/language_tools');
var editor = ace['edit']('editor');
BlocklyInterface.editor = editor;
editor['setTheme']('ace/theme/chrome');
editor['setShowPrintMargin'](false);
editor['setOptions']({
'enableBasicAutocompletion': true,
'enableLiveAutocompletion': true
});
var session = editor['getSession']();
session['setMode']('ace/mode/javascript');
session['setTabSize'](2);
session['setUseSoftTabs'](true);
session['on']('change', BlocklyInterface.codeChanged);
BlocklyAce.removeUnsupportedKeywords_();
return session;
};
/**
* Remove keywords not supported by the JS-Interpreter.
* This trims out bogus entries in the autocomplete.
* @private
*/
BlocklyAce.removeUnsupportedKeywords_ = function() {
var keywords = BlocklyInterface.editor['getSession']()['getMode']()['$highlightRules']['$keywordList'];
if (keywords) {
keywords.splice(0, Infinity, 'arguments', 'this', 'NaN', 'Math', 'JSON',
'parseInt', 'parseFloat', 'isNaN', 'isFinite', 'eval', 'String',
'RegExp', 'Object', 'Number', 'Function', 'Date', 'Boolean', 'Array',
'while', 'var', 'let', 'typeof', 'try', 'throw', 'switch', 'return',
'new', 'instanceof', 'of', 'in', 'if', 'function', 'for', 'finally',
'else', 'do', 'delete', 'continue', 'catch', 'case', 'break', 'const',
'undefined', 'Infinity', 'null', 'false', 'true');
} else {
// Keyword list doesn't appear until after the JS mode is loaded.
// Keep polling until it shows up.
setTimeout(BlocklyAce.removeUnsupportedKeywords_,
BlocklyAce.removeUnsupportedKeywords_.delay_ *= 2);
}
};
/**
* Exponential back-off for polling. Start at 1ms.
* @private
*/
BlocklyAce.removeUnsupportedKeywords_.delay_ = 1;
| google/blockly-games | appengine/js/lib-ace.js | JavaScript | apache-2.0 | 3,117 |
//定义中文消息
jQuery.extend(jQuery.validator.messages, {
required: "必需填写项",
remote: "内容输入错误!",
email: "E-mail格式错误,请重新输入!",
url: "网址格式错误,请重新输入!",
date: "日期格式错误,请重新输入!",
dateISO: "日期格式错误,请重新输入!",
number: "请输入合法的数字!",
digits: "请输入零或正整数!",
creditcard: "信用卡号格式错误,请重新输入!",
equalTo: "两次输入不一致,请重新输入!",
accept: "请输入拥有合法后缀名的字符串!",
maxlength: jQuery.validator.format("字符串长度不能大于{0}!"),
minlength: jQuery.validator.format("字符串长度不能小于{0}!"),
rangelength: jQuery.validator.format("字符串长度只允许在{0}-{1}之间!"),
range: jQuery.validator.format("输入的数值只允许在{0}-{1}之间!"),
max: jQuery.validator.format("输入的数值不允许大于{0}!"),
min: jQuery.validator.format("输入的数值不允许小于{0}!"),
integer: "请输入合法的整数!",
positive: "请输入合法的正数!",
positiveInteger: "请输入合法的正整数!",
mobile: "手机号码格式错误,请重新输入!",
phone: "电话号码格式错误,请重新输入!",
zipCode: "邮政编码格式错误,请重新输入!",
requiredTo: "此内容为必填项,请输入!",
username: "只允许包含中文、英文、数字和下划线!",
prefix: "请输入以 {0} 开头的字符串!",
lettersonly: "只允许包含字母!"
/*
required: "必需填写项",
remote: "请修正该字段",
email: "请输入正确格式的电子邮件",
url: "请输入合法的网址",
date: "请输入合法的日期",
dateISO: "请输入合法的日期 (ISO).",
number: "请输入合法的数字",
digits: "只能输入整数",
creditcard: "请输入合法的信用卡号",
equalTo: "请再次输入相同的值",
accept: "请输入拥有合法后缀名的字符串",
maxlength: jQuery.format("请输入一个长度最多是 {0} 的字符串"),
minlength: jQuery.format("请输入一个长度最少是 {0} 的字符串"),
rangelength: jQuery.format("请输入一个长度介于 {0} 和 {1} 之间的字符串"),
range: jQuery.format("请输入一个介于 {0} 和 {1} 之间的值"),
max: jQuery.format("请输入一个最大为 {0} 的值"),
min: jQuery.format("请输入一个最小为 {0} 的值"),
//自定义验证方法的提示信息
stringCheck: "用户名只能包括中文字、英文字母、数字和下划线",
byteRangeLength: "用户名必须在4-15个字符之间(一个中文字算2个字符)",
isIdCardNo: "请正确输入您的身份证号码"*/
});
/*
var cnmsg = {
required: "必需填写项",
remote: "请修正该字段",
email: "请输入正确格式的电子邮件",
url: "请输入合法的网址",
date: "请输入合法的日期",
dateISO: "请输入合法的日期 (ISO).",
number: "请输入合法的数字",
digits: "只能输入整数",
creditcard: "请输入合法的信用卡号",
equalTo: "请再次输入相同的值",
accept: "请输入拥有合法后缀名的字符串",
maxlength: jQuery.format("请输入一个长度最多是 {0} 的字符串"),
minlength: jQuery.format("请输入一个长度最少是 {0} 的字符串"),
rangelength: jQuery.format("请输入一个长度介于 {0} 和 {1} 之间的字符串"),
range: jQuery.format("请输入一个介于 {0} 和 {1} 之间的值"),
max: jQuery.format("请输入一个最大为 {0} 的值"),
min: jQuery.format("请输入一个最小为 {0} 的值"),
//自定义验证方法的提示信息
stringCheck: "用户名只能包括中文字、英文字母、数字和下划线",
byteRangeLength: "用户名必须在4-15个字符之间(一个中文字算2个字符)",
isIdCardNo: "请正确输入您的身份证号码",
};
jQuery.extend(jQuery.validator.messages, cnmsg);
*/
//字符验证
jQuery.validator.addMethod("stringCheck", function(value, element) {
return this.optional(element) || /^[\u0391-\uFFE5\w]+$/.test(value);
}, "只能包括中文字、英文字母、数字和下划线");
// 中文字两个字节
jQuery.validator.addMethod("byteRangeLength", function(value, element, param) {
var length = value.length;
for(var i = 0; i < value.length; i++){
if(value.charCodeAt(i) > 127){
length++;
}
}
return this.optional(element) || ( length >= param[0] && length <= param[1] );
}, "请确保输入的值在4-15个字节之间(一个中文字算2个字节)");
// 身份证号码验证
jQuery.validator.addMethod("isIdCardNo", function(value, element) {
return this.optional(element) || isIdCardNo(value);
}, "请正确输入您的18位身份证号码");
//身份证号码验证
jQuery.validator.addMethod("isMobileNo", function(value, element) {
return this.optional(element) || isMobileNo(value);
}, "请正确输入您的11位手机号码");
/**
* 身份证号码验证
*/
function isIdCardNo(num) {
var factorArr = new Array(7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2,1);
var parityBit=new Array("1","0","X","9","8","7","6","5","4","3","2");
var varArray = new Array();
var intValue;
var lngProduct = 0;
var intCheckDigit;
var intStrLen = num.length;
var idNumber = num;
// initialize
if ((intStrLen != 15) && (intStrLen != 18)) {
return false;
}
// check and set value
for(i=0;i<intStrLen;i++) {
varArray[i] = idNumber.charAt(i);
if ((varArray[i] < '0' || varArray[i] > '9') && (i != 17)) {
return false;
} else if (i < 17) {
varArray[i] = varArray[i] * factorArr[i];
}
}
if (intStrLen == 18) {
//check date
var date8 = idNumber.substring(6,14);
if (isDate8(date8) == false) {
return false;
}
// calculate the sum of the products
for(i=0;i<17;i++) {
lngProduct = lngProduct + varArray[i];
}
// calculate the check digit
intCheckDigit = parityBit[lngProduct % 11];
// check last digit
if (varArray[17] != intCheckDigit) {
return false;
}
}
else{ //length is 15
//check date
var date6 = idNumber.substring(6,12);
if (isDate6(date6) == false) {
return false;
}
}
return true;
}
/*
function isMobileNo(mobile)
{
if(mobile.length==0)
{
alert('请输入手机号码!');
document.form1.mobile.focus();
return false;
}
if(mobile.length!=11)
{
alert('请输入有效的手机号码!');
document.form1.mobile.focus();
return false;
}
var myreg = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\d{8})$/;
if(!myreg.test(mobile))
{
alert('请输入有效的手机号码!');
document.form1.mobile.focus();
return false;
}
} */
function isMobileNo(num) {
var intStrLen = num.length;
var idNumber = num;
// initialize
if ((intStrLen != 11) ) {
return false;
}
var myreg = /^(((13[0-9]{1})|159|153)+\d{8})$/;
if(!myreg.test(idNumber))
{
// alert('请输入有效的手机号码!');
// document.form1.mobile.focus();
return false;
}
// if (!$("#mobile").val().match(/^(((13[0-9]{1})|159|153)+\d{8})$/))
return true;
}
//电话号码检查
function isPhone(e, obj) {
phone = e.value;
if (phone != "" && phone.length < 3) {
$inval.outerror(e.name, '' + e.realname + '至少为3位!');
return false;
}
hasNumericChar = true;
for (i = 0; i < phone.length; i++) {
if ((phone.charAt(i) < '0' || phone.charAt(i) > '9') && phone.charAt(i) != '-'
&& phone.charAt(i) != ')'
&& phone.charAt(i) != '(') {
$inval.outerror(e.name, e.realname + "只能由数字和'-,(,)'构成!");
return false;
}
if (hasNumericChar && phone.charAt(i) > '0' && phone.charAt(i) < '9')
hasNumericChar = false;
if (hasNumericChar && (i >= phone.length - 1)) {
$inval.outerror(e.name, e.realname + "只能由数字和'-,(,)'构成!");
return false;
}
}
return true;
}
//手机号码检查
function isIdCardNo2(num) {
phone = num;
if (phone != "" && phone.length < 11) {
// $inval.outerror(e.name, '' + e.realname + '至少为11位,请重新输入!');
return false;
}
hasNumericChar = true;
for (i = 0; i < phone.length; i++) {
if (phone.charAt(i) < '0' || phone.charAt(i) > '9') {
// $inval.outerror(e.name, '' + e.realname + '只能由数字组成,请重新输入!');
return false;
}
if (hasNumericChar && phone.charAt(i) > '0' && phone.charAt(i) < '9')
hasNumericChar = false;
if (hasNumericChar && (i >= phone.length - 1)) {
// $inval.outerror(e.name, '' + e.realname + '只能由数字组成,请重新输入!');
return false;
}
}
return true;
} | neckhyg/dataChart | renren-web/src/main/webapp/czit/Scripts/jquery.validate.message_cn.js | JavaScript | apache-2.0 | 9,746 |
(function() {
'use strict';
var el = d3.select('.timeseries'),
elWidth = parseInt(el.style('width'), 10),
elHeight = parseInt(el.style('height'), 10),
margin = {top: 20, right: 20, bottom: 30, left: 50},
width = elWidth - margin.left - margin.right,
height = elHeight - margin.top - margin.bottom;
var svg = el.append("svg")
.attr("width", elWidth)
.attr("height", elHeight)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
d3.json("/data/timeseries.json", function(error, data) {
if (error) throw error;
visualize(data);
});
function visualize(data) {
// code here
}
}());
| victormejia/d3-workshop-playground | modules/pageviews/timeseries.js | JavaScript | apache-2.0 | 692 |
/* global ga */
import React, {Component, PropTypes} from 'react';
import {Grid, Well, Col, Row} from 'react-bootstrap';
import PerLetter from './viz/perLetterContainer';
import NameLength from './viz/nameLengthContainer';
import Filter from './filter/filterContainer';
import TextComponent from './TextComponent/textContainer';
export default class mainComponent extends Component {
componentDidMount() {
if (document.location.hostname !== 'localhost') {
ga('send', 'pageview', '/dogs');
}
const {getRaw, dispatch} = this.props;
getRaw()(dispatch);
}
render() {
return (<Grid fluid>
<h1>Dog Names in Zurich - a showcase</h1>
<h2>a.k.a. why do we need d3-react-squared?</h2>
<small><a target={'_blank'}
href={'https://data.stadt-zuerich.ch/dataset/' +
'pd-stapo-hundenamen/' +
'resource/11207c68-fc9f-4883-a2ef-3b4a60dd048a'}>Source: Open Data Zurich</a>
{' '}
<a target={'_blank'} href={'http://www.opendefinition.org/licenses/cc-zero'}>(under CC-Zero)</a>
</small>
<Well bsSize={'small'}>
<h3>Note/Disclaimer:</h3>
This page is to demonstrate a use-case
for <a target={'_blank'}
href={'https://github.com/bgrsquared/d3-react-squared'}>d3-react-squared</a>.
<br/>
<ul>
<li>
<a target={'_blank'}
href={'https://medium.com/@ilikepiecharts/about-using-d3-react-squared-an-example-8cc5e5a6b58e#.jso6use4q'}>
MEDIUM Blog Post</a>
</li>
<li>
<a target={'_blank'}
href={'https://github.com/bgrsquared/d3-react-squared'}>d3-react-squared on github</a>
</li>
<li>
<a target={'_blank'}
href={'https://github.com/bgrsquared/d3-react-squared-dogs-blog'}>
this page (source) on github</a>
</li>
</ul>
The graphs are just examples and by no means useful regarding the information presented
(or the way it is presented).
d3-react squared was designed to link charts, information, events.
</Well>
<Row>
<Col xs={6} md={5} lg={4}>
<Well bsSize={'small'}><Filter/></Well>
</Col>
<Col xs={6} md={7} lg={8}>
<TextComponent/>
</Col>
</Row>
<Row>
<Col xs={12} md={6}>
<PerLetter/>
</Col>
<Col xs={12} md={6}>
<NameLength/>
</Col>
</Row>
</Grid>);
}
}
mainComponent.propTypes = {
dispatch: PropTypes.func.isRequired,
dogData: PropTypes.object.isRequired,
getRaw: PropTypes.func.isRequired,
};
| webmaster444/webmaster444.github.io | react/squared_dogs_blog/app/GUI/mainComponent.js | JavaScript | apache-2.0 | 2,695 |
// @flow
import _ from 'lodash';
import { getCurrentConference } from '../base/conference';
import { toState } from '../base/redux';
import { FEATURE_KEY } from './constants';
/**
* Returns the rooms object for breakout rooms.
*
* @param {Function|Object} stateful - The redux store, the redux
* {@code getState} function, or the redux state itself.
* @returns {Object} Object of rooms.
*/
export const getBreakoutRooms = (stateful: Function | Object) => toState(stateful)[FEATURE_KEY].rooms;
/**
* Returns the main room.
*
* @param {Function|Object} stateful - The redux store, the redux
* {@code getState} function, or the redux state itself.
* @returns {Object|undefined} The main room object, or undefined.
*/
export const getMainRoom = (stateful: Function | Object) => {
const rooms = getBreakoutRooms(stateful);
return _.find(rooms, (room: Object) => room.isMainRoom);
};
/**
* Returns the room by Jid.
*
* @param {Function|Object} stateful - The redux store, the redux
* {@code getState} function, or the redux state itself.
* @param {string} roomJid - The jid of the room.
* @returns {Object|undefined} The main room object, or undefined.
*/
export const getRoomByJid = (stateful: Function | Object, roomJid: string): Object => {
const rooms = getBreakoutRooms(stateful);
return _.find(rooms, (room: Object) => room.jid === roomJid);
};
/**
* Returns the id of the current room.
*
* @param {Function|Object} stateful - The redux store, the redux
* {@code getState} function, or the redux state itself.
* @returns {string} Room id or undefined.
*/
export const getCurrentRoomId = (stateful: Function | Object) => {
const conference = getCurrentConference(stateful);
// $FlowExpectedError
return conference?.getName();
};
/**
* Determines whether the local participant is in a breakout room.
*
* @param {Function|Object} stateful - The redux store, the redux
* {@code getState} function, or the redux state itself.
* @returns {boolean}
*/
export const isInBreakoutRoom = (stateful: Function | Object) => {
const conference = getCurrentConference(stateful);
// $FlowExpectedError
return conference?.getBreakoutRooms()
?.isBreakoutRoom();
};
/**
* Returns the breakout rooms config.
*
* @param {Function|Object} stateful - The redux store, the redux
* {@code getState} function, or the redux state itself.
* @returns {Object}
*/
export const getBreakoutRoomsConfig = (stateful: Function | Object) => {
const state = toState(stateful);
const { breakoutRooms = {} } = state['features/base/config'];
return breakoutRooms;
};
| jitsi/jitsi-meet | react/features/breakout-rooms/functions.js | JavaScript | apache-2.0 | 2,637 |
/**
*
* Copyright 2017 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const express = require('express');
const downloads = express();
const path = require('path');
const adaro = require('adaro');
const helpersPath = path.join(__dirname, '..', 'helpers');
const viewPath = path.join(__dirname, '..', '..', 'views');
const packageReader = require('../utils/package-reader');
const version = packageReader.getVersion();
const dustOptions = {
cache: false,
whitespace: true,
helpers: [
require(`${helpersPath}/hash`)
]
};
const defaultViewOptions = {
title: 'LeFlux - Downloads',
version,
scripts: [
'dist/client/scripts/app.js',
'dist/client/scripts/downloads.js'
]
};
if (process.env.NODE_ENV === 'production') {
dustOptions.cache = true;
dustOptions.whitespace = false;
console.log('[App: Downloads] Templating is cached.');
}
downloads.engine('dust', adaro.dust(dustOptions));
downloads.set('view engine', 'dust');
downloads.set('views', viewPath);
downloads.use(require('../middleware/no-cache.js'));
downloads.get('/', (req, res) => {
const viewOptions = Object.assign({}, defaultViewOptions, {
css: [
'dist/client/styles/leflux.css'
],
colors: {
primary: {
r: 171, g: 247, b: 226
},
primaryLight: {
r: 218, g: 242, b: 245
},
secondary: {
r: 25, g: 213, b: 185
},
tertiary: {
r: 59, g: 85, b: 94
},
quaternary: {
r: 36, g: 52, b: 57
}
}
});
res.status(200).render('downloads', viewOptions);
});
console.log('[App: Downloads] initialized.');
module.exports = downloads;
| leflux/leflux | src/server/apps/downloads.js | JavaScript | apache-2.0 | 2,194 |
/* xlsx.js (C) 2013-present SheetJS -- http://sheetjs.com */
/* vim: set ts=2: */
/*exported XLSX */
/*global global, exports, module, require:false, process:false, Buffer:false */
var XLSX = {};
(function make_xlsx(XLSX){
| iCasa/js-xlsx | bits/00_header.js | JavaScript | apache-2.0 | 223 |
/**
* @file timeline.js
*
* @brief
* The Timeline is an interactive visualization chart to visualize events in
* time, having a start and end date.
* You can freely move and zoom in the timeline by dragging
* and scrolling in the Timeline. Items are optionally dragable. The time
* scale on the axis is adjusted automatically, and supports scales ranging
* from milliseconds to years.
*
* Timeline is part of the CHAP Links library.
*
* Timeline is tested on Firefox 3.6, Safari 5.0, Chrome 6.0, Opera 10.6, and
* Internet Explorer 6+.
*
* @license
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*
* Copyright (c) 2011-2012 Almende B.V.
*
* @author Jos de Jong, <jos@almende.org>
* @date 2012-11-02
* @version 2.4.1
*/
/*
* TODO
*
* Add zooming with pinching on Android
*
* Bug: when an item contains a javascript onclick or a link, this does not work
* when the item is not selected (when the item is being selected,
* it is redrawn, which cancels any onclick or link action)
* Bug: when an item contains an image without size, or a css max-width, it is not sized correctly
* Bug: neglect items when they have no valid start/end, instead of throwing an error
* Bug: Pinching on ipad does not work very well, sometimes the page will zoom when pinching vertically
* Bug: cannot set max width for an item, like div.timeline-event-content {white-space: normal; max-width: 100px;}
* Bug on IE in Quirks mode. When you have groups, and delete an item, the groups become invisible
*/
/**
* Declare a unique namespace for CHAP's Common Hybrid Visualisation Library,
* "links"
*/
if (typeof links === 'undefined') {
links = {};
// important: do not use var, as "var links = {};" will overwrite
// the existing links variable value with undefined in IE8, IE7.
}
/**
* Ensure the variable google exists
*/
if (typeof google === 'undefined') {
google = undefined;
// important: do not use var, as "var google = undefined;" will overwrite
// the existing google variable value with undefined in IE8, IE7.
}
// Internet Explorer 8 and older does not support Array.indexOf,
// so we define it here in that case
// http://soledadpenades.com/2007/05/17/arrayindexof-in-internet-explorer/
if(!Array.prototype.indexOf) {
Array.prototype.indexOf = function(obj){
for(var i = 0; i < this.length; i++){
if(this[i] == obj){
return i;
}
}
return -1;
}
}
// Internet Explorer 8 and older does not support Array.forEach,
// so we define it here in that case
// https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/forEach
if (!Array.prototype.forEach) {
Array.prototype.forEach = function(fn, scope) {
for(var i = 0, len = this.length; i < len; ++i) {
fn.call(scope || this, this[i], i, this);
}
}
}
/**
* @constructor links.Timeline
* The timeline is a visualization chart to visualize events in time.
*
* The timeline is developed in javascript as a Google Visualization Chart.
*
* @param {Element} container The DOM element in which the Timeline will
* be created. Normally a div element.
*/
links.Timeline = function(container) {
// create variables and set default values
this.dom = {};
this.conversion = {};
this.eventParams = {}; // stores parameters for mouse events
this.groups = [];
this.groupIndexes = {};
this.items = [];
this.renderQueue = {
show: [], // Items made visible but not yet added to DOM
hide: [], // Items currently visible but not yet removed from DOM
update: [] // Items with changed data but not yet adjusted DOM
};
this.renderedItems = []; // Items currently rendered in the DOM
this.clusterGenerator = new links.Timeline.ClusterGenerator(this);
this.currentClusters = [];
this.selection = undefined; // stores index and item which is currently selected
this.listeners = {}; // event listener callbacks
// Initialize sizes.
// Needed for IE (which gives an error when you try to set an undefined
// value in a style)
this.size = {
'actualHeight': 0,
'axis': {
'characterMajorHeight': 0,
'characterMajorWidth': 0,
'characterMinorHeight': 0,
'characterMinorWidth': 0,
'height': 0,
'labelMajorTop': 0,
'labelMinorTop': 0,
'line': 0,
'lineMajorWidth': 0,
'lineMinorHeight': 0,
'lineMinorTop': 0,
'lineMinorWidth': 0,
'top': 0
},
'contentHeight': 0,
'contentLeft': 0,
'contentWidth': 0,
'frameHeight': 0,
'frameWidth': 0,
'groupsLeft': 0,
'groupsWidth': 0,
'items': {
'top': 0
}
};
this.dom.container = container;
this.options = {
'width': "100%",
'height': "auto",
'minHeight': 0, // minimal height in pixels
'autoHeight': true,
'eventMargin': 10, // minimal margin between events
'eventMarginAxis': 20, // minimal margin between events and the axis
'dragAreaWidth': 10, // pixels
'min': undefined,
'max': undefined,
'intervalMin': 10, // milliseconds
'intervalMax': 1000 * 60 * 60 * 24 * 365 * 10000, // milliseconds
'moveable': true,
'zoomable': true,
'selectable': true,
'editable': false,
'snapEvents': true,
'groupChangeable': true,
'showCurrentTime': true, // show a red bar displaying the current time
'showCustomTime': false, // show a blue, draggable bar displaying a custom time
'showMajorLabels': true,
'showMinorLabels': true,
'showNavigation': false,
'showButtonNew': false,
'groupsOnRight': false,
'axisOnTop': false,
'stackEvents': true,
'animate': true,
'animateZoom': true,
'cluster': false,
'style': 'box'
};
this.clientTimeOffset = 0; // difference between client time and the time
// set via Timeline.setCurrentTime()
var dom = this.dom;
// remove all elements from the container element.
while (dom.container.hasChildNodes()) {
dom.container.removeChild(dom.container.firstChild);
}
// create a step for drawing the axis
this.step = new links.Timeline.StepDate();
// add standard item types
this.itemTypes = {
box: links.Timeline.ItemBox,
range: links.Timeline.ItemRange,
dot: links.Timeline.ItemDot
};
// initialize data
this.data = [];
this.firstDraw = true;
// date interval must be initialized
this.setVisibleChartRange(undefined, undefined, false);
// render for the first time
this.render();
// fire the ready event
this.trigger('ready');
};
/**
* Main drawing logic. This is the function that needs to be called
* in the html page, to draw the timeline.
*
* A data table with the events must be provided, and an options table.
*
* @param {google.visualization.DataTable} data
* The data containing the events for the timeline.
* Object DataTable is defined in
* google.visualization.DataTable
* @param {Object} options A name/value map containing settings for the
* timeline. Optional.
*/
links.Timeline.prototype.draw = function(data, options) {
this.setOptions(options);
// read the data
this.setData(data);
// set timer range. this will also redraw the timeline
if (options && (options.start || options.end)) {
this.setVisibleChartRange(options.start, options.end);
}
else if (this.firstDraw) {
this.setVisibleChartRangeAuto();
}
this.firstDraw = false;
};
/**
* Set options for the timeline.
* Timeline must be redrawn afterwards
* @param {Object} options A name/value map containing settings for the
* timeline. Optional.
*/
links.Timeline.prototype.setOptions = function(options) {
if (options) {
// retrieve parameter values
for (var i in options) {
if (options.hasOwnProperty(i)) {
this.options[i] = options[i];
}
}
// check for deprecated options
if (options.showButtonAdd != undefined) {
this.options.showButtonNew = options.showButtonAdd;
console.log('WARNING: Option showButtonAdd is deprecated. Use showButtonNew instead');
}
if (options.scale && options.step) {
this.step.setScale(options.scale, options.step);
}
}
// validate options
this.options.autoHeight = (this.options.height === "auto");
};
/**
* Add new type of items
* @param {String} typeName Name of new type
* @param {links.Timeline.Item} typeFactory Constructor of items
*/
links.Timeline.prototype.addItemType = function (typeName, typeFactory) {
this.itemTypes[typeName] = typeFactory;
};
/**
* Retrieve a map with the column indexes of the columns by column name.
* For example, the method returns the map
* {
* start: 0,
* end: 1,
* content: 2,
* group: undefined,
* className: undefined
* }
* @param {google.visualization.DataTable} dataTable
* @type {Object} map
*/
links.Timeline.mapColumnIds = function (dataTable) {
var cols = {},
colMax = dataTable.getNumberOfColumns(),
allUndefined = true;
// loop over the columns, and map the column id's to the column indexes
for (var col = 0; col < colMax; col++) {
var id = dataTable.getColumnId(col) || dataTable.getColumnLabel(col);
cols[id] = col;
if (id == 'start' || id == 'end' || id == 'content' ||
id == 'group' || id == 'className' || id == 'editable') {
allUndefined = false;
}
}
// if no labels or ids are defined,
// use the default mapping for start, end, content
if (allUndefined) {
cols.start = 0;
cols.end = 1;
cols.content = 2;
}
return cols;
};
/**
* Set data for the timeline
* @param {google.visualization.DataTable | Array} data
*/
links.Timeline.prototype.setData = function(data) {
// unselect any previously selected item
this.unselectItem();
if (!data) {
data = [];
}
// clear all data
this.stackCancelAnimation();
this.clearItems();
this.data = data;
var items = this.items;
this.deleteGroups();
if (google && google.visualization &&
data instanceof google.visualization.DataTable) {
// map the datatable columns
var cols = links.Timeline.mapColumnIds(data);
// read DataTable
for (var row = 0, rows = data.getNumberOfRows(); row < rows; row++) {
items.push(this.createItem({
'start': ((cols.start != undefined) ? data.getValue(row, cols.start) : undefined),
'end': ((cols.end != undefined) ? data.getValue(row, cols.end) : undefined),
'content': ((cols.content != undefined) ? data.getValue(row, cols.content) : undefined),
'group': ((cols.group != undefined) ? data.getValue(row, cols.group) : undefined),
'className': ((cols.className != undefined) ? data.getValue(row, cols.className) : undefined),
'editable': ((cols.editable != undefined) ? data.getValue(row, cols.editable) : undefined)
}));
}
}
else if (links.Timeline.isArray(data)) {
// read JSON array
for (var row = 0, rows = data.length; row < rows; row++) {
var itemData = data[row];
var item = this.createItem(itemData);
items.push(item);
}
}
else {
throw "Unknown data type. DataTable or Array expected.";
}
// prepare data for clustering, by filtering and sorting by type
if (this.options.cluster) {
this.clusterGenerator.setData(this.items);
}
this.render({
animate: false
});
};
/**
* Return the original data table.
* @return {google.visualization.DataTable | Array} data
*/
links.Timeline.prototype.getData = function () {
return this.data;
};
/**
* Update the original data with changed start, end or group.
*
* @param {Number} index
* @param {Object} values An object containing some of the following parameters:
* {Date} start,
* {Date} end,
* {String} content,
* {String} group
*/
links.Timeline.prototype.updateData = function (index, values) {
var data = this.data,
prop;
if (google && google.visualization &&
data instanceof google.visualization.DataTable) {
// update the original google DataTable
var missingRows = (index + 1) - data.getNumberOfRows();
if (missingRows > 0) {
data.addRows(missingRows);
}
// map the column id's by name
var cols = links.Timeline.mapColumnIds(data);
// merge all fields from the provided data into the current data
for (prop in values) {
if (values.hasOwnProperty(prop)) {
var col = cols[prop];
if (col == undefined) {
// create new column
var value = values[prop];
var valueType = 'string';
if (typeof(value) == 'number') valueType = 'number';
else if (typeof(value) == 'boolean') valueType = 'boolean';
else if (value instanceof Date) valueType = 'datetime';
col = data.addColumn(valueType, prop);
}
data.setValue(index, col, values[prop]);
}
}
}
else if (links.Timeline.isArray(data)) {
// update the original JSON table
var row = data[index];
if (row == undefined) {
row = {};
data[index] = row;
}
// merge all fields from the provided data into the current data
for (prop in values) {
if (values.hasOwnProperty(prop)) {
row[prop] = values[prop];
}
}
}
else {
throw "Cannot update data, unknown type of data";
}
};
/**
* Find the item index from a given HTML element
* If no item index is found, undefined is returned
* @param {Element} element
* @return {Number | undefined} index
*/
links.Timeline.prototype.getItemIndex = function(element) {
var e = element,
dom = this.dom,
frame = dom.items.frame,
items = this.items,
index = undefined;
// try to find the frame where the items are located in
while (e.parentNode && e.parentNode !== frame) {
e = e.parentNode;
}
if (e.parentNode === frame) {
// yes! we have found the parent element of all items
// retrieve its id from the array with items
for (var i = 0, iMax = items.length; i < iMax; i++) {
if (items[i].dom === e) {
index = i;
break;
}
}
}
return index;
};
/**
* Set a new size for the timeline
* @param {string} width Width in pixels or percentage (for example "800px"
* or "50%")
* @param {string} height Height in pixels or percentage (for example "400px"
* or "30%")
*/
links.Timeline.prototype.setSize = function(width, height) {
if (width) {
this.options.width = width;
this.dom.frame.style.width = width;
}
if (height) {
this.options.height = height;
this.options.autoHeight = (this.options.height === "auto");
if (height !== "auto" ) {
this.dom.frame.style.height = height;
}
}
this.render({
animate: false
});
};
/**
* Set a new value for the visible range int the timeline.
* Set start undefined to include everything from the earliest date to end.
* Set end undefined to include everything from start to the last date.
* Example usage:
* myTimeline.setVisibleChartRange(new Date("2010-08-22"),
* new Date("2010-09-13"));
* @param {Date} start The start date for the timeline. optional
* @param {Date} end The end date for the timeline. optional
* @param {boolean} redraw Optional. If true (default) the Timeline is
* directly redrawn
*/
links.Timeline.prototype.setVisibleChartRange = function(start, end, redraw) {
var range = {};
if (!start || !end) {
// retrieve the date range of the items
range = this.getDataRange(true);
}
if (!start) {
if (end) {
if (range.min && range.min.valueOf() < end.valueOf()) {
// start of the data
start = range.min;
}
else {
// 7 days before the end
start = new Date(end);
start.setDate(start.getDate() - 7);
}
}
else {
// default of 3 days ago
start = new Date();
start.setDate(start.getDate() - 3);
}
}
if (!end) {
if (range.max) {
// end of the data
end = range.max;
}
else {
// 7 days after start
end = new Date(start);
end.setDate(end.getDate() + 7);
}
}
// prevent start Date <= end Date
if (end.valueOf() <= start.valueOf()) {
end = new Date(start);
end.setDate(end.getDate() + 7);
}
// limit to the allowed range (don't let this do by applyRange,
// because that method will try to maintain the interval (end-start)
var min = this.options.min ? this.options.min.valueOf() : undefined;
if (min != undefined && start.valueOf() < min) {
start = new Date(min);
}
var max = this.options.max ? this.options.max.valueOf() : undefined;
if (max != undefined && end.valueOf() > max) {
end = new Date(max);
}
this.applyRange(start, end);
if (redraw == undefined || redraw == true) {
this.render({
animate: false
}); // TODO: optimize, no reflow needed
}
else {
this.recalcConversion();
}
};
/**
* Change the visible chart range such that all items become visible
*/
links.Timeline.prototype.setVisibleChartRangeAuto = function() {
var range = this.getDataRange(true),
start = undefined,
end = undefined;
this.setVisibleChartRange(range.min, range.max);
};
/**
* Adjust the visible range such that the current time is located in the center
* of the timeline
*/
links.Timeline.prototype.setVisibleChartRangeNow = function() {
var now = new Date();
var diff = (this.end.getTime() - this.start.getTime());
var startNew = new Date(now.getTime() - diff/2);
var endNew = new Date(startNew.getTime() + diff);
this.setVisibleChartRange(startNew, endNew);
};
/**
* Retrieve the current visible range in the timeline.
* @return {Object} An object with start and end properties
*/
links.Timeline.prototype.getVisibleChartRange = function() {
return {
'start': new Date(this.start),
'end': new Date(this.end)
};
};
/**
* Get the date range of the items.
* @param {boolean} [withMargin] If true, 5% of whitespace is added to the
* left and right of the range. Default is false.
* @return {Object} range An object with parameters min and max.
* - {Date} min is the lowest start date of the items
* - {Date} max is the highest start or end date of the items
* If no data is available, the values of min and max
* will be undefined
*/
links.Timeline.prototype.getDataRange = function (withMargin) {
var items = this.items,
min = undefined,
max = undefined;
if (items) {
for (var i = 0, iMax = items.length; i < iMax; i++) {
var item = items[i],
start = item.start ? item.start.valueOf() : undefined,
end = item.end ? item.end.valueOf() : start;
if (min != undefined && start != undefined) {
min = Math.min(min, start);
}
else {
min = start;
}
if (max != undefined && end != undefined) {
max = Math.max(max, end);
}
else {
max = end;
}
}
}
if (min && max && withMargin) {
// zoom out 5% such that you have a little white space on the left and right
var diff = (max.valueOf() - min.valueOf());
min = new Date(min.valueOf() - diff * 0.05);
max = new Date(max.valueOf() + diff * 0.05);
}
return {
'min': min ? new Date(min) : undefined,
'max': max ? new Date(max) : undefined
};
};
/**
* Re-render (reflow and repaint) all components of the Timeline: frame, axis,
* items, ...
* @param {Object} [options] Available options:
* {boolean} renderTimesLeft Number of times the
* render may be repeated
* 5 times by default.
* {boolean} animate takes options.animate
* as default value
*/
links.Timeline.prototype.render = function(options) {
var frameResized = this.reflowFrame();
var axisResized = this.reflowAxis();
var groupsResized = this.reflowGroups();
var itemsResized = this.reflowItems();
var resized = (frameResized || axisResized || groupsResized || itemsResized);
// TODO: only stackEvents/filterItems when resized or changed. (gives a bootstrap issue).
// if (resized) {
var animate = this.options.animate;
if (options && options.animate != undefined) {
animate = options.animate;
}
this.recalcConversion();
this.clusterItems();
this.filterItems();
this.stackItems(animate);
this.recalcItems();
/* TODO: use or cleanup
// re-cluster when the actualHeight is changed
if (this.options.cluster && this.size.actualHeight != this.size.prevActualHeight) {
// console.log('actualHeight changed. reclustering...'); // TODO: cleanup
// remove current clusters
this.unclusterItems();
// TODO: improve efficiency here (when unclustering, update the visibility of the affected items)
// filter and stack the unclustered items
this.filterItems();
this.stackItems(animate);
// apply clustering
this.clusterItems();
if (this.currentClusters && this.currentClusters.length) {
this.filterItems();
this.stackItems(animate);
}
this.size.prevActualHeight = this.size.actualHeight;
}
// }
*/
// TODO: only repaint when resized or when filterItems or stackItems gave a change?
var needsReflow = this.repaint();
// re-render once when needed (prevent endless re-render loop)
if (needsReflow) {
var renderTimesLeft = options ? options.renderTimesLeft : undefined;
if (renderTimesLeft == undefined) {
renderTimesLeft = 5;
}
if (renderTimesLeft > 0) {
this.render({
'animate': options ? options.animate: undefined,
'renderTimesLeft': (renderTimesLeft - 1)
});
}
}
};
/**
* Repaint all components of the Timeline
* @return {boolean} needsReflow Returns true if the DOM is changed such that
* a reflow is needed.
*/
links.Timeline.prototype.repaint = function() {
var frameNeedsReflow = this.repaintFrame();
var axisNeedsReflow = this.repaintAxis();
var groupsNeedsReflow = this.repaintGroups();
var itemsNeedsReflow = this.repaintItems();
this.repaintCurrentTime();
this.repaintCustomTime();
return (frameNeedsReflow || axisNeedsReflow || groupsNeedsReflow || itemsNeedsReflow);
};
/**
* Reflow the timeline frame
* @return {boolean} resized Returns true if any of the frame elements
* have been resized.
*/
links.Timeline.prototype.reflowFrame = function() {
var dom = this.dom,
options = this.options,
size = this.size,
resized = false;
// Note: IE7 has issues with giving frame.clientWidth, therefore I use offsetWidth instead
var frameWidth = dom.frame ? dom.frame.offsetWidth : 0,
frameHeight = dom.frame ? dom.frame.clientHeight : 0;
resized = resized || (size.frameWidth !== frameWidth);
resized = resized || (size.frameHeight !== frameHeight);
size.frameWidth = frameWidth;
size.frameHeight = frameHeight;
return resized;
};
/**
* repaint the Timeline frame
* @return {boolean} needsReflow Returns true if the DOM is changed such that
* a reflow is needed.
*/
links.Timeline.prototype.repaintFrame = function() {
var needsReflow = false,
dom = this.dom,
options = this.options,
size = this.size;
// main frame
if (!dom.frame) {
dom.frame = document.createElement("DIV");
dom.frame.className = "timeline-frame";
dom.frame.style.position = "relative";
dom.frame.style.overflow = "hidden";
dom.container.appendChild(dom.frame);
needsReflow = true;
}
var height = options.autoHeight ?
(size.actualHeight + "px") :
(options.height || "100%");
var width = options.width || "100%";
needsReflow = needsReflow || (dom.frame.style.height != height);
needsReflow = needsReflow || (dom.frame.style.width != width);
dom.frame.style.height = height;
dom.frame.style.width = width;
// contents
if (!dom.content) {
// create content box where the axis and items will be created
dom.content = document.createElement("DIV");
dom.content.style.position = "relative";
dom.content.style.overflow = "hidden";
dom.frame.appendChild(dom.content);
var timelines = document.createElement("DIV");
timelines.style.position = "absolute";
timelines.style.left = "0px";
timelines.style.top = "0px";
timelines.style.height = "100%";
timelines.style.width = "0px";
dom.content.appendChild(timelines);
dom.contentTimelines = timelines;
var params = this.eventParams,
me = this;
if (!params.onMouseDown) {
params.onMouseDown = function (event) {me.onMouseDown(event);};
links.Timeline.addEventListener(dom.content, "mousedown", params.onMouseDown);
}
if (!params.onTouchStart) {
params.onTouchStart = function (event) {me.onTouchStart(event);};
links.Timeline.addEventListener(dom.content, "touchstart", params.onTouchStart);
}
if (!params.onMouseWheel) {
params.onMouseWheel = function (event) {me.onMouseWheel(event);};
links.Timeline.addEventListener(dom.content, "mousewheel", params.onMouseWheel);
}
if (!params.onDblClick) {
params.onDblClick = function (event) {me.onDblClick(event);};
links.Timeline.addEventListener(dom.content, "dblclick", params.onDblClick);
}
needsReflow = true;
}
dom.content.style.left = size.contentLeft + "px";
dom.content.style.top = "0px";
dom.content.style.width = size.contentWidth + "px";
dom.content.style.height = size.frameHeight + "px";
this.repaintNavigation();
return needsReflow;
};
/**
* Reflow the timeline axis. Calculate its height, width, positioning, etc...
* @return {boolean} resized returns true if the axis is resized
*/
links.Timeline.prototype.reflowAxis = function() {
var resized = false,
dom = this.dom,
options = this.options,
size = this.size,
axisDom = dom.axis;
var characterMinorWidth = (axisDom && axisDom.characterMinor) ? axisDom.characterMinor.clientWidth : 0,
characterMinorHeight = (axisDom && axisDom.characterMinor) ? axisDom.characterMinor.clientHeight : 0,
characterMajorWidth = (axisDom && axisDom.characterMajor) ? axisDom.characterMajor.clientWidth : 0,
characterMajorHeight = (axisDom && axisDom.characterMajor) ? axisDom.characterMajor.clientHeight : 0,
axisHeight = (options.showMinorLabels ? characterMinorHeight : 0) +
(options.showMajorLabels ? characterMajorHeight : 0);
var axisTop = options.axisOnTop ? 0 : size.frameHeight - axisHeight,
axisLine = options.axisOnTop ? axisHeight : axisTop;
resized = resized || (size.axis.top !== axisTop);
resized = resized || (size.axis.line !== axisLine);
resized = resized || (size.axis.height !== axisHeight);
size.axis.top = axisTop;
size.axis.line = axisLine;
size.axis.height = axisHeight;
size.axis.labelMajorTop = options.axisOnTop ? 0 : axisLine +
(options.showMinorLabels ? characterMinorHeight : 0);
size.axis.labelMinorTop = options.axisOnTop ?
(options.showMajorLabels ? characterMajorHeight : 0) :
axisLine;
size.axis.lineMinorTop = options.axisOnTop ? size.axis.labelMinorTop : 0;
size.axis.lineMinorHeight = options.showMajorLabels ?
size.frameHeight - characterMajorHeight:
size.frameHeight;
if (axisDom && axisDom.minorLines && axisDom.minorLines.length) {
size.axis.lineMinorWidth = axisDom.minorLines[0].offsetWidth;
}
else {
size.axis.lineMinorWidth = 1;
}
if (axisDom && axisDom.majorLines && axisDom.majorLines.length) {
size.axis.lineMajorWidth = axisDom.majorLines[0].offsetWidth;
}
else {
size.axis.lineMajorWidth = 1;
}
resized = resized || (size.axis.characterMinorWidth !== characterMinorWidth);
resized = resized || (size.axis.characterMinorHeight !== characterMinorHeight);
resized = resized || (size.axis.characterMajorWidth !== characterMajorWidth);
resized = resized || (size.axis.characterMajorHeight !== characterMajorHeight);
size.axis.characterMinorWidth = characterMinorWidth;
size.axis.characterMinorHeight = characterMinorHeight;
size.axis.characterMajorWidth = characterMajorWidth;
size.axis.characterMajorHeight = characterMajorHeight;
var contentHeight = Math.max(size.frameHeight - axisHeight, 0);
size.contentLeft = options.groupsOnRight ? 0 : size.groupsWidth;
size.contentWidth = Math.max(size.frameWidth - size.groupsWidth, 0);
size.contentHeight = contentHeight;
return resized;
};
/**
* Redraw the timeline axis with minor and major labels
* @return {boolean} needsReflow Returns true if the DOM is changed such
* that a reflow is needed.
*/
links.Timeline.prototype.repaintAxis = function() {
var needsReflow = false,
dom = this.dom,
options = this.options,
size = this.size,
step = this.step;
var axis = dom.axis;
if (!axis) {
axis = {};
dom.axis = axis;
}
if (!size.axis.properties) {
size.axis.properties = {};
}
if (!axis.minorTexts) {
axis.minorTexts = [];
}
if (!axis.minorLines) {
axis.minorLines = [];
}
if (!axis.majorTexts) {
axis.majorTexts = [];
}
if (!axis.majorLines) {
axis.majorLines = [];
}
if (!axis.frame) {
axis.frame = document.createElement("DIV");
axis.frame.style.position = "absolute";
axis.frame.style.left = "0px";
axis.frame.style.top = "0px";
dom.content.appendChild(axis.frame);
}
// take axis offline
dom.content.removeChild(axis.frame);
axis.frame.style.width = (size.contentWidth) + "px";
axis.frame.style.height = (size.axis.height) + "px";
// the drawn axis is more wide than the actual visual part, such that
// the axis can be dragged without having to redraw it each time again.
var start = this.screenToTime(0);
var end = this.screenToTime(size.contentWidth);
// calculate minimum step (in milliseconds) based on character size
if (size.axis.characterMinorWidth) {
this.minimumStep =
this.screenToTime(size.axis.characterMinorWidth * 6).valueOf() -
this.screenToTime(0).valueOf();
step.setRange(start, end, this.minimumStep);
}
var charsNeedsReflow = this.repaintAxisCharacters();
needsReflow = needsReflow || charsNeedsReflow;
// The current labels on the axis will be re-used (much better performance),
// therefore, the repaintAxis method uses the mechanism with
// repaintAxisStartOverwriting, repaintAxisEndOverwriting, and
// this.size.axis.properties is used.
this.repaintAxisStartOverwriting();
step.start();
var xFirstMajorLabel = undefined;
var max = 0;
while (!step.end() && max < 1000) {
max++;
var cur = step.getCurrent(),
x = this.timeToScreen(cur),
isMajor = step.isMajor();
if (options.showMinorLabels) {
this.repaintAxisMinorText(x, step.getLabelMinor());
}
if (isMajor && options.showMajorLabels) {
if (x > 0) {
if (xFirstMajorLabel === undefined) {
xFirstMajorLabel = x;
}
this.repaintAxisMajorText(x, step.getLabelMajor());
}
this.repaintAxisMajorLine(x);
}
else {
this.repaintAxisMinorLine(x);
}
step.next();
}
// create a major label on the left when needed
if (options.showMajorLabels) {
var leftTime = this.screenToTime(0),
leftText = this.step.getLabelMajor(leftTime),
width = leftText.length * size.axis.characterMajorWidth + 10; // upper bound estimation
if (xFirstMajorLabel === undefined || width < xFirstMajorLabel) {
this.repaintAxisMajorText(0, leftText, leftTime);
}
}
// cleanup left over labels
this.repaintAxisEndOverwriting();
this.repaintAxisHorizontal();
// put axis online
dom.content.insertBefore(axis.frame, dom.content.firstChild);
return needsReflow;
};
/**
* Create characters used to determine the size of text on the axis
* @return {boolean} needsReflow Returns true if the DOM is changed such that
* a reflow is needed.
*/
links.Timeline.prototype.repaintAxisCharacters = function () {
// calculate the width and height of a single character
// this is used to calculate the step size, and also the positioning of the
// axis
var needsReflow = false,
dom = this.dom,
axis = dom.axis,
text;
if (!axis.characterMinor) {
text = document.createTextNode("0");
var characterMinor = document.createElement("DIV");
characterMinor.className = "timeline-axis-text timeline-axis-text-minor";
characterMinor.appendChild(text);
characterMinor.style.position = "absolute";
characterMinor.style.visibility = "hidden";
characterMinor.style.paddingLeft = "0px";
characterMinor.style.paddingRight = "0px";
axis.frame.appendChild(characterMinor);
axis.characterMinor = characterMinor;
needsReflow = true;
}
if (!axis.characterMajor) {
text = document.createTextNode("0");
var characterMajor = document.createElement("DIV");
characterMajor.className = "timeline-axis-text timeline-axis-text-major";
characterMajor.appendChild(text);
characterMajor.style.position = "absolute";
characterMajor.style.visibility = "hidden";
characterMajor.style.paddingLeft = "0px";
characterMajor.style.paddingRight = "0px";
axis.frame.appendChild(characterMajor);
axis.characterMajor = characterMajor;
needsReflow = true;
}
return needsReflow;
};
/**
* Initialize redraw of the axis. All existing labels and lines will be
* overwritten and reused.
*/
links.Timeline.prototype.repaintAxisStartOverwriting = function () {
var properties = this.size.axis.properties;
properties.minorTextNum = 0;
properties.minorLineNum = 0;
properties.majorTextNum = 0;
properties.majorLineNum = 0;
};
/**
* End of overwriting HTML DOM elements of the axis.
* remaining elements will be removed
*/
links.Timeline.prototype.repaintAxisEndOverwriting = function () {
var dom = this.dom,
props = this.size.axis.properties,
frame = this.dom.axis.frame,
num;
// remove leftovers
var minorTexts = dom.axis.minorTexts;
num = props.minorTextNum;
while (minorTexts.length > num) {
var minorText = minorTexts[num];
frame.removeChild(minorText);
minorTexts.splice(num, 1);
}
var minorLines = dom.axis.minorLines;
num = props.minorLineNum;
while (minorLines.length > num) {
var minorLine = minorLines[num];
frame.removeChild(minorLine);
minorLines.splice(num, 1);
}
var majorTexts = dom.axis.majorTexts;
num = props.majorTextNum;
while (majorTexts.length > num) {
var majorText = majorTexts[num];
frame.removeChild(majorText);
majorTexts.splice(num, 1);
}
var majorLines = dom.axis.majorLines;
num = props.majorLineNum;
while (majorLines.length > num) {
var majorLine = majorLines[num];
frame.removeChild(majorLine);
majorLines.splice(num, 1);
}
};
/**
* Repaint the horizontal line and background of the axis
*/
links.Timeline.prototype.repaintAxisHorizontal = function() {
var axis = this.dom.axis,
size = this.size,
options = this.options;
// line behind all axis elements (possibly having a background color)
var hasAxis = (options.showMinorLabels || options.showMajorLabels);
if (hasAxis) {
if (!axis.backgroundLine) {
// create the axis line background (for a background color or so)
var backgroundLine = document.createElement("DIV");
backgroundLine.className = "timeline-axis";
backgroundLine.style.position = "absolute";
backgroundLine.style.left = "0px";
backgroundLine.style.width = "100%";
backgroundLine.style.border = "none";
axis.frame.insertBefore(backgroundLine, axis.frame.firstChild);
axis.backgroundLine = backgroundLine;
}
if (axis.backgroundLine) {
axis.backgroundLine.style.top = size.axis.top + "px";
axis.backgroundLine.style.height = size.axis.height + "px";
}
}
else {
if (axis.backgroundLine) {
axis.frame.removeChild(axis.backgroundLine);
delete axis.backgroundLine;
}
}
// line before all axis elements
if (hasAxis) {
if (axis.line) {
// put this line at the end of all childs
var line = axis.frame.removeChild(axis.line);
axis.frame.appendChild(line);
}
else {
// make the axis line
var line = document.createElement("DIV");
line.className = "timeline-axis";
line.style.position = "absolute";
line.style.left = "0px";
line.style.width = "100%";
line.style.height = "0px";
axis.frame.appendChild(line);
axis.line = line;
}
axis.line.style.top = size.axis.line + "px";
}
else {
if (axis.line && axis.line.parentElement) {
axis.frame.removeChild(axis.line);
delete axis.line;
}
}
};
/**
* Create a minor label for the axis at position x
* @param {Number} x
* @param {String} text
*/
links.Timeline.prototype.repaintAxisMinorText = function (x, text) {
var size = this.size,
dom = this.dom,
props = size.axis.properties,
frame = dom.axis.frame,
minorTexts = dom.axis.minorTexts,
index = props.minorTextNum,
label;
if (index < minorTexts.length) {
label = minorTexts[index]
}
else {
// create new label
var content = document.createTextNode("");
label = document.createElement("DIV");
label.appendChild(content);
label.className = "timeline-axis-text timeline-axis-text-minor";
label.style.position = "absolute";
frame.appendChild(label);
minorTexts.push(label);
}
label.childNodes[0].nodeValue = text;
label.style.left = x + "px";
label.style.top = size.axis.labelMinorTop + "px";
//label.title = title; // TODO: this is a heavy operation
props.minorTextNum++;
};
/**
* Create a minor line for the axis at position x
* @param {Number} x
*/
links.Timeline.prototype.repaintAxisMinorLine = function (x) {
var axis = this.size.axis,
dom = this.dom,
props = axis.properties,
frame = dom.axis.frame,
minorLines = dom.axis.minorLines,
index = props.minorLineNum,
line;
if (index < minorLines.length) {
line = minorLines[index];
}
else {
// create vertical line
line = document.createElement("DIV");
line.className = "timeline-axis-grid timeline-axis-grid-minor";
line.style.position = "absolute";
line.style.width = "0px";
frame.appendChild(line);
minorLines.push(line);
}
line.style.top = axis.lineMinorTop + "px";
line.style.height = axis.lineMinorHeight + "px";
line.style.left = (x - axis.lineMinorWidth/2) + "px";
props.minorLineNum++;
};
/**
* Create a Major label for the axis at position x
* @param {Number} x
* @param {String} text
*/
links.Timeline.prototype.repaintAxisMajorText = function (x, text) {
var size = this.size,
props = size.axis.properties,
frame = this.dom.axis.frame,
majorTexts = this.dom.axis.majorTexts,
index = props.majorTextNum,
label;
if (index < majorTexts.length) {
label = majorTexts[index];
}
else {
// create label
var content = document.createTextNode(text);
label = document.createElement("DIV");
label.className = "timeline-axis-text timeline-axis-text-major";
label.appendChild(content);
label.style.position = "absolute";
label.style.top = "0px";
frame.appendChild(label);
majorTexts.push(label);
}
label.childNodes[0].nodeValue = text;
label.style.top = size.axis.labelMajorTop + "px";
label.style.left = x + "px";
//label.title = title; // TODO: this is a heavy operation
props.majorTextNum ++;
};
/**
* Create a Major line for the axis at position x
* @param {Number} x
*/
links.Timeline.prototype.repaintAxisMajorLine = function (x) {
var size = this.size,
props = size.axis.properties,
axis = this.size.axis,
frame = this.dom.axis.frame,
majorLines = this.dom.axis.majorLines,
index = props.majorLineNum,
line;
if (index < majorLines.length) {
line = majorLines[index];
}
else {
// create vertical line
line = document.createElement("DIV");
line.className = "timeline-axis-grid timeline-axis-grid-major";
line.style.position = "absolute";
line.style.top = "0px";
line.style.width = "0px";
frame.appendChild(line);
majorLines.push(line);
}
line.style.left = (x - axis.lineMajorWidth/2) + "px";
line.style.height = size.frameHeight + "px";
props.majorLineNum ++;
};
/**
* Reflow all items, retrieve their actual size
* @return {boolean} resized returns true if any of the items is resized
*/
links.Timeline.prototype.reflowItems = function() {
var resized = false,
i,
iMax,
group,
dom = this.dom,
groups = this.groups,
renderedItems = this.renderedItems;
if (groups) { // TODO: need to check if labels exists?
// loop through all groups to reset the items height
groups.forEach(function (group) {
group.itemsHeight = 0;
});
}
// loop through the width and height of all visible items
for (i = 0, iMax = renderedItems.length; i < iMax; i++) {
var item = renderedItems[i],
domItem = item.dom;
group = item.group;
if (domItem) {
// TODO: move updating width and height into item.reflow
var width = domItem ? domItem.clientWidth : 0;
var height = domItem ? domItem.clientHeight : 0;
resized = resized || (item.width != width);
resized = resized || (item.height != height);
item.width = width;
item.height = height;
//item.borderWidth = (domItem.offsetWidth - domItem.clientWidth - 2) / 2; // TODO: borderWidth
item.reflow();
}
if (group) {
group.itemsHeight = group.itemsHeight ?
Math.max(group.itemsHeight, item.height) :
item.height;
}
}
return resized;
};
/**
* Recalculate item properties:
* - the height of each group.
* - the actualHeight, from the stacked items or the sum of the group heights
* @return {boolean} resized returns true if any of the items properties is
* changed
*/
links.Timeline.prototype.recalcItems = function () {
var resized = false,
i,
iMax,
item,
finalItem,
finalItems,
group,
groups = this.groups,
size = this.size,
options = this.options,
renderedItems = this.renderedItems;
var actualHeight = 0;
if (groups.length == 0) {
// calculate actual height of the timeline when there are no groups
// but stacked items
if (options.autoHeight || options.cluster) {
var min = 0,
max = 0;
if (this.stack && this.stack.finalItems) {
// adjust the offset of all finalItems when the actualHeight has been changed
finalItems = this.stack.finalItems;
finalItem = finalItems[0];
if (finalItem && finalItem.top) {
min = finalItem.top;
max = finalItem.top + finalItem.height;
}
for (i = 1, iMax = finalItems.length; i < iMax; i++) {
finalItem = finalItems[i];
min = Math.min(min, finalItem.top);
max = Math.max(max, finalItem.top + finalItem.height);
}
}
else {
item = renderedItems[0];
if (item && item.top) {
min = item.top;
max = item.top + item.height;
}
for (i = 1, iMax = renderedItems.length; i < iMax; i++) {
item = renderedItems[i];
if (item.top) {
min = Math.min(min, item.top);
max = Math.max(max, (item.top + item.height));
}
}
}
actualHeight = (max - min) + 2 * options.eventMarginAxis + size.axis.height;
if (actualHeight < options.minHeight) {
actualHeight = options.minHeight;
}
if (size.actualHeight != actualHeight && options.autoHeight && !options.axisOnTop) {
// adjust the offset of all items when the actualHeight has been changed
var diff = actualHeight - size.actualHeight;
if (this.stack && this.stack.finalItems) {
finalItems = this.stack.finalItems;
for (i = 0, iMax = finalItems.length; i < iMax; i++) {
finalItems[i].top += diff;
finalItems[i].item.top += diff;
}
}
else {
for (i = 0, iMax = renderedItems.length; i < iMax; i++) {
renderedItems[i].top += diff;
}
}
}
}
}
else {
// loop through all groups to get the height of each group, and the
// total height
actualHeight = size.axis.height + 2 * options.eventMarginAxis;
for (i = 0, iMax = groups.length; i < iMax; i++) {
group = groups[i];
var groupHeight = Math.max(group.labelHeight || 0, group.itemsHeight || 0);
resized = resized || (groupHeight != group.height);
group.height = groupHeight;
actualHeight += groups[i].height + options.eventMargin;
}
// calculate top positions of the group labels and lines
var eventMargin = options.eventMargin,
top = options.axisOnTop ?
options.eventMarginAxis + eventMargin/2 :
size.contentHeight - options.eventMarginAxis + eventMargin/ 2,
axisHeight = size.axis.height;
for (i = 0, iMax = groups.length; i < iMax; i++) {
group = groups[i];
if (options.axisOnTop) {
group.top = top + axisHeight;
group.labelTop = top + axisHeight + (group.height - group.labelHeight) / 2;
group.lineTop = top + axisHeight + group.height + eventMargin/2;
top += group.height + eventMargin;
}
else {
top -= group.height + eventMargin;
group.top = top;
group.labelTop = top + (group.height - group.labelHeight) / 2;
group.lineTop = top - eventMargin/2;
}
}
// calculate top position of the visible items
for (i = 0, iMax = renderedItems.length; i < iMax; i++) {
item = renderedItems[i];
group = item.group;
if (group) {
item.top = group.top;
}
}
resized = true;
}
if (actualHeight < options.minHeight) {
actualHeight = options.minHeight;
}
resized = resized || (actualHeight != size.actualHeight);
size.actualHeight = actualHeight;
return resized;
};
/**
* This method clears the (internal) array this.items in a safe way: neatly
* cleaning up the DOM, and accompanying arrays this.renderedItems and
* the created clusters.
*/
links.Timeline.prototype.clearItems = function() {
// add all visible items to the list to be hidden
var hideItems = this.renderQueue.hide;
this.renderedItems.forEach(function (item) {
hideItems.push(item);
});
// clear the cluster generator
this.clusterGenerator.clear();
// actually clear the items
this.items = [];
};
/**
* Repaint all items
* @return {boolean} needsReflow Returns true if the DOM is changed such that
* a reflow is needed.
*/
links.Timeline.prototype.repaintItems = function() {
var i, iMax, item, index;
var needsReflow = false,
dom = this.dom,
size = this.size,
timeline = this,
renderedItems = this.renderedItems;
if (!dom.items) {
dom.items = {};
}
// draw the frame containing the items
var frame = dom.items.frame;
if (!frame) {
frame = document.createElement("DIV");
frame.style.position = "relative";
dom.content.appendChild(frame);
dom.items.frame = frame;
}
frame.style.left = "0px";
frame.style.top = size.items.top + "px";
frame.style.height = "0px";
// Take frame offline (for faster manipulation of the DOM)
dom.content.removeChild(frame);
// process the render queue with changes
var queue = this.renderQueue;
var newImageUrls = [];
needsReflow = needsReflow ||
(queue.show.length > 0) ||
(queue.update.length > 0) ||
(queue.hide.length > 0); // TODO: reflow needed on hide of items?
/* TODO: cleanup
console.log(
'show=', queue.show.length,
'hide=', queue.show.length,
'update=', queue.show.length
);
*/
while (item = queue.show.shift()) {
item.showDOM(frame);
item.getImageUrls(newImageUrls);
renderedItems.push(item);
}
while (item = queue.update.shift()) {
item.updateDOM(frame);
item.getImageUrls(newImageUrls);
index = this.renderedItems.indexOf(item);
if (index == -1) {
renderedItems.push(item);
}
}
while (item = queue.hide.shift()) {
item.hideDOM(frame);
index = this.renderedItems.indexOf(item);
if (index != -1) {
renderedItems.splice(index, 1);
}
}
// console.log('renderedItems=', renderedItems.length); // TODO: cleanup
// reposition all visible items
renderedItems.forEach(function (item) {
item.updatePosition(timeline);
});
// redraw the delete button and dragareas of the selected item (if any)
this.repaintDeleteButton();
this.repaintDragAreas();
// put frame online again
dom.content.appendChild(frame);
if (newImageUrls.length) {
// retrieve all image sources from the items, and set a callback once
// all images are retrieved
var callback = function () {
timeline.render();
};
var sendCallbackWhenAlreadyLoaded = false;
links.imageloader.loadAll(newImageUrls, callback, sendCallbackWhenAlreadyLoaded);
}
return needsReflow;
};
/**
* Reflow the size of the groups
* @return {boolean} resized Returns true if any of the frame elements
* have been resized.
*/
links.Timeline.prototype.reflowGroups = function() {
var resized = false,
options = this.options,
size = this.size,
dom = this.dom;
// calculate the groups width and height
// TODO: only update when data is changed! -> use an updateSeq
var groupsWidth = 0;
// loop through all groups to get the labels width and height
var groups = this.groups;
var labels = this.dom.groups ? this.dom.groups.labels : [];
for (var i = 0, iMax = groups.length; i < iMax; i++) {
var group = groups[i];
var label = labels[i];
group.labelWidth = label ? label.clientWidth : 0;
group.labelHeight = label ? label.clientHeight : 0;
group.width = group.labelWidth; // TODO: group.width is redundant with labelWidth
groupsWidth = Math.max(groupsWidth, group.width);
}
// limit groupsWidth to the groups width in the options
if (options.groupsWidth !== undefined) {
groupsWidth = dom.groups.frame ? dom.groups.frame.clientWidth : 0;
}
// compensate for the border width. TODO: calculate the real border width
groupsWidth += 1;
var groupsLeft = options.groupsOnRight ? size.frameWidth - groupsWidth : 0;
resized = resized || (size.groupsWidth !== groupsWidth);
resized = resized || (size.groupsLeft !== groupsLeft);
size.groupsWidth = groupsWidth;
size.groupsLeft = groupsLeft;
return resized;
};
/**
* Redraw the group labels
*/
links.Timeline.prototype.repaintGroups = function() {
var dom = this.dom,
options = this.options,
size = this.size,
groups = this.groups;
if (dom.groups === undefined) {
dom.groups = {};
}
var labels = dom.groups.labels;
if (!labels) {
labels = [];
dom.groups.labels = labels;
}
var labelLines = dom.groups.labelLines;
if (!labelLines) {
labelLines = [];
dom.groups.labelLines = labelLines;
}
var itemLines = dom.groups.itemLines;
if (!itemLines) {
itemLines = [];
dom.groups.itemLines = itemLines;
}
// create the frame for holding the groups
var frame = dom.groups.frame;
if (!frame) {
frame = document.createElement("DIV");
frame.className = "timeline-groups-axis";
frame.style.position = "absolute";
frame.style.overflow = "hidden";
frame.style.top = "0px";
frame.style.height = "100%";
dom.frame.appendChild(frame);
dom.groups.frame = frame;
}
frame.style.left = size.groupsLeft + "px";
frame.style.width = (options.groupsWidth !== undefined) ?
options.groupsWidth :
size.groupsWidth + "px";
// hide groups axis when there are no groups
if (groups.length == 0) {
frame.style.display = 'none';
}
else {
frame.style.display = '';
}
// TODO: only create/update groups when data is changed.
// create the items
var current = labels.length,
needed = groups.length;
// overwrite existing group labels
for (var i = 0, iMax = Math.min(current, needed); i < iMax; i++) {
var group = groups[i];
var label = labels[i];
label.innerHTML = this.getGroupName(group);
label.style.display = '';
}
// append new items when needed
for (var i = current; i < needed; i++) {
var group = groups[i];
// create text label
var label = document.createElement("DIV");
label.className = "timeline-groups-text";
label.style.position = "absolute";
if (options.groupsWidth === undefined) {
label.style.whiteSpace = "nowrap";
}
label.innerHTML = this.getGroupName(group);
frame.appendChild(label);
labels[i] = label;
// create the grid line between the group labels
var labelLine = document.createElement("DIV");
labelLine.className = "timeline-axis-grid timeline-axis-grid-minor";
labelLine.style.position = "absolute";
labelLine.style.left = "0px";
labelLine.style.width = "100%";
labelLine.style.height = "0px";
labelLine.style.borderTopStyle = "solid";
frame.appendChild(labelLine);
labelLines[i] = labelLine;
// create the grid line between the items
var itemLine = document.createElement("DIV");
itemLine.className = "timeline-axis-grid timeline-axis-grid-minor";
itemLine.style.position = "absolute";
itemLine.style.left = "0px";
itemLine.style.width = "100%";
itemLine.style.height = "0px";
itemLine.style.borderTopStyle = "solid";
dom.content.insertBefore(itemLine, dom.content.firstChild);
itemLines[i] = itemLine;
}
// remove redundant items from the DOM when needed
for (var i = needed; i < current; i++) {
var label = labels[i],
labelLine = labelLines[i],
itemLine = itemLines[i];
frame.removeChild(label);
frame.removeChild(labelLine);
dom.content.removeChild(itemLine);
}
labels.splice(needed, current - needed);
labelLines.splice(needed, current - needed);
itemLines.splice(needed, current - needed);
frame.style.borderStyle = options.groupsOnRight ?
"none none none solid" :
"none solid none none";
// position the groups
for (var i = 0, iMax = groups.length; i < iMax; i++) {
var group = groups[i],
label = labels[i],
labelLine = labelLines[i],
itemLine = itemLines[i];
label.style.top = group.labelTop + "px";
labelLine.style.top = group.lineTop + "px";
itemLine.style.top = group.lineTop + "px";
itemLine.style.width = size.contentWidth + "px";
}
if (!dom.groups.background) {
// create the axis grid line background
var background = document.createElement("DIV");
background.className = "timeline-axis";
background.style.position = "absolute";
background.style.left = "0px";
background.style.width = "100%";
background.style.border = "none";
frame.appendChild(background);
dom.groups.background = background;
}
dom.groups.background.style.top = size.axis.top + 'px';
dom.groups.background.style.height = size.axis.height + 'px';
if (!dom.groups.line) {
// create the axis grid line
var line = document.createElement("DIV");
line.className = "timeline-axis";
line.style.position = "absolute";
line.style.left = "0px";
line.style.width = "100%";
line.style.height = "0px";
frame.appendChild(line);
dom.groups.line = line;
}
dom.groups.line.style.top = size.axis.line + 'px';
// create a callback when there are images which are not yet loaded
// TODO: more efficiently load images in the groups
if (dom.groups.frame && groups.length) {
var imageUrls = [];
links.imageloader.filterImageUrls(dom.groups.frame, imageUrls);
if (imageUrls.length) {
// retrieve all image sources from the items, and set a callback once
// all images are retrieved
var callback = function () {
timeline.render();
};
var sendCallbackWhenAlreadyLoaded = false;
links.imageloader.loadAll(imageUrls, callback, sendCallbackWhenAlreadyLoaded);
}
}
};
/**
* Redraw the current time bar
*/
links.Timeline.prototype.repaintCurrentTime = function() {
var options = this.options,
dom = this.dom,
size = this.size;
if (!options.showCurrentTime) {
if (dom.currentTime) {
dom.contentTimelines.removeChild(dom.currentTime);
delete dom.currentTime;
}
return;
}
if (!dom.currentTime) {
// create the current time bar
var currentTime = document.createElement("DIV");
currentTime.className = "timeline-currenttime";
currentTime.style.position = "absolute";
currentTime.style.top = "0px";
currentTime.style.height = "100%";
dom.contentTimelines.appendChild(currentTime);
dom.currentTime = currentTime;
}
var now = new Date();
var nowOffset = new Date(now.getTime() + this.clientTimeOffset);
var x = this.timeToScreen(nowOffset);
var visible = (x > -size.contentWidth && x < 2 * size.contentWidth);
dom.currentTime.style.display = visible ? '' : 'none';
dom.currentTime.style.left = x + "px";
dom.currentTime.title = "Current time: " + nowOffset;
// start a timer to adjust for the new time
if (this.currentTimeTimer != undefined) {
clearTimeout(this.currentTimeTimer);
delete this.currentTimeTimer;
}
var timeline = this;
var onTimeout = function() {
timeline.repaintCurrentTime();
};
// the time equal to the width of one pixel, divided by 2 for more smoothness
var interval = 1 / this.conversion.factor / 2;
if (interval < 30) interval = 30;
this.currentTimeTimer = setTimeout(onTimeout, interval);
};
/**
* Redraw the custom time bar
*/
links.Timeline.prototype.repaintCustomTime = function() {
var options = this.options,
dom = this.dom,
size = this.size;
if (!options.showCustomTime) {
if (dom.customTime) {
dom.contentTimelines.removeChild(dom.customTime);
delete dom.customTime;
}
return;
}
if (!dom.customTime) {
var customTime = document.createElement("DIV");
customTime.className = "timeline-customtime";
customTime.style.position = "absolute";
customTime.style.top = "0px";
customTime.style.height = "100%";
var drag = document.createElement("DIV");
drag.style.position = "relative";
drag.style.top = "0px";
drag.style.left = "-10px";
drag.style.height = "100%";
drag.style.width = "20px";
customTime.appendChild(drag);
dom.contentTimelines.appendChild(customTime);
dom.customTime = customTime;
// initialize parameter
this.customTime = new Date();
}
var x = this.timeToScreen(this.customTime),
visible = (x > -size.contentWidth && x < 2 * size.contentWidth);
dom.customTime.style.display = visible ? '' : 'none';
dom.customTime.style.left = x + "px";
dom.customTime.title = "Time: " + this.customTime;
};
/**
* Redraw the delete button, on the top right of the currently selected item
* if there is no item selected, the button is hidden.
*/
links.Timeline.prototype.repaintDeleteButton = function () {
var timeline = this,
dom = this.dom,
frame = dom.items.frame;
var deleteButton = dom.items.deleteButton;
if (!deleteButton) {
// create a delete button
deleteButton = document.createElement("DIV");
deleteButton.className = "timeline-navigation-delete";
deleteButton.style.position = "absolute";
frame.appendChild(deleteButton);
dom.items.deleteButton = deleteButton;
}
var index = this.selection ? this.selection.index : -1,
item = this.selection ? this.items[index] : undefined;
if (item && item.rendered && this.isEditable(item)) {
var right = item.getRight(this),
top = item.top;
deleteButton.style.left = right + 'px';
deleteButton.style.top = top + 'px';
deleteButton.style.display = '';
frame.removeChild(deleteButton);
frame.appendChild(deleteButton);
}
else {
deleteButton.style.display = 'none';
}
};
/**
* Redraw the drag areas. When an item (ranges only) is selected,
* it gets a drag area on the left and right side, to change its width
*/
links.Timeline.prototype.repaintDragAreas = function () {
var timeline = this,
options = this.options,
dom = this.dom,
frame = this.dom.items.frame;
// create left drag area
var dragLeft = dom.items.dragLeft;
if (!dragLeft) {
dragLeft = document.createElement("DIV");
dragLeft.className="timeline-event-range-drag-left";
dragLeft.style.width = options.dragAreaWidth + "px";
dragLeft.style.position = "absolute";
frame.appendChild(dragLeft);
dom.items.dragLeft = dragLeft;
}
// create right drag area
var dragRight = dom.items.dragRight;
if (!dragRight) {
dragRight = document.createElement("DIV");
dragRight.className="timeline-event-range-drag-right";
dragRight.style.width = options.dragAreaWidth + "px";
dragRight.style.position = "absolute";
frame.appendChild(dragRight);
dom.items.dragRight = dragRight;
}
// reposition left and right drag area
var index = this.selection ? this.selection.index : -1,
item = this.selection ? this.items[index] : undefined;
if (item && item.rendered && this.isEditable(item) &&
(item instanceof links.Timeline.ItemRange)) {
var left = this.timeToScreen(item.start),
right = this.timeToScreen(item.end),
top = item.top,
height = item.height;
dragLeft.style.left = left + 'px';
dragLeft.style.top = top + 'px';
dragLeft.style.height = height + 'px';
dragLeft.style.display = '';
frame.removeChild(dragLeft);
frame.appendChild(dragLeft);
dragRight.style.left = (right - options.dragAreaWidth) + 'px';
dragRight.style.top = top + 'px';
dragRight.style.height = height + 'px';
dragRight.style.display = '';
frame.removeChild(dragRight);
frame.appendChild(dragRight);
}
else {
dragLeft.style.display = 'none';
dragRight.style.display = 'none';
}
};
/**
* Create the navigation buttons for zooming and moving
*/
links.Timeline.prototype.repaintNavigation = function () {
var timeline = this,
options = this.options,
dom = this.dom,
frame = dom.frame,
navBar = dom.navBar;
if (!navBar) {
if (options.showNavigation || options.showButtonNew) {
// create a navigation bar containing the navigation buttons
navBar = document.createElement("DIV");
navBar.style.position = "absolute";
navBar.className = "timeline-navigation";
if (options.groupsOnRight) {
navBar.style.left = '10px';
}
else {
navBar.style.right = '10px';
}
if (options.axisOnTop) {
navBar.style.bottom = '10px';
}
else {
navBar.style.top = '10px';
}
dom.navBar = navBar;
frame.appendChild(navBar);
}
if (options.editable && options.showButtonNew) {
// create a new in button
navBar.addButton = document.createElement("DIV");
navBar.addButton.className = "timeline-navigation-new";
navBar.addButton.title = "Create new event";
var onAdd = function(event) {
links.Timeline.preventDefault(event);
links.Timeline.stopPropagation(event);
// create a new event at the center of the frame
var w = timeline.size.contentWidth;
var x = w / 2;
var xstart = timeline.screenToTime(x - w / 10); // subtract 10% of timeline width
var xend = timeline.screenToTime(x + w / 10); // add 10% of timeline width
if (options.snapEvents) {
timeline.step.snap(xstart);
timeline.step.snap(xend);
}
var content = "New";
var group = timeline.groups.length ? timeline.groups[0].content : undefined;
timeline.addItem({
'start': xstart,
'end': xend,
'content': content,
'group': group
});
var index = (timeline.items.length - 1);
timeline.selectItem(index);
timeline.applyAdd = true;
// fire an add event.
// Note that the change can be canceled from within an event listener if
// this listener calls the method cancelAdd().
timeline.trigger('add');
if (!timeline.applyAdd) {
// undo an add
timeline.deleteItem(index);
}
};
links.Timeline.addEventListener(navBar.addButton, "mousedown", onAdd);
navBar.appendChild(navBar.addButton);
}
if (options.editable && options.showButtonNew && options.showNavigation) {
// create a separator line
navBar.addButton.style.borderRightWidth = "1px";
navBar.addButton.style.borderRightStyle = "solid";
}
if (options.showNavigation) {
// create a zoom in button
navBar.zoomInButton = document.createElement("DIV");
navBar.zoomInButton.className = "timeline-navigation-zoom-in";
navBar.zoomInButton.title = "Zoom in";
var onZoomIn = function(event) {
links.Timeline.preventDefault(event);
links.Timeline.stopPropagation(event);
timeline.zoom(0.4);
timeline.trigger("rangechange");
timeline.trigger("rangechanged");
};
links.Timeline.addEventListener(navBar.zoomInButton, "mousedown", onZoomIn);
navBar.appendChild(navBar.zoomInButton);
// create a zoom out button
navBar.zoomOutButton = document.createElement("DIV");
navBar.zoomOutButton.className = "timeline-navigation-zoom-out";
navBar.zoomOutButton.title = "Zoom out";
var onZoomOut = function(event) {
links.Timeline.preventDefault(event);
links.Timeline.stopPropagation(event);
timeline.zoom(-0.4);
timeline.trigger("rangechange");
timeline.trigger("rangechanged");
};
links.Timeline.addEventListener(navBar.zoomOutButton, "mousedown", onZoomOut);
navBar.appendChild(navBar.zoomOutButton);
// create a move left button
navBar.moveLeftButton = document.createElement("DIV");
navBar.moveLeftButton.className = "timeline-navigation-move-left";
navBar.moveLeftButton.title = "Move left";
var onMoveLeft = function(event) {
links.Timeline.preventDefault(event);
links.Timeline.stopPropagation(event);
timeline.move(-0.2);
timeline.trigger("rangechange");
timeline.trigger("rangechanged");
};
links.Timeline.addEventListener(navBar.moveLeftButton, "mousedown", onMoveLeft);
navBar.appendChild(navBar.moveLeftButton);
// create a move right button
navBar.moveRightButton = document.createElement("DIV");
navBar.moveRightButton.className = "timeline-navigation-move-right";
navBar.moveRightButton.title = "Move right";
var onMoveRight = function(event) {
links.Timeline.preventDefault(event);
links.Timeline.stopPropagation(event);
timeline.move(0.2);
timeline.trigger("rangechange");
timeline.trigger("rangechanged");
};
links.Timeline.addEventListener(navBar.moveRightButton, "mousedown", onMoveRight);
navBar.appendChild(navBar.moveRightButton);
}
}
};
/**
* Set current time. This function can be used to set the time in the client
* timeline equal with the time on a server.
* @param {Date} time
*/
links.Timeline.prototype.setCurrentTime = function(time) {
var now = new Date();
this.clientTimeOffset = time.getTime() - now.getTime();
this.repaintCurrentTime();
};
/**
* Get current time. The time can have an offset from the real time, when
* the current time has been changed via the method setCurrentTime.
* @return {Date} time
*/
links.Timeline.prototype.getCurrentTime = function() {
var now = new Date();
return new Date(now.getTime() + this.clientTimeOffset);
};
/**
* Set custom time.
* The custom time bar can be used to display events in past or future.
* @param {Date} time
*/
links.Timeline.prototype.setCustomTime = function(time) {
this.customTime = new Date(time);
this.repaintCustomTime();
};
/**
* Retrieve the current custom time.
* @return {Date} customTime
*/
links.Timeline.prototype.getCustomTime = function() {
return new Date(this.customTime);
};
/**
* Set a custom scale. Autoscaling will be disabled.
* For example setScale(SCALE.MINUTES, 5) will result
* in minor steps of 5 minutes, and major steps of an hour.
*
* @param {links.Timeline.StepDate.SCALE} scale
* A scale. Choose from SCALE.MILLISECOND,
* SCALE.SECOND, SCALE.MINUTE, SCALE.HOUR,
* SCALE.WEEKDAY, SCALE.DAY, SCALE.MONTH,
* SCALE.YEAR.
* @param {int} step A step size, by default 1. Choose for
* example 1, 2, 5, or 10.
*/
links.Timeline.prototype.setScale = function(scale, step) {
this.step.setScale(scale, step);
this.render(); // TODO: optimize: only reflow/repaint axis
};
/**
* Enable or disable autoscaling
* @param {boolean} enable If true or not defined, autoscaling is enabled.
* If false, autoscaling is disabled.
*/
links.Timeline.prototype.setAutoScale = function(enable) {
this.step.setAutoScale(enable);
this.render(); // TODO: optimize: only reflow/repaint axis
};
/**
* Redraw the timeline
* Reloads the (linked) data table and redraws the timeline when resized.
* See also the method checkResize
*/
links.Timeline.prototype.redraw = function() {
this.setData(this.data);
};
/**
* Check if the timeline is resized, and if so, redraw the timeline.
* Useful when the webpage is resized.
*/
links.Timeline.prototype.checkResize = function() {
// TODO: re-implement the method checkResize, or better, make it redundant as this.render will be smarter
this.render();
};
/**
* Check whether a given item is editable
* @param {links.Timeline.Item} item
* @return {boolean} editable
*/
links.Timeline.prototype.isEditable = function (item) {
if (item) {
if (item.editable != undefined) {
return item.editable;
}
else {
return this.options.editable;
}
}
return false;
};
/**
* Calculate the factor and offset to convert a position on screen to the
* corresponding date and vice versa.
* After the method calcConversionFactor is executed once, the methods screenToTime and
* timeToScreen can be used.
*/
links.Timeline.prototype.recalcConversion = function() {
this.conversion.offset = parseFloat(this.start.valueOf());
this.conversion.factor = parseFloat(this.size.contentWidth) /
parseFloat(this.end.valueOf() - this.start.valueOf());
};
/**
* Convert a position on screen (pixels) to a datetime
* Before this method can be used, the method calcConversionFactor must be
* executed once.
* @param {int} x Position on the screen in pixels
* @return {Date} time The datetime the corresponds with given position x
*/
links.Timeline.prototype.screenToTime = function(x) {
var conversion = this.conversion,
time = new Date(parseFloat(x) / conversion.factor + conversion.offset);
return time;
};
/**
* Convert a datetime (Date object) into a position on the screen
* Before this method can be used, the method calcConversionFactor must be
* executed once.
* @param {Date} time A date
* @return {int} x The position on the screen in pixels which corresponds
* with the given date.
*/
links.Timeline.prototype.timeToScreen = function(time) {
var conversion = this.conversion;
var x = (time.valueOf() - conversion.offset) * conversion.factor;
return x;
};
/**
* Event handler for touchstart event on mobile devices
*/
links.Timeline.prototype.onTouchStart = function(event) {
var params = this.eventParams,
me = this;
if (params.touchDown) {
// if already moving, return
return;
}
params.touchDown = true;
params.zoomed = false;
this.onMouseDown(event);
if (!params.onTouchMove) {
params.onTouchMove = function (event) {me.onTouchMove(event);};
links.Timeline.addEventListener(document, "touchmove", params.onTouchMove);
}
if (!params.onTouchEnd) {
params.onTouchEnd = function (event) {me.onTouchEnd(event);};
links.Timeline.addEventListener(document, "touchend", params.onTouchEnd);
}
/* TODO
// check for double tap event
var delta = 500; // ms
var doubleTapStart = (new Date()).getTime();
var target = links.Timeline.getTarget(event);
var doubleTapItem = this.getItemIndex(target);
if (params.doubleTapStart &&
(doubleTapStart - params.doubleTapStart) < delta &&
doubleTapItem == params.doubleTapItem) {
delete params.doubleTapStart;
delete params.doubleTapItem;
me.onDblClick(event);
params.touchDown = false;
}
params.doubleTapStart = doubleTapStart;
params.doubleTapItem = doubleTapItem;
*/
// store timing for double taps
var target = links.Timeline.getTarget(event);
var item = this.getItemIndex(target);
params.doubleTapStartPrev = params.doubleTapStart;
params.doubleTapStart = (new Date()).getTime();
params.doubleTapItemPrev = params.doubleTapItem;
params.doubleTapItem = item;
links.Timeline.preventDefault(event);
};
/**
* Event handler for touchmove event on mobile devices
*/
links.Timeline.prototype.onTouchMove = function(event) {
var params = this.eventParams;
if (event.scale && event.scale !== 1) {
params.zoomed = true;
}
if (!params.zoomed) {
// move
this.onMouseMove(event);
}
else {
if (this.options.zoomable) {
// pinch
// TODO: pinch only supported on iPhone/iPad. Create something manually for Android?
params.zoomed = true;
var scale = event.scale,
oldWidth = (params.end.valueOf() - params.start.valueOf()),
newWidth = oldWidth / scale,
diff = newWidth - oldWidth,
start = new Date(parseInt(params.start.valueOf() - diff/2)),
end = new Date(parseInt(params.end.valueOf() + diff/2));
// TODO: determine zoom-around-date from touch positions?
this.setVisibleChartRange(start, end);
this.trigger("rangechange");
}
}
links.Timeline.preventDefault(event);
};
/**
* Event handler for touchend event on mobile devices
*/
links.Timeline.prototype.onTouchEnd = function(event) {
var params = this.eventParams;
var me = this;
params.touchDown = false;
if (params.zoomed) {
this.trigger("rangechanged");
}
if (params.onTouchMove) {
links.Timeline.removeEventListener(document, "touchmove", params.onTouchMove);
delete params.onTouchMove;
}
if (params.onTouchEnd) {
links.Timeline.removeEventListener(document, "touchend", params.onTouchEnd);
delete params.onTouchEnd;
}
this.onMouseUp(event);
// check for double tap event
var delta = 500; // ms
var doubleTapEnd = (new Date()).getTime();
var target = links.Timeline.getTarget(event);
var doubleTapItem = this.getItemIndex(target);
if (params.doubleTapStartPrev &&
(doubleTapEnd - params.doubleTapStartPrev) < delta &&
params.doubleTapItem == params.doubleTapItemPrev) {
params.touchDown = true;
me.onDblClick(event);
params.touchDown = false;
}
links.Timeline.preventDefault(event);
};
/**
* Start a moving operation inside the provided parent element
* @param {event} event The event that occurred (required for
* retrieving the mouse position)
*/
links.Timeline.prototype.onMouseDown = function(event) {
event = event || window.event;
var params = this.eventParams,
options = this.options,
dom = this.dom;
// only react on left mouse button down
var leftButtonDown = event.which ? (event.which == 1) : (event.button == 1);
if (!leftButtonDown && !params.touchDown) {
return;
}
// get mouse position
if (!params.touchDown) {
params.mouseX = event.clientX;
params.mouseY = event.clientY;
}
else {
params.mouseX = event.targetTouches[0].clientX;
params.mouseY = event.targetTouches[0].clientY;
}
if (params.mouseX === undefined) {params.mouseX = 0;}
if (params.mouseY === undefined) {params.mouseY = 0;}
params.frameLeft = links.Timeline.getAbsoluteLeft(this.dom.content);
params.frameTop = links.Timeline.getAbsoluteTop(this.dom.content);
params.previousLeft = 0;
params.previousOffset = 0;
params.moved = false;
params.start = new Date(this.start);
params.end = new Date(this.end);
params.target = links.Timeline.getTarget(event);
var dragLeft = (dom.items && dom.items.dragLeft) ? dom.items.dragLeft : undefined;
var dragRight = (dom.items && dom.items.dragRight) ? dom.items.dragRight : undefined;
params.itemDragLeft = (params.target === dragLeft);
params.itemDragRight = (params.target === dragRight);
if (params.itemDragLeft || params.itemDragRight) {
params.itemIndex = this.selection ? this.selection.index : undefined;
}
else {
params.itemIndex = this.getItemIndex(params.target);
}
params.customTime = (params.target === dom.customTime ||
params.target.parentNode === dom.customTime) ?
this.customTime :
undefined;
params.addItem = (options.editable && event.ctrlKey);
if (params.addItem) {
// create a new event at the current mouse position
var x = params.mouseX - params.frameLeft;
var y = params.mouseY - params.frameTop;
var xstart = this.screenToTime(x);
if (options.snapEvents) {
this.step.snap(xstart);
}
var xend = new Date(xstart);
var content = "New";
var group = this.getGroupFromHeight(y);
this.addItem({
'start': xstart,
'end': xend,
'content': content,
'group': this.getGroupName(group)
});
params.itemIndex = (this.items.length - 1);
this.selectItem(params.itemIndex);
params.itemDragRight = true;
}
var item = this.items[params.itemIndex];
var isSelected = this.isSelected(params.itemIndex);
params.editItem = isSelected && this.isEditable(item);
if (params.editItem) {
params.itemStart = item.start;
params.itemEnd = item.end;
params.itemGroup = item.group;
params.itemLeft = item.start ? this.timeToScreen(item.start) : undefined;
params.itemRight = item.end ? this.timeToScreen(item.end) : undefined;
}
else {
this.dom.frame.style.cursor = 'move';
}
if (!params.touchDown) {
// add event listeners to handle moving the contents
// we store the function onmousemove and onmouseup in the timeline, so we can
// remove the eventlisteners lateron in the function mouseUp()
var me = this;
if (!params.onMouseMove) {
params.onMouseMove = function (event) {me.onMouseMove(event);};
links.Timeline.addEventListener(document, "mousemove", params.onMouseMove);
}
if (!params.onMouseUp) {
params.onMouseUp = function (event) {me.onMouseUp(event);};
links.Timeline.addEventListener(document, "mouseup", params.onMouseUp);
}
links.Timeline.preventDefault(event);
}
};
/**
* Perform moving operating.
* This function activated from within the funcion links.Timeline.onMouseDown().
* @param {event} event Well, eehh, the event
*/
links.Timeline.prototype.onMouseMove = function (event) {
event = event || window.event;
var params = this.eventParams,
size = this.size,
dom = this.dom,
options = this.options;
// calculate change in mouse position
var mouseX, mouseY;
if (!params.touchDown) {
mouseX = event.clientX;
mouseY = event.clientY;
}
else {
mouseX = event.targetTouches[0].clientX;
mouseY = event.targetTouches[0].clientY;
}
if (mouseX === undefined) {mouseX = 0;}
if (mouseY === undefined) {mouseY = 0;}
if (params.mouseX === undefined) {
params.mouseX = mouseX;
}
if (params.mouseY === undefined) {
params.mouseY = mouseY;
}
var diffX = parseFloat(mouseX) - params.mouseX;
var diffY = parseFloat(mouseY) - params.mouseY;
// if mouse movement is big enough, register it as a "moved" event
if (Math.abs(diffX) >= 1) {
params.moved = true;
}
if (params.customTime) {
var x = this.timeToScreen(params.customTime);
var xnew = x + diffX;
this.customTime = this.screenToTime(xnew);
this.repaintCustomTime();
// fire a timechange event
this.trigger('timechange');
}
else if (params.editItem) {
var item = this.items[params.itemIndex],
left,
right;
if (params.itemDragLeft) {
// move the start of the item
left = params.itemLeft + diffX;
right = params.itemRight;
item.start = this.screenToTime(left);
if (options.snapEvents) {
this.step.snap(item.start);
left = this.timeToScreen(item.start);
}
if (left > right) {
left = right;
item.start = this.screenToTime(left);
}
}
else if (params.itemDragRight) {
// move the end of the item
left = params.itemLeft;
right = params.itemRight + diffX;
item.end = this.screenToTime(right);
if (options.snapEvents) {
this.step.snap(item.end);
right = this.timeToScreen(item.end);
}
if (right < left) {
right = left;
item.end = this.screenToTime(right);
}
}
else {
// move the item
left = params.itemLeft + diffX;
item.start = this.screenToTime(left);
if (options.snapEvents) {
this.step.snap(item.start);
left = this.timeToScreen(item.start);
}
if (item.end) {
right = left + (params.itemRight - params.itemLeft);
item.end = this.screenToTime(right);
}
}
item.setPosition(left, right);
if (this.groups.length == 0) {
// TODO: does not work well in FF, forces redraw with every mouse move it seems
this.render(); // TODO: optimize, only redraw the items?
// Note: when animate==true, no redraw is needed here, its done by stackItems animation
}
else {
// move item from one group to another when needed
var y = mouseY - params.frameTop;
var group = this.getGroupFromHeight(y);
if (options.groupsChangeable && item.group !== group) {
// move item to the other group
var index = this.items.indexOf(item);
this.changeItem(index, {'group': this.getGroupName(group)});
}
else {
this.repaintDeleteButton();
this.repaintDragAreas();
}
}
}
else if (options.moveable) {
var interval = (params.end.valueOf() - params.start.valueOf());
var diffMillisecs = Math.round(parseFloat(-diffX) / size.contentWidth * interval);
var newStart = new Date(params.start.valueOf() + diffMillisecs);
var newEnd = new Date(params.end.valueOf() + diffMillisecs);
this.applyRange(newStart, newEnd);
// if the applied range is moved due to a fixed min or max,
// change the diffMillisecs accordingly
var appliedDiff = (this.start.valueOf() - newStart.valueOf());
if (appliedDiff) {
diffMillisecs += appliedDiff;
}
this.recalcConversion();
// move the items by changing the left position of their frame.
// this is much faster than repositioning all elements individually via the
// repaintFrame() function (which is done once at mouseup)
// note that we round diffX to prevent wrong positioning on millisecond scale
var previousLeft = params.previousLeft || 0;
var currentLeft = parseFloat(dom.items.frame.style.left) || 0;
var previousOffset = params.previousOffset || 0;
var frameOffset = previousOffset + (currentLeft - previousLeft);
var frameLeft = -diffMillisecs / interval * size.contentWidth + frameOffset;
dom.items.frame.style.left = (frameLeft) + "px";
// read the left again from DOM (IE8- rounds the value)
params.previousOffset = frameOffset;
params.previousLeft = parseFloat(dom.items.frame.style.left) || frameLeft;
this.repaintCurrentTime();
this.repaintCustomTime();
this.repaintAxis();
// fire a rangechange event
this.trigger('rangechange');
}
links.Timeline.preventDefault(event);
};
/**
* Stop moving operating.
* This function activated from within the funcion links.Timeline.onMouseDown().
* @param {event} event The event
*/
links.Timeline.prototype.onMouseUp = function (event) {
var params = this.eventParams,
options = this.options;
event = event || window.event;
this.dom.frame.style.cursor = 'auto';
// remove event listeners here, important for Safari
if (params.onMouseMove) {
links.Timeline.removeEventListener(document, "mousemove", params.onMouseMove);
delete params.onMouseMove;
}
if (params.onMouseUp) {
links.Timeline.removeEventListener(document, "mouseup", params.onMouseUp);
delete params.onMouseUp;
}
//links.Timeline.preventDefault(event);
if (params.customTime) {
// fire a timechanged event
this.trigger('timechanged');
}
else if (params.editItem) {
var item = this.items[params.itemIndex];
if (params.moved || params.addItem) {
this.applyChange = true;
this.applyAdd = true;
this.updateData(params.itemIndex, {
'start': item.start,
'end': item.end
});
// fire an add or change event.
// Note that the change can be canceled from within an event listener if
// this listener calls the method cancelChange().
this.trigger(params.addItem ? 'add' : 'change');
if (params.addItem) {
if (this.applyAdd) {
this.updateData(params.itemIndex, {
'start': item.start,
'end': item.end,
'content': item.content,
'group': this.getGroupName(item.group)
});
}
else {
// undo an add
this.deleteItem(params.itemIndex);
}
}
else {
if (this.applyChange) {
this.updateData(params.itemIndex, {
'start': item.start,
'end': item.end
});
}
else {
// undo a change
delete this.applyChange;
delete this.applyAdd;
var item = this.items[params.itemIndex],
domItem = item.dom;
item.start = params.itemStart;
item.end = params.itemEnd;
item.group = params.itemGroup;
// TODO: original group should be restored too
item.setPosition(params.itemLeft, params.itemRight);
}
}
this.render();
}
}
else {
if (!params.moved && !params.zoomed) {
// mouse did not move -> user has selected an item
if (params.target === this.dom.items.deleteButton) {
// delete item
if (this.selection) {
this.confirmDeleteItem(this.selection.index);
}
}
else if (options.selectable) {
// select/unselect item
if (params.itemIndex !== undefined) {
if (!this.isSelected(params.itemIndex)) {
this.selectItem(params.itemIndex);
this.trigger('select');
}
}
else {
this.unselectItem();
this.trigger('select');
}
}
}
else {
// timeline is moved
// TODO: optimize: no need to reflow and cluster again?
this.render();
if ((params.moved && options.moveable) || (params.zoomed && options.zoomable) ) {
// fire a rangechanged event
this.trigger('rangechanged');
}
}
}
};
/**
* Double click event occurred for an item
* @param {event} event
*/
links.Timeline.prototype.onDblClick = function (event) {
var params = this.eventParams,
options = this.options,
dom = this.dom,
size = this.size;
event = event || window.event;
if (params.itemIndex !== undefined) {
var item = this.items[params.itemIndex];
if (item && this.isEditable(item)) {
// fire the edit event
this.trigger('edit');
}
}
else {
if (options.editable) {
// create a new item
// get mouse position
if (!params.touchDown) {
params.mouseX = event.clientX;
params.mouseY = event.clientY;
}
if (params.mouseX === undefined) {params.mouseX = 0;}
if (params.mouseY === undefined) {params.mouseY = 0;}
var x = params.mouseX - links.Timeline.getAbsoluteLeft(dom.content);
var y = params.mouseY - links.Timeline.getAbsoluteTop(dom.content);
// create a new event at the current mouse position
var xstart = this.screenToTime(x);
var xend = this.screenToTime(x + size.frameWidth / 10); // add 10% of timeline width
if (options.snapEvents) {
this.step.snap(xstart);
this.step.snap(xend);
}
var content = "New";
var group = this.getGroupFromHeight(y); // (group may be undefined)
this.addItem({
'start': xstart,
'end': xend,
'content': content,
'group': this.getGroupName(group)
});
params.itemIndex = (this.items.length - 1);
this.selectItem(params.itemIndex);
this.applyAdd = true;
// fire an add event.
// Note that the change can be canceled from within an event listener if
// this listener calls the method cancelAdd().
this.trigger('add');
if (!this.applyAdd) {
// undo an add
this.deleteItem(params.itemIndex);
}
}
}
links.Timeline.preventDefault(event);
};
/**
* Event handler for mouse wheel event, used to zoom the timeline
* Code from http://adomas.org/javascript-mouse-wheel/
* @param {event} event The event
*/
links.Timeline.prototype.onMouseWheel = function(event) {
if (!this.options.zoomable)
return;
if (!event) { /* For IE. */
event = window.event;
}
// retrieve delta
var delta = 0;
if (event.wheelDelta) { /* IE/Opera. */
delta = event.wheelDelta/120;
} else if (event.detail) { /* Mozilla case. */
// In Mozilla, sign of delta is different than in IE.
// Also, delta is multiple of 3.
delta = -event.detail/3;
}
// If delta is nonzero, handle it.
// Basically, delta is now positive if wheel was scrolled up,
// and negative, if wheel was scrolled down.
if (delta) {
// TODO: on FireFox, the window is not redrawn within repeated scroll-events
// -> use a delayed redraw? Make a zoom queue?
var timeline = this;
var zoom = function () {
// perform the zoom action. Delta is normally 1 or -1
var zoomFactor = delta / 5.0;
var frameLeft = links.Timeline.getAbsoluteLeft(timeline.dom.content);
var zoomAroundDate =
(event.clientX != undefined && frameLeft != undefined) ?
timeline.screenToTime(event.clientX - frameLeft) :
undefined;
timeline.zoom(zoomFactor, zoomAroundDate);
// fire a rangechange and a rangechanged event
timeline.trigger("rangechange");
timeline.trigger("rangechanged");
/* TODO: smooth scrolling on FF
timeline.zooming = false;
if (timeline.zoomingQueue) {
setTimeout(timeline.zoomingQueue, 100);
timeline.zoomingQueue = undefined;
}
timeline.zoomCount = (timeline.zoomCount || 0) + 1;
console.log('zoomCount', timeline.zoomCount)
*/
};
zoom();
/* TODO: smooth scrolling on FF
if (!timeline.zooming || true) {
timeline.zooming = true;
setTimeout(zoom, 100);
}
else {
timeline.zoomingQueue = zoom;
}
//*/
}
// Prevent default actions caused by mouse wheel.
// That might be ugly, but we handle scrolls somehow
// anyway, so don't bother here...
links.Timeline.preventDefault(event);
};
/**
* Zoom the timeline the given zoomfactor in or out. Start and end date will
* be adjusted, and the timeline will be redrawn. You can optionally give a
* date around which to zoom.
* For example, try zoomfactor = 0.1 or -0.1
* @param {Number} zoomFactor Zooming amount. Positive value will zoom in,
* negative value will zoom out
* @param {Date} zoomAroundDate Date around which will be zoomed. Optional
*/
links.Timeline.prototype.zoom = function(zoomFactor, zoomAroundDate) {
// if zoomAroundDate is not provided, take it half between start Date and end Date
if (zoomAroundDate == undefined) {
zoomAroundDate = new Date((this.start.valueOf() + this.end.valueOf()) / 2);
}
// prevent zoom factor larger than 1 or smaller than -1 (larger than 1 will
// result in a start>=end )
if (zoomFactor >= 1) {
zoomFactor = 0.9;
}
if (zoomFactor <= -1) {
zoomFactor = -0.9;
}
// adjust a negative factor such that zooming in with 0.1 equals zooming
// out with a factor -0.1
if (zoomFactor < 0) {
zoomFactor = zoomFactor / (1 + zoomFactor);
}
// zoom start Date and end Date relative to the zoomAroundDate
var startDiff = parseFloat(this.start.valueOf() - zoomAroundDate.valueOf());
var endDiff = parseFloat(this.end.valueOf() - zoomAroundDate.valueOf());
// calculate new dates
var newStart = new Date(this.start.valueOf() - startDiff * zoomFactor);
var newEnd = new Date(this.end.valueOf() - endDiff * zoomFactor);
this.applyRange(newStart, newEnd, zoomAroundDate);
this.render({
animate: this.options.animate && this.options.animateZoom
});
};
/**
* Move the timeline the given movefactor to the left or right. Start and end
* date will be adjusted, and the timeline will be redrawn.
* For example, try moveFactor = 0.1 or -0.1
* @param {Number} moveFactor Moving amount. Positive value will move right,
* negative value will move left
*/
links.Timeline.prototype.move = function(moveFactor) {
// zoom start Date and end Date relative to the zoomAroundDate
var diff = parseFloat(this.end.valueOf() - this.start.valueOf());
// apply new dates
var newStart = new Date(this.start.valueOf() + diff * moveFactor);
var newEnd = new Date(this.end.valueOf() + diff * moveFactor);
this.applyRange(newStart, newEnd);
this.render(); // TODO: optimize, no need to reflow, only to recalc conversion and repaint
};
/**
* Apply a visible range. The range is limited to feasible maximum and minimum
* range.
* @param {Date} start
* @param {Date} end
* @param {Date} zoomAroundDate Optional. Date around which will be zoomed.
*/
links.Timeline.prototype.applyRange = function (start, end, zoomAroundDate) {
// calculate new start and end value
var startValue = start.valueOf();
var endValue = end.valueOf();
var interval = (endValue - startValue);
// determine maximum and minimum interval
var options = this.options;
var year = 1000 * 60 * 60 * 24 * 365;
var intervalMin = Number(options.intervalMin) || 10;
if (intervalMin < 10) {
intervalMin = 10;
}
var intervalMax = Number(options.intervalMax) || 10000 * year;
if (intervalMax > 10000 * year) {
intervalMax = 10000 * year;
}
if (intervalMax < intervalMin) {
intervalMax = intervalMin;
}
// determine min and max date value
var min = options.min ? options.min.valueOf() : undefined;
var max = options.max ? options.max.valueOf() : undefined;
if (min != undefined && max != undefined) {
if (min >= max) {
// empty range
var day = 1000 * 60 * 60 * 24;
max = min + day;
}
if (intervalMax > (max - min)) {
intervalMax = (max - min);
}
if (intervalMin > (max - min)) {
intervalMin = (max - min);
}
}
// prevent empty interval
if (startValue >= endValue) {
endValue += 1000 * 60 * 60 * 24;
}
// prevent too small scale
// TODO: IE has problems with milliseconds
if (interval < intervalMin) {
var diff = (intervalMin - interval);
var f = zoomAroundDate ? (zoomAroundDate.valueOf() - startValue) / interval : 0.5;
startValue -= Math.round(diff * f);
endValue += Math.round(diff * (1 - f));
}
// prevent too large scale
if (interval > intervalMax) {
var diff = (interval - intervalMax);
var f = zoomAroundDate ? (zoomAroundDate.valueOf() - startValue) / interval : 0.5;
startValue += Math.round(diff * f);
endValue -= Math.round(diff * (1 - f));
}
// prevent to small start date
if (min != undefined) {
var diff = (startValue - min);
if (diff < 0) {
startValue -= diff;
endValue -= diff;
}
}
// prevent to large end date
if (max != undefined) {
var diff = (max - endValue);
if (diff < 0) {
startValue += diff;
endValue += diff;
}
}
// apply new dates
this.start = new Date(startValue);
this.end = new Date(endValue);
};
/**
* Delete an item after a confirmation.
* The deletion can be cancelled by executing .cancelDelete() during the
* triggered event 'delete'.
* @param {int} index Index of the item to be deleted
*/
links.Timeline.prototype.confirmDeleteItem = function(index) {
this.applyDelete = true;
// select the event to be deleted
if (!this.isSelected(index)) {
this.selectItem(index);
}
// fire a delete event trigger.
// Note that the delete event can be canceled from within an event listener if
// this listener calls the method cancelChange().
this.trigger('delete');
if (this.applyDelete) {
this.deleteItem(index);
}
delete this.applyDelete;
};
/**
* Delete an item
* @param {int} index Index of the item to be deleted
* @param {boolean} [preventRender=false] Do not re-render timeline if true
* (optimization for multiple delete)
*/
links.Timeline.prototype.deleteItem = function(index, preventRender) {
if (index >= this.items.length) {
throw "Cannot delete row, index out of range";
}
if (this.selection) {
// adjust the selection
if (this.selection.index == index) {
// item to be deleted is selected
this.unselectItem();
}
else if (this.selection.index > index) {
// update selection index
this.selection.index--;
}
}
// actually delete the item and remove it from the DOM
var item = this.items.splice(index, 1)[0];
this.renderQueue.hide.push(item);
// delete the row in the original data table
if (this.data) {
if (google && google.visualization &&
this.data instanceof google.visualization.DataTable) {
this.data.removeRow(index);
}
else if (links.Timeline.isArray(this.data)) {
this.data.splice(index, 1);
}
else {
throw "Cannot delete row from data, unknown data type";
}
}
if (!preventRender) {
this.render();
}
};
/**
* Delete all items
*/
links.Timeline.prototype.deleteAllItems = function() {
this.unselectItem();
// delete the loaded items
this.clearItems();
// delete the groups
this.deleteGroups();
// empty original data table
if (this.data) {
if (google && google.visualization &&
this.data instanceof google.visualization.DataTable) {
this.data.removeRows(0, this.data.getNumberOfRows());
}
else if (links.Timeline.isArray(this.data)) {
this.data.splice(0, this.data.length);
}
else {
throw "Cannot delete row from data, unknown data type";
}
}
this.render();
};
/**
* Find the group from a given height in the timeline
* @param {Number} height Height in the timeline
* @return {Object | undefined} group The group object, or undefined if out
* of range
*/
links.Timeline.prototype.getGroupFromHeight = function(height) {
var i,
group,
groups = this.groups;
if (groups) {
if (this.options.axisOnTop) {
for (i = groups.length - 1; i >= 0; i--) {
group = groups[i];
if (height > group.top) {
return group;
}
}
}
else {
for (i = 0; i < groups.length; i++) {
group = groups[i];
if (height > group.top) {
return group;
}
}
}
return group; // return the last group
}
return undefined;
};
/**
* @constructor links.Timeline.Item
* @param {Object} data Object containing parameters start, end
* content, group. type, group.
* @param {Object} [options] Options to set initial property values
* {Number} top
* {Number} left
* {Number} width
* {Number} height
*/
links.Timeline.Item = function (data, options) {
if (data) {
this.start = links.Timeline.parseJSONDate(data.start);
if (data.end) {
this.end = links.Timeline.parseJSONDate(data.end);
}
this.content = data.content;
this.className = data.className;
this.editable = data.editable;
this.group = data.group;
if (this.start) {
if (this.end) {
// range
this.center = (this.start.valueOf() + this.end.valueOf()) / 2;
}
else {
// box, dot
this.center = this.start.valueOf();
}
}
}
this.top = 0;
this.left = 0;
this.width = 0;
this.height = 0;
this.lineWidth = 0;
this.dotWidth = 0;
this.dotHeight = 0;
this.rendered = false; // true when the item is draw in the Timeline DOM
if (options) {
// override the default properties
for (var option in options) {
if (options.hasOwnProperty(option)) {
this[option] = options[option];
}
}
}
};
/**
* Reflow the Item: retrieve its actual size from the DOM
* @return {boolean} resized returns true if the axis is resized
*/
links.Timeline.Item.prototype.reflow = function () {
// Should be implemented by sub-prototype
return false;
};
/**
* Append all image urls present in the items DOM to the provided array
* @param {String[]} imageUrls
*/
links.Timeline.Item.prototype.getImageUrls = function (imageUrls) {
if (this.dom) {
links.imageloader.filterImageUrls(this.dom, imageUrls);
}
};
/**
* Select the item
*/
links.Timeline.Item.prototype.select = function () {
// Should be implemented by sub-prototype
};
/**
* Unselect the item
*/
links.Timeline.Item.prototype.unselect = function () {
// Should be implemented by sub-prototype
};
/**
* Creates the DOM for the item, depending on its type
* @return {Element | undefined}
*/
links.Timeline.Item.prototype.createDOM = function () {
// Should be implemented by sub-prototype
};
/**
* Append the items DOM to the given HTML container. If items DOM does not yet
* exist, it will be created first.
* @param {Element} container
*/
links.Timeline.Item.prototype.showDOM = function (container) {
// Should be implemented by sub-prototype
};
/**
* Remove the items DOM from the current HTML container
* @param {Element} container
*/
links.Timeline.Item.prototype.hideDOM = function (container) {
// Should be implemented by sub-prototype
};
/**
* Update the DOM of the item. This will update the content and the classes
* of the item
*/
links.Timeline.Item.prototype.updateDOM = function () {
// Should be implemented by sub-prototype
};
/**
* Reposition the item, recalculate its left, top, and width, using the current
* range of the timeline and the timeline options.
* @param {links.Timeline} timeline
*/
links.Timeline.Item.prototype.updatePosition = function (timeline) {
// Should be implemented by sub-prototype
};
/**
* Check if the item is drawn in the timeline (i.e. the DOM of the item is
* attached to the frame. You may also just request the parameter item.rendered
* @return {boolean} rendered
*/
links.Timeline.Item.prototype.isRendered = function () {
return this.rendered;
};
/**
* Check if the item is located in the visible area of the timeline, and
* not part of a cluster
* @param {Date} start
* @param {Date} end
* @return {boolean} visible
*/
links.Timeline.Item.prototype.isVisible = function (start, end) {
// Should be implemented by sub-prototype
return false;
};
/**
* Reposition the item
* @param {Number} left
* @param {Number} right
*/
links.Timeline.Item.prototype.setPosition = function (left, right) {
// Should be implemented by sub-prototype
};
/**
* Calculate the right position of the item
* @param {links.Timeline} timeline
* @return {Number} right
*/
links.Timeline.Item.prototype.getRight = function (timeline) {
// Should be implemented by sub-prototype
return 0;
};
/**
* @constructor links.Timeline.ItemBox
* @extends links.Timeline.Item
* @param {Object} data Object containing parameters start, end
* content, group. type, group.
* @param {Object} [options] Options to set initial property values
* {Number} top
* {Number} left
* {Number} width
* {Number} height
*/
links.Timeline.ItemBox = function (data, options) {
links.Timeline.Item.call(this, data, options);
};
links.Timeline.ItemBox.prototype = new links.Timeline.Item();
/**
* Reflow the Item: retrieve its actual size from the DOM
* @return {boolean} resized returns true if the axis is resized
* @override
*/
links.Timeline.ItemBox.prototype.reflow = function () {
var dom = this.dom,
dotHeight = dom.dot.offsetHeight,
dotWidth = dom.dot.offsetWidth,
lineWidth = dom.line.offsetWidth,
resized = (
(this.dotHeight != dotHeight) ||
(this.dotWidth != dotWidth) ||
(this.lineWidth != lineWidth)
);
this.dotHeight = dotHeight;
this.dotWidth = dotWidth;
this.lineWidth = lineWidth;
return resized;
};
/**
* Select the item
* @override
*/
links.Timeline.ItemBox.prototype.select = function () {
var dom = this.dom;
links.Timeline.addClassName(dom, 'timeline-event-selected');
links.Timeline.addClassName(dom.line, 'timeline-event-selected');
links.Timeline.addClassName(dom.dot, 'timeline-event-selected');
};
/**
* Unselect the item
* @override
*/
links.Timeline.ItemBox.prototype.unselect = function () {
var dom = this.dom;
links.Timeline.removeClassName(dom, 'timeline-event-selected');
links.Timeline.removeClassName(dom.line, 'timeline-event-selected');
links.Timeline.removeClassName(dom.dot, 'timeline-event-selected');
};
/**
* Creates the DOM for the item, depending on its type
* @return {Element | undefined}
* @override
*/
links.Timeline.ItemBox.prototype.createDOM = function () {
// background box
var divBox = document.createElement("DIV");
divBox.style.position = "absolute";
divBox.style.left = this.left + "px";
divBox.style.top = this.top + "px";
// contents box (inside the background box). used for making margins
var divContent = document.createElement("DIV");
divContent.className = "timeline-event-content";
divContent.innerHTML = this.content;
divBox.appendChild(divContent);
// line to axis
var divLine = document.createElement("DIV");
divLine.style.position = "absolute";
divLine.style.width = "0px";
// important: the vertical line is added at the front of the list of elements,
// so it will be drawn behind all boxes and ranges
divBox.line = divLine;
// dot on axis
var divDot = document.createElement("DIV");
divDot.style.position = "absolute";
divDot.style.width = "0px";
divDot.style.height = "0px";
divBox.dot = divDot;
this.dom = divBox;
this.updateDOM();
return divBox;
};
/**
* Append the items DOM to the given HTML container. If items DOM does not yet
* exist, it will be created first.
* @param {Element} container
* @override
*/
links.Timeline.ItemBox.prototype.showDOM = function (container) {
var dom = this.dom;
if (!dom) {
dom = this.createDOM();
}
if (dom.parentNode != container) {
if (dom.parentNode) {
// container is changed. remove from old container
this.hideDOM();
}
// append to this container
container.appendChild(dom);
container.insertBefore(dom.line, container.firstChild);
// Note: line must be added in front of the this,
// such that it stays below all this
container.appendChild(dom.dot);
this.rendered = true;
}
};
/**
* Remove the items DOM from the current HTML container, but keep the DOM in
* memory
* @override
*/
links.Timeline.ItemBox.prototype.hideDOM = function () {
var dom = this.dom;
if (dom) {
var parent = dom.parentNode;
if (parent) {
parent.removeChild(dom);
parent.removeChild(dom.line);
parent.removeChild(dom.dot);
this.rendered = false;
}
}
};
/**
* Update the DOM of the item. This will update the content and the classes
* of the item
* @override
*/
links.Timeline.ItemBox.prototype.updateDOM = function () {
var divBox = this.dom;
if (divBox) {
var divLine = divBox.line;
var divDot = divBox.dot;
// update contents
divBox.firstChild.innerHTML = this.content;
// update class
divBox.className = "timeline-event timeline-event-box";
divLine.className = "timeline-event timeline-event-line";
divDot.className = "timeline-event timeline-event-dot";
if (this.isCluster) {
links.Timeline.addClassName(divBox, 'timeline-event-cluster');
links.Timeline.addClassName(divLine, 'timeline-event-cluster');
links.Timeline.addClassName(divDot, 'timeline-event-cluster');
}
// add item specific class name when provided
if (this.className) {
links.Timeline.addClassName(divBox, this.className);
links.Timeline.addClassName(divLine, this.className);
links.Timeline.addClassName(divDot, this.className);
}
// TODO: apply selected className?
}
};
/**
* Reposition the item, recalculate its left, top, and width, using the current
* range of the timeline and the timeline options.
* @param {links.Timeline} timeline
* @override
*/
links.Timeline.ItemBox.prototype.updatePosition = function (timeline) {
var dom = this.dom;
if (dom) {
var left = timeline.timeToScreen(this.start),
axisOnTop = timeline.options.axisOnTop,
axisTop = timeline.size.axis.top,
axisHeight = timeline.size.axis.height,
boxAlign = (timeline.options.box && timeline.options.box.align) ?
timeline.options.box.align : undefined;
dom.style.top = this.top + "px";
if (boxAlign == 'right') {
dom.style.left = (left - this.width) + "px";
}
else if (boxAlign == 'left') {
dom.style.left = (left) + "px";
}
else { // default or 'center'
dom.style.left = (left - this.width/2) + "px";
}
var line = dom.line;
var dot = dom.dot;
line.style.left = (left - this.lineWidth/2) + "px";
dot.style.left = (left - this.dotWidth/2) + "px";
if (axisOnTop) {
line.style.top = axisHeight + "px";
line.style.height = Math.max(this.top - axisHeight, 0) + "px";
dot.style.top = (axisHeight - this.dotHeight/2) + "px";
}
else {
line.style.top = (this.top + this.height) + "px";
line.style.height = Math.max(axisTop - this.top - this.height, 0) + "px";
dot.style.top = (axisTop - this.dotHeight/2) + "px";
}
}
};
/**
* Check if the item is visible in the timeline, and not part of a cluster
* @param {Date} start
* @param {Date} end
* @return {Boolean} visible
* @override
*/
links.Timeline.ItemBox.prototype.isVisible = function (start, end) {
if (this.cluster) {
return false;
}
return (this.start > start) && (this.start < end);
};
/**
* Reposition the item
* @param {Number} left
* @param {Number} right
* @override
*/
links.Timeline.ItemBox.prototype.setPosition = function (left, right) {
var dom = this.dom;
dom.style.left = (left - this.width / 2) + "px";
dom.line.style.left = (left - this.lineWidth / 2) + "px";
dom.dot.style.left = (left - this.dotWidth / 2) + "px";
if (this.group) {
this.top = this.group.top;
dom.style.top = this.top + 'px';
}
};
/**
* Calculate the right position of the item
* @param {links.Timeline} timeline
* @return {Number} right
* @override
*/
links.Timeline.ItemBox.prototype.getRight = function (timeline) {
var boxAlign = (timeline.options.box && timeline.options.box.align) ?
timeline.options.box.align : undefined;
var left = timeline.timeToScreen(this.start);
var right;
if (boxAlign == 'right') {
right = left;
}
else if (boxAlign == 'left') {
right = (left + this.width);
}
else { // default or 'center'
right = (left + this.width / 2);
}
return right;
};
/**
* @constructor links.Timeline.ItemRange
* @extends links.Timeline.Item
* @param {Object} data Object containing parameters start, end
* content, group. type, group.
* @param {Object} [options] Options to set initial property values
* {Number} top
* {Number} left
* {Number} width
* {Number} height
*/
links.Timeline.ItemRange = function (data, options) {
links.Timeline.Item.call(this, data, options);
};
links.Timeline.ItemRange.prototype = new links.Timeline.Item();
/**
* Select the item
* @override
*/
links.Timeline.ItemRange.prototype.select = function () {
var dom = this.dom;
links.Timeline.addClassName(dom, 'timeline-event-selected');
};
/**
* Unselect the item
* @override
*/
links.Timeline.ItemRange.prototype.unselect = function () {
var dom = this.dom;
links.Timeline.removeClassName(dom, 'timeline-event-selected');
};
/**
* Creates the DOM for the item, depending on its type
* @return {Element | undefined}
* @override
*/
links.Timeline.ItemRange.prototype.createDOM = function () {
// background box
var divBox = document.createElement("DIV");
divBox.style.position = "absolute";
// contents box
var divContent = document.createElement("DIV");
divContent.className = "timeline-event-content";
divBox.appendChild(divContent);
this.dom = divBox;
this.updateDOM();
return divBox;
};
/**
* Append the items DOM to the given HTML container. If items DOM does not yet
* exist, it will be created first.
* @param {Element} container
* @override
*/
links.Timeline.ItemRange.prototype.showDOM = function (container) {
var dom = this.dom;
if (!dom) {
dom = this.createDOM();
}
if (dom.parentNode != container) {
if (dom.parentNode) {
// container changed. remove the item from the old container
this.hideDOM();
}
// append to the new container
container.appendChild(dom);
this.rendered = true;
}
};
/**
* Remove the items DOM from the current HTML container
* The DOM will be kept in memory
* @override
*/
links.Timeline.ItemRange.prototype.hideDOM = function () {
var dom = this.dom;
if (dom) {
var parent = dom.parentNode;
if (parent) {
parent.removeChild(dom);
this.rendered = false;
}
}
};
/**
* Update the DOM of the item. This will update the content and the classes
* of the item
* @override
*/
links.Timeline.ItemRange.prototype.updateDOM = function () {
var divBox = this.dom;
if (divBox) {
// update contents
divBox.firstChild.innerHTML = this.content;
// update class
divBox.className = "timeline-event timeline-event-range";
if (this.isCluster) {
links.Timeline.addClassName(divBox, 'timeline-event-cluster');
}
// add item specific class name when provided
if (this.className) {
links.Timeline.addClassName(divBox, this.className);
}
// TODO: apply selected className?
}
};
/**
* Reposition the item, recalculate its left, top, and width, using the current
* range of the timeline and the timeline options. *
* @param {links.Timeline} timeline
* @override
*/
links.Timeline.ItemRange.prototype.updatePosition = function (timeline) {
var dom = this.dom;
if (dom) {
var contentWidth = timeline.size.contentWidth,
left = timeline.timeToScreen(this.start),
right = timeline.timeToScreen(this.end);
// limit the width of the this, as browsers cannot draw very wide divs
if (left < -contentWidth) {
left = -contentWidth;
}
if (right > 2 * contentWidth) {
right = 2 * contentWidth;
}
dom.style.top = this.top + "px";
dom.style.left = left + "px";
//dom.style.width = Math.max(right - left - 2 * this.borderWidth, 1) + "px"; // TODO: borderWidth
dom.style.width = Math.max(right - left, 1) + "px";
}
};
/**
* Check if the item is visible in the timeline, and not part of a cluster
* @param {Number} start
* @param {Number} end
* @return {boolean} visible
* @override
*/
links.Timeline.ItemRange.prototype.isVisible = function (start, end) {
if (this.cluster) {
return false;
}
return (this.end > start)
&& (this.start < end);
};
/**
* Reposition the item
* @param {Number} left
* @param {Number} right
* @override
*/
links.Timeline.ItemRange.prototype.setPosition = function (left, right) {
var dom = this.dom;
dom.style.left = left + 'px';
dom.style.width = (right - left) + 'px';
if (this.group) {
this.top = this.group.top;
dom.style.top = this.top + 'px';
}
};
/**
* Calculate the right position of the item
* @param {links.Timeline} timeline
* @return {Number} right
* @override
*/
links.Timeline.ItemRange.prototype.getRight = function (timeline) {
return timeline.timeToScreen(this.end);
};
/**
* @constructor links.Timeline.ItemDot
* @extends links.Timeline.Item
* @param {Object} data Object containing parameters start, end
* content, group, type.
* @param {Object} [options] Options to set initial property values
* {Number} top
* {Number} left
* {Number} width
* {Number} height
*/
links.Timeline.ItemDot = function (data, options) {
links.Timeline.Item.call(this, data, options);
};
links.Timeline.ItemDot.prototype = new links.Timeline.Item();
/**
* Reflow the Item: retrieve its actual size from the DOM
* @return {boolean} resized returns true if the axis is resized
* @override
*/
links.Timeline.ItemDot.prototype.reflow = function () {
var dom = this.dom,
dotHeight = dom.dot.offsetHeight,
dotWidth = dom.dot.offsetWidth,
contentHeight = dom.content.offsetHeight,
resized = (
(this.dotHeight != dotHeight) ||
(this.dotWidth != dotWidth) ||
(this.contentHeight != contentHeight)
);
this.dotHeight = dotHeight;
this.dotWidth = dotWidth;
this.contentHeight = contentHeight;
return resized;
};
/**
* Select the item
* @override
*/
links.Timeline.ItemDot.prototype.select = function () {
var dom = this.dom;
links.Timeline.addClassName(dom, 'timeline-event-selected');
};
/**
* Unselect the item
* @override
*/
links.Timeline.ItemDot.prototype.unselect = function () {
var dom = this.dom;
links.Timeline.removeClassName(dom, 'timeline-event-selected');
};
/**
* Creates the DOM for the item, depending on its type
* @return {Element | undefined}
* @override
*/
links.Timeline.ItemDot.prototype.createDOM = function () {
// background box
var divBox = document.createElement("DIV");
divBox.style.position = "absolute";
// contents box, right from the dot
var divContent = document.createElement("DIV");
divContent.className = "timeline-event-content";
divBox.appendChild(divContent);
// dot at start
var divDot = document.createElement("DIV");
divDot.style.position = "absolute";
divDot.style.width = "0px";
divDot.style.height = "0px";
divBox.appendChild(divDot);
divBox.content = divContent;
divBox.dot = divDot;
this.dom = divBox;
this.updateDOM();
return divBox;
};
/**
* Append the items DOM to the given HTML container. If items DOM does not yet
* exist, it will be created first.
* @param {Element} container
* @override
*/
links.Timeline.ItemDot.prototype.showDOM = function (container) {
var dom = this.dom;
if (!dom) {
dom = this.createDOM();
}
if (dom.parentNode != container) {
if (dom.parentNode) {
// container changed. remove it from old container first
this.hideDOM();
}
// append to container
container.appendChild(dom);
this.rendered = true;
}
};
/**
* Remove the items DOM from the current HTML container
* @override
*/
links.Timeline.ItemDot.prototype.hideDOM = function () {
var dom = this.dom;
if (dom) {
var parent = dom.parentNode;
if (parent) {
parent.removeChild(dom);
this.rendered = false;
}
}
};
/**
* Update the DOM of the item. This will update the content and the classes
* of the item
* @override
*/
links.Timeline.ItemDot.prototype.updateDOM = function () {
if (this.dom) {
var divBox = this.dom;
var divDot = divBox.dot;
// update contents
divBox.firstChild.innerHTML = this.content;
// update class
divDot.className = "timeline-event timeline-event-dot";
if (this.isCluster) {
links.Timeline.addClassName(divBox, 'timeline-event-cluster');
links.Timeline.addClassName(divDot, 'timeline-event-cluster');
}
// add item specific class name when provided
if (this.className) {
links.Timeline.addClassName(divBox, this.className);
links.Timeline.addClassName(divDot, this.className);
}
// TODO: apply selected className?
}
};
/**
* Reposition the item, recalculate its left, top, and width, using the current
* range of the timeline and the timeline options. *
* @param {links.Timeline} timeline
* @override
*/
links.Timeline.ItemDot.prototype.updatePosition = function (timeline) {
var dom = this.dom;
if (dom) {
var left = timeline.timeToScreen(this.start);
dom.style.top = this.top + "px";
dom.style.left = (left - this.dotWidth / 2) + "px";
dom.content.style.marginLeft = (1.5 * this.dotWidth) + "px";
//dom.content.style.marginRight = (0.5 * this.dotWidth) + "px"; // TODO
dom.dot.style.top = ((this.height - this.dotHeight) / 2) + "px";
}
};
/**
* Check if the item is visible in the timeline, and not part of a cluster.
* @param {Date} start
* @param {Date} end
* @return {boolean} visible
* @override
*/
links.Timeline.ItemDot.prototype.isVisible = function (start, end) {
if (this.cluster) {
return false;
}
return (this.start > start)
&& (this.start < end);
};
/**
* Reposition the item
* @param {Number} left
* @param {Number} right
* @override
*/
links.Timeline.ItemDot.prototype.setPosition = function (left, right) {
var dom = this.dom;
dom.style.left = (left - this.dotWidth / 2) + "px";
if (this.group) {
this.top = this.group.top;
dom.style.top = this.top + 'px';
}
};
/**
* Calculate the right position of the item
* @param {links.Timeline} timeline
* @return {Number} right
* @override
*/
links.Timeline.ItemDot.prototype.getRight = function (timeline) {
return timeline.timeToScreen(this.start) + this.width;
};
/**
* Retrieve the properties of an item.
* @param {Number} index
* @return {Object} properties Object containing item properties:<br>
* {Date} start (required),
* {Date} end (optional),
* {String} content (required),
* {String} group (optional)
*/
links.Timeline.prototype.getItem = function (index) {
if (index >= this.items.length) {
throw "Cannot get item, index out of range";
}
var item = this.items[index];
var properties = {};
properties.start = new Date(item.start);
if (item.end) {
properties.end = new Date(item.end);
}
properties.content = item.content;
if (item.group) {
properties.group = this.getGroupName(item.group);
}
return properties;
};
/**
* Add a new item.
* @param {Object} itemData Object containing item properties:<br>
* {Date} start (required),
* {Date} end (optional),
* {String} content (required),
* {String} group (optional)
*/
links.Timeline.prototype.addItem = function (itemData) {
var itemsData = [
itemData
];
this.addItems(itemsData);
};
/**
* Add new items.
* @param {Array} itemsData An array containing Objects.
* The objects must have the following parameters:
* {Date} start,
* {Date} end,
* {String} content with text or HTML code,
* {String} group
*/
links.Timeline.prototype.addItems = function (itemsData) {
var timeline = this,
items = this.items,
queue = this.renderQueue;
// append the items
itemsData.forEach(function (itemData) {
var index = items.length;
items.push(timeline.createItem(itemData));
timeline.updateData(index, itemData);
// note: there is no need to add the item to the renderQueue, that
// will be done when this.render() is executed and all items are
// filtered again.
});
this.render({
animate: false
});
};
/**
* Create an item object, containing all needed parameters
* @param {Object} itemData Object containing parameters start, end
* content, group.
* @return {Object} item
*/
links.Timeline.prototype.createItem = function(itemData) {
var type = itemData.end ? 'range' : this.options.style;
var data = {
start: itemData.start,
end: itemData.end,
content: itemData.content,
className: itemData.className,
editable: itemData.editable,
group: this.getGroup(itemData.group)
};
// TODO: optimize this, when creating an item, all data is copied twice...
// TODO: is initialTop needed?
var initialTop,
options = this.options;
if (options.axisOnTop) {
initialTop = this.size.axis.height + options.eventMarginAxis + options.eventMargin / 2;
}
else {
initialTop = this.size.contentHeight - options.eventMarginAxis - options.eventMargin / 2;
}
if (type in this.itemTypes) {
return new this.itemTypes[type](data, {'top': initialTop})
}
console.log('ERROR: Unknown event style "' + type + '"');
return new links.Timeline.Item(data, {
'top': initialTop
});
};
/**
* Edit an item
* @param {Number} index
* @param {Object} itemData Object containing item properties:<br>
* {Date} start (required),
* {Date} end (optional),
* {String} content (required),
* {String} group (optional)
*/
links.Timeline.prototype.changeItem = function (index, itemData) {
var oldItem = this.items[index];
if (!oldItem) {
throw "Cannot change item, index out of range";
}
// replace item, merge the changes
var newItem = this.createItem({
'start': itemData.hasOwnProperty('start') ? itemData.start : oldItem.start,
'end': itemData.hasOwnProperty('end') ? itemData.end : oldItem.end,
'content': itemData.hasOwnProperty('content') ? itemData.content : oldItem.content,
'group': itemData.hasOwnProperty('group') ? itemData.group : this.getGroupName(oldItem.group)
});
this.items[index] = newItem;
// append the changes to the render queue
this.renderQueue.hide.push(oldItem);
this.renderQueue.show.push(newItem);
// update the original data table
this.updateData(index, itemData);
// redraw timeline
this.render({
animate: false
});
newItem.select();
};
/**
* Delete all groups
*/
links.Timeline.prototype.deleteGroups = function () {
this.groups = [];
this.groupIndexes = {};
};
/**
* Get a group by the group name. When the group does not exist,
* it will be created.
* @param {String} groupName the name of the group
* @return {Object} groupObject
*/
links.Timeline.prototype.getGroup = function (groupName) {
var groups = this.groups,
groupIndexes = this.groupIndexes,
groupObj = undefined;
var groupIndex = groupIndexes[groupName];
if (groupIndex === undefined && groupName !== undefined) {
groupObj = {
'content': groupName,
'labelTop': 0,
'lineTop': 0
// note: this object will lateron get addition information,
// such as height and width of the group
};
groups.push(groupObj);
// sort the groups
groups = groups.sort(function (a, b) {
if (a.content > b.content) {
return 1;
}
if (a.content < b.content) {
return -1;
}
return 0;
});
// rebuilt the groupIndexes
for (var i = 0, iMax = groups.length; i < iMax; i++) {
groupIndexes[groups[i].content] = i;
}
}
else {
groupObj = groups[groupIndex];
}
return groupObj;
};
/**
* Get the group name from a group object.
* @param {Object} groupObject
* @return {String} groupName the name of the group, or undefined when group
* was not provided
*/
links.Timeline.prototype.getGroupName = function (groupObj) {
return groupObj ? groupObj.content : undefined;
}
/**
* Cancel a change item
* This method can be called insed an event listener which catches the "change"
* event. The changed event position will be undone.
*/
links.Timeline.prototype.cancelChange = function () {
this.applyChange = false;
};
/**
* Cancel deletion of an item
* This method can be called insed an event listener which catches the "delete"
* event. Deletion of the event will be undone.
*/
links.Timeline.prototype.cancelDelete = function () {
this.applyDelete = false;
};
/**
* Cancel creation of a new item
* This method can be called insed an event listener which catches the "new"
* event. Creation of the new the event will be undone.
*/
links.Timeline.prototype.cancelAdd = function () {
this.applyAdd = false;
};
/**
* Select an event. The visible chart range will be moved such that the selected
* event is placed in the middle.
* For example selection = [{row: 5}];
* @param {Array} selection An array with a column row, containing the row
* number (the id) of the event to be selected.
* @return {boolean} true if selection is succesfully set, else false.
*/
links.Timeline.prototype.setSelection = function(selection) {
if (selection != undefined && selection.length > 0) {
if (selection[0].row != undefined) {
var index = selection[0].row;
if (this.items[index]) {
var item = this.items[index];
this.selectItem(index);
// move the visible chart range to the selected event.
var start = item.start;
var end = item.end;
var middle;
if (end != undefined) {
middle = new Date((end.valueOf() + start.valueOf()) / 2);
} else {
middle = new Date(start);
}
var diff = (this.end.valueOf() - this.start.valueOf()),
newStart = new Date(middle.valueOf() - diff/2),
newEnd = new Date(middle.valueOf() + diff/2);
this.setVisibleChartRange(newStart, newEnd);
return true;
}
}
}
else {
// unselect current selection
this.unselectItem();
}
return false;
};
/**
* Retrieve the currently selected event
* @return {Array} sel An array with a column row, containing the row number
* of the selected event. If there is no selection, an
* empty array is returned.
*/
links.Timeline.prototype.getSelection = function() {
var sel = [];
if (this.selection) {
sel.push({"row": this.selection.index});
}
return sel;
};
/**
* Select an item by its index
* @param {Number} index
*/
links.Timeline.prototype.selectItem = function(index) {
this.unselectItem();
this.selection = undefined;
if (this.items[index] !== undefined) {
var item = this.items[index],
domItem = item.dom;
this.selection = {
'index': index,
'item': domItem
};
// TODO: move adjusting the domItem to the item itself
if (this.isEditable(item)) {
domItem.style.cursor = 'move';
}
item.select();
this.repaintDeleteButton();
this.repaintDragAreas();
}
};
/**
* Check if an item is currently selected
* @param {Number} index
* @return {boolean} true if row is selected, else false
*/
links.Timeline.prototype.isSelected = function (index) {
return (this.selection && this.selection.index === index);
};
/**
* Unselect the currently selected event (if any)
*/
links.Timeline.prototype.unselectItem = function() {
if (this.selection) {
var item = this.items[this.selection.index];
if (item && item.dom) {
var domItem = item.dom;
domItem.style.cursor = '';
item.unselect();
}
this.selection = undefined;
this.repaintDeleteButton();
this.repaintDragAreas();
}
};
/**
* Stack the items such that they don't overlap. The items will have a minimal
* distance equal to options.eventMargin.
* @param {boolean | undefined} animate if animate is true, the items are
* moved to their new position animated
* defaults to false.
*/
links.Timeline.prototype.stackItems = function(animate) {
if (this.groups.length > 0) {
// under this conditions we refuse to stack the events
// TODO: implement support for stacking items per group
return;
}
if (animate == undefined) {
animate = false;
}
// calculate the order and final stack position of the items
var stack = this.stack;
if (!stack) {
stack = {};
this.stack = stack;
}
stack.sortedItems = this.stackOrder(this.renderedItems);
stack.finalItems = this.stackCalculateFinal(stack.sortedItems);
if (animate || stack.timer) {
// move animated to the final positions
var timeline = this;
var step = function () {
var arrived = timeline.stackMoveOneStep(stack.sortedItems,
stack.finalItems);
timeline.repaint();
if (!arrived) {
stack.timer = setTimeout(step, 30);
}
else {
delete stack.timer;
}
};
if (!stack.timer) {
stack.timer = setTimeout(step, 30);
}
}
else {
// move immediately to the final positions
this.stackMoveToFinal(stack.sortedItems, stack.finalItems);
}
};
/**
* Cancel any running animation
*/
links.Timeline.prototype.stackCancelAnimation = function() {
if (this.stack && this.stack.timer) {
clearTimeout(this.stack.timer);
delete this.stack.timer;
}
};
/**
* Order the items in the array this.items. The order is determined via:
* - Ranges go before boxes and dots.
* - The item with the oldest start time goes first
* @param {Array} items Array with items
* @return {Array} sortedItems Array with sorted items
*/
links.Timeline.prototype.stackOrder = function(items) {
// TODO: store the sorted items, to have less work later on
var sortedItems = items.concat([]);
var f = function (a, b) {
if ((a instanceof links.Timeline.ItemRange) &&
!(b instanceof links.Timeline.ItemRange)) {
return -1;
}
if (!(a instanceof links.Timeline.ItemRange) &&
(b instanceof links.Timeline.ItemRange)) {
return 1;
}
return (a.left - b.left);
};
sortedItems.sort(f);
return sortedItems;
};
/**
* Adjust vertical positions of the events such that they don't overlap each
* other.
* @param {timeline.Item[]} items
* @return {Object[]} finalItems
*/
links.Timeline.prototype.stackCalculateFinal = function(items) {
var i,
iMax,
size = this.size,
axisTop = size.axis.top,
axisHeight = size.axis.height,
options = this.options,
axisOnTop = options.axisOnTop,
eventMargin = options.eventMargin,
eventMarginAxis = options.eventMarginAxis,
finalItems = [];
// initialize final positions
for (i = 0, iMax = items.length; i < iMax; i++) {
var item = items[i],
top,
bottom,
height = item.height,
width = item.width,
right = item.getRight(this),
left = right - width;
if (axisOnTop) {
top = axisHeight + eventMarginAxis + eventMargin / 2;
}
else {
top = axisTop - height - eventMarginAxis - eventMargin / 2;
}
bottom = top + height;
finalItems[i] = {
'left': left,
'top': top,
'right': right,
'bottom': bottom,
'height': height,
'item': item
};
}
if (this.options.stackEvents) {
// calculate new, non-overlapping positions
//var items = sortedItems;
for (i = 0, iMax = finalItems.length; i < iMax; i++) {
//for (var i = finalItems.length - 1; i >= 0; i--) {
var finalItem = finalItems[i];
var collidingItem = null;
do {
// TODO: optimize checking for overlap. when there is a gap without items,
// you only need to check for items from the next item on, not from zero
collidingItem = this.stackItemsCheckOverlap(finalItems, i, 0, i-1);
if (collidingItem != null) {
// There is a collision. Reposition the event above the colliding element
if (axisOnTop) {
finalItem.top = collidingItem.top + collidingItem.height + eventMargin;
}
else {
finalItem.top = collidingItem.top - finalItem.height - eventMargin;
}
finalItem.bottom = finalItem.top + finalItem.height;
}
} while (collidingItem);
}
}
return finalItems;
};
/**
* Move the events one step in the direction of their final positions
* @param {Array} currentItems Array with the real items and their current
* positions
* @param {Array} finalItems Array with objects containing the final
* positions of the items
* @return {boolean} arrived True if all items have reached their final
* location, else false
*/
links.Timeline.prototype.stackMoveOneStep = function(currentItems, finalItems) {
var arrived = true;
// apply new positions animated
for (i = 0, iMax = currentItems.length; i < iMax; i++) {
var finalItem = finalItems[i],
item = finalItem.item;
var topNow = parseInt(item.top);
var topFinal = parseInt(finalItem.top);
var diff = (topFinal - topNow);
if (diff) {
var step = (topFinal == topNow) ? 0 : ((topFinal > topNow) ? 1 : -1);
if (Math.abs(diff) > 4) step = diff / 4;
var topNew = parseInt(topNow + step);
if (topNew != topFinal) {
arrived = false;
}
item.top = topNew;
item.bottom = item.top + item.height;
}
else {
item.top = finalItem.top;
item.bottom = finalItem.bottom;
}
item.left = finalItem.left;
item.right = finalItem.right;
}
return arrived;
};
/**
* Move the events from their current position to the final position
* @param {Array} currentItems Array with the real items and their current
* positions
* @param {Array} finalItems Array with objects containing the final
* positions of the items
*/
links.Timeline.prototype.stackMoveToFinal = function(currentItems, finalItems) {
// Put the events directly at there final position
for (i = 0, iMax = currentItems.length; i < iMax; i++) {
var current = currentItems[i],
finalItem = finalItems[i];
current.left = finalItem.left;
current.top = finalItem.top;
current.right = finalItem.right;
current.bottom = finalItem.bottom;
}
};
/**
* Check if the destiny position of given item overlaps with any
* of the other items from index itemStart to itemEnd.
* @param {Array} items Array with items
* @param {int} itemIndex Number of the item to be checked for overlap
* @param {int} itemStart First item to be checked.
* @param {int} itemEnd Last item to be checked.
* @return {Object} colliding item, or undefined when no collisions
*/
links.Timeline.prototype.stackItemsCheckOverlap = function(items, itemIndex,
itemStart, itemEnd) {
var eventMargin = this.options.eventMargin,
collision = this.collision;
// we loop from end to start, as we suppose that the chance of a
// collision is larger for items at the end, so check these first.
var item1 = items[itemIndex];
for (var i = itemEnd; i >= itemStart; i--) {
var item2 = items[i];
if (collision(item1, item2, eventMargin)) {
if (i != itemIndex) {
return item2;
}
}
}
return undefined;
};
/**
* Test if the two provided items collide
* The items must have parameters left, right, top, and bottom.
* @param {Element} item1 The first item
* @param {Element} item2 The second item
* @param {Number} margin A minimum required margin. Optional.
* If margin is provided, the two items will be
* marked colliding when they overlap or
* when the margin between the two is smaller than
* the requested margin.
* @return {boolean} true if item1 and item2 collide, else false
*/
links.Timeline.prototype.collision = function(item1, item2, margin) {
// set margin if not specified
if (margin == undefined) {
margin = 0;
}
// calculate if there is overlap (collision)
return (item1.left - margin < item2.right &&
item1.right + margin > item2.left &&
item1.top - margin < item2.bottom &&
item1.bottom + margin > item2.top);
};
/**
* fire an event
* @param {String} event The name of an event, for example "rangechange" or "edit"
*/
links.Timeline.prototype.trigger = function (event) {
// built up properties
var properties = null;
switch (event) {
case 'rangechange':
case 'rangechanged':
properties = {
'start': new Date(this.start),
'end': new Date(this.end)
};
break;
case 'timechange':
case 'timechanged':
properties = {
'time': new Date(this.customTime)
};
break;
}
// trigger the links event bus
links.events.trigger(this, event, properties);
// trigger the google event bus
if (google && google.visualization) {
google.visualization.events.trigger(this, event, properties);
}
};
/**
* Cluster the events
*/
links.Timeline.prototype.clusterItems = function () {
if (!this.options.cluster) {
return;
}
var clusters = this.clusterGenerator.getClusters(this.conversion.factor);
if (this.clusters != clusters) {
// cluster level changed
var queue = this.renderQueue;
// remove the old clusters from the scene
if (this.clusters) {
this.clusters.forEach(function (cluster) {
queue.hide.push(cluster);
// unlink the items
cluster.items.forEach(function (item) {
item.cluster = undefined;
});
});
}
// append the new clusters
clusters.forEach(function (cluster) {
// don't add to the queue.show here, will be done in .filterItems()
// link all items to the cluster
cluster.items.forEach(function (item) {
item.cluster = cluster;
});
});
this.clusters = clusters;
}
};
/**
* Filter the visible events
*/
links.Timeline.prototype.filterItems = function () {
var queue = this.renderQueue,
window = this.end.valueOf() - this.start.valueOf(),
start = new Date(this.start.valueOf() - window),
end = new Date(this.end.valueOf() + window);
function filter (arr) {
arr.forEach(function (item) {
var rendered = item.rendered;
var visible = item.isVisible(start, end);
if (rendered != visible) {
if (rendered) {
queue.hide.push(item); // item is rendered but no longer visible
}
if (visible && (queue.show.indexOf(item) == -1)) {
queue.show.push(item); // item is visible but neither rendered nor queued up to be rendered
}
}
});
}
// filter all items and all clusters
filter(this.items);
if (this.clusters) {
filter(this.clusters);
}
};
/** ------------------------------------------------------------------------ **/
/**
* @constructor links.Timeline.ClusterGenerator
* Generator which creates clusters of items, based on the visible range in
* the Timeline. There is a set of cluster levels which is cached.
* @param {links.Timeline} timeline
*/
links.Timeline.ClusterGenerator = function (timeline) {
this.timeline = timeline;
this.clear();
};
/**
* Clear all cached clusters and data, and initialize all variables
*/
links.Timeline.ClusterGenerator.prototype.clear = function () {
// cache containing created clusters for each cluster level
this.items = [];
this.groups = {};
this.clearCache();
};
/**
* Clear the cached clusters
*/
links.Timeline.ClusterGenerator.prototype.clearCache = function () {
// cache containing created clusters for each cluster level
this.cache = {};
this.cacheLevel = -1;
this.cache[this.cacheLevel] = [];
};
/**
* Set the items to be clustered.
* This will clear cached clusters.
* @param {Item[]} items
* @param {Object} [options] Available options:
* {boolean} applyOnChangedLevel
* If true (default), the changed data is applied
* as soon the cluster level changes. If false,
* The changed data is applied immediately
*/
links.Timeline.ClusterGenerator.prototype.setData = function (items, options) {
this.items = items || [];
this.dataChanged = true;
this.applyOnChangedLevel = true;
if (options && options.applyOnChangedLevel) {
this.applyOnChangedLevel = options.applyOnChangedLevel;
}
// console.log('clustergenerator setData applyOnChangedLevel=' + this.applyOnChangedLevel); // TODO: cleanup
};
/**
* Filter the items per group.
* @private
*/
links.Timeline.ClusterGenerator.prototype.filterData = function () {
// filter per group
var items = this.items || [];
var groups = {};
this.groups = groups;
// split the items per group
items.forEach(function (item) {
var groupName = item.group ? item.group.content : '';
var group = groups[groupName];
if (!group) {
group = [];
groups[groupName] = group;
}
group.push(item);
});
// sort the items per group
for (var groupName in groups) {
if (groups.hasOwnProperty(groupName)) {
groups[groupName].sort(function (a, b) {
return (a.center - b.center);
});
}
}
this.dataChanged = false;
};
/**
* Cluster the events which are too close together
* @param {Number} scale The scale of the current window,
* defined as (windowWidth / (endDate - startDate))
* @return {Item[]} clusters
*/
links.Timeline.ClusterGenerator.prototype.getClusters = function (scale) {
var level = -1,
granularity = 2, // TODO: what granularity is needed for the cluster levels?
timeWindow = 0, // milliseconds
maxItems = 5; // TODO: do not hard code maxItems
if (scale > 0) {
level = Math.round(Math.log(100 / scale) / Math.log(granularity));
timeWindow = Math.pow(granularity, level);
// groups must have a larger time window, as the items will not be stacked
if (this.timeline.groups && this.timeline.groups.length) {
timeWindow *= 4;
}
}
// clear the cache when and re-filter the data when needed.
if (this.dataChanged) {
var levelChanged = (level != this.cacheLevel);
var applyDataNow = this.applyOnChangedLevel ? levelChanged : true;
if (applyDataNow) {
// TODO: currently drawn clusters should be removed! mark them as invisible?
this.clearCache();
this.filterData();
// console.log('clustergenerator: cache cleared...'); // TODO: cleanup
}
}
this.cacheLevel = level;
var clusters = this.cache[level];
if (!clusters) {
// console.log('clustergenerator: create cluster level ' + level); // TODO: cleanup
clusters = [];
// TODO: spit this method, it is too large
for (var groupName in this.groups) {
if (this.groups.hasOwnProperty(groupName)) {
var items = this.groups[groupName];
var iMax = items.length;
var i = 0;
while (i < iMax) {
// find all items around current item, within the timeWindow
var item = items[i];
var neighbors = 1; // start at 1, to include itself)
// loop through items left from the current item
var j = i - 1;
while (j >= 0 &&
(item.center - items[j].center) < timeWindow / 2) {
if (!items[j].cluster) {
neighbors++;
}
j--;
}
// loop through items right from the current item
var k = i + 1;
while (k < items.length &&
(items[k].center - item.center) < timeWindow / 2) {
neighbors++;
k++;
}
// loop through the created clusters
var l = clusters.length - 1;
while (l >= 0 &&
(item.center - clusters[l].center) < timeWindow / 2) {
if (item.group == clusters[l].group) {
neighbors++;
}
l--;
}
// aggregate until the number of items is within maxItems
if (neighbors > maxItems) {
// too busy in this window.
var num = neighbors - maxItems + 1;
var clusterItems = [];
// append the items to the cluster,
// and calculate the average start for the cluster
var avg = undefined; // average of all start dates
var min = undefined; // minimum of all start dates
var max = undefined; // maximum of all start and end dates
var containsRanges = false;
var count = 0;
var m = i;
while (clusterItems.length < num && m < items.length) {
var p = items[m];
var start = p.start.valueOf();
var end = p.end ? p.end.valueOf() : p.start.valueOf();
clusterItems.push(p);
if (count) {
// calculate new average (use fractions to prevent overflow)
avg = (count / (count + 1)) * avg + (1 / (count + 1)) * p.center;
}
else {
avg = p.center;
}
min = (min != undefined) ? Math.min(min, start) : start;
max = (max != undefined) ? Math.max(max, end) : end;
containsRanges = containsRanges || (p instanceof links.Timeline.ItemRange);
count++;
m++;
}
var cluster;
var title = 'Cluster containing ' + count +
' events. Zoom in to see the individual events.';
var content = '<div title="' + title + '">' + count + ' events</div>';
var group = item.group ? item.group.content : undefined;
if (containsRanges) {
// boxes and/or ranges
cluster = this.timeline.createItem({
'start': new Date(min),
'end': new Date(max),
'content': content,
'group': group
});
}
else {
// boxes only
cluster = this.timeline.createItem({
'start': new Date(avg),
'content': content,
'group': group
});
}
cluster.isCluster = true;
cluster.items = clusterItems;
cluster.items.forEach(function (item) {
item.cluster = cluster;
});
clusters.push(cluster);
i += num;
}
else {
delete item.cluster;
i += 1;
}
}
}
}
this.cache[level] = clusters;
}
return clusters;
};
/** ------------------------------------------------------------------------ **/
/**
* Event listener (singleton)
*/
links.events = links.events || {
'listeners': [],
/**
* Find a single listener by its object
* @param {Object} object
* @return {Number} index -1 when not found
*/
'indexOf': function (object) {
var listeners = this.listeners;
for (var i = 0, iMax = this.listeners.length; i < iMax; i++) {
var listener = listeners[i];
if (listener && listener.object == object) {
return i;
}
}
return -1;
},
/**
* Add an event listener
* @param {Object} object
* @param {String} event The name of an event, for example 'select'
* @param {function} callback The callback method, called when the
* event takes place
*/
'addListener': function (object, event, callback) {
var index = this.indexOf(object);
var listener = this.listeners[index];
if (!listener) {
listener = {
'object': object,
'events': {}
};
this.listeners.push(listener);
}
var callbacks = listener.events[event];
if (!callbacks) {
callbacks = [];
listener.events[event] = callbacks;
}
// add the callback if it does not yet exist
if (callbacks.indexOf(callback) == -1) {
callbacks.push(callback);
}
},
/**
* Remove an event listener
* @param {Object} object
* @param {String} event The name of an event, for example 'select'
* @param {function} callback The registered callback method
*/
'removeListener': function (object, event, callback) {
var index = this.indexOf(object);
var listener = this.listeners[index];
if (listener) {
var callbacks = listener.events[event];
if (callbacks) {
var index = callbacks.indexOf(callback);
if (index != -1) {
callbacks.splice(index, 1);
}
// remove the array when empty
if (callbacks.length == 0) {
delete listener.events[event];
}
}
// count the number of registered events. remove listener when empty
var count = 0;
var events = listener.events;
for (var e in events) {
if (events.hasOwnProperty(e)) {
count++;
}
}
if (count == 0) {
delete this.listeners[index];
}
}
},
/**
* Remove all registered event listeners
*/
'removeAllListeners': function () {
this.listeners = [];
},
/**
* Trigger an event. All registered event handlers will be called
* @param {Object} object
* @param {String} event
* @param {Object} properties (optional)
*/
'trigger': function (object, event, properties) {
var index = this.indexOf(object);
var listener = this.listeners[index];
if (listener) {
var callbacks = listener.events[event];
if (callbacks) {
for (var i = 0, iMax = callbacks.length; i < iMax; i++) {
callbacks[i](properties);
}
}
}
}
};
/** ------------------------------------------------------------------------ **/
/**
* @constructor links.Timeline.StepDate
* The class StepDate is an iterator for dates. You provide a start date and an
* end date. The class itself determines the best scale (step size) based on the
* provided start Date, end Date, and minimumStep.
*
* If minimumStep is provided, the step size is chosen as close as possible
* to the minimumStep but larger than minimumStep. If minimumStep is not
* provided, the scale is set to 1 DAY.
* The minimumStep should correspond with the onscreen size of about 6 characters
*
* Alternatively, you can set a scale by hand.
* After creation, you can initialize the class by executing start(). Then you
* can iterate from the start date to the end date via next(). You can check if
* the end date is reached with the function end(). After each step, you can
* retrieve the current date via get().
* The class step has scales ranging from milliseconds, seconds, minutes, hours,
* days, to years.
*
* Version: 1.1
*
* @param {Date} start The start date, for example new Date(2010, 9, 21)
* or new Date(2010, 9, 21, 23, 45, 00)
* @param {Date} end The end date
* @param {Number} minimumStep Optional. Minimum step size in milliseconds
*/
links.Timeline.StepDate = function(start, end, minimumStep) {
// variables
this.current = new Date();
this._start = new Date();
this._end = new Date();
this.autoScale = true;
this.scale = links.Timeline.StepDate.SCALE.DAY;
this.step = 1;
// initialize the range
this.setRange(start, end, minimumStep);
};
/// enum scale
links.Timeline.StepDate.SCALE = {
MILLISECOND: 1,
SECOND: 2,
MINUTE: 3,
HOUR: 4,
DAY: 5,
WEEKDAY: 6,
MONTH: 7,
YEAR: 8
};
/**
* Set a new range
* If minimumStep is provided, the step size is chosen as close as possible
* to the minimumStep but larger than minimumStep. If minimumStep is not
* provided, the scale is set to 1 DAY.
* The minimumStep should correspond with the onscreen size of about 6 characters
* @param {Date} start The start date and time.
* @param {Date} end The end date and time.
* @param {int} minimumStep Optional. Minimum step size in milliseconds
*/
links.Timeline.StepDate.prototype.setRange = function(start, end, minimumStep) {
if (isNaN(start) || isNaN(end)) {
//throw "No legal start or end date in method setRange";
return;
}
this._start = (start != undefined) ? new Date(start) : new Date();
this._end = (end != undefined) ? new Date(end) : new Date();
if (this.autoScale) {
this.setMinimumStep(minimumStep);
}
};
/**
* Set the step iterator to the start date.
*/
links.Timeline.StepDate.prototype.start = function() {
this.current = new Date(this._start);
this.roundToMinor();
};
/**
* Round the current date to the first minor date value
* This must be executed once when the current date is set to start Date
*/
links.Timeline.StepDate.prototype.roundToMinor = function() {
// round to floor
// IMPORTANT: we have no breaks in this switch! (this is no bug)
switch (this.scale) {
case links.Timeline.StepDate.SCALE.YEAR:
this.current.setFullYear(this.step * Math.floor(this.current.getFullYear() / this.step));
this.current.setMonth(0);
case links.Timeline.StepDate.SCALE.MONTH: this.current.setDate(1);
case links.Timeline.StepDate.SCALE.DAY: // intentional fall through
case links.Timeline.StepDate.SCALE.WEEKDAY: this.current.setHours(0);
case links.Timeline.StepDate.SCALE.HOUR: this.current.setMinutes(0);
case links.Timeline.StepDate.SCALE.MINUTE: this.current.setSeconds(0);
case links.Timeline.StepDate.SCALE.SECOND: this.current.setMilliseconds(0);
//case links.Timeline.StepDate.SCALE.MILLISECOND: // nothing to do for milliseconds
}
if (this.step != 1) {
// round down to the first minor value that is a multiple of the current step size
switch (this.scale) {
case links.Timeline.StepDate.SCALE.MILLISECOND: this.current.setMilliseconds(this.current.getMilliseconds() - this.current.getMilliseconds() % this.step); break;
case links.Timeline.StepDate.SCALE.SECOND: this.current.setSeconds(this.current.getSeconds() - this.current.getSeconds() % this.step); break;
case links.Timeline.StepDate.SCALE.MINUTE: this.current.setMinutes(this.current.getMinutes() - this.current.getMinutes() % this.step); break;
case links.Timeline.StepDate.SCALE.HOUR: this.current.setHours(this.current.getHours() - this.current.getHours() % this.step); break;
case links.Timeline.StepDate.SCALE.WEEKDAY: // intentional fall through
case links.Timeline.StepDate.SCALE.DAY: this.current.setDate((this.current.getDate()-1) - (this.current.getDate()-1) % this.step + 1); break;
case links.Timeline.StepDate.SCALE.MONTH: this.current.setMonth(this.current.getMonth() - this.current.getMonth() % this.step); break;
case links.Timeline.StepDate.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() - this.current.getFullYear() % this.step); break;
default: break;
}
}
};
/**
* Check if the end date is reached
* @return {boolean} true if the current date has passed the end date
*/
links.Timeline.StepDate.prototype.end = function () {
return (this.current.getTime() > this._end.getTime());
};
/**
* Do the next step
*/
links.Timeline.StepDate.prototype.next = function() {
var prev = this.current.getTime();
// Two cases, needed to prevent issues with switching daylight savings
// (end of March and end of October)
if (this.current.getMonth() < 6) {
switch (this.scale) {
case links.Timeline.StepDate.SCALE.MILLISECOND:
this.current = new Date(this.current.getTime() + this.step); break;
case links.Timeline.StepDate.SCALE.SECOND: this.current = new Date(this.current.getTime() + this.step * 1000); break;
case links.Timeline.StepDate.SCALE.MINUTE: this.current = new Date(this.current.getTime() + this.step * 1000 * 60); break;
case links.Timeline.StepDate.SCALE.HOUR:
this.current = new Date(this.current.getTime() + this.step * 1000 * 60 * 60);
// in case of skipping an hour for daylight savings, adjust the hour again (else you get: 0h 5h 9h ... instead of 0h 4h 8h ...)
var h = this.current.getHours();
this.current.setHours(h - (h % this.step));
break;
case links.Timeline.StepDate.SCALE.WEEKDAY: // intentional fall through
case links.Timeline.StepDate.SCALE.DAY: this.current.setDate(this.current.getDate() + this.step); break;
case links.Timeline.StepDate.SCALE.MONTH: this.current.setMonth(this.current.getMonth() + this.step); break;
case links.Timeline.StepDate.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() + this.step); break;
default: break;
}
}
else {
switch (this.scale) {
case links.Timeline.StepDate.SCALE.MILLISECOND: this.current = new Date(this.current.getTime() + this.step); break;
case links.Timeline.StepDate.SCALE.SECOND: this.current.setSeconds(this.current.getSeconds() + this.step); break;
case links.Timeline.StepDate.SCALE.MINUTE: this.current.setMinutes(this.current.getMinutes() + this.step); break;
case links.Timeline.StepDate.SCALE.HOUR: this.current.setHours(this.current.getHours() + this.step); break;
case links.Timeline.StepDate.SCALE.WEEKDAY: // intentional fall through
case links.Timeline.StepDate.SCALE.DAY: this.current.setDate(this.current.getDate() + this.step); break;
case links.Timeline.StepDate.SCALE.MONTH: this.current.setMonth(this.current.getMonth() + this.step); break;
case links.Timeline.StepDate.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() + this.step); break;
default: break;
}
}
if (this.step != 1) {
// round down to the correct major value
switch (this.scale) {
case links.Timeline.StepDate.SCALE.MILLISECOND: if(this.current.getMilliseconds() < this.step) this.current.setMilliseconds(0); break;
case links.Timeline.StepDate.SCALE.SECOND: if(this.current.getSeconds() < this.step) this.current.setSeconds(0); break;
case links.Timeline.StepDate.SCALE.MINUTE: if(this.current.getMinutes() < this.step) this.current.setMinutes(0); break;
case links.Timeline.StepDate.SCALE.HOUR: if(this.current.getHours() < this.step) this.current.setHours(0); break;
case links.Timeline.StepDate.SCALE.WEEKDAY: // intentional fall through
case links.Timeline.StepDate.SCALE.DAY: if(this.current.getDate() < this.step+1) this.current.setDate(1); break;
case links.Timeline.StepDate.SCALE.MONTH: if(this.current.getMonth() < this.step) this.current.setMonth(0); break;
case links.Timeline.StepDate.SCALE.YEAR: break; // nothing to do for year
default: break;
}
}
// safety mechanism: if current time is still unchanged, move to the end
if (this.current.getTime() == prev) {
this.current = new Date(this._end);
}
};
/**
* Get the current datetime
* @return {Date} current The current date
*/
links.Timeline.StepDate.prototype.getCurrent = function() {
return this.current;
};
/**
* Set a custom scale. Autoscaling will be disabled.
* For example setScale(SCALE.MINUTES, 5) will result
* in minor steps of 5 minutes, and major steps of an hour.
*
* @param {links.Timeline.StepDate.SCALE} newScale
* A scale. Choose from SCALE.MILLISECOND,
* SCALE.SECOND, SCALE.MINUTE, SCALE.HOUR,
* SCALE.WEEKDAY, SCALE.DAY, SCALE.MONTH,
* SCALE.YEAR.
* @param {Number} newStep A step size, by default 1. Choose for
* example 1, 2, 5, or 10.
*/
links.Timeline.StepDate.prototype.setScale = function(newScale, newStep) {
this.scale = newScale;
if (newStep > 0) {
this.step = newStep;
}
this.autoScale = false;
};
/**
* Enable or disable autoscaling
* @param {boolean} enable If true, autoascaling is set true
*/
links.Timeline.StepDate.prototype.setAutoScale = function (enable) {
this.autoScale = enable;
};
/**
* Automatically determine the scale that bests fits the provided minimum step
* @param {Number} minimumStep The minimum step size in milliseconds
*/
links.Timeline.StepDate.prototype.setMinimumStep = function(minimumStep) {
if (minimumStep == undefined) {
return;
}
var stepYear = (1000 * 60 * 60 * 24 * 30 * 12);
var stepMonth = (1000 * 60 * 60 * 24 * 30);
var stepDay = (1000 * 60 * 60 * 24);
var stepHour = (1000 * 60 * 60);
var stepMinute = (1000 * 60);
var stepSecond = (1000);
var stepMillisecond= (1);
// find the smallest step that is larger than the provided minimumStep
if (stepYear*1000 > minimumStep) {this.scale = links.Timeline.StepDate.SCALE.YEAR; this.step = 1000;}
if (stepYear*500 > minimumStep) {this.scale = links.Timeline.StepDate.SCALE.YEAR; this.step = 500;}
if (stepYear*100 > minimumStep) {this.scale = links.Timeline.StepDate.SCALE.YEAR; this.step = 100;}
if (stepYear*50 > minimumStep) {this.scale = links.Timeline.StepDate.SCALE.YEAR; this.step = 50;}
if (stepYear*10 > minimumStep) {this.scale = links.Timeline.StepDate.SCALE.YEAR; this.step = 10;}
if (stepYear*5 > minimumStep) {this.scale = links.Timeline.StepDate.SCALE.YEAR; this.step = 5;}
if (stepYear > minimumStep) {this.scale = links.Timeline.StepDate.SCALE.YEAR; this.step = 1;}
if (stepMonth*3 > minimumStep) {this.scale = links.Timeline.StepDate.SCALE.MONTH; this.step = 3;}
if (stepMonth > minimumStep) {this.scale = links.Timeline.StepDate.SCALE.MONTH; this.step = 1;}
if (stepDay*5 > minimumStep) {this.scale = links.Timeline.StepDate.SCALE.DAY; this.step = 5;}
if (stepDay*2 > minimumStep) {this.scale = links.Timeline.StepDate.SCALE.DAY; this.step = 2;}
if (stepDay > minimumStep) {this.scale = links.Timeline.StepDate.SCALE.DAY; this.step = 1;}
if (stepDay/2 > minimumStep) {this.scale = links.Timeline.StepDate.SCALE.WEEKDAY; this.step = 1;}
if (stepHour*4 > minimumStep) {this.scale = links.Timeline.StepDate.SCALE.HOUR; this.step = 4;}
if (stepHour > minimumStep) {this.scale = links.Timeline.StepDate.SCALE.HOUR; this.step = 1;}
if (stepMinute*15 > minimumStep) {this.scale = links.Timeline.StepDate.SCALE.MINUTE; this.step = 15;}
if (stepMinute*10 > minimumStep) {this.scale = links.Timeline.StepDate.SCALE.MINUTE; this.step = 10;}
if (stepMinute*5 > minimumStep) {this.scale = links.Timeline.StepDate.SCALE.MINUTE; this.step = 5;}
if (stepMinute > minimumStep) {this.scale = links.Timeline.StepDate.SCALE.MINUTE; this.step = 1;}
if (stepSecond*15 > minimumStep) {this.scale = links.Timeline.StepDate.SCALE.SECOND; this.step = 15;}
if (stepSecond*10 > minimumStep) {this.scale = links.Timeline.StepDate.SCALE.SECOND; this.step = 10;}
if (stepSecond*5 > minimumStep) {this.scale = links.Timeline.StepDate.SCALE.SECOND; this.step = 5;}
if (stepSecond > minimumStep) {this.scale = links.Timeline.StepDate.SCALE.SECOND; this.step = 1;}
if (stepMillisecond*200 > minimumStep) {this.scale = links.Timeline.StepDate.SCALE.MILLISECOND; this.step = 200;}
if (stepMillisecond*100 > minimumStep) {this.scale = links.Timeline.StepDate.SCALE.MILLISECOND; this.step = 100;}
if (stepMillisecond*50 > minimumStep) {this.scale = links.Timeline.StepDate.SCALE.MILLISECOND; this.step = 50;}
if (stepMillisecond*10 > minimumStep) {this.scale = links.Timeline.StepDate.SCALE.MILLISECOND; this.step = 10;}
if (stepMillisecond*5 > minimumStep) {this.scale = links.Timeline.StepDate.SCALE.MILLISECOND; this.step = 5;}
if (stepMillisecond > minimumStep) {this.scale = links.Timeline.StepDate.SCALE.MILLISECOND; this.step = 1;}
};
/**
* Snap a date to a rounded value. The snap intervals are dependent on the
* current scale and step.
* @param {Date} date the date to be snapped
*/
links.Timeline.StepDate.prototype.snap = function(date) {
if (this.scale == links.Timeline.StepDate.SCALE.YEAR) {
var year = date.getFullYear() + Math.round(date.getMonth() / 12);
date.setFullYear(Math.round(year / this.step) * this.step);
date.setMonth(0);
date.setDate(0);
date.setHours(0);
date.setMinutes(0);
date.setSeconds(0);
date.setMilliseconds(0);
}
else if (this.scale == links.Timeline.StepDate.SCALE.MONTH) {
if (date.getDate() > 15) {
date.setDate(1);
date.setMonth(date.getMonth() + 1);
// important: first set Date to 1, after that change the month.
}
else {
date.setDate(1);
}
date.setHours(0);
date.setMinutes(0);
date.setSeconds(0);
date.setMilliseconds(0);
}
else if (this.scale == links.Timeline.StepDate.SCALE.DAY ||
this.scale == links.Timeline.StepDate.SCALE.WEEKDAY) {
switch (this.step) {
case 5:
case 2:
date.setHours(Math.round(date.getHours() / 24) * 24); break;
default:
date.setHours(Math.round(date.getHours() / 12) * 12); break;
}
date.setMinutes(0);
date.setSeconds(0);
date.setMilliseconds(0);
}
else if (this.scale == links.Timeline.StepDate.SCALE.HOUR) {
switch (this.step) {
case 4:
date.setMinutes(Math.round(date.getMinutes() / 60) * 60); break;
default:
date.setMinutes(Math.round(date.getMinutes() / 30) * 30); break;
}
date.setSeconds(0);
date.setMilliseconds(0);
} else if (this.scale == links.Timeline.StepDate.SCALE.MINUTE) {
switch (this.step) {
case 15:
case 10:
date.setMinutes(Math.round(date.getMinutes() / 5) * 5);
date.setSeconds(0);
break;
case 5:
date.setSeconds(Math.round(date.getSeconds() / 60) * 60); break;
default:
date.setSeconds(Math.round(date.getSeconds() / 30) * 30); break;
}
date.setMilliseconds(0);
}
else if (this.scale == links.Timeline.StepDate.SCALE.SECOND) {
switch (this.step) {
case 15:
case 10:
date.setSeconds(Math.round(date.getSeconds() / 5) * 5);
date.setMilliseconds(0);
break;
case 5:
date.setMilliseconds(Math.round(date.getMilliseconds() / 1000) * 1000); break;
default:
date.setMilliseconds(Math.round(date.getMilliseconds() / 500) * 500); break;
}
}
else if (this.scale == links.Timeline.StepDate.SCALE.MILLISECOND) {
var step = this.step > 5 ? this.step / 2 : 1;
date.setMilliseconds(Math.round(date.getMilliseconds() / step) * step);
}
};
/**
* Check if the current step is a major step (for example when the step
* is DAY, a major step is each first day of the MONTH)
* @return {boolean} true if current date is major, else false.
*/
links.Timeline.StepDate.prototype.isMajor = function() {
switch (this.scale) {
case links.Timeline.StepDate.SCALE.MILLISECOND:
return (this.current.getMilliseconds() == 0);
case links.Timeline.StepDate.SCALE.SECOND:
return (this.current.getSeconds() == 0);
case links.Timeline.StepDate.SCALE.MINUTE:
return (this.current.getHours() == 0) && (this.current.getMinutes() == 0);
// Note: this is no bug. Major label is equal for both minute and hour scale
case links.Timeline.StepDate.SCALE.HOUR:
return (this.current.getHours() == 0);
case links.Timeline.StepDate.SCALE.WEEKDAY: // intentional fall through
case links.Timeline.StepDate.SCALE.DAY:
return (this.current.getDate() == 1);
case links.Timeline.StepDate.SCALE.MONTH:
return (this.current.getMonth() == 0);
case links.Timeline.StepDate.SCALE.YEAR:
return false;
default:
return false;
}
};
/**
* Returns formatted text for the minor axislabel, depending on the current
* date and the scale. For example when scale is MINUTE, the current time is
* formatted as "hh:mm".
* @param {Date} [date] custom date. if not provided, current date is taken
*/
links.Timeline.StepDate.prototype.getLabelMinor = function(date) {
var MONTHS_SHORT = ["Jan", "Feb", "Mar",
"Apr", "May", "Jun",
"Jul", "Aug", "Sep",
"Oct", "Nov", "Dec"];
var DAYS_SHORT = ["Sun", "Mon", "Tue",
"Wed", "Thu", "Fri", "Sat"];
if (date == undefined) {
date = this.current;
}
switch (this.scale) {
case links.Timeline.StepDate.SCALE.MILLISECOND: return String(date.getMilliseconds());
case links.Timeline.StepDate.SCALE.SECOND: return String(date.getSeconds());
case links.Timeline.StepDate.SCALE.MINUTE:
return this.addZeros(date.getHours(), 2) + ":" + this.addZeros(date.getMinutes(), 2);
case links.Timeline.StepDate.SCALE.HOUR:
return this.addZeros(date.getHours(), 2) + ":" + this.addZeros(date.getMinutes(), 2);
case links.Timeline.StepDate.SCALE.WEEKDAY: return DAYS_SHORT[date.getDay()] + ' ' + date.getDate();
case links.Timeline.StepDate.SCALE.DAY: return String(date.getDate());
case links.Timeline.StepDate.SCALE.MONTH: return MONTHS_SHORT[date.getMonth()]; // month is zero based
case links.Timeline.StepDate.SCALE.YEAR: return String(date.getFullYear());
default: return "";
}
};
/**
* Returns formatted text for the major axislabel, depending on the current
* date and the scale. For example when scale is MINUTE, the major scale is
* hours, and the hour will be formatted as "hh".
* @param {Date} [date] custom date. if not provided, current date is taken
*/
links.Timeline.StepDate.prototype.getLabelMajor = function(date) {
var MONTHS = ["January", "February", "March",
"April", "May", "June",
"July", "August", "September",
"October", "November", "December"];
var DAYS = ["Sunday", "Monday", "Tuesday",
"Wednesday", "Thursday", "Friday", "Saturday"];
if (date == undefined) {
date = this.current;
}
switch (this.scale) {
case links.Timeline.StepDate.SCALE.MILLISECOND:
return this.addZeros(date.getHours(), 2) + ":" +
this.addZeros(date.getMinutes(), 2) + ":" +
this.addZeros(date.getSeconds(), 2);
case links.Timeline.StepDate.SCALE.SECOND:
return date.getDate() + " " +
MONTHS[date.getMonth()] + " " +
this.addZeros(date.getHours(), 2) + ":" +
this.addZeros(date.getMinutes(), 2);
case links.Timeline.StepDate.SCALE.MINUTE:
return DAYS[date.getDay()] + " " +
date.getDate() + " " +
MONTHS[date.getMonth()] + " " +
date.getFullYear();
case links.Timeline.StepDate.SCALE.HOUR:
return DAYS[date.getDay()] + " " +
date.getDate() + " " +
MONTHS[date.getMonth()] + " " +
date.getFullYear();
case links.Timeline.StepDate.SCALE.WEEKDAY:
case links.Timeline.StepDate.SCALE.DAY:
return MONTHS[date.getMonth()] + " " +
date.getFullYear();
case links.Timeline.StepDate.SCALE.MONTH:
return String(date.getFullYear());
default:
return "";
}
};
/**
* Add leading zeros to the given value to match the desired length.
* For example addZeros(123, 5) returns "00123"
* @param {int} value A value
* @param {int} len Desired final length
* @return {string} value with leading zeros
*/
links.Timeline.StepDate.prototype.addZeros = function(value, len) {
var str = "" + value;
while (str.length < len) {
str = "0" + str;
}
return str;
};
/** ------------------------------------------------------------------------ **/
/**
* Image Loader service.
* can be used to get a callback when a certain image is loaded
*
*/
links.imageloader = (function () {
var urls = {}; // the loaded urls
var callbacks = {}; // the urls currently being loaded. Each key contains
// an array with callbacks
/**
* Check if an image url is loaded
* @param {String} url
* @return {boolean} loaded True when loaded, false when not loaded
* or when being loaded
*/
function isLoaded (url) {
if (urls[url] == true) {
return true;
}
var image = new Image();
image.src = url;
if (image.complete) {
return true;
}
return false;
}
/**
* Check if an image url is being loaded
* @param {String} url
* @return {boolean} loading True when being loaded, false when not loading
* or when already loaded
*/
function isLoading (url) {
return (callbacks[url] != undefined);
}
/**
* Load given image url
* @param {String} url
* @param {function} callback
* @param {boolean} sendCallbackWhenAlreadyLoaded optional
*/
function load (url, callback, sendCallbackWhenAlreadyLoaded) {
if (sendCallbackWhenAlreadyLoaded == undefined) {
sendCallbackWhenAlreadyLoaded = true;
}
if (isLoaded(url)) {
if (sendCallbackWhenAlreadyLoaded) {
callback(url);
}
return;
}
if (isLoading(url) && !sendCallbackWhenAlreadyLoaded) {
return;
}
var c = callbacks[url];
if (!c) {
var image = new Image();
image.src = url;
c = [];
callbacks[url] = c;
image.onload = function (event) {
urls[url] = true;
delete callbacks[url];
for (var i = 0; i < c.length; i++) {
c[i](url);
}
}
}
if (c.indexOf(callback) == -1) {
c.push(callback);
}
}
/**
* Load a set of images, and send a callback as soon as all images are
* loaded
* @param {String[]} urls
* @param {function } callback
* @param {boolean} sendCallbackWhenAlreadyLoaded
*/
function loadAll (urls, callback, sendCallbackWhenAlreadyLoaded) {
// list all urls which are not yet loaded
var urlsLeft = [];
urls.forEach(function (url) {
if (!isLoaded(url)) {
urlsLeft.push(url);
}
});
if (urlsLeft.length) {
// there are unloaded images
var countLeft = urlsLeft.length;
urlsLeft.forEach(function (url) {
load(url, function () {
countLeft--;
if (countLeft == 0) {
// done!
callback();
}
}, sendCallbackWhenAlreadyLoaded);
});
}
else {
// we are already done!
if (sendCallbackWhenAlreadyLoaded) {
callback();
}
}
}
/**
* Recursively retrieve all image urls from the images located inside a given
* HTML element
* @param {Node} elem
* @param {String[]} urls Urls will be added here (no duplicates)
*/
function filterImageUrls (elem, urls) {
var child = elem.firstChild;
while (child) {
if (child.tagName == 'IMG') {
var url = child.src;
if (urls.indexOf(url) == -1) {
urls.push(url);
}
}
filterImageUrls(child, urls);
child = child.nextSibling;
}
}
return {
'isLoaded': isLoaded,
'isLoading': isLoading,
'load': load,
'loadAll': loadAll,
'filterImageUrls': filterImageUrls
};
})();
/** ------------------------------------------------------------------------ **/
/**
* Add and event listener. Works for all browsers
* @param {Element} element An html element
* @param {string} action The action, for example "click",
* without the prefix "on"
* @param {function} listener The callback function to be executed
* @param {boolean} useCapture
*/
links.Timeline.addEventListener = function (element, action, listener, useCapture) {
if (element.addEventListener) {
if (useCapture === undefined)
useCapture = false;
if (action === "mousewheel" && navigator.userAgent.indexOf("Firefox") >= 0) {
action = "DOMMouseScroll"; // For Firefox
}
element.addEventListener(action, listener, useCapture);
} else {
element.attachEvent("on" + action, listener); // IE browsers
}
};
/**
* Remove an event listener from an element
* @param {Element} element An html dom element
* @param {string} action The name of the event, for example "mousedown"
* @param {function} listener The listener function
* @param {boolean} useCapture
*/
links.Timeline.removeEventListener = function(element, action, listener, useCapture) {
if (element.removeEventListener) {
// non-IE browsers
if (useCapture === undefined)
useCapture = false;
if (action === "mousewheel" && navigator.userAgent.indexOf("Firefox") >= 0) {
action = "DOMMouseScroll"; // For Firefox
}
element.removeEventListener(action, listener, useCapture);
} else {
// IE browsers
element.detachEvent("on" + action, listener);
}
};
/**
* Get HTML element which is the target of the event
* @param {Event} event
* @return {Element} target element
*/
links.Timeline.getTarget = function (event) {
// code from http://www.quirksmode.org/js/events_properties.html
if (!event) {
event = window.event;
}
var target;
if (event.target) {
target = event.target;
}
else if (event.srcElement) {
target = event.srcElement;
}
if (target.nodeType !== undefined && target.nodeType == 3) {
// defeat Safari bug
target = target.parentNode;
}
return target;
};
/**
* Stop event propagation
*/
links.Timeline.stopPropagation = function (event) {
if (!event)
event = window.event;
if (event.stopPropagation) {
event.stopPropagation(); // non-IE browsers
}
else {
event.cancelBubble = true; // IE browsers
}
};
/**
* Cancels the event if it is cancelable, without stopping further propagation of the event.
*/
links.Timeline.preventDefault = function (event) {
if (!event)
event = window.event;
if (event.preventDefault) {
event.preventDefault(); // non-IE browsers
}
else {
event.returnValue = false; // IE browsers
}
};
/**
* Retrieve the absolute left value of a DOM element
* @param {Element} elem A dom element, for example a div
* @return {number} left The absolute left position of this element
* in the browser page.
*/
links.Timeline.getAbsoluteLeft = function(elem) {
var left = 0;
while( elem != null ) {
left += elem.offsetLeft;
left -= elem.scrollLeft;
elem = elem.offsetParent;
}
if (!document.body.scrollLeft && window.pageXOffset) {
// FF
left -= window.pageXOffset;
}
return left;
};
/**
* Retrieve the absolute top value of a DOM element
* @param {Element} elem A dom element, for example a div
* @return {number} top The absolute top position of this element
* in the browser page.
*/
links.Timeline.getAbsoluteTop = function(elem) {
var top = 0;
while( elem != null ) {
top += elem.offsetTop;
top -= elem.scrollTop;
elem = elem.offsetParent;
}
if (!document.body.scrollTop && window.pageYOffset) {
// FF
top -= window.pageYOffset;
}
return top;
};
/**
* add a className to the given elements style
* @param {Element} elem
* @param {String} className
*/
links.Timeline.addClassName = function(elem, className) {
var classes = elem.className.split(' ');
if (classes.indexOf(className) == -1) {
classes.push(className); // add the class to the array
elem.className = classes.join(' ');
}
};
/**
* add a className to the given elements style
* @param {Element} elem
* @param {String} className
*/
links.Timeline.removeClassName = function(elem, className) {
var classes = elem.className.split(' ');
var index = classes.indexOf(className);
if (index != -1) {
classes.splice(index, 1); // remove the class from the array
elem.className = classes.join(' ');
}
};
/**
* Check if given object is a Javascript Array
* @param {*} obj
* @return {Boolean} isArray true if the given object is an array
*/
// See http://stackoverflow.com/questions/2943805/javascript-instanceof-typeof-in-gwt-jsni
links.Timeline.isArray = function (obj) {
if (obj instanceof Array) {
return true;
}
return (Object.prototype.toString.call(obj) === '[object Array]');
};
/**
* parse a JSON date
* @param {Object} date object to be parsed.
* Edited by Aaron Curtis on 23 Mar to
*
**/
links.Timeline.parseJSONDate = function (date)
{
return new Date(date);
}; | foobarbecue/afterflight | afterflight/media/js/timeline.js | JavaScript | apache-2.0 | 205,004 |
function FoursquareAPI(params) {
var clientId = params.clientId;
var redirectUri = params.redirectUri;
var authorized = false;
var accessToken = '';
function createAuthenticationUrl(clientId, redirectUri, action) {
var action = action || '/authenticate';
var authenticationUrl = "https://foursquare.com/oauth2" + action;
return String.format(
"%s?client_id=%s&response_type=token&redirect_uri=%s&display=touch",
authenticationUrl,
clientId,
redirectUri
);
};
function authenticate(params) {
var action = params.action;
var callback = params.callback;
var url = createAuthenticationUrl(clientId, redirectUri, params.action);
var win = Ti.UI.createWindow({
top: 0,
modal: true,
fullscreen: true
});
var webView;
if (Ti.Platform.osname=='iphone') {
webView = Ti.UI.createWebView({
url: url,
scalesPageToFit: true,
touchEnabled: true,
top:43,
backgroundColor: '#FFF'
});
var toolbar = Ti.UI.createToolbar({top:0});
var toolbarLabel = Ti.UI.createLabel({
text:'Login with Foursquare',
font:{fontSize:16,fontWeight:'bold'},
color:'#FFF',
textAlign:'center'
});
var flexSpace = Titanium.UI.createButton({
systemButton:Titanium.UI.iPhone.SystemButton.FLEXIBLE_SPACE
});
var btnClose = Titanium.UI.createButton({
title:'Cancel',
style:Titanium.UI.iPhone.SystemButtonStyle.BORDERED
});
toolbar.items = [flexSpace,flexSpace,toolbarLabel,flexSpace,btnClose];
win.add(toolbar);
// close login window
btnClose.addEventListener('click',function() {
webView.stopLoading();
win.remove(webView);
win.close();
});
} else {
webView = Ti.UI.createWebView({
url: url,
scalesPageToFit: true,
touchEnabled: true,
top:0,
backgroundColor: '#FFF'
});
}
webView.addEventListener('load',function(e) {
var fragment = "#access_token=";
var url = e.url;
Ti.API.info('[Foursquare] ' + e.url);
var index = url.indexOf(fragment);
if (index != -1) {
authorized = true;
accessToken = url.substring(index + fragment.length);
if (callback && typeof(callback) == 'function') {
callback({
accessToken: accessToken,
});
}
webView.stopLoading();
win.remove(webView);
win.close();
}
});
win.add(webView);
win.open();
};
function authorize(params) {
authenticate({
action: '/authorize',
callback: params.callback
});
};
this.authenticate = authenticate;
this.authorize = authorize;
this.authorized = function() { return authorized };
};
| xurde/yumit-mobile | Resources/yumit/lib/foursquare.js | JavaScript | apache-2.0 | 2,698 |
sap.ui.define([
"sap/ui/core/UIComponent"
], function (UIComponent) {
"use strict";
return UIComponent.extend("sap.tnt.sample.ToolPageHorizontalNavigation.Component", {
metadata: {
manifest: "json"
}
});
}); | SAP/openui5 | src/sap.tnt/test/sap/tnt/demokit/sample/ToolPageHorizontalNavigation/Component.js | JavaScript | apache-2.0 | 221 |
var merge = require('webpack-merge')
var baseEnv = require('./base.env')
module.exports = merge(baseEnv, {
NODE_ENV: '"development"'
});
| marcopaz/is-service-up | frontend/config/dev.env.js | JavaScript | apache-2.0 | 140 |
setHuListModal("#selectHuPerson",function(data){
if(data){
$("#idNumber").val(data.idNumber);
$("#queryBtn").click();
}
});
$.dropDownInput({
inputId : "#idNumber",
dropDownId : "#idNumberQueryPrDown",
url : sendUrl.onekeyQuery_getFuzzy,
urlType:"get",
valName:"fuzzy",
selectVal:"idNumber",
templateId : "#idNumberQueryPrDownTemplate",
lastFn:function(data){
return actionFormate(data,false);
},itemClick:function(data){
$("#idNumber").data("data",data);
}
});
$("#queryForm").validate({
rules: {
idNumber: {
required: true
}
}, submitHandler:function(form){
$.post("housePurchaseMansgement/hptSetGet.do",$("#queryForm").serialize(),function(data){
actionFormate(data, true,function(type,msg,datas){
var template = Handlebars.compile($("#entrytemplate").html());
var html = template();
var rHtml = $(html);
$("#qDataArea").html(html);
initSubData();
for ( var i in datas) {
var d = datas[i];
d.isCheck = d.ticketState == 'NORMAL';
d.ticketName = toTicketStr(d.ticketState);
d.ticketIndex = toTicketNumber(d.ticketState);
var t = Handlebars.compile($("#famItemTemplate").html());
var h = t(d);
var rH = $(h);
rH.data("data",d);
$("#famItems").append(rH);
}
});
},"json");
}
});
$("#lingQuModal").validate({
rules: {
name: {
required: true
}, idNumber: {
required: true
}, time: {
required: true
}
}, submitHandler:function(form){
var tempData = $("#lingQuModal").data("data");
var datas = [];
for ( var i in tempData.item) {
var item = tempData.item[i];
var data = {};
// /**购房券id*/
data.ticketId = item.hptId;
// /**购房券所有者*/
data.ownerId = item.fmlItemId;
// /**领取凭证*/
data.evidenceOfGetting = $("#yuLanBtn").data("img");
// /**领用人姓名*/
data.name = $("#lingQuModal [name='name']").val();
// /**领用人身份证*/
data.idNumber = $("#lingQuModal [name='idNumber']").val();
// /**领用时间*/
data.gettingDate = $("#lingQuModal [name='time']").val();
//领取备注
data.remark = $("#lingQuModal [name='remark']").val();
data.resideName = item.name;
data.resideIdNumber = item.idNumber;
data.resideTicketNumber = item.ticketNumber;
data.resideBonus = item.bonus;
data.resideMakeTime = item.makeTime;
datas.push(data);
}
$.post("housePurchaseMansgement/hptSetAdd.do",{
dataJson:JSON.stringify(datas)
},function(data){
actionFormate(data, true, function(type, msg, data) {
var template = Handlebars.compile($("#logItemTemplate").html());
var logHtml = template(datas);
operationLog("购房券户发放","购房券户发放",logHtml);
$("#lingQuModal").modal("hide");
$("#qDataArea").html("");
});
},"json");
}
});
$("#phonePaiZhaoModal").modal({
show:false,
keyboard:false,
backdrop:"static",
});
$("#phonePaiZhaoModal").on("hidden.bs.modal",function(){
if($(this).data("btnState") == true){
var imgData = $(this).data("imgData");
$("#paiZhaoFileLoginState").css("display","inline");
$("#zhaoBtn,#yuLanBtn,#paiZhaoFileCheckState").css("display","none");
$.post("share/saveFile.do",{
baseSFFile:imgData
},function(data){
actionFormate(data, true, function(type, msg, data) {
$("#yuLanBtn").data("img",data);
});
$("#paiZhaoFileLoginState").css("display","none");
$("#zhaoBtn,#yuLanBtn,#paiZhaoFileCheckState").css("display","inline");
},"json");
}
});
function initSubData(){
$("#faFangSelectData").click(function(){
var clickModal = {};
clickModal.money = 0;
clickModal.item = [];
$("#qDataArea input[type='checkbox'][name='check']:not(:disabled):checked").each(function(){
var data = $(this).closest("tr").data("data");
if(data.relationship == "户主"){
clickModal.huZhuName = data.name;
}
clickModal.money = clickModal.money + data.bonus;
clickModal.item.push(data);
});
if(clickModal.item.length < 1){
$(this).popover({
content:"请选择需要发放的人员"
});
$(this).popover("show");
setTimeout(function(){
$("#faFangSelectData").popover('destroy');
}, 1000);
return;
}
$("#lingQuModal").data("data",clickModal);
var t = Handlebars.compile($("#lingQuTemplate").html());
var h = t(clickModal);
var rH = $(h);
$("#yuLanBtn",rH).click(function(){
var img = $(this).data("img");
if(!img) return;
$.initShowImage([img]);
});
$('[data-plugin-masked-input]',rH).each(function() {
var $this = $(this), opts = {};
var pluginOptions = $this.data('plugin-options');
if (pluginOptions)
opts = pluginOptions;
$this.themePluginMaskedInput(opts);
});
$('[data-plugin-datepicker]',rH).each(function() {
var $this = $(this), opts = {};
$this.themePluginDatePicker(opts);
});
$("#upFile",rH).change(function(){
var val = $(this).val();
if(!val) return;
$("#paiZhaoFileLoginState").css("display","inline");
$("#zhaoBtn,#yuLanBtn,#paiZhaoFileCheckState,#upBtn").css("display","none");
submitFile(this,{
fileType:"EVIDENCE_FILE"
},"json",function(data){
actionFormate(data, true, function(type, msg, data) {
data = data.substring(data.indexOf("/")+1);
$("#yuLanBtn").data("img",data);
});
$("#paiZhaoFileLoginState").css("display","none");
$("#zhaoBtn,#yuLanBtn,#paiZhaoFileCheckState,#upBtn").css("display","inline");
},function(e){
$("#paiZhaoFileLoginState").css("display","none");
$("#zhaoBtn,#yuLanBtn,#paiZhaoFileCheckState,#upBtn").css("display","inline");
});
});
$("#lingQuArea").html(rH);
$("#lingQuModal").modal("show");
});
}
function paiZhao(){
$.get("share/photographs.do",function(html){
$("#phonePaiZhaoBody").html(html);
$("#phonePaiZhaoModal").modal("show");
});
}
function upFileZhaoPian(){
$("#upFile").click();
} | huahuajjh/requisition_land | WebRoot/assets/pageJs/housePurchaseMansgement/hptSet.js | JavaScript | apache-2.0 | 5,838 |
var AnalysisPriority = {
Emergency: 0,
ExternalRequestsForNewPositions: 1,
OptimizationOfNotAnalyzedEnough: 2,
MainLineOptimization: 3
};
module.exports = AnalysisPriority;
| Scorpibear/chegura | app/analysis/analysis-priority.js | JavaScript | apache-2.0 | 190 |
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
var dtypes = require( '@stdlib/array/dtypes' );
var nextDataType = require( './../lib' );
var DTYPES;
var dt;
var i;
// Get the list of supported array data types:
DTYPES = dtypes();
// Print the next larger data type for each supported data type...
for ( i = 0; i < DTYPES.length; i++ ) {
dt = nextDataType( DTYPES[ i ] );
console.log( '%s => %s', DTYPES[ i ], dt );
}
| stdlib-js/stdlib | lib/node_modules/@stdlib/array/next-dtype/examples/index.js | JavaScript | apache-2.0 | 1,008 |
//// [foo_1.js]
var foo = require('./test/foo');
var z = foo.x + 10;
| fdecampredon/jsx-typescript-old-version | tests/baselines/reference/relativePathMustResolve.js | JavaScript | apache-2.0 | 72 |
sap.ui.define(['module'], function(moduleInfo) {
return {
name: 'module3-v2',
info: moduleInfo
};
}); | cschuff/openui5 | src/sap.ui.core/test/sap/ui/core/qunit/testdata/modules/dependencies-with-contextual-mapping/module3-v2.js | JavaScript | apache-2.0 | 107 |
define([
'util/clipboardManager',
'util/promise'
], function(ClipboardManager, Promise) {
'use strict';
return withClipboard;
function getObjectsFromClipboardData(data) {
return new Promise(function(fulfill) {
var objects = { vertexIds: [], edgeIds: [] }
if (data) {
require(['util/vertex/urlFormatters'], function(F) {
var p = F.vertexUrl.parametersInUrl(data);
if (p && p.vertexIds) {
fulfill({...p});
} else {
fulfill(objects);
}
})
} else {
fulfill(objects);
}
});
}
function formatVertexAction(action, vertices) {
var len = vertices.length;
return i18n('element.clipboard.action.' + (
len === 1 ? 'one' : 'some'
), i18n('element.clipboard.action.' + action.toLowerCase()), len);
}
function withClipboard() {
this.after('initialize', function() {
ClipboardManager.attachTo(this.$node);
this.on('clipboardPaste', this.onClipboardPaste);
this.on('clipboardCut', this.onClipboardCut);
});
this.onClipboardCut = function(evt, data) {
var self = this;
getObjectsFromClipboardData(data.data).then(elements => {
this.trigger('elementsCut', elements);
});
};
this.onClipboardPaste = function(evt, data) {
var self = this;
getObjectsFromClipboardData(data.data).then(elements => {
const { vertexIds, edgeIds } = elements;
if (elements && !(_.isEmpty(vertexIds) && _.isEmpty(edgeIds))) {
this.trigger('elementsPasted', elements);
} else {
this.trigger('genericPaste', data);
}
});
};
}
});
| visallo/visallo | web/war/src/main/webapp/js/data/withClipboard.js | JavaScript | apache-2.0 | 1,987 |
'use strict'; // eslint-disable-line strict
const assert = require('assert');
const TTLVCodec = require('../../../lib/network/kmip/codec/ttlv.js');
const TransportTemplate =
require('../../../lib/network/kmip/transport/TransportTemplate.js');
const KMIP = require('../../../lib/network/kmip');
const {
logger,
MirrorChannel,
} = require('../../utils/kmip/ersatz.js');
const lowlevelFixtures = require('../../utils/kmip/lowlevelFixtures.js');
class MirrorTransport extends TransportTemplate {
constructor(options) {
super(new MirrorChannel(KMIP, TTLVCodec), options);
}
}
const options = {
kmip: {
codec: {},
transport: {
pipelineDepth: 8,
tls: {
port: 5696,
},
},
},
};
describe('KMIP Low Level Driver', () => {
lowlevelFixtures.forEach((fixture, n) => {
it(`should work with fixture #${n}`, done => {
const kmip = new KMIP(TTLVCodec, MirrorTransport, options);
const requestPayload = fixture.payload(kmip);
kmip.request(logger, fixture.operation,
requestPayload, (err, response) => {
if (err) {
return done(err);
}
const responsePayload = response.lookup(
'Response Message/Batch Item/Response Payload',
)[0];
assert.deepStrictEqual(responsePayload,
requestPayload);
return done();
});
});
});
});
| scality/Arsenal | tests/functional/kmip/lowlevel.spec.js | JavaScript | apache-2.0 | 1,602 |
/* eslint-disable react/prop-types */
/* eslint-disable no-shadow */
import React, { useState, useEffect, Children } from "react";
import PropTypes from "prop-types";
import { cx, css } from "emotion";
// import { polyfill } from "react-lifecycles-compat";
import memoize from "lodash.memoize";
import { createButtonEventHandlers, createCustomClassNames } from "@hig/utils";
import Tab from "./Tab";
import stylesheet from "./presenters/Tabs.stylesheet";
import TabsPresenter from "./presenters/TabsPresenter";
import ContentPresenter from "./presenters/ContentPresenter";
import {
AVAILABLE_ALIGNMENTS,
AVAILABLE_VARIANTS,
AVAILABLE_ORIENTATIONS,
alignments,
variants,
orientations
} from "./constants";
const FIRST_TAB_INDEX = 0;
const DEFAULT_HOVERED_TAB_INDEX = -1;
/**
* @typedef {Object} TabMeta
* @property {string} key
* @property {import("./tab").TabProps} props
*/
/**
* @typedef {Object} TabsProps
* @property {string} [align]
* @property {string} [variant]
* @property {string} [orientation]
* @property {bool} [showTabDivider]
* @property {number} [defaultActiveTabIndex]
* @property {number} [activeTabIndex]
* @property {function} [onTabChange]
* @property {function} [onTabClose]
* @property {ReactNode} [children]
*/
/**
* @typedef {Object} TabsState
* @property {number} activeTabIndex
* @property {number} hoveredTabIndex
* @property {string} effectiveAlign
* @property {string} effectiveOrientation
* @property {bool} effectiveShowTabDivider
*/
/**
* @param {ReactNode} children
* @returns {TabMeta[]}
*/
function createTabs(children) {
return Children.toArray(children).reduce((result, child) => {
const { type, key, props = {} } = child;
if (type === Tab) {
result.push({ key, props });
}
return result;
}, []);
}
/**
* @param {TabsProps} tabsProps
* @returns {number}
*/
function findInitialStateActiveTab(tabsProps) {
if (tabsProps.defaultActiveTabIndex !== undefined) {
return tabsProps.defaultActiveTabIndex;
}
const tabIndexWithActiveProp = createTabs(tabsProps.children).findIndex(
({ props }) => props.active
);
if (tabIndexWithActiveProp >= 0) {
return tabIndexWithActiveProp;
}
return FIRST_TAB_INDEX;
}
const Tabs = props => {
const [activeTabIndex, setActiveTabIndex] = useState(
findInitialStateActiveTab(props)
);
const [hoveredTabIndex, setHoveredTabIndex] = useState(
DEFAULT_HOVERED_TAB_INDEX
);
const [effectiveAlign, setEffectiveAlign] = useState(alignments.LEFT);
const [effectiveShowTabDivider, setEffectiveShowTabDivider] = useState(true);
const [effectiveOrientation, setEffectiveOrientation] = useState(
orientations.HORIZONTAL
);
/**
* @param {number} nextActiveTabIndex
* @param {TabMeta} tab
*/
const onTabSelection = (selectedTabIndex, { disabled }) => {
props.onTabChange(selectedTabIndex);
// eslint-disable-next-line no-use-before-define
const prevActiveTabIndex = getActiveTabIndex();
if (!disabled && prevActiveTabIndex !== selectedTabIndex) {
setActiveTabIndex(selectedTabIndex);
}
};
/**
* If the activeTabIndex has been passed, use it. Otherwise, use our
* internally managed activeTabIndex.
* @returns {number}
*/
const getActiveTabIndex = () =>
props.activeTabIndex !== undefined ? props.activeTabIndex : activeTabIndex;
/** @returns {TabMeta[]} */
const getTabs = () => createTabs(props.children);
/** @returns {TabMeta|undefined} */
const getActiveTab = () => getTabs()[getActiveTabIndex()];
/**
* @param {number} nextHoveredTabIndex
* @param {TabMeta} tab
*/
const setHoveredTab = (nextHoveredTabIndex, { disabled }) => {
const prevHoveredTabIndex = hoveredTabIndex;
if (disabled || prevHoveredTabIndex === nextHoveredTabIndex) return;
setHoveredTabIndex(nextHoveredTabIndex);
};
/**
* @param {number} index
*/
const removeHoveredTab = index => {
if (hoveredTabIndex === index) {
setHoveredTabIndex(DEFAULT_HOVERED_TAB_INDEX);
}
};
const createTabEventHandlers = memoize((index, { disabled }) => ({
...createButtonEventHandlers(() => onTabSelection(index, { disabled })),
onMouseEnter: () => setHoveredTab(index, { disabled }),
onMouseLeave: () => removeHoveredTab(index),
onClose: () => props.onTabClose(index)
}));
/**
* @param {TabMeta} tab
* @param {number} index
* @returns {JSX.Element}
*/
const renderTab = ({ key, props: propsParams }, index) => {
const { disabled, className: tabClassName } = propsParams;
const { variant, className: tabsClassName } = props;
// eslint-disable-next-line no-shadow
const activeTabIndex = getActiveTabIndex();
let showTabDivider = effectiveShowTabDivider;
if (index === activeTabIndex || index === activeTabIndex - 1) {
showTabDivider = false;
}
if (index === hoveredTabIndex || index === hoveredTabIndex - 1) {
showTabDivider = false;
}
const className = cx(
tabClassName,
createCustomClassNames(tabsClassName, "tab")
);
const payload = {
...propsParams,
key,
variant,
className,
showDivider: showTabDivider,
align: effectiveAlign,
orientation: effectiveOrientation,
active: activeTabIndex === index,
...createTabEventHandlers(index, { disabled })
};
return <Tab {...payload} />;
};
/**
* @returns {JSX.Element}
*/
const renderTabs = () => {
// eslint-disable-next-line react/prop-types
const { className, variant, stylesheet: customStylesheet } = props;
return (
<TabsPresenter
variant={variant}
align={effectiveAlign}
orientation={effectiveOrientation}
className={className}
stylesheet={customStylesheet}
>
{getTabs().map(renderTab)}
</TabsPresenter>
);
};
/**
* @returns {JSX.Element}
*/
const renderContent = () => {
// eslint-disable-next-line react/prop-types
const { className, stylesheet: customStylesheet } = props;
const activeTab = getActiveTab();
return (
<ContentPresenter className={className} stylesheet={customStylesheet}>
{activeTab ? activeTab.props.children : null}
</ContentPresenter>
);
};
const styles = stylesheet({ orientation: effectiveOrientation });
useEffect(
() => {
const { children, align, variant, orientation, showTabDivider } = props;
const prevActiveTabIndex = activeTabIndex;
const prevEffectiveAlign = effectiveAlign;
const prevEffectiveOrientation = effectiveOrientation;
const prevEffectiveShowTabDivider = effectiveShowTabDivider;
let hasStateChanged = false;
const nextTabs = createTabs(children);
const nextActiveTabIndex = nextTabs.findIndex(
// eslint-disable-next-line react/prop-types
({ props }) => props.active
);
if (
nextActiveTabIndex >= 0 &&
nextActiveTabIndex !== prevActiveTabIndex &&
props.defaultActiveTabIndex === undefined
) {
setActiveTabIndex(nextActiveTabIndex);
// newState.activeTabIndex = nextActiveTabIndex;
hasStateChanged = true;
}
// vertical tabs will only work when variant is "box"
const nextEffectiveOrientation =
variant === variants.BOX ? orientation : orientations.HORIZONTAL;
if (nextEffectiveOrientation !== prevEffectiveOrientation) {
setEffectiveOrientation(nextEffectiveOrientation);
// newState.effectiveOrientation = nextEffectiveOrientation;
hasStateChanged = true;
}
// align prop will not take effect when orientation is "vertical" or variant is "canvas"
const nextEffectiveAlign =
nextEffectiveOrientation === orientations.VERTICAL ||
variant === variants.CANVAS
? alignments.LEFT
: align;
if (nextEffectiveAlign !== prevEffectiveAlign) {
setEffectiveAlign(nextEffectiveAlign);
// newState.effectiveAlign = nextEffectiveAlign;
hasStateChanged = true;
}
// tab divider will not show when orientation is "vertical" or variant is "underline"
const nextEffectiveShowTabDivider =
nextEffectiveOrientation === orientations.VERTICAL ||
variant === variants.UNDERLINE
? false
: showTabDivider;
if (nextEffectiveShowTabDivider !== prevEffectiveShowTabDivider) {
setEffectiveShowTabDivider(nextEffectiveShowTabDivider);
// newState.effectiveShowTabDivider = nextEffectiveShowTabDivider;
hasStateChanged = true;
}
if (hasStateChanged) {
// return newState;
}
},
[props]
);
return (
<div className={cx(css(styles.wrapper), props.className)}>
{renderTabs()}
{renderContent()}
</div>
);
};
Tabs.displayName = "Tabs";
Tabs.propTypes = {
/**
* Control the active tab.
* Overrides the deprecated active property on the Tab component.
*/
activeTabIndex: PropTypes.number,
/**
* Specify how to justify the tabs within their container
* When variant is set to "canvas", the effective alignment will always be "left"
*/
// eslint-disable-next-line react/no-unused-prop-types
align: PropTypes.oneOf(AVAILABLE_ALIGNMENTS),
/**
* Accepts Tab components
*/
children: PropTypes.node,
/**
* Sets the initial active tab.
* Overrides the deprecated active property on the Tab component.
*/
defaultActiveTabIndex: PropTypes.number,
/**
* Called when user activates a tab
*/
onTabChange: PropTypes.func,
/**
* Called when user closes a tab
*/
onTabClose: PropTypes.func,
/**
* The list orientation of the tabs
* Vertical tabs only works when variant is set to "box"
*/
// eslint-disable-next-line react/no-unused-prop-types
orientation: PropTypes.oneOf(AVAILABLE_ORIENTATIONS),
/**
* Show dividers between tabs
* Only works in horizontal tabs and when variant is set to "box" or "canvas"
*/
// eslint-disable-next-line react/no-unused-prop-types
showTabDivider: PropTypes.bool,
/**
* Function to modify the component's styles
*/
// eslint-disable-next-line react/no-unused-prop-types
stylesheet: PropTypes.func,
/**
* The visual variant of the tabs
*/
// eslint-disable-next-line react/no-unused-prop-types
variant: PropTypes.oneOf(AVAILABLE_VARIANTS)
};
Tabs.defaultProps = {
align: alignments.LEFT,
onTabChange: () => {},
onTabClose: () => {},
variant: variants.UNDERLINE,
orientation: orientations.HORIZONTAL,
showTabDivider: true
};
export default Tabs;
| Autodesk/hig | packages/tabs/src/Tabs.js | JavaScript | apache-2.0 | 10,676 |
/*
Author : Johannes Rudolph
Fixes by : D Conway-Jones
*/
/* globals L: true */
L.Control.mouseCoordinate = L.Control.extend({
options: {
gps: true,
gpsLong: false,
utm: false,
utmref: false,
position: 'bottomleft',
_sm_a: 6378137.0,
_sm_b: 6356752.314,
_sm_EccSquared: 6.69437999013e-03,
_UTMScaleFactor: 0.9996
},
onAdd: function(map){
this._map = map;
if (L.Browser.mobile || L.Browser.mobileWebkit || L.Browser.mobileWebkit3d || L.Browser.mobileOpera || L.Browser.mobileGecko) {
return L.DomUtil.create('div');
}
var className = 'leaflet-control-mouseCoordinate';
var container = this._container = L.DomUtil.create('div',className);
this._gpsPositionContainer = L.DomUtil.create("div","gpsPos",container);
map.on("mousemove", this._update, this);
return container;
},
_update: function(e){
//lat: [-90,90]
//lng: [-180,180]
var lat = (e.latlng.lat+90)%180;
var lng = (e.latlng.lng+180)%360;
if (lat < 0) { lat += 180; }
lat -=90;
if (lng < 0) { lng+= 360; }
lng -= 180;
var gps = {lat:lat, lng:lng};
var content = "<table>";
if (this.options.gps) {
//Round for display only
var dLat = Math.round(lat * 100000) / 100000;
var dLng = Math.round(lng * 100000) / 100000;
content += "<tr><td>Lat, Lon </td><td>" + dLat + ", " + dLng +"</td></tr>";
}
if (this.options.gpsLong) {
// var gpsMinuten = this._geo2geodeziminuten(gps);
// content += "<tr><td>"+ gpsMinuten.NS + " " + gpsMinuten.latgrad + "° "+ gpsMinuten.latminuten+"</td><td> " + gpsMinuten.WE + " "+ gpsMinuten.lnggrad +"° "+ gpsMinuten.lngminuten +"</td></tr>";
var gpsMinutenSekunden = this._geo2gradminutensekunden(gps);
content += "<tr><td>"+ gpsMinutenSekunden.NS + " " + gpsMinutenSekunden.latgrad + "° "+ gpsMinutenSekunden.latminuten + "′ "+ gpsMinutenSekunden.latsekunden+"″</td><td> " + gpsMinutenSekunden.WE + " "+ gpsMinutenSekunden.lnggrad +"° "+ gpsMinutenSekunden.lngminuten + "′ "+ gpsMinutenSekunden.lngsekunden+"″</td></tr>";
}
if (this.options.utm) {
var utm = UTM.fromLatLng(gps);
if (utm !== undefined) {
content += "<tr><td>UTM</td><td>"+utm.zone+" " +utm.x+" " +utm.y+"</td></tr>";
}
}
if (this.options.utmref) {
var utmref = UTMREF.fromUTM(UTM.fromLatLng(gps));
if(utmref !== undefined){
content += "<tr><td>MGRS</td><td>"+utmref.zone+" " +utmref.band+" " +utmref.x+" " +utmref.y+"</td></tr>";
}
}
if (this.options.qth) {
var qth = QTH.fromLatLng(gps);
content += "<tr><td>QTH</td><td>"+qth+"</td></tr>";
}
if (this.options.nac) {
var nac = NAC.fromLatLng(gps);
content += "<tr><td>NAC</td><td>"+nac.y+" "+ nac.x +"</td></tr>";
}
content += "</table>";
this._gpsPositionContainer.innerHTML = content;
},
_geo2geodeziminuten: function (gps) {
var latgrad = parseInt(gps.lat,10);
var latminuten = Math.round( ((gps.lat - latgrad) * 60) * 10000 ) / 10000;
var lnggrad = parseInt(gps.lng,10);
var lngminuten = Math.round( ((gps.lng - lnggrad) * 60) * 10000 ) / 10000;
return this._AddNSEW({latgrad:latgrad, latminuten:latminuten, lnggrad:lnggrad, lngminuten:lngminuten},gps);
},
_geo2gradminutensekunden: function (gps) {
var latgrad = parseInt(gps.lat,10);
var latminuten = (gps.lat - latgrad) * 60;
var latsekunden = Math.round(((latminuten - parseInt(latminuten,10)) * 60) * 100) / 100;
latminuten = parseInt(latminuten,10);
var lnggrad = parseInt(gps.lng,10);
var lngminuten = (gps.lng - lnggrad) * 60;
var lngsekunden = Math.round(((lngminuten - parseInt(lngminuten,10)) * 60) * 100) /100;
lngminuten = parseInt(lngminuten,10);
return this._AddNSEW({latgrad:latgrad, latminuten:latminuten, latsekunden:latsekunden, lnggrad:lnggrad, lngminuten:lngminuten, lngsekunden:lngsekunden},gps);
},
_AddNSEW: function (coord,gps) {
coord.NS = "N";
coord.WE = "E";
if (gps.lat < 0) {
coord.latgrad = coord.latgrad * (-1);
coord.latminuten = coord.latminuten * (-1);
coord.latsekunden = coord.latsekunden * (-1);
coord.NS = "S";
}
if (gps.lng < 0) {
coord.lnggrad = coord.lnggrad * (-1);
coord.lngminuten = coord.lngminuten * (-1);
coord.lngsekunden = coord.lngsekunden * (-1);
coord.WE = "W";
}
return coord;
}
});
L.control.mouseCoordinate = function (options) {
return new L.Control.mouseCoordinate(options);
};
/**
* Created by Johannes Rudolph <johannes.rudolph@gmx.com> on 01.09.2016.
*/
/**
*
* @type {{fromLatLng: NAC.fromLatLng, _nac2Letter: NAC._nac2Letter}}
*/
var NAC = {
/**
* @param {{lat: number, lng: number}}
* @returns {string}
*/
fromLatLng: function(latlng) {
var lat = latlng.lat;
var lon = latlng.lng;
var x = [];
var y = [];
var xy = [];
xy.x = '';
xy.y = '';
if (lon >= -180 && lon <= 180) {
var xlon = (lon + 180) / 360;
x = this._calcValues(xlon);
} else {
x[0] = 0;
}
if (lat >= -90 && lat <= 90) {
var ylat = (lat + 90) / 180;
y = this._calcValues(ylat);
} else {
y[0] = 0;
}
for (var i = 0; i < x.length; i++) {
xy.x += this._nac2Letter(x[i]);
}
for (i = 0; i < y.length; i++) {
xy.y += this._nac2Letter(y[i]);
}
return xy;
},
/**
* @param z
* @returns {Array}
* @private
*/
_calcValues: function (z){
var ret = [];
ret[0] = parseInt(z * 30,10);
ret[1] = parseInt((z * 30 - ret[0]) * 30,10);
ret[2] = parseInt(((z * 30 - ret[0]) * 30 - ret[1]) * 30,10);
ret[3] = parseInt((((z * 30 - ret[0]) * 30 - ret[1]) * 30 - ret[2]) * 30,10);
ret[4] = parseInt(((((z * 30 - ret[0]) * 30 - ret[1]) * 30 - ret[2]) * 30 - ret[3]) * 30,10);
ret[5] = parseInt((((((z * 30 - ret[0]) * 30 - ret[1]) * 30 - ret[2]) * 30 - ret[3]) * 30 - ret[4]) * 30,10);
return ret;
},
/**
* @param number
* @returns {string}
* @private
*/
_nac2Letter: function(number){
var nac_letters = "0123456789BCDFGHJKLMNPQRSTVWXZ";
if(!isNaN(number) && number < 30)
return nac_letters.substr(number,1);
else return 0;
}
};
/**
* Created by Johannes Rudolph <johannes.rudolph@gmx.com> on 01.09.2016.
*/
/**
* @type {{fromLatLng: QTH.fromLatLng}}
*/
var QTH = {
/**
* @param {{lat: number, lng: number}}
* @returns {string}
*/
fromLatLng: function(latlng){
/* Long/Lat to QTH locator conversion largely */
/* inspired from the DL4MFM code found here : */
/* http://members.aol.com/mfietz/ham/calcloce.html */
var ychr = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var ynum = "0123456789";
var yqth, yi, yk, ydiv, yres, ylp;
var y = 0;
var ycalc = [0,0,0];
var yn = [0,0,0,0,0,0,0];
ycalc[1] = latlng.lng+ 180;
ycalc[2] = latlng.lat + 90;
for (yi = 1; yi < 3; ++yi) {
for (yk = 1; yk < 4; ++yk) {
if (yk !== 3) {
if (yi === 1) {
if (yk === 1) ydiv = 20;
if (yk === 2) ydiv = 2;
}
if (yi === 2) {
if (yk === 1) ydiv = 10;
if (yk === 2) ydiv = 1;
}
yres = ycalc[yi] / ydiv;
ycalc[yi] = yres;
if (ycalc[yi]>0)
ylp = Math.floor(yres);
else
ylp = Math.ceil(yres);
ycalc[yi] = (ycalc[yi] - ylp) * ydiv;
}
else {
if (yi === 1)
ydiv = 12;
else
ydiv = 24;
yres = ycalc[yi] * ydiv;
ycalc[yi] = yres;
if (ycalc[yi] > 0)
ylp = Math.floor(yres);
else
ylp = Math.ceil(yres);
}
++y;
yn[y] = ylp;
}
}
yqth = ychr.charAt(yn[1]) + ychr.charAt(yn[4]) + ynum.charAt(yn[2]);
yqth += ynum.charAt(yn[5]) + ychr.charAt(yn[3])+ ychr.charAt(yn[6]);
return yqth;
}
};
/**
* Created by Johannes Rudolph <johannes.rudolph@gmx.com> on 01.09.2016.
*/
/**
* @type {{fromLatLng: UTM.fromLatLng, toLatLng: UTM.toLatLng}}
*/
var UTM = {
/**
*
* @param {{lat: number, lng: number}}
* @returns {{zone: string, x: number, y: number}}
*/
fromLatLng: function (latlng) {
//Copyright (c) 2006, HELMUT H. HEIMEIER
/*
* Okay, this just gives the wrong result:
* `UTMREF.fromUTM(UTM.fromLatLng({lat: 0, lng: -179.9999999999999}))`
* Results in
* `Object {zone: "02N", band: "HF", x: "50564", y: "00000"}`
* but should be in zone `01N`...
**/
var lw = latlng.lng;
var bw = latlng.lat;
if (lw === -180) {
lw += 1e-13;//Number.MIN_VALUE;
}
if (lw === 180) {
lw -= 1e-13;//umber.MIN_VALUE;
}
if (bw === -90) bw += 1e-13;//umber.MIN_VALUE;
if (bw === 90) bw -= 1e-13;//umber.MIN_VALUE;
// Geographische Laenge lw und Breite bw im WGS84 Datum
if (lw <= -180 || lw >= 180 || bw <= -80 || bw >= 84) {
console.error("Out of lw <= -180 || lw >= 180 || bw <= -80 || bw >= 84 bounds, which is kinda similar to UTM bounds, if you ignore the poles");
//alert("Werte nicht im Bereich des UTM Systems\n -180 <= LW < +180, -80 < BW < 84 N"); // jshint ignore:line
return;
}
lw = parseFloat(lw);
bw = parseFloat(bw);
// WGS84 Datum
// Grosse Halbachse a und Abplattung f
var a = 6378137.000;
var f = 3.35281068e-3;
var pi = Math.PI;
var b_sel = 'CDEFGHJKLMNPQRSTUVWXX';
// Polkruemmungshalbmesser c
var c = a/(1-f);
// Quadrat der zweiten numerischen Exzentrizitaet
var ex2 = (2*f-f*f)/((1-f)*(1-f));
var ex4 = ex2*ex2;
var ex6 = ex4*ex2;
var ex8 = ex4*ex4;
// Koeffizienten zur Berechnung der Meridianbogenlaenge
var e0 = c*(pi/180)*(1 - 3*ex2/4 + 45*ex4/64 - 175*ex6/256 + 11025*ex8/16384);
var e2 = c*( - 3*ex2/8 + 15*ex4/32 - 525*ex6/1024 + 2205*ex8/4096);
var e4 = c*(15*ex4/256 - 105*ex6/1024 + 2205*ex8/16384);
var e6 = c*( - 35*ex6/3072 + 315*ex8/12288);
// Laengenzone lz und Breitenzone (Band) bz
var lzn = parseInt((lw+180)/6,10) + 1;
var lz = lzn;
if (lzn < 10) {
lz = "0" + lzn;
}
//Chunk of code from https://github.com/proj4js/mgrs/blob/e43d7d644564c09831587a5f01c911caae991d8c/mgrs.js#L128-L147
//MIT License
//Copyright (c) 2012, Mike Adair, Richard Greenwood, Didier Richard, Stephen Irons, Olivier Terral, Calvin Metcalf
//
//Portions of this software are based on a port of components from the OpenMap com.bbn.openmap.proj.coords Java package. An initial port was initially created by Patrice G. Cappelaere and included in Community Mapbuilder (http://svn.codehaus.org/mapbuilder/), which is licensed under the LGPL license as per http://www.gnu.org/copyleft/lesser.html. OpenMap is licensed under the following license agreement:
// Special zone for Norway
if (bw >= 56.0 && bw < 64.0 && lw >= 3.0 && lw < 12.0) {
lz = 32;
}
// Special zones for Svalbard
if (bw >= 72.0 && bw < 84.0) {
if (lw >= 0.0 && lw < 9.0) {
lz = 31;
}
else if (lw >= 9.0 && lw < 21.0) {
lz = 33;
}
else if (lw >= 21.0 && lw < 33.0) {
lz = 35;
}
else if (lw >= 33.0 && lw < 42.0) {
lz = 37;
}
}
//End part of code from proj4js/mgrs
var bd = parseInt(1 + (bw + 80)/8,10);
var bz = b_sel.substr(bd-1,1);
// Geographische Breite in Radianten br
var br = bw * pi/180;
var tan1 = Math.tan(br);
var tan2 = tan1*tan1;
var tan4 = tan2*tan2;
var cos1 = Math.cos(br);
var cos2 = cos1*cos1;
var cos4 = cos2*cos2;
var cos3 = cos2*cos1;
var cos5 = cos4*cos1;
var etasq = ex2*cos2;
// Querkruemmungshalbmesser nd
var nd = c/Math.sqrt(1 + etasq);
// Meridianbogenlaenge g aus gegebener geographischer Breite bw
var g = (e0*bw) + (e2*Math.sin(2*br)) + (e4*Math.sin(4*br)) + (e6*Math.sin(6*br));
// Laengendifferenz dl zum Bezugsmeridian lh
var lh = (lzn - 30)*6 - 3;
var dl = (lw - lh)*pi/180;
var dl2 = dl*dl;
var dl4 = dl2*dl2;
var dl3 = dl2*dl;
var dl5 = dl4*dl;
// Masstabsfaktor auf dem Bezugsmeridian bei UTM Koordinaten m = 0.9996
// Nordwert nw und Ostwert ew als Funktion von geographischer Breite und Laenge
var nw;
if ( bw < 0 ) {
nw = 10e6 + 0.9996*(g + nd*cos2*tan1*dl2/2 + nd*cos4*tan1*(5-tan2+9*etasq)*dl4/24);
}
else {
nw = 0.9996*(g + nd*cos2*tan1*dl2/2 + nd*cos4*tan1*(5-tan2+9*etasq)*dl4/24);
}
var ew = 0.9996*( nd*cos1*dl + nd*cos3*(1-tan2+etasq)*dl3/6 + nd*cos5 *(5-18*tan2+tan4)*dl5/120) + 500000;
var zone = lz+bz;
var nk = nw - parseInt(nw,10);
if (nk < 0.5) {
nw = "" + parseInt(nw,10);
}
else {
nw = "" + (parseInt(nw,10) + 1);
}
while (nw.length < 7) {
nw = "0" + nw;
}
nk = ew - parseInt(ew,10);
if (nk < 0.5) {
ew = "0" + parseInt(ew,10);
}
else {
ew = "0" + parseInt(ew+1,10);
}
return {zone: zone, x: ew, y: nw};
},
/**
* @param {{zone: string, x: number, y: number}}
* @returns {{lat: number, lng: number}}
*/
toLatLng: function (utm){
// Copyright (c) 2006, HELMUT H. HEIMEIER
var zone = utm.zone;
var ew = utm.x;
var nw = utm.y;
// Laengenzone zone, Ostwert ew und Nordwert nw im WGS84 Datum
if (zone === "" || ew === "" || nw === ""){
zone = "";
ew = "";
nw = "";
return;
}
var band = zone.substr(2,1);
zone = parseFloat(zone);
ew = parseFloat(ew);
nw = parseFloat(nw);
// WGS84 Datum
// Grosse Halbachse a und Abplattung f
var a = 6378137.000;
var f = 3.35281068e-3;
var pi = Math.PI;
// Polkruemmungshalbmesser c
var c = a/(1-f);
// Quadrat der zweiten numerischen Exzentrizitaet
var ex2 = (2*f-f*f)/((1-f)*(1-f));
var ex4 = ex2*ex2;
var ex6 = ex4*ex2;
var ex8 = ex4*ex4;
// Koeffizienten zur Berechnung der geographischen Breite aus gegebener
// Meridianbogenlaenge
var e0 = c*(pi/180)*(1 - 3*ex2/4 + 45*ex4/64 - 175*ex6/256 + 11025*ex8/16384);
var f2 = (180/pi)*( 3*ex2/8 - 3*ex4/16 + 213*ex6/2048 - 255*ex8/4096);
var f4 = (180/pi)*( 21*ex4/256 - 21*ex6/256 + 533*ex8/8192);
var f6 = (180/pi)*( 151*ex6/6144 - 453*ex8/12288);
// Entscheidung Nord-/Sued Halbkugel
var m_nw;
if (band >= "N"|| band === ""){
m_nw = nw;
}
else {
m_nw = nw - 10e6;
}
// Geographische Breite bf zur Meridianbogenlaenge gf = m_nw
var sigma = (m_nw/0.9996)/e0;
var sigmr = sigma*pi/180;
var bf = sigma + f2*Math.sin(2*sigmr) + f4*Math.sin(4*sigmr) + f6*Math.sin(6*sigmr);
// Breite bf in Radianten
var br = bf * pi/180;
var tan1 = Math.tan(br);
var tan2 = tan1*tan1;
var tan4 = tan2*tan2;
var cos1 = Math.cos(br);
var cos2 = cos1*cos1;
var etasq = ex2*cos2;
// Querkruemmungshalbmesser nd
var nd = c/Math.sqrt(1 + etasq);
var nd2 = nd*nd;
var nd4 = nd2*nd2;
var nd6 = nd4*nd2;
var nd3 = nd2*nd;
var nd5 = nd4*nd;
// Laengendifferenz dl zum Bezugsmeridian lh
var lh = (zone - 30)*6 - 3;
var dy = (ew-500000)/0.9996;
var dy2 = dy*dy;
var dy4 = dy2*dy2;
var dy3 = dy2*dy;
var dy5 = dy3*dy2;
var dy6 = dy3*dy3;
var b2 = - tan1*(1+etasq)/(2*nd2);
var b4 = tan1*(5+3*tan2+6*etasq*(1-tan2))/(24*nd4);
var b6 = - tan1*(61+90*tan2+45*tan4)/(720*nd6);
var l1 = 1/(nd*cos1);
var l3 = - (1+2*tan2+etasq)/(6*nd3*cos1);
var l5 = (5+28*tan2+24*tan4)/(120*nd5*cos1);
// Geographische Breite bw und Laenge lw als Funktion von Ostwert ew
// und Nordwert nw
var bw = bf + (180/pi) * (b2*dy2 + b4*dy4 + b6*dy6);
var lw = lh + (180/pi) * (l1*dy + l3*dy3 + l5*dy5);
return {lat: bw, lng: lw};
}
};
/**
* Created by Johannes Rudolph <johannes.rudolph@gmx.com> on 01.09.2016.
*/
/**
* @type {{fromUTM: UTMREF.fromUTM, toUTM: UTMREF.toUTM}}
*/
var UTMREF = {
/**
* @param {{zone: string, x: number, y: number}}
* @returns {{zone, band: string, x: string, y: string}}
*/
fromUTM: function (utm) {
// Copyright (c) 2006, HELMUT H. HEIMEIER
if(utm === undefined){
return;
}
var zone = utm.zone;
var ew = utm.x;
var nw = utm.y;
// Laengenzone zone, Ostwert ew und Nordwert nw im WGS84 Datum
var z1 = zone.substr(0, 2);
var z2 = zone.substr(2, 1);
var ew1 = parseInt(ew.substr(0, 2),10);
var nw1 = parseInt(nw.substr(0, 2),10);
var ew2 = ew.substr(2, 5);
var nw2 = nw.substr(2, 5);
var m_east = 'ABCDEFGHJKLMNPQRSTUVWXYZ';
var m_north = 'ABCDEFGHJKLMNPQRSTUV';
/*if (z1 < "01" || z1 > "60" || z2 < "C" || z2 > "X") {
alert(z1 + z2 + " ist keine gueltige UTM Zonenangabe"); // jshint ignore:line
}*/
var m_ce;
var i = z1 % 3;
if (i === 1) {
m_ce = ew1 - 1;
}
if (i === 2) {
m_ce = ew1 + 7;
}
if (i === 0) {
m_ce = ew1 + 15;
}
i = z1 % 2;
var m_cn;
if (i === 1) {
m_cn = 0;
}
else {
m_cn = 5;
}
i = nw1;
while (i - 20 >= 0) {
i = i - 20;
}
m_cn = m_cn + i;
if (m_cn > 19) {
m_cn = m_cn - 20;
}
var band = m_east.charAt(m_ce) + m_north.charAt(m_cn);
return {zone: zone, band: band, x: ew2, y: nw2};
},
/**
* @param {{zone, band: string, x: string, y: string}}
* @returns {{zone: string, x: number, y: number}}
*/
toUTM: function (mgr) {
// Copyright (c) 2006, HELMUT H. HEIMEIER
// Laengenzone zone, Ostwert ew und Nordwert nw im WGS84 Datum
var m_east_0 = "STUVWXYZ";
var m_east_1 = "ABCDEFGH";
var m_east_2 = "JKLMNPQR";
var m_north_0 = "FGHJKLMNPQRSTUVABCDE";
var m_north_1 = "ABCDEFGHJKLMNPQRSTUV";
//zone = raster.substr(0,3);
var zone = mgr.zone;
var r_east = mgr.band.substr(0, 1);
var r_north = mgr.band.substr(1, 1);
var i = parseInt(zone.substr(0, 2),10) % 3;
var m_ce;
if (i === 0) {
m_ce = m_east_0.indexOf(r_east) + 1;
}
if (i === 1) {
m_ce = m_east_1.indexOf(r_east) + 1;
}
if (i === 2) {
m_ce = m_east_2.indexOf(r_east) + 1;
}
var ew = "0" + m_ce;
var m_cn = this._mgr2utm_find_m_cn(zone);
var nw;
if (m_cn.length === 1) {
nw = "0" + m_cn;
}
else {
nw = "" + m_cn;
}
return {zone: zone, x: ew, y: nw};
}
}; | dceejay/RedMap | worldmap/leaflet/leaflet.mousecoordinate.js | JavaScript | apache-2.0 | 21,073 |
/**
* @license Apache-2.0
*
* Copyright (c) 2021 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
// MODULES //
var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var smskinv = require( './smskinv.js' );
var ndarray = require( './ndarray.js' );
// MAIN //
setReadOnly( smskinv, 'ndarray', ndarray );
// EXPORTS //
module.exports = smskinv;
| stdlib-js/stdlib | lib/node_modules/@stdlib/math/strided/special/smskinv/lib/main.js | JavaScript | apache-2.0 | 917 |
'use strict';
angular.module('myApp.home.rightpanel',[])
.config([function() {
// $routeProvider.when('/view2', {
// templateUrl: 'view2/home.html',
// controller: 'View2Ctrl'
// });
}])
.controller('RightPanelCtrl', ['$scope','$rootScope', 'FinSelection', function($scope,$rootScope,FinSelection) {
$scope.finSelect = FinSelection;
$scope.$watch('finSelect', function (newValue,oldValue, scope) {
if (newValue === oldValue){
return;
}
if (!newValue){
return;
}
var attrChange = false;
if (!oldValue || !newValue || !oldValue.attr || !newValue.attr){
attrChange = true;
}
else{
for (var i = 0; i < newValue.attr.length; i++){
var selElem = FinSelection.element;
if (oldValue.attr[i].value !== newValue.attr[i].value){
attrChange = true;
break;
}
}
}
if (attrChange){
var elem = newValue.element;
var appFrame = window.frames['appframe'];
var $elem = $(appFrame.document).find("#" + elem.id);
var $elemParent = $elem.parent();
var html = SFinProject.renderPage(elem);
var okHtml = appFrame.compileElement(html);
$elem.replaceWith($(okHtml));
}
}, true);
}])
.controller('PropTextCtrl', ['$scope', '$rootScope','$window', '$log', 'ActionManager', 'FinProjectRender'
,function($scope, $rootScope, $window, $log, ActionManager, FinProjectRender) {
// $scope.propText = {
// align: {desc: $rootScope.propTextDesc.align, value: 'center'}
// ,size: {comb: true, desc: $rootScope.propTextDesc.size, value: {desc: $rootScope.propTextDesc.size.value, value: 10}
// ,unit: {desc: $rootScope.propTextDesc.size.unit, value: 'pt'}}
// ,color: {desc: $rootScope.propTextDesc.color, value: '#FFFFFF00'}
// ,backColor: {desc: $rootScope.propTextDesc.backColor, value: '#FF00FF00'}
// ,position: {desc: $rootScope.propTextDesc.position, value: 'relative'}
// ,left: {desc: $rootScope.propTextDesc.left, value: '0'}
// ,visible: {desc: $rootScope.propTextDesc.visible, value: 'true'}
// };
$scope.propText = $rootScope.selElem.propText;
$scope.ary = ['a', 'b', 'c'];
$scope.slider = {
value: 150
,options: {
floor: 0
,ceil: 450
,hideLimitLabels:true
}
};
// $scope.$watchCollection('propText.align', function () {
// $log.info("sel: " + $scope.propText.align);
// });
$scope.onTextSizeUnit = function (unit) {
$scope.propText.size.unit.value = unit;
};
$scope.onBtnTest = function () {
};
/**
* 当单个数据发生变化时,将期加入undoredo中。
* @param newValue obj.field的新值
* @param oldValue obj.field的旧值
* @param scope obj所在的scope
* @param name action名称。
* @param obj action操作的对象。
* @param field 操作的对象的字段。
*/
function valueChange(newValue, oldValue, scope, name, propName, obj, field) {
if (oldValue == null || oldValue === newValue){
return;
}
if ($rootScope.selElem == null){
$log.info("no element selected.");
return;
}
var $elem = $("#" + $rootScope.selElem.id);
if (null == $elem){
$log.info("selected element not exist.");
return;
}
switch (propName){
case 'align':
$elem.css("text-align", obj[field]);
break;
case 'color':
$elem.css("color", obj[field]);
break;
case 'backColor':
$elem.css("background-color", obj[field]);
break;
case 'position':
$elem.css("position", obj[field]);
break;
case 'left':
$elem.css("left", obj[field] + "px");
break;
case 'visible':
$elem.css("visibility", obj[field]?"inherit":"hidden");
break;
case 'width':
$elem.css("width", $scope.propText.width.value.value + $scope.propText.width.unit.value);
break;
case 'size':
$elem.css("font-size", $scope.propText.size.value.value + $scope.propText.size.unit.value);
break;
}
if (obj.undo){
obj.undo = false;
return;
}
if (obj.redo){
obj.redo = false;
return;
}
var action = new ValueAction(name, obj, field, oldValue, newValue, $scope);
ActionManager.addAction(action);
}
function watchAll(obj, objVarName){
for (var item in obj){
if (typeof(obj[item]) !== "object"){
continue;
}
if ('comb' in obj[item]){
watchAll(obj[item], objVarName + '.' + item);
}
if ('desc' in obj[item]){
var actionName = obj[item]['desc']['actionName'];
var changeObj = obj[item];
// 使用匿名函数向回调函数传参。
(function (actionName, propName, changeObj) {
$scope.$watch(objVarName + '.' + item + '.value', function(newValue,oldValue, scope){
valueChange(newValue, oldValue, scope, actionName, propName, changeObj, "value");
});
// $log.debug("now watch: " + objVarName + '.' + item + '.value');
})(actionName, item, changeObj);
}
}
}
watchAll($scope.propText, 'propText');
// $scope.$watch('propText.align.value', function(newValue,oldValue, scope){
// valueChange(newValue, oldValue, scope, scope.propText.align['desc']['actionName'], scope.propText.align, "value");
// });
// $scope.$watch('propText.color.value', function(newValue,oldValue, scope){
// valueChange(newValue, oldValue, scope, scope.propText.color['desc']['actionName'], scope.propText.color, "value");
// });
}])
; | fingergit/visual-app-creator | app/home/rightpanel.js | JavaScript | apache-2.0 | 6,339 |
var madrona = {
onShow: function(callback) { callback(); },
setupForm: function($form) {
//var submitted = false;
$form.find('.btn-submit').hide();
$form.find('label').each(function (i, label) {
if ($(label).find('input[type="checkbox"]').length) {
$(label).addClass('checkbox');
}
});
$form.closest('.panel').on('click', '.cancel_button', function(e) {
app.viewModel.scenarios.reset({cancel: true});
});
$form.closest('.panel').on('click', '.submit_button', function(e) {
e.preventDefault();
var name = $('#id_name').val();
if ($.trim(name) === "") {
$('#invalid-name-message').show();
return false;
}
//submitted = true;
submitForm($form);
});
//no longer needed...? (if it was going here it meant there was a problem)
/*
$form.submit( function() {
var name = $('#id_name').val();
if ($.trim(name) === "") {
$('#invalid-name-message').show();
return false;
}
if (!submitted) {
submitForm($form);
}
});
*/
submitForm = function($form) {
//var $form = $(this).closest('.panel').find('form'),
var url = $form.attr('action'),
$bar = $form.closest('.tab-pane').find('.bar'),
data = new FormData(),
barTimer;
//progress bar
barTimer = setInterval(function () {
var width = parseInt($bar.css('width').replace('px', ''), 10) + 5,
barWidth = parseInt($bar.parent().css('width').replace('px',''), 10);
if (width < barWidth) {
$bar.css('width', width + "px");
} else {
clearInterval(barTimer);
}
}, 500);
app.checkboxes = {};
$form.find('input,select,textarea').each( function(index, input) {
var $input = $(input);
if ($input.attr('type') === 'checkbox') {
if ($input.attr('checked')) {
if ($input.attr('name').indexOf('checkboxes') >= 0) {
if ($input.attr('name') in app.checkboxes) {
app.checkboxes[$input.attr('name')].push($input.attr('value'));
} else {
app.checkboxes[$input.attr('name')] = [$input.attr('value')];
}
} else {
data.append($input.attr('name'), 'True');
}
} else {
data.append($input.attr('name'), 'False');
}
} else {
if ($input.attr('type') == 'file') {
$.each($input[0].files, function(i, file) {
data.append('file-'+i, file);
});
} else {
data.append($input.attr('name'), $input.val());
}
}
});
var checkboxList = Object.keys(app.checkboxes);
for (var i = 0; i < checkboxList.length; i++) {
data.append(checkboxList[i], app.checkboxes[checkboxList[i]]);
}
app.viewModel.scenarios.scenarioForm(false);
app.viewModel.scenarios.loadingMessage("Creating Design");
$.ajax( {
url: url,
data: data,
cache: false,
contentType: false,
processData: false,
type: 'POST',
traditional: true,
dataType: 'json',
success: function(result) {
app.viewModel.scenarios.addScenarioToMap(null, {uid: result['X-Madrona-Show']});
app.viewModel.scenarios.loadingMessage(false);
clearInterval(barTimer);
app.viewModel.scenarios.loadCollectionsFromServer();
},
error: function(result) {
app.viewModel.scenarios.loadingMessage(null);
clearInterval(barTimer);
if (result.status === 400) {
$('#'+app.viewModel.currentTocId()+'-scenario-form > div').append(result.responseText);
app.viewModel.scenarios.scenarioForm(true);
} else if (result.status = 504) {
app.viewModel.scenarios.errorMessage('Gateway Timeout: The\
server is taking longer than expected to respond. Please \
wait a few minutes and refresh the page. If this doesn\'t \
fix the issue, try breaking your scenario up into smaller, \
simpler pieces and uploading them individually.');
} else {
app.viewModel.scenarios.errorMessage(result.responseText.split('\n\n')[0]);
}
}
});
};
}
}; // end madrona init
function scenarioFormModel(options) {
var self = this;
self.species = ko.observable(false);
self.lifestage = ko.observable(false);
self.mean_fthm = ko.observable(false);
self.hsall_m2 = ko.observable(false);
self.hsall_m2_checkboxes_0 = ko.observable(true);
self.hsall_m2_checkboxes_1 = ko.observable(true);
self.hsall_m2_checkboxes_2 = ko.observable(true);
self.hsall_m2_checkboxes_3 = ko.observable(true);
self.hsall1_m2 = ko.observable(false);
self.hsall2_m2 = ko.observable(false);
self.hsall3_m2 = ko.observable(false);
self.hsall4_m2 = ko.observable(false);
self.hpc_est_m2 = ko.observable(false);
self.hpc_klp_m2 = ko.observable(false);
self.hpc_rck_m2 = ko.observable(false);
self.hpc_sgr_m2 = ko.observable(false);
self.sft_sub_m2 = ko.observable(false);
self.mix_sub_m2 = ko.observable(false);
self.hrd_sub_m2 = ko.observable(false);
self.rck_sub_m2 = ko.observable(false);
self.cnt_cs = ko.observable(false);
self.cnt_penn = ko.observable(false);
self.lastChange = (new Date()).getTime();
var defaultStyle = new OpenLayers.Style({
//display: 'none'
fillColor: '#ee9900',
fillOpacity: .5,
strokeColor: '#DDDDDD',
strokeOpacity: .6,
strokeWidth: 1
});
var styleMap = new OpenLayers.StyleMap( {
'default': defaultStyle
});
self.updatedFilterResultsLayer = new OpenLayers.Layer.Vector('Current Filter Results', {
projection: new OpenLayers.Projection('EPSG:3857'),
displayInLayerSwitcher: false,
styleMap: styleMap
});
app.map.addLayer(self.updatedFilterResultsLayer);
/** Toggle an input div. */
self.toggleParameter = function(param) {
var param_bool = self[param];
var param_element = $('#id_' + param);
var param_widget = $('#' + param + '_widget');
if (param_bool()) {
param_bool(false);
param_element.removeAttr('checked');
param_widget.css('display', 'none');
self.removeFilter(param);
} else {
if (param_widget) {
var input = param_widget.find('input');
var range = input.attr('range');
if (range) {
param_widget.find('.slider').first().slider('option', 'range', 'max');
}
}
param_bool(true);
param_element.attr('checked', 'checked');
param_widget.css('display', 'block');
self.updateFilters(param);
}
self.updateDesignScrollBar();
self.updateFilterCount(param);
};
self.filters = {};
// Toggle Data Layers and Layer Info
self.toggleLayerInfo = function(layerID) {
var layer = app.viewModel.getLayerById(layerID);
if (layer) {
if ( layer.infoActive() ) {
layer.hideDescription(layer);
} else {
layer.showDescription(layer);
}
return true;
}
return false;
};
self.isLayerInfoActive = function(layerID) {
var layer = app.viewModel.getLayerById(layerID);
if (layer) {
return layer.infoActive();
}
return false;
};
self.isLayerActive = function(layerID) {
var layer = app.viewModel.getLayerById(layerID);
if (layer) {
return layer.active();
}
return false;
};
self.isLayerVisible = function(layerID) {
var layer = app.viewModel.getLayerById(layerID);
if (layer) {
return layer.visible();
}
return false;
};
self.toggleLayer = function(layerID) {
var layer = app.viewModel.getLayerById(layerID);
if (layer) {
if ( layer.active() ) {
layer.deactivateLayer();
} else {
layer.activateLayer();
}
return true;
}
return false;
};
// Updating Dynamic Display
self.gridCellsRemaining = ko.observable('...');
self.showingFilteringResults = ko.observable(false);
self.inputsHaveChanged = ko.observable(true);
self.showButtonSpinner = ko.observable(false);
self.currentCountRequest = ko.observable(false);
self.currentGridRequest = ko.observable(false);
self.lastChange = (new Date()).getTime();
self.showFilteringResults = function() {
if (self.showingFilteringResults()) {
self.stopShowingFilteringResults();
} else {
self.showingFilteringResults(true);
self.updatedFilterResultsLayer.setVisibility(true);
if (self.inputsHaveChanged()) {
self.inputsHaveChanged(false);
self.getUpdatedFilterResults();
}
}
};
self.stopShowingFilteringResults = function() {
self.showingFilteringResults(false);
// app.map.removeLayer(self.scenarioFormModel.updatedFilterResultsLayer);
// self.updatedFilterResultsLayer.removeAllFeatures();
self.updatedFilterResultsLayer.setVisibility(false);
};
self.updateFiltersAndCount = function(param) {
self.updateFilters(param);
self.updateFilterCount(param);
};
self.updateFilterCount = function(param) {
if (self.updateTimeout) {
clearTimeout(self.updateTimeout);
}
self.inputsHaveChanged(true);
if (self.showingFilteringResults()) {
self.showButtonSpinner(true);
}
self.gridCellsRemaining('...');
self.updatedFilterResultsLayer.removeAllFeatures();
self.updateFilterResults();
};
self.updateFilterResults = function() {
if (self.showingFilteringResults()) {
self.getUpdatedFilterResults();
} else {
self.getUpdatedFilterCount();
}
};
// TODO: CHANGE TO A GET
self.getUpdatedFilterCount = function() {
(function() {
var request = $.ajax({
url: '/scenario/get_filter_count',
type: 'GET',
data: self.filters,
dataType: 'json',
success: function(data) {
if (self.currentCountRequest() === request) {
self.gridCellsRemaining(data);
}
},
error: function(error) {
console.log('error in getUpdatedFilterCount: ' + error);
}
});
self.currentCountRequest(request);
var request = request;
})();
};
// TODO: CHANGE TO A GET
self.getUpdatedFilterResults = function() {
self.updatedFilterResultsLayer.setVisibility(false);
self.showButtonSpinner(true);
(function() {
var request = $.ajax({
url: '/scenario/get_filter_results',
type: 'GET',
data: self.filters,
dataType: 'json',
success: function(data) {
if (self.currentGridRequest() === request) {
var wkt = data[0].wkt,
featureCount = data[0].count;
self.updatedFilterResultsLayer.removeAllFeatures();
if (featureCount) {
var format = new OpenLayers.Format.WKT()
feature = format.read(wkt);
self.updatedFilterResultsLayer.addFeatures([feature]);
}
self.updatedFilterResultsLayer.setVisibility(true);
self.gridCellsRemaining(featureCount);
self.showButtonSpinner(false);
}
},
error: function(result) {
self.showButtonSpinner(false);
self.showingFilteringResults(false);
console.log('error in getUpdatedFilterResults: ' + error);
}
});
self.currentGridRequest(request);
var request = request;
})();
};
self.updateFilters = function(param) {
var min, max, input, checkboxes,
param_element_min = $('#id_' + param + '_min')[0],
param_element_max = $('#id_' + param + '_max')[0],
param_element_input = $('#id_' + param + '_input')[0],
param_element_checkboxes = $('#id_' + param + '_checkboxes_0')[0];
if (param_element_min) {
min = param_element_min.value;
}
if (param_element_max) {
max = param_element_max.value;
}
if (param_element_input) {
input = param_element_input.value;
}
if (param_element_checkboxes) {
checkboxes = [];
var i = 0;
while ($('#id_' + param + '_checkboxes_' + i.toString())[0]) {
var box = $('#id_' + param + '_checkboxes_' + i.toString())[0];
if (box.checked) {
checkboxes.push(box.value);
}
i++;
}
}
self.updateFilter(param, min, max, input, checkboxes);
};
self.updateFilter = function(param, min, max, input, checkboxes) {
var key;
self.filters[param] = true;
if (min) {
key = param + '_min';
self.filters[key] = min;
}
if (max) {
key = param + '_max';
self.filters[key] = max;
}
if (input) {
key = param + '_input';
self.filters[key] = input;
}
if (checkboxes) {
key = param + '_checkboxes';
self.filters[key] = true;
for(var i = 0; i < checkboxes.length; i++) {
key = param + '_checkboxes_' + checkboxes[i];
self.filters[key] = true;
}
}
};
self.removeFilter = function(key) {
delete self.filters[key];
delete self.filters[key+'_min'];
delete self.filters[key+'_max'];
delete self.filters[key+'_input'];
if (self.filters.hasOwnProperty(key+'_checkboxes')) {
delete self.filters[key+'_checkboxes'];
var filter_keys = Object.keys(self.filters);
var box_keys = [];
for(var counter = 0; counter < filter_keys.length; counter++) {
if (filter_keys[counter].indexOf(key+'_checkboxes_') > -1) {
box_keys.push(filter_keys[counter]);
}
}
for(var i = 0; i < box_keys.length; i++) {
delete self.filters[box_keys[i]];
}
}
};
self.updateDesignScrollBar = function() {
var designsWizardScrollpane = $('#wind-design-form').data('jsp');
if (designsWizardScrollpane === undefined) {
$('#wind-design-form').jScrollPane();
} else {
setTimeout(function() {designsWizardScrollpane.reinitialise();},100);
}
};
return self;
} // end scenarioFormModel
function scenarioModel(options) {
var self = this;
self.id = options.uid || null;
self.uid = options.uid || null;
self.name = options.name;
self.display_name = options.display_name?options.display_name:self.name;
self.collection = options.collection;
self.featureAttributionName = self.name;
self.description = options.description;
self.shared = ko.observable();
self.sharedByName = options.sharedByName || null;
self.sharedByUsername = options.sharedByUsername;
if (self.sharedByName && $.trim(self.sharedByName) !== '') {
self.sharedByWho = self.sharedByName + ' (' + self.sharedByUsername + ')';
} else {
self.sharedByWho = self.sharedByUsername;
}
self.sharedBy = ko.observable();
if (options.shared) {
self.shared(true);
self.sharedBy('Shared by ' + self.sharedByWho);
} else {
self.shared(false);
self.sharedBy(false);
}
self.selectedGroups = ko.observableArray();
self.sharedGroupsList = [];
if (options.sharingGroups && options.sharingGroups.length) {
self.selectedGroups(options.sharingGroups);
}
self.sharedWith = ko.observable();
self.updateSharedWith = function() {
if (self.selectedGroups().length) {
self.sharedWith(self.selectedGroups().join(', '));
}
};
self.updateSharedWith();
self.selectedGroups.subscribe( function() {
self.updateSharedWith();
});
self.temporarilySelectedGroups = ko.observableArray();
self.selectedScenarios = ko.observableArray();
self.temporarilySelectedScenarios = ko.observableArray();
self.isLayerModel = ko.observable(false);
self.attributes = ko.observable([]);
self.scenarioAttributes = ko.observable(options.attributes ? options.attributes.attributes : []);
self.showingLayerAttribution = ko.observable(false);
self.toggleLayerAttribution = function() {
var layerID = '#' + app.viewModel.convertToSlug(self.name);
if ( self.showingLayerAttribution() ) {
self.showingLayerAttribution(false);
$(layerID).css('display', 'none');
} else {
self.showingLayerAttribution(true);
$(layerID).css('display', 'block');
}
//update scrollbar
app.viewModel.updateAggregatedAttributesOverlayScrollbar();
};
//self.overview = self.description || 'no description was provided';
self.constructInfoText = function() {
var attrs = self.scenarioAttributes(),
output = '';
if (attrs){
for (var i=0; i< attrs.length; i++) {
output += attrs[i].title + ': ' + attrs[i].data + '\n';
}
}
return output;
};
self.overview = self.constructInfoText();
self.scenarioReportValues = options.attributes ? options.attributes.report_values : [];
self.features = options.features;
self.active = ko.observable(false);
self.visible = ko.observable(false);
self.defaultOpacity = options.opacity || 0.8;
self.opacity = ko.observable(self.defaultOpacity);
self.type = 'Vector';
self.opacity.subscribe( function(newOpacity) {
if ( self.hasOwnProperty('layer') ) {
self.layer.styleMap.styles['default'].defaultStyle.strokeOpacity = newOpacity;
self.layer.styleMap.styles['default'].defaultStyle.fillOpacity = newOpacity;
self.layer.redraw();
}
});
self.toggleActive = function(self, event) {
var scenario = this;
// start saving restore state again and remove restore state message from map view
app.saveStateMode = true;
app.viewModel.error(null);
//app.viewModel.unloadedDesigns = [];
//app.viewModel.activeLayer(layer);
if (scenario.active()) { // if layer is active, then deactivate
scenario.deactivateLayer();
} else { // otherwise layer is not currently active, so activate
scenario.activateLayer();
//app.viewModel.scenarios.addScenarioToMap(scenario);
}
};
self.activateLayer = function() {
var scenario = this;
app.viewModel.scenarios.addScenarioToMap(scenario);
};
self.deactivateLayer = function() {
var scenario = this;
scenario.active(false);
scenario.visible(false);
scenario.opacity(scenario.defaultOpacity);
app.setLayerVisibility(scenario, false);
app.viewModel.activeLayers.remove(scenario);
app.viewModel.removeFromAggregatedAttributes(scenario.name);
};
self.editScenario = function() {
var scenario = this;
return $.ajax({
url: '/features/scenario/' + scenario.uid + '/form/',
success: function(data) {
app.viewModel.scenarios.scenarioForm(true);
$('#'+app.viewModel.currentTocId()+'-scenario-form > div').html(data);
app.viewModel.scenarios.scenarioFormModel = new scenarioFormModel();
var model = app.viewModel.scenarios.scenarioFormModel;
ko.applyBindings(model, document.getElementById(app.viewModel.currentTocId()+'-scenario-form').children[0]);
var parameters = [
'species',
'lifestage',
'mean_fthm',
'hsall_m2',
// 'hsall1_m2',
// 'hsall2_m2',
// 'hsall3_m2',
// 'hsall4_m2',
'hpc_est_m2',
'hpc_klp_m2',
'hpc_rck_m2',
'hpc_sgr_m2',
'sft_sub_m2',
'mix_sub_m2',
'hrd_sub_m2',
'rck_sub_m2',
'cnt_cs',
'cnt_penn'
];
for (var i = 0; i < parameters.length; i++) {
var id = '#id_' + parameters[i];
if ($(id).is(':checked')) {
model.toggleParameter(parameters[i]);
}
}
app.viewModel.scenarios.loadScenariosFromServer();
app.viewModel.scenarios.updateDesignsScrollBar();
window.dispatchEvent(new Event('resize'));
// model.updateFiltersAndLeaseBlocks();
},
error: function (result) {
console.log('error in scenarios.js: editScenario');
}
});
};
self.createCopyScenario = function() {
var scenario = this;
//create a copy of this shape to be owned by the user
$.ajax({
url: '/scenario/copy_design/' + scenario.uid + '/',
type: 'POST',
dataType: 'json',
success: function(data) {
//app.viewModel.scenarios.loadSelectionsFromServer();
app.viewModel.scenarios.addScenarioToMap(null, {uid: data[0].uid});
app.viewModel.scenarios.loadScenariosFromServer();
app.viewModel.scenarios.updateDesignsScrollBar();
},
error: function (result) {
console.log('error in scenarios.js: createCopyScenario');
}
});
};
self.deleteScenario = function() {
var scenario = this;
//first deactivate the layer
scenario.deactivateLayer();
//remove from activeLayers
app.viewModel.activeLayers.remove(scenario);
//remove from app.map
if (scenario.layer) {
app.map.removeLayer(scenario.layer);
}
//remove from scenarioList
app.viewModel.scenarios.scenarioList.remove(scenario);
//update scrollbar
app.viewModel.scenarios.updateDesignsScrollBar();
//remove from server-side db (this should provide error message to the user on fail)
$.ajax({
url: '/scenario/delete_design/' + scenario.uid + '/',
type: 'POST',
success: function(result){
app.viewModel.scenarios.loadScenariosFromServer();
app.viewModel.scenarios.loadCollectionsFromServer();
},
error: function(result) {
console.log('error in scenarios.js: deleteScenario');
}
});
};
self.visible = ko.observable(false);
// bound to click handler for layer visibility switching in Active panel
self.toggleVisible = function() {
var scenario = this;
if (scenario.visible()) { //make invisible
scenario.visible(false);
app.setLayerVisibility(scenario, false);
app.viewModel.removeFromAggregatedAttributes(scenario.name);
} else { //make visible
scenario.visible(true);
app.setLayerVisibility(scenario, true);
}
};
// is description active
self.infoActive = ko.observable(false);
app.viewModel.showOverview.subscribe( function() {
if ( app.viewModel.showOverview() === false ) {
self.infoActive(false);
} else {
console.log('show overview');
app.viewModel.scenarios.getAttributes(self.uid);
}
});
// display descriptive text below the map
self.toggleDescription = function(scenario) {
if ( ! scenario.infoActive() ) {
self.showDescription(scenario);
} else {
self.hideDescription(scenario);
}
};
self.showDescription = function(scenario) {
app.viewModel.showOverview(false);
app.viewModel.activeInfoSublayer(false);
app.viewModel.activeInfoLayer(scenario);
self.infoActive(true);
$('#overview-overlay').height(186);
app.viewModel.showOverview(true);
app.viewModel.updateCustomScrollbar('#overview-overlay-text');
// app.viewModel.hideMapAttribution();
app.viewModel.closeAttribution();
};
self.hideDescription = function(scenario) {
app.viewModel.showOverview(false);
app.viewModel.activeInfoSublayer(false);
app.viewModel.showMapAttribution();
};
return self;
} // end scenarioModel
/*
--Scenarios Model
-- This model manages a vast majority of the 'designs' tab.
-- These functions are for manipulating scenarios, drawings, and collections.
-- This is where a good share of the business logic for related modals is
-- contained as well.
-- This may have also been a bad design decision trying to treat collections
-- with the name 'sceanarios' even though there's a viewModel for collections
-- already in drawings.js.
*/
function scenariosModel(options) {
var self = this;
self.scenarioList = ko.observableArray();
self.scenarioForm = ko.observable(false);
self.drawingCollections = [];
self.drawingListCollections = ko.observableArray([]);
self.drawingList = ko.observableArray();
self.drawingForm = ko.observable(false);
self.drawingsExist = ko.observable();
self.collectionList = ko.observableArray();
self.collectionForm = ko.observable(false);
self.reportsVisible = ko.observable(false);
self.leaseblockLayer = ko.observable(false);
self.leaseblockLayer.subscribe( function() {
app.viewModel.updateAttributeLayers();
});
self.scenarioLeaseBlocksLayerName = 'Selected OCS Blocks';
// loading message for showing spinner
// false for normal operation
self.loadingMessage = ko.observable(false);
self.errorMessage = ko.observable(false);
self.sharingGroups = ko.observableArray();
self.hasSharingGroups = ko.observable(false);
self.sharingLayer = ko.observable();
self.showSharingModal = function(scenario) {
self.sharingLayer(scenario);
self.sharingLayer().temporarilySelectedGroups(self.sharingLayer().selectedGroups().slice(0));
$('#share-modal').modal('show');
};
self.groupMembers = function(groupName) {
var memberList = "";
for (var i=0; i<self.sharingGroups().length; i++) {
var group = self.sharingGroups()[i];
if (group.group_name === groupName) {
for (var m=0; m<group.members.length; m++) {
var member = group.members[m];
memberList += member + '<br>';
}
}
}
return memberList;
};
self.toggleGroup = function(obj) {
var groupName = obj.group_name,
indexOf = self.sharingLayer().temporarilySelectedGroups.indexOf(groupName);
if ( indexOf === -1 ) { //add group to list
self.sharingLayer().temporarilySelectedGroups.push(groupName);
} else { //remove group from list
self.sharingLayer().temporarilySelectedGroups.splice(indexOf, 1);
}
};
self.initSharingModal = function() {
for (var i=0; i<self.sharingGroups().length; i++) {
var groupID = '#' + self.sharingGroups()[i].group_slug;
$(groupID).collapse( { toggle: false } );
}
};
//TODO: Fix the problem in which the first group toggled open will not toggle open again, once it's closed
self.lastMembersClickTime = 0;
self.toggleGroupMembers = function(obj, e) {
var groupName = obj.group_name,
groupID = '#' + obj.group_slug,
clickTime = new Date().getTime();
if (clickTime - self.lastMembersClickTime > 800) {
self.lastMembersClickTime = clickTime;
if ( ! $(groupID).hasClass('in') ) { //toggle on and add group to list
$(groupID).css("display", "none"); //allows the fade effect to display as expected
if ( $.browser.msie ) {
$(groupID).fadeIn(0, function() {});
} else {
$(groupID).fadeIn('slow', function() {});
}
$(groupID).collapse('show');
} else { //toggle off and remove group from list
if ( $.browser.msie ) {
$(groupID).fadeOut(0, function() {});
} else {
$(groupID).fadeOut('slow', function() {});
}
$(groupID).collapse('hide');
//set .modal-body background to eliminate residue that appears when the last Group is opened and then closed?
}
setTimeout(function() { self.updateSharingScrollBar(groupID); }, 300);
}
};
self.groupIsSelected = function(groupName) {
if (self.sharingLayer()) {
var indexOf = self.sharingLayer().temporarilySelectedGroups.indexOf(groupName);
return indexOf !== -1;
}
return false;
};
self.hasAssociatedScenarios = ko.observable(false);
self.associatedDrawing = ko.observable();
self.showAssociationModal = function(drawing){
self.associatedDrawing(drawing);
self.associatedDrawing().temporarilySelectedScenarios(self.associatedDrawing().selectedScenarios().slice(0));
$('#draw-scenario-associate-modal').modal('show');
};
self.toggleScenario = function(obj) {
var scenarioId = obj.uid;
if (self.associatedDrawing()) {
var indexOf = self.associatedDrawing().temporarilySelectedScenarios.indexOf(scenarioId);
} else {
var indexOf = -1;
}
if ( indexOf === -1 ) { //add group to list
self.associatedDrawing().temporarilySelectedScenarios.push(scenarioId);
} else { //remove group from list
self.associatedDrawing().temporarilySelectedScenarios.splice(indexOf, 1);
}
}
self.scenarioIsSelected = function(scenarioId) {
if(self.associatedDrawing()) {
var indexOf = self.associatedDrawing().temporarilySelectedScenarios.indexOf(scenarioId);
return indexOf !== -1;
}
return false;
}
self.showImportRequirementsModal = function(){
$('#import-guidelines-modal').modal('show');
};
self.comparisonCollection = ko.observable();
self.showComparisonModal = function(collection){
self.comparisonCollection(collection);
self.comparisonCollection().temporarilySelectedScenarios(self.comparisonCollection().selectedScenarios().slice(0));
$('#collection-compare-modal').modal('show');
};
self.toggleCompareScenario = function(obj) {
var scenarioId = obj.uid;
if (self.comparisonCollection()) {
var indexOf = self.comparisonCollection().temporarilySelectedScenarios.indexOf(scenarioId);
} else {
var indexOf = -1;
}
if ( indexOf === -1 ) { //add group to list
self.comparisonCollection().temporarilySelectedScenarios.push(scenarioId);
} else { //remove group from list
self.comparisonCollection().temporarilySelectedScenarios.splice(indexOf, 1);
}
}
self.obsArrayValue = function(obsarray) {
return JSON.parse(ko.toJSON(obsarray));
}
self.compareScenarioIsSelected = function(scenarioId) {
if(self.comparisonCollection()) {
var indexOf = self.comparisonCollection().temporarilySelectedScenarios.indexOf(scenarioId);
return indexOf !== -1;
}
return false;
}
/*
Populate Scenario Comparison Report Modal
*/
self.originalComparisonReport = ko.observableArray();
self.comparisonReport = ko.observableArray();
self.comparisonReportCollections = ko.observableArray();
self.comparisonReportValues = ko.observableArray();
self.comparisonDownloadLink = ko.observable();
self.showComparisonReportModal = function(array,data,download_link) {
self.comparisonReportCollections(Object.getOwnPropertyNames(data));
self.comparisonReportValues(array);
self.comparisonDownloadLink(download_link);
var data_array = [];
for (var i=0; i < self.comparisonReportValues().length; i++) {
var key = self.comparisonReportValues()[i];
var row = [key];
for (var j=0; j < self.comparisonReportCollections().length; j++) {
collection_name = self.comparisonReportCollections()[j];
collection_object = data[collection_name]
row.push(collection_object[key]);
}
data_array.push(row);
}
self.originalComparisonReport(data_array);
self.comparisonReport(self.obsArrayValue(self.originalComparisonReport));
$('#compare-report-modal').modal('show');
};
self.setComparisonReportBaseline = function(baselineIndex) {
if (baselineIndex == 0) {
self.comparisonReport([]);
self.comparisonReport(self.obsArrayValue(self.originalComparisonReport));
} else {
reportValues = self.obsArrayValue(self.originalComparisonReport);
//Loop through fields
for(var i=0; i < reportValues.length; i++) {
if (
typeof(reportValues[i][1]) == 'object' &&
reportValues[i][1] != null &&
reportValues[i][1].hasOwnProperty('values') &&
reportValues[i][1].hasOwnProperty('text') &&
typeof(reportValues[i][1]['text']) == 'object'
){
//for values in each field (discluding field name at 0)
for (var j=1; j<reportValues[i].length; j++) {
blValues = reportValues[i][baselineIndex]['values'];
//change non-baseline displayed values
if (j!=baselineIndex){
for (k=0; k < reportValues[i][j]['values'].length; k++){
old_val = reportValues[i][j]['values'][k];
//Determine type of values: int or float
if (old_val%1 == 0) {
//calculate difference (absolute for now, maybe % later)
diff_val = parseInt(old_val) - parseInt(blValues[k]);
} else{
diff_val = parseFloat(old_val) - parseFloat(blValues[k])
// reportValues[i][j]['values'][k] = ().toString();
}
if (diff_val > 0) {
diff_val = "+" + diff_val.toString();
} else {
diff_val = diff_val.toString();
}
reportValues[i][j]['values'][k] = diff_val;
//assemble new label - assumes text & values will alternate
if (reportValues[i][j]['values'].length >= reportValues[i][j]['text'].length) {
big_list = reportValues[i][j]['values'];
small_list = reportValues[i][j]['text'];
} else {
big_list = reportValues[i][j]['text'];
small_list = reportValues[i][j]['values'];
}
label_list = []
for (l = 0; l < big_list.length; l++){
label_list.push(big_list[l]);
if (l < small_list.length){
label_list.push(small_list[l]);
}
}
reportValues[i][j]['label'] = label_list.join(' ');
}
}
}
}
}
self.comparisonReport([]);
self.comparisonReport(reportValues);
}
};
self.zoomToScenario = function(scenario) {
if (scenario.layer) {
var layer = scenario.layer;
if (!scenario.active()) {
scenario.activateLayer();
}
app.map.zoomToExtent(layer.getDataExtent());
if (scenario.uid.indexOf('drawing') !== -1) {
app.map.zoomOut();
app.map.zoomOut();
}
} else {
self.addScenarioToMap(scenario, {zoomTo: true});
}
};
self.updateSharingScrollBar = function(groupID) {
var sharingScrollpane = $('#sharing-groups').data('jsp');
if (sharingScrollpane === undefined) {
$('#sharing-groups').jScrollPane( {animateScroll: true});
} else {
sharingScrollpane.reinitialise();
var groupPosition = $(groupID).position().top,
containerPosition = $('#sharing-groups .jspPane').position().top,
actualPosition = groupPosition + containerPosition;
//console.log('group position = ' + groupPosition);
//console.log('container position = ' + containerPosition);
//console.log('actual position = ' + actualPosition);
if (actualPosition > 140) {
//console.log('scroll to ' + (groupPosition-120));
sharingScrollpane.scrollToY(groupPosition-120);
}
}
};
// scenariosLoaded will be set to true after they have been loaded
self.scenariosLoaded = false;
self.isScenariosOpen = ko.observable(false);
self.toggleScenariosOpen = function(force) {
// ensure designs tab is activated
if (force.hasOwnProperty('tocid')){
$('#'+force.tocid+'-designsTab').tab('show');
}
if (force === 'open') {
self.isScenariosOpen(true);
} else if (force === 'close') {
self.isScenariosOpen(false);
} else {
if ( self.isScenariosOpen() ) {
self.isScenariosOpen(false);
} else {
self.isScenariosOpen(true);
}
}
self.updateDesignsScrollBar();
};
self.isCollectionsOpen = ko.observable(false);
self.toggleCollectionsOpen = function(force) {
// ensure designs tab is activated
if (force.hasOwnProperty('tocid')){
$('#'+force.tocid+'-designsTab').tab('show');
}
if (force === 'open') {
self.isCollectionsOpen(true);
} else if (force === 'close') {
self.isCollectionsOpen(false);
} else {
if ( self.isCollectionsOpen() ) {
self.isCollectionsOpen(false);
} else {
self.isCollectionsOpen(true);
}
}
self.updateDesignsScrollBar();
};
self.isDrawingsOpen = ko.observable(false);
self.toggleDrawingsOpen = function(force) {
// ensure designs tab is activated
if (force.hasOwnProperty('tocid')){
$('#'+force.tocid+'-designsTab').tab('show');
}
if (force === 'open') {
self.isDrawingsOpen(true);
} else if (force === 'close') {
self.isDrawingsOpen(false);
} else {
if ( self.isDrawingsOpen() ) {
self.isDrawingsOpen(false);
} else {
self.isDrawingsOpen(true);
}
}
self.updateDesignsScrollBar();
};
self.updateDesignsScrollBar = function() {
var designsScrollpane = $('#'+app.viewModel.currentTocId()+'-designs-accordion').data('jsp');
if (designsScrollpane === undefined) {
$('#'+app.viewModel.currentTocId()+'-designs-accordion').jScrollPane();
} else {
designsScrollpane.reinitialise();
}
};
//restores state of Designs tab to the initial list of designs
self.reset = function (obj) {
self.loadingMessage(false);
self.errorMessage(false);
//clean up scenario form
if (self.scenarioForm() || self.scenarioFormModel) {
app.map.removeLayer(self.scenarioFormModel.updatedFilterResultsLayer);
self.removeScenarioForm();
}
//clean up drawing form
if (self.drawingForm() || self.drawingFormModel) {
self.removeDrawingForm(obj);
}
//clear up collection form
if (self.collectionForm() || self.collectionFormModel) {
self.removeCollectionForm();
}
//remove the key/value pair from aggregatedAttributes
app.viewModel.removeFromAggregatedAttributes(self.leaseblockLayer().name);
app.viewModel.updateAttributeLayers();
self.updateDesignsScrollBar();
};
self.removeDrawingForm = function(obj) {
self.drawingFormModel.cleanUp();
self.drawingForm(false);
var drawingForm = document.getElementById(app.viewModel.currentTocId()+'-drawing-form').children[0];
$(drawingForm).empty();
ko.cleanNode(drawingForm);
//in case of canceled edit
if ( obj && obj.cancel && self.drawingFormModel.originalDrawing ) {
self.drawingFormModel.originalDrawing.deactivateLayer();
self.drawingFormModel.originalDrawing.activateLayer();
}
delete self.drawingFormModel;
};
self.removeScenarioForm = function() {
self.scenarioForm(false);
var scenarioForm = document.getElementById(app.viewModel.currentTocId()+'-scenario-form').children[0];
$(scenarioForm).empty();
ko.cleanNode(scenarioForm);
delete self.scenarioFormModel;
//hide remaining leaseblocks
if ( self.leaseblockLayer() && app.map.getLayersByName(self.leaseblockLayer().name).length ) {
app.map.removeLayer(self.leaseblockLayer());
}
};
self.removeCollectionForm = function() {
self.collectionForm(false);
var collectionForm = document.getElementById(app.viewModel.currentTocId()+'-scenario-collection-form').children[0];
$(collectionForm).empty();
ko.cleanNode(collectionForm);
delete self.collectionFormModel;
//hide remaining leaseblocks
// if ( self.leaseblockLayer() && app.map.getLayersByName(self.leaseblockLayer().name).length ) {
// app.map.removeLayer(self.leaseblockLayer());
// }
};
self.createWindScenario = function() {
//hide designs tab by sliding left
return $.ajax({
url: '/features/scenario/form/',
success: function(data) {
// data = data.replace('http://openlayers.org/api/2.13/OpenLayers.js',"/media/assets/openlayers/OpenLayers-mp-min.js");
data = data.replace('<script type="text/javascript" src="http://openlayers.org/api/2.13/OpenLayers.js"></script>',"");
self.scenarioForm(true);
$('#'+app.viewModel.currentTocId()+'-scenario-form > .scenario-form').html(data);
self.scenarioFormModel = new scenarioFormModel();
ko.applyBindings(self.scenarioFormModel, document.getElementById(app.viewModel.currentTocId()+'-scenario-form').children[0]);
self.scenarioFormModel.updateDesignScrollBar();
if ( ! self.leaseblockLayer() && app.viewModel.modernBrowser() ) {
self.loadLeaseblockLayer();
}
window.dispatchEvent(new Event('resize'));
},
error: function (result) {
console.log('failure at scenarios.js line 1031.');
}
});
};
self.createPolygonDesign = function() {
return $.ajax({
url: '/features/aoi/form/',
success: function(data) {
app.viewModel.scenarios.drawingForm(true);
$('#'+app.viewModel.currentTocId()+'-drawing-form > .drawing-form').html(data);
app.viewModel.scenarios.drawingFormModel = new polygonFormModel();
ko.applyBindings(app.viewModel.scenarios.drawingFormModel, document.getElementById(app.viewModel.currentTocId()+'-drawing-form').children[0]);
window.dispatchEvent(new Event('resize'));
},
error: function (result) {
console.log('error in scenarios.js: createPolygonDesign');
}
});
};
self.createCollectionScenario = function() {
return $.ajax({
url: '/features/collection/form/',
success: function(data) {
app.viewModel.scenarios.collectionForm(true);
$('#'+app.viewModel.currentTocId()+'-scenario-collection-form > .scenario-collection-form').html(data);
app.viewModel.scenarios.collectionFormModel = new collectionFormModel();
ko.applyBindings(app.viewModel.scenarios.collectionFormModel, document.getElementById(app.viewModel.currentTocId()+'-scenario-collection-form').children[0]);
window.dispatchEvent(new Event('resize'));
},
error: function (result) {
console.log('error in scenarios.js: createCollectionScenario');
}
});
};
self.createLineDesign = function() {};
self.createPointDesign = function() {};
//
self.addScenarioToMap = function(scenario, options) {
var scenarioId,
opacity = .8,
stroke = 1,
fillColor = "#00A29B",
strokeColor = "#00827B",
zoomTo = (options && options.zoomTo) || false;
if ( scenario ) {
scenarioId = scenario.uid;
scenario.active(true);
scenario.visible(true);
} else {
scenarioId = options.uid;
}
var isDrawingModel = false,
isScenarioModel = false;
if (scenarioId.indexOf('drawing') !== -1) {
isDrawingModel = true;
} else {
isScenarioModel = true;
}
$('#loading-modal').modal('show');
//perhaps much of this is not necessary once a scenario has been added to app.map.layers initially...?
//(add check for scenario.layer, reset the style and move on?)
$.ajax( {
url: '/features/generic-links/links/geojson/' + scenarioId + '/',
type: 'GET',
dataType: 'json',
success: function(retFeatures) {
if ( scenario ) {
var opacity = scenario.opacity();
var stroke = scenario.opacity();
if (retFeatures.features.length > 0 && retFeatures.features[0].properties.hasOwnProperty('collection')) {
display_name = "[" + retFeatures.features[0].properties.collection.name +"] " + scenario.name;
} else {
display_name = scenario.name;
}
scenario.display_name = display_name;
}
if ( isDrawingModel ) {
for (var featIndex = 0; featIndex < retFeatures.features.length; featIndex++){
featureId = retFeatures.features[featIndex].properties.uid;
$.ajax( {
url: '/drawing/get_geometry_orig/' + featureId + '/',
type: 'GET',
dataType: 'json',
success: function(data) {
var format = new OpenLayers.Format.WKT(),
wkt = data.geometry_orig,
feature = format.read(wkt);
scenario.geometry_orig = feature;
},
error: function(result) {
console.log('error in scenarios.js: addScenarioToMap (get_geometry_orig featureId)');
}
});
}
if (scenario && scenario.id.indexOf('collection') < 0){
style = new OpenLayers.Style(
{
fillOpacity: scenario.opacity(),
strokeOpacity: scenario.opacity(),
fillColor: "#C9BE62",
strokeColor: "#A99E42"
}
);
} else {
var style = new OpenLayers.Style(
{
fillOpacity: opacity,
strokeOpacity: stroke
},
{
rules:[
new OpenLayers.Rule({
filter: new OpenLayers.Filter.Comparison({
type: OpenLayers.Filter.Comparison.EQUAL_TO,
property: "reg_action",
value: "close"
}),
symbolizer:{
fillColor: "#FF5555",
strokeColor: "#DF3535"
}
}),
new OpenLayers.Rule({
filter: new OpenLayers.Filter.Comparison({
type: OpenLayers.Filter.Comparison.EQUAL_TO,
property: "reg_action",
value: "Close"
}),
symbolizer:{
fillColor: "#FF5555",
strokeColor: "#DF3535"
}
}),
new OpenLayers.Rule({
filter: new OpenLayers.Filter.Comparison({
type: OpenLayers.Filter.Comparison.EQUAL_TO,
property: "reg_action",
value: "reopen"
}),
symbolizer:{
fillColor: "#55FF55",
strokeColor: "#35DF35"
}
}),
new OpenLayers.Rule({
filter: new OpenLayers.Filter.Comparison({
type: OpenLayers.Filter.Comparison.EQUAL_TO,
property: "reg_action",
value: "Reopen"
}),
symbolizer:{
fillColor: "#55FF55",
strokeColor: "#35DF35"
}
}),
new OpenLayers.Rule({
// apply this rule if no others apply
elseFilter: true,
symbolizer: {
fillColor: "#C9BE62",
strokeColor: "#A99E42"
}
})
]
}
);
}
}
var layer = new OpenLayers.Layer.Vector(
scenarioId,
{
projection: new OpenLayers.Projection('EPSG:3857'),
displayInLayerSwitcher: false,
styleMap: new OpenLayers.StyleMap(style),
scenarioModel: scenario
}
);
layer.addFeatures(new OpenLayers.Format.GeoJSON().read(retFeatures));
if ( scenario ) {
//reasigning opacity here, as opacity wasn't 'catching' on state load for scenarios
scenario.opacity(opacity);
scenario.layer = layer;
} else { //create new scenario
//only do the following if creating a scenario
if (retFeatures.features.length > 0){
var properties = retFeatures.features[0].properties;
if (properties.hasOwnProperty('collection')){
display_name = "[" + properties.collection.name + "] " + properties.name;
} else {
display_name = properties.name;
}
if (isDrawingModel) {
scenario = new drawingModel({
id: properties.uid,
uid: properties.uid,
name: properties.name,
display_name: display_name?display_name:properties.name,
description: properties.description,
features: layer.features
});
self.toggleDrawingsOpen('open');
self.zoomToScenario(scenario);
} else if (isScenarioModel) {
scenario = new scenarioModel({
id: properties.uid,
uid: properties.uid,
name: properties.name,
display_name: properties.display_name?properties.display_name:properties.name,
description: properties.description,
features: layer.features
});
self.toggleScenariosOpen('open');
self.zoomToScenario(scenario);
} else if (isCollectionModel) {
scenario = new collectionModel({
id: properties.uid,
uid: properties.uid,
name: properties.name,
display_name: properties.display_name?properties.display_name:properties.name,
description: properties.description,
features: layer.features
});
self.toggleCollectionsOpen('open');
self.zoomToScenario(scenario);
}
scenario.layer = layer;
scenario.layer.scenarioModel = scenario;
scenario.active(true);
scenario.visible(true);
}
$.ajax( {
url: '/drawing/get_attributes/' + scenarioId + '/',
type: 'GET',
dataType: 'json',
success: function(result) {
if (scenario) {
//TODO: figure out when and why this wouldn't have a scenario (on creating empty collection)
// and adjust if necessary
scenario.scenarioAttributes(result.attributes);
}
$('#loading-modal').modal('hide');
},
error: function (result) {
$('#loading-modal').modal('hide');
console.log('error in scenarios.js: addScenarioToMap (get_attributes scenarioId)');
}
});
//in case of edit, removes previously stored scenario
//self.scenarioList.remove(function(item) { return item.uid === scenario.uid } );
if (scenario) {
if ( isDrawingModel ) {
var previousDrawing = ko.utils.arrayFirst(self.drawingList(), function(oldDrawing) {
return oldDrawing.uid === scenario.uid;
});
if ( previousDrawing ) {
self.drawingList.replace( previousDrawing, scenario );
} else {
self.drawingList.push(scenario);
}
self.drawingList.sort(self.alphabetizeByName);
} else {
var previousScenario = ko.utils.arrayFirst(self.scenarioList(), function(oldScenario) {
return oldScenario.uid === scenario.uid;
});
if ( previousScenario ) {
self.scenarioList.replace( previousScenario, scenario );
} else {
self.scenarioList.push(scenario);
}
self.scenarioList.sort(self.alphabetizeByName);
}
}
//self.scenarioForm(false);
self.reset();
}
if (scenario) {
//app.addVectorAttribution(layer);
//in case of edit, removes previously displayed scenario
for (var i=0; i<app.map.layers.length; i++) {
if (app.map.layers[i].name === scenario.uid) {
app.map.removeLayer(app.map.layers[i]);
i--;
}
}
app.map.addLayer(scenario.layer);
//add scenario to Active tab
app.viewModel.activeLayers.remove(function(item) { return item.uid === scenario.uid; } );
app.viewModel.activeLayers.unshift(scenario);
if (zoomTo) {
self.zoomToScenario(scenario);
}
}
$('#loading-modal').modal('hide');
},
error: function(result) {
console.log('error in scenarios.js: addScenarioToMap (geojson scenarioId)');
app.viewModel.scenarios.errorMessage(result.responseText.split('\n\n')[0]);
$('#loading-modal').modal('hide');
}
});
}; // end addScenarioToMap
self.alphabetizeByName = function(a, b) {
var name1 = a.display_name.toLowerCase()?a.display_name:a.name.toLowerCase(),
name2 = b.display_name.toLowerCase()?b.display_name:b.name.toLowerCase();
if (name1 < name2) {
return -1;
} else if (name1 > name2) {
return 1;
}
return 0;
};
// activate any lingering designs not shown during loadCompressedState
self.showUnloadedDesigns = function() {
var designs = app.viewModel.unloadedDesigns;
if (designs && designs.length) {
//the following delay might help solve what appears to be a race condition
//that prevents the design in the layer list from displaying the checked box icon after loadin
setTimeout( function() {
for (var x=0; x < designs.length; x=x+1) {
var id = designs[x].id,
opacity = designs[x].opacity,
isVisible = designs[x].isVisible;
if (app.viewModel.layerIndex[id]) {
app.viewModel.layerIndex[id].opacity(opacity);
app.viewModel.layerIndex[id].activateLayer();
for (var i=0; i < app.viewModel.unloadedDesigns.length; i=i+1) {
if(app.viewModel.unloadedDesigns[i].id === id) {
app.viewModel.unloadedDesigns.splice(i,1);
i = i-1;
}
}
}
}
}, 400);
}
};
self.loadScenariosFromServer = function() {
$.ajax({
url: '/scenario/get_scenarios',
type: 'GET',
dataType: 'json',
success: function (scenarios) {
self.loadScenarios(scenarios);
self.scenariosLoaded = true;
self.showUnloadedDesigns();
app.viewModel.scenarios.updateDesignsScrollBar();
},
error: function (result) {
}
});
};
//populates scenarioList
self.loadScenarios = function (scenarios) {
self.scenarioList.removeAll();
$.each(scenarios, function (i, scenario) {
var scenarioViewModel = new scenarioModel({
id: scenario.uid,
uid: scenario.uid,
name: scenario.name,
display_name: scenario.display_name?scenario.display_name:scenario.name,
description: scenario.description,
attributes: scenario.attributes,
shared: scenario.shared,
sharedByUsername: scenario.shared_by_username,
sharedByName: scenario.shared_by_name,
sharingGroups: scenario.sharing_groups
});
self.scenarioList.push(scenarioViewModel);
app.viewModel.layerIndex[scenario.uid] = scenarioViewModel;
// self.getAttributes(scenario.uid);
});
self.scenarioList.sort(self.alphabetizeByName);
};
self.loadDrawingsFromServer = function() {
$.ajax({
url: '/drawing/get_drawings',
type: 'GET',
dataType: 'json',
success: function (drawings) {
self.loadDrawings(drawings);
self.drawingsLoaded = true;
self.showUnloadedDesigns();
app.viewModel.scenarios.updateDesignsScrollBar();
},
error: function (result) {
console.log('error in scenarios.js: loadDrawingsFromServer');
}
});
};
//populates drawingList
self.loadDrawings = function (drawings) {
self.drawingList.removeAll();
self.drawingListCollections.removeAll();
self.drawingCollections = [];
$.each(drawings, function (i, drawing) {
var drawingCollection = self.drawingInCollection(drawing);
var drawingViewModel = new drawingModel({
id: drawing.uid,
uid: drawing.uid,
name: drawing.name,
display_name: drawing.display_name?drawing.display_name:drawing.name,
collection: drawingCollection,
description: drawing.description,
attributes: drawing.attributes,
shared: drawing.shared,
sharedByUsername: drawing.shared_by_username,
sharedByName: drawing.shared_by_name,
sharingGroups: drawing.sharing_groups,
});
self.findDrawingCollections(i, drawingViewModel, drawingCollection);
app.viewModel.layerIndex[drawing.uid] = drawingViewModel;
// self.getAttributes(drawing.uid);
});
self.loadDrawingsCollections();
self.drawingList.sort(self.alphabetizeByName);
};
self.drawingInCollection = function(drawing) {
var displayName = drawing.display_name;
if (displayName.indexOf('[') > -1) {
var firstIndex = displayName.indexOf('[') + 1;
return displayName.substring( firstIndex, displayName.indexOf(']') );
} else {
return false;
}
}
// accordian for collections in drawings menu
self.findDrawingCollections = function(i, drawing, collect) {
// If drawing is not associated with a collection, add it to general list
if (!collect) {
self.drawingList.push(drawing);
} else {
var newCollection = true;
if (i === 0) {
self.pushNewCollection(collect);
}
self.drawingCollections.forEach(function(e) {
if (e.collection.name === collect) {
newCollection = false;
e.collection.drawings.push(drawing);
}
});
if (newCollection) {
self.pushNewCollection(collect);
self.drawingCollections.forEach(function(e) {
if (e.collection.name === collect) {
e.collection.drawings.push(drawing);
}
});
}
}
}
self.pushNewCollection = function(collection) {
self.drawingCollections.push({
collection: {
name: collection,
isActive: ko.observable(false), // set to toggle
drawings: []
}
});
}
self.collectionToggleActive = function(data, event) {
data.collection.isActive(!data.collection.isActive()); //toggle the isActive value between true/false
self.updateDesignsScrollBar();
}
self.loadDrawingsCollections = function() {
self.drawingCollections.forEach(function(e) {
self.drawingListCollections.push(e);
});
}
self.loadCollectionsFromServer = function() {
$.ajax({
url: '/drawing/get_collections',
type: 'GET',
dataType: 'json',
success: function (collections) {
self.loadCollections(collections);
self.collectionsLoaded = true;
self.showUnloadedDesigns();
app.viewModel.scenarios.updateDesignsScrollBar();
},
error: function (result) {
console.log('error in scenarios.js: loadCollectionsFromServer');
}
});
};
self.loadCollections = function(collections) {
self.collectionList.removeAll();
$.each(collections, function (i, collection) {
var collectionViewModel = new collectionModel({
id: collection.uid,
uid: collection.uid,
name: collection.name,
display_name: collection.display_name?collection.display_name:collection.name,
description: collection.description,
attributes: collection.attributes,
shared: collection.shared,
sharedByUsername: collection.shared_by_username,
sharedByName: collection.shared_by_name,
sharingGroups: collection.sharing_groups
});
self.collectionList.push(collectionViewModel);
app.viewModel.layerIndex[collection.uid] = collectionViewModel;
// self.getAttributes(collection.uid);
});
self.collectionList.sort(self.alphabetizeByName);
app.viewModel.scenarios.loadDrawingsFromServer();
app.viewModel.scenarios.updateDesignsScrollBar();
};
self.aggregateTranslate = function(inObjList) {
var outObjList = [];
for (var i=0; i < inObjList.length; i++) {
var inObj = inObjList[i];
var outObj = {};
outObj['data'] = inObj['data'];
outObj['display'] = inObj['title'];
outObjList.push(outObj);
}
return outObjList;
};
self.getAttributes = function(uid) {
if (uid != null) {
$.ajax({
url: '/drawing/get_attributes/' + uid,
type: 'GET',
dataType: 'json',
success: function(data){
if (app.viewModel.layerIndex.hasOwnProperty(uid)) {
if ( app.viewModel.layerIndex[uid].hasOwnProperty('attributes')){
app.viewModel.layerIndex[uid].attributes(data);
}
app.viewModel.layerIndex[uid].scenarioAttributes(data.attributes);
var activeLayer = app.viewModel.activeLayers().find(function(obj){return obj.uid == uid;})
if (activeLayer) {
activeLayer.attributes(data);
}
if (data.attributes.filter(function(obj){return obj.hasOwnProperty('Status');}).length > 0){
console.log('data not yet loaded. Retrying...');
setTimeout(app.viewModel.scenarios.getAttributes(uid), 5000);
} else {
if (app.viewModel.layerIndex[uid].showingLayerAttribution()){
var aggAttrs = {};
aggAttrs[app.viewModel.layerIndex[uid].name] = self.aggregateTranslate(data.attributes);
app.viewModel.aggregatedAttributes(aggAttrs);
}
}
}
},
error: function(response){
console.log('error in scenarios.js: getAttributes');
}
});
}
};
self.loadLeaseblockLayer = function() {
//console.log('loading lease block layer');
var leaseBlockLayer = new OpenLayers.Layer.Vector(
self.scenarioLeaseBlocksLayerName,
{
projection: new OpenLayers.Projection('EPSG:3857'),
displayInLayerSwitcher: false,
strategies: [new OpenLayers.Strategy.Fixed()],
protocol: new OpenLayers.Protocol.HTTP({
//url: '/media/data_manager/geojson/LeaseBlockWindSpeedOnlySimplifiedNoDecimal.json',
url: '/media/data_manager/geojson/ofr_planning_grid.json',
format: new OpenLayers.Format.GeoJSON()
}),
//styleMap: new OpenLayers.StyleMap( {
// "default": new OpenLayers.Style( { display: "none" } )
//})
layerModel: new layerModel({
name: self.scenarioLeaseBlocksLayerName
})
}
);
self.leaseblockLayer(leaseBlockLayer);
self.leaseblockLayer().events.register("loadend", self.leaseblockLayer(), function() {
if (self.scenarioFormModel && ! self.scenarioFormModel.IE) {
self.scenarioFormModel.showLeaseblockSpinner(false);
}
});
};
self.leaseblockList = [];
//populates leaseblockList
self.loadLeaseblocks = function (ocsblocks) {
self.leaseblockList = ocsblocks;
};
self.cancelShare = function() {
self.sharingLayer().temporarilySelectedGroups.removeAll();
};
//SHARING DESIGNS
self.submitShare = function() {
self.sharingLayer().selectedGroups(self.sharingLayer().temporarilySelectedGroups().slice(0));
var data = { 'scenario': self.sharingLayer().uid, 'groups': self.sharingLayer().selectedGroups() };
$.ajax( {
url: '/scenario/share_design',
data: data,
type: 'POST',
dataType: 'json',
error: function(result) {
console.log('error in scenarios.js: submitShare');
}
});
};
self.cancelAssociate = function() {
self.associatedDrawing().temporarilySelectedScenarios.removeAll();
};
self.submitAssociate = function() {
self.associatedDrawing().selectedScenarios(self.associatedDrawing().temporarilySelectedScenarios().slice(0));
var data = {
'scenario': self.associatedDrawing().uid,
'collections': self.associatedDrawing().selectedScenarios()
};
$.ajax( {
url: '/scenario/associate_scenario',
data: data,
type: 'POST',
dataType: 'json',
success: function(data) {
for (var data_index = 0; data_index < data.length; data_index++) {
app.viewModel.scenarios.addScenarioToMap(null, {uid: data[data_index].uid});
}
self.associatedDrawing().temporarilySelectedScenarios.removeAll();
app.viewModel.scenarios.loadCollectionsFromServer();
},
error: function(result) {
console.log('error in scenarios.js: submitAssociate');
window.alert(result.responseText);
self.associatedDrawing().temporarilySelectedScenarios.removeAll();
}
});
self.associatedDrawing().temporarilySelectedScenarios.removeAll();
};
self.cancelCompare = function() {
self.comparisonCollection().temporarilySelectedScenarios.removeAll();
};
self.submitCompare = function() {
console.log('submit compare!');
self.comparisonCollection().selectedScenarios(self.comparisonCollection().temporarilySelectedScenarios().slice(0));
var data = {
'scenario': self.comparisonCollection().uid,
'collections': self.comparisonCollection().selectedScenarios()
};
$('#loading-modal').modal('show');
$.ajax( {
url: '/scenario/compare_scenario',
data: data,
type: 'POST',
dataType: 'json',
success: function(data) {
attr_list = data[0];
report_data = data[1];
download_link = data[2];
app.viewModel.scenarios.showComparisonReportModal(attr_list,report_data,download_link);
$('#loading-modal').modal('hide');
},
error: function(result) {
$('#loading-modal').modal('hide');
console.log('error in scenarios.js: submitCompare');
window.alert(result.responseText);
}
});
};
self.setBaseLine = function(col_id, data) {
// Update observable value array with relative comparison values
app.viewModel.scenarios.setComparisonReportBaseline(col_id);
$('td.collection-report-cell').removeClass('active');
if (col_id !== 0) {
column = col_id + 1;
$('td:nth-of-type('+ column + ').collection-report-cell').addClass('active');
}
};
self.loadDesigns = function() {
if ( !self.drawingsLoaded ) {
// load the scenarios
self.loadScenariosFromServer();
// load the drawing
self.loadDrawingsFromServer();
// load the collections
self.loadCollectionsFromServer();
$.ajax({
url: '/scenario/get_sharing_groups',
type: 'GET',
dataType: 'json',
success: function (groups) {
app.viewModel.scenarios.sharingGroups(groups);
if (groups.length) {
app.viewModel.scenarios.hasSharingGroups(true);
}
},
error: function (result) {
console.log('error in scenarios.js: loadDesigns');
}
});
}
}
return self;
} // end scenariosModel
app.viewModel.scenarios = new scenariosModel();
$('.designsTab').on('show', function (e) {
app.viewModel.scenarios.loadDesigns();
});
| Ecotrust/PEW-EFH | media/js/scenarios.js | JavaScript | apache-2.0 | 76,896 |
/*
* Copyright 2016 Red Hat Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
var util = require('util');
var log = require('./log.js').logger();
var myutils = require('./utils.js');
var amqp = require('rhea').create_container();
var Artemis = function (connection) {
this.connection = connection;
this.sender = connection.open_sender('activemq.management');
this.sender.on('sender_open', this.sender_open.bind(this));
this.sender.on('sendable', this._send_pending_requests.bind(this));
connection.on('receiver_open', this.receiver_ready.bind(this));
connection.on('message', this.incoming.bind(this));
connection.on('receiver_error', this.on_receiver_error.bind(this));
connection.on('sender_error', this.on_sender_error.bind(this));
var self = this;
connection.on('connection_open', function (context) {
let previous = self.id;
self.id = context.connection.container_id;
if (previous !== undefined && previous !== self.id) {
log.info('[%s] connection opened (was %s)', self.id, previous);
} else {
log.info('[%s] connection opened', self.id);
}
});
connection.on('connection_error', this.on_connection_error.bind(this));
connection.on('connection_close', this.on_connection_close.bind(this));
connection.on('disconnected', this.disconnected.bind(this));
connection.on('error', this.on_error.bind(this));
this.handlers = [];
this.requests = [];
this.pushed = 0;
this.popped = 0;
};
Artemis.prototype.log_info = function (context) {
if (this.id) {
log.info('[%s] artemis requests pending: %d, made:%d, completed: %d, ready: %d', this.id, this.handlers.length, this.pushed, this.popped, this.address !== undefined);
}
};
Artemis.prototype.sender_open = function () {
var tmp_reply_address = 'activemq.management.tmpreply.' + amqp.generate_uuid();
log.debug('[%s] sender ready, creating reply to address: %s', this.connection.container_id, tmp_reply_address);
this._create_temp_response_queue(tmp_reply_address);
this.connection.open_receiver({source:{address: tmp_reply_address}});
}
Artemis.prototype.receiver_ready = function (context) {
this.address = context.receiver.remote.attach.source.address;
log.info('[%s] ready to send requests, reply to address: %s', this.connection.container_id, this.address);
this._send_pending_requests();
};
function as_handler(resolve, reject) {
return function (context) {
var message = context.message || context;
if (message.application_properties && message.application_properties._AMQ_OperationSucceeded) {
try {
if (message.body) {
resolve(JSON.parse(message.body)[0]);
} else {
resolve(true);
}
} catch (e) {
log.info('[%s] Error parsing message body: %s : %s', this.connection.container_id, message, e);
reject(message.body)
}
} else {
reject(message.body);
}
};
}
Artemis.prototype.incoming = function (context) {
var message = context.message;
log.debug('[%s] recv: %j', this.id || context.connection.container_id, message);
var handler = this.handlers.shift();
if (handler) {
this.popped++;
handler(context);
}
};
Artemis.prototype.disconnected = function (context) {
log.info('[%s] disconnected', this.id || context.connection.container_id);
this.address = undefined;
this.abort_requests('disconnected');
};
Artemis.prototype.abort_requests = function (error) {
while (this.handlers.length > 0) {
var handler = this.handlers.shift();
if (handler) {
this.popped++;
handler(error);
}
}
}
Artemis.prototype.on_sender_error = function (context) {
var error = this.connection.container_id + ' sender error ' + JSON.stringify(context.sender.error);
log.info('[' + this.connection.container_id + '] ' + error);
this.abort_requests(error);
};
Artemis.prototype.on_receiver_error = function (context) {
var error = this.connection.container_id + ' receiver error ' + JSON.stringify(context.receiver.error);
log.info('[' + this.connection.container_id + '] ' + error);
this.abort_requests(error);
};
Artemis.prototype.on_connection_error = function (context) {
var error = this.connection.container_id + ' connection error ' + JSON.stringify(context.connection.error);
log.info('[' + this.connection.container_id + '] connection error: ' + JSON.stringify(context.connection.error));
this.abort_requests(error);
};
Artemis.prototype.on_connection_close = function (context) {
var error = this.connection.container_id + ' connection closed';
log.info('[' + this.connection.container_id + '] connection closed');
this.abort_requests(error);
};
Artemis.prototype.on_error = function (error) {
log.error('[%s] socket error: %s', this.connection.container_id, JSON.stringify(error));
};
Artemis.prototype._send_pending_requests = function () {
if (this.address === undefined) return false;
var i = 0;
while (i < this.requests.length && this.sender.sendable()) {
this._send_request(this.requests[i++]);
}
this.requests.splice(0, i);
return this.requests.length === 0 && this.sender.sendable();
}
Artemis.prototype._send_request = function (request) {
request.application_properties.JMSReplyTo = this.address;
request.reply_to = this.address;
if (process.env.AGENT_CORRELATE_MGMT === 'true') {
// Aids debug, has no functional effect
request.correlation_id = amqp.generate_uuid();
}
this.sender.send(request);
log.debug('[%s] sent: %j', this.id, request);
}
Artemis.prototype._create_request_message = function(resource, operation, parameters) {
var request = {application_properties: {'_AMQ_ResourceName': resource, '_AMQ_OperationName': operation}};
request.body = JSON.stringify(parameters);
return request;
}
Artemis.prototype._request = function (resource, operation, parameters) {
var request = this._create_request_message(resource, operation, parameters);
if (this._send_pending_requests()) {
this._send_request(request);
} else {
this.requests.push(request);
}
var stack = this.handlers;
var self = this;
return new Promise(function (resolve, reject) {
self.pushed++;
stack.push(as_handler(resolve, reject));
});
}
// No response requested
Artemis.prototype._create_temp_response_queue = function (name) {
var request = this._create_request_message('broker', 'createQueue', [name/*address*/, 'ANYCAST', name/*queue name*/, null/*filter*/, false/*durable*/,
1/*max consumers*/, true/*purgeOnNoConsumers*/, true/*autoCreateAddress*/]);
this._send_request(request);
}
Artemis.prototype.createSubscription = function (name, address, maxConsumers) {
return this._request('broker', 'createQueue', [address, 'MULTICAST', name/*queue name*/, null/*filter*/, true/*durable*/,
maxConsumers/*max consumers*/, false/*purgeOnNoConsumers*/, false/*autoCreateAddress*/]);
}
Artemis.prototype.createQueue = function (name) {
return this._request('broker', 'createQueue', [name/*address*/, 'ANYCAST', name/*queue name*/, null/*filter*/, true/*durable*/,
-1/*max consumers*/, false/*purgeOnNoConsumers*/, true/*autoCreateAddress*/]);
}
Artemis.prototype.destroyQueue = function (name) {
return this._request('broker', 'destroyQueue', [name, true, true]);
}
Artemis.prototype.purgeQueue = function (name) {
return this._request('queue.'+name, 'removeMessages', [null]);
}
Artemis.prototype.getQueueNames = function () {
return this._request('broker', 'getQueueNames', []);
}
var queue_attributes = {
temporary: 'isTemporary',
durable: 'isDurable',
messages: 'getMessageCount',
consumers: 'getConsumerCount',
enqueued: 'getMessagesAdded',
delivering: 'getDeliveringCount',
acknowledged: 'getMessagesAcknowledged',
expired: 'getMessagesExpired',
killed: 'getMessagesKilled'
};
function add_queue_method(name) {
Artemis.prototype[name] = function (queue) {
return this._request('queue.'+queue, name, []);
};
}
for (var key in queue_attributes) {
add_queue_method(queue_attributes[key]);
}
var extra_queue_attributes = {
address: 'getAddress',
routing_type: 'getRoutingType'
}
for (var key in extra_queue_attributes) {
add_queue_method(extra_queue_attributes[key]);
}
var queue_attribute_aliases = {
'isTemporary': 'temporary',
'isDurable': 'durable',
'messageCount': 'messages',
'consumerCount': 'consumers',
'messagesAdded': 'enqueued',
'deliveringCount': 'delivering',
'messagesAcked': 'acknowledged',
'messagesExpired': 'expired',
'messagesKilled': 'killed'
};
function correct_type(o) {
var i = Number(o);
if (!Number.isNaN(i)) return i;
else if (o === 'true') return true;
else if (o === 'false') return false;
else if (o === null) return undefined;
else return o;
}
function set_queue_aliases(q) {
for (var f in queue_attribute_aliases) {
var a = queue_attribute_aliases[f];
if (q[f] !== undefined) {
q[a] = q[f];
delete q[f];
}
}
}
function fix_types(o) {
for (var k in o) {
o[k] = correct_type(o[k]);
}
}
function process_queue_stats(q) {
fix_types(q);
set_queue_aliases(q);
}
Artemis.prototype.listQueues = function () {
return this._request('broker', 'listQueues', ['{"field":"","operation":"","value":"","sortOrder":"","sortBy":"","sortColumn":""}', 1, 2147483647/*MAX_INT*/]).then(function (result) {
var queues = JSON.parse(result).data;
queues.forEach(process_queue_stats);
return queues;
});
};
function routing_type_to_type(t) {
if (t === 'MULTICAST') return 'topic';
if (t === 'ANYCAST') return 'queue';
return t;
}
function routing_types_to_type(t) {
if (t.indexOf('MULTICAST') >= 0) {
return 'topic';
} else if (t.indexOf('ANYCAST') >= 0) {
return 'queue';
} else {
return undefined;
}
}
function address_to_queue_or_topic(a) {
return {
name: a.name,
type: routing_types_to_type(a.routingTypes)
};
}
Artemis.prototype.getAddresses = function () {
return this._request('broker', 'listAddresses', ['{"field":"","operation":"","value":"","sortOrder":"","sortBy":"","sortColumn":""}', 1, 2147483647/*MAX_INT*/]).then(function (result) {
return JSON.parse(result).data.map(address_to_queue_or_topic);
});
};
Artemis.prototype.getQueueDetails = function (name, attribute_list) {
var attributes = attribute_list || Object.keys(queue_attributes);
var agent = this;
return Promise.all(
attributes.map(function (attribute) {
var method_name = queue_attributes[attribute];
if (method_name) {
return agent[method_name](name);
}
})
).then(function (results) {
var q = {'name':name};
for (var i = 0; i < results.length; i++) {
q[attributes[i]] = results[i];
}
return q;
});
}
function initialise_topic_stats(a) {
a.enqueued = 0;
a.messages = 0;
a.subscriptions = [];
a.subscription_count = 0;
a.durable_subscription_count = 0;
a.inactive_durable_subscription_count = 0;
}
function update_topic_stats(a, q) {
a.enqueued += q.enqueued;
a.messages += q.messages;
a.subscriptions.push(q);
a.subscription_count++;
if (q.durable) {
a.durable_subscription_count++;
if (q.consumers === 0) {
a.inactive_durable_subscription_count++;
}
}
}
function queues_to_addresses(addresses, queues, include_topic_stats, include_reverse_index) {
var index = {};
var reverse_index = include_reverse_index ? {} : undefined;
for (var i = 0; i < addresses.length; i++) {
var a = addresses[i];
var b = index[a.name];
if (b === undefined) {
index[a.name] = a;
if (include_topic_stats && a.type === 'topic') {
initialise_topic_stats(a);
}
} else {
log.warn('Duplicate address: %s (%s)', a.name, a.type);
}
}
for (var i = 0; i < queues.length; i++) {
var q = queues[i];
if (reverse_index) {
reverse_index[q.name] = q.address;
}
var a = index[q.address];
if (q.routingType === 'MULTICAST') {
if (a === undefined) {
log.warn('Missing address %s for topic queue %s', q.address, q.name);
a = {
name: q.address,
type: 'topic'
};
index[q.address] = a;
if (include_topic_stats) {
initialise_topic_stats(a);
}
} else if (a.type !== 'topic') {
log.warn('Unexpected address type: queue %s has type %s, address %s has type %s', q.name, q.routingType, q.address, a.type);
}
if (q.durable && !q.purgeOnNoConsumers) {
//treat as subscription
index[q.name] = myutils.merge(q, {
name: q.name,
type: 'subscription'
});
}
if (include_topic_stats) {
update_topic_stats(a, q);
}
} else if (q.routingType === 'ANYCAST') {
if (a === undefined) {
a = {
name: q.address,
type: 'queue'
};
index[q.address] = a;
log.warn('Missing address %s for queue %s', q.address, q.name);
} else if (q.name !== q.address) {
log.warn('Mismatched address %s for queue %s', q.address, q.name);
} else if (a.routingType !== undefined) {
log.warn('Duplicate queue for address %s: %j %j', q.address, a, q);
}
myutils.merge(a, q);
} else {
log.error('Unknown routingType: %s', q.routingType);
}
}
return {
addresses: addresses,
queues: queues,
index: index,
reverse_index: reverse_index
};
}
Artemis.prototype._get_address_data = function (include_topic_stats, include_reverse_index) {
return Promise.all([this.getAddresses(), this.listQueues()]).then(function (results) {
return queues_to_addresses(results[0], results[1], include_topic_stats, include_reverse_index);
});
};
Artemis.prototype.listAddresses = function () {
return this._get_address_data().then(function (data) {
return data.index;
});
};
Artemis.prototype.getAllAddressData = function () {
return this._get_address_data(true, true).then(function (data) {
return data;
});
};
Artemis.prototype.getAllQueuesAndTopics = function () {
return this._get_address_data(true, false).then(function (data) {
return data.index;
});
};
Artemis.prototype.getAddressNames = function () {
return this._request('broker', 'getAddressNames', []);
}
Artemis.prototype.createAddress = function (name, type) {
var routing_types = [];
if (type.anycast || type.queue) routing_types.push('ANYCAST');
if (type.multicast || type.topic) routing_types.push('MULTICAST');
return this._request('broker', 'createAddress', [name, routing_types.join(',')]);
};
Artemis.prototype.deleteAddress = function (name) {
return this._request('broker', 'deleteAddress', [name]);
};
var address_settings_fields = {
'DLA':'',
'expiryAddress':'',
'expiryDelay':-1,
'lastValueQueue':false,
'deliveryAttempts':-1,
'maxSizeBytes':-1,
'pageSizeBytes':-1,
'pageMaxCacheSize':-1,
'redeliveryDelay':-1,
'redeliveryMultiplier':-1,
'maxRedeliveryDelay':-1,
'redistributionDelay':-1,
'sendToDLAOnNoRoute':false,
'addressFullMessagePolicy': 'FAIL',
'slowConsumerThreshold':-1,
'slowConsumerCheckPeriod':-1,
'slowConsumerPolicy':'DROP',
'autoCreateJmsQueues':false,
'autoDeleteJmsQueues':false,
'autoCreateJmsTopics':false,
'autoDeleteJmsTopics':false,
'autoCreateQueues':false,
'autoDeleteQueues':false,
'autoCreateAddresses':false,
'autoDeleteAddresses':false
};
Artemis.prototype.addAddressSettings = function (match, settings) {
var args = [match];
for (var name in address_settings_fields) {
var v = settings[name] || address_settings_fields[name];
args.push(v);
}
return this._request('broker', 'addAddressSettings', args);
};
Artemis.prototype.removeAddressSettings = function (match) {
return this._request('broker', 'removeAddressSettings', [match]);
};
Artemis.prototype.deleteAddressAndBindings = function (address) {
var self = this;
return this.deleteBindingsFor(address).then(function () {
return self.deleteAddress(address);
});
};
Artemis.prototype.deleteBindingsFor = function (address) {
var self = this;
return this.getBoundQueues(address).then(function (results) {
return Promise.all(results.map(function (q) { return self.destroyQueue(q); }));
});
};
Artemis.prototype.getBoundQueues = function (address) {
return this._request('address.'+address, 'getQueueNames', []);
};
Artemis.prototype.createDivert = function (name, source, target) {
return this._request('broker', 'createDivert', [name, name, source, target, false, null, null]);
}
Artemis.prototype.destroyDivert = function (name) {
return this._request('broker', 'destroyDivert', [name]);
}
Artemis.prototype.getDivertNames = function () {
return this._request('broker', 'getDivertNames', []);
}
/**
* Create divert if one does not already exist.
*/
Artemis.prototype.ensureDivert = function (name, source, target) {
var broker = this;
return broker.findDivert(name).then(
function (found) {
if (!found) {
return broker.createDivert(name, source, target);
}
}
);
};
Artemis.prototype.findDivert = function (name) {
return this.getDivertNames().then(
function (results) {
return results.indexOf(name) >= 0;
}
);
};
Artemis.prototype.createConnectorService = function (connector) {
var parameters = {
"host": process.env.MESSAGING_SERVICE_HOST,
"port": process.env.MESSAGING_SERVICE_PORT_AMQPS_BROKER,
"clusterId": connector.clusterId
};
if (connector.containerId !== undefined) {
parameters.containerId = connector.containerId;
}
if (connector.linkName !== undefined) {
parameters.linkName = connector.linkName;
}
if (connector.targetAddress !== undefined) {
parameters.targetAddress = connector.targetAddress;
}
if (connector.sourceAddress !== undefined) {
parameters.sourceAddress = connector.sourceAddress;
}
if (connector.direction !== undefined) {
parameters.direction = connector.direction;
}
return this._request('broker', 'createConnectorService', [connector.name, "org.apache.activemq.artemis.integration.amqp.AMQPConnectorServiceFactory", parameters]);
}
Artemis.prototype.destroyConnectorService = function (name) {
return this._request('broker', 'destroyConnectorService', [name]);
}
Artemis.prototype.getConnectorServices = function () {
return this._request('broker', 'getConnectorServices', []);
}
Artemis.prototype.listConnections = function () {
return this._request('broker', 'listConnectionsAsJSON', []).then(function (result) {
return JSON.parse(result);
});
}
Artemis.prototype.listSessionsForConnection = function (connection_id) {
return this._request('broker', 'listSessionsAsJSON', [connection_id]).then(function (result) {
return JSON.parse(result);
});
}
Artemis.prototype.listConnectionsWithSessions = function () {
var self = this;
return this.listConnections().then(function (conns) {
return Promise.all(conns.map(function (c) { return self.listSessionsForConnection(c.connectionID)})).then(function (sessions) {
for (var i in conns) {
conns[i].sessions = sessions[i];
}
return conns;
});
});
}
Artemis.prototype.listConsumers = function () {
return this._request('broker', 'listAllConsumersAsJSON', []).then(function (result) {
return JSON.parse(result);
});
}
Artemis.prototype.listProducers = function () {
return this._request('broker', 'listProducersInfoAsJSON', []).then(function (result) {
return JSON.parse(result);
});
}
Artemis.prototype.getGlobalMaxSize = function ()
{
return this._request('broker', 'getGlobalMaxSize', []);
}
/**
* Create connector service if one does not already exist.
*/
Artemis.prototype.ensureConnectorService = function (connector) {
var broker = this;
return broker.findConnectorService(connector.name).then(
function (found) {
if (!found) {
return broker.createConnectorService(connector);
}
}
);
};
Artemis.prototype.findConnectorService = function (name) {
return this.getConnectorServices().then(
function (results) {
return results.indexOf(name) >= 0;
}
);
};
Artemis.prototype.close = function () {
if (this.connection) {
var connection = this.connection;
return new Promise(function (resolve) {
connection.on('connection_close', resolve);
connection.on('connection_error', resolve);
connection.close();
});
} else {
return Promise.resolve();
}
}
module.exports.Artemis = Artemis;
module.exports.connect = function (options) {
return new Artemis(amqp.connect(options));
}
| jenmalloy/enmasse | agent/lib/artemis.js | JavaScript | apache-2.0 | 22,695 |
// import loadAll from 'ember-osf-web/utils/load-relationship';
import {
module,
test,
} from 'qunit';
module('Unit | Utility | load relationship');
// Replace this with your real tests.
test('it works', function(assert) {
assert.ok(true);
});
| hmoco/ember-osf-web | tests/unit/utils/load-relationship-test.js | JavaScript | apache-2.0 | 258 |
/**
* @license Apache-2.0
*
* Copyright (c) 2021 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
// MODULES //
var logger = require( 'debug' );
var getHeaders = require( './headers.js' );
// VARIABLES //
var debug = logger( 'github-create-token:options' );
// MAIN //
/**
* Returns request options based on provided options.
*
* @param {Object} opts - provided options
* @param {string} opts.method - request method
* @param {string} opts.protocol - request protocol
* @param {string} opts.hostname - endpoint hostname
* @param {number} opts.port - endpoint port
* @param {string} opts.username - GitHub username
* @param {string} opts.password - GitHub password
* @param {string} [opts.otp] - GitHub one-time password
* @param {string} [opts.accept] - media type
* @param {string} [opts.useragent] - user agent string
* @returns {Object} request options
*/
function options( opts ) {
var out = {};
out.method = opts.method;
debug( 'Method: %s', opts.method );
out.protocol = opts.protocol+':';
debug( 'Protocol: %s', opts.protocol );
out.hostname = opts.hostname;
debug( 'Hostname: %s', opts.hostname );
out.port = opts.port;
debug( 'Port: %d', opts.port );
out.headers = getHeaders( opts );
// debug( 'Headers: %s', JSON.stringify( out.headers ) );
return out;
}
// EXPORTS //
module.exports = options;
| stdlib-js/stdlib | lib/node_modules/@stdlib/_tools/github/create-token/lib/options.js | JavaScript | apache-2.0 | 1,870 |
'use strict';
var os = require('os');
var DeviceController = require('./DeviceController.js');
var DeviceModel = require('./../model/DeviceModel');
var Firebase = require('firebase');
var chalk = require('chalk');
var config = require('./../config.json');
function ClientController() {
var deviceController;
var wrappedDevices = {};
var firebase = new Firebase(config.firebaseUrl);
firebase.authWithCustomToken(config.firebaseKey, function(err, authToken) {
if (err) {
throw new Error(err);
}
var deviceName = os.hostname();
if (deviceName.indexOf('.') >= 0) {
deviceName = deviceName.substring(0, deviceName.indexOf('.'));
}
var fbMonitor = firebase.child('monitor/' + deviceName);
fbMonitor.child('clientHeartbeart').set(Date.now());
setInterval(function() {
console.log('clientHeartbeart', Date.now());
fbMonitor.child('clientHeartbeart').set(Date.now());
}, 90 * 1000);
deviceController = new DeviceController();
deviceController.on('DeviceAdded', function(device) {
wrappedDevices[device.id] = new DeviceModel(
firebase,
deviceController.getAdbClient(),
device.id);
fbMonitor.child('clients/' + device.id).set(true);
});
deviceController.on('DeviceRemoved', function(device) {
if (wrappedDevices[device.id]) {
wrappedDevices[device.id].disconnected();
}
fbMonitor.child('clients/' + device.id).remove();
delete wrappedDevices[device.id];
});
}.bind(this));
this.getDeviceController = function() {
return deviceController;
};
}
ClientController.prototype.log = function(msg, arg) {
if (!arg) {
arg = '';
}
console.log(chalk.blue('ClientController: ') + msg, arg);
};
module.exports = ClientController;
| GoogleChromeLabs/MiniMobileDeviceLab | PiLab/controller/ClientController.js | JavaScript | apache-2.0 | 1,792 |
var mustacheLib = require('/lib/xp/mustache');
var portalLib = require('/lib/xp/portal');
var foosRetrievalLib = require('/lib/foos-retrieval');
var foosUrlLib = require('/lib/foos-url');
var foosUtilLib = require('/lib/foos-util');
var gamesWidgetLib = require('/lib/widgets/games/games');
var view = resolve('game.html');
// Handle the GET request
exports.get = function (req) {
var game = portalLib.getContent();
var gameDetails = generateGameDetails(game);
var body = mustacheLib.render(view, {
gamesWidget: gamesWidgetLib.render([game], false),
gameDetails: gameDetails,
tableImgUrl: portalLib.assetUrl({path: "img/table.png"})
});
var chartData = getChartData(game);
var chartUrl = portalLib.assetUrl({path: "js/Chart.bundle.min.js"});
var gameJsUrl = portalLib.assetUrl({path: "js/game.js"});
var contribScripts = [];
if (gameDetails != null) {
contribScripts = [
'<script src="' + chartUrl + '""></script>',
'<script>var GOALS = ' + JSON.stringify(chartData, null, 2) + ';\r\nvar WDN ="' + gameDetails.winnersDisplayName +
'"\r\nvar LDN ="' + gameDetails.losersDisplayName + '"</script>',
'<script src="' + gameJsUrl + '""></script>'
];
}
return {
body: body,
pageContributions: {
bodyEnd: contribScripts
}
}
};
function getChartData(game) {
var players = {};
var winners = [].concat(game.data.winners);
var losers = [].concat(game.data.losers);
winners.forEach(function (p) {
players[p.playerId] = {
name: p.gen.name,
winner: true
}
});
losers.forEach(function (p) {
players[p.playerId] = {
name: p.gen.name,
winner: false
}
});
var goalData = game.data.goals;
var chartData = [], chartPoint, team;
if (goalData) {
goalData.forEach(function (goal) {
if (goal.against) {
team = players[goal.playerId].winner ? 'loser' : 'winner';
} else {
team = players[goal.playerId].winner ? 'winner' : 'loser';
}
chartPoint = {
time: goal.time,
player: players[goal.playerId].name,
teamScore: team
};
chartData.push(chartPoint);
});
}
return chartData;
}
function generateGameDetails(game) {
if (!game.data.goals) {
return undefined;
}
var winnersDisplayName;
var losersDisplayName;
var winners;
var losers;
if (game.data.winners.length == 2) {
var winingTeam = foosRetrievalLib.getTeamByGame(game, true, true);
var losingTeam = foosRetrievalLib.getTeamByGame(game, false, true);
winnersDisplayName = winingTeam.displayName;
losersDisplayName = losingTeam.displayName;
winners = foosRetrievalLib.getPlayersByGame(game, true);
losers = foosRetrievalLib.getPlayersByGame(game, false);
} else {
var winner = foosRetrievalLib.getContentByKey(game.data.winners.playerId);
var loser = foosRetrievalLib.getContentByKey(game.data.losers.playerId);
winnersDisplayName = winner.displayName;
losersDisplayName = loser.displayName;
winners = [winner];
losers = [loser];
}
foosUtilLib.concat(winners, losers).forEach(function (player) {
foosUrlLib.generatePictureUrl(player);
foosUrlLib.generatePageUrl(player);
});
var firstHalfGoals = [], secondHalfGoals = [];
generateGoalsDetails(game, firstHalfGoals, secondHalfGoals)
return {
winnersDisplayName: winnersDisplayName,
losersDisplayName: losersDisplayName,
firstHalfWinners: winners,
secondHalfWinners: winners.slice(0).reverse(),
firstHalfLosers: losers.slice(0).reverse(),
secondHalfLosers: losers,
firstHalfGoals: firstHalfGoals,
secondHalfGoals: secondHalfGoals
};
}
function generateGoalsDetails(game, firstHalf, secondHalf) {
var winnersScore = 0;
var losersScore = 0;
var winnerIds = foosUtilLib.toArray(game.data.winners).map(function (playerResult) {
return playerResult.playerId
});
var playersById = {};
foosRetrievalLib.getPlayersByGame(game).forEach(function (player) {
playersById[player._id] = player;
});
var currentHalf = firstHalf;
game.data.goals.sort(function (goal1, goal2) {
return goal1.time - goal2.time;
}).forEach(function (goal) {
var winnerScored = (!goal.against && winnerIds.indexOf(goal.playerId) > -1) ||
(goal.against && winnerIds.indexOf(goal.playerId) == -1);
if (winnerScored) {
winnersScore++;
} else {
losersScore++;
}
var comment = playersById[goal.playerId].displayName + " scores! (" + formatTime(goal.time) +
")" + (goal.against ? " ... an own goal" : "");
var winner = winnerScored ? comment : "";
var loser = winnerScored ? "" : comment;
currentHalf.push({
time: formatTime(game.time),
winner: winner,
score: winnersScore + " - " + losersScore,
loser: loser
});
if (winnersScore >= 5 || losersScore >= 5) {
currentHalf = secondHalf;
}
});
}
function formatTime(time) {
var min = Math.floor(time / 60);
var sec = time % 60;
return (min < 10 ? "0" : "") + min + "′" + (sec < 10 ? "0" : "") + sec + "′′";
} | GlennRicaud/foos-app | src/main/resources/site/parts/game/game.js | JavaScript | apache-2.0 | 5,630 |