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
jsonp({"cep":"38412694","logradouro":"Rua Fernando Reis Cardoso","bairro":"Morada Nova","cidade":"Uberl\u00e2ndia","uf":"MG","estado":"Minas Gerais"});
lfreneda/cepdb
api/v1/38412694.jsonp.js
JavaScript
cc0-1.0
152
jsonp({"cep":"04348050","logradouro":"Rua Jos\u00e9 Teles de Matos","bairro":"Jardim Oriental","cidade":"S\u00e3o Paulo","uf":"SP","estado":"S\u00e3o Paulo"});
lfreneda/cepdb
api/v1/04348050.jsonp.js
JavaScript
cc0-1.0
160
jsonp({"cep":"29017230","logradouro":"Beco Jos\u00e9 Valfredo Santos","bairro":"Forte S\u00e3o Jo\u00e3o","cidade":"Vit\u00f3ria","uf":"ES","estado":"Esp\u00edrito Santo"});
lfreneda/cepdb
api/v1/29017230.jsonp.js
JavaScript
cc0-1.0
174
'use strict' module.exports = require('express').Router()
Webschool-io/be-mean
Apostila/module-nodejs/src/aula-express-generator-rotas/modules/Users/routerExpress.js
JavaScript
cc0-1.0
58
jsonp({"cep":"08715030","logradouro":"Rua S\u00e3o Jo\u00e3o","bairro":"Centro","cidade":"Mogi das Cruzes","uf":"SP","estado":"S\u00e3o Paulo"});
lfreneda/cepdb
api/v1/08715030.jsonp.js
JavaScript
cc0-1.0
146
// No dependencies. 'use strict'; var engine = engine || {}; engine.keyboard = { // Get functions. 'get': { // Check if an event function executes every frame // and return a boolean. // Required args: event, key 'loop': function(args){ return Boolean( engine.keyboard.keyBinds[args['key']] !== void 0 && engine.keyboard.keyBinds[args['key']][args['event']] !== void 0 && engine.keyboard.keyBinds[args['key']][args['event']]['loop'] ); }, // Get the key code from a key event // and return an integer. 'keyCode': function(event){ return Number( event.keyCode || event.which ); }, }, // Handling functions. 'handle': { // Handle bound event functions. // Required args: event, key 'functions': function(args){ if(engine.keyboard.keyBinds[args['key']] !== void 0 && engine.keyboard.keyBinds[args['key']][args['event']] !== void 0){ engine.keyboard.keyBinds[args['key']][args['event']](); } }, // Handle the onkeydown event. 'onkeydown': function(event){ var key = engine.keyboard.get.keyCode(event); engine.keyboard.keyStates[key] = true; if(!engine.keyboard.get.loop({'event': 'keydown', 'key': key,})){ engine.keyboard.handle.functions({ 'event': 'keydown', 'key': key, }); } }, // Handle the onkeypress event. 'onkeypress': function(event){ var key = engine.keyboard.get.keyCode(event); if(!engine.keyboard.get.loop({'event': 'keypress', 'key': key,})){ engine.keyboard.handle.functions({ 'event': 'keypress', 'key': key, }); } }, // Handle the onkeyup event. 'onkeyup': function(event){ var key = engine.keyboard.get.keyCode(event); delete engine.keyboard.keyStates[key]; if(!engine.keyboard.get.loop({'event': 'keyup', 'key': key,})){ engine.keyboard.handle.functions({ 'event': 'keyup', 'key': key, }); } }, }, // Initialize keyboard events. 'init': function(){ window.onkeydown = engine.keyboard.handle.onkeydown; window.onkeypress = engine.keyboard.handle.onkeypress; window.onkeyup = engine.keyboard.handle.onkeyup; }, // Repeat events. 'repeatEvents': function(){ for(var event in engine.keyboard.events){ if(engine.keyboard.events[event] !== true){ continue; } for(var key in engine.keyboard.keyBinds){ if(engine.keyboard.keyBinds[key][event] !== void 0 && engine.keyboard.keyStates[key] !== void 0){ engine.keyboard.keyBinds[key][event](); } } } }, // Set functions. 'set': { // Bind a function to a key. // Required args: event, key, loop, todo 'keyBind': function(args){ if(typeof args['key'] === 'string'){ var temp = args['key']; args['key'] = temp.charCodeAt(0); } if(engine.keyboard.keyBinds[args['key']] === void 0){ engine.keyboard.keyBinds[args['key']] = {}; } engine.keyboard.keyBinds[args['key']][args['event']] = args['todo']; engine.keyboard.keyBinds[args['key']][args['event']]['loop'] = args['loop']; engine.keyboard.events[args['event']] = args['loop']; }, }, //-----------------------// // An object to hold currently used events. 'events': {}, // An object to hold code bound to keys. 'keyBinds': {}, // An object to hold key states. 'keyStates': {}, };
honzi/Files
OldCode/Engine.htm/engine/js/keyboard.js
JavaScript
cc0-1.0
3,758
jsonp({"cep":"12091846","logradouro":"Rua Vicente Rodrigues Sales","bairro":"Cidade Jardim","cidade":"Taubat\u00e9","uf":"SP","estado":"S\u00e3o Paulo"});
lfreneda/cepdb
api/v1/12091846.jsonp.js
JavaScript
cc0-1.0
155
jsonp({"cep":"89286308","logradouro":"Rua Augusto Mallon","bairro":"Cruzeiro","cidade":"S\u00e3o Bento do Sul","uf":"SC","estado":"Santa Catarina"});
lfreneda/cepdb
api/v1/89286308.jsonp.js
JavaScript
cc0-1.0
150
jsonp({"cep":"76820354","logradouro":"Rua Em\u00eddio Alves Feitosa","bairro":"Agenor de Carvalho","cidade":"Porto Velho","uf":"RO","estado":"Rond\u00f4nia"});
lfreneda/cepdb
api/v1/76820354.jsonp.js
JavaScript
cc0-1.0
160
jsonp({"cep":"33840220","logradouro":"Rua das Ar\u00e1lias","bairro":"Rosaneves","cidade":"Ribeir\u00e3o das Neves","uf":"MG","estado":"Minas Gerais"});
lfreneda/cepdb
api/v1/33840220.jsonp.js
JavaScript
cc0-1.0
153
jsonp({"cep":"55291800","logradouro":"Rua Sebasti\u00e3o Ferreira de Lima","bairro":"Francisco Sim\u00e3o dos Santos Figueira","cidade":"Garanhuns","uf":"PE","estado":"Pernambuco"});
lfreneda/cepdb
api/v1/55291800.jsonp.js
JavaScript
cc0-1.0
183
jsonp({"cep":"33822785","logradouro":"Rua Quinze","bairro":"Liberdade","cidade":"Ribeir\u00e3o das Neves","uf":"MG","estado":"Minas Gerais"});
lfreneda/cepdb
api/v1/33822785.jsonp.js
JavaScript
cc0-1.0
143
jsonp({"cep":"04815230","logradouro":"Rua Am\u00e9rico Cioffi","bairro":"Interlagos","cidade":"S\u00e3o Paulo","uf":"SP","estado":"S\u00e3o Paulo"});
lfreneda/cepdb
api/v1/04815230.jsonp.js
JavaScript
cc0-1.0
150
jsonp({"cep":"68377055","logradouro":"Rua VII","bairro":"Mutir\u00e3o","cidade":"Altamira","uf":"PA","estado":"Par\u00e1"});
lfreneda/cepdb
api/v1/68377055.jsonp.js
JavaScript
cc0-1.0
125
jsonp({"cep":"19909110","logradouro":"Rodovia BR-153","bairro":"Vila Santos Dumont","cidade":"Ourinhos","uf":"SP","estado":"S\u00e3o Paulo"});
lfreneda/cepdb
api/v1/19909110.jsonp.js
JavaScript
cc0-1.0
143
jsonp({"cep":"86042420","logradouro":"Rua Adolfo Franciolli","bairro":"Laranjeiras","cidade":"Londrina","uf":"PR","estado":"Paran\u00e1"});
lfreneda/cepdb
api/v1/86042420.jsonp.js
JavaScript
cc0-1.0
140
jsonp({"cep":"02210020","logradouro":"Rua \u00c1guas Formosas","bairro":"Jardim Brasil (Zona Norte)","cidade":"S\u00e3o Paulo","uf":"SP","estado":"S\u00e3o Paulo"});
lfreneda/cepdb
api/v1/02210020.jsonp.js
JavaScript
cc0-1.0
166
jsonp({"cep":"15080290","logradouro":"Rua Matilde Jos\u00e9 Calil","bairro":"Jardim Santa Maria","cidade":"S\u00e3o Jos\u00e9 do Rio Preto","uf":"SP","estado":"S\u00e3o Paulo"});
lfreneda/cepdb
api/v1/15080290.jsonp.js
JavaScript
cc0-1.0
179
jsonp({"cep":"13903210","logradouro":"Avenida Vereador Armando Fornari","bairro":"Parque Dona Virg\u00ednia","cidade":"Amparo","uf":"SP","estado":"S\u00e3o Paulo"});
lfreneda/cepdb
api/v1/13903210.jsonp.js
JavaScript
cc0-1.0
166
jsonp({"cep":"37704094","logradouro":"Rua Louren\u00e7o Dias Ferreira","bairro":"Jardim Santa Ros\u00e1lia","cidade":"Po\u00e7os de Caldas","uf":"MG","estado":"Minas Gerais"});
lfreneda/cepdb
api/v1/37704094.jsonp.js
JavaScript
cc0-1.0
177
jsonp({"cep":"35702509","logradouro":"Rua Exaltino Ribeiro","bairro":"Fl\u00f3rida","cidade":"Sete Lagoas","uf":"MG","estado":"Minas Gerais"});
lfreneda/cepdb
api/v1/35702509.jsonp.js
JavaScript
cc0-1.0
144
jsonp({"cep":"40301290","logradouro":"Rua Botelho Benjamim","bairro":"Santo Ant\u00f4nio","cidade":"Salvador","uf":"BA","estado":"Bahia"});
lfreneda/cepdb
api/v1/40301290.jsonp.js
JavaScript
cc0-1.0
140
jsonp({"cep":"72852856","logradouro":"Quadra Quadra 26","bairro":"Jardim Umuarama Setor 7","cidade":"Luzi\u00e2nia","uf":"GO","estado":"Goi\u00e1s"});
lfreneda/cepdb
api/v1/72852856.jsonp.js
JavaScript
cc0-1.0
151
jsonp({"cep":"69033120","logradouro":"Rua Alfredo da Mata","bairro":"S\u00e3o Jorge","cidade":"Manaus","uf":"AM","estado":"Amazonas"});
lfreneda/cepdb
api/v1/69033120.jsonp.js
JavaScript
cc0-1.0
136
jsonp({"cep":"37500095","logradouro":"Rua Jo\u00e3o Pullit","bairro":"Morro Chic","cidade":"Itajub\u00e1","uf":"MG","estado":"Minas Gerais"});
lfreneda/cepdb
api/v1/37500095.jsonp.js
JavaScript
cc0-1.0
143
jsonp({"cep":"44053456","logradouro":"Caminho Ubat\u00e3","bairro":"Cidade Nova","cidade":"Feira de Santana","uf":"BA","estado":"Bahia"});
lfreneda/cepdb
api/v1/44053456.jsonp.js
JavaScript
cc0-1.0
139
jsonp({"cep":"72859257","logradouro":"Quadra Quadra 257","bairro":"Mans\u00f5es de Recreio Estrela Dalva VIII","cidade":"Luzi\u00e2nia","uf":"GO","estado":"Goi\u00e1s"});
lfreneda/cepdb
api/v1/72859257.jsonp.js
JavaScript
cc0-1.0
171
jsonp({"cep":"83702190","logradouro":"Rua Alfred Charvet","bairro":"Centro","cidade":"Arauc\u00e1ria","uf":"PR","estado":"Paran\u00e1"});
lfreneda/cepdb
api/v1/83702190.jsonp.js
JavaScript
cc0-1.0
138
jsonp({"cep":"41321430","logradouro":"Vila Cambonas-I","bairro":"Castelo Branco","cidade":"Salvador","uf":"BA","estado":"Bahia"});
lfreneda/cepdb
api/v1/41321430.jsonp.js
JavaScript
cc0-1.0
131
jsonp({"cep":"17021600","logradouro":"Rua Benedita Cardoso Madureira","bairro":"Jardim Estrela D'Alva","cidade":"Bauru","uf":"SP","estado":"S\u00e3o Paulo"});
lfreneda/cepdb
api/v1/17021600.jsonp.js
JavaScript
cc0-1.0
159
// Compiled by ClojureScript 0.0-3165 {} goog.provide('cljs.core.async.impl.channels'); goog.require('cljs.core'); goog.require('cljs.core.async.impl.buffers'); goog.require('cljs.core.async.impl.dispatch'); goog.require('cljs.core.async.impl.protocols'); cljs.core.async.impl.channels.box = (function cljs$core$async$impl$channels$box(val){ if(typeof cljs.core.async.impl.channels.t30720 !== 'undefined'){ } else { /** * @constructor */ cljs.core.async.impl.channels.t30720 = (function (val,box,meta30721){ this.val = val; this.box = box; this.meta30721 = meta30721; this.cljs$lang$protocol_mask$partition1$ = 0; this.cljs$lang$protocol_mask$partition0$ = 425984; }) cljs.core.async.impl.channels.t30720.prototype.cljs$core$IDeref$_deref$arity$1 = (function (_){ var self__ = this; var ___$1 = this; return self__.val; }); cljs.core.async.impl.channels.t30720.prototype.cljs$core$IMeta$_meta$arity$1 = (function (_30722){ var self__ = this; var _30722__$1 = this; return self__.meta30721; }); cljs.core.async.impl.channels.t30720.prototype.cljs$core$IWithMeta$_with_meta$arity$2 = (function (_30722,meta30721__$1){ var self__ = this; var _30722__$1 = this; return (new cljs.core.async.impl.channels.t30720(self__.val,self__.box,meta30721__$1)); }); cljs.core.async.impl.channels.t30720.cljs$lang$type = true; cljs.core.async.impl.channels.t30720.cljs$lang$ctorStr = "cljs.core.async.impl.channels/t30720"; cljs.core.async.impl.channels.t30720.cljs$lang$ctorPrWriter = (function (this__18435__auto__,writer__18436__auto__,opt__18437__auto__){ return cljs.core._write.call(null,writer__18436__auto__,"cljs.core.async.impl.channels/t30720"); }); cljs.core.async.impl.channels.__GT_t30720 = (function cljs$core$async$impl$channels$box_$___GT_t30720(val__$1,box__$1,meta30721){ return (new cljs.core.async.impl.channels.t30720(val__$1,box__$1,meta30721)); }); } return (new cljs.core.async.impl.channels.t30720(val,cljs$core$async$impl$channels$box,cljs.core.PersistentArrayMap.EMPTY)); }); /** * @constructor */ cljs.core.async.impl.channels.PutBox = (function (handler,val){ this.handler = handler; this.val = val; }) cljs.core.async.impl.channels.PutBox.cljs$lang$type = true; cljs.core.async.impl.channels.PutBox.cljs$lang$ctorStr = "cljs.core.async.impl.channels/PutBox"; cljs.core.async.impl.channels.PutBox.cljs$lang$ctorPrWriter = (function (this__18435__auto__,writer__18436__auto__,opt__18437__auto__){ return cljs.core._write.call(null,writer__18436__auto__,"cljs.core.async.impl.channels/PutBox"); }); cljs.core.async.impl.channels.__GT_PutBox = (function cljs$core$async$impl$channels$__GT_PutBox(handler,val){ return (new cljs.core.async.impl.channels.PutBox(handler,val)); }); cljs.core.async.impl.channels.put_active_QMARK_ = (function cljs$core$async$impl$channels$put_active_QMARK_(box){ return cljs.core.async.impl.protocols.active_QMARK_.call(null,box.handler); }); cljs.core.async.impl.channels.MAX_DIRTY = (64); cljs.core.async.impl.channels.MMC = (function (){var obj30724 = {}; return obj30724; })(); cljs.core.async.impl.channels.abort = (function cljs$core$async$impl$channels$abort(this$){ if((function (){var and__17844__auto__ = this$; if(and__17844__auto__){ return this$.cljs$core$async$impl$channels$MMC$abort$arity$1; } else { return and__17844__auto__; } })()){ return this$.cljs$core$async$impl$channels$MMC$abort$arity$1(this$); } else { var x__18492__auto__ = (((this$ == null))?null:this$); return (function (){var or__17856__auto__ = (cljs.core.async.impl.channels.abort[goog.typeOf(x__18492__auto__)]); if(or__17856__auto__){ return or__17856__auto__; } else { var or__17856__auto____$1 = (cljs.core.async.impl.channels.abort["_"]); if(or__17856__auto____$1){ return or__17856__auto____$1; } else { throw cljs.core.missing_protocol.call(null,"MMC.abort",this$); } } })().call(null,this$); } }); /** * @constructor */ cljs.core.async.impl.channels.ManyToManyChannel = (function (takes,dirty_takes,puts,dirty_puts,buf,closed,add_BANG_){ this.takes = takes; this.dirty_takes = dirty_takes; this.puts = puts; this.dirty_puts = dirty_puts; this.buf = buf; this.closed = closed; this.add_BANG_ = add_BANG_; }) cljs.core.async.impl.channels.ManyToManyChannel.prototype.cljs$core$async$impl$protocols$Channel$ = true; cljs.core.async.impl.channels.ManyToManyChannel.prototype.cljs$core$async$impl$protocols$Channel$closed_QMARK_$arity$1 = (function (_){ var self__ = this; var ___$1 = this; return self__.closed; }); cljs.core.async.impl.channels.ManyToManyChannel.prototype.cljs$core$async$impl$protocols$Channel$close_BANG_$arity$1 = (function (this$){ var self__ = this; var this$__$1 = this; if(self__.closed){ return null; } else { self__.closed = true; if(cljs.core.truth_((function (){var and__17844__auto__ = self__.buf; if(cljs.core.truth_(and__17844__auto__)){ return (self__.puts.length === (0)); } else { return and__17844__auto__; } })())){ self__.add_BANG_.call(null,self__.buf); } else { } while(true){ var taker_30725 = self__.takes.pop(); if((taker_30725 == null)){ } else { if(cljs.core.async.impl.protocols.active_QMARK_.call(null,taker_30725)){ var take_cb_30726 = cljs.core.async.impl.protocols.commit.call(null,taker_30725); var val_30727 = (cljs.core.truth_((function (){var and__17844__auto__ = self__.buf; if(cljs.core.truth_(and__17844__auto__)){ return (cljs.core.count.call(null,self__.buf) > (0)); } else { return and__17844__auto__; } })())?cljs.core.async.impl.protocols.remove_BANG_.call(null,self__.buf):null); cljs.core.async.impl.dispatch.run.call(null,((function (take_cb_30726,val_30727,taker_30725,this$__$1){ return (function (){ return take_cb_30726.call(null,val_30727); });})(take_cb_30726,val_30727,taker_30725,this$__$1)) ); } else { } continue; } break; } return null; } }); cljs.core.async.impl.channels.ManyToManyChannel.prototype.cljs$core$async$impl$protocols$ReadPort$ = true; cljs.core.async.impl.channels.ManyToManyChannel.prototype.cljs$core$async$impl$protocols$ReadPort$take_BANG_$arity$2 = (function (this$,handler){ var self__ = this; var this$__$1 = this; if(!(cljs.core.async.impl.protocols.active_QMARK_.call(null,handler))){ return null; } else { if((!((self__.buf == null))) && ((cljs.core.count.call(null,self__.buf) > (0)))){ var _ = cljs.core.async.impl.protocols.commit.call(null,handler); var retval = cljs.core.async.impl.channels.box.call(null,cljs.core.async.impl.protocols.remove_BANG_.call(null,self__.buf)); while(true){ if(cljs.core.truth_(cljs.core.async.impl.protocols.full_QMARK_.call(null,self__.buf))){ } else { var putter_30728 = self__.puts.pop(); if((putter_30728 == null)){ } else { var put_handler_30729 = putter_30728.handler; var val_30730 = putter_30728.val; if(cljs.core.async.impl.protocols.active_QMARK_.call(null,put_handler_30729)){ var put_cb_30731 = cljs.core.async.impl.protocols.commit.call(null,put_handler_30729); cljs.core.async.impl.protocols.commit.call(null,handler); cljs.core.async.impl.dispatch.run.call(null,((function (put_cb_30731,put_handler_30729,val_30730,putter_30728,_,retval,this$__$1){ return (function (){ return put_cb_30731.call(null,true); });})(put_cb_30731,put_handler_30729,val_30730,putter_30728,_,retval,this$__$1)) ); if(cljs.core.reduced_QMARK_.call(null,self__.add_BANG_.call(null,self__.buf,val_30730))){ cljs.core.async.impl.channels.abort.call(null,this$__$1); } else { } } else { } continue; } } break; } return retval; } else { var putter = (function (){while(true){ var putter = self__.puts.pop(); if(cljs.core.truth_(putter)){ if(cljs.core.async.impl.protocols.active_QMARK_.call(null,putter.handler)){ return putter; } else { continue; } } else { return null; } break; } })(); if(cljs.core.truth_(putter)){ var put_cb = cljs.core.async.impl.protocols.commit.call(null,putter.handler); cljs.core.async.impl.protocols.commit.call(null,handler); cljs.core.async.impl.dispatch.run.call(null,((function (put_cb,putter,this$__$1){ return (function (){ return put_cb.call(null,true); });})(put_cb,putter,this$__$1)) ); return cljs.core.async.impl.channels.box.call(null,putter.val); } else { if(cljs.core.truth_(self__.closed)){ if(cljs.core.truth_(self__.buf)){ self__.add_BANG_.call(null,self__.buf); } else { } if(cljs.core.truth_((function (){var and__17844__auto__ = cljs.core.async.impl.protocols.active_QMARK_.call(null,handler); if(cljs.core.truth_(and__17844__auto__)){ return cljs.core.async.impl.protocols.commit.call(null,handler); } else { return and__17844__auto__; } })())){ var has_val = (function (){var and__17844__auto__ = self__.buf; if(cljs.core.truth_(and__17844__auto__)){ return (cljs.core.count.call(null,self__.buf) > (0)); } else { return and__17844__auto__; } })(); var val = (cljs.core.truth_(has_val)?cljs.core.async.impl.protocols.remove_BANG_.call(null,self__.buf):null); return cljs.core.async.impl.channels.box.call(null,val); } else { return null; } } else { if((self__.dirty_takes > cljs.core.async.impl.channels.MAX_DIRTY)){ self__.dirty_takes = (0); self__.takes.cleanup(cljs.core.async.impl.protocols.active_QMARK_); } else { self__.dirty_takes = (self__.dirty_takes + (1)); } if((self__.takes.length < cljs.core.async.impl.protocols.MAX_QUEUE_SIZE)){ } else { throw (new Error([cljs.core.str("Assert failed: "),cljs.core.str([cljs.core.str("No more than "),cljs.core.str(cljs.core.async.impl.protocols.MAX_QUEUE_SIZE),cljs.core.str(" pending takes are allowed on a single channel.")].join('')),cljs.core.str("\n"),cljs.core.str(cljs.core.pr_str.call(null,cljs.core.list(new cljs.core.Symbol(null,"<","<",993667236,null),cljs.core.list(new cljs.core.Symbol(null,".-length",".-length",-280799999,null),new cljs.core.Symbol(null,"takes","takes",298247964,null)),new cljs.core.Symbol("impl","MAX-QUEUE-SIZE","impl/MAX-QUEUE-SIZE",1508600732,null))))].join(''))); } self__.takes.unbounded_unshift(handler); return null; } } } } }); cljs.core.async.impl.channels.ManyToManyChannel.prototype.cljs$core$async$impl$protocols$WritePort$ = true; cljs.core.async.impl.channels.ManyToManyChannel.prototype.cljs$core$async$impl$protocols$WritePort$put_BANG_$arity$3 = (function (this$,val,handler){ var self__ = this; var this$__$1 = this; if(!((val == null))){ } else { throw (new Error([cljs.core.str("Assert failed: "),cljs.core.str("Can't put nil in on a channel"),cljs.core.str("\n"),cljs.core.str(cljs.core.pr_str.call(null,cljs.core.list(new cljs.core.Symbol(null,"not","not",1044554643,null),cljs.core.list(new cljs.core.Symbol(null,"nil?","nil?",1612038930,null),new cljs.core.Symbol(null,"val","val",1769233139,null)))))].join(''))); } var closed__$1 = self__.closed; if((closed__$1) || (!(cljs.core.async.impl.protocols.active_QMARK_.call(null,handler)))){ return cljs.core.async.impl.channels.box.call(null,!(closed__$1)); } else { if(cljs.core.truth_((function (){var and__17844__auto__ = self__.buf; if(cljs.core.truth_(and__17844__auto__)){ return cljs.core.not.call(null,cljs.core.async.impl.protocols.full_QMARK_.call(null,self__.buf)); } else { return and__17844__auto__; } })())){ cljs.core.async.impl.protocols.commit.call(null,handler); var done_QMARK_ = cljs.core.reduced_QMARK_.call(null,self__.add_BANG_.call(null,self__.buf,val)); while(true){ if(((self__.takes.length > (0))) && ((cljs.core.count.call(null,self__.buf) > (0)))){ var taker_30732 = self__.takes.pop(); if(cljs.core.async.impl.protocols.active_QMARK_.call(null,taker_30732)){ var take_cb_30733 = cljs.core.async.impl.protocols.commit.call(null,taker_30732); var val_30734__$1 = cljs.core.async.impl.protocols.remove_BANG_.call(null,self__.buf); cljs.core.async.impl.dispatch.run.call(null,((function (take_cb_30733,val_30734__$1,taker_30732,done_QMARK_,closed__$1,this$__$1){ return (function (){ return take_cb_30733.call(null,val_30734__$1); });})(take_cb_30733,val_30734__$1,taker_30732,done_QMARK_,closed__$1,this$__$1)) ); } else { continue; } } else { } break; } if(done_QMARK_){ cljs.core.async.impl.channels.abort.call(null,this$__$1); } else { } return cljs.core.async.impl.channels.box.call(null,true); } else { var taker = (function (){while(true){ var taker = self__.takes.pop(); if(cljs.core.truth_(taker)){ if(cljs.core.truth_(cljs.core.async.impl.protocols.active_QMARK_.call(null,taker))){ return taker; } else { continue; } } else { return null; } break; } })(); if(cljs.core.truth_(taker)){ var take_cb = cljs.core.async.impl.protocols.commit.call(null,taker); cljs.core.async.impl.protocols.commit.call(null,handler); cljs.core.async.impl.dispatch.run.call(null,((function (take_cb,taker,closed__$1,this$__$1){ return (function (){ return take_cb.call(null,val); });})(take_cb,taker,closed__$1,this$__$1)) ); return cljs.core.async.impl.channels.box.call(null,true); } else { if((self__.dirty_puts > cljs.core.async.impl.channels.MAX_DIRTY)){ self__.dirty_puts = (0); self__.puts.cleanup(cljs.core.async.impl.channels.put_active_QMARK_); } else { self__.dirty_puts = (self__.dirty_puts + (1)); } if((self__.puts.length < cljs.core.async.impl.protocols.MAX_QUEUE_SIZE)){ } else { throw (new Error([cljs.core.str("Assert failed: "),cljs.core.str([cljs.core.str("No more than "),cljs.core.str(cljs.core.async.impl.protocols.MAX_QUEUE_SIZE),cljs.core.str(" pending puts are allowed on a single channel."),cljs.core.str(" Consider using a windowed buffer.")].join('')),cljs.core.str("\n"),cljs.core.str(cljs.core.pr_str.call(null,cljs.core.list(new cljs.core.Symbol(null,"<","<",993667236,null),cljs.core.list(new cljs.core.Symbol(null,".-length",".-length",-280799999,null),new cljs.core.Symbol(null,"puts","puts",-1883877054,null)),new cljs.core.Symbol("impl","MAX-QUEUE-SIZE","impl/MAX-QUEUE-SIZE",1508600732,null))))].join(''))); } self__.puts.unbounded_unshift((new cljs.core.async.impl.channels.PutBox(handler,val))); return null; } } } }); cljs.core.async.impl.channels.ManyToManyChannel.prototype.cljs$core$async$impl$channels$MMC$ = true; cljs.core.async.impl.channels.ManyToManyChannel.prototype.cljs$core$async$impl$channels$MMC$abort$arity$1 = (function (this$){ var self__ = this; var this$__$1 = this; while(true){ var putter_30735 = self__.puts.pop(); if((putter_30735 == null)){ } else { var put_handler_30736 = putter_30735.handler; var val_30737 = putter_30735.val; if(cljs.core.async.impl.protocols.active_QMARK_.call(null,put_handler_30736)){ var put_cb_30738 = cljs.core.async.impl.protocols.commit.call(null,put_handler_30736); cljs.core.async.impl.dispatch.run.call(null,((function (put_cb_30738,put_handler_30736,val_30737,putter_30735,this$__$1){ return (function (){ return put_cb_30738.call(null,true); });})(put_cb_30738,put_handler_30736,val_30737,putter_30735,this$__$1)) ); } else { continue; } } break; } self__.puts.cleanup(cljs.core.constantly.call(null,false)); return cljs.core.async.impl.protocols.close_BANG_.call(null,this$__$1); }); cljs.core.async.impl.channels.ManyToManyChannel.cljs$lang$type = true; cljs.core.async.impl.channels.ManyToManyChannel.cljs$lang$ctorStr = "cljs.core.async.impl.channels/ManyToManyChannel"; cljs.core.async.impl.channels.ManyToManyChannel.cljs$lang$ctorPrWriter = (function (this__18435__auto__,writer__18436__auto__,opt__18437__auto__){ return cljs.core._write.call(null,writer__18436__auto__,"cljs.core.async.impl.channels/ManyToManyChannel"); }); cljs.core.async.impl.channels.__GT_ManyToManyChannel = (function cljs$core$async$impl$channels$__GT_ManyToManyChannel(takes,dirty_takes,puts,dirty_puts,buf,closed,add_BANG_){ return (new cljs.core.async.impl.channels.ManyToManyChannel(takes,dirty_takes,puts,dirty_puts,buf,closed,add_BANG_)); }); cljs.core.async.impl.channels.ex_handler = (function cljs$core$async$impl$channels$ex_handler(ex){ console.log(ex); return null; }); cljs.core.async.impl.channels.handle = (function cljs$core$async$impl$channels$handle(buf,exh,t){ var else$ = (function (){var or__17856__auto__ = exh; if(cljs.core.truth_(or__17856__auto__)){ return or__17856__auto__; } else { return cljs.core.async.impl.channels.ex_handler; } })().call(null,t); if((else$ == null)){ return buf; } else { return cljs.core.async.impl.protocols.add_BANG_.call(null,buf,else$); } }); cljs.core.async.impl.channels.chan = (function() { var cljs$core$async$impl$channels$chan = null; var cljs$core$async$impl$channels$chan__1 = (function (buf){ return cljs$core$async$impl$channels$chan.call(null,buf,null); }); var cljs$core$async$impl$channels$chan__2 = (function (buf,xform){ return cljs$core$async$impl$channels$chan.call(null,buf,xform,null); }); var cljs$core$async$impl$channels$chan__3 = (function (buf,xform,exh){ return (new cljs.core.async.impl.channels.ManyToManyChannel(cljs.core.async.impl.buffers.ring_buffer.call(null,(32)),(0),cljs.core.async.impl.buffers.ring_buffer.call(null,(32)),(0),buf,false,(function (){var add_BANG_ = (cljs.core.truth_(xform)?xform.call(null,cljs.core.async.impl.protocols.add_BANG_):cljs.core.async.impl.protocols.add_BANG_); return ((function (add_BANG_){ return (function() { var G__30743 = null; var G__30743__1 = (function (buf__$1){ try{return add_BANG_.call(null,buf__$1); }catch (e30741){var t = e30741; return cljs.core.async.impl.channels.handle.call(null,buf__$1,exh,t); }}); var G__30743__2 = (function (buf__$1,val){ try{return add_BANG_.call(null,buf__$1,val); }catch (e30742){var t = e30742; return cljs.core.async.impl.channels.handle.call(null,buf__$1,exh,t); }}); G__30743 = function(buf__$1,val){ switch(arguments.length){ case 1: return G__30743__1.call(this,buf__$1); case 2: return G__30743__2.call(this,buf__$1,val); } throw(new Error('Invalid arity: ' + arguments.length)); }; G__30743.cljs$core$IFn$_invoke$arity$1 = G__30743__1; G__30743.cljs$core$IFn$_invoke$arity$2 = G__30743__2; return G__30743; })() ;})(add_BANG_)) })())); }); cljs$core$async$impl$channels$chan = function(buf,xform,exh){ switch(arguments.length){ case 1: return cljs$core$async$impl$channels$chan__1.call(this,buf); case 2: return cljs$core$async$impl$channels$chan__2.call(this,buf,xform); case 3: return cljs$core$async$impl$channels$chan__3.call(this,buf,xform,exh); } throw(new Error('Invalid arity: ' + arguments.length)); }; cljs$core$async$impl$channels$chan.cljs$core$IFn$_invoke$arity$1 = cljs$core$async$impl$channels$chan__1; cljs$core$async$impl$channels$chan.cljs$core$IFn$_invoke$arity$2 = cljs$core$async$impl$channels$chan__2; cljs$core$async$impl$channels$chan.cljs$core$IFn$_invoke$arity$3 = cljs$core$async$impl$channels$chan__3; return cljs$core$async$impl$channels$chan; })() ; //# sourceMappingURL=channels.js.map?rel=1430425802715
snackycracky/equilibrium
frontend/om-tut/resources/public/js/compiled/out/cljs/core/async/impl/channels.js
JavaScript
epl-1.0
18,525
// Compiled by ClojureScript 1.9.946 {} goog.provide('eckersdorf.events'); goog.require('cljs.core'); goog.require('re_frame.core'); goog.require('taoensso.encore'); goog.require('eckersdorf.csv.core'); re_frame.core.reg_event_fx.call(null,new cljs.core.Keyword(null,"change-url","change-url",-1138899515),(function (_,p__45339){ var vec__45340 = p__45339; var seq__45341 = cljs.core.seq.call(null,vec__45340); var first__45342 = cljs.core.first.call(null,seq__45341); var seq__45341__$1 = cljs.core.next.call(null,seq__45341); var ___$1 = first__45342; var elems = seq__45341__$1; var path = cljs.core.apply.call(null,taoensso.encore.path,cljs.core.into.call(null,new cljs.core.PersistentVector(null, 1, 5, cljs.core.PersistentVector.EMPTY_NODE, ["#/"], null),elems)); return (window["location"] = path); })); //# sourceMappingURL=events.js.map?rel=1510703504121
ribelo/eckersdorf
resources/public/js/out/eckersdorf/events.js
JavaScript
epl-1.0
865
(function(){ 'use strict'; angular .module('talkOrganizerApp') .factory('ParseLinks', ParseLinks); function ParseLinks () { var service = { parse : parse }; return service; function parse(header) { if (header.length === 0) { throw new Error('input must not be of zero length'); } // Split parts by comma var parts = header.split(','); var links = {}; // Parse each part into a named link angular.forEach(parts, function(p) { var section = p.split('>;'); if (section.length !== 2) { throw new Error('section could not be split on ">;"'); } var url = section[0].replace(/<(.*)/, '$1').trim(); var queryString = {}; url.replace( new RegExp('([^?=&]+)(=([^&]*))?', 'g'), function($0, $1, $2, $3) { queryString[$1] = $3; } ); var page = queryString.page; if (angular.isString(page)) { page = parseInt(page); } var name = section[1].replace(/rel="(.*)"/, '$1').trim(); links[name] = page; }); return links; } } })();
BSI-Business-Systems-Integration-AG/demo-jhipster-democamp-2017
jhipster-ide-presentation/TalkOrganizerApp/src/main/webapp/app/components/util/parse-links.service.js
JavaScript
epl-1.0
1,397
(function() { 'use strict'; angular .module('jhappApp') .factory('stateHandler', stateHandler); stateHandler.$inject = ['$rootScope', '$state', '$sessionStorage', '$translate', 'JhiLanguageService', 'translationHandler', '$window', 'Auth', 'Principal', 'VERSION']; function stateHandler($rootScope, $state, $sessionStorage, $translate, JhiLanguageService, translationHandler, $window, Auth, Principal, VERSION) { return { initialize: initialize }; function initialize() { $rootScope.VERSION = VERSION; var stateChangeStart = $rootScope.$on('$stateChangeStart', function (event, toState, toStateParams, fromState) { $rootScope.toState = toState; $rootScope.toStateParams = toStateParams; $rootScope.fromState = fromState; // Redirect to a state with an external URL (http://stackoverflow.com/a/30221248/1098564) if (toState.external) { event.preventDefault(); $window.open(toState.url, '_self'); } if (Principal.isIdentityResolved()) { Auth.authorize(); } // Update the language JhiLanguageService.getCurrent().then(function (language) { $translate.use(language); }); }); var stateChangeSuccess = $rootScope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams) { var titleKey = 'global.title' ; // Set the page title key to the one configured in state or use default one if (toState.data.pageTitle) { titleKey = toState.data.pageTitle; } translationHandler.updateTitle(titleKey); }); $rootScope.$on('$destroy', function () { if(angular.isDefined(stateChangeStart) && stateChangeStart !== null){ stateChangeStart(); } if(angular.isDefined(stateChangeSuccess) && stateChangeSuccess !== null){ stateChangeSuccess(); } }); } } })();
Jose-Badeau/boomslang-examples
boomslang.example.web.jhapp/src/main/webapp/app/blocks/handlers/state.handler.js
JavaScript
epl-1.0
2,312
// Compiled by ClojureScript 0.0-3308 {} goog.provide('clojure.string'); goog.require('cljs.core'); goog.require('goog.string'); goog.require('goog.string.StringBuffer'); clojure.string.seq_reverse = (function clojure$string$seq_reverse(coll){ return cljs.core.reduce.call(null,cljs.core.conj,cljs.core.List.EMPTY,coll); }); clojure.string.re_surrogate_pair = (new RegExp("([\\uD800-\\uDBFF])([\\uDC00-\\uDFFF])","g")); /** * Returns s with its characters reversed. */ clojure.string.reverse = (function clojure$string$reverse(s){ return s.replace(clojure.string.re_surrogate_pair,"$2$1").split("").reverse().join(""); }); /** * Replaces all instance of match with replacement in s. * match/replacement can be: * * string / string * pattern / (string or function of match). */ clojure.string.replace = (function clojure$string$replace(s,match,replacement){ if(typeof match === 'string'){ return s.replace((new RegExp(goog.string.regExpEscape(match),"g")),replacement); } else { if((match instanceof RegExp)){ return s.replace((new RegExp(match.source,"g")),replacement); } else { throw [cljs.core.str("Invalid match arg: "),cljs.core.str(match)].join(''); } } }); /** * Replaces the first instance of match with replacement in s. * match/replacement can be: * * string / string * pattern / (string or function of match). */ clojure.string.replace_first = (function clojure$string$replace_first(s,match,replacement){ return s.replace(match,replacement); }); /** * Returns a string of all elements in coll, as returned by (seq coll), * separated by an optional separator. */ clojure.string.join = (function clojure$string$join(){ var G__6442 = arguments.length; switch (G__6442) { case 1: return clojure.string.join.cljs$core$IFn$_invoke$arity$1((arguments[(0)])); break; case 2: return clojure.string.join.cljs$core$IFn$_invoke$arity$2((arguments[(0)]),(arguments[(1)])); break; default: throw (new Error([cljs.core.str("Invalid arity: "),cljs.core.str(arguments.length)].join(''))); } }); clojure.string.join.cljs$core$IFn$_invoke$arity$1 = (function (coll){ var sb = (new goog.string.StringBuffer()); var coll__$1 = cljs.core.seq.call(null,coll); while(true){ if(coll__$1){ var G__6444 = sb.append([cljs.core.str(cljs.core.first.call(null,coll__$1))].join('')); var G__6445 = cljs.core.next.call(null,coll__$1); sb = G__6444; coll__$1 = G__6445; continue; } else { return sb.toString(); } break; } }); clojure.string.join.cljs$core$IFn$_invoke$arity$2 = (function (separator,coll){ var sb = (new goog.string.StringBuffer()); var coll__$1 = cljs.core.seq.call(null,coll); while(true){ if(coll__$1){ sb.append([cljs.core.str(cljs.core.first.call(null,coll__$1))].join('')); var coll__$2 = cljs.core.next.call(null,coll__$1); if((coll__$2 == null)){ } else { sb.append(separator); } var G__6446 = sb; var G__6447 = coll__$2; sb = G__6446; coll__$1 = G__6447; continue; } else { return sb.toString(); } break; } }); clojure.string.join.cljs$lang$maxFixedArity = 2; /** * Converts string to all upper-case. */ clojure.string.upper_case = (function clojure$string$upper_case(s){ return s.toUpperCase(); }); /** * Converts string to all lower-case. */ clojure.string.lower_case = (function clojure$string$lower_case(s){ return s.toLowerCase(); }); /** * Converts first character of the string to upper-case, all other * characters to lower-case. */ clojure.string.capitalize = (function clojure$string$capitalize(s){ if((cljs.core.count.call(null,s) < (2))){ return clojure.string.upper_case.call(null,s); } else { return [cljs.core.str(clojure.string.upper_case.call(null,cljs.core.subs.call(null,s,(0),(1)))),cljs.core.str(clojure.string.lower_case.call(null,cljs.core.subs.call(null,s,(1))))].join(''); } }); clojure.string.pop_last_while_empty = (function clojure$string$pop_last_while_empty(v){ var v__$1 = v; while(true){ if(cljs.core._EQ_.call(null,"",cljs.core.peek.call(null,v__$1))){ var G__6448 = cljs.core.pop.call(null,v__$1); v__$1 = G__6448; continue; } else { return v__$1; } break; } }); clojure.string.discard_trailing_if_needed = (function clojure$string$discard_trailing_if_needed(limit,v){ if(cljs.core._EQ_.call(null,(0),limit)){ return clojure.string.pop_last_while_empty.call(null,v); } else { return v; } }); clojure.string.split_with_empty_regex = (function clojure$string$split_with_empty_regex(s,limit){ if(((limit <= (0))) || ((limit >= ((2) + cljs.core.count.call(null,s))))){ return cljs.core.conj.call(null,cljs.core.vec.call(null,cljs.core.cons.call(null,"",cljs.core.map.call(null,cljs.core.str,cljs.core.seq.call(null,s)))),""); } else { var pred__6452 = cljs.core._EQ_; var expr__6453 = limit; if(cljs.core.truth_(pred__6452.call(null,(1),expr__6453))){ return (new cljs.core.PersistentVector(null,1,(5),cljs.core.PersistentVector.EMPTY_NODE,[s],null)); } else { if(cljs.core.truth_(pred__6452.call(null,(2),expr__6453))){ return (new cljs.core.PersistentVector(null,2,(5),cljs.core.PersistentVector.EMPTY_NODE,["",s],null)); } else { var c = (limit - (2)); return cljs.core.conj.call(null,cljs.core.vec.call(null,cljs.core.cons.call(null,"",cljs.core.subvec.call(null,cljs.core.vec.call(null,cljs.core.map.call(null,cljs.core.str,cljs.core.seq.call(null,s))),(0),c))),cljs.core.subs.call(null,s,c)); } } } }); /** * Splits string on a regular expression. Optional argument limit is * the maximum number of splits. Not lazy. Returns vector of the splits. */ clojure.string.split = (function clojure$string$split(){ var G__6456 = arguments.length; switch (G__6456) { case 2: return clojure.string.split.cljs$core$IFn$_invoke$arity$2((arguments[(0)]),(arguments[(1)])); break; case 3: return clojure.string.split.cljs$core$IFn$_invoke$arity$3((arguments[(0)]),(arguments[(1)]),(arguments[(2)])); break; default: throw (new Error([cljs.core.str("Invalid arity: "),cljs.core.str(arguments.length)].join(''))); } }); clojure.string.split.cljs$core$IFn$_invoke$arity$2 = (function (s,re){ return clojure.string.split.call(null,s,re,(0)); }); clojure.string.split.cljs$core$IFn$_invoke$arity$3 = (function (s,re,limit){ return clojure.string.discard_trailing_if_needed.call(null,limit,((cljs.core._EQ_.call(null,[cljs.core.str(re)].join(''),"/(?:)/"))?clojure.string.split_with_empty_regex.call(null,s,limit):(((limit < (1)))?cljs.core.vec.call(null,[cljs.core.str(s)].join('').split(re)):(function (){var s__$1 = s; var limit__$1 = limit; var parts = cljs.core.PersistentVector.EMPTY; while(true){ if(cljs.core._EQ_.call(null,limit__$1,(1))){ return cljs.core.conj.call(null,parts,s__$1); } else { var temp__4421__auto__ = cljs.core.re_find.call(null,re,s__$1); if(cljs.core.truth_(temp__4421__auto__)){ var m = temp__4421__auto__; var index = s__$1.indexOf(m); var G__6458 = s__$1.substring((index + cljs.core.count.call(null,m))); var G__6459 = (limit__$1 - (1)); var G__6460 = cljs.core.conj.call(null,parts,s__$1.substring((0),index)); s__$1 = G__6458; limit__$1 = G__6459; parts = G__6460; continue; } else { return cljs.core.conj.call(null,parts,s__$1); } } break; } })()))); }); clojure.string.split.cljs$lang$maxFixedArity = 3; /** * Splits s on * or * . */ clojure.string.split_lines = (function clojure$string$split_lines(s){ return clojure.string.split.call(null,s,/\n|\r\n/); }); /** * Removes whitespace from both ends of string. */ clojure.string.trim = (function clojure$string$trim(s){ return goog.string.trim(s); }); /** * Removes whitespace from the left side of string. */ clojure.string.triml = (function clojure$string$triml(s){ return goog.string.trimLeft(s); }); /** * Removes whitespace from the right side of string. */ clojure.string.trimr = (function clojure$string$trimr(s){ return goog.string.trimRight(s); }); /** * Removes all trailing newline \n or return \r characters from * string. Similar to Perl's chomp. */ clojure.string.trim_newline = (function clojure$string$trim_newline(s){ var index = s.length; while(true){ if((index === (0))){ return ""; } else { var ch = cljs.core.get.call(null,s,(index - (1))); if((cljs.core._EQ_.call(null,ch,"\n")) || (cljs.core._EQ_.call(null,ch,"\r"))){ var G__6461 = (index - (1)); index = G__6461; continue; } else { return s.substring((0),index); } } break; } }); /** * True is s is nil, empty, or contains only whitespace. */ clojure.string.blank_QMARK_ = (function clojure$string$blank_QMARK_(s){ return goog.string.isEmptySafe(s); }); /** * Return a new string, using cmap to escape each character ch * from s as follows: * * If (cmap ch) is nil, append ch to the new string. * If (cmap ch) is non-nil, append (str (cmap ch)) instead. */ clojure.string.escape = (function clojure$string$escape(s,cmap){ var buffer = (new goog.string.StringBuffer()); var length = s.length; var index = (0); while(true){ if(cljs.core._EQ_.call(null,length,index)){ return buffer.toString(); } else { var ch = s.charAt(index); var temp__4421__auto___6462 = cljs.core.get.call(null,cmap,ch); if(cljs.core.truth_(temp__4421__auto___6462)){ var replacement_6463 = temp__4421__auto___6462; buffer.append([cljs.core.str(replacement_6463)].join('')); } else { buffer.append(ch); } var G__6464 = (index + (1)); index = G__6464; continue; } break; } }); //# sourceMappingURL=string.js.map
divs1210/snake-machine
out/clojure/string.js
JavaScript
epl-1.0
9,230
Ext.define('Rd.view.accessProviders.winApAddWizard', { extend: 'Ext.window.Window', alias : 'widget.winApAddWizard', closable: true, draggable: false, resizable: false, title: i18n('sNew_Access_Provider'), width: 400, height: 400, plain: true, border: false, layout: 'card', iconCls: 'add', glyph: Rd.config.icnAdd, autoShow: false, defaults: { border: false }, no_tree: false, //If the user has no children we don't bother giving them a branchless tree user_id: '', owner: '', urlCheckbox: '/cake2/rd_cake/access_providers/record_activity_checkbox.json', startScreen: 'scrnApTree', //Default start screen requires: [ 'Ext.layout.container.Card', 'Ext.form.Panel', 'Ext.form.field.Text', 'Ext.form.FieldContainer', 'Ext.form.field.Radio' ], initComponent: function() { var me = this; var scrnApTree = me.mkScrnApTree(); var scrnData = me.mkScrnData(); me.items = [ scrnApTree, scrnData ]; this.callParent(arguments); me.getLayout().setActiveItem(me.startScreen); }, //____ AccessProviders tree SCREEN ____ mkScrnApTree: function(){ var pnlTree = Ext.create('Rd.view.components.pnlAccessProvidersTree',{ itemId: 'scrnApTree' }); return pnlTree; }, //_______ Data for Access Provider _______ mkScrnData: function(){ var me = this; var aCb = Ext.create('Rd.view.components.ajaxCheckbox',{ 'url' : me.urlCheckbox, fieldLabel : i18n('sRecord_all_acivity'), name : 'monitor', inputValue : 'monitor', checked : true, boxLabelCls : 'lblRd' }); var frmData = Ext.create('Ext.form.Panel',{ border: false, layout: 'fit', itemId: 'scrnData', autoScroll: true, fieldDefaults: { msgTarget : 'under', labelClsExtra: 'lblRd', labelAlign : 'left', labelSeparator: '', labelClsExtra: 'lblRd', labelWidth : Rd.config.labelWidth, maxWidth : Rd.config.maxWidth, margin : Rd.config.fieldMargin }, defaultType: 'textfield', buttons : [ { itemId: 'btnDetailPrev', text: i18n('sPrev'), scale: 'large', iconCls: 'b-prev', glyph : Rd.config.icnBack, margin: Rd.config.buttonMargin }, { itemId: 'save', text: i18n('sOK'), scale: 'large', iconCls: 'b-btn_ok', glyph: Rd.config.icnNext, formBind: true, margin: Rd.config.buttonMargin } ], items:[ { xtype : 'tabpanel', layout : 'fit', xtype : 'tabpanel', margins : '0 0 0 0', plain : true, tabPosition: 'bottom', border : false, items : [ { 'title' : i18n('sRequired_info'), 'layout' : 'anchor', itemId : 'tabRequired', defaults : { anchor: '100%' }, items : [ { itemId : 'parent_id', xtype : 'textfield', name : "parent_id", value : me.user_id, hidden : true }, { itemId : 'owner', xtype : 'displayfield', fieldLabel : i18n('sOwner'), value : me.owner, labelClsExtra: 'lblRdReq' }, { xtype : 'textfield', fieldLabel : i18n('sUsername'), name : "username", allowBlank :false, blankText : i18n("sEnter_a_value"), labelClsExtra: 'lblRdReq' }, { xtype : 'textfield', fieldLabel : i18n('sPassword'), name : "password", allowBlank :false, blankText : i18n("sEnter_a_value"), labelClsExtra: 'lblRdReq' }, { xtype : 'cmbLanguages', width : 350, fieldLabel : i18n('sLanguage'), name : 'language', allowBlank : false, labelClsExtra: 'lblRdReq' }, { xtype : 'checkbox', fieldLabel : i18n('sActivate'), name : 'active', inputValue : 'active', checked : true, boxLabelCls : 'lblRd' }, aCb //Ajax checkbox - state depends on the rights of the AP and their own record activity setting ] }, { 'title' : i18n('sOptional_info'), 'layout' : 'anchor', itemId : 'tabOptional', defaults : { anchor: '100%' }, items : [ { xtype : 'textfield', fieldLabel : i18n('sName'), name : "name" }, { xtype : 'textfield', fieldLabel : i18n('sSurname'), name : "surname" }, { xtype : 'textfield', fieldLabel : i18n('sPhone'), name : "phone", vtype : 'Numeric' }, { xtype : 'textfield', fieldLabel : i18n('s_email'), name : "email", vtype : 'email' }, { xtype : 'textareafield', grow : true, name : 'address', fieldLabel: i18n('sAddress'), anchor : '100%' } ] } ] } ] }); return frmData; } });
smartwifi/stores-rd
rd/app/view/accessProviders/winApAddWizard.js
JavaScript
gpl-2.0
8,682
/** * Register controller * @namespace blog.authentication.controllers */ (function () { 'use strict'; angular .module('blog.authentication.controllers') .controller('RegisterController', RegisterController); RegisterController.$inject = ['$location', '$scope', '$http', 'Authentication']; /** * @namespace RegisterController */ function RegisterController($location, $scope, $http, Authentication) { var vm = this; vm.register = register; activate(); /** * @name activate * @desc Actions to be performed when this controller is instantiated * @memberOf blog.authentication.controllers.RegisterController */ function activate() { // If the user is authenticated, they should not be here. if (Authentication.isAuthenticated()) { $location.url('/'); } } /** * @name register * @desc Try to register a new user * @param {string} email The email entered by the user * @param {string} password The password entered by the user * @param {string} username The username entered by the user * @returns {Promise} * @memberOf blog.authentication.services.Authentication */ function register(email, password, username) { return $http.post('/api/v1/accounts/', { username: username, password: password, email: email }).then(registerSuccessFn, registerErrorFn); /** * @name registerSuccessFn * @desc Log the new user in */ function registerSuccessFn(data, status, headers, config) { Authentication.login(email, password); } /** * @name registerErrorFn * @desc Log "Epic failure!" to the console */ function registerErrorFn(data, status, headers, config) { console.error('Epic failure!'); } } } })();
DaniilLeksin/theblog
static/javascripts/authentication/controllers/register.controller.js
JavaScript
gpl-2.0
1,745
Sourcemash.Views.ProfileView = Backbone.View.extend({ template: JST['profile'], initialize: function(options) { this.listenTo(this.model, 'change', this.render); }, events: { "click #delete-user": 'deleteUser', "click #toggle-suggested-content": 'toggleShowSuggestedContent' }, render: function() { var content = this.template({model: this.model}); this.$el.html(content); return this; }, deleteUser: function() { this.model.destroy(); mixpanel.track("Deleted account"); }, toggleShowSuggestedContent: function() { this.model.save({'show_suggested_content': !this.model.get('show_suggested_content')}, {success: this.showContentToggled}); }, showContentToggled: function(user) { if (user.get('show_suggested_content')) { toast("Suggested content will be shown!", 3000); mixpanel.track("Enabled Suggested Content") } else { toast("Suggested content will no longer be shown.", 3000); mixpanel.track("Disabled Suggested Content") } } });
sourcemash/Sourcemash
sourcemash/frontend/static/js/views/profile_view.js
JavaScript
gpl-2.0
1,060
jQuery(document).ready(function() { jQuery('.slides').cycle({ fx: 'fade', speed: 500, timeout: 6000, pager: '.slidenav', pagerEvent: 'click', pauseOnPagerHover: true, pause: true }) });
mereszpingvin/skodaklub
sites/all/themes/skodaklubcom_sablon/js/utility.js
JavaScript
gpl-2.0
255
'use strict'; var COMMENT_TEXT = 'commenttext'; var COMMENT_EDITTYPE = 'commentedittype'; var DISPLAY_COMMENT_BLANK = 'Please enter a valid comment. The comment can\'t be empty.'; $(document).ready(function() { // Auto-loading for feedback responses $('div[id^="studentFeedback-"]').click(); $('a[id^="visibility-options-trigger"]').click(function() { var visibilityOptions = $(this).parent().next(); if (visibilityOptions.is(':visible')) { visibilityOptions.hide(); $(this).html('<span class="glyphicon glyphicon-eye-close"></span> Show Visibility Options'); } else { visibilityOptions.show(); $(this).html('<span class="glyphicon glyphicon-eye-close"></span> Hide Visibility Options'); } }); $('.panel-heading.student_feedback').click(toggleSingleCollapse); $('input[type=checkbox]').click(function(e) { var table = $(this).closest('table'); var form = table.closest('form'); var visibilityOptions = []; var target = $(e.target); var visibilityOptionsRow = target.closest('tr'); if (target.prop('class').includes('answerCheckbox') && !target.prop('checked')) { visibilityOptionsRow.find('input[class*=giverCheckbox]').prop('checked', false); visibilityOptionsRow.find('input[class*=recipientCheckbox]').prop('checked', false); } if ((target.prop('class').includes('giverCheckbox') || target.prop('class').includes('recipientCheckbox')) && target.prop('checked')) { visibilityOptionsRow.find('input[class*=answerCheckbox]').prop('checked', true); } table.find('.answerCheckbox:checked').each(function() { visibilityOptions.push($(this).val()); }); form.find('input[name="showcommentsto"]').val(visibilityOptions.join(', ')); visibilityOptions = []; table.find('.giverCheckbox:checked').each(function() { visibilityOptions.push($(this).val()); }); form.find('input[name="showgiverto"]').val(visibilityOptions.join(', ')); visibilityOptions = []; table.find('.recipientCheckbox:checked').each(function() { visibilityOptions.push($(this).val()); }); form.find('input[name="showrecipientto"]').val(visibilityOptions.join(', ')); }); readyStudentRecordsPage(); }); /** * To be loaded when instructorStudentRecords page is loaded * Contains key bindings, text area adjustment and auto-opening * of comment box if the request parameter asks for it */ function readyStudentRecordsPage() { // Bind form submission to check for blank comment field $('form.form_comment').submit(function() { return checkComment(this); }); // Adjust size of each text area, except the new comment area $('textarea').each(function() { if (!$(this).attr('placeholder')) { textAreaAdjust(this); } }); // Open the comment box if so desired by the request if (showCommentBox === 'yes') { $('#button_add_comment').click(); } } /** * Do the comment edit form submission * Currently done this way because the link is placed on a different column */ function submitCommentForm(commentIdx) { if ($('#' + COMMENT_EDITTYPE + '-' + commentIdx).val() !== 'delete') { tinymce.get('commentText' + commentIdx).save(); $('input[name=commentText' + commentIdx + ']').attr('name', 'commenttext'); } $('#form_commentedit-' + commentIdx).submit(); return false; } /** * Check the submitted comment text field of the form * Blanks are not allowed. */ function checkComment(form) { var formTextField; if ($(form).find('[id^=' + COMMENT_EDITTYPE + ']').val() === 'delete') { return true; } if ($(form).attr('name') === 'form_commentadd') { formTextField = tinymce.get(COMMENT_TEXT).getContent(); } else { var editorId = $(form).attr('id').match(/^form_commentedit-(\d+)$/)[1]; formTextField = tinymce.get('commentText' + editorId).getContent(); } if (isBlank(formTextField)) { setStatusMessage(DISPLAY_COMMENT_BLANK, StatusType.DANGER); scrollToTop(); return false; } } /** * Show the comment box, focus comment text area and hide "Add Comment link" */ function showAddCommentBox() { $('#comment_box').show(); if (typeof richTextEditorBuilder !== 'undefined') { /* eslint-disable camelcase */ // The property names are determined by external library (tinymce) richTextEditorBuilder.initEditor('#commenttext', { inline: true, fixed_toolbar_container: '#rich-text-toolbar-comment-container' }); /* eslint-enable camelcase */ } } function hideAddCommentBox() { $('#comment_box').hide(); } /** * Enable the comment form indicated by index, * disables the others */ function enableEdit(commentIdx, maxComments) { var i = 1; while (i <= maxComments) { if (commentIdx === i) { enableComment(i); } else { disableComment(i); } i++; } return false; } function enableComment(commentIdx) { $('#commentBar-' + commentIdx).hide(); $('#plainCommentText' + commentIdx).hide(); $('div[id="commentTextEdit' + commentIdx + '"]').show(); if (typeof richTextEditorBuilder !== 'undefined') { /* eslint-disable camelcase */ // The property names are determined by external library (tinymce) richTextEditorBuilder.initEditor('#commentText' + commentIdx, { inline: true, fixed_toolbar_container: '#rich-text-toolbar-comment-container-' + commentIdx }); /* eslint-enable camelcase */ } } function disableComment(commentIdx) { $('#commentBar-' + commentIdx).show(); $('#plainCommentText' + commentIdx).show(); $('div[id="commentTextEdit' + commentIdx + '"]').hide(); } function textAreaAdjust(o) { var height = o.scrollHeight + 5; o.style.height = height + 'px'; } /** * Pops up confirmation modal whether to delete specified comment * @param comment index * @returns */ function deleteComment(commentIdx) { var messageText = 'Are you sure you want to delete this comment?'; var okCallback = function() { document.getElementById(COMMENT_EDITTYPE + '-' + commentIdx).value = 'delete'; return submitCommentForm(commentIdx); }; BootboxWrapper.showModalConfirmation('Confirm Deletion', messageText, okCallback, null, BootboxWrapper.DEFAULT_OK_TEXT, BootboxWrapper.DEFAULT_CANCEL_TEXT, StatusType.WARNING); return false; } function loadFeedbackSession(courseId, stuEmail, user, fsName, sender) { $('.tooltip').hide(); var targetDiv = $(sender).find('div[id^="target-feedback-"]'); var fsNameForUrl = encodeURIComponent(fsName); var url = '/page/instructorStudentRecordsAjaxPage?courseid=' + courseId + '&studentemail=' + stuEmail + '&user=' + user + '&fsname=' + fsNameForUrl; $(sender).find('div[class^="placeholder-img-loading"]').html('<img src="/images/ajax-loader.gif">'); targetDiv.load(url, function(response, status) { if (status === 'success') { $(sender).removeAttr('onclick'); } $(sender).find('div[class^="placeholder-img-loading"]').html(''); }); }
nockc/teammates
src/main/webapp/js/instructorStudentRecords.js
JavaScript
gpl-2.0
7,523
window.txl_map = {}; /** * show address on map based on pre-provided address coordinates * no need to send request outside to ask for coordinates */ window.txl_map.show_map_at_coordinates = function( target_element_id, latitude, longitude, marker_icon, map_styles ) { var myLatlng = new google.maps.LatLng( latitude, longitude ); var map_options = { zoom: 12, center: myLatlng }; if ( map_styles ) { map_options.styles = map_styles; } var target = document.getElementById(target_element_id); if ( ! parseInt( window.getComputedStyle( target, null ).getPropertyValue( "height" ) ) ) { target.style.minHeight = "300px"; } var map = new google.maps.Map( target, map_options ); var marker = new google.maps.Marker( { position: myLatlng, map: map, icon: marker_icon } ); }; /** * take address information as params then send request to google to ask for address coordinates * then show address on map */ window.txl_map.ajax_gen_map = function( target_element_id, location, success_callback, error_callback, marker_icon, map_styles ) { var loc_string = location.street_number + ' ' + location.street + ', ' + location.city + ', ' + location.state + ', ' + location.country; //replace multiple spaces with single one loc_string = loc_string.replace( / +/g, " " ); var geocoder = new google.maps.Geocoder(); geocoder.geocode( { 'address': loc_string }, function( results, status ) { if (status == google.maps.GeocoderStatus.OK) { var latitude = results[0].geometry.location.lat(); var longitude = results[0].geometry.location.lng(); if ( success_callback ) { success_callback( latitude, longitude ); } window.txl_map.show_map_at_coordinates( target_element_id, latitude, longitude, marker_icon, map_styles ); } else { if ( error_callback ) { error_callback(); } } }); }; jQuery( document ).ready( function( $ ) { $( '.geocoder' ).on( 'click', function() { var prefix = 'txp_property_'; var street_number = $('[name=' + prefix + 'address_street_number]').val(), street = $('[name=' + prefix + 'address_street]').val(), city = $('[name=' + prefix + 'address_city]').val(), state = $('[name=' + prefix + 'address_state]').val(), country = $('[name=' + prefix + 'address_country').val(); var location = { street_number : street_number, street : street, city : city, state : state, country : country }; window.txl_map.ajax_gen_map( 'map-canvas', location, function(latitude, longitude) { $('[name=' + prefix + 'address_coordinates]').val(latitude + ',' + longitude); $('.map td').html('<div id="map-canvas" style="height:450px;width:100%;"></div>'); $(".map").show(); }, function() { $('.map td').html('<div id="map-canvas">Location not found.</div>'); $(".map").show(); } ); return false; } ); } );
wp-plugins/trexanh-property
assets/js/geocode.js
JavaScript
gpl-2.0
3,220
var parallax = { animationFrameHandler: null, layerOne: $(".parallax_under"), layerTwo: $(".parallax_over"), pageWidth : $(window).width(), pageHeight : $(window).height(), midpoint: { x: window.innerWidth/2, y: window.innerHeight/2 }, limit: { x: 20, y: 20 , device:{ x:30, y:35 } }, target: { x: 0, y: 0 }, curPos: { x: 0, y: 0 }, isMobile: false, easing: 0.1, init: function() { this.isMobile = navigator.userAgent.match(/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i) ? true : false; var self = this; if(this.isMobile && window.DeviceOrientationEvent) { window.addEventListener('deviceorientation', function(eventData){self.deviceMove(eventData)}, false); this.limit.x = this.limit.device.x; this.limit.y = this.limit.device.y; }else{ $('.promo-image').on('mousemove', $.proxy(this.mouseMove,this)); } this.sizePage(); this.render(); $(window).resize($.proxy(this.sizePage, this)); }, sizePage: function () { this.layerOne[0].style.position = "absolute"; this.layerOne[0].style.width = 100 + this.limit.x + "%"; this.layerOne[0].style.height = 100 + this.limit.y + "%"; this.layerOne[0].style.left = -this.limit.x/2+'%'; this.layerOne[0].style.top = -this.limit.y/2+'%'; this.layerTwo[0].style.width = 100 + this.limit.x + "%"; this.layerTwo[0].style.height = 100 + this.limit.y + "%"; }, mouseMove: function (e) { this.target.x = -(e.clientX - this.midpoint.x) / this.limit.x; this.target.y = -(e.clientY - this.midpoint.y) / this.limit.y; }, deviceMove: function (a) { this.target.x = a.gamma * 2; this.target.y = a.beta * 3; }, update:function(){ this.curPos.x += (this.target.x - this.curPos.x) * this.easing; this.curPos.y += (this.target.y - this.curPos.y) * this.easing; this.draw(); }, draw: function(){ TweenLite.set(this.layerOne, { x:this.curPos.x, y:this.curPos.y, }); TweenLite.set(this.layerTwo, { x:-this.curPos.x, y:-this.curPos.y, }); }, render: function(){ var self = this; this.update(); this.animationFrameHandler = window.requestAnimationFrame(function () { self.render(); }); }, shutdown : function () { window.cancelAnimationFrame(this.animationFrameHandler); } }; $(document).ready(function(){ parallax.init(); });
sunri5e/invertpictures.com
wp-content/themes/invert-pictures/js/parallax.js
JavaScript
gpl-2.0
3,073
var _ = require("underscore"), config = require("../config/config-" + process.env.NODE_ENV), tools = require("./tools"), redis = require("redis"), redisClient = redis.createClient(config.cache.port, config.cache.url ,{}); var session = { sessionManager: function(req, res, next){ // Try to retrieve token from body var token = req.body.token; // If no body is present, generate a new one token = token || tools.guid(); // Get session that is stored with that token redisClient.get(token, function(err, userSession){ // Store session in the "request" variable, in case something exists // We are storing it serialized! req.session = JSON.parse(userSession) || {}; // Store the token (useful when it has just been generated) req.session.__token = token; // Add function for session storage req.session.store = function(data, callback){ // Add to the session the new created object _.extend(req.session, data); // Clone with events and deeply var sessionToStore = _(req.session).clone(true, true); // Delete the function, as we don't want it to be stores in Redis delete sessionToStore.store; // Store the sessiojn object as it is now // We are storing it serialized! redisClient.set(req.session.__token, JSON.stringify(sessionToStore), function(){ if(callback){ callback({token: req.session.__token, data: req.session}); } }); }; // Continue execution next(); }); } }; module.exports = session;
jmescuderojustel/nodejs-tdd-base
source/server/common/session.js
JavaScript
gpl-2.0
1,863
/** * External dependencies */ import PropTypes from 'prop-types'; /** * WordPress dependencies */ import { useContext } from '@wordpress/element'; import { __, sprintf } from '@wordpress/i18n'; /** * Internal dependencies */ import { Options } from '../components/options-context-provider'; import { AMPDrawer } from '../components/amp-drawer'; import { AMPNotice, NOTICE_TYPE_INFO, NOTICE_SIZE_LARGE } from '../components/amp-notice'; import { STANDARD } from '../common/constants'; /** * @typedef {{name: string, slug: string, type: string}} Source * @typedef {{query_var: string[], path_suffix: string[], legacy_transitional: string[], legacy_reader: string[], custom: string[]}} PairedUrlExamplesData */ /** * Paired URL examples. * * @param {Object} props Component props. * @param {?Array} props.pairedUrls Paired URLs. */ const PairedUrlExamples = ( { pairedUrls } ) => { if ( ! pairedUrls ) { return null; } return ( <details className="amp-paired-url-examples"> <summary> { __( 'Examples', 'amp' ) } </summary> { pairedUrls.map( ( pairedUrl ) => { return ( <div className="amp-paired-url-example" key={ pairedUrl }> <code> { pairedUrl } </code> </div> ); } ) } </details> ); }; PairedUrlExamples.propTypes = { pairedUrls: PropTypes.arrayOf( PropTypes.string ), }; /** * Get custom paired structure sources. * * @param {Array.<Source>} sources Sources. * @return {string} Sources string. */ function getCustomPairedStructureSources( sources ) { let message = __( 'The custom structure is being introduced by:', 'amp' ) + ' '; message += sources.map( ( source ) => { let sourceString = source.name || source.slug; let typeString; switch ( source.type ) { case 'plugin': typeString = __( 'a plugin', 'amp' ); break; case 'theme': typeString = __( 'a theme', 'amp' ); break; case 'mu-plugin': typeString = __( 'a must-use plugin', 'amp' ); break; default: typeString = null; } if ( typeString ) { sourceString += ` (${ typeString })`; } return sourceString; } ).join( ', ' ) + '.'; return message; } /** * Slug conflicts notice. * * @param {Object} props Component props. * @param {string} props.slug Slug. * @param {Object} props.conflicts Conflicts. */ function SlugConflictsNotice( { slug, conflicts } ) { return ( <AMPNotice size={ NOTICE_SIZE_LARGE } type={ NOTICE_TYPE_INFO }> <p> { sprintf( /* translators: %s is the AMP slug */ __( 'There are one or more entities that are already using the “%s” URL slug. For this reason, you cannot currently use the path suffix or legacy reader paired URL structures. See below for the source of the slug conflict(s):', 'amp' ), slug, ) } </p> <ul> { conflicts.posts && ( conflicts.posts.map( ( entity ) => ( <li key={ `post-${ entity.id }` }> { entity.edit_link ? ( <a href={ entity.edit_link } target="_blank" rel="noreferrer"> { entity.label || entity.post_type } </a> ) : ( entity.label || entity.post_type ) } { entity.title && ( ': ' + entity.title ) } { ' ' } <small> { /* translators: %d is entity ID */ sprintf( __( '(ID: %d)', 'amp' ), entity.id ) } </small> </li> ) ) ) } { conflicts.terms && ( conflicts.terms.map( ( entity ) => ( <li key={ `term-${ entity.id }` }> { entity.edit_link ? ( <a href={ entity.edit_link } target="_blank" rel="noreferrer"> { entity.label || entity.taxonomy } </a> ) : ( entity.label || entity.taxonomy ) } { entity.name && ( ': ' + entity.name ) } { ' ' } <small> { /* translators: %d is entity ID */ sprintf( __( '(ID: %d)', 'amp' ), entity.id ) } </small> </li> ) ) ) } { conflicts.user && ( <li> { conflicts.user.edit_link ? ( <a href={ conflicts.user.edit_link } target="_blank" rel="noreferrer"> { __( 'User', 'amp' ) } </a> ) : ( __( 'User', 'amp' ) ) } { ': ' + conflicts.user.name } { ' ' } <small> { /* translators: %d is entity ID */ sprintf( __( '(ID: %d)', 'amp' ), conflicts.user.id ) } </small> </li> ) } { conflicts.post_type && ( <li> { sprintf( /* translators: %s is post type label */ __( 'Post type: %s', 'amp' ), conflicts.post_type.label || '--', ) } { ' ' } <small> { /* translators: %s is entity name */ sprintf( __( '(name: %s)', 'amp' ), conflicts.post_type.name ) } </small> </li> ) } { conflicts.taxonomy && ( <li> { sprintf( /* translators: %s is taxonomy label */ __( 'Taxonomy: %s', 'amp' ), conflicts.taxonomy.label || '--', ) } { ' ' } <small> { /* translators: %s is entity name */ sprintf( __( '(name: %s)', 'amp' ), conflicts.taxonomy.name ) } </small> </li> ) } { conflicts.rewrite && ( <li> { __( 'Rewrite rules: ', 'amp' ) } { conflicts.rewrite .map( ( entity ) => ( <code key={ entity }> { entity } </code> ) ) .reduce( ( prev, curr ) => [ prev, ', ', curr ] ) } </li> ) } </ul> </AMPNotice> ); } SlugConflictsNotice.propTypes = { slug: PropTypes.string.isRequired, conflicts: PropTypes.shape( { post_type: PropTypes.shape( { name: PropTypes.string.isRequired, label: PropTypes.string, } ), posts: PropTypes.arrayOf( PropTypes.shape( { id: PropTypes.number.isRequired, edit_link: PropTypes.string, label: PropTypes.string, post_type: PropTypes.string.isRequired, title: PropTypes.string, } ) ), rewrite: PropTypes.arrayOf( PropTypes.string ), taxonomy: PropTypes.shape( { name: PropTypes.string.isRequired, label: PropTypes.string, } ), terms: PropTypes.arrayOf( PropTypes.shape( { id: PropTypes.number.isRequired, edit_link: PropTypes.string, label: PropTypes.string, taxonomy: PropTypes.string.isRequired, name: PropTypes.string, } ) ), user: PropTypes.shape( { id: PropTypes.number.isRequired, edit_link: PropTypes.string, name: PropTypes.string.isRequired, } ), } ).isRequired, }; /** * Component rendering the paired URL structure. * * @param {Object} props Component props. * @param {string} props.focusedSection Focused section. */ export function PairedUrlStructure( { focusedSection } ) { /** @type {{amp_slug:string, endpoint_path_slug_conflicts:Array, custom_paired_endpoint_sources:Array.<Source>, paired_url_examples: PairedUrlExamplesData, rewrite_using_permalinks: boolean}} editedOptions */ const { editedOptions, updateOptions } = useContext( Options ); const { theme_support: themeSupport } = editedOptions || {}; // Don't show if the mode is standard or the themeSupport is not yet set. if ( ! themeSupport || STANDARD === themeSupport ) { return null; } const slug = editedOptions.amp_slug; const isCustom = 'custom' === editedOptions.paired_url_structure; const endpointSuffixAvailable = editedOptions.endpoint_path_slug_conflicts === null; return ( <AMPDrawer className="amp-paired-url-structure" heading={ ( <h3> { __( 'Paired URL Structure', 'amp' ) } </h3> ) } hiddenTitle={ __( 'Paired URL Structure', 'amp' ) } id="paired-url-structure" initialOpen={ 'paired-url-structure' === focusedSection } > { isCustom && ( <AMPNotice size={ NOTICE_SIZE_LARGE } type={ NOTICE_TYPE_INFO }> <p> { __( 'A custom paired URL structure is being applied so the following options are unavailable.', 'amp' ) } { editedOptions.custom_paired_endpoint_sources.length > 0 && ' ' + getCustomPairedStructureSources( editedOptions.custom_paired_endpoint_sources ) } </p> <PairedUrlExamples pairedUrls={ editedOptions.paired_url_examples.custom } /> </AMPNotice> ) } <p dangerouslySetInnerHTML={ { __html: sprintf( /* translators: 1: AMP Paired URL Structure documentation URL */ __( 'When using the Transitional or Reader template modes, your site is in a “Paired AMP” configuration. Your site\'s canonical URLs are non-AMP, and the separate AMP versions of your pages have AMP-specific URLs. The structure of a paired AMP URL is not important, whether using a query parameter or path suffix. The use of a query parameter is the most compatible across various sites and it has the benefit of not resulting in a 404 if the AMP plugin is deactivated. <em>Note: Changing the paired URL structure can cause AMP pages to temporarily disappear from search results until your site is re-indexed.</em> If you\'re migrating from another AMP plugin with a different paired URL structure, then you may want to change this setting. Otherwise we recommend leaving it as is. <a href="%1$s" target="_blank">Learn more</a>', 'amp' ), __( 'https://amp-wp.org/?p=10004', 'amp' ), ), } } /> { ! endpointSuffixAvailable && ( <SlugConflictsNotice slug={ slug } conflicts={ editedOptions.endpoint_path_slug_conflicts } /> ) } <ul> <li> <input id="paired_url_structure_query_var" type="radio" name="paired_url_structure" checked={ 'query_var' === editedOptions.paired_url_structure } onChange={ () => { updateOptions( { paired_url_structure: 'query_var' } ); } } disabled={ isCustom } /> <label htmlFor="paired_url_structure_query_var"> { __( 'Query parameter', 'amp' ) + ': ' } <code> { `?${ slug }=1` } </code> { ' ' } <em> { __( '(default)', 'amp' ) } </em> </label> <PairedUrlExamples pairedUrls={ editedOptions.paired_url_examples.query_var } /> </li> <li> <input id="paired_url_structure_path_suffix" type="radio" name="paired_url_structure" checked={ 'path_suffix' === editedOptions.paired_url_structure } onChange={ () => { updateOptions( { paired_url_structure: 'path_suffix' } ); } } disabled={ isCustom || ! endpointSuffixAvailable || ! editedOptions.rewrite_using_permalinks } /> <label htmlFor="paired_url_structure_path_suffix"> { __( 'Path suffix', 'amp' ) + ': ' } <code> { `/${ slug }/` } </code> { ! endpointSuffixAvailable && ( <em> { ' ' + __( '(unavailable due to slug conflict per above)', 'amp' ) } </em> ) } { ! editedOptions.rewrite_using_permalinks && ( <em> { ' ' + __( '(unavailable due to not using permalinks)', 'amp' ) } </em> ) } </label> <PairedUrlExamples pairedUrls={ editedOptions.paired_url_examples.path_suffix } /> </li> <li> <input id="paired_url_structure_legacy_transitional" type="radio" name="paired_url_structure" checked={ 'legacy_transitional' === editedOptions.paired_url_structure } onChange={ () => { updateOptions( { paired_url_structure: 'legacy_transitional' } ); } } disabled={ isCustom } /> <label htmlFor="paired_url_structure_legacy_transitional"> { __( 'Legacy transitional', 'amp' ) + ': ' } <code> { `?${ slug }` } </code> </label> <PairedUrlExamples pairedUrls={ editedOptions.paired_url_examples.legacy_transitional } /> </li> <li> <input id="paired_url_structure_legacy_reader" type="radio" name="paired_url_structure" checked={ 'legacy_reader' === editedOptions.paired_url_structure } onChange={ () => { updateOptions( { paired_url_structure: 'legacy_reader' } ); } } disabled={ isCustom || ! endpointSuffixAvailable || ! editedOptions.rewrite_using_permalinks } /> <label htmlFor="paired_url_structure_legacy_reader"> { __( 'Legacy reader', 'amp' ) + ': ' } <code> { `/${ slug }/` } </code> { ' & ' } <code> { `?${ slug }` } </code> { ! endpointSuffixAvailable && ( <em> { ' ' + __( '(unavailable due to slug conflict per above)', 'amp' ) } </em> ) } { ! editedOptions.rewrite_using_permalinks && ( <em> { ' ' + __( '(unavailable due to not using permalinks)', 'amp' ) } </em> ) } </label> <PairedUrlExamples pairedUrls={ editedOptions.paired_url_examples.legacy_reader } /> </li> </ul> </AMPDrawer> ); } PairedUrlStructure.propTypes = { focusedSection: PropTypes.string, };
ampproject/amp-wp
assets/src/settings-page/paired-url-structure.js
JavaScript
gpl-2.0
13,135
/** * Copyright 2013 IBM Corp. * * 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. **/ module.exports = function(RED) { "use strict"; var ntwitter = null; var OAuth= null; var request = null; var _load = false; function load () { if (!_load) { _load = true; if (RED.device) { var ntwitter = require('twitter-ng'); var OAuth= require('oauth').OAuth; var request = require('request'); } } } function TwitterNode(n) { load (); RED.nodes.createNode(this,n); this.screen_name = n.screen_name; this.consumer_key = n.consumer_key; this.consumer_secret = n.consumer_secret; this.access_token = n.access_token; this.access_token_secret = n.access_token_secret; } RED.nodes.registerType("twitter-credentials",TwitterNode); function TwitterInNode(n) { load (); RED.nodes.createNode(this,n); this.active = true; this.user = n.user; //this.tags = n.tags.replace(/ /g,''); this.tags = n.tags; this.twitter = n.twitter; this.topic = n.topic||"tweets"; this.twitterConfig = RED.nodes.getNode(this.twitter); var oa = new OAuth( "https://api.twitter.com/oauth/request_token", "https://api.twitter.com/oauth/access_token", this.twitterConfig.access_token, this.twitterConfig.access_token_secret, "1.0", null, "HMAC-SHA1" ); if (RED.device) { if (this.twitterConfig.screen_name) { // console.log (this.twitterConfig.consumer_key); // console.log (this.twitterConfig.consumer_secret); // console.log (this.twitterConfig.access_token); // console.log (this.twitterConfig.access_token_secret); var twit = new ntwitter({ consumer_key: this.twitterConfig.consumer_key, consumer_secret: this.twitterConfig.consumer_secret, access_token_key: this.twitterConfig.access_token, access_token_secret: this.twitterConfig.access_token_secret }); //setInterval(function() { // twit.get("/application/rate_limit_status.json",null,function(err,cb) { // console.log("direct_messages:",cb["resources"]["direct_messages"]); // }); // //},10000); var node = this; if (this.user === "user") { node.poll_ids = []; node.since_ids = {}; var users = node.tags.split(","); for (var i=0;i<users.length;i++) { var user = users[i].replace(" ",""); twit.getUserTimeline({ screen_name:user, trim_user:0, count:1 },function() { var u = user+""; return function(err,cb) { if (err) { node.error(err); return; } if (cb[0]) { node.since_ids[u] = cb[0].id_str; } else { node.since_ids[u] = '0'; } node.poll_ids.push(setInterval(function() { twit.getUserTimeline({ screen_name:u, trim_user:0, since_id:node.since_ids[u] },function(err,cb) { if (cb) { for (var t=cb.length-1;t>=0;t-=1) { var tweet = cb[t]; var where = tweet.user.location||""; var la = tweet.lang || tweet.user.lang; //console.log(tweet.user.location,"=>",tweet.user.screen_name,"=>",pay); var msg = { topic:node.topic+"/"+tweet.user.screen_name, payload:tweet.text, location:where, lang:la, tweet:tweet }; node.send(msg); if (t == 0) { node.since_ids[u] = tweet.id_str; } } } if (err) { node.error(err); } }); },60000)); } }()); } } else if (this.user === "dm") { node.poll_ids = []; twit.getDirectMessages({ screen_name:node.twitterConfig.screen_name, trim_user:0, count:1 },function(err,cb) { if (err) { node.error(err); return; } if (cb[0]) { node.since_id = cb[0].id_str; } else { node.since_id = '0'; } node.poll_ids.push(setInterval(function() { twit.getDirectMessages({ screen_name:node.twitterConfig.screen_name, trim_user:0, since_id:node.since_id },function(err,cb) { if (cb) { for (var t=cb.length-1;t>=0;t-=1) { var tweet = cb[t]; var msg = { topic:node.topic+"/"+tweet.sender.screen_name, payload:tweet.text, tweet:tweet }; node.send(msg); if (t == 0) { node.since_id = tweet.id_str; } } } if (err) { node.error(err); } }); },120000)); }); } else if (this.tags !== "") { try { var thing = 'statuses/filter'; if (this.user === "true") { thing = 'user'; } var st = { track: [node.tags] }; var bits = node.tags.split(","); if ((bits.length > 0) && (bits.length % 4 == 0)) { if ((Number(bits[0]) < Number(bits[2])) && (Number(bits[1]) < Number(bits[3]))) { st = { locations: node.tags }; } else { node.log("possible bad geo area format. Should be lower-left lon, lat, upper-right lon, lat"); } } var setupStream = function() { if (node.active) { twit.stream(thing, st, function(stream) { //console.log(st); //twit.stream('user', { track: [node.tags] }, function(stream) { //twit.stream('site', { track: [node.tags] }, function(stream) { //twit.stream('statuses/filter', { track: [node.tags] }, function(stream) { node.stream = stream; stream.on('data', function(tweet) { //console.log(tweet.user); //console.log (tweet); if (tweet.user !== undefined) { var where = tweet.user.location||""; var la = tweet.lang || tweet.user.lang; //console.log(tweet.user.location,"=>",tweet.user.screen_name,"=>",pay); var msg = { topic:node.topic+"/"+tweet.user.screen_name, payload:tweet.text, location:where, lang:la, tweet:tweet }; node.send(msg); } }); stream.on('limit', function(tweet) { node.log("tweet rate limit hit"); }); stream.on('error', function(tweet,rc) { if (rc == 420) { node.warn("Twitter rate limit hit"); } else { node.warn("Stream error:"+tweet.toString()+" ("+rc+")"); } setTimeout(setupStream,10000); }); stream.on('destroy', function (response) { if (this.active) { node.warn("twitter ended unexpectedly"); setTimeout(setupStream,10000); } }); }); } } setupStream(); } catch (err) { node.error(err); } } else { this.error("Invalid tag property"); } } else { this.error("missing twitter credentials"); } this.on('close', function() { if (this.stream) { this.active = false; this.stream.destroy(); } if (this.poll_ids) { for (var i=0;i<this.poll_ids.length;i++) { clearInterval(this.poll_ids[i]); } } }); } } RED.nodes.registerType("twitter in",TwitterInNode); function TwitterOutNode(n) { load (); RED.nodes.createNode(this,n); this.topic = n.topic; this.twitter = n.twitter; this.twitterConfig = RED.nodes.getNode(this.twitter); var oa = new OAuth( "https://api.twitter.com/oauth/request_token", "https://api.twitter.com/oauth/access_token", this.twitterConfig.access_token, this.twitterConfig.access_token_secret, "1.0", null, "HMAC-SHA1" ); var node = this; if (this.twitterConfig.screen_name) { var twit = new ntwitter({ consumer_key: this.twitterConfig.consumer_key, consumer_secret: this.twitterConfig.consumer_secret, access_token_key: this.twitterConfig.access_token, access_token_secret: this.twitterConfig.access_token_secret }); node.on("input", function(msg) { node.status({fill:"blue",shape:"dot",text:"tweeting"}); if (msg.payload.length > 140) { msg.payload = msg.payload.slice(0,139); node.warn("Tweet greater than 140 : truncated"); } if (msg.media && Buffer.isBuffer(msg.media)) { var apiUrl = "https://api.twitter.com/1.1/statuses/update_with_media.json"; var signedUrl = oa.signUrl(apiUrl, credentials.access_token, credentials.access_token_secret, "POST"); var r = request.post(signedUrl,function(err,httpResponse,body) { if (err) { node.error(err.toString()); node.status({fill:"red",shape:"ring",text:"failed"}); } else { var response = JSON.parse(body); if (body.errors) { var errorList = body.errors.map(function(er) { return er.code+": "+er.message }).join(", "); node.error("tweet failed: "+errorList); node.status({fill:"red",shape:"ring",text:"failed"}); } else { node.status({}); } } }); var form = r.form(); form.append("status",msg.payload); form.append("media[]",msg.media,{filename:"image"}); } else { twit.updateStatus(msg.payload, function (err, data) { if (err) { node.status({fill:"red",shape:"ring",text:"failed"}); node.error(err); } node.status({}); }); } }); } } RED.nodes.registerType("twitter out",TwitterOutNode); }
Wyliodrin/node-red
red/social/27-twitter.js
JavaScript
gpl-2.0
15,202
var PocketSphinx = require('../'); var app = require('express')(); var http = require('http').Server(app); var io = require('socket.io')(http); app.get('/', function(req, res){ res.sendfile('index.html'); }); io.on('connection', function(socket){ var ps = new PocketSphinx(); ps.on('utterance', function(hyp, utt, score) { socket.emit('utterance', {hyp: hyp, utterance: utt, score:score}); }); socket.on('audio', function(data) { ps.write(data); }); }); http.listen(3000, function(){ console.log('listening on *:3000'); });
moneppo/node-pocketsphinx
demo/demo.js
JavaScript
gpl-2.0
546
/*! Plugin: jQuery Parallax Version 1.1.3 Author: Ian Lunn Twitter: @IanLunn Author URL: http://www.ianlunn.co.uk/ Plugin URL: http://www.ianlunn.co.uk/plugins/jquery-parallax/ Dual licensed under the MIT and GPL licenses: http://www.opensource.org/licenses/mit-license.php http://www.gnu.org/licenses/gpl.html */ !function(a){var b=a(window),c=b.height();b.resize(function(){c=b.height()}),a.fn.parallax=function(d,e,f){function g(){var f=b.scrollTop();j.each(function(){var b=a(this),g=b.offset().top,k=h(b);f>g+k||g>f+c||j.css("backgroundPosition",d+" "+Math.round((i-f)*e)+"px")})}var h,i,j=a(this);j.each(function(){i=j.offset().top}),h=f?function(a){return a.outerHeight(!0)}:function(a){return a.height()},(arguments.length<1||null===d)&&(d="50%"),(arguments.length<2||null===e)&&(e=.1),(arguments.length<3||null===f)&&(f=!0),b.bind("scroll",g).resize(g),g()}}(jQuery);
estrategasdigitales/dictobas
wp-content/themes/decibel/js/lib/jquery.parallax.min.js
JavaScript
gpl-2.0
887
module.exports = function(grunt) { require("load-grunt-tasks")(grunt); // npm install --save-dev load-grunt-tasks grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), babel: { options: { sourceMap: true, plugins: ["transform-react-jsx"], presets: ['babel-preset-es2015'], compact: "auto" }, dist: { files: { "build/cloak.js": "src/cloak.js" } } }, uglify: { options: { banner: '/*! <%= pkg.name %> <%= pkg.author %> <%= grunt.template.today("yyyy-mm-dd") %> */\n' }, build: { files: { "build/cloak.min.js": "build/cloak.js", } } } }); grunt.loadNpmTasks("grunt-contrib-uglify"); grunt.registerTask("default", ["babel", "uglify"]); };
frankhale/cloak-of-darkness
Gruntfile.js
JavaScript
gpl-2.0
790
var postcss = require('postcss'), fs = require('fs'), path = require('path'), glob = require('glob'), vars = require('postcss-simple-vars'); var parseNameAndArgs = function (rule) { var name = rule.params.split('(', 1)[0], rest = rule.params.slice(name.length).trim(), args; if (rest.length) { if ( rest.substring(0, 1) !== '(' || rest.substring(rest.length - 1) !== ')' ) { throw rule.error( 'Syntax error', { plugin: 'postcss-sassy-mixins' } ); } args = postcss.list.comma(rest.substring(1, rest.length - 1)); } return { name: name, args: args }; }; var objectToNodes = function (node, obj, source) { Object.keys(obj).forEach(function(key) { if (typeof obj[key] === 'object') { var rule; if (key[0] === '@') rule = postcss.atRule({ name: key.match(/^@([^\s]*)/)[1], params: key.replace(/^@[^\s]*\s+/, '') }); else rule = postcss.rule({ selector: key, source: source }); node.append(rule); objectToNodes(rule, obj[key], source); } else { var decl = postcss.decl({ prop: key, value: obj[key].toString(), source: source }); node.append(decl); } }); return node; }; module.exports = postcss.plugin('postcss-sassy-mixins', function (opts) { opts = opts || {}; var mixins = {}; if (opts.mixinsDir) { var dirs = opts.mixinsDir; if (!(dirs instanceof Array)) dirs = [dirs]; dirs.forEach(function(dir) { var files = fs.readdirSync(dir); files.forEach(function(filename) { var file = path.join(dir, filename); if (path.extname(file) !== '.js') return; var name = path.basename(file, '.js'); mixins[name] = { mixin: require(file) }; }); }); } if (opts.mixinsFiles) { var globs = opts.mixinsFiles; if (!(globs instanceof Array)) globs = [globs]; globs.forEach(function(pattern) { glob.sync(pattern).forEach(function(file) { var name = path.basename(file, path.extname(file)); mixins[name] = { mixin: require(file) }; }); }); } if (typeof opts.mixins === 'object') { Object.keys(opts.mixins).forEach(function(name) { mixins[name] = { mixin: opts.mixins[name] }; }); } var defineMixin = function (rule) { var parsed = parseNameAndArgs(rule), args; if (parsed.args) args = parsed.args.map(function(str) { var arg = str.split(':', 1)[0]; var defaults = str.slice(arg.length + 1); return [arg.slice(1).trim(), defaults.trim()]; }); var content = false; rule.walkAtRules('content', function () { content = true; return false; }); mixins[parsed.name] = { mixin: rule, args: args, content: content }; rule.remove(); }; var includeMixin = function (rule) { var parsed = parseNameAndArgs(rule); var decl = mixins[parsed.name]; if (!decl && !opts.silent) throw rule.error('Undefined mixin ' + parsed.name); var mixin = decl && decl.mixin; var params = parsed.args || []; if (typeof mixin === 'function') { var args = [rule].concat(params); mixin = mixin.apply(this, args); } if (typeof mixin === 'object') { if (mixin.type && mixin.name && mixin.type === 'atrule' && mixin.name === 'mixin') { var values = {}; if (decl.args) decl.args.forEach(function (arg, i) { values[arg[0]] = params[i] || arg[1]; }); var clones = []; mixin.nodes.forEach(function(node) { clones.push(node.clone()); }); var proxy = postcss.rule({ nodes: clones }); if (decl.args) vars({ only: values })(proxy); if (decl.content) { proxy.walkAtRules('content', function (place) { place.replaceWith(rule.nodes); }); } rule.parent.insertBefore(rule, proxy.nodes); proxy.walkAtRules('include', includeMixin); } else { var root = objectToNodes(postcss.root(), mixin, rule.source); rule.parent.insertBefore(rule, root); } } rule.remove(); }; return function (css) { css.walkAtRules('mixin', defineMixin); css.walkAtRules('include', includeMixin); }; });
circleQu/greenPlant
helloworld/public/node_modules/postcss-sassy-mixins/index.js
JavaScript
gpl-2.0
3,972
!function(ns){var $,options,enqueue=function(fn){var queue=[],locked=1,working=0,fn=fn,instance=function(){queue.push([this,arguments]),locked||instance.execute()};return instance.execute=function(){if(!working){working=1,locked=0;for(var q;q=queue.shift();)fn.apply(q[0],q[1]);working=0}},instance.lock=function(){locked=0},instance},components={},initialized=0,installers=[],self=window[ns]={setup:function(o){options=o,self.init()},jquery:function(jquery){$||($=jquery,self.init())},init:function(){initialized||$&&options&&(self.$=$.initialize(options),self.plugin.execute(),initialized=1) },plugin:enqueue(function(name,factory){factory.apply(self,[$])}),module:enqueue(function(name,factory){$.module(name,factory)}),installer:function(recipient,name,factory){if(installers[recipient]||(installers[recipient]=[]),!name)return installers[recipient];var component=components[recipient];return component.registered?component.install(name,factory):(installers[recipient].push([name,factory]),void 0)},component:function(name,options){if(!name)return components;if(!options)return components[name];if("function"==typeof options){var component=options; return component.registered=!0,components[name]=component}var queue=[],abstractQueue=function(method,context,args){return{method:method,context:this,args:args}},abstractMethod=function(method,parent,chain){return function(){return(chain||queue).push(abstractQueue(method,this,arguments)),parent}},abstractInstance=function(instance,methods,chain){for(var i=0;i<methods.length;i++){var method=methods[i];instance[method]=abstractMethod(method,instance,chain)}return instance},abstractChain=function(name,methods){return function(){var chain=[abstractQueue(name,this,arguments)]; return queue.push(chain),abstractInstance({},methods,chain)}};queue.execute=function(){for(var component=components[name],i=0;i<queue.length;i++){var fn=queue[i];if("[object Array]"===Object.prototype.toString.call(fn))for(var chain=fn,context=component,j=0;j<chain.length;j++)context=context[chain[j].method].apply(context,chain[j].args);else component[fn.method].apply(component,fn.args)}};var component=abstractInstance(function(){component.run.apply(this.arguments)},["run","ready","module","template"]);return component.className=name,component.options=options,component.queue=queue,component.require=abstractChain("require",["library","script","stylesheet","language","template","view","done","always","fail","progress"]),window[name]=components[name]=component }}}("FD31");FD31.setup({"environment":"static","source":"local","mode":"compressed","path":"http:\/\/medicine-prof.info\/media\/foundry\/3.1","extension":".min.js","rootPath":"http:\/\/medicine-prof.info","basePath":"http:\/\/medicine-prof.info","indexUrl":"http:\/\/medicine-prof.info\/index.php","joomla":{"version":"3.4.4","debug":false},"locale":{"lang":"en-US"}});
kosmosby/medicine-prof
media/foundry/3.1/config/87fddba43e455b4b225ee31dd2c026a6.js
JavaScript
gpl-2.0
2,869
// -*- mode: js; js-indent-level: 4; indent-tabs-mode: nil -*- // // A widget showing the user avatar and name const AccountsService = imports.gi.AccountsService; const GLib = imports.gi.GLib; const Gio = imports.gi.Gio; const Lang = imports.lang; const St = imports.gi.St; const Params = imports.misc.params; const AVATAR_ICON_SIZE = 64; // Adapted from gdm/gui/user-switch-applet/applet.c // // Copyright (C) 2004-2005 James M. Cape <jcape@ignore-your.tv>. // Copyright (C) 2008,2009 Red Hat, Inc. const Avatar = new Lang.Class({ Name: 'Avatar', _init: function(user, params) { this._user = user; params = Params.parse(params, { reactive: false, iconSize: AVATAR_ICON_SIZE, styleClass: 'framed-user-icon' }); this._iconSize = params.iconSize; this.actor = new St.Bin({ style_class: params.styleClass, track_hover: params.reactive, reactive: params.reactive }); }, setSensitive: function(sensitive) { this.actor.can_focus = sensitive; this.actor.reactive = sensitive; }, update: function() { let iconFile = this._user.get_icon_file(); if (iconFile && !GLib.file_test(iconFile, GLib.FileTest.EXISTS)) iconFile = null; if (iconFile) { let file = Gio.File.new_for_path(iconFile); this.actor.child = null; this.actor.style = 'background-image: url("%s");'.format(iconFile); } else { this.actor.style = null; this.actor.child = new St.Icon({ icon_name: 'avatar-default-symbolic', icon_size: this._iconSize }); } } }); const UserWidget = new Lang.Class({ Name: 'UserWidget', _init: function(user) { this._user = user; this.actor = new St.BoxLayout({ style_class: 'user-widget', vertical: false }); this.actor.connect('destroy', Lang.bind(this, this._onDestroy)); this._avatar = new Avatar(user); this.actor.add(this._avatar.actor, { x_fill: true, y_fill: true }); this._label = new St.Label({ style_class: 'user-widget-label' }); this.actor.add(this._label, { expand: true, x_fill: true, y_fill: false, y_align: St.Align.MIDDLE }); this._userLoadedId = this._user.connect('notify::is-loaded', Lang.bind(this, this._updateUser)); this._userChangedId = this._user.connect('changed', Lang.bind(this, this._updateUser)); if (this._user.is_loaded) this._updateUser(); }, _onDestroy: function() { if (this._userLoadedId != 0) { this._user.disconnect(this._userLoadedId); this._userLoadedId = 0; } if (this._userChangedId != 0) { this._user.disconnect(this._userChangedId); this._userChangedId = 0; } }, _updateUser: function() { if (this._user.is_loaded) this._label.text = this._user.get_real_name(); else this._label.text = ''; this._avatar.update(); } });
gcampax/gnome-shell
js/ui/userWidget.js
JavaScript
gpl-2.0
3,455
import $ from 'jquery' /** * Handles our DOM security conditional logic based on the user selection * @return void * @since 4.0 */ export function handleSecurityConditionals () { /* Get the appropriate elements for use */ const $secTable = $('#gfpdf-fieldset-gfpdf_form_settings_advanced') const $pdfSecurity = $secTable.find('input[name="gfpdf_settings[security]"]') const $format = $secTable.find('input[name="gfpdf_settings[format]"]') const $securityQuestion = $secTable.find('#gfpdf-settings-field-wrapper-security') const $securityFields = $secTable.find('#gfpdf-settings-field-wrapper-password,#gfpdf-settings-field-wrapper-privileges,#gfpdf-settings-field-wrapper-master_password:not(.gfpdf-hidden)') /* Add change event to admin restrictions to show/hide dependant fields */ $pdfSecurity.on('change', function () { /* Get the format dependency */ const format = $format.filter(':checked').val() if ($(this).val() === 'No' || format !== 'Standard') { /* hide security password / privileges */ $securityFields.hide() } else { /* Show/hide security password / privileges fields under 'Enable PDF Security' */ if ($(this).is(':checked')) { $securityFields.show() } else { $securityFields.hide() } } if (format !== 'Standard') { $securityQuestion.hide() } else { $securityQuestion.show() } }).trigger('change') /* The format field effects the security field. When it changes it triggers the security field as changed */ $format.on('change', function () { if ($(this).is(':checked')) { $pdfSecurity.trigger('change') } }).trigger('change') }
GravityPDF/gravity-forms-pdf-extended
src/assets/js/admin/settings/pdf/handleSecurityConditionals.js
JavaScript
gpl-2.0
1,688
/* * https://github.com/5orenso * * Copyright (c) 2019 Øistein Sørensen * Licensed under the MIT license. */ 'use strict'; const { run, webUtil, utilHtml, util } = require('../../middleware/init')({ __filename, __dirname }); const Article = require('../../../lib/class/article'); const fields = { id: 1, status: 1, published: 1, updatedDate: 1, author: 1, sort: 1, category: 1, categoryId: 1, title: 1, teaser: 1, ingress: 1, body: 1, titleEn: 1, teaserEn: 1, ingressEn: 1, bodyEn: 1, notes: 1, url: 1, img: 1, youtubeVideos: 1, links: 1, tags: 1, youtube: 1, imageObject: 1, video: 1, aggregateRating: 1, nutrition: 1, relevantWords: 1, classifiedWords: 1, widget: 1, widgetList: 1, background: 1, forground: 1, fontsizeH1: 1, fontweightH1: 1, fontsizeH3: 1, fontweightH3: 1, fontsizeH5: 1, fontweightH5: 1, classNames: 1, cssStyles: 1, imgSizeList: 1, 'clock-class': 1, 'clock-style': 1, 'clock-countdownto': 1, 'clock-showDateOnly': 1, 'clock-showSeconds': 1, 'clock-showTimezone': 1, 'clock-showClockOnly': 1, 'booking-class': 1, 'booking-table-class': 1, 'booking-style': 1, 'booking-sheetId': 1, 'form-class': 1, 'form-table-class': 1, 'form-style': 1, 'form-sheetId': 1, 'sheet-class': 1, 'sheet-table-class': 1, 'sheet-style': 1, 'sheet-sheetId': 1, 'sheet-showDocTitle': 1, 'sheet-limit': 1, 'sheet-showSearch': 1, 'poll-class': 1, 'poll-style': 1, 'gallery-autoscroll': 1, 'gallery-nav-class': 1, 'gallery-nav-style': 1, 'gallery-nav-back': 1, 'gallery-nav-forward': 1, 'gallery-class': 1, 'gallery-wrapper-class': 1, 'gallery-wrapper-inner-class': 1, 'gallery-class-photo': 1, 'gallery-class-photo-img': 1, 'gallery-skip-background-images': 1, 'gallery-img-wrapper-class': 1, 'gallery-style': 1, 'gallery-start': 1, 'gallery-end': 1, 'weather-class': 1, 'weather-style': 1, 'weather-name': 1, 'weather-altitude': 1, 'weather-lat': 1, 'weather-lon': 1, 'weather-date': 1, 'rating-class': 1, 'rating-style': 1, 'rating-from': 1, 'rating-to': 1, 'related-class': 1, 'related-style': 1, 'related-tags': 1, 'cookies-class': 1, 'cookies-style': 1, }; module.exports = async (req, res) => { run(req); const art = new Article(); let query = {}; if (req.params.id) { query.id = parseInt(req.params.id, 10); } else if (req.params.category) { query.category = req.params.category; } query = webUtil.cleanObject(query); const limit = parseInt(req.query.limit || 10, 10); const skip = parseInt(req.query.offset || 0, 10); if (req.query.category) { query.category = req.query.category; } if (req.query.categoryId) { query.categoryId = parseInt(req.query.categoryId, 10); } if (req.query.categoryIn && req.query.categoryIn.length > 0) { query.categoryId = { $in: req.query.categoryIn.split(',').map(c => parseInt(c, 10)) }; } if (req.query.idIn && req.query.idIn.length > 0) { query.id = { $in: req.query.idIn.split(',').map(id => parseInt(id, 10)) }; } if (req.query.status) { query.status = req.query.status; } let apiContent; const data = { query, }; if (req.query.query) { const { list, total } = await art.search(req.query.query, {}, { limit, skip, query }); data.artlist = list; data.total = total; } else if (req.params.id) { apiContent = await art.findOne(query, fields); data.article = apiContent; } else { apiContent = await art.find(query, fields, { limit, skip }); data.artlist = apiContent; const total = await art.count(query); data.total = total; } if (data.artlist && data.artlist.length > 0) { data.artlist.forEach((a) => { if (!a.url) { a.url = `/v2/${utilHtml.asLinkPart(a.category)}/${utilHtml.asLinkPart(a.title)}/${a.id}`; } }); } // Find relevant words. if (data.article) { data.article.relevantWords = []; const tokens = util.tokenizeAndStem(data.article.body); // console.log('---> tokens', tokens); const wordCount = util.termsCount(tokens, data.article.body); const words = Object.keys(wordCount); for (let i = 0, l = words.length; i < l; i += 1) { const word = words[i]; // console.log('===> ', word, wordCount[word]); if (wordCount[word] >= 3 && word.length > 3) { data.article.relevantWords.push(word); } } // BayesClassifier: // if (data.article.body) { // const artlistClassify = await art.find({}, { id: 1, title: 1, tags: 1, body: 1 }, { limit: 500 }); // data.article.classifiedWords = util.classifyArticle(artlistClassify, data.article); // } } data.jwtToken = util.makeJwtToken({ readAccess: 1 }, req.config); data.imageServer = req.config.blog.imageServer; data.imagePath = req.config.blog.imagePath; utilHtml.renderApi(req, res, 200, data); };
5orenso/simple-blog
app/routes/api/get-article.js
JavaScript
gpl-2.0
5,401
import { createElement } from 'react'; import BillingHistoryComponent from 'calypso/me/purchases/billing-history/main'; import Receipt from './receipt'; export function billingHistory( context, next ) { context.primary = createElement( BillingHistoryComponent ); next(); } export function transaction( context, next ) { const receiptId = context.params.receiptId; if ( receiptId ) { context.primary = createElement( Receipt, { transactionId: receiptId } ); } next(); }
Automattic/wp-calypso
client/me/purchases/billing-history/controller.js
JavaScript
gpl-2.0
480
/* * This file is part of the TYPO3 CMS project. * * It is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, either version 2 * of the License, or any later version. * * For the full copyright and license information, please read the * LICENSE.txt file that was distributed with this source code. * * The TYPO3 project - inspiring people to share! */ /** * Module: TYPO3/CMS/Backend/PageTree/PageTree */ define(['jquery', 'd3', 'TYPO3/CMS/Backend/Icons', 'TYPO3/CMS/Backend/PageTree/PageTreeDragDrop', 'TYPO3/CMS/Backend/SvgTree', 'TYPO3/CMS/Backend/ContextMenu', 'TYPO3/CMS/Backend/Storage/Persistent', 'TYPO3/CMS/Backend/Notification' ], function($, d3, Icons, PageTreeDragDrop, SvgTree, ContextMenu, Persistent, Notification) { 'use strict'; /** * @constructor * @exports TYPO3/CMS/Backend/PageTree/PageTree */ var PageTree = function() { SvgTree.call(this); this.originalNodes = []; this.settings.defaultProperties = { hasChildren: false, nameSourceField: 'title', prefix: '', suffix: '', locked: false, loaded: false, overlayIcon: '', selectable: true, expanded: false, checked: false, backgroundColor: '', stopPageTree: false, class: '', readableRootline: '', isMountPoint: false, }; this.searchQuery = ''; }; PageTree.prototype = Object.create(SvgTree.prototype); var _super_ = SvgTree.prototype; /** * SelectTree initialization * * @param {String} selector * @param {Object} settings */ PageTree.prototype.initialize = function(selector, settings) { var _this = this; if (!_super_.initialize.call(_this, selector, settings)) { return false; } _this.settings.isDragAnDrop = settings.allowDragMove; _this.dispatch.on('nodeSelectedAfter.pageTree', _this.nodeSelectedAfter); _this.dispatch.on('nodeRightClick.pageTree', _this.nodeRightClick); _this.dispatch.on('contextmenu.pageTree', _this.contextmenu); _this.dispatch.on('updateSvg.pageTree', _this.updateSvg); _this.dispatch.on('prepareLoadedNode.pageTree', _this.prepareLoadedNode); _this.dragDrop = PageTreeDragDrop; _this.dragDrop.init(_this); if (_this.settings.temporaryMountPoint) { _this.addMountPoint(_this.settings.temporaryMountPoint); } return this; }; /** * Add mount point */ PageTree.prototype.addMountPoint = function(breadcrumb) { var _this = this; if (_this.wrapper.parent().find('.node-mount-point').length) { _this.wrapper.parent().find('.node-mount-point').remove(); } _this.mountPoint = _this.wrapper.before( '<div class="node-mount-point">' + '<div class="node-mount-point__icon" data-tree-icon="actions-document-info"></div>' + '<div class="node-mount-point__text"><div>' + breadcrumb + '</div></div>' + '<div class="node-mount-point__icon" data-tree-icon="actions-close" title="' + TYPO3.lang['labels.temporaryDBmount'] + '"></div>' + '</div>' ); _this.wrapper.parent() .find('[data-tree-icon=actions-close]') .on('click', function() { top.TYPO3.Backend.NavigationContainer.PageTree.unsetTemporaryMountPoint(); _this.wrapper.parent().find('.node-mount-point').remove(); }); //get icons _this.wrapper.parent().find('.node-mount-point [data-tree-icon]').each(function() { var $this = $(this); Icons.getIcon($this.attr('data-tree-icon'), Icons.sizes.small, null, null, 'inline').then(function(icon) { $this.append(icon); }); }); }; /** * Displays a notification message and refresh nodes * * @param error */ PageTree.prototype.errorNotification = function(error) { var title = TYPO3.lang.pagetree_networkErrorTitle; var desc = TYPO3.lang.pagetree_networkErrorDesc; if (error && error.target && (error.target.status || error.target.statusText)) { title += ' - ' + (error.target.status || '') + ' ' + (error.target.statusText || ''); } Notification.error(title, desc); this.loadData(); }; PageTree.prototype.sendChangeCommand = function(data) { var _this = this; var params = ''; if (data.target) { var targetUid = data.target.identifier; if (data.position === 'after') { targetUid = -targetUid; } } if (data.command === 'new') { params = '&data[pages][NEW_1][pid]=' + targetUid + '&data[pages][NEW_1][title]=' + encodeURIComponent(data.name) + '&data[pages][NEW_1][doktype]=' + data.type; } else if (data.command === 'edit') { params = '&data[pages][' + data.uid + '][' + data.nameSourceField + ']=' + encodeURIComponent(data.title); } else { if (data.command === 'delete') { if (data.uid === fsMod.recentIds.web) { _this.selectNode(_this.getFirstNode()); } params = '&cmd[pages][' + data.uid + '][delete]=1'; } else { params = 'cmd[pages][' + data.uid + '][' + data.command + ']=' + targetUid; } } _this.nodesAddPlaceholder(); d3.request(top.TYPO3.settings.ajaxUrls.record_process) .header('X-Requested-With', 'XMLHttpRequest') .header('Content-Type', 'application/x-www-form-urlencoded') .on('error', function(error) { _this.errorNotification(error); throw error; }) .post(params, function(data) { if (data) { var response = JSON.parse(data.response); if (response && response.hasErrors) { if (response.messages) { $.each(response.messages, function(id, message) { Notification.error( message.title, message.message ); }); } else { _this.errorNotification(); } _this.nodesContainer.selectAll('.node').remove(); _this.update(); _this.nodesRemovePlaceholder(); } else { _this.refreshOrFilterTree(); } } else { _this.errorNotification(); } }); }; PageTree.prototype.getFirstNode = function() { return this.nodes[0]; }; /** * Finds node by its stateIdentifier (e.g. "0_360") * @return {Node} */ PageTree.prototype.getNodeByIdentifier = function(identifier) { return this.nodes.find(function (node) { return node.stateIdentifier === identifier; }); }; /** * Observer for the selectedNode event * * @param {Node} node */ PageTree.prototype.nodeSelectedAfter = function(node) { if (!node.checked) { return; } //remember the selected page in the global state fsMod.recentIds.web = node.identifier; fsMod.currentBank = node.stateIdentifier.split('_')[0]; fsMod.navFrameHighlightedID.web = node.stateIdentifier; var separator = '?'; if (currentSubScript.indexOf('?') !== -1) { separator = '&'; } TYPO3.Backend.ContentContainer.setUrl( currentSubScript + separator + 'id=' + node.identifier ); }; PageTree.prototype.nodeRightClick = function(node) { d3.event.preventDefault(); var $node = $(node).closest('svg').find('.nodes .node[data-state-id=' + this.stateIdentifier + ']'); if ($node.length) { ContextMenu.show( $node.data('table'), this.identifier, $node.data('context'), $node.data('iteminfo'), $node.data('parameters') ); } }; PageTree.prototype.contextmenu = function(node) { var $node = $(node).closest('svg').find('.nodes .node[data-state-id=' + this.stateIdentifier + ']'); if ($node.length) { ContextMenu.show( $node.data('table'), this.identifier, $node.data('context'), $node.data('iteminfo'), $node.data('parameters') ); } }; PageTree.prototype.updateSvg = function(nodeEnter) { nodeEnter .select('use') .attr('data-table', 'pages') .attr('data-context', 'tree'); }; /** * Event listener called for each loaded node, * here used to mark node remembered in fsMode as selected * * @param node */ PageTree.prototype.prepareLoadedNode = function(node) { if (node.stateIdentifier === fsMod.navFrameHighlightedID.web) { node.checked = true; } }; PageTree.prototype.hideChildren = function(node) { _super_.hideChildren(node); Persistent.set('BackendComponents.States.Pagetree.stateHash.' + node.stateIdentifier, 0); }; PageTree.prototype.showChildren = function(node) { this.loadChildrenOfNode(node); _super_.showChildren(node); Persistent.set('BackendComponents.States.Pagetree.stateHash.' + node.stateIdentifier, 1); }; /** * Loads child nodes via Ajax (used when expanding a collapesed node) * * @param parentNode * @return {boolean} */ PageTree.prototype.loadChildrenOfNode = function(parentNode) { if (parentNode.loaded) { return; } var _this = this; _this.nodesAddPlaceholder(); d3.json(_this.settings.dataUrl + '&pid=' + parentNode.identifier + '&mount=' + parentNode.mountPoint + '&pidDepth=' + parentNode.depth, function(error, json) { if (error) { var title = TYPO3.lang.pagetree_networkErrorTitle; var desc = TYPO3.lang.pagetree_networkErrorDesc; if (error && error.target && (error.target.status || error.target.statusText)) { title += ' - ' + (error.target.status || '') + ' ' + (error.target.statusText || ''); } Notification.error( title, desc); _this.nodesRemovePlaceholder(); throw error; } var nodes = Array.isArray(json) ? json : []; //first element is a parent nodes.shift(); var index = _this.nodes.indexOf(parentNode) + 1; //adding fetched node after parent nodes.forEach(function (node, offset) { _this.nodes.splice(index + offset, 0, node); }); parentNode.loaded = true; _this.setParametersNode(); _this.prepareDataForVisibleNodes(); _this.update(); _this.nodesRemovePlaceholder(); _this.switchFocusNode(parentNode); }); }; PageTree.prototype.updateNodeBgClass = function(nodeBg) { return _super_.updateNodeBgClass.call(this, nodeBg).call(this.dragDrop.drag()); }; PageTree.prototype.nodesUpdate = function(nodes) { var _this = this; nodes = _super_.nodesUpdate.call(this, nodes) .call(this.dragDrop.drag()) .attr('data-table', 'pages') .attr('data-context', 'tree') .on('contextmenu', function(node) { _this.dispatch.call('nodeRightClick', node, this); }); var nodeStop = nodes .append('text') .text('+') .attr('class', 'node-stop') .attr('dx', 30) .attr('dy', 5) .attr('visibility', function(node) { return (node.stopPageTree && (node.depth !== 0)) ? 'visible' : 'hidden'; }) .on('click', function(node) { _this.setTemporaryMountPoint(node.identifier); }); return nodes; }; /** * Node selection logic (triggered by different events) * Page tree supports only one node to be selected at a time * so the default function from SvgTree needs to be overridden * * @param {Node} node */ PageTree.prototype.selectNode = function (node) { if (!this.isNodeSelectable(node)) { return; } var _this = this; var selectedNodes = this.getSelectedNodes(); selectedNodes.forEach(function (node) { if (node.checked === true) { node.checked = false; _this.dispatch.call('nodeSelectedAfter', _this, node); } }); node.checked = true; this.dispatch.call('nodeSelectedAfter', this, node); this.update(); }; /** * Event handler for double click on a node's label * Changed text position if there is 'stop page tree' option * * @param {Node} node */ PageTree.prototype.appendTextElement = function(node) { var _this = this; var clicks = 0; _super_.appendTextElement.call(this, node) .attr('dx', function(node) { var position = _this.textPosition; if (node.stopPageTree && node.depth !== 0) { position += 15; } if (node.locked) { position += 15; } return position; }) .on('click', function(node) { if (node.identifier !== 0) { clicks++; if (clicks === 1) { setTimeout(function() { if (clicks === 1) { _this.clickOnLabel(node, this); } else { _this.editNodeLabel(node); } clicks = 0; }, 300); } } else { _this.clickOnLabel(node, this); } }); }; PageTree.prototype.filterTree = function() { var _this = this; _this.nodesAddPlaceholder(); d3.json(_this.settings.filterUrl + '&q=' + _this.searchQuery, function(error, json) { if (error) { var title = TYPO3.lang.pagetree_networkErrorTitle; var desc = TYPO3.lang.pagetree_networkErrorDesc; if (error && error.target && (error.target.status || error.target.statusText)) { title += ' - ' + (error.target.status || '') + ' ' + (error.target.statusText || ''); } Notification.error( title, desc); _this.nodesRemovePlaceholder(); throw error; } var nodes = Array.isArray(json) ? json : []; if (nodes.length > 0) { if (_this.originalNodes.length === 0) { _this.originalNodes = JSON.stringify(_this.nodes); } _this.replaceData(nodes); } _this.nodesRemovePlaceholder(); }); }; PageTree.prototype.refreshOrFilterTree = function() { if (this.searchQuery !== '') { this.filterTree(); } else { this.refreshTree(); } } PageTree.prototype.resetFilter = function() { this.searchQuery = ''; if (this.originalNodes.length > 0) { var currentlySelected = this.getSelectedNodes()[0]; if (typeof currentlySelected === 'undefined') { this.refreshTree(); return; } this.nodes = JSON.parse(this.originalNodes); this.originalNodes = ''; var currentlySelectedNode = this.getNodeByIdentifier(currentlySelected.stateIdentifier); if (currentlySelectedNode) { this.selectNode(currentlySelectedNode); } else { this.refreshTree(); } } else { this.refreshTree(); } }; PageTree.prototype.setTemporaryMountPoint = function(pid) { var params = 'pid=' + pid; var _this = this; d3.request(top.TYPO3.settings.ajaxUrls.page_tree_set_temporary_mount_point) .header('X-Requested-With', 'XMLHttpRequest') .header('Content-Type', 'application/x-www-form-urlencoded') .on('error', function(error) { _this.errorNotification(error); throw error; }) .post(params, function(data) { if (data) { var response = JSON.parse(data.response); if (response && response.hasErrors) { if (response.messages) { $.each(response.messages, function(id, message) { Notification.error( message.title, message.message ); }); } else { _this.errorNotification(); } _this.update(); } else { _this.addMountPoint(response.mountPointPath); _this.refreshOrFilterTree(); } } else { _this.errorNotification(); } }); }; PageTree.prototype.unsetTemporaryMountPoint = function() { var _this = this; Persistent.unset('pageTree_temporaryMountPoint').then(function() { _this.refreshTree(); }); }; PageTree.prototype.sendEditNodeLabelCommand = function(node) { var _this = this; var params = '&data[pages][' + node.identifier + '][' + node.nameSourceField + ']=' + encodeURIComponent(node.newName); //remove old node from svg tree _this.nodesAddPlaceholder(node); d3.request(top.TYPO3.settings.ajaxUrls.record_process) .header('X-Requested-With', 'XMLHttpRequest') .header('Content-Type', 'application/x-www-form-urlencoded') .on('error', function(error) { _this.errorNotification(error); throw error; }) .post(params, function(data) { if (data) { var response = JSON.parse(data.response); if (response && response.hasErrors) { if (response.messages) { $.each(response.messages, function(id, message) { Notification.error( message.title, message.message ); }); } else { _this.errorNotification(); } _this.nodesAddPlaceholder(); _this.refreshOrFilterTree(); } else { node.name = node.newName; _this.svg.select('.node-placeholder[data-uid="' + node.stateIdentifier + '"]').remove(); _this.refreshOrFilterTree(); _this.nodesRemovePlaceholder(); } } else { _this.errorNotification(); } }); }; PageTree.prototype.editNodeLabel = function(node) { var _this = this; if (!node.allowEdit) { return; } _this.removeEditedText(); _this.nodeIsEdit = true; d3.select(_this.svg.node().parentNode) .append('input') .attr('class', 'node-edit') .style('top', function() { var top = node.y + _this.settings.marginTop; return top + 'px'; }) .style('left', (node.x + _this.textPosition + 5) + 'px') .style('width', _this.settings.width - (node.x + _this.textPosition + 20) + 'px') .style('height', _this.settings.nodeHeight + 'px') .attr('type', 'text') .attr('value', node.name) .on('keydown', function() { var code = d3.event.keyCode; if (code === 13 || code === 9) { //enter || tab var newName = this.value.trim(); if (newName.length && (newName !== node.name)) { _this.nodeIsEdit = false; _this.removeEditedText(); node.nameSourceField = node.nameSourceField || 'title'; node.newName = newName; _this.sendEditNodeLabelCommand(node); } else { _this.nodeIsEdit = false; _this.removeEditedText(); } } else if (code === 27) { //esc _this.nodeIsEdit = false; _this.removeEditedText(); } }) .on('blur', function() { if (_this.nodeIsEdit) { var newName = this.value.trim(); if (newName.length && (newName !== node.name)) { node.nameSourceField = node.nameSourceField || 'title'; node.newName = newName; _this.sendEditNodeLabelCommand(node); } _this.removeEditedText(); } }) .node() .select(); }; PageTree.prototype.removeEditedText = function() { var _this = this; var inputWrapper = d3.selectAll('.node-edit'); if (inputWrapper.size()) { try { inputWrapper.remove(); _this.nodeIsEdit = false; } catch (e) { } } }; return PageTree; });
maddy2101/TYPO3.CMS
typo3/sysext/backend/Resources/Public/JavaScript/PageTree/PageTree.js
JavaScript
gpl-2.0
20,826
(function($) { $.fn.pageRank = function(cb) { $.ajax({ url: 'http://api.camcimcumcem.com/page_rank/?url=' + encodeURIComponent($(this).text()) + '&output=js', dataType: 'jsonp', success: function(results) { cb(results.page_rank); } }); }; $.fn.alexaRank = function(cb) { $.ajax({ url: 'http://api.camcimcumcem.com/alexa/rank/?domain=' + encodeURIComponent($(this).text()) + '&output=js', dataType: 'jsonp', success: function(results) { cb(results.rank); } }); }; $.fn.density = function(cb) { var text = $(this).text(); var word_list = text.split(/\W+/); var counts = {}; var word; for (var i = 0; i < word_list.length; ++i) { word = word_list[i]; counts[word] = (counts[word] || 0) + 1; } var densities = {}; for (word in counts) { densities[word] = counts[word] / word_list.length; } cb(densities[word]); }; $.fn.wordCount = function(cb) { var text = $(this).text(); var word_list = text.split(/\W+/); cb(word_list.length); }; $.fn.h1Count = function(cb) { var word_list = $(this).find('h1'); cb(word_list.length); }; $.fn.h2Count = function(cb) { var word_list = $(this).find('h2'); cb(word_list.length); }; $.fn.h3Count = function(cb) { var word_list = $(this).find('h3'); cb(word_list.length); }; $.fn.h4Count = function(cb) { var word_list = $(this).find('h4'); cb(word_list.length); }; $.fn.h5Count = function(cb) { var word_list = $(this).find('h5'); cb(word_list.length); }; $.fn.h6Count = function(cb) { var word_list = $(this).find('h6'); cb(word_list.length); }; $.fn.linkCount = function(cb) { cb($('[href]').size()); }; }(jQuery));
mbejda/jQuerySEO
src/jquery.seo.js
JavaScript
gpl-2.0
2,038
'use strict'; const Joi = require('joi'); let schema = { a: Joi.date().format('YYYY-MM-DD') }; let values = [ {a: '2016-07-09'}, {a: '2016-07-99'}, {a: '2016-07-091'}, {a: '2016/07/09'}, {a: '20160709'}, ] for (let v of values) { let ret = Joi.validate(v , schema, { abortEarly: true, convert: true, allowUnknown: true, }) console.log('---------------------------') if (ret.error) { console.log(ret.error.details[0].message) } else { console.log(ret.value); } }
gensmusic/test
third_party/nodejs/third-party/joi/date.js
JavaScript
gpl-2.0
557
import { createSelector } from '@automattic/state-utils'; import { getCurrentUserId } from 'calypso/state/current-user/selectors'; import { hasLoadedUserPurchasesFromServer } from './fetching'; import { getPurchases } from './get-purchases'; import 'calypso/state/purchases/init'; /** * Returns a list of purchases associated with the current user * * @param {object} state Redux state * @returns {Array|null} array of the matching purchases or `null` if the list hasn't been loaded from server yet */ export const getUserPurchases = createSelector( ( state ) => { if ( ! hasLoadedUserPurchasesFromServer( state ) ) { return null; } const userId = getCurrentUserId( state ); return getPurchases( state ).filter( ( purchase ) => purchase.userId === userId ); }, ( state ) => [ hasLoadedUserPurchasesFromServer( state ), getCurrentUserId( state ), getPurchases( state ), ] );
Automattic/wp-calypso
client/state/purchases/selectors/get-user-purchases.js
JavaScript
gpl-2.0
902
/** * NOTES * block details are child block hash, parent block hash, isUncle, isProcessed, and total difficulty * block details are stored to key 'detail'+<blockhash> * meta.rawHead is the the head of the chain with the most POW * meta.head is the head of the chain that has had its state root verifed */ const async = require('async') const Block = require('ethereumjs-block') const utils = require('ethereumjs-util') const BN = utils.BN const Ethash = require('ethashjs') const rlp = utils.rlp var Blockchain = module.exports = function (db, validate) { this.db = db this.ethash = new Ethash(db) this.validate = validate === undefined ? true : validate this._initDone = false this._pendingSaves = [] this._pendingGets = [] this._init() } /** * Fetches the meta info about the blockchain from the db. Meta info contains * the hash of the head block and the hash of the genisis block * @method _init */ Blockchain.prototype._init = function () { var self = this function onHeadFound () { // run the pending save operations async.whilst(function () { return self._pendingSaves.length }, function (cb) { var op = self._pendingSaves.pop() self._addBlock(op[0], function () { op[1]() cb() }) }, function () { delete self._pendingSaves self._initDone = true // run the pending getHead self._pendingGets.forEach(function (args) { self.getHead.apply(self, args) }) }) } this.db.get('meta', { valueEncoding: 'json' }, function (err, meta) { if (!err && meta) { self.meta = meta self.meta.td = new BN(self.meta.td) } else { self.meta = { heads: {}, td: new BN() } } onHeadFound() }) } Blockchain.prototype.setCanicalGenesisBlock = function (cb) { var genesisBlock = new Block() genesisBlock.setGenesisParams() this.putBlock(genesisBlock, function () {}) } /** * Returns that head block * @method getHead * @param cb Function the callback */ Blockchain.prototype.getHead = function (name, cb) { if (typeof name === 'function') { cb = name name = 'vm' } if (!this._initDone) { this._pendingGets.push(arguments) } else { // if the head is not found return the rawHead var hash = this.meta.heads[name] || this.meta.rawHead this.getBlock(hash, cb) } } /** * Adds a block to the blockchain * @method addBlock * @param {object} block -the block to be added to the block chain * @param {function} cb - a callback function */ Blockchain.prototype.putBlock = function (block, cb) { if (!this._initDone) { this._pendingSaves.push([block, cb]) } else { this._addBlock(block, cb) } } Blockchain.prototype.putBlocks = function (blocks, cb) { var self = this async.eachSeries(blocks, function (block, done) { self.putBlock(block, done) }, cb) } Blockchain.prototype._addBlock = function (block, cb) { var self = this var blockHash = block.hash().toString('hex') var parentDetails var dbOps = [] if (block.constructor !== Block) { block = new Block(block) } async.series([ function verify (cb2) { if (!self.validate) { return cb2() } if (self.meta.genesis && block.isGenesis()) { return cb2('already have genesis set') } block.validate(self, cb2) }, function verifyPOW (cb2) { if (!self.validate) { return cb2() } self.ethash.verifyPOW(block, function (valid) { if (valid) { cb2() } else { cb2('invalid POW') } }) }, // look up the parent meta info function parentInfo (cb2) { // if genesis block if (block.isGenesis()) { return cb2() } self.getDetails(block.header.parentHash, function (err, pd) { parentDetails = pd if (!err && pd) { cb2(null, pd) } else { cb2('parent hash not found') } }) }, function rebuildInfo (cb2) { // calculate the total difficulty for this block var td = new BN(utils.bufferToInt(block.header.difficulty)) // add this block as a child to the parent's block details if (!block.isGenesis()) { td.iadd(new BN(parentDetails.td)) parentDetails.staleChildren.push(blockHash) } // store the block details var blockDetails = { parent: block.header.parentHash.toString('hex'), td: td.toString(), number: utils.bufferToInt(block.header.number), child: null, staleChildren: [], genesis: block.isGenesis() } dbOps.push({ type: 'put', key: 'detail' + blockHash, valueEncoding: 'json', value: blockDetails }) // store the block dbOps.push({ type: 'put', key: blockHash, valueEncoding: 'binary', value: block.serialize() }) if (td.cmp(self.meta.td) === 1 || block.isGenesis()) { blockDetails.inChain = true self.meta.rawHead = blockHash self.meta.height = utils.bufferToInt(block.header.number) self.meta.td = td // index by number dbOps.push({ type: 'put', key: parseInt(block.header.number.toString('hex'), 16).toString(), value: blockHash }) // save meta dbOps.push({ type: 'put', key: 'meta', valueEncoding: 'json', value: self.meta }) if (!block.isGenesis()) { self._rebuildBlockchain(blockHash, block.header.parentHash, parentDetails, dbOps, cb2) } else { self.meta.genesis = blockHash cb2() } } else { dbOps.push({ type: 'put', key: 'detail' + block.header.parentHash.toString('hex'), valueEncoding: 'json', value: parentDetails }) cb2() } }, function save (cb2) { self.db.batch(dbOps, cb2) } ], cb) } /** *Gets a block by its hash * @method getBlock * @param {String|Buffer|Number} hash - the sha256 hash of the rlp encoding of the block * @param {Function} cb - the callback function */ Blockchain.prototype.getBlock = function (hash, cb) { var self = this var block this.db.get(hash.toString('hex'), { valueEncoding: 'binary' }, function (err, value) { if (err) { return cb(err) } // if blockhash if (value.length === 32) { self.db.get(hash, function (err, block) { if (err) return cb(err) block = new Block(rlp.decode(value)) cb(err, block) }) } else { block = new Block(rlp.decode(value)) cb(err, block) } }) } /** * Gets a block by its hash * @method getBlockInfo * @param {String} hash - the sha256 hash of the rlp encoding of the block * @param {Function} cb - the callback function */ Blockchain.prototype.getDetails = function (hash, cb) { this.db.get('detail' + hash.toString('hex'), { valueEncoding: 'json' }, cb) } /** * Gets a block by its hash * @method getBlockInfo * @param {String} hash - the sha256 hash of the rlp encoding of the block * @param {Function} cb - the callback function */ Blockchain.prototype.putDetails = function (hash, val, cb) { this.db.put('detail' + hash.toString('hex'), val, { valueEncoding: 'json' }, cb) } Blockchain.prototype.iterator = function (func, name, cb) { var self = this var blockhash = this.meta['head' + name] || this.meta.genesis var lastBlock this.getDetails(blockhash, function (err, d) { if (err) cb(err) blockhash = d.child async.whilst(function () { return blockhash }, run, function () { self._saveMeta(cb) }) }) function run (cb2) { var details, block async.series([ function getDetails (cb3) { self.getDetails(blockhash, function (err, d) { details = d if (d) { self.meta.heads[name] = blockhash } cb3(err) }) }, function getBlock (cb3) { self.getBlock(blockhash, function (err, b) { block = b cb3(err) }) }, function runFunc (cb3) { var reorg = lastBlock ? lastBlock.hash().toString('hex') !== block.header.parentHash.toString('hex') : false lastBlock = block func(block, reorg, cb3) }, function saveDetails (cb3) { details[name] = true self.putDetails(blockhash, details, cb3) } ], function (err) { if (!err) { blockhash = details.child } else { blockhash = false } cb2(err) }) } } /** * Given an ordered array, returns to the callback an array of hashes that are * not in the blockchain yet * @method selectNeededHashes * @param {Array} hashes * @param {function} cb the callback */ Blockchain.prototype.selectNeededHashes = function (hashes, cb) { var max, mid, min var self = this max = hashes.length - 1 mid = min = 0 async.whilst(function () { return max >= min }, function (cb2) { self.getBlockInfo(hashes[mid], function (err, hash) { if (!err && hash) { min = mid + 1 } else { max = mid - 1 } mid = Math.floor((min + max) / 2) cb2() }) }, function (err) { cb(err, hashes.slice(min)) }) } Blockchain.prototype._saveMeta = function (cb) { this.db.put('meta', this.meta, { keyEncoding: 'json' }, cb) } // builds the chain double link list from the head to the tail. // TODO wrap in a semiphore Blockchain.prototype._rebuildBlockchain = function (hash, parentHash, parentDetails, ops, cb) { var self = this var ppDetails, staleHash parentHash = parentHash.toString('hex') parentDetails.child = hash ops.push({ type: 'put', key: 'detail' + parentHash, valueEncoding: 'json', value: parentDetails }) var i = parentDetails.staleChildren.indexOf(hash) if (i !== -1) { parentDetails.staleChildren.splice(i, 1) } if (parentDetails.child && parentDetails.child !== hash) { parentDetails.staleChildren.push(parentDetails.child) } parentDetails.child = hash if (parentDetails.inChain) return cb() parentDetails.inChain = true async.series([ function loadNumberIndex (done) { self.db.get(parentDetails.number, function (err, s) { staleHash = s.toString('hex') done(err) }) }, function loadStaleDetails (done) { if (!staleHash) return done() self.getDetails(staleHash, function (err, staleDetails) { staleDetails.inChain = false ops.push({ type: 'put', key: staleDetails.number, value: hash }) ops.push({ type: 'put', key: 'detail' + staleHash, value: staleDetails, valueEncoding: 'json' }) done(err) }) }, function getNextDetails (done) { self.getDetails(parentDetails.parent, function (err, d) { ppDetails = d done(err) }) } ], function () { self._rebuildBlockchain(parentHash, parentDetails.parent, ppDetails, ops, cb) }) } // todo add SEMIPHORE; the semiphore // also this doesn't reset the heads Blockchain.prototype.delBlock = function (blockhash, cb) { var self = this var dbOps = [] var resetHeads = [] if (!Buffer.isBuffer(blockhash)) { blockhash = blockhash.hash() } function buildDBops (cb2) { self._delBlock(blockhash, dbOps, resetHeads, cb2) } function getLastDeletesDetils (cb2) { self.getDetails(blockhash.toString('hex'), function (err, details) { if (details.inChain) { self.meta.rawHead = details.parent } resetHeads.forEach(function (head) { self.meta.heads[head] = details.parent }) cb2(err) }) } function runDB (cb2) { self.db.batch(dbOps, cb2) } async.series([ buildDBops, getLastDeletesDetils, runDB ], cb) } Blockchain.prototype._delBlock = function (blockhash, dbOps, resetHeads, cb) { var self = this var details dbOps.push({ type: 'del', key: 'detail' + blockhash.toString('hex') }) // delete the block dbOps.push({ type: 'del', key: blockhash.toString('hex') }) async.series([ function getDetails (cb2) { self.getDetails(blockhash, function (err, d) { for (var head in self.meta.heads) { if (blockhash.toString('hex') === self.meta.heads[head]) { resetHeads.push(head) } } details = d cb2(err) }) }, function removeChild (cb2) { if (details.child) { self._delBlock(details.child, dbOps, resetHeads, cb2) } else { cb2() } }, function removeStaleChildern (cb2) { if (details.staleChildren) { async.each(details.staleChildern, function (child, cb3) { self._delBlock(child, dbOps, resetHeads, cb3) }, function (err) { cb2(err, details) }) } else { cb2(null, details) } } ], cb) }
vaporry/ethereumjs-blockchain
index.js
JavaScript
gpl-2.0
13,252
/** * --------------------------------------------------------------------- * GLPI - Gestionnaire Libre de Parc Informatique * Copyright (C) 2015-2021 Teclib' and contributors. * * http://glpi-project.org * * based on GLPI - Gestionnaire Libre de Parc Informatique * Copyright (C) 2003-2014 by the INDEPNET Development Team. * * --------------------------------------------------------------------- * * LICENSE * * This file is part of GLPI. * * GLPI is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * GLPI is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GLPI. If not, see <http://www.gnu.org/licenses/>. * --------------------------------------------------------------------- */ // 'tinymce' and 'tinyMCE' objects have to be declared in global scope window.tinymce = window.tinyMCE = require('tinymce/tinymce'); // Base theme require('tinymce/themes/modern/theme'); // Used plugins require('tinymce/plugins/table'); require('tinymce/plugins/directionality'); require('tinymce/plugins/searchreplace'); require('tinymce/plugins/tabfocus'); require('tinymce/plugins/autoresize'); require('tinymce/plugins/link'); require('tinymce/plugins/image'); require('tinymce/plugins/paste'); require('tinymce/plugins/code'); require('tinymce/plugins/fullscreen'); require('tinymce/plugins/textcolor'); require('tinymce/plugins/colorpicker'); require('tinymce/plugins/lists'); // Custom plugins require('../tiny_mce/custom_plugins/stickytoolbar/plugin')
smartcitiescommunity/Civikmind
lib/bundles/tinymce.js
JavaScript
gpl-2.0
1,921
/** * MessageFormat Class - Custom formatting used with 'vue-i18n' * * https://messageformat.github.io/messageformat/MessageFormat * **/ import MessageFormat from 'messageformat' export default class CustomFormatter { constructor (options = {}) { // set locale this._locale = options.locale || 'en-US' // instanstantiate formatter this._formatter = new MessageFormat(this._locale) // initialize object cache this._caches = Object.create(null) } interpolate (message, values) { // reference cache let fn = this._caches[message] if (!fn) { // no cache, compile once fn = this._formatter.compile(message, this._locale) // cache this._caches[message] = fn } return [fn(values)] } }
inverse-inc/packetfence
html/pfappserver/root/src/utils/formatter.js
JavaScript
gpl-2.0
760
/** * Created by barak on 01/08/2015. */
BrkCoder/angularjs-resources
src/js/directives/ng-carousel.js
JavaScript
gpl-2.0
43
//////// about encryption (old PGP.js) var keyring; function initKeys(){ if (debug){ console.log("Initializing keyring"); } // Keys if (keyring == undefined) { keyring = generateKeyring(); } } // create keyring and import keys from localstore function generateKeyring(){ var keyring = new openpgp.Keyring(); if (debug){ console.log("--generateKeyRing"); console.log(keyring.getAllKeys()); } return keyring; } function newKeyPair(keyring,username,mail,passphrase){ /*var options = { numBits: 2048, //4096 userId: 'Test User <testuser@testserver.com>', passphrase: 'abcd1234567890' };*/ var options = { numBits: 2048, userId: username + ' <' + mail +'>', passphrase: passphrase }; return openpgp.generateKeyPair(options).then(function(keyPair) { // private key = keyPair.privateKeyArmored // public key = keyPair.publicKeyArmored keyring.privateKeys.importKey(keyPair.privateKeyArmored); // TO DO: To store private key ENCRYPTED keyring.publicKeys.importKey(keyPair.publicKeyArmored); keyring.store(); if (debug){ console.log("--newKeyPair: "); console.log(keyPair.privateKeyArmored); console.log(keyPair.publicKeyArmored); } return true }).catch(function(error) { //TO DO console.log(error); return false }); } /* TODO not to use global keyring to handle response (errors) to parse input key -- the key is updated if it is already in the keyring */ function importPublicKey(keyring, key){ // PUBLIC keyring.publicKeys.importKey(key); keyring.store(); return true; //TO DO } /* TODO not to use global keyring to handle response (errors) to parse input key -- the key is updated if it is already in the keyring */ function importMyKeys(keyring, key){ // PRIVATE keyring.privateKeys.importKey(key); keyring.publicKeys.importKey(key); keyring.store(); return true; //TO DO } function getPublicKeysByEmail(email){ var keyArray = keyring.publicKeys; var keys = keyArray.getForAddress(email); return keys; } //gets private keys with decrypted secret data function getPrivateKeysByEmail(email, password){ var keyArray = keyring.privateKeys; var keys = keyArray.getForAddress(email); for(i=0;i<keys.length;i++){ keys[i].decrypt(password); } return keys; } /* TO DO: more than one email address error */ function encrypt(text, emails){ //email = "testuser@testserver.com"; email = emails[0]; // TO DO: MORE THAN ONE EMAIL ADDRESS var pubKeys = getPublicKeysByEmail(email); return openpgp.encryptMessage(pubKeys, text)/*.catch(function(error) { //console.log(error); //return false })*/ } function sign(text, email){ // signClearMessage(privateKeys, text) //email = "testuser@testserver.com"; //password = "abcd1234567890"; var password = sessionStorage.getItem('psph'); if(debug){ console.log("--Signing message with password: " + password); } var privKeys = getPrivateKeysByEmail(email, password); if(debug){ console.log("--Signing message: " + text); } return openpgp.signClearMessage(privKeys, text) } function decrypt(pgpMessage, emails){ //email = "testuser@testserver.com"; //password = "abcd1234567890"; var password = sessionStorage.getItem('psph'); email = emails[0]; var privKeys = getPrivateKeysByEmail(email, password); var privKey = privKeys[0]; if(debug){ console.log("--Decrypting message: " + pgpMessage); console.log("--email: " + email + " | password: "+ password + " | privKey" + privKey); } pgpMessage = openpgp.message.readArmored(pgpMessage); return openpgp.decryptMessage(privKey, pgpMessage); } function unsign(pgpMessage){ if(debug){ console.log("--Unsigning message: " + pgpMessage); } pgpMessage = openpgp.cleartext.readArmored(pgpMessage); return pgpMessage.text; } function verify(pgpMessage, email){ //email = "testuser@testserver.com"; var pubKeys = getPublicKeysByEmail(email); pgpMessage = openpgp.cleartext.readArmored(pgpMessage); return openpgp.verifyClearSignedMessage(pubKeys, pgpMessage); } //TO DO: not using the global variable keyring function getPublicKeys(){ var pubKeys = keyring.publicKeys.keys; var response = []; for(i=0;i<pubKeys.length;i++){ var userid = pubKeys[i].users[0].userId.userid; var armoredKey = pubKeys[i].toPublic().armor(); var key = {userId: userid, key: armoredKey}; response.push(key); } return response; } //TO DO: not using the global variable keyring function getPrivateKeys(){ var privKeys = keyring.privateKeys.keys; var response = []; for(i=0;i<privKeys.length;i++){ var userid = privKeys[i].users[0].userId.userid; var armoredKey = privKeys[i].armor(); var key = {userId: userid, key: armoredKey}; response.push(key); } return response; }
Avo21/PGProject
src/background/model.js
JavaScript
gpl-2.0
4,736
/** * Initialize our global space with a couple setup content and shared resources. */ var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-108087545-1']); _gaq.push(['_setSessionCookieTimeout', 0]); _gaq.push(['_trackPageview', '/background']); var parser = document.createElement('a'); var state = {'count': 0, 'map': {}, 'flush': 0}; (function() { if (typeof localStorage.cfg_init === "undefined") { localStorage.cfg_init = true; localStorage.cfg_threshold = 5; // When to throw away noisy hosts localStorage.cfg_purge = 15; // How often to purge our state machine localStorage.cfg_auto_crawl = false; localStorage.cfg_auto_extract = false; localStorage.cfg_debug = false; localStorage.cfg_crawl_server = '--YOUR-SERVER-HERE--'; localStorage.cfg_crawl_token = '--YOUR-TOKEN-HERE--'; localStorage.cfg_crawl_key = '--YOUR-KEY-HERE--'; localStorage.cfg_profiles = JSON.stringify([]); localStorage.cfg_active_profile = ''; chrome.tabs.create({'url': OPTIONS_PAGE}); } var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = false; ga.src = 'https://ssl.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); /** Reset the state machine */ function flushState() { // This keeps our view of the world from being too bias. state = {'count': 0, 'map': {}, 'flush': 0}; } /** Sync state machine with observations from page content */ function syncState(map) { for (var key in map) { if (state.map.hasOwnProperty(key)) { state.map[key] += map[key]; } else { state.map[key] = map[key]; } } } /** * Submit Crawl Candidates * Take the payload created from our other processes and send it along to the * crawler API. This function will handle the authentication and entire post * processing back to the server. */ function submitCrawls(payload) { console.log("Submitting crawls."); payload = JSON.stringify(payload); var key = localStorage.cfg_crawl_token + ":" + localStorage.cfg_crawl_key; var auth = window.btoa(key); var properties = {method: "POST", body: payload, headers: {"Accept": "application/json", "Content-Type": "application/json", "Authorization": "Basic " + auth}}; fetch(localStorage.cfg_crawl_server, properties) .then(function(response) { return response.json(); }) .then(function(payload) { if (localStorage.cfg_debug === 'true') { console.log("Extension synced with the server."); } chrome.browserAction.setBadgeText({"text": String(0)}); _gaq.push(['_trackEvent', 'extension', 'crawls_submitted']); }) .catch(function(error) { console.log("ERROR", error); chrome.browserAction.setBadgeText({"text": String(-1)}); }); } /** * Process Events * Go through local storage and extract any of the saved URL information that * we collected and send it off to the landing page crawlers. As we prepare the * entries, we will remove them from storage. There's no real error handling in * this process. */ function processEvents() { var _saved = 0; var _discard = 0; if (localStorage.cfg_configured !== 'true') { if (localStorage.cfg_debug === 'true') { console.log("Extension has not been configured"); } return false; } var entries = []; for (var i = 0; i < localStorage.length; i++) { if (localStorage.key(i).substring(0, 4) === "cfg_") { continue; } var url = localStorage.getItem(localStorage.key(i)); var obj = {'url': url}; var sm = derive_state(url); if (state.map[sm] < parseInt(localStorage.cfg_threshold)) { entries.push(obj); _saved += 1; } else { _discard += 1; } localStorage.removeItem(localStorage.key(i)); } state.flush += 1; if (localStorage.cfg_debug === 'true') { console.log("Saved", _saved, "Discarded", _discard, "State", state); } if (state.flush >= parseInt(localStorage.cfg_purge)) { flushState(); } if (entries.length === 0) { if (localStorage.cfg_debug === 'true') { console.log("No new entries to submit for crawling."); } return false; } var prepped = {'entry': entries}; submitCrawls(prepped); } function extractLinks(message) { if (localStorage.cfg_auto_extract !== 'true' && !message.manual) { if (localStorage.cfg_debug === 'true') { console.log("Auto-extract is not set to process."); } return false; } var matches = []; var regmap = ['url']; for (var idx in regmap) { var rx = new RegExp(PATTERNS[regmap[idx]]); while((match = rx.exec(message.content)) !== null) { matches.push(match[0].toLowerCase()); } } matches = validTLD(matches); syncState(buildHostMap(matches)); matches = uniq(matches); var entries = []; for (var i = 0; i < matches.length; i++) { var sm = derive_state(matches[i]); if (state.map[sm] > parseInt(localStorage.cfg_threshold)) { continue; } entries.push({'url': matches[i]}); } var prepped = {'entry': entries}; submitCrawls(prepped); chrome.browserAction.setBadgeText({"text": String(entries.length)}); } /** * Alarm Listener * Listen for any Chrome-generated alarms and route the request to the proper * functions. These alarms get setup at the start of the extension. */ chrome.alarms.onAlarm.addListener(function(alarm) { if (alarm.name == "processEvents") { processEvents(); } }); /** * Network Interceptor * Look at all network requests happening in the browser and process the URLs * into localstorage if they match the types of request we care about. In an * effort to reduce the noise, we only load scripts, websites and AJAX requests. * Since we can't send the amount of data in real-time, we hash the URL and * store that inside of localstorage. An alarm will trigger in order to send * the information out to the crawlers. */ chrome.webRequest.onBeforeRequest.addListener( function(data) { if (localStorage.cfg_auto_crawl !== 'true') { if (localStorage.cfg_debug === 'true') { // console.log("Auto-crawling is not set to process."); } return {cancel: false}; } focus = ['xmlhttprequest', 'script', 'main_frame']; if (focus.indexOf(data.type) == -1) { return {cancel: false}; } var h = md5(data.url); localStorage[h] = data.url; var sm = derive_state(data.url); if (state.map.hasOwnProperty(sm)) { state.map[sm] += 1; } else { state.map[sm] = 1; } state.count += 1; return {cancel: false}; }, {urls: ["<all_urls>"]}, ["blocking"] ); /** * Context Menus * This dog knows a couple tricks. For cases when the user wants to manually * submit a url, or link from within a page, they can do so with custom context * menus. This handler will route the information to the proper place. When * handling in-page links, we smartly identify the item the user wishes to * crawl by looking at the submission context. If there's a `linkUrl`, then * we know the user submitted a hyper-link. If not, then we fall back to the * text of the submission and perform some analysis on top of it. */ chrome.contextMenus.onClicked.addListener(function(info, tab) { if (info.menuItemId === "options") { chrome.tabs.create({'url': OPTIONS_PAGE}); return false; } var entries = [{'url': info.pageUrl}]; if (info.hasOwnProperty('linkUrl')) { entries.push({'url': info.linkUrl}); } var matches = []; var regmap = ['domain', 'ip']; for (var idx in regmap) { var rx = new RegExp(PATTERNS[regmap[idx]]); while((match = rx.exec(info.selectionText)) !== null) { matches.push(match[0]); } } if (matches.length > 0) { if (info.selectionText.substring(0,4) !== 'http') { entries.push({'url': addProtocol(info.selectionText, 'http')}); entries.push({'url': addProtocol(info.selectionText, 'https')}); } else { entries.push({'url': info.selectionText}); } } var prepped = {'entry': entries}; _gaq.push(['_trackEvent', 'extension', 'context_submission']); submitCrawls(prepped); }); /** * Page Parser * Sniff, sniff! When users opt-in to having their pages inspected, we will * marshal the DOM over to this back-end handler. We start by first finding * all of the URLs within the page. From there, we prune anything without a * valid TLD. In order to reduce noise, we build and sync frequency for all * observed hosts. As a final pass, we check the hostname of the URL against * our aggregate state machine and prune anything over the set threshold. */ chrome.runtime.onMessage.addListener( function(request, sender, sendResponse) { if (request.msg === "page") { _gaq.push(['_trackEvent', 'extension', 'current_extract']); extractLinks(request); } if (request.msg === "crawl") { var entries = []; if (request.url.substring(0,4) !== 'http') { entries.push({'url': addProtocol(request.url, 'http')}); entries.push({'url': addProtocol(request.url, 'https')}); } else { entries.push({'url': request.url}); } var prepped = {'entry': entries}; _gaq.push(['_trackEvent', 'extension', 'manual_crawl']); submitCrawls(prepped); } if (request.msg === 'current_crawl') { chrome.tabs.query({active: true}, function(tabs) { if (tabs.length === 0) { return false; } var entries = [{'url': tabs[0]['url']}]; var prepped = {'entry': entries}; _gaq.push(['_trackEvent', 'extension', 'current_crawl']); submitCrawls(prepped); }); } if (request.msg === 'current_extract') { chrome.tabs.query({active: true}, function(tabs) { if (tabs.length === 0) { return false; } var tab = tabs[0]; chrome.tabs.executeScript(null, {file: JQUERY}); chrome.tabs.executeScript(tab.id, { code: 'window.woofWoofFBOverride = true;' }, function() { chrome.tabs.executeScript(tab.id, {file: INJECT}); }); }); } if (request.msg === 'options') { _gaq.push(['_trackEvent', 'extension', 'options_view']); chrome.tabs.create({'url': OPTIONS_PAGE}); } if (request.msg === 'reconfig') { if (request.hasOwnProperty('cfg_auto_crawl')) { if (request['cfg_auto_crawl'] === "true") { localStorage.cfg_auto_crawl = true; } else { localStorage.cfg_auto_crawl = false; } _gaq.push(['_trackEvent', 'extension', 'configure_auto_crawl']); } if (request.hasOwnProperty('cfg_auto_extract')) { if (request['cfg_auto_extract'] === "true") { localStorage.cfg_auto_extract = true; } else { localStorage.cfg_auto_extract = false; } _gaq.push(['_trackEvent', 'extension', 'configure_auto_extract']); } } if (request.msg === 'profile_change') { localStorage.cfg_crawl_server = request.cfg_crawl_server; localStorage.cfg_crawl_token = request.cfg_crawl_token; localStorage.cfg_crawl_key = request.cfg_crawl_key; _gaq.push(['_trackEvent', 'extension', 'change_profile']); } } ); chrome.extension.onRequest.addListener(function(request, sender, sendResponse) { if (request.method === "config") { sendResponse({'cfg_auto_crawl': localStorage.cfg_auto_crawl, 'cfg_auto_extract': localStorage.cfg_auto_extract}); } }); // Unleash the beagle! chrome.alarms.create("processEvents", {delayInMinutes: 0.1, periodInMinutes: 0.5}); chrome.runtime.onInstalled.addListener(loadContextMenus); chrome.runtime.onStartup.addListener(loadContextMenus);
9b/fatbeagle
extension/resources/js/core/background.js
JavaScript
gpl-2.0
12,852
/* * Copyright (C) 2009-2015 Pivotal Software, Inc * * This program is is free software; you can redistribute it and/or modify * it under the terms version 2 of the GNU General Public License as * published by the Free Software Foundation. * * 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 General Public License for more details. * * You should have received a copy of the GNU 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. */ ({"save":"Salva"})
pivotal/tcs-hq-management-plugin
com.springsource.hq.plugin.tcserver.serverconfig.web/src/main/webapp/dojox/editor/plugins/nls/it/Save.js
JavaScript
gpl-2.0
736
/* jslint node: true */ 'use strict'; var assert = require('assert'); describe('Canary', function () { it('should validate the set up', function () { assert.equal(true, true); }); });
WDOM/hoxio-2
server/test/canary.js
JavaScript
gpl-2.0
196
function navHeightFix() { var navHeight = jQuery('nav[role="navigation"]').outerHeight(); jQuery('body').css('margin-top',navHeight); } jQuery(document).ready(function($) { // Initialize Blazy var bLazy = new Blazy({ success: function(ele){ // Image has loaded // console.log('loaded',ele); if ( jQuery('.equalHeights').length ) { jQuery('.equalHeights').children().attr('style',''); jQuery('.equalHeights').equalHeights(); } } }); navHeightFix(); $('.menuToggle').click(function(e){ e.preventDefault(); $(this).parent().find('ul').first().slideToggle(); }); if ( $(window).width() < 1024 ) { $('.menu-item-has-children > a').one('click', function(e){ e.preventDefault(); $(this).parent().find('ul').first().slideToggle(); }); } $('.voucher-code-button').click(function(e){ vouchercode = $(this).data('voucher-code'); $(this).replaceWith('<input class="voucher-code-button" value="' + vouchercode + '" disabled="disabled" />'); // $(this).text(vouchercode); }); // Go Slider! by http://responsiveslides.com/ if ( $('.slides').length ) { $('.slides').responsiveSlides({ pager: false, nav: true, auto: true, timeout: 6000, speed: 1000, prevText: '&#9001;', nextText: '&#9002;' }); } // Top Nav show more // $('#menu-primary-nav li:last-child').click(function(e){ // e.preventDefault(); // var $toggle = $('#menu-primary-nav li:last-child'); // var more = 'More&nbsp;&raquo;'; // var less = '&laquo;&nbsp;Less'; // $toggle.toggleClass('active'); // if ( $toggle.hasClass('active') ) { // $toggle.find('a').html(less); // $('#menu-primary-nav li').show(); // } else { // $toggle.find('a').html(more); // $('#menu-primary-nav li').attr('style',''); // } // }); }); jQuery(window).load(function($){ if ( jQuery('.equalHeights').length ) { jQuery('.equalHeights').equalHeights(); } if ( jQuery('.index_ad_high').length ) { jQuery('.index_ad_high').css('min-height',''); } if ( jQuery('.slides').length ) { if ( jQuery(window).width() > 888 ) { jQuery('.slides').css({'width' : jQuery('.slides').width(), 'height' : jQuery('.slides').height()}).addClass('loaded'); } else { jQuery('.slides').removeAttr('style').removeClass('loaded'); } } }); jQuery(window).resize(function($){ navHeightFix(); if ( jQuery('.equalHeights').length ) { jQuery('.equalHeights').children().attr('style',''); jQuery('.equalHeights').equalHeights(); } if ( jQuery('.slides').length ) { var resizetimeout; jQuery('.slides').removeAttr('style').removeClass('loaded'); function resized(){ if ( jQuery(window).width() > 888 ) { jQuery('.slides').css({'width' : jQuery('.slides').width(), 'height' : jQuery('.slides').height()}).addClass('loaded'); } else { jQuery('.slides').removeAttr('style').removeClass('loaded'); } } clearTimeout(resizetimeout); resizetimeout = setTimeout(function() { resized(); }, 100); } });
jonheslop/LDNfashion
js/site.js
JavaScript
gpl-2.0
3,010
/** * jQuery behaviors for platform notification feeds. */ (function ($) { Drupal.behaviors.os_notifications = { attach: function (context, settings) { // Setup. var tourLink = '#os-tour-home'; var $tourLink = $(tourLink); if (!$tourLink.length) { return; } if (typeof hopscotch == 'undefined') { return; } $tourLink.attr('href', '#'); // Adds our tour overlay behavior with desired effects. $(tourLink, context).once('osTourHome', function() { $(this).wrap("<div class='os-tour-home-wrapper'></div>"); // When the page is first loaded, the "Take a tour" link is set to // `display: hidden`. Once the help modal is dismissed, it will appear, // and then remember not to attach this effect in the future. var eventName = 'drupalOverlayBeforeClose'; var welcomePage = 'body.page-cp-welcome'; $(document).bind(eventName, function(event) { if (!$("#overlay-container").find("iframe").contents().find(welcomePage).length) { return; } if ($('#os-tour-home').length) { // Settings Gear offsets for HWPI Classic default flavor. var settingsXOffset = 945; var settingsYOffset = 47; // Settings Gear offsets for HWPI Classic Indigo flavor w/ HWP Personal sidebar widget. if ($('#block-boxes-hwp-personal-contact-html').length) { settingsXOffset = 625; settingsYOffset = 36; } var tour = { showPrevButton: true, scrollTopMargin: 100, id: "os-tour-home", steps: [ { title: 'Welcome!', content: 'In this short tour, you\'ll learn all about how to build and manage your site.', target: document.querySelector('#header'), placement: "bottom", yOffset: -20 }, { title: 'Home: You are here', content: 'You can always go back home by clicking on this icon.', target: document.querySelector('#toolbar-home'), placement: "bottom" }, { title: 'Content: The master list', content: 'Click here to view and manage every single post of content on your site.<br/><br/>Hover to:<ul><li><strong>Add</strong> new pages and posts</li><li><strong>Find</strong> your existing posts and files</li><li><strong>Import</strong> new content in bulk from a file or a feed URL</li></ul>', target: document.querySelector('#toolbar-menu'), placement: "bottom", yOffset: 100, onShow: function() { $('#toolbar-menu li:first a').mouseover(); } }, { title: 'Build: Shape your site', content: 'Organize your site how you want.<ul><li><strong>Apps</strong>: the one-stop shop for new site sections</li><li><strong>Layout</strong>: add and drag \'n drop widgets where you want on the page</li><li><strong>Menu</strong>: control your sitemap and how users navigate your site</li><li><strong>Taxonomy</strong>: define categories to tag and organize posts in rich ways</li></ul>', target: document.querySelector('#toolbar-menu'), placement: "bottom", xOffset: 80, yOffset: 80, onShow: function() { $('#toolbar-menu li:nth-child(2) a').mouseover(); }, onNext: function() { $('#toolbar-menu li:nth-child(2) a').mouseout(); } }, { title: 'Appearance: Try on a new look', content: 'Switch up your color pallet, or try a completely different look and feel from many available themes.', target: document.querySelector('#toolbar-menu'), placement: "bottom", xOffset: 160 }, { title: 'Settings: Advanced options and features', content: 'Install Google Analytics for visitor tracking, change your site privacy settings, and much more.', target: document.querySelector('#toolbar-menu'), placement: "bottom", xOffset: 243, yOffset: 38, onShow: function() { $('#toolbar-menu li:nth-child(4) a').mouseover(); } }, { title: 'People: Add members to your site', content: 'Invite people by email to allow access or various levels of administrator privileges.', target: document.querySelector('#toolbar-menu'), placement: "bottom", xOffset: 313, yOffset: 38, onShow: function() { $('#toolbar-menu li:nth-child(5) a').mouseover(); }, onNext: function() { $('#toolbar-menu li:nth-child(5) a').mouseover(); } }, { title: 'Section settings', content: 'Every page on your site has a section settings gear like this one.<br/><br/>In fact, hover almost anywhere and you\'ll start seeing even more little gears...', target: document.querySelector('#block-os-primary-menu'), placement: "left", xOffset: settingsXOffset, yOffset: settingsYOffset, }, { title: 'Let\'s get started!', content: 'We hope you enjoyed this tour. Be sure to use the <strong>Support</strong> link to tell us what you think, or to ask any questions if something comes up.<br/><br/>Thanks, and happy site building!', target: document.querySelector('#toolbar-menu'), placement: "bottom", xOffset: 380, yOffset: 34, onShow: function() { $('#toolbar-menu li:nth-child(6) a').mouseover(); }, onNext: function() { $('#toolbar-menu li:nth-child(6) a').mouseout(); } } ] }; hopscotch.startTour(tour); } }); }); } }; })(jQuery);
RoySegall/OS-drop7
profiles/openscholar/modules/os/modules/os_tour/theme/os_tour.home.js
JavaScript
gpl-2.0
6,457
var moment = require('moment'), fb = require('fbgraph'), moment = require('moment'), oneDay = moment.duration(1, 'days').asMilliseconds(), logger = require('../util/logger'), birthday = require('./birthday'), posts = require('./posts'), intervalId = null, friends = []; function munge() { try { if (friends.lenght <= 0) stopMunging(); var friend = friends.pop(); logger.debug("Now munging data for " + friend.name); birthday.isClose(friend); posts.likeable(friend); if (friends.length <= 0) { // all friends processed, stop munging logger.debug('Clearing Interval'); stopMunging() } } catch (e) { throw new Error(e); } } function stopMunging() { clearInterval(intervalId); } function iterate(err, res) { if (err) logger.log(err); friends = friends.concat(res.data); if (res.paging && res.paging.next) { fb.get(res.paging.next, iterate); } if (!res.paging || !res.paging.next) { // friends.reverse(); var interval = oneDay / (friends.length + 1); logger.log('munge interval ' + moment.duration(interval).humanize()); munge(); intervalId = setInterval(munge, interval); } }; module.exports.start = function() { var fieldsStr = 'id,name,birthday,gender,first_name,name,link'; fb.get('me/friends?fields=' + fieldsStr, iterate); } /* // something like this needs to replace current module so that it'll run forever and ever var friendsCron = new cron({ cronTime: '00 01 00 * * *', onTick: function() { fb.get('me/friends?fields=id,name,birthday', iterate); }, start: false }); module.exports = friendsCron;*/
rishibaldawa/FacebookReport
js/fb/friends.js
JavaScript
gpl-2.0
1,764
/** * External dependencies */ import refx from 'refx'; import multi from 'redux-multi'; /** * Internal dependencies */ import routing from './routing/middleware'; import requests from './requests/middleware'; import effects from './effects'; export default [ multi, refx( effects ), routing, requests ];
aduth/dones
src/state/middlewares.js
JavaScript
gpl-2.0
311
var searchData= [ ['histogram_2efinc_2742',['histogram.finc',['../histogram_8finc.html',1,'']]] ];
reinh-bader/fgsl
doc/html/search/files_7.js
JavaScript
gpl-2.0
101
var container = require("container"); var vertxTests = require("vertx_tests"); var vassert = require("vertx_assert"); // The test methods must begin with "test" function test_1() { vassert.testComplete() } function test_2() { vassert.assertEquals("foo", "foo") vassert.testComplete() } var script = this; container.deployModule(java.lang.System.getProperty("vertx.modulename"), function(err, depID) { vassert.assertNull("err is not null", err); vertxTests.startTests(script); });
menzelths/scrabble
src/test/resources/integration_tests/javascript/mytest.js
JavaScript
gpl-2.0
496
function T4_CrossProviderTests() { //oData ComplexTypeTests({ name: 'oData', oDataServiceHost: "http://localhost:9000/odata", serviceUrl: 'http://localhost:9000/odata', dbCreation: $data.storageProviders.DbCreationType.DropAllExistingTables}, 'oDataV4'); //LiveArrayTests({ name: 'oData', oDataServiceHost: "http://localhost:9000/odata", serviceUrl: 'http://localhost:9000/odata', dbCreation: $data.storageProviders.DbCreationType.DropAllExistingTables }, 'oDataV4'); BatchExecuteQueryTests({ name: 'oData', oDataServiceHost: "http://localhost:9000/odata", serviceUrl: 'http://localhost:9000/odata', dbCreation: $data.storageProviders.DbCreationType.DropAllExistingTables }, 'oDataV4'); //BatchExecuteQueryTests({ name: 'oData', oDataServiceHost: "http://localhost:9000/odata", serviceUrl: 'http://localhost:9000/odata', dbCreation: $data.storageProviders.DbCreationType.DropAllExistingTables }, 'oDataV3'); //sqLite/WebSql if ($data.StorageProviderLoader.isSupported('sqLite')) { ComplexTypeTests({ name: 'sqLite', databaseName: 'ComplexTypeTests_T4', dbCreation: $data.storageProviders.DbCreationType.DropAllExistingTables }, 'sqLite'); //LiveArrayTests({ name: 'sqLite', databaseName: 'LiveArrayTests_T4', dbCreation: $data.storageProviders.DbCreationType.DropAllExistingTables }, 'sqLite'); if ($data.storageProviders.sqLitePro) { EntityContextOnUpdateTests({ name: 'sqLite', dbCreation: $data.storageProviders.DbCreationType.DropAllExistingTables }, 'sqLite'); } BatchExecuteQueryTests({ name: 'sqLite', databaseName: 'BatchExecuteQueryTests_T4', dbCreation: $data.storageProviders.DbCreationType.DropAllExistingTables }, 'sqLite'); } //indexedDb if ($data.StorageProviderLoader.isSupported('indexedDb')) { ComplexTypeTests({ name: 'indexedDb', databaseName: 'ComplexTypeTests_T4', dbCreation: $data.storageProviders.DbCreationType.DropAllExistingTables }, 'indexedDb'); //LiveArrayTests({ name: 'indexedDb', databaseName: 'LiveArrayTests_T4', dbCreation: $data.storageProviders.DbCreationType.DropAllExistingTables }, 'indexedDb'); if ($data.storageProviders.indexedDbPro) { EntityContextOnUpdateTests({ name: 'indexedDb', dbCreation: $data.storageProviders.DbCreationType.DropAllExistingTables }, 'indexedDb'); } BatchExecuteQueryTests({ name: 'indexedDb', databaseName: 'BatchExecuteQueryTests_T4', dbCreation: $data.storageProviders.DbCreationType.DropAllExistingTables }, 'indexedDb'); } //InMemory ComplexTypeTests({ name: 'InMemory', databaseName: 'ComplexTypeTests_T4', dbCreation: $data.storageProviders.DbCreationType.DropAllExistingTables }, 'InMemory'); //LiveArrayTests({ name: 'InMemory', databaseName: 'LiveArrayTests_T4', dbCreation: $data.storageProviders.DbCreationType.DropAllExistingTables }, 'InMemory'); BatchExecuteQueryTests({ name: 'InMemory', databaseName: 'BatchExecuteQueryTests_T4', dbCreation: $data.storageProviders.DbCreationType.DropAllExistingTables }, 'InMemory'); //LocalStore ComplexTypeTests({ name: 'LocalStore', databaseName: 'ComplexTypeTests_T4', dbCreation: $data.storageProviders.DbCreationType.DropAllExistingTables }, 'LocalStore'); //LiveArrayTests({ name: 'LocalStore', databaseName: 'LiveArrayTests_T4', dbCreation: $data.storageProviders.DbCreationType.DropAllExistingTables }, 'LocalStore'); BatchExecuteQueryTests({ name: 'LocalStore', databaseName: 'BatchExecuteQueryTests_T4', dbCreation: $data.storageProviders.DbCreationType.DropAllExistingTables }, 'LocalStore'); } function _finishCb(context) { if (context.storageProvider.db && context.storageProvider.db.close) context.storageProvider.db.close(); start(); } ComplexTypeTests = function ComplexTypeTests(providerConfig, msg) { if (typeof module == 'function') module("ComplexTypeTests_" + (msg || '')); if(providerConfig.name !== "oData"){ test("Save and load complex values", 5*7+1, function () { stop(); (new $news.Types.NewsContext(providerConfig)).onReady(function (context) { for (var i = 0; i < 5; i++) { context.UserProfiles.add(new $news.Types.UserProfile({ FullName: 'FullName_' + i, Birthday: new Date(), Location: new $news.Types.Location({ Address: 'Address' + i, Zip: 1000 * (i + 1), Country: 'Country' + i, City: 'City' + i }), User: new $news.Types.User({ Email: 'email', LoginName: 'login' + i }) })); } context.saveChanges(function () { context.UserProfiles.toArray(function (res) { equal(res.length, 5, 'result count'); for (var i = 0; i < 5; i++) { equal(res[i] instanceof $news.Types.UserProfile, true, 'item is UserProfile'); equal(res[i].FullName, 'FullName_' + i, 'item[i].FullName is string'); equal(res[i].Location instanceof $news.Types.Location, true, 'item is UserProfile'); equal(res[i].Location.Address, 'Address' + i, 'item[i].Location.Address is string'); equal(res[i].Location.Zip, 1000 * (i + 1), 'item[i].Location.Zip is string'); equal(res[i].Location.Country, 'Country' + i, 'item[i].Location.Country is string'); equal(res[i].Location.City, 'City' + i, 'item[i].Location.City is string'); } _finishCb(context); }); }); }); }); test("Map complex values", 5 * 7 + 1, function () { stop(); (new $news.Types.NewsContext(providerConfig)).onReady(function (context) { for (var i = 0; i < 5; i++) { context.UserProfiles.add(new $news.Types.UserProfile({ FullName: 'FullName_' + i, Birthday: new Date(), Location: new $news.Types.Location({ Address: 'Address' + i, Zip: 1000 * (i + 1), Country: 'Country' + i, City: 'City' + i }), User: new $news.Types.User({ Email: 'email', LoginName: 'login' + i }) })); } context.saveChanges(function () { context.UserProfiles.map(function (it) { return { Location: it.Location } }).toArray(function (res) { equal(res.length, 5, 'result count'); for (var i = 0; i < 5; i++) { equal(res[i] instanceof $news.Types.UserProfile, false, 'item is UserProfile'); ok(res[i].FullName === undefined, 'item[i].FullName is string'); equal(res[i].Location instanceof $news.Types.Location, true, 'item is UserProfile'); equal(res[i].Location.Address, 'Address' + i, 'item[i].Location.Address is string'); equal(res[i].Location.Zip, 1000 * (i + 1), 'item[i].Location.Zip is string'); equal(res[i].Location.Country, 'Country' + i, 'item[i].Location.Country is string'); equal(res[i].Location.City, 'City' + i, 'item[i].Location.City is string'); } _finishCb(context); }); }); }); }); test("filter Complex value", 5 * 7 + 1, function () { if (typeof $data.storageProviders.IndexedDBPro !== undefined && msg === 'indexedDb') { expect(1); ok(true, 'not supported'); return; } stop(); (new $news.Types.NewsContext(providerConfig)).onReady(function (context) { for (var i = 0; i < 5; i++) { context.UserProfiles.add(new $news.Types.UserProfile({ FullName: 'FullName_' + i, Birthday: new Date(), Location: new $news.Types.Location({ Address: 'Address' + i, Zip: 1000 * (i + 1), Country: 'Country' + i, City: 'City' + i }), User: new $news.Types.User({ Email: 'email', LoginName: 'login' + i }) })); } context.saveChanges(function () { context.UserProfiles.filter(function (it) { return it.Location.Address.contains('Address') }).toArray(function (res) { equal(res.length, 5, 'result count'); for (var i = 0; i < 5; i++) { equal(res[i] instanceof $news.Types.UserProfile, true, 'item is UserProfile'); equal(res[i].FullName, 'FullName_' + i, 'item[i].FullName is string'); equal(res[i].Location instanceof $news.Types.Location, true, 'item is UserProfile'); equal(res[i].Location.Address, 'Address' + i, 'item[i].Location.Address is string'); equal(res[i].Location.Zip, 1000 * (i + 1), 'item[i].Location.Zip is string'); equal(res[i].Location.Country, 'Country' + i, 'item[i].Location.Country is string'); equal(res[i].Location.City, 'City' + i, 'item[i].Location.City is string'); } _finishCb(context); }); }); }); }); test("filter Complex value 2", 5 * 7 + 1, function () { if (typeof $data.storageProviders.IndexedDBPro !== undefined && msg === 'indexedDb') { expect(1); ok(true, 'not supported'); return; } stop(); (new $news.Types.NewsContext(providerConfig)).onReady(function (context) { for (var i = 0; i < 5; i++) { context.UserProfiles.add(new $news.Types.UserProfile({ FullName: 'FullName_' + i, Birthday: new Date(), Location: new $news.Types.Location({ Address: 'Address' + i, Zip: 1000 * (i + 1), Country: 'Country' + i, City: 'City' + i }), User: new $news.Types.User({ Email: 'email', LoginName: 'login' + i }) })); } context.saveChanges(function () { context.UserProfiles.filter(function (it) { return it.Location.Address.contains('Address') && it.Location.Zip < 9999 }).toArray(function (res) { equal(res.length, 5, 'result count'); for (var i = 0; i < 5; i++) { equal(res[i] instanceof $news.Types.UserProfile, true, 'item is UserProfile'); equal(res[i].FullName, 'FullName_' + i, 'item[i].FullName is string'); equal(res[i].Location instanceof $news.Types.Location, true, 'item is UserProfile'); equal(res[i].Location.Address, 'Address' + i, 'item[i].Location.Address is string'); equal(res[i].Location.Zip, 1000 * (i + 1), 'item[i].Location.Zip is string'); equal(res[i].Location.Country, 'Country' + i, 'item[i].Location.Country is string'); equal(res[i].Location.City, 'City' + i, 'item[i].Location.City is string'); } _finishCb(context); }); }); }); }); test("filter string values", 5 * 7 + 1, function () { stop(); (new $news.Types.NewsContext(providerConfig)).onReady(function (context) { for (var i = 0; i < 5; i++) { context.UserProfiles.add(new $news.Types.UserProfile({ FullName: 'FullName_' + i, Birthday: new Date(), Location: new $news.Types.Location({ Address: 'Address' + i, Zip: 1000 * (i + 1), Country: 'Country' + i, City: 'City' + i }), User: new $news.Types.User({ Email: 'email', LoginName: 'login' + i }) })); } context.saveChanges(function () { context.UserProfiles.filter(function (it) { return it.FullName.contains('Full') == true }).toArray(function (res) { equal(res.length, 5, 'result count'); for (var i = 0; i < 5; i++) { equal(res[i] instanceof $news.Types.UserProfile, true, 'item is UserProfile'); equal(res[i].FullName, 'FullName_' + i, 'item[i].FullName is string'); equal(res[i].Location instanceof $news.Types.Location, true, 'item is UserProfile'); equal(res[i].Location.Address, 'Address' + i, 'item[i].Location.Address is string'); equal(res[i].Location.Zip, 1000 * (i + 1), 'item[i].Location.Zip is string'); equal(res[i].Location.Country, 'Country' + i, 'item[i].Location.Country is string'); equal(res[i].Location.City, 'City' + i, 'item[i].Location.City is string'); } _finishCb(context); }); }); }); }); } test("orderby with null field Value", 5 * 2 + 1, function () { stop(); (new $news.Types.NewsContext(providerConfig)).onReady(function (context) { for (var i = 0; i < 5; i++) { context.Categories.add(new $news.Types.Category({ Title: i < 3 ? null : 'Title_' + i, })); } context.saveChanges(function () { context.Categories.orderBy('it.Title').toArray(function (res) { equal(res.length, 5, 'result count'); for (var i = 0; i < res.length; i++) { equal(res[i] instanceof $news.Types.Category, true, 'item is Category'); if (i < 3) { equal(res[i].Title, null, 'item[i].Title is string'); } else { equal(res[i].Title, 'Title_' + i, 'item[i].Title is string'); } } _finishCb(context); }); }); }); }); test("orderbyDesc with null field Value", 5 * 2 + 1, function () { stop(); (new $news.Types.NewsContext(providerConfig)).onReady(function (context) { for (var i = 0; i < 5; i++) { context.Categories.add(new $news.Types.Category({ Title: i < 3 ? null : 'Title_' + i, })); } context.saveChanges(function () { context.Categories.orderByDescending('it.Title').toArray(function (res) { equal(res.length, 5, 'result count'); for (var i = 0; i < res.length; i++) { equal(res[i] instanceof $news.Types.Category, true, 'item is Category'); if (i > 1) { equal(res[i].Title, null, 'item[i].Title is string' + res[i].Title); } else { equal(res[i].Title, 'Title_' + (res.length - i - 1), 'item[i].Title is string' + res[i].Title); } } _finishCb(context); }); }); }); }); if(providerConfig.name !== "oData"){ test("orderbyDESC orderbyASC", 5 * 4*2 + 1, function () { stop(); (new $news.Types.NewsContext(providerConfig)).onReady(function (context) { for (var i = 0; i < 5; i++) { context.TestTable2.add({ Id: $data.createGuid(), i0: 1, s0: 'value' + i }); context.TestTable2.add({ Id: $data.createGuid(), i0: 1, s0: 'value' + i }); context.TestTable2.add({ Id: $data.createGuid(), i0: 2, s0: 'value' + i }); context.TestTable2.add({ Id: $data.createGuid(), i0: 2, s0: 'value' + i }); } context.saveChanges(function () { context.TestTable2.orderByDescending('it.i0').orderBy('it.s0').toArray(function (res) { equal(res.length, 20, 'result count'); for (var i = 0; i < res.length; i++) { var i0 = i < 10 ? 2 : 1; equal(res[i].i0, i0, 'i0: ' + i0); var s0 = 'value' + Math.floor((i > 9 ? (i - 10) : i) / 2); equal(res[i].s0, s0, 's0: ' + s0); } _finishCb(context); }); }); }); }); } }; function EntityContextOnUpdateTests(providerConfig, msg) { if (typeof module == 'function') module("EntityContextOnUpdateTests_" + (msg || '')); test("onupdate dropdb", 5, function () { stop(); var pconf = JSON.parse(JSON.stringify(providerConfig)); var afterUpdate = false; pconf.databaseName = 'onupdate_test_1'; pconf.dbCreation = $data.storageProviders.DbCreationType.DropAllExistingTables; pconf.onUpdated = function (ctx, callback) { ok(ctx instanceof $data.EntityContext, "param1 is context"); equal(typeof callback.success, 'function', "param2 has success"); equal(typeof callback.error, 'function', "param2 has error"); equal(afterUpdate, false, "afterUpdate is false"); afterUpdate = true; callback.success(); }; (new $news.Types.NewsContext(pconf)).onReady(function (context) { equal(afterUpdate, true, "afterUpdate is false"); _finishCb(context); }); }); test("onupdate fail test", 2, function () { stop(); var pconf = JSON.parse(JSON.stringify(providerConfig)); var afterUpdate = false; pconf.databaseName = 'onupdate_test_2'; pconf.dbCreation = $data.storageProviders.DbCreationType.DropAllExistingTables; pconf.onUpdated = function (ctx, callback) { afterUpdate = true; callback.error(ctx); }; var ctx; (ctx = new $news.Types.NewsContext(pconf)).onReady(function (context) { ok(false, "context is onready"); _finishCb(context); }).fail(function () { ok(true, "context is onready failed"); equal(afterUpdate, true, "afterUpdate is false"); _finishCb(ctx); }); }); test("onupdate if db change - no changes", 1, function () { stop(); var pconf = JSON.parse(JSON.stringify(providerConfig)); var afterUpdate = false; pconf.databaseName = 'onupdate_test_3'; (new $news.Types.NewsContext(pconf)).onReady(function (context) { stop(); _finishCb(context); pconf.dbCreation = $data.storageProviders.DbCreationType.DropTableIfChange; pconf.onUpdated = function (ctx, callback) { ok(false, "onUpdated is running"); afterUpdate = true; callback.success(); }; (new $news.Types.NewsContext(pconf)).onReady(function (context) { equal(afterUpdate, false, "afterUpdate is false"); _finishCb(context); }); }); }); $data.Entity.extend('OUType1', { Id: { type: 'int', key: true, computed: true }, Title: { type: 'string' } }); $data.Entity.extend('OUType2', { Id: { type: 'int', key: true, computed: true }, Title: { type: 'string' }, Lead: { type: 'string' } }); $data.Entity.extend('OUType3', { Id1: { type: 'int', key: true }, Id2: { type: 'int', key: true }, Title: { type: 'string' } }); $data.EntityContext.extend('OUCTX1', { OUTypes1: { type: $data.EntitySet, elementType: OUType1 } }); $data.EntityContext.extend('OUCTX2', { OUTypes2: { type: $data.EntitySet, elementType: OUType2 } }); $data.EntityContext.extend('OUCTX3', { OUTypes1: { type: $data.EntitySet, elementType: OUType3 } }); $data.EntityContext.extend('OUCTX12', { OUTypes1: { type: $data.EntitySet, elementType: OUType1 }, OUTypes2: { type: $data.EntitySet, elementType: OUType2 } }); test("onupdate double context instance, first recreate", 2, function () { stop(); var pconf = JSON.parse(JSON.stringify(providerConfig)); var afterUpdate = false; pconf.databaseName = 'onupdate_test_4'; pconf.dbCreation = $data.storageProviders.DbCreationType.DropAllExistingTables; pconf.onUpdated = function (ctx, callback) { equal(afterUpdate, false, "onUpdated is first running"); afterUpdate = true; callback.success(); }; (new OUCTX1(pconf)).onReady(function (context) { equal(afterUpdate, true, "afterUpdate is true"); stop(); _finishCb(context); pconf.dbCreation = $data.storageProviders.DbCreationType.DropTableIfChange; (new OUCTX1(pconf)).onReady(function (context) { _finishCb(context); }); }); }); test("onupdate entity change", 4, function () { if (providerConfig.name == "indexedDb") { expect(1); ok(true, "Not supported"); return; } stop(); var pconf = JSON.parse(JSON.stringify(providerConfig)); var afterUpdate = false; pconf.databaseName = 'onupdate_test_5'; pconf.dbCreation = $data.storageProviders.DbCreationType.DropAllExistingTables; pconf.onUpdated = function (ctx, callback) { //2 times run ok(true, "onUpdated is running"); afterUpdate = true; callback.success(); }; (new OUCTX1(pconf)).onReady(function (context) { equal(afterUpdate, true, "afterUpdate is true"); stop(); _finishCb(context); afterUpdate = false; pconf.dbCreation = $data.storageProviders.DbCreationType.DropTableIfChange; (new OUCTX2(pconf)).onReady(function (context) { equal(afterUpdate, true, "afterUpdate is true"); _finishCb(context); }); }); }); test("onupdate context change", 4, function () { var doTest = function () { stop(); var pconf = JSON.parse(JSON.stringify(providerConfig)); var afterUpdate = false; pconf.databaseName = 'onupdate_test_6'; pconf.dbCreation = $data.storageProviders.DbCreationType.DropAllExistingTables; pconf.onUpdated = function (ctx, callback) { //2 times run ok(true, "onUpdated is running"); afterUpdate = true; callback.success(); }; (new OUCTX1(pconf)).onReady(function (context) { equal(afterUpdate, true, "afterUpdate is true"); stop(); _finishCb(context); afterUpdate = false; pconf.dbCreation = $data.storageProviders.DbCreationType.DropTableIfChange; (new OUCTX12(pconf)).onReady(function (context) { equal(afterUpdate, true, "afterUpdate is true"); _finishCb(context); }); }); }; if (providerConfig.name == "indexedDb") { var indexedDB = window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB || window.msIndexedDB; if (indexedDB.deleteDatabase) { stop(); var tran = indexedDB.deleteDatabase('onupdate_test_6') tran.onsuccess = function () { start(); doTest(); }; tran.onerror = function () { start(); expect(1); ok(true, "cannot delete database"); return; }; } else { expect(1); ok(true, "Not supported"); return; } } else { doTest(); } }); test("onupdate entity key change", 4, function () { if (providerConfig.name == "indexedDb" && !$data.storageProviders.indexedDbPro) { expect(1); ok(true, "Not supported"); return; } stop(); var pconf = JSON.parse(JSON.stringify(providerConfig)); var afterUpdate = false; pconf.databaseName = 'onupdate_test_7'; pconf.dbCreation = $data.storageProviders.DbCreationType.DropAllExistingTables; pconf.onUpdated = function (ctx, callback) { //2 times run ok(true, "onUpdated is running"); afterUpdate = true; callback.success(); }; (new OUCTX1(pconf)).onReady(function (context) { equal(afterUpdate, true, "afterUpdate is true"); stop(); _finishCb(context); afterUpdate = false; pconf.dbCreation = $data.storageProviders.DbCreationType.DropTableIfChange; (new OUCTX3(pconf)).onReady(function (context) { equal(afterUpdate, true, "afterUpdate is true"); _finishCb(context); }); }); }); test("onupdate populate before ready", 2, function () { stop(); var pconf = JSON.parse(JSON.stringify(providerConfig)); pconf.databaseName = 'onupdate_test_8'; pconf.dbCreation = $data.storageProviders.DbCreationType.DropAllExistingTables; pconf.onUpdated = function (ctx, callback) { $news.Types.NewsContext.generateTestData(ctx, function () { ok(true, "data created"); callback.success(); }); }; (new $news.Types.NewsContext(pconf)).onReady(function (context) { context.Categories.toArray({ success: function (res) { ok(res.length > 0, "context loaded data"); _finishCb(context); }, error: function (e) { ok(false, "context loaded data"); console.log(e); _finishCb(context); } }); }); }); }; /*function LiveArrayTests(providerConfig, msg) { if (typeof module == 'function') module("LiveArrayTests_" + (msg || '')); test("toLiveArray", 5, function () { stop(); (new $news.Types.NewsContext(providerConfig)).onReady(function (context) { $news.Types.NewsContext.generateTestData(context, function () { var result = context.Articles.toLiveArray(); result.then(function (r) { equal(result.length, 26, 'result is not empty'); ok(result === r, 'result is equal with promise result'); result.length = 5; equal(result.length, 5, 'result is changed'); result.refresh(); result.then(function () { equal(result.length, 26, 'result is not empty 2'); }).then(function () { equal(result.length, 26, 'result is not empty 3'); _finishCb(context); }); }); }); }); }); test("toLiveArray - paging", 7, function () { stop(); (new $news.Types.NewsContext(providerConfig)).onReady(function (context) { $news.Types.NewsContext.generateTestData(context, function () { var result = context.Articles.take(5).toLiveArray(); result.then(function () { equal(result.length, 5, 'result is not empty'); var title = result[0].Title; result.next(); equal(result.length, 5, 'result is not empty before next'); result.then(function () { equal(result.length, 5, 'result is not empty 2'); var title2 = result[0].Title; notEqual(title2, title, 'result is paged'); result.prev(); equal(result.length, 5, 'result is not empty before prev'); result.then(function () { equal(result.length, 5, 'result is not empty 2'); equal(result[0].Title, title, 'result is paged back'); _finishCb(context); }); }); }); }); }); }); }*/ function BatchExecuteQueryTests(providerConfig, msg) { if (typeof module == 'function') module("BatchExecuteQueryTests_" + (msg || '')); test('missing queryable', 2, function () { stop(); (new $news.Types.NewsContext(providerConfig)).onReady(function (context) { context.batchExecuteQuery("alma", { success: function () { ok(false, 'success callback called'); } }).then(function (err) { ok(false, 'promise then called'); }).fail(function (err) { equal(err.message, '$data.Queryable is missing in queryableOptions at index 0', 'promise fail $data.Queryable is missing in queryableOptions at index 0'); }).always(function (err) { equal(err.message, '$data.Queryable is missing in queryableOptions at index 0', 'promise always $data.Queryable is missing in queryableOptions at index 0'); _finishCb(context); }); }); }); test('different entity context', 2, function () { stop(); (new $news.Types.NewsContext(providerConfig)).onReady(function (context) { var cfg = JSON.parse(JSON.stringify(providerConfig)); cfg.databaseName += "_test"; (new $news.Types.NewsContext(cfg)).onReady(function (context2) { context.batchExecuteQuery([context2.Articles], function () { ok(false, 'success callback called'); }).then(function (err) { ok(false, 'promise then called'); }).fail(function (err) { equal(err.message, 'Queryable at index 0 contains different entity context', 'promise fail Queryable at index 0 contains different entity context'); }).always(function (err) { equal(err.message, 'Queryable at index 0 contains different entity context', 'promise fail Queryable at index 0 contains different entity context'); _finishCb(context); _finishCb(context2); }); }); }); }); test('invalid frame method', 2, function () { stop(); (new $news.Types.NewsContext(providerConfig)).onReady(function (context) { context.batchExecuteQuery([[context.Articles, "filter"]], function () { ok(false, 'success callback called'); }).then(function (err) { ok(false, 'promise then called'); }).fail(function (err) { equal(err.message, 'Invalid frame method \'filter\' in queryableOptions at index 0', 'promise fail Invalid frame method \'filter\' in queryableOptions at index 0'); }).always(function (err) { equal(err.message, 'Invalid frame method \'filter\' in queryableOptions at index 0', 'promise fail Invalid frame method \'filter\' in queryableOptions at index 0'); _finishCb(context); }); }); }); test('one queryable', 4, function () { stop(); (new $news.Types.NewsContext(providerConfig)).onReady(function (context) { $news.Types.NewsContext.generateTestData(context, function () { context.batchExecuteQuery([context.Articles], function () { ok(true, 'success callback called'); }).then(function (result) { ok(result.length == 1, "has array result"); ok(result[0].length > 0, "has result"); ok(result[0][0] instanceof context.Articles.elementType); }).always(function (err) { _finishCb(context); }); }); }); }); test('queryables', 9, function () { stop(); (new $news.Types.NewsContext(providerConfig)).onReady(function (context) { $news.Types.NewsContext.generateTestData(context, function () { context.batchExecuteQuery([context.Articles, context.Articles.take(5), context.Categories], function () { ok(true, 'success callback called'); }).then(function (result) { ok(result.length == 3, "has array result"); ok(result[0].length > 0, "has result"); ok(result[0][0] instanceof context.Articles.elementType); ok(result[0].length > result[1].length, "result in length"); ok(result[1].length > 0, "has result"); ok(result[1][0] instanceof context.Articles.elementType); ok(result[2].length > 0, "has result"); ok(result[2][0] instanceof context.Categories.elementType); }).always(function (err) { _finishCb(context); }); }); }); }); test('queryable different params', 9, function () { stop(); (new $news.Types.NewsContext(providerConfig)).onReady(function (context) { $news.Types.NewsContext.generateTestData(context, function () { context.batchExecuteQuery([ [context.Articles], { queryable: context.Articles.take(5) }, { queryable: context.Categories, method: "first" }, [context.Categories, "count"] ], function () { ok(true, 'success callback called'); }).then(function (result) { ok(result.length == 4, "has array result"); ok(result[0].length > 0, "has result"); ok(result[0][0] instanceof context.Articles.elementType); ok(result[0].length > result[1].length, "result in length"); ok(result[1].length > 0, "has result"); ok(result[1][0] instanceof context.Articles.elementType); ok(result[2] instanceof context.Categories.elementType); equal(typeof result[3], "number"); }).always(function (err) { _finishCb(context); }); }); }); }); test('queryable with inline count', 4, function () { stop(); (new $news.Types.NewsContext(providerConfig)).onReady(function (context) { $news.Types.NewsContext.generateTestData(context, function () { try { context.batchExecuteQuery([ context.Articles.withInlineCount() ], function () { ok(true, 'success callback called'); }).then(function (result) { ok(result[0].length > 0, "has result"); ok(result[0][0] instanceof context.Articles.elementType); ok(typeof result[0].totalCount, 'number', "totalCount exists"); }).always(function (err) { _finishCb(context); }); } catch (e) { expect(1); equal(e.message, "Operation 'withInlineCount' is not supported by the provider", "Not supported"); _finishCb(context); } }); }); }); test('batch req error test', 1, function () { if (providerConfig.name !== 'oData') { expect(1); ok(true, 'not supported'); return; } stop(); (new $news.Types.NewsContext(providerConfig)).onReady(function (context) { $news.Types.NewsContext.generateTestData(context, function () { context.prepareRequest = function (request) { request[0].data.__batchRequests[2].requestUri = request[0].data.__batchRequests[2].requestUri.replace('Title', 'Title2'); }; context.batchExecuteQuery([ [context.Articles], { queryable: context.Articles.take(5) }, { queryable: context.Categories.filter("it.Title != null"), method: "first" }, [context.Categories, "count"] ]) .fail(function (err) { ok(true, 'Request error'); }) .always(function (err) { _finishCb(context); }); }); }); }); test('batch result error test', 1, function () { if (providerConfig.name !== 'oData') { expect(1); ok(true, 'not supported'); return; } stop(); (new $news.Types.NewsContext(providerConfig)).onReady(function (context) { $news.Types.NewsContext.generateTestData(context, function () { context.prepareRequest = function (request) { var origSuccess = request[1]; request[1] = function (data) { data.__batchResponses = []; origSuccess.apply(this, arguments); } }; context.batchExecuteQuery([ [context.Articles], { queryable: context.Articles.take(5) }, { queryable: context.Categories, method: "first" }, [context.Categories, "count"] ]) .fail(function (err) { equal(err.message, "Batch response count failed", 'Request error'); }) .always(function (err) { _finishCb(context); }); }); }); }); test('batch result item error test', 1, function () { stop(); (new $news.Types.NewsContext(providerConfig)).onReady(function (context) { $news.Types.NewsContext.generateTestData(context, function () { context.batchExecuteQuery([ [context.Articles], { queryable: context.Articles.take(5) }, { queryable: context.Categories.filter("it.Title == 'invalid category value'"), method: "single" }, [context.Categories, "count"] ]) .fail(function (err) { equal(err.message, "result count failed", 'Result error'); }) .always(function (err) { _finishCb(context); }); }); }); }); }
Malyngo/jaydata
test/qunit/scripts/T4.js
JavaScript
gpl-2.0
40,696
// Copyright 2020 Las Venturas Playground. All rights reserved. // Use of this source code is governed by the MIT license, a copy of which can // be found in the LICENSE file. import { GameBase } from 'features/games/game_base.js'; import { Vector } from 'base/vector.js'; import { random } from 'base/random.js'; // How many hay stacks will there by side by side? export const kEdge = 4; // Every how many game ticks should player progress be checked in the game? export const kPlayerProgressInterval = 8; // Implementation of the Game class specifically for the Haystack minigame. An instance of this // class will be created by the Games infrastructure when it's started. export class HaystackGame extends GameBase { // Type of object that can be stored in either of the matrices. static kPositionEmpty = 0; static kPositionHaystack = 1; static kPositionRock = 2; // Counter to determine whether to check for winning players in a game tick. counter_ = 0; // Matrix of the haystacks and rocks that have been created. Three-dimensional, [x][y][z]. matrix_ = []; // Set of positions ({x, y, z}) in which haystacks are located. Moving objects are removed until // their move operation has fully completed. haystacks_ = new Set(); // The settings for this game, which will be initialized based on the |settings| passed to us. settings_ = null; // Map of |player| to the time, in milliseconds, at which they started the attempt. startTime_ = new WeakMap(); // Counter used to skip unnecessary updates, based on the difficulty level. tickSkipCounter_ = 0; // Called when the game has been initialized. Here we create the haystacks and the rocks that // that the player is able to climb on. async onInitialized(settings, userData) { await super.onInitialized(settings, userData); this.settings_ = this.determineSettings(settings); if ((this.settings_.hayDensity + this.settings_.rockDensity) >= 1) throw new Error(`The total density of the hay stack must not >=1`); const kLevels = this.settings_.levels; for (let x = 0; x < kEdge; ++x) { this.matrix_[x] = []; // Fill the [x][y] with an empty position object for each level. for (let y = 0; y < kEdge; ++y) this.matrix_[x][y] = Array(kLevels).fill({ type: HaystackGame.kPositionEmpty }); } // Now populate the haystack objects in the matrix at the configured density. const haystackObjects = Math.floor((kEdge * kEdge * kLevels) * this.settings_.hayDensity); const rockObjects = Math.floor((kEdge * kEdge * kLevels) * this.settings_.rockDensity); for (let haystack = 0; haystack < haystackObjects; ++haystack) { const [x, y, z] = this.findAvailablePosition(); this.haystacks_.add({ x, y, z }); this.matrix_[x][y][z] = { type: HaystackGame.kPositionHaystack, object: this.scopedEntities.createObject({ modelId: 3374, // haystack position: this.vectorForPosition(x, y, z), rotation: new Vector(0, 0, random(0, 2) * 180), }) }; } for (let rock = 0; rock < rockObjects; ++rock) { const [x, y, z] = this.findAvailablePosition(); this.matrix_[x][y][z] = { type: HaystackGame.kPositionRock, object: this.scopedEntities.createObject({ modelId: 1305, // rock position: this.vectorForPosition(x, y, z), rotation: new Vector(random(0, 359), random(0, 359), random(0, 359)), }) }; } // Finally, we need a haystack way at the top. Climbing on this one signals that a player // has reached the top, and has thus won the game. this.scopedEntities.createObject({ modelId: 3374, // haystack position: new Vector((kEdge + 1) * -2, (kEdge + 1) * -2, (kLevels * 3) + 3), rotation: new Vector(0, 0, 0), }); } // Called when the |player| is ready to spawn. We position them near the hay so that they can // start running immediately. The countdown has already passed at this point. async onPlayerSpawned(player, countdown) { await super.onPlayerSpawned(player, countdown); const jitter = { x: (Math.random() * 8) - 4, y: (Math.random() * 8) - 4, }; player.position = new Vector(35.0 + jitter.x, 6.50 + jitter.y, 3.3); player.rotation = 135; player.updateStreamerObjects(); player.time = this.settings_.time; player.weather = this.settings_.weatherId; player.health = 100; player.armour = 0; // If this is their first spawn, then |countdown| will be included to help them out. if (countdown) await countdown(); // Only set their start time on first spawn. They can die and begin climbing the stack // again, but as far as this game is concerned that's still part of their original attempt. if (!this.startTime_.has(player)) this.startTime_.set(player, server.clock.monotonicallyIncreasingTime()); } // Called every tick, i.e. every ~100ms for this game. Each tick will be considered to move one // of the haystacks in the game, and every five ticks (~500ms) we'll check whether any of the // players has reached the top of the haystack. async onTick() { await super.onTick(); if ((this.counter_++) % kPlayerProgressInterval === 0) this.updatePlayerProgress(); if ((this.tickSkipCounter_++) % this.settings_.tickSkip !== 0) return; // skip this update const haystackArray = [ ...this.haystacks_ ]; if (!haystackArray.length) throw new Error(`There are no haystacks left in the game's set.`); const position = haystackArray[random(0, haystackArray.length)]; const cell = this.matrix_[position.x][position.y][position.z]; if (cell.type != HaystackGame.kPositionHaystack) throw new Error(`The identified haystack isn't known to be a haystack.`); let target = Object.assign({}, position); // Changes either [x, y, z] by [-1, 1], which maps to all valid haystack movement. const direction = ['x', 'y', 'z'][random(0, 3)]; const mutation = [-1, 1][random(0, 2)]; target[direction] += mutation; // The `target` position must be within bounds of the haystack matrix. if (target.x < 0 || target.x >= kEdge || target.y < 0 || target.y >= kEdge) return; if (target.z < 0 || target.z >= this.settings_.levels) return; // The `target` position must not yet be occupied by something else. if (this.matrix_[target.x][target.y][target.z].type != HaystackGame.kPositionEmpty) return; // Copy the |cell| over to the target destination, to mark it as occupied. this.matrix_[target.x][target.y][target.z] = cell; // Remove the |position| from the set of haystack objects that are able to move. this.haystacks_.delete(position); // The speed depends on the altitude, objects higher up will be moving faster. const speed = this.determineMovementSpeed(target.z, direction); // Move the object located in the |cell| to the new destination. When completed, mark the // existing |cell| as empty, so that other haystacks are able to move in to it. cell.object.moveTo(this.vectorForPosition(target.x, target.y, target.z), speed).then(() => { this.matrix_[position.x][position.y][position.z] = { type: HaystackGame.kPositionEmpty }; this.haystacks_.add(target); }); } // Checks the progress of each of the players in the game. This will be reflected in an on- // screen UI, but will also be used to determine whether they've won. updatePlayerProgress() { // TODO: Display some sort of UI with their progress. Something like races do would be ace. // Determine the area of the map in which a climbing player could be. const rangeX = [ kEdge * -4, 1 * -4 ]; const rangeY = [ kEdge * -4, 1 * -4 ]; for (const player of this.players) { const position = player.position; let score = 0; // on the ground // Only consider their height if they're standing on one of the haystacks. if (position.x >= rangeX[0] && position.x <= rangeX[1] && position.y >= rangeY[0] && position.y <= rangeY[1]) { score = Math.max(0, Math.min(Math.round(position.z / 3) - 1, this.settings_.levels + 1)); } // TODO: Update the UI with the player's current position. // If the player hasn't reached above the number of levels yet, they're still going. if (score <= this.settings_.levels) continue; // Otherwise they've won. Their score will be the total time it took them, in seconds, // rounded to two decimal points. const totalTimeMs = server.clock.monotonicallyIncreasingTime() - this.startTime_.get(player); this.playerWon(player, Math.round(totalTimeMs / 10) / 100); } } // --------------------------------------------------------------------------------------------- // Utility functions // --------------------------------------------------------------------------------------------- // Determines the movement speed given the |level|, for a movement in the given |direction|. // Movements at higher altitudes will be faster, to make the game more challenging. determineMovementSpeed(level, direction) { const kHorizontalRange = [ 0.75, 1.5 ]; const kVerticalRange = [ 1, 2 ]; const progress = level / this.settings_.levels; let vel = 0; switch (direction) { case 'x': case 'y': vel = kHorizontalRange[0] + (kHorizontalRange[1] - kHorizontalRange[0]) * progress; break; case 'z': vel = kVerticalRange[0] + (kVerticalRange[1] - kVerticalRange[0]) * progress; break; } return vel + this.settings_.speedAdjustment; } // Determines the internal configuration based on the given |settings|. These can be customized // by players, to create custom experiences for the haystack game. determineSettings(settings) { let hayDensity = .3; // density of haystack in the matrix let levels = 30; // number of levels that players will have to conqueror let rockDensity = .01; // density of rocks in the matrix let speedAdjustment = 0; // adjustment in movement speed, in units/sec. let tickSkip = 5; // number of ticks to skip when moving a haystack (lower = faster) let time = [ 12, 0 ]; // time to apply in the world during the game let weatherId = 2; // the weather to apply during the game switch (settings.get('haystack/difficulty')) { case 'easy': hayDensity = .35; rockDensity = 0; speedAdjustment = -0.25; tickSkip = 10; break; case 'normal': hayDensity = .3; rockDensity = .01; speedAdjustment = 0; tickSkip = 5; break; case 'difficult': hayDensity = .25; rockDensity = .04; speedAdjustment = 0.25; tickSkip = 3; break; case 'extreme': hayDensity = .2; rockDensity = .08; speedAdjustment = 0.35; tickSkip = 1; weatherId = 9; break; } if (settings.has('haystack/levels')) levels = settings.get('haystack/levels'); return { hayDensity, levels, rockDensity, speedAdjustment, tickSkip, time, weatherId }; } // Finds an available position in the matrix through randomness. That means that the algorithm // is not very optimised, but as long as the matrix' density is <1 it should be fine. findAvailablePosition() { let x, y, z; do { x = random(0, kEdge); y = random(0, kEdge); z = random(0, this.settings_.levels); } while (this.matrix_[x][y][z].type != HaystackGame.kPositionEmpty); return [x, y, z]; } // Returns a Vector instance for position [x, y, z] in the haystack matrix. vectorForPosition(x, y, z) { return new Vector(x * -4, y * -4, (z + 1) * 3); } }
LVPlayground/playground
javascript/features/haystack/haystack_game.js
JavaScript
gpl-2.0
13,114
/* Importar el modelo */ var models = require('../models/models.js'); /* MW que permite acciones solamente si el quiz al que pertenece el comentario objeto pertenece al usuario logeado o si es cuenta admin */ exports.ownershipRequired = function(req, res, next){ models.Quiz.find({ where: { id: Number(req.comment.QuizId) } }).then(function(quiz) { if (quiz) { var objQuizOwner = quiz.UserId; var logUser = req.session.user.id; var isAdmin = req.session.user.isAdmin; console.log(objQuizOwner, logUser, isAdmin); if (isAdmin || objQuizOwner === logUser) { next(); } else { res.redirect('/'); } } else{next(new Error('No existe quizId=' + quizId))} } ).catch(function(error){next(error);}); }; /* Autoload :id */ exports.load = function(req, res, next, commentId) { models.Comment.find( { where: { id: Number(commentId) } }).then(function(comment) { if(comment) { req.comment = comment; next(); } else { next(new Error('No existe commentId = ' + commentId)) } }).catch(function(error) { next(error); }); }; /* GET /quizes/:quizId/comments/new */ exports.new = function(req, res) { res.render('comments/new', { quizid: req.params.quizId, errors: [] }); }; /* POST /quizes/:quizId/comments */ exports.create = function(req, res) { var comment = models.Comment.build( { texto : req.body.comment.texto, QuizId: req.params.quizId }); comment.validate().then(function(err) { if (err) { res.render('comments/new.ejs', { comment: comment, quizid: req.params.quizId, errors: err.errors }); } else { // guarda en DB campo texto de comment comment.save().then(function() { // redirección HTTP a lista de preguntas res.redirect('/quizes/' + req.params.quizId); }); } }).catch(function(error) { next(error); }); }; /* GET /quizes/:quizId/comments/:commentId/publish */ exports.publish = function(req, res) { req.comment.publicado = true; req.comment.save( { fields: ["publicado"] }).then(function() { res.redirect('/quizes/' + req.params.quizId); }).catch(function(error) { next(error); }); };
pabloarcones/quiz
controllers/comment_controller.js
JavaScript
gpl-2.0
2,603
showHideDetails ();
lat9/snap_affiliates
includes/modules/pages/referrer_edit/on_load_main.js
JavaScript
gpl-2.0
19
/* * Copyright (c) 2009, 2010 and 2011 Frank G. Bennett, Jr. All Rights * Reserved. * * The contents of this file are subject to the Common Public * Attribution License Version 1.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://bitbucket.org/fbennett/citeproc-js/src/tip/LICENSE. * * The License is based on the Mozilla Public License Version 1.1 but * Sections 14 and 15 have been added to cover use of software over a * computer network and provide for limited attribution for the * Original Developer. In addition, Exhibit A has been modified to be * consistent with Exhibit B. * * Software distributed under the License is distributed on an “AS IS” * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See * the License for the specific language governing rights and limitations * under the License. * * The Original Code is the citation formatting software known as * "citeproc-js" (an implementation of the Citation Style Language * [CSL]), including the original test fixtures and software located * under the ./std subdirectory of the distribution archive. * * The Original Developer is not the Initial Developer and is * __________. If left blank, the Original Developer is the Initial * Developer. * * The Initial Developer of the Original Code is Frank G. Bennett, * Jr. All portions of the code written by Frank G. Bennett, Jr. are * Copyright (c) 2009, 2010 and 2011 Frank G. Bennett, Jr. All Rights Reserved. * * Alternatively, the contents of this file may be used under the * terms of the GNU Affero General Public License (the [AGPLv3] * License), in which case the provisions of [AGPLv3] License are * applicable instead of those above. If you wish to allow use of your * version of this file only under the terms of the [AGPLv3] License * and not to allow others to use your version of this file under the * CPAL, indicate your decision by deleting the provisions above and * replace them with the notice and other provisions required by the * [AGPLv3] License. If you do not delete the provisions above, a * recipient may use your version of this file under either the CPAL * or the [AGPLv3] License.” */ dojo.provide("citeproc_js.formats"); doh.register("citeproc_js.formats", [ function testStringyDefs() { doh.assertEqual( '<b>%%STRING%%</b>', CSL.Output.Formats.html["@font-weight/bold"] ); }, function testFunctionDefs() { doh.assertEqual( "function", typeof CSL.Output.Formats.html["@passthrough/true"] ); } ]);
co-alliance/adr
sites/all/modules/islandora_contrib/islandora_scholar/modules/citeproc/lib/citeproc-js/tests/citeproc-js/formats.js
JavaScript
gpl-2.0
2,610
/** █▒▓▒░ The FlexPaper Project This file is part of FlexPaper. FlexPaper is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 3 of the License. FlexPaper is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with FlexPaper. If not, see <http://www.gnu.org/licenses/>. For more information on FlexPaper please see the FlexPaper project home page: http://flexpaper.devaldi.com */ jQuery(function() { /** * Handles the event of external links getting clicked in the document. * * @example onExternalLinkClicked("http://www.google.com") * * @param String link */ jQuery('#documentViewer').bind('onExternalLinkClicked',function(e,link){ window.location.href = link; }); /** * Recieves progress information about the document being loaded * * @example onProgress( 100,10000 ); * * @param int loaded * @param int total */ jQuery('#documentViewer').bind('onProgress',function(e,loadedBytes,totalBytes){ }); /** * Handles the event of a document is in progress of loading * */ jQuery('#documentViewer').bind('onDocumentLoading',function(e){ }); /** * Handles the event of a document is in progress of loading * */ jQuery('#documentViewer').bind('onPageLoading',function(e,pageNumber){ }); /** * Receives messages about the current page being changed * * @example onCurrentPageChanged( 10 ); * * @param int pagenum */ jQuery('#documentViewer').bind('onCurrentPageChanged',function(e,pagenum){ }); /** * Receives messages about the document being loaded * * @example onDocumentLoaded( 20 ); * * @param int totalPages */ jQuery('#documentViewer').bind('onDocumentLoaded',function(e,totalPages){ }); /** * Receives messages about the page loaded * * @example onPageLoaded( 1 ); * * @param int pageNumber */ jQuery('#documentViewer').bind('onPageLoaded',function(e,pageNumber){ }); /** * Receives messages about the page loaded * * @example onErrorLoadingPage( 1 ); * * @param int pageNumber */ jQuery('#documentViewer').bind('onErrorLoadingPage',function(e,pageNumber){ }); /** * Receives error messages when a document is not loading properly * * @example onDocumentLoadedError( "Network error" ); * * @param String errorMessage */ jQuery('#documentViewer').bind('onDocumentLoadedError',function(e,errMessage){ }); /** * Receives error messages when a document has finished printed * * @example onDocumentPrinted(); * */ jQuery('#documentViewer').bind('onDocumentPrinted',function(e){ }); });
tsigma-bms/tsigma
sites/all/libraries/flexpaper/js/flexpaper_handlers.js
JavaScript
gpl-2.0
3,178
/* * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; under version 2 * of the License (non-upgradable). * * 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 General Public License for more details. * * You should have received a copy of the GNU 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. * * Copyright (c) 2014 - 2020 (original work) Open Assessment Techniologies SA * */ define([ 'lodash', 'i18n', 'layout/actions/binder', 'uri', 'ui/feedback', 'core/logger', 'taoTests/previewer/factory', 'module' ], function(_, __, binder, uri, feedback, loggerFactory, previewerFactory, module){ 'use strict'; const logger = loggerFactory('taoTests/controller/action'); binder.register('testPreview', function testPreview(actionContext) { previewerFactory( module.config().provider, uri.decode(actionContext.uri), { readOnly: false, fullPage: true }) .catch(err => { logger.error(err); feedback().error(__('Test Preview is not installed, please contact to your administrator.')); }); }); });
oat-sa/extension-tao-test
views/js/controller/tests/action.js
JavaScript
gpl-2.0
1,589
var c1 = {};var ctx1 = {};var c2 = {};var ctx2 = {};var c3 = {};var ctx3 = {}; function get_canvas() { c1 = document.getElementById("horo_canvas"); ctx1 = c1.getContext("2d"); ctx1.beginPath(); c2 = document.getElementById("moon_canvas"); ctx2 = c2.getContext("2d"); ctx2.beginPath(); c3 = document.getElementById("navamsha_canvas"); ctx3 = c3.getContext("2d"); ctx3.beginPath(); } function draw_horoscope() { get_canvas();ctx1.rect(5,5,250,250);ctx1.strokeStyle='black'; ctx1.lineWidth=1;ctx1.stroke(); ctx1.rect(65,65,130,130);ctx1.strokeStyle='black'; ctx1.lineWidth=1;ctx1.stroke(); get_canvas();ctx2.rect(5,5,250,250);ctx2.strokeStyle='black'; ctx2.lineWidth=1;ctx2.stroke(); ctx2.rect(65,65,130,130);ctx2.strokeStyle='black'; ctx2.lineWidth=1;ctx2.stroke(); get_canvas();ctx3.rect(5,5,250,250);ctx3.strokeStyle='black'; ctx3.lineWidth=1;ctx3.stroke(); ctx3.rect(65,65,130,130);ctx3.strokeStyle='black'; ctx3.lineWidth=1;ctx3.stroke(); draw_houses(65,5,65,65);draw_houses(5,65,65,65);draw_houses(65,195,5,195); draw_houses(65,195,65,255);draw_houses(65,195,5,195);draw_houses(195,5,195,65); draw_houses(255,65,195,65);draw_houses(195,195,195,255);draw_houses(255,195,195,195); draw_houses(130,5,130,65);draw_houses(130,195,130,255);draw_houses(5,130,65,130); draw_houses(195,130,255,130); assign_signs("1",67,15);assign_signs('2',132,15);assign_signs('3',197,15); assign_signs('4',197,75);assign_signs('5',197,140);assign_signs('6',197,205); assign_signs('7',132,205);assign_signs('8',67,205);assign_signs('9',7,205); assign_signs('10',7,140);assign_signs('11',7,75);assign_signs('12',7 ,15); } function draw_houses(a,b,c,d) { get_canvas(); ctx1.beginPath();ctx2.beginPath();ctx3.beginPath(); ctx1.moveTo(a,b);ctx2.moveTo(a,b);ctx3.moveTo(a,b); ctx1.lineTo(c,d);ctx2.lineTo(c,d);ctx3.lineTo(c,d); ctx1.stroke();ctx2.stroke();ctx3.stroke(); } function assign_signs(a,b,c) { ctx1.beginPath();ctx2.beginPath();ctx3.beginPath(); ctx1.font='8px Arial';ctx2.font='8px Arial';ctx3.font='8px Arial'; ctx1.fillText(a,b,c);ctx2.fillText(a,b,c);ctx3.fillText(a,b,c); } function getAscendant() { var x = document.getElementById("ascendant_sign").getAttribute('value'); main_chart("1"); assign_asc("1",x); set_planets("1"); } function getMoon() { var x = document.getElementById("moon_sign").getAttribute('value'); get_canvas(); assign_asc("2",x); main_chart("2"); set_planets("2"); } function getNavamsha() { var x = document.getElementById("ascendant_navamsha_sign").getAttribute('value'); get_canvas(); assign_asc("3",x); main_chart("3"); set_planets("3"); } function get_planets(a,sign) { var sign = sign; var planets = ["sun","moon","mars","mercury","jupiter","venus","saturn","rahu","ketu","uranus","neptune","pluto"]; //alert(document.getElementById("sun_sign").getAttribute('value')); //var name = planets[0]; //alert(name); var x;var y=[]; for(var i=0;i<planets.length; i++) { if(a == "3") { if(sign == document.getElementById(planets[i]+"_navamsha_sign").getAttribute('value')) { x = planets[i]; y.push(x); } } else { if(sign == document.getElementById(planets[i]+"_sign").getAttribute('value')) { x = planets[i]; y.push(x); } } } if(y.length > 0) // check if there are any planets in house { return y; } else { return "0"; } } function assign_asc(a, x) { if(a == "1") { var ctx = ctx1; } else if(a=="2") { var ctx = ctx2; } else if(a=="3") { var ctx = ctx3; } get_canvas(); ctx.font='10px Arial'; if(x == "Aries"){ ctx.fillText("Asc.",75,16);} else if(x == "Taurus"){ctx.fillText("Asc.",138,16);} else if(x == "Gemini"){ctx.fillText("Asc.",205,16);} else if(x == "Cancer"){ctx.fillText("Asc.",205,76);} else if(x == "Leo"){ctx.fillText("Asc.",205,140);} else if(x == "Virgo"){ctx.fillText("Asc.",205,205);} else if(x == "Libra"){ctx.fillText("Asc.",138,205);;} else if(x == "Scorpio"){ctx.fillText("Asc.",75,205);} else if(x == "Sagittarius"){ctx.fillText("Asc.",18,205);} else if(x == "Capricorn"){ctx.fillText("Asc.",18,140);} else if(x == "Aquarius"){ctx.fillText("Asc.",18,76);} else if(x == "Pisces"){ctx.fillText("Asc.",18,16);} else{y=1;} } function set_planets(a) { assign_planets(a,"Aries", 80, 40);assign_planets(a,"Taurus",145,40); assign_planets(a,"Gemini",210,40);assign_planets(a,"Cancer",210,90); assign_planets(a,"Leo",210,156);assign_planets(a,"Virgo",210,230); assign_planets(a,"Libra",145,230);assign_planets(a,"Scorpio",80,230); assign_planets(a,"Sagittarius",15,230);assign_planets(a,"Capricorn",15,156); assign_planets(a,"Aquarius",15,90);assign_planets(a,"Pisces",15,40); } function assign_planets(chart,x,a,b) { if(chart == "1") { var ctx = ctx1; } else if(chart=="2") { var ctx = ctx2; } else if(chart=="3") { var ctx = ctx3; } get_canvas(); ctx.font='10px Arial'; var y = get_planets(chart, x); var len = y.length; if(y == "0"){} else { if(len=="1") { ctx.fillText(y[0],a,b); } if(len=="2") { ctx.fillText(y[0],a,b-8); ctx.fillText(y[1],a,b); } if(len=="3") { ctx.fillText(y[0],a,b-8); ctx.fillText(y[1],a,b); ctx.fillText(y[2],a,b+8); } if(len=="4") { ctx.fillText(y[0],a,b-8); ctx.fillText(y[1],a,b); ctx.fillText(y[2],a,b+8); ctx.fillText(y[3],a,b+16); } if(len=="5") { ctx.fillText(y[0],a+25,b-16); ctx.fillText(y[1],a,b-8); ctx.fillText(y[2],a,b); ctx.fillText(y[3],a,b+8); ctx.fillText(y[4],a,b+16); } if(len=="6") { ctx.fillText(y[0],a+25,b-20); ctx.fillText(y[1],a,b-15); ctx.fillText(y[2],a,b-8); ctx.fillText(y[3],a,b); ctx.fillText(y[4],a,b+8); ctx.fillText(y[5],a,b+16); } if(len=="7") { ctx.fillText(y[0],a+25,b-20); ctx.fillText(y[1],a,b-15); ctx.fillText(y[2],a,b-8); ctx.fillText(y[3],a,b); ctx.fillText(y[4],a,b+8); ctx.fillText(y[5],a,b+16); ctx.fillText(y[6],a+15,b+20); } } } function main_chart(a) { get_canvas(); if(a == "1") { var ctx = ctx1; } else if(a=="2") { var ctx = ctx2; } else if(a=="3") { var ctx = ctx3; } ctx.font ='10px Arial'; var fname = document.getElementById("fname").getAttribute('value'); var n = fname.search(" "); var d = fname.includes(" "); if(d == true) { var name = "Name: "+ fname.substring(0, n); } else { var name = "Name: "+ fname; } var gender = "Gender: "+document.getElementById("gender").getAttribute('value'); var dob = "Date: "+document.getElementById("dob").getAttribute('value'); var tob = "Time: "+document.getElementById("tob").getAttribute('value'); var pob = "Place: "+document.getElementById("pob").getAttribute('value'); var s = pob.split(',')[0]; if(a == "1") { ctx.fillText("Main Chart",100,80); } else if(a == "2") { ctx.fillText("Moon Chart",100,80); } else if(a == "3") { ctx.fillText("Navamsha Chart",100,80); } ctx.fillText(name, 70, 95); ctx.fillText(gender, 70, 110); ctx.fillText(dob, 70, 125); ctx.fillText(tob,70,140); ctx.fillText(s,70,155); } getMoon(); getNavamsha();
luffy22/aisha
components/com_horoscope/script/asc_s.js
JavaScript
gpl-2.0
8,310
/** This class handles going in and out of Fullscreen mode. Supported on most (but not all) browsers. */ var FullScreenManager = function () { this.triggers = [] }; FullScreenManager.prototype.initialize = function() { var that = this; $(window).resize(function () { that.refreshTriggers(); }) }; FullScreenManager.prototype.isFullScreen = function() { return ((window.fullScreen) || (window.innerWidth == screen.width && window.innerHeight == screen.height)); }; FullScreenManager.prototype.goFullscreen = function() { console.log("Going FullScreen..."); var element = document.documentElement; if(element.requestFullscreen) { element.requestFullscreen(); } else if(element.mozRequestFullScreen) { element.mozRequestFullScreen(); } else if(element.webkitRequestFullscreen) { element.webkitRequestFullscreen(); } else if(element.msRequestFullscreen) { element.msRequestFullscreen(); } } FullScreenManager.prototype.exitFullscreen = function() { console.log("Exiting FullScreen..."); if(document.exitFullscreen) { document.exitFullscreen(); } else if(document.mozCancelFullScreen) { document.mozCancelFullScreen(); } else if(document.webkitExitFullscreen) { document.webkitExitFullscreen(); } } FullScreenManager.prototype.triggerFullscreen = function() { if(this.isFullScreen()) this.exitFullscreen() else this.goFullscreen(); } FullScreenManager.prototype.refreshTriggers = function() { if(this.isFullScreen()) { for(i in this.triggers) $(this.triggers[i]).addClass("active"); } else { for(i in this.triggers) $(this.triggers[i]).removeClass("active"); } } FullScreenManager.prototype.addTriggerElement = function(element) { this.triggers.push(element); var that = this; $(element).click(function () { that.triggerFullscreen(); }) this.refreshTriggers(); }
mbinette91/ConstructionLCA
webapp/js/FullscreenManager.js
JavaScript
gpl-2.0
2,009
(function ($) { Drupal.behaviors.bscmsSearchApp = { attach: function (context) { countries = globalCountryList; issues = globalIssuesList; cterms = globalCTermList; iterms = globalITermList; aterms = globalATermList; bundlelist = {'Article': 'article', 'Country Page': 'country_page', 'Event': 'event', 'Issue page':'issue_page'}; facetfilters = {'sm_field_issues': [], 'sm_field_contry_region': [], 'sm_field_article_type': [], 'bundle': [], 'ds_created': []}; datasearch = { 'wt': 'json', 'q':'*', 'facet': true, 'facet.field': ['bundle_name','sm_field_issues','sm_field_contry_region', 'sm_field_article_type'], 'facet.date': 'ds_created', 'facet.date.start': 'NOW/YEAR-20YEAR', 'facet.date.end': 'NOW/YEAR+1YEAR', 'facet.date.gap': '+1YEAR', 'fq': ['bundle:(article OR country_page OR issue_page)'], 'sort' : 'ds_created desc', 'f': [] }; var searchApp = new Vue({ el: '#search', data: { query: '', results: [], facetsdate: [], facetscountry: [], facetsissues: [], facetsarticles: [], ffilters: facetfilters, }, methods : { convertDate: function (data) { moment.locale('en-gb'); return moment(data).format('ll'); }, getCountryLink: function (country, type) { if (Array.isArray(country)) { var infocountry = _(countries).chain().filter(function (x) { return x.tid == country[0].replace('taxonomy_term:', ''); }).groupBy('tid').map(function (a) { return [a[0].country, '/node/' + a[0].entity_id]; }).value(); if (Array.isArray(infocountry) && infocountry.length > 0) { if (type == 'link') return infocountry[0][1]; if (type == 'name') return infocountry[0][0]; } } }, getIssueLink: function (issue, type) { if (Array.isArray(issue)) { var infoissue = _(issues).chain().filter(function (x) { return x.tid == issue[0].replace('taxonomy_term:', ''); }).groupBy('tid').map(function (a) { return [a[0].issue, '/node/' + a[0].entity_id]; }).value(); if (Array.isArray(infoissue) && infoissue.length > 0) { if (type == 'link') return infoissue[0][1]; if (type == 'name') return infoissue[0][0]; } } }, add_param: function (x,y,z) { me = this; if (JSON.stringify(me.ffilters).indexOf(y) === -1) { me.ffilters[z].push({'value':x, 'name':y, 'type':z}); datasearch.fq.push(z+':"'+x+'"'); //var hash = {}; //hash[z] = x; //jQuery.bbq.pushState(hash); } me.do_search(); }, add_param_date: function (x,y,z) { me = this; if (JSON.stringify(me.ffilters).indexOf(y) === -1) { me.ffilters[z].push({'value':x, 'name':y, 'type':z}); datasearch.fq.push(z+':['+x+']'); //var hash = {}; //hash[z] = x; //jQuery.bbq.pushState(hash); } me.do_search(); }, remove_param: function (x, y) { me = this; var index = datasearch.fq.indexOf(y+':"'+x+'"'); datasearch.fq.splice(index,1); me.ffilters[y] = _(me.ffilters[y]).chain().filter(function(a) { return a.value != x; }).value(); me.do_search(); }, do_search: function (q) { me = this; datasearch.q = q; $.ajaxSettings.traditional = true; $.ajax({ 'url': '/solr/'+ Drupal.settings.bscms_apache_solr_search.core + '/select', 'traditional': true, 'data': datasearch, 'success': function (data) { me.results = data.response.docs; me.facetstype = _(data.facet_counts.facet_fields.bundle_name).chain().groupBy(function(element, index) { return Math.floor(index/2); }).map(function(idx,x) { if (idx[1] > 3) { return [idx[0], idx[1], 'bundle']; } }).map(function(y) { if (y) { return [y[0], bundlelist[y[0]], y[1], y[2]] } }).filter(Boolean).value(); var fissues = _(data.facet_counts.facet_fields.sm_field_issues).chain().groupBy(function(element, index) { return Math.floor(index/2); }).map(function(idx,x) { if (idx[1] > 3) { return [idx[0], idx[1]]; } }).filter(Boolean).value(); var fcountries = _(data.facet_counts.facet_fields.sm_field_contry_region).chain().groupBy(function(element, index) { return Math.floor(index/2); }).map(function(idx,x) { if (idx[1] > 2) { return [idx[0], idx[1]]; } }).filter(Boolean).value(); var farticletypes = _(data.facet_counts.facet_fields.sm_field_article_type).chain().groupBy(function(element, index) { return Math.floor(index/2); }).map(function(idx,x) { if (idx[1] > 2) { return [idx[0], idx[1]]; } }).filter(Boolean).value(); me.facetsdate = _(data.facet_counts.facet_dates.ds_created).map(function(idx, x) { if (((Number(parseFloat(idx))== idx) && (idx!= 0))) { return [x, idx] } }).filter(Boolean).map(function(date) { return [moment(date[0]).format('YYYY'), date[0] + " TO " + moment(date[0]).add(1, "years").format("YYYY-MM-DDTHH:mm:ss")+'Z', date[1], 'ds_created'] }); me.facetscountry = _(fcountries ).chain().map(function(x) { var termino = _(cterms).filter(function(a) { return a.tid == x[0].replace('taxonomy_term:', '') }); return [termino[0].name, x[0], x[1]]; }).sortBy(function(x) { return x[0] }).value(); me.facetsarticles = _(farticletypes ).chain().map(function(x) { var termino = _(aterms).filter(function(a) { return a.tid == x[0].replace('taxonomy_term:', '') }); return [termino[0].name, x[0], x[1], 'sm_field_article_type']; }).sortBy(function(x) { return x[0] }).value().concat(me.facetstype); me.facetsissues = _(fissues ).chain().map(function(x) { var termino = _(iterms).filter(function(a) { return a.tid == x[0].replace('taxonomy_term:', '') }); return [termino[0].name, x[0], x[1]]; }).sortBy(function(x) { return x[0] }).value(); }, 'dataType': 'jsonp', 'jsonp': 'json.wrf' }); } }, ready: function() { me = this; /*var params = jQuery.bbq.getState(); if (params) { datasearch.fq.push(_(params).map(function(x, y) { return y+':'+'"'+x+'"'; }).toString()); }*/ me.do_search(''); }, watch: { query: function () { me = this; me.do_search(me.query); } }, }); } } })(jQuery);
msfuae/bscms-en
sites/all/modules/features/bscms_apache_solr_search/js/bscms_apache_solr_search.js
JavaScript
gpl-2.0
7,060
// Requires var sensorLib = require('node-dht-sensor'); var blessed = require('blessed'), contrib = require('blessed-contrib'), screen = blessed.screen(); screen.key(['escape', 'q', 'C-c'], function(ch, key) { return process.exit(0); }); // Create layout and widgets var grid1 = new contrib.grid({rows: 2, cols: 1, screen: screen}) var gauge = grid1.set(1, 0, 1, 1, contrib.gauge, {label: 'Humidité'}) var box = grid1.set(0, 0, 1, 1, blessed.box, {label: 'Température', style: {fg: 'white', bg: 'blue'}}) var temp, humid; var sensor = { initialize: function () { return sensorLib.initialize(22, 10); }, read: function () { var readout = sensorLib.read(); //console.log('Temperature: ' + readout.temperature.toFixed(2) + 'C, ' + 'humidity: ' + readout.humidity.toFixed(2) + '%'); temp = readout.temperature.toFixed(2); humid = readout.humidity.toFixed(2); box.setContent(temp); gauge.setPercent(humid); screen.render(); setTimeout(function () { sensor.read(); }, 2000); } }; if (sensor.initialize()) { sensor.read(); } else { console.warn('Failed to initialize sensor'); }
nbaudet/PiCellar
index.js
JavaScript
gpl-2.0
1,173
import React from 'react'; import { StoryPage } from 'StorybookConfig/preview'; import HelperText from './index'; import HelperTextDocs from './HelperText.md'; import HelperTextOptions from './HelperText.knobs.options'; export const HelperTextExample = (args) => ( <HelperText {...args} /> ); HelperTextExample.storyName = 'Default'; HelperTextExample.args = { inputId: HelperTextOptions.inputId, message: HelperTextOptions.message }; export default { title: 'forms/atoms/HelperText', component: HelperText, parameters: { docs: { page: () => <StoryPage Description={HelperTextDocs} /> } } };
massgov/mayflower
packages/react/src/components/forms/HelperText/HelperText.stories.js
JavaScript
gpl-2.0
623
/* This file is part of Plugin openzwave for jeedom. * * Plugin openzwave for jeedom is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Plugin openzwave for jeedom is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Plugin openzwave for jeedom. If not, see <http://www.gnu.org/licenses/>. */ $('#bt_syncEqLogic').off('click').on('click', function () { syncEqLogicWithOpenZwave(); }); $('.changeIncludeState').off('click').on('click', function () { if($(this).attr('data-state') == 0){ jeedom.openzwave.controller.action({ action : 'cancelCommand', error: function (error) { $('#div_alert').showAlert({message: error.message, level: 'danger'}); }, success: function () { $('#div_alert').showAlert({message: '{{Action réalisée avec succès}}', level: 'success'}); } }); return; } if ($(this).attr('data-mode') == 0) { jeedom.openzwave.controller.removeNodeFromNetwork({ error: function (error) { $('#div_alert').showAlert({message: error.message, level: 'danger'}); }, success: function (data) { $('#div_alert').showAlert({message: '{{Action réalisée avec succès}}', level: 'success'}); } }); return; } var dialog_title = '{{Inclusion}}'; var dialog_message = '<form class="form-horizontal onsubmit="return false;"> '; dialog_title = '{{Démarrer l\'inclusion}}'; dialog_message += '<label class="control-label" > {{Sélectionner le mode d\'inclusion ?}} </label> ' + '<div> <div class="radio"> <label > ' + '<input type="radio" name="secure" id="secure-0" value="0" checked="checked"> {{Mode non sécurisé}} </label> ' + '</div><div class="radio"> <label > ' + '<input type="radio" name="secure" id="secure-1" value="1"> {{Mode sécurisé}}</label> ' + '</div> ' + '</div><br>' + '<label class="lbl lbl-warning" for="name">{{Attention, Une fois démarré veuillez suivre la procédure d\'inclusion de votre module.}}</label> '; dialog_message += '</form>'; bootbox.dialog({ title: dialog_title, message: dialog_message, buttons: { "{{Annuler}}": { className: "btn-danger", callback: function () { } }, success: { label: "{{Démarrer}}", className: "btn-success", callback: function () { jeedom.openzwave.controller.addNodeToNetwork({ secure : $("input[name='secure']:checked").val(), error: function (error) { $('#div_alert').showAlert({message: error.message, level: 'danger'}); }, success: function (data) { $('#div_alert').showAlert({message: '{{Action réalisée avec succès}}', level: 'success'}); } }); } }, } }); }); $('body').delegate('.nodeConfiguration', 'click', function () { $('#md_modal2').dialog({title: "{{Configuration module Z-Wave}}"}); $('#md_modal2').load('index.php?v=d&plugin=openzwave&modal=node.configure&id=' + $(this).attr('data-node-id')).dialog('open'); }); $('#bt_displayZwaveData').off('click').on('click', function () { $('#md_modal').dialog({title: "{{Arbre Z-Wave de l'équipement}}"}); $('#md_modal').load('index.php?v=d&plugin=openzwave&modal=zwave.data&id=' + $('.eqLogicAttr[data-l1key=id]').value()).dialog('open'); }); $('#bt_zwaveNetwork').off('click').on('click', function () { $('#md_modal').dialog({title: "{{Réseaux zwave}}"}); $('#md_modal').load('index.php?v=d&plugin=openzwave&modal=network').dialog('open'); }); $('.eqLogicDisplayCard .bt_configureDevice').off('click').on('click', function (event) { var id = $(this).closest('.eqLogicDisplayCard').attr('data-logical-id') event.stopPropagation() $('#md_modal').dialog({title: "{{Configuration du module}}"}); $('#md_modal').load('index.php?v=d&plugin=openzwave&modal=node.configure&id=' + id).dialog('open'); }); $('#bt_configureDevice').off('click').on('click', function () { $('#md_modal').dialog({title: "{{Configuration du module}}"}); $('#md_modal').load('index.php?v=d&plugin=openzwave&modal=node.configure&id=' + $('.eqLogicAttr[data-l1key=logicalId]').value()).dialog('open'); }); $('#bt_zwaveHealth').on('click', function () { $('#md_modal').dialog({title: "{{Santé zwave}}"}); $('#md_modal').load('index.php?v=d&plugin=openzwave&modal=health').dialog('open'); }); $('#bt_zwaveBackup').off('click').on('click', function () { $('#md_modal2').dialog({title: "{{Sauvegardes}}"}); $('#md_modal2').load('index.php?v=d&plugin=openzwave&modal=backup').dialog('open'); }); if (is_numeric(getUrlVars('logical_id'))) { if ($('.eqLogicDisplayCard[data-logical-id=' + getUrlVars('logical_id') + ']').length != 0) { setTimeout(function () { $('.eqLogicDisplayCard[data-logical-id=' + getUrlVars('logical_id') + ']').click(); }, 10); } } $("#table_cmd").sortable({ axis: "y", cursor: "move", items: ".cmd", placeholder: "ui-state-highlight", tolerance: "intersect", forcePlaceholderSize: true }); function printEqLogic(_eqLogic) { if (_eqLogic.id != '') { $('#img_device').attr("src", $('.eqLogicDisplayCard[data-eqLogic_id=' + _eqLogic.id + '] img').attr('src')); } else { $('#img_device').attr("src", 'plugins/openzwave/plugin_info/openzwave_icon.png'); } if ($('.eqLogicDisplayCard.active').attr('data-assistant') != '') { $('#bt_deviceAssistant').show(); $('#bt_deviceAssistant').off().on('click', function () { $('#md_modal').dialog({title: "{{Assistant de configuration}}"}); $('#md_modal').load('index.php?v=d&plugin=openzwave&modal=device.assistant&id=' + _eqLogic.id + '&logical_id=' + _eqLogic.logicalId).dialog('open'); }); } else { $('#bt_deviceAssistant').hide(); } $.ajax({ type: "POST", url: "plugins/openzwave/core/ajax/openzwave.ajax.php", data: { action: "getConfiguration", manufacturer_id: _eqLogic.configuration.manufacturer_id, product_type: _eqLogic.configuration.product_type, product_id: _eqLogic.configuration.product_id, json: _eqLogic.configuration.fileconf, }, dataType: 'json', global: false, error: function (request, status, error) { handleAjaxError(request, status, error); }, success: function (data) { $('#bt_deviceRecommended').off('click'); if (isset(data.result.name)) { $('.eqLogicAttr[data-l1key=configuration][data-l2key=product_name]').value(data.result.name); } if (isset(data.result.documentation) && data.result.documentation != '') { $('#bt_deviceDocumentation').attr('href', data.result.documentation); $('#bt_deviceDocumentation').show(); } else { $('#bt_deviceDocumentation').hide(); } if (isset(data.result.recommended) && data.result.recommended != '') { $('#bt_deviceRecommended').show(); $('#bt_deviceRecommended').on('click', function () { bootbox.dialog({ title: "{{Configuration recommandée}}", message: '<form class="form-horizontal"> ' + '<label class="control-label" > {{Voulez-vous appliquer le jeu de configuration recommandée par l\'équipe Jeedom ?}} </label> ' + '<br><br>' + '<ul>' + '<li class="active">{{Paramètres.}}</li>' + '<li class="active">{{Associations.}}</li>' + '<li class="active">{{Intervalle de réveil.}}</li>' + '<li class="active">{{Rafraîchissement.}}</li>' + '</ul>' + '</form>', buttons: { main: { label: "{{Annuler}}", className: "btn-danger", callback: function () { } }, success: { label: "{{Appliquer}}", className: "btn-success", callback: function () { $.ajax({ type: "POST", url: "plugins/openzwave/core/ajax/openzwave.ajax.php", data: { action: "applyRecommended", id: _eqLogic.id, }, dataType: 'json', error: function (request, status, error) { handleAjaxError(request, status, error); }, success: function (data) { if (data.state != 'ok') { $('#div_alert').showAlert({message: data.result, level: 'danger'}); return; } if (data.result == "wakeup") { $('#div_alert').showAlert({ message: '{{Configuration appliquée. Cependant ce module nécessite un réveil pour que celle-ci soit effective.}}', level: 'success' }); } else { $('#div_alert').showAlert({ message: '{{Configuration appliquée et effective.}}', level: 'success' }); } } }); } } } } ); }); } else { $('#bt_deviceRecommended').hide(); } modifyWithoutSave = false; } }); $.ajax({ type: "POST", url: "plugins/openzwave/core/ajax/openzwave.ajax.php", data: { action: "getAllPossibleConf", id: _eqLogic.id, }, dataType: 'json', global: false, error: function (request, status, error) { handleAjaxError(request, status, error); }, success: function (data) { $('.eqLogicAttr[data-l1key=configuration][data-l2key=fileconf]').empty(); if (data.result.length > 1) { option = ''; for (var i in data.result) { option += '<option value="' + data.result[i] + '">' + data.result[i] + '</option>'; } $('.eqLogicAttr[data-l1key=configuration][data-l2key=fileconf]').append(option); $('.eqLogicAttr[data-l1key=configuration][data-l2key=fileconf]').closest('.form-group').show(); if (isset(_eqLogic.configuration.fileconf)) { $('.eqLogicAttr[data-l1key=configuration][data-l2key=fileconf]').value(_eqLogic.configuration.fileconf); } } else { $('.eqLogicAttr[data-l1key=configuration][data-l2key=fileconf]').closest('.form-group').hide(); } modifyWithoutSave = false; } }); } /**********************Envent js requests *****************************/ $('body').off('zwave::controller.data.controllerState').on('zwave::controller.data.controllerState', function (_event, _options) { $.hideAlert(); if (_options.state == 1) { $('.changeIncludeState[data-mode=1]:not(.card)').removeClass('btn-default').addClass('btn-success'); $('.changeIncludeState.card[data-mode=1]').removeClass('success').addClass('warning'); $('.changeIncludeState.card[data-mode=1] span').text('{{Arrêter l\'inclusion}}'); $('.changeIncludeState[data-mode=1]').attr('data-state', 0); $('.changeIncludeState[data-mode=1]:not(.card)').html('<i class="fas fa-sign-in-alt"></i> {{Arrêter l\'inclusion}}'); $('#div_inclusionAlert').showAlert({ message: '{{Vous êtes en mode inclusion}} ' + '. {{Cliquez à nouveau sur le bouton d\'inclusion pour sortir de ce mode. Pour inclure un module veuillez appuyer sur son bouton d\'inclusion (une ou plusieurs fois comme décrit dans la documentation du module).}}', level: 'warning', ttl: -1 }); } else if (_options.state == 5) { $('.changeIncludeState[data-mode=0]:not(.card)').removeClass('btn-default').addClass('btn-danger'); $('.changeIncludeState.card[data-mode=0]').removeClass('danger').addClass('warning'); $('.changeIncludeState.card[data-mode=0] span').text('{{Arrêter l\'exclusion}}'); $('.changeIncludeState[data-mode=0]').attr('data-state', 0); $('.changeIncludeState[data-mode=0]:not(.card)').html('<i class="fas fa-sign-out-alt"></i> {{Arrêter l\'exclusion}}'); $('#div_inclusionAlert').showAlert({ message: '{{Vous êtes en mode exclusion}} ' + '. {{Cliquez à nouveau sur le bouton d\'exclusion pour sortir de ce mode. Pour exclure un module veuillez appuyer sur son bouton d\'inclusion (une ou plusieurs fois comme décrit dans la documentation du module).}}', level: 'warning', ttl: -1 }); } else { $('.changeIncludeState.card[data-mode=1]').removeClass('warning').addClass('success'); $('.changeIncludeState.card[data-mode=0]').removeClass('warning').addClass('danger'); $('.changeIncludeState[data-mode=1]:not(.card)').html('<i class="fas fa-sign-in-alt fa-rotate-90"></i> {{Mode inclusion}}'); $('.changeIncludeState[data-mode=0]:not(.card)').html('<i class="fas fa-sign-in-alt fa-rotate-90"></i> {{Mode exclusion}}'); $('.changeIncludeState.card[data-mode=1] span').text('{{Mode inclusion}}'); $('.changeIncludeState.card[data-mode=0] span').text('{{Mode exclusion}}'); $('.changeIncludeState[data-mode=1]').attr('data-state', 1); $('.changeIncludeState[data-mode=0]').attr('data-state', 1); $('.changeIncludeState[data-mode=1]:not(.card)').removeClass('btn-success').addClass('btn-default'); $('.changeIncludeState[data-mode=0]:not(.card)').removeClass('btn-danger').addClass('btn-default'); } }); $('body').off('zwave::includeDevice').on('zwave::includeDevice', function (_event, _options) { if (modifyWithoutSave) { $('#div_inclusionAlert').showAlert({ message: '{{Un périphérique vient d\'être inclu/exclu. Veuillez réactualiser la page}}', level: 'warning' }); } else { if (_options == '') { window.location.reload(); } else { window.location.href = 'index.php?v=d&p=openzwave&m=openzwave&id=' + _options; } } }); $('#bt_autoDetectModule').off('click').on('click', function () { var dialog_title = '{{Recharge configuration}}'; var dialog_message = '<form class="form-horizontal onsubmit="return false;"> '; dialog_title = '{{Recharger la configuration}}'; dialog_message += '<label class="control-label" > {{Sélectionner le mode de rechargement de la configuration ?}} </label> ' + '<div> <div class="radio"> <label > ' + '<input type="radio" name="command" id="command-0" value="0" checked="checked"> {{Sans recréer les commandes mais en créeant les manquantes}} </label> ' + '</div><div class="radio"> <label > ' + '<input type="radio" name="command" id="command-1" value="1"> {{En recréant les commandes}}</label> ' + '</div> ' + '</div><br>' + '<label class="lbl lbl-warning" for="name">{{Attention, "en recréant les commandes" va supprimer les commandes existantes.}}</label> '; dialog_message += '</form>'; bootbox.dialog({ title: dialog_title, message: dialog_message, buttons: { "{{Annuler}}": { className: "btn-danger", callback: function () { } }, success: { label: "{{Démarrer}}", className: "btn-success", callback: function () { if ($("input[name='command']:checked").val() == "1"){ bootbox.confirm('{{Etes-vous sûr de vouloir récréer toutes les commandes ? Cela va supprimer les commandes existantes}}', function (result) { if (result) { $.ajax({ type: "POST", url: "plugins/openzwave/core/ajax/openzwave.ajax.php", data: { action: "autoDetectModule", id: $('.eqLogicAttr[data-l1key=id]').value(), createcommand: 1, }, dataType: 'json', global: false, error: function (request, status, error) { handleAjaxError(request, status, error); }, success: function (data) { if (data.state != 'ok') { $('#div_alert').showAlert({message: data.result, level: 'danger'}); return; } $('#div_alert').showAlert({message: '{{Opération réalisée avec succès}}', level: 'success'}); $('.eqLogicDisplayCard[data-eqLogic_id=' + $('.eqLogicAttr[data-l1key=id]').value() + ']').click(); } }); } }); } else { $.ajax({ type: "POST", url: "plugins/openzwave/core/ajax/openzwave.ajax.php", data: { action: "autoDetectModule", id: $('.eqLogicAttr[data-l1key=id]').value(), createcommand: 0, }, dataType: 'json', global: false, error: function (request, status, error) { handleAjaxError(request, status, error); }, success: function (data) { if (data.state != 'ok') { $('#div_alert').showAlert({message: data.result, level: 'danger'}); return; } $('#div_alert').showAlert({message: '{{Opération réalisée avec succès}}', level: 'success'}); $('.eqLogicDisplayCard[data-eqLogic_id=' + $('.eqLogicAttr[data-l1key=id]').value() + ']').click(); } }); } } }, } }); }); function syncEqLogicWithOpenZwave() { $.ajax({ type: "POST", url: "plugins/openzwave/core/ajax/openzwave.ajax.php", data: { action: "syncEqLogicWithOpenZwave", }, dataType: 'json', error: function (request, status, error) { handleAjaxError(request, status, error); }, success: function (data) { if (data.state != 'ok') { $('#div_alert').showAlert({message: data.result, level: 'danger'}); return; } window.location.reload(); } }); } function addCmdToTable(_cmd) { if (!isset(_cmd)) { var _cmd = {configuration: {}}; } var tr = '<tr class="cmd" data-cmd_id="' + init(_cmd.id) + '">'; tr += '<td>'; tr += '<a class="cmdAction btn btn-default btn-sm" data-l1key="chooseIcon"><i class="fas fa-flag"></i> {{Icône}}</a>'; tr += '<span class="cmdAttr" data-l1key="display" data-l2key="icon" style="margin-left:10px;"></span>'; tr += '<input class="cmdAttr form-control input-sm" data-l1key="name" style="margin-left:10px; margin-bottom:2px; width:185px; float:right">'; tr += '<select class="cmdAttr form-control input-sm" data-l1key="value" style="display : none;" title="{{La valeur de la commande vaut par défaut la commande}}">'; tr += '<option value="">Aucune</option>'; tr += '</select>'; tr += '</td>'; tr += '<td>'; tr += '<input class="cmdAttr form-control input-sm" data-l1key="id" style="display : none;">'; tr += '<span class="type" type="' + init(_cmd.type) + '">' + jeedom.cmd.availableType() + '</span>'; tr += '<span class="subType" subType="' + init(_cmd.subType) + '"></span>'; tr += '</td>'; tr += '<td><input class="cmdAttr form-control input-sm" data-l1key="configuration" data-l2key="class" ></td>'; tr += '<td><input class="cmdAttr form-control input-sm" data-l1key="configuration" data-l2key="instance" value="1"></td>'; tr += '<td><input class="cmdAttr form-control input-sm" data-l1key="configuration" data-l2key="index" ></td>'; tr += '<td>'; if (init(_cmd.type) == 'action'){ tr += '<input class="cmdAttr form-control input-sm" data-l1key="configuration" data-l2key="value" placeholder="{{Commande}}" >'; } tr += '<input class="cmdAttr form-control input-sm" data-l1key="configuration" data-l2key="returnStateValue" placeholder="{{Valeur retour d\'état}}" style="width:48%;display:inline-block;">'; tr += '<input class="cmdAttr form-control input-sm" data-l1key="configuration" data-l2key="returnStateTime" placeholder="{{Durée avant retour d\'état (min)}}" style="width:48%;display:inline-block;margin-left:2px;">'; tr += '</td>'; tr += '<td>'; tr += '<input class="tooltips cmdAttr form-control input-sm" data-l1key="configuration" data-l2key="minValue" placeholder="{{Min}}" title="{{Min}}" style="width:30%;display:inline-block;">'; tr += ' <input class="tooltips cmdAttr form-control input-sm" data-l1key="configuration" data-l2key="maxValue" placeholder="{{Max}}" title="{{Max}}" style="width:30%;display:inline-block;">'; tr += '<input class="cmdAttr form-control input-sm" data-l1key="unite" placeholder="Unité" title="{{Unité}}" style="width:30%;display:inline-block;margin-left:2px;">'; tr += '<span><label class="checkbox-inline"><input type="checkbox" class="cmdAttr checkbox-inline" data-l1key="isVisible" checked/>{{Afficher}}</label></span> '; tr += '<span><label class="checkbox-inline"><input type="checkbox" class="cmdAttr checkbox-inline" data-l1key="isHistorized" checked/>{{Historiser}}</label></span> '; tr += '<span><label class="checkbox-inline"><input type="checkbox" class="cmdAttr" data-l1key="display" data-l2key="invertBinary"/>{{Inverser}}</label></span> '; tr += '</td>'; tr += '<td style="width:125px">'; if (is_numeric(_cmd.id)) { tr += '<a class="btn btn-default btn-xs cmdAction" data-action="configure"><i class="fas fa-cogs"></i></a> '; tr += '<a class="btn btn-default btn-xs cmdAction" data-action="test"><i class="fas fa-rss"></i> {{Tester}}</a>'; } tr += ' <i class="fas fa-minus-circle cmdAction cursor" data-action="remove"></i></td>'; tr += '</tr>'; $('#table_cmd tbody').append(tr); var tr = $('#table_cmd tbody tr').last(); jeedom.eqLogic.builSelectCmd({ id: $('.eqLogicAttr[data-l1key=id]').value(), filter: {type: 'info'}, error: function (error) { $('#div_alert').showAlert({message: error.message, level: 'danger'}); }, success: function (result) { tr.find('.cmdAttr[data-l1key=value]').append(result); tr.setValues(_cmd, '.cmdAttr'); jeedom.cmd.changeType(tr, init(_cmd.subType)); } }); }
jeedom/plugin-openzwave
desktop/js/openzwave.js
JavaScript
gpl-2.0
22,549
(function ($) { /** * Drag and drop table rows with field manipulation. * * Using the drupal_add_tabledrag() function, any table with weights or parent * relationships may be made into draggable tables. Columns containing a field * may optionally be hidden, providing a better user experience. * * Created tableDrag instances may be modified with custom behaviors by * overriding the .onDrag, .onDrop, .row.onSwap, and .row.onIndent methods. * See blocks.js for an example of adding additional functionality to tableDrag. */ Drupal.behaviors.tableDrag = { attach: function (context, settings) { for (var base in settings.tableDrag) { $('#' + base, context).once('tabledrag', function () { // Create the new tableDrag instance. Save in the Drupal variable // to allow other scripts access to the object. Drupal.tableDrag[base] = new Drupal.tableDrag(this, settings.tableDrag[base]); }); } } }; /** * Constructor for the tableDrag object. Provides table and field manipulation. * * @param table * DOM object for the table to be made draggable. * @param tableSettings * Settings for the table added via drupal_add_dragtable(). */ Drupal.tableDrag = function (table, tableSettings) { var self = this; // Required object variables. this.table = table; this.tableSettings = tableSettings; this.dragObject = null; // Used to hold information about a current drag operation. this.rowObject = null; // Provides operations for row manipulation. this.oldRowElement = null; // Remember the previous element. this.oldY = 0; // Used to determine up or down direction from last mouse move. this.changed = false; // Whether anything in the entire table has changed. this.maxDepth = 0; // Maximum amount of allowed parenting. this.rtl = $(this.table).css('direction') == 'rtl' ? -1 : 1; // Direction of the table. // Configure the scroll settings. this.scrollSettings = { amount: 4, interval: 50, trigger: 70 }; this.scrollInterval = null; this.scrollY = 0; this.windowHeight = 0; // Check this table's settings to see if there are parent relationships in // this table. For efficiency, large sections of code can be skipped if we // don't need to track horizontal movement and indentations. this.indentEnabled = false; for (var group in tableSettings) { for (var n in tableSettings[group]) { if (tableSettings[group][n].relationship == 'parent') { this.indentEnabled = true; } if (tableSettings[group][n].limit > 0) { this.maxDepth = tableSettings[group][n].limit; } } } if (this.indentEnabled) { this.indentCount = 1; // Total width of indents, set in makeDraggable. // Find the width of indentations to measure mouse movements against. // Because the table doesn't need to start with any indentations, we // manually append 2 indentations in the first draggable row, measure // the offset, then remove. var indent = Drupal.theme('tableDragIndentation'); var testRow = $('<tr/>').addClass('draggable').appendTo(table); var testCell = $('<td/>').appendTo(testRow).prepend(indent).prepend(indent); this.indentAmount = $('.indentation', testCell).get(1).offsetLeft - $('.indentation', testCell).get(0).offsetLeft; testRow.remove(); } // Make each applicable row draggable. // Match immediate children of the parent element to allow nesting. $('> tr.draggable, > tbody > tr.draggable', table).each(function () { self.makeDraggable(this); }); // Add a link before the table for users to show or hide weight columns. $(table).before($('<a href="#" class="tabledrag-toggle-weight"></a>') .attr('title', Drupal.t('Re-order rows by numerical weight instead of dragging.')) .click(function () { if ($.cookie('Drupal.tableDrag.showWeight') == 1) { self.hideColumns(); } else { self.showColumns(); } return false; }) .wrap('<div class="tabledrag-toggle-weight-wrapper"></div>') .parent() ); // Initialize the specified columns (for example, weight or parent columns) // to show or hide according to user preference. This aids accessibility // so that, e.g., screen reader users can choose to enter weight values and // manipulate form elements directly, rather than using drag-and-drop.. self.initColumns(); // Add mouse bindings to the document. The self variable is passed along // as event handlers do not have direct access to the tableDrag object. $(document).bind('mousemove', function (event) { return self.dragRow(event, self); }); $(document).bind('mouseup', function (event) { return self.dropRow(event, self); }); }; /** * Initialize columns containing form elements to be hidden by default, * according to the settings for this tableDrag instance. * * Identify and mark each cell with a CSS class so we can easily toggle * show/hide it. Finally, hide columns if user does not have a * 'Drupal.tableDrag.showWeight' cookie. */ Drupal.tableDrag.prototype.initColumns = function () { for (var group in this.tableSettings) { // Find the first field in this group. for (var d in this.tableSettings[group]) { var field = $('.' + this.tableSettings[group][d].target + ':first', this.table); if (field.length && this.tableSettings[group][d].hidden) { var hidden = this.tableSettings[group][d].hidden; var cell = field.closest('td'); break; } } // Mark the column containing this field so it can be hidden. if (hidden && cell[0]) { // Add 1 to our indexes. The nth-child selector is 1 based, not 0 based. // Match immediate children of the parent element to allow nesting. var columnIndex = $('> td', cell.parent()).index(cell.get(0)) + 1; $('> thead > tr, > tbody > tr, > tr', this.table).each(function () { // Get the columnIndex and adjust for any colspans in this row. var index = columnIndex; var cells = $(this).children(); cells.each(function (n) { if (n < index && this.colSpan && this.colSpan > 1) { index -= this.colSpan - 1; } }); if (index > 0) { cell = cells.filter(':nth-child(' + index + ')'); if (cell[0].colSpan && cell[0].colSpan > 1) { // If this cell has a colspan, mark it so we can reduce the colspan. cell.addClass('tabledrag-has-colspan'); } else { // Mark this cell so we can hide it. cell.addClass('tabledrag-hide'); } } }); } } // Now hide cells and reduce colspans unless cookie indicates previous choice. // Set a cookie if it is not already present. if ($.cookie('Drupal.tableDrag.showWeight') === null) { $.cookie('Drupal.tableDrag.showWeight', 0, { path: Drupal.settings.basePath, // The cookie expires in one year. expires: 365 }); this.hideColumns(); } // Check cookie value and show/hide weight columns accordingly. else { if ($.cookie('Drupal.tableDrag.showWeight') == 1) { this.showColumns(); } else { this.hideColumns(); } } }; /** * Hide the columns containing weight/parent form elements. * Undo showColumns(). */ Drupal.tableDrag.prototype.hideColumns = function () { // Hide weight/parent cells and headers. $('.tabledrag-hide', 'table.tabledrag-processed').css('display', 'none'); // Show TableDrag handles. $('.tabledrag-handle', 'table.tabledrag-processed').css('display', ''); // Reduce the colspan of any effected multi-span columns. $('.tabledrag-has-colspan', 'table.tabledrag-processed').each(function () { this.colSpan = this.colSpan - 1; }); // Change link text. $('.tabledrag-toggle-weight').text(Drupal.t('Show row weights')); // Change cookie. $.cookie('Drupal.tableDrag.showWeight', 0, { path: Drupal.settings.basePath, // The cookie expires in one year. expires: 365 }); // Trigger an event to allow other scripts to react to this display change. $('table.tabledrag-processed').trigger('columnschange', 'hide'); }; /** * Show the columns containing weight/parent form elements * Undo hideColumns(). */ Drupal.tableDrag.prototype.showColumns = function () { // Show weight/parent cells and headers. $('.tabledrag-hide', 'table.tabledrag-processed').css('display', ''); // Hide TableDrag handles. $('.tabledrag-handle', 'table.tabledrag-processed').css('display', 'none'); // Increase the colspan for any columns where it was previously reduced. $('.tabledrag-has-colspan', 'table.tabledrag-processed').each(function () { this.colSpan = this.colSpan + 1; }); // Change link text. $('.tabledrag-toggle-weight').text(Drupal.t('Hide row weights')); // Change cookie. $.cookie('Drupal.tableDrag.showWeight', 1, { path: Drupal.settings.basePath, // The cookie expires in one year. expires: 365 }); // Trigger an event to allow other scripts to react to this display change. $('table.tabledrag-processed').trigger('columnschange', 'show'); }; /** * Find the target used within a particular row and group. */ Drupal.tableDrag.prototype.rowSettings = function (group, row) { var field = $('.' + group, row); for (var delta in this.tableSettings[group]) { var targetClass = this.tableSettings[group][delta].target; if (field.is('.' + targetClass)) { // Return a copy of the row settings. var rowSettings = {}; for (var n in this.tableSettings[group][delta]) { rowSettings[n] = this.tableSettings[group][delta][n]; } return rowSettings; } } }; /** * Take an item and add event handlers to make it become draggable. */ Drupal.tableDrag.prototype.makeDraggable = function (item) { var self = this; // Create the handle. var handle = $('<a href="#" class="tabledrag-handle"><div class="handle">&nbsp;</div></a>').attr('title', Drupal.t('Drag to re-order')); // Insert the handle after indentations (if any). if ($('td:first .indentation:last', item).length) { $('td:first .indentation:last', item).after(handle); // Update the total width of indentation in this entire table. self.indentCount = Math.max($('.indentation', item).length, self.indentCount); } else { $('td:first', item).prepend(handle); } // Add hover action for the handle. handle.hover(function () { self.dragObject == null ? $(this).addClass('tabledrag-handle-hover') : null; }, function () { self.dragObject == null ? $(this).removeClass('tabledrag-handle-hover') : null; }); // Add the mousedown action for the handle. handle.mousedown(function (event) { // Create a new dragObject recording the event information. self.dragObject = {}; self.dragObject.initMouseOffset = self.getMouseOffset(item, event); self.dragObject.initMouseCoords = self.mouseCoords(event); if (self.indentEnabled) { self.dragObject.indentMousePos = self.dragObject.initMouseCoords; } // If there's a lingering row object from the keyboard, remove its focus. if (self.rowObject) { $('a.tabledrag-handle', self.rowObject.element).blur(); } // Create a new rowObject for manipulation of this row. self.rowObject = new self.row(item, 'mouse', self.indentEnabled, self.maxDepth, true); // Save the position of the table. self.table.topY = $(self.table).offset().top; self.table.bottomY = self.table.topY + self.table.offsetHeight; // Add classes to the handle and row. $(this).addClass('tabledrag-handle-hover'); $(item).addClass('drag'); // Set the document to use the move cursor during drag. $('body').addClass('drag'); if (self.oldRowElement) { $(self.oldRowElement).removeClass('drag-previous'); } // Hack for IE6 that flickers uncontrollably if select lists are moved. if (navigator.userAgent.indexOf('MSIE 6.') != -1) { $('select', this.table).css('display', 'none'); } // Hack for Konqueror, prevent the blur handler from firing. // Konqueror always gives links focus, even after returning false on mousedown. self.safeBlur = false; // Call optional placeholder function. self.onDrag(); return false; }); // Prevent the anchor tag from jumping us to the top of the page. handle.click(function () { return false; }); // Similar to the hover event, add a class when the handle is focused. handle.focus(function () { $(this).addClass('tabledrag-handle-hover'); self.safeBlur = true; }); // Remove the handle class on blur and fire the same function as a mouseup. handle.blur(function (event) { $(this).removeClass('tabledrag-handle-hover'); if (self.rowObject && self.safeBlur) { self.dropRow(event, self); } }); // Add arrow-key support to the handle. handle.keydown(function (event) { // If a rowObject doesn't yet exist and this isn't the tab key. if (event.keyCode != 9 && !self.rowObject) { self.rowObject = new self.row(item, 'keyboard', self.indentEnabled, self.maxDepth, true); } var keyChange = false; switch (event.keyCode) { case 37: // Left arrow. case 63234: // Safari left arrow. keyChange = true; self.rowObject.indent(-1 * self.rtl); break; case 38: // Up arrow. case 63232: // Safari up arrow. var previousRow = $(self.rowObject.element).prev('tr').get(0); while (previousRow && $(previousRow).is(':hidden')) { previousRow = $(previousRow).prev('tr').get(0); } if (previousRow) { self.safeBlur = false; // Do not allow the onBlur cleanup. self.rowObject.direction = 'up'; keyChange = true; if ($(item).is('.tabledrag-root')) { // Swap with the previous top-level row. var groupHeight = 0; while (previousRow && $('.indentation', previousRow).length) { previousRow = $(previousRow).prev('tr').get(0); groupHeight += $(previousRow).is(':hidden') ? 0 : previousRow.offsetHeight; } if (previousRow) { self.rowObject.swap('before', previousRow); // No need to check for indentation, 0 is the only valid one. window.scrollBy(0, -groupHeight); } } else if (self.table.tBodies[0].rows[0] != previousRow || $(previousRow).is('.draggable')) { // Swap with the previous row (unless previous row is the first one // and undraggable). self.rowObject.swap('before', previousRow); self.rowObject.interval = null; self.rowObject.indent(0); window.scrollBy(0, -parseInt(item.offsetHeight, 10)); } handle.get(0).focus(); // Regain focus after the DOM manipulation. } break; case 39: // Right arrow. case 63235: // Safari right arrow. keyChange = true; self.rowObject.indent(1 * self.rtl); break; case 40: // Down arrow. case 63233: // Safari down arrow. var nextRow = $(self.rowObject.group).filter(':last').next('tr').get(0); while (nextRow && $(nextRow).is(':hidden')) { nextRow = $(nextRow).next('tr').get(0); } if (nextRow) { self.safeBlur = false; // Do not allow the onBlur cleanup. self.rowObject.direction = 'down'; keyChange = true; if ($(item).is('.tabledrag-root')) { // Swap with the next group (necessarily a top-level one). var groupHeight = 0; var nextGroup = new self.row(nextRow, 'keyboard', self.indentEnabled, self.maxDepth, false); if (nextGroup) { $(nextGroup.group).each(function () { groupHeight += $(this).is(':hidden') ? 0 : this.offsetHeight; }); var nextGroupRow = $(nextGroup.group).filter(':last').get(0); self.rowObject.swap('after', nextGroupRow); // No need to check for indentation, 0 is the only valid one. window.scrollBy(0, parseInt(groupHeight, 10)); } } else { // Swap with the next row. self.rowObject.swap('after', nextRow); self.rowObject.interval = null; self.rowObject.indent(0); window.scrollBy(0, parseInt(item.offsetHeight, 10)); } handle.get(0).focus(); // Regain focus after the DOM manipulation. } break; } if (self.rowObject && self.rowObject.changed == true) { $(item).addClass('drag'); if (self.oldRowElement) { $(self.oldRowElement).removeClass('drag-previous'); } self.oldRowElement = item; self.restripeTable(); self.onDrag(); } // Returning false if we have an arrow key to prevent scrolling. if (keyChange) { return false; } }); // Compatibility addition, return false on keypress to prevent unwanted scrolling. // IE and Safari will suppress scrolling on keydown, but all other browsers // need to return false on keypress. http://www.quirksmode.org/js/keys.html handle.keypress(function (event) { switch (event.keyCode) { case 37: // Left arrow. case 38: // Up arrow. case 39: // Right arrow. case 40: // Down arrow. return false; } }); }; /** * Mousemove event handler, bound to document. */ Drupal.tableDrag.prototype.dragRow = function (event, self) { if (self.dragObject) { self.currentMouseCoords = self.mouseCoords(event); var y = self.currentMouseCoords.y - self.dragObject.initMouseOffset.y; var x = self.currentMouseCoords.x - self.dragObject.initMouseOffset.x; // Check for row swapping and vertical scrolling. if (y != self.oldY) { self.rowObject.direction = y > self.oldY ? 'down' : 'up'; self.oldY = y; // Update the old value. // Check if the window should be scrolled (and how fast). var scrollAmount = self.checkScroll(self.currentMouseCoords.y); // Stop any current scrolling. clearInterval(self.scrollInterval); // Continue scrolling if the mouse has moved in the scroll direction. if (scrollAmount > 0 && self.rowObject.direction == 'down' || scrollAmount < 0 && self.rowObject.direction == 'up') { self.setScroll(scrollAmount); } // If we have a valid target, perform the swap and restripe the table. var currentRow = self.findDropTargetRow(x, y); if (currentRow) { if (self.rowObject.direction == 'down') { self.rowObject.swap('after', currentRow, self); } else { self.rowObject.swap('before', currentRow, self); } self.restripeTable(); } } // Similar to row swapping, handle indentations. if (self.indentEnabled) { var xDiff = self.currentMouseCoords.x - self.dragObject.indentMousePos.x; // Set the number of indentations the mouse has been moved left or right. var indentDiff = Math.round(xDiff / self.indentAmount); // Indent the row with our estimated diff, which may be further // restricted according to the rows around this row. var indentChange = self.rowObject.indent(indentDiff); // Update table and mouse indentations. self.dragObject.indentMousePos.x += self.indentAmount * indentChange * self.rtl; self.indentCount = Math.max(self.indentCount, self.rowObject.indents); } return false; } }; /** * Mouseup event handler, bound to document. * Blur event handler, bound to drag handle for keyboard support. */ Drupal.tableDrag.prototype.dropRow = function (event, self) { // Drop row functionality shared between mouseup and blur events. if (self.rowObject != null) { var droppedRow = self.rowObject.element; // The row is already in the right place so we just release it. if (self.rowObject.changed == true) { // Update the fields in the dropped row. self.updateFields(droppedRow); // If a setting exists for affecting the entire group, update all the // fields in the entire dragged group. for (var group in self.tableSettings) { var rowSettings = self.rowSettings(group, droppedRow); if (rowSettings.relationship == 'group') { for (var n in self.rowObject.children) { self.updateField(self.rowObject.children[n], group); } } } self.rowObject.markChanged(); if (self.changed == false) { $(Drupal.theme('tableDragChangedWarning')).insertBefore(self.table).hide().fadeIn('slow'); self.changed = true; } } if (self.indentEnabled) { self.rowObject.removeIndentClasses(); } if (self.oldRowElement) { $(self.oldRowElement).removeClass('drag-previous'); } $(droppedRow).removeClass('drag').addClass('drag-previous'); self.oldRowElement = droppedRow; self.onDrop(); self.rowObject = null; } // Functionality specific only to mouseup event. if (self.dragObject != null) { $('.tabledrag-handle', droppedRow).removeClass('tabledrag-handle-hover'); self.dragObject = null; $('body').removeClass('drag'); clearInterval(self.scrollInterval); // Hack for IE6 that flickers uncontrollably if select lists are moved. if (navigator.userAgent.indexOf('MSIE 6.') != -1) { $('select', this.table).css('display', 'block'); } } }; /** * Get the mouse coordinates from the event (allowing for browser differences). */ Drupal.tableDrag.prototype.mouseCoords = function (event) { if (event.pageX || event.pageY) { return { x: event.pageX, y: event.pageY }; } return { x: event.clientX + document.body.scrollLeft - document.body.clientLeft, y: event.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. */ Drupal.tableDrag.prototype.getMouseOffset = function (target, event) { var docPos = $(target).offset(); var mousePos = this.mouseCoords(event); return { x: mousePos.x - docPos.left, y: mousePos.y - docPos.top }; }; /** * Find the row the mouse is currently over. This row is then taken and swapped * with the one being dragged. * * @param x * The x coordinate of the mouse on the page (not the screen). * @param y * The y coordinate of the mouse on the page (not the screen). */ Drupal.tableDrag.prototype.findDropTargetRow = function (x, y) { var rows = $(this.table.tBodies[0].rows).not(':hidden'); for (var n = 0; n < rows.length; n++) { var row = rows[n]; var indentDiff = 0; var rowY = $(row).offset().top; // Because Safari does not report offsetHeight on table rows, but does on // table cells, grab the firstChild of the row and use that instead. // http://jacob.peargrove.com/blog/2006/technical/table-row-offsettop-bug-in-safari. if (row.offsetHeight == 0) { var rowHeight = parseInt(row.firstChild.offsetHeight, 10) / 2; } // Other browsers. else { var rowHeight = parseInt(row.offsetHeight, 10) / 2; } // Because we always insert before, we need to offset the height a bit. if ((y > (rowY - rowHeight)) && (y < (rowY + rowHeight))) { if (this.indentEnabled) { // Check that this row is not a child of the row being dragged. for (var n in this.rowObject.group) { if (this.rowObject.group[n] == row) { return null; } } } else { // Do not allow a row to be swapped with itself. if (row == this.rowObject.element) { return null; } } // Check that swapping with this row is allowed. if (!this.rowObject.isValidSwap(row)) { return null; } // We may have found the row the mouse just passed over, but it doesn't // take into account hidden rows. Skip backwards until we find a draggable // row. while ($(row).is(':hidden') && $(row).prev('tr').is(':hidden')) { row = $(row).prev('tr').get(0); } return row; } } return null; }; /** * After the row is dropped, update the table fields according to the settings * set for this table. * * @param changedRow * DOM object for the row that was just dropped. */ Drupal.tableDrag.prototype.updateFields = function (changedRow) { for (var group in this.tableSettings) { // Each group may have a different setting for relationship, so we find // the source rows for each separately. this.updateField(changedRow, group); } }; /** * After the row is dropped, update a single table field according to specific * settings. * * @param changedRow * DOM object for the row that was just dropped. * @param group * The settings group on which field updates will occur. */ Drupal.tableDrag.prototype.updateField = function (changedRow, group) { var rowSettings = this.rowSettings(group, changedRow); // Set the row as its own target. if (rowSettings.relationship == 'self' || rowSettings.relationship == 'group') { var sourceRow = changedRow; } // Siblings are easy, check previous and next rows. else if (rowSettings.relationship == 'sibling') { var previousRow = $(changedRow).prev('tr').get(0); var nextRow = $(changedRow).next('tr').get(0); var sourceRow = changedRow; if ($(previousRow).is('.draggable') && $('.' + group, previousRow).length) { if (this.indentEnabled) { if ($('.indentations', previousRow).length == $('.indentations', changedRow)) { sourceRow = previousRow; } } else { sourceRow = previousRow; } } else if ($(nextRow).is('.draggable') && $('.' + group, nextRow).length) { if (this.indentEnabled) { if ($('.indentations', nextRow).length == $('.indentations', changedRow)) { sourceRow = nextRow; } } else { sourceRow = nextRow; } } } // Parents, look up the tree until we find a field not in this group. // Go up as many parents as indentations in the changed row. else if (rowSettings.relationship == 'parent') { var previousRow = $(changedRow).prev('tr'); while (previousRow.length && $('.indentation', previousRow).length >= this.rowObject.indents) { previousRow = previousRow.prev('tr'); } // If we found a row. if (previousRow.length) { sourceRow = previousRow[0]; } // Otherwise we went all the way to the left of the table without finding // a parent, meaning this item has been placed at the root level. else { // Use the first row in the table as source, because it's guaranteed to // be at the root level. Find the first item, then compare this row // against it as a sibling. sourceRow = $(this.table).find('tr.draggable:first').get(0); if (sourceRow == this.rowObject.element) { sourceRow = $(this.rowObject.group[this.rowObject.group.length - 1]).next('tr.draggable').get(0); } var useSibling = true; } } // Because we may have moved the row from one category to another, // take a look at our sibling and borrow its sources and targets. this.copyDragClasses(sourceRow, changedRow, group); rowSettings = this.rowSettings(group, changedRow); // In the case that we're looking for a parent, but the row is at the top // of the tree, copy our sibling's values. if (useSibling) { rowSettings.relationship = 'sibling'; rowSettings.source = rowSettings.target; } var targetClass = '.' + rowSettings.target; var targetElement = $(targetClass, changedRow).get(0); // Check if a target element exists in this row. if (targetElement) { var sourceClass = '.' + rowSettings.source; var sourceElement = $(sourceClass, sourceRow).get(0); switch (rowSettings.action) { case 'depth': // Get the depth of the target row. targetElement.value = $('.indentation', $(sourceElement).closest('tr')).length; break; case 'match': // Update the value. targetElement.value = sourceElement.value; break; case 'order': var siblings = this.rowObject.findSiblings(rowSettings); if ($(targetElement).is('select')) { // Get a list of acceptable values. var values = []; $('option', targetElement).each(function () { values.push(this.value); }); var maxVal = values[values.length - 1]; // Populate the values in the siblings. $(targetClass, siblings).each(function () { // If there are more items than possible values, assign the maximum value to the row. if (values.length > 0) { this.value = values.shift(); } else { this.value = maxVal; } }); } else { // Assume a numeric input field. var weight = parseInt($(targetClass, siblings[0]).val(), 10) || 0; $(targetClass, siblings).each(function () { this.value = weight; weight++; }); } break; } } }; /** * Copy all special tableDrag classes from one row's form elements to a * different one, removing any special classes that the destination row * may have had. */ Drupal.tableDrag.prototype.copyDragClasses = function (sourceRow, targetRow, group) { var sourceElement = $('.' + group, sourceRow); var targetElement = $('.' + group, targetRow); if (sourceElement.length && targetElement.length) { targetElement[0].className = sourceElement[0].className; } }; Drupal.tableDrag.prototype.checkScroll = function (cursorY) { var de = document.documentElement; var b = document.body; var windowHeight = this.windowHeight = window.innerHeight || (de.clientHeight && de.clientWidth != 0 ? de.clientHeight : b.offsetHeight); var scrollY = this.scrollY = (document.all ? (!de.scrollTop ? b.scrollTop : de.scrollTop) : (window.pageYOffset ? window.pageYOffset : window.scrollY)); var trigger = this.scrollSettings.trigger; var delta = 0; // Return a scroll speed relative to the edge of the screen. if (cursorY - scrollY > windowHeight - trigger) { delta = trigger / (windowHeight + scrollY - cursorY); delta = (delta > 0 && delta < trigger) ? delta : trigger; return delta * this.scrollSettings.amount; } else if (cursorY - scrollY < trigger) { delta = trigger / (cursorY - scrollY); delta = (delta > 0 && delta < trigger) ? delta : trigger; return -delta * this.scrollSettings.amount; } }; Drupal.tableDrag.prototype.setScroll = function (scrollAmount) { var self = this; this.scrollInterval = setInterval(function () { // Update the scroll values stored in the object. self.checkScroll(self.currentMouseCoords.y); var aboveTable = self.scrollY > self.table.topY; var belowTable = self.scrollY + self.windowHeight < self.table.bottomY; if (scrollAmount > 0 && belowTable || scrollAmount < 0 && aboveTable) { window.scrollBy(0, scrollAmount); } }, this.scrollSettings.interval); }; Drupal.tableDrag.prototype.restripeTable = function () { // :even and :odd are reversed because jQuery counts from 0 and // we count from 1, so we're out of sync. // Match immediate children of the parent element to allow nesting. $('> tbody > tr.draggable:visible, > tr.draggable:visible', this.table) .removeClass('odd even') .filter(':odd').addClass('even').end() .filter(':even').addClass('odd'); }; /** * Stub function. Allows a custom handler when a row begins dragging. */ Drupal.tableDrag.prototype.onDrag = function () { return null; }; /** * Stub function. Allows a custom handler when a row is dropped. */ Drupal.tableDrag.prototype.onDrop = function () { return null; }; /** * Constructor to make a new object to manipulate a table row. * * @param tableRow * The DOM element for the table row we will be manipulating. * @param method * The method in which this row is being moved. Either 'keyboard' or 'mouse'. * @param indentEnabled * Whether the containing table uses indentations. Used for optimizations. * @param maxDepth * The maximum amount of indentations this row may contain. * @param addClasses * Whether we want to add classes to this row to indicate child relationships. */ Drupal.tableDrag.prototype.row = function (tableRow, method, indentEnabled, maxDepth, addClasses) { this.element = tableRow; this.method = method; this.group = [tableRow]; this.groupDepth = $('.indentation', tableRow).length; this.changed = false; this.table = $(tableRow).closest('table').get(0); this.indentEnabled = indentEnabled; this.maxDepth = maxDepth; this.direction = ''; // Direction the row is being moved. if (this.indentEnabled) { this.indents = $('.indentation', tableRow).length; this.children = this.findChildren(addClasses); this.group = $.merge(this.group, this.children); // Find the depth of this entire group. for (var n = 0; n < this.group.length; n++) { this.groupDepth = Math.max($('.indentation', this.group[n]).length, this.groupDepth); } } }; /** * Find all children of rowObject by indentation. * * @param addClasses * Whether we want to add classes to this row to indicate child relationships. */ Drupal.tableDrag.prototype.row.prototype.findChildren = function (addClasses) { var parentIndentation = this.indents; var currentRow = $(this.element, this.table).next('tr.draggable'); var rows = []; var child = 0; while (currentRow.length) { var rowIndentation = $('.indentation', currentRow).length; // A greater indentation indicates this is a child. if (rowIndentation > parentIndentation) { child++; rows.push(currentRow[0]); if (addClasses) { $('.indentation', currentRow).each(function (indentNum) { if (child == 1 && (indentNum == parentIndentation)) { $(this).addClass('tree-child-first'); } if (indentNum == parentIndentation) { $(this).addClass('tree-child'); } else if (indentNum > parentIndentation) { $(this).addClass('tree-child-horizontal'); } }); } } else { break; } currentRow = currentRow.next('tr.draggable'); } if (addClasses && rows.length) { $('.indentation:nth-child(' + (parentIndentation + 1) + ')', rows[rows.length - 1]).addClass('tree-child-last'); } return rows; }; /** * Ensure that two rows are allowed to be swapped. * * @param row * DOM object for the row being considered for swapping. */ Drupal.tableDrag.prototype.row.prototype.isValidSwap = function (row) { if (this.indentEnabled) { var prevRow, nextRow; if (this.direction == 'down') { prevRow = row; nextRow = $(row).next('tr').get(0); } else { prevRow = $(row).prev('tr').get(0); nextRow = row; } this.interval = this.validIndentInterval(prevRow, nextRow); // We have an invalid swap if the valid indentations interval is empty. if (this.interval.min > this.interval.max) { return false; } } // Do not let an un-draggable first row have anything put before it. if (this.table.tBodies[0].rows[0] == row && $(row).is(':not(.draggable)')) { return false; } return true; }; /** * Perform the swap between two rows. * * @param position * Whether the swap will occur 'before' or 'after' the given row. * @param row * DOM element what will be swapped with the row group. */ Drupal.tableDrag.prototype.row.prototype.swap = function (position, row) { Drupal.detachBehaviors(this.group, Drupal.settings, 'move'); $(row)[position](this.group); Drupal.attachBehaviors(this.group, Drupal.settings); this.changed = true; this.onSwap(row); }; /** * Determine the valid indentations interval for the row at a given position * in the table. * * @param prevRow * DOM object for the row before the tested position * (or null for first position in the table). * @param nextRow * DOM object for the row after the tested position * (or null for last position in the table). */ Drupal.tableDrag.prototype.row.prototype.validIndentInterval = function (prevRow, nextRow) { var minIndent, maxIndent; // Minimum indentation: // Do not orphan the next row. minIndent = nextRow ? $('.indentation', nextRow).length : 0; // Maximum indentation: if (!prevRow || $(prevRow).is(':not(.draggable)') || $(this.element).is('.tabledrag-root')) { // Do not indent: // - the first row in the table, // - rows dragged below a non-draggable row, // - 'root' rows. maxIndent = 0; } else { // Do not go deeper than as a child of the previous row. maxIndent = $('.indentation', prevRow).length + ($(prevRow).is('.tabledrag-leaf') ? 0 : 1); // Limit by the maximum allowed depth for the table. if (this.maxDepth) { maxIndent = Math.min(maxIndent, this.maxDepth - (this.groupDepth - this.indents)); } } return { 'min': minIndent, 'max': maxIndent }; }; /** * Indent a row within the legal bounds of the table. * * @param indentDiff * The number of additional indentations proposed for the row (can be * positive or negative). This number will be adjusted to nearest valid * indentation level for the row. */ Drupal.tableDrag.prototype.row.prototype.indent = function (indentDiff) { // Determine the valid indentations interval if not available yet. if (!this.interval) { var prevRow = $(this.element).prev('tr').get(0); var nextRow = $(this.group).filter(':last').next('tr').get(0); this.interval = this.validIndentInterval(prevRow, nextRow); } // Adjust to the nearest valid indentation. var indent = this.indents + indentDiff; indent = Math.max(indent, this.interval.min); indent = Math.min(indent, this.interval.max); indentDiff = indent - this.indents; for (var n = 1; n <= Math.abs(indentDiff); n++) { // Add or remove indentations. if (indentDiff < 0) { $('.indentation:first', this.group).remove(); this.indents--; } else { $('td:first', this.group).prepend(Drupal.theme('tableDragIndentation')); this.indents++; } } if (indentDiff) { // Update indentation for this row. this.changed = true; this.groupDepth += indentDiff; this.onIndent(); } return indentDiff; }; /** * Find all siblings for a row, either according to its subgroup or indentation. * Note that the passed-in row is included in the list of siblings. * * @param settings * The field settings we're using to identify what constitutes a sibling. */ Drupal.tableDrag.prototype.row.prototype.findSiblings = function (rowSettings) { var siblings = []; var directions = ['prev', 'next']; var rowIndentation = this.indents; for (var d = 0; d < directions.length; d++) { var checkRow = $(this.element)[directions[d]](); while (checkRow.length) { // Check that the sibling contains a similar target field. if ($('.' + rowSettings.target, checkRow)) { // Either add immediately if this is a flat table, or check to ensure // that this row has the same level of indentation. if (this.indentEnabled) { var checkRowIndentation = $('.indentation', checkRow).length; } if (!(this.indentEnabled) || (checkRowIndentation == rowIndentation)) { siblings.push(checkRow[0]); } else if (checkRowIndentation < rowIndentation) { // No need to keep looking for siblings when we get to a parent. break; } } else { break; } checkRow = $(checkRow)[directions[d]](); } // Since siblings are added in reverse order for previous, reverse the // completed list of previous siblings. Add the current row and continue. if (directions[d] == 'prev') { siblings.reverse(); siblings.push(this.element); } } return siblings; }; /** * Remove indentation helper classes from the current row group. */ Drupal.tableDrag.prototype.row.prototype.removeIndentClasses = function () { for (var n in this.children) { $('.indentation', this.children[n]) .removeClass('tree-child') .removeClass('tree-child-first') .removeClass('tree-child-last') .removeClass('tree-child-horizontal'); } }; /** * Add an asterisk or other marker to the changed row. */ Drupal.tableDrag.prototype.row.prototype.markChanged = function () { var marker = Drupal.theme('tableDragChangedMarker'); var cell = $('td:first', this.element); if ($('span.tabledrag-changed', cell).length == 0) { cell.append(marker); } }; /** * Stub function. Allows a custom handler when a row is indented. */ Drupal.tableDrag.prototype.row.prototype.onIndent = function () { return null; }; /** * Stub function. Allows a custom handler when a row is swapped. */ Drupal.tableDrag.prototype.row.prototype.onSwap = function (swappedRow) { return null; }; Drupal.theme.prototype.tableDragChangedMarker = function () { return '<span class="warning tabledrag-changed">*</span>'; }; Drupal.theme.prototype.tableDragIndentation = function () { return '<div class="indentation">&nbsp;</div>'; }; Drupal.theme.prototype.tableDragChangedWarning = function () { return '<div class="tabledrag-changed-warning messages warning">' + Drupal.theme('tableDragChangedMarker') + ' ' + Drupal.t('Changes made in this table will not be saved until the form is submitted.') + '</div>'; }; })(jQuery); ; (function ($) { /** * Attaches double-click behavior to toggle full path of Krumo elements. */ Drupal.behaviors.devel = { attach: function (context, settings) { // Add hint to footnote $('.krumo-footnote .krumo-call').once().before('<img style="vertical-align: middle;" title="Click to expand. Double-click to show path." src="' + settings.basePath + 'misc/help.png"/>'); var krumo_name = []; var krumo_type = []; function krumo_traverse(el) { krumo_name.push($(el).html()); krumo_type.push($(el).siblings('em').html().match(/\w*/)[0]); if ($(el).closest('.krumo-nest').length > 0) { krumo_traverse($(el).closest('.krumo-nest').prev().find('.krumo-name')); } } $('.krumo-child > div:first-child', context).dblclick( function(e) { if ($(this).find('> .krumo-php-path').length > 0) { // Remove path if shown. $(this).find('> .krumo-php-path').remove(); } else { // Get elements. krumo_traverse($(this).find('> a.krumo-name')); // Create path. var krumo_path_string = ''; for (var i = krumo_name.length - 1; i >= 0; --i) { // Start element. if ((krumo_name.length - 1) == i) krumo_path_string += '$' + krumo_name[i]; if (typeof krumo_name[(i-1)] !== 'undefined') { if (krumo_type[i] == 'Array') { krumo_path_string += "["; if (!/^\d*$/.test(krumo_name[(i-1)])) krumo_path_string += "'"; krumo_path_string += krumo_name[(i-1)]; if (!/^\d*$/.test(krumo_name[(i-1)])) krumo_path_string += "'"; krumo_path_string += "]"; } if (krumo_type[i] == 'Object') krumo_path_string += '->' + krumo_name[(i-1)]; } } $(this).append('<div class="krumo-php-path" style="font-family: Courier, monospace; font-weight: bold;">' + krumo_path_string + '</div>'); // Reset arrays. krumo_name = []; krumo_type = []; } } ); } }; })(jQuery); ; (function($) { Drupal.behaviors.custom_search = { attach: function(context) { if (!Drupal.settings.custom_search.solr) { // Check if the search box is not empty on submit $('form.search-form', context).submit(function(){ var $this = $(this); var box = $this.find('input.custom-search-box'); if (box.val() != undefined && box.val() == '') { $this.find('input.custom-search-box').addClass('error'); return false; } // If basic search is hidden, copy or value to the keys if ($this.find('#edit-keys').parents('div.element-invisible').attr('class') == 'element-invisible') { $this.find('#edit-keys').val($this.find('#edit-or').val()); $this.find('#edit-or').val(''); } return true; }); } // Search from target $('form.search-form').attr('target', Drupal.settings.custom_search.form_target); // Displays Popup. $('form.search-form input.custom-search-box', context).bind('click focus', function(e){ var $parentForm = $(this).parents('form'); // check if there's something in the popup and displays it var popup = $parentForm.find('fieldset.custom_search-popup'); if (popup.find('input,select').length && !popup.hasClass('opened')) { popup.fadeIn().addClass('opened'); } e.stopPropagation(); }); $(document).bind('click focus', function(){ $('fieldset.custom_search-popup').hide().removeClass('opened'); }); // Handle checkboxes $('.custom-search-selector input:checkbox', context).each(function(){ var el = $(this); if (el.val() == 'c-all') { el.change(function(){ $(this).parents('.custom-search-selector').find('input:checkbox[value!=c-all]').attr('checked', false); }); } else { if (el.val().substr(0,2) == 'c-') { el.change(function(){ $('.custom-search-selector input:checkbox').each(function(){ if ($(this).val().substr(0,2) == 'o-') { $(this).attr('checked', false); } }); $(this).parents('.custom-search-selector').find('input:checkbox[value=c-all]').attr('checked', false); }); } else { el.change(function(){ $(this).parents('.custom-search-selector').find('input:checkbox[value!=' + el.val() + ']').attr('checked', false); }); } } }); // Handle popup. var popup = $('fieldset.custom_search-popup:not(.custom_search-processed)', context).addClass("custom_search-processed"); popup.click(function(e){ e.stopPropagation(); }) popup.append('<a class="custom_search-popup-close" href="#">' + Drupal.t('Close') + '</a>'); $('a.custom_search-popup-close').click(function(e){ $('fieldset.custom_search-popup.opened').hide().removeClass('opened'); e.preventDefault(); }); } } })(jQuery); ; (function ($) { /** * A progressbar object. Initialized with the given id. Must be inserted into * the DOM afterwards through progressBar.element. * * method is the function which will perform the HTTP request to get the * progress bar state. Either "GET" or "POST". * * e.g. pb = new progressBar('myProgressBar'); * some_element.appendChild(pb.element); */ Drupal.progressBar = function (id, updateCallback, method, errorCallback) { var pb = this; this.id = id; this.method = method || 'GET'; this.updateCallback = updateCallback; this.errorCallback = errorCallback; // The WAI-ARIA setting aria-live="polite" will announce changes after users // have completed their current activity and not interrupt the screen reader. this.element = $('<div class="progress" aria-live="polite"></div>').attr('id', id); this.element.html('<div class="bar"><div class="filled"></div></div>' + '<div class="percentage"></div>' + '<div class="message">&nbsp;</div>'); }; /** * Set the percentage and status message for the progressbar. */ Drupal.progressBar.prototype.setProgress = function (percentage, message) { if (percentage >= 0 && percentage <= 100) { $('div.filled', this.element).css('width', percentage + '%'); $('div.percentage', this.element).html(percentage + '%'); } $('div.message', this.element).html(message); if (this.updateCallback) { this.updateCallback(percentage, message, this); } }; /** * Start monitoring progress via Ajax. */ Drupal.progressBar.prototype.startMonitoring = function (uri, delay) { this.delay = delay; this.uri = uri; this.sendPing(); }; /** * Stop monitoring progress via Ajax. */ Drupal.progressBar.prototype.stopMonitoring = function () { clearTimeout(this.timer); // This allows monitoring to be stopped from within the callback. this.uri = null; }; /** * Request progress data from server. */ Drupal.progressBar.prototype.sendPing = function () { if (this.timer) { clearTimeout(this.timer); } if (this.uri) { var pb = this; // When doing a post request, you need non-null data. Otherwise a // HTTP 411 or HTTP 406 (with Apache mod_security) error may result. $.ajax({ type: this.method, url: this.uri, data: '', dataType: 'json', success: function (progress) { // Display errors. if (progress.status == 0) { pb.displayError(progress.data); return; } // Update display. pb.setProgress(progress.percentage, progress.message); // Schedule next timer. pb.timer = setTimeout(function () { pb.sendPing(); }, pb.delay); }, error: function (xmlhttp) { pb.displayError(Drupal.ajaxError(xmlhttp, pb.uri)); } }); } }; /** * Display errors on the page. */ Drupal.progressBar.prototype.displayError = function (string) { var error = $('<div class="messages error"></div>').html(string); $(this.element).before(error).hide(); if (this.errorCallback) { this.errorCallback(this); } }; })(jQuery); ; (function ($) { /** * Attaches sticky table headers. */ Drupal.behaviors.tableHeader = { attach: function (context, settings) { if (!$.support.positionFixed) { return; } $('table.sticky-enabled', context).once('tableheader', function () { $(this).data("drupal-tableheader", new Drupal.tableHeader(this)); }); } }; /** * Constructor for the tableHeader object. Provides sticky table headers. * * @param table * DOM object for the table to add a sticky header to. */ Drupal.tableHeader = function (table) { var self = this; this.originalTable = $(table); this.originalHeader = $(table).children('thead'); this.originalHeaderCells = this.originalHeader.find('> tr > th'); this.displayWeight = null; // React to columns change to avoid making checks in the scroll callback. this.originalTable.bind('columnschange', function (e, display) { // This will force header size to be calculated on scroll. self.widthCalculated = (self.displayWeight !== null && self.displayWeight === display); self.displayWeight = display; }); // Clone the table header so it inherits original jQuery properties. Hide // the table to avoid a flash of the header clone upon page load. this.stickyTable = $('<table class="sticky-header"/>') .insertBefore(this.originalTable) .css({ position: 'fixed', top: '0px' }); this.stickyHeader = this.originalHeader.clone(true) .hide() .appendTo(this.stickyTable); this.stickyHeaderCells = this.stickyHeader.find('> tr > th'); this.originalTable.addClass('sticky-table'); $(window) .bind('scroll.drupal-tableheader', $.proxy(this, 'eventhandlerRecalculateStickyHeader')) .bind('resize.drupal-tableheader', { calculateWidth: true }, $.proxy(this, 'eventhandlerRecalculateStickyHeader')) // Make sure the anchor being scrolled into view is not hidden beneath the // sticky table header. Adjust the scrollTop if it does. .bind('drupalDisplaceAnchor.drupal-tableheader', function () { window.scrollBy(0, -self.stickyTable.outerHeight()); }) // Make sure the element being focused is not hidden beneath the sticky // table header. Adjust the scrollTop if it does. .bind('drupalDisplaceFocus.drupal-tableheader', function (event) { if (self.stickyVisible && event.clientY < (self.stickyOffsetTop + self.stickyTable.outerHeight()) && event.$target.closest('sticky-header').length === 0) { window.scrollBy(0, -self.stickyTable.outerHeight()); } }) .triggerHandler('resize.drupal-tableheader'); // We hid the header to avoid it showing up erroneously on page load; // we need to unhide it now so that it will show up when expected. this.stickyHeader.show(); }; /** * Event handler: recalculates position of the sticky table header. * * @param event * Event being triggered. */ Drupal.tableHeader.prototype.eventhandlerRecalculateStickyHeader = function (event) { var self = this; var calculateWidth = event.data && event.data.calculateWidth; // Reset top position of sticky table headers to the current top offset. this.stickyOffsetTop = Drupal.settings.tableHeaderOffset ? eval(Drupal.settings.tableHeaderOffset + '()') : 0; this.stickyTable.css('top', this.stickyOffsetTop + 'px'); // Save positioning data. var viewHeight = document.documentElement.scrollHeight || document.body.scrollHeight; if (calculateWidth || this.viewHeight !== viewHeight) { this.viewHeight = viewHeight; this.vPosition = this.originalTable.offset().top - 4 - this.stickyOffsetTop; this.hPosition = this.originalTable.offset().left; this.vLength = this.originalTable[0].clientHeight - 100; calculateWidth = true; } // Track horizontal positioning relative to the viewport and set visibility. var hScroll = document.documentElement.scrollLeft || document.body.scrollLeft; var vOffset = (document.documentElement.scrollTop || document.body.scrollTop) - this.vPosition; this.stickyVisible = vOffset > 0 && vOffset < this.vLength; this.stickyTable.css({ left: (-hScroll + this.hPosition) + 'px', visibility: this.stickyVisible ? 'visible' : 'hidden' }); // Only perform expensive calculations if the sticky header is actually // visible or when forced. if (this.stickyVisible && (calculateWidth || !this.widthCalculated)) { this.widthCalculated = true; var $that = null; var $stickyCell = null; var display = null; var cellWidth = null; // Resize header and its cell widths. // Only apply width to visible table cells. This prevents the header from // displaying incorrectly when the sticky header is no longer visible. for (var i = 0, il = this.originalHeaderCells.length; i < il; i += 1) { $that = $(this.originalHeaderCells[i]); $stickyCell = this.stickyHeaderCells.eq($that.index()); display = $that.css('display'); if (display !== 'none') { cellWidth = $that.css('width'); // Exception for IE7. if (cellWidth === 'auto') { cellWidth = $that[0].clientWidth + 'px'; } $stickyCell.css({'width': cellWidth, 'display': display}); } else { $stickyCell.css('display', 'none'); } } this.stickyTable.css('width', this.originalTable.outerWidth()); } }; })(jQuery); ; /** * @file * Attaches the behaviors for the Field UI module. */ (function($) { Drupal.behaviors.fieldUIFieldOverview = { attach: function (context, settings) { $('table#field-overview', context).once('field-overview', function () { Drupal.fieldUIFieldOverview.attachUpdateSelects(this, settings); }); } }; Drupal.fieldUIFieldOverview = { /** * Implements dependent select dropdowns on the 'Manage fields' screen. */ attachUpdateSelects: function(table, settings) { var widgetTypes = settings.fieldWidgetTypes; var fields = settings.fields; // Store the default text of widget selects. $('.widget-type-select', table).each(function () { this.initialValue = this.options[0].text; }); // 'Field type' select updates its 'Widget' select. $('.field-type-select', table).each(function () { this.targetSelect = $('.widget-type-select', $(this).closest('tr')); $(this).bind('change keyup', function () { var selectedFieldType = this.options[this.selectedIndex].value; var options = (selectedFieldType in widgetTypes ? widgetTypes[selectedFieldType] : []); this.targetSelect.fieldUIPopulateOptions(options); }); // Trigger change on initial pageload to get the right widget options // when field type comes pre-selected (on failed validation). $(this).trigger('change', false); }); // 'Existing field' select updates its 'Widget' select and 'Label' textfield. $('.field-select', table).each(function () { this.targetSelect = $('.widget-type-select', $(this).closest('tr')); this.targetTextfield = $('.label-textfield', $(this).closest('tr')); this.targetTextfield .data('field_ui_edited', false) .bind('keyup', function (e) { $(this).data('field_ui_edited', $(this).val() != ''); }); $(this).bind('change keyup', function (e, updateText) { var updateText = (typeof updateText == 'undefined' ? true : updateText); var selectedField = this.options[this.selectedIndex].value; var selectedFieldType = (selectedField in fields ? fields[selectedField].type : null); var selectedFieldWidget = (selectedField in fields ? fields[selectedField].widget : null); var options = (selectedFieldType && (selectedFieldType in widgetTypes) ? widgetTypes[selectedFieldType] : []); this.targetSelect.fieldUIPopulateOptions(options, selectedFieldWidget); // Only overwrite the "Label" input if it has not been manually // changed, or if it is empty. if (updateText && !this.targetTextfield.data('field_ui_edited')) { this.targetTextfield.val(selectedField in fields ? fields[selectedField].label : ''); } }); // Trigger change on initial pageload to get the right widget options // and label when field type comes pre-selected (on failed validation). $(this).trigger('change', false); }); } }; /** * Populates options in a select input. */ jQuery.fn.fieldUIPopulateOptions = function (options, selected) { return this.each(function () { var disabled = false; if (options.length == 0) { options = [this.initialValue]; disabled = true; } // If possible, keep the same widget selected when changing field type. // This is based on textual value, since the internal value might be // different (options_buttons vs. node_reference_buttons). var previousSelectedText = this.options[this.selectedIndex].text; var html = ''; jQuery.each(options, function (value, text) { // Figure out which value should be selected. The 'selected' param // takes precedence. var is_selected = ((typeof selected != 'undefined' && value == selected) || (typeof selected == 'undefined' && text == previousSelectedText)); html += '<option value="' + value + '"' + (is_selected ? ' selected="selected"' : '') + '>' + text + '</option>'; }); $(this).html(html).attr('disabled', disabled ? 'disabled' : false); }); }; Drupal.behaviors.fieldUIDisplayOverview = { attach: function (context, settings) { $('table#field-display-overview', context).once('field-display-overview', function() { Drupal.fieldUIOverview.attach(this, settings.fieldUIRowsData, Drupal.fieldUIDisplayOverview); }); } }; Drupal.fieldUIOverview = { /** * Attaches the fieldUIOverview behavior. */ attach: function (table, rowsData, rowHandlers) { var tableDrag = Drupal.tableDrag[table.id]; // Add custom tabledrag callbacks. tableDrag.onDrop = this.onDrop; tableDrag.row.prototype.onSwap = this.onSwap; // Create row handlers. $('tr.draggable', table).each(function () { // Extract server-side data for the row. var row = this; if (row.id in rowsData) { var data = rowsData[row.id]; data.tableDrag = tableDrag; // Create the row handler, make it accessible from the DOM row element. var rowHandler = new rowHandlers[data.rowHandler](row, data); $(row).data('fieldUIRowHandler', rowHandler); } }); }, /** * Event handler to be attached to form inputs triggering a region change. */ onChange: function () { var $trigger = $(this); var row = $trigger.closest('tr').get(0); var rowHandler = $(row).data('fieldUIRowHandler'); var refreshRows = {}; refreshRows[rowHandler.name] = $trigger.get(0); // Handle region change. var region = rowHandler.getRegion(); if (region != rowHandler.region) { // Remove parenting. $('select.field-parent', row).val(''); // Let the row handler deal with the region change. $.extend(refreshRows, rowHandler.regionChange(region)); // Update the row region. rowHandler.region = region; } // Ajax-update the rows. Drupal.fieldUIOverview.AJAXRefreshRows(refreshRows); }, /** * Lets row handlers react when a row is dropped into a new region. */ onDrop: function () { var dragObject = this; var row = dragObject.rowObject.element; var rowHandler = $(row).data('fieldUIRowHandler'); if (typeof rowHandler !== 'undefined') { var regionRow = $(row).prevAll('tr.region-message').get(0); var region = regionRow.className.replace(/([^ ]+[ ]+)*region-([^ ]+)-message([ ]+[^ ]+)*/, '$2'); if (region != rowHandler.region) { // Let the row handler deal with the region change. refreshRows = rowHandler.regionChange(region); // Update the row region. rowHandler.region = region; // Ajax-update the rows. Drupal.fieldUIOverview.AJAXRefreshRows(refreshRows); } } }, /** * Refreshes placeholder rows in empty regions while a row is being dragged. * * Copied from block.js. * * @param table * The table DOM element. * @param rowObject * The tableDrag rowObject for the row being dragged. */ onSwap: function (draggedRow) { var rowObject = this; $('tr.region-message', rowObject.table).each(function () { // If the dragged row is in this region, but above the message row, swap // it down one space. if ($(this).prev('tr').get(0) == rowObject.group[rowObject.group.length - 1]) { // Prevent a recursion problem when using the keyboard to move rows up. if ((rowObject.method != 'keyboard' || rowObject.direction == 'down')) { rowObject.swap('after', this); } } // This region has become empty. if ($(this).next('tr').is(':not(.draggable)') || $(this).next('tr').length == 0) { $(this).removeClass('region-populated').addClass('region-empty'); } // This region has become populated. else if ($(this).is('.region-empty')) { $(this).removeClass('region-empty').addClass('region-populated'); } }); }, /** * Triggers Ajax refresh of selected rows. * * The 'format type' selects can trigger a series of changes in child rows. * The #ajax behavior is therefore not attached directly to the selects, but * triggered manually through a hidden #ajax 'Refresh' button. * * @param rows * A hash object, whose keys are the names of the rows to refresh (they * will receive the 'ajax-new-content' effect on the server side), and * whose values are the DOM element in the row that should get an Ajax * throbber. */ AJAXRefreshRows: function (rows) { // Separate keys and values. var rowNames = []; var ajaxElements = []; $.each(rows, function (rowName, ajaxElement) { rowNames.push(rowName); ajaxElements.push(ajaxElement); }); if (rowNames.length) { // Add a throbber next each of the ajaxElements. var $throbber = $('<div class="ajax-progress ajax-progress-throbber"><div class="throbber">&nbsp;</div></div>'); $(ajaxElements) .addClass('progress-disabled') .after($throbber); // Fire the Ajax update. $('input[name=refresh_rows]').val(rowNames.join(' ')); $('input#edit-refresh').mousedown(); // Disabled elements do not appear in POST ajax data, so we mark the // elements disabled only after firing the request. $(ajaxElements).attr('disabled', true); } } }; /** * Row handlers for the 'Manage display' screen. */ Drupal.fieldUIDisplayOverview = {}; /** * Constructor for a 'field' row handler. * * This handler is used for both fields and 'extra fields' rows. * * @param row * The row DOM element. * @param data * Additional data to be populated in the constructed object. */ Drupal.fieldUIDisplayOverview.field = function (row, data) { this.row = row; this.name = data.name; this.region = data.region; this.tableDrag = data.tableDrag; // Attach change listener to the 'formatter type' select. this.$formatSelect = $('select.field-formatter-type', row); this.$formatSelect.change(Drupal.fieldUIOverview.onChange); return this; }; Drupal.fieldUIDisplayOverview.field.prototype = { /** * Returns the region corresponding to the current form values of the row. */ getRegion: function () { return (this.$formatSelect.val() == 'hidden') ? 'hidden' : 'visible'; }, /** * Reacts to a row being changed regions. * * This function is called when the row is moved to a different region, as a * result of either : * - a drag-and-drop action (the row's form elements then probably need to be * updated accordingly) * - user input in one of the form elements watched by the * Drupal.fieldUIOverview.onChange change listener. * * @param region * The name of the new region for the row. * @return * A hash object indicating which rows should be Ajax-updated as a result * of the change, in the format expected by * Drupal.displayOverview.AJAXRefreshRows(). */ regionChange: function (region) { // When triggered by a row drag, the 'format' select needs to be adjusted // to the new region. var currentValue = this.$formatSelect.val(); switch (region) { case 'visible': if (currentValue == 'hidden') { // Restore the formatter back to the default formatter. Pseudo-fields do // not have default formatters, we just return to 'visible' for those. var value = (typeof this.defaultFormatter !== 'undefined') ? this.defaultFormatter : this.$formatSelect.find('option').val(); } break; default: var value = 'hidden'; break; } if (value != undefined) { this.$formatSelect.val(value); } var refreshRows = {}; refreshRows[this.name] = this.$formatSelect.get(0); return refreshRows; } }; })(jQuery); ; (function ($) { /** * Toggle the visibility of a fieldset using smooth animations. */ Drupal.toggleFieldset = function (fieldset) { var $fieldset = $(fieldset); if ($fieldset.is('.collapsed')) { var $content = $('> .fieldset-wrapper', fieldset).hide(); $fieldset .removeClass('collapsed') .trigger({ type: 'collapsed', value: false }) .find('> legend span.fieldset-legend-prefix').html(Drupal.t('Hide')); $content.slideDown({ duration: 'fast', easing: 'linear', complete: function () { Drupal.collapseScrollIntoView(fieldset); fieldset.animating = false; }, step: function () { // Scroll the fieldset into view. Drupal.collapseScrollIntoView(fieldset); } }); } else { $fieldset.trigger({ type: 'collapsed', value: true }); $('> .fieldset-wrapper', fieldset).slideUp('fast', function () { $fieldset .addClass('collapsed') .find('> legend span.fieldset-legend-prefix').html(Drupal.t('Show')); fieldset.animating = false; }); } }; /** * Scroll a given fieldset into view as much as possible. */ Drupal.collapseScrollIntoView = function (node) { var h = document.documentElement.clientHeight || document.body.clientHeight || 0; var offset = document.documentElement.scrollTop || document.body.scrollTop || 0; var posY = $(node).offset().top; var fudge = 55; if (posY + node.offsetHeight + fudge > h + offset) { if (node.offsetHeight > h) { window.scrollTo(0, posY); } else { window.scrollTo(0, posY + node.offsetHeight - h + fudge); } } }; Drupal.behaviors.collapse = { attach: function (context, settings) { $('fieldset.collapsible', context).once('collapse', function () { var $fieldset = $(this); // Expand fieldset if there are errors inside, or if it contains an // element that is targeted by the URI fragment identifier. var anchor = location.hash && location.hash != '#' ? ', ' + location.hash : ''; if ($fieldset.find('.error' + anchor).length) { $fieldset.removeClass('collapsed'); } var summary = $('<span class="summary"></span>'); $fieldset. bind('summaryUpdated', function () { var text = $.trim($fieldset.drupalGetSummary()); summary.html(text ? ' (' + text + ')' : ''); }) .trigger('summaryUpdated'); // Turn the legend into a clickable link, but retain span.fieldset-legend // for CSS positioning. var $legend = $('> legend .fieldset-legend', this); $('<span class="fieldset-legend-prefix element-invisible"></span>') .append($fieldset.hasClass('collapsed') ? Drupal.t('Show') : Drupal.t('Hide')) .prependTo($legend) .after(' '); // .wrapInner() does not retain bound events. var $link = $('<a class="fieldset-title" href="#"></a>') .prepend($legend.contents()) .appendTo($legend) .click(function () { var fieldset = $fieldset.get(0); // Don't animate multiple times. if (!fieldset.animating) { fieldset.animating = true; Drupal.toggleFieldset(fieldset); } return false; }); $legend.append(summary); }); } }; })(jQuery); ; /** * @file * Javascript functionality for Display Suite's administration UI. */ (function($) { Drupal.DisplaySuite = Drupal.DisplaySuite || {}; Drupal.DisplaySuite.fieldopened = ''; Drupal.DisplaySuite.layout_original = ''; /** * Ctools selection content. */ Drupal.behaviors.CToolsSelection = { attach: function (context) { if ($('#ctools-content-selection').length > 0) { $('#ctools-content-selection .section-link').click(function() { $('#ctools-content-selection .content').hide(); container = $(this).attr('id') + '-container'; $('#' + container).show(); return false; }); } } }; /** * Save the Dynamic field content configuration. */ $.fn.dsCtoolsContentConfiguration = function (configuration) { $(this[0]).val(configuration); } /** * Update the select content text. */ $.fn.dsCtoolsContentUpdate = function () { $(this[0]).html(Drupal.t('Click update to save the configuration')); } /** * Save the page after saving a new field. */ $.fn.dsRefreshDisplayTable = function () { $('#edit-submit').click(); } /** * Row handlers for the 'Manage display' screen. */ Drupal.fieldUIDisplayOverview = Drupal.fieldUIDisplayOverview || {}; Drupal.fieldUIDisplayOverview.ds = function (row, data) { this.row = row; this.name = data.name; this.region = data.region; this.tableDrag = data.tableDrag; // Attach change listener to the 'region' select. this.$regionSelect = $('select.ds-field-region', row); this.$regionSelect.change(Drupal.fieldUIOverview.onChange); // Attach change listener to the 'formatter type' select. this.$formatSelect = $('select.field-formatter-type', row); this.$formatSelect.change(Drupal.fieldUIOverview.onChange); return this; }; Drupal.fieldUIDisplayOverview.ds.prototype = { /** * Returns the region corresponding to the current form values of the row. */ getRegion: function () { return this.$regionSelect.val(); }, /** * Reacts to a row being changed regions. * * This function is called when the row is moved to a different region, as a * result of either : * - a drag-and-drop action * - user input in one of the form elements watched by the * Drupal.fieldUIOverview.onChange change listener. * * @param region * The name of the new region for the row. * @return * A hash object indicating which rows should be AJAX-updated as a result * of the change, in the format expected by * Drupal.displayOverview.AJAXRefreshRows(). */ regionChange: function (region) { // Replace dashes with underscores. region = region.replace(/-/g, '_'); // Set the region of the select list. this.$regionSelect.val(region); // Prepare rows to be refreshed in the form. var refreshRows = {}; refreshRows[this.name] = this.$regionSelect.get(0); // If a row is handled by field_group module, loop through the children. if ($(this.row).hasClass('field-group') && $.isFunction(Drupal.fieldUIDisplayOverview.group.prototype.regionChangeFields)) { Drupal.fieldUIDisplayOverview.group.prototype.regionChangeFields(region, this, refreshRows); } return refreshRows; } }; })(jQuery); ; (function ($) { /** * Retrieves the summary for the first element. */ $.fn.drupalGetSummary = function () { var callback = this.data('summaryCallback'); return (this[0] && callback) ? $.trim(callback(this[0])) : ''; }; /** * Sets the summary for all matched elements. * * @param callback * Either a function that will be called each time the summary is * retrieved or a string (which is returned each time). */ $.fn.drupalSetSummary = function (callback) { var self = this; // To facilitate things, the callback should always be a function. If it's // not, we wrap it into an anonymous function which just returns the value. if (typeof callback != 'function') { var val = callback; callback = function () { return val; }; } return this .data('summaryCallback', callback) // To prevent duplicate events, the handlers are first removed and then // (re-)added. .unbind('formUpdated.summary') .bind('formUpdated.summary', function () { self.trigger('summaryUpdated'); }) // The actual summaryUpdated handler doesn't fire when the callback is // changed, so we have to do this manually. .trigger('summaryUpdated'); }; /** * Sends a 'formUpdated' event each time a form element is modified. */ Drupal.behaviors.formUpdated = { attach: function (context) { // These events are namespaced so that we can remove them later. var events = 'change.formUpdated click.formUpdated blur.formUpdated keyup.formUpdated'; $(context) // Since context could be an input element itself, it's added back to // the jQuery object and filtered again. .find(':input').andSelf().filter(':input') // To prevent duplicate events, the handlers are first removed and then // (re-)added. .unbind(events).bind(events, function () { $(this).trigger('formUpdated'); }); } }; /** * Prepopulate form fields with information from the visitor cookie. */ Drupal.behaviors.fillUserInfoFromCookie = { attach: function (context, settings) { $('form.user-info-from-cookie').once('user-info-from-cookie', function () { var formContext = this; $.each(['name', 'mail', 'homepage'], function () { var $element = $('[name=' + this + ']', formContext); var cookie = $.cookie('Drupal.visitor.' + this); if ($element.length && cookie) { $element.val(cookie); } }); }); } }; })(jQuery); ; (function($) { Drupal.behaviors.fieldUIFieldsOverview = { attach: function (context, settings) { $('table#field-overview', context).once('field-field-overview', function() { Drupal.fieldUIOverview.attach(this, settings.fieldUIRowsData, Drupal.fieldUIFieldOverview); }); } }; /** * Row handlers for the 'Manage fields' screen. */ Drupal.fieldUIFieldOverview = Drupal.fieldUIFieldOverview || {}; Drupal.fieldUIFieldOverview.group = function(row, data) { this.row = row; this.name = data.name; this.region = data.region; this.tableDrag = data.tableDrag; // Attach change listener to the 'group format' select. this.$formatSelect = $('select.field-group-type', row); this.$formatSelect.change(Drupal.fieldUIOverview.onChange); return this; }; Drupal.fieldUIFieldOverview.group.prototype = { getRegion: function () { return 'main'; }, regionChange: function (region, recurse) { return {}; }, regionChangeFields: function (region, element, refreshRows) { // Create a new tabledrag rowObject, that will compute the group's child // rows for us. var tableDrag = element.tableDrag; rowObject = new tableDrag.row(element.row, 'mouse', true); // Skip the main row, we handled it above. rowObject.group.shift(); // Let child rows handlers deal with the region change - without recursing // on nested group rows, we are handling them all here. $.each(rowObject.group, function() { var childRow = this; var childRowHandler = $(childRow).data('fieldUIRowHandler'); $.extend(refreshRows, childRowHandler.regionChange(region, false)); }); } }; /** * Row handlers for the 'Manage display' screen. */ Drupal.fieldUIDisplayOverview = Drupal.fieldUIDisplayOverview || {}; Drupal.fieldUIDisplayOverview.group = function(row, data) { this.row = row; this.name = data.name; this.region = data.region; this.tableDrag = data.tableDrag; // Attach change listener to the 'group format' select. this.$formatSelect = $('select.field-group-type', row); this.$formatSelect.change(Drupal.fieldUIOverview.onChange); return this; }; Drupal.fieldUIDisplayOverview.group.prototype = { getRegion: function () { return (this.$formatSelect.val() == 'hidden') ? 'hidden' : 'visible'; }, regionChange: function (region, recurse) { // Default recurse to true. recurse = (recurse == undefined) || recurse; // When triggered by a row drag, the 'format' select needs to be adjusted to // the new region. var currentValue = this.$formatSelect.val(); switch (region) { case 'visible': if (currentValue == 'hidden') { // Restore the group format back to 'fieldset'. var value = 'fieldset'; } break; default: var value = 'hidden'; break; } if (value != undefined) { this.$formatSelect.val(value); } var refreshRows = {}; refreshRows[this.name] = this.$formatSelect.get(0); if (recurse) { this.regionChangeFields(region, this, refreshRows); } return refreshRows; }, regionChangeFields: function (region, element, refreshRows) { // Create a new tabledrag rowObject, that will compute the group's child // rows for us. var tableDrag = element.tableDrag; rowObject = new tableDrag.row(element.row, 'mouse', true); // Skip the main row, we handled it above. rowObject.group.shift(); // Let child rows handlers deal with the region change - without recursing // on nested group rows, we are handling them all here. $.each(rowObject.group, function() { var childRow = this; var childRowHandler = $(childRow).data('fieldUIRowHandler'); $.extend(refreshRows, childRowHandler.regionChange(region, false)); }); } }; })(jQuery);; (function ($) { Drupal.toolbar = Drupal.toolbar || {}; /** * Attach toggling behavior and notify the overlay of the toolbar. */ Drupal.behaviors.toolbar = { attach: function(context) { // Set the initial state of the toolbar. $('#toolbar', context).once('toolbar', Drupal.toolbar.init); // Toggling toolbar drawer. $('#toolbar a.toggle', context).once('toolbar-toggle').click(function(e) { Drupal.toolbar.toggle(); // Allow resize event handlers to recalculate sizes/positions. $(window).triggerHandler('resize'); return false; }); } }; /** * Retrieve last saved cookie settings and set up the initial toolbar state. */ Drupal.toolbar.init = function() { // Retrieve the collapsed status from a stored cookie. var collapsed = $.cookie('Drupal.toolbar.collapsed'); // Expand or collapse the toolbar based on the cookie value. if (collapsed == 1) { Drupal.toolbar.collapse(); } else { Drupal.toolbar.expand(); } }; /** * Collapse the toolbar. */ Drupal.toolbar.collapse = function() { var toggle_text = Drupal.t('Show shortcuts'); $('#toolbar div.toolbar-drawer').addClass('collapsed'); $('#toolbar a.toggle') .removeClass('toggle-active') .attr('title', toggle_text) .html(toggle_text); $('body').removeClass('toolbar-drawer').css('paddingTop', Drupal.toolbar.height()); $.cookie( 'Drupal.toolbar.collapsed', 1, { path: Drupal.settings.basePath, // The cookie should "never" expire. expires: 36500 } ); }; /** * Expand the toolbar. */ Drupal.toolbar.expand = function() { var toggle_text = Drupal.t('Hide shortcuts'); $('#toolbar div.toolbar-drawer').removeClass('collapsed'); $('#toolbar a.toggle') .addClass('toggle-active') .attr('title', toggle_text) .html(toggle_text); $('body').addClass('toolbar-drawer').css('paddingTop', Drupal.toolbar.height()); $.cookie( 'Drupal.toolbar.collapsed', 0, { path: Drupal.settings.basePath, // The cookie should "never" expire. expires: 36500 } ); }; /** * Toggle the toolbar. */ Drupal.toolbar.toggle = function() { if ($('#toolbar div.toolbar-drawer').hasClass('collapsed')) { Drupal.toolbar.expand(); } else { Drupal.toolbar.collapse(); } }; Drupal.toolbar.height = function() { var $toolbar = $('#toolbar'); var height = $toolbar.outerHeight(); // In modern browsers (including IE9), when box-shadow is defined, use the // normal height. var cssBoxShadowValue = $toolbar.css('box-shadow'); var boxShadow = (typeof cssBoxShadowValue !== 'undefined' && cssBoxShadowValue !== 'none'); // In IE8 and below, we use the shadow filter to apply box-shadow styles to // the toolbar. It adds some extra height that we need to remove. if (!boxShadow && /DXImageTransform\.Microsoft\.Shadow/.test($toolbar.css('filter'))) { height -= $toolbar[0].filters.item("DXImageTransform.Microsoft.Shadow").strength; } return height; }; })(jQuery); ;
SquareHook/norbdrupal
sites/default/files/js/js_WoRZdLyjwpNs4Rw6LqZ-KFk4LVagPZqxSkTWb_d5vU4.js
JavaScript
gpl-2.0
83,460
/** * Arstider Utilities and namespace wrapper * * @version 1.1 * @author frederic charette <fredericcharette@gmail.com> */ /** * Engine Namespace * @namespace Arstider */ Arstider = {}; /** * Gets a number timestamp, usefull for id-ing or cache busting * @memberof Arstider * @type {function} * @return {number} the timestamp */ Arstider.timestamp = function(){ return Date.now(); }; /** * Global access to check if page is visible or not * @memberof Arstider * @type {boolean} */ Arstider.pageHidden = false; Arstider.tempBufferLabel = "_temp_"; /** * Get Node from Arstider Element * @memberof Arstider * @type {function} */ Arstider.getNode = function(obj, maxDepth){ maxDepth = Arstider.checkIn(maxDepth, 5); var orig = obj, depth = 0 ; if(orig){ //add protected flag to buffer tags of background/watermark if(orig.data){ while(orig.data.nodeName == undefined){ depth++; if(depth > maxDepth) break; if(orig.data.data){ orig = orig.data; } else break; } } } return orig; }; Arstider.error = function(type, props){ var i, err = new type(props.message); for(i in props){ if(i != "message") err[i] = props[i]; } return err; }; Arstider.min = function(){ for(var i =1, min=0, len = arguments.length; i<len; i++){ if(arguments[i]<arguments[min])min = i; } return arguments[min]; }; Arstider.max = function(){ for(var i =1, max=0, len = arguments.length; i<len; i++){ if(arguments[max]<arguments[i])max = i; } return arguments[max]; }; Arstider.floor = function(num){ return num >> 0; }; Arstider.ceil = function(num){ var c = num >> 0; return c == num ? c : c + 1; }; Arstider.log = function(data, level){ level = level || 1; var message = "", asset = null ; if(typeof data === 'string') message=data; else{ if(data.message) message=data.message; if(data.asset) asset=data.asset; } if(Arstider.verbose >= level){ //Error output, for stack info if(asset!=null){ console.log('%c', 'padding:'+(asset.height || null)+'px '+(asset.width || null)+'px;line-height:'+(asset.height || null)+'px;background:url('+(asset.src || null)+')'); } console.error('%c'+message, 'color:purple'); } }; Arstider.powerOf2 = function(num){ return (num > 0 && (num & (num - 1)) === 0); }; Arstider.nextPowerOf2 = function(number){ if (number > 0 && (number & (number - 1)) === 0) // see: http://goo.gl/D9kPj return number; else{ var result = 1; while (result < number) result <<= 1; return result; } }; /** * Generates a Unique UID string * @memberof Arstider * @type {function} * @return {String} the resulting unique ID */ Arstider.guid = function() { function s4(){ return Arstider.floor((1 + Math.random()) * 0x10000).toString(16).substring(1); } return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4(); }; //IE9 iframe fallback if(Object.create == undefined){ Object.create = function(parent){ function F () {} // An empty constructor. F.prototype = parent; // Set its prototype to the parent object. return new F; // Instantiate it to get an empty object that inherits `parent`. }; } /** * Disables the console element * @memberof Arstider * @type {function} */ Arstider.disableConsole = function(){ window.console = { log:Arstider.emptyFunction, warn:Arstider.emptyFunction //error:Arstider.emptyFunction }; }; /** * Indicates if the engine should remain with canvas2D context or attempt WebGl rendering * @memberof Arstider * @type {boolean} */ Arstider.force2d = true; /** * Re-usable empty object * @memberof Arstider * @const * @type {Object} */ Arstider.emptyObject = {}; /** * Re-usable empty function * @memberof Arstider * @const * @type {function()} */ Arstider.emptyFunction = function(){}; /** * Re-usable empty string * @memberof Arstider * @const * @type {string} */ Arstider.emptyString = ""; /** * Skip update logic flag * memberof Arstider * @type {boolean} */ Arstider.skipUpdate = false; /** * Cancel bubbleFlag * @type {Object} */ Arstider.__cancelBubble = {}; /** * Cancels input Bubble for the selected input * @memberof Arstider * @type {function} */ Arstider.cancelBubble = function(id){ id = Arstider.checkIn(id, 0); Arstider.__cancelBubble[id] = true; }; /** * Re-usable empty images url * @memberof Arstider * @const * @type {string} */ Arstider.emptyImgSrc = "data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs="; /** * Max FPS value * @memberof Arstider * @type {number} */ Arstider.FPS = 60; /** * Saved screen states * @memberof Arstider * @const * @type {Object} */ Arstider.savedStates = {}; Arstider.queryStringToObject = function(str) { return (str || document.location.search).replace(/(^\?)/,'').split("&").map(function(n){return n = n.split("="),this[n[0]] = n[1],this;}.bind({}))[0]; }; /** * Disposes of a saved screen state * @memberof Arstider * @type {function} */ Arstider.disposeSavedState = function(name){ if(name in Arstider.savedStates){ if(Arstider.savedStates[name]._unload) Arstider.savedStates[name]._unload(); delete Arstider.savedStates[name]; } }; /** * Degrees-to-radians constant * @memberof Arstider * @const * @type {number} */ Arstider.degToRad = Math.PI/180; /** * Radians to degrees constant * @memberof Arstider * @const * @type {number} */ Arstider.radToDeg = 180/Math.PI; /** * Default composition mode constant * @memberof Arstider * @const * @type {string} */ Arstider.defaultComposition = "source-over"; /** * Default color constant * @memberof Arstider * @const * @type {string} */ Arstider.defaultColor = "transparent"; /** * Utility function to apply a method through a desired scope * @memberof Arstider * @const * @param {function(this:selfObj)} fn Method to call * @param {*} selfObj The scope * @param {Array|null} var_args Arguments * @return {function()} The function with the proper scope */ Arstider.delegate = function(fn, selfObj, var_args){ return (fn.call.apply(fn.bind, arguments)); }; /** * Quick if-exist method * @memberof Arstider * @const * @param {*} val The value to check against undefined * @param {*} def The default value to provide is val is undefined * @return {*} The final value */ Arstider.checkIn = function(val, def){ if(val === undefined) return def; return val; }; /** * Test if a value exist * @memberof Arstider * @const * @param {*} val The value to check against undefined * @return {*} A boolean */ Arstider.isDefine = function(val){ return typeof val != 'undefined'; }; /** * Multiple check-if-exist method in order of fallback * @memberof Arstider * @const * @param {Array} val The values to check against undefined, one after another * @param {*} def The default value to provide if all val are undefined * @return {*} The final value */ Arstider.firstOf = function(val, def){ if(!val.length) return def; for(var i = 0; i<val.length; i++){ if(val[i] != undefined) return val[i]; } return def; }; /** * Indicates whether or not to output full verbose warnings * * 0 = nothing, * 1 = important warnings * 2 = notices * 3+ = EVERYTHING! * @memberof Arstider * @type {number} */ Arstider.verbose = 0; /** * Calculate the distance between 2 coordinates * @memberof Arstider * @type {function} * @param {number} x1 The x coordinate of the first point * @param {number} y1 The y coordinate of the first point * @param {number} x2 The x coordinate of the second point * @param {number} y2 The y coordinate of the second point * @return {number} the distance between the 2 points */ Arstider.distance = function(x1, y1, x2, y2){ return Math.sqrt(Math.pow((x2 - x1),2) + Math.pow((y2 - y1),2)); }; /** * Calculate the distance between 2 coordinates in 3d space * @memberof Arstider * @type {function} * @param {number} x1 The x coordinate of the first point * @param {number} y1 The y coordinate of the first point * @param {number} z1 The z coordinate of the first point * @param {number} x2 The x coordinate of the second point * @param {number} y2 The y coordinate of the second point * @param {number} z2 The z coordinate of the second point * @return {number} the distance between the 2 points */ Arstider.distance3 = function(x1, y1, z1, x2, y2, z2){ return Math.sqrt(Math.pow((x2 - x1),2) + Math.pow((y2 - y1),2) + Math.pow((z2 - z1),2)); }; /** * Calculate direction in degrees with 2 points * @memberof Arstider * @type {function} * @param {number} x1 The x coordinate of the first point * @param {number} y1 The y coordinate of the first point * @param {number} x2 The x coordinate of the second point * @param {number} y2 The y coordinate of the second point * @return {number} the distance between the 2 points */ Arstider.direction = function(x1, y1, x2, y2){ var relX = x2 - x1; var relY = y2 - y1; var theta = Math.atan2(-relY, relX); return theta * Arstider.radToDeg; }; /** * Removes duplicate entries from an array * @memberof Arstider * @const * @param {Array} arr The array to shuffle * @return {Array} The shuffled array */ Arstider.trimDuplicates = function(arr){ var o = {}, i = 0, l = arr.length, r = [] ; for (; i < l; i++){ o[arr[i]] = arr[i]; } for (i in o) { if(o.hasOwnProperty(i)) r.push(o[i]); } arr = r; return arr; }; /** * Attempts to reload the page * @memberof Arstider * @const */ Arstider.reload = function() { if("reload" in window.location) window.location.reload(); else if("history" in window && "go" in window.history) window.history.go(0); else window.location.href = window.location.href; }; /** * Detects if an element is a plain object * @memberof Arstider * @const * @param {*} obj The object to analyse * @return {boolean} */ Arstider.isObject = function(obj){ if(!obj || !(typeof obj === "object") || obj.nodeType || Arstider.isWindow(obj)) return false; if (obj.constructor && !Object.prototype.hasOwnProperty.call(obj, "constructor") && !Object.prototype.hasOwnProperty.call(obj.constructor.prototype, "isPrototypeOf")) return false; var key; for (key in obj) { if(obj.hasOwnProperty(key)) continue; } return (key == undefined) || Object.prototype.hasOwnProperty.call(obj, key); }; /** * Detects if an element is the window element * @memberof Arstider * @const * @param {*} obj The object to analyse * @return {boolean} */ Arstider.isWindow = function(obj){ return obj && (typeof obj === "object") && "setInterval" in obj; }; /** * Detects if an object is a function * @memberof Arstider * @const * @param {*} obj The object or function to analyse * @return {boolean} */ Arstider.isFunction = function(functionToCheck) { var getType = {}; return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]'; }; /** * Find the length of an Object or array * @memberof Arstider * @const * @param {*} obj The object to find the length of * @return {number} The length */ Arstider.lengthOf = function(obj){ if(typeof obj === "array") return obj.length; else if(Arstider.isObject(obj)){ var l = 0, i ; for (i in obj) { if (obj.hasOwnProperty(i)) l ++; } return l; } return 0; }; /** * Compares two elements * @memberof Arstider * @const * @param {*} a The first element * @param {*} b The second element * @return {boolean} */ Arstider.compare = function(a, b){ var i; if(typeof a !== typeof b) return false; switch (typeof a){ case "object": if(Arstider.lengthOf(a) !== Arstider.lengthOf(b)) return false; for(i in a) { if (a.hasOwnProperty(i)){ if(!b.hasOwnProperty(i) || !Arstider.compare(a[i], b[i])) return false; } } for(i in b){ if(b.hasOwnProperty(i) && !a.hasOwnProperty(i)) return false; } break; case "array": i = a.length; if(i !== b.length) return false; i--; while(i >= 0){ if(!Arstider.compare(a[i], b[i])) return false; i--; } break; default: return a === b; } return true; }; /** * Fisher-Yates array shuffling method * @memberof Arstider * @const * @param {Array} arr The array to shuffle * @return {Array} The shuffled array */ Arstider.randomSort = function(arr){ var i = arr.length, j, temp; if ( i === 0 ) return false; while ( --i ) { j = Arstider.floor( Math.random() * ( i + 1 ) ); temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } return arr; }; /** * Quick number rounding method (see jsperf) * @memberof Arstider * @const * @param {number} i The number to round * @return {number} The rounded number */ Arstider.chop = function(i){ return (0.5 + i) | 0; }; /** * Generic, simple mixin function. Replaces undefined elements in obj A with properties of obj B * @memberof Arstider * @const * @param {Object} objA The object that will receive the new properties * @param {Object} objB The object to transfer the properties from * @param {boolean} force Whether or not to override objA values with objB values in case they were already defined * @param {boolean} includeMethods Whether or not to include functions, defaults to false * @return {Object} Returns the updated objA */ Arstider.mixin = function(objA, objB, force, includeMethods, prefix){ for(var i in objB){ if(objA[i] == undefined || force){ if(objB[i] instanceof Function || typeof objB[i] === 'function'){ if(includeMethods){ objA[(prefix || "") + i] = objB[i]; } } else objA[(prefix || "") + i] = objB[i]; } } return objA; }; /** * Utility function to copy the simple direct properties of an object * @memberof Arstider * @const * @param {Object} obj The object to copy * @param {boolean} includeMethods Whether or not to include functions, defaults to false * @return {Object} The newly created object */ Arstider.clone = function(obj, includeMethods, prefix){ return Arstider.mixin({}, obj, true, includeMethods, prefix); }; /** * Utility function to clone an object recursively * @memberof Arstider * @const * @param {Object} obj The object to copy */ Arstider.deepClone = function(obj) { // Handle the 3 simple types, and null or undefined if (null == obj || "object" != typeof obj) return obj; // Handle Date if (obj instanceof Date) { var copy = new Date(); copy.setTime(obj.getTime()); return copy; } // Handle Array if (obj instanceof Array) { var copy = []; for (var i = 0, len = obj.length; i < len; i++) { copy[i] = Arstider.deepClone(obj[i]); } return copy; } // Handle Object if (obj instanceof Object) { var copy = {}; for (var attr in obj) { if (obj.hasOwnProperty(attr)) copy[attr] = Arstider.deepClone(obj[attr]); } return copy; } if(Arstider.verbose > 0){ console.warn("Arstider.deepClone: Object type unsupported ",obj); } }; /** * Utility function to merge two objects recursively * @memberof Arstider * @const * @param {Object} src The object to copy from * @param {Object} target The object to copy to * @param {Boolean} clone Clones the source object first when true */ Arstider.deepMerge = function(src, target, clone) { if(clone) src = Arstider.deepClone(src); var isArray = Array.isArray(src); if (isArray) { target = target || []; src.forEach(function(val, i) { var val = src[i]; if (typeof src[i] === 'undefined') { target[i] = val; } else if (typeof val === 'object') { target[i] = Arstider.deepMerge(val, target[i]); } else if (Array.isArray(val)){ target[i] = Arstider.deepMerge(val, target[i]); } else { target[i] = val; } }); } else { target = target || {}; Object.keys(src).forEach(function (key) { var val = src[key]; if(Array.isArray(val)){ target[key] = Arstider.deepMerge(val, target[key]); } else if(typeof val === 'object'){ target[key] = target[key] || {}; if (!src[key]) { target[key] = val; } else { target[key] = Arstider.deepMerge(val, target[key]); } } else{ target[key] = val; } }); } return target; }; /** * Supers the values of a module to it's parent module * @memberof Arstider * @param {*} child The child that will super to a defined inherited parent - requires the constructor to have been Inherited at least once */ Arstider.Super = function(child, parent){ if(arguments.length > 2) parent.apply(child, Array.prototype.slice.call(arguments,2)); else parent.call(child); }; /** * Parse a string for safe server storage * http://ajaxref.com/ * @memberof Arstider * @type {function} * @param {string} val The string to make uri-safe * @return {string} The uri-safe string */ Arstider.URIEncode = function(val){ var encodedVal; if(!encodeURIComponent){ encodedVal = escape(val); encodedVal = encodedVal.replace(/@/g, '%40'); encodedVal = encodedVal.replace(/\//g, '%2F'); encodedVal = encodedVal.replace(/\+/g, '%2B'); }else{ encodedVal = encodeURIComponent(val); encodedVal = encodedVal.replace(/~/g, '%7E'); encodedVal = encodedVal.replace(/!/g, '%21'); encodedVal = encodedVal.replace(/\(/g, '%28'); encodedVal = encodedVal.replace(/\)/g, '%29'); encodedVal = encodedVal.replace(/'/g, '%27'); } /* clean up the spaces and return */ return encodedVal.replace(/\%20/g,'+'); }; /** * Creates Inheritance for a module * @memberof Arstider * @param {*} child The child module * @param {*} parent The module that will gives it's properties to the child */ Arstider.Inherit = function(child, parent){ if(parent instanceof Function || typeof parent === 'function'){ child.prototype = Object.create(parent.prototype); child.prototype.constructor = child; } else console.warn("Arstider.Inherit: Could not make ",child, " inherit", parent); }; /** * Fixed drawing rate, when vendor-prefixed is unavailable or because of platform restrictions * @memberof Arstider * @const * @param {function()} callback The called method for rendering */ Arstider.fixedAnimationFrame = function(callback, dt){ /*var targetFPS = Arstider.chop(); var nextFrame = Math.max(10, targetFPS - (dt - targetFPS)); console.log(nextFrame);*/ var targetFPS = 1000/Arstider.FPS; var allowedMS = 3; if(dt > targetFPS+allowedMS){ targetFPS = targetFPS - ((dt-targetFPS)*0.5); } Arstider.__animTimer = window.setTimeout(callback, targetFPS); }; /** * Cancels the fixed drawing rate, when vendor-prefixed is unavailable or because of platform restrictions * @memberof Arstider * @const * @param {*} ref The requestAnimationFrame method */ Arstider.fixedCancelAnimationFrame = function(ref){ if(Arstider.__animTimer != undefined) window.clearTimeout(Arstider.__animTimer); }; /** * Global blobURL cache * @memberof Arstider * @private * @type {Object} */ Arstider.blobCache = {empty:{url:Arstider.emptyImgSrc, size:0}}; /** * Sets the FPS of the game (max 60) * @memberof Arstider * @type {function} */ Arstider.setFPS = function(val){ val = val || 60; if(val == "auto" || val >= 60){ Arstider.FPS = 60; /** * Parses vendor-prefixed values for requesting an animation frame * @memberof Arstider * @const */ Arstider.requestAnimFrame = (function(){ return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || Arstider.fixedAnimationFrame; })(); /** * Parses vendor-prefixed values for canceling request animation frame * @memberof Arstider * @const */ Arstider.cancelAnimFrame = (function(){ return window.cancelAnimationFrame || window.webkitCancelAnimationFrame || window.mozCancelAnimationFrame || window.oCancelAnimationFrame || window.msCancelAnimationFrame || Arstider.fixedCancelAnimationFrame; })(); } else{ Arstider.FPS = val; Arstider.requestAnimFrame = Arstider.fixedAnimationFrame; Arstider.cancelAnimFrame = Arstider.fixedCancelAnimationFrame; } }; /** * Default rendering style * @memberof Arstider * @type {string} */ Arstider.defaultRenderStyle = "auto"; /** * Collection of the intantiated buffers * @memberof Arstider * @type {Object} */ Arstider.bufferPool = {}; /** * Serializes Objects for XHR data * @memberof Arstider * @type {function} * @param {Object} obj The object to serialize * @return {string} The serialized Object */ Arstider.serialize = function(obj, prefix) { if(typeof obj === "string" || obj == null) return obj; var str = []; for(var p in obj){ var k = prefix ? prefix + "[" + p + "]" : p, v = obj[p]; str.push(typeof v == "object" ? Arstider.serialize(v, k) : encodeURIComponent(k) + "=" + encodeURIComponent(v)); } return str.join("&"); }; /** * Counts the number of buffers in the system * @memberof Arstider * @type {function} * @return {number} The number of buffers */ Arstider.countBuffers = function(){ var i, total = 0 ; for(i in Arstider.bufferPool){ total ++; } return total; }; /** * Returns the total size of assets in memory * @memberof Arstider * @type {function} * @return {number} memory (in MB) */ Arstider.getMemory = function(){ var i, total = 0 ; for(i in Arstider.blobCache){ total += ((Arstider.blobCache[i].size || 0) >> 10); } for(i in Arstider.bufferPool){ total += ((Arstider.bufferPool[i].getMemory()) >> 20); } return (total/1024).toFixed(2); };
fed135/Arstider
src/sdk/core/Utils.js
JavaScript
gpl-2.0
22,016
showWord(["v. ","amelyore, avanse, macha annavan. 2. Lè yon malad pwogrese, li ap refè. Lè yon maladi pwogrese, malad la vin pi mal, li anpire." ])
georgejhunt/HaitiDictionary.activity
data/words/pwogrese.js
JavaScript
gpl-2.0
150
/* * * This file is part of the OpenLink Software Virtuoso Open-Source (VOS) * project. * * Copyright (C) 1998-2012 OpenLink Software * * This project is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; only version 2 of the License, dated June 1991. * * 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 * General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * */ TBL.createCell40 = function (td, prefix, fldName, No, fldOptions) { var fld = new OAT.Combolist([], fldOptions.value, {name: fldName}); fld.input.name = fldName; fld.input.id = fldName; fld.input.style.width = "85%"; fld.addOption('xml-sql'); fld.addOption('xml-sql-root'); fld.addOption('xml-sql-dtd'); fld.addOption('xml-sql-schema'); fld.addOption('xml-sql-description'); fld.addOption('xml-sql-encoding'); fld.addOption('xml-stylesheet'); fld.addOption('xml-template'); fld.addOption('xper'); td.appendChild(fld.div); return fld; } TBL.createCell41 = function (td, prefix, fldName, No, fldOptions) { var fld = OAT.Dom.create("select"); fld.name = fldName; fld.id = fldName; TBL.selectOption(fld, fldOptions.value, "Set", "U"); TBL.selectOption(fld, fldOptions.value, "Remove", "R"); td.appendChild(fld); return fld; } TBL.createCell42 = function (td, prefix, fldName, No, fldOptions, disabled) { function cb(td, prefix, fldName, No, fldOptions, disabled, ndx) { var fld = OAT.Dom.create("input"); fld.type = 'checkbox'; fld.id = fldName; fld.name = fld.id; fld.value = 1; if (fldOptions.value && fldOptions.value[ndx]) fld.checked = true; if (fldOptions.onclick) fld.onclick = fldOptions.onclick; if (disabled) fld.disabled = disabled; td.appendChild(fld); } var suffix = ''; if (fldOptions.suffix) suffix = fldOptions.suffix; cb(td, prefix, fldName+'_r'+suffix, No, fldOptions, disabled, 0); cb(td, prefix, fldName+'_w'+suffix, No, fldOptions, disabled, 1); cb(td, prefix, fldName+'_x'+suffix, No, fldOptions, disabled, 2); } TBL.createCell43 = function (td, prefix, fldName, No, fldOptions) { var fld = TBL.createCellSelect(fldName, fldOptions); TBL.selectOption(fld, fldOptions.value, 'This object only', 0); if (fldOptions.objectType == 'C') { TBL.selectOption(fld, fldOptions.value, 'This object, subfolders and files', 1); TBL.selectOption(fld, fldOptions.value, 'Subfolders and files', 2); } td.appendChild(fld); return fld; } TBL.viewCell42 = function (td, prefix, fldName, No, fldOptions) { TBL.createCell42(td, prefix, fldName, No, fldOptions, true); } TBL.clickCell42 = function (fld) { var fldName = fld.name; if (fldName.indexOf('_deny') != -1) { fldName = fldName.replace('_deny', '_grant'); fldName = fldName.replace('fld_4', 'fld_3'); } else if (fldName.indexOf('_grant') != -1) { fldName = fldName.replace('_grant', '_deny'); fldName = fldName.replace('fld_3', 'fld_4'); } $(fldName).checked = false; } var Cartridges; TBL.createCell45 = function (td, prefix, fldName, No, fldOptions) { var fld = TBL.createCellSelect(fldName, fldOptions); if (Cartridges) { TBL.createCell45Options(fld, fldOptions.value); } else { var x = function (data) { try { Cartridges = OAT.JSON.parse(data); TBL.createCell45Options(fld, fldOptions.value); } catch (e) {Cartridges = null;} } OAT.AJAX.GET('ajax.vsp?a=cartridges', '', x); } td.appendChild(fld); return fld; } TBL.createCell45Options = function (fld, fldValue) { for (var i = 0; i < Cartridges.length; i++) TBL.selectOption(fld, fldValue, Cartridges[i][1], Cartridges[i][0]); } var MetaCartridges; TBL.createCell46 = function (td, prefix, fldName, No, fldOptions) { var fld = TBL.createCellSelect(fldName, fldOptions); if (MetaCartridges) { TBL.createCell46Options(fld, fldOptions.value); } else { var x = function (data) { try { MetaCartridges = OAT.JSON.parse(data); TBL.createCell46Options(fld, fldOptions.value); } catch (e) {MetaCartridges = null;} } OAT.AJAX.GET('ajax.vsp?a=metaCartridges', '', x); } td.appendChild(fld); return fld; } TBL.createCell46Options = function (fld, fldValue) { for (var i = 0; i < MetaCartridges.length; i++) TBL.selectOption(fld, fldValue, MetaCartridges[i][1], MetaCartridges[i][0]); }
trueg/virtuoso-opensource
appsrc/ODS-Briefcase/www/js/tbl.js
JavaScript
gpl-2.0
4,816
(function($) { var EA = {}; Backbone.ajax = function() { var args = Array.prototype.slice.call(arguments, 0)[0]; var change = {}; if(args.type === 'PUT' || args.type === 'DELETE') { change.type = 'POST'; change.url = args.url + '&_method=' + args.type; } var newArgs = _.extend(args, change); return Backbone.$.ajax.apply(Backbone.$, [newArgs]); }; /** * Single location */ EA.Location = Backbone.Model.extend({ defaults : { name:"", address: "", location: "", cord: null }, url: function() { return ajaxurl+'?action=ea_location&id=' + encodeURIComponent(this.id) }, toJSON : function() { var attrs = _.clone( this.attributes ); return attrs; } }); /** * Service model */ EA.Service = Backbone.Model.extend({ defaults : { name:"", duration: 60, price: 10 }, url : function() { return ajaxurl+'?action=ea_service&id=' + this.id; }, toJSON : function() { var attrs = _.clone( this.attributes ); return attrs; } }); /** * Service model */ EA.Worker = Backbone.Model.extend({ defaults : { name:"", description : "", email: "", phone: "" }, url : function() { return ajaxurl+'?action=ea_worker&id=' + this.id; }, toJSON : function() { var attrs = _.clone( this.attributes ); return attrs; } }); /** * Single connection */ EA.Connection = Backbone.Model.extend({ defaults : { group_id : null, location : null, service : null, worker : null, day_of_week : [], time_from : null, time_to : null, day_from : '2015-01-01', day_to : '2020-01-01', is_working : 0 }, url: function() { return ajaxurl+'?action=ea_connection&id=' + encodeURIComponent(this.id) }, toJSON: function() { var attrs = _.clone( this.attributes ); //console.log(attrs); return attrs; }, parse: function(data, options) { if(typeof data.day_of_week !== "undefined" && data.day_of_week != null) { data.day_of_week = data.day_of_week.split(','); } else { // console.log(this.get('day_of_week').split(',')); this.set('day_of_week', this.get('day_of_week')); } if(typeof data.time_from !== "undefined" && typeof data.time_to !== "undefined") { if(data.time_from.length === 8) { data.time_from = data.time_from.substring(0, 5); } if(data.time_to.length === 8) { data.time_to = data.time_to.substring(0, 5); } } return data; }, save: function(attrs, options) { options || (options = {}); attrs || (attrs = _.clone(this.attributes)); attrs.day_of_week = attrs.day_of_week.join(','); return Backbone.Model.prototype.save.call(this, attrs, options); } }); /** * Service model */ EA.Setting = Backbone.Model.extend({ defaults : { ea_key:"", ea_value : "", type: "" }, url : function() { return ajaxurl+'?action=ea_setting&id=' + this.id; }, toJSON : function() { var attrs = _.clone( this.attributes ); return attrs; }, parse: function(data, options) { // console.log(data); return data; } }); /** * Locations collection */ EA.Locations = Backbone.Collection.extend({ url : ajaxurl+'?action=ea_locations', model: EA.Location, cacheData: function() { if(typeof eaData !== 'undefined') { eaData.Locations = this.toJSON(); } } }); /** * Services collection */ EA.Services = Backbone.Collection.extend({ url : ajaxurl+'?action=ea_services', model: EA.Service, parse: function(response) { // console.log(response); return response; }, cacheData: function() { if(typeof eaData !== 'undefined') { eaData.Services = this.toJSON(); } } }); /** * Workers collection */ EA.Workers = Backbone.Collection.extend({ url : ajaxurl+'?action=ea_workers', model: EA.Worker, cacheData: function() { if(typeof eaData !== 'undefined') { eaData.Workers = this.toJSON(); } } }); /** * Connections collection */ EA.Connections = Backbone.Collection.extend({ url : ajaxurl+'?action=ea_connections', model: EA.Connection }); /** * Settings collection */ EA.Settings = Backbone.Collection.extend({ url : ajaxurl+'?action=ea_settings', model: EA.Setting }); /** * Wrapper around settings data */ EA.SettingsWrapper = Backbone.Model.extend({ url : ajaxurl+'?action=ea_settings', /*toJSON : function() { return this.model.toJSON(); }*/ }); /** * Main Report View * Renders Report Admin page * **/ EA.ReportView = Backbone.View.extend({ el : $('#wpbody-content'), template : _.template( $("#ea-report-main").html() ), events : { "click .report" : "reportSelected" }, initialize: function () { this.render(); }, render: function () { this.$el.empty(); this.$el.html( this.template()); return this; }, reportSelected: function(elem) { var report = $(elem.currentTarget).data('report'); switch (report) { case 'overview' : var rep = new EA.OverviewReportView(); var output = rep.render(); this.$el.find('#report-content').html(output.$el); break; } }, }); /** * Overvire report view */ EA.OverviewReportView = Backbone.View.extend({ template : _.template( $("#ea-report-overview").html() ), events : { 'change select' : 'selectChange', 'click .refresh': 'selectChange' }, initialize: function () { jQuery.datepicker.setDefaults( $.datepicker.regional[ea_settings.datepicker] ); this.render(); }, render: function() { var view = this; this.$el.empty(); this.$el.html( this.template({ cache: eaData }) ); this.$el.find('.datepicker').datepicker({ firstDay: 1, dayNamesMin: $.datepicker.regional[ea_settings.datepicker].dayNames, onChangeMonthYear: function(year, month, widget) { view.selectChange(month, year); }, beforeShowDay: function(date) { var month = date.getMonth() + 1; var days = date.getDate(); if(month < 10) { month = '0' + month; } if(days < 10) { days = '0' + days; } var response = [false, date.getFullYear() + '-' + month + '-' + days, '']; return response; } }); return this; }, selectChange: function(month, year) { var self = this; if(typeof month === 'undefined' || typeof year === 'undefined') { var currentDate = this.$el.find('.datepicker').datepicker('getDate'); month = currentDate.getMonth() + 1; year = currentDate.getFullYear(); } // check is all filled if(this.checkStatus()) { var selects = this.$el.find('select'); var fields = selects.serializeArray(); fields.push({ 'name' : 'action', 'value': 'ea_report' }); fields.push({ 'name' : 'report', 'value': 'overview' }); fields.push({ 'name' : 'month', 'value': month }); fields.push({ 'name' : 'year', 'value': year }); $.get(ajaxurl, fields, function(result) { self.refreshData(result); }, 'json'); } }, /** * Is everything selected * @return {boolean} Is ready for sending data */ checkStatus: function() { var selects = this.$el.find('select'); var isComplete = true; selects.each(function(index, element) { isComplete = isComplete && $(element).val() !== ''; }); return isComplete; }, refreshData: function(data) { var datepicker = this.$el.find('.datepicker'); $.each(data, function(key, slots){ var td = datepicker.find('.' + key); td.find('.single-item').remove(); if(slots.length === 0) { td.addClass('empty-day'); return; } else { td.removeClass('empty-day'); } var itemElement; for (var i = 0; i < slots.length; i++) { itemElement = $(document.createElement('div')) .text(slots[i].show + ' - x ' + slots[i].count ) .addClass('single-item') .addClass('free-items-' + slots[i].count) .data('value', slots[i].value) .appendTo(td); if(slots[i].count < 0) { itemElement.addClass('error-booking'); } } }); } }); var mainView = new EA.ReportView(); }(jQuery));
seanlon/profile-page
BookingPortal/wp-content/plugins/easy-appointments/js/report.prod.js
JavaScript
gpl-2.0
9,612
/** * My Cylinder constructor. * @constructor * @param scene {CGFscene} to which this cylinder belongs. * @param height {Float} Cylinder height * @param bRadius {Float} Cylinder bottom radius * @param tRadius {Float} Cylinder top radius * @param slices {Integer} Number of divisions of each circle * @param stacks {Integer} Number of divisions of the cylinder */ function MyCylinder(scene, height, bRadius, tRadius, stacks, slices) { CGFobject.call(this,scene); this.height = height; this.slices=slices; this.stacks=stacks; this.bRadius = bRadius; this.tRadius = tRadius; this.initBuffers(); } MyCylinder.prototype = Object.create(CGFobject.prototype); MyCylinder.prototype.constructor = MyCylinder; /** * Method in which the geometry of the cylinder is defined. */ MyCylinder.prototype.initBuffers = function() { var dTheta = 2*Math.PI/this.slices; var dRadius = (this.tRadius - this.bRadius) / this.stacks; var dHeight = this.height / this.stacks; this.vertices=[]; this.normals=[]; this.texCoords=[]; var vecNormal = vec3.create(); for (var stack = 0; stack <= this.stacks; ++stack) { var radius = this.bRadius + dRadius * stack; var height = dHeight * stack; for (var slice = 0; slice <= this.slices; ++slice) { var theta = dTheta * slice; this.vertices.push(radius * Math.cos(theta),radius*Math.sin(theta),height); var vecDiffSlice = vec3.fromValues(radius*(-Math.sin(theta))*dTheta, radius*Math.cos(theta)*dTheta, 0); var vecDiffStack = vec3.fromValues(Math.cos(theta)*dRadius, Math.sin(theta)*dRadius, dHeight); vec3.cross(vecNormal, vecDiffSlice, vecDiffStack); vec3.normalize(vecNormal, vecNormal); this.normals.push(vecNormal[0],vecNormal[1],vecNormal[2]); this.texCoords.push(slice/this.slices, 1-stack/this.stacks); } } this.indices=[]; for (var stack = 0; stack < this.stacks; ++stack) { for (var slice = 0; slice < this.slices; ++slice) { this.indices.push(stack * (this.slices+1) + slice, stack * (this.slices+1) + slice + 1, (stack+1) * (this.slices+1) + slice + 1); this.indices.push(stack * (this.slices+1) + slice, (stack+1) * (this.slices+1) + slice + 1, (stack+1) * (this.slices+1) + slice); } } this.primitiveType=this.scene.gl.TRIANGLES; this.initGLBuffers(); }; /** * texCoords scaling (no effect). */ MyCylinder.prototype.scaleTexCoords = function() {}
sceptross/LAIG-Projeto2
reader/primitives/MyCylinder.js
JavaScript
gpl-2.0
2,396
function test1(a, b) { if (a == b) { print("wrong !"); } if (a != b) { print("OK"); } } function test2(a, b) { if (a == b) { print("wrong !"); } else { print("OK"); } if (a != b) { print("OK"); } else { print("wrong !"); } } test1(4, 7); test2(4, 7);
forax/jsjs
test/test7.js
JavaScript
gpl-2.0
277
module.exports = require('./launchpad.js');
tjhorner/collaborative-launchpad
midi-launchpad/midi-launchpad.js
JavaScript
gpl-2.0
44
document.observe("dom:loaded", function() { var td = $("product_option_values"); var add_link = new Element("a", { href: "#" }); add_link.update("Add new value"); td.appendChild(add_link); var index = parseInt($("newvaluecount").value); add_link.observe("click", function(ev) { ev.stop(); ++index; var div = new Element("div"); var name = "newvalue" + index; var label = new Element("label", { for: name }); label.update("Value:"); div.appendChild(label); var input = new Element("input", { type: "text", name: name, id: name }); div.appendChild(input); td.insertBefore(div, add_link); $("newvaluecount").value = index; }); });
tonycoz/bse
site/htdocs/js/admin_editprodopt.js
JavaScript
gpl-2.0
687
/*! * VisualEditor UserInterface LinkInspector class. * * @copyright 2011-2013 VisualEditor Team and others; see AUTHORS.txt * @license The MIT License (MIT); see LICENSE.txt */ /*global mw */ /** * MediaWiki link inspector. * * @class * @extends ve.ui.LinkInspector * * @constructor * @param {ve.ui.WindowSet} windowSet Window set this inspector is part of * @param {Object} [config] Configuration options */ ve.ui.MWLinkInspector = function VeUiMWLinkInspector( windowSet, config ) { // Parent constructor ve.ui.LinkInspector.call( this, windowSet, config ); }; /* Inheritance */ OO.inheritClass( ve.ui.MWLinkInspector, ve.ui.LinkInspector ); /* Static properties */ ve.ui.MWLinkInspector.static.name = 'link'; ve.ui.MWLinkInspector.static.modelClasses = [ ve.dm.MWExternalLinkAnnotation, ve.dm.MWInternalLinkAnnotation ]; ve.ui.MWLinkInspector.static.linkTargetInputWidget = ve.ui.MWLinkTargetInputWidget; /* Methods */ /** * Gets an annotation object from a target. * * The type of link is automatically detected based on some crude heuristics. * * @method * @param {string} target Link target * @returns {ve.dm.MWInternalLinkAnnotation|ve.dm.MWExternalLinkAnnotation|null} */ ve.ui.MWLinkInspector.prototype.getAnnotationFromText = function ( target ) { var title = mw.Title.newFromText( target ); // Figure out if this is an internal or external link if ( ve.init.platform.getExternalLinkUrlProtocolsRegExp().test( target ) ) { // External link return new ve.dm.MWExternalLinkAnnotation( { 'type': 'link/mwExternal', 'attributes': { 'href': target } } ); } else if ( title ) { // Internal link // TODO: In the longer term we'll want to have autocompletion and existence and validity // checks using AJAX if ( title.getNamespaceId() === 6 || title.getNamespaceId() === 14 ) { // File: or Category: link // We have to prepend a colon so this is interpreted as a link // rather than an image inclusion or categorization target = ':' + target; } return new ve.dm.MWInternalLinkAnnotation( { 'type': 'link/mwInternal', 'attributes': { 'title': target, 'normalizedTitle': ve.dm.MWInternalLinkAnnotation.static.normalizeTitle( target ) } } ); } else { // Doesn't look like an external link and mw.Title considered it an illegal value, // for an internal link. return null; } }; /* Registration */ ve.ui.inspectorFactory.register( ve.ui.MWLinkInspector );
Wikia/OldStructuredDataPrototype
extensions/VisualEditor/modules/ve-mw/ui/inspectors/ve.ui.MWLinkInspector.js
JavaScript
gpl-2.0
2,468
$(function() { if ($('#edit-entry').length==0) {return;} if (dotclear.legacy_editor_context===undefined || dotclear.legacy_editor_tags_context[dotclear.legacy_editor_context]===undefined) { return; } if ((dotclear.legacy_editor_tags_context[dotclear.legacy_editor_context].indexOf('#post_content')!==-1) && (dotclear.legacy_editor_tags_context[dotclear.legacy_editor_context].indexOf('#post_excerpt')!==-1)) { // Get document format and prepare toolbars var formatField = $('#post_format').get(0); var last_post_format = $(formatField).val(); $(formatField).change(function() { if (this.value!='dcLegacyEditor') { return;} var post_format = this.value; // Confirm post format change if (window.confirm(dotclear.msg.confirm_change_post_format_noconvert)) { excerptTb.switchMode(post_format); contentTb.switchMode(post_format); last_post_format = $(this).val(); } else { // Restore last format if change cancelled $(this).val(last_post_format); } $('.format_control > *').addClass('hide'); $('.format_control:not(.control_no_'+post_format+') > *').removeClass('hide'); }); var excerptTb = new jsToolBar(document.getElementById('post_excerpt')); var contentTb = new jsToolBar(document.getElementById('post_content')); excerptTb.context = contentTb.context = 'post'; $('.format_control > *').addClass('hide'); $('.format_control:not(.control_no_'+last_post_format+') > *').removeClass('hide'); } if (dotclear.legacy_editor_tags_context[dotclear.legacy_editor_context].indexOf('#comment_content')!==-1) { if ($('#comment_content').length>0) { var commentTb = new jsToolBar(document.getElementById('comment_content')); commentTb.draw('xhtml'); } } $('#edit-entry').onetabload(function() { // Markup validator var v = $('<div class="format_control"><p><a id="a-validator"></a></p><div/>').get(0); $('.format_control').before(v); var a = $('#a-validator').get(0); a.href = '#'; a.className = 'button '; $(a).click(function() { excerpt_content = $('#post_excerpt').css('display') != 'none' ? $('#post_excerpt').val() : $('#excerpt-area iframe').contents().find('body').html(); post_content = $('#post_content').css('display') != 'none' ? $('#post_content').val() : $('#content-area iframe').contents().find('body').html(); var params = { xd_check: dotclear.nonce, f: 'validatePostMarkup', excerpt: excerpt_content, content: post_content, format: $('#post_format').get(0).value, lang: $('#post_lang').get(0).value }; $.post('services.php',params,function(data) { if ($(data).find('rsp').attr('status') != 'ok') { alert($(data).find('rsp message').text()); return false; } $('.message, .success, .error, .warning-msg').remove(); if ($(data).find('valid').text() == 1) { var p = document.createElement('p'); p.id = 'markup-validator'; $(p).addClass('success'); $(p).text(dotclear.msg.xhtml_valid); $('#entry-content h3').after(p); $(p).backgroundFade({sColor: dotclear.fadeColor.beginValidatorMsg, eColor: dotclear.fadeColor.endValidatorMsg, steps: 50},function() { $(this).backgroundFade({sColor: dotclear.fadeColor.endValidatorMsg, eColor: dotclear.fadeColor.beginValidatorMsg}); }); } else { var div = document.createElement('div'); div.id = 'markup-validator'; $(div).addClass('error'); $(div).html('<p><strong>' + dotclear.msg.xhtml_not_valid + '</strong></p>' + $(data).find('errors').text()); $('#entry-content h3').after(div); $(div).backgroundFade({sColor: dotclear.fadeColor.beginValidatorErr,eColor: dotclear.fadeColor.endValidatorErr, steps: 50},function() { $(this).backgroundFade({sColor: dotclear.fadeColor.endValidatorErr, eColor: dotclear.fadeColor.beginValidatorErr}); }); } if ( $('#post_excerpt').text() != excerpt_content || $('#post_content').text() != post_content ) { var pn = document.createElement('p'); $(pn).addClass('warning-msg'); $(pn).text(dotclear.msg.warning_validate_no_save_content); $('#entry-content h3').after(pn); } return false; }); return false; }); a.appendChild(document.createTextNode(dotclear.msg.xhtml_validator)); // Load toolbars if (contentTb!==undefined && excerptTb!==undefined) { contentTb.switchMode(formatField.value); excerptTb.switchMode(formatField.value); } // Check unsaved changes before XHTML conversion var excerpt = $('#post_excerpt').val(); var content = $('#post_content').val(); $('#convert-xhtml').click(function() { if (excerpt != $('#post_excerpt').val() || content != $('#post_content').val()) { return window.confirm(dotclear.msg.confirm_change_post_format); } }); }); });
julienw/dotclear-test
plugins/dcLegacyEditor/js/_post_editor.js
JavaScript
gpl-2.0
4,791
jQuery.namespace("Collective.Home"); (function () { Collective.Home.About = { DataUrl: "Home/About", Server: false, ViewModel: {}, View: {}, Load: function (control) { //Initial set var self = this; self.View = control; //initializarion callback function init() { var content = self.View.find("[name='Content']").val(); self.View.find("div:first").html(content); } //Get server data (if needed) Collective.Global.Get(this, {}, init); //Custom Controls (include translations) Collective.Global.Init(this.View); } }; })(jQuery);
CarlosNetMty/Collective
Collective/Collective.Web/Scripts/Home/About.js
JavaScript
gpl-2.0
742
// "prop" method fix for previous versions of jQuery (1.5 and below) if( typeof jQuery.fn.prop === 'undefined' ) { jQuery.fn.prop = jQuery.fn.attr; } jQuery(document).ready(function(){ //Formatting free form currency fields to currency jQuery(document).bind('gform_post_render', gformBindFormatPricingFields); }); function gformBindFormatPricingFields(){ jQuery(".ginput_amount, .ginput_donation_amount").bind("change", function(){ gformFormatPricingField(this); }); jQuery(".ginput_amount, .ginput_donation_amount").each(function(){ gformFormatPricingField(this); }); } //------------------------------------------------ //---------- CURRENCY ---------------------------- //------------------------------------------------ function Currency(currency){ this.currency = currency; this.toNumber = function(text){ if(this.isNumeric(text)) return parseFloat(text); return gformCleanNumber(text, this.currency["symbol_right"], this.currency["symbol_left"], this.currency["decimal_separator"]); }; this.toMoney = function(number){ if(!this.isNumeric(number)) number = this.toNumber(number); if(number === false) return ""; number = number + ""; negative = ""; if(number[0] == "-"){ number = parseFloat(number.substr(1)); negative = '-'; } money = this.numberFormat(number, this.currency["decimals"], this.currency["decimal_separator"], this.currency["thousand_separator"]); if ( money == '0.00' ){ negative = ''; } var symbol_left = this.currency["symbol_left"] ? this.currency["symbol_left"] + this.currency["symbol_padding"] : ""; var symbol_right = this.currency["symbol_right"] ? this.currency["symbol_padding"] + this.currency["symbol_right"] : ""; money = negative + this.htmlDecode(symbol_left) + money + this.htmlDecode(symbol_right); return money; }; this.numberFormat = function(number, decimals, dec_point, thousands_sep, padded){ var padded = typeof padded == 'undefined'; number = (number+'').replace(',', '').replace(' ', ''); var n = !isFinite(+number) ? 0 : +number, prec = !isFinite(+decimals) ? 0 : Math.abs(decimals), sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep, dec = (typeof dec_point === 'undefined') ? '.' : dec_point, s = '', toFixedFix = function (n, prec) { var k = Math.pow(10, prec); return '' + Math.round(n * k) / k; }; if(decimals == '0') { s = ('' + Math.round(n)).split('.'); } else if(decimals == -1) { s = ('' + n).split('.'); } else { // Fix for IE parseFloat(0.55).toFixed(0) = 0; s = toFixedFix(n, prec).split('.'); } if (s[0].length > 3) { s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep); } if(padded) { if ((s[1] || '').length < prec) { s[1] = s[1] || ''; s[1] += new Array(prec - s[1].length + 1).join('0'); } } return s.join(dec); } this.isNumeric = function(number){ return gformIsNumber(number); }; this.htmlDecode = function(text) { var c,m,d = text; // look for numerical entities &#34; var arr=d.match(/&#[0-9]{1,5};/g); // if no matches found in string then skip if(arr!=null){ for(var x=0;x<arr.length;x++){ m = arr[x]; c = m.substring(2,m.length-1); //get numeric part which is refernce to unicode character // if its a valid number we can decode if(c >= -32768 && c <= 65535){ // decode every single match within string d = d.replace(m, String.fromCharCode(c)); }else{ d = d.replace(m, ""); //invalid so replace with nada } } } return d; }; } function gformCleanNumber(text, symbol_right, symbol_left, decimal_separator){ var clean_number = '', float_number = '', digit = '', is_negative = false; //converting to a string if a number as passed text = text + " "; //Removing symbol in unicode format (i.e. &#4444;) text = text.replace(/&.*?;/, ""); //Removing symbol from text text = text.replace(symbol_right, ""); text = text.replace(symbol_left, ""); //Removing all non-numeric characters for(var i=0; i<text.length; i++){ digit = text.substr(i,1); if( (parseInt(digit) >= 0 && parseInt(digit) <= 9) || digit == decimal_separator ) clean_number += digit; else if(digit == '-') is_negative = true; } //Removing thousand separators but keeping decimal point for(var i=0; i<clean_number.length; i++) { digit = clean_number.substr(i,1); if (digit >= '0' && digit <= '9') float_number += digit; else if(digit == decimal_separator){ float_number += "."; } } if(is_negative) float_number = "-" + float_number; return gformIsNumber(float_number) ? parseFloat(float_number) : false; } function gformGetDecimalSeparator(numberFormat){ var s; switch (numberFormat){ case 'currency' : var currency = new Currency(gf_global.gf_currency_config); s = currency.currency["decimal_separator"]; break; case 'decimal_comma' : s = ','; break; default : s = "." } return s; } function gformIsNumber(n) { return !isNaN(parseFloat(n)) && isFinite(n); } function gformIsNumeric(value, number_format){ switch(number_format){ case "decimal_dot" : var r = new RegExp("^(-?[0-9]{1,3}(?:,?[0-9]{3})*(?:\.[0-9]+)?)$"); return r.test(value); break; case "decimal_comma" : var r = new RegExp("^(-?[0-9]{1,3}(?:\.?[0-9]{3})*(?:,[0-9]+)?)$"); return r.test(value); break; } return false; } //------------------------------------------------ //---------- MULTI-PAGE -------------------------- //------------------------------------------------ function gformDeleteUploadedFile(formId, fieldId, deleteButton){ var parent = jQuery("#field_" + formId + "_" + fieldId); var fileIndex = jQuery(deleteButton).parent().index(); parent.find(".ginput_preview").eq(fileIndex).remove(); //displaying single file upload field parent.find("input[type=\"file\"]").removeClass("gform_hidden"); //displaying post image label parent.find(".ginput_post_image_file").show(); //clearing post image meta fields parent.find("input[type=\"text\"]").val(''); //removing file from uploaded meta var filesJson = jQuery('#gform_uploaded_files_' + formId).val(); if(filesJson){ var files = jQuery.secureEvalJSON(filesJson); if(files) { var inputName = "input_" + fieldId; var $multfile = parent.find("#gform_multifile_upload_" + formId + "_" + fieldId ); if( $multfile.length > 0 ) { files[inputName].splice(fileIndex, 1); var settings = $multfile.data('settings'); var max = settings.gf_vars.max_files; jQuery("#" + settings.gf_vars.message_id).html(''); if(files[inputName].length < max) gfMultiFileUploader.toggleDisabled(settings, false); } else { files[inputName] = null; } jQuery('#gform_uploaded_files_' + formId).val(jQuery.toJSON(files)); } } } //------------------------------------------------ //---------- PRICE ------------------------------- //------------------------------------------------ var _gformPriceFields = new Array(); var _anyProductSelected; function gformIsHidden(element){ return element.parents('.gfield').not(".gfield_hidden_product").css("display") == "none"; } function gformCalculateTotalPrice(formId){ if(!_gformPriceFields[formId]) return; var price = 0; _anyProductSelected = false; //Will be used by gformCalculateProductPrice(). for(var i=0; i<_gformPriceFields[formId].length; i++){ price += gformCalculateProductPrice(formId, _gformPriceFields[formId][i]); } //add shipping price if a product has been selected if(_anyProductSelected){ //shipping price var shipping = gformGetShippingPrice(formId) price += shipping; } //gform_product_total filter. Allows uers to perform custom price calculation if(window["gform_product_total"]) price = window["gform_product_total"](formId, price); price = gform.applyFilters('gform_product_total', price, formId); //updating total var totalElement = jQuery(".ginput_total_" + formId); if( totalElement.length > 0 ) { var currentTotal = totalElement.next().val(); if( currentTotal == price ) { return; } totalElement.next().val( price ).change(); totalElement.html( gformFormatMoney( price ) ); } } function gformGetShippingPrice(formId){ var shippingField = jQuery(".gfield_shipping_" + formId + " input[type=\"hidden\"], .gfield_shipping_" + formId + " select, .gfield_shipping_" + formId + " input:checked"); var shipping = 0; if(shippingField.length == 1 && !gformIsHidden(shippingField)){ if(shippingField.attr("type") && shippingField.attr("type").toLowerCase() == "hidden") shipping = shippingField.val(); else shipping = gformGetPrice(shippingField.val()); } return gformToNumber(shipping); } function gformGetFieldId(element){ var id = jQuery(element).attr("id"); var pieces = id.split("_"); if(pieces.length <=0) return 0; var fieldId = pieces[pieces.length-1]; return fieldId; } function gformCalculateProductPrice(form_id, productFieldId){ var suffix = "_" + form_id + "_" + productFieldId; //Drop down auto-calculating labels jQuery(".gfield_option" + suffix + ", .gfield_shipping_" + form_id).find("select").each(function(){ var dropdown_field = jQuery(this); var selected_price = gformGetPrice(dropdown_field.val()); var field_id = dropdown_field.attr("id").split("_")[2]; dropdown_field.children("option").each(function(){ var choice_element = jQuery(this); var label = gformGetOptionLabel(choice_element, choice_element.val(), selected_price, form_id, field_id); choice_element.html(label); }); dropdown_field.trigger('chosen:updated'); }); //Checkboxes labels with prices jQuery(".gfield_option" + suffix).find(".gfield_checkbox").find("input").each(function(){ var checkbox_item = jQuery(this); var id = checkbox_item.attr("id"); var field_id = id.split("_")[3]; var label_id = id.replace("choice_", "#label_"); var label_element = jQuery(label_id); var label = gformGetOptionLabel(label_element, checkbox_item.val(), 0, form_id, field_id); label_element.html(label); }); //Radio button auto-calculating lables jQuery(".gfield_option" + suffix + ", .gfield_shipping_" + form_id).find(".gfield_radio").each(function(){ var selected_price = 0; var radio_field = jQuery(this); var id = radio_field.attr("id"); var fieldId = id.split("_")[3]; var selected_value = radio_field.find("input:checked").val(); if(selected_value) selected_price = gformGetPrice(selected_value); jQuery(this).find("input").each(function(){ var radio_item = jQuery(this); var label_id = radio_item.attr("id").replace("choice_", "#label_"); var label_element = jQuery(label_id); var label = gformGetOptionLabel(label_element, radio_item.val(), selected_price, form_id, fieldId); label_element.html(label); }); }); var price = gformGetBasePrice(form_id, productFieldId); var quantity = gformGetProductQuantity( form_id, productFieldId ); //calculating options if quantity is more than 0 (a product was selected). if( quantity > 0 ) { jQuery(".gfield_option" + suffix).find("input:checked, select").each(function(){ if(!gformIsHidden(jQuery(this))) price += gformGetPrice(jQuery(this).val()); }); //setting global variable if quantity is more than 0 (a product was selected). Will be used when calculating total _anyProductSelected = true; } price = price * quantity; price = Math.round(price * 100) / 100; return price; } function gformGetProductQuantity( formId, productFieldId ) { //If product is not selected if ( ! gformIsProductSelected( formId, productFieldId )){ return 0; } var quantity, quantityInput = jQuery( '#ginput_quantity_' + formId + '_' + productFieldId); if( quantityInput.length > 0 ) { quantity = ! gformIsNumber( quantityInput.val() ) ? 0 : quantityInput.val(); } else { quantityElement = jQuery( '.gfield_quantity_' + formId + '_' + productFieldId); quantity = 1; if( quantityElement.find( 'select' ).length > 0 ) { quantity = quantityElement.find( 'select' ).val(); } else if( quantityElement.find( 'input' ).length > 0 ) { quantity = quantityElement.find( 'input' ).val(); } if( ! gformIsNumber( quantity ) ) quantity = 0; } quantity = parseFloat( quantity ); return quantity; } function gformIsProductSelected( formId, productFieldId ) { var suffix = "_" + formId + "_" + productFieldId; var productField = jQuery("#ginput_base_price" + suffix + ", .gfield_donation" + suffix + " input[type=\"text\"], .gfield_product" + suffix + " .ginput_amount"); if( productField.val() && ! gformIsHidden(productField) ){ return true; } else { productField = jQuery(".gfield_product" + suffix + " select, .gfield_product" + suffix + " input:checked, .gfield_donation" + suffix + " select, .gfield_donation" + suffix + " input:checked"); if( productField.val() && ! gformIsHidden(productField) ){ return true; } } return false; } function gformGetBasePrice(formId, productFieldId){ var suffix = "_" + formId + "_" + productFieldId; var price = 0; var productField = jQuery("#ginput_base_price" + suffix+ ", .gfield_donation" + suffix + " input[type=\"text\"], .gfield_product" + suffix + " .ginput_amount"); if(productField.length > 0){ price = productField.val(); //If field is hidden by conditional logic, don't count it for the total if(gformIsHidden(productField)){ price = 0; } } else { productField = jQuery(".gfield_product" + suffix + " select, .gfield_product" + suffix + " input:checked, .gfield_donation" + suffix + " select, .gfield_donation" + suffix + " input:checked"); var val = productField.val(); if(val){ val = val.split("|"); price = val.length > 1 ? val[1] : 0; } //If field is hidden by conditional logic, don't count it for the total if(gformIsHidden(productField)) price = 0; } var c = new Currency(gf_global.gf_currency_config); price = c.toNumber(price); return price === false ? 0 : price; } function gformFormatMoney(text){ if(!gf_global.gf_currency_config) return text; var currency = new Currency(gf_global.gf_currency_config); return currency.toMoney(text); } function gformFormatPricingField(element){ if(gf_global.gf_currency_config){ var currency = new Currency(gf_global.gf_currency_config); var price = currency.toMoney(jQuery(element).val()); jQuery(element).val(price); } } function gformToNumber(text){ var currency = new Currency(gf_global.gf_currency_config); return currency.toNumber(text); } function gformGetPriceDifference(currentPrice, newPrice){ //getting price difference var diff = parseFloat(newPrice) - parseFloat(currentPrice); price = gformFormatMoney(diff); if(diff > 0) price = "+" + price; return price; } function gformGetOptionLabel(element, selected_value, current_price, form_id, field_id){ element = jQuery(element); var price = gformGetPrice(selected_value); var current_diff = element.attr('price'); var original_label = element.html().replace(/<span(.*)<\/span>/i, "").replace(current_diff, ""); var diff = gformGetPriceDifference(current_price, price); diff = gformToNumber(diff) == 0 ? "" : " " + diff; element.attr('price', diff); //don't add <span> for drop down items (not supported) var price_label = element[0].tagName.toLowerCase() == "option" ? " " + diff : "<span class='ginput_price'>" + diff + "</span>"; var label = original_label + price_label; //calling hook to allow for custom option formatting if(window["gform_format_option_label"]) label = gform_format_option_label(label, original_label, price_label, current_price, price, form_id, field_id); return label; } function gformGetProductIds(parent_class, element){ var classes = jQuery(element).hasClass(parent_class) ? jQuery(element).attr("class").split(" ") : jQuery(element).parents("." + parent_class).attr("class").split(" "); for(var i=0; i<classes.length; i++){ if(classes[i].substr(0, parent_class.length) == parent_class && classes[i] != parent_class) return {formId: classes[i].split("_")[2], productFieldId: classes[i].split("_")[3]}; } return {formId:0, fieldId:0}; } function gformGetPrice(text){ var val = text.split("|"); var currency = new Currency(gf_global.gf_currency_config); if(val.length > 1 && currency.toNumber(val[1]) !== false) return currency.toNumber(val[1]); return 0; } function gformRegisterPriceField(item){ if(!_gformPriceFields[item.formId]) _gformPriceFields[item.formId] = new Array(); //ignore price fields that have already been registered for(var i=0; i<_gformPriceFields[item.formId].length; i++) if(_gformPriceFields[item.formId][i] == item.productFieldId) return; //registering new price field _gformPriceFields[item.formId].push(item.productFieldId); } function gformInitPriceFields(){ jQuery(".gfield_price").each(function(){ var productIds = gformGetProductIds("gfield_price", this); gformRegisterPriceField(productIds); <<<<<<< HEAD jQuery(this).find("input[type=\"text\"], input[type=\"number\"], select").change(function(){ ======= jQuery( this ).on( 'change', 'input[type="text"], input[type="number"], select', function() { >>>>>>> c4ed0da5825345f6b0fe3527d88a7e02d1806836 var productIds = gformGetProductIds("gfield_price", this); if(productIds.formId == 0) productIds = gformGetProductIds("gfield_shipping", this); jQuery(document).trigger('gform_price_change', [productIds, this]); gformCalculateTotalPrice(productIds.formId); }); <<<<<<< HEAD jQuery(this).find("input[type=\"radio\"], input[type=\"checkbox\"]").click(function(){ ======= jQuery( this ).on( 'click', 'input[type="radio"], input[type="checkbox"]', function() { >>>>>>> c4ed0da5825345f6b0fe3527d88a7e02d1806836 var productIds = gformGetProductIds("gfield_price", this); if(productIds.formId == 0) productIds = gformGetProductIds("gfield_shipping", this); jQuery(document).trigger('gform_price_change', [productIds, this]); gformCalculateTotalPrice(productIds.formId); }); }); for(formId in _gformPriceFields){ //needed when implementing for in loops if(!_gformPriceFields.hasOwnProperty(formId)) continue; gformCalculateTotalPrice(formId); } } //------------------------------------------- //---------- PASSWORD ----------------------- //------------------------------------------- function gformShowPasswordStrength(fieldId){ var password = jQuery("#" + fieldId).val(); var confirm = jQuery("#" + fieldId + "_2").val(); var result = gformPasswordStrength(password, confirm); var text = window['gf_text']["password_" + result]; jQuery("#" + fieldId + "_strength").val(result); jQuery("#" + fieldId + "_strength_indicator").removeClass("blank mismatch short good bad strong").addClass(result).html(text); } // Password strength meter function gformPasswordStrength(password1, password2) { var shortPass = 1, badPass = 2, goodPass = 3, strongPass = 4, mismatch = 5, symbolSize = 0, natLog, score; if(password1.length <=0) return "blank"; // password 1 != password 2 if ( (password1 != password2) && password2.length > 0) return "mismatch"; //password < 4 if ( password1.length < 4 ) return "short"; if ( password1.match(/[0-9]/) ) symbolSize +=10; if ( password1.match(/[a-z]/) ) symbolSize +=26; if ( password1.match(/[A-Z]/) ) symbolSize +=26; if ( password1.match(/[^a-zA-Z0-9]/) ) symbolSize +=31; natLog = Math.log( Math.pow(symbolSize, password1.length) ); score = natLog / Math.LN2; if (score < 40 ) return "bad"; if (score < 56 ) return "good"; return "strong"; } //---------------------------- //------ LIST FIELD ---------- //---------------------------- var gfield_original_title = ""; function gformAddListItem(element, max){ if(jQuery(element).hasClass("gfield_icon_disabled")) return; var tr = jQuery(element).closest('tr'); var clone = tr.clone(); var tabindex = clone.find(":input:last").attr("tabindex"); clone.find("input, select").attr("tabindex", tabindex).not(":checkbox, :radio").val(""); clone.find(":checkbox, :radio").prop("checked", false); clone = gform.applyFilters( 'gform_list_item_pre_add', clone ); tr.after(clone); gformToggleIcons(tr.parent(), max); gformAdjustClasses(tr.parent()); } function gformDeleteListItem(element, max){ var tr = jQuery(element).parent().parent(); var parent = tr.parent(); tr.remove(); gformToggleIcons(parent, max); gformAdjustClasses(parent); } function gformAdjustClasses(table){ var rows = table.children(); for(var i=0; i<rows.length; i++){ var odd_even_class = (i+1) % 2 == 0 ? "gfield_list_row_even" : "gfield_list_row_odd"; jQuery(rows[i]).removeClass("gfield_list_row_odd").removeClass("gfield_list_row_even").addClass(odd_even_class); } } function gformToggleIcons(table, max){ var rowCount = table.children().length; if(rowCount == 1){ table.find(".delete_list_item").css("visibility", "hidden"); } else{ table.find(".delete_list_item").css("visibility", "visible"); } if(max > 0 && rowCount >= max){ gfield_original_title = table.find(".add_list_item:first").attr("title"); table.find(".add_list_item").addClass("gfield_icon_disabled").attr("title", ""); } else{ var addIcons = table.find(".add_list_item"); addIcons.removeClass("gfield_icon_disabled"); if(gfield_original_title) addIcons.attr("title", gfield_original_title); } } //----------------------------------- //------ CREDIT CARD FIELD ---------- //----------------------------------- function gformMatchCard(id) { var cardType = gformFindCardType(jQuery('#' + id).val()); var cardContainer = jQuery('#' + id).parents('.gfield').find('.gform_card_icon_container'); if(!cardType) { jQuery(cardContainer).find('.gform_card_icon').removeClass('gform_card_icon_selected gform_card_icon_inactive'); } else { jQuery(cardContainer).find('.gform_card_icon').removeClass('gform_card_icon_selected').addClass('gform_card_icon_inactive'); jQuery(cardContainer).find('.gform_card_icon_' + cardType).removeClass('gform_card_icon_inactive').addClass('gform_card_icon_selected'); } } function gformFindCardType(value) { if(value.length < 4) return false; var rules = window['gf_cc_rules']; var validCardTypes = new Array(); for(type in rules) { //needed when implementing for in loops if(!rules.hasOwnProperty(type)) continue; for(i in rules[type]) { if(!rules[type].hasOwnProperty(i)) continue; if(rules[type][i].indexOf(value.substring(0, rules[type][i].length)) === 0) { validCardTypes[validCardTypes.length] = type; break; } } } return validCardTypes.length == 1 ? validCardTypes[0].toLowerCase() : false; } function gformToggleCreditCard(){ if(jQuery("#gform_payment_method_creditcard").is(":checked")) jQuery(".gform_card_fields_container").slideDown(); else jQuery(".gform_card_fields_container").slideUp(); } //---------------------------------------- //------ CHOSEN DROP DOWN FIELD ---------- //---------------------------------------- function gformInitChosenFields(fieldList, noResultsText){ return jQuery(fieldList).each(function(){ var element = jQuery( this ); // RTL support if( jQuery( 'html' ).attr( 'dir' ) == 'rtl' ) { element.addClass( 'chosen-rtl chzn-rtl' ); } // only initialize once if( element.is(":visible") && element.siblings(".chosen-container").length == 0 ){ var options = gform.applyFilters( 'gform_chosen_options', { no_results_text: noResultsText }, element ); element.chosen( options ); } }); } //---------------------------------------- //--- CURRENCY FORMAT NUMBER FIELD ------- //---------------------------------------- function gformInitCurrencyFormatFields(fieldList){ jQuery(fieldList).each(function(){ var $this = jQuery(this); $this.val( gformFormatMoney( jQuery(this).val() ) ); }).change( function( event ) { jQuery(this).val( gformFormatMoney( jQuery(this).val() ) ); }); } //---------------------------------------- //------ CALCULATION FUNCTIONS ----------- //---------------------------------------- var GFCalc = function(formId, formulaFields){ this.patt = /{[^{]*?:(\d+(\.\d+)?)(:(.*?))?}/i; this.exprPatt = /^[0-9 -/*\(\)]+$/i; this.isCalculating = {}; this.init = function(formId, formulaFields) { var calc = this; jQuery(document).bind("gform_post_conditional_logic", function(){ for(var i=0; i<formulaFields.length; i++) { var formulaField = jQuery.extend({}, formulaFields[i]); calc.runCalc(formulaField, formId); } }); for(var i=0; i<formulaFields.length; i++) { var formulaField = jQuery.extend({}, formulaFields[i]); this.runCalc(formulaField, formId); this.bindCalcEvents(formulaField, formId); } } this.runCalc = function(formulaField, formId) { var calcObj = this, field = jQuery('#field_' + formId + '_' + formulaField.field_id), formulaInput = jQuery('#input_' + formId + '_' + formulaField.field_id), previous_val = formulaInput.val(), formula = gform.applyFilters( 'gform_calculation_formula', formulaField.formula, formulaField, formId, calcObj ), expr = calcObj.replaceFieldTags( formId, formula, formulaField ).replace(/(\r\n|\n|\r)/gm,""), result = ''; if(calcObj.exprPatt.test(expr)) { try { //run calculation result = eval(expr); } catch( e ) { } } // if result is postive infinity, negative infinity or a NaN, defaults to 0 if( ! isFinite( result ) ) result = 0; // allow users to modify result with their own function if( window["gform_calculation_result"] ) { result = window["gform_calculation_result"](result, formulaField, formId, calcObj); if( window.console ) console.log( '"gform_calculation_result" function is deprecated since version 1.8! Use "gform_calculation_result" JS hook instead.' ); } // allow users to modify result with their own function result = gform.applyFilters( 'gform_calculation_result', result, formulaField, formId, calcObj ); // allow result to be custom formatted var formattedResult = gform.applyFilters( 'gform_calculation_format_result', false, result, formulaField, formId, calcObj ); var numberFormat = gf_global.number_formats[formId][formulaField.field_id]; //formatting number if( formattedResult !== false) { result = formattedResult; } else if( field.hasClass( 'gfield_price' ) || numberFormat == "currency") { result = gformFormatMoney(result ? result : 0); } else { var decimalSeparator = "."; var thousandSeparator = ","; if(numberFormat == "decimal_comma"){ decimalSeparator = ","; thousandSeparator = "."; } result = gformFormatNumber(result, !gformIsNumber(formulaField.rounding) ? -1 : formulaField.rounding, decimalSeparator, thousandSeparator); } //If value doesn't change, abort. //This is needed to prevent an infinite loop condition with conditional logic if( result == previous_val ) return; // if this is a calculation product, handle differently if(field.hasClass('gfield_price')) { formulaInput.text(result); jQuery('#ginput_base_price_' + formId + '_' + formulaField.field_id).val(result).trigger('change'); gformCalculateTotalPrice(formId); } else { formulaInput.val(result).trigger('change'); } } this.bindCalcEvents = function(formulaField, formId) { var calcObj = this; var formulaFieldId = formulaField.field_id; var matches = getMatchGroups(formulaField.formula, this.patt); calcObj.isCalculating[formulaFieldId] = false; for(var i in matches) { if(! matches.hasOwnProperty(i)) continue; var inputId = matches[i][1]; var fieldId = parseInt(inputId); var input = jQuery('#field_' + formId + '_' + fieldId).find('input[name="input_' + inputId + '"], select[name="input_' + inputId + '"]'); if(input.prop('type') == 'checkbox' || input.prop('type') == 'radio') { jQuery(input).click(function(){ calcObj.bindCalcEvent(inputId, formulaField, formId, 0); }); } else if(input.is('select') || input.prop('type') == 'hidden') { jQuery(input).change(function(){ calcObj.bindCalcEvent(inputId, formulaField, formId, 0); }); } else { jQuery(input).keydown(function(){ calcObj.bindCalcEvent(inputId, formulaField, formId); }).change(function(){ calcObj.bindCalcEvent(inputId, formulaField, formId, 0); }); } // allow users to add custom methods for triggering calculations gform.doAction( 'gform_post_calculation_events', matches[i], formulaField, formId, calcObj ); } } this.bindCalcEvent = function(inputId, formulaField, formId, delay) { var calcObj = this; var formulaFieldId = formulaField.field_id; delay = delay == undefined ? 345 : delay; if(calcObj.isCalculating[formulaFieldId][inputId]) clearTimeout(calcObj.isCalculating[formulaFieldId][inputId]); calcObj.isCalculating[formulaFieldId][inputId] = window.setTimeout(function() { calcObj.runCalc(formulaField, formId); }, delay); } this.replaceFieldTags = function( formId, expr, formulaField ) { var matches = getMatchGroups(expr, this.patt); var origExpr = expr; for(i in matches) { if(! matches.hasOwnProperty(i)) continue; var inputId = matches[i][1]; var fieldId = parseInt(inputId); var columnId = matches[i][3]; var value = 0; var input = jQuery('#field_' + formId + '_' + fieldId).find('input[name="input_' + inputId + '"], select[name="input_' + inputId + '"]'); // radio buttons will return multiple inputs, checkboxes will only return one but it may not be selected, filter out unselected inputs if( input.length > 1 || input.prop('type') == 'checkbox' ) input = input.filter(':checked'); var isVisible = window['gf_check_field_rule'] ? gf_check_field_rule( formId, fieldId, true, '' ) == 'show' : true; if( input.length > 0 && isVisible ) { var val = input.val(); val = val.split( '|' ); if( val.length > 1 ) { value = val[1]; } else { value = input.val(); } } var numberFormat = gf_global.number_formats[formId][fieldId]; if( ! numberFormat ) numberFormat = gf_global.number_formats[formId][formulaField.field_id]; var decimalSeparator = gformGetDecimalSeparator(numberFormat); // allow users to modify value with their own function value = gform.applyFilters( 'gform_merge_tag_value_pre_calculation', value, matches[i], isVisible, formulaField, formId ); value = gformCleanNumber( value, '', '', decimalSeparator ); if( ! value ) value = 0; expr = expr.replace( matches[i][0], value ); } return expr; } this.init(formId, formulaFields); } function gformFormatNumber(number, rounding, decimalSeparator, thousandSeparator){ if(typeof decimalSeparator == "undefined"){ if(window['gf_global']){ var currency = new Currency(gf_global.gf_currency_config); decimalSeparator = currency.currency["decimal_separator"]; } else{ decimalSeparator = "."; } } if(typeof thousandSeparator == "undefined"){ if(window['gf_global']){ var currency = new Currency(gf_global.gf_currency_config); thousandSeparator = currency.currency["thousand_separator"]; } else{ thousandSeparator = ","; } } var currency = new Currency(); return currency.numberFormat(number, rounding, decimalSeparator, thousandSeparator, false) } function gformToNumber(text) { var currency = new Currency(gf_global.gf_currency_config); return currency.toNumber(text); } function getMatchGroups(expr, patt) { var matches = new Array(); while(patt.test(expr)) { var i = matches.length; matches[i] = patt.exec(expr) expr = expr.replace('' + matches[i][0], ''); } return matches; } //---------------------------------------- //------ JAVASCRIPT HOOK FUNCTIONS ------- //---------------------------------------- var gform = { hooks: { action: {}, filter: {} }, addAction: function( action, callable, priority, tag ) { gform.addHook( 'action', action, callable, priority, tag ); }, addFilter: function( action, callable, priority, tag ) { gform.addHook( 'filter', action, callable, priority, tag ); }, doAction: function( action ) { gform.doHook( 'action', action, arguments ); }, applyFilters: function( action ) { return gform.doHook( 'filter', action, arguments ); }, removeAction: function( action, tag ) { gform.removeHook( 'action', action, tag ); }, removeFilter: function( action, priority, tag ) { gform.removeHook( 'filter', action, priority, tag ); }, addHook: function( hookType, action, callable, priority, tag ) { if ( undefined == gform.hooks[hookType][action] ) { gform.hooks[hookType][action] = []; } var hooks = gform.hooks[hookType][action]; if ( undefined == tag ) { tag = action + '_' + hooks.length; } gform.hooks[hookType][action].push( { tag:tag, callable:callable, priority:priority } ); }, doHook: function( hookType, action, args ) { // splice args from object into array and remove first index which is the hook name args = Array.prototype.slice.call(args, 1); if ( undefined != gform.hooks[hookType][action] ) { var hooks = gform.hooks[hookType][action], hook; //sort by priority hooks.sort(function(a,b){return a["priority"]-b["priority"]}); for( var i=0; i<hooks.length; i++) { hook = hooks[i].callable; if(typeof hook != 'function') hook = window[hook]; if ( 'action' == hookType ) { hook.apply(null, args); } else { args[0] = hook.apply(null, args); } } } if ( 'filter'==hookType ) { return args[0]; } }, removeHook: function( hookType, action, priority, tag ) { if ( undefined != gform.hooks[hookType][action] ) { var hooks = gform.hooks[hookType][action]; for( var i=hooks.length-1; i>=0; i--) { if ((undefined==tag||tag==hooks[i].tag) && (undefined==priority||priority==hooks[i].priority)){ hooks.splice(i,1); } } } } }; //---------------------------------------- //------ MULTIFILE UPLOAD FUNCTIONS ------ //---------------------------------------- (function (gfMultiFileUploader, $) { gfMultiFileUploader.uploaders = {}; var strings = typeof gform_gravityforms != 'undefined' ? gform_gravityforms.strings : {}; var imagesUrl = typeof gform_gravityforms != 'undefined' ? gform_gravityforms.vars.images_url : ""; $(document).bind('gform_post_render', function(e, formID){ $("form#gform_" + formID + " .gform_fileupload_multifile").each(function(){ setup(this); }); var $form = $("form#gform_" + formID); if($form.length > 0){ $form.submit(function(){ var pendingUploads = false; $.each(gfMultiFileUploader.uploaders, function(i, uploader){ if(uploader.total.queued>0){ pendingUploads = true; return false; } }); if(pendingUploads){ alert(strings.currently_uploading); window["gf_submitting_" + formID] = false; $('#gform_ajax_spinner_' + formID).remove(); return false; } }); } }); $(document).bind("gform_post_conditional_logic", function(e,formID, fields, isInit){ if(!isInit){ $.each(gfMultiFileUploader.uploaders, function(i, uploader){ uploader.refresh(); }); } }); $(document).ready(function () { if((typeof adminpage !== 'undefined' && adminpage === 'toplevel_page_gf_edit_forms')|| typeof plupload == 'undefined'){ $(".gform_button_select_files").prop("disabled", true); } else if (typeof adminpage !== 'undefined' && adminpage.indexOf('_page_gf_entries') > -1) { $(".gform_fileupload_multifile").each(function(){ setup(this); }); } }); gfMultiFileUploader.setup = function (uploadElement){ setup( uploadElement ); }; function setup(uploadElement){ var settings = $(uploadElement).data('settings'); var uploader = new plupload.Uploader(settings); formID = uploader.settings.multipart_params.form_id; gfMultiFileUploader.uploaders[settings.container] = uploader; var formID; var uniqueID; uploader.bind('Init', function(up, params) { if(!up.features.dragdrop) $(".gform_drop_instructions").hide(); var fieldID = up.settings.multipart_params.field_id; var maxFiles = parseInt(up.settings.gf_vars.max_files); var initFileCount = countFiles(fieldID); if(maxFiles > 0 && initFileCount >= maxFiles){ gfMultiFileUploader.toggleDisabled(up.settings, true); } }); gfMultiFileUploader.toggleDisabled = function (settings, disabled){ var button = typeof settings.browse_button == "string" ? $("#" + settings.browse_button) : $(settings.browse_button); button.prop("disabled", disabled); }; function addMessage(messagesID, message){ $("#" + messagesID).prepend("<li>" + message + "</li>"); } uploader.init(); uploader.bind('FilesAdded', function(up, files) { var max = parseInt(up.settings.gf_vars.max_files), fieldID = up.settings.multipart_params.field_id, totalCount = countFiles(fieldID), disallowed = up.settings.gf_vars.disallowed_extensions, extension; if( max > 0 && totalCount >= max){ $.each(files, function(i, file) { up.removeFile(file); return; }); return; } $.each(files, function(i, file) { extension = file.name.split('.').pop(); if($.inArray(extension, disallowed) > -1){ addMessage(up.settings.gf_vars.message_id, file.name + " - " + strings.illegal_extension); up.removeFile(file); return; } if ((file.status == plupload.FAILED) || (max > 0 && totalCount >= max)){ up.removeFile(file); return; } var size = typeof file.size !== 'undefined' ? plupload.formatSize(file.size) : strings.in_progress; var status = '<div id="' + file.id + '" class="ginput_preview">' + file.name + ' (' + size + ') <b></b> ' + '<a href="javascript:void(0)" title="' + strings.cancel_upload + '" onclick=\'$this=jQuery(this); var uploader = gfMultiFileUploader.uploaders.' + up.settings.container + ';uploader.stop();uploader.removeFile(uploader.getFile("' + file.id +'"));$this.after("' + strings.cancelled + '"); uploader.start();$this.remove();\'>' + strings.cancel + '</a>' + '</div>'; $('#' + up.settings.filelist).prepend(status); totalCount++; }); up.refresh(); // Reposition Flash var formElementID = "form#gform_" + formID; var uidElementID = "input:hidden[name='gform_unique_id']"; var uidSelector = formElementID + " " + uidElementID; var $uid = $(uidSelector); if($uid.length==0){ $uid = $(uidElementID); } uniqueID = $uid.val(); if('' === uniqueID){ uniqueID = generateUniqueID(); $uid.val(uniqueID); } if(max > 0 && totalCount >= max){ gfMultiFileUploader.toggleDisabled(up.settings, true); addMessage(up.settings.gf_vars.message_id, strings.max_reached) } up.settings.multipart_params.gform_unique_id = uniqueID; up.start(); }); uploader.bind('UploadProgress', function(up, file) { var html = file.percent + "%"; $('#' + file.id + " b").html(html); }); uploader.bind('Error', function(up, err) { if(err.code === plupload.FILE_EXTENSION_ERROR){ var extensions = typeof up.settings.filters.mime_types != 'undefined' ? up.settings.filters.mime_types[0].extensions /* plupoad 2 */ : up.settings.filters[0].extensions; addMessage(up.settings.gf_vars.message_id, err.file.name + " - " + strings.invalid_file_extension + " " + extensions); } else if (err.code === plupload.FILE_SIZE_ERROR) { addMessage(up.settings.gf_vars.message_id, err.file.name + " - " + strings.file_exceeds_limit); } else { var m = "<li>Error: " + err.code + ", Message: " + err.message + (err.file ? ", File: " + err.file.name : "") + "</li>"; addMessage(up.settings.gf_vars.message_id, m); } $('#' + err.file.id ).html(''); up.refresh(); // Reposition Flash }); uploader.bind('FileUploaded', function(up, file, result) { var response = $.secureEvalJSON(result.response); if(response.status == "error"){ addMessage(up.settings.gf_vars.message_id, file.name + " - " + response.error.message); $('#' + file.id ).html(''); return; } var html = '<strong>' + file.name + '</strong>'; var formId = up.settings.multipart_params.form_id; var fieldId = up.settings.multipart_params.field_id; html = "<img " + "class='gform_delete' " + "src='" + imagesUrl + "/delete.png' " + "onclick='gformDeleteUploadedFile(" + formId + "," + fieldId + ", this);' " + "alt='"+ strings.delete_file + "' " + "title='" + strings.delete_file + "' /> " + html; html = gform.applyFilters( 'gform_file_upload_markup', html, file, up, strings, imagesUrl ); $( '#' + file.id ).html( html ); var fieldID = up.settings.multipart_params["field_id"]; if(file.percent == 100){ if(response.status && response.status == 'ok'){ addFile(fieldID, response.data); } else { addMessage(up.settings.gf_vars.message_id, strings.unknown_error + ': ' + file.name); } } }); <<<<<<< HEAD function getAllFiles(){ var selector = '#gform_uploaded_files_' + formID, $uploadedFiles = $(selector), files; files = $uploadedFiles.val(); files = '' === files ? {} : $.parseJSON(files); return files; } ======= function getAllFiles(){ var selector = '#gform_uploaded_files_' + formID, $uploadedFiles = $(selector), files; files = $uploadedFiles.val(); files = (typeof files === "undefined") || files === '' ? {} : $.parseJSON(files); return files; } >>>>>>> c4ed0da5825345f6b0fe3527d88a7e02d1806836 function getFiles(fieldID){ var allFiles = getAllFiles(); var inputName = getInputName(fieldID); if(typeof allFiles[inputName] == 'undefined') allFiles[inputName] = []; return allFiles[inputName]; } function countFiles(fieldID){ var files = getFiles(fieldID); return files.length; } function addFile(fieldID, fileInfo){ var files = getFiles(fieldID); files.unshift(fileInfo); setUploadedFiles(fieldID, files); } function setUploadedFiles(fieldID, files){ var allFiles = getAllFiles(); var $uploadedFiles = $('#gform_uploaded_files_' + formID); var inputName = getInputName(fieldID); allFiles[inputName] = files; $uploadedFiles.val($.toJSON(allFiles)); } function getInputName(fieldID){ return "input_" + fieldID; } // fixes drag and drop in IE10 $("#" + settings.drop_element).on({ "dragenter": ignoreDrag, "dragover": ignoreDrag }); function ignoreDrag( e ) { e.preventDefault(); } } function generateUniqueID() { return 'xxxxxxxx'.replace(/[xy]/g, function (c) { var r = Math.random() * 16 | 0, v = c == 'x' ? r : r & 0x3 | 0x8; return v.toString(16); }); } }(window.gfMultiFileUploader = window.gfMultiFileUploader || {}, jQuery)); //---------------------------------------- //------ GENERAL FUNCTIONS ------- //---------------------------------------- function gformInitSpinner( formId, spinnerUrl ) { if( typeof spinnerUrl == 'undefined' || ! spinnerUrl ) spinnerUrl = gform.applyFilters( "gform_spinner_url", gf_global.spinnerUrl, formId ); jQuery('#gform_' + formId).submit(function () { if (jQuery('#gform_ajax_spinner_' + formId).length == 0) { jQuery('#gform_submit_button_' + formId + ', #gform_wrapper_' + formId + ' .gform_next_button, #gform_send_resume_link_button_' + formId) .after('<img id="gform_ajax_spinner_' + formId + '" class="gform_ajax_spinner" src="' + spinnerUrl + '" alt="" />'); } }); }
creative2020/mu2
wp-content/plugins/gravityforms/js/gravityforms.js
JavaScript
gpl-2.0
49,412
//定义画布宽高和生成点的个数 var WIDTH = window.innerWidth, HEIGHT = window.innerHeight, POINT = 35; var canvas = document.getElementById('js-particles'); canvas.width = WIDTH, canvas.height = HEIGHT; var context = canvas.getContext('2d'); context.strokeStyle = 'rgba(0,0,0,0.02)', context.strokeWidth = 1, context.fillStyle = 'rgba(0,0,0,0.05)'; var circleArr = []; //线条:开始xy坐标,结束xy坐标,线条透明度 function Line(x, y, _x, _y, o) { this.beginX = x, this.beginY = y, this.closeX = _x, this.closeY = _y, this.o = o; } //点:圆心xy坐标,半径,每帧移动xy的距离 function Circle(x, y, r, moveX, moveY) { this.x = x, this.y = y, this.r = r, this.moveX = moveX, this.moveY = moveY; } //生成max和min之间的随机数 function num(max, _min) { var min = arguments[1] || 0; return Math.floor(Math.random() * (max - min + 1) + min); } // 绘制原点 function drawCricle(cxt, x, y, r, moveX, moveY) { var circle = new Circle(x, y, r, moveX, moveY) cxt.beginPath() cxt.arc(circle.x, circle.y, circle.r, 0, 2 * Math.PI) cxt.closePath() cxt.fill(); return circle; } //绘制线条 function drawLine(cxt, x, y, _x, _y, o) { var line = new Line(x, y, _x, _y, o) cxt.beginPath() cxt.strokeStyle = 'rgba(0,0,0,' + o + ')' cxt.moveTo(line.beginX, line.beginY) cxt.lineTo(line.closeX, line.closeY) cxt.closePath() cxt.stroke(); } //初始化生成原点 function init() { circleArr = []; for (var i = 0; i < POINT; i++) { circleArr.push(drawCricle(context, num(WIDTH), num(HEIGHT), num(15, 2), num(10, -10) / 40, num(10, -10) / 40)); } draw(); } //每帧绘制 function draw() { context.clearRect(0, 0, canvas.width, canvas.height); for (var i = 0; i < POINT; i++) { drawCricle(context, circleArr[i].x, circleArr[i].y, circleArr[i].r); } for (var i = 0; i < POINT; i++) { for (var j = 0; j < POINT; j++) { if (i + j < POINT) { var A = Math.abs(circleArr[i + j].x - circleArr[i].x), B = Math.abs(circleArr[i + j].y - circleArr[i].y); var lineLength = Math.sqrt(A * A + B * B); var C = 1 / lineLength * 7 - 0.009; var lineOpacity = C > 0.03 ? 0.03 : C; if (lineOpacity > 0) { drawLine(context, circleArr[i].x, circleArr[i].y, circleArr[i + j].x, circleArr[i + j].y, lineOpacity); } } } } } //调用执行 window.onload = function () { init(); setInterval(function () { for (var i = 0; i < POINT; i++) { var cir = circleArr[i]; cir.x += cir.moveX; cir.y += cir.moveY; if (cir.x > WIDTH) cir.x = 0; else if (cir.x < 0) cir.x = WIDTH; if (cir.y > HEIGHT) cir.y = 0; else if (cir.y < 0) cir.y = HEIGHT; } draw(); }, 16); }
firewenda/firewenda.github.io
js/cavas.code.js
JavaScript
gpl-2.0
3,056
App.View.Map = Backbone.View.extend({ _tooltip_template : $('#map-tooltip_template').html(), currentWMSLayers: [], events:{}, initialize: function() { $("#map").outerHeight($("#map").outerHeight()-$("footer").outerHeight()-$("header").outerHeight()); $("#map").css({"top": $("header").outerHeight()}); //create the left map's leaflet instance this._map = new L.Map('map', {'zoomControl': false}).setView([App.Cons.iniLat, App.Cons.iniLng], App.Cons.iniZoom); L.tileLayer('http://{s}.tile.thunderforest.com/landscape/{z}/{x}/{y}.png', {attribution: '&copy; <a href="http://www.opencyclemap.org">OpenCycleMap</a>, &copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>'} ).addTo(this._map); // add zoom control to map left var zoomControl = new L.Control.Zoom({ position : 'topright' }); zoomControl.addTo(this._map); this._map.touchZoom.disable(); this.listenTo(App.currentLayers, 'add', this.renderLayers); this.listenTo(App.currentLayers, 'remove', this.renderLayers); this.listenTo(App.currentLayers, 'change:visible', this.updateLayers); this.listenTo(App.currentLayers, 'change:opacity', this.updateLayers); this._map.on("click", this.getFeatureInfo, this); this.render(); var aux = Backbone.history.getFragment(); if(aux){ aux = aux.split(App.router.langRoutes["_link map"][[App.lang]]); if(aux.length >1){ this.getRoute(aux[1]); } } }, onClose: function(){ // Remove events on close this.stopListening(); $("#map").hide(); }, render: function() { // this.$el.html(this._template()); // $("#map").show(); return this; }, addLayers: function(layers, z_index) { if(layers != null && layers.length > 0){ var gSLayerWMS = new GSLayerWMS(layers, 1000, this._map); gSLayerWMS.setVisibility(layers[0].visible, z_index, this._map._zoom); if(layers[0].opacity < 1){ gSLayerWMS.setOpacity(layers[0].opacity); } for(var idx in layers){ var layerModel = App.currentLayers.get(layers[idx]); layerModel.set({'layerInstance': gSLayerWMS}); } this.currentWMSLayers.push(gSLayerWMS); } }, removeLayer: function(elem) { elem.get('layerInstance').setVisibility(false, null, null); }, updateLayers: function(elem) { var gSLayerWMS = elem.get('layerInstance'); var visible = elem.get('visible'); if(gSLayerWMS.numLayers === 1){ gSLayerWMS.setVisibility(visible, gSLayerWMS.z_index, this._map._zoom); gSLayerWMS.setOpacity(elem.get('opacity')); }else{ this.renderLayers(); } this.setRoute(); }, renderLayers: function() { // Clear current layers while(this.currentWMSLayers.length){ var wmsLayer = this.currentWMSLayers.pop(); wmsLayer.setVisibility(false, null, null); } // Load layers var groups = []; var i = 0; groups[i] = []; var currentLayers = App.currentLayers.toJSON() for (var idx in currentLayers){ if(idx == 0){ groups[i].push(currentLayers[idx]); }else{ if (currentLayers[idx].opacity === currentLayers[idx-1].opacity && currentLayers[idx].visible === currentLayers[idx-1].visible && currentLayers[idx].wmsServer === currentLayers[idx-1].wmsServer){ groups[i].unshift(currentLayers[idx]); }else{ i++; groups[i] = []; groups[i].push(currentLayers[idx]); } } } var numLayers = groups.length; for (var j in groups){ this.addLayers(groups[j], numLayers - j); } this.setRoute(); }, getFeatureInfo : function(e,id){ if(!id){ id = 0; } var map = this._map; var latlngStr = '(' + e.latlng.lat.toFixed(3) + ', ' + e.latlng.lng.toFixed(3) + ')'; var BBOX = map.getBounds().toBBoxString(); var WIDTH = map.getSize().x; var HEIGHT = map.getSize().y; var X = map.layerPointToContainerPoint(e.layerPoint).x; var Y = map.layerPointToContainerPoint(e.layerPoint).y; var layers = null; var server = null; var requestIdx = null; var currentLayers = App.currentLayers.toJSON(); for (var i=id;i<currentLayers.length;i++){ var l = currentLayers[i].layerInstance; if (l.visible && l.layer.options.opacity>0){ server = currentLayers[i].wmsServer; layers = currentLayers[i].wmsLayName; requestIdx = i; break; } } if (layers==null || server==null || requestIdx==null) { $("#container_feature_info").html("No hay información sobre este punto"); return; } var request = server + '?SERVICE=WMS&VERSION=1.1.1&REQUEST=GetFeatureInfo&LAYERS=' +layers+'&QUERY_LAYERS='+layers+'&STYLES=&BBOX='+BBOX+'&FEATURE_COUNT=5&HEIGHT='+HEIGHT+'&WIDTH='+WIDTH+'&FORMAT=image%2Fpng&INFO_FORMAT=application%2Fjson&SRS=EPSG%3A4326&X='+X+'&Y='+Y; request = request.replace("wmts","wms"); var obj = this; $.ajax({ url : request, type: "GET", success: function(data) { try { if (!data || data.features.length === 0){ obj.getFeatureInfo(e,requestIdx+1); } else{ if(currentLayers[requestIdx].gis) currentLayers[requestIdx].gis = App.config.static_path + 'gis/' + currentLayers[requestIdx].gis; if(currentLayers[requestIdx].xls) currentLayers[requestIdx].xls = App.config.static_path + 'xls/' + currentLayers[requestIdx].xls; var content = new App.View.MapTooltip({model: currentLayers[requestIdx]}); obj.listenTo(content, 'openPdf', this.openPdf); var popup = L.popup() .setLatLng(e.latlng) .setContent(content.render().el) .openOn(obj._map); } }catch (ex){ if((i+1) < currentLayers.length){ obj.getFeatureInfo(e, requestIdx+1); }else{ console.log('No data'); } } }, error: function(){ if((i+1) < currentLayers.length){ obj.getFeatureInfo(e, requestIdx+1); }else{ console.log('No data'); } } }); }, buildRoute: function() { var layers = ""; var actives = ""; var opacity = ""; var currentLayers = App.currentLayers.toJSON(); currentLayers.forEach(function(layer) { layers += layer.id + "_" if(layer.visible){ actives += "1_" }else{ actives += "0_" } opacity += (layer.opacity * 100) + "_"; }); layers = layers.replace(/_([^_]*)$/,"/"+'$1'); actives = actives.replace(/_([^_]*)$/,"/"+'$1'); opacity = opacity.replace(/_([^_]*)$/,"/"+'$1'); return layers + actives + opacity; }, setRoute: function() { if(Backbone.history.fragment.indexOf(App.router.langRoutes["_link map"][[App.lang]]) == 0){ var result = this.buildRoute(); if(result != ""){ App.router.navigate(App.router.langRoutes["_link map"][[App.lang]] + "/" + result,{trigger: false}); }else{ App.router.navigate(App.router.langRoutes["_link map"][[App.lang]],{trigger: false}); } } }, getRoute: function(route) { var args = route.split('/'); if(args.length > 3){ if(args[1].indexOf(App.router.langRoutes['_link map'][[App.lang]]) == -1){ var layers = args[1].split('_'); var actives = args[2].split('_'); var opacity = args[3].split('_'); for(var i=layers.length -1; i>=0; i--){ var layer = App.catalog.getLayerById(parseInt(layers[i])); var visible = (actives[i] == "1"); layer.set({'visible': visible, opacity: (parseInt(opacity[i]) / 100)}); App.currentLayers.add(layer); } } } }, toggleOpen: function(e, force){ if(force === undefined) this.$el.toggleClass('shrink'); else this.$el.toggleClass('shrink', force); }, openPdf: function(e){ this.toggleOpen(); this.trigger('openPdf'); } });
GeographicaGS/IUCNRedBook
www/src/js/View/MapView.js
JavaScript
gpl-2.0
8,932