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
function showThunk (thunk) { return thunk.function+"("+thunk.arguments.map(showTerm).join(", ")+")" } function showTerm (term) { if (term.Right) { return (typeof term.Right === "string") ? JSON.stringify(term.Right) : term.Right } return "?"+term.Left } return function (datas) { var ready = true var history = $("<ul>") .addClass("history") // var current = $("<div>") // .addClass("current") var input = $("<input>") .prop("type", "text") .prop("disabled", true) var button = $("<button>") .html("Input") .prop("disabled", true) var output = $("<div>") .addClass("output") var jqo = $("<div>") .addClass("pursuer") .append($("<h2>").html("Pursuer")) .append($("<div>") .append($("<h3>").html("Promises")) .append(history)) // .append($("<div>") // .append($("<span>").html("Current promise:") // .append(current)))) .append($("<div>") .append($("<h3>").html("Input - Output")) .append(output) .append($("<div>") .append(input) .append(button))) jqo.$catchup = function (thunk, callback) { if (!ready) { return false } ready = false //current.html("?"+datas.length+" = "+showThunk(thunk)+"]") var args = thunk.arguments.map(function (term) { return (typeof term.Left !== "undefined") ? datas[term.Left] : term.Right }) function end (data) { history.append($("<div>").html("?"+datas.length+" = "+JSON.stringify(data)+" ["+showThunk(thunk)+"]")) //current.html("") datas.push(data) ready = true callback() } switch (thunk.function) { // Type case "?number?": end(typeof args[0] === "number"); break case "?string?": end(typeof args[0] === "string"); break case "?boolean?": end(args[0] === true || args(1) === false); break case "?null?": end(args[0] === null); break // Equal case "?equal?": end(args[0] === args[1]); break // Boolean case "?and": end(Boolean(args[0] && args[1])); break case "?or": end(Boolean(args[0] && args[1])); break case "?not": end(Boolean(!args[0])); break // Number case "?<": end(args[0] < args[1]); break case "?<=": end(args[0] <= args[1]); break case "?+": end(args[0] + args[1]); break case "?-": end(args[0] + args[1]); break case "?*": end(args[0] * args[1]); break case "?/": end(args[0] / args[1]); break // String case "?string->data": var data = null try { data = JSON.parse(args[0]) } catch (err) { } end(data) break case "?data->string": end(JSON.stringify(args[0])); break // Actions case "!read": input.prop("disabled", false) button.prop("disabled", false) button.one("click", function () { end(input.val()) input.val("") input.prop("disabled", true) button.prop("disabled", true) }) break case "!write": output.append($("<div>").html(+"> "+args[0]+"\n")) end(null) break } return true } jqo.$solve = function (promises) { promises = promises.slice() for (var i=0; i<datas.length; i++) { promises[i] = datas[i] } return promises } jqo.$next = function () { return datas.length } jqo.$fork = function (symbol) { return Boolean(datas[symbol]) } return jqo }
lachrist/kusasa-hs
client/js/pursuer.js
JavaScript
gpl-2.0
3,446
DateInput = (function ($) { function DateInput(el, opts) { if (typeof (opts) != "object") opts = {}; $.extend(this, DateInput.DEFAULT_OPTS, opts); this.input = $(el); this.bindMethodsToObj("show", "hide", "hideIfClickOutside", "keydownHandler", "selectDate"); this.build(); this.selectDate(); this.hide() }; DateInput.DEFAULT_OPTS = { month_names: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"], short_month_names: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], short_day_names: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"], start_of_week: 1 }; DateInput.prototype = { build: function () { var monthNav = $('<p class="month_nav">' + '<span class="button prev" title="[Page-Up]">&#171;</span>' + ' <span class="month_name"></span> ' + '<span class="button next" title="[Page-Down]">&#187;</span>' + '</p>'); this.monthNameSpan = $(".month_name", monthNav); $(".prev", monthNav).click(this.bindToObj(function () { this.moveMonthBy(-1) })); $(".next", monthNav).click(this.bindToObj(function () { this.moveMonthBy(1) })); var yearNav = $('<p class="year_nav">' + '<span class="button prev" title="[Ctrl+Page-Up]">&#171;</span>' + ' <span class="year_name"></span> ' + '<span class="button next" title="[Ctrl+Page-Down]">&#187;</span>' + '</p>'); this.yearNameSpan = $(".year_name", yearNav); $(".prev", yearNav).click(this.bindToObj(function () { this.moveMonthBy(-12) })); $(".next", yearNav).click(this.bindToObj(function () { this.moveMonthBy(12) })); var nav = $('<div class="nav"></div>').append(monthNav, yearNav); var tableShell = "<table><thead><tr>"; $(this.adjustDays(this.short_day_names)).each(function () { tableShell += "<th>" + this + "</th>" }); tableShell += "</tr></thead><tbody></tbody></table>"; this.dateSelector = this.rootLayers = $('<div class="date_selector"></div>').append(nav, tableShell).insertAfter(this.input); if ($.browser.msie && $.browser.version < 7) { this.ieframe = $('<iframe class="date_selector_ieframe" frameborder="0" src="#"></iframe>').insertBefore(this.dateSelector); this.rootLayers = this.rootLayers.add(this.ieframe); $(".button", nav).mouseover(function () { $(this).addClass("hover") }); $(".button", nav).mouseout(function () { $(this).removeClass("hover") }) }; this.tbody = $("tbody", this.dateSelector); this.input.change(this.bindToObj(function () { this.selectDate() })); this.selectDate() }, selectMonth: function (date) { var newMonth = new Date(date.getFullYear(), date.getMonth(), 1); if (!this.currentMonth || !(this.currentMonth.getFullYear() == newMonth.getFullYear() && this.currentMonth.getMonth() == newMonth.getMonth())) { this.currentMonth = newMonth; var rangeStart = this.rangeStart(date), rangeEnd = this.rangeEnd(date); var numDays = this.daysBetween(rangeStart, rangeEnd); var dayCells = ""; for (var i = 0; i <= numDays; i++) { var currentDay = new Date(rangeStart.getFullYear(), rangeStart.getMonth(), rangeStart.getDate() + i, 12, 00); if (this.isFirstDayOfWeek(currentDay)) dayCells += "<tr>"; if (currentDay.getMonth() == date.getMonth()) { dayCells += '<td class="selectable_day" date="' + this.dateToString(currentDay) + '">' + currentDay.getDate() + '</td>' } else { dayCells += '<td class="unselected_month" date="' + this.dateToString(currentDay) + '">' + currentDay.getDate() + '</td>' }; if (this.isLastDayOfWeek(currentDay)) dayCells += "</tr>" }; this.tbody.empty().append(dayCells); this.monthNameSpan.empty().append(this.monthName(date)); this.yearNameSpan.empty().append(this.currentMonth.getFullYear()); $(".selectable_day", this.tbody).click(this.bindToObj(function (event) { this.changeInput($(event.target).attr("date")) })); $("td[date=" + this.dateToString(new Date()) + "]", this.tbody).addClass("today"); $("td.selectable_day", this.tbody).mouseover(function () { $(this).addClass("hover") }); $("td.selectable_day", this.tbody).mouseout(function () { $(this).removeClass("hover") }) }; $('.selected', this.tbody).removeClass("selected"); $('td[date=' + this.selectedDateString + ']', this.tbody).addClass("selected") }, selectDate: function (date) { if (typeof (date) == "undefined") { date = this.stringToDate(this.input.val()) }; if (!date) date = new Date(); this.selectedDate = date; this.selectedDateString = this.dateToString(this.selectedDate); this.selectMonth(this.selectedDate) }, changeInput: function (dateString) { this.input.val(dateString).change(); this.hide() }, show: function () { this.rootLayers.css("display", "block"); $([window, document.body]).click(this.hideIfClickOutside); this.input.unbind("focus", this.show); $(document.body).keydown(this.keydownHandler); this.setPosition() }, hide: function () { this.rootLayers.css("display", "none"); $([window, document.body]).unbind("click", this.hideIfClickOutside); this.input.focus(this.show); $(document.body).unbind("keydown", this.keydownHandler) }, hideIfClickOutside: function (event) { if (event.target != this.input[0] && !this.insideSelector(event)) { this.hide() } }, insideSelector: function (event) { var offset = this.dateSelector.position(); offset.right = offset.left + this.dateSelector.outerWidth(); offset.bottom = offset.top + this.dateSelector.outerHeight(); return event.pageY < offset.bottom && event.pageY > offset.top && event.pageX < offset.right && event.pageX > offset.left }, keydownHandler: function (event) { switch (event.keyCode) { case 9: case 27: this.hide(); return; break; case 13: this.changeInput(this.selectedDateString); break; case 33: this.moveDateMonthBy(event.ctrlKey ? -12 : -1); break; case 34: this.moveDateMonthBy(event.ctrlKey ? 12 : 1); break; case 38: this.moveDateBy(-7); break; case 40: this.moveDateBy(7); break; case 37: this.moveDateBy(-1); break; case 39: this.moveDateBy(1); break; default: return } event.preventDefault() }, stringToDate: function (string) { var matches; if (matches = string.match(/^(\d{1,2}) ([^\s]+) (\d{4,4})$/)) { return new Date(matches[3], this.shortMonthNum(matches[2]), matches[1], 12, 00) } else { return null } }, dateToString: function (date) { return date.getDate() + " " + this.short_month_names[date.getMonth()] + " " + date.getFullYear() }, setPosition: function () { var offset = this.input.offset(); this.rootLayers.css({ top: offset.top + this.input.outerHeight(), left: offset.left }); if (this.ieframe) { this.ieframe.css({ width: this.dateSelector.outerWidth(), height: this.dateSelector.outerHeight() }) } }, moveDateBy: function (amount) { var newDate = new Date(this.selectedDate.getFullYear(), this.selectedDate.getMonth(), this.selectedDate.getDate() + amount); this.selectDate(newDate) }, moveDateMonthBy: function (amount) { var newDate = new Date(this.selectedDate.getFullYear(), this.selectedDate.getMonth() + amount, this.selectedDate.getDate()); if (newDate.getMonth() == this.selectedDate.getMonth() + amount + 1) { newDate.setDate(0) }; this.selectDate(newDate) }, moveMonthBy: function (amount) { var newMonth = new Date(this.currentMonth.getFullYear(), this.currentMonth.getMonth() + amount, this.currentMonth.getDate()); this.selectMonth(newMonth) }, monthName: function (date) { return this.month_names[date.getMonth()] }, bindToObj: function (fn) { var self = this; return function () { return fn.apply(self, arguments) } }, bindMethodsToObj: function () { for (var i = 0; i < arguments.length; i++) { this[arguments[i]] = this.bindToObj(this[arguments[i]]) } }, indexFor: function (array, value) { for (var i = 0; i < array.length; i++) { if (value == array[i]) return i } }, monthNum: function (month_name) { return this.indexFor(this.month_names, month_name) }, shortMonthNum: function (month_name) { return this.indexFor(this.short_month_names, month_name) }, shortDayNum: function (day_name) { return this.indexFor(this.short_day_names, day_name) }, daysBetween: function (start, end) { start = Date.UTC(start.getFullYear(), start.getMonth(), start.getDate()); end = Date.UTC(end.getFullYear(), end.getMonth(), end.getDate()); return (end - start) / 86400000 }, changeDayTo: function (dayOfWeek, date, direction) { var difference = direction * (Math.abs(date.getDay() - dayOfWeek - (direction * 7)) % 7); return new Date(date.getFullYear(), date.getMonth(), date.getDate() + difference) }, rangeStart: function (date) { return this.changeDayTo(this.start_of_week, new Date(date.getFullYear(), date.getMonth()), -1) }, rangeEnd: function (date) { return this.changeDayTo((this.start_of_week - 1) % 7, new Date(date.getFullYear(), date.getMonth() + 1, 0), 1) }, isFirstDayOfWeek: function (date) { return date.getDay() == this.start_of_week }, isLastDayOfWeek: function (date) { return date.getDay() == (this.start_of_week - 1) % 7 }, adjustDays: function (days) { var newDays = []; for (var i = 0; i < days.length; i++) { newDays[i] = days[(i + this.start_of_week) % 7] }; return newDays } }; $.fn.date_input = function (opts) { return this.each(function () { new DateInput(this, opts) }) }; $.date_input = { initialize: function (opts) { $("input.date_input").date_input(opts) } }; return DateInput })(jQuery);
lavajumper/pgmmcfe
www/js/jquery.date_input.pack.js
JavaScript
gpl-2.0
12,327
( function(){ var Promise = function() { var callbacks = []; var result = null; this.then = function(cb) { if(result != null) cb(result); else callbacks.push(cb); return this; }; this.fulfil = function(res) { result = res; for(var i in callbacks) { callbacks[i](result); } } }; window.PDFTeX = function(root) { var worker = new Worker(root+'pdftex.js/release/pdftex-webworker.js'); var promises = []; var self = this; worker.onmessage = function(ev) { var obj; try{ obj = JSON.parse(ev.data); console.log('PDFTeX:', obj); } catch(e) { console.log('PDFTeX:', ev.data); return; } if('id' in obj) promises[obj.id].fulfil(obj); if(obj.cmd) { if(obj.cmd == 'stdout' && typeof(self.on_stdout) === 'function') self.on_stdout(obj.contents) if(obj.cmd == 'stderr' && typeof(self.on_stderr) === 'function') self.on_stderr(obj.contents) } }; this.addUrl = function(real_url, pseudo_path, pseudo_name) { var prom = new Promise(); promises.push(prom); worker.postMessage(JSON.stringify({ cmd: 'addUrl', id: (promises.length-1), real_url: real_url, pseudo_path: pseudo_path, pseudo_name: pseudo_name })); return prom; } this.getFile = function(pseudo_path, pseudo_name) { var prom1 = new Promise(); promises.push(prom1); worker.postMessage(JSON.stringify({ cmd: 'getFile', id: (promises.length-1), pseudo_path: pseudo_path, pseudo_name: pseudo_name })); var prom2 = new Promise(); var chunks = []; prom1.then(function(msg) { var id = msg.chunk_id; chunks[id] = msg.contents; var complete = true; for(var i = 0; i < msg.chunk_count; i++) { if(typeof(chunks[i]) === 'undefined') { complete = false; break; } } if(complete) { prom2.fulfil(chunks.join('')); } }); return prom2; } this.addData = function(contents, pseudo_path, pseudo_name) { var prom = new Promise(); promises.push(prom); worker.postMessage(JSON.stringify({ cmd: 'addData', id: (promises.length-1), contents: contents, pseudo_path: pseudo_path, pseudo_name: pseudo_name })); return prom; } this.compile = function(code) { var prom1 = this.addData(code, '/', 'pdftex-input-file.tex') var prom2 = new Promise(); prom1.then(function() { var prom3 = new Promise(); promises.push(prom3); worker.postMessage(JSON.stringify({ cmd: 'run', id: (promises.length-1), args: ['-no-mktex=tex', '-no-mktex=tfm', '-no-mktex=pk', '-interaction=nonstopmode', '-output-format', 'pdf', '&latex', 'pdftex-input-file.tex'] })); prom3.then(function(obj) {prom2.fulfil(obj)}); }); return prom2; } } })()
manuels/pdftex.js
release/pdftex.js
JavaScript
gpl-2.0
3,238
'use strict'; egdApp .config(function ($stateProvider) { $stateProvider .state('test', { abstract: true, parent: 'site' }); });
esutoniagodesu/egd-web
src/main/webapp/scripts/app/test/test.js
JavaScript
gpl-2.0
201
Ext.define('EscomApp.model.admin.Submodule', { extend : 'Ext.data.Model', fields : [ {name: 'modulo_k', type: 'int'}, {name: 'submodulo_k', type: 'int'}, {name: 'text', type: 'string', mapping: 'nombre'}, {name: 'descripcion', type: 'string'}, {name: 'controlador', type: 'string'}, {name: 'iconCls', type: 'string', mapping: 'icono'} ] });
BucketDev/escom
assets/js/escomapp/model/admin/Submodule.js
JavaScript
gpl-2.0
436
/* * Author: Pleisterman * Info: * Web: www.pleisterman.nl * Mail: info@pleisterman.nl * GitHub: Pleisterman * * Purpose: this module controls the drawing of the mars for the application space invaders * mars is animated along the bottom middle of the screen * * Last revision: 17-05-2015 * * Status: code: ready * comments: ready * memory: ready * development: ready * * NOTICE OF LICENSE * * Copyright (C) 2015 Pleisterman * * 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, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ ( function( gameDevelopment ){ gameDevelopment.marsModule = function() { /* * module marsModule * * functions: * private: * construct called internal * show called by the public function * layoutChange called by the event subscription * animate called by the event subscription * debug * public: * show * * event subscription: * layoutChange called from gameLayoutModule * animate called from gameModule */ // private var self = this; self.MODULE = 'marsModule'; self.debugOn = false; self.visible = false; // visibility self.canvasSurface = null; // canvas surface to draw on self.position = { "top" : 43, // constant percentage of background height "left" : 30.0, // calculated image is placed in middle of the background "height" : 9, // constant percentage of background height "width" : 65 }; // constant percentage of background width self.curveHeight = 9.2; // percentage of background height that the mars will rise up in the middle self.curveOffset = -15; // percentage of background height that the mars will rise up in the middle self.clearRect = { "top" : 0, // px, the rect that the image was drawn in "left" : 0, // px "height" : 0, // px "width" : 0 }; // px self.drawRect = { "top" : 0, // px, the rect that the image is drawn in "left" : 0, // px "height" : 0, // px "width" : 0 }; // px self.globalAlpha = 0.7; // alpha with wicj the image is drawn self.animationStep = -0.02; // space that the image will move per animation step self.animationDelay = 500; // ms self.lastAnimationDate = 0; // save last animation time for delay // functions self.construct = function() { self.debug( 'construct' ); // get the canvas surface to draw on self.canvasSurface = document.getElementById( 'marsDrawLayer' ).getContext( '2d' ); // subscribe to events jsProject.subscribeToEvent( 'animate', self.animate ); jsProject.subscribeToEvent( 'layoutChange', self.layoutChange ); // done subscribe to events }; self.show = function( visible ) { self.visible = visible; if( visible ) { self.debug( 'show' ); // change the layout according to new dimensions self.layoutChange(); } else { // clear the whole canvas self.canvasSurface.clearRect( self.clearRect["left"], self.clearRect["top"], self.clearRect["width"], self.clearRect["height"] ); } }; self.layoutChange = function( ) { if( !self.visible ) { return; } self.debug( 'layoutChange' ); // calculate the draw rect self.drawRect["top"] = ( ( $( '#background' ).height() ) / 100 ) * self.position["top"]; self.drawRect["left"] = ( ( $( '#background' ).width() ) / 100 ) * self.position["left"]; self.drawRect["height"] = ( $( '#background' ).height() / 100 ) * self.position["height"]; self.drawRect["width"] = self.drawRect["height"]; // done calculate the draw rect // animate without delay self.animate( true ); }; self.animate = function( skipDelay ){ if( !self.visible ) { return; } // check for delay var date = new Date(); if( !skipDelay ){ if( date - self.lastAnimationDate < self.animationDelay ){ return; } } // done delay self.lastAnimationDate = date; // clear the canvas surface self.canvasSurface.clearRect( self.clearRect["left"], self.clearRect["top"], self.clearRect["width"], self.clearRect["height"] ); // add movement self.position["left"] += self.animationStep; // reset to first position if( self.position["left"] < -20 ){ self.position["left"] = 120; } self.drawRect["left"] = ( ( $( '#background' ).width() ) / 100 ) * self.position["left"]; // done add the movement // calcultate the curve var curveHeight = ( $( '#background' ).height() / 100 ) * self.curveHeight; curveHeight = ( $( '#background' ).height() / 100 ) * self.curveHeight; // add the curve var top = self.drawRect["top"]; top += Math.abs( Math.sin( ( ( 50 + self.curveOffset ) - self.position["left"] ) / 70 ) ) * curveHeight; // get the image var image = jsProject.getResource( 'mars', 'image' ); // draw the image self.canvasSurface.drawImage( image, 0, 0, image.width, image.height, self.drawRect["left"], top, self.drawRect["width"], self.drawRect["height"] ); // set new clearRect self.clearRect["top"] = top; self.clearRect["left"] = self.drawRect["left"]; self.clearRect["height"] = self.drawRect["height"]; self.clearRect["width"] = self.drawRect["width"]; // done set new clearRect }; // debug self.debug = function( string ) { if( self.debugOn ) { jsProject.debug( self.MODULE + ' ' + string ); } }; // initialize the class self.construct(); // public return { show : function( visible ){ self.show( visible ); } }; }; })( gameDevelopment );
Pleisterman/gameDevelopment
gameDevelopment/spaceInvaders/javascript/marsModule.js
JavaScript
gpl-2.0
8,127
app.factory("Menus", ["WPRest", "SITE_INFO", function(WPRest, SITE_INFO) { //our old friend from bootstrap_play function createHashMap(MenuLinksData) { var menuTree = []; var hash = {}; MenuLinksData.sort(function(x, y) { return x.order > y.order; }); MenuLinksData.forEach(function(link) { //with a small modification //(removes http://{{site root}}/ from link urls) link.url = link.url.replace(SITE_INFO.http_root, ""); // add an array called children to thisData link.children = []; // thisData contains a value of mlid that getting an underscore before the int. And because we are in a for each loop // it will add to every mlid's value in thisData. The underscore make mlid to a string. // Now we make sure mlid is a key and by make it a string secure the key from "math" problems. hash["_"+link.ID] = link; // if i am top level, add to tree right away if(link.parent === 0){ //remember: menuTree.push(link); return; } }); //then add children to all menu_links using the hash map //(so we don't have to loop through any number of sublevels) for(var i in hash){ link = hash[i]; //if no parent (no parent), skip this iteration of the loop if(link.parent === 0){continue;} //add me to menuTree using the hash map "shortcut" to each link hash["_"+link.parent].children.push(link); } return menuTree; } //the callback function for GET requests with a menuId //that converts menu.items from a "flat" array into a tree function prepareMenu(menuObj) { menuObj.items = createHashMap(menuObj.items); return menuObj; } //our factory object var menuObject = { get : function(menuId) { var callUrl = menuId ? "/menus/" + menuId : "/menus"; var broadcastInstructions = menuId ? //only use callback function if we are asking to a specific menu //using a menuId { broadcastName : "gotMenuLinks", callback: prepareMenu } : //else only provide the broadcast name "gotMenus"; WPRest.restCall(callUrl, "GET", {}, broadcastInstructions); } }; return menuObject; }]);
moller-g-peter/sellforce
wp-content/themes/ngTheme-master/js/services/menufactory.js
JavaScript
gpl-2.0
2,271
/** * Custom Media Library modal window interaction * * @package SlideDeck * @author dtelepathy * @version 1.0.0 */ var SlideDeckMediaLibrary = function(){ // Class for single add buttons this.singleAddClass = "add-to-slidedeck-button"; // ID for multi add button this.addAllId = "slidedeck-add-all-images"; // ID for add-selected button this.addSelectedId = "slidedeck-add-selected-images"; // Class for add multiple checkboxes this.addMultipleCheckboxClass = "slidedeck-add-multiple"; // Buttons used by this Class this.buttons = {}; // Current Add Media tab this.tab = "upload"; // Image container on parent document this.imageContainer; // Content Source Flyout this.contentSource; // Initiate Class this.__construct(); }; (function($){ // Class construct routine SlideDeckMediaLibrary.prototype.__construct = function(){ var self = this; // This isn't a SlideDeck media upload, do NOT process further if(!parent.document.location.search.match(/page\=slidedeck2\.php/)) return false; if(parent.jQuery('input[name="source"]').val() != "medialibrary") return false; $(document).ready(function(){ self.initialize(); }); }; // Add images to the SlideDeck - accepts a single ID or an array of IDs SlideDeckMediaLibrary.prototype.addImages = function(mediaIds){ var self = this; // Convert a single ID to an array for consistent data submission if(!$.isArray(mediaIds)){ mediaIds = [mediaIds]; } var queryString = 'action=slidedeck_medialibrary_add_images'; for (var i=0; i < mediaIds.length; i++) { queryString += '&media[]=' + mediaIds[i]; }; queryString += '&_wpnonce=' + _medialibrary_nonce; $.ajax({ url: ajaxurl, data: queryString, success: function(data){ // Add the images self.imageContainer.append(data); // Hide the flyout self.contentSource.addClass('hidden'); // Close the Thickbox parent.tb_remove(); // Update the preview parent.SlideDeckPreview.ajaxUpdate(); } }); }; // Bind all submission events to appropriate buttons SlideDeckMediaLibrary.prototype.bind = function(){ var self = this; $('body').delegate('.' + this.singleAddClass, 'click', function(event){ event.preventDefault(); var mediaId = $.data(this, 'mediaId'); self.addImages(mediaId); }); $('#' + this.addAllId).bind('click', function(event){ event.preventDefault(); var mediaIds = []; $('.' + self.singleAddClass).each(function(ind){ var mediaId = $.data(this, 'mediaId'); mediaIds.push(mediaId); }); self.addImages(mediaIds); }); $('#' + this.addSelectedId).bind('click', function(event){ event.preventDefault(); var mediaIds = []; $('.' + self.addMultipleCheckboxClass).each(function(ind){ if(this.checked) mediaIds.push(this.value); }); self.addImages(mediaIds); }); }; // Route which tab initialize routine to run SlideDeckMediaLibrary.prototype.initialize = function(){ // Get the current tab var location = document.location.search.match(/tab\=([a-zA-Z0-9\-_]+)/); if(location) this.tab = location[1]; this.imageContainer = parent.jQuery('#slidedeck-medialibrary-images'); this.contentSource = parent.jQuery('#slidedeck-content-source'); // Hide the gallery tab to prevent confusion $('#tab-gallery').remove(); // Hide the from URL tab since we can't accommodate for this $('#tab-type_url').remove(); switch(this.tab){ case "upload": case "type": this.tabUpload(); break; case "library": this.tabLibrary(); break; } }; // Method for replacing "Insert into Post" buttons with "Add to SlideDeck" buttons SlideDeckMediaLibrary.prototype.replaceButton = function(el){ var $button = $(el); var buttonId = $button.attr('id'); var mediaId = buttonId.match(/\[(\d+)\]/)[1]; $button.replaceWith('<input type="button" id="' + buttonId + '" class="button add-to-slidedeck-button" value="Add to SlideDeck" />'); // Map the mediaId for the image as a data property for access later $.data(document.getElementById(buttonId), 'mediaId', mediaId); }; // Media Library tab SlideDeckMediaLibrary.prototype.tabLibrary = function(){ var self = this; var $mediaItems = $('#media-items'); var $buttons = $mediaItems.find('input[type="submit"]'); $buttons.each(function(ind){ self.replaceButton(this); }); $mediaItems.find('.toggle.describe-toggle-on').each(function(){ var $this = $(this); var mediaId = $this.closest('.media-item').attr('id').split('-')[2]; $this.before('<input type="checkbox" value="' + mediaId + '" class="' + self.addMultipleCheckboxClass + '" style="float:right;margin:12px 15px 0 5px;" />'); }); $mediaItems.find('.media-item:first-child').before('<p style="margin:5px;text-align:right;"><label style="margin-right:8px;font-weight:bold;font-style:italic;">Select All to add to SlideDeck <input type="checkbox" id="slidedeck-add-multiple-select-all" style="margin-left:5px;" /></label></p>'); $('#slidedeck-add-multiple-select-all').bind('click', function(event){ var selectAll = this; $mediaItems.find('.' + self.addMultipleCheckboxClass).each(function(){ this.checked = selectAll.checked; }); }); $('.ml-submit').append('<a href="#" id="' + this.addSelectedId + '" class="button" style="margin-left: 10px;">Add Selected to SlideDeck</a>'); this.bind(); }; // Upload tab SlideDeckMediaLibrary.prototype.tabUpload = function(){ $('.savebutton.ml-submit').append('<a href="#" id="' + this.addAllId + '" class="button" style="margin-left: 10px;">Add all to SlideDeck</a>'); new this.Watcher('image-form'); this.bind(); }; // Watcher Class for Upload tab - watches for addition of "Insert into Post" buttons to replace them SlideDeckMediaLibrary.prototype.Watcher = function(el){ var self = this; this.el = document.getElementById(el); this.getButtons = function(){ var inputs = self.el.getElementsByTagName('input'), count = 0, buttons = []; for(var i in inputs){ if(inputs[i].type == "submit" && inputs[i].id.match(/send\[(\d+)\]/)){ buttons.push(inputs[i]); } } return buttons; }; this.checker = function(){ var buttons = self.getButtons(); for(var b in buttons){ SlideDeckMediaLibrary.prototype.replaceButton(buttons[b]); } }; this.interval = setInterval(this.checker, 100); }; new SlideDeckMediaLibrary(); })(jQuery);
rigelstpierre/Everlovin-Press
wp-content/plugins/slidedeck2-pro/decks/image/medialibrary.js
JavaScript
gpl-2.0
8,235
var url = require('url') , querystring = require('querystring'); module.exports = function(rules) { 'use strict'; rules = (rules || []).map(function(rule) { var parts = rule.replace(/\s+|\t+/g, ' ').split(' '); var flags = '', flagRegex = /\[(.*)\]$/; if(flagRegex.test(rule)) { flags = flagRegex.exec(rule)[1]; } // Check inverted urls var inverted = parts[0].substr(0,1) === '!'; if(inverted) { parts[0] = parts[0].substr(1); } return { regex : typeof parts[2] !== 'undefined' && /NC/.test(flags) ? new RegExp(parts[0], 'i') : new RegExp(parts[0]), replace : parts[1], inverted : inverted, last : /L/.test(flags), proxy : /P/.test(flags), redirect : /R=?(\d+)?/.test(flags) ? (typeof /R=?(\d+)?/.exec(flags)[1] !== 'undefined' ? /R=?(\d+)?/.exec(flags)[1] : 301) : false, forbidden : /F/.test(flags), gone : /G/.test(flags), type : /T=([\w|\/]+)/.test(flags) ? (typeof /T=([\w|\/]+)/.exec(flags)[1] !== 'undefined' ? /T=([\w|\/]+)/.exec(flags)[1] : 'text/plain') : false, }; }); return function(req, res, next) { var protocol = req.connection.encrypted ? 'https' : 'http' , request = require(protocol).request , _next = true; rules.some(function(rewrite) { var location = protocol + '://' + req.headers.host + req.url.replace(rewrite.regex, rewrite.replace); // Rewrite Url if(rewrite.regex.test(req.url) && rewrite.type) { res.setHeader('Content-Type', rewrite.type); } if(rewrite.regex.test(req.url) && rewrite.gone) { res.writeHead(410); res.end(); _next = false; return true; } else if(rewrite.regex.test(req.url) && rewrite.forbidden) { res.writeHead(403); res.end(); _next = false; return true; } else if(rewrite.regex.test(req.url) && rewrite.proxy) { var opts = url.parse(req.url.replace(rewrite.regex, rewrite.replace)); var query = (opts.search != null) ? opts.search : ''; if(query === '') { opts.path = opts.pathname; } else { opts.path = opts.pathname + '/' + query; } opts.method = req.method; opts.headers = req.headers; var via = '1.1 ' + require('os').hostname(); if(req.headers.via) { via = req.headers.via + ', ' + via; } opts.headers.via = via; delete opts.headers['host']; var _req = request(opts, function (_res) { _res.headers.via = via; res.writeHead(_res.statusCode, _res.headers); _res.on('error', function (err) { next(err); }); _res.pipe(res); }); _req.on('error', function (err) { next(err); }); if(!req.readable) { _req.end(); } else { req.pipe(_req); } _next = false; return true; } else if(rewrite.regex.test(req.url) && rewrite.redirect) { res.writeHead(rewrite.redirect, { Location : location }); res.end(); _next = false; return true; } else if(!rewrite.regex.test(req.url) && rewrite.inverted) { res.setHeader('Location', location); req.url = rewrite.replace; return rewrite.last; } else if(rewrite.regex.test(req.url) && !rewrite.inverted) { res.setHeader('Location', location); req.url = req.url.replace(rewrite.regex, rewrite.replace); return rewrite.last; } }); // Add to query object if(/\?.*/.test(req.url)) { req.params = req.query = querystring.parse(/\?(.*)/.exec(req.url)[1]); } if(_next) { next(); } }; }
localnerve/wpspa
node_modules/connect-modrewrite/src/modrewrite.js
JavaScript
gpl-2.0
3,873
(function($){ $(window).load(function(){ var _p="mPS2id", _o=mPS2id_params; for(var i=0; i<_o.total_instances; i++){ var shortcodeClass=_o.shortcode_class; // Shortcode without suffix //var shortcodeClass=_o.shortcode_class+"_"+(i+1); // Shortcode with suffix $(_o.instances[_p+"_instance_"+i]["selector"]["value"]+",."+shortcodeClass).mPageScroll2id({ scrollSpeed:_o.instances[_p+"_instance_"+i]["scrollSpeed"]["value"], autoScrollSpeed:(_o.instances[_p+"_instance_"+i]["autoScrollSpeed"]["value"] === "true") ? true : false, scrollEasing:_o.instances[_p+"_instance_"+i]["scrollEasing"]["value"], scrollingEasing:_o.instances[_p+"_instance_"+i]["scrollingEasing"]["value"], pageEndSmoothScroll:(_o.instances[_p+"_instance_"+i]["pageEndSmoothScroll"]["value"] === "true") ? true : false, layout:_o.instances[_p+"_instance_"+i]["layout"]["value"], offset:_o.instances[_p+"_instance_"+i]["offset"]["value"], highlightSelector:_o.instances[_p+"_instance_"+i]["highlightSelector"]["value"], clickedClass:_o.instances[_p+"_instance_"+i]["clickedClass"]["value"], targetClass:_o.instances[_p+"_instance_"+i]["targetClass"]["value"], highlightClass:_o.instances[_p+"_instance_"+i]["highlightClass"]["value"], forceSingleHighlight:(_o.instances[_p+"_instance_"+i]["forceSingleHighlight"]["value"] === "true") ? true : false }); } }); })(jQuery);
afhall/uSamp
wp-content/plugins/page-scroll-to-id/js/jquery.malihu.PageScroll2id-init.js
JavaScript
gpl-2.0
1,433
export function getConfiguredTitanMailboxCount( domain ) { return domain.titanMailSubscription?.numberOfMailboxes ?? 0; }
Automattic/wp-calypso
client/lib/titan/get-configured-titan-mailbox-count.js
JavaScript
gpl-2.0
123
var QrValidation = function() { }; QrValidation.prototype.stringExtractor = function(string){ container = string.split(','); return container; }; QrValidation.prototype.postcodeValidator = function(postcode){ if (postcodeCounter(postcode) == true && postcodeSplitter(postcode) == true){ return true; } else { return false; } }; function postcodeSplitter (postcode){ parts = {}; // get the first three letters of the postcode parts.part1 = postcode.substring(0,3); // get the last three letters of the postcode parts.part2 = postcode.substring(3); if (postcodeLetterCheckPartOne(parts.part1) && postcodeLetterCheckPartTwo(parts.part2)) { return true; } else { return false; } }; function postcodeCounter(postcode) { if(postcode.length == 6 || postcode.length == 7){ return true; } else { return false; } }; function postcodeLetterCheckPartOne(postcode){ if(postcode.charAt(0).constructor == String && postcode.charAt(1).constructor == String && parseInt(postcode.charAt(2)) == true){ return true; } else { return false; } }; function postcodeLetterCheckPartTwo(postcode){ if(postcode.length == 3){ if(parseInt(postcode.charAt(0)) && postcode.charAt(1).constructor == String && postcode.charAt(2).constructor == String){ return true; } else { return false; } } else if (postcode.length == 4) { if(parseInt(postcode.charAt(0)) && parseInt(postcode.charAt(1)) && postcode.charAt(2).constructor == String && postcode.charAt(3).constructor == String){ return true; } else { return false; } } else { return false; } };
lukeexton96/Postcode-Validator
QR-Format_validations/src/QrValidations.js
JavaScript
gpl-2.0
1,583
define("dc/boardevents",[],function(){ return function(board){ var events=this.events={}; this.on=board.on=function(event,callback){ if(!events[event]) events[event]=[]; events[event].push(callback); } this.send=function(event){ if(!events[event]) return; var args=Array.prototype.slice.call(arguments,1); this.events[event].forEach(function(callback){ callback.apply(null,args); }); } }});
KaltZK/drawcraft
static/script/dc/boardevents.js
JavaScript
gpl-2.0
551
jQuery(function($){ var BRUSHED = window.BRUSHED || {}; /* ================================================== Mobile Navigation ================================================== */ var mobileMenuClone = $('#menu').clone().attr('id', 'navigation-mobile'); BRUSHED.mobileNav = function(){ var windowWidth = $(window).width(); if( windowWidth <= 979 ) { if( $('#mobile-nav').length > 0 ) { mobileMenuClone.insertAfter('#menu'); $('#navigation-mobile #menu-nav').attr('id', 'menu-nav-mobile'); } } else { $('#navigation-mobile').css('display', 'none'); if ($('#mobile-nav').hasClass('open')) { $('#mobile-nav').removeClass('open'); } } } BRUSHED.listenerMenu = function(){ $('#mobile-nav').on('click', function(e){ $(this).toggleClass('open'); if ($('#mobile-nav').hasClass('open')) { $('#navigation-mobile').slideDown(500, 'easeOutExpo'); } else { $('#navigation-mobile').slideUp(500, 'easeOutExpo'); } e.preventDefault(); }); $('#menu-nav-mobile a').on('click', function(){ $('#mobile-nav').removeClass('open'); $('#navigation-mobile').slideUp(350, 'easeOutExpo'); }); } /* ================================================== Slider Options ================================================== */ BRUSHED.slider = function(){ $.supersized({ // Functionality slideshow : 1, // Slideshow on/off autoplay : 1, // Slideshow starts playing automatically start_slide : 1, // Start slide (0 is random) stop_loop : 0, // Pauses slideshow on last slide random : 0, // Randomize slide order (Ignores start slide) slide_interval : 12000, // Length between transitions transition : 1, // 0-None, 1-Fade, 2-Slide Top, 3-Slide Right, 4-Slide Bottom, 5-Slide Left, 6-Carousel Right, 7-Carousel Left transition_speed : 300, // Speed of transition new_window : 1, // Image links open in new window/tab pause_hover : 0, // Pause slideshow on hover keyboard_nav : 1, // Keyboard navigation on/off performance : 1, // 0-Normal, 1-Hybrid speed/quality, 2-Optimizes image quality, 3-Optimizes transition speed // (Only works for Firefox/IE, not Webkit) image_protect : 1, // Disables image dragging and right click with Javascript // Size & Position min_width : 0, // Min width allowed (in pixels) min_height : 0, // Min height allowed (in pixels) vertical_center : 1, // Vertically center background horizontal_center : 1, // Horizontally center background fit_always : 0, // Image will never exceed browser width or height (Ignores min. dimensions) fit_portrait : 1, // Portrait images will not exceed browser height fit_landscape : 0, // Landscape images will not exceed browser width // Components slide_links : 'blank', // Individual links for each slide (Options: false, 'num', 'name', 'blank') thumb_links : 0, // Individual thumb links for each slide thumbnail_navigation : 0, // Thumbnail navigation slides : [ // Slideshow Images {image : '_include/img/slider-images/image01.jpg', title : '<div class="slide-content">Brushed</div>', thumb : '', url : ''}, {image : '_include/img/slider-images/image02.jpg', title : '<div class="slide-content">Brushed</div>', thumb : '', url : ''}, {image : '_include/img/slider-images/image03.jpg', title : '<div class="slide-content">Brushed</div>', thumb : '', url : ''}, {image : '_include/img/slider-images/image04.jpg', title : '<div class="slide-content">Brushed</div>', thumb : '', url : ''} ], // Theme Options progress_bar : 0, // Timer for each slide mouse_scrub : 0 }); } /* ================================================== Navigation Fix ================================================== */ BRUSHED.nav = function(){ $('.sticky-nav').waypoint('sticky'); } /* ================================================== Filter Works ================================================== */ BRUSHED.filter = function (){ if($('#projects').length > 0){ var $container = $('#projects'); $container.isotope({ // options animationEngine: 'best-available', itemSelector : '.item-thumbs', layoutMode : 'fitRows' }); // filter items when filter link is clicked var $optionSets = $('#options .option-set'), $optionLinks = $optionSets.find('a'); $optionLinks.click(function(){ var $this = $(this); // don't proceed if already selected if ( $this.hasClass('selected') ) { return false; } var $optionSet = $this.parents('.option-set'); $optionSet.find('.selected').removeClass('selected'); $this.addClass('selected'); // make option object dynamically, i.e. { filter: '.my-filter-class' } var options = {}, key = $optionSet.attr('data-option-key'), value = $this.attr('data-option-value'); // parse 'false' as false boolean value = value === 'false' ? false : value; options[ key ] = value; if ( key === 'layoutMode' && typeof changeLayoutMode === 'function' ) { // changes in layout modes need extra logic changeLayoutMode( $this, options ) } else { // otherwise, apply new options $container.isotope( options ); } return false; }); } } /* ================================================== FancyBox ================================================== */ BRUSHED.fancyBox = function(){ if($('.fancybox').length > 0 || $('.fancybox-media').length > 0 || $('.fancybox-various').length > 0){ $(".fancybox").fancybox({ padding : 0, beforeShow: function () { this.title = $(this.element).attr('title'); this.title = '<h4>' + this.title + '</h4>' + '<p>' + $(this.element).parent().find('img').attr('alt') + '</p>'; }, helpers : { title : { type: 'inside' }, } }); $('.fancybox-media').fancybox({ openEffect : 'none', closeEffect : 'none', helpers : { media : {} } }); } } /* ================================================== Contact Form ================================================== */ BRUSHED.contactForm = function(){ $("#contact-submit").on('click',function() { $contact_form = $('#contact-form'); var fields = $contact_form.serialize(); $.ajax({ type: "POST", url: "_include/php/contact.php", data: fields, dataType: 'json', success: function(response) { if(response.status){ $('#contact-form input').val(''); $('#contact-form textarea').val(''); } $('#response').empty().html(response.html); } }); return false; }); } /* ================================================== Twitter Feed ================================================== */ BRUSHED.tweetFeed = function(){ var valueTop = -64; $("#ticker").tweet({ username: "Bluxart", page: 1, avatar_size: 0, count: 10, template: "{text}{time}", filter: function(t){ return ! /^@\w+/.test(t.tweet_raw_text); }, loading_text: "loading ..." }).bind("loaded", function() { var ul = $(this).find(".tweet_list"); var ticker = function() { setTimeout(function() { ul.find('li:first').animate( {marginTop: valueTop + 'px'}, 500, 'linear', function() { $(this).detach().appendTo(ul).removeAttr('style'); }); ticker(); }, 5000); }; ticker(); }); } /* ================================================== Menu Highlight ================================================== */ BRUSHED.menu = function(){ $('#menu-nav, #menu-nav-mobile').onePageNav({ currentClass: 'current', changeHash: false, scrollSpeed: 750, scrollOffset: 30, scrollThreshold: 0.5, easing: 'easeOutExpo', filter: ':not(.external)' }); } /* ================================================== Next Section ================================================== */ BRUSHED.goSection = function(){ $('#nextsection').on('click', function(){ $target = $($(this).attr('href')).offset().top-30; $('body, html').animate({scrollTop : $target}, 750, 'easeOutExpo'); return false; }); } /* ================================================== GoUp ================================================== */ BRUSHED.goUp = function(){ $('#goUp').on('click', function(){ $target = $($(this).attr('href')).offset().top-30; $('body, html').animate({scrollTop : $target}, 750, 'easeOutExpo'); return false; }); } /* ================================================== Scroll to Top ================================================== */ BRUSHED.scrollToTop = function(){ var windowWidth = $(window).width(), didScroll = false; var $arrow = $('#back-to-top'); $arrow.click(function(e) { $('body,html').animate({ scrollTop: "0" }, 750, 'easeOutExpo' ); e.preventDefault(); }) $(window).scroll(function() { didScroll = true; }); setInterval(function() { if( didScroll ) { didScroll = false; if( $(window).scrollTop() > 1000 ) { $arrow.css('display', 'block'); } else { $arrow.css('display', 'none'); } } }, 250); } /* ================================================== Thumbs / Social Effects ================================================== */ BRUSHED.utils = function(){ $('.item-thumbs').bind('touchstart', function(){ $(".active").removeClass("active"); $(this).addClass('active'); }); $('.image-wrap').bind('touchstart', function(){ $(".active").removeClass("active"); $(this).addClass('active'); }); $('#social ul li').bind('touchstart', function(){ $(".active").removeClass("active"); $(this).addClass('active'); }); } /* ================================================== Accordion ================================================== */ BRUSHED.accordion = function(){ var accordion_trigger = $('.accordion-heading.accordionize'); accordion_trigger.delegate('.accordion-toggle','click', function(event){ if($(this).hasClass('active')){ $(this).removeClass('active'); $(this).addClass('inactive'); } else{ accordion_trigger.find('.active').addClass('inactive'); accordion_trigger.find('.active').removeClass('active'); $(this).removeClass('inactive'); $(this).addClass('active'); } event.preventDefault(); }); } /* ================================================== Toggle ================================================== */ BRUSHED.toggle = function(){ var accordion_trigger_toggle = $('.accordion-heading.togglize'); accordion_trigger_toggle.delegate('.accordion-toggle','click', function(event){ if($(this).hasClass('active')){ $(this).removeClass('active'); $(this).addClass('inactive'); } else{ $(this).removeClass('inactive'); $(this).addClass('active'); } event.preventDefault(); }); } /* ================================================== Tooltip ================================================== */ BRUSHED.toolTip = function(){ $('a[data-toggle=tooltip]').tooltip(); } /* ================================================== Init ================================================== */ BRUSHED.slider(); $(document).ready(function(){ Modernizr.load([ { test: Modernizr.placeholder, nope: '_include/js/placeholder.js', complete : function() { if (!Modernizr.placeholder) { Placeholders.init({ live: true, hideOnFocus: false, className: "yourClass", textColor: "#999" }); } } } ]); // Preload the page with jPreLoader $('body').jpreLoader({ splashID: "#jSplash", showSplash: true, showPercentage: true, autoClose: true, splashFunction: function() { $('#circle').delay(250).animate({'opacity' : 1}, 500, 'linear'); } }); BRUSHED.nav(); BRUSHED.mobileNav(); BRUSHED.listenerMenu(); BRUSHED.menu(); BRUSHED.goSection(); BRUSHED.goUp(); BRUSHED.filter(); BRUSHED.fancyBox(); BRUSHED.contactForm(); BRUSHED.tweetFeed(); BRUSHED.scrollToTop(); BRUSHED.utils(); BRUSHED.accordion(); BRUSHED.toggle(); BRUSHED.toolTip(); }); $(window).resize(function(){ BRUSHED.mobileNav(); }); });
sudocoda/crimzonbeats_onepage
v3/_include/js/main.js
JavaScript
gpl-2.0
12,367
/** * DO NOT EDIT THIS FILE. * See the following change record for more information, * https://www.drupal.org/node/2815083 * @preserve **/ (function ($, Drupal, window) { Drupal.MediaLibrary = { currentSelection: [] }; Drupal.AjaxCommands.prototype.updateMediaLibrarySelection = function (ajax, response, status) { Object.values(response.mediaIds).forEach(function (value) { Drupal.MediaLibrary.currentSelection.push(value); }); }; Drupal.behaviors.MediaLibraryWidgetWarn = { attach: function attach(context) { $('.js-media-library-item a[href]', context).once('media-library-warn-link').on('click', function (e) { var message = Drupal.t('Unsaved changes to the form will be lost. Are you sure you want to leave?'); var confirmation = window.confirm(message); if (!confirmation) { e.preventDefault(); } }); } }; Drupal.behaviors.MediaLibraryTabs = { attach: function attach(context) { var $menu = $('.js-media-library-menu'); $menu.find('a', context).once('media-library-menu-item').on('click', function (e) { e.preventDefault(); e.stopPropagation(); var ajaxObject = Drupal.ajax({ wrapper: 'media-library-content', url: e.currentTarget.href, dialogType: 'ajax', progress: { type: 'fullscreen', message: Drupal.t('Please wait...') } }); ajaxObject.success = function (response, status) { var _this = this; if (this.progress.element) { $(this.progress.element).remove(); } if (this.progress.object) { this.progress.object.stopMonitoring(); } $(this.element).prop('disabled', false); Object.keys(response || {}).forEach(function (i) { if (response[i].command && _this.commands[response[i].command]) { _this.commands[response[i].command](_this, response[i], status); } }); document.getElementById('media-library-content').focus(); this.settings = null; }; ajaxObject.execute(); $menu.find('.active-tab').remove(); $menu.find('a').removeClass('active'); $(e.currentTarget).addClass('active').html(Drupal.t('@title<span class="active-tab visually-hidden"> (active tab)</span>', { '@title': $(e.currentTarget).html() })); }); } }; Drupal.behaviors.MediaLibraryViewsDisplay = { attach: function attach(context) { var $view = $(context).hasClass('.js-media-library-view') ? $(context) : $('.js-media-library-view', context); $view.closest('.views-element-container').attr('id', 'media-library-view'); $('.views-display-link-widget, .views-display-link-widget_table', context).once('media-library-views-display-link').on('click', function (e) { e.preventDefault(); e.stopPropagation(); var $link = $(e.currentTarget); var loadingAnnouncement = ''; var displayAnnouncement = ''; var focusSelector = ''; if ($link.hasClass('views-display-link-widget')) { loadingAnnouncement = Drupal.t('Loading grid view.'); displayAnnouncement = Drupal.t('Changed to grid view.'); focusSelector = '.views-display-link-widget'; } else if ($link.hasClass('views-display-link-widget_table')) { loadingAnnouncement = Drupal.t('Loading table view.'); displayAnnouncement = Drupal.t('Changed to table view.'); focusSelector = '.views-display-link-widget_table'; } var ajaxObject = Drupal.ajax({ wrapper: 'media-library-view', url: e.currentTarget.href, dialogType: 'ajax', progress: { type: 'fullscreen', message: loadingAnnouncement || Drupal.t('Please wait...') } }); if (displayAnnouncement || focusSelector) { var success = ajaxObject.success; ajaxObject.success = function (response, status) { success.bind(this)(response, status); if (focusSelector) { $(focusSelector).focus(); } if (displayAnnouncement) { Drupal.announce(displayAnnouncement); } }; } ajaxObject.execute(); if (loadingAnnouncement) { Drupal.announce(loadingAnnouncement); } }); } }; Drupal.behaviors.MediaLibraryItemSelection = { attach: function attach(context, settings) { var $form = $('.js-media-library-views-form, .js-media-library-add-form', context); var currentSelection = Drupal.MediaLibrary.currentSelection; if (!$form.length) { return; } var $mediaItems = $('.js-media-library-item input[type="checkbox"]', $form); function disableItems($items) { $items.prop('disabled', true).closest('.js-media-library-item').addClass('media-library-item--disabled'); } function enableItems($items) { $items.prop('disabled', false).closest('.js-media-library-item').removeClass('media-library-item--disabled'); } function updateSelectionCount(remaining) { var selectItemsText = remaining < 0 ? Drupal.formatPlural(currentSelection.length, '1 item selected', '@count items selected') : Drupal.formatPlural(remaining, '@selected of @count item selected', '@selected of @count items selected', { '@selected': currentSelection.length }); $('.js-media-library-selected-count').html(selectItemsText); } $mediaItems.once('media-item-change').on('change', function (e) { var id = e.currentTarget.value; var position = currentSelection.indexOf(id); if (e.currentTarget.checked) { if (position === -1) { currentSelection.push(id); } } else if (position !== -1) { currentSelection.splice(position, 1); } $form.find('#media-library-modal-selection').val(currentSelection.join()).trigger('change'); $('.js-media-library-add-form-current-selection').val(currentSelection.join()); }); $('#media-library-modal-selection', $form).once('media-library-selection-change').on('change', function (e) { updateSelectionCount(settings.media_library.selection_remaining); if (currentSelection.length === settings.media_library.selection_remaining) { disableItems($mediaItems.not(':checked')); enableItems($mediaItems.filter(':checked')); } else { enableItems($mediaItems); } }); currentSelection.forEach(function (value) { $form.find('input[type="checkbox"][value="' + value + '"]').prop('checked', true).trigger('change'); }); $(window).once('media-library-selection-info').on('dialog:aftercreate', function () { var $buttonPane = $('.media-library-widget-modal .ui-dialog-buttonpane'); if (!$buttonPane.length) { return; } $buttonPane.append(Drupal.theme('mediaLibrarySelectionCount')); updateSelectionCount(settings.media_library.selection_remaining); }); } }; Drupal.behaviors.MediaLibraryModalClearSelection = { attach: function attach() { $(window).once('media-library-clear-selection').on('dialog:afterclose', function () { Drupal.MediaLibrary.currentSelection = []; }); } }; Drupal.theme.mediaLibrarySelectionCount = function () { return '<div class="media-library-selected-count js-media-library-selected-count" role="status" aria-live="polite" aria-atomic="true"></div>'; }; })(jQuery, Drupal, window);
gitkyo/tamtam
core/modules/media_library/js/media_library.ui.js
JavaScript
gpl-2.0
7,770
/* * 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.fun"); doh.register("citeproc_js.fun", [ function testInstantiation() { function testme () { try { var obj = new CSL.Engine.Fun(); return "Success"; } catch (e) { return e; } } var res = testme(); doh.assertEqual( "Success", res ); }, ]);
co-alliance/adr
sites/all/modules/islandora_contrib/islandora_scholar/modules/citeproc/lib/citeproc-js/tests/citeproc-js/fun.js
JavaScript
gpl-2.0
2,584
var searchData= [ ['j',['j',['../class_m_matrix.html#aac8360b87dde4abf36fc5993594adf87',1,'MMatrix']]] ];
DruggedBunny/openb3d.mod
openb3d.mod/html/search/variables_9.js
JavaScript
gpl-2.0
108
var searchData= [ ['reset',['reset',['../interface_a_f_d_x_detector.html#a854270927a6a4c95ea9953507dcde899',1,'AFDXDetector']]] ];
Affectiva/developerportal
pages/platforms/v3/ios/classdocs/search/functions_4.js
JavaScript
gpl-2.0
133
/** * Created by faiz on 11/25/15. */
faizulhaque/oyster-auth
lib/middlewares/index.js
JavaScript
gpl-2.0
40
/** * @file * A JavaScript file for the theme. * * In order for this JavaScript to be loaded on pages, see the instructions in * the README.txt next to this file. */ // JavaScript should be made compatible with libraries other than jQuery by // wrapping it with an "anonymous closure". See: // - https://drupal.org/node/1446420 // - http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth (function ($, Drupal, window, document, undefined) { // To understand behaviors, see https://drupal.org/node/756722#behaviors Drupal.behaviors.my_custom_behavior = { attach: function(context, settings) { //CHECK BANNER FOR BACKGROUND IMAGE $(document).ready(function(){ if ($('.banner').css('background-image') != 'none') { $('body').addClass('bg-image'); } }); //EQUAL HEIGHT $(document).ready(function(){ /* homepage highlights */ $('.front .panel-3col-33-stacked .center-wrapper .panel-panel .inside').matchHeight(); }); //COLORBOX $(document).ready(function(){ /* open $('.front #cbtrigger').trigger( "click" ); */ /* close */ $('#colorbox .cbox-close').click(function(){ $('#cboxClose').trigger( "click" ); }); }); //CHECK FOR MAINTENANCE MODE $(document).ready(function(){ $('body.maintenance-page').parent('html').addClass('no-bg'); }); } }; })(jQuery, Drupal, this, this.document);
stevepolitodesign/cjv
sites/all/themes/cjv/js/script.js
JavaScript
gpl-2.0
1,435
/* * Kendo UI v2015.2.624 (http://www.telerik.com/kendo-ui) * Copyright 2015 Telerik AD. All rights reserved. * * Kendo UI commercial licenses may be obtained at * http://www.telerik.com/purchase/license-agreement/kendo-ui-complete * If you do not own a commercial license, this file shall be governed by the trial license terms. */ (function(f, define){ define([ "./kendo.core", "./kendo.userevents" ], f); })(function(){ (function($, undefined) { var kendo = window.kendo, Widget = kendo.ui.Widget, proxy = $.proxy, abs = Math.abs, MAX_DOUBLE_TAP_DISTANCE = 20; var Touch = Widget.extend({ init: function(element, options) { var that = this; Widget.fn.init.call(that, element, options); options = that.options; element = that.element; that.wrapper = element; function eventProxy(name) { return function(e) { that._triggerTouch(name, e); }; } function gestureEventProxy(name) { return function(e) { that.trigger(name, { touches: e.touches, distance: e.distance, center: e.center, event: e.event }); }; } that.events = new kendo.UserEvents(element, { filter: options.filter, surface: options.surface, minHold: options.minHold, multiTouch: options.multiTouch, allowSelection: true, press: eventProxy("touchstart"), hold: eventProxy("hold"), tap: proxy(that, "_tap"), gesturestart: gestureEventProxy("gesturestart"), gesturechange: gestureEventProxy("gesturechange"), gestureend: gestureEventProxy("gestureend") }); if (options.enableSwipe) { that.events.bind("start", proxy(that, "_swipestart")); that.events.bind("move", proxy(that, "_swipemove")); } else { that.events.bind("start", proxy(that, "_dragstart")); that.events.bind("move", eventProxy("drag")); that.events.bind("end", eventProxy("dragend")); } kendo.notify(that); }, events: [ "touchstart", "dragstart", "drag", "dragend", "tap", "doubletap", "hold", "swipe", "gesturestart", "gesturechange", "gestureend" ], options: { name: "Touch", surface: null, global: false, multiTouch: false, enableSwipe: false, minXDelta: 30, maxYDelta: 20, maxDuration: 1000, minHold: 800, doubleTapTimeout: 800 }, cancel: function() { this.events.cancel(); }, _triggerTouch: function(type, e) { if (this.trigger(type, { touch: e.touch, event: e.event })) { e.preventDefault(); } }, _tap: function(e) { var that = this, lastTap = that.lastTap, touch = e.touch; if (lastTap && (touch.endTime - lastTap.endTime < that.options.doubleTapTimeout) && kendo.touchDelta(touch, lastTap).distance < MAX_DOUBLE_TAP_DISTANCE ) { that._triggerTouch("doubletap", e); that.lastTap = null; } else { that._triggerTouch("tap", e); that.lastTap = touch; } }, _dragstart: function(e) { this._triggerTouch("dragstart", e); }, _swipestart: function(e) { if (abs(e.x.velocity) * 2 >= abs(e.y.velocity)) { e.sender.capture(); } }, _swipemove: function(e) { var that = this, options = that.options, touch = e.touch, duration = e.event.timeStamp - touch.startTime, direction = touch.x.initialDelta > 0 ? "right" : "left"; if ( abs(touch.x.initialDelta) >= options.minXDelta && abs(touch.y.initialDelta) < options.maxYDelta && duration < options.maxDuration ) { that.trigger("swipe", { direction: direction, touch: e.touch }); touch.cancel(); } } }); kendo.ui.plugin(Touch); })(window.kendo.jQuery); return window.kendo; }, typeof define == 'function' && define.amd ? define : function(_, f){ f(); });
cuongnd/test_pro
media/Kendo_UI_Professional_Q2_2015/src/js/kendo.touch.js
JavaScript
gpl-2.0
4,885
'use strict'; /** * @ngdoc function * @name d8intranetApp.controller:MainCtrl * @description * # MainCtrl * Controller of the d8intranetApp */ angular.module('d8intranetApp') .controller('UserCtrl', function ($scope, $http, $routeParams, getJsonData) { getJsonData.getUsers().then(function (d) { $scope.users = d; $scope.user = {}; var cameToCompany = ''; angular.forEach($scope.users, function (user) { if (user.uid[0].value == $routeParams.userId) { $scope.user = user; cameToCompany = user.field_came_to_propeople[0].value; return $scope.user; } }); // Create new variable where we replace all '-' with ',' //var formattedDate = ; var today = new Date(); var past = new Date(cameToCompany.replace(/-/g, ',')); var months; // Calculate amount of months from user started to work in company function calcDate(date1,date2) { var diff = Math.floor(date1.getTime() - date2.getTime()); var day = 1000 * 60 * 60 * 24; var days = Math.floor(diff/day); var years = Math.floor(months/12); months = Math.floor(days/31); return months; } // Get amount of Years and Months of user work in company function getWorkPeriod(month) { $scope.yearsOfWork = Math.floor(month/12); $scope.monthsOfWork = month%12; } getWorkPeriod(calcDate(today,past)); }); }) .controller('ShowUserCtrl', function ($scope, $routeParams) { $scope.user_id = $routeParams.userId; });
M1r1k/d8intranet
angular/app/scripts/controllers/user.js
JavaScript
gpl-2.0
1,596
(function($){ window.YouTubeSource = { elems: {}, updateYouTubePlaylists: function(){ var self = this; $.ajax({ url: ajaxurl + "?action=update_youtube_playlists&youtube_username=" + $('#options-youtube_username').val(), type: "GET", success: function(data){ $('#youtube-user-playlists').html( data ).find('.fancy').fancy(); SlideDeckPreview.ajaxUpdate(); } }); }, updateYouTubeChannellist: function(){ var self = this; $.ajax({ url: ajaxurl + "?action=update_youtube_channellist&youtube_channelid=" + $('#options-youtube_channel').val(), type: "GET", success: function(data){ $('#youtube-user-playlists').html( data ).find('.fancy').fancy(); SlideDeckPreview.ajaxUpdate(); } }); }, initialize: function(){ var self = this; this.elems.form = $('#slidedeck-update-form'); this.slidedeck_id = $('#slidedeck_id').val(); // YouTube Username this.elems.form.delegate('.youtube-username-ajax-update', 'click', function(event){ event.preventDefault(); self.updateYouTubePlaylists(); }); // YouTube Channel this.elems.form.delegate('.youtube-channel-ajax-update ', 'click', function(event){ event.preventDefault(); self.updateYouTubeChannellist(); }); // Prevent enter key from submitting text fields this.elems.form.delegate('#options-youtube_username', 'keydown', function(event){ if( 13 == event.keyCode){ event.preventDefault(); $('.youtube-username-ajax-update').click(); return false; } return true; }); this.elems.form.delegate('#options-search_or_user-user, #options-search_or_user-search, #options-search_or_user-channel_id', 'change', function(event){ switch( event.target.id ){ case 'options-search_or_user-user': $('li.youtube-search').hide(); $('li.youtube-username').show(); $('li.youtube-channelid').hide(); $('li.youtube-playlist').show(); break; case 'options-search_or_user-search': $('li.youtube-username').hide(); $('li.youtube-search').show(); $('li.youtube-channelid').hide(); $('li.youtube-playlist').hide(); break; case 'options-search_or_user-channel_id': $('li.youtube-username').hide(); $('li.youtube-search').hide(); $('li.youtube-channelid').show(); $('li.youtube-playlist').show(); break; } }); } }; $(document).ready(function(){ YouTubeSource.initialize(); }); var ajaxOptions = [ "options[youtube_playlist]", "options[youtube_q]" ]; for(var o in ajaxOptions){ SlideDeckPreview.ajaxOptions.push(ajaxOptions[o]); } })(jQuery);
elmehdiboutaleb/mjwebsite
wp-content/plugins/slidedeck3/sources/youtube/source.js
JavaScript
gpl-2.0
3,518
/* * translate * * allow to translate text in input * */ ; (function($) { $.fn.translate = function(inParam) { var toInit = []; this.each(function(){ var translate = this; var $translate = $(translate); if ($(translate).data('initialized')) { return; } else { if (this.type != 'text' && this.type != 'textarea') { throw new Error('Element should be text or \ textarea in order to use translator for it. [' + this.type + '] given.'); } $(translate).data('initialized', 1); } var param = $.extend({ }, inParam) var $div = $('<div style="display:none;"></div>'); var $a = $('<a class="local" href="javascript:;"></a>'); $a.click(function(){ $div.dialog('open'); }) $(translate).after($a); $a.before(' '); $('body').append($div); $translate.bind('change', function(){ init(); }) toInit.push({ text : $translate.val().replace(/\r?\n/g, "\r\n"), callback : function (stat, form) {init(stat, form)} }); function init(stat, form) { if (arguments.length == 0) { synchronize($translate.val()); } else { updateStat(stat); updateForm(form); } } function synchronize(text) { $.ajax({ type: 'post', data : { 'text' : text.replace(/\r?\n/g, "\r\n") }, url : window.rootUrl + '/admin-trans-local/synchronize', dataType : 'json', success : function(data, textStatus, XMLHttpRequest) { updateStat(data.stat); updateForm(data.form); } }); } function updateStat(data) { data.total && $a.empty().append('Translate (' + data.translated + '/' + data.total + ')'); } function updateForm(data) { $div.empty().append(data); } $div.dialog({ autoOpen: false, modal : true, title : "Translations", width : 600, position : ['center', 100], buttons: { "Save" : function() { $div.find('form').ajaxSubmit({ success : function() { $div.dialog('close'); init(); } }); }, "Cancel" : function() { $(this).dialog("close"); } } }); }) if (toInit.length) { initBatch(toInit); } function initBatch(toInit) { var text = []; for (var i in toInit) { text.push(toInit[i].text); } $.ajax({ type: 'post', data : { 'text' : text }, url : window.rootUrl + '/admin-trans-local/synchronize-batch', dataType : 'json', success : function(data, textStatus, XMLHttpRequest) { for (var i in toInit) { toInit[i].callback(data[toInit[i].text].stat, data[toInit[i].text].form); } } }); } return this; } })(jQuery);
grlf/eyedock
amember/application/default/views/public/js/translate.js
JavaScript
gpl-2.0
4,038
exports.requestOptions = { hostname: '127.0.0.1', port: 8000, path: '/', method: 'POST', rejectUnauthorized: false, requestCert: true, agent: false } exports.procedure_auth = 'key'; exports.uniqueId = '987';
dpxxdp/Pipes
client/client/client_settings.js
JavaScript
gpl-2.0
241
/** * Copyright (c) 2009-2010 The Open Planning Project */ GeoExt.Lang.add("es", { "GeoExplorer.prototype": { zoomSliderText: "<div>Nivel de detalle: {zoom}</div><div>Escala: 1:{scale}</div>", loadConfigErrorText: "Problemas leyendo la configuración guardada: <br />", loadConfigErrorDefaultText: "Error del servidor.", xhrTroubleText: "Problemas de comunicación: Estado ", layersText: "Capas", titleText: "Título", bookmarkText: "URL del marcador", permakinkText: "Enlace permanente", appInfoText: "GeoExplorer", aboutText: "Acerca de GeoExplorer", mapInfoText: "Información del mapa", descriptionText: "Descripción", contactText: "Contacto", aboutThisMapText: "Acerca de este mapa" }, "GeoExplorer.Composer.prototype": { mapText: "Mapa", tableText: "Table", queryText: "Query", exportMapText: "Exportar Mapa", saveMapText: "Guardar Mapa", saveErrorText: "Problemas guardando: ", toolsTitle: "Escoja los elementos que desea incluir en la barra de herramientas:", previewText: "Vista previa", backText: "Anterior", nextText: "Siguiente", loginText: "Login", loginErrorText: "Invalid username or password.", userFieldText: "User", passwordFieldText: "Password", logoutConfirmTitle: "Warning", logoutConfirmMessage: "Logging out will undo any unsaved changes, remove any layers you may have added, and reset the map composition. Do you want to save your composition first?" } });
fedesanchez/suite-3.1
geoexplorer/app/static/script/app/locale/app/es.js
JavaScript
gpl-2.0
1,642
/* * dashboard.js * * (c) 2020-2021 Jörg Wendel * * This code is distributed under the terms and conditions of the * GNU GENERAL PUBLIC LICENSE. See the file COPYING for details. * */ var widgetWidthBase = null; var widgetHeightBase = null; var weatherData = null; var wInterval = null; var actDashboard = -1; var moseDownOn = { 'object' : null }; var lightClickTimeout = null; var lightClickPosX = null; var lightClickPosY = null; const symbolColorDefault = '#ffffff'; const symbolOnColorDefault = '#059eeb'; function initDashboard(update = false) { // console.log("initDashboard " + JSON.stringify(allSensors, undefined, 4)); if (allSensors == null) { console.log("Fatal: Missing widgets!"); return; } if (!update) { $('#container').removeClass('hidden'); $('#dashboardMenu').removeClass('hidden'); $('#dashboardMenu').html(''); } if (!Object.keys(dashboards).length) setupMode = true; // setupMode = true; // to debug if (setupMode) { $('#dashboardMenu').append($('<button></button>') .addClass('rounded-border buttonDashboardTool') .addClass('mdi mdi-close-outline') .attr('title', 'Setup beenden') .click(function() { setupDashboard(); }) ); } var jDashboards = []; for (var did in dashboards) jDashboards.push([dashboards[did].order, did]); jDashboards.sort(); for (var i = 0; i < jDashboards.length; i++) { var did = jDashboards[i][1]; if (actDashboard < 0) actDashboard = did; if (kioskBackTime > 0 && actDashboard != jDashboards[0][1]) { setTimeout(function() { actDashboard = jDashboards[0][1]; initDashboard(false); }, kioskBackTime * 1000); } var classes = dashboards[did].symbol != '' ? dashboards[did].symbol.replace(':', ' ') : ''; if (dashboards[actDashboard] == dashboards[did]) classes += ' buttonDashboardActive'; $('#dashboardMenu').append($('<button></button>') .addClass('rounded-border buttonDashboard widgetDropZone') .addClass(classes) .attr('id', did) .attr('draggable', setupMode) .attr('data-droppoint', setupMode) .attr('data-dragtype', 'dashboard') .on('dragstart', function(event) {dragDashboard(event)}) .on('dragover', function(event) {dragOverDashboard(event)}) .on('dragleave', function(event) {dragLeaveDashboard(event)}) .on('drop', function(event) {dropDashboard(event)}) .html(dashboards[did].title) .click({"id" : did}, function(event) { actDashboard = event.data.id; console.log("Activate dashboard " + actDashboard); initDashboard(); })); if (kioskMode) $('#'+did).css('font-size', '-webkit-xxx-large'); if (setupMode && did == actDashboard) $('#dashboardMenu').append($('<button></button>') .addClass('rounded-border buttonDashboardTool') .addClass('mdi mdi-lead-pencil') // mdi-draw-pen .click({"id" : did}, function(event) { dashboardSetup(event.data.id); }) ); } // additional elements in setup mode if (setupMode) { $('#dashboardMenu') .append($('<div></div>') .css('float', 'right') .append($('<button></button>') .addClass('rounded-border buttonDashboardTool') .addClass('mdi mdi-shape-plus') .attr('title', 'widget zum dashboard hinzufügen') .css('font-size', 'x-large') .click(function() { addWidget(); }) ) .append($('<input></input>') .addClass('rounded-border input') .css('margin', '15px,15px,15px,0px') .attr('id', 'newDashboard') .attr('title', 'Neues Dashboard') ) .append($('<button></button>') .addClass('rounded-border buttonDashboardTool') .addClass('mdi mdi-file-plus-outline') .attr('title', 'dashboard hinzufügen') .click(function() { newDashboard(); }) ) ); } // widgets document.getElementById("container").innerHTML = '<div id="widgetContainer" class="widgetContainer"></div>'; if (dashboards[actDashboard] != null) { for (var key in dashboards[actDashboard].widgets) { initWidget(key, dashboards[actDashboard].widgets[key]); updateWidget(allSensors[key], true, dashboards[actDashboard].widgets[key]); } } initLightColorDialog(); // calc container size $("#container").height($(window).height() - getTotalHeightOf('menu') - getTotalHeightOf('dashboardMenu') - 15); window.onresize = function() { $("#container").height($(window).height() - getTotalHeightOf('menu') - getTotalHeightOf('dashboardMenu') - 15); }; } function newDashboard() { if (!$('#newDashboard').length) return; var name = $('#newDashboard').val(); $('#newDashboard').val(''); if (name != '') { console.log("new dashboard: " + name); socket.send({ "event" : "storedashboards", "object" : { [-1] : { 'title' : name, 'widgets' : {} } } }); socket.send({ "event" : "forcerefresh", "object" : {} }); } } var keyTimeout = null; function initWidget(key, widget, fact) { // console.log("Widget " + JSON.stringify(widget)); if (key == null || key == '') return ; if (fact == null) fact = valueFacts[key]; if (fact == null && widget.widgettype != 10 && widget.widgettype != 11) { console.log("Fact '" + key + "' not found, ignoring"); return; } if (widget == null) { console.log("Missing widget for '" + key + "' ignoring"); return; } // console.log("initWidget " + key + " : " + (fact ? fact.name : '')); // console.log("fact: " + JSON.stringify(fact, undefined, 4)); // console.log("widget: " + JSON.stringify(widget, undefined, 4)); var root = document.getElementById("widgetContainer"); var id = 'div_' + key; var elem = document.getElementById(id); if (elem == null) { // console.log("element '" + id + "' not found, creating"); elem = document.createElement("div"); root.appendChild(elem); elem.setAttribute('id', id); if (!widgetHeightBase) widgetHeightBase = elem.clientHeight; if (!kioskMode && dashboards[actDashboard].options && dashboards[actDashboard].options.heightfactor) elem.style.height = widgetHeightBase * dashboards[actDashboard].options.heightfactor + 'px'; if (kioskMode && dashboards[actDashboard].options && dashboards[actDashboard].options.heightfactorKiosk) elem.style.height = widgetHeightBase * dashboards[actDashboard].options.heightfactorKiosk + 'px'; } elem.innerHTML = ""; if (widgetWidthBase == null) widgetWidthBase = elem.clientWidth; // console.log("clientWidth: " + elem.clientWidth + ' : ' + widgetWidthBase); const marginPadding = 8; elem.style.width = widgetWidthBase * widget.widthfactor + ((widget.widthfactor-1) * marginPadding-1) + 'px'; if (setupMode && (widget.widgettype < 900 || widget.widgettype == null)) { elem.setAttribute('draggable', true); elem.dataset.droppoint = true; elem.dataset.dragtype = 'widget'; elem.addEventListener('dragstart', function(event) {dragWidget(event)}, false); elem.addEventListener('dragover', function(event) {dragOver(event)}, false); elem.addEventListener('dragleave', function(event) {dragLeave(event)}, false); elem.addEventListener('drop', function(event) {dropWidget(event)}, false); } var titleClass = ''; var title = setupMode ? ' ' : ' '; if (fact != null) title += fact.usrtitle && fact.usrtitle != '' ? fact.usrtitle : fact.title; if (!setupMode && widget.unit == '°C') titleClass = 'mdi mdi-thermometer'; else if (!setupMode && widget.unit == 'hPa') titleClass = 'mdi mdi-gauge'; else if (!setupMode && widget.unit == 'xxxx') // can't detect if '%' is humidity titleClass = 'mdi mdi-water-percent'; if (!widget.color) widget.color = 'white'; $(document).on({'mouseup touchend' : function(e){ if (!moseDownOn.object) return; e.preventDefault(); var scale = parseInt((e.pageX - $(moseDownOn.div).position().left) / ($(moseDownOn.div).innerWidth() / 100)); if (scale > 100) scale = 100; if (scale < 0) scale = 0; console.log("dim: " + scale + '%'); toggleIo(moseDownOn.fact.address, moseDownOn.fact.type, scale); moseDownOn = { 'object' : null }; }}); $(document).on({'mousemove touchmove' : function(e){ if (!moseDownOn.object) return; e.preventDefault(); var scale = parseInt((e.pageX - $(moseDownOn.div).position().left) / ($(moseDownOn.div).innerWidth() / 100)); if (scale > 100) scale = 100; if (scale < 0) scale = 0; $(moseDownOn.object).css('width', scale + '%'); }}) switch (widget.widgettype) { case 0: { // Symbol $(elem) .addClass("widget rounded-border widgetDropZone") .append($('<div></div>') .addClass('widget-title ' + (setupMode ? 'mdi mdi-lead-pencil widget-edit' : '')) .addClass(titleClass) .click(function() { titleClick(fact.type, fact.address, key); }) .css('user-select', 'none') .html(title)) .append($('<button></button>') .attr('id', 'button' + fact.type + fact.address) .attr('type', 'button') .css('color', widget.color) .css('user-select', 'none') .addClass('widget-main') .append($('<img></img>') .attr('id', 'widget' + fact.type + fact.address) .attr('draggable', false) .css('user-select', 'none'))) .append($('<div></div>') .attr('id', 'progress' + fact.type + fact.address) .addClass('widget-progress') .css('user-select', 'none') .on({'mousedown touchstart' : function(e){ e.preventDefault(); moseDownOn.object = $('#progressBar' + fact.type + fact.address); moseDownOn.fact = fact; moseDownOn.div = $(this); console.log("mousedown on " + moseDownOn.object.attr('id')); }}) .append($('<div></div>') .attr('id', 'progressBar' + fact.type + fact.address) .css('user-select', 'none') .addClass('progress-bar'))); if (!setupMode) { $('#button' + fact.type + fact.address) .on('mousedown touchstart', {"fact" : fact}, function(e) { if (e.touches != null) { lightClickPosX = e.touches[0].pageX; lightClickPosY = e.touches[0].pageY; } else { e.preventDefault(); lightClickPosX = e.clientX; lightClickPosY = e.clientY; } // e.preventDefault(); if ((e.which != 0 && e.which != 1) || $('#lightColorDiv').css('display') != 'none') return; if (fact.options & 0x04) { lightClickTimeout = setTimeout(function(event) { lightClickTimeout = lightClickPosX = lightClickPosY = null; showLightColorDialog(key); }, 400); } }) .on('mouseup mouseleave touchend', {"fact" : fact}, function(e) { if ($('#lightColorDiv').css('display') != 'none') return; if (e.changedTouches != null) { posX = e.changedTouches[0].pageX; posY = e.changedTouches[0].pageY; } else { posX = e.clientX; posY = e.clientY; } if (lightClickPosX != null || lightClickPosY != null) { if (Math.abs(lightClickPosX - posX) < 15 && Math.abs(lightClickPosY - posY) < 15) { e.preventDefault(); e.stopPropagation(); toggleIo(fact.address, fact.type); } } if (lightClickTimeout) clearTimeout(lightClickTimeout); lightClickTimeout = lightClickPosX = lightClickPosY = null; }); } // needed for shower progress bar ?!? // .append($('<div></div>') // .attr('id', 'progress' + fact.type + fact.address) // .addClass('widget-progress') // .css('visibility', 'hidden') // .append($('<div></div>') // .attr('id', 'progressBar' + fact.type + fact.address) // .addClass('progress-bar'))); // .css('visible', true))); break; } case 1: { // Chart elem.className = "widgetChart rounded-border widgetDropZone"; var eTitle = document.createElement("div"); var cls = setupMode ? 'mdi mdi-lead-pencil widget-edit' : ''; eTitle.className = "widget-title " + cls + ' ' + titleClass; eTitle.innerHTML = title; eTitle.addEventListener("click", function() {titleClick(fact.type, fact.address, key)}, false); elem.appendChild(eTitle); var ePeak = document.createElement("div"); ePeak.setAttribute('id', 'peak' + fact.type + fact.address); ePeak.className = "chart-peak"; elem.appendChild(ePeak); var eValue = document.createElement("div"); eValue.setAttribute('id', 'value' + fact.type + fact.address); eValue.className = "chart-value"; eValue.style.color = widget.color; elem.appendChild(eValue); var eChart = document.createElement("div"); eChart.className = "chart-canvas-container"; var cFact = fact; if (!setupMode && fact.record) eChart.setAttribute("onclick", "toggleChartDialog('" + cFact.type + "'," + cFact.address + ")"); elem.appendChild(eChart); var eCanvas = document.createElement("canvas"); eCanvas.setAttribute('id', 'widget' + fact.type + fact.address); eCanvas.className = "chart-canvas"; eChart.appendChild(eCanvas); break; } case 3: { // type 3 (Value) $(elem) .addClass("widgetValue rounded-border widgetDropZone") .append($('<div></div>') .addClass('widget-title ' + (setupMode ? 'mdi mdi-lead-pencil widget-edit' : '')) .addClass(titleClass) .css('user-select', 'none') .click(function() {titleClick(fact.type, fact.address, key);}) .html(title)) .append($('<div></div>') .attr('id', 'widget' + fact.type + fact.address) .addClass('widget-value') .css('user-select', 'none') .css('color', widget.color)) .append($('<div></div>') .attr('id', 'peak' + fact.type + fact.address) .css('user-select', 'none') .addClass('chart-peak')); var cFact = fact; if (!setupMode && fact.record) $(elem).click(function() {toggleChartDialog(cFact.type, cFact.address, key);}); break; } case 4: { // Gauge $(elem) .addClass("widgetGauge rounded-border participation widgetDropZone") .append($('<div></div>') .addClass('widget-title ' + (setupMode ? 'mdi mdi-lead-pencil widget-edit' : '')) .addClass(titleClass) .css('user-select', 'none') .click(function() {titleClick(fact.type, fact.address, key);}) .html(title)) .append($('<div></div>') .attr('id', 'svgDiv' + fact.type + fact.address) .addClass('widget-main-gauge') .css('user-select', 'none') .append($('<svg></svg>') .attr('viewBox', '0 0 1000 600') .attr('preserveAspectRatio', 'xMidYMin slice') .append($('<path></path>') .attr('id', 'pb' + fact.type + fact.address)) .append($('<path></path>') .attr('id', 'pv' + fact.type + fact.address) .addClass('data-arc')) .append($('<path></path>') .attr('id', 'pp' + fact.type + fact.address) .addClass('data-peak')) .append($('<text></text>') .attr('id', 'value' + fact.type + fact.address) .addClass('gauge-value') .attr('font-size', "140") .attr('font-weight', 'bold') .attr('text-anchor', 'middle') .attr('alignment-baseline', 'middle') .attr('x', '500') .attr('y', '450')) .append($('<text></text>') .attr('id', 'sMin' + fact.type + fact.address) .addClass('scale-text') .attr('text-anchor', 'middle') .attr('alignment-baseline', 'middle') .attr('x', '50') .attr('y', '550')) .append($('<text></text>') .attr('id', 'sMax' + fact.type + fact.address) .addClass('scale-text') .attr('text-anchor', 'middle') .attr('alignment-baseline', 'middle') .attr('x', '950') .attr('y', '550')))); var cFact = fact; if (!setupMode && fact.record) $(elem).click(function() {toggleChartDialog(cFact.type, cFact.address, key);}); var divId = '#svgDiv' + fact.type + fact.address; $(divId).html($(divId).html()); // redraw to activate the SVG !! break; } case 5: // Meter case 6: { // MeterLevel var radial = widget.widgettype == 5; elem.className = radial ? "widgetMeter rounded-border" : "widgetMeterLinear rounded-border"; elem.className += " widgetDropZone"; var eTitle = document.createElement("div"); eTitle.className = "widget-title " + (setupMode ? 'mdi mdi-lead-pencil widget-edit' : titleClass); eTitle.addEventListener("click", function() {titleClick(fact.type, fact.address, key)}, false); eTitle.innerHTML = title; elem.appendChild(eTitle); var main = document.createElement("div"); main.className = radial ? "widget-main-meter" : "widget-main-meter-lin"; elem.appendChild(main); var canvas = document.createElement('canvas'); main.appendChild(canvas); canvas.setAttribute('id', 'widget' + fact.type + fact.address); var cFact = fact; if (!setupMode && fact.record) $(canvas).click(function() {toggleChartDialog(cFact.type, cFact.address, key);}); if (!radial) { var value = document.createElement("div"); value.setAttribute('id', 'widgetValue' + fact.type + fact.address); value.className = "widget-main-value-lin"; elem.appendChild(value); $("#widgetValue" + fact.type + fact.address).css('color', widget.color); var ePeak = document.createElement("div"); ePeak.setAttribute('id', 'peak' + fact.type + fact.address); ePeak.className = "widget-main-peak-lin"; elem.appendChild(ePeak); } if (widget.scalemin == null) widget.scalemin = 0; var ticks = []; var scaleRange = widget.scalemax - widget.scalemin; var stepWidth = widget.scalestep != null ? widget.scalestep : 0; if (!stepWidth) { var steps = 10; if (scaleRange <= 100) steps = scaleRange % 10 == 0 ? 10 : scaleRange % 5 == 0 ? 5 : scaleRange; if (steps < 10) steps = 10; if (!radial && widget.unit == '%') steps = 4; stepWidth = scaleRange / steps; } if (stepWidth <= 0) stepWidth = 1; stepWidth = Math.round(stepWidth*10) / 10; var steps = -1; for (var step = widget.scalemin; step.toFixed(2) <= widget.scalemax; step += stepWidth) { ticks.push(step % 1 ? parseFloat(step).toFixed(1) : parseInt(step)); steps++; } var scalemax = widget.scalemin + stepWidth * steps; // cals real scale max based on stepWidth and step count! var highlights = {}; var critmin = (widget.critmin == null || widget.critmin == -1) ? widget.scalemin : widget.critmin; var critmax = (widget.critmax == null || widget.critmax == -1) ? scalemax : widget.critmax; var minColor = widget.unit == '°C' ? 'blue' : 'rgba(255,0,0,.6)'; highlights = [ { from: widget.scalemin, to: critmin, color: minColor }, { from: critmin, to: critmax, color: 'rgba(0,255,0,.6)' }, { from: critmax, to: scalemax, color: 'rgba(255,0,0,.6)' } ]; // console.log("widget: " + JSON.stringify(widget, undefined, 4)); // console.log("ticks: " + ticks + " range; " + scaleRange); // console.log("highlights: " + JSON.stringify(highlights, undefined, 4)); options = { renderTo: 'widget' + fact.type + fact.address, units: radial ? widget.unit : '', // title: radial ? false : widget.unit minValue: widget.scalemin, maxValue: scalemax, majorTicks: ticks, minorTicks: 5, strokeTicks: false, highlights: highlights, highlightsWidth: radial ? 8 : 6, colorPlate: radial ? '#2177AD' : 'rgba(0,0,0,0)', colorBar: colorStyle.getPropertyValue('--scale'), // 'gray', colorBarProgress: widget.unit == '%' ? 'blue' : 'red', colorBarStroke: 'red', colorMajorTicks: colorStyle.getPropertyValue('--scale'), // '#f5f5f5', colorMinorTicks: colorStyle.getPropertyValue('--scale'), // '#ddd', colorTitle: colorStyle.getPropertyValue('--scaleText'), colorUnits: colorStyle.getPropertyValue('--scaleText'), // '#ccc', colorNumbers: colorStyle.getPropertyValue('--scaleText'), colorNeedle: 'rgba(240, 128, 128, 1)', colorNeedleEnd: 'rgba(255, 160, 122, .9)', fontNumbersSize: radial ? 34 : (onSmalDevice ? 45 : 45), fontUnitsSize: 45, fontUnitsWeight: 'bold', borderOuterWidth: 0, borderMiddleWidth: 0, borderInnerWidth: 0, borderShadowWidth: 0, needle: radial, fontValueWeight: 'bold', valueBox: radial, valueInt: 0, valueDec: 2, colorValueText: colorStyle.getPropertyValue('--scale'), colorValueBoxBackground: 'transparent', // colorValueBoxBackground: '#2177AD', valueBoxStroke: 0, fontValueSize: 45, valueTextShadow: false, animationRule: 'bounce', animationDuration: 500, barWidth: radial ? 0 : (widget.unit == '%' ? 10 : 7), numbersMargin: 0, // linear gauge specials barBeginCircle: widget.unit == '°C' ? 15 : 0, tickSide: 'left', needleSide: 'right', numberSide: 'left', colorPlate: 'transparent' }; var gauge = null; if (radial) gauge = new RadialGauge(options); else gauge = new LinearGauge(options); gauge.draw(); $('#widget' + fact.type + fact.address).data('gauge', gauge); break; } case 7: { // 7 (PlainText) $(elem).addClass('widgetPlain rounded-border widgetDropZone'); if (setupMode) $(elem).append($('<div></div>') .addClass('widget-title ' + (setupMode ? 'mdi mdi-lead-pencil widget-edit' : '')) .addClass(titleClass) .css('user-select', 'none') .click(function() {titleClick(fact.type, fact.address, key);}) .html(title)); var wFact = fact; $(elem).append($('<div></div>') .attr('id', 'widget' + fact.type + fact.address) .addClass(fact.type == 'WEA' ? 'widget-weather' : 'widget-value') .css('user-select', 'none') .css('color', widget.color) .css('height', 'inherit') .click(function() { if (wFact.type == 'WEA') weatherForecast(); })); break; } case 8: { // 8 (Choice) $(elem) .addClass("widget rounded-border widgetDropZone") .css('cursor', 'pointer') .click(function() { socket.send({"event": "toggleio", "object": {"address": fact.address, "type": fact.type}}); }) .append($('<div></div>') .addClass('widget-title ' + (setupMode ? 'mdi mdi-lead-pencil widget-edit' : '')) .addClass(titleClass) .css('user-select', 'none') .click(function() {titleClick(fact.type, fact.address, key);}) .html(title)) .append($('<div></div>') .attr('id', 'widget' + fact.type + fact.address) .addClass('widget-value') .css('user-select', 'none') .css('color', widget.color)); break; } case 9: { // Symbol-Value $(elem) .addClass("widgetSymbolValue rounded-border widgetDropZone") .append($('<div></div>') .addClass('widget-title ' + (setupMode ? 'mdi mdi-lead-pencil widget-edit' : '')) .addClass(titleClass) .click(function() {titleClick(fact.type, fact.address, key);}) .css('user-select', 'none') .html(title)) .append($('<button></button>') .attr('id', 'button' + fact.type + fact.address) .addClass('widget-main') .attr('type', 'button') .css('color', widget.color) .css('user-select', 'none') .append($('<img></img>') .attr('id', 'widget' + fact.type + fact.address) .attr('draggable', false) .css('user-select', 'none')) .click(function() { toggleIo(fact.address, fact.type); })) .append($('<div></div>') .attr('id', 'progress' + fact.type + fact.address) .addClass('widget-progress') .css('user-select', 'none') .on({'mousedown touchstart' : function(e){ e.preventDefault(); moseDownOn.object = $('#progressBar' + fact.type + fact.address); moseDownOn.fact = fact; moseDownOn.div = $(this); console.log("mousedown on " + moseDownOn.object.attr('id')); }}) .append($('<div></div>') .attr('id', 'progressBar' + fact.type + fact.address) .css('user-select', 'none') .addClass('progress-bar'))) .append($('<div></div>') .attr('id', 'value' + fact.type + fact.address) .addClass('symbol-value') .css('user-select', 'none') ); break; } case 10: { // space $(elem).addClass("widgetSpacer rounded-border widgetDropZone"); $(elem).append($('<div></div>') .addClass('widget-title ' + (setupMode ? 'mdi mdi-lead-pencil widget-edit' : '')) .addClass(titleClass) .click(function() {titleClick('', 0, key);}) .html(setupMode ? ' spacer' : '')); if (!setupMode) $(elem).css('background-color', widget.color); if (widget.linefeed) { $(elem) .css('flex-basis', '100%') .css('height', setupMode ? '40px' : '0px') .css('padding', '0px') .css('margin', '0px'); } break; } case 11: { // actual time $(elem) .addClass("widgetPlain rounded-border widgetDropZone") .append($('<div></div>') .addClass('widget-title ' + (setupMode ? 'mdi mdi-lead-pencil widget-edit' : '')) .addClass(titleClass) .css('user-select', 'none') .click(function() {titleClick('', 0, key);}) .html(setupMode ? ' time' : '')); $(elem).append($('<div></div>') .attr('id', 'widget' + key) .addClass('widget-time') .css('height', 'inherit') .css('color', widget.color) .css('user-select', 'none') .html(getTimeHtml())); setInterval(function() { var timeId = '#widget'+key.replace(':', '\\:'); $(timeId).html(getTimeHtml()); }, 1*1000); break; } default: { // type 2 (Text) $(elem) .addClass("widget rounded-border widgetDropZone") .append($('<div></div>') .addClass('widget-title ' + (setupMode ? 'mdi mdi-lead-pencil widget-edit' : '')) .addClass(titleClass) .css('user-select', 'none') .click(function() {titleClick(fact.type, fact.address, key);}) .html(title)) .append($('<div></div>') .attr('id', 'widget' + fact.type + fact.address) .css('user-select', 'none') .css('color', widget.color) .addClass('widget-value')); var cFact = fact; if (!setupMode && fact.record) $(elem).click(function() {toggleChartDialog(cFact.type, cFact.address, key);}); break; } } } function initLightColorDialog() { $("#container").append($('<div></div>)') .attr('id', 'lightColorDiv') .addClass('rounded-border lightColorDiv') .append($('<input></input>)') .attr('id', 'lightColor') .addClass('lightColor') .attr('type', 'text')) .append($('<button></button>)') .html('Ok') .click(function() { $('#lightColorDiv').css('display', 'none'); })) ); var options = { 'cssClass' : 'lightColor', 'layout' : 'block', 'format' : 'hsv', 'sliders' : 'wsvp', 'autoResize' : false } $('#lightColor').wheelColorPicker(options); $('#lightColorDiv').css('display', 'none'); $('#lightColor').on('sliderup', function(e) { if (!$(this).data('key')) return; var fact = valueFacts[$(this).data('key')]; var hue = parseInt($(this).wheelColorPicker('getColor').h * 360); var sat = parseInt($(this).wheelColorPicker('getColor').s * 100); var bri = parseInt($(this).wheelColorPicker('getColor').v * 100); console.log("color of " + fact.address + " changed to '" + hue + "' / " + bri + '% / ' + sat + '%'); socket.send({ "event": "toggleio", "object": { 'action': 'color', 'type': fact.type, 'address': fact.address, 'hue': hue, 'saturation' : sat, 'bri': bri }}); }); $('#container').on('mouseup', function(e) { e.preventDefault(); if ($(e.target).attr('id') != 'lightColorDiv' && !$('#lightColorDiv').has(e.target).length) $('#lightColorDiv').css('display', 'none'); }); } function showLightColorDialog(key) { var posX = ($('#container').innerWidth() - $('#lightColorDiv').outerWidth()) / 2; var posY = ($('#container').innerHeight() - $('#lightColorDiv').outerHeight()) / 2; var sensor = allSensors[key]; $('#lightColor').data('key', key); $('#lightColorDiv').css('left', posX + 'px'); $('#lightColorDiv').css('top', posY + 'px'); $('#lightColorDiv').css('display', 'block'); $('#lightColor').wheelColorPicker('setColor', { 'h': sensor.hue/360.0, 's': sensor.sat/100.0, 'v': sensor.score/100.0 }); } function getTimeHtml() { var now = new Date(); // calc daytime every 60 seconds if (!daytimeCalcAt || now.getTime() >= daytimeCalcAt.getTime()+60000){ daytimeCalcAt = now; var sunset = new Date().sunset(config.latitude.replace(',', '.'), config.longitude.replace(',', '.')); var sunrise = new Date().sunrise(config.latitude.replace(',', '.'), config.longitude.replace(',', '.')); isDaytime = daytimeCalcAt > sunrise && daytimeCalcAt < sunset; // console.log("isDaytime: " + isDaytime + ' : ' + sunrise + ' : '+ sunset); } var cls = isDaytime ? 'mdi mdi-weather-sunny' : 'mdi mdi-weather-night'; return '<div>' + '<span class="' + cls + ' " style="color:orange;"></span>' + '<span> ' + moment().format('dddd Do') + '</span>' + '<span> ' + moment().format('MMMM YYYY') + '</span>' + '</div>' + '<div style="font-size:2em">' + moment().format('HH:mm:ss') + '</div>'; } function getWeatherHtml(symbolView, wfact, weather) { // https://openweathermap.org/weather-conditions#Weather-Condition-Codes-2 var html = ''; if (symbolView) { var wIconRef = 'img/weather/' + weather.icon + '@4x.png'; if (!images.find(img => img == wIconRef)) wIconRef = 'http://openweathermap.org/img/wn/' + weather.icon + '@4x.png'; html += '<div style="display:block;color:orange;font-weight:bold;height:75%;padding-left:5px;"><span>' + weather.detail + '</span><img style="height:100%" src="' + wIconRef + '"></img></div>'; html += '<div style="display:flex;justify-content:space-between;padding-top:3px;">'; html += ' <span style="color:#00c3ff;font-weight:bold;padding-left:5px;">' + weather.temp.toFixed(1) + '°C</span>'; html += ' <span class="mdi mdi-walk" style="color:#00c3ff;font-weight:bold;font-size:smaller;">' + weather.tempfeels.toFixed(1) + '</span>'; html += '</div>'; } else { var wIconRef = 'img/weather/' + weather.icon + '.png'; if (!images.find(img => img == wIconRef)) wIconRef = 'http://openweathermap.org/img/wn/' + weather.icon + '.png'; html += '<div style="display:inline-flex;color:orange;align-items:center;font-weight:bold;"><span><img src="' + wIconRef + '"></img></span><span>' + weather.detail + '</span></div>'; html += '<div><span style="color:#00c3ff;font-weight:bold;">' + weather.temp.toFixed(1) + '°C</span>'; html += '<span style="font-size:smaller;"> (' + weather.tempmin.toFixed(1) + ' / ' + weather.tempmax.toFixed(1) + ')' + '</span></div>'; html += '<div>Luftdruck: <span style="color:#00c3ff;font-weight:bold;">' + weather.pressure + ' hPa' + '</span></div>'; html += '<div>Luftfeuchte: <span style="color:#00c3ff;font-weight:bold;">' + weather.humidity + ' %' + '</span></div>'; html += '<div>Wind: <span style="color:#00c3ff;font-weight:bold;">' + weather.windspeed + ' m/s' + '</span></div>'; } return html; } function weatherForecast() { var lastDay = ''; var form = document.createElement("div"); $(form).addClass('rounded-border weatherForecast'); $(form).attr('tabindex', 0); $(form).click(function() { $(form).remove(); }); $('#container').append(form); var showExtras = $(form).outerWidth() > 580; var html = '<div class="rounded-border" style="justify-content:center;font-weight:bold;background-color:#2f2f2fd1;">' + weatherData.city + '</div>'; for (var i = 0; i < weatherData.forecasts.length; i++) { var weather = weatherData.forecasts[i]; var day = moment(weather.time*1000).format('dddd Do MMMM'); var time = moment(weather.time*1000).format('HH:00'); var wIconRef = 'img/weather/' + weather.icon + '.png'; if (!images.find(img => img == wIconRef)) wIconRef = 'http://openweathermap.org/img/wn/' + weather.icon + '.png'; if (day != lastDay) { lastDay = day; html += '<div class="rounded-border" style="background-color:#2f2f2fd1;">' + day + '</div>'; } var tempColor = weather.temp < 0 ? '#2c99eb' : (weather.temp > 20 ? 'red' : 'white'); html += '<div class="rounded-border">'; html += '<span>' + time + '</span>'; html += '<span><img src="' + wIconRef + '"></img></span>'; html += '<span class="mdi mdi-thermometer" style="color:' + tempColor + ';"> ' + weather.temp + ' °C</span>'; if (showExtras) html += '<span class="mdi mdi-walk">' + weather.tempfeels + ' °C</span>'; html += '<span class="mdi mdi-water-percent"> ' + weather.humidity + ' %</span>'; html += '<span>' + weather.pressure + ' hPa</span>'; html += '<span class="mdi mdi-weather-windy"> ' + weather.windspeed + ' m/s</span>'; html += '</div>' } html += '</div>' $(form).html(html); $(form).focus(); $(form).keydown(function(event) { if (event.which == 27 || event.which == 13) { event.preventDefault(); $(form).remove(); } }); } function titleClick(type, address, key) { if (setupMode) widgetSetup(key); else { var fact = valueFacts[key]; if (fact && localStorage.getItem(storagePrefix + 'Rights') & fact.rights) // console.log("toggleMode(", fact.address, fact.type, ')'); toggleMode(fact.address, fact.type); } } function updateDashboard(widgets, refresh) { if (widgets != null && dashboards[actDashboard] != null) { for (var key in widgets) { if (dashboards[actDashboard].widgets[key] == null) continue; updateWidget(widgets[key], refresh, dashboards[actDashboard].widgets[key]); } } } function updateWidget(sensor, refresh, widget) { if (sensor == null) return ; var key = toKey(sensor.type, sensor.address); fact = valueFacts[key]; // console.log("updateWidget " + fact.name + " of type " + widget.widgettype); // console.log("updateWidget" + JSON.stringify(sensor, undefined, 4)); if (fact == null) { console.log("Fact for widget '" + key + "' not found, ignoring"); return ; } if (widget == null) { console.log("Widget '" + key + "' not found, ignoring"); return; } if (widget.widgettype == 0 || widget.widgettype == 9) // Symbol, Symbol-Value { // console.log("sensor: ", JSON.stringify(sensor)); var state = fact.type != 'HMB' ? sensor.value != 0 : sensor.value == 100; var image = ''; var classes = ''; if (sensor.image != null) image = sensor.image; else if (state && widget.symbolOn && widget.symbolOn != '') { classes = widget.symbolOn.replace(':', ' '); image = ''; $("#widget" + fact.type + fact.address).remove(); } else if (!state && widget.symbol && widget.symbol != '') { classes = widget.symbol.replace(':', ' '); image = ''; $("#widget" + fact.type + fact.address).remove(); } else if (widget.symbol && widget.symbol != '') { classes = widget.symbol.replace(':', ' '); image = ''; $("#widget" + fact.type + fact.address).remove(); } else image = state ? widget.imgon : widget.imgoff; if (image != '') $("#widget" + fact.type + fact.address).attr("src", image); else { $("#button" + fact.type + fact.address).removeClass(); $("#button" + fact.type + fact.address).addClass('widget-main'); $("#button" + fact.type + fact.address).addClass(classes); } $('#div_'+key.replace(':', '\\:')).css('background-color', (sensor.options == 3 && sensor.mode == 'manual') ? '#a27373' : ''); widget.colorOn = widget.colorOn == null ? symbolOnColorDefault : widget.colorOn; if (sensor.hue) widget.colorOn = tinycolor({ 'h': sensor.hue, 's': sensor.sat, 'v': sensor.score }).toHslString(); widget.color = widget.color == null ? symbolColorDefault : widget.color; // console.log("set color to: : ", widget.colorOn); $("#button" + fact.type + fact.address).css('color', state ? widget.colorOn : widget.color); if (widget.widgettype == 9) { $("#value" + fact.type + fact.address).text(sensor.value.toFixed(widget.unit=="%" ? 0 : 2) + (widget.unit!="" ? " " : "") + widget.unit); } var prs = $('#progressBar' + fact.type + fact.address); $('#progress' + fact.type + fact.address).css('display', fact.options & 0x02 && sensor.value ? 'block' : 'none'); if (sensor.score && prs != null) { $(prs).css('width', sensor.score + '%'); // prs.style.visibility = (sensor.next == null || sensor.next == 0) ? "hidden" : "visible"; } if (sensor.mode == "auto" && sensor.next > 0) { var pWidth = 100; var s = sensor; var id = fact.type + fact.address; var iid = setInterval(progress, 200); function progress() { if (pWidth <= 0) { clearInterval(iid); } else { var d = new Date(); pWidth = 100 - ((d/1000 - s.last) / ((s.next - s.last) / 100)); document.getElementById("progressBar" + id).style.width = pWidth + "%"; } } } } else if (widget.widgettype == 1) // Chart { if (widget.showpeak != null && widget.showpeak) $("#peak" + fact.type + fact.address).text(sensor.peak != null ? sensor.peak.toFixed(2) + " " + widget.unit : ""); $("#value" + fact.type + fact.address).text(sensor.value.toFixed(2) + " " + widget.unit); if (refresh) { var jsonRequest = {}; prepareChartRequest(jsonRequest, toKey(fact.type, fact.address), 0, 1, "chartwidget"); socket.send({ "event" : "chartdata", "object" : jsonRequest }); } } else if (widget.widgettype == 2 || widget.widgettype == 7 || widget.widgettype == 8) // Text, PlainText, Choice { if (sensor.type == 'WEA' && sensor.text != null) { var bigView = false; var wfact = fact; weatherData = JSON.parse(sensor.text); // console.log("weather" + JSON.stringify(weatherData, undefined, 4)); $("#widget" + wfact.type + wfact.address).html(getWeatherHtml(bigView, wfact, weatherData)); if (wInterval) clearInterval(wInterval); if (weatherData && config.toggleWeatherView != 0) { wInterval = setInterval(function() { bigView = !bigView; $("#widget" + wfact.type + wfact.address).html(getWeatherHtml(bigView, wfact, weatherData)); }, 5*1000); } } else if (sensor.text != null) { var text = sensor.text.replace(/(?:\r\n|\r|\n)/g, '<br>'); $("#widget" + fact.type + fact.address).html(text); } } else if (widget.widgettype == 3) // plain value { $("#widget" + fact.type + fact.address).html(sensor.value + " " + widget.unit); if (widget.showpeak != null && widget.showpeak) $("#peak" + fact.type + fact.address).text(sensor.peak != null ? sensor.peak.toFixed(2) + " " + widget.unit : ""); } else if (widget.widgettype == 4) // Gauge { var value = sensor.value.toFixed(2); var scaleMax = !widget.scalemax || widget.unit == '%' ? 100 : widget.scalemax.toFixed(0); var scaleMin = value >= 0 ? "0" : Math.ceil(value / 5) * 5 - 5; var _peak = sensor.peak != null ? sensor.peak : 0; if (scaleMax < Math.ceil(value)) scaleMax = value; if (widget.showpeak != null && widget.showpeak && scaleMax < Math.ceil(_peak)) scaleMax = _peak.toFixed(0); $("#sMin" + fact.type + fact.address).text(scaleMin); $("#sMax" + fact.type + fact.address).text(scaleMax); $("#value" + fact.type + fact.address).text(value + " " + widget.unit); var ratio = (value - scaleMin) / (scaleMax - scaleMin); var peak = (_peak.toFixed(2) - scaleMin) / (scaleMax - scaleMin); $("#pb" + fact.type + fact.address).attr("d", "M 950 500 A 450 450 0 0 0 50 500"); $("#pv" + fact.type + fact.address).attr("d", svg_circle_arc_path(500, 500, 450 /*radius*/, -90, ratio * 180.0 - 90)); if (widget.showpeak != null && widget.showpeak) $("#pp" + fact.type + fact.address).attr("d", svg_circle_arc_path(500, 500, 450 /*radius*/, peak * 180.0 - 91, peak * 180.0 - 90)); } else if (widget.widgettype == 5 || widget.widgettype == 6) // Meter { if (sensor.value != null) { var value = (widget.factor != null && widget.factor) ? widget.factor*sensor.value : sensor.value; // console.log("DEBUG: Update " + '#widget' + fact.type + fact.address + " to: " + value + " (" + sensor.value +")"); $('#widgetValue' + fact.type + fact.address).html(value.toFixed(widget.unit == '%' ? 0 : 1) + ' ' + widget.unit); var gauge = $('#widget' + fact.type + fact.address).data('gauge'); if (gauge != null) gauge.value = value; else console.log("Missing gauge instance for " + '#widget' + fact.type + fact.address); if (widget.showpeak != null && widget.showpeak) $("#peak" + fact.type + fact.address).text(sensor.peak != null ? sensor.peak.toFixed(2) + " " + widget.unit : ""); } else console.log("Missing value for " + '#widget' + fact.type + fact.address); } } function addWidget() { // console.log("add widget .."); var form = document.createElement("div"); $(form).append($('<div></div>') .append($('<div></div>') .css('display', 'flex') .append($('<span></span>') .css('width', '30%') .css('text-align', 'end') .css('align-self', 'center') .css('margin-right', '10px') .html('Filter')) .append($('<input></input>') .attr('id', 'incFilter') .attr('type', 'search') .attr('placeholder', 'expression...') .addClass('rounded-border inputSetting') .on('input', function() {updateSelection();}) )) .append($('<br></br>')) .append($('<div></div>') .css('display', 'flex') .append($('<span></span>') .css('width', '30%') .css('text-align', 'end') .css('align-self', 'center') .css('margin-right', '10px') .html('Widget')) .append($('<span></span>') .append($('<select></select>') .addClass('rounded-border inputSetting') .attr('id', 'widgetKey') )))); $(form).dialog({ modal: true, resizable: false, closeOnEscape: true, hide: "fade", width: "auto", title: "Add Widget", open: function() { updateSelection(); }, buttons: { 'Cancel': function () { $(this).dialog('close'); }, 'Ok': function () { var json = {}; console.log("store widget"); $('#widgetContainer > div').each(function () { var key = $(this).attr('id').substring($(this).attr('id').indexOf("_") + 1); // console.log(" add " + sensor + " for sensor " + $(this).attr('id')); json[key] = dashboards[actDashboard].widgets[key]; }); if ($("#widgetKey").val() == 'ALL') { for (var key in valueFacts) { if (!valueFacts[key].state) // use only active facts here continue; if (dashboards[actDashboard].widgets[key] != null) continue; json[key] = ""; } } else json[$("#widgetKey").val()] = ""; // console.log("storedashboards " + JSON.stringify(json, undefined, 4)); // console.log("storedashboards key " + $("#widgetKey").val()); socket.send({ "event" : "storedashboards", "object" : { [actDashboard] : { 'title' : dashboards[actDashboard].title, 'widgets' : json } } }); socket.send({ "event" : "forcerefresh", "object" : {} }); $(this).dialog('close'); } }, close: function() { $(this).dialog('destroy').remove(); } }); function updateSelection() { var addrSpacer = -1; var addrTime = -1; $('#widgetKey').empty(); // console.log("update selection: " + $('#incFilter').val()); for (var key in dashboards[actDashboard].widgets) { n = parseInt(key.split(":")[1]); if (key.split(":")[0] == 'SPACER' && n > addrSpacer) addrSpacer = n; if (key.split(":")[0] == 'TIME' && n > addrTime) addrTime = n; } $('#widgetKey').append($('<option></option>') .val('SPACER:0x' + (addrSpacer + 1).toString(16)) .html('Spacer')); $('#widgetKey').append($('<option></option>') .val('TIME:0x' + (addrTime + 1).toString(16)) .html('Time')); var jArray = []; var filterExpression = null; if ($('#incFilter').val() != '') filterExpression = new RegExp($('#incFilter').val()); for (var key in valueFacts) { if (!valueFacts[key].state) // use only active facts here continue; // if (dashboards[actDashboard].widgets[key] != null) // continue; if (filterExpression && !filterExpression.test(valueFacts[key].title) && !filterExpression.test(valueFacts[key].usrtitle) && !filterExpression.test(valueFacts[key].type)) continue; jArray.push([key, valueFacts[key]]); } jArray.push(['ALL', { 'title': '- ALLE -'}]); jArray.sort(function(a, b) { var A = (a[1].usrtitle ? a[1].usrtitle : a[1].title).toLowerCase(); var B = (b[1].usrtitle ? b[1].usrtitle : b[1].title).toLowerCase(); if (B > A) return -1; if (A > B) return 1; return 0; }); for (var i = 0; i < jArray.length; i++) { var key = jArray[i][0]; var title = jArray[i][1].usrtitle ? jArray[i][1].usrtitle : jArray[i][1].title; if (valueFacts[key] != null) title += ' / ' + valueFacts[key].type; if (jArray[i][1].unit != null && jArray[i][1].unit != '') title += ' [' + jArray[i][1].unit + ']'; $('#widgetKey').append($('<option></option>') .val(jArray[i][0]) .html(title)); } } } function toggleChartDialog(type, address) { var dialog = document.querySelector('dialog'); dialog.style.position = 'fixed'; console.log("chart for " + type + address); if (type != "" && !dialog.hasAttribute('open')) { var canvas = document.querySelector("#chartDialog"); canvas.getContext('2d').clearRect(0, 0, canvas.width, canvas.height); chartDialogSensor = type + address; // show the dialog dialog.setAttribute('open', 'open'); var jsonRequest = {}; prepareChartRequest(jsonRequest, toKey(type, address), 0, 1, "chartdialog"); socket.send({ "event" : "chartdata", "object" : jsonRequest }); // EventListener für ESC-Taste document.addEventListener('keydown', closeChartDialog); // only hide the background *after* you've moved focus out of // the content that will be "hidden" var div = document.createElement('div'); div.id = 'backdrop'; document.body.appendChild(div); } else { chartDialogSensor = ""; document.removeEventListener('keydown', closeChartDialog); dialog.removeAttribute('open'); var div = document.querySelector('#backdrop'); div.parentNode.removeChild(div); } } function closeChartDialog(event) { if (event.keyCode == 27) toggleChartDialog("", 0); } // --------------------------------- // gauge stuff ... function polar_to_cartesian(cx, cy, radius, angle) { var radians = (angle - 90) * Math.PI / 180.0; return [Math.round((cx + (radius * Math.cos(radians))) * 100) / 100, Math.round((cy + (radius * Math.sin(radians))) * 100) / 100]; }; function svg_circle_arc_path(x, y, radius, start_angle, end_angle) { var start_xy = polar_to_cartesian(x, y, radius, end_angle); var end_xy = polar_to_cartesian(x, y, radius, start_angle); return "M " + start_xy[0] + " " + start_xy[1] + " A " + radius + " " + radius + " 0 0 0 " + end_xy[0] + " " + end_xy[1]; }; // --------------------------------- // drag&drop stuff ... function dragDashboard(ev) { // console.log("drag: " + ev.target.getAttribute('id')); ev.originalEvent.dataTransfer.setData("source", ev.target.getAttribute('id')); } function dragOverDashboard(ev) { event.preventDefault(); var target = ev.target; target.setAttribute('drop-active', true); } function dragLeaveDashboard(ev) { event.preventDefault(); var target = ev.target; target.removeAttribute('drop-active', true); } function dropDashboard(ev) { ev.preventDefault(); var target = ev.target; target.removeAttribute('drop-active', true); // console.log("drop: " + ev.target.getAttribute('id')); var source = document.getElementById(ev.originalEvent.dataTransfer.getData("source")); if (source.dataset.dragtype == 'widget') { var key = source.getAttribute('id').substring(source.getAttribute('id').indexOf("_") + 1); // console.log("drag widget " + key + " from dashboard " + parseInt(actDashboard) + " to " + parseInt(target.getAttribute('id'))); source.remove(); socket.send({ "event" : "storedashboards", "object" : { 'action' : 'move', 'key' : key, 'from' : parseInt(actDashboard), 'to': parseInt(target.getAttribute('id')) } }); return; } if (source.dataset.dragtype != 'dashboard') { console.log("drag source not a dashboard"); return; } // console.log("drop element: " + source.getAttribute('id') + ' on ' + target.getAttribute('id')); target.after(source); // -> The order for json objects follows a certain set of rules since ES2015, // but it does not (always) follow the insertion order. Simply, // the iteration order is a combination of the insertion order for strings keys, // and ascending order for number keys // terefore we use a array instead var jOrder = []; var i = 0; $('#dashboardMenu > button').each(function () { if ($(this).attr('data-dragtype') == 'dashboard') { var did = $(this).attr('id'); console.log("add: " + did); jOrder[i++] = parseInt(did); } }); // console.log("store: " + JSON.stringify( { 'action' : 'order', 'order' : jOrder }, undefined, 4)); socket.send({ "event" : "storedashboards", "object" : { 'action' : 'order', 'order' : jOrder } }); socket.send({ "event" : "forcerefresh", "object" : {} }); } // widgets function dragWidget(ev) { console.log("drag: " + ev.target.getAttribute('id')); ev.dataTransfer.setData("source", ev.target.getAttribute('id')); } function dragOver(ev) { event.preventDefault(); var target = ev.target; while (target) { if (target.dataset.droppoint) break; target = target.parentElement; } target.setAttribute('drop-active', true); } function dragLeave(ev) { event.preventDefault(); var target = ev.target; while (target) { if (target.dataset.droppoint) break; target = target.parentElement; } target.removeAttribute('drop-active', true); } function dropWidget(ev) { ev.preventDefault(); var target = ev.target; while (target) { if (target.dataset.droppoint) break; target = target.parentElement; } target.removeAttribute('drop-active', true); var source = document.getElementById(ev.dataTransfer.getData("source")); if (source.dataset.dragtype != 'widget') { console.log("drag source not a widget"); return; } console.log("drop element: " + source.getAttribute('id') + ' on ' + target.getAttribute('id')); target.after(source); var json = {}; $('#widgetContainer > div').each(function () { var key = $(this).attr('id').substring($(this).attr('id').indexOf("_") + 1); // console.log(" add " + key + " for " + $(this).attr('id')); json[key] = dashboards[actDashboard].widgets[key]; }); // console.log("dashboards " + JSON.stringify(json)); socket.send({ "event" : "storedashboards", "object" : { [actDashboard] : { 'title' : dashboards[actDashboard].title, 'widgets' : json } } }); socket.send({ "event" : "forcerefresh", "object" : {} }); } function dashboardSetup(dashboardId) { var form = document.createElement("div"); if (dashboards[dashboardId].options == null) dashboards[dashboardId].options = {}; $(form).append($('<div></div>') .css('z-index', '9999') .css('minWidth', '40vh') .append($('<div></div>') .css('display', 'flex') .append($('<span></span>') .css('width', '25%') .css('text-align', 'end') .css('align-self', 'center') .css('margin-right', '10px') .html('Titel')) .append($('<span></span>') .append($('<input></input>') .addClass('rounded-border inputSetting') .attr('id', 'dashTitle') .attr('type', 'search') .val(dashboards[dashboardId].title) ))) .append($('<div></div>') .css('display', 'flex') .append($('<span></span>') .css('width', '25%') .css('text-align', 'end') .css('align-self', 'center') .css('margin-right', '10px') .html('Symbol')) .append($('<span></span>') .append($('<input></input>') .addClass('rounded-border inputSetting') .attr('id', 'dashSymbol') .attr('type', 'search') .val(dashboards[dashboardId].symbol) ))) .append($('<div></div>') .css('display', 'flex') .append($('<span></span>') .css('width', '25%') .css('text-align', 'end') .css('align-self', 'center') .css('margin-right', '10px') .html('Zeilenhöhe')) .append($('<span></span>') .append($('<select></select>') .addClass('rounded-border inputSetting') .attr('id', 'heightfactor') .val(dashboards[dashboardId].options.heightfactor) )) .append($('<span></span>') .css('width', '25%') .css('text-align', 'end') .css('align-self', 'center') .css('margin-right', '10px') .html('Kiosk')) .append($('<span></span>') .append($('<select></select>') .addClass('rounded-border inputSetting') .attr('id', 'heightfactorKiosk') .val(dashboards[dashboardId].options.heightfactorKiosk) ))) ); $(form).dialog({ modal: true, resizable: false, closeOnEscape: true, hide: "fade", width: "auto", title: "Dashbord - " + dashboards[dashboardId].title, open: function() { $(".ui-dialog-buttonpane button:contains('Dashboard löschen')").attr('style','color:red'); if (!dashboards[dashboardId].options.heightfactor) dashboards[dashboardId].options.heightfactor = 1; if (!dashboards[dashboardId].options.heightfactorKiosk) dashboards[dashboardId].options.heightfactorKiosk = 1; for (var w = 0.5; w <= 2.0; w += 0.5) { $('#heightfactor').append($('<option></option>') .val(w).html(w).attr('selected', dashboards[dashboardId].options.heightfactor == w)); $('#heightfactorKiosk').append($('<option></option>') .val(w).html(w).attr('selected', dashboards[dashboardId].options.heightfactorKiosk == w)); } }, buttons: { 'Dashboard löschen': function () { console.log("delete dashboard: " + dashboards[dashboardId].title); socket.send({ "event" : "storedashboards", "object" : { [dashboardId] : { 'action' : 'delete' } } }); socket.send({ "event" : "forcerefresh", "object" : {} }); $(this).dialog('close'); }, 'Ok': function () { dashboards[dashboardId].options = {}; dashboards[dashboardId].options.heightfactor = $("#heightfactor").val(); dashboards[dashboardId].options.heightfactorKiosk = $("#heightfactorKiosk").val(); console.log("change title from: " + dashboards[dashboardId].title + " to " + $("#dashTitle").val()); dashboards[dashboardId].title = $("#dashTitle").val(); dashboards[dashboardId].symbol = $("#dashSymbol").val(); socket.send({ "event" : "storedashboards", "object" : { [dashboardId] : { 'title' : dashboards[dashboardId].title, 'symbol' : dashboards[dashboardId].symbol, 'options' : dashboards[dashboardId].options} } }); socket.send({ "event" : "forcerefresh", "object" : {} }); $(this).dialog('close'); }, 'Cancel': function () { $(this).dialog('close'); } }, close: function() { $(this).dialog('destroy').remove(); } }); } function widgetSetup(key) { var item = valueFacts[key]; var widget = dashboards[actDashboard].widgets[key]; var battery = null; if (allSensors[key] != null) { console.log("sensor " + JSON.stringify(allSensors[key], undefined, 4)); console.log("sensor found, batt is : " + allSensors[key].battery); battery = allSensors[key].battery; } else console.log("sensor not found: " + key); if (widget == null) console.log("widget not found: " + key); var form = document.createElement("div"); $(form).append($('<div></div>') .css('z-index', '9999') .css('minWidth', '40vh') .append($('<div></div>') .css('display', 'flex') .append($('<span></span>') .css('width', '30%') .css('text-align', 'end') .css('align-self', 'center') .css('margin-right', '10px') .html('ID')) .append($('<span></span>') .append($('<div></div>') .addClass('rounded-border') .html(key + ' (' + parseInt(key.split(":")[1]) + ')') ))) .append($('<div></div>') .css('display', 'flex') .append($('<span></span>') .css('width', '30%') .css('text-align', 'end') .css('align-self', 'center') .css('margin-right', '10px') .html('Battery')) .append($('<span></span>') .append($('<div></div>') .addClass('rounded-border') .html(battery ? battery + ' %' : '-') ))) .append($('<br></br>')) .append($('<div></div>') .css('display', 'flex') .append($('<span></span>') .css('width', '30%') .css('text-align', 'end') .css('align-self', 'center') .css('margin-right', '10px') .html('Widget')) .append($('<span></span>') .css('width', '300px') .append($('<select></select>') .change(function() {widgetTypeChanged();}) .addClass('rounded-border inputSetting') .attr('id', 'widgettype') ))) .append($('<div></div>') .attr('id', 'divUnit') .css('display', 'flex') .append($('<span></span>') .css('width', '30%') .css('text-align', 'end') .css('align-self', 'center') .css('margin-right', '10px') .html('Einheit')) .append($('<span></span>') .css('width', '300px') .append($('<input></input>') .addClass('rounded-border inputSetting') .attr('type', 'search') .attr('id', 'unit') .val(widget.unit) ))) .append($('<div></div>') .attr('id', 'divFactor') .css('display', 'flex') .append($('<span></span>') .css('width', '30%') .css('text-align', 'end') .css('align-self', 'center') .css('margin-right', '10px') .html('Faktor')) .append($('<span></span>') .append($('<input></input>') .addClass('rounded-border inputSetting') .attr('id', 'factor') .attr('type', 'number') .attr('step', '0.1') .val(widget.factor) ))) .append($('<div></div>') .attr('id', 'divScalemin') .css('display', 'flex') .append($('<span></span>') .css('width', '30%') .css('text-align', 'end') .css('align-self', 'center') .css('margin-right', '10px') .html('Skala Min')) .append($('<span></span>') .append($('<input></input>') .addClass('rounded-border inputSetting') .attr('id', 'scalemin') .attr('type', 'number') .attr('step', '0.1') .val(widget.scalemin) ))) .append($('<div></div>') .attr('id', 'divScalemax') .css('display', 'flex') .append($('<span></span>') .css('width', '30%') .css('text-align', 'end') .css('align-self', 'center') .css('margin-right', '10px') .html('Skala Max')) .append($('<span></span>') .append($('<input></input>') .addClass('rounded-border inputSetting') .attr('id', 'scalemax') .attr('type', 'number') .attr('step', '0.1') .val(widget.scalemax) ))) .append($('<div></div>') .attr('id', 'divScalestep') .css('display', 'flex') .append($('<span></span>') .css('width', '30%') .css('text-align', 'end') .css('align-self', 'center') .css('margin-right', '10px') .html('Skala Step')) .append($('<span></span>') .append($('<input></input>') .addClass('rounded-border inputSetting') .attr('id', 'scalestep') .attr('type', 'number') .attr('step', '0.1') .val(widget.scalestep) ))) .append($('<div></div>') .attr('id', 'divCritmin') .css('display', 'flex') .append($('<span></span>') .css('width', '30%') .css('text-align', 'end') .css('align-self', 'center') .css('margin-right', '10px') .html('Skala Crit Min')) .append($('<span></span>') .css('width', '300px') .append($('<input></input>') .addClass('rounded-border inputSetting') .attr('id', 'critmin') .attr('type', 'number') .attr('step', '0.1') .val(widget.critmin) ))) .append($('<div></div>') .attr('id', 'divCritmax') .css('display', 'flex') .append($('<span></span>') .css('width', '30%') .css('text-align', 'end') .css('align-self', 'center') .css('margin-right', '10px') .html('Skala Crit Max')) .append($('<span></span>') .css('width', '300px') .append($('<input></input>') .addClass('rounded-border inputSetting') .attr('id', 'critmax') .attr('type', 'number') .attr('step', '0.1') .val(widget.critmax) ))) .append($('<div></div>') .attr('id', 'divSymbol') .css('display', 'flex') .append($('<a></a>') .css('width', '30%') .css('text-align', 'end') .css('align-self', 'center') .css('margin-right', '10px') .css('color', 'blue') .html('Icon') .attr('target','_blank') .attr('href', 'https://pictogrammers.github.io/@mdi/font/6.5.95')) .append($('<span></span>') .css('width', '300px') .append($('<input></input>') .addClass('rounded-border inputSetting') .attr('id', 'symbol') .attr('type', 'search') .val(widget.symbol) .change(function() {widgetTypeChanged();}) ))) .append($('<div></div>') .attr('id', 'divSymbolOn') .css('display', 'flex') .append($('<a></a>') .css('width', '30%') .css('text-align', 'end') .css('align-self', 'center') .css('margin-right', '10px') .css('color', 'blue') .html('Icon an') .attr('target','_blank') .attr('href', 'https://pictogrammers.github.io/@mdi/font/6.5.95')) .append($('<span></span>') .css('width', '300px') .append($('<input></input>') .addClass('rounded-border inputSetting') .attr('id', 'symbolOn') .attr('type', 'search') .val(widget.symbolOn) .change(function() {widgetTypeChanged();}) ))) .append($('<div></div>') .attr('id', 'divImgoff') .css('display', 'flex') .append($('<span></span>') .css('width', '30%') .css('text-align', 'end') .css('align-self', 'center') .css('margin-right', '10px') .html('Image')) .append($('<span></span>') .css('width', '300px') .append($('<select></select>') .addClass('rounded-border inputSetting') .attr('id', 'imgoff') ))) .append($('<div></div>') .attr('id', 'divImgon') .css('display', 'flex') .append($('<span></span>') .css('width', '30%') .css('text-align', 'end') .css('align-self', 'center') .css('margin-right', '10px') .html('Image An')) .append($('<span></span>') .css('width', '300px') .append($('<select></select>') .addClass('rounded-border inputSetting') .attr('id', 'imgon') ))) .append($('<div></div>') .attr('id', 'divColor') .css('display', 'flex') .append($('<span></span>') .attr('id', 'spanColor') .css('width', '30%') .css('text-align', 'end') .css('align-self', 'center') .css('margin-right', '10px') .html('Farbe aus / an')) .append($('<span></span>') .append($('<input></input>') .addClass('rounded-border inputSetting') .css('width', '80px') .attr('id', 'color') .attr('type', 'text') .val(widget.color) )) .append($('<span></span>') .append($('<input></input>') .addClass('rounded-border inputSetting') .css('width', '80px') .attr('id', 'colorOn') .attr('type', 'text') .val(widget.colorOn) ))) .append($('<div></div>') .attr('id', 'divPeak') .css('display', 'flex') .append($('<span></span>') .css('width', '30%') .css('text-align', 'end') .css('align-self', 'center') .css('margin-right', '10px') .html('Peak anzeigen')) .append($('<span></span>') .append($('<input></input>') .addClass('rounded-border inputSetting') .attr('id', 'peak') .attr('type', 'checkbox') .prop('checked', widget.showpeak)) .append($('<label></label>') .prop('for', 'peak') ))) .append($('<div></div>') .attr('id', 'divLinefeed') .css('display', 'flex') .append($('<span></span>') .css('width', '30%') .css('text-align', 'end') .css('align-self', 'center') .css('margin-right', '10px') .html('Zeilenumbruch')) .append($('<span></span>') .append($('<input></input>') .addClass('rounded-border inputSetting') .attr('id', 'linefeed') .attr('type', 'checkbox') .prop('checked', widget.linefeed)) .append($('<label></label>') .prop('for', 'linefeed') ))) .append($('<div></div>') .css('display', 'flex') .append($('<span></span>') .css('width', '30%') .css('text-align', 'end') .css('align-self', 'center') .css('margin-right', '10px') .html('Breite')) .append($('<span></span>') .css('width', '300px') .append($('<select></select>') .addClass('rounded-border inputSetting') .attr('id', 'widthfactor') .val(widget.unit) ))) ); function widgetTypeChanged() { var wType = parseInt($('#widgettype').val()); $("#divUnit").css("display", [1,3,4,6,9].includes(wType) ? 'flex' : 'none'); $("#divFactor").css("display", [1,3,4,6,9].includes(wType) ? 'flex' : 'none'); $("#divScalemax").css("display", [5,6].includes(wType) ? 'flex' : 'none'); $("#divScalemin").css("display", [5,6].includes(wType) ? 'flex' : 'none'); $("#divScalestep").css("display", [5,6].includes(wType) ? 'flex' : 'none'); $("#divCritmin").css("display", [5,6].includes(wType) ? 'flex' : 'none'); $("#divCritmax").css("display", [5,6].includes(wType) ? 'flex' : 'none'); $("#divSymbol").css("display", [0,9].includes(wType) ? 'flex' : 'none'); $("#divSymbolOn").css("display", [0,9].includes(wType) ? 'flex' : 'none'); $("#divImgon").css("display", ([0,9].includes(wType) && $('#symbol').val() == '') ? 'flex' : 'none'); $("#divImgoff").css("display", ([0,9].includes(wType) && $('#symbol').val() == '') ? 'flex' : 'none'); $("#divPeak").css("display", [1,3,6,9].includes(wType) ? 'flex' : 'none'); $("#divColor").css("display", [0,1,3,4,6,7,9,10,11].includes(wType) ? 'flex' : 'none'); $("#divLinefeed").css("display", [10].includes(wType) ? 'flex' : 'none'); if ([0].includes(wType) && $('#symbol').val() == '' && $('#symbolOn').val() == '') $("#divColor").css("display", 'none'); if (![0,9].includes(wType) || $('#symbolOn').val() == '') { $('.spColorOn').css('display', 'none'); $('#spanColor').html("Farbe"); } else { $('.spColorOn').css('display', 'flex'); $('#spanColor').html("Farbe aus / an"); } } var title = key.split(":")[0]; if (item != null) title = (item.usrtitle ? item.usrtitle : item.title); $(form).dialog({ modal: true, resizable: false, closeOnEscape: true, hide: "fade", width: "auto", title: "Widget - " + title, open: function() { for (var wdKey in widgetTypes) { $('#widgettype').append($('<option></option>') .val(widgetTypes[wdKey]) .html(wdKey) .attr('selected', widgetTypes[wdKey] == widget.widgettype)); } images.sort(); for (var img in images) { $('#imgoff').append($('<option></option>') .val(images[img]) .html(images[img]) .attr('selected', widget.imgoff == images[img])); $('#imgon').append($('<option></option>') .val(images[img]) .html(images[img]) .attr('selected', widget.imgon == images[img])); } if (widget.widthfactor == null) widget.widthfactor = 1; for (var w = 0.5; w <= 2.0; w += 0.5) $('#widthfactor').append($('<option></option>') .val(w) .html(w) .attr('selected', widget.widthfactor == w)); $('#color').spectrum({ type: "color", showPalette: true, showSelectionPalette: true, palette: [ ], localStorageKey: "homectrl", togglePaletteOnly: false, showInitial: true, showAlpha: true, allowEmpty: false, replacerClassName: 'spColor' }); $('#colorOn').spectrum({ type : "color", showPalette: true, showSelectionPalette: true, palette: [ ], localStorageKey: "homectrl", togglePaletteOnly: false, showInitial: true, showAlpha: true, allowEmpty: false, replacerClassName: 'spColorOn' }); var wType = parseInt($('#widgettype').val()); if (![0,9].includes(wType) || $('#symbolOn').val() == '') { $('.spColorOn').css('display', 'none'); $('#spanColor').html("Farbe"); } widgetTypeChanged(); $(".ui-dialog-buttonpane button:contains('Widget löschen')").attr('style','color:red'); }, buttons: { 'Widget löschen': function () { console.log("delete widget: " + key); document.getElementById('div_' + key).remove(); var json = {}; $('#widgetContainer > div').each(function () { var key = $(this).attr('id').substring($(this).attr('id').indexOf("_") + 1); json[key] = dashboards[actDashboard].widgets[key]; }); // console.log("delete widget " + JSON.stringify(json, undefined, 4)); socket.send({ "event" : "storedashboards", "object" : { [actDashboard] : { 'title' : dashboards[actDashboard].title, 'widgets' : json } } }); socket.send({ "event" : "forcerefresh", "object" : {} }); $(this).dialog('close'); }, 'Cancel': function () { // socket.send({ "event" : "forcerefresh", "object" : {} }); if (allSensors[key] == null) { console.log("missing sensor!!"); } initWidget(key, dashboards[actDashboard].widgets[key]); updateWidget(allSensors[key], true, dashboards[actDashboard].widgets[key]); $(this).dialog('close'); }, 'Preview': function () { widget = Object.create(dashboards[actDashboard].widgets[key]); // valueFacts[key]); widget.unit = $("#unit").val(); widget.scalemax = parseFloat($("#factor").val()) || 1.0; widget.scalemax = parseFloat($("#scalemax").val()) || 0.0; widget.scalemin = parseFloat($("#scalemin").val()) || 0.0; widget.scalestep = parseFloat($("#scalestep").val()) || 0.0; widget.critmin = parseFloat($("#critmin").val()) || -1; widget.critmax = parseFloat($("#critmax").val()) || -1; widget.symbol = $("#symbol").val(); widget.symbolOn = $("#symbolOn").val(); widget.imgon = $("#imgon").val(); widget.imgoff = $("#imgoff").val(); widget.widgettype = parseInt($("#widgettype").val()); widget.color = $("#color").spectrum('get').toRgbString(); widget.colorOn = $("#colorOn").spectrum('get').toRgbString(); widget.showpeak = $("#peak").is(':checked'); widget.linefeed = $("#linefeed").is(':checked'); widget.widthfactor = $("#widthfactor").val(); initWidget(key, widget); if (allSensors[key] != null) updateWidget(allSensors[key], true, widget); }, 'Ok': function () { widget.unit = $("#unit").val(); widget.scalemax = parseFloat($("#factor").val()) || 1.0; widget.scalemax = parseFloat($("#scalemax").val()) || 0.0; widget.scalemin = parseFloat($("#scalemin").val()) || 0.0; widget.scalestep = parseFloat($("#scalestep").val()) || 0.0; widget.critmin = parseFloat($("#critmin").val()) || -1; widget.critmax = parseFloat($("#critmax").val()) || -1; widget.symbol = $("#symbol").val(); widget.symbolOn = $("#symbolOn").val(); widget.imgon = $("#imgon").val(); widget.imgoff = $("#imgoff").val(); widget.widgettype = parseInt($("#widgettype").val()); widget.color = $("#color").spectrum("get").toRgbString(); widget.colorOn = $("#colorOn").spectrum("get").toRgbString(); widget.showpeak = $("#peak").is(':checked'); widget.linefeed = $("#linefeed").is(':checked'); widget.widthfactor = $("#widthfactor").val(); initWidget(key, widget); if (allSensors[key] != null) updateWidget(allSensors[key], true, widget); var json = {}; $('#widgetContainer > div').each(function () { var key = $(this).attr('id').substring($(this).attr('id').indexOf("_") + 1); json[key] = dashboards[actDashboard].widgets[key]; }); if ($("#unit").length) json[key]["unit"] = $("#unit").val(); if ($("#factor").length) json[key]["factor"] = parseFloat($("#factor").val()); if ($("#scalemax").length) json[key]["scalemax"] = parseFloat($("#scalemax").val()); if ($("#scalemin").length) json[key]["scalemin"] = parseFloat($("#scalemin").val()); if ($("#scalestep").length) json[key]["scalestep"] = parseFloat($("#scalestep").val()); if ($("#critmin").length) json[key]["critmin"] = parseFloat($("#critmin").val()); if ($("#critmax").length) json[key]["critmax"] = parseFloat($("#critmax").val()); if ($("#symbol").length) json[key]["symbol"] = $("#symbol").val(); if ($("#symbolOn").length) json[key]["symbolOn"] = $("#symbolOn").val(); if ($("#imgon").length) json[key]["imgon"] = $("#imgon").val(); if ($("#imgoff").length) json[key]["imgoff"] = $("#imgoff").val(); json[key]["widthfactor"] = parseFloat($("#widthfactor").val()); json[key]["widgettype"] = parseInt($("#widgettype").val()); json[key]["showpeak"] = $("#peak").is(':checked'); json[key]["linefeed"] = $("#linefeed").is(':checked'); json[key]["color"] = $("#color").spectrum("get").toRgbString(); json[key]["colorOn"] = $("#colorOn").spectrum("get").toRgbString(); socket.send({ "event" : "storedashboards", "object" : { [actDashboard] : { 'title' : dashboards[actDashboard].title, 'widgets' : json } } }); socket.send({ "event" : "forcerefresh", "object" : {} }); $(this).dialog('close'); } }, close: function() { $(this).dialog('destroy').remove(); } }); }
horchi/linux-p4d
htdocs/dashboard.js
JavaScript
gpl-2.0
96,718
angular.module('bhima.controllers') .controller('StockDefineLotsModalController', StockDefineLotsModalController); StockDefineLotsModalController.$inject = [ 'appcache', '$uibModalInstance', 'uiGridConstants', 'data', 'LotService', 'InventoryService', 'SessionService', 'CurrencyService', 'NotifyService', 'ExchangeRateService', 'ModalService', 'BarcodeService', 'StockEntryModalForm', 'bhConstants', '$translate', 'focus', ]; function StockDefineLotsModalController( AppCache, Instance, uiGridConstants, Data, Lots, Inventory, Session, Currencies, Notify, ExchangeRate, Modal, Barcode, EntryForm, bhConstants, $translate, Focus, ) { const vm = this; const cache = new AppCache('StockEntryModal'); // initialize the form instance if (Data.stockLine.wac) { Data.stockLine.unit_cost = Data.stockLine.wac; } vm.serialNumberVisible = Data.stockLine.is_asset; const tracking = Data.stockLine.tracking_expiration; Data.stockLine.prev_unit_cost = Data.stockLine.unit_cost; // Save for later checks vm.form = new EntryForm({ max_quantity : Data.stockLine.quantity, unit_cost : Data.stockLine.unit_cost, tracking_expiration : tracking, entry_date : Data.entry_date, rows : Data.stockLine.lots, }); vm.bhConstants = bhConstants; vm.hasMissingLotIdentifier = false; vm.hasInvalidLotExpiration = false; vm.hasInvalidLotQuantity = false; vm.hasDuplicateLotInvent = false; vm.hasDuplicateLotOrder = false; vm.globalExpirationDate = new Date(); vm.enableGlobalDescriptionAndExpiration = false; vm.enterprise = Session.enterprise; vm.stockLine = angular.copy(Data.stockLine); vm.entryType = Data.entry_type; vm.entryDate = Data.entry_date; vm.currencyId = Data.currency_id !== undefined ? Data.currency_id : vm.enterprise.currency_id; vm.currency = null; vm.isTransfer = (vm.entryType === 'transfer_reception'); // Get the status for this inventory article Inventory.getInventoryUnitCosts(Data.stockLine.inventory_uuid) .then(({ stats }) => { // Save the stats for later checks vm.stockLine.stats = stats; }); // exposing method to the view vm.submit = submit; vm.cancel = cancel; vm.onLotBlur = onLotBlur; vm.addItems = addItems; vm.removeItem = removeItem; vm.onChanges = onChanges; vm.onChangeQuantity = onChangeQuantity; vm.onExpDateEditable = onExpDateEditable; vm.onChangeUnitCost = onChangeUnitCost; vm.onSelectLot = onSelectLot; vm.onDateChange = onDateChange; vm.enterLotByBarcode = enterLotByBarcode; vm.onGlobalDateChange = onGlobalDateChange; vm.toggleGlobalDescExpColumn = toggleGlobalDescExpColumn; vm.isCostEditable = (vm.entryType !== 'transfer_reception'); vm.editExpirationDates = false; const cols = [{ field : 'status', width : 25, displayName : '', cellTemplate : 'modules/stock/entry/modals/templates/lot.status.tmpl.html', }, { field : 'lot', displayName : 'TABLE.COLUMNS.LOT', headerCellFilter : 'translate', aggregationType : uiGridConstants.aggregationTypes.count, aggregationHideLabel : true, cellTemplate : 'modules/stock/entry/modals/templates/lot.input.tmpl.html', }, { field : 'reference_number', displayName : 'FORM.LABELS.REFERENCE_NUMBER', headerCellFilter : 'translate', visible : false, width : 150, cellTemplate : '/modules/stock/lots/templates/reference_number.cell.html', }, { field : 'serial_number', displayName : 'TABLE.COLUMNS.SERIAL_NUMBER', headerCellFilter : 'translate', aggregationHideLabel : true, visible : vm.serialNumberVisible, width : 220, cellTemplate : 'modules/stock/entry/modals/templates/serial_number.input.tmpl.html', }, { field : 'barcode', displayName : 'BARCODE.BARCODE', headerCellFilter : 'translate', width : 110, cellTemplate : 'modules/stock/entry/modals/templates/lot.barcode.tmpl.html', }, { field : 'quantity', type : 'number', width : 120, displayName : 'TABLE.COLUMNS.QUANTITY', headerCellFilter : 'translate', aggregationType : uiGridConstants.aggregationTypes.sum, aggregationHideLabel : true, footerCellClass : 'text-right', cellTemplate : 'modules/stock/entry/modals/templates/lot.quantity.tmpl.html', }, { field : 'expiration_date', type : 'date', cellFilter : `date:"${bhConstants.dates.format}"`, width : 150, visible : tracking, displayName : 'TABLE.COLUMNS.EXPIRATION_DATE', headerCellFilter : 'translate', cellTemplate : 'modules/stock/entry/modals/templates/lot.expiration.tmpl.html', }, { field : 'actions', displayName : '', width : 25, cellTemplate : 'modules/stock/entry/modals/templates/lot.actions.tmpl.html', }]; vm.gridOptions = { appScopeProvider : vm, enableSorting : false, enableColumnResize : true, enableColumnMenus : false, showColumnFooter : true, fastWatch : true, flatEntityAccess : true, data : vm.form.rows, minRowsToShow : 4, columnDefs : cols, onRegisterApi, }; function init() { if (cache.enableFastInsert) { vm.enableFastInsert = cache.enableFastInsert; } // Load the currency info Currencies.read() .then((currencies) => { vm.currency = currencies.find(curr => curr.id === vm.currencyId); vm.currency.label = Currencies.format(vm.currencyId); const rate = ExchangeRate.getExchangeRate(vm.currencyId, new Date()); vm.wacValue = rate * Data.stockLine.wacValue; }) .catch(Notify.handleError); if (vm.form.rows.length) { // If we are visiting the form again, re-validate it validateForm(); return; } vm.form.addItem(); } function onRegisterApi(api) { vm.gridApi = api; } function toggleGlobalDescExpColumn(value) { const EXPIRATION_DATE_COLUMN = 4; cols[EXPIRATION_DATE_COLUMN].visible = !!value; vm.gridApi.grid.refresh(); } function lookupLotByLabel(label) { return vm.stockLine.availableLots .find(l => l.label.toUpperCase() === label.toUpperCase()); } function lookupLotByUuid(uuid) { return vm.stockLine.availableLots .find(l => l.uuid === uuid); } /** * @method getExistingLot * * @description * If the lot given is a string, it is a label, so look it up by label. * If the lot is not a string, it will contain the lots UUID, use it to look up the lot * @param {lot} the 'lot' object from the lot selection popup modal form */ function getExistingLot(lot) { return typeof lot === 'string' ? lookupLotByLabel(lot) : lookupLotByUuid(lot.uuid); } // Handle the extra validation for expired lot labels function validateForm() { vm.errors = vm.form.validate(vm.entryDate); vm.form.rows.forEach((row) => { if (!row.lot) { // Ignore corner case where the user clicks elsewhere // BEFORE typing in a lot name return; } const existingLot = getExistingLot(row.lot); row.editExpDateDisabled = (existingLot && !vm.editExpirationDates); // Check to make sure the lot has not expired if (existingLot && existingLot.expired) { vm.errors.push($translate.instant('ERRORS.ER_STOCK_LOT_IS_EXPIRED', { label : existingLot.label })); vm.form.$invalid = true; } }); } /** * @method onLotBlur * * @description * if the fast insert option is enable do this : * - add new row automatically on blur * - set the focus in the new row * @param {string} rowLot the row.entity.lot string/object */ function onLotBlur(rowLot) { // NOTE: rowLot will be an object if an existed lot was // selected from the typeahead. Otherwise // it will be the lot name string that was typed in. // Complain if the lot exists and is expired. if (!rowLot) { // Handle corner case return; } vm.errors = vm.form.validate(vm.entryDate); // First make sure that if the entered lot label exists // that it is not expired const rowLotLabel = typeof rowLot === 'string' ? rowLot : rowLot.label; const existingLot = vm.stockLine.availableLots .find(l => l.label.toUpperCase() === rowLotLabel.toUpperCase()); if (rowLot && existingLot && existingLot.expired) { vm.errors.push($translate.instant('ERRORS.ER_STOCK_LOT_IS_EXPIRED', { label : existingLot.label })); vm.form.$invalid = true; return; } if (vm.enableFastInsert && rowLot) { const emptyLotRow = getFirstEmptyLot(); if (emptyLotRow) { if (vm.enableGlobalDescriptionAndExpiration && vm.globalExpirationDate) { emptyLotRow.expiration_date = vm.globalExpirationDate; } // don't add new row but focus on the empty lot row Focus(emptyLotRow.identifier); } else { // add a new row const newLotRow = vm.form.addItem(); if (vm.enableGlobalDescriptionAndExpiration && vm.globalExpirationDate) { newLotRow.expiration_date = vm.globalExpirationDate; } // set the focus on the new row Focus(newLotRow.identifier); } } } function removeItem(rowRenderIndex) { vm.form.removeItem(rowRenderIndex); vm.errors = vm.form.validate(vm.entryDate); } function addItems(n) { const defaultValues = vm.enableGlobalDescriptionAndExpiration && vm.globalExpirationDate ? { expiration_date : vm.globalExpirationDate } : {}; vm.form.addItems(n, defaultValues); } function getFirstEmptyLot() { let line; for (let i = 0; i < vm.form.rows.length; i++) { const row = vm.form.rows[i]; if (!row.lot || row.lot.length === 0) { line = row; break; } } return line; } function onChanges() { validateForm(); vm.gridApi.core.notifyDataChange(uiGridConstants.dataChange.EDIT); } // validate only if there are lots rows function onChangeQuantity() { vm.form.setMaxQuantity(vm.stockLine.quantity); if (!vm.form.rows.length) { return; } onChanges(); } function onExpDateEditable() { vm.form.rows.forEach((row) => { if (row.lot === null) { return; } row.editExpDateDisabled = (getExistingLot(row.lot) && !vm.editExpirationDates); }); } function onChangeUnitCost() { // Sanity check on new unit cost const prevPurchases = vm.stockLine.stats.median_unit_cost !== null; // NOTE: If there are no previous purchases, there is no purchase history to rely on // for sanity checks so use the unit cost was from the purchase order for the sanity check const prevUnitCost = Number(vm.stockLine.prev_unit_cost); const medianUnitCost = prevPurchases ? Number(vm.stockLine.stats.median_unit_cost) : prevUnitCost; const newUnitCost = Number(vm.stockLine.unit_cost); const allowableMinChange = 0.5; // Warn about entries that are less than half the previous unit cost const allowableMaxChange = 2.0; // Warn entries that more than double the previous unit cost const lowerUnitCostBound = (medianUnitCost * allowableMinChange); const upperUnitCostBound = (medianUnitCost * allowableMaxChange); if ((newUnitCost < lowerUnitCostBound) || (newUnitCost > upperUnitCostBound)) { const msgParams = { newUnitCost, medianUnitCost, curr : vm.currency.symbol }; const errMsg1 = newUnitCost > upperUnitCostBound ? $translate.instant('WARNINGS.WARN_UNIT_COST_TOO_HIGH', msgParams) : $translate.instant('WARNINGS.WARN_UNIT_COST_TOO_LOW', msgParams); const errMsg = errMsg1 .concat($translate.instant('WARNINGS.WARN_UNIT_COST_REASON')) .concat($translate.instant('WARNINGS.WARN_UNIT_COST_CONFIRM')); Modal.confirm(errMsg) .then(() => { // Accept the new unit cost into the form vm.form.setUnitCost(vm.stockLine.unit_cost); onChanges(); }) .catch(() => { // Revert to the previous unit cost in the form and display the warning vm.stockLine.unit_cost = prevUnitCost; vm.form.setUnitCost(vm.stockLine.unit_cost); vm.errors = [errMsg1]; vm.form.$invalid = true; }); return; } vm.form.setUnitCost(vm.stockLine.unit_cost); onChanges(); } function onDateChange(date, row) { if (date) { row.expiration_date = date; onChanges(); } } function lotMatch(row, label) { if (row.lot === null) { return false; } if (typeof row.lot === 'string') { return row.lot.toUpperCase() === label; } if (typeof row.lot.label === 'string') { return row.lot.label.toUpperCase() === label; } return false; } function lookupLotInForm(label) { return vm.form.rows.find(row => lotMatch(row, label)); } /** * @method enterLotByBarcode * * @description * Pops up modal to scan the lot barcode * * @param {object} row the affected row */ function enterLotByBarcode(row) { Barcode.modal({ shouldSearch : false }) .then(record => { if (record.uuid) { const newLotLabel = record.uuid.toUpperCase(); if (vm.enableGlobalDescriptionAndExpiration) { // In this mode, the new lot IDs must not already be known or in already entered // TODO: Make this a separate user check box option? if (lookupLotByLabel(record.uuid)) { vm.errors.push($translate.instant('STOCK.DUPLICATE_LOT_INVENTORY')); vm.form.$invalid = true; return; } if (lookupLotInForm(newLotLabel)) { vm.errors.push($translate.instant('STOCK.DUPLICATE_LOT_ORDER')); vm.form.$invalid = true; return; } } // Save the new lot! row.lot = newLotLabel; if (vm.enableGlobalDescriptionAndExpiration && vm.globalExpirationDate) { row.expiration_date = vm.globalExpirationDate; } onChanges(); if (vm.enableFastInsert) { vm.form.addItem(); } } }); } function onGlobalDateChange(date) { if (date) { vm.globalExpirationDate = date; vm.form.rows.forEach((row) => { row.expiration_date = vm.globalExpirationDate; }); onChanges(); } } /** * @method onSelectLot * * @description * Updates the expiration field based on the date in * the corresponding candidate lot. * * NOTE: This function is only called when a lot is selected * from the typeahead (which is created from the list * valid candidate lots for this inventory item). So * the 'find()' below should always work. * * @param {object} entity the row.entity.lot object (being displayed) * @param {object} item the active typeahead model object */ function onSelectLot(entity, item) { const lot = vm.stockLine.candidateLots.find(l => l.uuid === item.uuid); entity.expiration_date = new Date(lot.expiration_date); entity.editExpDateDisabled = !vm.editExpirationDates; onChanges(); } function cancel() { saveSetting(); Instance.close(); } function submit(form) { validateForm(); // unfortunately, a negative number will not trigger the onChange() function // on the quantity, since the "min" property is set on the input. So, we // need to through a generic error here. if (form.$invalid) { return null; } // Handle differences in selecting vs creating lots vm.form.rows.forEach((row) => { if (typeof row.lot !== 'string') { const { label, uuid } = row.lot; row.lot = label; row.uuid = uuid; } if (vm.enableGlobalDescriptionAndExpiration && vm.description) { row.description = vm.description; } }); // Maybe update some lot expiration dates const promises = []; if (vm.editExpirationDates) { vm.form.rows.forEach((row) => { const existingLot = getExistingLot(row.lot); if (existingLot && (row.expiration_date !== existingLot.expiration_date)) { promises.push(Lots.update(existingLot.uuid, { expiration_date : row.expiration_date })); } }); } return Promise.all(promises) .then(() => { saveSetting(); Instance.close({ lots : vm.form.rows, unit_cost : vm.stockLine.unit_cost, quantity : vm.form.total(), }); }) .catch(Notify.handleError); } function saveSetting() { // save the cache setting cache.enableFastInsert = vm.enableFastInsert; } init(); }
IMA-WorldHealth/bhima
client/src/modules/stock/entry/modals/lots.modal.js
JavaScript
gpl-2.0
16,796
/*----------------------------------------------------------------------------------| www.giz.de |----/ Deutsche Gesellschaft für International Zusammenarbeit (GIZ) Gmb /-------------------------------------------------------------------------------------------------------/ @version 3.4.x @build 2nd March, 2022 @created 15th June, 2012 @package Cost Benefit Projection @subpackage health_data.js @author Llewellyn van der Merwe <http://www.vdm.io> @owner Deutsche Gesellschaft für International Zusammenarbeit (GIZ) Gmb @copyright Copyright (C) 2015. All Rights Reserved @license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html /-------------------------------------------------------------------------------------------------------/ Cost Benefit Projection Tool. /------------------------------------------------------------------------------------------------------*/ jQuery(document).ready(function() { var values_a = jQuery('#jform_maledeath').val(); if (values_a) { values_a = jQuery.parseJSON(values_a); buildTable(values_a,'jform_maledeath'); } var values_b = jQuery('#jform_femaledeath').val(); if (values_b) { values_b = jQuery.parseJSON(values_b); buildTable(values_b,'jform_femaledeath'); } var values_c = jQuery('#jform_maleyld').val(); if (values_c) { values_c = jQuery.parseJSON(values_c); buildTable(values_c,'jform_maleyld'); } var values_d = jQuery('#jform_femaleyld').val(); if (values_d) { values_d = jQuery.parseJSON(values_d); buildTable(values_d,'jform_femaleyld'); } }); function buildTable(array,id){ jQuery('#table_'+id).remove(); jQuery('#'+id).closest('.control-group').append('<table style="margin: 5px 0 20px;" class="table" id="table_'+id+'">'); jQuery('#table_'+id).append(tableHeader(array)); jQuery('#table_'+id).append(tableBody(array)); jQuery('#table_'+id).append('</table>'); } function tableHeader(array) { var header = '<thead><tr>'; jQuery.each(array, function(key, value) { header += '<th style="padding: 10px; text-align: center; border: 1px solid rgb(221, 221, 221);">'+capitalizeFirstLetter(key)+'</th>'; }); header += '</tr></thead>'; return header; } function tableBody(array) { var body = '<tbody>'; var rows = new Array(); jQuery.each(array, function(key, value) { jQuery.each(value, function(i, line) { if( rows[i] === undefined ) { rows[i] = '<td style="padding: 10px; text-align: center; border: 1px solid rgb(221, 221, 221);">' + line + '</td>'; } else { rows[i] = rows[i] + '<td style="padding: 10px; text-align: center; border: 1px solid rgb(221, 221, 221);">' + line + '</td>'; } }); }); // now load to body the rows jQuery.each(rows, function(a, row) { body += '<tr>' + row + '</tr>'; }); body += '</tbody>'; return body; } function capitalizeFirstLetter(string) { return string.charAt(0).toUpperCase() + string.slice(1); }
namibia/CBP-Joomla-3-Component
media/js/health_data.js
JavaScript
gpl-2.0
3,118
module.exports = function(grunt) { require('load-grunt-tasks')(grunt); grunt.initConfig({ pkg: grunt.file.readJSON( 'package.json' ), makepot: { target: { options: { domainPath: '/languages', // Where to save the POT file. exclude: ['.git/.*', '.svn/.*', '.node_modules/.*', '.vendor/.*'], mainFile: 'anspress-question-answer.php', potHeaders: { poedit: true, // Includes common Poedit headers. 'x-poedit-keywordslist': true // Include a list of all possible gettext functions. }, // Headers to add to the generated POT file. type: 'wp-plugin', // Type of project (wp-plugin or wp-theme). updateTimestamp: true // Whether the POT-Creation-Date should be updated without other changes. } } }, addtextdomain: { options: { textdomain: 'anspress-question-answer', // Project text domain. updateDomains: ['ap'] // List of text domains to replace. }, target: { files: { src: [ '*.php', '**/*.php', '!node_modules/**', '!tests/**', '!.git/.*', '!.svn/.*', '!.vendor/.*' ] } } }, phpdocumentor: { dist: { options: { directory : './', target : 'M:\wamp\www\anspress-docs\\' } } }, csscomb: { files: ['**/*.css', '!**/node_modules/**'], tasks: ['csscomb'], }, copy: { main: { files: [ {nonull:true, expand: true, cwd: 'M:\\xampp\\htdocs\\anspress\\wp-content\\plugins\\anspress-question-answer', src: ['**/*', '!**/.git/**', '!**/.svn/**', '!**/node_modules/**', '!**/bin/**', '!**/docs/**', '!**/tests/**'], dest: 'M:\\wamp\\www\\aptest\\wp-content\\plugins\\anspress-question-answer'}, {nonull:true, expand: true, cwd: 'M:\\xampp\\htdocs\\anspress\\wp-content\\plugins\\anspress-question-answer', src: ['**/*', '!**/.git/**', '!**/.svn/**', '!**/node_modules/**', '!**/bin/**', '!**/docs/**', '!**/tests/**'], dest: 'M:\\xampp\\htdocs\\askbug\\wp-content\\plugins\\anspress-question-answer'} ] } }, version: { css: { options: { prefix: 'Version\\:\\s' }, src: [ 'style.css' ], }, php: { options: { prefix: 'Version\\:\\s+' }, src: [ 'anspress-question-answer.php' ], }, mainplugin: { options: { pattern: '\$_plugin_version = (?:\')(.+)(?:\')/g' }, src: [ 'anspress-question-answer.php' ], }, project: { src: ['plugin.json'] } }, sass: { dist: { options: { style: 'expanded' }, files: { "templates/css/main.css": "templates/scss/main.scss", "templates/css/RTL.css": "templates/scss/RTL.scss", "assets/ap-admin.css": "assets/ap-admin.scss" } } }, uglify: { my_target: { files: { 'assets/js/min/question.min.js': ['assets/js/question.js'], 'assets/js/min/common.min.js': ['assets/js/common.js'], 'assets/js/min/upload.min.js': ['assets/js/upload.js'], 'assets/js/min/ap-admin.min.js': ['assets/js/ap-admin.js'], 'assets/js/min/ask.min.js': ['assets/js/ask.js'], 'assets/js/min/list.min.js': ['assets/js/list.js'], 'assets/js/min/tags.min.js': ['assets/js/tags.js'], 'assets/js/min/notifications.min.js': ['assets/js/notifications.js'], 'templates/js/min/theme.min.js': ['templates/js/theme.js'], } } }, wp_readme_to_markdown: { your_target: { files: { 'README.md': 'readme.txt' }, }, }, phplint : { options : { spawn : false }, all: ['**/*.php'] }, cssmin: { options: { shorthandCompacting: false, roundingPrecision: -1, rebase: true }, target: { files: { 'templates/css/min/main.min.css': 'templates/css/main.css', 'templates/css/min/RTL.min.css': 'templates/css/RTL.css', 'templates/css/min/fonts.min.css': 'templates/css/fonts.css', 'assets/ap-admin.min.css': 'assets/ap-admin.css' } } }, watch: { sass: { files: ['**/*.scss'], tasks: ['sass', 'cssmin'], }, uglify: { files: ['templates/js/*.js','assets/js/*.js'], tasks: ['uglify'], } }, }); grunt.registerTask( 'build', [ 'phplint', 'makepot', 'version', 'sass', 'uglify', 'compress' ]); }
priard/anspress
Gruntfile.js
JavaScript
gpl-2.0
4,416
var KEYS = { moveForward: 119, moveBackward: 115, strideLeft: 97, strideRight: 100, turnLeft: 113, turnRight: 101 }; function processKeyPress(key) { switch (key) { case KEYS.moveForward: if (!dr.webGLPositionDiff.anythingToMove) { party.position.forward(); } break; case KEYS.turnLeft: if (!dr.webGLPositionDiff.anythingToMove) { party.position.turn(TURN_LEFT); } break; case KEYS.moveBackward: if (!dr.webGLPositionDiff.anythingToMove) { party.position.backward(); } break; case KEYS.turnRight: if (!dr.webGLPositionDiff.anythingToMove) { party.position.turn(TURN_RIGHT); } break; case KEYS.strideLeft: if (!dr.webGLPositionDiff.anythingToMove) { party.position.strideLeft(); } break; case KEYS.strideRight: if (!dr.webGLPositionDiff.anythingToMove) { party.position.strideRight(); } break; } dr.startMovingParty(); hud.refresh(); }
lotcz/ghobok
src/controls.js
JavaScript
gpl-2.0
932
function capitalise(t){return t.charAt(0).toUpperCase()+t.slice(1)}function cleanseCSV(t){var e=t.split(",");return _.map(e,function(t){return t.trim()})}function getCSSPath(){return _.getDebug(),"/assets/css/litchi.css"}function getDebug(){var t=document.location.hostname,e=["localhost"];return-1==_.indexOf(e,t)?!1:!0}function returnLayout(t){return"app/sections/section."+t+"/layout.html"}_.mixin({capitalise:capitalise}),_.mixin({cleanseCSV:cleanseCSV}),_.mixin({getCSSPath:getCSSPath}),_.mixin({getDebug:getDebug}),_.mixin({returnLayout:returnLayout});
slavomirvojacek/litchi-www
www/app/build/lodash.js
JavaScript
gpl-2.0
558
/** * Youxi Gallery Form Field JS * * This script contains the initialization code for the gallery form field. * * @package Youxi Core * @author Mairel Theafila <maimairel@gmail.com> * @copyright Copyright (c) 2013-2015, Mairel Theafila */ ;(function( $, window, document, undefined ) { "use strict"; if( 'undefined' == typeof wp || ! wp.media || ! wp.media.gallery || ! $.widget ) return; var media = wp.media, gallery = wp.media.gallery; $.widget( 'youxi.galleryform', { options: { fieldName: '' }, _mediaTemplate: media.template( 'youxi-gallery-preview' ), _create: function() { /* Bind event handlers */ this._on({ 'click': function( e ) { this.open(); e.preventDefault(); } }); /* Extract attachment ids upon creation */ this.ids = $( '.youxi-gallery-preview-item', this.element ).map(function() { return $( this ).find( 'input.youxi-gallery-value' ).val(); }).get(); if( ! this.ids.length ) { /* Prefetch attachment to prevent uploader to get stuck */ gallery.attachments( wp.shortcode.next( 'gallery', '[gallery]' ).shortcode ).more(); } }, _handleUpdate: function( attachments ) { /* Generate gallery preview from selected attachments */ var galleryItems = attachments.map(function( attachment ) { return this._mediaTemplate({ id: attachment.id, url: this._getAttachmentSize( attachment, 'thumbnail' ).url, fieldName: this.options.fieldName }); }, this ).join( '' ); /* Extract attachment ids */ this.ids = attachments.pluck( 'id' ); /* Append all generated gallery previews */ $( '.youxi-gallery-previews', this.element ) .html( galleryItems ); }, _getAttachmentSize: function( attachment, size ) { var sizes = attachment.attributes.sizes || {}; if( _.has( sizes, size ) ) { return _.pick( sizes[ size ], 'url' ); } return { url: attachment.url }; }, open: function() { var frame = gallery.edit( '[gallery' + ( this.ids ? ' ids="' + this.ids.join( ',' ) + '"' : '' ) + ']' ); frame.state( 'gallery-edit' ).on( 'update', this._handleUpdate, this ); frame.on( 'close', function() { frame.detach(); }); } }); if( $.Youxi.Form.Manager ) { $.Youxi.Form.Manager.addCallbacks( 'gallery_form', function( context ) { if( $.fn.galleryform ) { $( '.youxi-gallery-form', context ).each( function() { $( this ).galleryform( $( this ).data() ); }); } }, function( context ) { if( $.fn.galleryform ) { $( '.youxi-gallery-form:youxi-galleryform', context ).each( function() { $( this ).galleryform( 'destroy' ); }); } }); } })( jQuery, window, document );
yemingyuen/mingsg
wp-content/plugins/youxi-core/admin/field_assets/js/youxi.form.gallery.js
JavaScript
gpl-2.0
2,808
/** * Creates an instance of the canvas. Also handles the configuration of the canvas. * @constructor * @param {HTML} document - The descriptor of the HTML. */ function GraphicsDevice(document) { "use strict"; /*global Element*/ this.canvas = document.querySelector("canvas"); } /** * Gets the preferred back-buffer height. * @name PreferredBackBufferHeight * @function * @memberOf GraphicsDevice */ GraphicsDevice.prototype.PreferredBackBufferHeight = function () { "use strict"; return this.canvas.height; }; /** * Gets the preferred back-buffer width. * @name PreferredBackBufferWidth * @function * @memberOf GraphicsDevice */ GraphicsDevice.prototype.PreferredBackBufferWidth = function () { "use strict"; return this.canvas.width; }; /** * Specifies the default minimum back-buffer height (600). * @name DefaultBackBufferHeight * @function * @memberOf GraphicsDevice * @static */ GraphicsDevice.prototype.DefaultBackBufferHeight = function () { "use strict"; return 600; }; /** * Specifies the default minimum back-buffer width (800). * @name DefaultBackBufferWidth * @function * @memberOf GraphicsDevice * @static */ GraphicsDevice.prototype.DefaultBackBufferWidth = function () { "use strict"; return 800; }; /** * Toggles between full page and windowed mode. * @name ToggleFullPage * @function * @memberOf GraphicsDevice */ GraphicsDevice.prototype.ToggleFullPage = function () { "use strict"; var self = this, canvas = self.canvas, scaleX = 0, scaleY = 0; //Don't go to full page if full screen is activated if (!self.IsFullScreen()) { if (self.IsFullPage()) { canvas.width = self.DefaultBackBufferWidth(); canvas.height = self.DefaultBackBufferHeight(); } else { scaleX = window.innerWidth / canvas.width; scaleY = window.innerHeight / canvas.height; canvas.width = window.innerWidth; canvas.height = window.innerHeight; canvas.getContext("2d").scale(scaleX, scaleY); } } }; /** * Toggles between full screen and windowed mode. * @name ToggleFullScreen * @function * @memberOf GraphicsDevice */ GraphicsDevice.prototype.ToggleFullScreen = function () { "use strict"; /*global setTimeout*/ var self = this, canvas = self.canvas, scaleX = 0, scaleY = 0; if (!self.IsFullScreen()) { //If canvas is full page turn it normal if (self.IsFullPage()) { self.ToggleFullPage(); } if (canvas.requestFullScreen) { canvas.requestFullScreen(); } else if (canvas.mozRequestFullScreen) { canvas.mozRequestFullScreen(); } else if (canvas.webkitRequestFullScreen) { canvas.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT); } scaleX = window.innerWidth / canvas.width; canvas.width = window.innerWidth; //For some reason (that I dunno), setTimeout is compulsory for the correct resizing setTimeout(function () { scaleY = window.innerHeight / canvas.height; canvas.height = window.innerHeight; canvas.getContext("2d").scale(scaleX, scaleY); }, 150); } else { if (document.cancelFullScreen) { document.cancelFullScreen(); } else if (document.mozCancelFullScreen) { document.mozCancelFullScreen(); } else if (document.webkitCancelFullScreen) { document.webkitCancelFullScreen(); } canvas.width = self.DefaultBackBufferWidth(); canvas.height = self.DefaultBackBufferHeight(); } }; /** * Gets a value that indicates whether the device should start in full-page mode. * @name IsFullPage * @function * @memberOf GraphicsDevice */ GraphicsDevice.prototype.IsFullPage = function () { "use strict"; /*global window */ return (this.canvas.width === window.innerWidth && this.canvas.height === window.innerHeight); }; /** * Gets a value that indicates whether the device should start in full-screen mode. * @name IsFullScreen * @function * @memberOf GraphicsDevice */ GraphicsDevice.prototype.IsFullScreen = function () { "use strict"; /*global document */ return !((document.fullScreenElement && document.fullScreenElement !== null) || (!document.mozFullScreen && !document.webkitIsFullScreen)); }; /** * Clear the canvas rectangle. * @name Clear * @function * @memberOf GraphicsDevice */ GraphicsDevice.prototype.Clear = function () { "use strict"; var canvas = this.canvas; canvas.getContext("2d").clearRect(0, 0, canvas.width, canvas.height); };
Rockam/XgameJS
src/JS/XNA_Classes/GraphicsDevice.js
JavaScript
gpl-2.0
4,744
/** * @file * Views Slideshow Xtra Javascript. */ (function ($) { Drupal.viewsSlideshowXtra = Drupal.viewsSlideshowXtra || {}; var pageX = 0, pageY = 0, timeout; Drupal.viewsSlideshowXtra.transitionBegin = function (options) { // Find our views slideshow xtra elements $('[id^="views-slideshow-xtra-"]:not(.views-slideshow-xtra-processed)').addClass('views-slideshow-xtra-processed').each(function() { // Get the slide box. var slideArea = $(this).parent().parent().find('.views_slideshow_main'); // Remove the views slideshow xtra html from the dom var xtraHTML = $(this).detach(); // Attach the views slideshow xtra html to below the main slide. $(xtraHTML).appendTo(slideArea); // Get the offsets of the slide and the views slideshow xtra elements var slideAreaOffset = slideArea.offset(); var xtraOffset = $(this).offset(); // Move the views slideshow xtra element over the top of the slide. var marginMove = slideAreaOffset.top - xtraOffset.top; $(this).css({'margin-top': marginMove + 'px'}); // Move type=text slide elements into place. var slideData = Drupal.settings.viewsSlideshowXtra[options.slideshowID].slideInfo.text; var slideNum = 0; for (slide in slideData) { var items = slideData[slide]; var itemNum = 0; for (item in items) { //alert('#views-slideshow-xtra-' + options.slideshowID + ' .views-slideshow-xtra-text-' + slideNum + '-' + itemNum); $('#views-slideshow-xtra-' + options.slideshowID + ' .views-slideshow-xtra-text-' + slideNum + '-' + itemNum).css({ 'width': slideArea.width() }); itemNum++; } slideNum++; } // Move type=link slide elements into place. var slideData = Drupal.settings.viewsSlideshowXtra[options.slideshowID].slideInfo.link; var slideNum = 0; for (slide in slideData) { var items = slideData[slide]; var itemNum = 0; for (item in items) { //alert('#views-slideshow-xtra-' + options.slideshowID + ' .views-slideshow-xtra-link-' + slideNum + '-' + itemNum); $('#views-slideshow-xtra-' + options.slideshowID + ' .views-slideshow-xtra-link-' + slideNum + '-' + itemNum).css({ 'width': slideArea.width() }); itemNum++; } slideNum++; } // Move type=image slide elements into place. var slideData = Drupal.settings.viewsSlideshowXtra[options.slideshowID].slideInfo.image; var slideNum = 0; for (slide in slideData) { var items = slideData[slide]; var itemNum = 0; for (item in items) { //alert('#views-slideshow-xtra-' + options.slideshowID + ' .views-slideshow-xtra-image-' + slideNum + '-' + itemNum); $('#views-slideshow-xtra-' + options.slideshowID + ' .views-slideshow-xtra-image-' + slideNum + '-' + itemNum).css({ 'width': slideArea.width() }); itemNum++; } slideNum++; } var settings = Drupal.settings.viewsSlideshowXtra[options.slideshowID]; if (settings.pauseAfterMouseMove) { //if(true) { slideArea.mousemove(function(e) { if (pageX - e.pageX > 5 || pageY - e.pageY > 5) { Drupal.viewsSlideshow.action({ "action": 'pause', "slideshowID": options.slideshowID }); clearTimeout(timeout); timeout = setTimeout(function() { Drupal.viewsSlideshow.action({ "action": 'play', "slideshowID": options.slideshowID }); }, 2000); } pageX = e.pageX; pageY = e.pageY; }); } }); // TODO Find a better way to detect if xtra module is enabled but this is not // an xtra slideshow. This seems to work but its probably not the right way. //if (Drupal.settings.viewsSlideshowXtra[options.slideshowID]) { THIS DOES NOT WORK! if ('viewsSlideshowXtra' in Drupal.settings) { var settings = Drupal.settings.viewsSlideshowXtra[options.slideshowID]; // Hide elements either by fading or not if (settings.displayDelayFade) { $('#views-slideshow-xtra-' + options.slideshowID + ' .views-slideshow-xtra-row').fadeOut(); } else { $('#views-slideshow-xtra-' + options.slideshowID + ' .views-slideshow-xtra-row').hide(); } settings.currentTransitioningSlide = options.slideNum; // Pause from showing the text and links however long the user decides. setTimeout(function() { if (options.slideNum == settings.currentTransitioningSlide) { if (settings.displayDelayFade) { $('#views-slideshow-xtra-' + options.slideshowID + ' .views-slideshow-xtra-row-' + options.slideNum).fadeIn(); } else { $('#views-slideshow-xtra-' + options.slideshowID + ' .views-slideshow-xtra-row-' + options.slideNum).show(); } } }, settings.displayDelay ); } }; })(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); ; (function($) { Drupal.admin = Drupal.admin || {}; Drupal.admin.behaviors = Drupal.admin.behaviors || {}; /** * @ingroup admin_behaviors * @{ */ /** * Apply active trail highlighting based on current path. * * @todo Not limited to toolbar; move into core? */ Drupal.admin.behaviors.toolbarActiveTrail = function (context, settings, $adminMenu) { if (settings.admin_menu.toolbar && settings.admin_menu.toolbar.activeTrail) { $adminMenu.find('> div > ul > li > a[href="' + settings.admin_menu.toolbar.activeTrail + '"]').addClass('active-trail'); } }; /** * @} End of "ingroup admin_behaviors". */ Drupal.admin.behaviors.shorcutcollapsed = function (context, settings, $adminMenu) { // Create the dropdown base $("<li class=\"label\"><a>"+Drupal.t('Shortcuts')+"</a></li>").prependTo("body.menu-render-collapsed div.toolbar-shortcuts ul"); } Drupal.admin.behaviors.shorcutselect = function (context, settings, $adminMenu) { // Create the dropdown base $("<select id='shortcut-menu'/>").appendTo("body.menu-render-dropdown div.toolbar-shortcuts"); // Create default option "Select" $("<option />", { "selected" : "selected", "value" : "", "text" : Drupal.t('Shortcuts') }).appendTo("body.menu-render-dropdown div.toolbar-shortcuts select"); // Populate dropdown with menu items $("body.menu-render-dropdown div.toolbar-shortcuts a").each(function() { var el = $(this); $("<option />", { "value" : el.attr("href"), "text" : el.text() }).appendTo("body.menu-render-dropdown div.toolbar-shortcuts select"); }); $("body.menu-render-dropdown div.toolbar-shortcuts select").change(function() { window.location = $(this).find("option:selected").val(); }); $('body.menu-render-dropdown div.toolbar-shortcuts ul').remove(); }; })(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); ; (function ($) { Drupal.behaviors.textarea = { attach: function (context, settings) { $('.form-textarea-wrapper.resizable', context).once('textarea', function () { var staticOffset = null; var textarea = $(this).addClass('resizable-textarea').find('textarea'); var grippie = $('<div class="grippie"></div>').mousedown(startDrag); grippie.insertAfter(textarea); function startDrag(e) { staticOffset = textarea.height() - e.pageY; textarea.css('opacity', 0.25); $(document).mousemove(performDrag).mouseup(endDrag); return false; } function performDrag(e) { textarea.height(Math.max(32, staticOffset + e.pageY) + 'px'); return false; } function endDrag(e) { $(document).unbind('mousemove', performDrag).unbind('mouseup', endDrag); textarea.css('opacity', 1); } }); } }; })(jQuery); ; (function ($) { Drupal.behaviors.tokenTree = { attach: function (context, settings) { $('table.token-tree', context).once('token-tree', function () { $(this).treeTable(); }); } }; Drupal.behaviors.tokenDialog = { attach: function (context, settings) { $('a.token-dialog', context).once('token-dialog').click(function() { var url = $(this).attr('href'); var dialog = $('<div style="display: none" class="loading">' + Drupal.t('Loading token browser...') + '</div>').appendTo('body'); // Emulate the AJAX data sent normally so that we get the same theme. var data = {}; data['ajax_page_state[theme]'] = Drupal.settings.ajaxPageState.theme; data['ajax_page_state[theme_token]'] = Drupal.settings.ajaxPageState.theme_token; dialog.dialog({ title: $(this).attr('title') || Drupal.t('Available tokens'), width: 700, close: function(event, ui) { dialog.remove(); } }); // Load the token tree using AJAX. dialog.load( url, data, function (responseText, textStatus, XMLHttpRequest) { dialog.removeClass('loading'); } ); // Prevent browser from following the link. return false; }); } } Drupal.behaviors.tokenInsert = { attach: function (context, settings) { // Keep track of which textfield was last selected/focused. $('textarea, input[type="text"]', context).focus(function() { Drupal.settings.tokenFocusedField = this; }); $('.token-click-insert .token-key', context).once('token-click-insert', function() { var newThis = $('<a href="javascript:void(0);" title="' + Drupal.t('Insert this token into your form') + '">' + $(this).html() + '</a>').click(function(){ if (typeof Drupal.settings.tokenFocusedField == 'undefined') { alert(Drupal.t('First click a text field to insert your tokens into.')); } else { var myField = Drupal.settings.tokenFocusedField; var myValue = $(this).text(); //IE support if (document.selection) { myField.focus(); sel = document.selection.createRange(); sel.text = myValue; } //MOZILLA/NETSCAPE support else if (myField.selectionStart || myField.selectionStart == '0') { var startPos = myField.selectionStart; var endPos = myField.selectionEnd; myField.value = myField.value.substring(0, startPos) + myValue + myField.value.substring(endPos, myField.value.length); } else { myField.value += myValue; } $('html,body').animate({scrollTop: $(myField).offset().top}, 500); } return false; }); $(this).html(newThis); }); } }; })(jQuery); ;
gocosmonaut/packwood
sites/default/files/js/js_CfeNDle0-FEDne-b5nwDvZC3V5IyC1g2IYKSzrjdUCQ.js
JavaScript
gpl-2.0
19,386
openerp.bahmni_web_extensions.fixingErrorInCancelEdition = function(instance) { instance.web.ListView.include({ cancel_edition: function (force) { var self = this; return this.with_event('cancel', { editor: this.editor, form: this.editor.form, cancel: false }, function () { return this.editor.cancel(force).then(function (attrs) { if(attrs == null){ return; } if (attrs && attrs.id) { var record = self.records.get(attrs.id); if (!record) { // Record removed by third party during edition return } return self.reload_record(record); } var to_delete = self.records.find(function (r) { return !r.get('id'); }); if (to_delete) { self.records.remove(to_delete); } }); }); }, }); }
3dfxsoftware/cbss-addons
bahmni_web_extensions/static/src/js/fixingErrorInCancelEdition.js
JavaScript
gpl-2.0
1,215
import $ from 'jquery' /** * Display a message or error to the user with an appropriate timeout * @param String msg The message to be displayed * @param Integer timeout How long to show the message * @param Boolean error Whether to show an error (true) or a message (false or undefined) * @return void * @since 4.0 */ export function showMessage (msg, timeout, error) { timeout = typeof timeout !== 'undefined' ? timeout : 4500 error = typeof error !== 'undefined' ? error : false let $elm = $('<div id="message">').html('<p>' + msg + '</p>') if (error === true) { $elm.addClass('error') } else { $elm.addClass('updated') } $('.wrap > h2').after($elm) setTimeout(function () { $elm.slideUp() }, timeout) }
blueliquiddesigns/gravity-forms-pdf-extended
src/assets/js/admin/helper/showMessage.js
JavaScript
gpl-2.0
757
/* Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ (function() { CKEDITOR.plugins.add( 'templates', { requires : [ 'dialog' ], init : function( editor ) { CKEDITOR.dialog.add( 'templates', CKEDITOR.getUrl( this.path + 'dialogs/templates.js' ) ); editor.addCommand( 'templates', new CKEDITOR.dialogCommand( 'templates' ) ); editor.ui.addButton( 'Templates', { label : editor.lang.templates.button, command : 'templates' }); } }); var templates = {}, loadedTemplatesFiles = {}; CKEDITOR.addTemplates = function( name, definition ) { templates[ name ] = definition; }; CKEDITOR.getTemplates = function( name ) { return templates[ name ]; }; CKEDITOR.loadTemplates = function( templateFiles, callback ) { // Holds the templates files to be loaded. var toLoad = []; // Look for pending template files to get loaded. for ( var i = 0 ; i < templateFiles.length ; i++ ) { if ( !loadedTemplatesFiles[ templateFiles[ i ] ] ) { toLoad.push( templateFiles[ i ] ); loadedTemplatesFiles[ templateFiles[ i ] ] = 1; } } if ( toLoad.length > 0 ) CKEDITOR.scriptLoader.load( toLoad, callback ); else setTimeout( callback, 0 ); }; })(); /** * The templates definition set to use. It accepts a list of names separated by * comma. It must match definitions loaded with the templates_files setting. * @type String * @default 'default' * @example * config.templates = 'my_templates'; */ CKEDITOR.config.templates = 'default'; /** * The list of templates definition files to load. * @type (String) Array * @default [ 'plugins/templates/templates/default.js' ] * @example * config.templates_files = * [ * '/editor_templates/site_default.js', * 'http://www.example.com/user_templates.js * ]; * */ CKEDITOR.config.templates_files = [ CKEDITOR.getUrl( '_source/' + // @Packager.RemoveLine 'plugins/templates/templates/default.js' ) ]; /** * Whether the "Replace actual contents" checkbox is checked by default in the * Templates dialog. * @type Boolean * @default true * @example * config.templates_replaceContent = false; */ CKEDITOR.config.templates_replaceContent = true;
JonathanMatthey/hudsongray-website2
wp-content/themes/grey/js/ckeditor/_source/plugins/templates/plugin.js
JavaScript
gpl-2.0
2,321
(function($) { $.fn.getWidget = function () { return $( '#ctx_linker' ); } $.fn.getWidgetType = function () { return $.fn.getWidget().attr( 'widget-type' ); } $.fn.classChanger = function ( widgetClass, hasClassName, addClassName) { if( $( '.' + widgetClass ).hasClass( hasClassName ) ) { $( '.' + widgetClass ).removeClass( hasClassName ); } $( '.' + widgetClass ).addClass( addClassName ); } $.fn.responsiveResizeHandler = function () { var screenWidth = window.innerWidth; var cxt_popup_width; var cxt_popup_height; if(screenWidth > 605) { cxt_popup_width = 552; cxt_popup_height = 292; } else { cxt_popup_width = 250; cxt_popup_height = 500; } $("#ctx_branding_open").prettyPhoto({ theme:'light_square', autoplay_slideshow: false, default_width: cxt_popup_width, default_height: cxt_popup_height, social_tools: false, show_title: false }); var widgetType = $.fn.getWidgetType(); var getWidgetWidth = $.fn.getWidget().width(); var resizeMinLimit = 350; if ( widgetType == 'blocks2' ) { if(getWidgetWidth < resizeMinLimit) { $.fn.classChanger('ctx_blocks_widget2','ctx_blocks2site', 'ctx_blocks2mobile'); } else { $.fn.classChanger('ctx_blocks_widget2','ctx_blocks2mobile', 'ctx_blocks2site'); } } if ( widgetType == 'float' ) { if(getWidgetWidth < resizeMinLimit) { $(".ctx_float_widget li").css({"width":"100%", "min-height":"90px"}); $(".ctx_float_widget img").css("width", "100%"); $(".ctx_float_widget p.ctx_link").css({ "width":"100%", "max-width":"100%", "margin-left":"0"}); } else if(getWidgetWidth < 550 && getWidgetWidth > resizeMinLimit) { $(".ctx_float_widget li").css({"width":"100%", "min-height":"90px"}); $(".ctx_float_widget img").css("width", "38%"); $(".ctx_float_widget p.ctx_link").css({ "width":"59%", "max-width":"100%", "margin-left":"2%"}); } else { $(".ctx_float_widget li").css({"width":"32.3%"}); $(".ctx_float_widget img").css("width", "100%"); $(".ctx_float_widget p.ctx_link").css({ "width":"100%", "max-width":"100%", "margin-left":"0"}); } } if ( widgetType == 'blocks' ) { var getImageHeight = $('.ctx_blocks_widget li img').height(); $(".vidpop-playbutton-big").css("height", getImageHeight); if( getWidgetWidth < 500 ) { $(".ctx_blocks_widget li").css({"width":"153px", "margin-left":"6.4%", "margin-bottom":"5%"}); } else { $(".ctx_blocks_widget li").css({"width":"22%", "margin-left":"2.4%", "margin-bottom":"2.2%"}); } $(".ctx_blocks_widget li a").on("mouseover", function(event){ $(this).toggleClass('heightauto'); var getTextHeight = $('.heightauto p span').height(); if(getTextHeight>50) { $(".heightauto p").css("height", getTextHeight); } }); $(".ctx_blocks_widget li a").on("mouseout", function(event){ $(".heightauto p").css("height", "46px"); $(this).removeClass('heightauto'); }); } var getLeftSidebarWidth = $('.ctx_sidebar').width(); if(getLeftSidebarWidth < 240) { $(".ctx_sidebar .ctx_horizontal_line li").css("float", "left"); $("ctx_horizontal_line").css("float", "left"); $(".ctx_sidebar .linker_images li:first-child").css("margin-bottom", "5px"); } else { $(".ctx_sidebar .ctx_horizontal_line li").css("float", "none"); $(".ctx_sidebar .linker_images li:first-child").css("margin-bottom", "0"); } if( getWidgetWidth < resizeMinLimit ) { $(".vidpop-playbutton-big").css("width", "30%"); } else { $(".vidpop-playbutton-big").css("width", "94%"); } } $.fn.checkIfWidgetLoadedAndResize = function () { var widgetType = $.fn.getWidgetType(); $.documentLoadCheckCount++; if ( widgetType ) { $.fn.responsiveResizeHandler(); $.fn.clearIfWidgetLoadedInterval(); } if ( $.documentLoadCheckCount > 10 ) { $.fn.clearIfWidgetLoadedInterval(); } } $.fn.clearIfWidgetLoadedInterval = function () { if ( $.documentLoadInterval ) { clearInterval( $.documentLoadInterval ); } } $(window).resize( function() { $.fn.responsiveResizeHandler(); } ); $.documentLoadInterval = null; $.documentLoadCheckCount = 0; $(document).ready( function() { $.documentLoadInterval = self.setInterval( function () { $.fn.checkIfWidgetLoadedAndResize(); }, 500 ); } ); })(jQuery);
Make-Magazine/makeblog
includes/contextly-related-links/js/mobile_optimization.js
JavaScript
gpl-2.0
5,265
(function(){var m=window.cfx,b=window.sfx,s={Version:"7.2.5289.19355"};m.highlow=s;var o=function j(){j._ic();this.a=this.b=0};o.prototype={_0dM:function(j,a){j.x==a.x?(this.a=j.x,this.b=b.D.e):(this.a=(a.y-j.y)/(a.x-j.x),this.b=a.y-this.a*a.x);return this},d:function(j){if(this.a==j.a)return new b.e;var a=0,c=0;b.D.h(this.b)?(a=this.a,c=j.a*a+j.b):(a=(j.b-this.b)/(this.a-j.a),c=this.a*a+this.b);return(new b.e)._01e(a,c)}};o._dt("CWHL",b.Sy,0);var k=function a(){a._ic();this.d=this.e=this.j=this.k= null;this.h=!1;this.c=0;this.f=this.g=null;this.i=0;this.l=this.b=this.m=this.a=null;this._0_1()};s.HighLow=k;k.prototype={_0_1:function(){this.o=new b.m;this.n=new b.m;return this},p:function(a,c,d,t,e){var f=new b.e,i=this.a.Se();if(!a){var l=this.a.So(i-2).x,h=this.a.So(i-1).x,g=(new o)._0dM((new b.e)._01e(l,this.a.So(i-2).y),(new b.e)._01e(h,this.a.So(i-1).y)),l=(new o)._0dM((new b.e)._01e(l,this.b.So(i-2)),(new b.e)._01e(h,this.b.So(i-1)));f._cf(g.d(l));i--}g=2*i;a||g++;l=b.f._ca(g);for(g=h= 0;g<i;g++,h++)l[h]._cf(this.a.So(g));a||(l[h++]=b.e.f(f));for(g=i-1;0<=g;g--,h++)l[h]._i1(this.a.So(g).x,this.b.So(g));g=null;h=0;0<this.c?(g=this.k,h=c.d-1):(g=this.j,h=c.d);0!=(c.u&8)&&(h=h.toString(),h=(new m.c5)._01c5("Attribute"+h),h.e="C,"+(c.d-1).toString(),c.c.sidc(h));c.c.idQ(g,l);if(c.b.a.b){l=c.d;h=c.e;null==this.d&&(this.d=(new m.cJ)._01cJ(b.m.c()._nc(),1,0),this.e=(new m.cJ)._01cJ(b.m.c()._nc(),1,2));var p=null,q=null,k=0,r=0;0<this.c?(p=this.d,q=this.e,k=5,r=-5):(p=this.e,q=this.d,k= -5,r=5);p.sy(this.o);q.sy(this.n);var n=0;0!=this.i&&(n=1,i--);0==e&&i++;for(g=0;g<i;g++,n++)c.e=this.i+g,c.d=1,c.aY((new b.e)._01e(this.a.So(n).x,this.a.So(n).y+r),!1,q),c.d=0,c.aY((new b.e)._01e(this.a.So(n).x,this.b.So(n)+k),!1,p);c.e=h;c.d=l}a||(this.a.clear(),this.b.clear(),this.a.Si(b.e.f(f)),this.b.Si(f.y),this.a.Si(b.e.f(t)),this.b.Si(d))},t:function(a){this.a=(new b._L)._0_L();this.b=(new b._L)._0_L();this.m=(new b._L)._0_L();this.l=(new b._L)._0_L();this.j=a.z.b();this.f=(new b.ao)._03ao(a.p.d(), a.b.l.a);this.n._cf(a.b.a.a);a.aK(a.d-1);a.P(!0);this.k=a.z;this.g=(new b.ao)._03ao(a.p.d(),a.b.l.a);this.o._cf(a.b.a.a)},r:function(){this.g._d();this.f._d();this.k._d();this.j._d();null!=this.e&&(this.e._d(),this.d._d());this.d=this.e=this.j=this.k=this.f=this.g=null},reset:function(){},icX:function(){return 2},icY:function(){return 553988},icW:function(a,b,d){switch(b){case 5:return"%s\n%l - %l\n%v - %v\n%s2\n%v~ - %v~";case 11:return this.q(d)}return null},icZ:function(a,c,d){a.b=1;a.a=0;var k= c=!1;if(d.e==d.n){k=!0;if(this.h)return;this.i=d.e;this.t(d)}else if(d.e==d.q){this.h=!this.h;if(!this.h){this.r();return}c=!0}else if(this.h)return;var e=d.w,f=0;0<d.l?(f=e,e=d.a.b.iaP().getItem(d.d+1,d.e)):f=d.a.b.iaP().getItem(d.d-1,d.e);if(!(d.Q||1.0E108==f))if(a=0,a=e==f?0:e<f?-1:1,e=d.h.valueToPixel(f),f=(new b.e)._01e(d.k.b,d.k.a),this.m.Si(b.e.f(f)),this.l.Si(e),k)this.c=a,this.a.Si(b.e.f(f)),this.b.Si(e);else{if(a==this.c&&(0==a?(this.a.sSo(0,(new b.f)._01e(f.x,f.y)),this.b.sSo(0,e)):(this.a.Si(b.e.f(f)), this.b.Si(e)),!c))return;this.a.Si(b.e.f(f));this.b.Si(e);if(0!=this.c||c)if(this.p(a==this.c,d,e,f,a),0==a&&(this.a.clear(),this.b.clear(),this.a.Si(b.e.f(f)),this.b.Si(e)),c&&a!=this.c&&(this.c=a,this.p(!0,d,e,f,a)),c){c=this.m.toArray();if(k=0!=(d.u&8))e=d.d-1,e=(new m.c5)._01c5("AttributeLine Attribute"+e.toString()+"Line"),d.c.sidc(e);d.c.idA(this.g,c);for(e=0;e<c.length;e++)c[e].y=this.l.So(e);k&&(e=(new m.c5)._01c5("AttributeLine Attribute"+d.d.toString()+"Line"),d.c.sidc(e));d.c.idA(this.f, c)}this.c=a;this.i=d.e}},q:function(a){a=a.a;a.e=1;a.b=4096;return null}};k._dt("CWHH",b.Sy,0,m.icV)})();
elayarajap/dolo_dev
includes/charts/js/jchartfx.highlow.js
JavaScript
gpl-2.0
3,655
var searchData= [ ['increment',['increment',['../classBmobObject.html#ac725ea22c4471549c97481f86f4c0bd1',1,'BmobObject::increment(string column, int value=1)'],['../classBmobObject.html#a4005600e120af2ed659623eaaad13e41',1,'BmobObject::increment(string column, int value=1)']]], ['index',['index',['../classJson_1_1ValueIteratorBase.html#aa90591f5f7f8d2f06cc4605816b53738',1,'Json::ValueIteratorBase::index() const '],['../classJson_1_1ValueIteratorBase.html#aa90591f5f7f8d2f06cc4605816b53738',1,'Json::ValueIteratorBase::index() const ']]], ['initialize',['initialize',['../classBmobSDKInit.html#a23098fc89e1b98e773ba461f706458cf',1,'BmobSDKInit::initialize(string app_id, string app_key)'],['../classBmobSDKInit.html#a58b2c952a958a5370041d6866700c5c6',1,'BmobSDKInit::initialize(string app_id, string app_key)']]], ['isinitialize',['isInitialize',['../classBmobSDKInit.html#a7f082849c54d8ae48e32eea74562f623',1,'BmobSDKInit::isInitialize()'],['../classBmobSDKInit.html#ad51634162bd95e3dfc73c5d51e3d7755',1,'BmobSDKInit::isInitialize()']]], ['ismember',['isMember',['../classJson_1_1Value.html#a196defba501d70ea2b6793afb04108e3',1,'Json::Value::isMember(const char *key) const '],['../classJson_1_1Value.html#af728b5738aaa133f3aad2e39dc4f415e',1,'Json::Value::isMember(const std::string &amp;key) const '],['../classJson_1_1Value.html#a196defba501d70ea2b6793afb04108e3',1,'Json::Value::isMember(const char *key) const '],['../classJson_1_1Value.html#af728b5738aaa133f3aad2e39dc4f415e',1,'Json::Value::isMember(const std::string &amp;key) const ']]], ['isvalidindex',['isValidIndex',['../classJson_1_1Value.html#a193dd42bf77a7a704971e6de07656367',1,'Json::Value::isValidIndex(UInt index) const '],['../classJson_1_1Value.html#a193dd42bf77a7a704971e6de07656367',1,'Json::Value::isValidIndex(UInt index) const ']]] ];
bmob/BmobCocos2d-x
html/search/functions_7.js
JavaScript
gpl-2.0
1,828
EasyBlog.module("media/constrain",function($){var module=this;EasyBlog.require().library("image").done(function(){$.fn.constrain=function(){var constrain=this.data("constrain");if(constrain instanceof $.Constrain)if(arguments.length>0)constrain.update(arguments[0]);else return constrain;else{constrain=new $.Constrain(this,arguments[0]);this.data("constrain",constrain)}};$.Constrain=function(element,options){var self=this;var defaultOptions={selector:{width:".inputWidth",height:".inputHeight",constrain:".inputConstrain"}, forceConstrain:false};var userOptions=options?options:{};self.options=$.extend(true,{},defaultOptions,userOptions);self.options.element={width:element.find(self.options.selector.width).data("type","width"),height:element.find(self.options.selector.height).data("type","height"),constrain:element.find(self.options.selector.constrain)};self.options.initial=self.options.initial||self.options.source;if(self.options.allowedMax!==undefined){self.options.max=$.Image.resizeWithin(self.options.source.width, self.options.source.height,self.options.allowedMax.width,self.options.allowedMax.height);self.options.initial.width=Math.min(self.options.max.width,self.options.initial.width);self.options.initial.height=Math.min(self.options.max.height,self.options.initial.height)}self.options.element.width.data("initial",self.options.initial.width);self.options.element.height.data("initial",self.options.initial.height);self.fieldValues(self.calculate("width",self.options.initial));$.each([self.options.element.width, self.options.element.height],function(i,element){var thisType=element.data("type"),oppositeType=self.getOppositeType(thisType),element=$(element),opposite=self.options.element[oppositeType];element.bind("keyup",function(event){if(event.keyCode==9||event.keyCode==16)return false;self.fieldValues(self.calculate(thisType))});element.bind("blur",function(){if(!self.options.element.constrain.is(":checked")&&$.trim(element.val())=="")element.val(self.options.initial[thisType]);if($.trim(element.val())== ""&&$.trim(opposite.val())==""){element.val(self.options.initial[thisType]);opposite.val(self.options.initial[oppositeType])}})});$(self.options.element.constrain).bind("change",function(){if($(this).is(":checked")){var values=self.fieldValues(),type=values.width===""?"height":"width";self.fieldValues(self.calculate(type))}})};$.extend($.Constrain.prototype,{calculate:function(thisType,values){var self=this,values=values!==undefined?values:self.fieldValues(),oppositeType=self.getOppositeType(thisType), thisMax=self.options.max?self.options.max[thisType]:undefined,oppositeMax=self.options.max?self.options.max[oppositeType]:undefined,thisSource=self.options.source[thisType],oppositeSource=self.options.source[oppositeType],thisVal=values[thisType],oppositeVal=values[oppositeType];thisVal=thisVal!=""&&thisMax&&thisVal>thisMax?thisMax:thisVal;if(this.enforceConstrain())if(thisVal=="")oppositeVal="";else{var ratio=thisSource/thisVal;oppositeVal=Math.round(oppositeSource/ratio);if(oppositeMax&&oppositeVal> oppositeMax)oppositeVal=oppositeMax}var result={};result[thisType]=thisVal;result[oppositeType]=oppositeVal;return result},getOppositeType:function(type){return type=="width"?"height":"width"},getInput:function(type){var self=this,value=self.options.element[type].val();value=$.trim(value);value=value.replace(new RegExp("[^0-9.]","g"),"");value=parseInt(value,10);return isNaN(value)?"":value},fieldValues:function(values){var self=this,result={};if(values===undefined){result.width=self.getInput("width"); result.height=self.getInput("height")}else{self.options.element.width.val(Math.floor(values.width));self.options.element.height.val(Math.floor(values.height));result=values}return result},enforceConstrain:function(){var self=this;return self.options.forceConstrain?true:self.options.element.constrain.length<1?true:self.options.element.constrain.is(":checked")},update:function(options){var self=this;self.options.initial=options.initial||options.source||self.options.initial;if(options.allowedMax!==undefined&& options.source!==undefined){options.max=$.Image.resizeWithin(options.source.width,options.source.height,options.allowedMax.width,options.allowedMax.height);self.options.initial.width=Math.min(options.max.width,self.options.initial.width);self.options.initial.height=Math.min(options.max.height,self.options.initial.height)}self.options=$.extend(true,{},self.options,options);values=this.calculate("width",{width:self.options.initial.width||self.options.source.width,height:self.options.initial.height|| self.options.source.height});this.fieldValues(values)}});module.resolve()})});
cuongnd/banhangonline88_joomla
media/com_easyblog/scripts_/media/constrain.min.js
JavaScript
gpl-2.0
4,657
$(document).ready(function() { //// Menu var scrollOffset; function getOffset(){ scrollOffset = $('header').outerHeight(); } getOffset(); $('.content').anchorific({ anchorText: '', spyOffset: -30 }); ///// Navigation $('nav li a').on('click', navclick); $('#logo a').on('click', navclick); function navclick(e, section){ $('body').panelSnap('disable'); if( e ) e.preventDefault(); var dataTag; if (e) dataTag = e.currentTarget.parentElement.getAttribute('data-tag'); var target; section ? target = "#"+section : target = e.currentTarget.hash ; var targetY = $(target).offset().top - scrollOffset; $('html, body').animate({ scrollTop: targetY }, 0); window.history.pushState( {}, null, target.replace('#','') ); if ( $('.anchorific').hasClass('active') && dataTag != 1 ) $('.anchorific').toggleClass('active'); $('body').panelSnap('enable'); }; $('#mobile-nav').on('click', function(){ $('.anchorific').toggleClass('active'); }); // $('body').panelSnap({ // panelSelector: '#content section', // offset: scrollOffset, // directionThreshold: 50, // delay: 1000 // }); //// Gallery $(".owl-gallery").each(function() { var $this = $(this); $this.on('initialized.owl.carousel', function(event){ // $this.trigger("to.owl.carousel", 0); updateCount(event); }) $this.owlCarousel({ items : 1, startPosition: 0, loop: true, onResized: owlResized, lazyLoad: true }); $this.on('changed.owl.carousel', function(event){ console.log( event.item.index ); updateCount(event); }) function owlResized(event){ $this.trigger('refresh.owl.carousel'); } // Custom Navigation Events $this.parent().find("#next").click(function(){ $this.trigger('next.owl.carousel'); }); $this.parent().find("#prev").click(function(){ $this.trigger('prev.owl.carousel'); }); }); function updateCount(event){ var ele = $(event.target).parent().find('#count'); var cur = event.page.index + 1; var tot = event.page.count; ele.html( cur +"/"+ tot ); } //// Single Images // $('.single-image img').each(function(){ // $(this).css({opacity:0}).load(function(){ // $(this).animate({opacity:1},200); // fade them in // }).attr('src', $(this).data('src')); // }); $("img.lazy").lazyload({ effect : "fadeIn" }); //// Foooter setFooterMargin(); //// Navigate if( section ) navclick(null, section); $(window).on('resize', function(){ getOffset() setFooterMargin(); }); }); function setFooterMargin(){ $('footer').animate({ marginBottom: ($('footer').outerHeight()*-1 + 25) }, 100); } function toggleFooter(){ if( $('footer').css('margin-bottom') == "0px" ){ setFooterMargin(); $('footer').removeClass('active'); $('#toggle-footer').html('Impressum'); }else{ $('footer').animate({ marginBottom: 0 }, 100); $('footer').addClass('active'); $('#toggle-footer').html('&times; Schließen'); } } function resizeIframe(iframe) { if (iframe) { var iframeWin = iframe.contentWindow || iframe.contentDocument.parentWindow; if (iframeWin.document.body) { iframe.height = iframeWin.document.documentElement.scrollHeight || iframeWin.document.body.scrollHeight; } } }
stinlemp/praxis
site/templates/scripts/main.js
JavaScript
gpl-2.0
3,338
//require <jquery.packed.js> //require <xmp-js/xmp.iif.min.js> (function() { var $ = jQuery; registerXatafaceDecorator(function() { $('img[attribution]').each(function() { console.log("found attribution"); var src = $(this).attr('src'); if (!src) { return; } console.log("src=", src); fetch(src).then(function(response) { return response.blob(); }).then(function(blob) { return blob.arrayBuffer(); }).then(function(buf){ let xmp = new XMP(buf); //raw.value = xmp.find(); console.log(JSON.stringify(xmp.parse(), null, 4)); }); }); }); })();
shannah/xataface
js/xataface/img_attribution.js
JavaScript
gpl-2.0
771
var searchData= [ ['page',['Page',['../classPage.html',1,'']]], ['pagegenerator',['PageGenerator',['../classPageGenerator.html',1,'']]], ['panel',['Panel',['../classPanel.html',1,'']]], ['passwordtpl',['PasswordTpl',['../classPasswordTpl.html',1,'']]], ['pluginconfig',['PluginConfig',['../classmmc_1_1support_1_1config_1_1PluginConfig.html',1,'mmc::support::config']]], ['pluginconfigfactory',['PluginConfigFactory',['../classmmc_1_1support_1_1config_1_1PluginConfigFactory.html',1,'mmc::support::config']]], ['pluginmanager',['PluginManager',['../classmmc_1_1agent_1_1PluginManager.html',1,'mmc::agent']]], ['popupform',['PopupForm',['../classPopupForm.html',1,'']]], ['popupwindowform',['PopupWindowForm',['../classPopupWindowForm.html',1,'']]], ['ppolicy',['PPolicy',['../classmmc_1_1plugins_1_1ppolicy_1_1PPolicy.html',1,'mmc::plugins::ppolicy']]], ['ppolicyconfig',['PPolicyConfig',['../classmmc_1_1plugins_1_1ppolicy_1_1PPolicyConfig.html',1,'mmc::plugins::ppolicy']]], ['processscheduler',['ProcessScheduler',['../classmmc_1_1support_1_1mmctools_1_1ProcessScheduler.html',1,'mmc::support::mmctools']]], ['provisionerconfig',['ProvisionerConfig',['../classmmc_1_1plugins_1_1base_1_1provisioning_1_1ProvisionerConfig.html',1,'mmc::plugins::base::provisioning']]], ['provisioneri',['ProvisionerI',['../classmmc_1_1plugins_1_1base_1_1provisioning_1_1ProvisionerI.html',1,'mmc::plugins::base::provisioning']]], ['provisioningerror',['ProvisioningError',['../classmmc_1_1plugins_1_1base_1_1provisioning_1_1ProvisioningError.html',1,'mmc::plugins::base::provisioning']]], ['provisioningmanager',['ProvisioningManager',['../classmmc_1_1plugins_1_1base_1_1provisioning_1_1ProvisioningManager.html',1,'mmc::plugins::base::provisioning']]], ['proxy',['Proxy',['../classmmc_1_1client_1_1sync_1_1Proxy.html',1,'mmc::client::sync']]] ];
pulse-project/mmc-core
doc-doxy/html/search/classes_d.js
JavaScript
gpl-2.0
1,865
function LunaAssistant() { // we'll need this for the subscription based services this.subscription = false; }; LunaAssistant.prototype.setup = function() { this.controller.get('title').innerHTML = $L("Luna Manager"); this.controller.get('rescan-text').innerHTML = $L("Due to a webOS bug, this will close and stop notifications from the phone, email and messaging applications when it rescans."); this.controller.get('restart-luna-text').innerHTML = $L("This will close all the applications you have open when it restarts."); this.controller.get('restart-java-text').innerHTML = $L("This will cause your device to lose network connections and be pretty slow until it's done restarting."); // setup back tap if (Mojo.Environment.DeviceInfo.modelNameAscii.indexOf('TouchPad') == 0 || Mojo.Environment.DeviceInfo.modelNameAscii == 'Emulator') this.backElement = this.controller.get('back'); else this.backElement = this.controller.get('header'); this.backTapHandler = this.backTap.bindAsEventListener(this); this.controller.listen(this.backElement, Mojo.Event.tap, this.backTapHandler); try { this.controller.setupWidget(Mojo.Menu.appMenu, { omitDefaultItems: true }, { visible: false }); this.controller.setupWidget ( 'Rescan', this.attributes = { type: Mojo.Widget.activityButton }, this.model = { buttonLabel: $L("Rescan"), buttonClass: 'palm-button', disabled: false } ); this.controller.setupWidget ( 'RestartLuna', this.attributes = { type: Mojo.Widget.activityButton }, this.model = { buttonLabel: $L("Restart Luna"), buttonClass: 'palm-button', disabled: false } ); this.controller.setupWidget ( 'RestartJava', this.attributes = { type: Mojo.Widget.activityButton }, this.model = { buttonLabel: $L("Restart Java"), buttonClass: 'palm-button', disabled: false } ); this.controller.listen('Rescan', Mojo.Event.tap, this.doRescan.bindAsEventListener(this)); this.controller.listen('RestartLuna', Mojo.Event.tap, this.doRestartLuna.bindAsEventListener(this)); this.controller.listen('RestartJava', Mojo.Event.tap, this.doRestartJava.bindAsEventListener(this)); } catch (e) { Mojo.Log.logException(e, 'luna#setup'); this.alertMessage('luna#setup Error', e); } }; LunaAssistant.prototype.callbackFunction = function(payload, item) { if (!payload) { this.alertMessage('Luna Manager', $L("Cannot access the service. First try restarting Preware, or reboot your device and try again.")); } else if (payload.errorCode == -1 && item != 'RestartJava') { if (payload.errorText == "org.webosinternals.ipkgservice is not running.") { this.alertMessage('Luna Manager', $L("The service is not running. First try restarting Preware, or reboot your device and try again.")); } else { this.alertMessage('Luna Manager', payload.errorText); } } else { if (payload.apiVersion && payload.apiVersion < this.ipkgServiceVersion) { this.alertMessage('Luna Manager', $L("The service version is too old. First try rebooting your device, or reinstall Preware and try again.")); } } this.controller.get(item).mojo.deactivate(); }; LunaAssistant.prototype.doRescan = function() { try { var callback = this.callbackFunction.bindAsEventListener(this, 'Rescan'); this.subscription = IPKGService.rescan(callback); } catch (e) { Mojo.Log.logException(e, 'luna#doRescan'); this.alertMessage('luna#doRescan Error', e); } }; LunaAssistant.prototype.doRestartLuna = function() { try { var callback = this.callbackFunction.bindAsEventListener(this, 'RestartLuna'); this.subscription = IPKGService.restartluna(callback); } catch (e) { Mojo.Log.logException(e, 'luna#doRestartLuna'); this.alertMessage('luna#doRestartLuna Error', e); } }; LunaAssistant.prototype.doRestartJava = function() { try { var callback = this.callbackFunction.bindAsEventListener(this, 'RestartJava'); this.subscription = IPKGService.restartjava(callback); } catch (e) { Mojo.Log.logException(e, 'luna#doRestartJava'); this.alertMessage('luna#doRestartJava Error', e); } }; LunaAssistant.prototype.alertMessage = function(title, message) { this.controller.showAlertDialog( { onChoose: function(value) {}, allowHTMLMessage: true, title: title, message: removeAuth(message), choices:[{label:$L("Ok"), value:""}] }); }; LunaAssistant.prototype.backTap = function(event) { this.controller.stageController.popScene(); }; LunaAssistant.prototype.activate = function(event) {}; LunaAssistant.prototype.deactivate = function(event) {}; LunaAssistant.prototype.cleanup = function(event) { this.controller.stopListening('Rescan', Mojo.Event.tap, this.doRescan.bindAsEventListener(this)); this.controller.stopListening('RestartLuna', Mojo.Event.tap, this.doRestartLuna.bindAsEventListener(this)); this.controller.stopListening('RestartJava', Mojo.Event.tap, this.doRestartJava.bindAsEventListener(this)); this.controller.stopListening(this.backElement, Mojo.Event.tap, this.backTapHandler); }; // Local Variables: // tab-width: 4 // End:
webos-internals/preware
app/assistants/luna-assistant.js
JavaScript
gpl-2.0
5,187
if(Drupal.jsEnabled) { // Run the code when the DOM has been fully loaded $(document).ready(function(){ // Attach the code to click plusone-click $('a.plusone-link').click(function(){ var voteSaved = function(data){ $('div.score').html(data.total_votes); $('div.vote').html(data.voted); }; alert(this.href); $.ajax({ type: 'POST', url: this.href, dataType: 'json', success: votedSaved, data: 'js=1' }); return false; }); }); }
niying126/beacon
sites/all/modules/plusone/plusone.js
JavaScript
gpl-2.0
482
function reverse(s){ return s.split("").reverse().join(""); } rs=reverse("Hello Javascript"); console.log(rs);
sebastiankalinowski/coderbyte
eReverse/Reverse.js
JavaScript
gpl-2.0
112
'use strict'; angular.module('yeashopApp', [ 'ngCookies', 'ngResource', 'ngSanitize', 'btford.socket-io', 'ui.router', 'ngAnimate', 'ui.navbar', 'ui.bootstrap', 'ngFileUpload', //za slike 'ngCart', 'braintree-angular' //paypal, kartice ]) .config(function($stateProvider, $urlRouterProvider, $locationProvider, $httpProvider) { $urlRouterProvider .otherwise('/'); $locationProvider.html5Mode(true); $httpProvider.interceptors.push('authInterceptor'); }) .factory('authInterceptor', function($rootScope, $q, $cookies, $injector) { var state; return { // Add authorization token to headers request: function(config) { config.headers = config.headers || {}; if ($cookies.get('token')) { config.headers.Authorization = 'Bearer ' + $cookies.get('token'); } return config; }, // Intercept 401s and redirect you to login responseError: function(response) { if (response.status === 401) { (state || (state = $injector.get('$state'))).go('login'); // remove any stale tokens $cookies.remove('token'); return $q.reject(response); } else { return $q.reject(response); } } }; }) .run(function($rootScope, $state, Auth) { // Redirect to login if route requires auth and the user is not logged in $rootScope.$on('$stateChangeStart', function(event, next) { if (next.authenticate) { Auth.isLoggedIn(function(loggedIn) { if (!loggedIn) { event.preventDefault(); $state.go('login'); } }); } }); });
yeahnyea/yshop
client/app/app.js
JavaScript
gpl-2.0
1,695
/* * jQuery plugin used do the message loading, into the main view */ (function($) { $.fn.loadCommunityMessage = function() { // Locate the content to be added $content = $(this) .find('.node-type-community_message') .parent(); // Locate the view content area $wrapper = $(this) .closest('#content') .find('.view-community-messages > .view-content'); // Create a view content area, if no one exists if(!$wrapper.size()){ $wrapper = $(this) .closest('#content') .find('.view-community-messages') .append('<div class="view-content"></div>') .find('.view-content'); } // Create the wrapper to put the content into, with class names and other stuff $item = $('<div></div>') .addClass('views-row') .addClass('views-row-first') .append($content) .hide(); var odd = true; if(!$wrapper.children().size()){ $item.addClass('views-row-last'); } else { odd = $wrapper.children(':first-child') .removeClass('views-row-first') .hasClass('views-row-even'); } $item.addClass(odd ? 'views-row-odd' : 'views-row-even'); // Put the element into the view $wrapper.prepend($item); $item.show('slow'); // Remove the content of the ahah response container $(this).children().remove(); // Remove the form data $('#node-form textarea').val(''); }; }(jQuery));
bsiete2000/redinmob
sites/default/modules/community_messages_alters/js/jquery.plugins.js
JavaScript
gpl-2.0
1,497
var express = require('express'); var Model = require('../models/Model'); var router = express.Router(); var Errors = require('../controllers/common/errors'); var Constants = require('../controllers/common/constants'); /* GET users listing. */ router.get('/', function(req, res, next) { var result = []; var agencies = Model.getAllAgencies(); res.render('index', { agencies: agencies}); }); router.get('/agencies', function(req, res, next) { res.contentType('application/json'); res.setHeader("Access-Control-Allow-Origin", "*"); var agencies = Model.getAllAgencies() || []; var result = []; agencies.forEach(function (item) { var agencyObj = Model.getAgency(item); result.push({ code: agencyObj.name, name: agencyObj.name }) }); res.json(result); }); router.get('/:agencyName/routes', function (req, res, next) { var agencyName = req.params.agencyName; var agencyObj = Model.getAgency(agencyName); var result = []; var err; if (agencyObj) { var routeArray = agencyObj.getAllRouteCodes(); routeArray.forEach(function(item) { var routeObj = agencyObj.getRoute(item); var directionArray = routeObj.getAllDirections() || []; var dirArray = []; directionArray.forEach(function (dirCode) { var dirObj = routeObj.getDirection(dirCode); dirArray.push({ name: dirObj.directionName, code: dirObj.directionCode }); }); result.push({ name: routeObj.routeName, code: routeObj.code, directionArray: dirArray }); }); } else { result = { err: Errors.ERR_INVALID_AGENCY_NAME }; } res.contentType('application/json'); res.setHeader("Access-Control-Allow-Origin", "*"); res.json(result); }); router.get('/:agencyName/:routeCode/:directionCode/stops', function (req, res, next) { var agencyName = req.params.agencyName; var routeCode = req.params.routeCode; var directionCode = req.params.directionCode; var result; var agencyObj = Model.getAgency(agencyName); if (agencyObj) { var routeObj = agencyObj.getRoute(routeCode); if (routeObj) { var dirObj = routeObj.getDirection(directionCode); if (dirObj) { var stopCodeArray = dirObj.getAllStops() || []; result = []; stopCodeArray.forEach(function (item) { var stopObj = dirObj.getStop(item); result.push({ code: stopObj.stopCode, name: stopObj.stopName }); }); } else { result = { err: Errors.ERR_INVALID_DIRECTION_CODE }; } } else { result = { err: Errors.ERR_INVALID_ROUTE_CODE }; } } else { result = { err: Errors.ERR_INVALID_AGENCY_NAME }; } res.contentType('application/json'); res.setHeader("Access-Control-Allow-Origin", "*"); res.json(result); }); router.get('/:agencyName/:routeCode/:directionCode/:stopCode/departures', function (req, res, next) { var currentTime = new Date().getTime(); var agencyName = req.params.agencyName; var routeCode = req.params.routeCode; var directionCode = req.params.directionCode; var stopCode = req.params.stopCode; var agencyObj = Model.getAgency(agencyName); res.contentType('application/json'); res.setHeader("Access-Control-Allow-Origin", "*"); if (agencyObj) { var routeObj = agencyObj.getRoute(routeCode); if (routeObj) { var dirObj = routeObj.getDirection(directionCode); if (dirObj) { var stopObj = dirObj.getStop(stopCode); if (stopObj) { var lastUpdated = stopObj.lastUpdated; if ((currentTime - lastUpdated) > Constants.DEPARTURE_REFRESH_INTERVAL) { // If more than 30 sec var service = req.service; service.getDepartures(stopCode, function (departList, currentRouteCode) { if (currentRouteCode === routeCode) { result = departList; res.json(result); } }); return; // wait for the callback } else { result = stopObj.departureList; } } else { result = { err: Errors.ERR_INVALID_STOP_CODE }; } } else { result = { err: Errors.ERR_INVALID_DIRECTION_CODE }; } } else { result = { err: Errors.ERR_INVALID_ROUTE_CODE }; } } else { result = { err: Errors.ERR_INVALID_AGENCY_NAME }; } res.json(result); }); module.exports = router;
neer300/uberchallenge
RTTransit/routes/agency.js
JavaScript
gpl-2.0
5,362
var searchData= [ ['galeshapleyadmission',['GaleShapleyAdmission',['../classalgo1_1_1GaleShapleyAdmission.html',1,'algo1']]] ];
animeshbaranawalIIT/SeatAllocation
lab10_group26_final/code/GS/html/search/classes_1.js
JavaScript
gpl-2.0
130
//define used to prevent the polluting of global namespace. //first argument of define requires other modules. // second argument is function that requires modules. define([ 'jquery' , 'url/main' , 'backbone' ], function ( $ , BurberryPictureRouter , Backbone ){ var DOMReady = function (){ URL.routers = { //creating new router, which is defined in url/main.js BurberryPictureRouter: new BurberryPictureRouter({ //will append $el to .wrapper.canvas on index.html $el: $('.wrapper.canvas') //will append $search to .wrapper.search , $search: $('.wrapper.search') }) }; }; //DOMReady will be called by jquery on index load. $(document).ready(DOMReady); //Start backbone history a necessary step for bookmarkable URL's will tell backbone that it should start monitoring backbone events Backbone.history.start(); });
NaomiGaynor/playback
public/js/contents.js
JavaScript
gpl-2.0
884
/* global setUserSetting, ajaxurl, commonL10n, alert, confirm, pagenow */ var showNotice, adminMenu, columns, validateForm, screenMeta; ( function( $, window, undefined ) { // Removed in 3.3. // (perhaps) needed for back-compat adminMenu = { init : function() {}, fold : function() {}, restoreMenuState : function() {}, toggle : function() {}, favorites : function() {} }; // show/hide/save table columns columns = { init : function() { var that = this; $('.hide-column-tog', '#adv-settings').click( function() { var $t = $(this), column = $t.val(); if ( $t.prop('checked') ) that.checked(column); else that.unchecked(column); columns.saveManageColumnsState(); }); }, saveManageColumnsState : function() { var hidden = this.hidden(); $.post(ajaxurl, { action: 'hidden-columns', hidden: hidden, screenoptionnonce: $('#screenoptionnonce').val(), page: pagenow }); }, checked : function(column) { $('.column-' + column).removeClass( 'hidden' ); this.colSpanChange(+1); }, unchecked : function(column) { $('.column-' + column).addClass( 'hidden' ); this.colSpanChange(-1); }, hidden : function() { return $( '.manage-column[id]' ).filter( ':hidden' ).map(function() { return this.id; }).get().join( ',' ); }, useCheckboxesForHidden : function() { this.hidden = function(){ return $('.hide-column-tog').not(':checked').map(function() { var id = this.id; return id.substring( id, id.length - 5 ); }).get().join(','); }; }, colSpanChange : function(diff) { var $t = $('table').find('.colspanchange'), n; if ( !$t.length ) return; n = parseInt( $t.attr('colspan'), 10 ) + diff; $t.attr('colspan', n.toString()); } }; $(document).ready(function(){columns.init();}); validateForm = function( form ) { return !$( form ) .find( '.form-required' ) .filter( function() { return $( 'input:visible', this ).val() === ''; } ) .addClass( 'form-invalid' ) .find( 'input:visible' ) .change( function() { $( this ).closest( '.form-invalid' ).removeClass( 'form-invalid' ); } ) .size(); }; // stub for doing better warnings showNotice = { warn : function() { var msg = commonL10n.warnDelete || ''; if ( confirm(msg) ) { return true; } return false; }, note : function(text) { alert(text); } }; screenMeta = { element: null, // #screen-meta toggles: null, // .screen-meta-toggle page: null, // #wpcontent init: function() { this.element = $('#screen-meta'); this.toggles = $( '#screen-meta-links' ).find( '.show-settings' ); this.page = $('#wpcontent'); this.toggles.click( this.toggleEvent ); }, toggleEvent: function() { var panel = $( '#' + $( this ).attr( 'aria-controls' ) ); if ( !panel.length ) return; if ( panel.is(':visible') ) screenMeta.close( panel, $(this) ); else screenMeta.open( panel, $(this) ); }, open: function( panel, button ) { $( '#screen-meta-links' ).find( '.screen-meta-toggle' ).not( button.parent() ).css( 'visibility', 'hidden' ); panel.parent().show(); panel.slideDown( 'fast', function() { panel.focus(); button.addClass( 'screen-meta-active' ).attr( 'aria-expanded', true ); }); $( document ).trigger( 'screen:options:open' ); }, close: function( panel, button ) { panel.slideUp( 'fast', function() { button.removeClass( 'screen-meta-active' ).attr( 'aria-expanded', false ); $('.screen-meta-toggle').css('visibility', ''); panel.parent().hide(); }); $( document ).trigger( 'screen:options:close' ); } }; /** * Help tabs. */ $('.contextual-help-tabs').delegate('a', 'click', function(e) { var link = $(this), panel; e.preventDefault(); // Don't do anything if the click is for the tab already showing. if ( link.is('.active a') ) return false; // Links $('.contextual-help-tabs .active').removeClass('active'); link.parent('li').addClass('active'); panel = $( link.attr('href') ); // Panels $('.help-tab-content').not( panel ).removeClass('active').hide(); panel.addClass('active').show(); }); $(document).ready( function() { var checks, first, last, checked, sliced, mobileEvent, transitionTimeout, focusedRowActions, lastClicked = false, pageInput = $('input.current-page'), currentPage = pageInput.val(), isIOS = /iPhone|iPad|iPod/.test( navigator.userAgent ), isAndroid = navigator.userAgent.indexOf( 'Android' ) !== -1, isIE8 = $( document.documentElement ).hasClass( 'ie8' ), $document = $( document ), $window = $( window ), $body = $( document.body ), $adminMenuWrap = $( '#adminmenuwrap' ), $wpwrap = $( '#wpwrap' ), $adminmenu = $( '#adminmenu' ), $overlay = $( '#wp-responsive-overlay' ), $toolbar = $( '#wp-toolbar' ), $toolbarPopups = $toolbar.find( 'a[aria-haspopup="true"]' ), $sortables = $('.meta-box-sortables'), wpResponsiveActive = false, $adminbar = $( '#wpadminbar' ), lastScrollPosition = 0, pinnedMenuTop = false, pinnedMenuBottom = false, menuTop = 0, menuIsPinned = false, height = { window: $window.height(), wpwrap: $wpwrap.height(), adminbar: $adminbar.height(), menu: $adminMenuWrap.height() }; // when the menu is folded, make the fly-out submenu header clickable $adminmenu.on('click.wp-submenu-head', '.wp-submenu-head', function(e){ $(e.target).parent().siblings('a').get(0).click(); }); $('#collapse-menu').on('click.collapse-menu', function() { var body = $( document.body ), respWidth, state; // reset any compensation for submenus near the bottom of the screen $('#adminmenu div.wp-submenu').css('margin-top', ''); if ( window.innerWidth ) { // window.innerWidth is affected by zooming on phones respWidth = Math.max( window.innerWidth, document.documentElement.clientWidth ); } else { // IE < 9 doesn't support @media CSS rules respWidth = 961; } if ( respWidth && respWidth < 960 ) { if ( body.hasClass('auto-fold') ) { body.removeClass('auto-fold').removeClass('folded'); setUserSetting('unfold', 1); setUserSetting('mfold', 'o'); state = 'open'; } else { body.addClass('auto-fold'); setUserSetting('unfold', 0); state = 'folded'; } } else { if ( body.hasClass('folded') ) { body.removeClass('folded'); setUserSetting('mfold', 'o'); state = 'open'; } else { body.addClass('folded'); setUserSetting('mfold', 'f'); state = 'folded'; } } $( document ).trigger( 'wp-collapse-menu', { state: state } ); }); /** * Ensure an admin submenu is within the visual viewport. * * @since 4.1.0 * * @param {jQuery} $menuItem The parent menu item containing the submenu. */ function adjustSubmenu( $menuItem ) { var bottomOffset, pageHeight, adjustment, theFold, menutop, wintop, maxtop, $submenu = $menuItem.find( '.wp-submenu' ); menutop = $menuItem.offset().top; wintop = $window.scrollTop(); maxtop = menutop - wintop - 30; // max = make the top of the sub almost touch admin bar bottomOffset = menutop + $submenu.height() + 1; // Bottom offset of the menu pageHeight = $wpwrap.height(); // Height of the entire page adjustment = 60 + bottomOffset - pageHeight; theFold = $window.height() + wintop - 50; // The fold if ( theFold < ( bottomOffset - adjustment ) ) { adjustment = bottomOffset - theFold; } if ( adjustment > maxtop ) { adjustment = maxtop; } if ( adjustment > 1 ) { $submenu.css( 'margin-top', '-' + adjustment + 'px' ); } else { $submenu.css( 'margin-top', '' ); } } if ( 'ontouchstart' in window || /IEMobile\/[1-9]/.test(navigator.userAgent) ) { // touch screen device // iOS Safari works with touchstart, the rest work with click mobileEvent = isIOS ? 'touchstart' : 'click'; // close any open submenus when touch/click is not on the menu $(document.body).on( mobileEvent+'.wp-mobile-hover', function(e) { if ( $adminmenu.data('wp-responsive') ) { return; } if ( ! $( e.target ).closest( '#adminmenu' ).length ) { $adminmenu.find( 'li.opensub' ).removeClass( 'opensub' ); } }); $adminmenu.find( 'a.wp-has-submenu' ).on( mobileEvent + '.wp-mobile-hover', function( event ) { var $menuItem = $(this).parent(); if ( $adminmenu.data( 'wp-responsive' ) ) { return; } // Show the sub instead of following the link if: // - the submenu is not open // - the submenu is not shown inline or the menu is not folded if ( ! $menuItem.hasClass( 'opensub' ) && ( ! $menuItem.hasClass( 'wp-menu-open' ) || $menuItem.width() < 40 ) ) { event.preventDefault(); adjustSubmenu( $menuItem ); $adminmenu.find( 'li.opensub' ).removeClass( 'opensub' ); $menuItem.addClass('opensub'); } }); } if ( ! isIOS && ! isAndroid ) { $adminmenu.find( 'li.wp-has-submenu' ).hoverIntent({ over: function() { var $menuItem = $( this ), $submenu = $menuItem.find( '.wp-submenu' ), top = parseInt( $submenu.css( 'top' ), 10 ); if ( isNaN( top ) || top > -5 ) { // the submenu is visible return; } if ( $adminmenu.data( 'wp-responsive' ) ) { // The menu is in responsive mode, bail return; } adjustSubmenu( $menuItem ); $adminmenu.find( 'li.opensub' ).removeClass( 'opensub' ); $menuItem.addClass( 'opensub' ); }, out: function(){ if ( $adminmenu.data( 'wp-responsive' ) ) { // The menu is in responsive mode, bail return; } $( this ).removeClass( 'opensub' ).find( '.wp-submenu' ).css( 'margin-top', '' ); }, timeout: 200, sensitivity: 7, interval: 90 }); $adminmenu.on( 'focus.adminmenu', '.wp-submenu a', function( event ) { if ( $adminmenu.data( 'wp-responsive' ) ) { // The menu is in responsive mode, bail return; } $( event.target ).closest( 'li.menu-top' ).addClass( 'opensub' ); }).on( 'blur.adminmenu', '.wp-submenu a', function( event ) { if ( $adminmenu.data( 'wp-responsive' ) ) { return; } $( event.target ).closest( 'li.menu-top' ).removeClass( 'opensub' ); }).find( 'li.wp-has-submenu.wp-not-current-submenu' ).on( 'focusin.adminmenu', function() { adjustSubmenu( $( this ) ); }); } $( 'div.updated, div.error, div.notice' ).not( '.inline' ).insertAfter( $( '.wrap' ).children( ':header' ).first() ); // Make notices dismissible $( '.notice.is-dismissible' ).each( function() { var $this = $( this ), $button = $( '<button type="button" class="notice-dismiss"><span class="screen-reader-text"></span></button>' ), btnText = commonL10n.dismiss || ''; // Ensure plain text $button.find( '.screen-reader-text' ).text( btnText ); $this.append( $button ); $button.on( 'click.wp-dismiss-notice', function( event ) { event.preventDefault(); $this.fadeTo( 100 , 0, function() { $(this).slideUp( 100, function() { $(this).remove(); }); }); }); }); // Init screen meta screenMeta.init(); // check all checkboxes $('tbody').children().children('.check-column').find(':checkbox').click( function(e) { if ( 'undefined' == e.shiftKey ) { return true; } if ( e.shiftKey ) { if ( !lastClicked ) { return true; } checks = $( lastClicked ).closest( 'form' ).find( ':checkbox' ).filter( ':visible:enabled' ); first = checks.index( lastClicked ); last = checks.index( this ); checked = $(this).prop('checked'); if ( 0 < first && 0 < last && first != last ) { sliced = ( last > first ) ? checks.slice( first, last ) : checks.slice( last, first ); sliced.prop( 'checked', function() { if ( $(this).closest('tr').is(':visible') ) return checked; return false; }); } } lastClicked = this; // toggle "check all" checkboxes var unchecked = $(this).closest('tbody').find(':checkbox').filter(':visible:enabled').not(':checked'); $(this).closest('table').children('thead, tfoot').find(':checkbox').prop('checked', function() { return ( 0 === unchecked.length ); }); return true; }); $('thead, tfoot').find('.check-column :checkbox').on( 'click.wp-toggle-checkboxes', function( event ) { var $this = $(this), $table = $this.closest( 'table' ), controlChecked = $this.prop('checked'), toggle = event.shiftKey || $this.data('wp-toggle'); $table.children( 'tbody' ).filter(':visible') .children().children('.check-column').find(':checkbox') .prop('checked', function() { if ( $(this).is(':hidden,:disabled') ) { return false; } if ( toggle ) { return ! $(this).prop( 'checked' ); } else if ( controlChecked ) { return true; } return false; }); $table.children('thead, tfoot').filter(':visible') .children().children('.check-column').find(':checkbox') .prop('checked', function() { if ( toggle ) { return false; } else if ( controlChecked ) { return true; } return false; }); }); // Show row actions on keyboard focus of its parent container element or any other elements contained within $( '#wpbody-content' ).on({ focusin: function() { clearTimeout( transitionTimeout ); focusedRowActions = $( this ).find( '.row-actions' ); // transitionTimeout is necessary for Firefox, but Chrome won't remove the CSS class without a little help. $( '.row-actions' ).not( this ).removeClass( 'visible' ); focusedRowActions.addClass( 'visible' ); }, focusout: function() { // Tabbing between post title and .row-actions links needs a brief pause, otherwise // the .row-actions div gets hidden in transit in some browsers (ahem, Firefox). transitionTimeout = setTimeout( function() { focusedRowActions.removeClass( 'visible' ); }, 30 ); } }, '.has-row-actions' ); // Toggle list table rows on small screens $( 'tbody' ).on( 'click', '.toggle-row', function() { $( this ).closest( 'tr' ).toggleClass( 'is-expanded' ); }); $('#default-password-nag-no').click( function() { setUserSetting('default_password_nag', 'hide'); $('div.default-password-nag').hide(); return false; }); // tab in textareas $('#newcontent').bind('keydown.wpevent_InsertTab', function(e) { var el = e.target, selStart, selEnd, val, scroll, sel; if ( e.keyCode == 27 ) { // escape key // when pressing Escape: Opera 12 and 27 blur form fields, IE 8 clears them e.preventDefault(); $(el).data('tab-out', true); return; } if ( e.keyCode != 9 || e.ctrlKey || e.altKey || e.shiftKey ) // tab key return; if ( $(el).data('tab-out') ) { $(el).data('tab-out', false); return; } selStart = el.selectionStart; selEnd = el.selectionEnd; val = el.value; if ( document.selection ) { el.focus(); sel = document.selection.createRange(); sel.text = '\t'; } else if ( selStart >= 0 ) { scroll = this.scrollTop; el.value = val.substring(0, selStart).concat('\t', val.substring(selEnd) ); el.selectionStart = el.selectionEnd = selStart + 1; this.scrollTop = scroll; } if ( e.stopPropagation ) e.stopPropagation(); if ( e.preventDefault ) e.preventDefault(); }); if ( pageInput.length ) { pageInput.closest('form').submit( function() { // Reset paging var for new filters/searches but not for bulk actions. See #17685. if ( $('select[name="action"]').val() == -1 && $('select[name="action2"]').val() == -1 && pageInput.val() == currentPage ) pageInput.val('1'); }); } $('.search-box input[type="search"], .search-box input[type="submit"]').mousedown(function () { $('select[name^="action"]').val('-1'); }); // Scroll into view when focused $('#contextual-help-link, #show-settings-link').on( 'focus.scroll-into-view', function(e){ if ( e.target.scrollIntoView ) e.target.scrollIntoView(false); }); // Disable upload buttons until files are selected (function(){ var button, input, form = $('form.wp-upload-form'); if ( ! form.length ) return; button = form.find('input[type="submit"]'); input = form.find('input[type="file"]'); function toggleUploadButton() { button.prop('disabled', '' === input.map( function() { return $(this).val(); }).get().join('')); } toggleUploadButton(); input.on('change', toggleUploadButton); })(); function pinMenu( event ) { var windowPos = $window.scrollTop(), resizing = ! event || event.type !== 'scroll'; if ( isIOS || isIE8 || $adminmenu.data( 'wp-responsive' ) ) { return; } if ( height.menu + height.adminbar < height.window || height.menu + height.adminbar + 20 > height.wpwrap ) { unpinMenu(); return; } menuIsPinned = true; if ( height.menu + height.adminbar > height.window ) { // Check for overscrolling if ( windowPos < 0 ) { if ( ! pinnedMenuTop ) { pinnedMenuTop = true; pinnedMenuBottom = false; $adminMenuWrap.css({ position: 'fixed', top: '', bottom: '' }); } return; } else if ( windowPos + height.window > $document.height() - 1 ) { if ( ! pinnedMenuBottom ) { pinnedMenuBottom = true; pinnedMenuTop = false; $adminMenuWrap.css({ position: 'fixed', top: '', bottom: 0 }); } return; } if ( windowPos > lastScrollPosition ) { // Scrolling down if ( pinnedMenuTop ) { // let it scroll pinnedMenuTop = false; menuTop = $adminMenuWrap.offset().top - height.adminbar - ( windowPos - lastScrollPosition ); if ( menuTop + height.menu + height.adminbar < windowPos + height.window ) { menuTop = windowPos + height.window - height.menu - height.adminbar; } $adminMenuWrap.css({ position: 'absolute', top: menuTop, bottom: '' }); } else if ( ! pinnedMenuBottom && $adminMenuWrap.offset().top + height.menu < windowPos + height.window ) { // pin the bottom pinnedMenuBottom = true; $adminMenuWrap.css({ position: 'fixed', top: '', bottom: 0 }); } } else if ( windowPos < lastScrollPosition ) { // Scrolling up if ( pinnedMenuBottom ) { // let it scroll pinnedMenuBottom = false; menuTop = $adminMenuWrap.offset().top - height.adminbar + ( lastScrollPosition - windowPos ); if ( menuTop + height.menu > windowPos + height.window ) { menuTop = windowPos; } $adminMenuWrap.css({ position: 'absolute', top: menuTop, bottom: '' }); } else if ( ! pinnedMenuTop && $adminMenuWrap.offset().top >= windowPos + height.adminbar ) { // pin the top pinnedMenuTop = true; $adminMenuWrap.css({ position: 'fixed', top: '', bottom: '' }); } } else if ( resizing ) { // Resizing pinnedMenuTop = pinnedMenuBottom = false; menuTop = windowPos + height.window - height.menu - height.adminbar - 1; if ( menuTop > 0 ) { $adminMenuWrap.css({ position: 'absolute', top: menuTop, bottom: '' }); } else { unpinMenu(); } } } lastScrollPosition = windowPos; } function resetHeights() { height = { window: $window.height(), wpwrap: $wpwrap.height(), adminbar: $adminbar.height(), menu: $adminMenuWrap.height() }; } function unpinMenu() { if ( isIOS || ! menuIsPinned ) { return; } pinnedMenuTop = pinnedMenuBottom = menuIsPinned = false; $adminMenuWrap.css({ position: '', top: '', bottom: '' }); } function setPinMenu() { resetHeights(); if ( $adminmenu.data('wp-responsive') ) { $body.removeClass( 'sticky-menu' ); unpinMenu(); } else if ( height.menu + height.adminbar > height.window ) { pinMenu(); $body.removeClass( 'sticky-menu' ); } else { $body.addClass( 'sticky-menu' ); unpinMenu(); } } if ( ! isIOS ) { $window.on( 'scroll.pin-menu', pinMenu ); $document.on( 'tinymce-editor-init.pin-menu', function( event, editor ) { editor.on( 'wp-autoresize', resetHeights ); }); } window.wpResponsive = { init: function() { var self = this; // Modify functionality based on custom activate/deactivate event $document.on( 'wp-responsive-activate.wp-responsive', function() { self.activate(); }).on( 'wp-responsive-deactivate.wp-responsive', function() { self.deactivate(); }); $( '#wp-admin-bar-menu-toggle a' ).attr( 'aria-expanded', 'false' ); // Toggle sidebar when toggle is clicked $( '#wp-admin-bar-menu-toggle' ).on( 'click.wp-responsive', function( event ) { event.preventDefault(); // close any open toolbar submenus $adminbar.find( '.hover' ).removeClass( 'hover' ); $wpwrap.toggleClass( 'wp-responsive-open' ); if ( $wpwrap.hasClass( 'wp-responsive-open' ) ) { $(this).find('a').attr( 'aria-expanded', 'true' ); $( '#adminmenu a:first' ).focus(); } else { $(this).find('a').attr( 'aria-expanded', 'false' ); } } ); // Add menu events $adminmenu.on( 'click.wp-responsive', 'li.wp-has-submenu > a', function( event ) { if ( ! $adminmenu.data('wp-responsive') ) { return; } $( this ).parent( 'li' ).toggleClass( 'selected' ); event.preventDefault(); }); self.trigger(); $document.on( 'wp-window-resized.wp-responsive', $.proxy( this.trigger, this ) ); // This needs to run later as UI Sortable may be initialized later on $(document).ready() $window.on( 'load.wp-responsive', function() { var width = navigator.userAgent.indexOf('AppleWebKit/') > -1 ? $window.width() : window.innerWidth; if ( width <= 782 ) { self.disableSortables(); } }); }, activate: function() { setPinMenu(); if ( ! $body.hasClass( 'auto-fold' ) ) { $body.addClass( 'auto-fold' ); } $adminmenu.data( 'wp-responsive', 1 ); this.disableSortables(); }, deactivate: function() { setPinMenu(); $adminmenu.removeData('wp-responsive'); this.enableSortables(); }, trigger: function() { var width; if ( window.innerWidth ) { // window.innerWidth is affected by zooming on phones width = Math.max( window.innerWidth, document.documentElement.clientWidth ); } else { // Exclude IE < 9, it doesn't support @media CSS rules return; } if ( width <= 782 ) { if ( ! wpResponsiveActive ) { $document.trigger( 'wp-responsive-activate' ); wpResponsiveActive = true; } } else { if ( wpResponsiveActive ) { $document.trigger( 'wp-responsive-deactivate' ); wpResponsiveActive = false; } } if ( width <= 480 ) { this.enableOverlay(); } else { this.disableOverlay(); } }, enableOverlay: function() { if ( $overlay.length === 0 ) { $overlay = $( '<div id="wp-responsive-overlay"></div>' ) .insertAfter( '#wpcontent' ) .hide() .on( 'click.wp-responsive', function() { $toolbar.find( '.menupop.hover' ).removeClass( 'hover' ); $( this ).hide(); }); } $toolbarPopups.on( 'click.wp-responsive', function() { $overlay.show(); }); }, disableOverlay: function() { $toolbarPopups.off( 'click.wp-responsive' ); $overlay.hide(); }, disableSortables: function() { if ( $sortables.length ) { try { $sortables.sortable('disable'); } catch(e) {} } }, enableSortables: function() { if ( $sortables.length ) { try { $sortables.sortable('enable'); } catch(e) {} } } }; window.wpResponsive.init(); setPinMenu(); $document.on( 'wp-pin-menu wp-window-resized.pin-menu postboxes-columnchange.pin-menu postbox-toggled.pin-menu wp-collapse-menu.pin-menu wp-scroll-start.pin-menu', setPinMenu ); }); // Fire a custom jQuery event at the end of window resize ( function() { var timeout; function triggerEvent() { $(document).trigger( 'wp-window-resized' ); } function fireOnce() { window.clearTimeout( timeout ); timeout = window.setTimeout( triggerEvent, 200 ); } $(window).on( 'resize.wp-fire-once', fireOnce ); }()); // Make Windows 8 devices play along nicely. (function(){ if ( '-ms-user-select' in document.documentElement.style && navigator.userAgent.match(/IEMobile\/10\.0/) ) { var msViewportStyle = document.createElement( 'style' ); msViewportStyle.appendChild( document.createTextNode( '@-ms-viewport{width:auto!important}' ) ); document.getElementsByTagName( 'head' )[0].appendChild( msViewportStyle ); } })(); }( jQuery, window ));
hanwoody/WordPress
wp-admin/js/common.js
JavaScript
gpl-2.0
24,308
/** * Contempo Mapping * * @package WP Pro Real Estate 3 * @subpackage JavaScript */ var estateMapping = (function () { var self = {}, marker_list = [], open_info_window = null, x_center_offset = 0, // x,y offset in px when map gets built with marker bounds y_center_offset = -100, x_info_offset = 0, // x,y offset in px when map pans to marker -- to accomodate infoBubble y_info_offset = -100; function build_marker(latlng, property) { var marker = new MarkerWithLabel({ map: self.map, draggable: false, flat: true, labelContent: property.price, labelAnchor: new google.maps.Point(22, 0), labelClass: "label", // the CSS class for the label labelStyle: {opacity: 1}, icon: 'wp-content/themes/realestate_3/images/blank.png', position: latlng }); self.bounds.extend(latlng); self.map.fitBounds(self.bounds); self.map.setCenter(convert_offset(self.bounds.getCenter(), x_center_offset, y_center_offset)); var infoBubble = new InfoBubble({ maxWidth: 275, content: contentString, borderRadius: 3, disableAutoPan: true }); var residentialString = ''; if(property['commercial'] != 'commercial') { var residentialString='<p class="details">'+property.bed+' br, '+property.bath+' ba'; } var contentString = '<div class="info-content">'+ '<a href="'+property.permalink+'"><img class="left" src="'+property.thumb+'" /></a>'+ '<div class="listing-details left">'+ '<h3><a href="'+property.permalink+'">'+property.street+'</a></h3>'+ '<p class="location">'+property.city+', '+property.state+'&nbsp;'+property.zip+'</p>'+ '<p class="price"><strong>'+property.fullPrice+'</strong></p>'+residentialString+', '+property.size+'</p></div>'+ '</div>'; var tabContent = '<div class="info-content">'+ '<img class="left" src="'+property.agentThumb+'" />'+ '<div class="listing-details left">'+ '<h3>'+property.agentName+'</h3>'+ '<p class="tagline">'+property.agentTagline+'</p>'+ '<p class="phone"><strong>Tel:</strong> '+property.agentPhone+'</p>'+ '<p class="email"><a href="mailto:'+property.agentEmail+'">'+property.agentEmail+'</a></p>'+ '</div>'+ '</div>'; infoBubble.addTab('Details', contentString); infoBubble.addTab('Contact Agent', tabContent); google.maps.event.addListener(marker, 'click', function() { if(open_info_window) open_info_window.close(); if (!infoBubble.isOpen()) { infoBubble.open(self.map, marker); self.map.panTo(convert_offset(this.position, x_info_offset, y_info_offset)); open_info_window = infoBubble; } }); } function geocode_and_place_marker(property) { var geocoder = new google.maps.Geocoder(); var address = property.street+', '+property.city+' '+property.state+', '+property.zip; //If latlong exists build the marker, otherwise geocode then build the marker if (property['latlong']) { var lat = parseFloat(property['latlong'].split(',')[0]), lng = parseFloat(property['latlong'].split(',')[1]); var latlng = new google.maps.LatLng(lat,lng); build_marker(latlng, property); } else { geocoder.geocode({ address : address }, function( results, status ) { if(status == google.maps.GeocoderStatus.OK) { var latlng = results[0].geometry.location; build_marker(latlng, property); } }); } } function init_canvas_projection() { function CanvasProjectionOverlay() {} CanvasProjectionOverlay.prototype = new google.maps.OverlayView(); CanvasProjectionOverlay.prototype.constructor = CanvasProjectionOverlay; CanvasProjectionOverlay.prototype.onAdd = function(){}; CanvasProjectionOverlay.prototype.draw = function(){}; CanvasProjectionOverlay.prototype.onRemove = function(){}; self.canvasProjectionOverlay = new CanvasProjectionOverlay(); self.canvasProjectionOverlay.setMap(self.map); } function convert_offset(latlng, x_offset, y_offset) { var proj = self.canvasProjectionOverlay.getProjection(); var point = proj.fromLatLngToContainerPixel(latlng); point.x = point.x + x_offset; point.y = point.y + y_offset; return proj.fromContainerPixelToLatLng(point); } self.init_property_map = function (properties, defaultmapcenter) { var center=defaultmapcenter.mapcenter.split(","); var options = { zoom: 15, //center: new google.maps.LatLng(defaultmapcenter.mapcenter), center: new google.maps.LatLng(center[0],center[1]), mapTypeId: google.maps.MapTypeId.ROADMAP, disableDefaultUI: true, streetViewControl: false }; self.map = new google.maps.Map( document.getElementById( 'map' ), options ); self.bounds = new google.maps.LatLngBounds(); init_canvas_projection(); //wait for idle to give time to grab the projection (for calculating offset) var idle_listener = google.maps.event.addListener(self.map, 'idle', function() { for (i=0;i<properties.length;i++) { geocode_and_place_marker(properties[i]); } google.maps.event.removeListener(idle_listener); }); } return self; }());
Alexscandal/Motel-explore
wp-content/themes/realestate_3/js/mapping.js
JavaScript
gpl-2.0
5,516
// remap jQuery to $ ;(function($){ $.fn.attentionGrabber = function(options) { var defaults = { duration : 500, position : 'top', closeable : true, showAfter : 0, keepHidden : false, borderSize : 3, height : 40, easing : "linear" }, settings = $.extend({}, defaults, options); if( settings.easing == "swing" ){ settings.easing = ''; } settings.totalHeight = parseInt( settings.height, 10 ) + parseInt( settings.borderSize, 10 ); settings.duration = parseInt( settings.duration, 10 ); settings.showAfter = parseInt( settings.showAfter, 10 )*1000; settings.foundCookie = (settings.foundCookie === 'true') ? true : false; // Disable attentionGrabber on Safari Mobile when placed at the bottom var deviceAgent = navigator.userAgent.toLowerCase(); var agentID = deviceAgent.match(/(iphone|ipod|ipad)/); if ( agentID && settings.position == 'bottom_fixed' ) { return false; } // Main elements var wrap = $(this), grabber = wrap.find("#attentionGrabber"), link = grabber.find(".link"), closeBtn = grabber.find("#closeAttentionGrabber"), openBtn = wrap.find("#openAttentionGrabber"), animationParam = {}, animationProperty = "", buttonAnimationParam = {}, buttonAnimationProperty = "", showOpenButton = function(){ buttonAnimationParam[buttonAnimationProperty] = settings.totalHeight; openBtn.animate( buttonAnimationParam, (settings.duration/2), settings.easing ); wrap.removeClass("openGrabber"); }, hideOpenButton = function(){ buttonAnimationParam[buttonAnimationProperty] = - Math.abs(34 - settings.height); openBtn.animate( buttonAnimationParam, (settings.duration/2), function(){ showGrabber(); } ); }, // The show/hide animations showGrabber = function(){ animationParam[animationProperty] = 0; wrap.animate( animationParam , settings.duration, settings.easing ,function(){ wrap.addClass("openGrabber"); // If buddypress bar is enabled if( $("#wp-admin-bar").length ) { $("#wp-admin-bar").css({ top : settings.totalHeight }); } } ); }, hideGrabber = function(){ animationParam[animationProperty] = -settings.totalHeight; wrap.animate( animationParam , settings.duration, function(){ showOpenButton(); // If buddypress bar is enabled if( $("#wp-admin-bar").length ) { $("#wp-admin-bar").css({ top : 0 }); } } ); }; // If the admin bar is enabled if( $("#wpadminbar").length && settings.position == 'top_fixed' ){ wrap.addClass("admBar"); } // Initialize the property for the slide animation switch( settings.position ){ case "top" : animationProperty = "marginTop"; buttonAnimationProperty = "top"; break; case "top_fixed" : animationProperty = "top"; buttonAnimationProperty = "top"; break; case "bottom_fixed" : animationProperty = "bottom"; buttonAnimationProperty = "bottom"; break; } // Extra functionalities attentionGrabberExtras = { multipleMessages : { clearTimer : function(){ clearTimeout( this.timer ); }, setTimer : function(){ var obj = this; this.clearTimer(); this.timer = setTimeout( function(){ obj.showNext(); }, this.pause ); }, showNext : function(){ var obj = this; this.currentMsg.fadeOut( this.speed, function(){ obj.nextMsg.fadeIn(obj.speed, function(){ obj.prepareNext(); }); }); }, prepareNext : function(){ var nextIndex = this.nextMsg.index(); this.currentMsg = this.nextMsg; if( nextIndex == this.msgLength ){ // If this is the last one if( this.loop ){ // If the loop is enabled nextIndex = 0; }else{ return false; } }else{ nextIndex++; } this.nextMsg = this.messages.eq( nextIndex ); this.setTimer(); }, init : function(){ this.main = grabber.find(".multiMessages"); this.messages = this.main.find(".singleMessage"); this.currentMsg = this.messages.eq(0); this.nextMsg = this.messages.eq(1); this.msgLength = this.messages.length -1; this.pause = this.main.data("pause"); this.speed = Math.round( this.main.data("speed")/2 ); this.hoverPause = this.main.data("pauseonhover"); this.loop = this.main.data("loop"); // Show the first message this.currentMsg.addClass("current"); if( this.msgLength > 0 ){ this.setTimer(); }else{ // If there are no other messages // Do nothing } if( this.hoverPause ){ var obj = this; grabber.hover(function(){ obj.clearTimer(); }, function(){ obj.setTimer(); }); } } } }; // Remove it from the DOM wrap.detach(); // Move it to the right position wrap.prependTo("body").css({ display : "block" }); // Execute any extra functionalities if( grabber.find(".multiMessages").length ){ attentionGrabberExtras.multipleMessages.init(); } if( settings.foundCookie && settings.keepHidden && settings.closeable ){ // Show only the open button setTimeout( function(){ showOpenButton(); }, settings.showAfter ); }else { // Show the grabber for the first time setTimeout( function(){ showGrabber(); }, settings.showAfter ); } // Close grabber closeBtn.click(function(){ hideGrabber(); setCookie(); }); // Open grabber openBtn.click(function(){ hideOpenButton(); setCookie(); }); // Set the cookie function setCookie(){ if( settings.keepHidden ){ var dataObj = { 'action' : 'ag_do_ajax', 'function' : 'unset_cookie' }, cb = function(){ settings.foundCookie = false; }; if( !settings.foundCookie ){ dataObj['function'] = 'set_cookie'; cb = function(){ settings.foundCookie = true; }; } $.ajax({ type : 'post', dataType : 'JSON', url : settings.ajaxUrl, data : dataObj, success : function(results){ console.log(results); cb(); } }); } } // Add a click counter link.click(function(){ var dataObj = { 'action' : 'ag_do_ajax', 'function' : 'register_click' }; $.ajax({ type : 'post', dataType : 'JSON', url : settings.ajaxUrl, data : dataObj, success : function(results){ console.log(results); cb(); } }); return true; }); }; })(window.jQuery); jQuery(document).ready(function($){ // Custom jQuery Easing if( !$.easing.hasOwnProperty( 'easeOutBounce' ) ){ $.extend( $.easing,{ easeOutBounce: function (x, t, b, c, d) { if ((t/=d) < (1/2.75)) { return c*(7.5625*t*t) + b; } else if (t < (2/2.75)) { return c*(7.5625*(t-=(1.5/2.75))*t + 0.75) + b; } else if (t < (2.5/2.75)) { return c*(7.5625*(t-=(2.25/2.75))*t + 0.9375) + b; } else { return c*(7.5625*(t-=(2.625/2.75))*t + 0.984375) + b; } } }); } if( window.attentionGrabber_params && typeof window.attentionGrabber_params === 'object' ) { $("#attentionGrabberWrap").attentionGrabber( window.attentionGrabber_params ); } });
damond-pocketatl/invitationHomes
wp-content/plugins/attentionGrabber_v1.6/js/attentionGrabber.js
JavaScript
gpl-2.0
7,237
/** * Created with JetBrains PhpStorm. * User: edvinbrobeck * Date: 2013-08-28 * Time: 15:50 * To change this template use File | Settings | File Templates. */
MaxHill/omelettfoto
wp-content/themes/omelettfoto/assets/js/source/plugins/sample.js
JavaScript
gpl-2.0
166
var stones = [] var running = true function stonePlaced(stoneComponent, parent) { if(running) { var stone = stoneComponent.createObject(parent); stone.handleDetectionStarted() stones.push(stone); stone.destructionRequested.connect(removeStone) console.log("added stone to list: # of stone=" + stones.length) } } // handle colorDetected event function colorDetected(color, trayId, position) { var handled = false var index = 0 while(index < stones.length) { var stone = stones[index] if(stone) { if(stone.handleColorDetected(color, trayId, position)) { handled = true break; } } index++ } if(!handled) { console.log("WARNING: colorDetected event was not handled!") } } // handle detectorEndReached event function detectorEndReached() { var handled = false var index = 0 while(index < stones.length) { var stone = stones[index] if(stone) { if(stone.handleDetectorEndReached()) { handled = true break; } } index++ } if(!handled) { console.log("WARNING: detectorEndReached event was not handled!") } } // handle startEjecting event function startEjecting(trayId) { var handled = false var index = 0 while(index < stones.length) { var stone = stones[index] if(stone) { if(stone.handleStartEjecting(trayId)) { handled = true break; } } index++ } if(!handled) { console.log("WARNING: detectorEndReached event was not handled!") } } // handle trayReached event function trayReached(trayId) { var index = 0 while(index < stones.length) { var stone = stones[index] if(stone) { if(stone.handleTrayReached(trayId)) { var neededTime = stone.neededTime() console.log("----------------------- stone in tray#" + trayId + " reached in " + neededTime + "ms") return neededTime } } index++ } console.log("WARNING: trayReached event was not handled!") return false } // removes all stones in the given tray function removeStonesFromTray(trayId) { var index = 0 while(index < stones.length) { var stone = stones[index] if(stone) { if(stone.handleReachedTray(trayId)) { stones.splice(index, 1) console.log("INFO: handled removeStonesFromTray on tray #" + trayId + " .... remaining " + stones.length) stone.destroy() continue } } index++ } } // removes the given stone function removeStone(stoneToRemove) { var index = stones.indexOf(stoneToRemove) if(index >= 0) { stones.splice(index, 1) stoneToRemove.destroy() console.log("INFO: handled removeStone .... remaining " + stones.length) } } // removes all stones from the list function removeAllStones() { while(stones.length > 0) { var stone = stones[0] stones.splice(0, 1) console.log("INFO: handled removeAllStones .... remaining " + stones.length) stone.destroy() } console.assert(0 == stones.length, "stone list is not empty after removeAllStones!"); } function shutdown() { if(running) { running = false // remove all stones for(var index = 0; index < stones.length; index++) { stones[index].destroy(); } } }
bbvch/farbsort-gui
qml/items/StoneHandler.js
JavaScript
gpl-3.0
3,648
'use strict'; const http = require('http'); module.exports = function *errorHandler(next) { try { yield next; if (this.response.status === 404 && !this.response.body) { this.throw(404); } } catch (err) { this.status = err.status || 500; this.app.emit('error', err, this); switch (this.accepts('html', 'json', 'text')) { case 'json': this.body = { error: http.STATUS_CODES[this.status] }; yield next; break; case 'html': yield this.render('error', { error: http.STATUS_CODES[this.status], code: this.status, url: this.originalUrl }); break; case 'text': this.body = http.STATUS_CODES[this.status]; yield next; break; default: yield this.throw(406); } } };
plugCubed/plugCubed-Website
middleware/error.js
JavaScript
gpl-3.0
1,044
/** * Created by kozhevnikov on 01.04.2016. */ var onmotion = {}; onmotion.gallery = function (id, extOptions) { document.getElementById('gallery-links').onclick = function (event) { event = event || window.event; var target = event.target || event.srcElement, options = typeof extOptions == 'object' ? extOptions : JSON.parse(extOptions), links = this.getElementsByTagName('a'); options.index = target.src ? target.parentNode : target; options.event = event; blueimp.Gallery(links, options); }; }; $(document).ready(function () { var $galleryItem = $('.gallery-item > img'); var count = 0; var $deleteBtn = $('#photos-delete-btn'); var $resetBtn = $('#reset-all'); var $checkAllBtn = $('#check-all'); function editClick(e) { e.preventDefault(); if ($(this).hasClass('checked')) { $(this).removeClass('checked'); count--; } else { $(this).addClass('checked'); count++; } (count > 0) ? $deleteBtn.show() : $deleteBtn.hide(); return false; } $(document).on('click', '#check-toggle', function (e) { e.preventDefault(); if ($(this).hasClass('checked')) { $(this).removeClass('checked'); $galleryItem.off('click', editClick); $checkAllBtn.hide(); $resetBtn.hide(); $galleryItem.each(function () { $(this).removeClass('edit-mode'); }); } else { $(this).addClass('checked'); $galleryItem.on('click', editClick); $checkAllBtn.show(); $resetBtn.show(); $galleryItem.each(function () { $(this).addClass('edit-mode'); }); } }); $checkAllBtn.click(function (e) { e.preventDefault(); $galleryItem.each(function () { $(this).trigger('click'); }); }); $(document).on('click', '#reset-all', function (e) { e.preventDefault(); $galleryItem.each(function () { $(this).removeClass('checked'); }); count = 0; $deleteBtn.hide(); }); $(document).on('click', '#photos-delete-confirm-btn', function (e) { e.preventDefault(); var idForRemove = []; var $modal = $('#gallery-modal'); $('img.checked').each(function () { idForRemove.push($(this).parent().attr('data-id')); }); var dataForRemove = {}; dataForRemove.ids = idForRemove; $.ajax({ type: 'post', url: $(this).attr('href'), data: dataForRemove, beforeSend: function () { $modal.find('.modal-body').html('<div class="progress"><div class="progress-bar progress-bar-striped active" role="progressbar" aria-valuenow="100" aria-valuemin="0" aria-valuemax="100" style="width:100%"><span class="sr-only">100</span></div></div>'); }, success: function (data, textStatus, xhr) { $modal.find('.modal-body').html('Success!'); $(this).hide(); location.reload(); }, error: function (xhr, textStatus, errorThrown) { console.log(xhr); console.log(textStatus); console.log(errorThrown); $modal.find('.modal-body').html(xhr); } }); }); });
onmotion/yii2-gallery
assets/js/onmotion-gallery.js
JavaScript
gpl-3.0
3,510
'use strict'; var logger = require('winston'); module.exports = function(role){ return function(req, res, next){ logger.debug(req.user); if(!req.user) return res.status(401).json({ err: 'Unauthorized' }); if( req.user.role !== role ) return res.status(403).json({ err: 'Access Denied' }); next(); }; };
ahmed-dinar/JustOJ
server/middlewares/roles.js
JavaScript
gpl-3.0
341
/** * @license Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved. * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license */ /** * @fileOverview Defines the {@link CKEDITOR.dom.document} class, which * represents a DOM document. */ /** * Represents a DOM window. * * var document = new CKEDITOR.dom.window( window ); * * @class * @extends CKEDITOR.dom.domObject * @constructor Creates a window class instance. * @param {Object} domWindow A native DOM window. */ CKEDITOR.dom.window = function( domWindow ) { CKEDITOR.dom.domObject.call( this, domWindow ); }; CKEDITOR.dom.window.prototype = new CKEDITOR.dom.domObject(); CKEDITOR.tools.extend( CKEDITOR.dom.window.prototype, { /** * Moves the selection focus to this window. * * var win = new CKEDITOR.dom.window( window ); * win.focus(); */ focus: function() { this.$.focus(); }, /** * Gets the width and height of this window's viewable area. * * var win = new CKEDITOR.dom.window( window ); * var size = win.getViewPaneSize(); * alert( size.width ); * alert( size.height ); * * @returns {Object} An object with the `width` and `height` * properties containing the size. */ getViewPaneSize: function() { var doc = this.$.document, stdMode = doc.compatMode == 'CSS1Compat'; return { width: ( stdMode ? doc.documentElement.clientWidth : doc.body.clientWidth ) || 0, height: ( stdMode ? doc.documentElement.clientHeight : doc.body.clientHeight ) || 0 }; }, /** * Gets the current position of the window's scroll. * * var win = new CKEDITOR.dom.window( window ); * var pos = win.getScrollPosition(); * alert( pos.x ); * alert( pos.y ); * * @returns {Object} An object with the `x` and `y` properties * containing the scroll position. */ getScrollPosition: function() { var $ = this.$; if ( 'pageXOffset' in $ ) { return { x: $.pageXOffset || 0, y: $.pageYOffset || 0 }; } else { var doc = $.document; return { x: doc.documentElement.scrollLeft || doc.body.scrollLeft || 0, y: doc.documentElement.scrollTop || doc.body.scrollTop || 0 }; } }, /** * Gets the frame element containing this window context. * * @returns {CKEDITOR.dom.element} The frame element or `null` if not in a frame context. */ getFrame: function() { var iframe = this.$.frameElement; return iframe ? new CKEDITOR.dom.element.get( iframe ) : null; } } );
ernestbuffington/PHP-Nuke-Titanium
includes/wysiwyg/ckeditor/core/dom/window.js
JavaScript
gpl-3.0
2,489
/** * @author Timur Kuzhagaliyev <tim.kuzh@gmail.com> * @copyright 2017 * @license GPL-3.0 */ class Helper { lerp(current, target, fraction) { if(isNaN(target) || target === Infinity || target === -Infinity) return current; return current + (target - current) * fraction; } constrain(max, min, value) { return Math.min(max, Math.max(min, value)); } } module.exports = Helper;
TimboKZ/Akko
lib/Helper.js
JavaScript
gpl-3.0
425
/** File menu / Top navigation control @class NavigationView @constructor @return {Object} instantiated FileMenu **/ define(['jquery', 'backbone', 'bootbox'], function ($, Backbone, bootbox) { BB.SERVICES.NAVIGATION_VIEW = 'NavigationView'; var NavigationView = BB.View.extend({ /** Constructor @method initialize all listeners on all navigation UI buttons **/ initialize: function () { var self = this; BB.comBroker.setService(BB.SERVICES.NAVIGATION_VIEW, self); self._render(); self._listenToiFrameEvents(); $(Elements.LIVE_CHAT).on('click', function () { var pop = window.open(BB.globs['CHAT'], '_blank'); self._closeMobileNavigation(); }); $(Elements.DOWNLOAD_SIGNAGE_PLAYER).on('click', function (e) { e.preventDefault(); //var pop = window.open('http://start.digitalsignage.com', '_blank'); Backbone.comBroker.getService(Backbone.SERVICES.LAYOUT_ROUTER).navigate('directDownload', {trigger: true}); return false; }); $(Elements.LANGUAGE_PROMPT).on('click', function () { require(['LanguageSelectorView'], function (LanguageSelectorView) { var uniqueID = _.uniqueId('languagePrompt') var modal = bootbox.dialog({ message: '<div id="' + uniqueID + '"></div>', title: $(Elements.MSG_BOOTBOX_COSTUME_TITLE).text(), show: false, buttons: { success: { label: '<i style="font-size: 1em" class="fa fa-forward "></i>', className: "btn-success", callback: function () { $('#' + uniqueID).empty(); } } } }); modal.modal("show"); new LanguageSelectorView({appendTo: '#' + uniqueID}); }); }); }, _closeMobileNavigation: function () { if ($('.navbar-header .navbar-toggle').css('display') != 'none') { $(".navbar-header .navbar-toggle").trigger("click"); } }, /** Action on application resize @method _onAppResized @param {Event} e **/ _onAppResized: function (e) { var self = this; self._toggleIcons(e.edata.width) }, /** Toggle visibility of navigation icons depending on app total width @method _toggleIcons @param {Number} i_size **/ _toggleIcons: function (i_size) { if (i_size > 1500) { $(Elements.CLASS_NAV_ICONS).show(); } else { $(Elements.CLASS_NAV_ICONS).hide(); } }, _render: function () { $('.navbar-nav').css({ display: 'block' }) }, _listenToiFrameEvents: function () { var self = this; var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent"; var eventer = window[eventMethod]; var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message"; eventer(messageEvent, function (e) { switch (e.data.command) { case 'setTitle': { parent.document.title = e.data.param; break; } case 'logout': { self.logUserOut(); break; } } }, false); }, logUserOut: function () { var self = this; var appEntryFaderView = BB.comBroker.getService(BB.SERVICES['APP_ENTRY_FADER_VIEW']); appEntryFaderView.selectView(Elements.APP_LOGOUT); BB.comBroker.getService(BB.SERVICES['APP_AUTH']).logout(); }, enableLogout: function () { var self = this; $(Elements.LOGOUT_HEADER).fadeIn(); $(Elements.LOGOUT).on('click', function () { self.logUserOut(); }); } }); return NavigationView; });
onezerone/msgetstarted
_views/NavigationView.js
JavaScript
gpl-3.0
4,578
/** * Copyright 2016-present Telldus Technologies AB. * * This file is part of the Telldus Live! app. * * Telldus Live! app is free : 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. * * Telldus Live! app 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 Telldus Live! app. If not, see <http://www.gnu.org/licenses/>. * */ // @flow 'use strict'; import React from 'react'; import { View, TouchableButton, InfoBlock, ThemedScrollView, } from '../../../../BaseComponents'; import capitalize from '../../../Lib/capitalize'; import Theme from '../../../Theme'; import i18n from '../../../Translations/common'; type Props = { appLayout: Object, route: Object, intl: Object, onDidMount: (string, string, ?Object) => void, actions: Object, navigation: Object, }; class NoDeviceFound extends View<Props, null> { props: Props; onPressExclude: () => void; onPressTryAgain: () => void; onPressExit: () => void; constructor(props: Props) { super(props); this.onPressExclude = this.onPressExclude.bind(this); this.onPressTryAgain = this.onPressTryAgain.bind(this); this.onPressExit = this.onPressExit.bind(this); } componentDidMount() { const { onDidMount, intl } = this.props; const { formatMessage } = intl; onDidMount(capitalize(formatMessage(i18n.noDeviceFound)), formatMessage(i18n.checkAndTryAgain)); } onPressExit() { const { navigation } = this.props; navigation.popToTop(); } onPressExclude() { const { navigation, route } = this.props; const { params = {}} = route; navigation.navigate('ExcludeScreen', {...params}); } onPressTryAgain() { const { navigation, route } = this.props; const { params = {}} = route; navigation.navigate('IncludeDevice', {...params}); } render(): Object { const { intl, appLayout } = this.props; const { formatMessage } = intl; const { container, infoContainer, infoTextStyle, statusIconStyle, buttonStyle, brandDanger, } = this.getStyles(); return ( <ThemedScrollView level={3}> <View style={container}> <InfoBlock text={formatMessage(i18n.noDeviceFoundMessageInclude)} appLayout={appLayout} infoContainer={infoContainer} textStyle={infoTextStyle} infoIconStyle={statusIconStyle}/> <TouchableButton text={capitalize(formatMessage(i18n.tryAgain))} onPress={this.onPressTryAgain} style={buttonStyle}/> <TouchableButton text={i18n.headerExclude} onPress={this.onPressExclude} style={[buttonStyle, { backgroundColor: brandDanger, }]}/> <TouchableButton text={i18n.exit} onPress={this.onPressExit} style={buttonStyle}/> </View> </ThemedScrollView> ); } getStyles(): Object { const { appLayout } = this.props; const { height, width } = appLayout; const isPortrait = height > width; const deviceWidth = isPortrait ? width : height; const { paddingFactor, shadow, brandDanger, fontSizeFactorFour, fontSizeFactorNine, } = Theme.Core; const padding = deviceWidth * paddingFactor; const innerPadding = 5 + padding; const infoTextFontSize = deviceWidth * fontSizeFactorFour; return { padding, brandDanger, container: { flex: 1, margin: padding, }, infoContainer: { flex: 1, flexDirection: 'row', padding: innerPadding, ...shadow, alignItems: 'center', justifyContent: 'space-between', borderRadius: 2, marginBottom: padding / 2, }, statusIconStyle: { fontSize: deviceWidth * fontSizeFactorNine, }, infoTextStyle: { flex: 1, fontSize: infoTextFontSize, flexWrap: 'wrap', marginLeft: innerPadding, }, buttonStyle: { marginTop: padding, }, }; } } export default (NoDeviceFound: Object);
telldus/telldus-live-mobile-v3
js/App/Components/Device/AddDevice/NoDeviceFound.js
JavaScript
gpl-3.0
4,116
function register() { if($("#span1").text()=="" && $("#span2").text()=="" && $("#span3").text()=="" && $("#span4").text()=="" ){ if($("#cname").val()=="" || $("#cpwd").val()=="" || $("#checkpwd").val()=="" || $("#email").val()=="" ){ alert("请按要求填写!"); return false; } alert("注册成功,请前往邮箱激活后登录!"); return true; } alert("请按要求填写!"); return false; } function checkcname(){ if($("#cname").val().trim()==""){ $("#span1").html("请输入用户名!"); return; } $("#span1").html(""); $.post("user/checkcname",{"cname":$("#cname").val().trim()},function(data){ if(data!=null && data!=""){ $("#span1").html("用户名已存在!"); }else{ $("#span1").html('<img src="images/1.gif" >'); } } ); } function checkEmail()//检查邮箱名是否正确 { var emailValue = $("#email").val(); if (!isEmail(emailValue)) { $("#span4").html("邮箱格式错误!"); return; } $("#span4").html('<img src="images/1.gif" >'); } function Pwd(){ var pwd=$("#cpwd").val(); if (!isPwd(pwd)){ $("#span2").html("格式不正确!"); return; } $("#span2").html('<img src="images/1.gif" >'); } function checkPwd(){ if($("#cpwd").val().trim()==""){ $("#span3").html("请先输入密码!"); return; }else if($("#span2").text()!=""){ $("#span3").html("请先输入密码!"); return; }else if($("#cpwd").val()!=$("#checkpwd").val()){ $("#span3").html("输入不一致!"); return; }else{ $("#span3").html('<img src="images/1.gif" >'); return; } } //匹配邮箱的正则表达式 function isEmail(str) { var reg = /^(\w)+(\.\w+)*@(\w)+((\.\w+)+)$/; return reg.test(str); } //匹配密码格式的正则表达式 function isPwd(str) { var reg = /^(\w){6,20}$/; return reg.test(str); } $(function(){ $("#cname").val(""); $("#cpwd").val(""); $("#checkpwd").val(""); $("#email").val(""); });
mavenBell1994/DrivingTest
DrivingTest/src/main/webapp/js/formregister.js
JavaScript
gpl-3.0
2,139
"use strict"; const dataFrame = require('./data-frame.js'); const KeyedData = require('./data-pool.js').KeyedData; const sqlite3 = require('sqlite3'); const jsonfile = require('jsonfile'); const config = jsonfile.readFileSync('../resources/fellajn.conf'); $.fn.serializeObject = function() { var o = {}; var a = this.serializeArray(); $.each(a, function() { if (o[this.name] !== undefined) { if (!o[this.name].push) { o[this.name] = [o[this.name]]; } o[this.name].push(this.value || ''); } else { o[this.name] = this.value || ''; } }); return o; }; var assignValue = function(n, v){ var field = $('form input[name="' + n + '"]'); if (field.attr('type')=='text'){ field.val(v); } else if (field.attr('type')=='checkbox') { field.prop('checked',v); } } var assignSettings = function(list, prefix){ if (typeof prefix != 'undefined'){ prefix += '.'; } else { prefix = ''; } for (var item in list) { if ((typeof list[item]=='string') || (typeof list[item]=='boolean')){ assignValue(prefix+item,list[item]); } else if (typeof list[item]=='object'){ var n1 = item; assignSettings(list[n1],prefix+n1); } } } $(document).ready(function() { document.dataPool = [] document.app = {} var filesList = $('#list-files'); var datasource = new KeyedData(); const db = new sqlite3.Database(config.db.location); db.each("select id as file_id, name_group, name, location from need_process order by name" , (err, row) => { if (err) throw err; row.file_id = row.file_id.toString(); datasource.push(row, d => d.file_id) } , (err, num) => { if (err) throw err; datasource.allKeys(key => { var item = datasource.get(key); var html = '<button id="btn-listitem" type="button" class="list-group-item" ' + 'onClick="btnListItem_onClick(' + item["file_id"] + ')">' + item["name"] + '</button>'; filesList.append(html); }); document.app["list-files"] = { "data": datasource, "el": filesList } }); window.btnListItem_onClick = btnListItem_onClick; }); $("#mgr-form").submit(function (e) { var data = $('form').serializeObject(); var genres = [] for (var item of data["genres"].split(/\r?\n/)) { genres.push(item.trim()) } var casts = [], cast_jas = [] for (var item of data["casts"].split(/\r?\n/)) { casts.push(item.trim()) } for (var item of data["casts_ja"].split(/\r?\n/)) { cast_jas.push(item.trim()) } var formalData = dataFrame.crawlData() .withId(data["movie-code"]) .withTitle(data["title"]) .withTitleJa(data["title-ja"]) .withDirector(data["director"]) .withDirectorJa(data["director-ja"]) .withMaker(data["maker"]) .withMakerJa(data["maker-ja"]) .withLabel(data["label"]) .withLabelJa(data["label-ja"]) .withReleaseDate(data["release-date"]) .withLength(data["length"]) .withGenres(genres) .withCasts(casts) .withCastsJa(cast_jas) .getData(); document.dataPool.push(formalData); alert('Saved ok'); return false; }); $('#btn-submit').on('click', function (e) { if (document.dataPool.length > 0) { jsonfile.writeFileSync( config.data.location, { "d" : document.dataPool }, { spaces: 2 } ); } }); function btnListItem_onClick (key) { var filesList= document.app["list-files"]; var datasrc = filesList.data; var data = datasrc.get(key); console.log(data); assignSettings(data); }
mksimpler/fellajn
fellajn.app/appcode/index.js
JavaScript
gpl-3.0
3,937
/* Copyright 2011 OCAD University Copyright 2011 Lucendo Development Ltd. Licensed under the Educational Community License (ECL), Version 2.0 or the New BSD license. You may not use this file except in compliance with one these Licenses. You may obtain a copy of the ECL 2.0 License and BSD License at https://github.com/fluid-project/infusion/raw/master/Infusion-LICENSE.txt */ // Declare dependencies /*global fluid_1_4:true, jQuery, window*/ // JSLint options /*jslint white: true, funcinvoke: true, undef: true, newcap: true, nomen: true, regexp: true, bitwise: true, browser: true, forin: true, maxerr: 100, indent: 4 */ var fluid_1_4 = fluid_1_4 || {}; (function ($, fluid) { /*************************************** * fluid.uiOptions.fatPanelEventBinder * ***************************************/ fluid.defaults("fluid.uiOptions.fatPanelEventBinder", { gradeNames: ["fluid.eventedComponent", "autoInit"], finalInitFunction: "fluid.uiOptions.fatPanelEventBinder.finalInit", components: { uiOptionsLoader: { type: "fluid.uiOptions.loader" }, slidingPanel: { type: "fluid.slidingPanel" } } }); fluid.defaults("fluid.uiOptions.fatPanelEventBinder.binder", { gradeNames: ["fluid.eventedComponent", "autoInit"] }); fluid.registerNamespace("fluid.dom"); fluid.dom.getDocumentHeight = function (dokkument) { var body = $("body", dokkument)[0]; return body.offsetHeight; }; fluid.uiOptions.fatPanelEventBinder.updateView = function (uiOptions) { uiOptions.uiEnhancer.updateFromSettingsStore(); uiOptions.events.onSignificantDOMChange.fire(); }; fluid.uiOptions.fatPanelEventBinder.bindLateEvents = function (uiOptions, eventBinder, fatPanel) { eventBinder.uiOptions = uiOptions; uiOptions.events.modelChanged.addListener(function (model) { eventBinder.uiEnhancer.updateModel(model.selections); uiOptions.save(); }); uiOptions.events.onReset.addListener(function (uiOptions) { fluid.uiOptions.fatPanelEventBinder.updateView(uiOptions); }); uiOptions.events.onSignificantDOMChange.addListener(function () { var dokkument = uiOptions.container[0].ownerDocument; var height = fluid.dom.getDocumentHeight(dokkument); var iframe = fatPanel.markupRenderer.iframe; var attrs = {height: height + 15}; // TODO: Configurable padding here iframe.animate(attrs, 400); }); fatPanel.slidingPanel.events.afterPanelHide.addListener(function () { fatPanel.markupRenderer.iframe.height(0); }); }; fluid.uiOptions.fatPanelEventBinder.finalInit = function (that) { //TODO: This binding should be done declaratively - needs ginger world in order to bind onto slidingPanel // which is a child of this component - and also uiOptionsLoader which is another child that.slidingPanel.events.afterPanelShow.addListener(function () { fluid.uiOptions.fatPanelEventBinder.updateView(that.uiOptions); }); }; // show immediately, animation will be done after size calculation above fluid.uiOptions.fatPanelEventBinder.showPanel = function (panel, callback) { panel.show(); // A bizarre race condition has emerged under FF where the iframe held within the panel does not // react synchronously to being shown setTimeout(callback, 1); }; /*************************************************************** * Fat Panel UI Options Top Level Driver (out in normal world) * ***************************************************************/ fluid.defaults("fluid.uiOptions.fatPanel", { gradeNames: ["fluid.viewComponent"], selectors: { iframe: ".flc-uiOptions-iframe" }, relativePrefix: "./", // Prefix for "other world" component templates relative to the iframe URL components: { slidingPanel: { type: "fluid.slidingPanel", container: "{fatPanel}.container", options: { invokers: { operateShow: { funcName: "fluid.uiOptions.fatPanelEventBinder.showPanel" } } }, createOnEvent: "afterRender" }, markupRenderer: { type: "fluid.uiOptions.renderIframe", container: "{fatPanel}.dom.iframe", options: { markupProps: { src: "%prefix/FatPanelUIOptionsFrame.html" }, events: { afterRender: "{fatPanel}.events.afterRender" } } }, uiEnhancer: "{uiEnhancer}", eventBinder: { type: "fluid.uiOptions.fatPanelEventBinder", options: { components: { uiEnhancer: "{fatPanel}.uiEnhancer", uiOptionsLoader: "{fatPanel}.bridge.uiOptionsLoader", slidingPanel: "{fatPanel}.slidingPanel", binder: { type: "fluid.uiOptions.fatPanelEventBinder.binder", priority: "last", options: { events: { onUIOptionsComponentReady: { event: "{uiOptionsLoader}.events.onUIOptionsComponentReady", args: ["{arguments}.0", "{fluid.uiOptions.fatPanelEventBinder}", "{fatPanel}"] } }, listeners: { // This literal specification works around FLUID-4337 // The actual behaviour should really be handled by FLUID-4335 onUIOptionsComponentReady: fluid.uiOptions.fatPanelEventBinder.bindLateEvents } } } } }, createOnEvent: "afterRender", priority: "last" }, bridge: { type: "fluid.uiOptions.bridge", createOnEvent: "afterRender", priority: "first", options: { components: { uiEnhancer: "{fatPanel}.uiEnhancer", markupRenderer: "{fatPanel}.markupRenderer" } } } }, uiOptionsTransform: { transformer: "fluid.uiOptions.mapOptions", config: { "*.slidingPanel": "slidingPanel", "*.markupRenderer": "markupRenderer", "*.markupRenderer.options.prefix": "prefix", "*.eventBinder": "eventBinder", "selectors.iframe": "iframe", "*.bridge.options.templateLoader": "templateLoader", "*.bridge.options.prefix": "relativePrefix", "*.bridge.options.uiOptionsLoader": "uiOptionsLoader", "*.bridge.options.uiOptions": "uiOptions", "*.bridge.options.textControls": "textControls", "*.bridge.options.layoutControls": "layoutControls", "*.bridge.options.linksControls": "linksControls", "*.bridge.options.uiEnhancer": "uiEnhancer" } }, events: { afterRender: null } }); /******************************** * fluid.uiOptions.renderIframe * ********************************/ fluid.defaults("fluid.uiOptions.renderIframe", { gradeNames: ["fluid.viewComponent", "autoInit"], finalInitFunction: "fluid.uiOptions.renderIframe.finalInit", events: { afterRender: null }, styles: { containerFlex: "fl-container-flex", container: "fl-uiOptions-fatPanel-iframe" }, prefix: "./", markupProps: { // This overflow specification fixes anomalous x overflow on FF, but may not on IE style: "overflow-x:hidden; overflow-y:auto;", "class": "flc-iframe", src: "%prefix/uiOptionsIframe.html" } }); fluid.uiOptions.renderIframe.finalInit = function (that) { var styles = that.options.styles; // TODO: get earlier access to templateLoader, that.options.markupProps.src = fluid.stringTemplate(that.options.markupProps.src, {"prefix/": that.options.prefix}); that.iframeSrc = that.options.markupProps.src; //create iframe and append to container that.iframe = $("<iframe/>"); that.iframe.load(function () { that.events.afterRender.fire(); }); that.iframe.attr(that.options.markupProps); that.iframe.addClass(styles.containerFlex); that.iframe.addClass(styles.container); that.iframe.appendTo(that.container); }; /*********************************** * fluid.uiOptions.bridge * ***********************************/ fluid.defaults("fluid.uiOptions.bridge", { gradeNames: ["fluid.littleComponent", "autoInit"], finalInitFunction: "fluid.uiOptions.bridge.finalInit", iframe: null }); // TODO: This function is only necessary through lack of listener boiling power - it should // be possible to directly relay one event firing to another, FLUID-4398 fluid.uiOptions.tabSelectRelay = function (uiOptions) { uiOptions.events.onSignificantDOMChange.fire(); }; fluid.defaults("fluid.uiOptions.FatPanelOtherWorldLoader", { gradeNames: ["fluid.uiOptions.inline", "autoInit"], // TODO: This material is not really transformation, but would be better expressed by // FLUID-4392 additive demands blocks derivedDefaults: { uiOptions: { options: { events: { onSignificantDOMChange: null }, components: { uiEnhancer: { type: "fluid.uiEnhancer", container: "body", priority: "first", options: { tocTemplate: "../../tableOfContents/html/TableOfContents.html" } }, settingsStore: "{uiEnhancer}.settingsStore", preview: { type: "fluid.emptySubcomponent" }, tabs: { type: "fluid.tabs", container: "body", createOnEvent: "onUIOptionsComponentReady", options: { events: { // TODO: this mess required through lack of FLUID-4398 boiledTabShow: { event: "tabsshow", args: ["{uiOptions}"] } }, listeners: { // FLUID-4337 bug again boiledTabShow: fluid.uiOptions.tabSelectRelay } } } } } } }, uiOptionsTransform: { config: { // For FLUID-4409 "!*.uiOptionsLoader.*.uiOptions.*.uiEnhancer.options": "uiEnhancer.options" } } }); fluid.uiOptions.bridge.finalInit = function (that) { var iframe = that.markupRenderer.iframe; var origPrefix = that.markupRenderer.options.prefix; var iframeDoc = iframe.contents(); var iframeWin = iframe[0].contentWindow; var innerFluid = iframeWin.fluid; var container = $("body", iframeDoc); var outerLocation = window.location.href; var iframeLocation = iframeWin.location.href; var relativePrefix = fluid.url.computeRelativePrefix(outerLocation, iframeLocation, origPrefix); that.options.relativePrefix = relativePrefix; // TODO: more flexible defaulting here var overallOptions = {}; overallOptions.container = container; var bridgeMapping = fluid.defaults("fluid.uiOptions.fatPanel").uiOptionsTransform.config; var swappedBridgeMapping = {}; // Swap the mapping for easier extraction on FatPanelOtherWorldLoader options fluid.each(bridgeMapping, function (value, key) { swappedBridgeMapping[value] = key; }); // Extracts the mappings that only belong to FatPanelOtherWorldLoader var bridgeSymbol = "*.bridge.options"; fluid.each(swappedBridgeMapping, function (value, key) { if (value.indexOf(bridgeSymbol) === 0 && that.options[key]) { // find out the option name used in the other world var keyInOtherWorld = value.substring(bridgeSymbol.length + 1); fluid.set(overallOptions, keyInOtherWorld, that.options[key]); } }); var defaults = fluid.defaults("fluid.uiOptions.FatPanelOtherWorldLoader"); // Hack for FLUID-4409: Capabilities of our ad hoc "mapOptions" function have been exceeded - put weak priority instance of outer // merged options into the inner world fluid.set(overallOptions, "uiEnhancer.options", that.uiEnhancer.options.originalUserOptions); var mappedOptions = fluid.uiOptions.mapOptions(overallOptions, defaults.uiOptionsTransform.config, defaults.mergePolicy, fluid.copy(defaults.derivedDefaults)); var component = innerFluid.invokeGlobalFunction("fluid.uiOptions.FatPanelOtherWorldLoader", [container, mappedOptions]); that.uiOptionsLoader = component.uiOptionsLoader; }; /************************ * Fat Panel UI Options * ************************/ fluid.uiOptions.fatPanel = function (container, options) { var defaults = fluid.defaults("fluid.uiOptions.fatPanel"); var config = defaults.uiOptionsTransform.config; var mappedOptions = fluid.uiOptions.mapOptions(options, config, defaults.mergePolicy); var that = fluid.initView("fluid.uiOptions.fatPanel", container, mappedOptions); fluid.initDependents(that); return that; }; })(jQuery, fluid_1_4);
gregrgay/booking
Web/scripts/infusion/components/uiOptions/js/FatPanelUIOptions.js
JavaScript
gpl-3.0
15,480
'use strict'; const _ = require('lodash'); const path = require('path'); const config = require('../../config'); const formatAddress = require('../common/behaviours/format-address'); const getPageCustomBackLink = require('./behaviours/custom-back-links'); const existingAuthorityController = require('../common/controllers/existing-authority-documents-add-another'); const existingAuthorityBehaviour = require('../common/behaviours/existing-authority-documents-add'); const supportingDocumentsBehaviour = require('../common/behaviours/supporting-documents-add'); const resetUploadedDocuments = require('../common/behaviours/reset-on-change'); const ammunition = req => _.includes(req.sessionModel.get('weapons-ammunition'), 'ammunition'); const weapons = req => _.includes(req.sessionModel.get('weapons-ammunition'), 'weapons'); const storedOnPremises = req => req.sessionModel.get('stored-on-premises') === 'true'; const Submission = require('../common/behaviours/casework-submission'); const submission = Submission({ prepare: require('./models/submission') }); const pdf = require('../common/behaviours/pdf-upload'); const Emailer = require('../common/behaviours/emailer'); const emailer = Emailer({ template: path.resolve(__dirname, './emails/confirm.html'), recipient: 'contact-email', subject: data => `Ref: ${data.caseid} - Section 5 firearms licence application`, type: 'Section 5 authority', nameKey: data => { const contact = data['contact-holder']; return contact === 'other' ? 'someone-else-name' : `${contact}-authority-holders-name`; } }); module.exports = { name: 'new-dealer', baseUrl: '/s5', params: '/:action?/:id?', steps: { '/privacy': { template: 'privacy', next: '/before-you-start' }, '/before-you-start': { next: '/activity' }, '/activity': { behaviours: resetUploadedDocuments({ currentField: 'activity', fieldsForRemoval: [ 'existing-authority-documents', 'supporting-documents' ] }), fields: [ 'activity' ], next: '/supporting-documents', forks: [{ target: '/existing-authority', condition: req => { return _.includes(['vary', 'renew'], req.sessionModel.get('activity')); } }] }, '/existing-authority': { behaviours: getPageCustomBackLink('existing-authority'), controller: require('../common/controllers/existing-authority-documents'), fields: [ 'existing-authority-upload', 'existing-authority-description' ], continueOnEdit: true, next: '/existing-authority-add-another' }, '/existing-authority-add-another': { controller: existingAuthorityController, behaviours: [existingAuthorityBehaviour, getPageCustomBackLink('existing-authority-add-another')], fields: [ 'existing-authority-add-another' ], forks: [{ isLoop: true, target: '/existing-authority', condition: { field: 'existing-authority-add-another', value: 'yes' } }], continueOnEdit: true, next: '/supporting-documents' }, '/supporting-documents': { behaviours: getPageCustomBackLink('supporting-documents'), controller: require('../common/controllers/supporting-documents'), fields: [ 'supporting-document-upload', 'supporting-document-description' ], continueOnEdit: true, next: '/supporting-documents-add-another' }, '/supporting-documents-add-another': { controller: require('../common/controllers/supporting-documents-add-another'), behaviours: [supportingDocumentsBehaviour, getPageCustomBackLink('supporting-documents-add-another')], fields: [ 'supporting-document-add-another' ], forks: [{ target: '/supporting-documents', condition: { field: 'supporting-document-add-another', value: 'yes' } }], continueOnEdit: true, next: '/company-name' }, '/company-name': { fields: [ 'organisation', 'company-name', 'company-house-number', 'sole-trader-name', 'shooting-club-name', 'charity-name', 'charity-number', 'museum-name', 'other-name' ], next: '/handle', locals: { section: 'business-details' } }, '/handle': { fields: [ 'weapons-ammunition' ], next: '/obtain', locals: { renew: true, section: 'authority-details', step: 'handle' } }, '/obtain': { fields: [ 'obtain', 'other-means-details' ], next: '/import', locals: { renew: true, section: 'authority-details', step: 'obtain' } }, '/import': { fields: [ 'import', 'import-country' ], next: '/storage', locals: { renew: true, section: 'authority-details', step: 'import' } }, '/storage': { fields: [ 'stored-on-premises', 'no-storage-details' ], next: '/usage', forks: [{ target: '/storage-address', condition(req) { return storedOnPremises(req); } }], locals: { renew: true, step: 'storage' } }, '/storage-address': { template: 'storage-address', behaviours: formatAddress('storage', 'storage-address'), fields: [ 'storage-building', 'storage-street', 'storage-townOrCity', 'storage-postcodeOrZIPCode' ], locals: { section: 'storage-details', renew: true, step: 'storage-address'}, fieldSettings: { className: 'address' }, next: '/storage-add-another-address', backLinks: '/storage', continueOnEdit: true }, '/storage-add-another-address': { template: 'storage-add-another-address', controller: require('./controllers/storage-address-loop'), next: '/usage', returnTo: '/storage-address', aggregateTo: 'storageAddresses', aggregateFields: [ 'storage-building', 'storage-street', 'storage-townOrCity', 'storage-postcodeOrZIPCode', 'storage-address' ], fieldSettings: { legend: { className: 'visuallyhidden' } }, locals: { section: 'storage-details', renew: true, step: 'storage-address'} }, '/usage': { fields: [ 'usage', 'other-details' ], next: '/ammunition', forks: [{ target: '/weapons', condition: weapons }], locals: { renew: true, section: 'authority-details', step: 'usage' } }, '/weapons': { template: 'weapons-ammunition.html', fields: [ 'weapons-types', 'weapons-unspecified-details', 'fully-automatic-quantity', 'self-loading-quantity', 'short-pistols-quantity', 'short-self-loading-quantity', 'large-revolvers-quantity', 'rocket-launchers-quantity', 'air-rifles-quantity', 'fire-noxious-substance-quantity', 'disguised-firearms-quantity', 'military-use-rockets-quantity', 'projecting-launchers-quantity' ], next: '/authority-holders', forks: [{ target: '/ammunition', condition: ammunition }], locals: { weaponsOrAmmunition: 'weapons' } }, '/ammunition': { template: 'weapons-ammunition.html', fields: [ 'ammunition-types', 'ammunition-unspecified-details', 'explosive-cartridges-quantity', 'incendiary-missile-quantity', 'armour-piercing-quantity', 'expanding-missile-quantity', 'missiles-for-above-quantity' ], next: '/authority-holders', locals: { weaponsOrAmmunition: 'ammunition' } }, '/authority-holders': { fields: [ 'authority-holders' ], next: '/first-authority-holders-name', locals: { renew: true, step: 'authority-holders' } }, '/first-authority-holders-name': { fields: [ 'first-authority-holders-name' ], next: '/first-authority-holders-birth', locals: { section: 'first-authority-holder' } }, '/first-authority-holders-birth': { fields: [ 'first-authority-dob', 'first-authority-town-birth', 'first-authority-country-birth' ], next: '/first-authority-holders-nationality', locals: { key: 'first-authority-country-birth', section: 'first-authority-holder' } }, '/first-authority-holders-nationality': { template: 'authority-holders-nationality.html', controller: require('./controllers/authority-holders-nationality'), fields: [ 'first-authority-holders-nationality', 'first-authority-holders-nationality-multi', 'first-authority-holders-nationality-second', 'first-authority-holders-nationality-third' ], next: '/first-authority-holders-address', locals: { key: 'first-authority-holders-nationality', section: 'first-authority-holder' } }, '/first-authority-holders-address': { behaviours: formatAddress('first-authority-holders', 'first-authority-holders-address-manual'), fields: [ 'first-authority-holders-building', 'first-authority-holders-street', 'first-authority-holders-townOrCity', 'first-authority-holders-postcodeOrZIPCode' ], locals: { step: '/first-authority-holders-address', field: 'first-authority-holders-address-manual', useOriginalValue: true, section: 'first-authority-holder' }, fieldSettings: { className: 'address' }, next: '/contact', forks: [{ target: '/second-authority-holders-name', condition(req) { return req.sessionModel.get('authority-holders') === 'two'; } }] }, '/second-authority-holders-name': { fields: [ 'second-authority-holders-name' ], next: '/second-authority-holders-birth', locals: { section: 'second-authority-holder' } }, '/second-authority-holders-birth': { fields: [ 'second-authority-dob', 'second-authority-town-birth', 'second-authority-country-birth' ], next: '/second-authority-holders-nationality', locals: { key: 'second-authority-country-birth', section: 'second-authority-holder' } }, '/second-authority-holders-nationality': { template: 'authority-holders-nationality.html', controller: require('./controllers/authority-holders-nationality'), fields: [ 'second-authority-holders-nationality', 'second-authority-holders-nationality-multi', 'second-authority-holders-nationality-second', 'second-authority-holders-nationality-third' ], next: '/second-authority-holders-address', locals: { key: 'second-authority-holders-nationality', section: 'second-authority-holder' } }, '/second-authority-holders-address': { behaviours: formatAddress('second-authority-holders', 'second-authority-holders-address-manual'), fields: [ 'second-authority-holders-building', 'second-authority-holders-street', 'second-authority-holders-townOrCity', 'second-authority-holders-postcodeOrZIPCode' ], locals: { field: 'second-authority-holders-address-manual', section: 'second-authority-holder' }, fieldSettings: { className: 'address' }, next: '/contact' }, '/contact': { fields: [ 'contact-holder', 'someone-else-name' ], controller: require('./controllers/contact'), next: '/contact-details', locals: { renew: true, section: 'contacts-details', step: 'contact' }, continueOnEdit: true }, '/contact-details': { fields: [ 'contact-email', 'contact-phone' ], next: '/authority-holder-contact-postcode', forks: [{ target: '/contact-address', condition(req) { return req.sessionModel.get('contact-holder') === 'other'; } }], locals: { section: 'contacts-details' }, continueOnEdit: true }, '/authority-holder-contact-postcode': { fields: [ 'use-different-address' ], next: '/authority-holder-contact-address', forks: [{ target: '/invoice-contact-details', condition: { field: 'use-different-address', value: 'false' } }, { target: '/authority-holder-contact-address', condition(req) { const addresses = req.sessionModel.get('authority-holder-contact-addresses'); return addresses && addresses.length; } }], locals: { field: 'authority-holder-contact', section: 'contacts-details' } }, '/authority-holder-contact-address': { behaviours: formatAddress('authority-holder-contact', 'authority-holder-contact-address-manual'), template: 'address.html', fields: [ 'authority-holder-contact-building', 'authority-holder-contact-street', 'authority-holder-contact-townOrCity', 'authority-holder-contact-postcodeOrZIPCode' ], locals: { section: 'contacts-details', field: 'authority-holder-contact-address-manual' }, fieldSettings: { className: 'address' }, next: '/invoice-contact-details' }, '/contact-address': { behaviours: formatAddress('contact', 'contact-address-manual'), fields: ['contact-building', 'contact-street', 'contact-townOrCity', 'contact-postcodeOrZIPCode'], fieldSettings: { className: 'address' }, next: '/invoice-contact-details' }, '/invoice-contact-details': { fields: ['invoice-contact-name', 'invoice-contact-email', 'invoice-contact-phone'], locals: { section: 'invoice-details' }, next: '/invoice-address-input' }, '/invoice-address-input': { behaviours: formatAddress('invoice', 'invoice-address'), fields: ['invoice-building', 'invoice-street', 'invoice-townOrCity', 'invoice-postcodeOrZIPCode'], locals: { section: 'invoice-details' }, fieldSettings: { className: 'address' }, next: '/purchase-order' }, '/purchase-order': { fields: [ 'purchase-order', 'purchase-order-number' ], next: '/confirm', locals: { renew: true, section: 'invoice-details', step: 'purchase-order' } }, '/confirm': { controller: require('./controllers/confirm'), fieldsConfig: require('./fields'), behaviours: [pdf], next: '/declaration' }, '/declaration': { template: 'declaration', behaviours: ['complete', submission, emailer], next: '/confirmation' }, '/confirmation': { locals: { 'survey-url': config.survey.urls['new-dealer'] }, backLink: false } } };
UKHomeOffice/firearms
apps/new-dealer/index.js
JavaScript
gpl-3.0
15,500
Ext.define('Onc.controller.DashboardController', { extend: 'Ext.app.Controller', stores: ['ComputesStore', 'PhysicalComputesStore', 'GaugesChartComputesStore', 'TasksPortletStore', 'VmGridTypeStore'], });
opennode/opennode-console
app/controller/DashboardController.js
JavaScript
gpl-3.0
214
import ColorMap from '../src/ColorMap.js' import Model from '../src/Model.js' import { util } from '../agentscript/agentscript.esm.js' util.toWindow({ ColorMap, Model, util }) class LinksModel extends Model { setup() { this.turtles.own('speed') this.turtles.setDefault('atEdge', 'bounce') // this.turtles.setDefault('z', 0.1) this.patchesCmap = ColorMap.grayColorMap(200, 255) // light gray map this.patches.ask(p => { p.color = this.patchesCmap.randomColor() }) this.turtles.create(1000, t => { t.size = util.randomFloat2(0.2, 0.5) // + Math.random() t.speed = util.randomFloat2(0.01, 0.05) // 0.5 + Math.random() }) this.turtles.ask(turtle => { const other = this.turtles.otherOneOf(turtle) if (turtle.links.length === 0 || other.links.length === 0) { this.links.create(turtle, other, link => { link.color = this.randomColor() }) } }) } step() { // REMIND: Three mouse picking this.turtles.ask(t => { t.theta += util.randomCentered(0.1) t.forward(t.speed) }) } } const model = new LinksModel() model.setup() model.start() // Debugging console.log('patches:', model.patches.length) console.log('turtles:', model.turtles.length) console.log('links:', model.links.length) const { world, patches, turtles, links } = model util.toWindow({ world, patches, turtles, links, model })
backspaces/asx
models/links.js
JavaScript
gpl-3.0
1,552
define( "dojo/cldr/nls/nb/indian", //begin v1.x content { "field-quarter-short-relative+0": "dette kv.", "field-quarter-short-relative+1": "neste kv.", "field-tue-relative+-1": "forrige tirsdag", "field-year": "år", "field-wed-relative+0": "onsdag", "field-wed-relative+1": "neste onsdag", "field-minute": "minutt", "field-month-narrow-relative+-1": "forrige md.", "field-tue-narrow-relative+0": "denne ti.", "field-tue-narrow-relative+1": "neste ti.", "field-day-short-relative+-1": "i går", "field-thu-short-relative+0": "denne tor.", "dateTimeFormat-short": "{1} {0}", "field-day-relative+0": "i dag", "field-day-short-relative+-2": "i forgårs", "field-thu-short-relative+1": "neste tor.", "field-day-relative+1": "i morgen", "field-week-narrow-relative+0": "denne uken", "field-day-relative+2": "i overmorgen", "field-week-narrow-relative+1": "neste uke", "field-wed-narrow-relative+-1": "sist on.", "field-year-narrow": "år", "field-era-short": "tidsalder", "field-year-narrow-relative+0": "i år", "field-tue-relative+0": "tirsdag", "field-year-narrow-relative+1": "neste år", "field-tue-relative+1": "neste tirsdag", "field-weekdayOfMonth": "ukedag i måneden", "field-second-short": "sek", "dateFormatItem-yyyyMM": "MM.y G", "dateFormatItem-MMMd": "d. MMM", "field-weekdayOfMonth-narrow": "uked. i md.", "field-week-relative+0": "denne uken", "field-month-relative+0": "denne måneden", "field-week-relative+1": "neste uke", "field-month-relative+1": "neste måned", "field-sun-narrow-relative+0": "denne sø.", "field-mon-short-relative+0": "denne man.", "field-sun-narrow-relative+1": "neste sø.", "field-mon-short-relative+1": "neste man.", "field-second-relative+0": "nå", "dateFormatItem-yyyyQQQ": "QQQ y G", "months-standAlone-narrow": [ "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12" ], "eraNames": [ "saka" ], "field-weekOfMonth": "uke i måneden", "field-month-short": "mnd.", "dateFormatItem-GyMMMEd": "E d. MMM y G", "dateFormatItem-yyyyMd": "d.M.y G", "field-day": "dag", "field-dayOfYear-short": "dag i året", "field-year-relative+-1": "i fjor", "field-sat-short-relative+-1": "sist lør.", "field-hour-relative+0": "denne timen", "dateFormatItem-yyyyMEd": "E d.M.y G", "field-second-short-relative+0": "nå", "field-wed-relative+-1": "forrige onsdag", "dateTimeFormat-medium": "{1} {0}", "field-sat-narrow-relative+-1": "sist lø.", "field-second": "sekund", "dateFormat-long": "d. MMMM y G", "dateFormatItem-GyMMMd": "d. MMM y G", "field-quarter": "kvartal", "field-week-short": "uke", "field-day-narrow-relative+0": "i dag", "field-day-narrow-relative+1": "i morgen", "field-day-narrow-relative+2": "+2 d.", "field-tue-short-relative+0": "denne tir.", "field-tue-short-relative+1": "neste tir.", "field-month-short-relative+-1": "forrige md.", "field-mon-relative+-1": "forrige mandag", "dateFormatItem-GyMMM": "MMM y G", "field-month": "måned", "field-day-narrow": "d.", "dateFormatItem-MMM": "LLL", "field-minute-short": "min", "field-dayperiod": "a.m./p.m.", "field-sat-short-relative+0": "denne lør.", "field-sat-short-relative+1": "neste lør.", "dateFormat-medium": "d. MMM y G", "dateFormatItem-yyyyMMMM": "MMMM y G", "eraAbbr": [ "saka" ], "dateFormatItem-yyyyM": "M.y G", "field-second-narrow": "s", "field-mon-relative+0": "mandag", "field-mon-relative+1": "neste mandag", "field-day-narrow-relative+-1": "i går", "field-year-short": "år", "field-day-narrow-relative+-2": "-2 d.", "months-format-narrow": [ "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12" ], "field-quarter-relative+-1": "forrige kvartal", "dateFormatItem-yyyyMMMd": "d. MMM y G", "field-dayperiod-narrow": "am/pm", "field-week-narrow-relative+-1": "forrige uke", "field-dayOfYear": "dag i året", "field-sat-relative+-1": "forrige lørdag", "dateTimeFormat-long": "{1} {0}", "dateFormatItem-Md": "d.M.", "field-hour": "time", "months-format-wide": [ "chaitra", "vaisakha", "jyaistha", "asadha", "sravana", "bhadra", "asvina", "kartika", "agrahayana", "pausa", "magha", "phalguna" ], "dateFormat-full": "EEEE d. MMMM y G", "field-month-relative+-1": "forrige måned", "field-quarter-short": "kv.", "field-sat-narrow-relative+0": "denne lø.", "field-fri-relative+0": "fredag", "field-sat-narrow-relative+1": "neste lø.", "field-fri-relative+1": "neste fredag", "field-month-narrow-relative+0": "denne md.", "field-month-narrow-relative+1": "neste md.", "field-sun-short-relative+0": "denne søn.", "field-sun-short-relative+1": "neste søn.", "field-week-relative+-1": "forrige uke", "field-quarter-short-relative+-1": "forrige kv.", "months-format-abbr": [ "chaitra", "vaisakha", "jyaistha", "asadha", "sravana", "bhadra", "asvina", "kartika", "agrahayana", "pausa", "magha", "phalguna" ], "field-quarter-relative+0": "dette kvartalet", "field-minute-relative+0": "dette minuttet", "field-quarter-relative+1": "neste kvartal", "field-wed-short-relative+-1": "sist ons.", "dateFormat-short": "d.M.y G", "field-year-narrow-relative+-1": "i fjor", "field-thu-short-relative+-1": "sist tor.", "dateFormatItem-yyyyMMMEd": "E d. MMM y G", "field-mon-narrow-relative+-1": "sist ma.", "dateFormatItem-MMMMd": "d. MMMM", "field-thu-narrow-relative+-1": "sist to.", "dateFormatItem-E": "ccc", "field-weekOfMonth-short": "uke i mnd.", "field-tue-narrow-relative+-1": "sist ti.", "dateFormatItem-yyyy": "y G", "dateFormatItem-M": "L.", "months-standAlone-wide": [ "chaitra", "vaisakha", "jyaistha", "asadha", "sravana", "bhadra", "asvina", "kartika", "agrahayana", "pausa", "magha", "phalguna" ], "field-wed-short-relative+0": "denne ons.", "field-wed-short-relative+1": "neste ons.", "field-sun-relative+-1": "forrige søndag", "dateTimeFormat-full": "{1} {0}", "field-second-narrow-relative+0": "nå", "dateFormatItem-d": "d.", "field-weekday": "ukedag", "field-day-short-relative+0": "i dag", "field-quarter-narrow-relative+0": "dette kv.", "field-day-short-relative+1": "i morgen", "field-sat-relative+0": "lørdag", "field-quarter-narrow-relative+1": "neste kv.", "field-day-short-relative+2": "i overmorgen", "field-sat-relative+1": "neste lørdag", "field-week-short-relative+0": "denne uken", "field-week-short-relative+1": "neste uke", "months-standAlone-abbr": [ "chaitra", "vaisakha", "jyaistha", "asadha", "sravana", "bhadra", "asvina", "kartika", "agrahayana", "pausa", "magha", "phalguna" ], "field-dayOfYear-narrow": "d. i året", "field-month-short-relative+0": "denne md.", "field-month-short-relative+1": "neste md.", "field-weekdayOfMonth-short": "uked. i mnd.", "dateFormatItem-MEd": "E d.M", "field-zone-narrow": "tidssone", "dateFormatItem-y": "y G", "field-thu-narrow-relative+0": "denne to.", "field-sun-narrow-relative+-1": "sist sø.", "field-mon-short-relative+-1": "sist man.", "field-thu-narrow-relative+1": "neste to.", "field-thu-relative+0": "torsdag", "field-thu-relative+1": "neste torsdag", "field-fri-short-relative+-1": "sist fre.", "field-thu-relative+-1": "forrige torsdag", "field-week": "uke", "dateFormatItem-Ed": "E d.", "field-wed-narrow-relative+0": "denne on.", "field-wed-narrow-relative+1": "neste on.", "field-quarter-narrow-relative+-1": "forrige kv.", "field-year-short-relative+0": "i år", "dateFormatItem-yyyyMMM": "MMM y G", "field-dayperiod-short": "am/pm", "field-year-short-relative+1": "neste år", "field-fri-short-relative+0": "denne fre.", "field-fri-short-relative+1": "neste fre.", "field-week-short-relative+-1": "forrige uke", "dateFormatItem-yyyyQQQQ": "QQQQ y G", "field-hour-short": "t", "field-zone-short": "tidssone", "field-month-narrow": "md.", "field-hour-narrow": "t", "field-fri-narrow-relative+-1": "sist fr.", "field-year-relative+0": "i år", "field-year-relative+1": "neste år", "field-era-narrow": "tidsalder", "field-fri-relative+-1": "forrige fredag", "eraNarrow": "saka", "field-tue-short-relative+-1": "sist tir.", "field-minute-narrow": "m", "field-mon-narrow-relative+0": "denne ma.", "field-mon-narrow-relative+1": "neste ma.", "field-year-short-relative+-1": "i fjor", "field-zone": "tidssone", "dateFormatItem-MMMEd": "E d. MMM", "field-weekOfMonth-narrow": "uke i md.", "field-weekday-narrow": "uked.", "field-quarter-narrow": "kv.", "field-sun-short-relative+-1": "sist søn.", "field-day-relative+-1": "i går", "field-day-relative+-2": "i forgårs", "field-weekday-short": "ukedag", "field-sun-relative+0": "søndag", "dateFormatItem-MMdd": "d.M.", "field-sun-relative+1": "neste søndag", "dateFormatItem-Gy": "y G", "field-day-short": "dag", "field-week-narrow": "u.", "field-era": "tidsalder", "field-fri-narrow-relative+0": "denne fr.", "field-fri-narrow-relative+1": "neste fr." } //end v1.x content );
ustegrew/ustegrew.github.io
courses/it001/lib/dojo/dojo/cldr/nls/nb/indian.js.uncompressed.js
JavaScript
gpl-3.0
8,997
import anime from 'animejs'; export function animeBatch({ targets, props, sharedProps }) { const properties = (props) ? Object.keys(props) : []; const animes = targets.map((target, targetIndex) => { const targetProperties = { targets: target }; properties.forEach((property) => { targetProperties[property] = props[property][targetIndex]; }); return anime({ ...targetProperties, ...sharedProps }); }); animes.play = function playAll() { animes.forEach(anim => anim.play()); }; return animes; } export function playBatch(...args) { args.forEach(item => item.play()); playBatch.add = function add(...anims) { playBatch(...anims); }; return playBatch; } export function getTransitionAnimation( onTransitionEnd = () => null, direction = 'normal', ) { const TransitionAnimation = { autoplay: false, direction, duration: 400, targets: '#root', easing: 'easeInSine', opacity: [0, 1], complete: onTransitionEnd, }; return anime(TransitionAnimation); }
soulchainer/simongamejs
src/utils/animation.js
JavaScript
gpl-3.0
1,034
angular.module('kunturApp') .controller('MainCtrl', function ($scope, $mdSidenav, $location, rolFactory, socketFactory) { $scope.toggle = function() { $mdSidenav('menu-general').toggle(); }; $scope.navigateTo = function(url, event) { $location.path(url); $mdSidenav('menu-general').close(); }; $scope.menu = [ { name: 'Home', icon: 'home', url: '/', permission: ["admin", "office", "coordinator", "student"] }, { name: 'Universidades', icon: 'account_balance', url: '/gestionUniversidades', permission: ['admin'] }, { name: 'Acuerdos', svg: 'images/agreement.svg', url: '/moduloConvenios', permission: ['admin'] }, { name: 'Postulaciones', icon: 'assignment', url: '/postulaciones', permission: ["admin", "office", "coordinator","student"] }, { name: 'Coordinadores', icon: 'local_library', url: '/coordinadores', permission: ["admin"] }, { name: 'Grupos', icon: 'group', url: '/grupos', permission: ["admin", "office", "coordinator", "student"] }, { name: 'Nuevo Usuario', icon: 'person_add', url: '/nuevoUsuario', permission: ["admin"] }, { name: 'Convocatorias', icon: 'event_note', url: '/convocatorias', permission: ["admin", "office", "coordinator", "student"] } ]; //var stringInArray = function(string, array){ // return array. //} // this.openMenu = function($mdOpenMenu, ev) { // originatorEv = ev; // $mdOpenMenu(ev); // }; $scope.rol= null; socketFactory.connect(); socket = socketFactory.getSocket(); $scope.closeSession = function(e){ // alert("cerrado"); socketFactory.closeSession(); }; socket.on('rol', function (message) { $scope.rol = message; }); });
org-kuntur/kuntur
app/scripts/controllers/main.js
JavaScript
gpl-3.0
1,911
document.addEventListener('polymer-ready', function() { setTimeout(function() { Array.prototype.forEach.call(document.querySelectorAll('paper-input[hidden]'), function(node) { node.removeAttribute('hidden'); }); }, 500); });
burnnat/midi-player
bower_components/paper-input/demo.html.0.js
JavaScript
gpl-3.0
278
function testAudio() { var bufferLoader; var filter; var audio; var source; var frequency = 40; var buffer; var gainNode; var volume = 1; var src = 'https://access-all-areas-assets.s3.amazonaws.com/uploads/production/2015/10/20/11/03/54/569/AAA_Rod_Onboarding_Stereo_32000_2.mp3'; window.AudioContext = window.AudioContext || window.webkitAudioContext || window.msAudioContext; if (AudioContext) { var context = new AudioContext(); } console.log('AudioContext', AudioContext); if (!AudioContext) return false; var xhr = new XMLHttpRequest(); xhr.open('GET', src, true); xhr.responseType = 'arraybuffer'; xhr.onload = function(e) { console.log('url loaded', this.response); context.decodeAudioData(this.response, function(loadedBuffer){ console.log('decodeAudioData', loadedBuffer); if (source && !$("html").is(".safari")) { if (!source.stop){ source.stop = source.noteOff; } source.stop(0); } buffer = loadedBuffer; // Create the source. source = context.createBufferSource(); source.buffer = buffer; console.log('source', source); // Hook up volume gainNode = context.createGain(); gainNode.gain.value = volume; console.log('gainNode', gainNode); // Create the filter. filter = context.createBiquadFilter(); filter.type = (typeof filter.type === 'string') ? 'lowpass' : 0; // LOWPASS filter.frequency.value = frequency; console.log('filter', filter); // Connect source to filter, filter to destination. source.connect(filter); filter.connect(gainNode); //source.connect(gainNode); gainNode.connect(context.destination); source.start(0); source.loop = true; // setFrequency(frequencyProgress); }) }; xhr.send(); console.log('adsfasdf'); } testAudio();
dodi-rotterdam/dodi-rotterdam.github.io
eredivisie2016/scripts/audio_test.js
JavaScript
gpl-3.0
1,929
/** * * Generic configuration file for all the GulpJS tasks. */ var gulp = require( 'gulp' ); var path = require( 'path' ); var os = require( 'os' ); var fs = require( 'fs' ); var expand = require( 'glob-expand' ); var plugins = require( 'gulp-load-plugins' )( { camelize: true } ); var minimist = require( 'minimist' ); var extend = require( 'extend' ); var gutil = require( 'gulp-util' ); /* * Function to check if a value is in a array. */ Array.prototype.inArray = function ( obj, wildcard ) { if ( typeof obj == 'object' ) { var a = obj.length; while ( a-- ) { if ( this.inArray( obj[ a ] ) ) return true; } return false; } var i = this.length; while ( i-- ) { if ( this[ i ] === obj ) { return true; } if ( typeof wildcard !== 'undefined' && wildcard === true ) { if ( this[ i ].indexOf( obj ) !== -1 ) { return true; } } } return false; }; // /** * Function to replace special paths. */ String.prototype.ReplaceSpecialPaths = function ( config ) { return this .replace( '$COMMON_DIR', config.common ) .replace( '$THEME_DIR', config.src ) .replace( '$BUILD_DIR', config.build ) .replace( /^(\/)/, "" ); }; /** * Read JSON files. */ var readJSON = function ( path ) { return JSON.parse( fs.readFileSync( path ) ); }; /* * Creates the config module that returns all the configurations for WordPresskit. */ module.exports = function () { // Stores the main configurations. var config = { }; // Stores the configurations that can be set in the console. var knownOptions = { string: [ 'project', 'dist' ], boolean: [ 'debug', 'bundle' ], default: { debug: false, project: false, bundle: true, src: process.cwd() + '/src', build: process.cwd() + '/build', dist: process.cwd() + '/dist', common: process.cwd() + '/src/_common', bower: process.cwd() + '/bower_components/', modules: process.cwd() + '/node_modules/' } }; var options = minimist( process.argv.slice( 2 ), knownOptions ); global.debug = options.debug; global.bundle = options.bundle; // Expand the configurations by JSON files. var expandConfigFile = function ( value ) { var file = value.split( '/' ).pop(), configKey = file.split( '.' ).shift(), configValue = readJSON( path.join( process.cwd(), value ) ); if ( Array.isArray( config[ configKey ] ) ) { if ( Array.isArray( configValue ) ) { configValue.forEach( function ( configValueItem ) { config[ configKey ].push( configValueItem ); } ); } else { config[ configKey ].push( configValue ); } } if ( typeof config[ configKey ] == 'undefined' ) { config[ configKey ] = configValue; } }; var expandConfigDirectory = function ( value ) { expand( { cwd: process.cwd(), filter: 'isFile' }, value + '/*.json' ).forEach( expandConfigFile ); }; expand( { cwd: process.cwd(), filter: 'isDirectory' }, 'configs/*' ).forEach( expandConfigDirectory ); expand( { cwd: process.cwd(), filter: 'isFile' }, 'configs/*.json' ).forEach( expandConfigFile ); // Check if there is a project selected. if ( !options.project ) { gutil.log( gutil.colors.red( 'You must specify a project by using the --project [name] option.' ) ); process.exit( 1 ); } // Store all the options selected from files and the console. extend( true, config, options ); // Add the project folder to the src, dist and build folder. config.src += '/' + config.project; config.build += '/' + config.project; config.dist += '/' + config.project; return config; }();
michaelbeers/WordPresskit
gulpfile.js/config.js
JavaScript
gpl-3.0
4,070
/*** * Contains basic SlickGrid editors. * @module Editors * @namespace Slick */ (function ($) { // register namespace $.extend(true, window, { "Slick": { "Editors": { "Text": TextEditor, "Integer": IntegerEditor, "Date": DateEditor, "SelfDate": SelfDateEditor, "YesNoSelect": YesNoSelectEditor, "Checkbox": CheckboxEditor, "PercentComplete": PercentCompleteEditor, "LongText": LongTextEditor, "SelfLongText":SelfLongTextEditor,//object "SelfLongTextArray":SelfLongTextArrayEditor,//array "SelfNumber":SelfNumberEditor, "NumericRangeEditor":zidingyi, "PointerSelect": PointerSelectEditor, "FileText":FileTextEditor, "SelfAcl":SelfAclEditor } } }); function SelfAclEditor(args) { var $select; var $input; var defaultValue; var scope = this; var tempColumn=args.column.field; this.init = function () { $input = $("<INPUT type=text class='editor-text' />"); $input.appendTo(args.container); debugger; // $input.modal({keyboard: false}); $input.focus(); }; this.destroy = function () { $select.remove(); }; this.focus = function () { $select.focus(); }; this.loadValue = function (item) { var tempInputValue=""; var tempItem=item[args.column.field]||""; defaultValue=tempItem; $input.val(tempInputValue); $select.select(); }; this.serializeValue = function () { var tempClazzName=$select.val(); var tempId=$input.val(); return tempObj; // return ($select.val() == "yes"); }; this.applyValue = function (item, state) {// return 返回的值 state item[args.column.field] = state; }; this.isValueChanged = function () { return ($select.val() != defaultValue); }; this.validate = function () { return { valid: true, msg: null }; }; this.init(); } function FileTextEditor(args) { var $select; var $input; var defaultValue; var scope = this; var tempColumn=args.column.field; this.init = function () { var textH='<input type="hidden" value="" name="fileValue">'; var uploadFormH='<form class="uploadFormId" method="post" action="http://upload.qiniu.com/"enctype="multipart/form-data">'; var uploadFileH='<input style="float: left;width: 150px;" onchange="bwConfig.bwDatagrid.initAjaxUploadForm(this)" name="file" type="file" />'; var uploadTipH='<div style="float: right;" class="uploadTip"></div>'; var uploadFormCH='</form>'; // container.append(uploadFormH+uploadFileH+uploadTipH+uploadFormCH); // var input=$(textH).appendTo(container); var tempOptionStr=''; var tempFn=args.column.bgdbScope.uploadForm; var inputH='<a href="javascript:;" class="upload-a">选择文件<input class="upload-file" type="file" name="file"></a>'; var tempWrap=uploadFormH+inputH+uploadFormCH; $input=$(tempWrap); $input.appendTo(args.container); //$input.change(tempFn); $input.find(".upload-file").change(tempFn); //$select.focus(); $input.focus(); }; this.destroy = function () { $select.remove(); }; this.focus = function () { $select.focus(); }; this.loadValue = function (item) { var tempInputValue=""; var tempSelectValue=""; var tempItem=item[args.column.field]||""; defaultValue=tempItem; if($.type(tempItem)==="object") { tempSelectValue=tempItem.className; tempInputValue=tempItem._id; // $select.val(tempSelectValue); // $input.val(tempInputValue); } $select.val(tempSelectValue); $input.val(tempInputValue); // $select.val((defaultValue = item[args.column.field]||"")); $select.select(); }; this.serializeValue = function () { //{"setction":{"__type":"Pointer","className":"tempRecommendSection","_id":"b5dbb2aae1c640c6bdd8a78851da8f09"}} var tempClazzName=$select.val(); var tempId=$input.val(); var tempObj={"__type":"Pointer","className":tempClazzName,"_id":tempId}; return tempObj; // return ($select.val() == "yes"); }; this.applyValue = function (item, state) {// return 返回的值 state item[args.column.field] = state; }; this.isValueChanged = function () { return ($select.val() != defaultValue); }; this.validate = function () { return { valid: true, msg: null }; }; this.init(); } function PointerSelectEditor(args) { var $select; var $input; var defaultValue; var scope = this; var tempColumn=args.column.field; this.init = function () { var tempOptionStr=''; var tempClazzModel=args.column.classModel; for(var i in tempClazzModel) { var tempName=tempClazzModel[i].name; tempOptionStr+='<OPTION value='+tempName+'>'+tempName+'</OPTION>'; } $select = $("<SELECT tabIndex='0' class='editor-pointer-select form-control'>"+tempOptionStr+"</SELECT>"); $input = $("<INPUT type=text class='editor-text' />"); $select.appendTo(args.container); $input.appendTo(args.container); //$select.focus(); $input.focus(); }; this.destroy = function () { $select.remove(); }; this.focus = function () { $select.focus(); }; this.loadValue = function (item) { var tempInputValue=""; var tempSelectValue=""; var tempItem=item[args.column.field]||""; defaultValue=tempItem; if($.type(tempItem)==="object") { tempSelectValue=tempItem.className; tempInputValue=tempItem._id; // $select.val(tempSelectValue); // $input.val(tempInputValue); } $select.val(tempSelectValue); $input.val(tempInputValue); // $select.val((defaultValue = item[args.column.field]||"")); $select.select(); }; this.serializeValue = function () { //{"setction":{"__type":"Pointer","className":"tempRecommendSection","_id":"b5dbb2aae1c640c6bdd8a78851da8f09"}} var tempClazzName=$select.val(); var tempId=$input.val(); var tempObj={"__type":"Pointer","className":tempClazzName,"_id":tempId}; return tempObj; // return ($select.val() == "yes"); }; this.applyValue = function (item, state) {// return 返回的值 state item[args.column.field] = state; }; this.isValueChanged = function () { return ($select.val() != defaultValue); }; this.validate = function () { return { valid: true, msg: null }; }; this.init(); } /* * An example of a "detached" editor. * The UI is added onto document BODY and .position(), .show() and .hide() are implemented. * KeyDown events are also handled to provide handling for Tab, Shift-Tab, Esc and Ctrl-Enter. */ function SelfLongTextArrayEditor(args) { var $input, $wrapper; var defaultValue; var scope = this; this.init = function () { var $container = $("body"); $wrapper = $("<DIV style='z-index:10000;position:absolute;background:white;padding:5px;border:3px solid gray; -moz-border-radius:10px; border-radius:10px;'/>") .appendTo($container); $input = $("<TEXTAREA hidefocus rows=5 style='backround:white;width:250px;height:80px;border:0;outline:0'>") .appendTo($wrapper); $("<DIV style='text-align:right'><BUTTON>Save</BUTTON><BUTTON>Cancel</BUTTON></DIV>") .appendTo($wrapper); $wrapper.find("button:first").bind("click", this.save); $wrapper.find("button:last").bind("click", this.cancel); $input.bind("keydown", this.handleKeyDown); scope.position(args.position); $input.focus().select(); }; this.handleKeyDown = function (e) { if (e.which == $.ui.keyCode.ENTER && e.ctrlKey) { scope.save(); } else if (e.which == $.ui.keyCode.ESCAPE) { e.preventDefault(); scope.cancel(); } else if (e.which == $.ui.keyCode.TAB && e.shiftKey) { e.preventDefault(); args.grid.navigatePrev(); } else if (e.which == $.ui.keyCode.TAB) { e.preventDefault(); args.grid.navigateNext(); } }; this.save = function () { args.commitChanges(); }; this.cancel = function () { $input.val(defaultValue); args.cancelChanges(); }; this.hide = function () { $wrapper.hide(); }; this.show = function () { $wrapper.show(); }; this.position = function (position) { $wrapper .css("top", position.top - 5) .css("left", position.left - 5) }; this.destroy = function () { $wrapper.remove(); }; this.focus = function () { $input.focus(); }; this.loadValue = function (item) { var tempValue=item[args.column.field]; if($.type(tempValue)==="array") { tempValue=tempValue.join(","); tempValue="["+tempValue+"]"; $input.val(defaultValue = tempValue); } else { $input.val(defaultValue = item[args.column.field]); } $input.select(); }; this.serializeValue = function () { var tempValue=$input.val(); var tempArrayValue=tempValue.replace('[',"").replace(']',"").split(","); if($.type(tempArrayValue)==="array") { return tempValue; } else { return $input.val(); } }; this.applyValue = function (item, state) { var tempState=state.replace('[',"").replace(']',"").split(","); item[args.column.field] = tempState; }; this.isValueChanged = function () { return (!($input.val() == "" && defaultValue == null)) && ($input.val() != defaultValue); }; this.validate = function () { var tempValue=$input.val(); var tempArrayValue=tempValue.replace('[',"").replace(']',"").split(","); if($.type(tempArrayValue)==="array") { return { valid: true, msg: null }; } else { return { valid: false, msg: "数组格式不对" }; } }; this.init(); } /* * * 编辑number类型 * * */ function SelfNumberEditor(args) { var $input; var defaultValue; var scope = this; this.init = function () { $input = $("<INPUT type=text class='editor-text' />") .appendTo(args.container) .bind("keydown.nav", function (e) { if (e.keyCode === $.ui.keyCode.LEFT || e.keyCode === $.ui.keyCode.RIGHT) { e.stopImmediatePropagation(); } }) .focus() .select(); }; this.handleKeyDown = function (e) { if (e.keyCode == $.ui.keyCode.LEFT || e.keyCode == $.ui.keyCode.RIGHT || e.keyCode == $.ui.keyCode.TAB) { e.stopImmediatePropagation(); } }; this.destroy = function () { $input.remove(); }; this.focus = function () { $input.focus(); }; this.serializeValue = function () { return $input.val(); }; this.applyValue = function (item, state) { item[args.column.field] = state; }; this.isValueChanged = function () { return (!($input.val() == "" && defaultValue == null)) && ($input.val() != defaultValue); }; this.validate = function () { if (isNaN(parseInt($input.val(), 10))) { return {valid: false, msg: "必须为数字类型"}; } return {valid: true, msg: null}; }; this.getValue = function () { return $input.val(); }; this.setValue = function (val) { $input.val(val); }; this.loadValue = function (item) { defaultValue = item[args.column.field] || ""; $input.val(defaultValue); $input[0].defaultValue = defaultValue; $input.select(); }; this.init(); } function zidingyi(args) { var $input; var defaultValue; var scope = this; this.init = function () { $input = $("<INPUT type=text class='editor-text' />") .appendTo(args.container) .bind("keydown.nav", function (e) { if (e.keyCode === $.ui.keyCode.LEFT || e.keyCode === $.ui.keyCode.RIGHT) { e.stopImmediatePropagation(); } }) .focus() .select(); }; this.destroy = function () { $input.remove(); }; this.focus = function () { $input.focus(); }; this.getValue = function () { return $input.val(); }; this.setValue = function (val) { $input.val(val); }; this.loadValue = function (item) { defaultValue = item[args.column.field] || ""; $input.val(defaultValue); $input[0].defaultValue = defaultValue; $input.select(); }; this.serializeValue = function () { return $input.val(); }; this.applyValue = function (item, state) { item[args.column.field] = state; }; this.isValueChanged = function () { return (!($input.val() == "" && defaultValue == null)) && ($input.val() != defaultValue); }; this.validate = function () { if (args.column.validator) { var validationResults = args.column.validator($input.val()); if (!validationResults.valid) { return validationResults; } } return { valid: true, msg: null }; }; this.init(); } function TextEditor(args) { var $input; var defaultValue; var scope = this; this.init = function () { $input = $("<INPUT type=text class='editor-text form-control' />") .appendTo(args.container) .bind("keydown.nav", function (e) { if (e.keyCode === $.ui.keyCode.LEFT || e.keyCode === $.ui.keyCode.RIGHT) { e.stopImmediatePropagation(); } }) .focus() .select(); }; this.destroy = function () { $input.remove(); }; this.focus = function () { $input.focus(); }; this.getValue = function () { return $input.val(); }; this.setValue = function (val) { $input.val(val); }; this.loadValue = function (item) { defaultValue = item[args.column.field] || ""; $input.val(defaultValue); $input[0].defaultValue = defaultValue; $input.select(); }; this.serializeValue = function () { return $input.val(); }; this.applyValue = function (item, state) { item[args.column.field] = state; }; this.isValueChanged = function () { return (!($input.val() == "" && defaultValue == null)) && ($input.val() != defaultValue); }; this.validate = function () { if (args.column.validator) { var validationResults = args.column.validator($input.val()); if (!validationResults.valid) { return validationResults; } } return { valid: true, msg: null }; }; this.init(); } function IntegerEditor(args) { var $input; var defaultValue; var scope = this; this.init = function () { $input = $("<INPUT type=text class='editor-text form-control' />"); $input.bind("keydown.nav", function (e) { if (e.keyCode === $.ui.keyCode.LEFT || e.keyCode === $.ui.keyCode.RIGHT) { e.stopImmediatePropagation(); } }); $input.appendTo(args.container); $input.focus().select(); }; this.destroy = function () { $input.remove(); }; this.focus = function () { $input.focus(); }; this.loadValue = function (item) { defaultValue = item[args.column.field]; $input.val(defaultValue); $input[0].defaultValue = defaultValue; $input.select(); }; this.serializeValue = function () { return parseInt($input.val(), 10) || 0; }; this.applyValue = function (item, state) { item[args.column.field] = state; }; this.isValueChanged = function () { return (!($input.val() == "" && defaultValue == null)) && ($input.val() != defaultValue); }; this.validate = function () { if (isNaN($input.val())) { return { valid: false, msg: "请输入数字类型" }; } return { valid: true, msg: null }; }; this.init(); } function DateEditor(args) { var $input; var defaultValue; var scope = this; var calendarOpen = false; this.init = function () { $input = $("<INPUT type=text class='editor-text' />"); $input.appendTo(args.container); $input.focus().select(); $input.datepicker({ showOn: "button", buttonImageOnly: true, buttonImage: "./lib/slickgrid/images/calendar.gif", beforeShow: function () { calendarOpen = true }, onClose: function () { calendarOpen = false } }); $input.width($input.width() - 18); }; this.destroy = function () { $.datepicker.dpDiv.stop(true, true); $input.datepicker("hide"); $input.datepicker("destroy"); $input.remove(); }; this.show = function () { if (calendarOpen) { $.datepicker.dpDiv.stop(true, true).show(); } }; this.hide = function () { if (calendarOpen) { $.datepicker.dpDiv.stop(true, true).hide(); } }; this.position = function (position) { if (!calendarOpen) { return; } $.datepicker.dpDiv .css("top", position.top + 30) .css("left", position.left); }; this.focus = function () { $input.focus(); }; this.loadValue = function (item) { defaultValue = item[args.column.field]; $input.val(defaultValue); $input[0].defaultValue = defaultValue; $input.select(); }; this.serializeValue = function () { return $input.val(); }; this.applyValue = function (item, state) { item[args.column.field] = state; }; this.isValueChanged = function () { return (!($input.val() == "" && defaultValue == null)) && ($input.val() != defaultValue); }; this.validate = function () { return { valid: true, msg: null }; }; this.init(); } function SelfDateEditor(args) { var $input; var defaultValue; var scope = this; var calendarOpen = false; this.init = function () { //$input = $("<INPUT type=text class='editor-text' />"); $input = $("<INPUT type='text'/>"); $input.appendTo(args.container); $input.focus().select(); $input.datetimepicker({value:'2015/04/15 05:03',step:10}); $input.width($input.width() - 18); }; this.destroy = function () { $input.datetimepicker("remove"); $input.remove(); // $.datepicker.dpDiv.stop(true, true); // $input.datepicker("hide"); // $input.datepicker("destroy"); // $input.remove(); }; this.show = function () { // if (calendarOpen) { // $.datepicker.dpDiv.stop(true, true).show(); // } }; this.hide = function () { // if (calendarOpen) { // $.datepicker.dpDiv.stop(true, true).hide(); // } }; this.position = function (position) { // if (!calendarOpen) { // return; // } // $.datepicker.dpDiv // .css("top", position.top + 30) // .css("left", position.left); }; this.focus = function () { // $input.focus(); }; this.loadValue = function (item) { // defaultValue = item[args.column.field]; // $input.val(defaultValue); // $input[0].defaultValue = defaultValue; // $input.select(); }; this.serializeValue = function () { return $input.val(); }; this.applyValue = function (item, state) { item[args.column.field] =state; }; this.isValueChanged = function () { return (!($input.val() == "" && defaultValue == null)) && ($input.val() != defaultValue); }; this.validate = function () { return { valid: true, msg: null }; }; this.init(); } function YesNoSelectEditor(args) { var $select; var defaultValue; var scope = this; this.init = function () { $select = $("<SELECT tabIndex='0' class='editor-yesno form-control'><OPTION value='yes'>Yes</OPTION><OPTION value='no'>No</OPTION></SELECT>"); $select.appendTo(args.container); $select.focus(); }; this.destroy = function () { $select.remove(); }; this.focus = function () { $select.focus(); }; this.loadValue = function (item) { $select.val((defaultValue = item[args.column.field]) ? "yes" : "no"); $select.select(); }; this.serializeValue = function () { return ($select.val() == "yes"); }; this.applyValue = function (item, state) { item[args.column.field] = state; }; this.isValueChanged = function () { return ($select.val() != defaultValue); }; this.validate = function () { return { valid: true, msg: null }; }; this.init(); } function CheckboxEditor(args) { var $select; var defaultValue; var scope = this; this.init = function () { $select = $("<INPUT type=checkbox value='true' class='editor-checkbox' hideFocus>"); $select.appendTo(args.container); $select.focus(); }; this.destroy = function () { $select.remove(); }; this.focus = function () { $select.focus(); }; this.loadValue = function (item) { defaultValue = !!item[args.column.field]; if (defaultValue) { $select.prop('checked', true); } else { $select.prop('checked', false); } }; this.serializeValue = function () { return $select.prop('checked'); }; this.applyValue = function (item, state) { item[args.column.field] = state; }; this.isValueChanged = function () { return (this.serializeValue() !== defaultValue); }; this.validate = function () { return { valid: true, msg: null }; }; this.init(); } function PercentCompleteEditor(args) { var $input, $picker; var defaultValue; var scope = this; this.init = function () { $input = $("<INPUT type=text class='editor-percentcomplete' />"); $input.width($(args.container).innerWidth() - 25); $input.appendTo(args.container); $picker = $("<div class='editor-percentcomplete-picker' />").appendTo(args.container); $picker.append("<div class='editor-percentcomplete-helper'><div class='editor-percentcomplete-wrapper'><div class='editor-percentcomplete-slider' /><div class='editor-percentcomplete-buttons' /></div></div>"); $picker.find(".editor-percentcomplete-buttons").append("<button val=0>Not started</button><br/><button val=50>In Progress</button><br/><button val=100>Complete</button>"); $input.focus().select(); $picker.find(".editor-percentcomplete-slider").slider({ orientation: "vertical", range: "min", value: defaultValue, slide: function (event, ui) { $input.val(ui.value) } }); $picker.find(".editor-percentcomplete-buttons button").bind("click", function (e) { $input.val($(this).attr("val")); $picker.find(".editor-percentcomplete-slider").slider("value", $(this).attr("val")); }) }; this.destroy = function () { $input.remove(); $picker.remove(); }; this.focus = function () { $input.focus(); }; this.loadValue = function (item) { $input.val(defaultValue = item[args.column.field]); $input.select(); }; this.serializeValue = function () { return parseInt($input.val(), 10) || 0; }; this.applyValue = function (item, state) { item[args.column.field] = state; }; this.isValueChanged = function () { return (!($input.val() == "" && defaultValue == null)) && ((parseInt($input.val(), 10) || 0) != defaultValue); }; this.validate = function () { if (isNaN(parseInt($input.val(), 10))) { return { valid: false, msg: "Please enter a valid positive number" }; } return { valid: true, msg: null }; }; this.init(); } /* * An example of a "detached" editor. * The UI is added onto document BODY and .position(), .show() and .hide() are implemented. * KeyDown events are also handled to provide handling for Tab, Shift-Tab, Esc and Ctrl-Enter. */ function SelfLongTextEditor(args) { var $input, $wrapper; var defaultValue; var scope = this; this.init = function () { var $container = $("body"); $wrapper = $("<DIV style='z-index:10000;position:absolute;background:white;padding:5px;border:3px solid gray; -moz-border-radius:10px; border-radius:10px;'/>") .appendTo($container); $input = $("<TEXTAREA hidefocus rows=5 style='backround:white;width:250px;height:80px;border:0;outline:0'>") .appendTo($wrapper); $("<DIV style='text-align:right'><BUTTON>Save</BUTTON><BUTTON>Cancel</BUTTON></DIV>") .appendTo($wrapper); $wrapper.find("button:first").bind("click", this.save); $wrapper.find("button:last").bind("click", this.cancel); $input.bind("keydown", this.handleKeyDown); scope.position(args.position); $input.focus().select(); }; this.handleKeyDown = function (e) { if (e.which == $.ui.keyCode.ENTER && e.ctrlKey) { scope.save(); } else if (e.which == $.ui.keyCode.ESCAPE) { e.preventDefault(); scope.cancel(); } else if (e.which == $.ui.keyCode.TAB && e.shiftKey) { e.preventDefault(); args.grid.navigatePrev(); } else if (e.which == $.ui.keyCode.TAB) { e.preventDefault(); args.grid.navigateNext(); } }; this.save = function () { args.commitChanges(); }; this.cancel = function () { $input.val(defaultValue); args.cancelChanges(); }; this.hide = function () { $wrapper.hide(); }; this.show = function () { $wrapper.show(); }; this.position = function (position) { $wrapper .css("top", position.top - 5) .css("left", position.left - 5) }; this.destroy = function () { $wrapper.remove(); }; this.focus = function () { $input.focus(); }; this.loadValue = function (item) {//加载是向编辑框内加载 var tempValue=item[args.column.field]; if(typeof tempValue=="object") { tempValue= JSON.stringify(tempValue); } $input.val(defaultValue = tempValue);//设置为字符串 $input.select(); }; this.serializeValue = function () { var tempValue=$input.val();//字符串 // if(typeof tempValue=="string"&&tempValue!="") if($.type(tempValue)==="string"&&tempValue!="") { return JSON.parse($input.val()); } //if(typeof tempValue=="object") if($.type(tempValue)==="object") { return JSON.stringify($input.val()); } return tempValue; }; this.applyValue = function (item, state) { item[args.column.field] =state;//对象 }; this.isValueChanged = function () { return (!($input.val() == "" && defaultValue == null)) && ($input.val() != defaultValue); }; this.validate = function () { var tempValue=$input.val();//字符串 if($.type(tempValue)==="string"&&tempValue!="") { try { JSON.parse(tempValue); } catch (e) { return { valid: false, msg:"格式错误" }; } } return { valid: true, msg: null }; }; this.init(); } /* * An example of a "detached" editor. * The UI is added onto document BODY and .position(), .show() and .hide() are implemented. * KeyDown events are also handled to provide handling for Tab, Shift-Tab, Esc and Ctrl-Enter. */ function LongTextEditor(args) { var $input, $wrapper; var defaultValue; var scope = this; this.init = function () { var $container = $("body"); $wrapper = $("<DIV style='z-index:10000;position:absolute;background:white;padding:5px;border:3px solid gray; -moz-border-radius:10px; border-radius:10px;'/>") .appendTo($container); $input = $("<TEXTAREA hidefocus rows=5 style='backround:white;width:250px;height:80px;border:0;outline:0'>") .appendTo($wrapper); $("<DIV style='text-align:right'><BUTTON>Save</BUTTON><BUTTON>Cancel</BUTTON></DIV>") .appendTo($wrapper); $wrapper.find("button:first").bind("click", this.save); $wrapper.find("button:last").bind("click", this.cancel); $input.bind("keydown", this.handleKeyDown); scope.position(args.position); $input.focus().select(); }; this.handleKeyDown = function (e) { if (e.which == $.ui.keyCode.ENTER && e.ctrlKey) { scope.save(); } else if (e.which == $.ui.keyCode.ESCAPE) { e.preventDefault(); scope.cancel(); } else if (e.which == $.ui.keyCode.TAB && e.shiftKey) { e.preventDefault(); args.grid.navigatePrev(); } else if (e.which == $.ui.keyCode.TAB) { e.preventDefault(); args.grid.navigateNext(); } }; this.save = function () { args.commitChanges(); }; this.cancel = function () { $input.val(defaultValue); args.cancelChanges(); }; this.hide = function () { $wrapper.hide(); }; this.show = function () { $wrapper.show(); }; this.position = function (position) { $wrapper .css("top", position.top - 5) .css("left", position.left - 5) }; this.destroy = function () { $wrapper.remove(); }; this.focus = function () { $input.focus(); }; this.loadValue = function (item) { $input.val(defaultValue = item[args.column.field]); $input.select(); }; this.serializeValue = function () { return $input.val(); }; this.applyValue = function (item, state) { item[args.column.field] = state; }; this.isValueChanged = function () { return (!($input.val() == "" && defaultValue == null)) && ($input.val() != defaultValue); }; this.validate = function () { return { valid: true, msg: null }; }; this.init(); } })(jQuery);
s249359986/JavaBaasServer
src/main/resources/static/lib/slickgrid/slick.editors.js
JavaScript
gpl-3.0
34,101
function polarToVector(theta, radius) { let x = cos(theta) * radius let y = sin(theta) * radius return createVector(x, y) } function getSlope(v1, v2) { //m = rise/run //m = y/x return (v2.y - v1.y) / (v2.x - v1.x) } //THE B IS INVERTED!!!! function getYintersect(slope, v) { //y = mx + b //b = mx + y //or is it -b = mx -y // b = (mx - y) * -1 //maybe it should be slope * v.y - v.x return (slope * v.x - v.y) * -1//THIS IS WHERE YOU BREAK THE REST } function Vertex(v) { this.v = v this.draw = function () { ellipse(v.x, v.y, 10, 10) } } function Line(v1, v2) { this.v1 = v1 this.v2 = v2 this.slope = function () { return getSlope(this.v1, this.v2) } this.yIntersect = function () { return getYintersect(this.slope(), this.v1) } this.draw = function () { line(this.v1.x, this.v1.y, this.v2.x, this.v2.y) } this.solveX = function (y) { let m = this.slope() let b = this.yIntersect() y -= b return y / m } //in pixels this.extend = function (len = 1) { let newV2 = this.v2.copy() newV2.sub(this.v1) newV2.normalize() newV2.mult(len) newV2.add(this.v1) this.v2 = newV2 return newV2 } this.intersect = function (other) { let m1 = this.slope() let b1 = this.yIntersect() let m2 = other.slope() let b2 = other.yIntersect() let m = m1 + m2 * -1 let b = b1 + b2 * -1 let x = b / -m//dont know why minus m let y = (m1 * x) + b1 return createVector(x, y) } this.getPerpendicular = function (intersect = 0.5) { let v = lerpVector(v1, v2, intersect) let m = this.slope() //find the negative reciprocal of the slope //nr = -1/-m let m2 = -1 / m //then plug in the point and solve x // let b2 = getYintersect(m2, v) let l = new Line(v, createVector(0, b2)) l.extend(-100) l.draw() return l } } function Polygon(center, vertices) { this.center = center this.lines = [] for (let i = 0; i < vertices.length - 1; i++) { this.lines.push(new Line(vertices[i], vertices[i + 1])) } this.lines.push(new Line(vertices[vertices.length - 1], vertices[0])) this.getVertex = function (i) { return this.lines[i].v1 } this.getBarycentricNormal = function (i) { let len = this.lines.length let hlen = len / 2 let v1 = this.getVertex(i) let v2 if (len % 2 === 0) { let i2 = (i + hlen) % len v2 = this.getVertex(i2) } else { let i2a = (i + floor(hlen)) % len let i2b = (i + ceil(hlen)) % len v2 = averageVector([this.getVertex(i2a), this.getVertex(i2b)]) } let l = new Line(v1, v2) return l } this.setVertex = function (i, v) { this.lines[i].v1 = v let i2 = i === 0 ? this.lines.length - 1 : i - 1 this.lines[i2].v2 = v } this.draw = function () { push() translate(this.center.x, this.center.y) this.lines.forEach(l => l.draw()) pop() } } function averageVector(vectors) { let sum = createVector() vectors.forEach(v => sum.add(v)) return sum.div(vectors.length) } function lerp(a, b, t) { return (b - a) * t + a } function lerpVector(v1, v2, t) { let x = lerp(v1.x, v2.x, t) let y = lerp(v1.y, v2.y, t) return createVector(x, y) }
peteyhayman/peteyhayman.github.io
Libraries/Geometry/geometry.js
JavaScript
gpl-3.0
3,427
"use strict"; var SHOW_DATA = { "venue_name": "Oklahoma City Fairgrounds Arena, Oklahoma City, Oklahoma", "venue_id": 208, "show_date": "19th of Oct, 1973", "sets": [ {"set_title": "1st set", "encore": false, "songs": [ {"name": "Promised Land", "length":"3:01", "trans":"/"}, {"name": "Sugaree", "length":"7:43", "trans":"/"}, {"name": "Mexicali Blues", "length":"3:24", "trans":"/"}, {"name": "Tennessee Jed", "length":"7:25", "trans":"/"}, {"name": "Looks Like Rain", "length":"7:12", "trans":"/"}, {"name": "Don't Ease Me In", "length":"3:52", "trans":"/"}, {"name": "Jack Straw", "length":"4:50", "trans":"/"}, {"name": "They Love Each Other", "length":"5:08", "trans":"/"}, {"name": "El Paso", "length":"4:28", "trans":"/"}, {"name": "Row Jimmy", "length":"9:04", "trans":"/"}, {"name": "Playing In The Band", "length":"3:07", "trans":">"}, {"name": "PITB Jam", "length":"12:35", "trans":">"}, {"name": "Playing Reprise", "length":"2:22", "trans":"/"}, ]}, {"set_title": "2nd set", "encore": false, "songs": [ {"name": "China Cat Sunflower", "length":"3:26", "trans":">"}, {"name": "Weir's Segue", "length":"3:49", "trans":">"}, {"name": "Feelin' Groovy Jam", "length":"1:43", "trans":">"}, {"name": "I Know You Rider", "length":"5:24", "trans":"/"}, {"name": "Me & My Uncle", "length":"2:53", "trans":"/"}, {"name": "Mississippi Half-Step", "length":"6:45", "trans":"/"}, {"name": "Big River", "length":"4:37", "trans":"/"}, {"name": "Dark Star Jam", "length":"4:50", "trans":">"}, {"name": "Free Form Jam", "length":"4:33", "trans":">"}, {"name": "Dark Star", "length":"4:15", "trans":">"}, {"name": "Free Form Jam", "length":"3:13", "trans":">"}, {"name": "Descending Four Chord Sequence", "length":"4:19", "trans":">"}, {"name": "Explorations", "length":"3:44", "trans":">"}, {"name": "Free Form Jam", "length":"1:20", "trans":">"}, {"name": "Morning Dew", "length":"12:42", "trans":"/"}, {"name": "Sugar Magnolia", "length":"0:00", "trans":"/"}, ]}, {"set_title": "3rd set", "encore": false, "songs": [ {"name": "Eyes Of The World", "length":"7:30", "trans":">"}, {"name": "Untitled Post-Eyes Jam", "length":"7:00", "trans":">"}, {"name": "Stella Blue", "length":"7:40", "trans":"/"}, ]}, {"set_title": "4th set", "encore": false, "songs": [ {"name": "Johnny B. Goode", "length":"3:49", "trans":"/"}, ]}, ], };
maximinus/grateful-dead-songs
gdsongs/static/data/shows/19.js
JavaScript
gpl-3.0
2,467
var navlist = Y.one('.instancelist-wrapper'); var details = Y.one('.instanceinfo'), page = getDataFromStr('page', window.location.toString(), '='), resetpage = true; if(!page){ page = 0; } if($("#region-main").length) { // Скрываем первую пагинацию if (Y.one('.paging')) { Y.one('.paging').setAttribute('style', 'display:none'); } /** * Открывает select/input-поле для редактирования */ Y.one("#region-main").delegate('click', function () { var field = this, addon = field.next(".ce-addon"); if (addon) { field.setAttribute('style', 'display:none'); addon.setAttribute('style', 'display:inline-block'); addon.one("select, input").focus(); } }, ".contenteditable"); Y.one('#region-main').delegate('click', function () { closeInstance(); }, '.close-instance'); /** * Скрывает редактируемое поле */ Y.use('event-focus', function () { Y.one("#region-main").delegate('blur', function () { var addon = this, field = addon.previous('.contenteditable'), list = Y.one(".yui3-widget.yui3-aclist.yui3-widget-positioned"); if (list == null || list != null && list.hasClass("yui3-aclist-hidden")) { addon.setAttribute('style', 'display:none'); field.setAttribute('style', 'display:inline-block'); } }, ".ce-addon"); }); } function addNewRowIn(tablenode){ var table = Y.one(tablenode), tplrows = table.all("tr.clone.hide"), lastrow = table.one(".lastrow"), rnum = 0; if(lastrow) { rnum = lastrow.getAttribute("class"); rnum = rnum.match(/r([0-9]*)\s/)[1]; rnum = rnum ? 0: 1; } tplrows.each(function(node){ lastrow.removeClass("lastrow"); table.one("tbody").append(node.cloneNode(true).addClass("lastrow")); lastrow = table.one(".lastrow").removeClass("clone hide"); }); if(tplrows._nodes.length > 1){ lastrow.addClass('hide'); } return lastrow; } function closeInstance(){ var ac_fio = document.getElementById('activityinfo'); if(!ac_fio) { ac_fio = document.getElementById('partnerinfo'); } if(ac_fio){ ac_fio = ac_fio.getElementsByClassName('userfioinput'); if(ac_fio[0] != null){ document.getElementById('userfio-tmp').appendChild(ac_fio[0]); } } navlist.setAttribute('style', 'display:block'); details.setHTML(''); goSearch(); } function openInstance(){ navlist.setAttribute('style', 'display:none'); details.setHTML(indicatorbig); } /** * Возвращает численные данные по шаблону из строки * Например, если у нас есть строка "somestring-999 anything", и мы хотим извлечь идентификатор 999, то * эта функция то что нужно! Вызываем так: getDataFromStr('999', 'somestring-999 anything'); * * @param search * @param classname * @param separator * @returns {*} */ function getDataFromStr(search, classname, separator){ if(typeof separator == 'undefined'){ separator = '-'; } re = new RegExp(search+separator+'([0-9]*)', "i"); data = classname.match(re); if(data != null && 1 in data && typeof data[1] != 'undefined' && data != 0){ return data[1]; } return null; } /** * Разбирает Json, в случае ошибки переадресовывает на reproductionlink * Например, если закончилась сессия у пользователя и он пытается сделать аякс-запрос, он * будет переадресован на страницу входа * * @param data * @returns {*} */ function getJSON(data){ if(!data || typeof data === 'object'){ return data; } data = eval('('+data+')'); if(data.reproductionlink){ window.location = data.reproductionlink; } return data; } if(typeof $.fn.editableutils != "undefined") { (function ($) { "use strict"; var Address = function (options) { this.init('address', options, Address.defaults); }; //inherit from Abstract input $.fn.editableutils.inherit(Address, $.fn.editabletypes.abstractinput); $.extend(Address.prototype, { init: function (type, options, defaults) { this.type = type; this.options = $.extend({}, defaults, options); return false; }, /** Renders input from tpl @method render() **/ render: function () { this.$input = this.$tpl.find('input, select'); }, /** Default method to show value in element. Can be overwritten by display option. @method value2html(value, element) **/ value2html: function (value, element) { if (!value) { $(element).empty(); return; } if (typeof value == 'string') { $.ajax({ type: "POST", url: value, success: $.proxy(function (v) { v = getJSON(v); this.value = v; this.updpreview(v, element); }, this) }); $(element).html('Не указано'); //Хак, чтобы не считалось пустым } else { this.value = value; this.updpreview(value, element); } }, updpreview: function (value, element) { if (!value.cityid.text) { return false; } var html = $('<div>').text(value.cityid.text).html(); if (value.street) html += ', ' + $('<div>').text(value.street).html(); if (value.num) html += ', ' + $('<div>').text(value.num).html(); if (value.bld) html = html + ', стр.' + $('<div>').text(value.bld).html(); if (value.corp) html = html + ', корп.' + $('<div>').text(value.corp).html(); if (value.floor) html = html + ', эт.' + $('<div>').text(value.floor).html(); if (value.metro) html = html + ' (м.' + $('<div>').text(value.metro).html() + ')'; $(element).html(html); }, /** Converts value to string. It is used in internal comparing (not for sending to server). @method value2str(value) **/ value2str: function (value) { var str = ''; if (value) { for (var k in value) { str = str + k + ':' + value[k] + ';'; } } return str; }, /* Converts string to value. Used for reading value from 'data-value' attribute. @method str2value(str) */ str2value: function (str) { /* this is mainly for parsing value defined in data-value attribute. If you will always set value by javascript, no need to overwrite it */ return str; }, /** Sets value of input. @method value2input(value) @param {mixed} value **/ value2input: function (value) { if (!this.value) { return; } var v = this.value; this.$input.filter('[name="cityid"]').val(v.cityid.value); this.$input.filter('[name="street"]').val(v.street); this.$input.filter('[name="metro"]').val(v.metro); this.$input.filter('[name="num"]').val(v.num); this.$input.filter('[name="bld"]').val(v.bld); this.$input.filter('[name="corp"]').val(v.corp); this.$input.filter('[name="floor"]').val(v.floor); }, /** Returns value of input. @method input2value() **/ input2value: function () { this.value = { cityid: { value: this.$input.find('option:selected').val(), text: this.$input.find('option:selected').text() }, street: this.$input.filter('[name="street"]').val(), metro: this.$input.filter('[name="metro"]').val(), num: this.$input.filter('[name="num"]').val(), bld: this.$input.filter('[name="bld"]').val(), corp: this.$input.filter('[name="corp"]').val(), floor: this.$input.filter('[name="floor"]').val() }; return this.value; }, /** Activates input: sets focus on the first field. @method activate() **/ activate: function () { this.$input.filter('[name="cityid"]').focus(); }, validate: function () { }, /** Attaches handler to submit form in case of 'showbuttons=false' mode @method autosubmit() **/ autosubmit: function () { this.$input.keydown(function (e) { if (e.which === 13) { $(this).closest('form').submit(); } }); } }); var tpl = $.ajax({ type: "POST", url: "/blocks/manage/ajax.php?ajc=get_address_tpl", async: false }).responseText; tpl = getJSON(tpl).html; Address.defaults = $.extend({}, $.fn.editabletypes.abstractinput.defaults, { tpl: tpl, inputclass: '' }); $.fn.editabletypes.address = Address; }(window.jQuery)); }
Slaffka/moodel
blocks/manage/yui/base.js
JavaScript
gpl-3.0
11,043
var CRUD = require('../crud'); module.exports = { middlewares: { params: (req, res, next) => { if(CRUD.valid.params(req.params.entity)) { return next(); } res.status(400).send(Object.assign({ entity: req.params.entity }, CRUD.errors.params)); } }, create: (req, res) => { CRUD.create({ entity: req.params.entity, data: req.body, }, (err, result) => { if (err) { return res.status(500).send({ error: err.message }); } res.send(result); }); }, read: (req, res) => { CRUD.read({ id: req.params.id, entity: req.params.entity, params: req.query }, (err, result) => { if (err) { return res.status(500).send({ error: err.message }); } res.send(result); }); }, update: (req, res) => { CRUD.update({ entity: req.params.entity, id: req.params.id, data: req.body }, (err, result) => { if (err) { return res.status(500).send({ error: err.message }); } res.send(result); }); }, delete: (req, res) => { CRUD.delete({ entity: req.params.entity, id: req.params.id }, (err) => { if (err) { return res.status(500).send({ error: err.message }); } res.send({ id: req.params.id, message: 'deleted' }); }); }, count: (req, res) => { CRUD.count({ entity: req.params.entity, field: req.query.field, match: req.query.match, sort: req.query.sort, limit: req.query.limit }, (err, counts) => { if(err) { return res.status(500).send({ error: err.message }); } res.send(counts); }); } };
jiminikiz/mean-auth
controllers/crud.js
JavaScript
gpl-3.0
2,107
/*global annotator*/ /*global Markdown*/ angular.module('madisonApp.controllers') .controller('DocumentPageController', ['$scope', '$state', '$timeout', 'growl', '$location', '$window', 'Doc', '$sce', '$stateParams', '$http', 'loginPopupService', 'annotationService', '$anchorScroll', 'AuthService', '$translate', 'pageService', 'SITE', function ($scope, $state, $timeout, growl, $location, $window, Doc, $sce, $stateParams, $http, loginPopupService, annotationService, $anchorScroll, AuthService, $translate, pageService, SITE) { $scope.annotations = []; $scope.activeTab = 'content'; $scope.doc = {}; $scope.setSponsor = function () { try { //If the sponsor is a group if ($scope.doc.group_sponsor.length > 0) { $scope.doc.sponsor = $scope.doc.group_sponsor; } else if ($scope.doc.user_sponsor.length > 0) { //Otherwise it's an individual $scope.doc.sponsor = $scope.doc.user_sponsor; $scope.doc.sponsor[0].display_name = $scope.doc.sponsor[0].fname + ' ' + $scope.doc.sponsor[0].lname; } else { //This document has no sponsor! console.error("No sponsor found."); } } catch (err) { console.error(err); } }; $scope.getSupported = function () { if ($scope.user) { $http.get('/api/users/' + $scope.user.id + '/support/' + $scope.doc.id) .success(function (data) { $scope._updateSupport(data); }).error(function () { console.error("Unable to get support info for user %o and doc %o", $scope.user, $scope.doc); }); } }; $scope.support = function (supported, $event) { if (!$scope.user) { loginPopupService.showLoginForm($event); } else { $http.post('/api/docs/' + $scope.doc.id + '/support', { 'support': supported }) .success(function (data) { $scope._updateSupport(data); }) .error(function (data) { console.error("Error posting support: %o", data); }); } }; //Ensure that we actually get a document back from the server $scope.checkExists = function (doc) { //This document does not exist, redirect home if (!doc.id) { growl.error('That document does not exist!'); $state.go('index'); } }; $scope.loadContent = function (doc) { //Set the document content $scope.doc.content = Doc.getDocContent({id: doc.id}); $scope.doc.content.$promise.then(function () { $scope.doc.html = $sce.trustAsHtml($scope.doc.content.html); $scope.$broadcast('docContentUpdated');//Broadcast that the body has been updated }); return $scope.doc.content.$promise; }; //Load the introtext if we have one $scope.loadIntrotext = function (doc) { //Set the document introtext if (doc.introtext) { var converter = new Markdown.Converter(); $scope.introtext = $sce.trustAsHtml(converter.makeHtml(doc.introtext)); } }; $scope.checkActiveTab = function () { // Check which tab needs to be active - if the location hash // is #annsubcomment or there is no hash, the annotation/bill tab needs to be active // Otherwise, the hash is #subcomment/#comment and the discussion tab should be active var annotationHash = $location.hash().match(/^annsubcomment_([0-9]+)$/); $scope.secondtab = false; if (!annotationHash && ($location.hash())) { $scope.secondtab = true; $scope.changeTab('comment'); } else { $scope.changeTab('content'); } }; $scope.changeTab = function (activeTab) { $scope.activeTab = activeTab; }; $scope.attachAnnotator = function (doc, user) { //Grab the doc_content element that we want to attach Annotator to var element = $('#doc_content'); //Use AnnotationService to create / store Annotator and annotations $timeout(function () { annotationService.createAnnotator(element, doc, user); }); }; $scope._updateSupport = function (data) { $scope.doc.support = data.supports; $scope.doc.oppose = data.opposes; $scope.voted = data.support === null ? false : true; $scope.$broadcast('supportUpdated'); //Parse data to see what user's action is currently if (data.support === null) { $scope.supported = false; $scope.opposed = false; } else { $scope.supported = data.support; $scope.opposed = !data.support; } }; $scope._calculateSupport = function () { $scope.doc.support_percent = 0; if ($scope.doc.support > 0) { $scope.doc.support_percent = Math.round($scope.doc.support * 100 / ($scope.doc.support + $scope.doc.oppose)); } $scope.doc.oppose_percent = 0; if ($scope.doc.oppose > 0) { $scope.doc.oppose_percent = Math.round($scope.doc.oppose * 100 / ($scope.doc.support + $scope.doc.oppose)); } }; /** * Executed on controller initialization */ //Load annotations $scope.$on('annotationsUpdated', function () { $scope.annotations = annotationService.annotations; //Check that we have a direct annotation link if ($location.$hash) { $scope.evalAsync(function () { $anchorScroll(); }); } }); $scope.$on('supportUpdated', function () { $scope._calculateSupport(); }); //Load the document $scope.doc = Doc.getDocBySlug({slug: $stateParams.slug}); //After loading the document $scope.doc.$promise.then(function (doc) { pageService.setTitle($translate.instant('content.document.title', {title: SITE.name, docTitle: doc.title})); $scope.setSponsor(); $scope.getSupported(); $scope.checkExists(doc);//Redirect if document doesn't exist //Load content. Then attach annotator. $scope.loadContent(doc).then(function () { $scope.attachAnnotator($scope.doc, $scope.user); }); if(typeof $scope.doc.comments === 'undefined') { $scope.doc.comments = []; } //Load introduction section from sponsor $scope.loadIntrotext(doc);//Load the document introduction text //Check if we're linking to the discussion tab $scope.checkActiveTab($scope.doc, $scope.user); /*jslint unparam: true*/ $scope.$on('tocAdded', function (event, toc) { $scope.toc = toc; }); /*jslint unparam: false*/ //When the session is changed, re-attach annotator $scope.$on('sessionChanged', function () { $scope.attachAnnotator($scope.doc, $scope.user); }); $scope._calculateSupport(); }); }]);
OpinionWise/madison
public/js/controllers/documentPageController.js
JavaScript
gpl-3.0
7,175
import React from 'react'; import Header from '../components/Header'; import Mainstage from '../components/Mainstage'; import * as KeyboardActions from '../actions/KeyboardActions'; import NavigationStore from '../stores/NavigationStore'; import TypographyStore from '../stores/TypographyStore'; export default class Dmlf extends React.Component { constructor(props) { super(props); this.state = { mounted: false, content: {}, page: 0, fontFactor: 2 }; } componentWillMount() { NavigationStore.on('experience:navigate', (obj) => { switch (obj.direction) { case 'prev': this.prev(this.props); break; case 'next': this.next(this.props); break; } }); TypographyStore.on('experience:fontfactor', (obj) => { this.setState({ fontFactor: obj.value }); }); } componentDidMount() { this.setState({ mounted: true }); window.addEventListener('keyup', (evt) => { const prevKeys = ['arrowleft', 'arrowup', 'p', 'b']; if (prevKeys.indexOf(evt.key.toLowerCase()) >= 0) { KeyboardActions.navigate({direction: 'prev'}); } const nextKeys = ['arrowright', 'arrowdown', 'n', 'f']; if (nextKeys.indexOf(evt.key.toLowerCase()) >= 0) { KeyboardActions.navigate({direction: 'next'}); } const fontFactorKeys = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']; if (fontFactorKeys.indexOf(evt.key.toLowerCase()) >= 0) { KeyboardActions.fontfactor({value: parseInt(evt.key.toLowerCase(), 10)}); } }); } componentWillUnmount() { this.setState({ mounted: false }); } prev() { if (this.state.page === 0) { return; } this.setState({ page: this.state.page - 1 }); } next(props) { if (this.state.page === props.content.pages.length - 1) { return; } this.setState({ page: this.state.page + 1 }); } render() { return ( <div class={[ "dmlf", ].join(' ')} ref={(experience) => {this.experience = experience}} > <Header addclass="header-experience" type="1" text={this.props.content.pages[this.state.page].heading} fontfactor={this.state.fontFactor} /> <Mainstage config={this.state.config} fontfactor={this.state.fontFactor} content={this.props.content.pages[this.state.page]} page={this.state.page} /> <div className="btn-group horizontal"> <button class="btn btn-prev" onClick={this.prev.bind(this, this.props)} >{this.props.content.buttons.prev}</button> <button class="btn btn-next" onClick={this.next.bind(this, this.props)} >{this.props.content.buttons.next}</button> </div> </div> ); } }
storfarmand/dmlf
scripts/experiences/Dmlf.js
JavaScript
gpl-3.0
2,981
var methods = ["isa100.getSystemStatus", "user.logout"]; function InitSystemStatusPage() { SetPageCommonElements() InitJSON(); GetData(); start(); //start counter } function GetData() { var response; try { var service = new jsonrpc.ServiceProxy(serviceURL, methods); response = service.isa100.getSystemStatus(); } catch(e) { HandleException(e, "Unexpected error reading System Status !"); return; } var spnBackboneStatus = document.getElementById("spnBackboneStatus"); var spnGatewayStatus = document.getElementById("spnGatewayStatus"); var spnNetworkManagerStatus = document.getElementById("spnNetworkManagerStatus"); var spnMODBUSStatus = document.getElementById("spnMODBUSStatus"); var spnMonitorHostStatus = document.getElementById("spnMonitorHostStatus"); for (var i=0; i<response.processes.length; i++) { if(response.processes[i].name == "AccessPoint") { if(response.processes[i].status != "Running") { spnBackboneStatus.className = "opResultRed"; } else { spnBackboneStatus.className = "opResultGreen"; } spnBackboneStatus.innerHTML = response.processes[i].status; document.getElementById("spnBackboneMemory").innerHTML = roundNumber(response.processes[i].memKb / 1024, 2) + " MB (" + (100 * response.processes[i].memKb / response.sysMemTotalKb).toFixed(2) + "%)"; document.getElementById("spnBackboneProcessor").innerHTML = response.processes[i].processorUsage + " %"; } if(response.processes[i].name == "Gateway") { if(response.processes[i].status != "Running") { spnGatewayStatus.className = "opResultRed"; } else { spnGatewayStatus.className = "opResultGreen"; } spnGatewayStatus.innerHTML = response.processes[i].status; document.getElementById("spnGatewayMemory").innerHTML = roundNumber(response.processes[i].memKb / 1024, 2) + " MB (" + (100 * response.processes[i].memKb / response.sysMemTotalKb).toFixed(2) + "%)"; document.getElementById("spnGatewayProcessor").innerHTML = response.processes[i].processorUsage + " %"; } if(response.processes[i].name == "NetworkManager") { if(response.processes[i].status != "Running") { spnNetworkManagerStatus.className = "opResultRed"; } else { spnNetworkManagerStatus.className = "opResultGreen"; } spnNetworkManagerStatus.innerHTML = response.processes[i].status; document.getElementById("spnNetworkManagerMemory").innerHTML = roundNumber(response.processes[i].memKb / 1024, 2) + " MB (" + (100 * response.processes[i].memKb / response.sysMemTotalKb).toFixed(2) + "%)"; document.getElementById("spnNetworkManagerProcessor").innerHTML = response.processes[i].processorUsage + " %"; } if(response.processes[i].name == "MODBUS") { if(response.processes[i].status != "Running") { spnMODBUSStatus.className = "opResultRed"; } else { spnMODBUSStatus.className = "opResultGreen"; } spnMODBUSStatus.innerHTML = response.processes[i].status; document.getElementById("spnMODBUSMemory").innerHTML = roundNumber(response.processes[i].memKb / 1024, 2) + " MB (" + (100 * response.processes[i].memKb / response.sysMemTotalKb).toFixed(2) + "%)"; document.getElementById("spnMODBUSProcessor").innerHTML = response.processes[i].processorUsage + " %"; } if(response.processes[i].name == "MonitorHost") { if(response.processes[i].status != "Running") { spnMonitorHostStatus.className = "opResultRed"; } else { spnMonitorHostStatus.className = "opResultGreen"; } spnMonitorHostStatus.innerHTML = response.processes[i].status; document.getElementById("spnMonitorHostMemory").innerHTML = roundNumber(response.processes[i].memKb / 1024, 2) + " MB (" + (100 * response.processes[i].memKb / response.sysMemTotalKb).toFixed(2) + "%)"; document.getElementById("spnMonitorHostProcessor").innerHTML = response.processes[i].processorUsage + " %"; } } document.getElementById("spnSystemMemoryTotal").innerHTML = roundNumber(response.sysMemTotalKb / 1024, 2) + " MB"; document.getElementById("spnSystemMemoryUsed").innerHTML = roundNumber((response.sysMemTotalKb - response.sysMemFreeKb) / 1024, 2) + " MB (" + (100 * (response.sysMemTotalKb - response.sysMemFreeKb) / response.sysMemTotalKb).toFixed(2) + "%)"; document.getElementById("spnSystemMemoryFree").innerHTML = roundNumber(response.sysMemFreeKb / 1024, 2) + " MB (" + (100 * response.sysMemFreeKb / response.sysMemTotalKb).toFixed(2) + "%)"; document.getElementById("spnFlashMemoryTotal").innerHTML = roundNumber(response.sysFlashTotalKb / 1024, 2)+ " MB"; document.getElementById("spnFlashMemoryUsed").innerHTML = roundNumber((response.sysFlashTotalKb - response.sysFlashFreeKb) / 1024, 2) + " MB (" + (100 * (response.sysFlashTotalKb - response.sysFlashFreeKb) / response.sysFlashTotalKb).toFixed(2) + "%)"; document.getElementById("spnFlashMemoryFree").innerHTML = roundNumber(response.sysFlashFreeKb / 1024, 2) + " MB (" + (100 * response.sysFlashFreeKb / response.sysFlashTotalKb).toFixed(2) + "%)"; document.getElementById("spnLoadAverage").innerHTML = response.load; }
irares/WirelessHart-Gateway
MCSWebsite/scripts/systemstatus.js
JavaScript
gpl-3.0
5,655
var colors = require('colors'); var _ = require('lodash'); var async = require('async'); var Store = require('./store.js'); var download = require('./download.js'); var init = function() { var json = {}; var currentYear = (new Date()).getFullYear(); var thatYear = 2009; async.whilst( function() { return thatYear <= currentYear; }, function(cb) { console.log(('start download the Google Summer of Code\'s projects list for ' + thatYear).cyan); download(json, thatYear, function(){ console.log(('finished download the Google Summer of Code\'s projects list for ' + thatYear).green); thatYear += 1; cb(); }); }, function(err){ if (err) { throw err; } Store.setData(json); } ); }; var buildResult = function(projects, keys) { var res = {}; for (var i = 0; i < keys.length; i++) { res[keys[i]] = projects[keys[i]]; } return res; }; /* * filter given array of keys with a name. remain those keys contains the name. * case-insentient. * * @param {Array} keys * @param {String} name */ var filterKeysWithName = function(keys, name) { keys = keys.filter(function(key){ // case-insentient name = name.trim().toLowerCase(); return name && key.toLowerCase().indexOf(name) != -1; }); return keys; }; var listName = function(projects, name) { return filterKeysWithName(Object.keys(projects), name); }; /* * list projects have **all** given tags * * @param {Object} tags - tags contains many tags with relative projects * @param {Array} tagList - a list of tags */ var listTag = function(tags, tagList) { var projects; if (!tagList || !tagList.length) { return []; } var projectsContainKeys = tags[tagList[0]]; for (var i = 1; i < tagList.length; i++) { // case-insentient projects = tags[(tagList[i]).toLowerCase()]; projectsContainKeys = _.intersection(projectsContainKeys, projects); } // if tags[tagList[0]] is undefined and tagList.length === 1 if (!projectsContainKeys) { projectsContainKeys = []; } return projectsContainKeys; }; // {Number or Array with 2 elements} year // {String} name // {Array} tags var searchProjects = function(year, name, cb) { Store.getData(function(data) { if (typeof(year) === typeof([])) { var thatYear = year[0]; var names = listName(data[thatYear].projects, name); var lastYear = year[1]; var otherNames = []; var contains = function(e){ return otherNames.indexOf(e) != -1; }; while (names.length && thatYear != lastYear) { thatYear += 1; otherNames = listName(data[thatYear].projects, name); names = names.filter(contains); } cb( buildResult(data[lastYear].projects, names) ); } else { cb( buildResult(data[year].projects, listName(data[year].projects, name)) ); } }); }; var searchProjectsWithTags = function(year, name, tagList, cb) { var keys; Store.getData(function(data) { if (typeof(year) === typeof([])) { var thatYear = year[0]; keys = listTag(data[thatYear].tags, tagList); var lastYear = year[1]; var otherKeys = []; var contains = function(e){ return otherKeys.indexOf(e) != -1; }; while (keys.length && thatYear != lastYear) { thatYear += 1; otherKeys = listTag(data[thatYear].tags, tagList); keys = keys.filter(contains); } keys = filterKeysWithName(keys, name); cb( buildResult(data[lastYear].projects, keys) ); } else { keys = filterKeysWithName(listTag(data[year].tags, tagList), name); cb( buildResult(data[year].projects, keys)); } }); }; var searchTags = function(year, tagList, cb) { Store.getData(function(data) { if (typeof(year) === typeof([])) { var thatYear = year[0]; var keys = listTag(data[thatYear].tags, tagList); var lastYear = year[1]; var otherKeys = []; var contains = function(e){ return otherKeys.indexOf(e) != -1; }; while (keys.length && thatYear != lastYear) { thatYear += 1; otherKeys = listTag(data[thatYear].tags, tagList); keys = keys.filter(contains); } cb( buildResult(data[lastYear].projects, keys) ); } else { cb( buildResult(data[year].projects, listTag(data[year].tags, tagList)) ); } }); }; var getProjectsList = function(year, cb) { var data = Store.getData(function(data){ if (typeof(year) === typeof([])) { var thatYear = year[0]; var names = Object.keys(data[thatYear].projects); var lastYear = year[1]; var otherNames = []; var contains = function(e, i){ return otherNames.indexOf(names[i]) != -1; }; while (names.length && thatYear != lastYear) { thatYear += 1; otherNames = Object.keys(data[thatYear].projects); names = names.filter(contains); } cb( buildResult(data[lastYear].projects, names) ); } else { cb(data[year].projects); } }); }; module.exports = { init: init, searchProjects: searchProjects, searchProjectsWithTags: searchProjectsWithTags, searchTags: searchTags, getProjectsList: getProjectsList };
spacewander/GSoC
lib/GSoC.js
JavaScript
gpl-3.0
5,394
import AIHandler from '@/classes/AIHandler/AIHandler' import PlayBestCard from '@/classes/AIHandler/PlayBestCard' import PlayRandomCard from '@/classes/AIHandler/PlayRandomCard' // card orders for different AI personalities const CARD_ORDER = { standard: [ "INSTRUCTION", "METHOD", "VARIABLE", "REPEAT", "SORT", "SEARCH", "ANTIVIRUS", "FIREWALL", "SCAN", "SQL_INJECTION", "RANSOM", "TROJAN", "VIRUS", "STACK_OVERFLOW", "DDOS", "STACK_UNDERFLOW", "SEARCH" ], aggresive: [ "SORT", "SEARCH", "STACK_OVERFLOW", "VIRUS", "SQL_INJECTION", "RANSOM", "TROJAN", "DDOS", "STACK_UNDERFLOW", "VARIABLE", "REPEAT", "INSTRUCTION", "METHOD", "FIREWALL", "ANTIVIRUS", "SCAN" ], defensive: [ "SORT", "SEARCH", "FIREWALL", "ANTIVIRUS", "SCAN", "METHOD", "VARIABLE", "REPEAT", "INSTRUCTION", "STACK_OVERFLOW", "TROJAN", "VIRUS", "RANSOM", "SQL_INJECTION", "DDOS", "STACK_UNDERFLOW" ] } /** * A factory to create different types of AIHandlers. */ class AIHandlerFactory { /** * Create and return an AIHandler with the given personality. * @param {string} personality - The personality for the handler to use. * @return {AIHandler} The new AIHandler. */ newHandler (personality) { if (personality === 'beginner') { return this._newBeginnerHandler() } else { return this._newStandardHandler(personality) } } /** * Creates a new standard handler with the given personality (card priority list name). * @private */ _newStandardHandler (personality) { let actions = [] let cards = CARD_ORDER.standard if (personality in CARD_ORDER) { cards = CARD_ORDER[personality] } actions.push( new PlayBestCard(cards) ) let handler = new AIHandler(actions) return handler } /** * Creates a new beginner AIHandler with just the PlayRandomCard action handler. * @private */ _newBeginnerHandler () { return new AIHandler([new PlayRandomCard()]) } } export default AIHandlerFactory;
johnanvik/program-wars
src/classes/AIHandler/AIHandlerFactory.js
JavaScript
gpl-3.0
2,009
Template.arfcnBands.helpers({ count: function(){ return ARFCNBands.ARFCNBands.find().count() } });
He3556/SDR-Detector
client/templates/arfcn-bands/arfcnBands.js
JavaScript
gpl-3.0
107
/* Developed with the contribution of the European Commission - Directorate General for Maritime Affairs and Fisheries © European Union, 2015-2016. This file is part of the Integrated Fisheries Data Management (IFDM) Suite. The IFDM Suite 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 any later version. The IFDM Suite 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 the IFDM Suite. If not, see <http://www.gnu.org/licenses/>. */ describe('GetListRequest', function() { beforeEach(module('unionvmsWeb')); it('should set correct values from the start with empty constructor', inject(function(GetListRequest) { var getListRequest = new GetListRequest(); expect(getListRequest.listSize).toEqual(10); expect(getListRequest.page).toEqual(1); expect(getListRequest.isDynamic).toEqual(true); expect(getListRequest.criterias).toEqual([]); })); it('should set correct values from the start', inject(function(GetListRequest, SearchField) { var searchField1 = new SearchField("NAME", "TEST"), searchField2 = new SearchField("COUNTRY", "Swe"), criterias = [searchField1, searchField2], listSize = 15, page = 2, dynamic = false; var getListRequest = new GetListRequest(page, listSize, dynamic, criterias); expect(getListRequest.listSize).toEqual(listSize); expect(getListRequest.page).toEqual(page); expect(getListRequest.isDynamic).toEqual(dynamic); expect(getListRequest.criterias.length).toEqual(criterias.length); })); /** * it should look like: * {pagination: {listSize: "10", page: "1"}, searchCriteria: {criterias: [], isDynamic: "true"}} * */ it('toJson should return correctly formatted data', inject(function(GetListRequest, SearchField) { var searchField1 = new SearchField("NAME", "TEST"), searchField2 = new SearchField("COUNTRY", "Swe"), criterias = [searchField1, searchField2], listSize = 15, page = 2, dynamic = false; var getListRequest = new GetListRequest(page, listSize, dynamic, criterias); var toJsonObject = JSON.parse(getListRequest.toJson()); expect(toJsonObject.pagination.listSize).toEqual(listSize); expect(toJsonObject.pagination.page).toEqual(page); expect(toJsonObject.searchCriteria.isDynamic).toEqual(dynamic); expect(angular.equals(toJsonObject.searchCriteria.criterias, criterias)).toBeTruthy(); })); it('DTOForMobileTerminal should return correctly formatted data', inject(function(GetListRequest, SearchField) { var searchField1 = new SearchField("NAME", "TEST"), searchField2 = new SearchField("COUNTRY", "Swe"), criterias = [searchField1, searchField2], listSize = 15, page = 2, dynamic = false; var getListRequest = new GetListRequest(page, listSize, dynamic, criterias); var DTO = getListRequest.DTOForMobileTerminal(); expect(DTO.pagination.listSize).toEqual(listSize); expect(DTO.pagination.page).toEqual(page); expect(DTO.mobileTerminalSearchCriteria.isDynamic).toEqual(dynamic); expect(DTO.mobileTerminalSearchCriteria.criterias.length).toBe(2); expect(DTO.mobileTerminalSearchCriteria.criterias[0].key).toBe("NAME"); expect(DTO.mobileTerminalSearchCriteria.criterias[0].value).toBe("TEST*"); expect(DTO.mobileTerminalSearchCriteria.criterias[1].key).toBe("COUNTRY"); expect(DTO.mobileTerminalSearchCriteria.criterias[1].value).toBe("Swe"); })); it('setPage should set correct page', inject(function(GetListRequest) { var getListRequest = new GetListRequest(); getListRequest.setPage(5); expect(getListRequest.page).toEqual(5); })); it('addSearchCriteria to add a search criteria to the list', inject(function(GetListRequest) { var getListRequest = new GetListRequest(); expect(getListRequest.criterias.length).toEqual(0); //Add criteria 1 getListRequest.addSearchCriteria("NAME", "TEST"); expect(getListRequest.criterias.length).toEqual(1); //Add criteria 2); getListRequest.addSearchCriteria("COUNTRY", "Swe"); expect(getListRequest.criterias.length).toEqual(2); })); it('removeSearchCriteria to remove a search criteria from the list', inject(function(GetListRequest) { var getListRequest = new GetListRequest(); //Add criterias getListRequest.addSearchCriteria("NAME", "TEST"); getListRequest.addSearchCriteria("COUNTRY", "Swe"); getListRequest.addSearchCriteria("IRCS", "ABCD123"); expect(getListRequest.criterias.length).toEqual(3, "Should be 3 search criterias before removeing one"); //remove country search criteria getListRequest.removeSearchCriteria("COUNTRY"); expect(getListRequest.criterias.length).toEqual(2, "Should be 2 search criterias after removing one"); expect(getListRequest.criterias[0].key).toEqual("NAME"); expect(getListRequest.criterias[1].key).toEqual("IRCS"); })); it('setSearchCriteria should set the search criteria list', inject(function(GetListRequest, SearchField) { var getListRequest = new GetListRequest(); var searchField0 = new SearchField("NAME", "TADA"); getListRequest.addSearchCriteria(searchField0); expect(getListRequest.criterias.length).toEqual(1); var searchField1 = new SearchField("NAME", "TEST"), searchField2 = new SearchField("COUNTRY", "Swe"), criterias = [searchField1, searchField2]; getListRequest.setSearchCriterias(criterias); expect(getListRequest.criterias.length).toEqual(2); expect(getListRequest.criterias[0]).toEqual(searchField1); })); it('resetCriterias to remove all search criterias from the list', inject(function(GetListRequest, SearchField) { var searchField1 = new SearchField("NAME", "TEST"), searchField2 = new SearchField("COUNTRY", "Swe"), criterias = [searchField1, searchField2]; var getListRequest = new GetListRequest(1, 10, false, criterias); expect(getListRequest.criterias.length).toEqual(2); //Reset criterias getListRequest.resetCriterias(); expect(getListRequest.criterias.length).toEqual(0); })); it('setDynamicToFalse should set dynamic to false', inject(function(GetListRequest) { var getListRequest = new GetListRequest(); expect(getListRequest.isDynamic).toEqual(true); getListRequest.setDynamicToFalse(); expect(getListRequest.isDynamic).toEqual(false); })); it('setDynamicToTrue should set dynamic to true', inject(function(GetListRequest) { var getListRequest = new GetListRequest(); getListRequest.setDynamicToFalse(); expect(getListRequest.isDynamic).toEqual(false); getListRequest.setDynamicToTrue(); expect(getListRequest.isDynamic).toEqual(true); })); });
UnionVMS/UVMS-Frontend
app/service/common/model/getListRequestModel-spec.js
JavaScript
gpl-3.0
7,224
/* Copyright (c) 2015-2016 The Open Source Geospatial Foundation * * 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, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** * Data model holding an OpenLayers feature (`ol.Feature`). * * @class GeoExt.data.model.Feature */ Ext.define('GeoExt.data.model.Feature', { extend: 'GeoExt.data.model.OlObject', /** * Returns the underlying `ol.Feature` of this record. * * @return {ol.Feature} The underlying `ol.Feature`. */ getFeature: function() { return this.olObject; } });
eoss-cloud/madxxx_catalog_client
extgui/packages/remote/GeoExt/src/data/model/Feature.js
JavaScript
gpl-3.0
1,119
/* --------------------------------------------------- By Pellgrain - 05/04/2016 Page de chat --------------------------------------------------- */ var encap = require('./util/encap'); // Hérite de l'objet page var page = require('./util/page'); var p = new page(); // Code spécifique p.scriptFileList.push('/socket.io/socket.io.js'); p.scriptFileList.push('/clientScript/chatClient.js'); // Nav p.url = '/chat'; p.navName = 'Chat'; p.addToNav(); p.title = 'Chat'; p.header = { toString: function(){ var response = new encap(). h1('Chater avec des gens'); return response.content; }}; p.section = { toString: function(){ var response = new encap(). h2('Raconte des trucs !'). p('Ceci est un chat en direct avec des gens. Attention, aucune vérification n\'est faite sur l\'authenticité des utilisateurs.'). p('Ton pseudo : <b><span id="pseudoIHM"></span></b>.'). p('<span id="nbUserIHM"></span> connecté.'). raw('<div id="chatArea" class="cadreText"></div>'). raw('<input type="text" id="messageField" class="textInput" onkeypress="touche(event)"></input>'); return response.content; }}; module.exports.out = function(){return p.out();}; module.exports.url = p.url;
VivienGaluchot/NodeProject
pages/chat.js
JavaScript
gpl-3.0
1,193
var searchData= [ ['name_5fstring',['name_string',['../strutture__dati_8h.html#a0229c622e2f5ffe85ce727c022a9442f',1,'strutture_dati.h']]], ['numbering_5fstring',['numbering_string',['../strutture__dati_8h.html#a84f11ad7f630d06f905b5353288a42ac',1,'strutture_dati.h']]] ];
broskh/SpaceInvaders
doc/html/search/typedefs_1.js
JavaScript
gpl-3.0
276
App = function() { "use strict"; /* <!-- DEPENDS on JQUERY to work, but not to initialise --> */ /* <!-- Returns an instance of this if required --> */ if (this && this._isF && this._isF(this.App)) return new this.App().initialise(this); /* <!-- Internal Constants --> */ const ID = "Debug_Tests"; /* <!-- Internal Constants --> */ /* <!-- Internal Variables --> */ var ಠ_ಠ, _total = 0, _succeeded = 0, _running = 0; /* <!-- Internal Variables --> */ /* <!-- Internal Functions --> */ const RANDOM = (lower, higher) => Math.random() * (higher - lower) + lower, GENERATE = { d: () => chance.date(), b: p => chance.bool({ likelihood: p ? p : 50 }), s: l => l === undefined ? chance.string() : chance.string({ length: l }), p: (l, p) => chance.string( _.extend(l === undefined ? {} : { length: l }, p === undefined ? {} : { pool: p })), a: l => GENERATE.p(l, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), n: l => GENERATE.p(l, "0123456789"), an: l => GENERATE.p(l, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"), t: l => GENERATE.p(l, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 _-.,:;()!?'"), f: (min, max, fixed) => min === undefined || max === undefined ? chance.floating : chance.floating({ min: min, max: max, fixed: fixed !== undefined ? fixed : 2, }), i: (min, max) => min === undefined || max === undefined ? chance.integer : chance.integer({ min: min, max: max }), c: () => GENERATE.p(6, "0123456789abcdef"), cn: (min, max) => `rgb(${GENERATE.i(min, max ? max : 255)},${GENERATE.i(min, max ? max : 255)},${GENERATE.i(min, max ? max : 255)})`, ca: alpha => `rgba(${GENERATE.i(0, 255)},${GENERATE.i(0, 255)},${GENERATE.i(0, 255)},${alpha === undefined ? GENERATE.f(0, 1, 2) : alpha})`, o: array => array[GENERATE.i(0, array.length - 1)], }, ARRAYS = value => value === undefined || value === null ? [] : _.isArray(value) ? value : [value], SIMPLIFY = value => value && _.isArray(value) && value.length === 1 ? value[0] : value, NUMBER = /^\+?[1-9][\d]*$/; var _promisify = (fn, value) => new Promise(resolve => resolve(fn ? ಠ_ಠ._isF(fn) ? fn(value) : fn : true)); var _update = (result, expected) => { _running -= 1; var _success = (result === (expected ? /^\s*(false|0)\s*$/i.test(expected) ? false : _.isString(expected) ? expected.toLowerCase() : true : true)); _succeeded += _success ? 1 : 0; $(`#${ID}_counter .content`) .html(`${_succeeded}/${_total} <strong>${Math.round(_succeeded/_total*100)}%</strong>`) .toggleClass("text-success", _succeeded == _total); return _success; }; var _click = buttons => Promise.each(_.map(buttons, button => () => new Promise((resolve, reject) => { var running, observer = new MutationObserver((mutationsList, observer) => { for (var mutation of mutationsList) { if (mutation.type == "attributes" && mutation.attributeName == "class") { if (button.classList.contains("loader")) { running = true; } else if (running) { if (button.classList.contains("success")) { observer.disconnect(); resolve(); } else if (button.classList.contains("failure")) { observer.disconnect(); reject(); } } } } }); observer.observe(button, { attributes: true }); var _scroll = $(button).closest(".row").offset().top - $(".row.sticky-top").outerHeight(); if (typeof _scroll === "number" && isFinite(_scroll) && _scroll > 10) $([document.documentElement, document.body]).scrollTop(_scroll - 10); button.click(); }))); var _all = (module, id, times) => { var _this = $(`#${id}`), _buttons = _this.parent().siblings("a.btn").toArray(); ಠ_ಠ.Flags.log("TEST BUTTONS:", _buttons); /* <!-- Clear the status and indicate busy status --> */ _this.removeClass("success failure").addClass("loader disabled").find("i.result").addClass("d-none"); /* <!-- Not returning as we are using a Singleton Router (for testing), which doesn't allow us to run parallel routes! --> */ new Promise((resolve, reject) => { (times && times > 1 ? Promise.each(_.map(_.range(0, times), () => () => _click(_buttons))) : _click(_buttons)) .then(() => { _this.removeClass("loader disabled").addClass("success") .find("i.result-success").removeClass("d-none"); resolve(); }) .catch(() => { _this.removeClass("loader disabled").addClass("failure") .find("i.result-failure").removeClass("d-none"); reject(); }); }); }; var _one = (module, test, id, expected) => { /* <!-- Check we have a module and a button --> */ var _module = ಠ_ಠ._tests[module], _id = $(`#${id}`); if (!_module || _id.length === 0) return; /* <!-- Clear the status and indicate busy status --> */ _id.removeClass("success failure").addClass("loader disabled").find("i.result").addClass("d-none"); /* <!-- Instatiate the Module if required, and call all relevant methods --> */ _module = ಠ_ಠ._isF(_module) ? _module.call(ಠ_ಠ) : _module; var _start = _module.start, _finish = _module.finish, _command = _module[test], _result; /* <!-- Increment the total tests run counter --> */ _total += 1; /* <!-- Used to set overall success --> */ var _outcome; _promisify(_start) .then(value => _promisify(_command, value)) .then(result => { result = _.isArray(result) ? _.reduce(result, (outcome, result) => outcome === false || result === false ? false : result, null) : result; _outcome = _update((_result = result), expected); return _promisify(_finish, { test: test, result: _result }); }) .catch(e => { _outcome = _update("error", expected); ಠ_ಠ.Flags.error(`Module: ${module} | Test: ${test}`, e); }) .then(() => _id.removeClass("loader disabled") .addClass(_outcome ? "success" : "failure") .find(`i.result-${_result ? "success" : "failure"}`) .removeClass("d-none")); }; var _run = (module, test, id, expected) => test == "__all" ? _all(module, id, expected && NUMBER.test(expected) ? parseInt(expected, 10) : null) : (_running += 1) && _one(module, test, id, expected); var _everything = () => { var _this = $("#____run_everything"), _buttons = $(".btn.test-all").toArray(); ಠ_ಠ.Flags.log("ALL TEST BUTTONS:", _buttons); /* <!-- Clear the status and indicate busy status --> */ _this.removeClass("success failure").addClass("loader disabled").find("i.result").addClass("d-none"); /* <!-- Not returning as we are using a Singleton Router (for testing), which doesn't allow us to run parallel routes! --> */ _click(_buttons) .then(() => _this.removeClass("loader disabled").addClass("success") .find("i.result-success").removeClass("d-none")) .catch(() => _this.removeClass("loader disabled").addClass("failure") .find("i.result-failure").removeClass("d-none")); }; /* <!-- Internal Functions --> */ /* <!-- Overridable Configuration --> */ var _hooks = { start: [], test: [], clear: [], route: [], routes: { __loud: { matches: /LOUD/i, length: 0, fn: () => ಠ_ಠ.Display.state().toggle("traces") }, __run_all: { matches: [/RUN/i, /ALL/i], length: 0, fn: _everything, }, __run_test: { matches: /RUN/i, length: { min: 3, max: 4 }, fn: command => _run.apply(this, command), }, }, singleton: null }; /* <!-- Overridable Configuration --> */ /* <!-- External Visibility --> */ return { /* <!-- External Functions --> */ initialise: function(container) { /* <!-- Get a reference to the Container --> */ ಠ_ಠ = container; /* <!-- Set Container Reference to this --> */ container.App = this; /* <!-- Initialise all the test modules --> */ for (var test in ಠ_ಠ._tests) ಠ_ಠ._tests[test] = ಠ_ಠ._tests[test].call(ಠ_ಠ); /* <!-- Set Up the Default Router --> */ this.route = ಠ_ಠ.Router.create({ name: "Debug", recent: false, simple: true, singular: true, start: () => { ಠ_ಠ.Display.template.show({ template: "host", id: ID, target: ಠ_ಠ.container, instructions: ಠ_ಠ.Display.doc.get({ name: "INSTRUCTIONS" }), run_all: ಠ_ಠ.Display.doc.get({ name: "RUN_ALL" }), tests: ಠ_ಠ.Display.doc.get({ name: "TESTS" }), clear: !ಠ_ಠ.container || ಠ_ಠ.container.children().length !== 0 }); _.each(_hooks.start, fn => fn()); /* <!-- Handle Highlights --> */ ಠ_ಠ.Display.highlight(); /* <!-- Handle Sticky Scrolling --> */ var _sticky = $(".row.sticky-top"); window.onscroll = () => { var _top = window.pageYOffset > _sticky.height(); _sticky.find(".hidable").toggleClass("hidden", _top); _sticky.toggleClass("top", _top); }; return true; }, test: () => { _.each(_hooks.test, fn => fn()); return false; }, clear: () => { _.each(_hooks.clear, fn => fn()); return true; }, routes: _hooks.routes, route: (handled, command) => { _.each(_hooks.route, fn => fn(handled, command)); return true; }, }); /* <!-- Return for Chaining --> */ return this; }, hooks: _hooks, delay: ms => new Promise(resolve => setTimeout(resolve, ms)), race: time => promise => { var _timeout, _time = time ? time : 1000; var _success = val => { clearTimeout(_timeout); return Promise.resolve(val); }, _failure = err => { clearTimeout(_timeout); return Promise.reject(err); }; return Promise.race([ promise.then(_success).catch(_failure), new Promise((resolve, reject) => _timeout = setTimeout(() => reject(new Error(`Debug Test Timed Out after running for ${_time} ms`)), _time)) ]); }, running: _running, /* <!-- Helper Functions --> */ arrays: ARRAYS, generate: GENERATE, random: RANDOM, simplify: SIMPLIFY, /* <!-- Helper Functions --> */ }; };
Educ-IO/educ-io.github.io
_includes/apps/debug.js
JavaScript
gpl-3.0
11,122
var searchData= [ ['cachedutilities',['CachedUtilities',['../classpstat_1_1_cached_utilities.html',1,'pstat']]], ['cachedutilities',['CachedUtilities',['../classpstat_1_1_cached_utilities.html#a81ef2e6118c5be2a3100f41cc0a93fb4',1,'pstat::CachedUtilities']]], ['concurrent_5fqueue',['concurrent_queue',['../classtbb_1_1concurrent__queue.html',1,'tbb']]], ['concurrent_5fqueue_3c_20std_3a_3apair_3c_20std_3a_3astring_2c_20starrec_20_3e_20_3e',['concurrent_queue&lt; std::pair&lt; std::string, StarRec &gt; &gt;',['../classtbb_1_1concurrent__queue.html',1,'tbb']]], ['concurrent_5fqueue_3c_20std_3a_3astring_20_3e',['concurrent_queue&lt; std::string &gt;',['../classtbb_1_1concurrent__queue.html',1,'tbb']]], ['concurrent_5funordered_5fmap',['concurrent_unordered_map',['../classtbb_1_1concurrent__unordered__map.html',1,'tbb']]], ['concurrent_5funordered_5fmap_3c_20gid_5ft_2c_20std_3a_3astring_20_3e',['concurrent_unordered_map&lt; gid_t, std::string &gt;',['../classtbb_1_1concurrent__unordered__map.html',1,'tbb']]], ['concurrent_5funordered_5fmap_3c_20time_5ft_2c_20std_3a_3astring_20_3e',['concurrent_unordered_map&lt; time_t, std::string &gt;',['../classtbb_1_1concurrent__unordered__map.html',1,'tbb']]], ['concurrent_5funordered_5fmap_3c_20uid_5ft_2c_20std_3a_3astring_20_3e',['concurrent_unordered_map&lt; uid_t, std::string &gt;',['../classtbb_1_1concurrent__unordered__map.html',1,'tbb']]] ];
ParallelMazen/pstat
docs/html/search/all_0.js
JavaScript
gpl-3.0
1,420
/// <autosync enabled="true" /> /// <reference path="js/app.js" /> /// <reference path="js/controllers/about_ctr.js" /> /// <reference path="js/controllers/assist_ctr.js" /> /// <reference path="js/controllers/climate_history_ctr.js" /> /// <reference path="js/controllers/crop_forecast_ctr.js" /> /// <reference path="js/controllers/crop_history_ctr.js" /> /// <reference path="js/controllers/expert_ctr.js" /> /// <reference path="js/controllers/glossary_ctr.js" /> /// <reference path="js/controllers/location_ctr.js" /> /// <reference path="js/controllers/social_media_ctr.js" /> /// <reference path="js/controllers/sub_menu_ctr.js" /> /// <reference path="js/lib/compatibilty/ie.js" /> /// <reference path="js/lib/d3graphics/bars.js" /> /// <reference path="js/lib/d3graphics/base.js" /> /// <reference path="js/lib/d3graphics/calendar.js" /> /// <reference path="js/lib/d3graphics/calendarheatmap.js" /> /// <reference path="js/lib/d3graphics/line.js" /> /// <reference path="js/lib/d3graphics/pie.js" /> /// <reference path="js/lib/d3graphics/trend.js" /> /// <reference path="js/menu.js" /> /// <reference path="js/seo/analytics.js" /> /// <reference path="js/services/agronomy.js" /> /// <reference path="js/services/assist.js" /> /// <reference path="js/services/climate_climatology.js" /> /// <reference path="js/services/climate_forecast.js" /> /// <reference path="js/services/climate_historical.js" /> /// <reference path="js/services/climate_scenario.js" /> /// <reference path="js/services/crop_vars.js" /> /// <reference path="js/services/crop_yield_forecast.js" /> /// <reference path="js/services/crop_yield_historical.js" /> /// <reference path="js/services/cultivar.js" /> /// <reference path="js/services/forecast_api.js" /> /// <reference path="js/services/geographic.js" /> /// <reference path="js/services/municipality.js" /> /// <reference path="js/services/setup.js" /> /// <reference path="js/services/soil.js" /> /// <reference path="js/services/tutorial.js" /> /// <reference path="js/services/weather_station.js" /> /// <reference path="js/site.min.js" /> /// <reference path="lib/angular/angular.js" /> /// <reference path="lib/angular-cookies/angular-cookies.js" /> /// <reference path="lib/bootstrap/dist/js/bootstrap.js" /> /// <reference path="lib/d3/d3.js" /> /// <reference path="lib/jquery/dist/jquery.js" /> /// <reference path="lib/jquery-validation/dist/jquery.validate.js" /> /// <reference path="lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js" /> /// <reference path="lib/please-wait/build/please-wait.js" /> /// <reference path="lib/select2/dist/js/select2.js" />
CIAT-DAPA/usaid_forecast_web
src/CIAT.DAPA.USAID.Forecast.Web/wwwroot/_references.js
JavaScript
gpl-3.0
2,630
/* * Facebox (for jQuery) * version: 1.2 (05/05/2008) * @requires jQuery v1.2 or later * * Examples at http://famspam.com/facebox/ * * Licensed under the MIT: * http://www.opensource.org/licenses/mit-license.php * * Copyright 2007, 2008 Chris Wanstrath [ chris@ozmm.org ] * * Usage: * * jQuery(document).ready(function() { * jQuery('a[rel*=facebox]').facebox() * }) * * <a href="#terms" rel="facebox">Terms</a> * Loads the #terms div in the box * * <a href="terms.html" rel="facebox">Terms</a> * Loads the terms.html page in the box * * <a href="terms.png" rel="facebox">Terms</a> * Loads the terms.png image in the box * * * You can also use it programmatically: * * jQuery.facebox('some html') * jQuery.facebox('some html', 'my-groovy-style') * * The above will open a facebox with "some html" as the content. * * jQuery.facebox(function($) { * $.get('blah.html', function(data) { $.facebox(data) }) * }) * * The above will show a loading screen before the passed function is called, * allowing for a better ajaxy experience. * * The facebox function can also display an ajax page, an image, or the contents of a div: * * jQuery.facebox({ ajax: 'remote.html' }) * jQuery.facebox({ ajax: 'remote.html' }, 'my-groovy-style') * jQuery.facebox({ image: 'stairs.jpg' }) * jQuery.facebox({ image: 'stairs.jpg' }, 'my-groovy-style') * jQuery.facebox({ div: '#box' }) * jQuery.facebox({ div: '#box' }, 'my-groovy-style') * * Want to close the facebox? Trigger the 'close.facebox' document event: * * jQuery(document).trigger('close.facebox') * * Facebox also has a bunch of other hooks: * * loading.facebox * beforeReveal.facebox * reveal.facebox (aliased as 'afterReveal.facebox') * init.facebox * afterClose.facebox * * Simply bind a function to any of these hooks: * * $(document).bind('reveal.facebox', function() { ...stuff to do after the facebox and contents are revealed... }) * */ (function($) { $.facebox = function(data, klass) { $.facebox.loading() if (data.ajax) fillFaceboxFromAjax(data.ajax, klass) else if (data.image) fillFaceboxFromImage(data.image, klass) else if (data.div) fillFaceboxFromHref(data.div, klass) else if ($.isFunction(data)) data.call($) else $.facebox.reveal(data, klass) } /* * Public, $.facebox methods */ $.extend($.facebox, { settings: { opacity : 0.2, overlay : true, loadingImage : '../base/js/jquery/facebox/loading.gif', closeImage : '../base/js/jquery/facebox/closelabel.png', imageTypes : [ 'png', 'jpg', 'jpeg', 'gif' ], faceboxHtml : '\ <div id="facebox" style="display:none;"> \ <div class="popup"> \ <div class="content"> \ </div> \ <a href="#" class="close"><img src="/facebox/closelabel.png" title="Fechar" class="close_image" /></a> \ </div> \ </div>' }, loading: function() { init() if ($('#facebox .loading').length == 1) return true showOverlay() $('#facebox .content').empty() $('#facebox .body').children().hide().end(). append('<div class="loading"><img src="'+$.facebox.settings.loadingImage+'"/></div>') $('#facebox').css({ top: getPageScroll()[1] + (getPageHeight() / 10), left: $(window).width() / 2 - 205 }).show() $(document).bind('keydown.facebox', function(e) { if (e.keyCode == 27) $.facebox.close() return true }) $(document).trigger('loading.facebox') }, reveal: function(data, klass) { $(document).trigger('beforeReveal.facebox') if (klass) $('#facebox .content').addClass(klass) $('#facebox .content').append(data) $('#facebox .loading').remove() $('#facebox .body').children().fadeIn('normal') $('#facebox').css('left', $(window).width() / 2 - ($('#facebox .popup').width() / 2)) $(document).trigger('reveal.facebox').trigger('afterReveal.facebox') }, close: function() { $(document).trigger('close.facebox') return false } }) /* * Public, $.fn methods */ $.fn.facebox = function(settings) { if ($(this).length == 0) return init(settings) function clickHandler() { $.facebox.loading(true) // support for rel="facebox.inline_popup" syntax, to add a class // also supports deprecated "facebox[.inline_popup]" syntax var klass = this.rel.match(/facebox\[?\.(\w+)\]?/) if (klass) klass = klass[1] fillFaceboxFromHref(this.href, klass) return false } return this.bind('click.facebox', clickHandler) } /* * Private methods */ // called one time to setup facebox on this page function init(settings) { if ($.facebox.settings.inited) return true else $.facebox.settings.inited = true $(document).trigger('init.facebox') makeCompatible() var imageTypes = $.facebox.settings.imageTypes.join('|') $.facebox.settings.imageTypesRegexp = new RegExp('\.(' + imageTypes + ')$', 'i') if (settings) $.extend($.facebox.settings, settings) $('body').append($.facebox.settings.faceboxHtml) var preload = [ new Image(), new Image() ] preload[0].src = $.facebox.settings.closeImage preload[1].src = $.facebox.settings.loadingImage $('#facebox').find('.b:first, .bl').each(function() { preload.push(new Image()) preload.slice(-1).src = $(this).css('background-image').replace(/url\((.+)\)/, '$1') }) $('#facebox .close').click($.facebox.close) $('#facebox .close_image').attr('src', $.facebox.settings.closeImage) } // getPageScroll() by quirksmode.com function getPageScroll() { var xScroll, yScroll; if (self.pageYOffset) { yScroll = self.pageYOffset; xScroll = self.pageXOffset; } else if (document.documentElement && document.documentElement.scrollTop) { // Explorer 6 Strict yScroll = document.documentElement.scrollTop; xScroll = document.documentElement.scrollLeft; } else if (document.body) {// all other Explorers yScroll = document.body.scrollTop; xScroll = document.body.scrollLeft; } return new Array(xScroll,yScroll) } // Adapted from getPageSize() by quirksmode.com function getPageHeight() { var windowHeight if (self.innerHeight) { // all except Explorer windowHeight = self.innerHeight; } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode windowHeight = document.documentElement.clientHeight; } else if (document.body) { // other Explorers windowHeight = document.body.clientHeight; } return windowHeight } // Backwards compatibility function makeCompatible() { var $s = $.facebox.settings $s.loadingImage = $s.loading_image || $s.loadingImage $s.closeImage = $s.close_image || $s.closeImage $s.imageTypes = $s.image_types || $s.imageTypes $s.faceboxHtml = $s.facebox_html || $s.faceboxHtml } // Figures out what you want to display and displays it // formats are: // div: #id // image: blah.extension // ajax: anything else function fillFaceboxFromHref(href, klass) { // div if (href.match(/#/)) { var url = window.location.href.split('#')[0] var target = href.replace(url,'') if (target == '#') return $.facebox.reveal($(target).html(), klass) // image } else if (href.match($.facebox.settings.imageTypesRegexp)) { fillFaceboxFromImage(href, klass) // ajax } else { fillFaceboxFromAjax(href, klass) } } function fillFaceboxFromImage(href, klass) { var image = new Image() image.onload = function() { $.facebox.reveal('<div class="image"><img src="' + image.src + '" /></div>', klass) } image.src = href } function fillFaceboxFromAjax(href, klass) { $.get(href, function(data) { $.facebox.reveal(data, klass) }) } function skipOverlay() { return $.facebox.settings.overlay == false || $.facebox.settings.opacity === null } function showOverlay() { if (skipOverlay()) return if ($('#facebox_overlay').length == 0) $("body").append('<div id="facebox_overlay" class="facebox_hide"></div>') $('#facebox_overlay').hide().addClass("facebox_overlayBG") .css('opacity', $.facebox.settings.opacity) .click(function() { $(document).trigger('close.facebox') }) .fadeIn(200) return false } function hideOverlay() { if (skipOverlay()) return $('#facebox_overlay').fadeOut(200, function(){ $("#facebox_overlay").removeClass("facebox_overlayBG") $("#facebox_overlay").addClass("facebox_hide") $("#facebox_overlay").remove() }) return false } /* * Bindings */ $(document).bind('close.facebox', function() { $(document).unbind('keydown.facebox') $('#facebox').fadeOut(function() { $('#facebox .content').removeClass().addClass('content') $('#facebox .loading').remove() $(document).trigger('afterClose.facebox') }) hideOverlay() }) })(jQuery);
bjverde/formDin
base/js/jquery/facebox/facebox.js
JavaScript
gpl-3.0
9,219
/** * Render a frog demo for infohub_demo * * @author Peter Lembke <info@infohub.se> * @version 2019-03-28 * @since 2018-04-21 * @copyright Copyright (c) 2018, Peter Lembke * @license https://opensource.org/licenses/gpl-license.php GPL-3.0-or-later * @see https://github.com/peterlembke/infohub/blob/master/folder/plugins/infohub/demo/frog/infohub_demo_frog.md Documentation * @link https://infohub.se/ InfoHub main page */ function infohub_demo_frog() { 'use strict'; // include "infohub_base.js" $functions.push('_Version'); /** * Version information, used by the version function * @returns {{date: string, note: string, 'SPDX-License-Identifier': string, checksum: string, version: string, class_name: string, since: string, status: string}} * @private */ const _Version = function() { return { 'date': '2019-03-28', 'since': '2018-04-21', 'version': '2.0.0', 'checksum': '{{checksum}}', 'class_name': 'infohub_demo_frog', 'note': 'Render a frog demo for infohub_demo', 'status': 'normal', 'SPDX-License-Identifier': 'GPL-3.0-or-later', }; }; $functions.push('_GetCmdFunctions'); /** * List with all public functions you can call * @returns {*} * @private */ const _GetCmdFunctions = function() { const $list = { 'create': 'normal', 'click_frog': 'normal', }; return _GetCmdFunctionsBase($list); }; let $classTranslations = {}; // *********************************************************** // * your class functions below, only declare with var // * Can only be reached through cmd() // *********************************************************** /** * Get instructions and create the message to InfoHub View * @version 2016-10-16 * @since 2016-10-16 * @author Peter Lembke */ $functions.push('create'); const create = function($in = {}) { const $default = { 'parent_box_id': '', 'translations': {}, 'step': 'step_start', 'response': { 'answer': 'false', 'message': 'Nothing to report from infohub_demo_form2', }, }; $in = _Default($default, $in); if ($in.step === 'step_start') { $classTranslations = $in.translations; return _SubCall({ 'to': { 'node': 'client', 'plugin': 'infohub_render', 'function': 'create', }, 'data': { 'what': { 'instructions_box': { 'plugin': 'infohub_rendermajor', 'type': 'presentation_box', 'head_label': _Translate('INSTRUCTIONS'), 'content_data': '[my_foot_text]', 'content_embed_new_tab': '[my_external_link]', }, 'result_box': { 'plugin': 'infohub_rendermajor', 'type': 'presentation_box', 'head_label': _Translate('RESULT'), 'foot_text': _Translate('WHEN_YOU_DO_A_MISTAKE_IN_YOUR_RENDERING_CODE_THEN_THE_FROG_SHOWS_UP_AS_A_PLACEHOLDER.'), 'content_data': _Translate('HAVE_YOU_SEEN_ANY_FROGS?'), }, 'my_foot_text': { 'type': 'text', 'text': _Translate('I_MADE_A_FROG_IS_A_SWEDISH_EXPRESSION_FOR_MAKING_A_MISTAKE.') + ' ' + _Translate('JAG_GJORDE_EN_GRODA.') + ' ' + _Translate('IF_YOU_RENDER_AN_OBJECT_WITH_AN_UNKNOWN_TYPE_OR_SUBTYPE_THEN_A_FROG_APPEAR_INSTEAD.') }, 'my_external_link': { 'type': 'link', 'subtype': 'external', 'alias': 'my_external_link', 'data': 'my_external_link', 'show': 'Wiktionary', 'url': 'https://sv.wiktionary.org/wiki/g%C3%B6ra_en_groda', }, 'my_menu': { 'plugin': 'infohub_rendermenu', 'type': 'menu', 'head_label': _Translate('MAKE_A_FROG'), 'options': { 'correct': { 'alias': 'correct_link', 'event_data': 'frog|frog|frog_correct', // demo_frog | click_frog 'button_label': _Translate('CORRECT_WAY'), 'to_plugin': 'infohub_demo', 'to_function': 'click', }, 'mistake1': { 'alias': 'mistake1_link', 'event_data': 'frog|frog|frog_mistake1', 'button_label': _Translate('MISTAKE_#1_-_WRONG_SUBTYPE'), 'to_plugin': 'infohub_demo', 'to_function': 'click', }, 'mistake2': { 'alias': 'mistake2_link', 'event_data': 'frog|frog|frog_mistake2', 'button_label': _Translate('MISTAKE_#2_-_WRONG_TYPE'), 'to_plugin': 'infohub_demo', 'to_function': 'click', }, }, }, }, 'how': { 'mode': 'one box', 'text': '[my_menu][instructions_box][result_box]', }, 'where': { 'box_id': $in.parent_box_id + '.demo', 'max_width': 320, 'scroll_to_box_id': 'true', }, 'cache_key': 'frog', }, 'data_back': {'step': 'step_end'}, }); } return { 'answer': $in.response.answer, 'message': $in.response.message, 'data': $in.response.data, }; }; /** * Handle the events from the frog buttons * @version 2019-03-28 * @since 2019-01-09 * @author Peter Lembke */ $functions.push('click_frog'); const click_frog = function($in = {}) { const $default = { 'step': 'step_start', 'event_data': '', 'box_id': '', 'data_back': {}, }; $in = _Default($default, $in); let $data; if ($in.step === 'step_start') { $data = { 'frog_correct': { 'type': 'frog', 'subtype': '', 'text': _Translate('CORRECT,_THE_FROG_IS_RENDERED_BY_CALLING_THE_RENDER_FROG_PLUGIN.'), 'ok': 'true', }, 'frog_mistake1': { 'type': 'common', 'subtype': 'fizbaz', 'text': _Translate('MISTAKE_#1,_THE_FROG_WERE_RENDERED_BY_CALLING_RENDER_COMMON_WITH_THE_NONE_EXISTING_SUBTYPE_FIZBAZ.') + ' ' + _Translate('THAT_GIVES_A_FROG_AND_AN_ERROR_MESSAGE_ON_TOP.'), 'ok': 'false', }, 'frog_mistake2': { 'type': 'foobar', 'subtype': '', 'text': _Translate('MISTAKE_#2,_THE_FROG_WERE_RENDERED_BY_CALLING_THE_NONE_EXISTING_PLUGIN_FOOBAR.') + ' ' + _Translate('THAT_GIVES_A_FROG_AND_AN_ERROR_MESSAGE_ON_TOP.'), 'ok': 'false', }, }; if (_IsSet($data[$in.event_data]) === 'true') { $in.step = 'step_make_frog'; } } if ($in.step === 'step_make_frog') { return _SubCall({ 'to': { 'node': 'client', 'plugin': 'infohub_render', 'function': 'create', }, 'data': { 'what': { 'my_frog': { 'type': $data[$in.event_data].type, 'subtype': $data[$in.event_data].subtype, }, }, 'how': { 'mode': 'one box', 'text': '[my_frog]', }, 'where': { 'box_id': $in.box_id + '_result_box_content', 'max_width': 640, 'scroll_to_box_id': 'true', }, }, 'data_back': { 'box_id': $in.box_id, 'text': $data[$in.event_data].text, 'ok': $data[$in.event_data].ok, 'step': 'step_write_text', }, }); } if ($in.step === 'step_write_text') { return _SubCall({ 'to': { 'node': 'client', 'plugin': 'infohub_view', 'function': 'set_text', }, 'data': { 'id': $in.data_back.box_id + '_result_box_foot', 'text': $in.data_back.text, }, 'data_back': { 'ok': $in.data_back.ok, 'step': 'step_end', }, }); } return { 'answer': 'true', 'message': 'Frog is made', 'ok': $in.data_back.ok, }; }; } //# sourceURL=infohub_demo_frog.js
peterlembke/infohub
folder/plugins/infohub/demo/frog/infohub_demo_frog.js
JavaScript
gpl-3.0
10,722
function ValidURL(str) { var pattern = new RegExp('^(https?:\/\/)?'+ // protocol '((([a-z\d]([a-z\d-]*[a-z\d])*)\.)+[a-z]{2,}|'+ // domain name '((\d{1,3}\.){3}\d{1,3}))'+ // OR ip (v4) address '(\:\d+)?(\/[-a-z\d%_.~+]*)*'+ // port and path '(\?[;&a-z\d%_.~+=-]*)?'+ // query string '(\#[-a-z\d_]*)?$','i'); // fragment locater if(!pattern.test(str)) { alert("Please enter a valid URL."); return false; } else { return true; } } module.exports = function validate(obj) { if(obj && typeof obj.name == 'string' && typeof obj.sis instanceof Array) { obj.sis.forEach((val) => { if(!ValidURL(val)) throw new Error(val + 'isnt an url') }) } }
doodzik/semantic-tag
src/semantic-tag.js
JavaScript
gpl-3.0
705
(function() { var directives = { }; var filters = { }; var app = angular.module('optc'); /************** * Directives * **************/ directives.characterTable = function($rootScope, $timeout, $compile, $storage) { return { restrict: 'E', replace: true, template: '<table id="mainTable" class="table table-striped-column panel panel-default"></table>', link: function(scope, element, attrs) { var table = element.dataTable({ iDisplayLength: $storage.get('unitsPerPage', 10), stateSave: true, data: scope.table.data, columns: scope.table.columns, rowCallback: function(row, data, index) { if (!row || row.hasAttribute('loaded')) return; var $row = $(row); if (!$row) return; // lazy thumbnails $row.find('[data-original]').each(function(n,x) { x.setAttribute('src',x.getAttribute('data-original')); x.removeAttribute('data-original'); }); // character log checkbox var id = data[data.length - 1] + 1; var checkbox = $('<label><input type="checkbox" ng-change="checkLog(' + id + ')" ng-model="characterLog[' + id + ']"></input></label>'); $(row.cells[10 + scope.table.additional]).append(checkbox); // cosmetic fixes //$(row.cells[1]).addClass('cell-imgtext'); $(row.cells[2]).wrapInner( "<div></div>" ).addClass('cell-' + row.cells[2].textContent); var n = row.cells.length - 2 - scope.table.additional; $(row.cells[n]).addClass('starsx-' + row.cells[n].textContent); $(row.cells[n]).wrapInner( "<div></div>" ) //$(row.cells[n]).wrap("<img src='./img/" + row.cells[n].textContent + "estrellas.png'>"); row.cells[n].textContent = ''; // compile $compile($(row).contents())($rootScope); if (window.units[id - 1].preview) $(row).addClass('preview'); else if (window.units[id - 1].incomplete) $(row).addClass('incomplete'); row.setAttribute('loaded','true'); }, headerCallback : function(header) { if (header.hasAttribute('loaded')) return; header.cells[header.cells.length - 1].setAttribute('title', 'Character Log'); header.setAttribute('loaded',true); } }); scope.table.refresh = function() { $rootScope.$emit('table.refresh'); $timeout(function() { element.fnDraw(); }); }; // report link var link = $('<span class="help-link">¿Quieres informar o solicitar algo? Utilice <a> este correo</a>.</span>'); link.find('a').attr('href', 'mailto:sonrics123@gmail.com'); link.insertAfter($('.dataTables_length')); // pick column link var pick = $('<a id="pick-link" popover-placement="bottom" popover-trigger="click" popover-title="Columnas Adicionales" ' + 'uib-popover-template="\'views/pick.html\'" popover-append-to-body="\'true\'">Columnas Adicionales</a>'); $compile(pick)(scope); pick.insertAfter($('.dataTables_length')); // night toggle var nightToggle = $('<label class="night-toggle"><input type="checkbox">Modo Oscuro</input></label>'); nightToggle.find('input').change(function(e) { $rootScope.nightMode = e.target.checked; if (!$rootScope.$$phase) $rootScope.$apply(); }); if ($rootScope.nightMode) nightToggle.find('input').attr('checked', 'checked'); nightToggle.insertBefore($('.dataTables_length')); // fuzzy toggle var fuzzyToggle = $('<label class="fuzzy-toggle"><input type="checkbox">Habilitar búsqueda especial</input></label>'); fuzzyToggle.attr('title','Cuando está activado, las búsquedas también mostrarán unidades cuyo nombre no coincida exactamente con las palabras claves de búsqueda. \nEs útil si no sabe la forma correcta de escribir una cierta unidad.'); fuzzyToggle.find('input').prop('checked', scope.table.fuzzy); fuzzyToggle.find('input').change(function() { var checked = $(this).is(':checked'); if (checked == scope.table.fuzzy) return; scope.table.fuzzy = checked; $storage.set('fuzzy', scope.table.fuzzy); scope.table.refresh(); }); fuzzyToggle.insertBefore($('.dataTables_length')); } }; }; directives.decorateSlot = function() { return { restrict: 'A', scope: { uid: '=', big: '@' }, link: function(scope, element, attrs) { if (scope.big) element[0].style.backgroundImage = 'url(' + Utils.getBigThumbnailUrl(scope.uid) + ')'; else element[0].style.backgroundImage = 'url(' + Utils.getThumbnailUrl(scope.uid) + ')'; } }; }; directives.autoFocus = function($timeout) { return { restrict: 'A', link: function(scope, element, attrs) { $timeout(function(){ element[0].focus(); }); } }; }; directives.addCaptainOptions = function($timeout, $compile, MATCHER_IDS) { var TARGET = MATCHER_IDS['captain.ClassBoostingCaptains']; return { restrict: 'A', link: function(scope, element, attrs) { if (scope.n !== TARGET) return; var filter = $('<div id="class-filters" ng-class="{ enabled: filters.custom[' + TARGET + '] }"></div>'); var classes = [ 'Fighter', 'Shooter', 'Slasher', 'Striker', 'Free Spirit', 'Cerebral', 'Powerhouse', 'Driven' ]; classes.forEach(function(x,n) { var template = '<span class="filter subclass %c" ng-class="{ active: filters.classCaptain == \'%s\' }" ' + 'ng-click="onCaptainClick($event,\'%s\')">%s</span>'; filter.append($(template.replace(/%s/g,x).replace(/%c/,'width-6'))); }); element.after(filter); $compile(filter)(scope); scope.onCaptainClick = function(e,type) { scope.filters.classCaptain = (scope.filters.classCaptain == type ? null : type); }; } }; }; directives.addSpecialOptions = function($timeout, $compile, MATCHER_IDS) { var TARGET = MATCHER_IDS['special.ClassBoostingSpecials']; return { restrict: 'A', link: function(scope, element, attrs) { if (scope.n !== TARGET) return; var filter = $('<div id="class-filters" ng-class="{ enabled: filters.custom[' + TARGET + '] }"></div>'); var classes = [ 'Fighter', 'Shooter', 'Slasher', 'Striker', 'Free Spirit', 'Cerebral', 'Powerhouse', 'Driven' ]; classes.forEach(function(x,n) { var template = '<span class="filter subclass %c" ng-class="{ active: filters.classSpecial == \'%s\' }" ' + 'ng-click="onSpecialClick($event,\'%s\')">%s</span>'; filter.append($(template.replace(/%s/g,x).replace(/%c/,'width-6'))); }); element.after(filter); $compile(filter)(scope); scope.onSpecialClick = function(e,type) { scope.filters.classSpecial = (scope.filters.classSpecial == type ? null : type); }; } }; }; directives.addOrbOptions = function($timeout, $compile, MATCHER_IDS) { var TARGET = MATCHER_IDS['special.OrbControllers']; return { restrict: 'A', link: function(scope,element,attrs) { if (scope.n !== TARGET) return; var orbs = { ctrlFrom: [ ], ctrlTo: [ ] }; var filter = $('<div id="controllers" ng-class="{ enabled: filters.custom[' + TARGET + '] }">' + '<span class="separator">&darr;</span></div>'); var separator = filter.find('.separator'); [ 'STR', 'DEX', 'QCK', 'PSY', 'INT', 'RCV', 'TND', 'NEGATIVO', 'VACIO', 'BOMBA', 'G' ].forEach(function(type) { var template = '<span class="filter orb %s" ng-class="{ active: filters.%f.indexOf(\'%s\') > -1 }" ' + 'ng-model="filters.%f" ng-click="onOrbClick($event,\'%s\')">%S</span>'; separator.before($(template.replace(/%s/g,type).replace(/%S/g,type[0]).replace(/%f/g,'ctrlFrom'))); filter.append($(template.replace(/%s/g,type).replace(/%S/g,type[0]).replace(/%f/g,'ctrlTo'))); }); element.after(filter); $compile(filter)(scope); scope.onOrbClick = function(e,type) { var target = e.target.getAttribute('ng-model'); if (!target) return; target = target.match(/filters\.(.+)$/)[1]; if (orbs[target].indexOf(type) == -1) orbs[target].push(type); else orbs[target].splice(orbs[target].indexOf(type), 1); orbs[target] = orbs[target].slice(-2); scope.filters[target] = orbs[target]; }; } }; }; directives.goBack = function($state) { return { restrict: 'A', link: function(scope, element, attrs) { element.click(function(e) { if (!e.target || e.target.className.indexOf('inner-container') == -1) return; element.find('.modal-content').addClass('rollOut'); $('.backdrop').addClass('closing'); setTimeout(function() { $state.go('^'); },300); }); } }; }; directives.evolution = function($state, $stateParams) { return { restrict: 'E', replace: true, scope: { unit: '=', base: '=', evolvers: '=', evolution: '=', size: '@' }, templateUrl: 'views/evolution.html', link: function(scope, element, attrs) { scope.goToState = function(id) { if (id == parseInt($stateParams.id,10)) return; var previous = $stateParams.previous.concat([ $stateParams.id ]); $state.go('main.search.view',{ id: id, previous: previous }); }; } }; }; directives.unit = function($state, $stateParams) { return { restrict: 'E', scope: { uid: '=' }, template: '<a class="slot medium" decorate-slot uid="uid" ng-click="goToState(uid)"></a>', link: function(scope, element, attrs) { scope.goToState = function(id) { if (id == parseInt($stateParams.id,10)) return; var previous = $stateParams.previous.concat([ $stateParams.id ]); $state.go('main.search.view',{ id: id, previous: previous }); }; } }; }; directives.compare = function() { var fuse = new Fuse(window.units, { keys: [ 'name' ], id: 'number' }); return { restrict: 'A', link: function(scope, element, attrs) { var target = element.typeahead( { minLength: 3, highlight: true }, { source: function(query, callback) { callback(fuse.search(query)); }, templates: { suggestion: function(id) { var name = units[id].name, url = Utils.getThumbnailUrl(id+1); if (name.length > 63) name = name.slice(0,60) + '...'; var thumb = '<div class="slot small" style="background-image: url(' + url + ')"></div>'; return '<div><div class="suggestion-container">' + thumb + '<span>' + name + '</span></div></div>'; } }, display: function(id) { return units[id].name; } } ); target.bind('typeahead:select',function(e,suggestion) { $(e.currentTarget).prop('disabled', true); scope.compare = window.units[suggestion]; scope.compareDetails = window.details[suggestion + 1]; scope.compareCooldown = window.cooldowns[suggestion]; scope.isCompareCaptainHybrid = (scope.compareDetails && scope.compareDetails.captain && scope.compareDetails.captain.global); scope.isCompareSailorHybrid = (scope.compareDetails && scope.compareDetails.sailor && scope.compareDetails.sailor.global); scope.isCompareSpecialHybrid = (scope.compareDetails && scope.compareDetails.special && scope.compareDetails.special.global); scope.isCompareSpecialStaged = (scope.compareDetails && scope.compareDetails.special && scope.compareDetails.special.constructor == Array); if (!scope.$$phase) scope.$apply(); }); element[0].style.backgroundColor = null; } }; }; directives.comparison = function() { return { restrict: 'A', link: function(scope, element, attrs) { var positive = (attrs.comparison == 'positive'); var watch = scope.$watch( function() { return element.html(); }, function() { var isNegative = parseFloat(element.text(),10) < 0; element.removeClass('positive negative withPlus'); if ((positive && !isNegative) || (!positive && isNegative)) element.addClass('positive'); else element.addClass('negative'); if (!isNegative) element.addClass('withPlus'); } ); scope.$on('$destroy',watch); } }; }; directives.addTags = function($stateParams, $rootScope) { return { restrict: 'E', replace: true, template: '<div class="tag-container"></div>', link: function(scope, element, attrs) { var id = $stateParams.id, data = details[id]; // flags var flags = window.flags[id] || { }; element.append($('<span class="tag flag">' + (flags.global ? 'Unidad Global' : 'Unidad Japonesa') + '</div>')); element.append($('<span class="tag flag">' + (CharUtils.isFarmable(id) ? 'Farmeable' : 'No-farmeable') + '</div>')); if (flags.rr) element.append($('<span class="tag flag">Sólo Rare Recruit</div>')); if (flags.lrr) element.append($('<span class="tag flag">Limitado Sólo Rare Recruit</div>')); if (flags.promo) element.append($('<span class="tag flag">Sólo por Código Promocional</div>')); if (flags.shop) element.append($('<span class="tag flag">Unidades Tienda Ray</div>')); if (flags.special) element.append($('<span class="tag flag">Personajes Limitados</div>')); if (CharUtils.checkFarmable(id, { 'Story Island': true })) element.append($('<span class="tag flag">Sólo en Modo Historia</div>')); if (CharUtils.checkFarmable(id, { Quincenal: true })) element.append($('<span class="tag flag">Sólo Quincenales</div>')); if (CharUtils.checkFarmable(id, { Raid: true })) element.append($('<span class="tag flag">Sólo Raid</div>')); if (CharUtils.checkFarmable(id, { 'Story Island': true, Quincenal: true })) element.append($('<span class="tag flag">Sólo en Modo Historia y Quincenales</div>')); if (CharUtils.checkFarmable(id, { Raid: true, Quincenal: true })) element.append($('<span class="tag flag">Sólo Raid y Quincenales</div>')); // matchers if (!data) return; matchers.forEach(function(matcher) { var name; // captain effects if (matcher.target == 'captain' && matcher.matcher.test(data.captain)) { name = matcher.name; if (!/captains$/.test(name)) name = name.replace(/ers$/,'ing').replace(/s$/,'') + ' - Capitán'; else name = name.replace(/s$/,''); name = name.replace(/iing/,'ying'); element.append($('<span class="tag captain">' + name + '</div>')); } // sailor effects if (matcher.target.indexOf('sailor') === 0 && matcher.matcher.test(data[matcher.target]) && !(data[matcher.target] === undefined)) { name = matcher.name; /*if (!/sailor$/.test(name)) name = name.replace(/ers$/,'ing').replace(/s$/,'') + ' - Sailor'; else name = name.replace(/s$/,''); name = name.replace(/iing/,'ying');*/ element.append($('<span class="tag sailor">' + name + '</div>')); } // specials if (matcher.target.indexOf('special') === 0 && matcher.matcher.test(data[matcher.target])) { name = matcher.name; if (!/specials$/.test(name)) name = name.replace(/ers$/,'ing').replace(/s$/,'') + ' - Especial'; else name = name.replace(/s$/,''); name = name.replace(/iing/,'ying'); element.append($('<span class="tag special">' + name + '</div>')); } }); } }; }; directives.addLinks = function($stateParams) { return { restrict: 'E', replace: true, template: '<div class="link-container"></div>', link: function(scope, element, attrs) { var id = parseInt($stateParams.id,10), data = details[id]; if (!units[id - 1]) return; var incomplete = units[id - 1].incomplete; var ul = $('<ul></ul>'); if (!incomplete && window.flags[id] && window.flags[id].global) { var link = 'http://onepiece-treasurecruise.com/en/' + (id == '5' ? 'roronoa-zoro' : 'c-' + id); ul.append($('<li><a href="' + link + '" target="_blank">Official Guide (English)</a></li>')); } if (!incomplete) { ul.append($('<li><a href="http://onepiece-treasurecruise.com/c-' + id + '" target="_blank">' + 'Guía Oficial (Japonesa)</a></li>')); } if (!isNaN(gw[id-1])) { ul.append($('<li><a href="http://xn--pck6bvfc.gamewith.jp/article/show/' + gw[id-1] + '" target="_blank">' + 'Página GameWith (Japonesa)</a></li>')); } if (ul.children().length > 0) element.append(ul); } }; }; directives.costSlider = function($timeout) { return { restrict: 'A', link: function(scope, element, attrs) { element.ionRangeSlider({ grid: true, type: 'double', min: scope.filters.cost[0], max: scope.filters.cost[1], from: scope.filters.cost[0], to: scope.filters.cost[1], postfix: ' coste', onFinish: function(data) { scope.filters.cost[0] = data.from; scope.filters.cost[1] = data.to; if (!scope.$$phase) scope.$apply(); } }); } }; }; /****************** * Initialization * ******************/ for (var directive in directives) app.directive(directive, directives[directive]); for (var filter in filters) app.filter(filter, filters[filter]); })();
mvshivaa71/mvshivaa71.github.io
characters/js/directives.js
JavaScript
gpl-3.0
19,912
"use strict"; // ScriptQueue // script queue { const $g = Symbol.for( '[[global]]' ); // ScriptQueue - for exploring and loading scripts class ScriptQueue_Tools { constructor( queue ) { this.queue = queue; } requestScript( queue, next ) { queue.isExecuting = true; queue.reportStartExecuting(); queue.status.set( next, ScriptQueue.REQUESTED ); return setTimeout( () => this.failScript( queue, next ), queue.LOAD_TIMEOUT_MS ); } failScript( queue, next, timer ) { if ( timer ) clearTimeout( timer ); queue.isExecuting = false; queue.reportStopExecuting(); queue.current = null; queue.status.set( next, ScriptQueue.FAILED ); queue.failListeners.forEach( f => f.call( queue, next ) ); } succeedScript( queue, next, timer ) { if ( timer ) clearTimeout( timer ); queue.isExecuting = false; queue.reportStopExecuting(); queue.current = null; queue.status.set( next, ScriptQueue.SUCCEEDED ); queue.success ++; queue.successListeners.forEach( f => f.call( queue, next ) ); } createRunAndRemove( element, f ) { return function () { f(); element.remove(); }; } chromeImport( uri, succeed, fail ) { chrome.runtime.sendMessage( { file : uri }, report_results ); function report_results( result_report ) { if ( ! result_report.execute ) { console.warn( "Results are not in expected format. Failing." ); console.info( result_report ); fail(); return; } switch( result_report.execute ) { case "success": console.info( `${ uri } exectued successfully. Results : `, result_report.results ); succeed(); break; case "fail": console.warn( `${ uri } failed to execute. Results : `, result_report.results ); fail(); break; default: console.warn( `Execution of ${ uri } gave results in unexpected format. Failing.` ); console.info( result_report ); fail(); break; } } } browsingImport( uri, succeed, fail ) { const script = document.createElement( 'script' ); script.onload = this.createRunAndRemove( script, succeed ); script.onerror = this.createRunAndRemove( script, fail ); script.src = uri; ( document.head || document.documentElement ).appendChild( script ); } buildImport( uri, succeed, fail ) { const exchange = { method : 'GET', mode : 'cors', credentials : 'include' }, request = new Request( uri , exchange ), result = fetch( request ); result.then( obtain_body_text ).then( print_body_text ).then( succeed ).catch( fail ); function obtain_body_text( response ) { console.group( "obtain body" ); const body = response.text( ); console.groupEnd( ); return body; } function print_body_text( body_text ) { console.group( "print body" ); console.info( "body", body_text ); console.groupEnd( ); } } hasChrome( ) { try { chrome.extension.getURL(''); } catch ( e ) { return false; } return true; } importScript( uri, succeed, fail ) { self.extensioncurrentscript = uri; if ( this.queue.buildMode ) { this.buildImport( uri, succeed, fail ); } else if ( this.hasChrome() ) { this.chromeImport( uri, succeed, fail ); } else if( self.importScripts instanceof Function ) { this.workerImport( uri, succeed, fail ); } else { this.browsingImport( uri, succeed, fail ); } } workerImport( uri, succeed, fail ) { try { importScripts( uri ); } catch ( e ) { if ( e instanceof DOMException ) fail(); } succeed(); } } class ScriptQueue { static get ENQUEUED() { return 0; } static get REQUESTED() { return 1; } static get SUCCEEDED() { return 2; } static get FAILED() { return 3; } static get QUEUE_RUNNING() { return 4; } static get QUEUE_COMPLETE() { return 5; } static get DEFAULT_LOAD_TIMEOUT_MS() { return 1200; } constructor( name = '' ) { this.name = name; this.queue = new Array(); this.status = new Map(); this.successListeners = new Array(); this.failListeners = new Array(); this.completeListeners = new Array(); this.addListeners = new Array(); this.LOAD_TIMEOUT_MS = ScriptQueue.DEFAULT_LOAD_TIMEOUT_MS; this.isExecuting = false; this.current = null; this.success = 0; this.$ = new ScriptQueue_Tools( this ); } reportStartExecuting() { if( ! self[$g].report ) return ; Report.green.open( `${ this.name } executing ${ this.current }` ); } reportStopExecuting() { if( ! self[$g].report ) return ; Report.blue.say( `${ this.name } finished ${ this.current }` ); Report.close(); } add( uri ) { this.queue.push( uri ); this.status.set( uri, ScriptQueue.ENQUEUED ); this.state = ScriptQueue.QUEUE_RUNNING; this.addListeners.forEach( f => f.call( this ) ); } next() { if ( this.isExecuting ) return; const next = this.current = this.queue.shift(); if ( ! next ) return setTimeout( () => this.complete(), 0 ); const note_failure = this.$.requestScript( this, next ); this.$.importScript( next, () => this.$.succeedScript( this, next, note_failure ), () => this.$.failScript( this, next, note_failure ) ); } complete() { this.state = ScriptQueue.QUEUE_COMPLETE; this.completeListeners.forEach( f => f.call( this, this ) ); } } self.ScriptQueue = ScriptQueue; } // test script queue { function test_sq( ) { const sq = new ScriptQueue(), sq2 = new ScriptQueue( ), tests = [ { test : v => v.value = sq }, { async : ( v, cb ) => ( v.value.completeListeners.push( cb ), v.value.next( ) ) }, { check : v => v.value.success == 3 }, { test : v => v.value = sq2 }, { async : ( v, cb ) => ( v.value.completeListeners.push( cb ), v.value.next( ) ) }, { check : v => v.value.success == 1 } ], tester = new Tester( tests, 'script_queue' ); sq.add( 'sqa1.js' ); sq.add( 'sqa2.js' ); sq.add( 'sqa3.js' ); sq.successListeners.push( () => sq.next( ) ); sq2.successListeners.push( () => sq2.next( ) ); sq2.add( 'sqa1.js' ); sq2.buildMode = true; tester.run( ); } self.test_sq = test_sq; if ( self.test_script_queue ) test_sq( ); }
dosaygo-coder-0/postjs
postloader/test/script_queue.js
JavaScript
gpl-3.0
7,840