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
import WindowController from "@/modv/window-controller"; import getLargestWindow from "@/modv/get-largest-window"; const state = { windows: [], size: { width: 0, height: 0 } }; // We can't store Window Objects in Vuex because the Observer traversal exceeds the stack size const externalState = []; // getters const getters = { allWindows: state => state.windows, windowReference: () => index => externalState[index], largestWindowSize: state => state.size, largestWindowReference() { return () => getLargestWindow(state.windows).window || externalState[0]; }, largestWindowController() { return () => getLargestWindow(state.windows).controller; }, getWindowById: state => id => state.windows.find(windowController => windowController.id === id), windowIds: state => state.windows.map(windowController => windowController.id) }; // actions const actions = { createWindow({ commit }, { Vue }) { const number = state.windows.length; return new WindowController(Vue, number).then(windowController => { const windowRef = windowController.window; delete windowController.window; commit("addWindow", { windowController, windowRef }); return windowController; }); }, destroyWindow({ commit }, { windowRef }) { commit("removeWindow", { windowRef }); }, resize({ state, commit }, { width, height, dpr }) { state.windows.forEach(windowController => { windowController.resize(width, height, dpr, false); }); commit("setSize", { width, height, dpr }); } }; // mutations const mutations = { addWindow(state, { windowController, windowRef }) { const index = state.windows.length; windowController.window = index; state.windows.push(windowController); externalState.push(windowRef); getters.largestWindowReference(); }, removeWindow(state, { windowRef }) { state.windows.splice(windowRef, 1); externalState.splice(windowRef, 1); getters.largestWindowReference(); }, setSize(state, { width, height, dpr }) { state.size = { width, height, dpr, area: width * height }; } }; export default { namespaced: true, state, getters, actions, mutations };
2xAA/modV
src/store/modules/windows.js
JavaScript
gpl-3.0
2,225
(function() { 'use strict'; angular.module('pteroWorkflowClient.services', []); })();
genome/ptero-workflow-client
src/app/services.module.js
JavaScript
gpl-3.0
90
/** * Genji Scrum Tool and Issue Tracker * Copyright (C) 2015 Steinbeis GmbH & Co. KG Task Management Solutions * <a href="http://www.trackplus.com">Genji Scrum Tool</a> * * 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/>. */ /* $Id:$ */ Ext.define("com.trackplus.admin.customize.filter.ReportConfigController", { extend: "Ext.app.ViewController", alias: "controller.reportConfig", mixins: { baseController: "com.trackplus.admin.customize.category.CategoryBaseController" }, //used in FieldExpressionAction (not directly here) //issueFilter : true, folderAction: "categoryConfig", baseServerAction: "reportConfig", entityDialog: "com.trackplus.admin.customize.report.ReportEdit", enableDisableToolbarButtons : function(view, arrSelections) { if (CWHF.isNull(arrSelections) || arrSelections.length === 0) { this.getView().actionDeleteGridRow.setDisabled(true); this.getView().actionEditGridRow.setDisabled(true); this.getView().actionExecuteGridRow.setDisabled(true); this.getView().actionDownloadGridRow.setDisabled(true); } else { if (arrSelections.length === 1) { var selectedRecord = arrSelections[0]; var isLeaf = selectedRecord.get("leaf"); var modifiable = selectedRecord.get("modifiable"); this.getView().actionEditGridRow.setDisabled(!modifiable); this.getView().actionExecuteGridRow.setDisabled(!isLeaf); this.getView().actionDownloadGridRow.setDisabled(!isLeaf); } else { // more than one selection this.getView().actionEditGridRow.setDisabled(true); this.getView().actionExecuteGridRow.setDisabled(true); this.getView().actionDownloadGridRow.setDisabled(true); } var allIsDeletable = true; for (var i = 0; i < arrSelections.length; i++) { var selectedRecord = arrSelections[i]; var deletable = selectedRecord.data.deletable; if (!deletable) { allIsDeletable = false; } } this.getView().actionDeleteGridRow.setDisabled(!allIsDeletable); } }, /** * Execute a leaf node */ onExecuteTreeNode: function() { this.onExecute(true); }, /** * Execute a grid row */ onExecuteGridRow: function() { this.onExecute(false); }, /** * Execute a tree node or a grid row */ onExecute: function(fromTree) { var recordData = this.getView().getSingleSelectedRecordData(fromTree); if (recordData ) { var leaf = this.getView().selectedIsLeaf(fromTree); var node = this.getRecordID(recordData, { fromTree : fromTree }); if (leaf) { var lastIndex = node.lastIndexOf("_"); var objectID = node.substring(lastIndex + 1); //customFeature: whether record configuration is needed com.trackplus.admin.Report.executeReport(this, objectID, recordData["customFeature"], false); } } }, /** * Download the report for a tree node */ onDownloadTreeNode : function() { this.downloadReport(true); }, /** * Download the report for the grid row */ onDownloadGridRow : function() { this.downloadReport(false); }, /** * Downloads a report zip */ downloadReport : function(fromTree) { var recordData = this.getView().getSingleSelectedRecordData(fromTree); if (recordData ) { var leaf = this.getView().selectedIsLeaf(fromTree); if (leaf) { var node = this.getRecordID(recordData, { fromTree : fromTree }); attachmentURI = "reportConfig!download.action?node=" + node; window.open(attachmentURI); } } } });
trackplus/Genji
src/main/webapp/js/admin/customize/report/ReportConfigController.js
JavaScript
gpl-3.0
4,196
(function() { var StatisticPresenter = function() {}; BH.Presenters.StatisticPresenter = StatisticPresenter; })();
chrome-enhanced-history/enhanced-history
scripts/presenters/statistic_presenter.js
JavaScript
gpl-3.0
120
import { moduleFor, test } from 'ember-qunit'; moduleFor('adapter:contacts', 'Unit | Adapter | contacts', { // Specify the other units that are required for this test. // needs: ['serializer:foo'] }); // Replace this with your real tests. test('it exists', function(assert) { let adapter = this.subject(); assert.ok(adapter); });
jtolbert1975/imanjesolutions
tests/unit/adapters/contacts-test.js
JavaScript
gpl-3.0
340
Ext.define('Healthsurvey.view.usermanagement.roles.AddNewRolesController', { extend : 'Ext.app.ViewController', alias : 'controller.newRolesController', defaultMenuStore:null, init:function() { this.initializeDragZone(); }, afterAllFeatureTreeRender:function() { debugger; var currentObject = this; var loadMask = new Ext.LoadMask({ msg : 'Loading data...', target : currentObject.getView() }).show(); Ext.Ajax.request({ url : "secure/MenuService/fetchmenus", method:'POST', loadMask:loadMask, controller:currentObject, jsonData:{ }, success : function(response,currentObject) { debugger; var responseJson = Ext.JSON.decode(response.responseText); var rawData=Ext.JSON.decode(responseJson.response.data); currentObject.controller.defaultMenuStore=rawData; currentObject.controller.createTree(rawData) currentObject.loadMask.hide(); }, failure : function(response,currentObject){ currentObject.loadMask.hide(); Ext.Msg.alert({title: 'Error',msg: "Cannot connect to server.",icon: Ext.MessageBox.ERROR}); } },currentObject); }, createTree:function(rawData) { var allTreePanel=this.getView().down("#allFeatureTree"); var rootNode=allTreePanel.getRootNode(); /*for(i=0;i<rawData.length;i++){ data=rawData[i]; var fChild=data.children;*/ var fChild=rawData; for(var x1=0;x1<fChild.length;x1++) { this.addChild(rootNode,fChild[x1]); } //} /**Use this for loop if menu list order is changed **/ }, addChild:function(parentNode,node) { if(node.hasOwnProperty("children")&& node.children!=null) { var child={ text:node.text, menuId:node.menuId, icon : 'images/folder-database-icon.png', read :true, } child["expanded"]=true; child["isRead"]=true; child["isWrite"]=true; child["isExecute"]=false; /** here we are not getting does the menu is head or not from db so i am adding headMenu property here to identify it**/ child["isHeadMenu"] = true; var newNode=parentNode.appendChild(child); for(var x=0;x<node.children.length;x++) { this.addChild(newNode,node.children[x]); } }else{ debugger; node["isRead"]=true; node["isWrite"]=true; node["isExecute"]=false; node['visible'] = (node.text=="")?false:true; node["isHeadMenu"] = false; parentNode.appendChild(node); } }, // Propagate change downwards (for all children of current node). setChildrenCheckedStatus : function (node, property, checked) { if ((node.data.isHeadMenu) && (node.hasChildNodes())) { for(var i=0; i<node.childNodes.length; i++) { var child = node.childNodes[i]; if ((child.data.isHeadMenu) && (child.hasChildNodes())) { this.setChildrenCheckedStatus(child, property, checked); } if(child.data.visible) child.set(property,checked); } } }, // Propagate change upwards (if all siblings are the same, update parent). updateParentCheckedStatus : function (current, property, checked) { debugger; if (current.parentNode.data.isHeadMenu) { debugger; var parent = current.parentNode; var checkedCount = 0; var visibleChildLength = 0; parent.eachChild(function(n) { if(n.data.visible) { visibleChildLength++; checkedCount += (n.get(property) ? 1 : 0); } }); // a single child is checked, so check the parent. if (checkedCount == 1){ debugger; parent.set(property, true); if(parent.parentNode.data.isHeadMenu && checked == true) { this.updateParentCheckedStatus(parent, property, checked); } } // Children have same value if all of them are checked or none is checked. var sameValue = (checkedCount == visibleChildLength) || (checkedCount == 0); //parent.childNodes.length) || (checkedCount == 0); if (sameValue) { parent.set(property, checked); if(parent.parentNode.data.isHeadMenu) { this.updateParentCheckedStatus(parent, property, checked); } } } }, onIsReadCheckChange : function(checkcolumn, rowIndex, checked, eOpts) { this.applyCheckBehaviour(rowIndex,'isRead',checked); }, onIsWriteCheckChange : function(checkcolumn, rowIndex, checked, eOpts) { this.applyCheckBehaviour(rowIndex,'isWrite',checked); }, onIsExecuteCheckChange : function(checkcolumn, rowIndex, checked, eOpts) { this.applyCheckBehaviour(rowIndex,'isExecute',checked); }, applyCheckBehaviour : function(rowIndex, property, checked){ debugger; var mappingTree = this.getView().down('#mappedFeatureTree'); var node = mappingTree.store.getAt(rowIndex); // Propagate change downwards (for all children of current node). this.setChildrenCheckedStatus(node, property, checked); // Propagate change upwards (if all siblings are the same, update parent). this.updateParentCheckedStatus(node, property, checked); }, initializeDragZone:function() { var dragData = null; var treeComponentPanel = this.getView().down("#allFeatureTree"); treeComponentPanel.on('itemmousedown', function( treeComponentPanel, record, item, index, e, eOpts ){ dragData = record //record.data will give only the selected node }); treeComponentPanel.on('render', function(v) { treeComponentPanel.dragZone = new Ext.dd.DragZone(v.getEl(), { onBeforeDrag : function(data, e) { //Parent Node not allowed to dragged /*if(data.draggedRecord.data.leaf==false){ return false; }*/ if (data.draggedRecord.cannotDrag) { return false; } }, getDragData: function(e) { var sourceEl = e.getTarget(v.itemSelector, 10); if (sourceEl) { d = sourceEl.cloneNode(true); var dragDataToSend = d.id; if (dragData.component == d.textContent){ dragDataToSend = dragData; } d.id = Ext.id(); return { ddel: d, sourceEl: sourceEl, repairXY: Ext.fly(sourceEl).getXY(), sourceStore: v.store, draggedRecord: dragData }; } }, getRepairXY: function() { //console.log('Drag Zone: getRepairXY() called...'); return this.dragData.repairXY; }, ddGroup : 'myDDGroup' }); }); },//initializeDragZone initializeDropZone:function(panel) { debugger; var me =this; //dBBuilderController /**Click Event of Panel's items*/ panel.getEl().on('click', function(e,el,panel){ var targetNode =this.getNodeForEl(e.getTarget()); },me); /**Initialize DropZone*/ var drop = new Ext.dd.DropZone(panel.el, { ddGroup:'myDDGroup', scope:this, getTargetFromEvent: function(e) { //return e.getTarget(this.layoutPanel); }, notifyOver : function(src,e,data) { return Ext.dd.DropZone.prototype.dropAllowed; }, notifyDrop : function(src,e,data) { debugger; var rootNode=this.scope.getView().down('#mappedFeatureTree').getRootNode(); var draggedRecord=data.draggedRecord; //If leaf node is dragged then drag its parent nodes in hierarchy also if(draggedRecord.data.leaf==true) { var tempArr=[]; while(draggedRecord.data.text!="Root") { tempArr.push(draggedRecord.data); draggedRecord=draggedRecord.parentNode; } var parentNode=rootNode; for(i=tempArr.length-1;i>=0;i--) { if(parentNode.findChild("text",tempArr[i].text,true)==null){ parentNode=parentNode.appendChild(tempArr[i]); } else{ parentNode=parentNode.findChild("text",tempArr[i].text,true); } } } //If folder node is dragged then drag its parent nodes in hierarchy as well as all its children else{ var tempArr1=[]; tempArr1.push(draggedRecord); while(draggedRecord.parentNode.data.text!="Root") { draggedRecord=draggedRecord.parentNode; tempArr1.push(draggedRecord.data); } var parentNode=rootNode; for(i=tempArr1.length-1;i>=0;i--) { if(parentNode.findChild("text",tempArr1[i].data.text,true)==null){ parentNode=parentNode.appendChild(tempArr1[i]); } else{ parentNode=parentNode.findChild("text",tempArr1[i].text,true); } } this.scope.refreshDefaultTree() } }, notifyOut : function(src,e,data) { //this.removehighlightElement(); //Ext.fly(src).removeCls('my-row-highlight-class') } }); panel.drop=drop; },//initializeDropZone ends getNodeForEl : function(el) { var search = 0; var target = null; while (search < 10) { target = Ext.ComponentMgr.get(el.id); if (target) { return target; } el = el.parentNode; if (!el) { break; } search++; } return null; }, refreshDefaultTree : function() { if (this.defaultMenuStore != null){ debugger; this.getView().down('#allFeatureTree').getRootNode().removeAll(); this.createTree(this.defaultMenuStore); } }, itemContextMenuClick:function(obj, record, item, index, e, eOpts ) { e.stopEvent(); Ext.create('Ext.menu.Menu', { items : [ Ext.create('Ext.Action', { text : 'Remove', iconCls:'menu-delete', handler : function() { /*if(record.data.leaf == true){*/ Ext.Msg.confirm('Confirm', 'Are you sure you want to delete',function(btn, text){ if (btn == 'yes') { this.record.remove(); }},{ me:this, record:record });//MessageBox ends //}//if closes }//handler }) ]//menu items closes }).showAt(e.getXY()); },//itemContextMenu ends onSaveRolesClick:function() { debugger; var me =this; var roleName=this.getView().down('#roleName').getValue(); var roleDesc=this.getView().down('#roleDesc').getValue(); if(roleName==""){ Ext.Msg.alert({title:'Info',msg:"Enter Role Name",icon:Ext.MessageBox.INFO});return;} var mappedTree=this.getView().down('#mappedFeatureTree'); roleMenuBridge=this.prepareRoleMenuBridge(mappedTree); var jsonData ={ roleName : roleName, roleDescription : roleDesc, roleMenuBridge : roleMenuBridge }; Ext.Ajax.request({ url:'secure/Roles', method : 'POST', me:me, jsonData : jsonData, success : function(response,currentObject) { debugger; var responseJson = Ext.JSON.decode(response.responseText); if(responseJson.response.success==true) { Ext.Msg.alert('Success',"Data Saved Successfully"); rolesTree=currentObject.me.getView().up().up().down('#rolesTree'); rolesTree.store.load(); currentObject.me.onResetRolesClick(); } else{ Ext.Msg.alert({title : 'Error',msg : 'Data Transaction Failed',icon : Ext.MessageBox.ERROR}); } }, failure : function() { Ext.Msg.alert({title : 'Error',msg : 'Cannot connect to server',icon : Ext.MessageBox.ERROR}); } }); },//onSaveRolesClick ends prepareRoleMenuBridge : function(mappedTree) { debugger; var criteria = []; var store = mappedTree.getStore(); Ext.Array.each(store.data.items,function(item, idx, items) { var object = { menuId : item.data.menuId, isRead: item.data.isRead, isWrite: item.data.isWrite, isExecute: item.data.isExecute }; this.criteria.push(object); }, { criteria : criteria, mappedTree : mappedTree, scope : this }); return criteria; },//prepareRoleMenuBridge ends onResetRolesClick:function() { this.getView().down('#roleFormPanel').reset(); this.getView().down('#mappedFeatureTree').getRootNode().removeAll() } });
applifireAlgo/appApplifire
healthsurvey/src/main/webapp/app/view/usermanagement/roles/AddNewRolesController.js
JavaScript
gpl-3.0
12,519
/*--------------------------------------------------------------------------------+ - Dateiname: app/proxy/Proxy.js - Beschreibung: JsonP Proxy - Autor(en): Andreas Gärtner <andreas.gaertner@hotmail.com> +--------------------------------------------------------------------------------+ 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 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/>. +--------------------------------------------------------------------------------+ Inoffizielle deutsche Übersetzung (http://www.gnu.de/documents/gpl.de.html): Dieses Programm ist freie Software. Sie können es unter den Bedingungen der GNU General Public License, wie von der Free Software Foundation veröffentlicht, weitergeben und/oder modifizieren, entweder gemäß Version 3 der Lizenz oder jeder späteren Version. +--------------------------------------------------------------------------------+ Die Veröffentlichung dieses Programms erfolgt in der Hoffnung, daß es Ihnen von Nutzen sein wird, aber OHNE IRGENDEINE GARANTIE, sogar ohne die implizite Garantie der MARKTREIFE oder der VERWENDBARKEIT FÜR EINEN BESTIMMTEN ZWECK. Details finden Sie in der GNU General Public License. Sie sollten ein Exemplar der GNU General Public License zusammen mit diesem Programm erhalten haben. Falls nicht, siehe <http://www.gnu.org/licenses/>. +--------------------------------------------------------------------------------+ */ Ext.define('LearningApp.proxy.Proxy', { extend: 'Ext.data.Connection', xtype: 'proxy', config: { url: "http://ilias-staging.mni.thm.de:8080/connector/ilias/", //url: "http://localhost:8080/connector-service/ilias/", //url: "https://quizapp.uni-giessen.de/connector/ilias/", useDefaultXhrHeader: false, withCredentials: true, disableCaching: false, method: 'GET' }, /** * removes custom headers from requests */ resetDefaultRequestHeaders: function() { this.setDefaultHeaders(null); }, /** * checks online status of service */ check: function(callback) { this.request({ url: this.getUrl() + "check", success: function(response) { if(response.responseText = 'OK') { callback.success.call(this, arguments); } }, failure: function(response) { callback.failure.apply(this, arguments); }, callback: function(response) { callback.callback.apply(this, arguments); }, scope: this }) }, /** * check login state */ checkLogin: function(callback) { var me = this; LearningApp.app.storageController.getLoggedInUserObj(function(loginObj) { if(loginObj != null) me.setDefaultHeaders(loginObj.authObj); }); }, /** * perform login through basic authentication * @param uname: username * @param upass: password */ login: function(uname, upass, callback) { this.request({ url: this.getUrl() + "login", method : 'POST', params: { uname: uname, upass: upass }, success: function(response) { callback.success.call(this, Ext.decode(response.responseText)); }, failure: function(response) { callback.failure.apply(this, arguments); }, scope: this }); }, /** * Gets the card index tree * @param object with success-callback * @return cardindex-objects, if found * @return false, if nothing found */ getCardIndexTree: function(callback) { this.request({ url: this.getUrl() + "1", success: function(response) { if (response.status === 204) { callback.success.call(this, []); } else { callback.success.call(this, Ext.decode(response.responseText)); } }, failure: function(response) { Ext.Viewport.setMasked(false); if (response.status === 401) { Ext.Msg.alert('Login', 'Ihre Logindaten sind abgelaufen. Bitte erneut einloggen.', function() { LearningApp.app.getController('LoginController').logout(); }); } else { Ext.Msg.alert('Offline-Modus', 'Das Programm wird im Offline-Modus ausgeführt.'); callback.failure.apply(this, arguments); } }, scope: this }); }, /** * Gets random choosen questions from a test * @param object with success-callback * @return cardindex-objects, if found * @return false, if nothing found */ getRandomQuestions: function(refId, callbacks) { this.request({ url: this.getUrl() + "question/" + refId, success: function(response) { if (response.status === 204) { callbacks.success.call(this, {}); } else { callbacks.success.call(this, { refId: refId, data: Ext.decode(response.responseText) }); } }, failure: function(response) { if (response.status === 401) { callbacks.unauthorized.apply(this, arguments); } else if (response.status === 404) { callbacks.notFound.apply(this, arguments); } else if (response.status = 403) { callbacks.forbidden.apply(this, arguments); } else { callbacks.failure.apply(this, arguments); } }, scope: this }); }, /** * Gets all questions from a test * @param object with success-callback * @return cardindex-objects, if found * @return false, if nothing found */ getAllQuestions: function(refId, callbacks) { this.request({ url: this.getUrl() + "question/" + refId + "?source=ALL", success: function(response) { if (response.status === 204) { callbacks.success.call(this, {}); } else { callbacks.success.call(this, { refId: refId, data: Ext.decode(response.responseText) }); } }, failure: function(response) { if (response.status === 401) { callbacks.unauthorized.apply(this, arguments); } else if (response.status === 404) { callbacks.notFound.apply(this, arguments); } else if (response.status = 403) { callbacks.forbidden.apply(this, arguments); } else { callbacks.failure.apply(this, arguments); } }, scope: this }); } });
thm-projects/ilias-flashcards
app/proxy/Proxy.js
JavaScript
gpl-3.0
8,134
/** * * Wait for an element (selected by css selector) for the provided amount of * milliseconds to be present within the DOM. Returns true if the selector * matches at least one element that exists in the DOM, otherwise throws an * error. If the reverse flag is true, the command will instead return true * if the selector does not match any elements. * * <example> :waitForExistSyncExample.js it('should display a notification message after successful form submit', function () { var form = $('form'); var notification = $('.notification'); form.submit(); notification.waitForExist(5000); // same as `browser.waitForExist('.notification', 5000)` expect(notification.getText()).to.be.equal('Data transmitted successfully!') }); * </example> * * @alias browser.waitForExist * @param {String} selector element selector to wait for * @param {Number=} ms time in ms (default: 500) * @param {Boolean=} reverse if true it instead waits for the selector to not match any elements (default: false) * @uses utility/waitUntil, state/isExisting * @type utility * */ let waitForExist = function (selector, ms, reverse) { /** * we can't use default values for function parameter here because this would * break the ability to chain the command with an element if reverse is used, like * * ```js * var elem = $('#elem'); * elem.waitForXXX(10000, true); * ``` */ reverse = typeof reverse === 'boolean' ? reverse : false /*! * ensure that ms is set properly */ if (typeof ms !== 'number') { ms = this.options.waitforTimeout } const isReversed = reverse ? '' : 'not ' const errorMsg = `element ("${selector || this.lastResult.selector}") still ${isReversed}existing after ${ms}ms` return this.waitUntil(() => { return this.isExisting(selector).then((isExisting) => { if (!Array.isArray(isExisting)) { return isExisting !== reverse } let result = reverse for (let val of isExisting) { if (!reverse) { result = result || val } else { result = result && val } } return result !== reverse }) }, ms, errorMsg) } export default waitForExist
Cy6erlion/wharica
node_modules/webdriverio/lib/commands/waitForExist.js
JavaScript
gpl-3.0
2,393
/*! pl-sql-client - Query many database at once Copyright (C) 2015 Kyle Ilantzis, Pier-Luc Caron St-Pierre 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(pl) { var gui = require('nw.gui'); var Watcher = require('./backend/watcher.js'); var TAG = "SettingsStore:::"; var NAME = "SettingsStore"; var SettingsStore = { BROADCAST_LOADED: "SettingsStore-BCAST_LOADED", LOAD: "SettingsStore-LOAD", SET_THEME: "SettingsStore-SET_THEME", SET_WINDOW_RECT: "SettingsStore-SET_WINDOW_RECT" }; var DEFAULT_CONFIG = { theme: null, databases: [], windowRect: null }; var config; var watcher; var notify = pl.observable(SettingsStore); var init = function() { loaded = false; config = DEFAULT_CONFIG; if (watcher) { watcher.die(); } watcher = new Watcher(gui.App.dataPath, NAME, DEFAULT_CONFIG, update); notify.init(); }; var load = function() { watcher.watch(update); }; var setTheme = function(theme) { var i = pl.Themes.getThemes().indexOf(theme); config.theme = i >= 0 ? theme : pl.Themes.getDefaultTheme(); watcher.save(config); notify(); }; var setWindowRect = function(x, y, width, height) { config.windowRect = { x: x, y: y, width: width, height: height }; watcher.save(config); notify(); }; var setDatabases = function() { config.databases = pl.DbItemStore.getDatabases(); watcher.save(config); notify(); }; var update = function(newConfig) { config = pl.extend(DEFAULT_CONFIG, newConfig); pl.BroadcastActions.settingsLoaded(); notify(); }; pl.Dispatcher.register(NAME, function(action) { switch (action.actionType) { case pl.DbItemStore.BROADCAST_CHANGED: setDatabases(); break; case SettingsStore.LOAD: load(); break; case SettingsStore.SET_THEME: setTheme(action.theme); break; case SettingsStore.SET_WINDOW_RECT: setWindowRect(action.x, action.y, action.width, action.height); break; } }); pl.SettingsStore = pl.extend(SettingsStore, { _init: init, getTheme: function() { return config.theme || pl.Themes.getDefaultTheme(); }, getDatabases: function() { return config.databases; }, getWindowRect: function() { return config.windowRect; } }); init(); })(pl||{});
kyle-ilantzis/pl-sql-client
src/js/stores/SettingsStore.js
JavaScript
gpl-3.0
2,879
var Phaser = Phaser || {}; var Mst = Mst || {}; Mst.BootState = function () { "use strict"; Phaser.State.call(this); }; Mst.prototype = Object.create(Phaser.State.prototype); Mst.prototype.constructor = Mst.BootState; Mst.BootState.prototype.init = function (map_int, usr_id) { "use strict"; var d = new Date(); var n = d.getTime(); this.core_file = "assets/maps/core.json"; this.quest_file = "assets/maps/quest.json"; this.map_int = map_int; this.map_file = "map.php?time="+n+"&uid="+usr_id+"&mapi="+map_int; //this.map_file = "assets/maps/map"+map_int+".json?time="+n+"&uid="+usr_id+"&mapi="+map_int; console.log(this.map_file); this.usr_id = usr_id; }; Mst.BootState.prototype.preload = function () { "use strict"; if (this.usr_id > 0) { this.load.text("core", this.core_file); this.load.text("quest", this.quest_file); this.load.text("map", this.map_file); } else { var a = this.load.image("login", "assets/images/loader2.png"); //console.log(a); } }; Mst.BootState.prototype.create = function () { "use strict"; var map_text, map_data, core_text, core_data, root_data, quest_text, quest_data; if (this.usr_id > 0) { map_text = this.game.cache.getText("map"); var n = map_text.lastIndexOf(">"); if (n > -1) { map_text = map_text.substring(n + 1); } //console.log(map_text); map_data = JSON.parse(map_text); console.log(map_data); core_text = this.game.cache.getText("core"); core_data = JSON.parse(core_text); quest_text = this.game.cache.getText("quest"); quest_data = JSON.parse(quest_text); console.log(quest_data); } root_data = { map_int: this.map_int, usr_id: this.usr_id }; console.log("Boot State"); console.log(root_data); this.game.state.start("LoadingState", true, false, core_data, map_data, root_data, quest_data); };
oremir/Mst
mst/js/states/BootState.js
JavaScript
gpl-3.0
1,903
Simpla CMS 2.3.8 = 0f9e3c6a3ac53725fa229f3620b7ca52
gohdan/DFC
known_files/hashes/simpla/design/js/highcharts/js/themes/grid.js
JavaScript
gpl-3.0
52
// ========================================================================== // Project: Brochurno // Copyright: @2011 Jason Dooley // ========================================================================== /*globals Brochurno module test ok equals same stop start */ module("Brochurno.SectionView"); // TODO: Replace with real unit test for Brochurno.SectionView test("test description", function() { var expected = "test"; var result = "test"; equals(result, expected, "test should equal test"); });
sevifives/Brochurno
tests/views/section_test.js
JavaScript
gpl-3.0
517
/** * @author Matthew Foster * @date December 27th 2007 */ var MultiCalendarBase = Class.create(); Object.extend(Object.extend(MultiCalendarBase.prototype, EventDispatcher.prototype), { buildInterface : function(container){ this.container = $(container); this.view = this.container.down(".view"); this.wrap = this.container.down(".wrap"); this.control = this.container.down(".control"); this.nextControl = this.control.down(".next"); this.prevControl = this.control.down(".previous"); }, setItemIncrement : function(num){ this.increment = num; }, getItemIncrement : function(){ return this.increment || 0; }, buildOptions : function(options){ this.options = Object.extend({ rangeOffset : 3, buffer : 25}, options || {}); }, createCalendar : function(element, date){ return new LabeledCalendar(element, date); }, scrollLeft : function(){ this.wrap.scrollLeft -= this.getItemIncrement(); }, scrollRight : function(){ this.wrap.scrollLeft += this.getItemIncrement(); }, insertCalendar : function(element){ try{ this.view.insertBefore(element, this.view.firstChild); } catch(e){ this.appendCalendar(element); } }, appendCalendar : function(element){ this.view.appendChild(element); }, getInitialRange : function(){ var date = new Date(); var start = new GregorianCalendar(date.getFullYear(), date.getMonth() -2); var end = new GregorianCalendar(date.getFullYear(),date.getMonth()+this.options.rangeOffset ); return $A(new GregorianCalendarRange(start, end)); } } );
TamuGeoInnovation/Tamu.GeoInnovation.websites.healthgis.tamu.edu
src/Main/scripts/Calendar/MultiCalendarBase.js
JavaScript
gpl-3.0
2,036
var request = require("request"); var AuthDetails = require("../../auth.json"); exports.commands = [ "image", //gives top image from google search "rimage", //gives random image from google search "ggif" //gives random gif from google search ]; exports.image = { usage: "<search query>", description: "gets the top matching image from google", process: function(bot, msg, args) { if (!AuthDetails || !AuthDetails.youtube_api_key || !AuthDetails.google_custom_search) { bot.sendMessage(msg.channel, "Image search requires both a YouTube API key and a Google Custom Search key!"); return; } //gets us a random result in first 5 pages var page = 1; //we request 10 items request("https://www.googleapis.com/customsearch/v1?key=" + AuthDetails.youtube_api_key + "&cx=" + AuthDetails.google_custom_search + "&q=" + (args.replace(/\s/g, '+')) + "&searchType=image&alt=json&num=10&start=" + page, function(err, res, body) { var data, error; try { data = JSON.parse(body); } catch (error) { console.log(error) return; } if (!data) { console.log(data); bot.sendMessage(msg.channel, "Error:\n" + JSON.stringify(data)); return; } else if (!data.items || data.items.length == 0) { console.log(data); bot.sendMessage(msg.channel, "No result for '" + args + "'"); return; } var randResult = data.items[0]; bot.sendMessage(msg.channel, randResult.title + '\n' + randResult.link); }); } } exports.rimage = { usage: "<search query>", description: "gets a random image matching tags from google", process: function(bot, msg, args) { if (!AuthDetails || !AuthDetails.youtube_api_key || !AuthDetails.google_custom_search) { bot.sendMessage(msg.channel, "Image search requires both a YouTube API key and a Google Custom Search key!"); return; } //gets us a random result in first 5 pages var page = 1 + Math.floor(Math.random() * 5) * 10; //we request 10 items request("https://www.googleapis.com/customsearch/v1?key=" + AuthDetails.youtube_api_key + "&cx=" + AuthDetails.google_custom_search + "&q=" + (args.replace(/\s/g, '+')) + "&searchType=image&alt=json&num=10&start=" + page, function(err, res, body) { var data, error; try { data = JSON.parse(body); } catch (error) { console.log(error) return; } if (!data) { console.log(data); bot.sendMessage(msg.channel, "Error:\n" + JSON.stringify(data)); return; } else if (!data.items || data.items.length == 0) { console.log(data); bot.sendMessage(msg.channel, "No result for '" + args + "'"); return; } var randResult = data.items[Math.floor(Math.random() * data.items.length)]; bot.sendMessage(msg.channel, randResult.title + '\n' + randResult.link); }); } } exports.ggif = { usage: "<search query>", description: "get random gif matching tags from google", process: function(bot, msg, args) { //gets us a random result in first 5 pages var page = 1 + Math.floor(Math.random() * 5) * 10; //we request 10 items request("https://www.googleapis.com/customsearch/v1?key=" + AuthDetails.youtube_api_key + "&cx=" + AuthDetails.google_custom_search + "&q=" + (args.replace(/\s/g, '+')) + "&searchType=image&alt=json&num=10&start=" + page + "&fileType=gif", function(err, res, body) { var data, error; try { data = JSON.parse(body); } catch (error) { console.log(error) return; } if (!data) { console.log(data); bot.sendMessage(msg.channel, "Error:\n" + JSON.stringify(data)); return; } else if (!data.items || data.items.length == 0) { console.log(data); bot.sendMessage(msg.channel, "No result for '" + args + "'"); return; } var randResult = data.items[Math.floor(Math.random() * data.items.length)]; bot.sendMessage(msg.channel, randResult.title + '\n' + randResult.link); }); } }
sr229/nodejs-kotori
plugins/Images/images.js
JavaScript
gpl-3.0
4,604
export default function * responseTime(next) { /* * A simple middleware to set X response time header */ let start = new Date; yield next let ms = new Date - start this.set('X-Response-Time', ms + 'ms') }
Fenykepy/simplepass
src/utils/response-time.js
JavaScript
gpl-3.0
223
const ajaxurl = window.mc4wp_vars.ajaxurl const m = require('mithril') if (!Element.prototype.matches) { Element.prototype.matches = Element.prototype.msMatchesSelector || Element.prototype.webkitMatchesSelector } function showDetails (evt) { evt.preventDefault() const link = evt.target const next = link.parentElement.parentElement.nextElementSibling const listID = link.getAttribute('data-list-id') const mount = next.querySelector('div') if (next.style.display === 'none') { m.request({ method: 'GET', url: ajaxurl + '?action=mc4wp_get_list_details&ids=' + listID }).then(details => { m.render(mount, view(details.shift())) }) next.style.display = '' } else { next.style.display = 'none' } } function view (data) { return [ m('h3', 'Merge fields'), m('table.widefat.striped', [ m('thead', [ m('tr', [ m('th', 'Name'), m('th', 'Tag'), m('th', 'Type') ]) ]), m('tbody', data.merge_fields.map(f => ( m('tr', [ m('td', [ f.name, f.required && m('span.mc4wp-red', '*') ]), m('td', [ m('code', f.tag) ]), m('td', [ f.type, ' ', f.options && f.options.date_format ? '(' + f.options.date_format + ')' : '', f.options && f.options.choices ? '(' + f.options.choices.join(', ') + ')' : '' ]) ]) ))) ]), data.interest_categories.length > 0 && [ m('h3', 'Interest Categories'), m('table.striped.widefat', [ m('thead', [ m('tr', [ m('th', 'Name'), m('th', 'Type'), m('th', 'Interests') ]) ]), m('tbody', data.interest_categories.map(f => ( m('tr', [ m('td', [ m('strong', f.title), m('br'), m('br'), 'ID: ', m('code', f.id) ]), m('td', f.type), m('td', [ m('div.mc4wp-row', { style: 'margin-bottom: 4px;' }, [ m('div.mc4wp-col.mc4wp-col-3', [ m('strong', { style: 'display: block; border-bottom: 1px solid #eee;' }, 'Name') ]), m('div.mc4wp-col.mc4wp-col-3', [ m('strong', { style: 'display: block; border-bottom: 1px solid #eee;' }, 'ID') ]) ]), Object.keys(f.interests).map((id) => ( m('div.mc4wp-row.mc4wp-margin-s', [ m('div.mc4wp-col.mc4wp-col-3', f.interests[id]), m('div.mc4wp-col.mc4wp-col-3', [ m('code', { title: 'Interest ID' }, id) ]), m('br.clearfix.clear.cf') ]) )) ]) ]) ))) ]) ] ] } const table = document.getElementById('mc4wp-mailchimp-lists-overview') if (table) { table.addEventListener('click', (evt) => { if (!evt.target.matches('.mc4wp-mailchimp-list')) { return } showDetails(evt) }) }
ibericode/mailchimp-for-wordpress
assets/src/js/admin/list-overview.js
JavaScript
gpl-3.0
3,182
import Ember from 'ember'; import DS from 'ember-data'; export default DS.Transform.extend({ deserialize: function(serialized) { return (Ember.typeOf(serialized) == "array") ? serialized : []; }, serialize: function(deserialized) { var type = Ember.typeOf(deserialized); if (type == 'array') { return deserialized } else if (type == 'string') { return deserialized.split(',').map(function(item) { return Ember.$.trim(item); }); } else { return []; } } });
johan--/rose
rui/app/transforms/array.js
JavaScript
gpl-3.0
522
const protobuf = require('protobufjs') const path = require('path') protobuf.load(path.resolve('../protobuf/meetings.proto')) .then(start) .catch(console.error) function start (root) { const User = root.lookupType('meetings.User') const payload = { firstName: 'Lucas', lastName: 'Santos', addresses: [ { line1: 'Rua X', line2: 3540, type: 0 } ] } const message = User.fromObject(payload) const buffer = User.encode(message).finish() console.log(buffer, message) const decoded = User.decode(buffer) const obj = User.toObject(decoded) console.log(decoded, obj) }
khaosdoctor/my-notes
protobuf/examples/protobuf-js/proto.js
JavaScript
gpl-3.0
639
var core__cm_func_8h = [ [ "__CORE_CMFUNC_H", "core__cm_func_8h.html#a50c339231579f3b052ed89428a8a2453", null ] ];
MyEmbeddedWork/ARM_CORTEX_M3-STM32
1. Docs/Doxygen/html/core__cm_func_8h.js
JavaScript
gpl-3.0
118
(function(window) { var RectInternalRepresentation = function(primitive) { var me = new ArmContext.InternalRepresentation(primitive); this._width = 10; this._height = 10; me.GetWidth = function() { return this._width; }; me.SetWidth = function(O) { gizmo.Filter(O, "Number"); this.Update({ width: O, height: this.GetHeight() }); }; me.GetHeight = function() { return this._height; }; me.SetHeight = function(O) { gizmo.Filter(O, "Number"); this.UpdatePoints({x: this.GetX(), y: this.GetY(), width: this.GetWidth(), height: O}); }; me.GetPointsOfMatrix = function() { return this._points; }; me.SetPointsOfMatrix = function(O) { gizmo.Filter(O, "Array"); return this._points; }; me.Set = function(O) { for(var name in O) { switch( name ) { case "width" : { this._width = O[name]; if(this._onChanged) { this._onChanged.call(primitive); }; }; break; case "height" : { this._height = O[name]; if(this._onChanged) { this._onChanged.call(primitive); }; }; break; }; }; this._points = new $M( [ [0 ,0 ,1], [this._width,0 ,1], [this._width,this._height,1], [0 ,this._height,1] ] ); }; return me; } ArmContext.RectInternalRepresentation = RectInternalRepresentation; })();
sogimu/ArmContext
modules/Primitve/Rect/RectInternalRepresentation.js
JavaScript
gpl-3.0
1,900
function iniciarFormularioRegistro() { // animacion de fadeIn $('.register').addClass('animated fadeIn'); // elimino la clase para poder animar nuevamente setTimeout(function () { $('.register').removeClass('fadeIn'); }, 3000); $('.sigPaso').on('click', function () { if ($(this).hasClass('locked') === false) { if ($(this).parent().attr('id') === 'first_name_form') { submitFirstName(); } if ($(this).parent().parent().attr('id') === 'email_form') { submitEmail(); } if ($(this).parent().parent().attr('id') === 'phone_form') { submitPhone(); } if ($(this).parent().parent().attr('id') === 'codigo_form') { submitCodigo(); } } }); $('.antPaso').on('click', function () { if ($(this).hasClass('locked') === false) { if ($(this).parent().parent().attr('id') === 'email_form') { $('#termsPriv').fadeIn(); $('.register').addClass('bounceOut'); setTimeout(function () { $('.register').removeClass(' bounceOut'); $('.register').addClass('fadeIn'); $("#email_form").addClass('hide'); $('#first_name_form').removeClass('hide'); $('#first_name_form').addClass('animated fadeIn'); $('.register').removeClass('fadeIn'); }, 600); } if ($(this).parent().parent().attr('id') === 'phone_form') { $('.register').addClass('bounceOut'); setTimeout(function () { $('.register').removeClass(' bounceOut'); $('.register').addClass('fadeIn'); $("#phone_form").addClass('hide'); $('#email_form').removeClass('hide'); $('#email_form').addClass('animated fadeIn'); $('.register').removeClass('fadeIn'); }, 600); } } }); $('#first_name').on('keyup', function (e) { if (e.keyCode === 13) { submitFirstName(); return false; } }); $('#email').on('keyup', function (e) { if (e.keyCode === 13) { submitEmail(); return false; } }); $('#phone').on('keyup', function (e) { if (e.keyCode === 13) { submitPhone(); return false; } }); $('#codigo').on('keyup', function (e) { if (e.keyCode === 13) { submitCodigo(); return false; } }); } function submitFirstName() { if ($('#first_name').val() === '') { $('.register').addClass('shake'); setTimeout(function () { $('.register').removeClass('shake'); }, 3000); } else { if (validateName($('#first_name').val())) { $('#leyendaNombre').html(""); $('#first_name').removeClass('invalid'); $('#first_name').siblings('.fa').removeClass('invalid'); } if (!validateName($('#first_name').val())) { $('.register').addClass('shake'); $('#first_name').addClass('invalid'); $('#first_name').siblings('.fa').addClass('invalid'); setTimeout(function () { $('.register').removeClass('shake'); }, 3000); $('#leyendaNombre').html("<small style='color: red;'>Tu nombre no puede contener caracteres especiales.</small>"); } else { $('#termsPriv').fadeOut(); $('.register').addClass('bounceOut'); setTimeout(function () { $('.register').removeClass(' bounceOut'); $('.register').addClass('fadeIn'); $("#first_name_form").addClass('hide'); $('#email_form').removeClass('hide'); $('#email_form').addClass('animated fadeIn'); $('.register').removeClass('fadeIn'); }, 600); } } } function submitEmail() { if ($('#email').val() === '') { $('.register').addClass('shake'); setTimeout(function () { $('.register').removeClass('shake'); }, 3000); } else { if (validateEmail($('#email').val())) { $('#leyendaEmail').html(""); $('#email').removeClass('invalid'); $('#email').siblings('.fa').removeClass('invalid'); } if (!validateEmail($('#email').val())) { $('.register').addClass('shake'); $('#email').addClass('invalid'); $('#email').siblings('.fa').addClass('invalid'); setTimeout(function () { $('.register').removeClass('shake'); }, 3000); $('#leyendaEmail').html("<small style='color: red;'>Tu dirección de correo es incorrecta, verifica la estructura. Ej. ejemplo@mail.com</small>"); } else { $('.register').addClass('bounceOut'); setTimeout(function () { $('.register').removeClass(' bounceOut'); $('.register').addClass('fadeIn'); $('#email_form').addClass('hide'); $('#phone_form').removeClass('hide'); $('#phone_form').addClass('animated fadeIn'); $('.register').removeClass('fadeIn'); }, 600); } } } function submitPhone() { var phone = $('#phone').val(); phone= phone.replace(/\-/g,""); if ($('#phone').val() === '') { $('.register').addClass('shake'); setTimeout(function () { $('.register').removeClass('shake'); }, 3000); } if ((phone.length < 10 || phone.length > 10) || validarSiNumero(phone) === true ) { $('.register').addClass('shake'); setTimeout(function () { $('.register').removeClass('shake'); }, 3000); $('#leyendaTelError').html("<small style='color: red;'>El teléfono debe contener 10 caracteres numéricos</small>"); } else { if ($('#phone').hasClass('invalid')) { $('.register').addClass('shake'); setTimeout(function () { $('.register').removeClass('shake'); }, 3000); } else { $('#leyendaTelError').html(""); $('#phone').prop('disabled', true); $('.sigPaso').addClass('locked'); $.ajax({ type: 'POST', data: { telefonoCelular: $('#phone').val(), email: $('#email').val(), nombreCompleto: $('#first_name').val() }, url: $.contextAwarePathJS + "cotizador/solicitarCodigo", success: function (data, textStatus) { var respuesta = eval(data); console.log(respuesta); if (respuesta.mensajeEnviado === true) { $('#editarTelefono').html(""); $('#editarTelefono').hide(); $('.register').addClass('bounceOut'); setTimeout(function () { $('.register').removeClass(' bounceOut'); $('.register').addClass('fadeIn'); $('#phone_form').addClass('hide'); $('#codigo_form').removeClass('hide'); $('.register').removeClass('fadeIn'); $('#leyendaCodigo').html("<small style='color: #25a3ff;'><strong>Espera por favor entre 15 y 30 segundos para recibir tu código. Si después de 30 segundos no recibes el código, puedes avanzar capturando 00000.</strong></small>"); }, 600); setTimeout(function () { $('#editarTelefono').html("<span class='backBtn'>Corregir Teléfono</span>"); $('#editarTelefono').fadeIn(); $('#editarTelefono').click(function () { $('.register').addClass('bounceOut'); setTimeout(function () { $('.register').removeClass(' bounceOut'); $('.register').addClass('fadeIn'); $('#codigo_form').addClass('hide'); $('#phone_form').removeClass('hide'); $('#phone_form').addClass('animated fadeIn'); $('.register').removeClass('fadeIn'); }, 600); }); }, 20000); } else if (respuesta.encontrado === true && respuesta.shortUrl) { $('#resumirSolicitud').html(""); $('#resumirSolicitud').hide(); $('.register').addClass('bounceOut'); setTimeout(function () { $('.register').removeClass(' bounceOut'); $('.register').addClass('fadeIn'); $('#phone_form').addClass('hide'); $('#resume_form').removeClass('hide'); $('.register').removeClass('fadeIn'); }, 600); $('#resumirSolicitud').html("<span class='resumenBtn'>Continuar Solicitud</span>"); $('#resumirSolicitud').fadeIn(); $('#resumirSolicitud').click(function () { window.location.href = respuesta.shortUrl; }); } else if (respuesta.multiplesClientes === true){ $('#resumirSolicitud').html(""); $('#resumirSolicitud').hide(); $('.register').addClass('bounceOut'); setTimeout(function () { $('.register').removeClass(' bounceOut'); $('.register').addClass('fadeIn'); $('#phone_form').addClass('hide'); $('#many_form').removeClass('hide'); $('.register').removeClass('fadeIn'); }, 600); $('#resumirSolicitud').html("<span class='resumenBtn'>Existe más de una solicitud vigente a este número</span>"); $('#resumirSolicitud').fadeIn(); } else { $('#leyendaTel').html("<small style='color: red;'>Ocurrió un problema al enviar el mensaje. Verifica tu número de Celular.</small>"); } $('#phone').prop('disabled', false); $('.sigPaso').removeClass('locked'); }, error: function (XMLHttpRequest, textStatus, errorThrown) { sweetAlert("Oops...", "Algo salió mal, intenta nuevamente en unos minutos.", "error"); $('#phone').prop('disabled', false); $('.sigPaso').removeClass('locked'); } }); } } } function submitCodigo() { var codigo = $('#codigo').val(); if ($('#codigo').val() === '') { $('.register').addClass('shake'); setTimeout(function () { $('.register').removeClass('shake'); }, 3000); } if ((codigo.length < 5 || codigo.length > 5) || validarSiNumero(codigo) === true ) { $('.register').addClass('shake'); setTimeout(function () { $('.register').removeClass('shake'); }, 3000); $('#leyendaCodigoError').html("<small style='color: red;'>El código debe contener 5 caracteres numéricos</small>"); } else { if ($('#codigo').hasClass('invalid')) { $('.register').addClass('shake'); setTimeout(function () { $('.register').removeClass('shake'); }, 3000); } else { $('#leyendaCodigoError').html(""); $.ajax({ type: 'POST', data: { codigoConfirmacion: $('#codigo').val() }, url: $.contextAwarePathJS + "cotizador/resultadoVerificacion", success: function (data, textStatus) { var respuesta = eval(data); if (respuesta.resultado === true) { $('.register').addClass('bounceOut'); setTimeout(function () { $('.register').removeClass(' bounceOut'); $('.register').addClass('fadeIn'); $('#codigo_form').addClass('hide'); $('#thanks').removeClass('hide'); var registeredName = $('#first_name').val(); $('.register').removeClass('fadeIn'); $('#thanks').addClass('animated fadeIn'); $('#registeredName').html(registeredName); }, 600); $('#datosRegistro').text("¡Registrado Correctamente!"); $('#divRegistroCompleto').html("<p id='btnRegistro' class='marginAuto width350 nextAction cotizador-box'>Siguiente</p>"); $('#divRegistroCompleto').fadeIn(); initActions(); } else { $('#leyendaCodigo').html("<small style='color: red;'>El código indicado no es correcto, Verificalo e intenta nuevamente por favor.</small>"); } }, error: function (XMLHttpRequest, textStatus, errorThrown) { sweetAlert("Oops...", "Algo salió mal, intenta nuevamente en unos minutos.", "error"); } }); } } } function validateName(nombre) { var re = /^([a-zA-Z \. \- \@ ñáéíóúüÑÁÉÍÓÚÜ])+$/; return re.test(nombre); } function validarSiNumero(numero){ if (!/^([0-9])*$/.test(numero)){ return true; } else{ return false; } }
therealthom/kosmos-app
web-app/js/registro.js
JavaScript
gpl-3.0
14,506
/* url utils @sha0coder */ exports.getUrlDir = function(url) { return url.replace(/\/[^\/]*$/,'/') } exports.getBase = function(url) { var spl = url.split('/'); return spl[0]+'//'+spl[2]; }; exports.getDomain = function(url) { return url.split('/')[2]; }; exports.isDir = function(url) { return (url.charAt(url.length-1) == '/') }; exports.isDirListing = function(html) { return (html.search('<title>Index of /') > 0); }; exports.fixUrl = function(url) { url = url.replace(/\x0d/,'%0d').replace('/./','/'); //.replace(/\/\/$/,'/'); if (url.charAt(0)!='h') url = 'http://'+url; if (url.charAt(url.length-1) != '/') url = url+'/'; return url; }; exports.fixDir = function(dir) { if (dir.charAt(0) == '/') dir = dir.substring(1,dir.length); return dir; };
0x0mar/bluebox-ng
external/dirscan-node/lib/url.js
JavaScript
gpl-3.0
880
module.exports = { // Scale for HTML Canvas (1=2kx2k, 2=1kx1k, 4=500x500, ...) scaleFactor: 4, };
DigitalShooting/DSM
config/dsm.js
JavaScript
gpl-3.0
103
var express = require('express'); var routes = function (Page) { var feedbackController = require('../controllers/feedbackController')(Page); var feedbackRouter = express.Router(); feedbackRouter.route('/') .get(feedbackController.findByPage); return feedbackRouter; }; module.exports = routes;
devrecipe/codendoc
routes/feedbackRoutes.js
JavaScript
gpl-3.0
324
import Ember from 'ember'; var total = 0; export default Ember.Controller.extend({ isShowingHelp: false, isShowingModal: false, actions: { toggleModal: function() { this.toggleProperty('isShowingModal'); }, toggleModal1: function() { this.toggleProperty('isShowingModals'); }, toggleModal2: function() { this.toggleProperty('isShowingModalss'); }, toggleModal3: function() { this.toggleProperty('isShowingModalsss'); }, toggleModal4: function() { this.toggleProperty('isShowingModalssss'); }, toggleModal5: function() { this.toggleProperty('isShowingModalsssss'); }, agreement: function() { this.transitionToRoute('agreement'); }, norewardSelection: function(arg, arg1) { var amount = this.get('amount'); if (amount === null || amount === undefined || amount === "") { this.set('amounterrormessage', "field cannot be empty") return; } var amount = arg; var reward = arg1; console.log(amount); this.set('message', "You have not selected any rewards and you want to contribute Rs "+ amount +" and You will get "+ reward +" reward. Do you want to continue?"); }, rewardSelection: function(arg, arg1) { var amount = arg; var reward = arg1; this.set('message', "You have selected Rs. " + amount + " and You will get " + reward + " reward. Do you want to continue?"); console.log("display"); }, addtocart : function(){ var quantity = this.get("quantity"); var amt = 1000* quantity; total =total + amt; console.log(total); var jsonvariable =Ember.$.getJSON("reward.json"); console.log( Ember.inspect(jsonvariable) ) console.log("jsonvariable",JSON.stringify(jsonvariable)); console.log("ResponseText: " + JSON.stringify(jsonvariable)); // console.log(str.reward[0].rewardamount); // alert(object.toSource(jsonvariable)); this.toggleProperty('isShowingModals'); //var str =JSON.parse(jsonvariable); // console.log(str); var title=""; var array2 = []; console.log("JSON2:before function "+array2); Ember.$.getJSON( "reward.json", function(json) { var array = []; for (var key in json) { if (json.hasOwnProperty(key)) { var item = json[key]; array.push({ rewardtitle: item.rewardtitle, rewardamount: item.rewardamount, rewarddescription: item.rewarddescription }); console.log("rewardtitle"+JSON.stringify(array[0])); /*var item2 =json[key]; array2.push({ rewardtitle: item.rewardtitle, rewardamount: item.rewardamount, rewarddescription: item.rewarddescription }) */ } } console.log("JSON: "+ JSON.stringify(array)); title= JSON.stringify(array[0].rewardtitle); console.log('title :'+title); // this.set('myrewardtitle',title); /* array2=array.slice(); console.log("JSON2: "+ JSON.stringify(array2));*/ // var array2 = array.concat(); for(var i=0;i<array.length;i++){ console.log("1"); array2[i]=array[i]; console.log("2"); } }); this.set('myrewardtitle',title); /* var array3=[]; array3=array.slice(); console.log("JSON3: "+ JSON.stringify(array3));*/ console.log("JSON2: "+ JSON.stringify(array2)); /* var jsstr=JSON.parse(abc); console.log(abc.rewardamount); for(var i=0;i<JSONItems.length;i++){ console.log(JSONItems[i]); }*/ /* var JSONItems1 = []; var strs=Ember.$.get( "reward.json", function( data){ JSONItems1 = JSON.parse(data); console.log(JSONItems1); }); console.log(strs);*/ //console.log(abc.reward[0]); }, payment: function() { alert("Do not Refresh the page...."); window.location.replace("https://www.billdesk.com/savepgi/"); }, showHelp: function() { this.toggleProperty('isShowingHelp'); } } });
vikramviswanathan/CrowdFundingUI
app/controllers/reward.js
JavaScript
gpl-3.0
5,172
/** * LifterLMS Checkout Screen related events and interactions * * @package LifterLMS/Scripts * * @since 3.0.0 * @version 3.34.5 */ ( function( $ ) { var llms_checkout = function() { /** * Array of validation functions to call on form submission * * @type array * @since 3.0.0 * @version 3.0.0 */ var before_submit = []; /** * Array of gateways to be automatically bound when needed * * @type array * @since 3.0.0 * @version 3.0.0 */ var gateways = []; this.$checkout_form = $( '#llms-product-purchase-form' ); this.$confirm_form = $( '#llms-product-purchase-confirm-form' ); this.$form_sections = false; this.form_action = false; /** * Initialize checkout JS & bind if on the checkout screen * * @since 3.0.0 * @since 3.34.5 Make sure we bind click events for the Show / Hide login area at the top of the checkout screen * even if there's no llms product purchase form. * * @return void */ this.init = function() { var self = this; if ( $( '.llms-checkout-wrapper' ).length ) { this.bind_login(); } if ( this.$checkout_form.length ) { this.form_action = 'checkout'; this.$form_sections = this.$checkout_form.find( '.llms-checkout-section' ); this.$checkout_form.on( 'submit', this, this.submit ); // add before submit event for password strength meter if one's found if ( $( '.llms-password-strength-meter' ).length ) { this.add_before_submit_event( { data: LLMS.PasswordStrength, handler: LLMS.PasswordStrength.checkout, } ); } this.bind_coupon(); this.bind_gateways(); } else if ( this.$confirm_form.length ) { this.form_action = 'confirm'; this.$form_sections = this.$confirm_form.find( '.llms-checkout-section' ); this.$confirm_form.on( 'submit', function() { self.processing( 'start' ); } ); } }; /** * Public function which allows other classes or extensions to add * before submit events to llms checkout private "before_submit" array * * @param object obj object of data to push to the array * requires at least a "handler" key which should pass a callable function * "data" can be anything, will be passed as the first parameter to the handler function * @since 3.0.0 * @version 3.0.0 */ this.add_before_submit_event = function( obj ) { if ( ! obj.handler || 'function' !== typeof obj.handler ) { return; } if ( ! obj.data ) { obj.data = null; } before_submit.push( obj ); }; /** * Add an error message * * @param string message error message string * @param mixed data optional error data to output on the console * @return void * @since 3.27.0 * @version 3.27.0 */ this.add_error = function( message, data ) { var id = 'llms-checkout-errors'; $err = $( '#' + id ); if ( ! $err.length ) { $err = $( '<ul class="llms-notice llms-error" id="' + id + '" />' ); $( '.llms-checkout-wrapper' ).prepend( $err ); } $err.append( '<li>' + message + '</li>' ); if ( data ) { console.error( data ); } }; /** * Public function which allows other classes or extensions to add * gateways classes that should be bound by this class * * @param obj gateway_class callable class object * @since 3.0.0 * @version 3.0.0 */ this.add_gateway = function( gateway_class ) { gateways.push( gateway_class ); }; /** * Bind coupon add & remove button events * * @return void * @since 3.0.0 * @version 3.0.0 */ this.bind_coupon = function() { var self = this; // show & hide the coupon field & button $( 'a[href="#llms-coupon-toggle"]' ).on( 'click', function( e ) { e.preventDefault(); $( '.llms-coupon-entry' ).slideToggle( 400 ); } ); // apply coupon click $( '#llms-apply-coupon' ).on( 'click', function( e ) { e.preventDefault(); self.coupon_apply( $( this ) ); } ); // remove coupon click $( '#llms-remove-coupon' ).on( 'click', function( e ) { e.preventDefault(); self.coupon_remove( $( this ) ); } ); }; /** * Bind gateway section events * * @return void * @since 3.0.0 * @version 3.0.0 */ this.bind_gateways = function() { this.load_gateways(); if ( ! $( 'input[name="llms_payment_gateway"]' ).length ) { $( '#llms_create_pending_order' ).removeAttr( 'disabled' ); } // add class and trigger watchable event when gateway selection changes $( 'input[name="llms_payment_gateway"]' ).on( 'change', function() { $( 'input[name="llms_payment_gateway"]' ).each( function() { var $el = $( this ), $parent = $el.closest( '.llms-payment-gateway' ), $fields = $parent.find( '.llms-gateway-fields' ).find( 'input, textarea, select' ), checked = $el.is( ':checked' ), display_func = ( checked ) ? 'addClass' : 'removeClass'; $parent[ display_func ]( 'is-selected' ); if ( checked ) { // enable fields $fields.removeAttr( 'disabled' ); // emit a watchable event for extensions to hook onto $( '.llms-payment-gateways' ).trigger( 'llms-gateway-selected', { id: $el.val(), $selector: $parent, } ); } else { // disable fields $fields.attr( 'disabled', 'disabled' ); } } ); } ); // enable / disable buttons depending on field validation status $( '.llms-payment-gateways' ).on( 'llms-gateway-selected', function( e, data ) { var $submit = $( '#llms_create_pending_order' ); if ( data.$selector && data.$selector.find( '.llms-gateway-fields .invalid' ).length ) { $submit.attr( 'disabled', 'disabled' ); } else { $submit.removeAttr( 'disabled' ); } } ); }; /** * Bind click events for the Show / Hide login area at the top of the checkout screen * * @since 3.0.0 * @since 3.34.5 When showing the login form area make sure we slide up the `.llms-notice` link's parent too. * * @return void */ this.bind_login = function() { $( 'a[href="#llms-show-login"]' ).on( 'click', function( e ) { e.preventDefault(); $( this ).closest( '.llms-info,.llms-notice' ).slideUp( 400 ); $( 'form.llms-login' ).slideDown( 400 ); } ); }; /** * Clear error messages * * @return void * @since 3.27.0 * @version 3.27.0 */ this.clear_errors = function() { $( '#llms-checkout-errors' ).remove(); }; /** * Triggered by clicking the "Apply Coupon" Button * Validates the coupon via JS and adds error / success messages * On success it will replace partials on the checkout screen with updated * prices and a "remove coupon" button * * @param obj $btn jQuery selector of the Apply button * @return void * @since 3.0.0 * @version 3.0.0 */ this.coupon_apply = function ( $btn ) { var self = this, $code = $( '#llms_coupon_code' ), code = $code.val(), $messages = $( '.llms-coupon-messages' ), $errors = $messages.find( '.llms-error' ), $container = $( 'form.llms-checkout' ); LLMS.Spinner.start( $container ); window.LLMS.Ajax.call( { data: { action: 'validate_coupon_code', code: code, plan_id: $( '#llms-plan-id' ).val(), }, beforeSend: function() { $errors.hide(); }, success: function( r ) { LLMS.Spinner.stop( $container ); if ( 'error' === r.code ) { var $message = $( '<li>' + r.message + '</li>' ); if ( ! $errors.length ) { $errors = $( '<ul class="llms-notice llms-error" />' ); $messages.append( $errors ); } else { $errors.empty(); } $message.appendTo( $errors ); $errors.show(); } else if ( r.success ) { $( '.llms-coupon-wrapper' ).replaceWith( r.data.coupon_html ); self.bind_coupon(); $( '.llms-payment-gateways' ).replaceWith( r.data.gateways_html ); self.bind_gateways(); $( '.llms-order-summary' ).replaceWith( r.data.summary_html ); } } } ); }; /** * Called by clicking the "Remove Coupon" button * Removes the coupon via AJAX and unsets related session data * * @param obj $btn jQuery selector of the Remove button * @return void * @since 3.0.0 * @version 3.0.0 */ this.coupon_remove = function( $btn ) { var self = this, $container = $( 'form.llms-checkout' ); LLMS.Spinner.start( $container ); window.LLMS.Ajax.call( { data: { action: 'remove_coupon_code', plan_id: $( '#llms-plan-id' ).val(), }, success: function( r ) { LLMS.Spinner.stop( $container ); if ( r.success ) { $( '.llms-coupon-wrapper' ).replaceWith( r.data.coupon_html ); self.bind_coupon(); $( '.llms-order-summary' ).replaceWith( r.data.summary_html ); $( '.llms-payment-gateways' ).replaceWith( r.data.gateways_html ); self.bind_gateways(); } } } ); }; /** * Scroll error messages into view * * @return void * @since 3.27.0 * @version 3.27.0 */ this.focus_errors = function() { $( 'html, body' ).animate( { scrollTop: $( '#llms-checkout-errors' ).offset().top - 50, }, 200 ); }; /** * Bind external gateway JS * * @return void * @since 3.0.0 * @version 3.0.0 */ this.load_gateways = function() { for ( var i = 0; i <= gateways.length; i++ ) { var g = gateways[i]; if ( typeof g === 'object' && g !== null ) { if ( g.bind !== undefined && 'function' === typeof g.bind ) { g.bind(); } } } }; /** * Start or stop processing events on the checkout form * * @param string action whether to start or stop processing [start|stop] * @return void * @since 3.0.0 * @version 3.24.1 */ this.processing = function( action ) { var func, $form; switch ( action ) { case 'stop': func = 'removeClass'; break; case 'start': default: func = 'addClass'; break; } if ( 'checkout' === this.form_action ) { $form = this.$checkout_form; } else if ( 'confirm' === this.form_action ) { $form = this.$confirm_form; } $form[ func ]( 'llms-is-processing' ); LLMS.Spinner[ action ]( this.$form_sections ); }; /** * Handles form submission * Calls all validation events in `before_submit[]` * waits for call backs and either displays returned errors * or submits the form when all are successful * * @param obj e JS event object * @return void * @since 3.0.0 * @version 3.27.0 */ this.submit = function( e ) { var self = e.data, num = before_submit.length, checks = 0, max_checks = 60000, errors = [], finishes = 0, successes = 0, interval; e.preventDefault(); // add spinners self.processing( 'start' ); // remove errors to prevent duplicates self.clear_errors(); // start running all the events for ( var i = 0; i < before_submit.length; i++ ) { var obj = before_submit[ i ]; obj.handler( obj.data, function( r ) { finishes++; if ( true === r ) { successes++; } else if ( 'string' === typeof r ) { errors.push( r ); } } ); } // run an interval to wait for finishes interval = setInterval( function() { var clear = false, stop = false; // timeout... if ( checks >= max_checks ) { clear = true; stop = true; } else if ( num === finishes ) { // everything has finished // all were successful, submit the form if ( num === successes ) { clear = true; self.$checkout_form.off( 'submit', self.submit ); self.$checkout_form.trigger( 'submit' ); } else if ( errors.length ) { clear = true; stop = true; for ( var i = 0; i < errors.length; i++ ) { self.add_error( errors[ i ] ); } self.focus_errors(); } } if ( clear ) { clearInterval( interval ); } if ( stop ) { self.processing( 'stop' ); } checks++; }, 100 ); }; // initialize this.init(); return this; }; window.llms = window.llms || {}; window.llms.checkout = new llms_checkout(); } )( jQuery );
gocodebox/lifterlms
assets/js/llms-form-checkout.js
JavaScript
gpl-3.0
12,594
'use strict'; angular.module('tucha') .controller('GridCtrl', function ($rootScope, $scope, $location, $http, $timeout, states, columns) { var stateName = $location.path().split('/')[1]; for (var i = 0; i < states.length; i++) { if (states[i].name === stateName) { $scope.state = states[i]; states[i].active = true; $scope.title = states[i].title; } else { states[i].active = false; } } $http.get('/r/' + stateName).then(function (data) { //$scope.data = data.data; var columnDefs = []; if (stateName === 'animal') { columnDefs.push({ field: 'id', name: '', width: 50, cellTemplate: '<div class="grid-image-cell"><img width="50" src="r/animal/{{row.entity.id}}/photo_wh50"/></div>' }); } else if (stateName === 'associate') { $scope.feesDueList = []; $scope.currentYear = new Date().getFullYear(); for (var i = 0; i < data.data.length; i++) { if (!data.data[i].last_paid_fee || data.data[i].last_paid_fee < $scope.currentYear) { $scope.feesDueList.push(data.data[i]); } } } for (var key in data.data[0]) { columnDefs.push(columns[key]); } $scope.gridOptions = { data: data.data, columnDefs: columnDefs, minRowsToShow: data.data.length + 0.1, enableHorizontalScrollbar: 0, enableVerticalScrollbar: 0, enableGridMenu: true, rowTemplate: 'views/directives/rowTemplate.html', rowHeight: 50, onRegisterApi: function (gridApi) { $scope.gridApi = gridApi; }, appScopeProvider: { rowClick: function (row) { if (stateName === 'animal') { // generate current sort ids for the next and previous button to work $rootScope.animalsSequence = []; var rows = $scope.gridApi.core.getVisibleRows(); for (var i = 0; i < rows.length; i++) { $rootScope.animalsSequence.push(rows[i].entity.id); } } else if (stateName === 'volunteer' || stateName === 'associate') { // theese 2 sections are only shortcuts to persons with different filtered lists stateName = 'person'; } $location.path('/' + stateName + '/' + row.entity.id); } } }; }); $scope.add = function () { $location.path('/' + stateName + "/new"); }; });
aurhe/tucha
client/app/scripts/controllers/grid.js
JavaScript
gpl-3.0
3,120
module.exports={A:{A:{"2":"H D HB","132":"G E A B"},B:{"132":"C p z J L N I"},C:{"2":"5 bB F K H D G E A B C p z J L N I ZB TB","132":"0 1 3 4 6 7 8 O P Q R S T U V W X Y Z a c d e f g h i j k l m n o M q r s t u v w x y DB AB BB"},D:{"1":"0 1 3 4 6 7 8 J L N I O P Q R S T U V W X Y Z a c d e f g h i j k l m n o M q r s t u v w x y DB AB BB NB dB GB IB FB JB KB LB","16":"F K H D G E A B C p z"},E:{"2":"F K H D G E A B C MB EB OB PB QB RB SB b UB"},F:{"1":"1 J L N I O P Q R S T U V W X Y Z a c d e f g h i j k l m n o M q r s t u v w x y","132":"2 E B C VB WB XB YB b CB aB"},G:{"2":"9 G C EB cB eB fB gB hB iB jB kB lB mB nB"},H:{"16":"oB"},I:{"16":"5 9 F GB pB qB rB sB tB uB"},J:{"16":"D A"},K:{"16":"2 A B C b CB","258":"M"},L:{"1":"FB"},M:{"132":"0"},N:{"258":"A B"},O:{"258":"vB"},P:{"1":"F K wB xB"},Q:{"1":"yB"},R:{"1":"zB"}},B:5,C:"CSS Paged Media (@page)"};
lyy289065406/expcodes
java/01-framework/dubbo-admin/incubator-dubbo-ops/dubbo-admin-frontend/node_modules/caniuse-lite/data/features/css-paged-media.js
JavaScript
gpl-3.0
872
module.exports = { //--------------------------------------------------------------------- // Action Name // // This is the name of the action displayed in the editor. //--------------------------------------------------------------------- name: "Run Script", //--------------------------------------------------------------------- // Action Section // // This is the section the action will fall into. //--------------------------------------------------------------------- section: "Other Stuff", //--------------------------------------------------------------------- // Action Subtitle // // This function generates the subtitle displayed next to the name. //--------------------------------------------------------------------- subtitle: function(data) { return `${data.code}`; }, //--------------------------------------------------------------------- // Action Storage Function // // Stores the relevant variable info for the editor. //--------------------------------------------------------------------- variableStorage: function(data, varType) { const type = parseInt(data.storage); if(type !== varType) return; return ([data.varName, 'Unknown Type']); }, //--------------------------------------------------------------------- // Action Fields // // These are the fields for the action. These fields are customized // by creating elements with corresponding IDs in the HTML. These // are also the names of the fields stored in the action's JSON data. //--------------------------------------------------------------------- fields: ["behavior", "interpretation", "code", "storage", "varName"], //--------------------------------------------------------------------- // Command HTML // // This function returns a string containing the HTML used for // editting actions. // // The "isEvent" parameter will be true if this action is being used // for an event. Due to their nature, events lack certain information, // so edit the HTML to reflect this. // // The "data" parameter stores constants for select elements to use. // Each is an array: index 0 for commands, index 1 for events. // The names are: sendTargets, members, roles, channels, // messages, servers, variables //--------------------------------------------------------------------- html: function(isEvent, data) { return ` <div> <div style="float: left; width: 45%;"> End Behavior:<br> <select id="behavior" class="round"> <option value="0" selected>Call Next Action Automatically</option> <option value="1">Do Not Call Next Action</option> </select> </div> <div style="padding-left: 5%; float: left; width: 55%;"> Interpretation Style:<br> <select id="interpretation" class="round"> <option value="0" selected>Evaluate Text First</option> <option value="1">Evaluate Text Directly</option> </select> </div> </div><br><br><br> <div style="padding-top: 8px;"> Custom Code:<br> <textarea id="code" rows="9" name="is-eval" style="width: 99%; white-space: nowrap; resize: none;"></textarea> </div><br> <div> <div style="float: left; width: 35%;"> Store In:<br> <select id="storage" class="round" onchange="glob.variableChange(this, 'varNameContainer')"> ${data.variables[0]} </select> </div> <div id="varNameContainer" style="display: none; float: right; width: 60%;"> Variable Name:<br> <input id="varName" class="round" type="text"> </div> </div>` }, //--------------------------------------------------------------------- // Action Editor Init Code // // When the HTML is first applied to the action editor, this code // is also run. This helps add modifications or setup reactionary // functions for the DOM elements. //--------------------------------------------------------------------- init: function() { const {glob, document} = this; glob.variableChange(document.getElementById('storage'), 'varNameContainer'); }, //--------------------------------------------------------------------- // Action Bot Function // // This is the function for the action within the Bot's Action class. // Keep in mind event calls won't have access to the "msg" parameter, // so be sure to provide checks for variable existance. //--------------------------------------------------------------------- action: function(cache) { const data = cache.actions[cache.index]; let code; if(data.interpretation === "0") { code = this.evalMessage(data.code, cache); } else { code = data.code; } const result = this.eval(code, cache); const varName = this.evalMessage(data.varName, cache); const storage = parseInt(data.storage); this.storeValue(result, storage, varName, cache); if(data.behavior === "0") { this.callNextAction(cache); } }, //--------------------------------------------------------------------- // Action Bot Mod // // Upon initialization of the bot, this code is run. Using the bot's // DBM namespace, one can add/modify existing functions if necessary. // In order to reduce conflictions between mods, be sure to alias // functions you wish to overwrite. //--------------------------------------------------------------------- mod: function(DBM) { } }; // End of module
Bourbbbon/PickleRi6
actions/run_script.js
JavaScript
gpl-3.0
5,145
$(function(){ $('#theInput').typed({ strings: ["type a word (e.g. 'website')", "type a word (e.g. 'grammar')", "type a word (e.g. 'paper')"], typeSpeed: 50, startDelay: 150, attr: 'placeholder', backSpeed: 100, backDelay: 500, loop: true, showCursor: false, contentType: 'html', }); });
isabellaperalta/appellation
js/delete.js
JavaScript
gpl-3.0
309
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); /** * Created by kib357 on 22/01/16. */ class copy { static arrayStructure(target, source, exclude) { if (!Array.isArray(target) || !Array.isArray(source)) { throw new TypeError('copy.arrayStructure cannot be called with not arrays'); } for (let index = 0; index < source.length; index++) { if (typeof source[index] === 'object' && !Array.isArray(source[index])) { target[index] = {}; copy.objectStructure(target[index], source[index], exclude); continue; } if (Array.isArray(source[index])) { target[index] = []; copy.arrayStructure(target[index], source[index], exclude); continue; } target[index] = null; } return target; } static objectStructure(target, source, exclude) { if (target == null || source == null) { throw new TypeError('copy.objectStructure cannot be called with null or undefined'); } for (let key of Object.keys(source)) { if (exclude instanceof RegExp && exclude.test(key)) { continue; } if (typeof source[key] === 'object' && !Array.isArray(source[key])) { target[key] = {}; copy.objectStructure(target[key], source[key], exclude); continue; } if (Array.isArray(source[key])) { target[key] = []; copy.arrayStructure(target[key], source[key], exclude); continue; } target[key] = null; } return target; } } exports.default = copy;
getblank/blank-node-worker
lib/blank-js-core/utils/copy.js
JavaScript
gpl-3.0
1,810
var searchData= [ ['analog',['Analog',['../namespace_d_s_g_1_1_analog.html',1,'DSG']]], ['blit',['BLIT',['../namespace_d_s_g_1_1_b_l_i_t.html',1,'DSG']]], ['dpw',['DPW',['../namespace_d_s_g_1_1_d_p_w.html',1,'DSG']]], ['dsg',['DSG',['../namespace_d_s_g.html',1,'']]], ['eptr',['EPTR',['../namespace_d_s_g_1_1_e_p_t_r.html',1,'DSG']]], ['filter',['Filter',['../namespace_d_s_g_1_1_filter.html',1,'DSG']]], ['fourier',['Fourier',['../namespace_d_s_g_1_1_fourier.html',1,'DSG']]], ['midi',['MIDI',['../namespace_d_s_g_1_1_m_i_d_i.html',1,'DSG']]], ['noise',['Noise',['../namespace_d_s_g_1_1_noise.html',1,'DSG']]], ['window',['Window',['../namespace_d_s_g_1_1_window.html',1,'DSG']]] ];
zyvitski/DSG
doxygen/html/search/namespaces_0.js
JavaScript
gpl-3.0
704
var http = require('supertest'); var shared = require('../shared'); var server = require('../app'); var app; describe('v2 user#page', function () { before(function (done) { server(function (data) { app = data; done(); }); }); it('should show user index', function (done) { var req = http(app); req.get('/user/page/' + shared.user.username) .expect(200, function (err, res) { var texts = [ '注册时间', '仍然很懒', '最近创建的话题', '无话题', '最近参与的话题', '无话题' ]; texts.forEach(function (text) { res.text.should.containEql(text); }); done(err); }); }); });
calidion/server.xiv.im
test/v2/user/page.js
JavaScript
gpl-3.0
751
import { respond } from "theme/styles/mixins"; export default ` .resource-meta, .resource-meta-mobile { .resource-type { margin-bottom: 14px; ${respond(`margin-bottom: 2px;`, 65)} } /* <ul> */ .meta-list-secondary { margin-bottom: 22px; &:not(:first-child) { margin-top: 10px; } } /* Only shown on mobile */ .meta-list-primary { margin-bottom: 22px; } } `;
ManifoldScholar/manifold
client/src/theme/styles/components/frontend/resource/meta.js
JavaScript
gpl-3.0
444
/*eslint-env browser */ // main dannybot script const mail = require('./mail'); const storage = require('electron-json-storage'); const fs = require('fs'); const q = require('q'); var readFile = q.nbind(fs.readFile); /* Function to run when DOM loaded */ function ready() { init_tab_handler(); show_counts(); construct_checklist(document.getElementById('checklist')); } window.onload = ready; /* Tab functions */ function init_tab_handler() { var tab_buttons = document.querySelectorAll('#tab-buttons *[data-tab]'); for(var i = 0; i < tab_buttons.length; ++i) { tab_buttons[i].onclick = function () { var active = find_active_tab(tab_buttons); switch_active_tab(active, this); }; } } function find_active_tab(tb) { for(var i = 0; i < tb.length; ++i) { if (tb[i].classList.contains('active')) { return tb[i]; } } } function tab_div(tab) { var div_id = tab.dataset.tab; return document.getElementById(div_id); } function switch_active_tab(last_active, new_active) { tab_div(last_active).style.display = 'none'; tab_div(new_active).style.display = 'block'; last_active.classList.remove('active'); new_active.classList.add('active'); } /* Email count updater */ async function show_counts() { try { var folders = await mail.get_mail_config(); var counts = ''; for (var k in folders) { var f = folders[k]; counts = counts + ' ' + await f.count(); update_mail_count(counts); } } catch (e) { throw e; } } function update_mail_count(s) { document.getElementById('inbox_num').innerHTML = s; } /* Checklist */ async function construct_checklist(hn) { hn.classList.add('checklist-container'); var cl = await read_checklist(); var a_checklist = cl.evening; Object.keys(a_checklist).forEach(function (k) { var item = a_checklist[k]; var div = document.createElement('div'); div.classList.add('checklist-item'); var checkbox = document.createElement('input'); checkbox.type = 'checkbox'; checkbox.id = `evening${k}`; checkbox.name = `evening${k}`; checkbox.value = '1'; if (item.value) { checkbox.checked = true; } checkbox.onchange = function () { item.value = this.checked; write_checklist(cl); }; div.appendChild(checkbox); div.appendChild(document.createTextNode(item.text)); hn.appendChild(div); }); var reset = document.createElement('button'); reset.type = 'reset'; reset.innerText = 'Clear'; reset.onclick = function () { Object.keys(a_checklist).forEach(function (k) { var item = a_checklist[k]; item.value = false; }); var buttons = hn.querySelectorAll('.checklist-container input[type=checkbox]'); for (var i = 0; i < buttons.length; ++i) { buttons[i].checked = false; } write_checklist(cl); }; hn.appendChild(reset); } async function read_checklist() { var url = await storage.get('checklist_url'); if (!url) { var url_json = await readFile('/home/danny/Private/lifehacking/checklist-url.js'); url = JSON.parse(url_json).api; storage.set('checklist_url', url); } var response = await window.fetch(url); var checklist = await response.json(); return checklist; } async function write_checklist(checklist) { var url = await storage.get('checklist_url'); if (!url) { var url_json = await readFile('/home/danny/Private/lifehacking/checklist-url.js'); url = JSON.parse(url_json).api; storage.set('checklist_url', url); } console.log(JSON.stringify(checklist)); var response = await window.fetch(url, { method: 'PUT', headers: { 'Content-Type': 'application/json'}, body: JSON.stringify(checklist)}); console.log(response.status); }
dannyob/dannybot
src/dannybot.js
JavaScript
gpl-3.0
4,042
/** * @author alteredq / http://alteredqualia.com/ * * Full-screen textured quad shader */ var THREE = window.THREE || require('three'); THREE.CopyShader = { uniforms: { "tDiffuse": { type: "t", value: null }, "opacity": { type: "f", value: 1.0 } }, vertexShader: [ "varying vec2 vUv;", "void main() {", "vUv = uv;", "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );", "}" ].join("\n"), fragmentShader: [ "uniform float opacity;", "uniform sampler2D tDiffuse;", "varying vec2 vUv;", "void main() {", "vec4 texel = texture2D( tDiffuse, vUv );", "gl_FragColor = opacity * texel;", "}" ].join("\n") };
Pwntus/JStrike
src/lib/shaders/CopyShader.js
JavaScript
gpl-3.0
686
import { history } from 'byebye'; import React from 'react'; import AltContainer from 'alt-container'; import { MANUAL_LOGOUT } from 'app-constants'; import { loginIfAuthorized as autoFacebookLogin } from 'managers/facebook'; import Analytics from 'instances/analytics'; import parseJWT from 'helpers/parseJWT'; import { decode as decodeBase64 } from 'helpers/base64'; import Auth from 'controllers/auth'; import LoginActions from 'actions/LoginActions'; import LoginStore from 'stores/LoginStore'; import EmailLoginPage from './EmailLoginPage'; import TokenErrorPage from './TokenErrorPage'; export function openTokenLogin(token) { LoginActions.loginWithEmailTokenAndRedirect(token); return ( <AltContainer component={TokenErrorPage} stores={{ LoginStore }} actions={{ LoginActions }} inject={{ data: parseJWT(token), }} /> ); } export function openItemLogin(itemId, token, force) { if (Auth.getId()) { const url = `/item/${itemId}`; history.navigate(url, { trigger: true, replace: false }, { returnUrl: '/' }); return <span />; } Analytics.track('Email login/deeplink landing'); const tokenData = JSON.parse(decodeBase64(token)); const data = { item_id: itemId, user_id: tokenData.id, domain: tokenData.domain, name: tokenData.name, }; // auto login with facebook, and when FB login fails we will send you an email autoFacebookLogin() .then(() => { LoginActions.loginSuccess(null, { login_type: 'facebookautologin', platform: 'facebook', }); }) .catch((err) => { if (err.type === MANUAL_LOGOUT || err.type === 'UnableToLogin') { // Convert the force parameter to a boolean. If `true`, it forces the backend to send the // email, regardless of the default time limit of once a day. LoginActions.sendLoginEmail(data.user_id, data.item_id, data.redirect, !!force); return; } throw err; }); return ( <AltContainer component={EmailLoginPage} stores={{ loginState: LoginStore }} inject={{ data }} /> ); } // WEBPACK FOOTER // // ./src/js/app/modules/emailLogin/module.js
BramscoChill/BlendleParser
information/blendle-frontend-react-source/app/modules/emailLogin/module.js
JavaScript
gpl-3.0
2,195
module.exports = function(grunt) { grunt.loadNpmTasks('grunt-ts'); grunt.loadNpmTasks('grunt-karma'); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-bump'); grunt.loadNpmTasks('grunt-tslint'); var pkg = grunt.file.readJSON('package.json'); grunt.initConfig({ pkg: pkg, ts: { options: { sourceMap: false, declaration: true, baseDir: '.', comments: true, }, lib: { src: [ 'refs/common.d.ts', 'src/*.ts' ], out: 'dist/<%= pkg.name %>.js' }, tests: { src: [ 'refs/test.d.ts', 'test/*.ts', 'test/**/*.ts' ], out: 'dist/tests.js', options: { declaration: false } } }, karma: { options: { basePath: '.', frameworks: ['jasmine'], singleRun: true, browsers: ['PhantomJS'], reporters: ['progress', 'coverage'], preprocessors: { 'dist/<%= pkg.name %>.js': 'coverage', }, coverageReporter: { type: 'text', dir: 'coverage' }, files: [ 'bower_components/jquery/dist/jquery.js', 'bower_components/jquery-bracket/dist/jquery.bracket.min.js', 'dist/<%= pkg.name %>.js', 'dist/tests.js' ] }, lib: { options: { coverageReporter: { type: 'html', dir: 'coverage' }, frameworks: ['jasmine'] } }, server: { options: { coverageReporter: {}, preprocessors: {}, reporters: ['progress'] }, autoWatch: true, singleRun: false, } }, uglify: { options: { mangle: true, compress: true, wrap: false }, dist: { src: 'dist/<%= pkg.name %>.js', dest: 'dist/<%= pkg.name %>.min.js' } }, bump: { options: { files: ['package.json', 'bower.json'], updateConfigs: [], commit: true, commitMessage: 'Release v%VERSION%', commitFiles: ['package.json', 'bower.json'], createTag: true, tagName: 'v%VERSION%', tagMessage: 'Version %VERSION%', push: false, pushTo: 'upstream', gitDescribeOptions: '--tags --always --abbrev=1 --dirty=-d' } }, tslint: { options: { configuration: grunt.file.readJSON('tslint.json') }, files: { src: ['src/**/*.ts', 'src/**/**/*.ts'] } } }); grunt.registerTask('default', ['ts:lib']); grunt.registerTask('lib', ['ts:lib']); grunt.registerTask('tests', ['ts:tests']); grunt.registerTask('test', ['karma:lib']); grunt.registerTask('dist', [ 'default', 'uglify:dist', ]); grunt.registerTask('all', ['ts', 'dist']); };
clemby/tournament-bracket-converter
Gruntfile.js
JavaScript
gpl-3.0
2,935
export { SavingButton } from './SavingButton';
AdguardTeam/AdguardBrowserExtension
Extension/src/pages/common/components/SavingButton/index.js
JavaScript
gpl-3.0
47
import sinon from 'sinon'; import expect from 'expect'; import sleeper from '..'; describe('sleeper', () => { it('should be a function', () => { expect(sleeper).toEqual(expect.any(Function)); }); it('should expose the Resource constructor', () => { expect(sleeper.Resource).toEqual(expect.any(Function)); }); it('should initialize with a URL', () => { let url = '/api/users'; expect(() => { sleeper(url); }).not.toThrow(); let api = sleeper(url); expect(api).toBeInstanceOf(sleeper.Resource); expect(api.url).toEqual(url); }); // CRUD server let server, users; beforeAll(() => { let multi = /^\/api\/users\/?(?:\?.*)?$/, single = /^\/api\/users\/([^/?]+)\/?(?:\?.*)?$/, counter = 0; server = sinon.useFakeServer(); server.autoRespond = true; server.autoRespondAfter = 1; users = []; user(null, { name: 'brian' }); user(null, { name: 'betty' }); user(null, { name: 'bob' }); function reply(xhr, json) { json = json || { success: false }; xhr.respond( json.status || (json.success === false ? 500 : 200), { 'Content-Type': 'application/json' }, JSON.stringify(json) ); } // get(id), set(id, user), create(null, user), delete(id, false) function user(id, update) { if (!id) { users.push({ id: id = ++counter + '' }); } for (let i = users.length, u; i--;) { u = users[i]; if (u.id === id) { if (update) { u = users[i] = update; u.id = id; } if (update === false) { users.splice(i, 1); } return u; } } return false; } // Index server.respondWith('GET', multi, (r) => { reply(r, users); }); // Create server.respondWith('POST', multi, (r) => { reply(r, user(null, JSON.parse(r.requestBody))); }); // Read server.respondWith('GET', single, (r, id) => { reply(r, user(id) || { success: false, status: 404, message: 'Not Found' }); }); // Update server.respondWith('PUT', single, (r, id) => { reply(r, user(id, JSON.parse(r.requestBody))); }); // Delete server.respondWith('DELETE', single, (r, id) => { let rem = user(id, false); reply(r, { success: !!rem }); }); }); afterAll(() => { server.restore(); }); describe('#index()', () => { it('should issue a request to /', (done) => { let api = sleeper('/api/users'); api.index((err, list) => { expect(err).toEqual(null); expect(list).toMatchObject(users); done(); }); }); }); describe('#get(id)', () => { it('should issue a GET request to /:id', (done) => { let api = sleeper('/api/users'); api.get(users[0].id, (err, user) => { expect(err).toEqual(null); expect(user).toMatchObject(users[0]); done(); }); }); it('should return an error if status>=400', (done) => { let api = sleeper('/api/users'); api.get('does-not-exist', (err, user) => { expect(err).toEqual('Not Found'); //expect(user).toEqual(null); done(); }); }); it('should return an error property if messageProp is set', (done) => { let api = sleeper('/api/users'); api.messageProp = 'message'; api.get('also-does-not-exist', (err, user) => { expect(err).toEqual('Not Found'); //expect(user).toEqual(null); done(); }); }); }); describe('#post(obj)', () => { it('should issue a form-encoded POST request to /', (done) => { let api = sleeper('/api/users'), newUser = { name: 'billiam' }; api.post(newUser, (err, user) => { expect(err).toEqual(null); // simpler newUser.id = users[users.length - 1].id; expect(user).toMatchObject(newUser); done(); }); }); }); describe('#put([id, ] obj)', () => { it('should issue a JSON-encoded PUT request to /:id', (done) => { let api = sleeper('/api/users'), updatedUser = {}; updatedUser = Object.assign({}, users[0], { name: 'sheryll', concern: 'Who is this sheryll?' }); api.put(updatedUser.id, updatedUser, (err, user) => { expect(err).toEqual(null); expect(user).toMatchObject(updatedUser); done(); }); }); it('should use an `id` property for an object via #idKey', (done) => { let api = sleeper('/api/users'), updatedUser = { id: users[1].id, name: 'benny', associations: ['The Jets'] }; api.put(updatedUser, (err, user) => { expect(err).toEqual(null); expect(user).toMatchObject(updatedUser); done(); }); }); }); describe('#del(id)', () => { it('should issue a DELETE request to /:id', (done) => { let api = sleeper('/api/users'), id = users[1].id; api.del(id, (err, info) => { expect(err).toEqual(null); expect(info).toMatchObject({ success: true }); // make sure Benny's really gone: expect(users[1].id).not.toEqual(id); done(); }); }); }); describe('#param(key [, value])', () => { it('should set a value when given (key, value)', () => { let api = sleeper('/api/users'); expect(api.query).toEqual({}); api.param('some_key', 'some_value'); expect(api.query).toEqual({ some_key: 'some_value' }); }); it('should add values from an object when given (hash)', () => { let api = sleeper('/api/users'), vals = { k1: 'v1', k2: 'v2' }; api.param('k', 'v'); api.param(vals); expect(api.query).toEqual({ k: 'v', k1: 'v1', k2: 'v2' }); }); it('should return the value for a key when given (key)', () => { let api = sleeper('/api/users'); api.query = { k1: 'v1', k2: 'v2' }; expect(api.param('k1')).toEqual('v1'); expect(api.param('k2')).toEqual('v2'); expect(api.param('foo')).toEqual(undefined); }); it('should send params on each request', (done) => { let api = sleeper('/api/users'); api.param('auth_token', 'asdf1234'); api.index((err, list) => { expect(server.requests[server.requests.length - 1].url).toMatch(/\?auth_token=asdf1234$/g); done(); }); }); }); describe('#create(obj)', () => { it('should be an alias of post()', () => { let api = sleeper(); expect(api.create).toEqual(api.post); }); }); describe('#read(id)', () => { it('should be an alias of get()', () => { let api = sleeper(); expect(api.get).toEqual(api.read); }); }); describe('#update(id, obj)', () => { it('should be an alias of put()', () => { let api = sleeper(); expect(api.update).toEqual(api.put); }); }); describe('#delete(id)', () => { it('should be an alias of del()', () => { let api = sleeper(); expect(api.delete).toEqual(api.del); }); }); describe('#remove(id)', () => { it('should be an alias of del()', () => { let api = sleeper(); expect(api.remove).toEqual(api.del); }); }); });
developit/sleeper
test/sleeper.test.js
JavaScript
gpl-3.0
6,745
import 'babel-polyfill'; import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { createStore, applyMiddleware } from 'redux'; import thunk from 'redux-thunk'; import promise from 'redux-promise'; import createLogger from 'redux-logger'; import allReducers from './reducers'; import App from './components/App'; const logger = createLogger(); const store = createStore(allReducers, applyMiddleware(thunk, promise, logger)); ReactDOM.render( <Provider store={store}> <App /> </Provider>, document.getElementById('app') );
designcreative/react-redux-template
src/js/index.js
JavaScript
gpl-3.0
586
var a00250 = [ [ "data_count", "a00250.html#a370358835ed2aa53bcc515894b13eb87", null ], [ "evt_type", "a00250.html#a622197dded7bfa292535944e6870c5f7", null ] ];
DroneBucket/Drone_Bucket_CrazyFlie2_NRF_Firmware
nrf51_sdk/Documentation/s310/html/a00250.js
JavaScript
gpl-3.0
168
jQuery(document).ready(function($) { $('.modalClose').click(function() { $('.Cart66Unavailable').fadeOut(800); }); $('#Cart66CancelPayPalSubscription').click(function() { return confirm('Are you sure you want to cancel your subscription?\n'); }); }); var $pj = jQuery.noConflict(); function getCartButtonFormData(formId) { var theForm = $pj('#' + formId); var str = ''; $pj('input:not([type=checkbox], :radio), input[type=checkbox]:checked, input:radio:checked, select, textarea', theForm).each( function() { var name = $pj(this).attr('name'); var val = $pj(this).val(); str += name + '=' + encodeURIComponent(val) + '&'; } ); return str.substring(0, str.length-1); }
vleo/vleo-notebook
bluecherry/Bluecherry DVR » Version 2 beta signup information_files/cart66-library.js
JavaScript
gpl-3.0
739
chrome.runtime.onInstalled.addListener(function(details){ if(details.reason == "install"){ console.log("This is a first install!"); }else if(details.reason == "update"){ var thisVersion = chrome.runtime.getManifest().version; console.log("Updated from " + details.previousVersion + " to " + thisVersion + "!"); } }); //Redirect from Valve's version of gamehighlightplayer.js to our stub file. We need this to prevent errors. chrome.webRequest.onBeforeRequest.addListener( function(details) { console.log('this ran'); if( details.url.indexOf("gamehighlightplayer.js")>-1){ return {redirectUrl: "chrome-extension://"+chrome.runtime.id+"/js/gamehighlightplayer_stub.js" }; } }, {urls: ["*://*.steamstatic.com/*"]}, ["blocking"]);
dbalz3/SuperSteam_Chrome
js/background.js
JavaScript
gpl-3.0
821
var _ = require('underscore'); var express = require('express'); var router = express.Router(); var Autocomplete = require('autocomplete'); var autocomplete = Autocomplete.connectAutocomplete(); var categoryNames = []; var categories = require('../data/categories.json'); _.each(categories, function (category) { if( category.name!=undefined || category.name!=null ) categoryNames.push(category.name.toLowerCase()); }) autocomplete.initialize(function(onReady) { onReady(categoryNames); }); /* GET categories listing. */ router.get('/autocomplete/', function(req, res, next){ var category = req.query["term"].toLowerCase(); var results = autocomplete.search(category); var categoryResults = _.map(results, function(result){ var found = _.find(categories,function(category){ if( category.name!=undefined || category.name!=null ) return category.name.toLowerCase() === result; else return false }); return {label:found.name, value:found.id}; }) res.send(categoryResults); }); router.get('/', function(req, res, next) { res.setHeader('Content-Type', 'application/json'); res.send(JSON.stringify(categories)); }); module.exports = router;
jalalahmad/autocomplete
routes/categories.js
JavaScript
gpl-3.0
1,255
/** * helper functions for event entities */ (function () { /** * show self contained popup for listing Course Event entities */ radio('Event-CourseEvent').subscribe(function(modelId){ var id = new Date().getTime(); $.get(document.endpoints.event.getCourseEvent + "/" + modelId , function (html) { var id = new Date().getTime(); var selected = [] ; radio("show-modal").broadcast({ id: id, title: "<i class='icon-event'></i> Event Entities <small>Course Event for Course " + modelId + "</small>", content: html}) }) }) /** * show self contained popup for listing Delegate Event (event) entities */ radio('Event-DelegateEvent').subscribe(function (modelId) { $.get(document.endpoints.delegate.getDelegateEvent + "/" + modelId + "?selected=true", function (html) { var id = new Date().getTime(); var selected = [] ; radio("show-modal").broadcast({ id: id, title: "<i class='icon-delegate'></i> Delegate Entities <small>Delegate Event for Event " + modelId + "</small><hr/><button class='btn btn-success btn-sm disableOnAjax' onclick='radio(\"Delegate-Pick-DelegateEvent\").broadcast(" + modelId + ")' ><i class='icon-delegate'></i> Add Delegate</button>", content: html, pickText: "Update", onPick: function (e) { if (e.state == 0) { if (selected.indexOf(e.id) == -1) { selected.push(e.id); } } if (e.state == 1) { selected = _.reject(selected, function (x) { return x == e.id }); } if (e.state == -1) { $.ajax({ type: 'POST', url: "/event/UnLinkDelegateEvent", data: { modelId: modelId, items: selected }, dataType: "json", cache: false }).done(function (e) { if (e.Success) { radio("close-modal-" + id).broadcast(); radio("notify-success").broadcast({ title: "Event (" + modelId + ") updated", message: "<span onclick=\"radio('app-event-view').broadcast(" + modelId + ")\"><i class='icon-event'></i> View Event</span>" }) radio("app-isDirty").broadcast(true); } else { radio("showError-modal-" + id).broadcast(e.Errors); } }); } } }) }) }) /** * show self contained popup for adding new event Delegate Event */ radio('Event-Add-DelegateEvent').subscribe(function (modelId) { $.get(document.endpoints.event.addDelegateEvent , function (html) { var id = new Date().getTime(); radio("show-modal").broadcast({ id: id, title: "<i class='icon-event'></i> Add New Event <small>Delegate Event for Delegate " + modelId + "</small>", content: html, saveText : "Save", onSave: function (data) { data.modelId = modelId; radio("clear-modal-" + id).broadcast(); $.ajax({ type: 'POST', url: document.endpoints.event.saveDelegateEvent, data: data, dataType: "json", cache: false }).done(function (e) { if (e.Success) { radio("close-modal-" + id).broadcast(); radio("notify-success").broadcast({ title: "Event (" + e.Model.Id + ") updated", message: "<span onclick=\"radio('app-event-view').broadcast(" + e.Model.Id + ")\"><i class='icon-event'></i> View Event</span>" }) radio("app-isDirty").broadcast(true); } else { radio("showError-modal-" + id).broadcast(e.Errors); } }); } }) }) }) /** * show self contained popup for adding new event Delegate Event */ radio('Event-Pick-DelegateEvent').subscribe(function (modelId) { var selected = [] ; // register a refresh function radio("app-refresh-register").broadcast(function () { radio("app-refresh-unregister").broadcast(); // unsubscribe us radio("close-modal-" + id).broadcast(); // close this modal radio('Event-DelegateEvent').broadcast(modelId); // re open it }) $.get(document.endpoints.event.list, function (html) { var id = new Date().getTime(); radio("show-modal").broadcast({ id: id, title: "<i class='icon-event'></i> Pick Existing Event <small>Delegate Event for Delegate " + modelId + "</small>", content: html, pickText: "Pick", onPick: function (e) { if (e.state == 1) { if (selected.indexOf(e.id) == -1) { selected.push(e.id); } } if (e.state == 0) { selected = _.reject(selected, function (x) { return x == e.id }); } if (e.state == -1) { $.ajax({ type: 'POST', url: "/event/LinkDelegateEvent", data: { modelId: modelId, items: selected }, dataType: "json", cache: false }).done(function (e) { if (e.Success) { radio("close-modal-" + id).broadcast(); // close this modal radio("notify-success").broadcast({ title: "Event (" + modelId + ") updated", message: "<span onclick=\"radio('app-event-view').broadcast(" + modelId + ")\"><i class='icon-event'></i> View Event</span>" }) radio("app-isDirty").broadcast(true); } else { radio("showError-modal-" + id).broadcast(e.Errors); } }); } } }) }) }) /** * show self contained popup for listing Event Location (event) entities */ radio('Event-EventLocation').subscribe(function (modelId) { var selected = [] ; $.get(document.endpoints.location.getEventLocation + "/" + modelId , function (html) { var id = new Date().getTime(); // register a refresh function radio("app-refresh-register").broadcast(function () { radio("app-refresh-unregister").broadcast(); // unsubscribe us radio("close-modal-" + id).broadcast(); // close this modal radio('Event-EventLocation').broadcast(modelId); // re open it }) radio("show-modal").broadcast({ id: id, title: "<i class='icon-location'></i> Location Entities <small>Event Location for Event " + modelId + "</small><hr/><button class='btn btn-success btn-sm disableOnAjax' onclick='radio(\"Location-Pick-EventLocation\").broadcast(" + modelId + ")' ><i class='icon-location'></i> Add Location</button>", content: html , pickText: "Update", onPick: function (e) { if (e.state == 0) { if (selected.indexOf(e.id) == -1) { selected.push(e.id); } } if (e.state == 1) { selected = _.reject(selected, function (x) { return x == e.id }); } if (e.state == -1) { $.ajax({ type: 'POST', url: "/location/UnLinkEventLocation", data: { modelId: modelId, items: selected }, dataType: "json", cache: false }).done(function (e) { if (e.Success) { radio("close-modal-" + id).broadcast(); radio("app-refresh-unregister").broadcast(); // unsubscribe us radio("notify-success").broadcast({ title: "Location (" + modelId + ") updated", message: "<span onclick=\"radio('app-location-view').broadcast(" + modelId + ")\"><i class='icon-location'></i> View Location</span>" }) radio("app-isDirty").broadcast(true); } else { radio("showError-modal-" + id).broadcast(e.Errors); } }); } } }) }) }) /** * show self contained popup for adding new event Event Location */ radio('Event-Add-EventLocation').subscribe(function (modelId) { $.get(document.endpoints.event.addEventLocation + "/" + modelId, function (html) { var id = new Date().getTime(); radio("show-modal").broadcast({ id: id, title: "<i class='icon-event'></i> Add New Event <small>Event Location for Location " + modelId + "</small>", content: html, saveText: "Save", onSave: function (data) { radio("clear-modal-" + id).broadcast(); data.modelId = modelId $.ajax({ type: 'Post', data: data, url: document.endpoints.event.saveEventLocation, dataType: "json", cache: false }).done(function (e) { if (e.Success) { radio("close-modal-" + id).broadcast(); radio("notify-success").broadcast({ title: "Event updated", message: "" }) radio("app-isDirty").broadcast(true); } else { radio("showError-modal-" + id).broadcast(e.Errors); } }); }, }) }) }) /** * show self contained popup for picking existing event Event Location */ radio('Event-Pick-EventLocation').subscribe(function (modelId) { var selected = []; $.get(document.endpoints.event.list, function (html) { var id = new Date().getTime(); radio("show-modal").broadcast({ id: id, title: "<i class='icon-event'></i> Pick Existing Event <small>Event Location for Location " + modelId + "</small>", content: html, pickText: "Pick", onPick: function (e) { if (e.state == 1) { if (selected.indexOf(e.id) == -1) { selected.push(e.id); } } if (e.state == 0) { selected = _.reject(selected, function (x) { return x == e.id }); } if (e.state == -1) { $.ajax({ type: 'POST', url: "/location/LinkEventLocation", data: { modelId: modelId, items: selected }, dataType: "json", cache: false }).done(function (e) { if (e.Success) { radio("close-modal-" + id).broadcast(); radio("notify-success").broadcast({ title: "Location (" + modelId + ") updated", message: "<span onclick=\"radio('app-location-view').broadcast(" + modelId + ")\"><i class='icon-location'></i> View Location</span>" }) radio("app-isDirty").broadcast(true); } else { radio("showError-modal-" + id).broadcast(e.Errors); } }); } } }) }) }) /** * show self contained popup for listing Event Delegate (event) entities */ radio('Event-EventDelegate').subscribe(function (modelId) { var selected = [] ; $.get(document.endpoints.delegate.getEventDelegate + "/" + modelId , function (html) { var id = new Date().getTime(); // register a refresh function radio("app-refresh-register").broadcast(function () { radio("app-refresh-unregister").broadcast(); // unsubscribe us radio("close-modal-" + id).broadcast(); // close this modal radio('Event-EventDelegate').broadcast(modelId); // re open it }) radio("show-modal").broadcast({ id: id, title: "<i class='icon-delegate'></i> Delegate Entities <small>Event Delegate for Event " + modelId + "</small><hr/><button class='btn btn-success btn-sm disableOnAjax' onclick='radio(\"Delegate-Pick-EventDelegate\").broadcast(" + modelId + ")' ><i class='icon-delegate'></i> Add Delegate</button>", content: html , pickText: "Update", onPick: function (e) { if (e.state == 0) { if (selected.indexOf(e.id) == -1) { selected.push(e.id); } } if (e.state == 1) { selected = _.reject(selected, function (x) { return x == e.id }); } if (e.state == -1) { $.ajax({ type: 'POST', url: "/delegate/UnLinkEventDelegate", data: { modelId: modelId, items: selected }, dataType: "json", cache: false }).done(function (e) { if (e.Success) { radio("close-modal-" + id).broadcast(); radio("app-refresh-unregister").broadcast(); // unsubscribe us radio("notify-success").broadcast({ title: "Delegate (" + modelId + ") updated", message: "<span onclick=\"radio('app-delegate-view').broadcast(" + modelId + ")\"><i class='icon-delegate'></i> View Delegate</span>" }) radio("app-isDirty").broadcast(true); } else { radio("showError-modal-" + id).broadcast(e.Errors); } }); } } }) }) }) /** * show self contained popup for adding new event Event Delegate */ radio('Event-Add-EventDelegate').subscribe(function (modelId) { $.get(document.endpoints.event.addEventDelegate + "/" + modelId, function (html) { var id = new Date().getTime(); radio("show-modal").broadcast({ id: id, title: "<i class='icon-event'></i> Add New Event <small>Event Delegate for Delegate " + modelId + "</small>", content: html, saveText: "Save", onSave: function (data) { radio("clear-modal-" + id).broadcast(); data.modelId = modelId $.ajax({ type: 'Post', data: data, url: document.endpoints.event.saveEventDelegate, dataType: "json", cache: false }).done(function (e) { if (e.Success) { radio("close-modal-" + id).broadcast(); radio("notify-success").broadcast({ title: "Event updated", message: "" }) radio("app-isDirty").broadcast(true); } else { radio("showError-modal-" + id).broadcast(e.Errors); } }); }, }) }) }) /** * show self contained popup for picking existing event Event Delegate */ radio('Event-Pick-EventDelegate').subscribe(function (modelId) { var selected = []; $.get(document.endpoints.event.list, function (html) { var id = new Date().getTime(); radio("show-modal").broadcast({ id: id, title: "<i class='icon-event'></i> Pick Existing Event <small>Event Delegate for Delegate " + modelId + "</small>", content: html, pickText: "Pick", onPick: function (e) { if (e.state == 1) { if (selected.indexOf(e.id) == -1) { selected.push(e.id); } } if (e.state == 0) { selected = _.reject(selected, function (x) { return x == e.id }); } if (e.state == -1) { $.ajax({ type: 'POST', url: "/delegate/LinkEventDelegate", data: { modelId: modelId, items: selected }, dataType: "json", cache: false }).done(function (e) { if (e.Success) { radio("close-modal-" + id).broadcast(); radio("notify-success").broadcast({ title: "Delegate (" + modelId + ") updated", message: "<span onclick=\"radio('app-delegate-view').broadcast(" + modelId + ")\"><i class='icon-delegate'></i> View Delegate</span>" }) radio("app-isDirty").broadcast(true); } else { radio("showError-modal-" + id).broadcast(e.Errors); } }); } } }) }) }) })();
NTiering/TrainingManager
App.Mvc/Scripts/Tools/event.js
JavaScript
gpl-3.0
19,404
angular.module('qmsk.e2.server', [ 'qmsk.e2', 'qmsk.e2.console', 'qmsk.e2.web', 'ngResource', 'ngRoute', 'jsonFormatter', 'ui.bootstrap', ]) .config(function($routeProvider) { $routeProvider .when('/main', { templateUrl: '/static/qmsk.e2/server/main.html', controller: 'MainCtrl', reloadOnSearch: false, }) .when('/sources', { templateUrl: '/static/qmsk.e2/server/sources.html', controller: 'SourcesCtrl', }) .when('/screens', { templateUrl: '/static/qmsk.e2/server/screens.html', controller: 'ScreensCtrl', }) .when('/auxes', { templateUrl: '/static/qmsk.e2/server/auxes.html', controller: 'AuxesCtrl', }) .when('/presets', { templateUrl: '/static/qmsk.e2/server/presets.html', controller: 'PresetsCtrl', reloadOnSearch: false, }) .when('/system', { templateUrl: '/static/qmsk.e2/server/system.html', controller: 'SystemCtrl', }) .otherwise({ redirectTo: '/main', }); }) .factory('Preset', function($resource) { return $resource('/api/presets/:id', { }, { get: { method: 'GET', url: '/api/presets', }, all: { method: 'GET', isArray: true, }, query: { method: 'GET', isArray: false, }, activate: { method: 'POST', url: '/api/presets', }, }, {stripTrailingSlashes: false}); }) .filter('dimensions', function() { return function(dimensions) { if (dimensions && dimensions.width && dimensions.height) { return dimensions.width + "x" + dimensions.height; } else { return null; } }; }) .directive('e2Source', function() { return { restrict: 'AE', scope: { source: '=source', input: '=input', detail: '=detail', }, templateUrl: '/static/qmsk.e2/server/source.html', }; }) .controller('MainCtrl', function($scope, $location) { $scope.sources = []; $scope.$watch('state.System', function(system) { // compute a merged state mapping sources to their active destinations // TODO: aux destinations $scope.sources = $.map(system.SrcMgr.SourceCol, function(source, sourceID){ var item = { id: sourceID, type: source.SrcType, name: source.Name, source: source, active: false, preview: [], program: [], }; if (source.SrcType == "input") { item.input = system.SrcMgr.InputCfgCol[source.InputCfgIndex]; } $.each(system.DestMgr.ScreenDestCol, function(screenID, screen) { var output = { type: "screen", id: screenID, name: screen.Name, active: screen.IsActive > 0, }; $.each(screen.LayerCollection, function(layerID, layer) { if (layer.PgmMode > 0 && layer.LastSrcIdx == sourceID) { output.program = true; } if (layer.PvwMode > 0 && layer.LastSrcIdx == sourceID) { output.preview = true; } }); if (output.program) { item.program.push(output); } if (output.preview) { item.preview.push(output); } if (output.active && output.preview) { item.active = true; } }); return item; }); }); $scope.selectOrder = function(order) { $scope.order = order; $scope.orderBy = function(){ switch (order) { case 'source': return ['-type', 'name']; case 'preview': return ['preview_screens', 'program_screens']; case 'program': return ['program_screens', 'preview_screens']; default: return []; } }(); $location.search('order', order || null); }; $scope.selectOrder($location.search().order || 'source'); }) .controller('SourcesCtrl', function($scope) { }) .controller('ScreensCtrl', function($scope) { }) .controller('AuxesCtrl', function($scope) { }) .controller('PresetsCtrl', function($scope, Preset, $location, Console) { // size $scope.displaySize = $location.search().size || 'normal'; $scope.$watch('displaySize', function(displaySize) { $location.search('size', displaySize); }); // collapsing $scope.showGroup = $location.search().group || null; $scope.collapseGroups = {}; $scope.selectGroup = function(groupID) { $scope.collapseGroups = {}; if (groupID != $scope.showGroup) { $scope.showGroup = groupID; $location.search('group', groupID); } } $scope.clearGroup = function() { $scope.collapseGroups = {}; $scope.showGroup = null; $location.search('group', null); }; $scope.toggleGroup = function(groupID) { $scope.collapseGroups[groupID] = !$scope.collapseGroups[groupID]; }; // grouping $scope.groupBy = $location.search().groupBy || 'sno'; $scope.$watch('groupBy', function(groupBy) { $location.search('groupBy', groupBy); }); function groupBySno(presets) { var groups = { }; $.each(presets, function(id, preset) { var groupID = preset.presetSno.Group; var groupIndex = preset.presetSno.Index; preset = $.extend({groupIndex: groupIndex}, preset); // group it var group = groups[groupID]; if (!group) { group = groups[groupID] = { id: groupID, name: groupID, presets: [] }; } group.presets.push(preset); }); return $.map(groups, function(group, id){ return group; }); }; function groupByConsole(presets) { var groups = { }; $.each($scope.state.System.ConsoleLayoutMgr.ConsoleLayout.PresetBusColl, function(buttonID, button) { var groupID = Math.floor(button.id / 12); // rows of 12 keys var group = groups[groupID]; var preset = presets[button.ConsoleButtonTypeIndex]; if (button.ConsoleButtonType != 'preset' || !preset) { return; } // copy with groupIndex, since the same preset can be included multiple times preset = $.extend({ groupIndex: button.id }, preset); if (!group) { group = groups[groupID] = { id: groupID+1, name: "Preset PG" + (groupID+1), presets: [] }; } group.presets.push(preset); }); return $.map(groups, function(group) { return group; }); } $scope.groups = []; $scope.$watchGroup(['groupBy', 'state.System'], function() { var presets = $scope.state.System.PresetMgr.Preset; var groups; if ($scope.groupBy == 'sno') { groups = groupBySno(presets); } else if ($scope.groupBy == 'console') { groups = groupByConsole(presets); } else { groups = [{ id: 0, name: "", presets: $.map(presets, function(preset){ return $.extend({groupIndex: preset.id}, preset); }), }]; } Console.log("Refresh presets: presets=" + Object.keys(presets).length + ", groupBy=" + $scope.groupBy + ", groups=" + groups.length); $scope.groups = groups; }); // active preset on server; reset while changing... $scope.activePresetID = null; $scope.$watch('state.System', function(system) { $scope.activePresetID = system.PresetMgr.LastRecall }); // select preset for preview $scope.previewPreset = null $scope.select = function(preset) { $scope.activePresetID = null; Console.log("Recall preset " + preset.id + ": " + preset.name); Preset.activate({id: preset.id}, function success(r) { $scope.previewPreset = preset; }, function error(e) { } ); }; // take preset for program $scope.autoTake = $location.search().autotake || false; $scope.$watch('autoTake', function(autoTake) { $location.search('autotake', autoTake ? true : null); }); $scope.programPreset = null; $scope.take = function(preset) { if (preset) { } else if ($scope.previewPreset) { preset = $scope.previewPreset; } else { return; } Console.log("Take preset " + preset.id + ": " + preset.name); $scope.activePresetID = null; Preset.activate({id: preset.id, live: true}, function success(r) { $scope.programPreset = preset; }, function error(e) { } ); }; // preview -> program $scope.cut = function() { Console.log("Cut") Preset.activate({cut: true}); }; $scope.autotrans = function() { Console.log("AutoTrans") Preset.activate({autotrans: 0}); }; }) .controller('SystemCtrl', function($scope) { }) ;
depili/e2
static/qmsk.e2/server.js
JavaScript
mpl-2.0
10,066
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. */ function blockReferer () { if (document.referrer) { // Blocks cross-origin referer var parser = document.createElement('a') parser.href = document.referrer if (parser.origin !== document.location.origin) { window.Document.prototype.__defineGetter__('referrer', () => { return document.location.origin }) } } } function getBlockRefererScript () { return '(' + Function.prototype.toString.call(blockReferer) + '());' } if (chrome.contentSettings.referer != 'allow' && document.location.origin && document.location.origin !== 'https://youtube.googleapis.com') { executeScript(getBlockRefererScript()) }
manninglucas/browser-laptop
app/extensions/brave/content/scripts/block3rdPartyContent.js
JavaScript
mpl-2.0
846
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ define( [ 'underscore', 'backbone', 'lib/localizer' ], function (_, Backbone, Localizer) { 'use strict'; /** * Base class for views that provides common rendering, model presentation, DOM assignment, * subview tracking, and tear-down. * * @class BaseView * * @constructor * * @param {Object} options configuration options passed along to Backbone.View */ var BaseView = Backbone.View.extend({ constructor: function (options) { this.subviews = []; Backbone.View.call(this, options); }, /** * Gets context from model's attributes. Can be overridden to provide custom context for template. * * @method getContext * @return {Object} context */ getContext: function () { var context; if (this.model) { context = this.model.attributes; } else { context = {}; } return context; }, /** * Localizes English input text. * * @method localize * @return {String} localized text */ localize: function (text) { return Localizer.localize(text); }, /** * Renders by combining template and context and inserting into the associated element. * * @method render * @return {BaseView} this * @chainable */ render: function () { this.destroySubviews(); var context = this.getContext(); var self = this; context.l = function () { return function (text, render) { return render(self.localize(text)); }; }; this.$el.html(this.template(context)); this.afterRender(); return this; }, /** * Called after render completes. Provides easy access to custom rendering for subclasses * without having to override render. * * @method afterRender */ afterRender: function () { // Implement in subclasses }, /** * Renders local collection using the provided view and inserts into the provided selector. * * @method renderCollection * @param {Backbone.View} ItemView view for rendering each item in the collection * @param {String} selector jQuery selector to insert the collected elements */ renderCollection: function (ItemView, selector) { var els = this.collection.collect(function (item) { return this.trackSubview(new ItemView({ model: item })).render().el; }.bind(this)); this.$(selector).append(els); }, /** * Assigns view to a selector. * * @method assign * @param {Backbone.View} view to assign * @param {String} selector jQuery selector for the element to be assigned * @return {BaseView} this */ assign: function (view, selector) { view.setElement(this.$(selector)); view.render(); }, /** * Destroys view by stopping Backbone event listeners, disabling jQuery events, and destroying * subviews. * * @method destroy */ destroy: function () { if (this.beforeDestroy) { this.beforeDestroy(); } this.stopListening(); this.destroySubviews(); this.$el.off(); }, /** * Keeps track of a subview so that it can later be destroyed. * * @method trackSubview * @param {BaseView} view to track * @return {BaseView} tracked view */ trackSubview: function (view) { if (!_.contains(this.subviews, view)) { this.subviews.push(view); } return view; }, /** * Destroys all subviews. * * @method destroySubviews */ destroySubviews: function () { _.invoke(this.subviews, 'destroy'); this.subviews = []; } }); return BaseView; } );
mozilla/chronicle
app/scripts/views/base.js
JavaScript
mpl-2.0
4,193
// @flow import type { Action, ExpandedSet, ProfileSelection, } from '../actions/types'; import type { Days, StartEndRange } from '../../common/types/units'; import type { IndexIntoFuncTable, Profile, ThreadIndex } from '../../common/types/profile'; import type { TransformStacksPerThread } from '../../common/types/transforms'; import type { TrackedData } from '../../common/types/trackedData'; import type { DateGraph, CategorySummary } from '../../common/types/workers'; export type Reducer<T> = (T, Action) => T; export type RequestedLib = { pdbName: string, breakpadId: string }; export type ThreadViewOptions = { selectedStack: IndexIntoFuncTable[], expandedStacks: Array<IndexIntoFuncTable[]>, }; export type ProfileViewState = { viewOptions: { threadOrder: number[], perThread: ThreadViewOptions[], selection: ProfileSelection, scrollToSelectionGeneration: number, rootRange: StartEndRange, zeroAt: Days, }, profile: Profile, }; export type TrackedDataViewState = { trackedData: TrackedData, }; export type AppState = { view: string, error: string, isURLSetupDone: boolean, }; export type RangeFilterState = { start: number, end: number, }; export type RunnablesViewState = { expanded: Set<number>, runnables: Object[], }; export type CategoriesViewState = { expanded: Set<number> | null, categories: CategorySummary[] | null, }; export type ExploreURLState = { selectedTab: string, rangeFilters: RangeFilterState[], selectedThread: ThreadIndex, callTreeSearchString: string, invertCallstack: boolean, hidePlatformDetails: boolean, historical: boolean, durationSpec: string, runnableFilter: string | null, categoryFilter: string, platformFilter: string, onlyUserInteracting: boolean, payloadID: string | null, mode: string, transforms: TransformStacksPerThread, }; export type TrackURLState = { trackedStat: string, mode: string, }; export type UnknownURLState = { mode: string, }; export type URLState = ExploreURLState | TrackURLState | UnknownURLState; export type IconState = Set<string>; export type State = { app: AppState, profileView: ProfileViewState, trackedDataView: TrackedDataViewState, runnablesView: RunnablesViewState, categoriesView: CategoriesViewState, urlState: URLState, dateGraph: DateGraph, icons: IconState, }; export type IconWithClassName = { icon: string, className: string, };
squarewave/bhr.html
src/content/reducers/types.js
JavaScript
mpl-2.0
2,440
if (typeof parseRegExp === 'undefined') quit(); load(libdir + "regexp_parse.js"); test_mix("^", no_multiline_flags, Assertion("START_OF_INPUT")); test_mix("^", multiline_flags, Assertion("START_OF_LINE")); test_mix("$", no_multiline_flags, Assertion("END_OF_INPUT")); test_mix("$", multiline_flags, Assertion("END_OF_LINE")); test_mix("\\b", all_flags, Assertion("BOUNDARY")); test_mix("\\B", all_flags, Assertion("NON_BOUNDARY"));
Yukarumya/Yukarum-Redfoxes
js/src/jit-test/tests/regexp_parse/Assertion.js
JavaScript
mpl-2.0
495
dojo.provide("dojox.charting.widget.Sparkline"); dojo.require("dojox.charting.widget.Chart2D"); dojo.require("dojox.charting.themes.ET.greys"); (function(){ var d = dojo; dojo.declare("dojox.charting.widget.Sparkline", dojox.charting.widget.Chart2D, { theme: dojox.charting.themes.ET.greys, margins: { l: 0, r: 0, t: 0, b: 0 }, type: "Lines", valueFn: "Number(x)", store: "", field: "", query: "", queryOptions: "", start: "0", count: "Infinity", sort: "", data: "", name: "default", buildRendering: function(){ var n = this.srcNodeRef; if( !n.childNodes.length || // shortcut the query !d.query("> .axis, > .plot, > .action, > .series", n).length){ var plot = document.createElement("div"); d.attr(plot, { "class": "plot", "name": "default", "type": this.type }); n.appendChild(plot); var series = document.createElement("div"); d.attr(series, { "class": "series", plot: "default", name: this.name, start: this.start, count: this.count, valueFn: this.valueFn }); d.forEach( ["store", "field", "query", "queryOptions", "sort", "data"], function(i){ if(this[i].length){ d.attr(series, i, this[i]); } }, this ); n.appendChild(series); } this.inherited(arguments); } } ); })();
ThesisPlanet/EducationPlatform
src/public/js/libs/dojox/charting/widget/Sparkline.js
JavaScript
mpl-2.0
1,469
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* eslint-env browser */ "use strict"; const { TAKE_SCREENSHOT_START, TAKE_SCREENSHOT_END, } = require("./index"); const { getFormatStr } = require("../utils/l10n"); const { getToplevelWindow } = require("sdk/window/utils"); const { Task: { spawn } } = require("devtools/shared/task"); const e10s = require("../utils/e10s"); const Services = require("Services"); const CAMERA_AUDIO_URL = "resource://devtools/client/themes/audio/shutter.wav"; const animationFrame = () => new Promise(resolve => { window.requestAnimationFrame(resolve); }); function getFileName() { let date = new Date(); let month = ("0" + (date.getMonth() + 1)).substr(-2); let day = ("0" + date.getDate()).substr(-2); let dateString = [date.getFullYear(), month, day].join("-"); let timeString = date.toTimeString().replace(/:/g, ".").split(" ")[0]; return getFormatStr("responsive.screenshotGeneratedFilename", dateString, timeString); } function createScreenshotFor(node) { let mm = node.frameLoader.messageManager; return e10s.request(mm, "RequestScreenshot"); } function saveToFile(data, filename) { return spawn(function* () { const chromeWindow = getToplevelWindow(window); const chromeDocument = chromeWindow.document; // append .png extension to filename if it doesn't exist filename = filename.replace(/\.png$|$/i, ".png"); chromeWindow.saveURL(data, filename, null, true, true, chromeDocument.documentURIObject, chromeDocument); }); } function simulateCameraEffects(node) { if (Services.prefs.getBoolPref("devtools.screenshot.audio.enabled")) { let cameraAudio = new window.Audio(CAMERA_AUDIO_URL); cameraAudio.play(); } node.animate({ opacity: [ 0, 1 ] }, 500); } module.exports = { takeScreenshot() { return function* (dispatch, getState) { yield dispatch({ type: TAKE_SCREENSHOT_START }); // Waiting the next repaint, to ensure the react components // can be properly render after the action dispatched above yield animationFrame(); let iframe = document.querySelector("iframe"); let data = yield createScreenshotFor(iframe); simulateCameraEffects(iframe); yield saveToFile(data, getFileName()); dispatch({ type: TAKE_SCREENSHOT_END }); }; } };
Yukarumya/Yukarum-Redfoxes
devtools/client/responsive.html/actions/screenshot.js
JavaScript
mpl-2.0
2,551
// Tests. Mocha TDD/assert style. See // http://visionmedia.github.com/mocha/ // http://nodejs.org/docs/latest/api/assert.html var constants = require('constants'); var assert = require('assert'); var sslConfig = require('../index.js'); var log = console.log.bind(console); suite('Checking generated config', function(){ test('modern config', function(done){ var config = sslConfig('modern'); assert.equal(config.ciphers, 'ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!3DES:!MD5:!PSK'); assert.equal(config.minimumTLSVersion, constants.SSL_OP_NO_TLSv1_1|constants.SSL_OP_NO_TLSv1|constants.SSL_OP_NO_SSLv3|constants.SSL_OP_NO_SSLv2); done(); }); test('intermediate config', function(done){ var config = sslConfig('intermediate'); assert.equal(config.ciphers, 'ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA:ECDHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-RSA-AES256-SHA256:DHE-RSA-AES256-SHA:ECDHE-ECDSA-DES-CBC3-SHA:ECDHE-RSA-DES-CBC3-SHA:EDH-RSA-DES-CBC3-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:DES-CBC3-SHA:!DSS:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!aECDH:!EDH-DSS-DES-CBC3-SHA:!EDH-RSA-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA'); assert.equal(config.minimumTLSVersion, constants.SSL_OP_NO_SSLv3|constants.SSL_OP_NO_SSLv2); done(); }); test('old config', function(done){ var config = sslConfig('old'); assert.equal(config.ciphers, 'ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:ECDHE-RSA-DES-CBC3-SHA:ECDHE-ECDSA-DES-CBC3-SHA:EDH-RSA-DES-CBC3-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:AES:DES-CBC3-SHA:HIGH:SEED:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!RSAPSK:!aDH:!aECDH:!EDH-DSS-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA:!SRP'); assert.equal(config.minimumTLSVersion, constants.SSL_OP_NO_SSLv2); done(); }); test('non-existent config', function(done){ assert.throws( function() { var config = sslConfig('banana'); }, Error ); done(); }); });
certsimple/ssl-config
test/tests.js
JavaScript
mpl-2.0
3,120
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ const $ = require('jquery'); const _ = require('underscore'); const {assert} = require('chai'); const Account = require('models/account'); const AuthErrors = require('lib/auth-errors'); const Backbone = require('backbone'); const BaseBroker = require('models/auth_brokers/base'); const Metrics = require('lib/metrics'); const Relier = require('models/reliers/relier'); const sinon = require('sinon'); const View = require('views/sign_in_totp_code'); const WindowMock = require('../../mocks/window'); const TOTP_CODE = '123123'; describe('views/sign_in_totp_code', () => { let account; let broker; let metrics; let model; let notifier; let relier; let view; let windowMock; beforeEach(() => { windowMock = new WindowMock(); relier = new Relier({ window: windowMock }); broker = new BaseBroker({ relier: relier, window: windowMock }); account = new Account({ email: 'a@a.com', sessionToken: 'someToken', uid: 'uid' }); model = new Backbone.Model({ account: account, lastPage: 'signin', password: 'password' }); notifier = _.extend({}, Backbone.Events); metrics = new Metrics({ notifier, sentryMetrics: { captureException () {} } }); view = new View({ broker, canGoBack: true, metrics, model, notifier, relier, viewName: 'sign-in-totp-code', window: windowMock }); sinon.stub(view, 'getSignedInAccount').callsFake(() => model.get('account')); $(windowMock.document.body).attr('data-flow-id', '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef'); $(windowMock.document.body).attr('data-flow-begin', Date.now()); sinon.spy(view, 'logFlowEvent'); return view.render() .then(() => $('#container').html(view.$el)); }); afterEach(() => { metrics.destroy(); view.remove(); view.destroy(); view = metrics = null; }); describe('render', () => { it('renders the view', () => { assert.lengthOf(view.$('#fxa-totp-code-header'), 1); assert.include(view.$('.verification-totp-message').text(), 'security code'); assert.equal(view.$('#use-recovery-code-link').attr('href'), '/signin_recovery_code'); assert.equal(view.$('.different-account-link').attr('href'), '/signin'); }); describe('without an account', () => { beforeEach(() => { account = model.get('account').unset('sessionToken'); sinon.spy(view, 'navigate'); return view.render(); }); it('redirects to the signin page', () => { assert.isTrue(view.navigate.calledWith('signin')); }); }); }); describe('validateAndSubmit', () => { beforeEach(() => { sinon.stub(view, 'submit').callsFake(() => Promise.resolve()); sinon.spy(view, 'showValidationError'); }); describe('with an empty code', () => { beforeEach(() => { view.$('#totp-code').val(''); return view.validateAndSubmit().then(assert.fail, () => {}); }); it('displays a tooltip, does not call submit', () => { assert.isTrue(view.showValidationError.called); assert.isFalse(view.submit.called); }); }); const validCodes = [ TOTP_CODE, ' ' + TOTP_CODE, TOTP_CODE + ' ', ' ' + TOTP_CODE + ' ', '001-001', '111 111' ]; validCodes.forEach((code) => { describe(`with a valid code: '${code}'`, () => { beforeEach(() => { view.$('.totp-code').val(code); return view.validateAndSubmit(); }); it('calls submit', () => { assert.equal(view.submit.callCount, 1); }); }); }); }); describe('submit', () => { describe('success', () => { beforeEach(() => { sinon.stub(account, 'verifyTotpCode').callsFake(() => Promise.resolve({success: true})); sinon.stub(view, 'invokeBrokerMethod').callsFake(() => Promise.resolve()); view.$('.totp-code').val(TOTP_CODE); return view.submit(); }); it('calls correct broker methods', () => { assert.isTrue(account.verifyTotpCode.calledWith(TOTP_CODE), 'verify with correct code'); assert.isTrue(view.invokeBrokerMethod.calledWith('afterCompleteSignInWithCode', account)); }); it('logs flowEvent', () => { assert.equal(view.logFlowEvent.callCount, 1); }); }); describe('invalid TOTP code', () => { beforeEach(() => { sinon.stub(account, 'verifyTotpCode').callsFake(() => Promise.resolve({success: false})); sinon.spy(view, 'showValidationError'); view.$('.totp-code').val(TOTP_CODE); return view.submit(); }); it('rejects with the error for display', () => { assert.equal(view.showValidationError.args[0][1].errno, 1054, 'correct error thrown'); }); }); describe('errors', () => { beforeEach(() => { sinon.stub(account, 'verifyTotpCode').callsFake(() => Promise.reject(AuthErrors.toError('UNEXPECTED_ERROR'))); sinon.spy(view, 'showValidationError'); view.$('.totp-code').val(TOTP_CODE); return view.submit(); }); it('rejects with the error for display', () => { assert.equal(view.showValidationError.args[0][1].errno, 999, 'correct error thrown'); }); }); }); });
mozilla/fxa-content-server
app/tests/spec/views/sign_in_totp_code.js
JavaScript
mpl-2.0
5,647
// Copyright 2011-2012 Norbert Lindenberg. All rights reserved. // Copyright 2012 Mozilla Corporation. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /** * @description Tests that the number of fractional digits is determined correctly for currencies. * @author Norbert Lindenberg */ // data from http://www.currency-iso.org/dl_iso_table_a1.xml, 2013-02-25 var currencyDigits = { AED: 2, AFN: 2, ALL: 2, AMD: 2, ANG: 2, AOA: 2, ARS: 2, AUD: 2, AWG: 2, AZN: 2, BAM: 2, BBD: 2, BDT: 2, BGN: 2, BHD: 3, BIF: 0, BMD: 2, BND: 2, BOB: 2, BOV: 2, BRL: 2, BSD: 2, BTN: 2, BWP: 2, BYR: 0, BZD: 2, CAD: 2, CDF: 2, CHE: 2, CHF: 2, CHW: 2, CLF: 4, CLP: 0, CNY: 2, COP: 2, COU: 2, CRC: 2, CUC: 2, CUP: 2, CVE: 2, CZK: 2, DJF: 0, DKK: 2, DOP: 2, DZD: 2, EGP: 2, ERN: 2, ETB: 2, EUR: 2, FJD: 2, FKP: 2, GBP: 2, GEL: 2, GHS: 2, GIP: 2, GMD: 2, GNF: 0, GTQ: 2, GYD: 2, HKD: 2, HNL: 2, HRK: 2, HTG: 2, HUF: 2, IDR: 2, ILS: 2, INR: 2, IQD: 3, IRR: 2, ISK: 0, JMD: 2, JOD: 3, JPY: 0, KES: 2, KGS: 2, KHR: 2, KMF: 0, KPW: 2, KRW: 0, KWD: 3, KYD: 2, KZT: 2, LAK: 2, LBP: 2, LKR: 2, LRD: 2, LSL: 2, LTL: 2, LVL: 2, LYD: 3, MAD: 2, MDL: 2, MGA: 2, MKD: 2, MMK: 2, MNT: 2, MOP: 2, MRO: 2, MUR: 2, MVR: 2, MWK: 2, MXN: 2, MXV: 2, MYR: 2, MZN: 2, NAD: 2, NGN: 2, NIO: 2, NOK: 2, NPR: 2, NZD: 2, OMR: 3, PAB: 2, PEN: 2, PGK: 2, PHP: 2, PKR: 2, PLN: 2, PYG: 0, QAR: 2, RON: 2, RSD: 2, RUB: 2, RWF: 0, SAR: 2, SBD: 2, SCR: 2, SDG: 2, SEK: 2, SGD: 2, SHP: 2, SLL: 2, SOS: 2, SRD: 2, SSP: 2, STD: 2, SVC: 2, SYP: 2, SZL: 2, THB: 2, TJS: 2, TMT: 2, TND: 3, TOP: 2, TRY: 2, TTD: 2, TWD: 2, TZS: 2, UAH: 2, UGX: 0, USD: 2, USN: 2, USS: 2, UYI: 0, UYU: 2, UZS: 2, VEF: 2, VND: 0, VUV: 0, WST: 2, XAF: 0, XCD: 2, XOF: 0, XPF: 0, YER: 2, ZAR: 2, ZMW: 2, ZWL: 2 }; Object.getOwnPropertyNames(currencyDigits).forEach(function (currency) { var digits = currencyDigits[currency]; format = Intl.NumberFormat([], {style: "currency", currency: currency}); var min = format.resolvedOptions().minimumFractionDigits; var max = format.resolvedOptions().maximumFractionDigits; if (min !== digits) { $ERROR("Didn't get correct minimumFractionDigits for currency " + currency + "; expected " + digits + ", got " + min + "."); } if (max !== digits) { $ERROR("Didn't get correct maximumFractionDigits for currency " + currency + "; expected " + digits + ", got " + max + "."); } });
cstipkovic/spidermonkey-research
js/src/tests/test262/intl402/ch11/11.1/11.1.1_20_c.js
JavaScript
mpl-2.0
3,125
var DB = require('./lib/db.js'); function SQLContext(options) { this.readOnly = options.isReadOnly; this.db = options.db; } function _put(db, key, value, callback) { db.createOrUpdate(key, value, function(err) { if(err) { return callback(err); } callback(); }); } SQLContext.prototype.putObject = function(key, value, callback) { if(this.readOnly) { return callback(new Error('write operation on read-only context.')); } var json = JSON.stringify(value); var buf = new Buffer(json, 'utf8'); _put(this.db, key, buf, callback); }; SQLContext.prototype.putBuffer = function(key, value, callback) { if(this.readOnly) { return callback(new Error('write operation on read-only context.')); } _put(this.db, key, value, callback); }; SQLContext.prototype.delete = function (key, callback) { if(this.readOnly) { return callback(new Error('write operation on read-only context.')); } this.db.remove(key, function(err) { if(err) { return callback(err); } callback(); }); }; SQLContext.prototype.clear = function (callback) { if(this.readOnly) { return callback(new Error('write operation on read-only context.')); } this.db.clearAll(callback); }; function _get(db, key, callback) { db.find(key, callback); } SQLContext.prototype.getObject = function(key, callback) { _get(this.db, key, function(err, data) { if(err) { return callback(err); } if(data) { try { data = JSON.parse(data.toString('utf8')); } catch(e) { return callback(e); } } callback(null, data); }); }; SQLContext.prototype.getBuffer = function(key, callback) { _get(this.db, key, callback); }; function SQLProvider(options) { this.options = options || {}; this.user = options.user; } SQLProvider.isSupported = function() { return (typeof module !== 'undefined' && module.exports); }; SQLProvider.prototype.open = function(callback) { if(!this.user) { return callback(new Error('missing user')); } this.db = new DB(this.options, function(err) { if (err) { return callback(err); } callback(); }); }; SQLProvider.prototype.getReadOnlyContext = function() { return new SQLContext({isReadOnly: true, db: this.db}); }; SQLProvider.prototype.getReadWriteContext = function() { return new SQLContext({isReadOnly: false, db: this.db}); }; // Forward db type constants SQLProvider.MYSQL = DB.MYSQL; SQLProvider.SQLITE = DB.SQLITE; SQLProvider.POSTGRES = DB.POSTGRES; SQLProvider.MARIADB = DB.MARIADB; module.exports = SQLProvider;
filerjs/filer-sql
index.js
JavaScript
mpl-2.0
2,594
/* kJscsspFONT_FACE_RULE */ function jscsspFontFaceRule() { this.type = kJscsspFONT_FACE_RULE; this.parsedCssText = null; this.descriptors = []; this.parentStyleSheet = null; this.parentRule = null; } jscsspFontFaceRule.prototype = { cssText: function() { var rv = gTABS + "@font-face {\n"; var preservedGTABS = gTABS; gTABS += " "; for (var i = 0; i < this.descriptors.length; i++) rv += gTABS + this.descriptors[i].cssText() + "\n"; gTABS = preservedGTABS; return rv + gTABS + "}"; }, setCssText: function(val) { var sheet = {cssRules: []}; var parser = new CSSParser(val); var token = parser.getToken(true, true); if (token.isAtRule("@font-face")) { if (parser.parseFontFaceRule(token, sheet)) { var newRule = sheet.cssRules[0]; this.descriptors = newRule.descriptors; this.parsedCssText = newRule.parsedCssText; return; } } throw DOMException.SYNTAX_ERR; } };
therealglazou/jscssp
src/om/jscsspFontFaceRule.js
JavaScript
mpl-2.0
985
'use strict'; QUnit.module('ellipse', function() { var boundaryOnAngle = function(ellipse, angle) { var a = ellipse.a; var b = ellipse.b; var rad = angle * Math.PI / 180; return g.Point(ellipse.x + a * Math.cos(rad), ellipse.y + b * Math.sin(rad)).round(); }; QUnit.test('validate helper boundaryOnAngle', function(assert) { var a = 150; var b = 50; var c = g.Point(0, 0); var ellipse = g.Ellipse(c, a, b); assert.propEqual(boundaryOnAngle(ellipse, 0), g.Point(150, 0)); assert.propEqual(boundaryOnAngle(ellipse, 90), (g.Point(0, 50))); assert.propEqual(boundaryOnAngle(ellipse, 180), (g.Point(-150, 0))); assert.propEqual(boundaryOnAngle(ellipse, 270), (g.Point(0, -50))); }); QUnit.module('constructor', function() { QUnit.test('creates a new Ellipse object', function(assert) { assert.ok(g.ellipse() instanceof g.ellipse); assert.ok(g.ellipse({ x: 1, y: 2 }, 3, 4) instanceof g.ellipse); assert.equal(g.ellipse({ x: 1, y: 2 }, 3, 4).x, 1); assert.equal(g.ellipse({ x: 1, y: 2 }, 3, 4).y, 2); assert.equal(g.ellipse({ x: 1, y: 2 }, 3, 4).a, 3); assert.equal(g.ellipse({ x: 1, y: 2 }, 3, 4).b, 4); assert.ok(g.ellipse(g.ellipse({ x: 1, y: 2 }, 3, 4)).equals(g.ellipse({ x: 1, y: 2 }, 3, 4))); // default values assert.ok(g.ellipse().equals(g.rect({ x: 0, y: 0 }, 0, 0))); }); }); QUnit.module('fromRect(rect)', function() { QUnit.test('creates a new Ellipse object', function(assert) { assert.ok(g.ellipse.fromRect(g.rect()) instanceof g.ellipse); var r = g.rect(100, 50, 150, 70); assert.ok(g.rect.fromEllipse(g.ellipse.fromRect(r)).equals(r)); }); }); QUnit.module('tangentTheta', function(hooks) { var radiusTangentAngle = function(ellipse, angle) { var theta = ellipse.tangentTheta(boundaryOnAngle(ellipse, angle), angle); return Math.round((theta + angle) % 180); }; QUnit.test('validate on circle', function(assert) { var a = 50; var b = 50; var c = g.Point(0, 0); var ellipse = g.Ellipse(c, a, b); for (var angle = 0; angle <= 360; angle += 10) { var tangentAngle = radiusTangentAngle(ellipse, angle); var tolerance = 2; assert.ok(tangentAngle - 90 < tolerance && tangentAngle - 90 > -tolerance, angle + 'deg, should be 90deg, actual: ' + tangentAngle); } }); QUnit.test('validate helper boundaryOnAngle', function(assert) { function checkTangentThetaOnEllipse(ellipse, message) { assert.equal(ellipse.tangentTheta(boundaryOnAngle(ellipse, 0)), 270, '0 on ' + message); assert.equal(ellipse.tangentTheta(boundaryOnAngle(ellipse, 180)), 90, '180 on ' + message); assert.equal(ellipse.tangentTheta(boundaryOnAngle(ellipse, 90)), 180, '90 on ' + message); assert.equal(ellipse.tangentTheta(boundaryOnAngle(ellipse, 270)), 0, '270 on ' + message); for (var angle = 0; angle <= 360; angle += 5) { var theta = ellipse.tangentTheta(boundaryOnAngle(ellipse, angle), angle); assert.ok(theta >= 0, 'tangent theta is numeric on ' + message); } } checkTangentThetaOnEllipse(g.Ellipse(g.Point(11, 22), 50, 100), 'wide ellipse'); checkTangentThetaOnEllipse(g.Ellipse(g.Point(11, 22), 100, 50), 'tall ellipse'); }); }); QUnit.module('Where is point in space with ellipse', function(hooks) { QUnit.test('normalizedDistance', function(assert) { var tolerance = 0.009; var ellipse = g.Ellipse(g.Point(111, 111), 150, 150); var r1 = ellipse.normalizedDistance(ellipse.center()); assert.ok(r1 < 1 && r1 >= 0); assert.ok(ellipse.normalizedDistance(ellipse.center().offset(500, 500)) > 1); for (var angle = 0; angle < 360; angle += 1) { var b = boundaryOnAngle(ellipse, angle); var x = ellipse.normalizedDistance(b); assert.ok(x - 1 < tolerance && x - 1 > -tolerance, 'point on angle: ' + angle + ' result:' + x); } }); }); QUnit.module('inflate()', function() { QUnit.test('inflate ellipse', function(assert) { assert.ok(g.ellipse({ x: 0, y: 0 }, 1, 1).inflate().equals(g.ellipse({ x: 0, y: 0 }, 1, 1))); assert.ok(g.ellipse({ x: 0, y: 0 }, 1, 1).inflate(2, 1).equals(g.ellipse({ x: 0, y: 0 }, 5, 3))); assert.ok(g.ellipse({ x: 0, y: 0 }, 1, 1).inflate(0, 1).equals(g.ellipse({ x: 0, y: 0 }, 1, 3))); assert.ok(g.ellipse({ x: 0, y: 0 }, 1, 1).inflate(2, 0).equals(g.ellipse({ x: 0, y: 0 }, 5, 1))); assert.ok(g.ellipse({ x: 0, y: 0 }, 1, 1).inflate(5).equals(g.ellipse({ x: 0, y: 0 }, 11, 11))); assert.ok(g.ellipse({ x: 0, y: 0 }, 1, 1).inflate(2).equals( g.ellipse.fromRect(g.rect.fromEllipse(g.ellipse({ x: 0, y: 0 }, 1, 1).inflate(2))) )); }); }); QUnit.module('prototype', function() { QUnit.module('bbox()', function() { }); QUnit.module('clone()', function() { }); QUnit.module('equals(ellipse)', function() { }); QUnit.module('intersectionWithLineFromCenterToPoint(point, angle)', function() { }); QUnit.module('toString()', function() { }); }); });
chill117/joint
test/geometry/ellipse.js
JavaScript
mpl-2.0
5,747
import { inject as service } from '@ember/service'; import Component from '@ember/component'; import { task } from 'ember-concurrency'; export default Component.extend({ router: service(), controlGroup: service(), store: service(), // public attrs model: null, controlGroupResponse: null, //internal state error: null, unwrapData: null, unwrap: task(function* (token) { let adapter = this.store.adapterFor('tools'); this.set('error', null); try { let response = yield adapter.toolAction('unwrap', null, { clientToken: token }); this.set('unwrapData', response.auth || response.data); this.controlGroup.deleteControlGroupToken(this.model.id); } catch (e) { this.set('error', `Token unwrap failed: ${e.errors[0]}`); } }).drop(), markAndNavigate: task(function* () { this.controlGroup.markTokenForUnwrap(this.model.id); let { url } = this.controlGroupResponse.uiParams; yield this.router.transitionTo(url); }).drop(), });
hashicorp/vault
ui/app/components/control-group-success.js
JavaScript
mpl-2.0
1,006
/* * This program is part of the OpenLMIS logistics management information system platform software. * Copyright © 2017 VillageReach * * This program is free software: you can redistribute it and/or modify it under the terms * of the GNU Affero General Public License as published by the Free Software Foundation, either * version 3 of the License, or (at your option) any later version. *   * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  * See the GNU Affero General Public License for more details. You should have received a copy of * the GNU Affero General Public License along with this program. If not, see * http://www.gnu.org/licenses.  For additional information contact info@OpenLMIS.org.  */ (function() { 'use strict'; /** * @module admin-rejection-reason * * @description * Rejection Reason. */ angular.module('admin-rejection-reason', [ 'openlmis-rights', 'openlmis-admin', 'openlmis-class-extender', 'openlmis-i18n', 'openlmis-repository', 'openlmis-templates', 'openlmis-modal-state', 'ui.router' ]); })();
OpenLMIS/openlmis-requisition-ui
src/admin-rejection-reason/admin-rejection-reason.module.js
JavaScript
agpl-3.0
1,288
'use strict'; exports.up = function(knex, Promise) { return knex.schema.table('settings', function(table) { table.integer('next_invoice_number'); }); }; exports.down = function(knex, Promise) { return knex.schema.table('settings', function(t) { t.dropColumn('next_invoice_number'); }); };
nnarhinen/nerve
migrations/20141102214329_settings_invoice_number.js
JavaScript
agpl-3.0
307
import React, { Component, PropTypes } from 'react' import { updateCurrentUser, notify } from '../actions' import ListItemTagInput from './ListItemTagInput' export default class ProfileSkillsModule extends Component { static propTypes = { person: PropTypes.object } static contextTypes = { dispatch: PropTypes.func } constructor (props) { super(props) this.state = { tags: [], valid: false } } update = (type, tags) => { const valid = tags.length > 0 return this.setState({ tags, valid }) } save = () => { const { tags } = this.state const { dispatch } = this.context return Promise.all([ dispatch(updateCurrentUser({tags})), dispatch(notify('Skills added successfully.', {type: 'info'})) ]) } render () { const { update, save } = this const { person } = this.props const { valid } = this.state const firstName = person.name.split(' ')[0] return <div className='feed-module profile-skills'> <h2> Welcome {firstName}! Are there any skills, passions or interests you’d like to be known for in the community? </h2> <p> Pick “tags” to describe yourself and to find people and opportunities that match your interests. </p> <ListItemTagInput type='tags' className='modal-input' person={person} update={update} context='feed-module' /> <div className='meta'> Press Enter (Return) after each tag. Use a dash (-) between words in a tag. </div> <button type='button' className='btn-primary' disabled={!valid} onClick={save}> Save </button> </div> } }
Hylozoic/hylo-redux
src/components/ProfileSkillsModule.js
JavaScript
agpl-3.0
1,727
var Password = require('../../lib/Interactor/Password.js'); var should = require('should'); describe('Password test', function() { var crypted = ''; it('should crypt a password', function() { crypted = Password.generate('testpass'); }); it('should fail with wrong password', function() { Password.verify('testpasds', crypted).should.be.false; }); it('should success with right password', function() { Password.verify('testpass', crypted).should.be.true; }); });
PaulGuo/PM25
PM25-Cli/test/interface/password.mocha.js
JavaScript
agpl-3.0
496
(function ($, undefined) { $.widget("ui.HarvesterInlineEditor", $.ui.CiteInlineEditor, { options: { }, _refreshView: function () { this._super(); //var item = this.option('item'); this.element.empty(); this.initEditor(); //this.showData(item); //this.setCurrentDisplayModeAndApply($.ui.CiteBaseControl.DisplayMode.Edit); }, initEditor: function () { var self = this; var definitionTable = $('<table></table>'); this.element.append(definitionTable); { var r = $('<tr></tr>'); var c = $('<td></td>'); this.sveEndpoint = $('<div id="' + $.ui.CiteBaseControl.generateControlId() + '"></div>'); c.append(this.sveEndpoint); var c2 = $('<td></td>'); var lbl = $('<label class="formFieldLabel" for="' + this.sveEndpoint[0].id + '">' + 'Endpoint' +'</label>'); c2.append(lbl); r.append(c2); r.append(c); definitionTable.append(r); this.sveEndpoint.CiteStringValueEditor({ currentDisplayMode: $.ui.CiteBaseControl.DisplayMode.Edit, autoInitialize: true }); } { var r = $('<tr></tr>'); var c = $('<td></td>'); this.sveEndpointAlias = $('<div id="' + $.ui.CiteBaseControl.generateControlId() + '"></div>'); c.append(this.sveEndpointAlias); var c2 = $('<td></td>'); var lbl = $('<label class="formFieldLabel" for="' + this.sveEndpointAlias[0].id + '">' + 'Endpoint Alias' +'</label>'); c2.append(lbl); r.append(c2); r.append(c); definitionTable.append(r); this.sveEndpointAlias.CiteStringValueEditor({ currentDisplayMode: $.ui.CiteBaseControl.DisplayMode.Edit, autoInitialize: true }); } { var r = $('<tr></tr>'); var c = $('<td></td>'); this.svePeriod = $('<div id="' + $.ui.CiteBaseControl.generateControlId() + '"></div>'); c.append(this.svePeriod); var c2 = $('<td></td>'); var lbl = $('<label class="formFieldLabel" for="' + this.svePeriod[0].id + '">' + 'Period' +'</label>'); c2.append(lbl); r.append(c2); r.append(c); definitionTable.append(r); this.svePeriod.CiteStringValueEditor({ currentDisplayMode: $.ui.CiteBaseControl.DisplayMode.Edit, autoInitialize: true }); } { var r = $('<tr></tr>'); var c = $('<td></td>'); this.asgPeriodType = $('<div id="' + $.ui.CiteBaseControl.generateControlId() + '"></div>'); c.append(this.asgPeriodType); var c2 = $('<td></td>'); var lbl = $('<label class="formFieldLabel" for="' + this.asgPeriodType[0].id + '">' + 'Period Type' +'</label>'); c2.append(lbl); r.append(c2); r.append(c); definitionTable.append(r); var suggestions = [{ 'Text': 'Seconds' , 'Value': 'SECONDS' }, { 'Text': 'Minutes' , 'Value': 'MINUTES' }, { 'Text': 'Hours' , 'Value': 'HOURS' }, { 'Text': 'Days' , 'Value': 'DAYS' }]; this.asgPeriodType.CiteAutoSuggest({ currentDisplayMode: $.ui.CiteBaseControl.DisplayMode.Edit, suggestionMode: $.ui.CiteAutoSuggest.SuggestionMode.Static, uiMode: $.ui.CiteAutoSuggest.UIMode.DropDown, selectionNameProperty: 'Text', selectionValueProperty: 'Value', staticSuggestions: suggestions, autoInitialize: true }); } { var r = $('<tr></tr>'); var c1 = $('<td></td>'); this.saveButton = $('<button id="cancel" name="save" class="btn btn-default" value="1">Save</button>'); c1.append(this.saveButton); var c2 = $('<td></td>'); this.cancelButton = $('<button id="cancel" name="cancel" class="btn btn-default" value="1">Cancel</button>'); c2.append(this.cancelButton); r.append(c1); r.append(c2); definitionTable.append(r); this.saveButton.on('click', function() { eval(self.options.saveCallback)(); }) this.cancelButton.on('click', function() { eval(self.options.cancelCallback)(); }) } }, getData: function () { var result = {}; result.endpoint = this.sveEndpoint.CiteStringValueEditor('getValue'); result.endpointAlias = this.sveEndpointAlias.CiteStringValueEditor('getValue'); result.period = this.svePeriod.CiteStringValueEditor('getValue'); var values = this.asgPeriodType.CiteAutoSuggest('getSelectedValues'); result.periodType = (values.length == 0) ? '' : values[0]; console.log(result); return result; } }) }(jQuery));
cite-sa/xwcps
xwcps-parser-ui/libs/js/general/widgets/jquery.harvesterInlineEditor.js
JavaScript
agpl-3.0
4,417
module.exports = (app) => { let Base58 = {}; Base58.alphabet = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'; Base58.alphabetMap = {}; for(let i = 0; i < Base58.alphabet.length; i++) { Base58.alphabetMap[Base58.alphabet.charAt(i)] = i } Base58.encode = function(buffer) { if (buffer.length === 0) return ''; let i, j, digits = [0]; for (i = 0; i < buffer.length; i++) { for (j = 0; j < digits.length; j++) digits[j] <<= 8 digits[digits.length - 1] += buffer[i]; let carry = 0; for (j = digits.length - 1; j >= 0; j--){ digits[j] += carry; carry = (digits[j] / 58) | 0; digits[j] %= 58 } while (carry) { digits.unshift(carry); carry = (digits[0] / 58) | 0; digits[0] %= 58 } } // deal with leading zeros for (i = 0; i < buffer.length - 1 && buffer[i] == 0; i++) digits.unshift(0) return digits.map(function(digit) { return Base58.alphabet[digit] }).join('') }; Base58.decode = function(string) { if (string.length === 0) return (new Uint8Array()); let input = string.split('').map(function(c){ return Base58.alphabetMap[c] }); let i, j, bytes = [0]; for (i = 0; i < input.length; i++) { for (j = 0; j < bytes.length; j++) bytes[j] *= 58 bytes[bytes.length - 1] += input[i]; let carry = 0; for (j = bytes.length - 1; j >= 0; j--){ bytes[j] += carry; carry = bytes[j] >> 8; bytes[j] &= 0xff } while (carry) { bytes.unshift(carry); carry = bytes[0] >> 8; bytes[0] &= 0xff } } // deal with leading zeros for (i = 0; i < input.length - 1 && input[i] == 0; i++) bytes.unshift(0) return (new Uint8Array(bytes)) }; app.factory('Base58', function() { return { encode: Base58.encode, decode: Base58.decode }; }); };
duniter/duniter-ui
app/js/services/base58.js
JavaScript
agpl-3.0
1,932
import React from 'react'; import SPELLS from 'common/SPELLS/index'; import { formatDuration } from 'common/format'; import StatisticBox, { STATISTIC_ORDER } from 'interface/others/StatisticBox'; import STATISTIC_CATEGORY from 'interface/others/STATISTIC_CATEGORY'; import SpellLink from 'common/SpellLink'; import SpellIcon from 'common/SpellIcon'; import Events from 'parser/core/Events'; import Analyzer, { SELECTED_PLAYER } from 'parser/core/Analyzer'; import SpellUsable from 'parser/shared/modules/SpellUsable'; import EventEmitter from 'parser/core/modules/EventEmitter'; import indexById from 'common/indexById'; import safeMerge from 'common/safeMerge'; import T_DEATH_KNIGHT from 'common/SPELLS/talents/deathknight'; import T_DEMON_HUNTER from 'common/SPELLS/talents/demonhunter'; import T_DRUID from 'common/SPELLS/talents/druid'; import T_HUNTER from 'common/SPELLS/talents/hunter'; import T_MAGE from 'common/SPELLS/talents/mage'; import T_MONK from 'common/SPELLS/talents/monk'; import T_PALADIN from 'common/SPELLS/talents/paladin'; import T_PRIEST from 'common/SPELLS/talents/priest'; import T_ROGUE from 'common/SPELLS/talents/rogue'; import T_SHAMAN from 'common/SPELLS/talents/shaman'; import T_WARLOCK from 'common/SPELLS/talents/warlock'; import T_WARRIOR from 'common/SPELLS/talents/warrior'; import DEATH_KNIGHT from 'common/SPELLS/deathknight'; import DEMON_HUNTER from 'common/SPELLS/demonhunter'; import DRUID from 'common/SPELLS/druid'; import HUNTER from 'common/SPELLS/hunter'; import MAGE from 'common/SPELLS/mage'; import MONK from 'common/SPELLS/monk'; import PALADIN from 'common/SPELLS/paladin'; import PRIEST from 'common/SPELLS/priest'; import ROGUE from 'common/SPELLS/rogue'; import SHAMAN from 'common/SPELLS/shaman'; import WARLOCK from 'common/SPELLS/warlock'; import WARRIOR from 'common/SPELLS/warrior'; const CLASS_ABILITIES = { ...safeMerge(T_DEATH_KNIGHT, T_DEMON_HUNTER, T_DRUID, T_HUNTER, T_MAGE, T_MONK, T_PALADIN, T_PRIEST, T_ROGUE, T_SHAMAN, T_WARLOCK, T_WARRIOR), ...safeMerge(DEATH_KNIGHT, DEMON_HUNTER, DRUID, HUNTER, MAGE, MONK, PALADIN, PRIEST, ROGUE, SHAMAN, WARLOCK, WARRIOR), }; indexById(CLASS_ABILITIES); const SMALL_TRUTH = 0.3; const BIG_TRUTH = 0.5; const debug = false; class IneffableTruth extends Analyzer { static dependencies = { spellUsable: SpellUsable, }; buffActive = false; lastTimestamp = 0; reducedDuration = []; reductionPercent = 0; constructor(...args) { super(...args); this.active = this.selectedCombatant.hasCorruptionByName("Ineffable Truth"); if (!this.active) { return; } this.reductionPercent += this.selectedCombatant.getCorruptionCount(SPELLS.INEFFABLE_TRUTH_T1.id) * SMALL_TRUTH; this.reductionPercent += this.selectedCombatant.getCorruptionCount(SPELLS.INEFFABLE_TRUTH_T2.id) * BIG_TRUTH; this.addEventListener(Events.applybuff.by(SELECTED_PLAYER).spell(SPELLS.INEFFABLE_TRUTH_BUFF), this.setBuffActive); this.addEventListener(Events.removebuff.by(SELECTED_PLAYER).spell(SPELLS.INEFFABLE_TRUTH_BUFF), this.setBuffInactive); this.addEventListener(EventEmitter.catchAll, this.reduceCooldowns); } setBuffActive(event) { this.buffActive = true; this.lastTimestamp = event.timestamp; } setBuffInactive() { this.buffActive = false; debug && this.log(this.reducedDuration); } reduceCooldowns(event) { if (!this.buffActive) { return; } /** * This is assuming that stacking this corruption works additive, might need adjustment in the future * 1x 50%: For every 1 second of elapsed time, reduce cooldowns for another 50% of that (0.5 seconds) * 1x 30% 1x 50%: For every 1 second of elapsed time, reduce cooldowns for another 80% of that (0.8 seconds) * 2x 50%: For every 1 second of elapsed time, reduce cooldowns for another 100% of that (1.0 seconds) */ const reduction = (event.timestamp - this.lastTimestamp) * this.reductionPercent; Object.keys(this.spellUsable._currentCooldowns) .filter(cd => CLASS_ABILITIES[cd]) .forEach(cooldown => { debug && this.log(cooldown); this.spellUsable.reduceCooldown(cooldown, reduction, event.timestamp); if (!this.reducedDuration[cooldown]) { this.reducedDuration[cooldown] = reduction; } else { this.reducedDuration[cooldown] += reduction; } }); this.lastTimestamp = event.timestamp; } get totalReduction() { return this.reducedDuration.reduce((acc, curr) => acc + curr, 0) / 1000; } statistic() { return ( <StatisticBox icon={<SpellIcon id={SPELLS.INEFFABLE_TRUTH_BUFF.id} />} value={`${formatDuration(this.totalReduction)} min reduction`} category={STATISTIC_CATEGORY.ITEMS} position={STATISTIC_ORDER.OPTIONAL(60)} label="Ineffable Truth" > <table className="table table-condensed"> <thead> <tr> <th /> <th>Spell</th> <th>Reduction</th> </tr> </thead> <tbody> { Object.entries(this.reducedDuration).map((cd) => ( <tr key={cd[0]}> <td><SpellIcon id={cd[0]} /></td> <td><SpellLink id={cd[0]} icon={false} /></td> <td>{formatDuration(cd[1] / 1000)}</td> </tr> ))} </tbody> </table> </StatisticBox> ); } } export default IneffableTruth;
ronaldpereira/WoWAnalyzer
src/parser/shared/modules/spells/bfa/corruptions/IneffableTruth.js
JavaScript
agpl-3.0
5,526
toastr.options = { "closeButton": true, "debug": false, "newestOnTop": true, "progressBar": true, "positionClass": "toast-bottom-full-width", "preventDuplicates": false, "showDuration": "300", "hideDuration": "1000", "timeOut": "5000", "extendedTimeOut": "1000", "showEasing": "swing", "hideEasing": "linear", "showMethod": "fadeIn", "hideMethod": "fadeOut" }; function checkEmpty(o,n) { if (o.val() === '' || o.val() === null) { var text = n.replace(":",""); toastr.error(text + " Required"); o.addClass("ui-state-error"); return false; } else { o.removeClass("ui-state-error"); return true; } } function checkNumeric(o,n) { if (! $.isNumeric(o.val())) { var text = n.replace(":",""); toastr.error(text + " is not a number!"); o.addClass("ui-state-error"); return false; } else { o.removeClass("ui-state-error"); return true; } } function checkRegexp( o, regexp, n ) { if ( !( regexp.test( o.val() ) ) ) { var text = n.replace(":",""); toastr.error("Incorrect format: " + text); o.addClass("ui-state-error"); return false; } else { o.removeClass("ui-state-error"); return true; } } function split( val ) { return val.split( /\n\s*/ ); } function extractLast( term ) { return split( term ).pop(); } function search_array(a, query_value){ var query_value1 = query_value.replace('?','\\?'); var query_value2 = query_value1.replace('(','\\('); var query_value3 = query_value2.replace(')','\\)'); var query_value4 = query_value3.replace('+','\\+'); var query_value5 = query_value4.replace('/','\\/'); var found = $.map(a, function (value) { var re = RegExp(query_value5, "g"); if(value.match(re)) { return value; } else { return null; } }); return found; } function progressbartrack() { if (parseInt(noshdata.progress) < 100) { if (noshdata.progress === 0) { $("#dialog_progressbar").progressbar({value:0}); } $.ajax({ type: "POST", url: "ajaxdashboard/progressbar-track", success: function(data){ $("#dialog_progressbar").progressbar("value", parseInt(data)); if (parseInt(data) < 100) { setTimeout(progressbartrack(),1000); noshdata.progress = data; } else { $.ajax({ type: "POST", url: "ajaxdashboard/delete-progress", success: function(data){ $("#dialog_progressbar").progressbar('destroy'); $("#dialog_load").dialog('close'); noshdata.progress = 0; } }); } } }); } } function reload_grid(id) { if ($("#"+id)[0].grid) { jQuery("#"+id).trigger("reloadGrid"); } } function open_demographics() { $.ajax({ type: "POST", url: "ajaxdashboard/demographics", dataType: "json", success: function(data){ $.each(data, function(key, value){ if (key == 'DOB') { value = editDate1(data.DOB); } $("#edit_demographics_form :input[name='" + key + "']").val(value); }); if (noshdata.group_id != '100') { $.ajax({ type: "POST", url: "ajaxdashboard/check-registration-code", success: function(data){ if (data == 'n') { $("#register_menu_demographics").show(); } else { $("#register_menu_demographics").hide(); $("#menu_registration_code").html(data); } } }); } $("#menu_lastname").focus(); $("#demographics_list_dialog").dialog('open'); } }); } function schedule_autosave() { var d = $('#providers_calendar').fullCalendar('getDate'); var n = d.getFullYear(); n = n + "," + d.getMonth(); n = n + "," + d.getDate(); var view = $('#providers_calendar').fullCalendar('getView'); n = n + "," + view.name; $.cookie('nosh-schedule', n, { path: '/' }); } function addMinutes(date, minutes) { return new Date(date.getTime() + minutes*60000); } function isOverlapping(start){ var array = $('#providers_calendar').fullCalendar('clientEvents'); var end = addMinutes(start, 15); for(var i in array){ if(!(array[i].start >= end || array[i].end <= start)){ return true; } } return false; } function loadappt() { $("#patient_appt").show(); $("#start_form").show(); $("#reason_form").show(); $("#other_event").hide(); $("#event_choose").hide(); $("#patient_search").focus(); } function loadevent() { $("#patient_appt").hide(); $("#other_event").show(); $("#start_form").show(); $("#reason_form").show(); $("#event_choose").hide(); $("#reason").focus(); } function loadcalendar (y,m,d,view) { $('#providers_calendar').fullCalendar('destroy'); $('#providers_calendar').fullCalendar({ year: y, month: m, date: d, weekends: noshdata.weekends, minTime: noshdata.minTime, maxTime: noshdata.maxTime, theme: true, allDayDefault: false, slotMinutes: 15, defaultView: view, aspectRatio: 0.8, header: { left: 'prev,next today', center: 'title', right: 'agendaWeek,agendaDay' }, editable: true, events: function(start, end, callback) { var starttime = Math.round(start.getTime() / 1000); var endtime = Math.round(end.getTime() / 1000); $.ajax({ type: "POST", url: "ajaxschedule/provider-schedule", dataType: 'json', data: "start=" + starttime + "&end=" + endtime, success: function(events) { callback(events); } }); }, dayClick: function(date, allDay, jsEvent, view) { if (allDay) { $.jGrowl('Clicked on the entire day: ' + date); } else { if (noshdata.group_id == 'schedule') { if(confirm('You will need to login to schedule an appointment. Proceed?')){ window.location = noshdata.login_url; } } else { if (noshdata.group_id != '1') { if (noshdata.group_id != '100') { $("#event_dialog").dialog("option", "title", "Schedule an Appointment"); $("#event_dialog").dialog('open'); $("#title").focus(); $("#start_date").val($.fullCalendar.formatDate(date, 'MM/dd/yyyy')); $("#start_time").val($.fullCalendar.formatDate(date, 'hh:mmTT')); $("#end").val(''); $("#schedule_visit_type").val(''); $("#end_row").show(); $("#title").val(''); $("#reason").val(''); $("#until").val(''); $("#until_row").hide(); $('#repeat').val(''); $('#status').val(''); $("#delete_form").hide(); $(".nosh_schedule_exist_event").hide(); $("#patient_appt").hide(); $("#other_event").hide(); $("#until_row").hide(); $("#start_form").hide(); $("#reason_form").hide(); $("#event_choose").show(); } else { if (isOverlapping(date)) { $.jGrowl('You cannot schedule an appointment in this time slot!'); } else { $("#schedule_visit_type").focus(); $("#start").text($.fullCalendar.formatDate(date, 'dddd, MM/dd/yyyy, hh:mmTT')); $("#start_date").val($.fullCalendar.formatDate(date, 'MM/dd/yyyy')); $("#start_time").val($.fullCalendar.formatDate(date, 'hh:mmTT')); $("#end").val(''); $("#schedule_visit_type").val(''); $("#reason").val(''); $("#until").val(''); $("#until_row").hide(); $('#repeat').val(''); $("#delete_form").hide("fast"); $("#patient_appt").show(); $("#start_form").show(); $("#reason_form").show(); $("#other_event").hide(); $("#event_choose").hide(); $("#event_dialog").dialog("option", "title", "Schedule an Appointment"); $("#event_dialog").dialog('open'); } } } } } }, eventClick: function(calEvent, jsEvent, view) { if (noshdata.group_id != '1') { $("#event_id").val(calEvent.id); $("#event_id_span").text(calEvent.id); $("#schedule_pid").val(calEvent.pid); $("#pid_span").text(calEvent.pid); $("#timestamp_span").text(calEvent.timestamp); $("#start_date").val($.fullCalendar.formatDate(calEvent.start, 'MM/dd/yyyy')); $("#start_time").val($.fullCalendar.formatDate(calEvent.start, 'hh:mmTT')); $("#end").val($.fullCalendar.formatDate(calEvent.end, 'hh:mmTT')); $("#schedule_title").val(calEvent.title); $("#schedule_visit_type").val(calEvent.visit_type); if (calEvent.visit_type){ loadappt(); $("#patient_search").val(calEvent.title); $("#end").val(''); } else { loadevent(); } $("#reason").val(calEvent.reason); $("#repeat").val(calEvent.repeat); $("#until").val(calEvent.until); var repeat_select = $("#repeat").val(); if (repeat_select != ''){ $("#until_row").show(); } else { $("#until_row").hide(); $("#until").val(''); } $("#status").val(calEvent.status); $("#notes").val(calEvent.notes); $("#delete_form").show(); $(".nosh_schedule_exist_event").show(); $("#event_choose").hide(); if (calEvent.editable != false) { $("#event_dialog").dialog("option", "title", "Edit an Appointment"); $("#event_dialog").dialog('open'); $("#title").focus(); } } }, eventDrop: function(event,dayDelta,minuteDelta,allDay,revertFunc) { if (noshdata.group_id != '1') { var start = Math.round(event.start.getTime() / 1000); var end = Math.round(event.end.getTime() / 1000); if(start){ $.ajax({ type: "POST", url: "ajaxschedule/drag-event", data: "start=" + start + "&end=" + end + "&id=" + event.id, success: function(data){ $.jGrowl("Event updated!"); } }); } else { revertFunc(); } $('.fc-event').each(function(){ $(this).tooltip('disable'); }); } else { revertFunc(); $.jGrowl("You don't have permission to do this!"); } }, eventResize: function(event,dayDelta,minuteDelta,allDay,revertFunc) { if (noshdata.group_id != '1') { var start = Math.round(event.start.getTime() / 1000); var end = Math.round(event.end.getTime() / 1000); if(start){ $.ajax({ type: "POST", url: "ajaxschedule/drag-event", data: "start=" + start + "&end=" + end + "&id=" + event.id, success: function(data){ $.jGrowl("Event updated!"); } }); } else { revertFunc(); } $('.fc-event').each(function(){ $(this).tooltip('disable'); }); } else { revertFunc(); $.jGrowl("You don't have permission to do this!"); } }, eventRender: function(event, element) { var display = 'Reason: ' + event.reason + '<br>Status: ' + event.status + '<br>' + event.notes; element.tooltip({ items: element, hide: false, show: false, content: display }); element.tooltip('enable'); } }); $('#providers_datepicker').datepicker('destroy'); $('#providers_datepicker').datepicker({ inline: true, onSelect: function(dateText, inst) { var d = new Date(dateText); $('#providers_calendar').fullCalendar('gotoDate', d); var n = d.getFullYear(); n = n + "," + d.getMonth(); n = n + "," + d.getDate(); var view = $('#providers_calendar').fullCalendar('getView'); n = n + "," + view.name; $.cookie('nosh-schedule', n, { path: '/' }); } }); } function open_schedule_list(dateText, inst, load) { var starttime = Math.round(+new Date(dateText)/1000); var endtime = starttime+86400; var startday = moment(starttime*1000).format('YYYY-MM-DD'); var startday1 = 'Appointments for ' + moment(starttime*1000).format('MMMM Do YYYY') + ":"; $ul = $("#events"); $.mobile.loading("show"); $("#providers_date").html(startday1); var html = '<li><a href="#" id="patient_appt_button" class="nosh_schedule_event" data-nosh-start="' + startday + '">Add Appointment</a></li>'; html += '<li><a href="#" id="event_appt_button" class="nosh_schedule_event" data-nosh-start="' + startday + '">Add Event</a></li>'; $.ajax({ type: "POST", url: "ajaxschedule/provider-schedule", dataType: 'json', data: "start=" + starttime + "&end=" + endtime }) .then(function(response) { $.each(response, function ( i, val ) { var label = '<h3>' + val.title + '</h3>'; if (val.reason != val.title) { label += '<p>Reason: ' + val.reason + '</p>'; } if (val.visit_type != undefined) { label += '<p>Visit Type: ' + val.visit_type + '</p>'; } var date = $.datepicker.formatDate('M dd, yy, ', new Date(val.start)); var start_time = moment(new Date(val.start)).format('HH:mmA'); var end_time = moment(new Date(val.end)).format('HH:mmA'); var start_date = moment(new Date(val.start)).format('MM/DD/YYYY'); var color1 = 'clr-black'; if(val.className==" colorred"){ color1 = 'clr-red'; } if(val.className==" colororange"){ color1 = "clr-orange"; } if(val.className==" coloryellow"){ color1 = "clr-yellow"; } if(val.className==" colorgreen"){ color1 = "clr-green"; } if(val.className==" colorblue"){ color1 = "clr-blue"; } if(val.className==" colorpurple"){ color1 = "clr-purple"; } if(val.className==" colorbrown"){ color1 = "clr-brown" } label += '<span class="'+ color1 + '">' + date + start_time + '-' + end_time + '</span>'; html += '<li><a href="#" class="nosh_schedule_event" data-nosh-event-id="' + val.id + '" data-nosh-pid="' + val.pid + '" data-nosh-title="' + val.title + '" data-nosh-start-date="' + start_date + '" data-nosh-start-time="' + start_time + '" data-nosh-end-time="' + end_time + '" data-nosh-visit-type="' + val.visit_type + '" data-nosh-timestamp="' + val.timestamp + '" data-nosh-repeat="' + val.repeat + '" data-nosh-reason="' + val.reason + '" data-nosh-until="' + val.until + '" data-nosh-notes="' + val.notes + '" data-nosh-status="' + val.status + '" data-nosh-editable="' + val.editable + '">' + label + '</a></li>'; }); $ul.html(html); $ul.listview("refresh"); $ul.trigger("updatelayout"); $.mobile.loading("hide"); if (load !== undefined) { $('html, body').animate({ scrollTop: $("#patient_appt_button").offset().top }); } }); } function open_schedule(startdate) { $('#providers_datepicker').datepicker({ inline: true, onSelect: function (dateText, inst) { open_schedule_list(dateText, inst, true); } }); if (startdate == null) { $("#providers_datepicker").datepicker("setDate", new Date()); var date = moment().valueOf(); } else { var date = moment(startdate).valueOf(); $("#providers_datepicker").datepicker("setDate", new Date(date)); } open_schedule_list(date); $("#provider_list2").focus(); } function open_messaging(type) { $.mobile.loading("show"); $ul = $("#"+type); var command = type.replace('_', '-'); $.ajax({ type: "POST", url: "ajaxmessaging/" + command, data: "sidx=date&sord=desc&rows=1000000&page=1", dataType: 'json' }).then(function(response) { if (type == 'internal_inbox') { var col = ['message-id','message-to','read','date','message-from','message-from-label','subject','body','cc','pid','patient_name','bodytext','t-messages-id','documents-id']; } if (type == 'internal_draft') { var col = ['message-id','date','message-to','cc','subject','body','pid','patient_name']; } if (type == 'internal_outbox') { var col = ['message-id','date','message-to','cc','subject','pid','body']; } var html = ''; if (response.rows != '') { $.each(response.rows, function ( i, item ) { var obj = {}; $.each(item.cell, function ( j, val ) { obj[col[j]] = val; }); if (type == 'internal_inbox') { var label = '<h3>' + obj['message-from-label'] + '</h3><p>' + obj['subject'] + '</p>'; } else { var label = '<h3>' + obj['message-to'] + '</h3><p>' + obj['subject'] + '</p>'; } var datastring = ''; $.each(obj, function ( key, value ) { datastring += 'data-nosh-' + key + '="' + value + '" '; }); html += '<li><a href="#" class="nosh_messaging_item" ' + datastring + ' data-origin="' + type + '">' + label + '</a></li>'; }); } $ul.html(html); $ul.listview("refresh"); $ul.trigger("updatelayout"); $.mobile.loading("hide"); }); } function chart_notification() { if (noshdata.group_id == '2') { $.ajax({ type: "POST", url: "ajaxchart/notification", dataType: "json", success: function(data){ if (data.appt != noshdata.notification_appt && data.appt != '') { $.jGrowl(data.appt, {sticky:true, header:data.appt_header}); noshdata.notification_appt = data.appt; } if (data.alert != noshdata.notification_alert && data.alert != '') { $.jGrowl(data.alert, {sticky:true, header:data.alert_header}); noshdata.notification_alert = data.alert; } } }); } } function openencounter() { $("#encounter_body").html(''); $("#encounter_body").empty(); if ($(".ros_dialog").hasClass('ui-dialog-content')) { $(".ros_dialog").dialog('destroy'); } if ($(".pe_dialog").hasClass('ui-dialog-content')) { $(".pe_dialog").dialog('destroy'); } $("#encounter_body").load('ajaxencounter/loadtemplate'); $('#dialog_load').dialog('option', 'title', "Loading encounter...").dialog('open'); $("#encounter_link_span").html('<a href="#" id="encounter_panel">[Active Encounter #: ' + noshdata.eid + ']</a>'); $.ajax({ type: "POST", url: "ajaxsearch/get-tags/eid/" + noshdata.eid, dataType: "json", success: function(data){ $("#encounter_tags").tagit("fill",data); } }); } function closeencounter() { var $hpi = $('#hpi_form'); console.log($hpi.length); if($hpi.length) { hpi_autosave('hpi'); } var $situation = $('#situation_form'); if($situation.length) { hpi_autosave('situation'); } var $oh = $('#oh_form'); if($oh.length) { oh_autosave(); } var $vitals = $('#vitals_form'); if($vitals.length) { vitals_autosave(); } var $proc = $('#procedure_form'); if($proc.length) { proc_autosave(); } var $assessment = $('#assessment_form'); if($assessment.length) { assessment_autosave(); } var $orders = $('#orders_form'); if($orders.length) { orders_autosave(); } var $medications = $('#mtm_medications_form'); if($medications.length) { medications_autosave(); } $.ajax({ type: "POST", url: "ajaxchart/closeencounter", success: function(data){ noshdata.encounter_active = 'n'; $("#nosh_encounter_div").hide(); $("#nosh_chart_div").show(); $("#encounter_link_span").html(''); } }); } function signedlabel (cellvalue, options, rowObject){ if (cellvalue == 'No') { return 'Draft'; } if (cellvalue == 'Yes') { return 'Signed'; } } function loadbuttons() { $(".nosh_button").button(); $(".nosh_button_save").button({icons: {primary: "ui-icon-disk"}}); $(".nosh_button_cancel").button({icons: {primary: "ui-icon-close"}}); $(".nosh_button_delete").button({icons: {primary: "ui-icon-trash"}}); $(".nosh_button_calculator").button({icons: {primary: "ui-icon-calculator"}}); $(".nosh_button_check").button({icons: {primary: "ui-icon-check"}}); $(".nosh_button_preview").button({icons: {primary: "ui-icon-comment"}}); $(".nosh_button_edit").button({icons: {primary: "ui-icon-pencil"}}); $(".nosh_button_add").button({icons: {primary: "ui-icon-plus"}}); $(".nosh_button_print").button({icons: {primary: "ui-icon-print"}}); $(".nosh_button_alert").button({icons: {primary: "ui-icon-alert"}}); $(".nosh_button_copy").button({icons: {primary: "ui-icon-copy"}}); $(".nosh_button_extlink").button({icons: {primary: "ui-icon-extlink"}}); $(".nosh_button_reactivate").button({icons: {primary: "ui-icon-arrowreturnthick-1-w"}}); $(".nosh_button_reply").button({icons: {primary: "ui-icon-arrowreturn-1-w"}}); $(".nosh_button_forward").button({icons: {primary: "ui-icon-arrow-1-e"}}); $(".nosh_button_open").button({icons: {primary: "ui-icon-folder-open"}}); $(".nosh_button_calendar").button({icons: {primary: "ui-icon-calendar"}}); $(".nosh_button_cart").button({icons: {primary: "ui-icon-cart"}}); $(".nosh_button_image").button({icons: {primary: "ui-icon-image"}}); $(".nosh_button_star").button({icons: {primary: "ui-icon-star"}}); $(".nosh_button_script").button({icons: {primary: "ui-icon-script"}}); $(".nosh_button_next").button({text: false, icons: {primary: "ui-icon-seek-next"}}); $(".nosh_button_prev").button({text: false, icons: {primary: "ui-icon-seek-prev"}}); } function swipe(){ if(supportsTouch === true){ $('.textdump').swipe({ excludedElements:'button, input, select, a, .noSwipe', tap: function(){ $(this).swipe('disable'); $(this).focus(); $(this).on('focusout', function() { $(this).swipe('enable'); }); }, swipeRight: function(){ var elem = $(this); textdump(elem); } }); $('.textdump_text').text('Swipe right'); $('#swipe').show(); } else { $('.textdump_text').text('Click shift-right arrow key'); $('#swipe').hide(); } } function menu_update(type) { $.ajax({ type: "POST", url: "ajaxchart/" + type + "-list", success: function(data){ $("#menu_accordion_" + type + "-list_content").html(data); $("#menu_accordion_" + type + "-list_load").hide(); } }); } function remove_text(parent_id_entry, a, label_text, ret) { var old = $("#" + parent_id_entry).val(); var old_arr = old.split(' '); if (label_text != '') { var new_arr = search_array(old_arr, label_text); } else { var new_arr = []; } if (new_arr.length > 0) { var arr_index = old_arr.indexOf(new_arr[0]); a = a.replace(label_text, ''); old_arr[arr_index] = old_arr[arr_index].replace(label_text, ''); var old_arr1 = old_arr[arr_index].split('; ') var new_arr1 = search_array(old_arr1, a); if (new_arr1.length > 0) { var arr_index1 = old_arr1.indexOf(new_arr1[0]); old_arr1.splice(arr_index1,1); if (old_arr1.length > 0) { old_arr[arr_index] = label_text + old_arr1.join('; '); } else { old_arr.splice(arr_index,1); } } } else { var new_arr2 = search_array(old_arr, a); if (new_arr2.length > 0) { var arr_index2 = old_arr.indexOf(new_arr2[0]); old_arr.splice(arr_index2,1); } } var b = old_arr.join(" "); if (ret == true) { return b; } else { $("#" + parent_id_entry).val(b); } } function repeat_text(parent_id_entry, a, label_text) { var ret = false; var old = $("#" + parent_id_entry).val(); var old_arr = old.split(' '); if (label_text != '') { var new_arr = search_array(old_arr, label_text); } else { var new_arr = []; } if (new_arr.length > 0) { var arr_index = old_arr.indexOf(new_arr[0]); a = a.replace(label_text, ''); old_arr[arr_index] = old_arr[arr_index].replace(label_text, ''); var old_arr1 = old_arr[arr_index].split('; ') var new_arr1 = search_array(old_arr1, a); if (new_arr1.length > 0) { ret = true; } } else { var new_arr2 = search_array(old_arr, a); if (new_arr2.length > 0) { ret = true; } } return ret; } function refresh_documents() { $.ajax({ type: "POST", url: "ajaxsearch/documents-count", dataType: "json", success: function(data){ jQuery("#labs").jqGrid('setCaption', 'Labs: ' + data.labs_count); jQuery("#radiology").jqGrid('setCaption', 'Imaging: ' + data.radiology_count); jQuery("#cardiopulm").jqGrid('setCaption', 'Cardiopulmonary: ' + data.cardiopulm_count); jQuery("#endoscopy").jqGrid('setCaption', 'Endoscopy: ' + data.endoscopy_count); jQuery("#referrals").jqGrid('setCaption', 'Referrals: ' + data.referrals_count); jQuery("#past_records").jqGrid('setCaption', 'Past Records: ' + data.past_records_count); jQuery("#outside_forms").jqGrid('setCaption', 'Outside Forms: ' + data.outside_forms_count); jQuery("#letters").jqGrid('setCaption', 'Letters: ' + data.letters_count); } }); } function checkorders() { $.ajax({ type: "POST", url: "ajaxencounter/check-orders", dataType: "json", success: function(data){ $('#button_orders_labs_status').html(data.labs_status); $('#button_orders_rad_status').html(data.rad_status); $('#button_orders_cp_status').html(data.cp_status); $('#button_orders_ref_status').html(data.ref_status); $('#button_orders_rx_status').html(data.rx_status); $('#button_orders_imm_status').html(data.imm_status); $('#button_orders_sup_status').html(data.sup_status); } }); } function check_oh_status() { $.ajax({ type: "POST", url: "ajaxencounter/check-oh", dataType: "json", success: function(data){ $('#button_oh_sh_status').html(data.sh_status); $('#button_oh_etoh_status').html(data.etoh_status); $('#button_oh_tobacco_status').html(data.tobacco_status); $('#button_oh_drugs_status').html(data.drugs_status); $('#button_oh_employment_status').html(data.employment_status); $('#button_oh_meds_status').html(data.meds_status); $('#button_oh_supplements_status').html(data.supplements_status); $('#button_oh_allergies_status').html(data.allergies_status); $('#button_oh_psychosocial_status').html(data.psychosocial_status); $('#button_oh_developmental_status').html(data.developmental_status); $('#button_oh_medtrials_status').html(data.medtrials_status); } }); } function check_ros_status() { $.ajax({ type: "POST", url: "ajaxencounter/check-ros", dataType: "json", success: function(data){ $('#button_ros_gen_status').html(data.gen); $('#button_ros_eye_status').html(data.eye); $('#button_ros_ent_status').html(data.ent); $('#button_ros_resp_status').html(data.resp); $('#button_ros_cv_status').html(data.cv); $('#button_ros_gi_status').html(data.gi); $('#button_ros_gu_status').html(data.gu); $('#button_ros_mus_status').html(data.mus); $('#button_ros_neuro_status').html(data.neuro); $('#button_ros_psych_status').html(data.psych); $('#button_ros_heme_status').html(data.heme); $('#button_ros_endocrine_status').html(data.endocrine); $('#button_ros_skin_status').html(data.skin); $('#button_ros_wcc_status').html(data.wcc); $('#button_ros_psych1_status').html(data.psych1); $('#button_ros_psych2_status').html(data.psych2); $('#button_ros_psych3_status').html(data.psych3); $('#button_ros_psych4_status').html(data.psych4); $('#button_ros_psych5_status').html(data.psych5); $('#button_ros_psych6_status').html(data.psych6); $('#button_ros_psych7_status').html(data.psych7); $('#button_ros_psych8_status').html(data.psych8); $('#button_ros_psych9_status').html(data.psych9); $('#button_ros_psych10_status').html(data.psych10); $('#button_ros_psych11_status').html(data.psych11); } }); } function check_pe_status() { $.ajax({ type: "POST", url: "ajaxencounter/check-pe", dataType: "json", success: function(data){ $('#button_pe_gen_status').html(data.gen); $('#button_pe_eye_status').html(data.eye); $('#button_pe_ent_status').html(data.ent); $('#button_pe_neck_status').html(data.neck); $('#button_pe_resp_status').html(data.resp); $('#button_pe_cv_status').html(data.cv); $('#button_pe_ch_status').html(data.ch); $('#button_pe_gi_status').html(data.gi); $('#button_pe_gu_status').html(data.gu); $('#button_pe_lymph_status').html(data.lymph); $('#button_pe_ms_status').html(data.ms); $('#button_pe_neuro_status').html(data.neuro); $('#button_pe_psych_status').html(data.psych); $('#button_pe_skin_status').html(data.skin); $('#button_pe_constitutional_status').html(data.constitutional); $('#button_pe_mental_status').html(data.mental); } }); } function check_labs1() { $.ajax({ type: "POST", url: "ajaxencounter/check-labs", dataType: "json", success: function(data){ $('#button_labs_ua_status').html(data.ua); $('#button_labs_rapid_status').html(data.rapid); $('#button_labs_micro_status').html(data.micro); $('#button_labs_other_status').html(data.other); } }); } function total_balance() { if (noshdata.pid != '') { $.ajax({ type: "POST", url: "ajaxchart/total-balance", success: function(data){ $('#total_balance').html(data); } }); } } function hpi_autosave(type) { var old0 = $("#"+type+"_old").val(); var new0 = $("#"+type).val(); if (old0 != new0) { var str = encodeURIComponent(new0); $.ajax({ type: "POST", url: "ajaxencounter/hpi-save/" + type, data: type+'=' + str, success: function(data){ $.jGrowl(data); $("#"+type+"_old").val(new0); } }); } } function oh_autosave() { var bValid = false; $("#oh_form").find(".text").each(function() { if (bValid == false) { var input_id = $(this).attr('id'); var a = $("#" + input_id).val(); var b = $("#" + input_id + "_old").val(); if (a != b) { bValid = true; } } }); if (bValid) { var oh_str = $("#oh_form").serialize(); if(oh_str){ $.ajax({ type: "POST", url: "ajaxencounter/oh-save", data: oh_str, success: function(data){ $.jGrowl(data); $("#oh_form").find(".text").each(function() { var input_id = $(this).attr('id'); var a = $("#" + input_id).val(); $("#" + input_id + "_old").val(a); }); } }); } else { $.jGrowl("Please complete the form"); } } } function vitals_autosave() { var bValid = false; $("#vitals_form").find(".text").each(function() { if (bValid == false) { var input_id = $(this).attr('id'); var a = $("#" + input_id).val(); var b = $("#" + input_id + "_old").val(); if (a != b) { bValid = true; } } }); if (bValid) { var vitals_str = $("#vitals_form").serialize(); if(vitals_str){ $.ajax({ type: "POST", url: "ajaxencounter/vitals-save", data: vitals_str, success: function(data){ $.jGrowl(data); $("#vitals_form").find(".text").each(function() { var input_id = $(this).attr('id'); var a = $("#" + input_id).val(); $("#" + input_id + "_old").val(a); }); } }); } else { $.jGrowl("Please complete the form"); } } } function proc_autosave() { var bValid = false; $("#procedure_form").find(".text").each(function() { if (bValid == false) { var input_id = $(this).attr('id'); var a = $("#" + input_id).val(); var b = $("#" + input_id + "_old").val(); if (a != b) { bValid = true; } } }); if (bValid) { var proc_str = $("#procedure_form").serialize(); if(proc_str){ $.ajax({ type: "POST", url: "ajaxencounter/proc-save", data: proc_str, success: function(data){ $.jGrowl(data); $("#procedure_form").find(".text").each(function() { var input_id = $(this).attr('id'); var a = $("#" + input_id).val(); $("#" + input_id + "_old").val(a); }); } }); } else { $.jGrowl("Please complete the form"); } } } function assessment_autosave() { var bValid = false; $("#assessment_form").find(".text").each(function() { if (bValid == false) { var input_id = $(this).attr('id'); var a = $("#" + input_id).val(); var b = $("#" + input_id + "_old").val(); if (a != b) { bValid = true; } } }); if (bValid) { var assessment_str = $("#assessment_form").serialize(); if(assessment_str){ $.ajax({ type: "POST", url: "ajaxencounter/assessment-save", data: assessment_str, success: function(data){ $.jGrowl(data); $("#assessment_form").find(".text").each(function() { var input_id = $(this).attr('id'); var a = $("#" + input_id).val(); $("#" + input_id + "_old").val(a); }); $.ajax({ type: "POST", url: "ajaxencounter/get-billing", dataType: "json", success: function(data){ $("#billing_icd").removeOption(/./); $("#billing_icd").addOption(data, false); } }); } }); } else { $.jGrowl("Please complete the form"); } } } function orders_autosave() { var bValid = false; $("#orders_form").find(".text").each(function() { if (bValid == false) { var input_id = $(this).attr('id'); var a = $("#" + input_id).val(); var b = $("#" + input_id + "_old").val(); if (a != b) { bValid = true; } } }); if (bValid) { var orders_str = $("#orders_form").serialize(); if(orders_str){ $.ajax({ type: "POST", url: "ajaxencounter/orders-save", data: orders_str, success: function(data){ $.jGrowl(data); $("#orders_form").find(".text").each(function() { var input_id = $(this).attr('id'); var a = $("#" + input_id).val(); $("#" + input_id + "_old").val(a); }); } }); } else { $.jGrowl("Please complete the form"); } } } function medications_autosave() { $.ajax({ type: "POST", url: "ajaxencounter/oh-save1/meds", success: function(data){ $.jGrowl(data); } }); } function results_autosave() { var bValid = false; $("#oh_results_form").find(".text").each(function() { if (bValid == false) { var input_id = $(this).attr('id'); var a = $("#" + input_id).val(); var b = $("#" + input_id + "_old").val(); if (a != b) { bValid = true; } } }); if (bValid) { var oh_str = $("#oh_results_form").serialize(); if(oh_str){ $.ajax({ type: "POST", url: "ajaxencounter/oh-save1/results", data: oh_str, success: function(data){ $.jGrowl(data); $("#oh_results_form").find(".text").each(function() { var input_id = $(this).attr('id'); var a = $("#" + input_id).val(); $("#" + input_id + "_old").val(a); }); } }); } else { $.jGrowl("Please complete the form"); } } } function billing_autosave() { var bValid = false; $("#encounter_billing_form").find(".text").each(function() { if (bValid == false) { var input_id = $(this).attr('id'); var a = $("#" + input_id).val(); var b = $("#" + input_id + "_old").val(); if (a != b) { bValid = true; } } }); if (bValid) { var billing_str = $("#encounter_billing_form").serialize(); if(billing_str){ $.ajax({ type: "POST", url: "ajaxencounter/billing-save1", data: billing_str, success: function(data){ $.jGrowl(data); $("#encounter_billing_form").find(".text").each(function() { var input_id = $(this).attr('id'); var a = $("#" + input_id).val(); $("#" + input_id + "_old").val(a); }); } }); } else { $.jGrowl("Please complete the form"); } } } function pending_order_load(item) { $.ajax({ url: "ajaxchart/order-type/" + item, dataType: "json", type: "POST", success: function(data){ var label = data.label; var status = ""; var type = ""; if (label == 'messages_lab') { status = 'Details for Lab Order #' + item; type = 'lab'; } if (label == 'messages_rad') { status = 'Details for Radiology Order #' + item; type = 'rad'; } if (label == 'messages_cp') { status = 'Details for Cardiopulmonary Order #' + item; type = 'cp'; } load_outside_providers(type,'edit'); $.each(data, function(key, value){ if (key != 'label') { if (key == 'orders_pending_date') { var value = getCurrentDate(); } $("#edit_"+label+"_form :input[name='" + key + "']").val(value); } }); $("#"+label+"_status").html(status); if ($("#"+label+"_provider_list").val() == '' && noshdata.group_id == '2') { $("#"+label+"_provider_list").val(noshdata.user_id); } $("#"+label+"_edit_fields").dialog("option", "title", "Edit Lab Order"); $("#"+label+"_edit_fields").dialog('open'); } }); } function load_outside_providers(type,action) { $("#messages_"+type+"_location").removeOption(/./); var type1 = ''; var type2 = ''; if (type == 'lab') { type1 = 'Laboratory'; type2 = 'lab'; } if (type == 'rad') { type1 = 'Radiology'; type2 = 'imaging'; } if (type == 'cp') { type1 = 'Cardiopulmonary'; type2 = 'cardiopulmonary'; } $.ajax({ url: "ajaxsearch/orders-provider/" + type1, dataType: "json", type: "POST", async: false, success: function(data){ if(data.response == 'true'){ $("#messages_"+type+"_location").addOption({"":"Add "+type2+" provider."}, false); $("#messages_"+type+"_location").addOption(data.message, false); } else { $("#messages_"+type+"_location").addOption({"":"No "+type2+" provider. Click Add."}, false); } } }); $("#messages_"+type+"_provider_list").removeOption(/./); $.ajax({ url: "ajaxsearch/provider-select", dataType: "json", type: "POST", async: false, success: function(data){ $("#messages_"+type+"_provider_list").addOption({"":"Select a provider for the order."}, false); $("#messages_"+type+"_provider_list").addOption(data, false); if(action == 'add') { if (noshdata.group_id == '2') { $("#messages_"+type+"_provider_list").val(noshdata.user_id); } else { $("#messages_"+type+"_provider_list").val(''); } } } }); } function hpi_template_renew() { $("#hpi_template").removeOption(/./); $.ajax({ type: "POST", url: "ajaxencounter/hpi-template-select-list", dataType: "json", success: function(data){ $('#hpi_template').addOption({"":"*Select a template"}, false); $('#hpi_template').addOption(data.options, false); $('#hpi_template').sortOptions(); $('#hpi_template').val(""); } }); } function situation_template_renew() { $("#situation_template").removeOption(/./); $.ajax({ type: "POST", url: "ajaxencounter/situation-template-select-list", dataType: "json", success: function(data){ $('#situation_template').addOption({"":"*Select a template"}, false); $('#situation_template').addOption(data.options, false); $('#situation_template').sortOptions(); $('#situation_template').val(""); } }); } function referral_template_renew() { $("#messages_ref_template").removeOption(/./); $.ajax({ type: "POST", url: "ajaxchart/get-ref-templates-list", dataType: "json", success: function(data){ $('#messages_ref_template').addOption({"":"*Select a template"}, false); $('#messages_ref_template').addOption(data.options, false); $('#messages_ref_template').sortOptions(); } }); } function ros_form_load() { $('.ros_buttonset').buttonset(); $('.ros_detail_text').hide(); $("#ros_gu_menarche").datepicker(); $("#ros_gu_lmp").datepicker(); } function get_ros_templates(group, id, type) { $.ajax({ type: "POST", url: "ajaxencounter/get-ros-templates/" + group + "/" + id + "/" + type, dataType: "json", success: function(data){ $('#'+group+'_form').html(''); $('#'+group+'_form').dform(data); ros_form_load(); } }); } function ros_template_renew() { $.ajax({ type: "POST", url: "ajaxencounter/ros-template-select-list", dataType: "json", success: function(data){ $.each(data, function(key, value){ $('#'+key+'_template').removeOption(/./); $('#'+key+'_template').addOption({"":"*Select a template"}, false); $('#'+key+'_template').addOption(value, false); $('#'+key+'_template').sortOptions(); $('#'+key+'_template').val(""); }); } }); $.ajax({ type: "POST", url: "ajaxencounter/get-default-ros-templates", dataType: "json", success: function(data){ $.each(data, function(key, value){ $('#'+key+'_form').html(''); $('#'+key+'_form').dform(value); $("." + key + "_div").css("padding","5px"); $('.ros_template_div select').addOption({'':'Select option'},true); ros_form_load(); if (key == 'ros_wcc' && noshdata.agealldays <= 2191.44) { $.ajax({ type: "POST", url: "ajaxencounter/get-ros-wcc-template", dataType: "json", success: function(data){ $('#ros_wcc_age_form').html(''); $('#ros_wcc_age_form').dform(data); ros_form_load(); } }); } }); $('#dialog_load').dialog('close'); } }); } function ros_get_data() { $.ajax({ type: "POST", url: "ajaxencounter/get-ros", dataType: "json", success: function(data){ if (data && data != '') { $.each(data, function(key, value){ if (key != 'eid' || key != 'pid' || key != 'ros_date' || key != 'encounter_provider') { $('#'+key).val(value); $('#'+key+'_old').val(value); } }); } } }); } function ros_dialog_open() { if ($('#ros_skin_form').is(':empty')) { $('#dialog_load').dialog('option', 'title', "Loading templates...").dialog('open'); ros_template_renew(); } ros_get_data(); } function pe_form_load() { $('.pe_buttonset').buttonset(); $('.pe_detail_text').hide(); } function get_pe_templates(group, id, type) { $.ajax({ type: "POST", url: "ajaxencounter/get-pe-templates/" + group + "/" + id + "/" + type, dataType: "json", success: function(data){ $('#'+group+'_form').html(''); $('#'+group+'_form').dform(data); pe_form_load(); } }); } function pe_accordion_action(id, dialog_id) { $("#" + id + " .text").first().focus(); $("#"+dialog_id).find('.pe_entry').each(function(){ var parent_id1 = $(this).attr("id"); if (!!$(this).val()) { $('#' + parent_id1 + '_h').html(noshdata.item_present); } else { $('#' + parent_id1 + '_h').html(noshdata.item_empty); } }); } function pe_template_renew() { $.ajax({ type: "POST", url: "ajaxencounter/pe-template-select-list", dataType: "json", success: function(data){ $.each(data, function(key, value){ $('#'+key+'_template').removeOption(/./); $('#'+key+'_template').addOption({"":"*Select a template"}, false); $('#'+key+'_template').addOption(value, false); $('#'+key+'_template').sortOptions(); $('#'+key+'_template').val(""); }); } }); $.ajax({ type: "POST", url: "ajaxencounter/get-default-pe-templates", dataType: "json", success: function(data){ $.each(data, function(key, value){ $('#'+key+'_form').html(''); $('#'+key+'_form').dform(value); $("." + key + "_div").css("padding","5px"); $('.pe_template_div select').addOption({'':'Select option'},true); pe_form_load(); }); $('#dialog_load').dialog('close'); } }); } function pe_get_data() { $.ajax({ type: "POST", url: "ajaxencounter/get-pe", dataType: "json", success: function(data){ if (data && data != '') { $.each(data, function(key, value){ if (key != 'eid' || key != 'pid' || key != 'pe_date' || key != 'encounter_provider') { $('#'+key).val(value); $('#'+key+'_old').val(value); if (!!value) { $('#' + key + '_h').html(noshdata.item_present); } else { $('#' + key + '_h').html(noshdata.item_empty); } } }); } } }); } function pe_dialog_open() { var bValid = false; $('.pe_dialog').each(function() { var dialog_id = $(this).attr('id'); var accordion_id = dialog_id.replace('_dialog', '_accordion'); if (!$("#"+accordion_id).hasClass('ui-accordion')) { $("#"+accordion_id).accordion({ create: function(event, ui) { var id = ui.panel[0].id; pe_accordion_action(id, dialog_id); }, activate: function(event, ui) { var id = ui.newPanel[0].id; pe_accordion_action(id, dialog_id); }, heightStyle: "content" }); bValid = true; } }); if (bValid == true) { $('#dialog_load').dialog('option', 'title', "Loading templates...").dialog('open'); pe_template_renew(); } pe_get_data(); } function pe_dialog_open1() { $('.pe_dialog').each(function() { var dialog_id = $(this).attr('id'); var accordion_id = dialog_id.replace('_dialog', '_accordion'); if (!$("#"+accordion_id).hasClass('ui-accordion')) { $("#"+accordion_id).accordion({ create: function(event, ui) { var id = ui.panel[0].id; pe_accordion_action(id, dialog_id); }, activate: function(event, ui) { var id = ui.newPanel[0].id; pe_accordion_action(id, dialog_id); }, heightStyle: "content" }); } }); pe_get_data(); } function parse_date(string) { var date = new Date(); var parts = String(string).split(/[- :]/); date.setFullYear(parts[0]); date.setMonth(parts[1] - 1); date.setDate(parts[2]); date.setHours(parts[3]); date.setMinutes(parts[4]); date.setSeconds(parts[5]); date.setMilliseconds(0); return date; } function parse_date1(string) { var date = new Date(); var parts = String(string).split("/"); date.setFullYear(parts[2]); date.setMonth(parts[0] - 1); date.setDate(parts[1]); date.setHours(0); date.setMinutes(0); date.setSeconds(0); date.setMilliseconds(0); return date; } function editDate(string) { var result = string.split("-"); var edit_date = result[1] + '/' + result[2] + '/' + result[0]; return edit_date; } function editDate1(string) { var result1 = string.split(" "); var result = result1[0].split("-"); var edit_date = result[1] + '/' + result[2] + '/' + result[0]; if (edit_date == '00/00/0000') { var edit_date1 = ''; } else { var edit_date1 = edit_date; } return edit_date1; } function editDate2(string) { var result1 = string.split(" "); var result = result1[1].split(":"); var hour1 = result[0]; var hour2 = parseInt(hour1); if (hour2 > 12) { var hour3 = hour2 - 12; var hour4 = hour3 + ''; var pm = 'PM'; if (hour4.length == 1) { var hour = "0" + hour4; } else { var hour = hour4; } } else { if (hour2 == 0) { var hour = '12'; var pm = 'AM'; } if (hour2 == 12) { var hour = hour2; var pm = 'PM'; } if (hour2 < 12) { var pm = 'AM'; if (hour2.length == 1) { var hour = "0" + hour2; } else { var hour = hour2; } } } var minute1 = result[1]; var minute2 = minute1 + ''; if (minute2.length == 1) { var minute = "0" + minute2; } else { var minute = minute2; } var time = hour + ":" + minute + ' ' + pm; return time; } function getCurrentDate() { var d = new Date(); var day1 = d.getDate(); var day2 = day1 + ''; if (day2.length == 1) { var day = "0" + day2; } else { var day = day2; } var month1 = d.getMonth(); var month2 = parseInt(month1); var month3 = month2 + 1; var month4 = month3 + ''; if (month4.length == 1) { var month = "0" + month4; } else { var month = month4; } var date = month + "/" + day + "/" + d.getFullYear(); return date; } function getCurrentTime() { var d = new Date(); var hour1 = d.getHours(); var hour2 = parseInt(hour1); if (hour2 > 12) { var hour3 = hour2 - 12; var hour4 = hour3 + ''; var pm = 'PM'; if (hour4.length == 1) { var hour = "0" + hour4; } else { var hour = hour4; } } else { if (hour2 == 0) { var hour = '12'; var pm = 'AM'; } if (hour2 == 12) { var hour = hour2; var pm = 'PM'; } if (hour2 < 12) { var pm = 'AM'; if (hour2.length == 1) { var hour = "0" + hour2; } else { var hour = hour2; } } } var minute1 = d.getMinutes(); var minute2 = minute1 + ''; if (minute2.length == 1) { var minute = "0" + minute2; } else { var minute = minute2; } var time = hour + ":" + minute + ' ' + pm; return time; } function typelabel (cellvalue, options, rowObject){ if (cellvalue == 'standardmedical') { return 'Standard Medical Visit V1'; } if (cellvalue == 'standardmedical1') { return 'Standard Medical Visit V2'; } if (cellvalue == 'clinicalsupport') { return 'Clinical Support Visit'; } if (cellvalue == 'standardpsych') { return 'Annual Psychiatric Evaluation'; } if (cellvalue == 'standardpsych1') { return 'Psychiatric Encounter'; } if (cellvalue == 'standardmtm') { return 'MTM Encounter'; } } function t_messages_tags() { var id = $("#t_messages_id").val(); $.ajax({ type: "POST", url: "ajaxsearch/get-tags/t_messages_id/" + id, dataType: "json", success: function(data){ $(".t_messages_tags").tagit("fill",data); } }); } function refresh_timeline() { var $timeline_block = $('.cd-timeline-block'); //hide timeline blocks which are outside the viewport $timeline_block.each(function(){ if($(this).offset().top > $(window).scrollTop()+$(window).height()*0.75) { $(this).find('.cd-timeline-img, .cd-timeline-content').hide(); } }); //on scolling, show/animate timeline blocks when enter the viewport $(window).on('scroll', function(){ $timeline_block.each(function(){ if( $(this).offset().top <= $(window).scrollTop()+$(window).height()*0.75 && $(this).find('.cd-timeline-img').is(":hidden")) { $(this).find('.cd-timeline-img, .cd-timeline-content').show("slide"); } }); }); } $.fn.clearForm = function() { return this.each(function() { var type = this.type, tag = this.tagName.toLowerCase(); if (tag == 'form') { return $(':input',this).clearForm(); } if (type == 'text' || type == 'password' || type == 'hidden' || tag == 'textarea') { this.value = ''; $(this).removeClass("ui-state-error"); } else if (type == 'checkbox' || type == 'radio') { this.checked = false; $(this).removeClass("ui-state-error"); $(this).checkboxradio('refresh'); } else if (tag == 'select') { this.selectedIndex = 0; $(this).removeClass("ui-state-error"); $(this).selectmenu('refresh'); } }); }; $.fn.clearDiv = function() { return this.each(function() { var type = this.type, tag = this.tagName.toLowerCase(); if (tag == 'div') { return $(':input',this).clearForm(); } if (type == 'text' || type == 'password' || type == 'hidden' || tag == 'textarea') { this.value = ''; $(this).removeClass("ui-state-error"); } else if (type == 'checkbox' || type == 'radio') { this.checked = false; $(this).removeClass("ui-state-error"); $(this).checkboxradio('refresh'); } else if (tag == 'select') { this.selectedIndex = 0; $(this).removeClass("ui-state-error"); $(this).selectmenu('refresh'); } }); }; $.fn.serializeJSON = 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; }; $.widget( "custom.catcomplete", $.ui.autocomplete, { _renderMenu: function( ul, items ) { var that = this, currentCategory = ""; $.each( items, function( index, item ) { if ( item.category != currentCategory ) { ul.append( "<li class='ui-autocomplete-category'>" + item.category + "</li>" ); currentCategory = item.category; } that._renderItemData( ul, item ); }); } }); $.ajaxSetup({ headers: {"cache-control":"no-cache"}, beforeSend: function(request) { return request.setRequestHeader("X-CSRF-Token", $("meta[name='token']").attr('content')); } }); $(document).ajaxError(function(event,xhr,options,exc) { if (xhr.status == "404" ) { alert("Route not found!"); //window.location.replace(noshdata.error); } else { if(xhr.responseText){ var response1 = $.parseJSON(xhr.responseText); var error = "Error:\nType: " + response1.error.type + "\nMessage: " + response1.error.message + "\nFile: " + response1.error.file; alert(error); } } }); $(document).idleTimeout({ inactivity: 3600000, noconfirm: 10000, alive_url: noshdata.error, redirect_url: noshdata.logout_url, logout_url: noshdata.logout_url, sessionAlive: false }); $(document).ready(function() { if ($("#provider_schedule1").length) { open_schedule(); } $('.cd-read-more').css('color', '#000000'); if ($('#internal_inbox').length) { open_messaging('internal_inbox'); } $(".headericon").offset({top: 23}); $(".headericon1").offset({top: 7}); if ($('.template_class').length) { var width = $('.template_class').width(); $('.template_class').wrap('<div class="template_class_wrap" style="position:relative;width:100%"></div>'); $('.template_class_wrap').append('<i class="template_click zmdi zmdi-favorite zmdi-hc-lg" style="position:absolute;right:5px;top:5px;width:30px;color:red;"></i>'); } //refresh_timeline(); //$('.js').show(); //loadbuttons(); //$(".nosh_tooltip").tooltip(); //$(".phonemask").mask("(999) 999-9999"); //$("#dialog_load").dialog({ //height: 100, //autoOpen: false, //closeOnEscape: false, //dialogClass: "noclose", //modal: true //}); //var tz = jstz.determine(); //$.cookie('nosh_tz', tz.name(), { path: '/' }); //$('.textdump').swipe({ //swipeRight: function(){ //var elem = $(this); //textdump(elem); //} //}); //$("#textdump_group").dialog({ //bgiframe: true, //autoOpen: false, //height: 300, //width: 400, //draggable: false, //resizable: false, //focus: function (event, ui) { //var id = $("#textdump_group_id").val(); //if (id != '') { //$("#"+id).focus(); //} //}, //close: function (event, ui) { //$("#textdump_group_target").val(''); //$("#textdump_group_add").val(''); //$("#textdump_group_html").html(''); //} //}); //$("#restricttextgroup_dialog").dialog({ //bgiframe: true, //autoOpen: false, //height: 200, //width: 400, //draggable: false, //resizable: false, //closeOnEscape: false, //dialogClass: "noclose", //close: function (event, ui) { //$("#restricttextgroup_form").clearForm(); //}, //buttons: { //'Save': function() { //var str = $("#restricttextgroup_form").serialize(); //$.ajax({ //type: "POST", //url: "ajaxsearch/restricttextgroup-save", //data: str, //success: function(data){ //$.jGrowl(data); //$("#restricttextgroup_dialog").dialog('close'); //} //}); //}, //Cancel: function() { //$("#restricttextgroup_dialog").dialog('close'); //} //} //}); //$("#textdump").dialog({ //bgiframe: true, //autoOpen: false, //height: 300, //width: 400, //draggable: false, //resizable: false, //closeOnEscape: false, //dialogClass: "noclose", //close: function (event, ui) { //$("#textdump_target").val(''); //$("#textdump_input").val(''); //$("#textdump_add").val(''); //$("#textdump_group_item").val(''); //$("#textdump_html").html(''); //}, //buttons: [{ //text: 'Save', //id: 'textdump_dialog_save', //class: 'nosh_button_save', //click: function() { //var id = $("#textdump_target").val(); //var old = $("#"+id).val(); //var delimiter = $("#textdump_delimiter1").val(); //var input = ''; //var text = []; //$("#textdump_html").find('.textdump_item').each(function() { //if ($(this).find(':first-child').hasClass("ui-state-error") == true) { //var a = $(this).text(); //text.push(a); //} //}); //if (old != '') { //input += old + '\n' + $("#textdump_group_item").val() + ": "; //} else { //input += $("#textdump_group_item").val() + ": "; //} //input += text.join(delimiter); //$("#"+id).val(input); //$("#textdump").dialog('close'); //} //},{ //text: 'Cancel', //id: 'textdump_dialog_cancel', //class: 'nosh_button_cancel', //click: function() { //$("#textdump").dialog('close'); //} //}] //}); //$("#textdump_specific").dialog({ //bgiframe: true, //autoOpen: false, //height: 300, //width: 400, //draggable: false, //resizable: false, //closeOnEscape: false, //dialogClass: "noclose", //close: function (event, ui) { //$("#textdump_specific_target").val(''); //$("#textdump_specific_start").val(''); //$("#textdump_specific_length").val(''); //$("#textdump_specific_origin").val(''); //$("#textdump_specific_add").val(''); //$("#textdump_specific_html").html(''); //$("#textdump_specific_save").show(); //$("#textdump_specific_cancel").show(); //$("#textdump_specific_done").show(); //$("#textdump_delimiter_div").show(); //}, //buttons: [{ //text: 'Save', //id: 'textdump_specific_save', //class: 'nosh_button_save', //click: function() { //var origin = $("#textdump_specific_origin").val(); //if (origin != 'configure') { //var id = $("#textdump_specific_target").val(); //var start = $("#textdump_specific_start").val(); //var length = $("#textdump_specific_length").val(); //var delimiter = $("#textdump_delimiter").val(); //var text = []; //$("#textdump_specific_html").find('.textdump_item_specific').each(function() { //if ($(this).find(':first-child').hasClass("ui-state-error") == true) { //var a = $(this).text(); //text.push(a); //} //}); //var input = text.join(delimiter); //$("#"+id).textrange('set', start, length); //$("#"+id).textrange('replace', input); //} //$("#textdump_specific").dialog('close'); //} //},{ //text: 'Cancel', //id: 'textdump_specific_cancel', //class: 'nosh_button_cancel', //click: function() { //$("#textdump_specific").dialog('close'); //} //},{ //text: 'Done', //id: 'textdump_specific_done', //class: 'nosh_button_check', //click: function() { //$("#textdump_specific").dialog('close'); //} //}] //}); //$("#textdump_group_html").tooltip(); //$("#textdump_html").tooltip(); //$("#textdump_hint").tooltip({ //content: function(callback) { //var ret = ''; //$.ajax({ //type: "POST", //url: "ajaxdashboard/listmacros", //success: function(data){ //callback(data); //} //}); //}, //position: { my: "left bottom+15", at: "left top", collision: "flipfit" }, //open: function (event, ui) { //setTimeout(function() { //$(ui.tooltip).hide('explode'); //}, 6000); //}, //track: true //}); //$("#template_encounter_edit_dialog").dialog({ //bgiframe: true, //autoOpen: false, //height: 400, //width: 600, //closeOnEscape: false, //dialogClass: "noclose", //close: function(event, ui) { //$('#template_encounter_edit_form').clearForm(); //$('#template_encounter_edit_div').empty(); //reload_grid("encounter_templates_list"); //if ($("#template_encounter_dialog").dialog("isOpen")) { //$.ajax({ //type: "POST", //url: "ajaxencounter/get-encounter-templates", //dataType: "json", //success: function(data){ //$("#template_encounter_choose").removeOption(/./); //if(data.response == true){ //$("#template_encounter_choose").addOption(data.message, false); //} else { //$("#template_encounter_choose").addOption({"":"No encounter templates"}, false); //} //} //}); //} //}, //buttons: { //'Add Field': function() { //var a = $("#template_encounter_edit_div > :last-child").attr("id"); //if (a == 'encounter_template_grid_label') { //var count = 0; //} else { //var a1 = a.split("_"); //var count = parseInt(a1[4]) + 1; //} //$("#template_encounter_edit_div").append('<div id="group_encounter_template_div_'+count+'" class="pure-u-1-3"><select name="group[]" id="encounter_template_group_id_'+count+'" class="text encounter_template_group_group" style="width:95%"></select></div><div id="array_encounter_template_div_'+count+'" class="pure-u-1-3"><select name="array[]" id="encounter_template_array_id_'+count+'" class="text" style="width:95%"></select></div><div id="remove_encounter_template_div_'+count+'" class="pure-u-1-3"><button type="button" id="remove_encounter_template_field_'+count+'" class="remove_encounter_template_field nosh_button_cancel">Remove Field</button></div>'); //if (a == 'encounter_template_grid_label') { //var b = $("#template_encounter_edit_dialog_encounter_template").val(); //$.ajax({ //type: "POST", //url: "ajaxsearch/get-template-fields/" + b, //dataType: "json", //success: function(data){ //$("#encounter_template_group_id_"+count).addOption({'':'Choose Field'}, false); //$("#encounter_template_group_id_"+count).addOption(data, false); //$("#encounter_template_group_id_"+count).focus(); //loadbuttons(); //} //}); //} else { //$("#encounter_template_group_id_0").copyOptions("#encounter_template_group_id_"+count, "all"); //$("#encounter_template_group_id_"+count).val($("#encounter_template_group_id_"+count+" option:first").val()) //$("#encounter_template_group_id_"+count).focus(); //loadbuttons(); //} //}, //'Save': function() { //var bValid = true; //$("#template_encounter_edit_form").find("[required]").each(function() { //var input_id = $(this).attr('id'); //var id1 = $("#" + input_id); //var text = $("label[for='" + input_id + "']").html(); //bValid = bValid && checkEmpty(id1, text); //}); //if (bValid) { //var str = $("#template_encounter_edit_form").serialize(); //if(str){ //$('#dialog_load').dialog('option', 'title', "Saving template...").dialog('open'); //$.ajax({ //type: "POST", //url: "ajaxsearch/save-encounter-templates", //data: str, //success: function(data){ //$('#dialog_load').dialog('close'); //if (data == 'There is already a template with the same name!') { //$.jGrowl(data); //$("#encounter_template_name_text").addClass("ui-state-error"); //} else { //$.jGrowl(data); //$('#template_encounter_edit_dialog').dialog('close'); //} //} //}); //} else { //$.jGrowl("Please complete the form"); //} //} //}, //Cancel: function() { //$('#template_encounter_edit_dialog').dialog('close'); //} //} //}); //$("#timeline_dialog").dialog({ //bgiframe: true, //autoOpen: false, //height: 500, //width: 650, //draggable: false, //resizable: false, //open: function(event, ui) { //}, //close: function(event, ui) { //$("#timeline").html(''); //}, //position: { my: 'center', at: 'center', of: '#maincontent' } //}); }); $(document).on("click", "#encounter_panel", function() { noshdata.encounter_active = 'y'; openencounter(); $("#nosh_chart_div").hide(); $("#nosh_encounter_div").show(); }); $(document).on("click", ".ui-jqgrid-titlebar", function() { $(".ui-jqgrid-titlebar-close", this).click(); }); $(document).on('click', '#save_oh_sh_form', function(){ var old = $("#oh_sh").val(); var old1 = old.trim(); var a = $("#sh1").val(); var b = $("#sh2").val(); var c = $("#sh3").val(); var d = $("#oh_sh_marital_status").val(); var d0 = $("#oh_sh_marital_status_old").val(); var e = $("#oh_sh_partner_name").val(); var e0 = $("#oh_sh_partner_name").val(); var f = $("#sh4").val(); var g = $("#sh5").val(); var h = $("#sh6").val(); var i = $("#sh7").val(); var j = $("#sh8").val(); var k = $("input[name='sh9']:checked").val(); var l = $("input[name='sh10']:checked").val(); var m = $("input[name='sh11']:checked").val(); if(a){ var a1 = 'Family members in the household: ' + a + '\n'; } else { var a1 = ''; } if(b){ var b1 = 'Children: ' + b + '\n'; } else { var b1 = ''; } if(c){ var c1 = 'Pets: ' + c + '\n'; } else { var c1 = ''; } if(d){ var d1 = 'Marital status: ' + d + '\n'; } else { var d1 = ''; } if(e){ var e1 = 'Partner name: ' + e + '\n'; } else { var e1 = ''; } if(f){ var f1 = 'Diet: ' + f + '\n'; } else { var f1 = ''; } if(g){ var g1 = 'Exercise: ' + g + '\n'; } else { var g1 = ''; } if(h){ var h1 = 'Sleep: ' + h + '\n'; } else { var h1 = ''; } if(i){ var i1 = 'Hobbies: ' + i + '\n'; } else { var i1 = ''; } if(j){ var j1 = 'Child care arrangements: ' + j + '\n'; } else { var j1 = ''; } if(k){ var k1 = k + '\n'; } else { var k1 = ''; } if(l){ var l1 = l + '\n'; } else { var l1 = ''; } if(m){ var m1 = m + '\n'; } else { var m1 = ''; } var full = d1+e1+a1+b1+c1+f1+g1+h1+i1+j1+k1+l1+m1; var full1 = full.trim(); if (old1 != '') { var n = old1+'\n'+full1+'\n'; } else { var n = full1+'\n'; } var o = n.length; $("#oh_sh").val(n).caret(o); if(d != d0 || e != e0) { $.ajax({ type: "POST", url: "ajaxencounter/edit-demographics/sh", data: "marital_status=" + d + "&partner_name=" + e, success: function(data){ $.jGrowl(data); } }); } var sh9_y = $('#sh9_y').attr('checked'); var sh9_n = $('#sh9_n').attr('checked'); if(sh9_y){ $.ajax({ type: "POST", url: "ajaxencounter/edit-demographics/sex", data: "status=yes", success: function(data){ $.jGrowl(data); } }); } if(sh9_n){ $.ajax({ type: "POST", url: "ajaxencounter/edit-demographics/sex", data: "status=no", success: function(data){ $.jGrowl(data); } }); } }); $(document).on("click", '#save_oh_etoh_form', function(){ var old = $("#oh_etoh").val(); var old1 = old.trim(); var a = $("input[name='oh_etoh_select']:checked").val(); var a0 = $("#oh_etoh_text").val(); if(a){ var a1 = a + a0; } else { var a1 = ''; } if (old1 != '') { var b = old1+'\n'+a1+'\n'; } else { var b = a1+'\n'; } var c = b.length; $("#oh_etoh").val(b).caret(c); }); $(document).on('click', '#save_oh_tobacco_form', function(){ var old = $("#oh_tobacco").val(); var old1 = old.trim(); var a = $("input[name='oh_tobacco_select']:checked").val(); var a0 = $("#oh_tobacco_text").val(); if(a){ var a1 = a + a0; } else { var a1 = ''; } if (old1 != '') { var b = old1+'\n'+a1+'\n'; } else { var b = a1+'\n'; } var c = b.length; $("#oh_tobacco").val(b).caret(c); var tobacco_y = $('#oh_tobacco_y').prop('checked'); var tobacco_n = $('#oh_tobacco_n').prop('checked'); if(tobacco_y){ $.ajax({ type: "POST", url: "ajaxencounter/edit-demographics/tobacco", data: "status=yes", success: function(data){ $.jGrowl(data); } }); } if(tobacco_n){ $.ajax({ type: "POST", url: "ajaxencounter/edit-demographics/tobacco", data: "status=no", success: function(data){ $.jGrowl(data); } }); } }); $(document).on('click', '#save_oh_drugs_form', function(){ var old = $("#oh_drugs").val(); var old1 = old.trim(); var a = $("input[name='oh_drugs_select']:checked").val(); if(a){ if (a == 'No illicit drug use.') { var a1 = a; } else { var a0 = $("#oh_drugs_text").val(); var a2 = $("#oh_drugs_text1").val(); var a1 = a + a0 + '\nFrequency of drug use: ' + a2; $('#oh_drugs_input').hide(); $('#oh_drugs_text').val(''); $("#oh_drugs_text1").val(''); $("input[name='oh_drugs_select']").each(function(){ $(this).prop('checked', false); }); $('#oh_drugs_form input[type="radio"]').button('refresh'); } } else { var a1 = ''; $('#oh_drugs_input').hide(); } if (old1 != '') { var b = old1+'\n'+a1+'\n'; } else { var b = a1+'\n'; } var c = b.length; $("#oh_drugs").val(b).caret(c); }); $(document).on('click', '#save_oh_employment_form', function(){ var old = $("#oh_employment").val(); var old1 = old.trim(); var a = $("input[name='oh_employment_select']:checked").val(); var b = $("#oh_employment_text").val(); var c = $("#oh_employment_employer").val(); var c0 = $("#oh_employment_employer_old").val(); if(a){ var a1 = a + '\n'; } else { var a1 = ''; } if(b){ var b1 = 'Employment field: ' + b + '\n'; } else { var b1 = ''; } if(c){ var c1 = 'Employer: ' + c + '\n'; } else { var c1 = ''; } var full = a1+b1+c1; var full1 = full.trim(); if (old1 != '') { var d = old1+'\n'+full1+'\n'; } else { var d = full1+'\n'; } var e = d.length; $("#oh_employment").val(d).caret(e); if(c != c0){ $.ajax({ type: "POST", url: "ajaxencounter/edit-demographics/employer", data: "employer=" + c, success: function(data){ $.jGrowl(data); } }); } }); function updateTextArea(parent_id_entry) { var newtext = ''; $('#' + parent_id_entry + '_form :checked').each(function() { newtext += $(this).val() + ' '; }); $('#' + parent_id_entry).val(newtext); } function ros_normal(parent_id) { var id = parent_id; var x = parent_id.length - 1; parent_id = parent_id.slice(0,x); $("#" + id).siblings('input:checkbox').each(function(){ var parent_id = $(this).attr("id"); $(this).prop('checked',false); var parts = parent_id.split('_'); if (parts[1] == 'wccage') { var parent_id_entry = 'ros_wcc'; } else { var parent_id_entry = parts[0] + '_' + parts[1]; } var a = $(this).val(); remove_text(parent_id_entry,a,'',false); if (parts[1] == 'wccage') { $("#ros_wcc_age_form input:checkbox").button('refresh'); } else { $("#" + parent_id_entry + "_form input:checkbox").button('refresh'); } }); $("#" + parent_id + "_div").find('.ros_detail_text').each(function(){ var parent_id = $(this).attr("id"); var parts = parent_id.split('_'); if (parts[1] == 'wccage') { var parent_id_entry = 'ros_wcc'; } else { var parent_id_entry = parts[0] + '_' + parts[1]; } var old = $("#" + parent_id_entry).val(); var a = ' ' + $(this).val(); remove_text(parent_id_entry,a,'',false); $(this).hide(); }); } function ros_other(parent_id) { var x = parent_id.length - 1; parent_id = parent_id.slice(0,x); $("#" + parent_id + "_div").find('.ros_normal:checkbox').each(function(){ var parent_id = $(this).attr("id"); $(this).prop('checked',false); var parts = parent_id.split('_'); if (parts[1] == 'wccage') { var parent_id_entry = 'ros_wcc'; } else { var parent_id_entry = parts[0] + '_' + parts[1]; } var old = $("#" + parent_id_entry).val(); var a = $(this).val(); remove_text(parent_id_entry,a,'',false); if (parts[1] == 'wccage') { $("#ros_wcc_age_form input:checkbox").button('refresh'); } else { $("#" + parent_id_entry + "_form input:checkbox").button('refresh'); } }); } $(document).on("click", '.ros_template_div input[type="checkbox"]', function() { var parent_id = $(this).attr("id"); var parts = parent_id.split('_'); if (parts[1] == 'wccage') { var parent_id_entry = 'ros_wcc'; } else { var parent_id_entry = parts[0] + '_' + parts[1]; } var label = parts[0] + '_' + parts[1] + '_' + parts[2] + '_label'; var label_text = $("#" + label).text() + ': '; var old = $("#" + parent_id_entry).val(); var a = $(this).val(); var repeat = repeat_text(parent_id_entry,a,label_text); if ($(this).prop('checked') && repeat !== true) { if (old != '') { var comma = a.charAt(0); var old_arr = old.split(' '); var new_arr = search_array(old_arr, label_text); if (new_arr.length > 0 && label_text != ': ') { var arr_index = old_arr.indexOf(new_arr[0]); a = a.replace(label_text, '; '); old_arr[arr_index] += a; } else { old_arr.push(a); } var b = old_arr.join(" "); } else { var b = a; } $("#" + parent_id_entry).val(b); if ($(this).is('.ros_normal')) { ros_normal(parent_id); } else { ros_other(parent_id); } } else { if (label_text == ': ') { label_text = ''; } remove_text(parent_id_entry,a,label_text,false); } }); $(document).on("click", '.ros_template_div input[type="radio"]', function() { var parent_id = $(this).attr("id"); var parts = parent_id.split('_'); if (parts[1] == 'wccage') { var parent_id_entry = 'ros_wcc'; } else { var parent_id_entry = parts[0] + '_' + parts[1]; } var old = $("#" + parent_id_entry).val(); var a = $(this).val(); var repeat = repeat_text(parent_id_entry,a,''); console.log(repeat); if ($(this).prop('checked') && repeat !== true) { if (old != '') { $(this).siblings('input:radio').each(function() { var d = $(this).val(); var d1 = ' ' + d; old = old.replace(d1,''); old = old.replace(d, ''); }); if (old != '') { var b = old + ' ' + a; } else { var b = a; } } else { var b = a; } $("#" + parent_id_entry).val(b); } else { remove_text(parent_id_entry,a,'',false); } }); $(document).on("change", '.ros_template_div select', function() { var parent_id = $(this).attr("id"); var parts = parent_id.split('_'); if (parts[1] == 'wccage') { var parent_id_entry = 'ros_wcc'; } else { var parent_id_entry = parts[0] + '_' + parts[1]; } var old = $("#" + parent_id_entry).val(); var a = $(this).val(); if (old != '') { $(this).siblings('option').each(function() { var d = $(this).val(); var d1 = ' ' + d; old = old.replace(d1,''); old = old.replace(d, ''); }); var b = old + ' ' + a; } else { var b = a; } $("#" + parent_id_entry).val(b); }); $(document).on('focus', '.ros_template_div input[type="text"]', function() { noshdata.old_text = $(this).val(); }); $(document).on('focusout', '.ros_template_div input[type="text"]', function() { var a = $(this).val(); if (a != noshdata.old_text) { if (a != '') { var parent_id = $(this).attr("id"); var parts = parent_id.split('_'); if (parts[1] == 'wccage') { var parent_id_entry = 'ros_wcc'; } else { var parent_id_entry = parts[0] + '_' + parts[1]; } var x = parent_id.length - 1; var parent_div = parent_id.slice(0,x); var start1 = $("#" + parent_div + "_div").find('span:first').text(); if (start1 == '') { start1 = $("#" + parts[0] + '_' + parts[1] + '_' + parts[2] + '_label').text(); } var start1_n = start1.lastIndexOf(' ('); if (start1_n != -1) { var start1_n1 = start1.substring(0,start1_n); var start1_n2 = start1_n1.toLowerCase(); } else { var start1_n1 = start1; var start1_n2 = start1; } var start2 = $("label[for='" + parent_id + "']").text(); var start3_n = start1.lastIndexOf('degrees'); if (start3_n != -1) { var end_text = ' degrees.'; } else { var end_text = ''; } var start4 = $(this).closest('div.ui-accordion').find('h3.ui-state-active').text(); if (start4 != '') { var start4_n = start4.lastIndexOf('-'); if (start4_n != -1) { var parts2 = start4.split(' - '); var mid_text = ', ' + parts2[1].toLowerCase(); } else { var mid_text = ', ' + start4.toLowerCase(); } } else { var mid_text = ''; } if (!!start2) { var start_text = start2 + ' ' + start1_n2; } else { var start_text = start1_n1; } var old = $("#" + parent_id_entry).val(); var a_pointer = a.length - 1; var a_pointer2 = a.lastIndexOf('.'); if (!!old) { if (!!start_text) { var c = start_text + mid_text + ': ' + a + end_text; if (noshdata.old_text != '') { var c_old = start_text + mid_text + ': ' + noshdata.old_text + end_text; } } else { if (a_pointer != a_pointer2) { var c = a + '.'; } else { var c = a; } } if (noshdata.old_text != '') { var old_text_pointer = noshdata.old_text.length - 1; var old_text_pointer2 = noshdata.old_text.lastIndexOf('.'); if (old_text_pointer != old_text_pointer2) { var old_text1 = noshdata.old_text + '.'; } else { var old_text1 = noshdata.old_text; } if (!!start_text) { var b = old.replace(c_old, c); } else { var b = old.replace(old_text1, c); } noshdata.old_text = ''; } else { var b = old + ' ' + c; } } else { if (!!start_text) { var b = start_text + mid_text + ': ' + a + end_text; } else { if (a_pointer != a_pointer2) { var b = a + '.'; } else { var b = a; } } } $("#" + parent_id_entry).val(b); } } }); $(document).on('click', '.ros_template_div .ros_detail', function() { var detail_id = $(this).attr("id") + '_detail'; if ($(this).prop('checked')) { $('#' + detail_id).show('fast'); $('#' + detail_id).focus(); } else { var parent_id = $(this).attr("id"); var parts = parent_id.split('_'); if (parts[1] == 'wccage') { var parent_id_entry = 'ros_wcc'; } else { var parent_id_entry = parts[0] + '_' + parts[1]; } var old = $("#" + parent_id_entry).val(); var a = ' ' + $('#' + detail_id).val(); var a1 = a + ' '; var c = old.replace(a1,''); c = c.replace(a, ''); $("#" + parent_id_entry).val(c); $('#' + detail_id).hide('fast'); } }); $(document).on("click", '.all_normal', function(){ var a = $(this).prop('checked'); var parent_id = $(this).attr("id"); var parts = parent_id.split('_'); if (parts[1] == 'wcc') { if(a){ $("#ros_wcc_form").find("input.ros_normal:checkbox").each(function(){ $(this).prop("checked",true); }); $("#ros_wcc_age_form").find("input.ros_normal:checkbox").each(function(){ $(this).prop("checked",true); }); var newtext = ''; $('#ros_wcc_form :checked').each(function() { newtext += $(this).val() + ' '; }); $('#ros_wcc_age_form :checked').each(function() { newtext += $(this).val() + ' '; }); $('#ros_wcc').val(newtext); } else { $("#ros_wcc").val(''); $("#ros_wcc_form").find('input.ros_normal:checkbox').each(function(){ $(this).prop("checked",false); }); $("#ros_wcc_age_form").find('input.ros_normal:checkbox').each(function(){ $(this).prop("checked",false); }); } $('#ros_wcc_form input[type="checkbox"]').button('refresh'); $('#ros_wcc_age_form input[type="checkbox"]').button('refresh'); } else { var parent_id_entry = parts[0] + '_' + parts[1]; if(a){ $("#" + parent_id_entry + "_form").find("input.ros_normal:checkbox").each(function(){ $(this).prop("checked",true); }); updateTextArea(parent_id_entry); } else { $("#" + parent_id_entry).val(''); $("#" + parent_id_entry + "_form").find('input.ros_normal:checkbox').each(function(){ $(this).prop("checked",false); }); } $("#" + parent_id_entry + '_form input[type="checkbox"]').button('refresh'); } }); $(document).on("click", '.all_normal1_ros', function(){ var a = $(this).prop('checked'); var parent_id = $(this).attr("id"); var parts = parent_id.split('_'); var parent_id_entry = parts[0] + '_' + parts[1]; $.ajax({ type: "POST", url: "ajaxencounter/all-normal/ros/" + parent_id_entry, dataType: 'json', success: function(data){ var message = ''; $.each(data, function(key, value){ if(a){ $("#" + key).val(value); message = "All normal values set!"; } else { $("#" + key).val(''); message = "All normal values cleared!"; } }); $.jGrowl(message); } }); }); function updateTextArea_pe(parent_id_entry) { var newtext = ''; $('#' + parent_id_entry + '_form :checked').each(function() { newtext += $(this).val() + ' '; }); $('#' + parent_id_entry).val(newtext); } function pe_normal(parent_id) { var id = parent_id; var x = parent_id.length - 1; parent_id = parent_id.slice(0,x); $("#" + id).siblings('input:checkbox').each(function() { var parent_id = $(this).attr("id"); $(this).prop('checked',false); var parts = parent_id.split('_'); var parent_id_entry = parts[0] + '_' + parts[1]; var old = $("#" + parent_id_entry).val(); var a = $(this).val(); remove_text(parent_id_entry,a,'',false); $(this).button('refresh'); }); $("#" + parent_id + "_div").find('.pe_detail_text').each(function(){ var parent_id = $(this).attr("id"); var parts = parent_id.split('_'); var parent_id_entry = parts[0] + '_' + parts[1]; var old = $("#" + parent_id_entry).val(); if ($(this).val() != '') { var text_pointer = $(this).val().length - 1; var text_pointer2 = $(this).val().lastIndexOf('.'); if (text_pointer != text_pointer2) { var text1 = $(this).val() + '.'; } else { var text1 = $(this).val(); } var a = ' ' + text1; remove_text(parent_id_entry,a,'',false); } $(this).val(''); $(this).hide(); }); } function pe_other(parent_id) { var x = parent_id.length - 1; parent_id = parent_id.slice(0,x); $("#" + parent_id + "_div").find('.pe_normal:checkbox').each(function(){ var parent_id = $(this).attr("id"); $(this).prop('checked',false); var parts = parent_id.split('_'); var parent_id_entry = parts[0] + '_' + parts[1]; var old = $("#" + parent_id_entry).val(); var a = $(this).val(); remove_text(parent_id_entry,a,'',false); //var a1 = a + ' '; //var c = old.replace(a1,''); //c = c.replace(a, ''); //$("#" + parent_id_entry).val(c); $(this).button('refresh'); }); } $(document).on("click", '.pe_template_div input[type="checkbox"]', function() { var parent_id = $(this).attr("id"); var parts = parent_id.split('_'); var parent_id_entry = parts[0] + '_' + parts[1]; var label = parts[0] + '_' + parts[1] + '_' + parts[2] + '_label'; var label_text = $("#" + label).text() + ': '; var old = $("#" + parent_id_entry).val(); var a = $(this).val(); var repeat = repeat_text(parent_id_entry,a,label_text); if ($(this).is(':checked') && repeat !== true) { if (old != '') { var comma = a.charAt(0); var old_arr = old.split(' '); var new_arr = search_array(old_arr, label_text); if (new_arr.length > 0) { var arr_index = old_arr.indexOf(new_arr[0]); a = a.replace(label_text, '; '); old_arr[arr_index] += a; } else { old_arr.push(a); } var b = old_arr.join(" "); } else { var b = a; } $("#" + parent_id_entry).val(b); if ($(this).is('.pe_normal')) { pe_normal(parent_id); } else { pe_other(parent_id); } } else { remove_text(parent_id_entry,a,label_text,false); } }); $(document).on("change", '.pe_template_div input[type="radio"]', function() { var parent_id = $(this).attr("id"); var parts = parent_id.split('_'); var parent_id_entry = parts[0] + '_' + parts[1]; var old = $("#" + parent_id_entry).val(); var a = $(this).val(); var repeat = repeat_text(parent_id_entry,a,''); if ($(this).is(':checked') && repeat !== true) { if (old != '') { $(this).siblings('input:radio').each(function() { var d = $(this).val(); var d1 = ' ' + d; old = old.replace(d1,''); old = old.replace(d, ''); }); if (old != '') { var b = old + ' ' + a; } else { var b = a; } } else { var b = a; } $("#" + parent_id_entry).val(b); } else { remove_text(parent_id_entry,a,'',false); } }); $(document).on("change", '.pe_template_div select', function() { var parent_id = $(this).attr("id"); var parts = parent_id.split('_'); var parent_id_entry = parts[0] + '_' + parts[1]; var old = $("#" + parent_id_entry).val(); var a = $(this).val(); if (old != '') { $(this).siblings('option').each(function() { var d = $(this).val(); var d1 = ' ' + d; old = old.replace(d1,''); old = old.replace(d, ''); }); var b = old + ' ' + a; } else { var b = a; } $("#" + parent_id_entry).val(b); }); $(document).on("focus", '.pe_template_div input[type="text"]', function() { noshdata.old_text = $(this).val(); }); $(document).on("focusout", '.pe_template_div input[type="text"]', function() { var a = $(this).val(); if (a != noshdata.old_text) { if (a != '') { var parent_id = $(this).attr("id"); var parts = parent_id.split('_'); var parent_id_entry = parts[0] + '_' + parts[1]; var x = parent_id.length - 1; var parent_div = parent_id.slice(0,x); var start1 = $("#" + parent_div + "_div").find('span:first').text(); if (start1 == '') { start1 = $("#" + parts[0] + '_' + parts[1] + '_' + parts[2] + '_label').text(); } var start1_n = start1.lastIndexOf(' ('); if (start1_n != -1) { var start1_n1 = start1.substring(0,start1_n); var start1_n2 = start1_n1.toLowerCase(); } else { var start1_n1 = start1; var start1_n2 = start1; } var start2 = $("label[for='" + parent_id + "']").text(); var start3_n = start1.lastIndexOf('degrees'); if (start3_n != -1) { var end_text = ' degrees.'; } else { var end_text = ''; } var start4 = $(this).closest('div.ui-accordion').find('h3.ui-state-active').text(); if (start4 != '') { var start4_n = start4.lastIndexOf('-'); if (start4_n != -1) { var parts2 = start4.split(' - '); var mid_text = ', ' + parts2[1].toLowerCase(); } else { var mid_text = ', ' + start4.toLowerCase(); } } else { var mid_text = ''; } if (!!start2) { var start_text = start2 + ' ' + start1_n2; } else { var start_text = start1_n1; } var old = $("#" + parent_id_entry).val(); var a_pointer = a.length - 1; var a_pointer2 = a.lastIndexOf('.'); if (!!old) { if (!!start_text) { var c = start_text + mid_text + ': ' + a + end_text; if (noshdata.old_text != '') { var c_old = start_text + mid_text + ': ' + noshdata.old_text + end_text; } } else { if (a_pointer != a_pointer2) { var c = a + '.'; } else { var c = a; } } if (noshdata.old_text != '') { var old_text_pointer = noshdata.old_text.length - 1; var old_text_pointer2 = noshdata.old_text.lastIndexOf('.'); if (old_text_pointer != old_text_pointer2) { var old_text1 = noshdata.old_text + '.'; } else { var old_text1 = noshdata.old_text; } if (!!start_text) { var b = old.replace(c_old, c); } else { var b = old.replace(old_text1, c); } noshdata.old_text = ''; } else { var b = old + ' ' + c; } } else { if (!!start_text) { var b = start_text + mid_text + ': ' + a + end_text; } else { if (a_pointer != a_pointer2) { var b = a + '.'; } else { var b = a; } } } $("#" + parent_id_entry).val(b); } } }); $(document).on("click", '.pe_template_div .pe_detail', function() { var detail_id = $(this).attr("id") + '_detail'; if ($(this).is(':checked')) { $('#' + detail_id).show('fast'); $('#' + detail_id).focus(); } else { var parent_id = $(this).attr("id"); var parts = parent_id.split('_'); var parent_id_entry = parts[0] + '_' + parts[1]; var old = $("#" + parent_id_entry).val(); if ($('#' + detail_id).val() != '') { var text_pointer = $('#' + detail_id).val().length - 1; var text_pointer2 = $('#' + detail_id).val().lastIndexOf('.'); if (text_pointer != text_pointer2) { var text1 = $('#' + detail_id).val() + '.'; } else { var text1 = $('#' + detail_id).val(); } var a = ' ' + text1; var a1 = a + ' '; var c = old.replace(a1,''); c = c.replace(a, ''); $("#" + parent_id_entry).val(c); } $('#' + detail_id).val(''); $('#' + detail_id).hide('fast'); } }); $(document).on("click", '.all_normal_pe', function(){ var a = $(this).is(':checked'); var parent_id = $(this).attr("id"); var n = parent_id.lastIndexOf('_'); var parent_id_entry = parent_id.substring(0,n); if(a){ $("#" + parent_id_entry + "_form").find("input.pe_normal:checkbox").each(function(){ $(this).prop("checked",true); }); updateTextArea_pe(parent_id_entry); } else { $("#" + parent_id_entry).val(''); $("#" + parent_id_entry + "_form").find('input.pe_normal:checkbox').each(function(){ $(this).prop("checked",false); }); } $("#" + parent_id_entry + '_form input[type="checkbox"]').button('refresh'); }); $(document).on("click", '.all_normal1_pe', function(){ var a = $(this).is(':checked'); var parent_id = $(this).attr("id"); var parent_id_entry = parent_id.replace('normal','dialog'); if(a){ $("#" + parent_id_entry).find(".all_normal_pe").each(function(){ $(this).prop("checked",true); var parent_id1 = $(this).attr("id"); var n1 = parent_id1.lastIndexOf('_'); var parent_id_entry1 = parent_id1.substring(0,n1); $("#" + parent_id_entry1 + "_form").find("input.pe_normal:checkbox").each(function(){ $(this).prop("checked",true); }); updateTextArea_pe(parent_id_entry1); $("#" + parent_id_entry1 + '_form input[type="checkbox"]').button('refresh'); }).button('refresh'); $("#" + parent_id_entry).find(".all_normal2_pe").each(function(){ $(this).prop("checked",true); var parent_id2 = $(this).attr("id"); var parent_id_entry2 = parent_id2.replace('_normal1',''); var old2 = $("#" + parent_id_entry2).val(); var a2 = $(this).val(); if (old2 != '') { var b2 = old2 + ' ' + a2; } else { var b2 = a2; } $("#" + parent_id_entry2).val(b2); }).button('refresh'); } else { $("#" + parent_id_entry).find(".all_normal_pe").each(function(){ $(this).prop("checked",false); var parent_id2 = $(this).attr("id"); var n2 = parent_id2.lastIndexOf('_'); var parent_id_entry2 = parent_id2.substring(0,n2); $("#" + parent_id_entry2).val(''); $("#" + parent_id_entry2 + "_form").find('input.pe_normal:checkbox').each(function(){ $(this).prop("checked",false); }); $("#" + parent_id_entry2 + '_form input[type="checkbox"]').button('refresh'); }).button('refresh'); $("#" + parent_id_entry).find(".all_normal2_pe").each(function(){ $(this).prop("checked",true); var parent_id2 = $(this).attr("id"); var parent_id_entry2 = parent_id2.replace('_normal1',''); var old2 = $("#" + parent_id_entry2).val(); var a2 = $(this).val(); var a3 = ' ' + a2; var c2 = old2.replace(a3,''); c2 = c2.replace(a2, ''); $("#" + parent_id_entry2).val(c2); }).button('refresh'); } $("#"+parent_id_entry).find('.pe_entry').each(function(){ var parent_id1 = $(this).attr("id"); if (!!$(this).val()) { $('#' + parent_id1 + '_h').html(noshdata.item_present); } else { $('#' + parent_id1 + '_h').html(noshdata.item_empty); } }); }); $(document).on("click", ".all_normal2_pe", function(){ var parent_id = $(this).attr("id"); var parent_id_entry = parent_id.replace('_normal1',''); var old = $("#" + parent_id_entry).val(); var a = $(this).val(); if ($(this).is(':checked')) { if (old != '') { var b = old + ' ' + a; } else { var b = a; } $("#" + parent_id_entry).val(b); } else { var a1 = ' ' + a; var c = old.replace(a1,''); c = c.replace(a, ''); $("#" + parent_id_entry).val(c); } }); $(document).on("click", ".all_normal3_pe", function(){ var a = $(this).is(':checked'); var parent_id = $(this).attr("id"); var parent_id_entry = parent_id.replace('_normal1',''); $.ajax({ type: "POST", url: "ajaxencounter/all-normal/pe/" + parent_id_entry, dataType: 'json', success: function(data){ var message = ''; $.each(data, function(key, value){ if(a){ $("#" + key).val(value); message = "All normal values set!"; } else { $("#" + key).val(''); message = "All normal values cleared!"; } }); $.jGrowl(message); $("#"+parent_id_entry+"_dialog").find('.pe_entry').each(function(){ var parent_id1 = $(this).attr("id"); if (!!$(this).val()) { $('#' + parent_id1 + '_h').html(noshdata.item_present); } else { $('#' + parent_id1 + '_h').html(noshdata.item_empty); } }); } }); }); function loadimagepreview(){ $('#image_placeholder').html(''); $('#image_placeholder').empty(); var image_total = ''; $.ajax({ url: "ajaxchart/image-load", type: "POST", success: function(data){ $('#image_placeholder').html(data); image_total = $("#image_placeholder img").length; var $image = $("#image_placeholder img"); $image.tooltip(); $image.first().show(); var i = 1; $("#image_status").html('Image ' + i + ' of ' + image_total); $('#next_image').click(function () { var $next = $image.filter(':visible').hide().next('img'); i++; if($next.length === 0) { $next = $image.first(); i = 1; } $next.show(); $("#image_status").html('Image ' + i + ' of ' + image_total); }); $('#prev_image').click(function () { var $prev = $image.filter(':visible').hide().prev('img'); i--; if($prev.length === 0) { $next = $image.last(); i = image_total; } $prev.show(); $("#image_status").html('Image ' + i + ' of ' + image_total); }); } }); } $(document).on('click', '#edit_image', function () { var image = $("#image_placeholder img").filter(':visible').attr('src'); var image_id1 = $("#image_placeholder img").filter(':visible').attr('id'); var image_id = image_id1.replace('_image', ''); $('#wPaint').css({ width: document.getElementById(image_id1).naturalWidth, height: document.getElementById(image_id1).naturalHeight }).wPaint('resize'); $('.wPaint-menu-name-main').css({width:579}); $('.wPaint-menu-name-text').css({width:182,left:0,top:42}); $('.wPaint-menu-select').css({"overflow-y":"scroll"}); $('#wPaint').wPaint('image', image); $.ajax({ url: "ajaxchart/image-get/" + image_id, dataType: "json", type: "POST", success: function(data){ $.each(data, function(key, value){ $("#image_form :input[name='" + key + "']").val(value); }); $("#image_dialog").dialog('open'); } }); }); $(document).on('click', "#del_image", function() { var image_id1 = $("#image_placeholder img").filter(':visible').attr('id'); var image_id = image_id1.replace('_image', ''); if(confirm('Are you sure you want to delete this image?')){ $.ajax({ type: "POST", url: "ajaxchart/delete-image", data: "image_id=" + image_id, success: function(data){ $.jGrowl(data); loadimagepreview(); } }); } }); $(document).on('keydown', ':text', function(e){ if(e.keyCode==13) { e.preventDefault(); } }); $(document).on('keydown', ':password', function(e){ var a = $(this).attr('id'); if(a != 'password') { if(e.keyCode==13) { e.preventDefault(); } } }); $(document).on('keydown', '.textdump', function(e){ if(e.keyCode==39) { if(e.shiftKey==true) { e.preventDefault(); var id = $(this).attr('id'); $.ajax({ type: "POST", url: "ajaxsearch/textdump-group/" + id, success: function(data){ $("#textdump_group_html").html(''); $("#textdump_group_html").append(data); $(".edittextgroup").button({text: false, icons: {primary: "ui-icon-pencil"}}); $(".deletetextgroup").button({text: false, icons: {primary: "ui-icon-trash"}}); $(".normaltextgroup").button({text: false, icons: {primary: "ui-icon-check"}}); $(".restricttextgroup").button({text: false, icons: {primary: "ui-icon-close"}}); $('.textdump_group_item_text').editable('destroy'); $('.textdump_group_item_text').editable({ toggle:'manual', ajaxOptions: { headers: {"cache-control":"no-cache"}, beforeSend: function(request) { return request.setRequestHeader("X-CSRF-Token", $("meta[name='token']").attr('content')); }, error: function(xhr) { if (xhr.status == "404" ) { alert("Route not found!"); //window.location.replace(noshdata.error); } else { if(xhr.responseText){ var response1 = $.parseJSON(xhr.responseText); var error = "Error:\nType: " + response1.error.type + "\nMessage: " + response1.error.message + "\nFile: " + response1.error.file; alert(error); } } } } }); $("#textdump_group_target").val(id); $("#textdump_group").dialog("option", "position", { my: 'left top', at: 'right top', of: '#'+id }); $("#textdump_group").dialog('open'); } }); } } }); $(document).on('click', '.textdump_item', function() { if ($(this).find(':first-child').hasClass("ui-state-error") == false) { $(this).find(':first-child').addClass("ui-state-error ui-corner-all"); } else { $(this).find(':first-child').removeClass("ui-state-error ui-corner-all"); } }); $(document).on('click', '.textdump_item_specific', function() { if ($(this).find(':first-child').hasClass("ui-state-error") == false) { $(this).find(':first-child').addClass("ui-state-error ui-corner-all"); } else { $(this).find(':first-child').removeClass("ui-state-error ui-corner-all"); } }); $(document).on('click', '.edittextgroup', function(e) { var id = $(this).attr('id'); var isEditable= $("#"+id+"_b").is('.editable'); $("#"+id+"_b").prop('contenteditable',!isEditable).toggleClass('editable'); if (isEditable) { var url = $("#"+id+"_b").attr('data-url'); var pk = $("#"+id+"_b").attr('data-pk'); var name = $("#"+id+"_b").attr('data-name'); var title = $("#"+id+"_b").attr('data-title'); var type = $("#"+id+"_b").attr('data-type'); var value = encodeURIComponent($("#"+id+"_b").html()); $.ajax({ type: "POST", url: url, data: 'value=' + value + "&pk=" + pk + "&name=" + name, success: function(data){ toastr.success(data); } }); $(this).html('<i class="zmdi zmdi-edit"></i>'); $(this).siblings('.deletetextgroup').show(); $(this).siblings('.restricttextgroup').show(); } else { $(this).html('<i class="zmdi zmdi-check"></i>'); $(this).siblings('.deletetextgroup').hide(); $(this).siblings('.restricttextgroup').hide(); } }); $(document).on('click', '.edittexttemplate', function(e) { var id = $(this).attr('id'); e.stopPropagation(); $("#"+id+"_span").editable('show', true); }); $(document).on('click', '.edittexttemplatespecific', function(e) { var id = $(this).attr('id'); e.stopPropagation(); $("#"+id+"_span").editable('show', true); }); $(document).on('click', '.deletetextgroup', function() { var id = $(this).attr('id'); var template_id = id.replace('deletetextgroup_',''); $.ajax({ type: "POST", url: "ajaxsearch/deletetextdumpgroup/" + template_id, success: function(data){ $("#textgroupdiv_"+template_id).remove(); } }); }); $(document).on('click', '.restricttextgroup', function() { var id = $(this).attr('id'); var template_id = id.replace('restricttextgroup_',''); $("#restricttextgroup_template_id").val(template_id); $.ajax({ type: "POST", url: "ajaxsearch/restricttextgroup-get/" + template_id, dataType: 'json', success: function(data){ $.each(data, function(key, value){ $("#restricttextgroup_form :input[name='" + key + "']").val(value); }); } }); $("#restricttextgroup_dialog").dialog('open'); }); $(document).on('click', '.deletetexttemplate', function() { var id = $(this).attr('id'); var template_id = id.replace('deletetexttemplate_',''); $.ajax({ type: "POST", url: "ajaxsearch/deletetextdump/" + template_id, success: function(data){ $("#texttemplatediv_"+template_id).remove(); } }); }); $(document).on('click', '.deletetexttemplatespecific', function() { var id = $(this).attr('id'); var template_id = id.replace('deletetexttemplatespecific_',''); $.ajax({ type: "POST", url: "ajaxsearch/deletetextdump/" + template_id, success: function(data){ $("#texttemplatespecificdiv_"+template_id).remove(); } }); }); $(document).on('click', '.normaltextgroup', function() { var id = $("#textdump_group_target").val(); var a = $(this).val(); var old = $("#"+id).val(); var delimiter = $("#textdump_delimiter2").val(); if (a != 'No normal values set.') { var a_arr = a.split("\n"); var d = a_arr.join(delimiter); if ($(this).prop('checked')) { if (old != '') { var b = old + '\n' + d; } else { var b = d; } $("#"+id).val(b); } else { var a1 = d + ' '; var c = old.replace(a1,''); c = c.replace(d, ''); $("#" +id).val(c); } } else { $.jGrowl(a); } }); $(document).on('click', '.normaltexttemplate', function() { var id = $(this).attr('id'); var template_id = id.replace('normaltexttemplate_',''); if ($(this).prop('checked')) { $.ajax({ type: "POST", url: "ajaxsearch/defaulttextdump/" + template_id, success: function(data){ $.jGrowl('Template marked as normal default!'); $("#textdump_group_html").html(''); $("#textdump_group_html").append(data); $(".edittextgroup").button({text: false, icons: {primary: "ui-icon-pencil"}}); $(".deletetextgroup").button({text: false, icons: {primary: "ui-icon-trash"}}); $(".normaltextgroup").button({text: false, icons: {primary: "ui-icon-check"}}); $(".restricttextgroup").button({text: false, icons: {primary: "ui-icon-close"}}); $('.textdump_group_item_text').editable('destroy'); $('.textdump_group_item_text').editable({ toggle:'manual', ajaxOptions: { headers: {"cache-control":"no-cache"}, beforeSend: function(request) { return request.setRequestHeader("X-CSRF-Token", $("meta[name='token']").attr('content')); }, error: function(xhr) { if (xhr.status == "404" ) { alert("Route not found!"); //window.location.replace(noshdata.error); } else { if(xhr.responseText){ var response1 = $.parseJSON(xhr.responseText); var error = "Error:\nType: " + response1.error.type + "\nMessage: " + response1.error.message + "\nFile: " + response1.error.file; alert(error); } } } } }); } }); } else { $.ajax({ type: "POST", url: "ajaxsearch/undefaulttextdump/" + template_id, success: function(data){ $.jGrowl('Template unmarked as normal default!'); $("#textdump_group_html").html(''); $("#textdump_group_html").append(data); $(".edittextgroup").button({text: false, icons: {primary: "ui-icon-pencil"}}); $(".deletetextgroup").button({text: false, icons: {primary: "ui-icon-trash"}}); $(".normaltextgroup").button({text: false, icons: {primary: "ui-icon-check"}}); $(".restricttextgroup").button({text: false, icons: {primary: "ui-icon-close"}}); $('.textdump_group_item_text').editable('destroy'); $('.textdump_group_item_text').editable({ toggle:'manual', ajaxOptions: { headers: {"cache-control":"no-cache"}, beforeSend: function(request) { return request.setRequestHeader("X-CSRF-Token", $("meta[name='token']").attr('content')); }, error: function(xhr) { if (xhr.status == "404" ) { alert("Route not found!"); //window.location.replace(noshdata.error); } else { if(xhr.responseText){ var response1 = $.parseJSON(xhr.responseText); var error = "Error:\nType: " + response1.error.type + "\nMessage: " + response1.error.message + "\nFile: " + response1.error.file; alert(error); } } } } }); } }); } }); $(document).on('keydown', '#textdump_group_add', function(e){ if(e.keyCode==13) { e.preventDefault(); var a = $("#textdump_group_add").val(); if (a != '') { var str = $("#textdump_group_form").serialize(); if(str){ $.ajax({ type: "POST", url: "ajaxsearch/add-text-template-group", data: str, dataType: 'json', success: function(data){ $.jGrowl(data.message); var app = '<div id="textgroupdiv_' + data.id + '" style="width:99%" class="pure-g"><div class="pure-u-2-3"><input type="checkbox" id="normaltextgroup_' + data.id + '" class="normaltextgroup" value="No normal values set."><label for="normaltextgroup_' + data.id + '">Normal</label> <b id="edittextgroup_' + data.id + '_b" class="textdump_group_item textdump_group_item_text" data-type="text" data-pk="' + data.id + '" data-name="group" data-url="ajaxsearch/edit-text-template-group" data-title="Group">' + a + '</b></div><div class="pure-u-1-3" style="overflow:hidden"><div style="width:200px;"><button type="button" id="edittextgroup_' + data.id + '" class="edittextgroup">Edit</button><button type="button" id="deletetextgroup_' + data.id + '" class="deletetextgroup">Remove</button><button type="button" id="restricttextgroup_' + data.id + '" class="restricttextgroup">Restrictions</button></div></div><hr class="ui-state-default"/></div>'; $("#textdump_group_html").append(app); $(".edittextgroup").button({text: false, icons: {primary: "ui-icon-pencil"}}); $(".deletetextgroup").button({text: false, icons: {primary: "ui-icon-trash"}}); $(".normaltextgroup").button({text: false, icons: {primary: "ui-icon-check"}}); $(".restricttextgroup").button({text: false, icons: {primary: "ui-icon-close"}}); $('.textdump_group_item_text').editable('destroy'); $('.textdump_group_item_text').editable({ toggle:'manual', ajaxOptions: { headers: {"cache-control":"no-cache"}, beforeSend: function(request) { return request.setRequestHeader("X-CSRF-Token", $("meta[name='token']").attr('content')); }, error: function(xhr) { if (xhr.status == "404" ) { alert("Route not found!"); //window.location.replace(noshdata.error); } else { if(xhr.responseText){ var response1 = $.parseJSON(xhr.responseText); var error = "Error:\nType: " + response1.error.type + "\nMessage: " + response1.error.message + "\nFile: " + response1.error.file; alert(error); } } } } }); $("#textdump_group_add").val(''); } }); } else { $.jGrowl("Please complete the form"); } } else { $.jGrowl("No text to add!"); } } }); $(document).on('keydown', '#textdump_add', function(e){ if(e.keyCode==13) { e.preventDefault(); var a = $("#textdump_add").val(); if (a != '') { var str = $("#textdump_form").serialize(); if(str){ $.ajax({ type: "POST", url: "ajaxsearch/add-text-template", data: str, dataType: 'json', success: function(data){ $.jGrowl(data.message); var app = '<div id="texttemplatediv_' + data.id + '" style="width:99%" class="pure-g"><div class="textdump_item pure-u-2-3"><span id="edittexttemplate_' + data.id + '_span" class="textdump_item_text ui-state-error ui-corner-all" data-type="text" data-pk="' + data.id + '" data-name="array" data-url="ajaxsearch/edit-text-template" data-title="Item">' + a + '</span></div><div class="pure-u-1-3" style="overflow:hidden"><div style="width:400px;"><input type="checkbox" id="normaltexttemplate_' + data.id + '" class="normaltexttemplate" value="normal"><label for="normaltexttemplate_' + data.id + '">Mark as Default Normal</label><button type="button" id="edittexttemplate_' + data.id + '" class="edittexttemplate">Edit</button><button type="button" id="deletetexttemplate_' + data.id + '" class="deletetexttemplate">Remove</button></div></div><hr class="ui-state-default"/></div>'; $("#textdump_html").append(app); $(".edittexttemplate").button({text: false, icons: {primary: "ui-icon-pencil"}}); $(".deletetexttemplate").button({text: false, icons: {primary: "ui-icon-trash"}}); $(".normaltexttemplate").button({text: false, icons: {primary: "ui-icon-check"}}); $('.textdump_item_text').editable('destroy'); $('.textdump_item_text').editable({ toggle:'manual', ajaxOptions: { headers: {"cache-control":"no-cache"}, beforeSend: function(request) { return request.setRequestHeader("X-CSRF-Token", $("meta[name='token']").attr('content')); }, error: function(xhr) { if (xhr.status == "404" ) { alert("Route not found!"); //window.location.replace(noshdata.error); } else { if(xhr.responseText){ var response1 = $.parseJSON(xhr.responseText); var error = "Error:\nType: " + response1.error.type + "\nMessage: " + response1.error.message + "\nFile: " + response1.error.file; alert(error); } } } } }); $("#textdump_add").val(''); } }); } else { $.jGrowl("Please complete the form"); } } else { $.jGrowl("No text to add!"); } } }); $(document).on('keydown', '#textdump_specific_add', function(e){ if(e.keyCode==13) { e.preventDefault(); var a = $("#textdump_specific_add").val(); if (a != '') { var specific_name = $("#textdump_specific_name").val(); if (specific_name == '') { var id = $("#textdump_specific_target").val(); var start = $("#textdump_specific_start").val(); var length = $("#textdump_specific_length").val(); $("#"+id).textrange('set', start, length); $("#"+id).textrange('replace', a); $("#textdump_specific").dialog('close'); } else { var str = $("#textdump_specific_form").serialize(); if(str){ $.ajax({ type: "POST", url: "ajaxsearch/add-specific-template", data: str, dataType: 'json', success: function(data){ $.jGrowl(data.message); var app = '<div id="texttemplatespecificdiv_' + data.id + '" style="width:99%" class="pure-g"><div class="textdump_item_specific pure-u-2-3"><span id="edittexttemplatespecific_' + data.id + '_span" class="textdump_item_specific_text ui-state-error ui-corner-all" data-type="text" data-pk="' + data.id + '" data-name="array" data-url="ajaxsearch/edit-text-template-specific" data-title="Item">' + a + '</span></div><div class="pure-u-1-3" style="overflow:hidden"><div style="width:400px;"><button type="button" id="edittexttemplatespecific_' + data.id + '" class="edittexttemplatespecific">Edit</button><button type="button" id="deletetexttemplatespecific_' + data.id + '" class="deletetexttemplatespecific">Remove</button></div></div><hr class="ui-state-default"/></div>'; $("#textdump_specific_html").append(app); $(".edittexttemplatespecific").button({text: false, icons: {primary: "ui-icon-pencil"}}); $(".deletetexttemplatespecific").button({text: false, icons: {primary: "ui-icon-trash"}}); $(".defaulttexttemplatespecific").button(); $('.textdump_item_specific_text').editable('destroy'); $('.textdump_item_specific_text').editable({ toggle:'manual', ajaxOptions: { headers: {"cache-control":"no-cache"}, beforeSend: function(request) { return request.setRequestHeader("X-CSRF-Token", $("meta[name='token']").attr('content')); }, error: function(xhr) { if (xhr.status == "404" ) { alert("Route not found!"); //window.location.replace(noshdata.error); } else { if(xhr.responseText){ var response1 = $.parseJSON(xhr.responseText); var error = "Error:\nType: " + response1.error.type + "\nMessage: " + response1.error.message + "\nFile: " + response1.error.file; alert(error); } } } } }); $("#textdump_specific_add").val(''); } }); } else { $.jGrowl("Please complete the form"); } } } else { $.jGrowl("No text to add!"); } } }); $(document).on("change", "#hippa_address_id", function () { var a = $(this).find("option:selected").first().text(); if (a != 'Select Provider') { $("#hippa_provider1").val(a); } else { $("#hippa_provider1").val(''); } }); $(document).on('click', "#hippa_address_id2", function (){ var id = $("#hippa_address_id").val(); if(id){ $("#print_to_dialog").dialog("option", "title", "Edit Provider"); $.ajax({ type: "POST", url: "ajaxsearch/orders-provider1", data: "address_id=" + id, dataType: "json", success: function(data){ $.each(data, function(key, value){ $("#print_to_form :input[name='" + key + "']").val(value); }); } }); } else { $("#print_to_dialog").dialog("option", "title", "Add Provider"); } $("#print_to_origin").val('hippa'); $("#print_to_dialog").dialog('open'); }); $(document).on("change", "#hippa_request_address_id", function () { var a = $(this).find("option:selected").first().text(); if (a != 'Select Provider') { $("#hippa_request_to").val(a); } else { $("#hippa_request_to").val(''); } }); $(document).on('click', "#hippa_request_address_id2", function (){ var id = $("#hippa_request_address_id").val(); if(id){ $("#print_to_dialog").dialog("option", "title", "Edit Provider"); $.ajax({ type: "POST", url: "ajaxsearch/orders-provider1", data: "address_id=" + id, dataType: "json", success: function(data){ $.each(data, function(key, value){ $("#print_to_form :input[name='" + key + "']").val(value); }); } }); } else { $("#print_to_dialog").dialog("option", "title", "Add Provider"); } $("#print_to_origin").val('request'); $("#print_to_dialog").dialog('open'); }); $(document).on('click', '.assessment_clear', function(){ var id = $(this).attr('id'); var parts = id.split('_'); console.log(parts[2]); $("#assessment_" + parts[2]).val(''); $("#assessment_icd" + parts[2]).val(''); $("#assessment_icd" + parts[2] + "_div").html(''); $("#assessment_icd" + parts[2] + "_div_button").hide(); }); $(document).on('click', '.hedis_patient', function() { var id = $(this).attr('id'); var pid = id.replace('hedis_', ''); $.ajax({ type: "POST", url: "ajaxsearch/openchart", data: "pid=" + pid, success: function(data){ $.ajax({ type: "POST", url: "ajaxsearch/hedis-set", dataType: "json", success: function(data){ window.location = data.url; } }); } }); }); $(document).on('click', '.claim_associate', function() { var id = $(this).attr('id'); var form_id = id.replace('era_button_', 'era_form_'); var div_id = id.replace('era_button_', 'era_div_'); var bValid = true; $("#" + form_id).find("[required]").each(function() { var input_id = $(this).attr('id'); var id1 = $("#" + input_id); var text = $("label[for='" + input_id + "']").html(); bValid = bValid && checkEmpty(id1, text); }); if (bValid) { var str = $("#" + form_id).serialize(); if(str){ $.ajax({ type: "POST", url: "ajaxfinancial/associate-claim", data: str, success: function(data){ $.jGrowl(data); $("#" + form_id).clearForm(); $('#' + div_id).remove(); } }); } else { $.jGrowl("Please complete the form"); } } }); function textdump(elem) { var id = $(elem).attr('id'); $.ajax({ type: "POST", url: "ajaxsearch/textdump-group/" + id, success: function(data){ $("#textdump_group_html").html(''); $("#textdump_group_html").append(data); $(".edittextgroup").button({text: false, icons: {primary: "ui-icon-pencil"}}); $(".deletetextgroup").button({text: false, icons: {primary: "ui-icon-trash"}}); $(".normaltextgroup").button({text: false, icons: {primary: "ui-icon-check"}}); $(".restricttextgroup").button({text: false, icons: {primary: "ui-icon-close"}}); $('.textdump_group_item_text').editable('destroy'); $('.textdump_group_item_text').editable({ toggle:'manual', ajaxOptions: { headers: {"cache-control":"no-cache"}, beforeSend: function(request) { return request.setRequestHeader("X-CSRF-Token", $("meta[name='token']").attr('content')); }, error: function(xhr) { if (xhr.status == "404" ) { alert("Route not found!"); //window.location.replace(noshdata.error); } else { if(xhr.responseText){ var response1 = $.parseJSON(xhr.responseText); var error = "Error:\nType: " + response1.error.type + "\nMessage: " + response1.error.message + "\nFile: " + response1.error.file; alert(error); } } } } }); $("#textdump_group_target").val(id); $("#textdump_group").dialog("option", "position", { my: 'left top', at: 'right top', of: '#'+id }); $("#textdump_group").dialog('open'); } }); } $(document).on('click', 'textarea', function(e) { var stopCharacters = [' ', '\n', '\r', '\t', ',']; var id = $(this).attr('id'); var val = $(this).val(); $(this).html(val.replace(/[&\/\-\.]/g, 'a')); var text = $(this).html(); var start = $(this)[0].selectionStart; var end = $(this)[0].selectionEnd; while (start > 0) { if (stopCharacters.indexOf(text[start]) == -1) { --start; } else { break; } }; ++start; while (end < text.length) { if (stopCharacters.indexOf(text[end]) == -1) { ++end; } else { break; } } if (start == 1) { start = 0; } var startW = text.substr(start,1); var endW = text.substr(end-1,1); if (startW == '*' && endW == '*') { $(this).textrange('set', start, end - start); var currentWord = text.substr(start + 1, end - start - 2); if (currentWord != '') { if (currentWord == '~') { $("#textdump_specific_target").val(id); $("#textdump_specific_name").val(''); $("#textdump_specific_start").val(start); $("#textdump_specific_length").val(end - start); $("#textdump_delimiter_div").hide(); $("#textdump_specific_save").hide(); $("#textdump_specific_done").hide(); $("#textdump_specific").dialog("option", "position", { my: 'left top', at: 'right top', of: '#'+id }); $("#textdump_specific").dialog('open'); } else { $.ajax({ type: "POST", url: "ajaxsearch/textdump-specific/" + currentWord, success: function(data){ $("#textdump_specific_html").html(''); $("#textdump_specific_html").append(data); $(".edittexttemplatespecific").button({text: false, icons: {primary: "ui-icon-pencil"}}); $(".deletetexttemplatespecific").button({text: false, icons: {primary: "ui-icon-trash"}}); $(".defaulttexttemplatespecific").button(); $('.textdump_item_specific_text').editable('destroy'); $('.textdump_item_specific_text').editable({ toggle:'manual', ajaxOptions: { headers: {"cache-control":"no-cache"}, beforeSend: function(request) { return request.setRequestHeader("X-CSRF-Token", $("meta[name='token']").attr('content')); }, error: function(xhr) { if (xhr.status == "404" ) { alert("Route not found!"); //window.location.replace(noshdata.error); } else { if(xhr.responseText){ var response1 = $.parseJSON(xhr.responseText); var error = "Error:\nType: " + response1.error.type + "\nMessage: " + response1.error.message + "\nFile: " + response1.error.file; alert(error); } } } } }); $("#textdump_specific_target").val(id); $("#textdump_specific_name").val(currentWord); $("#textdump_specific_start").val(start); $("#textdump_specific_length").val(end - start); $("#textdump_specific_done").hide(); $("#textdump_specific").dialog("option", "position", { my: 'left top', at: 'right top', of: '#'+id }); $("#textdump_specific").dialog('open'); } }); } } } }); $(document).on('change', '.encounter_template_group_group', function() { var id = $(this).attr('id'); var a1 = id.split("_"); var count = a1[4]; var a = $("#"+id).val(); $.ajax({ type: "POST", url: "ajaxsearch/get-template-normal-options/" + a, dataType: "json", success: function(data){ $("#encounter_template_array_id_"+count).removeOption(/./); $("#encounter_template_array_id_"+count).addOption({'':'Choose Group'}, false); $("#encounter_template_array_id_"+count).addOption(data, false); } }); }); $(document).on('click', '#autogenerate_encounter_template', function() { $('#dialog_load').dialog('option', 'title', "Autogenerating template...").dialog('open'); var str = $("#template_encounter_edit_form").serialize(); if(str){ $.ajax({ type: "POST", url: "ajaxsearch/autogenerate-encounter-template", data: str, dataType: "json", success: function(data){ $.jGrowl(data.message); if (data.name != '') { $("#template_encounter_edit_dialog").dialog('close'); $('#dialog_load').dialog('close'); $('#dialog_load').dialog('option', 'title', "Loading template...").dialog('open'); $.ajax({ type: "POST", url: "ajaxsearch/get-encounter-templates-details", data: 'template_name='+data.name, dataType: "json", success: function(data){ $('#dialog_load').dialog('close'); $("#template_encounter_edit_div").html(data.html); loadbuttons(); $("#template_encounter_edit_dialog").dialog("option", "title", "Edit Encounter Template"); $("#template_encounter_edit_dialog").dialog('open'); } }); } } }); } }); $(document).on('click', '.remove_encounter_template_field', function() { var id = $(this).attr('id'); var a1 = id.split("_"); var count = a1[4]; $("#group_encounter_template_div_"+count).remove(); $("#array_encounter_template_div_"+count).remove(); $("#remove_encounter_template_div_"+count).remove(); }); $(document).on('click', "#timeline_chart", function() { $('#dialog_load').dialog('option', 'title', "Loading timeline...").dialog('open'); $.ajax({ type: "POST", url: "ajaxsearch/timeline", dataType: "json", success: function(data){ var json = data.json; for (var key in json) { if (json.hasOwnProperty(key)) { json[key]['startDate'] = new Date(json[key]['startDate'] * 1000); if (json[key]['endDate'] != null) { json[key]['endDate'] = new Date(json[key]['endDate'] * 1000); } } } $("#timeline").timeCube({ data: json, granularity: data.granular, startDate: new Date(data.start * 1000), endDate: new Date(data.end * 1000), transitionAngle: 60, transitionSpacing: 100, nextButton: $("#next-link"), previousButton: $("#prev-link"), showDate: true }); $('#dialog_load').dialog('close'); $('#timeline_dialog').dialog('open'); } }); }); $(document).on('click', '.timeline_event', function() { var type = $(this).attr('type'); var value = $(this).attr('value'); var status = $(this).attr('status'); var acl = false; if (noshdata.group_id == '2' || noshdata.group_id == '3') { acl = true; } if (type == 'eid') { if (status == 'Yes') { if (acl) { $("#encounter_view").load('ajaxchart/modal-view/' + value); } else { $.ajax({ type: "POST", url: "ajaxcommon/opennotes", success: function(data){ if (data == 'y') { $("#encounter_view").load('ajaxcommon/modal-view2/' + value); } else { $.jGrowl('You cannot view the encounter as your provider has not activated OpenNotes.'); } } }); } $("#encounter_view_dialog").dialog('open'); } else { $.jGrowl('Encounter is not signed. You cannot view it at this time.'); } } else if (type == 't_messages_id') { if (status == 'Yes') { if (acl) { $("#message_view").load('ajaxcommon/tmessages-view/' + value); $("#t_messages_id").val(value); t_messages_tags(); $("#messages_view_dialog").dialog('open'); } else { $.ajax({ type: "POST", url: "ajaxcommon/opennotes", success: function(data){ if (data == 'y') { $("#message_view").load('ajaxcommon/tmessages-view/' + value); $("#t_messages_id").val(value); $("#messages_view_dialog").dialog('open'); } else { $.jGrowl('You cannot view the message as your provider has not activated OpenNotes.'); } } }); } } else { $.jGrowl('Message is not signed. You cannot view it at this time.'); } } console.log(value + "," + type); }); // Mobile $(document).on('click', '.ui-title', function(e) { $("#form_item").val(''); $("#search_results").html(''); var url = $(location).attr('href'); var parts = url.split("/"); if (parts[4] == 'chart_mobile') { $.mobile.loading("show"); $.ajax({ type: "POST", url: "../ajaxchart/refresh-timeline", success: function(data){ $("#content_inner_timeline").html(data); $("#content_inner_main").show(); $("#content_inner").hide(); //refresh_timeline(); $.mobile.loading("hide"); } }); } }); $(document).on('click', '.mobile_click_home', function(e) { var classes = $(this).attr('class').split(' '); for (var i=0; i<classes.length; i++) { if (classes[i].indexOf("ui-") == -1) { if (classes[i] != 'mobile_click_home') { //console.log(classes[i]); //var link = classes[i].replace("mobile_",""); //$.mobile.loading("show"); //$.ajax({ //type: "POST", //url: "ajaxdashboard/" + link, //success: function(data){ //$("#content_inner").html(data).trigger('create').show(); //$("#content_inner_main").hide(); //$.mobile.loading("hide"); //} //}); window.location = classes[i]; break; } } } }); $(document).on('click', '.mobile_click_chart', function(e) { var classes = $(this).attr('class').split(' '); for (var i=0; i<classes.length; i++) { if (classes[i].indexOf("ui-") == -1) { if (classes[i] != 'mobile_click_chart') { console.log(classes[i]); var link = classes[i].replace("mobile_",""); $.ajax({ type: "POST", url: "../ajaxchart/" + link + "/true", success: function(data){ $("#content_inner").html(data).trigger('create').show(); $.mobile.loading("hide"); $("#content_inner_main").hide(); $("#left_panel").panel('close'); } }); break; } } } }); $(document).on('click', '.mobile_link', function(e) { $.mobile.loading("show"); $("#content").hide(); $("#chart_header").hide(); var url = $(this).attr('data-nosh-url'); var origin = $(this).attr('data-nosh-origin'); $.ajax({ type: "POST", url: url, data: 'origin=' + origin, dataType: 'json', success: function(data){ $("#navigation_header_back").attr('data-nosh-origin', origin); $("#navigation_header_save").attr('data-nosh-form', data.form); $("#navigation_header_save").attr('data-nosh-origin', origin); if (data.search != '') { $(".search_class").hide(); $("#"+data.search+"_div").show(); $("#"+data.search+"_div").find('ul').attr('data-nosh-paste-to',data.search_to); } $("#edit_content_inner").html(data.content).trigger('create'); $("#navigation_header").show(); $("#edit_content").show(); $.mobile.loading("hide"); } }); }); $(document).on('click', '#navigation_header_back', function(e) { $.mobile.loading("show"); var origin = $(this).attr('data-nosh-origin'); if (origin == 'Chart') { $("#navigation_header").hide(); $("#content_inner").hide(); $("#chart_header").show(); $("#content_inner_main").show(); $.mobile.loading("hide"); var scroll = parseInt($(this).attr('data-nosh-scroll')); $.mobile.silentScroll(scroll-70); } else { $.ajax({ type: "POST", url: origin, success: function(data){ $("#content_inner").html(data).trigger('create'); $("#edit_content").hide(); $("#navigation_header").hide(); $("#content").show(); $("#chart_header").show(); $.mobile.loading("hide"); } }); } }); $(document).on('click', '.cancel_edit', function(e) { $.mobile.loading("show"); var origin = $(this).attr('data-nosh-origin'); $.ajax({ type: "POST", url: origin, success: function(data){ $("#content_inner").html(data).trigger('create'); $("#edit_content").hide(); $("#navigation_header").hide(); $("#content").show(); $("#chart_header").show(); $.mobile.loading("hide"); } }); }); $(document).on('click', '.cancel_edit2', function(e) { var form = $(this).attr('data-nosh-form'); $("#"+form).clearForm(); $("#edit_content").hide(); $("#content").show(); }); $(document).on('click', '.nosh_schedule_event', function(e) { var editable = $(this).attr('data-nosh-editable'); if (editable != "false") { var id = $(this).attr('id'); if (id == 'patient_appt_button') { loadappt(); var startday = $(this).attr('data-nosh-start'); $('#start_date').val(startday); $("#edit_content").show(); $("#content").hide(); $("#title").focus(); $.mobile.silentScroll(0); return false; } if (id == 'event_appt_button') { loadevent(); var startday = $(this).attr('data-nosh-start'); $('#start_date').val(startday); $("#edit_content").show(); $("#content").hide(); $("#title").focus(); $.mobile.silentScroll(0); return false; } var form = {}; $.each($(this).get(0).attributes, function(i, attr) { if (attr.name.indexOf("data-nosh-") == '0') { var field = attr.name.replace('data-nosh-',''); field = field.replace('-', '_'); if (field == 'visit_type') { form.visit_type = attr.value; } if (field == 'title') { form.title = attr.value; } if (attr.value != 'undefined') { if (field != 'timestamp') { var value = attr.value; if (field.indexOf('_date') > 0) { value = moment(new Date(value)).format('YYYY-MM-DD'); } if (field == 'pid') { field = 'schedule_pid'; } if (field == 'title') { field = 'schedule_title'; } $('#' + field).val(value); } } } }); var timestamp = $(this).attr('data-nosh-timestamp'); $("#event_id_span").text(form.event_id); $("#pid_span").text(form.pid); $("#timestamp_span").text(timestamp); if (form.visit_type){ loadappt(); $("#patient_search").val(form.title); $("#end").val(''); } else { loadevent(); } var repeat_select = $("#repeat").val(); if (repeat_select != ''){ $("#until_row").show(); } else { $("#until_row").hide(); $("#until").val(''); } $("#delete_form").show(); $("#schedule_form select").selectmenu('refresh'); $("#edit_content").show(); $("#content").hide(); $("#title").focus(); $.mobile.silentScroll(0); return false; } else { toastr.error('You cannot edit this entry!'); return false; } }); $(document).on('click', '.nosh_messaging_item', function(e) { var form = {}; var datastring = ''; var label = $(this).html(); label = label.replace('<h3>','<h3 class="card-primary-title">'); label = label.replace('<p>','<h5 class="card-subtitle">'); label = label.replace('</p>','</h5>'); var origin = $(this).attr('data-origin'); var id = $(this).attr('data-nosh-message-id'); $.each($(this).get(0).attributes, function(i, attr) { if (attr.name.indexOf("data-nosh-") == '0') { datastring += attr.name + '="' + attr.value + '" '; var field = attr.name.replace('data-nosh-',''); if (field == 'message-from-label') { form.displayname = attr.value; } if (field == 'date') { form.date = attr.value; } if (field == 'subject') { form.subject = attr.value; } if (field == 'body') { form.body = attr.value; } if (field == 'bodytext') { form.bodytext = attr.value; } } }); var text = '<br><strong>From:</strong> ' + form.displayname + '<br><br><strong>Date:</strong> ' + form.date + '<br><br><strong>Subject:</strong> ' + form.subject + '<br><br><strong>Message:</strong> ' + form.bodytext; var action = '<div class="card-action">'; action += '<div class="row between-xs">'; action += '<div class="col-xs-4">'; action += '<div class="box">'; action += '<a href="#" class="ui-btn ui-btn-inline ui-btn-fab back_message" data-origin="' + origin + '" data-origin-id="' + id + '"><i class="zmdi zmdi-arrow-left"></i></a>'; action += '</div>' action += '</div>' if (origin == 'internal_inbox') { action += '<div class="col-xs-8 align-right">'; action += '<div class="box">'; action += '<a href="#" class="ui-btn ui-btn-inline ui-btn-fab reply_message"' + datastring + '><i class="zmdi zmdi-mail-reply"></i></a>'; action += '<a href="#" class="ui-btn ui-btn-inline ui-btn-fab reply_all_message"' + datastring + '><i class="zmdi zmdi-mail-reply-all"></i></a>'; action += '<a href="#" class="ui-btn ui-btn-inline ui-btn-fab forward_message"' + datastring + '><i class="zmdi zmdi-forward"></i></a>'; action += '<a href="#" class="ui-btn ui-btn-inline ui-btn-fab export_message"' + datastring + '><i class="zmdi zmdi-sign-in"></i></a>'; action += '</div>'; action += '</div>'; } action += '</div>'; action += '</div>'; var html = '<div class="nd2-card">'; html += '<div class="card-title">' + label + '</div>' + action; html += '<div class="card-supporting-text">' + text + '</div>' + action; html += '</div>'; $("#message_view1").html(html); //$("#message_view_rawtext").val(rawtext); //$("#message_view_message_id").val(id); //$("#message_view_from").val(row['message_from']); //$("#message_view_to").val(row['message_to']); //$("#message_view_cc").val(row['cc']); //$("#message_view_subject").val(row['subject']); //$("#message_view_body").val(row['body']); //$("#message_view_date").val(row['date']); //$("#message_view_pid").val(row['pid']); //$("#message_view_patient_name").val(row['patient_name']); //$("#message_view_t_messages_id").val(row['t_messages_id']); //$("#message_view_documents_id").val(row['documents_id']); //messages_tags(); //if (row['pid'] == '' || row['pid'] == "0") { //$("#export_message").hide(); //} else { //$("#export_message").show(); //} //$("#internal_messages_view_dialog").dialog('open'); //setTimeout(function() { //var a = $("#internal_messages_view_dialog" ).dialog("isOpen"); //if (a) { //var id = $("#message_view_message_id").val(); //var documents_id = $("#message_view_documents_id").val(); //if (documents_id == '') { //documents_id = '0'; //} //$.ajax({ //type: "POST", //url: "ajaxmessaging/read-message/" + id + "/" + documents_id, //success: function(data){ //$.jGrowl(data); //reload_grid("internal_inbox"); //} //}); //} //}, 3000); //form.event_id = $(this).attr('data-nosh-event-id'); //form.pid = $(this).attr('data-nosh-pid'); //form.start_date = moment(new Date($(this).attr('data-nosh-start-date'))).format('YYYY-MM-DD'); //form.start_time = $(this).attr('data-nosh-start-time'); //form.end = $(this).attr('data-nosh-end-time'); //form.visit_type = $(this).attr('data-nosh-visit-type'); //form.title = $(this).attr('data-nosh-title'); //form.repeat = $(this).attr('data-nosh-repeat'); //form.reason = $(this).attr('data-nosh-reason'); //form.until = $(this).attr('data-nosh-until'); //form.notes = $(this).attr('data-nosh-notes'); //form.status = $(this).attr('data-nosh-status'); //$.each(form, function(key, value){ //if (value != 'undefined') { //$('#'+key).val(value); //} //}); //var timestamp = $(this).attr('data-nosh-timestamp'); //$("#event_id_span").text(form.event_id); //$("#pid_span").text(form.pid); //$("#timestamp_span").text(timestamp); //if (form.visit_type){ //loadappt(); //$("#patient_search").val(form.title); //$("#end").val(''); //} else { //loadevent(); //} //var repeat_select = $("#repeat").val(); //if (repeat_select != ''){ //$("#until_row").show(); //} else { //$("#until_row").hide(); //$("#until").val(''); //} //$("#delete_form").show(); //$("#schedule_form select").selectmenu('refresh'); $("#view_content").show(); $("#content").hide(); $("#edit_content").hide(); $('html, body').animate({ scrollTop: $("#view_content").offset().top }); return false; }); $(document).on('click', '.mobile_form_action', function(e) { var form_id = $(this).attr('data-nosh-form'); var table = $(this).attr('data-nosh-table'); var row_id = $(this).attr('data-nosh-id'); var action = $(this).attr('data-nosh-action'); var refresh_url = $(this).attr('data-nosh-origin'); var row_index = $(this).attr('data-nosh-index'); var bValid = true; $("#"+form_id).find("[required]").each(function() { var input_id = $(this).attr('id'); var id1 = $("#" + input_id); var text = $("label[for='" + input_id + "']").html(); bValid = bValid && checkEmpty(id1, text); }); if (bValid) { var str = $("#"+form_id).serialize(); $.ajax({ type: "POST", url: "../ajaxcommon/mobile-form-action/" + table + '/' + action + '/' + row_id + '/' + row_index, data: str, dataType: 'json', success: function(data){ if (data.response == 'OK') { $('#'+form_id).clearForm(); $.mobile.loading("show"); toastr.success(data.message); $.ajax({ type: "POST", url: refresh_url, success: function(data1){ $("#content_inner").html(data1).trigger('create'); $("#edit_content").hide(); $("#navigation_header").hide(); $("#content").show(); $("#chart_header").show(); $.mobile.loading("hide"); } }); } else { // error handling } } }); } }); $(document).on('click', '.mobile_form_action2', function(e) { var form_id = $(this).attr('data-nosh-form'); var action = $(this).attr('data-nosh-action'); var refresh_url = $(this).attr('data-nosh-origin'); if (refresh_url == 'mobile_schedule') { var start_date = $("#start_date").val(); var end = $("#end").val(); var visit_type = $("#visit_type").val(); var pid = $("#pid").val(); if (pid == '') { var reason = $("#reason").val(); $("#title").val(reason); } if ($("#repeat").val() != '' && $("#event_id").val() != '' && $("#event_id").val().indexOf("R") === -1) { var event_id = $("#event_id").val(); $("#event_id").val("N" + event_id); } if ($("#repeat").val() == '' && $("#event_id").val() != '' && $("#event_id").val().indexOf("R") !== -1) { var event_id1 = $("#event_id").val(); $("#event_id").val("N" + event_id1); } var str = $("#"+form_id).serialize(); if (visit_type == '' || visit_type == null && end == '') { toastr.error("No visit type or end time selected!"); } else { $.mobile.loading("show"); $.ajax({ type: "POST", url: "ajaxschedule/edit-event", data: str, success: function(data){ open_schedule(start_date); $("#"+form_id).clearForm(); $("#edit_content").hide(); $("#content").show(); $.mobile.loading("hide"); } }); } } if (refresh_url == 'mobile_inbox') { if (action == 'save') { var bValid = true; $("#"+form_id).find("[required]").each(function() { var input_id = $(this).attr('id'); var id1 = $("#" + input_id); var text = $("label[for='" + input_id + "']").html(); bValid = bValid && checkEmpty(id1, text); }); if (bValid) { $.mobile.loading("show"); var str = $("#"+form_id).serialize(); $.ajax({ type: "POST", url: "ajaxmessaging/send-message", data: str, success: function(data){ toastr.success(data); $("#"+form_id).clearForm(); $("#edit_content").hide(); $("#content").show(); $.mobile.loading("hide"); } }); } } if (action == 'draft') { var str = $("#"+form_id).serialize(); $.ajax({ type: "POST", url: "ajaxmessaging/draft-message", data: str, success: function(data){ toastr.success(data); $("#"+form_id).clearForm(); $("#edit_content").hide(); $("#content").show(); $.mobile.loading("hide"); } }); } } // more stuff $("#edit_content").hide(); $("#content").show(); }); $(document).on("click", ".mobile_paste", function(e) { var value = $(this).attr('data-nosh-value'); var to = $(this).attr('data-nosh-paste-to'); $('#'+to).val(value); $('input[data-type="search"]').val(""); $('input[data-type="search"]').trigger("keyup"); }); $(document).on("click", ".mobile_paste1", function(e) { var form = {}; form.rxl_medication = $(this).attr('data-nosh-med'); form.rxl_dosage = $(this).attr('data-nosh-value'); form.rxl_dosage_unit = $(this).attr('data-nosh-unit'); form.rxl_ndcid = $(this).attr('data-nosh-ndc'); $.each(form, function(key, value){ if (value != 'undefined') { $('#'+key).val(value); } }); $('input[data-type="search"]').val(""); $('input[data-type="search"]').trigger("keyup"); }); $(document).on("click", ".mobile_paste2", function(e) { var value = $(this).attr('data-nosh-value'); var to = $("#form_item").val(); $('#'+to).val(value); if (to == 'patient_search') { var id = $(this).attr('data-nosh-id'); $("#schedule_pid").val(id); $("#schedule_title").val(value); } $("#right_panel").panel('close'); $("#"+to).focus(); }); $(document).on("click", ".mobile_paste3", function(e) { var form = {}; form.sup_supplement = $(this).attr('data-nosh-value'); form.sup_dosage = $(this).attr('data-nosh-dosage'); form.sup_dosage_unit = $(this).attr('data-nosh-dosage-unit'); form.supplement_id = $(this).attr('data-nosh-supplement-id'); $.each(form, function(key, value){ if (value != 'undefined') { $('#'+key).val(value); } }); $('input[data-type="search"]').val(""); $('input[data-type="search"]').trigger("keyup"); }); $(document).on("click", ".mobile_paste4", function(e) { var value = $(this).attr('data-nosh-value'); var to = $(this).attr('data-nosh-paste-to'); var cvx = $(this).attr('data-nosh-cvx'); $('#'+to).val(value); $('#imm_cvxcode').val(cvx); $('input[data-type="search"]').val(""); $('input[data-type="search"]').trigger("keyup"); }); $(document).on("click", ".return_button", function(e) { $("#right_panel").panel('close'); }); $(document).on("click", "input", function(e) { if ($(this).hasClass('texthelper')) { var id = $(this).attr('id'); $("#form_item").val(id); $("#navigation_header_fav").show(); } else { $("#navigation_header_fav").hide(); } }); $(document).on('keydown', '.texthelper', function(e){ var value = $(this).val(); var input = $(this).attr('id'); if (value && value.length > 1) { $("#form_item").val(input); var $ul = $("#search_results"); var html = ""; var parts = input.split('_'); if (parts[0] == 'rxl') { var url = "../ajaxsearch/rx-search/" + input + "/true"; } if (parts[0] == 'sup') { var url = "../ajaxsearch/sup-"+ parts[1]; } if (parts[0] == 'allergies') { var url = "../ajaxsearch/reaction/true"; } $.mobile.loading("show"); $.ajax({ url: url, dataType: "json", type: "POST", data: "term=" + value }) .then(function(response) { if (response.response == 'true') { $.each(response.message, function ( i, val ) { if (val.value != null) { html += '<li><a href=# class="ui-btn ui-btn-icon-left ui-icon-carat-l mobile_paste2" data-nosh-value="' + val.value +'">' + val.label + '</a></li>'; } }); $ul.html(html); $ul.listview("refresh"); $ul.trigger("updatelayout"); $.mobile.loading("hide"); $("#right_panel").panel('open'); } else { $.mobile.loading("hide"); } }); } }); $(document).on('keydown', '.texthelper1', function(e){ var value = $(this).val(); var input = $(this).attr('id'); if (value && value.length > 2) { $.mobile.loading("show"); $("#form_item").val(input); var $ul = $("#search_results"); var html = ""; $.ajax({ url: "ajaxsearch/search", dataType: "json", type: "POST", data: "term=" + value }) .then(function(response) { if (response.response == 'true') { $.each(response.message, function ( i, val ) { if (val.value != null) { html += '<li><a href=# class="ui-btn ui-btn-icon-left ui-icon-carat-l mobile_paste2" data-nosh-value="' + val.value +'" data-nosh-id="' + val.id + '">' + val.label + '</a></li>'; } }); $ul.html(html); $("#right_panel").width("500px"); $ul.listview("refresh"); $ul.trigger("updatelayout"); $.mobile.loading("hide"); $("#right_panel").panel('open'); } else { $.mobile.loading("hide"); } }); } }); $(document).on("click", "#nosh_fab", function(e) { $(".nosh_fab_child").toggle('fade'); return false; }); $(document).on("click", "#nosh_fab1", function(e) { $("#view_content").hide(); $("#content").hide(); $("#edit_content").show(); return false; }); $(document).on("change", "#provider_list2", function(e) { var id = $('#provider_list2').val(); if(id){ $.ajax({ type: "POST", url: "ajaxschedule/set-provider", data: "id=" + id, success: function(data){ $("#visit_type").removeOption(/./); $.ajax({ url: "ajaxsearch/visit-types/" + id, dataType: "json", type: "POST", async: false, success: function(data){ if (data.response == 'true') { $("#visit_type").addOption(data.message, false); } else { $("#visit_type").addOption({"":"No visit types available."},false); } } }); } }); } }); $(document).on("click", ".cd-read-more", function(e) { $.mobile.loading("show"); var type = $(this).attr('data-nosh-type'); var value = $(this).attr('data-nosh-value'); var status = $(this).attr('data-nosh-status'); var scroll = $(this).closest('.cd-timeline-block').offset().top; var acl = false; if (noshdata.group_id == '2' || noshdata.group_id == '3') { acl = true; } if (type == 'eid') { if (status == 'Yes') { if (acl) { $("#content_inner_main").hide(); $.ajax({ type: "GET", url: "../ajaxchart/modal-view-mobile/" + value, success: function(data){ $("#content_inner").html(data).trigger('create').show(); $('#content_inner').find('h4').css('color','blue'); $("#navigation_header_back").attr('data-nosh-origin', 'Chart'); $("#navigation_header_back").attr('data-nosh-scroll', scroll); $("#chart_header").hide(); $("#navigation_header").show(); $("#left_panel").panel('close'); $.mobile.loading("hide"); } }); } else { $("#content_inner_main").hide(); $.ajax({ type: "POST", url: "../ajaxcommon/opennotes", success: function(data){ if (data == 'y') { $.ajax({ type: "GET", url: "../ajaxcommon/modal-view2-mobile/" + value, success: function(data){ $("#content_inner").html(data).trigger('create').show(); $('#content_inner').find('h4').css('color','blue'); $("#navigation_header_back").attr('data-nosh-origin', 'Chart'); $("#navigation_header_back").attr('data-nosh-scroll', scroll); $("#chart_header").hide(); $("#navigation_header").show(); $("#left_panel").panel('close'); $.mobile.loading("hide"); } }); } else { $toastr.error('You cannot view the encounter as your provider has not activated OpenNotes.'); $.mobile.loading("hide"); return false; } } }); } } else { toastr.error('Encounter is not signed. You cannot view it at this time.'); $.mobile.loading("hide"); return false; } } else if (type == 't_messages_id') { if (status == 'Yes') { if (acl) { $("#content_inner_main").hide(); $.ajax({ type: "GET", url: "../ajaxcommon/tmessages-view/" + value, success: function(data){ $("#content_inner").html(data).trigger('create').show(); $('#content_inner').find('strong').css('color','blue'); $("#navigation_header_back").attr('data-nosh-origin', 'Chart'); $("#navigation_header_back").attr('data-nosh-scroll', scroll); $("#chart_header").hide(); $("#navigation_header").show(); $("#left_panel").panel('close'); $.mobile.loading("hide"); } }); //$("#message_view").load('ajaxcommon/tmessages-view/' + value); //$("#t_messages_id").val(value); //t_messages_tags(); //$("#messages_view_dialog").dialog('open'); } else { $("#content_inner_main").hide(); $.ajax({ type: "POST", url: "../ajaxcommon/opennotes", success: function(data){ if (data == 'y') { $.ajax({ type: "GET", url: "../ajaxcommon/tmessages-view/" + value, success: function(data){ $("#content_inner").html(data).trigger('create').show(); $('#content_inner').find('strong').css('color','blue'); $("#navigation_header_back").attr('data-nosh-origin', 'Chart'); $("#navigation_header_back").attr('data-nosh-scroll', scroll); $("#chart_header").hide(); $("#navigation_header").show(); $("#left_panel").panel('close'); $.mobile.loading("hide"); } }); //$("#t_messages_id").val(value); //$("#messages_view_dialog").dialog('open'); } else { toastr.error('You cannot view the message as your provider has not activated OpenNotes.'); $.mobile.loading("hide"); return false; } } }); } } else { toastr.error('Message is not signed. You cannot view it at this time.'); $.mobile.loading("hide"); return false; } } }); $(document).on("click", ".messaging_tab", function(e) { var tab = $(this).attr('data-tab'); open_messaging(tab); $("#edit_content").hide(); $("#content").show(); }); $(document).on("click", ".back_message", function(e) { var tab = $(this).attr('data-origin'); var id = $(this).attr('data-origin-id'); open_messaging(tab); $("#view_content").hide(); $("#edit_content").hide(); $("#content").show(); var scroll = parseInt($('.nosh_messaging_item[data-nosh-message-id="' + id + '"]').offset().top); $.mobile.silentScroll(scroll-70); }); $(document).on("click", ".reply_message", function(e) { var form = {}; $.each($(this).get(0).attributes, function(i, attr) { if (attr.name.indexOf("data-nosh-") == '0') { var field = attr.name.replace('data-nosh-',''); field = field.replace(/-/g, '_'); form[field] = attr.value; if (attr.value != 'undefined') { if (attr.value != 'null') { if (field != 'timestamp') { var value = attr.value; if (field == 'date') { value = moment(new Date(value)).format('YYYY-MM-DD'); } $('input[name="' + field + '"]').val(value); } } } } }); $.ajax({ type: "POST", url: "ajaxmessaging/get-displayname", data: "id=" + form['message_from'], success: function(data){ $('select[name="messages_to[]"]').val(data); $('select[name="messages_to[]"]').selectmenu('refresh'); var subject = 'Re: ' + form['subject']; $('input[name="subject"]').val(subject); var newbody = '\n\n' + 'On ' + form['date'] + ', ' + data + ' wrote:\n---------------------------------\n' + form['body']; $('textarea[name="body"]').val(newbody).caret(0); $('textarea[name="body"]').focus(); $("#view_content").hide(); $("#content").hide(); $("#edit_content").show(); } }); }); $(document).on("click", ".reply_all_message", function(e) { var form = {}; $.each($(this).get(0).attributes, function(i, attr) { if (attr.name.indexOf("data-nosh-") == '0') { var field = attr.name.replace('data-nosh-',''); field = field.replace(/-/g, '_'); form[field] = attr.value; if (attr.value != 'undefined') { if (attr.value != 'null') { if (field != 'timestamp') { var value = attr.value; if (field == 'date') { value = moment(new Date(value)).format('YYYY-MM-DD'); } $('input[name="' + field + '"]').val(value); } } } } }); if (form['cc'] == ''){ $.ajax({ type: "POST", url: "ajaxmessaging/get-displayname", data: "id=" + form['message_from'], success: function(data){ $('select[name="messages_to[]"]').val(data); $('select[name="messages_to[]"]').selectmenu('refresh'); var subject = 'Re: ' + form['subject']; $('input[name="subject"]').val(subject); var newbody = '\n\n' + 'On ' + form['date'] + ', ' + data + ' wrote:\n---------------------------------\n' + form['body']; $('textarea[name="body"]').val(newbody).caret(0); $('textarea[name="body"]').focus(); $("#view_content").hide(); $("#content").hide(); $("#edit_content").show(); } }); } else { var to1 = to + ';' + cc; $.ajax({ type: "POST", url: ".ajaxmessaging/get-displayname1", data: "id=" + form['message_from'] + ';' + form['cc'], success: function(data){ var a_array = String(data).split(";"); $('select[name="messages_to[]"]').val(a_array); $('select[name="messages_to[]"]').selectmenu('refresh'); //var a_length = a_array.length; //for (var i = 0; i < a_length; i++) { //$('select[name="messages_to[]"]').selectOptions(a_array[i]); //} var subject = 'Re: ' + form['subject']; $('input[name="subject"]').val(subject); var newbody = '\n\n' + 'On ' + form['date'] + ', ' + data + ' wrote:\n---------------------------------\n' + form['body']; $('textarea[name="body"]').val(newbody).caret(0); $('textarea[name="body"]').focus(); $("#view_content").hide(); $("#content").hide(); $("#edit_content").show(); } }); } }); $(document).on("click", ".forward_message", function(e) { var form = {}; $.each($(this).get(0).attributes, function(i, attr) { if (attr.name.indexOf("data-nosh-") == '0') { var field = attr.name.replace('data-nosh-',''); field = field.replace(/-/g, '_'); form[field] = attr.value; if (attr.value != 'undefined') { if (attr.value != 'null') { if (field != 'timestamp') { var value = attr.value; if (field == 'date') { value = moment(new Date(value)).format('YYYY-MM-DD'); } $('input[name="' + field + '"]').val(value); } } } } }); var rawtext = 'From: ' + form['message_from_label'] + '\nDate: ' + form['date'] + '\nSubject: ' + form['subject'] + '\n\nMessage: ' + form['body']; var subject = 'Fwd: ' + form['subject']; $('input[name="subject"]').val(subject); var newbody = '\n\n' + 'On ' + form['date'] + ', ' + data + ' wrote:\n---------------------------------\n' + form['body']; $('input[name="body"]').val(newbody).caret(0); $('input[name="messages_to"]').focus(); $("#view_content").hide(); $("#content").hide(); $("#edit_content").show(); }); $(document).on("click", ".template_click", function(e) { $.mobile.loading("show"); //var id = $(this).prev().attr('id'); //console.log(id); var id = 'hpi'; $.mobile.loading("show"); $.ajax({ url: "ajaxsearch/textdump-group/" + id, type: "POST" }) .then(function(response) { $("#textdump_group_html").html(''); $("#textdump_group_html").append(response); $("#textdump_group_html").children().css({"padding":"6px"}); $("#textdump_group_html").children().not(':last-child').css({"border-width":"2px","border-bottom":"2px black solid"}); $(".edittextgroup").html('<i class="zmdi zmdi-edit"></i>').addClass('ui-btn ui-btn-inline'); $(".deletetextgroup").html('<i class="zmdi zmdi-delete"></i>').addClass('ui-btn ui-btn-inline'); $(".normaltextgroup").each(function(){ $item = $(this); $nextdiv = $(this).parent().next(); $($item).next('label').html('ALL NORMAL').css('color','blue').andSelf().wrapAll('<fieldset data-role="controlgroup" data-type="horizontal" data-mini="true"></fieldset>').parent().prependTo($nextdiv); }); $(".restricttextgroup").html('<i class="zmdi zmdi-close"></i>').addClass('ui-btn ui-btn-inline'); $("#textdump_group_target").val(id); $('#textdump_group_html_div').css('overflow-y', 'scroll'); $.mobile.loading("hide"); $("#textdump_group_html").trigger('create'); $('#textdump_group_html_div').popup('open'); }); }); $('#textdump_group_html_div').on({ popupbeforeposition: function() { var maxHeight = $(window).height() - 30; $('#textdump_group_html_div').css('max-height', maxHeight + 'px'); } }); $(document).on('click', '.textdump_group_item', function(){ $.mobile.loading("show"); var id = $("#textdump_group_target").val(); var group = $(this).text(); $("#textdump_group_item").val(group); var id1 = $(this).attr('id'); $("#textdump_group_id").val(id1); $.ajax({ type: "POST", url: "ajaxsearch/textdump/" + id, data: 'group='+group }) .then(function(response) { $("#textdump_html").html(''); $("#textdump_html").append(response); $("#textdump_html").children().css({"padding":"6px"}); $("#textdump_html").children().not(':last-child').css({"border-width":"2px","border-bottom":"2px black solid"}); $(".edittexttemplate").html('<i class="zmdi zmdi-edit"></i>').addClass('ui-btn ui-btn-inline'); $(".deletetexttemplate").html('<i class="zmdi zmdi-delete"></i>').addClass('ui-btn ui-btn-inline'); $(".normaltexttemplate").each(function(){ $item = $(this); $nextdiv = $(this).parent(); $($item).next('label').html('DEFAULT').css('color','blue').andSelf().wrapAll('<fieldset data-role="controlgroup" data-type="horizontal" data-mini="true"></fieldset>').parent().prependTo($nextdiv); }); // $(".normaltexttemplate").button({text: false, icons: {primary: "ui-icon-check"}}); // $('.textdump_item_text').editable('destroy'); // $('.textdump_item_text').editable({ // toggle:'manual', // ajaxOptions: { // headers: {"cache-control":"no-cache"}, // beforeSend: function(request) { // return request.setRequestHeader("X-CSRF-Token", $("meta[name='token']").attr('content')); // }, // error: function(xhr) { // if (xhr.status == "404" ) { // alert("Route not found!"); // //window.location.replace(noshdata.error); // } else { // if(xhr.responseText){ // var response1 = $.parseJSON(xhr.responseText); // var error = "Error:\nType: " + response1.error.type + "\nMessage: " + response1.error.message + "\nFile: " + response1.error.file; // alert(error); // } // } // } // } // }); $("#textdump_target").val(id); $('#textdump_html_div').css('overflow-y', 'scroll'); $.mobile.loading("hide"); $("#textdump_html").trigger('create'); $('#textdump_group_html_div').popup('close'); $('#textdump_html_div').popup('open'); }); }); $('#textdump_html_div').on({ popupbeforeposition: function() { var maxHeight = $(window).height() - 30; $('#textdump_html_div').css('max-height', maxHeight + 'px'); } }); /*! jQuery UI - v1.11.1 - 2014-09-10 * http://jqueryui.com * Includes: core.js, datepicker.js * Copyright 2014 jQuery Foundation and other contributors; Licensed MIT */ (function( factory ) { if ( typeof define === "function" && define.amd ) { // AMD. Register as an anonymous module. define([ "jquery" ], factory ); } else { // Browser globals factory( jQuery ); } }(function( $ ) { /*! * jQuery UI Core 1.11.1 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/category/ui-core/ */ // $.ui might exist from components with no dependencies, e.g., $.ui.position $.ui = $.ui || {}; $.extend( $.ui, { version: "1.11.1", keyCode: { BACKSPACE: 8, COMMA: 188, DELETE: 46, DOWN: 40, END: 35, ENTER: 13, ESCAPE: 27, HOME: 36, LEFT: 37, PAGE_DOWN: 34, PAGE_UP: 33, PERIOD: 190, RIGHT: 39, SPACE: 32, TAB: 9, UP: 38 } }); // plugins $.fn.extend({ scrollParent: function( includeHidden ) { var position = this.css( "position" ), excludeStaticParent = position === "absolute", overflowRegex = includeHidden ? /(auto|scroll|hidden)/ : /(auto|scroll)/, scrollParent = this.parents().filter( function() { var parent = $( this ); if ( excludeStaticParent && parent.css( "position" ) === "static" ) { return false; } return overflowRegex.test( parent.css( "overflow" ) + parent.css( "overflow-y" ) + parent.css( "overflow-x" ) ); }).eq( 0 ); return position === "fixed" || !scrollParent.length ? $( this[ 0 ].ownerDocument || document ) : scrollParent; }, uniqueId: (function() { var uuid = 0; return function() { return this.each(function() { if ( !this.id ) { this.id = "ui-id-" + ( ++uuid ); } }); }; })(), removeUniqueId: function() { return this.each(function() { if ( /^ui-id-\d+$/.test( this.id ) ) { $( this ).removeAttr( "id" ); } }); } }); // selectors function focusable( element, isTabIndexNotNaN ) { var map, mapName, img, nodeName = element.nodeName.toLowerCase(); if ( "area" === nodeName ) { map = element.parentNode; mapName = map.name; if ( !element.href || !mapName || map.nodeName.toLowerCase() !== "map" ) { return false; } img = $( "img[usemap='#" + mapName + "']" )[ 0 ]; return !!img && visible( img ); } return ( /input|select|textarea|button|object/.test( nodeName ) ? !element.disabled : "a" === nodeName ? element.href || isTabIndexNotNaN : isTabIndexNotNaN) && // the element and all of its ancestors must be visible visible( element ); } function visible( element ) { return $.expr.filters.visible( element ) && !$( element ).parents().addBack().filter(function() { return $.css( this, "visibility" ) === "hidden"; }).length; } $.extend( $.expr[ ":" ], { data: $.expr.createPseudo ? $.expr.createPseudo(function( dataName ) { return function( elem ) { return !!$.data( elem, dataName ); }; }) : // support: jQuery <1.8 function( elem, i, match ) { return !!$.data( elem, match[ 3 ] ); }, focusable: function( element ) { return focusable( element, !isNaN( $.attr( element, "tabindex" ) ) ); }, tabbable: function( element ) { var tabIndex = $.attr( element, "tabindex" ), isTabIndexNaN = isNaN( tabIndex ); return ( isTabIndexNaN || tabIndex >= 0 ) && focusable( element, !isTabIndexNaN ); } }); // support: jQuery <1.8 if ( !$( "<a>" ).outerWidth( 1 ).jquery ) { $.each( [ "Width", "Height" ], function( i, name ) { var side = name === "Width" ? [ "Left", "Right" ] : [ "Top", "Bottom" ], type = name.toLowerCase(), orig = { innerWidth: $.fn.innerWidth, innerHeight: $.fn.innerHeight, outerWidth: $.fn.outerWidth, outerHeight: $.fn.outerHeight }; function reduce( elem, size, border, margin ) { $.each( side, function() { size -= parseFloat( $.css( elem, "padding" + this ) ) || 0; if ( border ) { size -= parseFloat( $.css( elem, "border" + this + "Width" ) ) || 0; } if ( margin ) { size -= parseFloat( $.css( elem, "margin" + this ) ) || 0; } }); return size; } $.fn[ "inner" + name ] = function( size ) { if ( size === undefined ) { return orig[ "inner" + name ].call( this ); } return this.each(function() { $( this ).css( type, reduce( this, size ) + "px" ); }); }; $.fn[ "outer" + name] = function( size, margin ) { if ( typeof size !== "number" ) { return orig[ "outer" + name ].call( this, size ); } return this.each(function() { $( this).css( type, reduce( this, size, true, margin ) + "px" ); }); }; }); } // support: jQuery <1.8 if ( !$.fn.addBack ) { $.fn.addBack = function( selector ) { return this.add( selector == null ? this.prevObject : this.prevObject.filter( selector ) ); }; } // support: jQuery 1.6.1, 1.6.2 (http://bugs.jquery.com/ticket/9413) if ( $( "<a>" ).data( "a-b", "a" ).removeData( "a-b" ).data( "a-b" ) ) { $.fn.removeData = (function( removeData ) { return function( key ) { if ( arguments.length ) { return removeData.call( this, $.camelCase( key ) ); } else { return removeData.call( this ); } }; })( $.fn.removeData ); } // deprecated $.ui.ie = !!/msie [\w.]+/.exec( navigator.userAgent.toLowerCase() ); $.fn.extend({ focus: (function( orig ) { return function( delay, fn ) { return typeof delay === "number" ? this.each(function() { var elem = this; setTimeout(function() { $( elem ).focus(); if ( fn ) { fn.call( elem ); } }, delay ); }) : orig.apply( this, arguments ); }; })( $.fn.focus ), disableSelection: (function() { var eventType = "onselectstart" in document.createElement( "div" ) ? "selectstart" : "mousedown"; return function() { return this.bind( eventType + ".ui-disableSelection", function( event ) { event.preventDefault(); }); }; })(), enableSelection: function() { return this.unbind( ".ui-disableSelection" ); }, zIndex: function( zIndex ) { if ( zIndex !== undefined ) { return this.css( "zIndex", zIndex ); } if ( this.length ) { var elem = $( this[ 0 ] ), position, value; while ( elem.length && elem[ 0 ] !== document ) { // Ignore z-index if position is set to a value where z-index is ignored by the browser // This makes behavior of this function consistent across browsers // WebKit always returns auto if the element is positioned position = elem.css( "position" ); if ( position === "absolute" || position === "relative" || position === "fixed" ) { // IE returns 0 when zIndex is not specified // other browsers return a string // we ignore the case of nested elements with an explicit value of 0 // <div style="z-index: -10;"><div style="z-index: 0;"></div></div> value = parseInt( elem.css( "zIndex" ), 10 ); if ( !isNaN( value ) && value !== 0 ) { return value; } } elem = elem.parent(); } } return 0; } }); // $.ui.plugin is deprecated. Use $.widget() extensions instead. $.ui.plugin = { add: function( module, option, set ) { var i, proto = $.ui[ module ].prototype; for ( i in set ) { proto.plugins[ i ] = proto.plugins[ i ] || []; proto.plugins[ i ].push( [ option, set[ i ] ] ); } }, call: function( instance, name, args, allowDisconnected ) { var i, set = instance.plugins[ name ]; if ( !set ) { return; } if ( !allowDisconnected && ( !instance.element[ 0 ].parentNode || instance.element[ 0 ].parentNode.nodeType === 11 ) ) { return; } for ( i = 0; i < set.length; i++ ) { if ( instance.options[ set[ i ][ 0 ] ] ) { set[ i ][ 1 ].apply( instance.element, args ); } } } }; /*! * jQuery UI Datepicker 1.11.1 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/datepicker/ */ $.extend($.ui, { datepicker: { version: "1.11.1" } }); var datepicker_instActive; function datepicker_getZindex( elem ) { var position, value; while ( elem.length && elem[ 0 ] !== document ) { // Ignore z-index if position is set to a value where z-index is ignored by the browser // This makes behavior of this function consistent across browsers // WebKit always returns auto if the element is positioned position = elem.css( "position" ); if ( position === "absolute" || position === "relative" || position === "fixed" ) { // IE returns 0 when zIndex is not specified // other browsers return a string // we ignore the case of nested elements with an explicit value of 0 // <div style="z-index: -10;"><div style="z-index: 0;"></div></div> value = parseInt( elem.css( "zIndex" ), 10 ); if ( !isNaN( value ) && value !== 0 ) { return value; } } elem = elem.parent(); } return 0; } /* Date picker manager. Use the singleton instance of this class, $.datepicker, to interact with the date picker. Settings for (groups of) date pickers are maintained in an instance object, allowing multiple different settings on the same page. */ function Datepicker() { this._curInst = null; // The current instance in use this._keyEvent = false; // If the last event was a key event this._disabledInputs = []; // List of date picker inputs that have been disabled this._datepickerShowing = false; // True if the popup picker is showing , false if not this._inDialog = false; // True if showing within a "dialog", false if not this._mainDivId = "ui-datepicker-div"; // The ID of the main datepicker division this._inlineClass = "ui-datepicker-inline"; // The name of the inline marker class this._appendClass = "ui-datepicker-append"; // The name of the append marker class this._triggerClass = "ui-datepicker-trigger"; // The name of the trigger marker class this._dialogClass = "ui-datepicker-dialog"; // The name of the dialog marker class this._disableClass = "ui-datepicker-disabled"; // The name of the disabled covering marker class this._unselectableClass = "ui-datepicker-unselectable"; // The name of the unselectable cell marker class this._currentClass = "ui-datepicker-current-day"; // The name of the current day marker class this._dayOverClass = "ui-datepicker-days-cell-over"; // The name of the day hover marker class this.regional = []; // Available regional settings, indexed by language code this.regional[""] = { // Default regional settings closeText: "Done", // Display text for close link prevText: "Prev", // Display text for previous month link nextText: "Next", // Display text for next month link currentText: "Today", // Display text for current month link monthNames: ["January","February","March","April","May","June", "July","August","September","October","November","December"], // Names of months for drop-down and formatting monthNamesShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], // For formatting dayNames: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"], // For formatting dayNamesShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"], // For formatting dayNamesMin: ["Su","Mo","Tu","We","Th","Fr","Sa"], // Column headings for days starting at Sunday weekHeader: "Wk", // Column header for week of the year dateFormat: "mm/dd/yy", // See format options on parseDate firstDay: 0, // The first day of the week, Sun = 0, Mon = 1, ... isRTL: false, // True if right-to-left language, false if left-to-right showMonthAfterYear: false, // True if the year select precedes month, false for month then year yearSuffix: "" // Additional text to append to the year in the month headers }; this._defaults = { // Global defaults for all the date picker instances showOn: "focus", // "focus" for popup on focus, // "button" for trigger button, or "both" for either showAnim: "fadeIn", // Name of jQuery animation for popup showOptions: {}, // Options for enhanced animations defaultDate: null, // Used when field is blank: actual date, // +/-number for offset from today, null for today appendText: "", // Display text following the input box, e.g. showing the format buttonText: "...", // Text for trigger button buttonImage: "", // URL for trigger button image buttonImageOnly: false, // True if the image appears alone, false if it appears on a button hideIfNoPrevNext: false, // True to hide next/previous month links // if not applicable, false to just disable them navigationAsDateFormat: false, // True if date formatting applied to prev/today/next links gotoCurrent: false, // True if today link goes back to current selection instead changeMonth: false, // True if month can be selected directly, false if only prev/next changeYear: false, // True if year can be selected directly, false if only prev/next yearRange: "c-10:c+10", // Range of years to display in drop-down, // either relative to today's year (-nn:+nn), relative to currently displayed year // (c-nn:c+nn), absolute (nnnn:nnnn), or a combination of the above (nnnn:-n) showOtherMonths: false, // True to show dates in other months, false to leave blank selectOtherMonths: false, // True to allow selection of dates in other months, false for unselectable showWeek: false, // True to show week of the year, false to not show it calculateWeek: this.iso8601Week, // How to calculate the week of the year, // takes a Date and returns the number of the week for it shortYearCutoff: "+10", // Short year values < this are in the current century, // > this are in the previous century, // string value starting with "+" for current year + value minDate: null, // The earliest selectable date, or null for no limit maxDate: null, // The latest selectable date, or null for no limit duration: "fast", // Duration of display/closure beforeShowDay: null, // Function that takes a date and returns an array with // [0] = true if selectable, false if not, [1] = custom CSS class name(s) or "", // [2] = cell title (optional), e.g. $.datepicker.noWeekends beforeShow: null, // Function that takes an input field and // returns a set of custom settings for the date picker onSelect: null, // Define a callback function when a date is selected onChangeMonthYear: null, // Define a callback function when the month or year is changed onClose: null, // Define a callback function when the datepicker is closed numberOfMonths: 1, // Number of months to show at a time showCurrentAtPos: 0, // The position in multipe months at which to show the current month (starting at 0) stepMonths: 1, // Number of months to step back/forward stepBigMonths: 12, // Number of months to step back/forward for the big links altField: "", // Selector for an alternate field to store selected dates into altFormat: "", // The date format to use for the alternate field constrainInput: true, // The input is constrained by the current date format showButtonPanel: false, // True to show button panel, false to not show it autoSize: false, // True to size the input for the date format, false to leave as is disabled: false // The initial disabled state }; $.extend(this._defaults, this.regional[""]); this.regional.en = $.extend( true, {}, this.regional[ "" ]); this.regional[ "en-US" ] = $.extend( true, {}, this.regional.en ); this.dpDiv = datepicker_bindHover($("<div id='" + this._mainDivId + "' class='ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all'></div>")); } $.extend(Datepicker.prototype, { /* Class name added to elements to indicate already configured with a date picker. */ markerClassName: "hasDatepicker", //Keep track of the maximum number of rows displayed (see #7043) maxRows: 4, // TODO rename to "widget" when switching to widget factory _widgetDatepicker: function() { return this.dpDiv; }, /* Override the default settings for all instances of the date picker. * @param settings object - the new settings to use as defaults (anonymous object) * @return the manager object */ setDefaults: function(settings) { datepicker_extendRemove(this._defaults, settings || {}); return this; }, /* Attach the date picker to a jQuery selection. * @param target element - the target input field or division or span * @param settings object - the new settings to use for this date picker instance (anonymous) */ _attachDatepicker: function(target, settings) { var nodeName, inline, inst; nodeName = target.nodeName.toLowerCase(); inline = (nodeName === "div" || nodeName === "span"); if (!target.id) { this.uuid += 1; target.id = "dp" + this.uuid; } inst = this._newInst($(target), inline); inst.settings = $.extend({}, settings || {}); if (nodeName === "input") { this._connectDatepicker(target, inst); } else if (inline) { this._inlineDatepicker(target, inst); } }, /* Create a new instance object. */ _newInst: function(target, inline) { var id = target[0].id.replace(/([^A-Za-z0-9_\-])/g, "\\\\$1"); // escape jQuery meta chars return {id: id, input: target, // associated target selectedDay: 0, selectedMonth: 0, selectedYear: 0, // current selection drawMonth: 0, drawYear: 0, // month being drawn inline: inline, // is datepicker inline or not dpDiv: (!inline ? this.dpDiv : // presentation div datepicker_bindHover($("<div class='" + this._inlineClass + " ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all'></div>")))}; }, /* Attach the date picker to an input field. */ _connectDatepicker: function(target, inst) { var input = $(target); inst.append = $([]); inst.trigger = $([]); if (input.hasClass(this.markerClassName)) { return; } this._attachments(input, inst); input.addClass(this.markerClassName).keydown(this._doKeyDown). keypress(this._doKeyPress).keyup(this._doKeyUp); this._autoSize(inst); $.data(target, "datepicker", inst); //If disabled option is true, disable the datepicker once it has been attached to the input (see ticket #5665) if( inst.settings.disabled ) { this._disableDatepicker( target ); } }, /* Make attachments based on settings. */ _attachments: function(input, inst) { var showOn, buttonText, buttonImage, appendText = this._get(inst, "appendText"), isRTL = this._get(inst, "isRTL"); if (inst.append) { inst.append.remove(); } if (appendText) { inst.append = $("<span class='" + this._appendClass + "'>" + appendText + "</span>"); input[isRTL ? "before" : "after"](inst.append); } input.unbind("focus", this._showDatepicker); if (inst.trigger) { inst.trigger.remove(); } showOn = this._get(inst, "showOn"); if (showOn === "focus" || showOn === "both") { // pop-up date picker when in the marked field input.focus(this._showDatepicker); } if (showOn === "button" || showOn === "both") { // pop-up date picker when button clicked buttonText = this._get(inst, "buttonText"); buttonImage = this._get(inst, "buttonImage"); inst.trigger = $(this._get(inst, "buttonImageOnly") ? $("<img/>").addClass(this._triggerClass). attr({ src: buttonImage, alt: buttonText, title: buttonText }) : $("<button type='button'></button>").addClass(this._triggerClass). html(!buttonImage ? buttonText : $("<img/>").attr( { src:buttonImage, alt:buttonText, title:buttonText }))); input[isRTL ? "before" : "after"](inst.trigger); inst.trigger.click(function() { if ($.datepicker._datepickerShowing && $.datepicker._lastInput === input[0]) { $.datepicker._hideDatepicker(); } else if ($.datepicker._datepickerShowing && $.datepicker._lastInput !== input[0]) { $.datepicker._hideDatepicker(); $.datepicker._showDatepicker(input[0]); } else { $.datepicker._showDatepicker(input[0]); } return false; }); } }, /* Apply the maximum length for the date format. */ _autoSize: function(inst) { if (this._get(inst, "autoSize") && !inst.inline) { var findMax, max, maxI, i, date = new Date(2009, 12 - 1, 20), // Ensure double digits dateFormat = this._get(inst, "dateFormat"); if (dateFormat.match(/[DM]/)) { findMax = function(names) { max = 0; maxI = 0; for (i = 0; i < names.length; i++) { if (names[i].length > max) { max = names[i].length; maxI = i; } } return maxI; }; date.setMonth(findMax(this._get(inst, (dateFormat.match(/MM/) ? "monthNames" : "monthNamesShort")))); date.setDate(findMax(this._get(inst, (dateFormat.match(/DD/) ? "dayNames" : "dayNamesShort"))) + 20 - date.getDay()); } inst.input.attr("size", this._formatDate(inst, date).length); } }, /* Attach an inline date picker to a div. */ _inlineDatepicker: function(target, inst) { var divSpan = $(target); if (divSpan.hasClass(this.markerClassName)) { return; } divSpan.addClass(this.markerClassName).append(inst.dpDiv); $.data(target, "datepicker", inst); this._setDate(inst, this._getDefaultDate(inst), true); this._updateDatepicker(inst); this._updateAlternate(inst); //If disabled option is true, disable the datepicker before showing it (see ticket #5665) if( inst.settings.disabled ) { this._disableDatepicker( target ); } // Set display:block in place of inst.dpDiv.show() which won't work on disconnected elements // http://bugs.jqueryui.com/ticket/7552 - A Datepicker created on a detached div has zero height inst.dpDiv.css( "display", "block" ); }, /* Pop-up the date picker in a "dialog" box. * @param input element - ignored * @param date string or Date - the initial date to display * @param onSelect function - the function to call when a date is selected * @param settings object - update the dialog date picker instance's settings (anonymous object) * @param pos int[2] - coordinates for the dialog's position within the screen or * event - with x/y coordinates or * leave empty for default (screen centre) * @return the manager object */ _dialogDatepicker: function(input, date, onSelect, settings, pos) { var id, browserWidth, browserHeight, scrollX, scrollY, inst = this._dialogInst; // internal instance if (!inst) { this.uuid += 1; id = "dp" + this.uuid; this._dialogInput = $("<input type='text' id='" + id + "' style='position: absolute; top: -100px; width: 0px;'/>"); this._dialogInput.keydown(this._doKeyDown); $("body").append(this._dialogInput); inst = this._dialogInst = this._newInst(this._dialogInput, false); inst.settings = {}; $.data(this._dialogInput[0], "datepicker", inst); } datepicker_extendRemove(inst.settings, settings || {}); date = (date && date.constructor === Date ? this._formatDate(inst, date) : date); this._dialogInput.val(date); this._pos = (pos ? (pos.length ? pos : [pos.pageX, pos.pageY]) : null); if (!this._pos) { browserWidth = document.documentElement.clientWidth; browserHeight = document.documentElement.clientHeight; scrollX = document.documentElement.scrollLeft || document.body.scrollLeft; scrollY = document.documentElement.scrollTop || document.body.scrollTop; this._pos = // should use actual width/height below [(browserWidth / 2) - 100 + scrollX, (browserHeight / 2) - 150 + scrollY]; } // move input on screen for focus, but hidden behind dialog this._dialogInput.css("left", (this._pos[0] + 20) + "px").css("top", this._pos[1] + "px"); inst.settings.onSelect = onSelect; this._inDialog = true; this.dpDiv.addClass(this._dialogClass); this._showDatepicker(this._dialogInput[0]); if ($.blockUI) { $.blockUI(this.dpDiv); } $.data(this._dialogInput[0], "datepicker", inst); return this; }, /* Detach a datepicker from its control. * @param target element - the target input field or division or span */ _destroyDatepicker: function(target) { var nodeName, $target = $(target), inst = $.data(target, "datepicker"); if (!$target.hasClass(this.markerClassName)) { return; } nodeName = target.nodeName.toLowerCase(); $.removeData(target, "datepicker"); if (nodeName === "input") { inst.append.remove(); inst.trigger.remove(); $target.removeClass(this.markerClassName). unbind("focus", this._showDatepicker). unbind("keydown", this._doKeyDown). unbind("keypress", this._doKeyPress). unbind("keyup", this._doKeyUp); } else if (nodeName === "div" || nodeName === "span") { $target.removeClass(this.markerClassName).empty(); } }, /* Enable the date picker to a jQuery selection. * @param target element - the target input field or division or span */ _enableDatepicker: function(target) { var nodeName, inline, $target = $(target), inst = $.data(target, "datepicker"); if (!$target.hasClass(this.markerClassName)) { return; } nodeName = target.nodeName.toLowerCase(); if (nodeName === "input") { target.disabled = false; inst.trigger.filter("button"). each(function() { this.disabled = false; }).end(). filter("img").css({opacity: "1.0", cursor: ""}); } else if (nodeName === "div" || nodeName === "span") { inline = $target.children("." + this._inlineClass); inline.children().removeClass("ui-state-disabled"); inline.find("select.ui-datepicker-month, select.ui-datepicker-year"). prop("disabled", false); } this._disabledInputs = $.map(this._disabledInputs, function(value) { return (value === target ? null : value); }); // delete entry }, /* Disable the date picker to a jQuery selection. * @param target element - the target input field or division or span */ _disableDatepicker: function(target) { var nodeName, inline, $target = $(target), inst = $.data(target, "datepicker"); if (!$target.hasClass(this.markerClassName)) { return; } nodeName = target.nodeName.toLowerCase(); if (nodeName === "input") { target.disabled = true; inst.trigger.filter("button"). each(function() { this.disabled = true; }).end(). filter("img").css({opacity: "0.5", cursor: "default"}); } else if (nodeName === "div" || nodeName === "span") { inline = $target.children("." + this._inlineClass); inline.children().addClass("ui-state-disabled"); inline.find("select.ui-datepicker-month, select.ui-datepicker-year"). prop("disabled", true); } this._disabledInputs = $.map(this._disabledInputs, function(value) { return (value === target ? null : value); }); // delete entry this._disabledInputs[this._disabledInputs.length] = target; }, /* Is the first field in a jQuery collection disabled as a datepicker? * @param target element - the target input field or division or span * @return boolean - true if disabled, false if enabled */ _isDisabledDatepicker: function(target) { if (!target) { return false; } for (var i = 0; i < this._disabledInputs.length; i++) { if (this._disabledInputs[i] === target) { return true; } } return false; }, /* Retrieve the instance data for the target control. * @param target element - the target input field or division or span * @return object - the associated instance data * @throws error if a jQuery problem getting data */ _getInst: function(target) { try { return $.data(target, "datepicker"); } catch (err) { throw "Missing instance data for this datepicker"; } }, /* Update or retrieve the settings for a date picker attached to an input field or division. * @param target element - the target input field or division or span * @param name object - the new settings to update or * string - the name of the setting to change or retrieve, * when retrieving also "all" for all instance settings or * "defaults" for all global defaults * @param value any - the new value for the setting * (omit if above is an object or to retrieve a value) */ _optionDatepicker: function(target, name, value) { var settings, date, minDate, maxDate, inst = this._getInst(target); if (arguments.length === 2 && typeof name === "string") { return (name === "defaults" ? $.extend({}, $.datepicker._defaults) : (inst ? (name === "all" ? $.extend({}, inst.settings) : this._get(inst, name)) : null)); } settings = name || {}; if (typeof name === "string") { settings = {}; settings[name] = value; } if (inst) { if (this._curInst === inst) { this._hideDatepicker(); } date = this._getDateDatepicker(target, true); minDate = this._getMinMaxDate(inst, "min"); maxDate = this._getMinMaxDate(inst, "max"); datepicker_extendRemove(inst.settings, settings); // reformat the old minDate/maxDate values if dateFormat changes and a new minDate/maxDate isn't provided if (minDate !== null && settings.dateFormat !== undefined && settings.minDate === undefined) { inst.settings.minDate = this._formatDate(inst, minDate); } if (maxDate !== null && settings.dateFormat !== undefined && settings.maxDate === undefined) { inst.settings.maxDate = this._formatDate(inst, maxDate); } if ( "disabled" in settings ) { if ( settings.disabled ) { this._disableDatepicker(target); } else { this._enableDatepicker(target); } } this._attachments($(target), inst); this._autoSize(inst); this._setDate(inst, date); this._updateAlternate(inst); this._updateDatepicker(inst); } }, // change method deprecated _changeDatepicker: function(target, name, value) { this._optionDatepicker(target, name, value); }, /* Redraw the date picker attached to an input field or division. * @param target element - the target input field or division or span */ _refreshDatepicker: function(target) { var inst = this._getInst(target); if (inst) { this._updateDatepicker(inst); } }, /* Set the dates for a jQuery selection. * @param target element - the target input field or division or span * @param date Date - the new date */ _setDateDatepicker: function(target, date) { var inst = this._getInst(target); if (inst) { this._setDate(inst, date); this._updateDatepicker(inst); this._updateAlternate(inst); } }, /* Get the date(s) for the first entry in a jQuery selection. * @param target element - the target input field or division or span * @param noDefault boolean - true if no default date is to be used * @return Date - the current date */ _getDateDatepicker: function(target, noDefault) { var inst = this._getInst(target); if (inst && !inst.inline) { this._setDateFromField(inst, noDefault); } return (inst ? this._getDate(inst) : null); }, /* Handle keystrokes. */ _doKeyDown: function(event) { var onSelect, dateStr, sel, inst = $.datepicker._getInst(event.target), handled = true, isRTL = inst.dpDiv.is(".ui-datepicker-rtl"); inst._keyEvent = true; if ($.datepicker._datepickerShowing) { switch (event.keyCode) { case 9: $.datepicker._hideDatepicker(); handled = false; break; // hide on tab out case 13: sel = $("td." + $.datepicker._dayOverClass + ":not(." + $.datepicker._currentClass + ")", inst.dpDiv); if (sel[0]) { $.datepicker._selectDay(event.target, inst.selectedMonth, inst.selectedYear, sel[0]); } onSelect = $.datepicker._get(inst, "onSelect"); if (onSelect) { dateStr = $.datepicker._formatDate(inst); // trigger custom callback onSelect.apply((inst.input ? inst.input[0] : null), [dateStr, inst]); } else { $.datepicker._hideDatepicker(); } return false; // don't submit the form case 27: $.datepicker._hideDatepicker(); break; // hide on escape case 33: $.datepicker._adjustDate(event.target, (event.ctrlKey ? -$.datepicker._get(inst, "stepBigMonths") : -$.datepicker._get(inst, "stepMonths")), "M"); break; // previous month/year on page up/+ ctrl case 34: $.datepicker._adjustDate(event.target, (event.ctrlKey ? +$.datepicker._get(inst, "stepBigMonths") : +$.datepicker._get(inst, "stepMonths")), "M"); break; // next month/year on page down/+ ctrl case 35: if (event.ctrlKey || event.metaKey) { $.datepicker._clearDate(event.target); } handled = event.ctrlKey || event.metaKey; break; // clear on ctrl or command +end case 36: if (event.ctrlKey || event.metaKey) { $.datepicker._gotoToday(event.target); } handled = event.ctrlKey || event.metaKey; break; // current on ctrl or command +home case 37: if (event.ctrlKey || event.metaKey) { $.datepicker._adjustDate(event.target, (isRTL ? +1 : -1), "D"); } handled = event.ctrlKey || event.metaKey; // -1 day on ctrl or command +left if (event.originalEvent.altKey) { $.datepicker._adjustDate(event.target, (event.ctrlKey ? -$.datepicker._get(inst, "stepBigMonths") : -$.datepicker._get(inst, "stepMonths")), "M"); } // next month/year on alt +left on Mac break; case 38: if (event.ctrlKey || event.metaKey) { $.datepicker._adjustDate(event.target, -7, "D"); } handled = event.ctrlKey || event.metaKey; break; // -1 week on ctrl or command +up case 39: if (event.ctrlKey || event.metaKey) { $.datepicker._adjustDate(event.target, (isRTL ? -1 : +1), "D"); } handled = event.ctrlKey || event.metaKey; // +1 day on ctrl or command +right if (event.originalEvent.altKey) { $.datepicker._adjustDate(event.target, (event.ctrlKey ? +$.datepicker._get(inst, "stepBigMonths") : +$.datepicker._get(inst, "stepMonths")), "M"); } // next month/year on alt +right break; case 40: if (event.ctrlKey || event.metaKey) { $.datepicker._adjustDate(event.target, +7, "D"); } handled = event.ctrlKey || event.metaKey; break; // +1 week on ctrl or command +down default: handled = false; } } else if (event.keyCode === 36 && event.ctrlKey) { // display the date picker on ctrl+home $.datepicker._showDatepicker(this); } else { handled = false; } if (handled) { event.preventDefault(); event.stopPropagation(); } }, /* Filter entered characters - based on date format. */ _doKeyPress: function(event) { var chars, chr, inst = $.datepicker._getInst(event.target); if ($.datepicker._get(inst, "constrainInput")) { chars = $.datepicker._possibleChars($.datepicker._get(inst, "dateFormat")); chr = String.fromCharCode(event.charCode == null ? event.keyCode : event.charCode); return event.ctrlKey || event.metaKey || (chr < " " || !chars || chars.indexOf(chr) > -1); } }, /* Synchronise manual entry and field/alternate field. */ _doKeyUp: function(event) { var date, inst = $.datepicker._getInst(event.target); if (inst.input.val() !== inst.lastVal) { try { date = $.datepicker.parseDate($.datepicker._get(inst, "dateFormat"), (inst.input ? inst.input.val() : null), $.datepicker._getFormatConfig(inst)); if (date) { // only if valid $.datepicker._setDateFromField(inst); $.datepicker._updateAlternate(inst); $.datepicker._updateDatepicker(inst); } } catch (err) { } } return true; }, /* Pop-up the date picker for a given input field. * If false returned from beforeShow event handler do not show. * @param input element - the input field attached to the date picker or * event - if triggered by focus */ _showDatepicker: function(input) { input = input.target || input; if (input.nodeName.toLowerCase() !== "input") { // find from button/image trigger input = $("input", input.parentNode)[0]; } if ($.datepicker._isDisabledDatepicker(input) || $.datepicker._lastInput === input) { // already here return; } var inst, beforeShow, beforeShowSettings, isFixed, offset, showAnim, duration; inst = $.datepicker._getInst(input); if ($.datepicker._curInst && $.datepicker._curInst !== inst) { $.datepicker._curInst.dpDiv.stop(true, true); if ( inst && $.datepicker._datepickerShowing ) { $.datepicker._hideDatepicker( $.datepicker._curInst.input[0] ); } } beforeShow = $.datepicker._get(inst, "beforeShow"); beforeShowSettings = beforeShow ? beforeShow.apply(input, [input, inst]) : {}; if(beforeShowSettings === false){ return; } datepicker_extendRemove(inst.settings, beforeShowSettings); inst.lastVal = null; $.datepicker._lastInput = input; $.datepicker._setDateFromField(inst); if ($.datepicker._inDialog) { // hide cursor input.value = ""; } if (!$.datepicker._pos) { // position below input $.datepicker._pos = $.datepicker._findPos(input); $.datepicker._pos[1] += input.offsetHeight; // add the height } isFixed = false; $(input).parents().each(function() { isFixed |= $(this).css("position") === "fixed"; return !isFixed; }); offset = {left: $.datepicker._pos[0], top: $.datepicker._pos[1]}; $.datepicker._pos = null; //to avoid flashes on Firefox inst.dpDiv.empty(); // determine sizing offscreen inst.dpDiv.css({position: "absolute", display: "block", top: "-1000px"}); $.datepicker._updateDatepicker(inst); // fix width for dynamic number of date pickers // and adjust position before showing offset = $.datepicker._checkOffset(inst, offset, isFixed); inst.dpDiv.css({position: ($.datepicker._inDialog && $.blockUI ? "static" : (isFixed ? "fixed" : "absolute")), display: "none", left: offset.left + "px", top: offset.top + "px"}); if (!inst.inline) { showAnim = $.datepicker._get(inst, "showAnim"); duration = $.datepicker._get(inst, "duration"); inst.dpDiv.css( "z-index", datepicker_getZindex( $( input ) ) + 1 ); $.datepicker._datepickerShowing = true; if ( $.effects && $.effects.effect[ showAnim ] ) { inst.dpDiv.show(showAnim, $.datepicker._get(inst, "showOptions"), duration); } else { inst.dpDiv[showAnim || "show"](showAnim ? duration : null); } if ( $.datepicker._shouldFocusInput( inst ) ) { inst.input.focus(); } $.datepicker._curInst = inst; } }, /* Generate the date picker content. */ _updateDatepicker: function(inst) { this.maxRows = 4; //Reset the max number of rows being displayed (see #7043) datepicker_instActive = inst; // for delegate hover events inst.dpDiv.empty().append(this._generateHTML(inst)); this._attachHandlers(inst); var origyearshtml, numMonths = this._getNumberOfMonths(inst), cols = numMonths[1], width = 17, activeCell = inst.dpDiv.find( "." + this._dayOverClass + " a" ); if ( activeCell.length > 0 ) { datepicker_handleMouseover.apply( activeCell.get( 0 ) ); } inst.dpDiv.removeClass("ui-datepicker-multi-2 ui-datepicker-multi-3 ui-datepicker-multi-4").width(""); if (cols > 1) { inst.dpDiv.addClass("ui-datepicker-multi-" + cols).css("width", (width * cols) + "em"); } inst.dpDiv[(numMonths[0] !== 1 || numMonths[1] !== 1 ? "add" : "remove") + "Class"]("ui-datepicker-multi"); inst.dpDiv[(this._get(inst, "isRTL") ? "add" : "remove") + "Class"]("ui-datepicker-rtl"); if (inst === $.datepicker._curInst && $.datepicker._datepickerShowing && $.datepicker._shouldFocusInput( inst ) ) { inst.input.focus(); } // deffered render of the years select (to avoid flashes on Firefox) if( inst.yearshtml ){ origyearshtml = inst.yearshtml; setTimeout(function(){ //assure that inst.yearshtml didn't change. if( origyearshtml === inst.yearshtml && inst.yearshtml ){ inst.dpDiv.find("select.ui-datepicker-year:first").replaceWith(inst.yearshtml); } origyearshtml = inst.yearshtml = null; }, 0); } }, // #6694 - don't focus the input if it's already focused // this breaks the change event in IE // Support: IE and jQuery <1.9 _shouldFocusInput: function( inst ) { return inst.input && inst.input.is( ":visible" ) && !inst.input.is( ":disabled" ) && !inst.input.is( ":focus" ); }, /* Check positioning to remain on screen. */ _checkOffset: function(inst, offset, isFixed) { var dpWidth = inst.dpDiv.outerWidth(), dpHeight = inst.dpDiv.outerHeight(), inputWidth = inst.input ? inst.input.outerWidth() : 0, inputHeight = inst.input ? inst.input.outerHeight() : 0, viewWidth = document.documentElement.clientWidth + (isFixed ? 0 : $(document).scrollLeft()), viewHeight = document.documentElement.clientHeight + (isFixed ? 0 : $(document).scrollTop()); offset.left -= (this._get(inst, "isRTL") ? (dpWidth - inputWidth) : 0); offset.left -= (isFixed && offset.left === inst.input.offset().left) ? $(document).scrollLeft() : 0; offset.top -= (isFixed && offset.top === (inst.input.offset().top + inputHeight)) ? $(document).scrollTop() : 0; // now check if datepicker is showing outside window viewport - move to a better place if so. offset.left -= Math.min(offset.left, (offset.left + dpWidth > viewWidth && viewWidth > dpWidth) ? Math.abs(offset.left + dpWidth - viewWidth) : 0); offset.top -= Math.min(offset.top, (offset.top + dpHeight > viewHeight && viewHeight > dpHeight) ? Math.abs(dpHeight + inputHeight) : 0); return offset; }, /* Find an object's position on the screen. */ _findPos: function(obj) { var position, inst = this._getInst(obj), isRTL = this._get(inst, "isRTL"); while (obj && (obj.type === "hidden" || obj.nodeType !== 1 || $.expr.filters.hidden(obj))) { obj = obj[isRTL ? "previousSibling" : "nextSibling"]; } position = $(obj).offset(); return [position.left, position.top]; }, /* Hide the date picker from view. * @param input element - the input field attached to the date picker */ _hideDatepicker: function(input) { var showAnim, duration, postProcess, onClose, inst = this._curInst; if (!inst || (input && inst !== $.data(input, "datepicker"))) { return; } if (this._datepickerShowing) { showAnim = this._get(inst, "showAnim"); duration = this._get(inst, "duration"); postProcess = function() { $.datepicker._tidyDialog(inst); }; // DEPRECATED: after BC for 1.8.x $.effects[ showAnim ] is not needed if ( $.effects && ( $.effects.effect[ showAnim ] || $.effects[ showAnim ] ) ) { inst.dpDiv.hide(showAnim, $.datepicker._get(inst, "showOptions"), duration, postProcess); } else { inst.dpDiv[(showAnim === "slideDown" ? "slideUp" : (showAnim === "fadeIn" ? "fadeOut" : "hide"))]((showAnim ? duration : null), postProcess); } if (!showAnim) { postProcess(); } this._datepickerShowing = false; onClose = this._get(inst, "onClose"); if (onClose) { onClose.apply((inst.input ? inst.input[0] : null), [(inst.input ? inst.input.val() : ""), inst]); } this._lastInput = null; if (this._inDialog) { this._dialogInput.css({ position: "absolute", left: "0", top: "-100px" }); if ($.blockUI) { $.unblockUI(); $("body").append(this.dpDiv); } } this._inDialog = false; } }, /* Tidy up after a dialog display. */ _tidyDialog: function(inst) { inst.dpDiv.removeClass(this._dialogClass).unbind(".ui-datepicker-calendar"); }, /* Close date picker if clicked elsewhere. */ _checkExternalClick: function(event) { if (!$.datepicker._curInst) { return; } var $target = $(event.target), inst = $.datepicker._getInst($target[0]); if ( ( ( $target[0].id !== $.datepicker._mainDivId && $target.parents("#" + $.datepicker._mainDivId).length === 0 && !$target.hasClass($.datepicker.markerClassName) && !$target.closest("." + $.datepicker._triggerClass).length && $.datepicker._datepickerShowing && !($.datepicker._inDialog && $.blockUI) ) ) || ( $target.hasClass($.datepicker.markerClassName) && $.datepicker._curInst !== inst ) ) { $.datepicker._hideDatepicker(); } }, /* Adjust one of the date sub-fields. */ _adjustDate: function(id, offset, period) { var target = $(id), inst = this._getInst(target[0]); if (this._isDisabledDatepicker(target[0])) { return; } this._adjustInstDate(inst, offset + (period === "M" ? this._get(inst, "showCurrentAtPos") : 0), // undo positioning period); this._updateDatepicker(inst); }, /* Action for current link. */ _gotoToday: function(id) { var date, target = $(id), inst = this._getInst(target[0]); if (this._get(inst, "gotoCurrent") && inst.currentDay) { inst.selectedDay = inst.currentDay; inst.drawMonth = inst.selectedMonth = inst.currentMonth; inst.drawYear = inst.selectedYear = inst.currentYear; } else { date = new Date(); inst.selectedDay = date.getDate(); inst.drawMonth = inst.selectedMonth = date.getMonth(); inst.drawYear = inst.selectedYear = date.getFullYear(); } this._notifyChange(inst); this._adjustDate(target); }, /* Action for selecting a new month/year. */ _selectMonthYear: function(id, select, period) { var target = $(id), inst = this._getInst(target[0]); inst["selected" + (period === "M" ? "Month" : "Year")] = inst["draw" + (period === "M" ? "Month" : "Year")] = parseInt(select.options[select.selectedIndex].value,10); this._notifyChange(inst); this._adjustDate(target); }, /* Action for selecting a day. */ _selectDay: function(id, month, year, td) { var inst, target = $(id); if ($(td).hasClass(this._unselectableClass) || this._isDisabledDatepicker(target[0])) { return; } inst = this._getInst(target[0]); inst.selectedDay = inst.currentDay = $("a", td).html(); inst.selectedMonth = inst.currentMonth = month; inst.selectedYear = inst.currentYear = year; this._selectDate(id, this._formatDate(inst, inst.currentDay, inst.currentMonth, inst.currentYear)); }, /* Erase the input field and hide the date picker. */ _clearDate: function(id) { var target = $(id); this._selectDate(target, ""); }, /* Update the input field with the selected date. */ _selectDate: function(id, dateStr) { var onSelect, target = $(id), inst = this._getInst(target[0]); dateStr = (dateStr != null ? dateStr : this._formatDate(inst)); if (inst.input) { inst.input.val(dateStr); } this._updateAlternate(inst); onSelect = this._get(inst, "onSelect"); if (onSelect) { onSelect.apply((inst.input ? inst.input[0] : null), [dateStr, inst]); // trigger custom callback } else if (inst.input) { inst.input.trigger("change"); // fire the change event } if (inst.inline){ this._updateDatepicker(inst); } else { this._hideDatepicker(); this._lastInput = inst.input[0]; if (typeof(inst.input[0]) !== "object") { inst.input.focus(); // restore focus } this._lastInput = null; } }, /* Update any alternate field to synchronise with the main field. */ _updateAlternate: function(inst) { var altFormat, date, dateStr, altField = this._get(inst, "altField"); if (altField) { // update alternate field too altFormat = this._get(inst, "altFormat") || this._get(inst, "dateFormat"); date = this._getDate(inst); dateStr = this.formatDate(altFormat, date, this._getFormatConfig(inst)); $(altField).each(function() { $(this).val(dateStr); }); } }, /* Set as beforeShowDay function to prevent selection of weekends. * @param date Date - the date to customise * @return [boolean, string] - is this date selectable?, what is its CSS class? */ noWeekends: function(date) { var day = date.getDay(); return [(day > 0 && day < 6), ""]; }, /* Set as calculateWeek to determine the week of the year based on the ISO 8601 definition. * @param date Date - the date to get the week for * @return number - the number of the week within the year that contains this date */ iso8601Week: function(date) { var time, checkDate = new Date(date.getTime()); // Find Thursday of this week starting on Monday checkDate.setDate(checkDate.getDate() + 4 - (checkDate.getDay() || 7)); time = checkDate.getTime(); checkDate.setMonth(0); // Compare with Jan 1 checkDate.setDate(1); return Math.floor(Math.round((time - checkDate) / 86400000) / 7) + 1; }, /* Parse a string value into a date object. * See formatDate below for the possible formats. * * @param format string - the expected format of the date * @param value string - the date in the above format * @param settings Object - attributes include: * shortYearCutoff number - the cutoff year for determining the century (optional) * dayNamesShort string[7] - abbreviated names of the days from Sunday (optional) * dayNames string[7] - names of the days from Sunday (optional) * monthNamesShort string[12] - abbreviated names of the months (optional) * monthNames string[12] - names of the months (optional) * @return Date - the extracted date value or null if value is blank */ parseDate: function (format, value, settings) { if (format == null || value == null) { throw "Invalid arguments"; } value = (typeof value === "object" ? value.toString() : value + ""); if (value === "") { return null; } var iFormat, dim, extra, iValue = 0, shortYearCutoffTemp = (settings ? settings.shortYearCutoff : null) || this._defaults.shortYearCutoff, shortYearCutoff = (typeof shortYearCutoffTemp !== "string" ? shortYearCutoffTemp : new Date().getFullYear() % 100 + parseInt(shortYearCutoffTemp, 10)), dayNamesShort = (settings ? settings.dayNamesShort : null) || this._defaults.dayNamesShort, dayNames = (settings ? settings.dayNames : null) || this._defaults.dayNames, monthNamesShort = (settings ? settings.monthNamesShort : null) || this._defaults.monthNamesShort, monthNames = (settings ? settings.monthNames : null) || this._defaults.monthNames, year = -1, month = -1, day = -1, doy = -1, literal = false, date, // Check whether a format character is doubled lookAhead = function(match) { var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) === match); if (matches) { iFormat++; } return matches; }, // Extract a number from the string value getNumber = function(match) { var isDoubled = lookAhead(match), size = (match === "@" ? 14 : (match === "!" ? 20 : (match === "y" && isDoubled ? 4 : (match === "o" ? 3 : 2)))), minSize = (match === "y" ? size : 1), digits = new RegExp("^\\d{" + minSize + "," + size + "}"), num = value.substring(iValue).match(digits); if (!num) { throw "Missing number at position " + iValue; } iValue += num[0].length; return parseInt(num[0], 10); }, // Extract a name from the string value and convert to an index getName = function(match, shortNames, longNames) { var index = -1, names = $.map(lookAhead(match) ? longNames : shortNames, function (v, k) { return [ [k, v] ]; }).sort(function (a, b) { return -(a[1].length - b[1].length); }); $.each(names, function (i, pair) { var name = pair[1]; if (value.substr(iValue, name.length).toLowerCase() === name.toLowerCase()) { index = pair[0]; iValue += name.length; return false; } }); if (index !== -1) { return index + 1; } else { throw "Unknown name at position " + iValue; } }, // Confirm that a literal character matches the string value checkLiteral = function() { if (value.charAt(iValue) !== format.charAt(iFormat)) { throw "Unexpected literal at position " + iValue; } iValue++; }; for (iFormat = 0; iFormat < format.length; iFormat++) { if (literal) { if (format.charAt(iFormat) === "'" && !lookAhead("'")) { literal = false; } else { checkLiteral(); } } else { switch (format.charAt(iFormat)) { case "d": day = getNumber("d"); break; case "D": getName("D", dayNamesShort, dayNames); break; case "o": doy = getNumber("o"); break; case "m": month = getNumber("m"); break; case "M": month = getName("M", monthNamesShort, monthNames); break; case "y": year = getNumber("y"); break; case "@": date = new Date(getNumber("@")); year = date.getFullYear(); month = date.getMonth() + 1; day = date.getDate(); break; case "!": date = new Date((getNumber("!") - this._ticksTo1970) / 10000); year = date.getFullYear(); month = date.getMonth() + 1; day = date.getDate(); break; case "'": if (lookAhead("'")){ checkLiteral(); } else { literal = true; } break; default: checkLiteral(); } } } if (iValue < value.length){ extra = value.substr(iValue); if (!/^\s+/.test(extra)) { throw "Extra/unparsed characters found in date: " + extra; } } if (year === -1) { year = new Date().getFullYear(); } else if (year < 100) { year += new Date().getFullYear() - new Date().getFullYear() % 100 + (year <= shortYearCutoff ? 0 : -100); } if (doy > -1) { month = 1; day = doy; do { dim = this._getDaysInMonth(year, month - 1); if (day <= dim) { break; } month++; day -= dim; } while (true); } date = this._daylightSavingAdjust(new Date(year, month - 1, day)); if (date.getFullYear() !== year || date.getMonth() + 1 !== month || date.getDate() !== day) { throw "Invalid date"; // E.g. 31/02/00 } return date; }, /* Standard date formats. */ ATOM: "yy-mm-dd", // RFC 3339 (ISO 8601) COOKIE: "D, dd M yy", ISO_8601: "yy-mm-dd", RFC_822: "D, d M y", RFC_850: "DD, dd-M-y", RFC_1036: "D, d M y", RFC_1123: "D, d M yy", RFC_2822: "D, d M yy", RSS: "D, d M y", // RFC 822 TICKS: "!", TIMESTAMP: "@", W3C: "yy-mm-dd", // ISO 8601 _ticksTo1970: (((1970 - 1) * 365 + Math.floor(1970 / 4) - Math.floor(1970 / 100) + Math.floor(1970 / 400)) * 24 * 60 * 60 * 10000000), /* Format a date object into a string value. * The format can be combinations of the following: * d - day of month (no leading zero) * dd - day of month (two digit) * o - day of year (no leading zeros) * oo - day of year (three digit) * D - day name short * DD - day name long * m - month of year (no leading zero) * mm - month of year (two digit) * M - month name short * MM - month name long * y - year (two digit) * yy - year (four digit) * @ - Unix timestamp (ms since 01/01/1970) * ! - Windows ticks (100ns since 01/01/0001) * "..." - literal text * '' - single quote * * @param format string - the desired format of the date * @param date Date - the date value to format * @param settings Object - attributes include: * dayNamesShort string[7] - abbreviated names of the days from Sunday (optional) * dayNames string[7] - names of the days from Sunday (optional) * monthNamesShort string[12] - abbreviated names of the months (optional) * monthNames string[12] - names of the months (optional) * @return string - the date in the above format */ formatDate: function (format, date, settings) { if (!date) { return ""; } var iFormat, dayNamesShort = (settings ? settings.dayNamesShort : null) || this._defaults.dayNamesShort, dayNames = (settings ? settings.dayNames : null) || this._defaults.dayNames, monthNamesShort = (settings ? settings.monthNamesShort : null) || this._defaults.monthNamesShort, monthNames = (settings ? settings.monthNames : null) || this._defaults.monthNames, // Check whether a format character is doubled lookAhead = function(match) { var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) === match); if (matches) { iFormat++; } return matches; }, // Format a number, with leading zero if necessary formatNumber = function(match, value, len) { var num = "" + value; if (lookAhead(match)) { while (num.length < len) { num = "0" + num; } } return num; }, // Format a name, short or long as requested formatName = function(match, value, shortNames, longNames) { return (lookAhead(match) ? longNames[value] : shortNames[value]); }, output = "", literal = false; if (date) { for (iFormat = 0; iFormat < format.length; iFormat++) { if (literal) { if (format.charAt(iFormat) === "'" && !lookAhead("'")) { literal = false; } else { output += format.charAt(iFormat); } } else { switch (format.charAt(iFormat)) { case "d": output += formatNumber("d", date.getDate(), 2); break; case "D": output += formatName("D", date.getDay(), dayNamesShort, dayNames); break; case "o": output += formatNumber("o", Math.round((new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime() - new Date(date.getFullYear(), 0, 0).getTime()) / 86400000), 3); break; case "m": output += formatNumber("m", date.getMonth() + 1, 2); break; case "M": output += formatName("M", date.getMonth(), monthNamesShort, monthNames); break; case "y": output += (lookAhead("y") ? date.getFullYear() : (date.getYear() % 100 < 10 ? "0" : "") + date.getYear() % 100); break; case "@": output += date.getTime(); break; case "!": output += date.getTime() * 10000 + this._ticksTo1970; break; case "'": if (lookAhead("'")) { output += "'"; } else { literal = true; } break; default: output += format.charAt(iFormat); } } } } return output; }, /* Extract all possible characters from the date format. */ _possibleChars: function (format) { var iFormat, chars = "", literal = false, // Check whether a format character is doubled lookAhead = function(match) { var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) === match); if (matches) { iFormat++; } return matches; }; for (iFormat = 0; iFormat < format.length; iFormat++) { if (literal) { if (format.charAt(iFormat) === "'" && !lookAhead("'")) { literal = false; } else { chars += format.charAt(iFormat); } } else { switch (format.charAt(iFormat)) { case "d": case "m": case "y": case "@": chars += "0123456789"; break; case "D": case "M": return null; // Accept anything case "'": if (lookAhead("'")) { chars += "'"; } else { literal = true; } break; default: chars += format.charAt(iFormat); } } } return chars; }, /* Get a setting value, defaulting if necessary. */ _get: function(inst, name) { return inst.settings[name] !== undefined ? inst.settings[name] : this._defaults[name]; }, /* Parse existing date and initialise date picker. */ _setDateFromField: function(inst, noDefault) { if (inst.input.val() === inst.lastVal) { return; } var dateFormat = this._get(inst, "dateFormat"), dates = inst.lastVal = inst.input ? inst.input.val() : null, defaultDate = this._getDefaultDate(inst), date = defaultDate, settings = this._getFormatConfig(inst); try { date = this.parseDate(dateFormat, dates, settings) || defaultDate; } catch (event) { dates = (noDefault ? "" : dates); } inst.selectedDay = date.getDate(); inst.drawMonth = inst.selectedMonth = date.getMonth(); inst.drawYear = inst.selectedYear = date.getFullYear(); inst.currentDay = (dates ? date.getDate() : 0); inst.currentMonth = (dates ? date.getMonth() : 0); inst.currentYear = (dates ? date.getFullYear() : 0); this._adjustInstDate(inst); }, /* Retrieve the default date shown on opening. */ _getDefaultDate: function(inst) { return this._restrictMinMax(inst, this._determineDate(inst, this._get(inst, "defaultDate"), new Date())); }, /* A date may be specified as an exact value or a relative one. */ _determineDate: function(inst, date, defaultDate) { var offsetNumeric = function(offset) { var date = new Date(); date.setDate(date.getDate() + offset); return date; }, offsetString = function(offset) { try { return $.datepicker.parseDate($.datepicker._get(inst, "dateFormat"), offset, $.datepicker._getFormatConfig(inst)); } catch (e) { // Ignore } var date = (offset.toLowerCase().match(/^c/) ? $.datepicker._getDate(inst) : null) || new Date(), year = date.getFullYear(), month = date.getMonth(), day = date.getDate(), pattern = /([+\-]?[0-9]+)\s*(d|D|w|W|m|M|y|Y)?/g, matches = pattern.exec(offset); while (matches) { switch (matches[2] || "d") { case "d" : case "D" : day += parseInt(matches[1],10); break; case "w" : case "W" : day += parseInt(matches[1],10) * 7; break; case "m" : case "M" : month += parseInt(matches[1],10); day = Math.min(day, $.datepicker._getDaysInMonth(year, month)); break; case "y": case "Y" : year += parseInt(matches[1],10); day = Math.min(day, $.datepicker._getDaysInMonth(year, month)); break; } matches = pattern.exec(offset); } return new Date(year, month, day); }, newDate = (date == null || date === "" ? defaultDate : (typeof date === "string" ? offsetString(date) : (typeof date === "number" ? (isNaN(date) ? defaultDate : offsetNumeric(date)) : new Date(date.getTime())))); newDate = (newDate && newDate.toString() === "Invalid Date" ? defaultDate : newDate); if (newDate) { newDate.setHours(0); newDate.setMinutes(0); newDate.setSeconds(0); newDate.setMilliseconds(0); } return this._daylightSavingAdjust(newDate); }, /* Handle switch to/from daylight saving. * Hours may be non-zero on daylight saving cut-over: * > 12 when midnight changeover, but then cannot generate * midnight datetime, so jump to 1AM, otherwise reset. * @param date (Date) the date to check * @return (Date) the corrected date */ _daylightSavingAdjust: function(date) { if (!date) { return null; } date.setHours(date.getHours() > 12 ? date.getHours() + 2 : 0); return date; }, /* Set the date(s) directly. */ _setDate: function(inst, date, noChange) { var clear = !date, origMonth = inst.selectedMonth, origYear = inst.selectedYear, newDate = this._restrictMinMax(inst, this._determineDate(inst, date, new Date())); inst.selectedDay = inst.currentDay = newDate.getDate(); inst.drawMonth = inst.selectedMonth = inst.currentMonth = newDate.getMonth(); inst.drawYear = inst.selectedYear = inst.currentYear = newDate.getFullYear(); if ((origMonth !== inst.selectedMonth || origYear !== inst.selectedYear) && !noChange) { this._notifyChange(inst); } this._adjustInstDate(inst); if (inst.input) { inst.input.val(clear ? "" : this._formatDate(inst)); } }, /* Retrieve the date(s) directly. */ _getDate: function(inst) { var startDate = (!inst.currentYear || (inst.input && inst.input.val() === "") ? null : this._daylightSavingAdjust(new Date( inst.currentYear, inst.currentMonth, inst.currentDay))); return startDate; }, /* Attach the onxxx handlers. These are declared statically so * they work with static code transformers like Caja. */ _attachHandlers: function(inst) { var stepMonths = this._get(inst, "stepMonths"), id = "#" + inst.id.replace( /\\\\/g, "\\" ); inst.dpDiv.find("[data-handler]").map(function () { var handler = { prev: function () { $.datepicker._adjustDate(id, -stepMonths, "M"); }, next: function () { $.datepicker._adjustDate(id, +stepMonths, "M"); }, hide: function () { $.datepicker._hideDatepicker(); }, today: function () { $.datepicker._gotoToday(id); }, selectDay: function () { $.datepicker._selectDay(id, +this.getAttribute("data-month"), +this.getAttribute("data-year"), this); return false; }, selectMonth: function () { $.datepicker._selectMonthYear(id, this, "M"); return false; }, selectYear: function () { $.datepicker._selectMonthYear(id, this, "Y"); return false; } }; $(this).bind(this.getAttribute("data-event"), handler[this.getAttribute("data-handler")]); }); }, /* Generate the HTML for the current state of the date picker. */ _generateHTML: function(inst) { var maxDraw, prevText, prev, nextText, next, currentText, gotoDate, controls, buttonPanel, firstDay, showWeek, dayNames, dayNamesMin, monthNames, monthNamesShort, beforeShowDay, showOtherMonths, selectOtherMonths, defaultDate, html, dow, row, group, col, selectedDate, cornerClass, calender, thead, day, daysInMonth, leadDays, curRows, numRows, printDate, dRow, tbody, daySettings, otherMonth, unselectable, tempDate = new Date(), today = this._daylightSavingAdjust( new Date(tempDate.getFullYear(), tempDate.getMonth(), tempDate.getDate())), // clear time isRTL = this._get(inst, "isRTL"), showButtonPanel = this._get(inst, "showButtonPanel"), hideIfNoPrevNext = this._get(inst, "hideIfNoPrevNext"), navigationAsDateFormat = this._get(inst, "navigationAsDateFormat"), numMonths = this._getNumberOfMonths(inst), showCurrentAtPos = this._get(inst, "showCurrentAtPos"), stepMonths = this._get(inst, "stepMonths"), isMultiMonth = (numMonths[0] !== 1 || numMonths[1] !== 1), currentDate = this._daylightSavingAdjust((!inst.currentDay ? new Date(9999, 9, 9) : new Date(inst.currentYear, inst.currentMonth, inst.currentDay))), minDate = this._getMinMaxDate(inst, "min"), maxDate = this._getMinMaxDate(inst, "max"), drawMonth = inst.drawMonth - showCurrentAtPos, drawYear = inst.drawYear; if (drawMonth < 0) { drawMonth += 12; drawYear--; } if (maxDate) { maxDraw = this._daylightSavingAdjust(new Date(maxDate.getFullYear(), maxDate.getMonth() - (numMonths[0] * numMonths[1]) + 1, maxDate.getDate())); maxDraw = (minDate && maxDraw < minDate ? minDate : maxDraw); while (this._daylightSavingAdjust(new Date(drawYear, drawMonth, 1)) > maxDraw) { drawMonth--; if (drawMonth < 0) { drawMonth = 11; drawYear--; } } } inst.drawMonth = drawMonth; inst.drawYear = drawYear; prevText = this._get(inst, "prevText"); prevText = (!navigationAsDateFormat ? prevText : this.formatDate(prevText, this._daylightSavingAdjust(new Date(drawYear, drawMonth - stepMonths, 1)), this._getFormatConfig(inst))); prev = (this._canAdjustMonth(inst, -1, drawYear, drawMonth) ? "<a class='ui-datepicker-prev ui-corner-all' data-handler='prev' data-event='click'" + " title='" + prevText + "'><span class='ui-icon ui-icon-circle-triangle-" + ( isRTL ? "e" : "w") + "'>" + prevText + "</span></a>" : (hideIfNoPrevNext ? "" : "<a class='ui-datepicker-prev ui-corner-all ui-state-disabled' title='"+ prevText +"'><span class='ui-icon ui-icon-circle-triangle-" + ( isRTL ? "e" : "w") + "'>" + prevText + "</span></a>")); nextText = this._get(inst, "nextText"); nextText = (!navigationAsDateFormat ? nextText : this.formatDate(nextText, this._daylightSavingAdjust(new Date(drawYear, drawMonth + stepMonths, 1)), this._getFormatConfig(inst))); next = (this._canAdjustMonth(inst, +1, drawYear, drawMonth) ? "<a class='ui-datepicker-next ui-corner-all' data-handler='next' data-event='click'" + " title='" + nextText + "'><span class='ui-icon ui-icon-circle-triangle-" + ( isRTL ? "w" : "e") + "'>" + nextText + "</span></a>" : (hideIfNoPrevNext ? "" : "<a class='ui-datepicker-next ui-corner-all ui-state-disabled' title='"+ nextText + "'><span class='ui-icon ui-icon-circle-triangle-" + ( isRTL ? "w" : "e") + "'>" + nextText + "</span></a>")); currentText = this._get(inst, "currentText"); gotoDate = (this._get(inst, "gotoCurrent") && inst.currentDay ? currentDate : today); currentText = (!navigationAsDateFormat ? currentText : this.formatDate(currentText, gotoDate, this._getFormatConfig(inst))); controls = (!inst.inline ? "<button type='button' class='ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all' data-handler='hide' data-event='click'>" + this._get(inst, "closeText") + "</button>" : ""); buttonPanel = (showButtonPanel) ? "<div class='ui-datepicker-buttonpane ui-widget-content'>" + (isRTL ? controls : "") + (this._isInRange(inst, gotoDate) ? "<button type='button' class='ui-datepicker-current ui-state-default ui-priority-secondary ui-corner-all' data-handler='today' data-event='click'" + ">" + currentText + "</button>" : "") + (isRTL ? "" : controls) + "</div>" : ""; firstDay = parseInt(this._get(inst, "firstDay"),10); firstDay = (isNaN(firstDay) ? 0 : firstDay); showWeek = this._get(inst, "showWeek"); dayNames = this._get(inst, "dayNames"); dayNamesMin = this._get(inst, "dayNamesMin"); monthNames = this._get(inst, "monthNames"); monthNamesShort = this._get(inst, "monthNamesShort"); beforeShowDay = this._get(inst, "beforeShowDay"); showOtherMonths = this._get(inst, "showOtherMonths"); selectOtherMonths = this._get(inst, "selectOtherMonths"); defaultDate = this._getDefaultDate(inst); html = ""; dow; for (row = 0; row < numMonths[0]; row++) { group = ""; this.maxRows = 4; for (col = 0; col < numMonths[1]; col++) { selectedDate = this._daylightSavingAdjust(new Date(drawYear, drawMonth, inst.selectedDay)); cornerClass = " ui-corner-all"; calender = ""; if (isMultiMonth) { calender += "<div class='ui-datepicker-group"; if (numMonths[1] > 1) { switch (col) { case 0: calender += " ui-datepicker-group-first"; cornerClass = " ui-corner-" + (isRTL ? "right" : "left"); break; case numMonths[1]-1: calender += " ui-datepicker-group-last"; cornerClass = " ui-corner-" + (isRTL ? "left" : "right"); break; default: calender += " ui-datepicker-group-middle"; cornerClass = ""; break; } } calender += "'>"; } calender += "<div class='ui-datepicker-header ui-widget-header ui-helper-clearfix" + cornerClass + "'>" + (/all|left/.test(cornerClass) && row === 0 ? (isRTL ? next : prev) : "") + (/all|right/.test(cornerClass) && row === 0 ? (isRTL ? prev : next) : "") + this._generateMonthYearHeader(inst, drawMonth, drawYear, minDate, maxDate, row > 0 || col > 0, monthNames, monthNamesShort) + // draw month headers "</div><table class='ui-datepicker-calendar'><thead>" + "<tr>"; thead = (showWeek ? "<th class='ui-datepicker-week-col'>" + this._get(inst, "weekHeader") + "</th>" : ""); for (dow = 0; dow < 7; dow++) { // days of the week day = (dow + firstDay) % 7; thead += "<th scope='col'" + ((dow + firstDay + 6) % 7 >= 5 ? " class='ui-datepicker-week-end'" : "") + ">" + "<span title='" + dayNames[day] + "'>" + dayNamesMin[day] + "</span></th>"; } calender += thead + "</tr></thead><tbody>"; daysInMonth = this._getDaysInMonth(drawYear, drawMonth); if (drawYear === inst.selectedYear && drawMonth === inst.selectedMonth) { inst.selectedDay = Math.min(inst.selectedDay, daysInMonth); } leadDays = (this._getFirstDayOfMonth(drawYear, drawMonth) - firstDay + 7) % 7; curRows = Math.ceil((leadDays + daysInMonth) / 7); // calculate the number of rows to generate numRows = (isMultiMonth ? this.maxRows > curRows ? this.maxRows : curRows : curRows); //If multiple months, use the higher number of rows (see #7043) this.maxRows = numRows; printDate = this._daylightSavingAdjust(new Date(drawYear, drawMonth, 1 - leadDays)); for (dRow = 0; dRow < numRows; dRow++) { // create date picker rows calender += "<tr>"; tbody = (!showWeek ? "" : "<td class='ui-datepicker-week-col'>" + this._get(inst, "calculateWeek")(printDate) + "</td>"); for (dow = 0; dow < 7; dow++) { // create date picker days daySettings = (beforeShowDay ? beforeShowDay.apply((inst.input ? inst.input[0] : null), [printDate]) : [true, ""]); otherMonth = (printDate.getMonth() !== drawMonth); unselectable = (otherMonth && !selectOtherMonths) || !daySettings[0] || (minDate && printDate < minDate) || (maxDate && printDate > maxDate); tbody += "<td class='" + ((dow + firstDay + 6) % 7 >= 5 ? " ui-datepicker-week-end" : "") + // highlight weekends (otherMonth ? " ui-datepicker-other-month" : "") + // highlight days from other months ((printDate.getTime() === selectedDate.getTime() && drawMonth === inst.selectedMonth && inst._keyEvent) || // user pressed key (defaultDate.getTime() === printDate.getTime() && defaultDate.getTime() === selectedDate.getTime()) ? // or defaultDate is current printedDate and defaultDate is selectedDate " " + this._dayOverClass : "") + // highlight selected day (unselectable ? " " + this._unselectableClass + " ui-state-disabled": "") + // highlight unselectable days (otherMonth && !showOtherMonths ? "" : " " + daySettings[1] + // highlight custom dates (printDate.getTime() === currentDate.getTime() ? " " + this._currentClass : "") + // highlight selected day (printDate.getTime() === today.getTime() ? " ui-datepicker-today" : "")) + "'" + // highlight today (if different) ((!otherMonth || showOtherMonths) && daySettings[2] ? " title='" + daySettings[2].replace(/'/g, "&#39;") + "'" : "") + // cell title (unselectable ? "" : " data-handler='selectDay' data-event='click' data-month='" + printDate.getMonth() + "' data-year='" + printDate.getFullYear() + "'") + ">" + // actions (otherMonth && !showOtherMonths ? "&#xa0;" : // display for other months (unselectable ? "<span class='ui-state-default'>" + printDate.getDate() + "</span>" : "<a class='ui-state-default" + (printDate.getTime() === today.getTime() ? " ui-state-highlight" : "") + (printDate.getTime() === currentDate.getTime() ? " ui-state-active" : "") + // highlight selected day (otherMonth ? " ui-priority-secondary" : "") + // distinguish dates from other months "' href='#'>" + printDate.getDate() + "</a>")) + "</td>"; // display selectable date printDate.setDate(printDate.getDate() + 1); printDate = this._daylightSavingAdjust(printDate); } calender += tbody + "</tr>"; } drawMonth++; if (drawMonth > 11) { drawMonth = 0; drawYear++; } calender += "</tbody></table>" + (isMultiMonth ? "</div>" + ((numMonths[0] > 0 && col === numMonths[1]-1) ? "<div class='ui-datepicker-row-break'></div>" : "") : ""); group += calender; } html += group; } html += buttonPanel; inst._keyEvent = false; return html; }, /* Generate the month and year header. */ _generateMonthYearHeader: function(inst, drawMonth, drawYear, minDate, maxDate, secondary, monthNames, monthNamesShort) { var inMinYear, inMaxYear, month, years, thisYear, determineYear, year, endYear, changeMonth = this._get(inst, "changeMonth"), changeYear = this._get(inst, "changeYear"), showMonthAfterYear = this._get(inst, "showMonthAfterYear"), html = "<div class='ui-datepicker-title'>", monthHtml = ""; // month selection if (secondary || !changeMonth) { monthHtml += "<span class='ui-datepicker-month'>" + monthNames[drawMonth] + "</span>"; } else { inMinYear = (minDate && minDate.getFullYear() === drawYear); inMaxYear = (maxDate && maxDate.getFullYear() === drawYear); monthHtml += "<select class='ui-datepicker-month' data-handler='selectMonth' data-event='change'>"; for ( month = 0; month < 12; month++) { if ((!inMinYear || month >= minDate.getMonth()) && (!inMaxYear || month <= maxDate.getMonth())) { monthHtml += "<option value='" + month + "'" + (month === drawMonth ? " selected='selected'" : "") + ">" + monthNamesShort[month] + "</option>"; } } monthHtml += "</select>"; } if (!showMonthAfterYear) { html += monthHtml + (secondary || !(changeMonth && changeYear) ? "&#xa0;" : ""); } // year selection if ( !inst.yearshtml ) { inst.yearshtml = ""; if (secondary || !changeYear) { html += "<span class='ui-datepicker-year'>" + drawYear + "</span>"; } else { // determine range of years to display years = this._get(inst, "yearRange").split(":"); thisYear = new Date().getFullYear(); determineYear = function(value) { var year = (value.match(/c[+\-].*/) ? drawYear + parseInt(value.substring(1), 10) : (value.match(/[+\-].*/) ? thisYear + parseInt(value, 10) : parseInt(value, 10))); return (isNaN(year) ? thisYear : year); }; year = determineYear(years[0]); endYear = Math.max(year, determineYear(years[1] || "")); year = (minDate ? Math.max(year, minDate.getFullYear()) : year); endYear = (maxDate ? Math.min(endYear, maxDate.getFullYear()) : endYear); inst.yearshtml += "<select class='ui-datepicker-year' data-handler='selectYear' data-event='change'>"; for (; year <= endYear; year++) { inst.yearshtml += "<option value='" + year + "'" + (year === drawYear ? " selected='selected'" : "") + ">" + year + "</option>"; } inst.yearshtml += "</select>"; html += inst.yearshtml; inst.yearshtml = null; } } html += this._get(inst, "yearSuffix"); if (showMonthAfterYear) { html += (secondary || !(changeMonth && changeYear) ? "&#xa0;" : "") + monthHtml; } html += "</div>"; // Close datepicker_header return html; }, /* Adjust one of the date sub-fields. */ _adjustInstDate: function(inst, offset, period) { var year = inst.drawYear + (period === "Y" ? offset : 0), month = inst.drawMonth + (period === "M" ? offset : 0), day = Math.min(inst.selectedDay, this._getDaysInMonth(year, month)) + (period === "D" ? offset : 0), date = this._restrictMinMax(inst, this._daylightSavingAdjust(new Date(year, month, day))); inst.selectedDay = date.getDate(); inst.drawMonth = inst.selectedMonth = date.getMonth(); inst.drawYear = inst.selectedYear = date.getFullYear(); if (period === "M" || period === "Y") { this._notifyChange(inst); } }, /* Ensure a date is within any min/max bounds. */ _restrictMinMax: function(inst, date) { var minDate = this._getMinMaxDate(inst, "min"), maxDate = this._getMinMaxDate(inst, "max"), newDate = (minDate && date < minDate ? minDate : date); return (maxDate && newDate > maxDate ? maxDate : newDate); }, /* Notify change of month/year. */ _notifyChange: function(inst) { var onChange = this._get(inst, "onChangeMonthYear"); if (onChange) { onChange.apply((inst.input ? inst.input[0] : null), [inst.selectedYear, inst.selectedMonth + 1, inst]); } }, /* Determine the number of months to show. */ _getNumberOfMonths: function(inst) { var numMonths = this._get(inst, "numberOfMonths"); return (numMonths == null ? [1, 1] : (typeof numMonths === "number" ? [1, numMonths] : numMonths)); }, /* Determine the current maximum date - ensure no time components are set. */ _getMinMaxDate: function(inst, minMax) { return this._determineDate(inst, this._get(inst, minMax + "Date"), null); }, /* Find the number of days in a given month. */ _getDaysInMonth: function(year, month) { return 32 - this._daylightSavingAdjust(new Date(year, month, 32)).getDate(); }, /* Find the day of the week of the first of a month. */ _getFirstDayOfMonth: function(year, month) { return new Date(year, month, 1).getDay(); }, /* Determines if we should allow a "next/prev" month display change. */ _canAdjustMonth: function(inst, offset, curYear, curMonth) { var numMonths = this._getNumberOfMonths(inst), date = this._daylightSavingAdjust(new Date(curYear, curMonth + (offset < 0 ? offset : numMonths[0] * numMonths[1]), 1)); if (offset < 0) { date.setDate(this._getDaysInMonth(date.getFullYear(), date.getMonth())); } return this._isInRange(inst, date); }, /* Is the given date in the accepted range? */ _isInRange: function(inst, date) { var yearSplit, currentYear, minDate = this._getMinMaxDate(inst, "min"), maxDate = this._getMinMaxDate(inst, "max"), minYear = null, maxYear = null, years = this._get(inst, "yearRange"); if (years){ yearSplit = years.split(":"); currentYear = new Date().getFullYear(); minYear = parseInt(yearSplit[0], 10); maxYear = parseInt(yearSplit[1], 10); if ( yearSplit[0].match(/[+\-].*/) ) { minYear += currentYear; } if ( yearSplit[1].match(/[+\-].*/) ) { maxYear += currentYear; } } return ((!minDate || date.getTime() >= minDate.getTime()) && (!maxDate || date.getTime() <= maxDate.getTime()) && (!minYear || date.getFullYear() >= minYear) && (!maxYear || date.getFullYear() <= maxYear)); }, /* Provide the configuration settings for formatting/parsing. */ _getFormatConfig: function(inst) { var shortYearCutoff = this._get(inst, "shortYearCutoff"); shortYearCutoff = (typeof shortYearCutoff !== "string" ? shortYearCutoff : new Date().getFullYear() % 100 + parseInt(shortYearCutoff, 10)); return {shortYearCutoff: shortYearCutoff, dayNamesShort: this._get(inst, "dayNamesShort"), dayNames: this._get(inst, "dayNames"), monthNamesShort: this._get(inst, "monthNamesShort"), monthNames: this._get(inst, "monthNames")}; }, /* Format the given date for display. */ _formatDate: function(inst, day, month, year) { if (!day) { inst.currentDay = inst.selectedDay; inst.currentMonth = inst.selectedMonth; inst.currentYear = inst.selectedYear; } var date = (day ? (typeof day === "object" ? day : this._daylightSavingAdjust(new Date(year, month, day))) : this._daylightSavingAdjust(new Date(inst.currentYear, inst.currentMonth, inst.currentDay))); return this.formatDate(this._get(inst, "dateFormat"), date, this._getFormatConfig(inst)); } }); /* * Bind hover events for datepicker elements. * Done via delegate so the binding only occurs once in the lifetime of the parent div. * Global datepicker_instActive, set by _updateDatepicker allows the handlers to find their way back to the active picker. */ function datepicker_bindHover(dpDiv) { var selector = "button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a"; return dpDiv.delegate(selector, "mouseout", function() { $(this).removeClass("ui-state-hover"); if (this.className.indexOf("ui-datepicker-prev") !== -1) { $(this).removeClass("ui-datepicker-prev-hover"); } if (this.className.indexOf("ui-datepicker-next") !== -1) { $(this).removeClass("ui-datepicker-next-hover"); } }) .delegate( selector, "mouseover", datepicker_handleMouseover ); } function datepicker_handleMouseover() { if (!$.datepicker._isDisabledDatepicker( datepicker_instActive.inline? datepicker_instActive.dpDiv.parent()[0] : datepicker_instActive.input[0])) { $(this).parents(".ui-datepicker-calendar").find("a").removeClass("ui-state-hover"); $(this).addClass("ui-state-hover"); if (this.className.indexOf("ui-datepicker-prev") !== -1) { $(this).addClass("ui-datepicker-prev-hover"); } if (this.className.indexOf("ui-datepicker-next") !== -1) { $(this).addClass("ui-datepicker-next-hover"); } } } /* jQuery extend now ignores nulls! */ function datepicker_extendRemove(target, props) { $.extend(target, props); for (var name in props) { if (props[name] == null) { target[name] = props[name]; } } return target; } /* Invoke the datepicker functionality. @param options string - a command, optionally followed by additional parameters or Object - settings for attaching new datepicker functionality @return jQuery object */ $.fn.datepicker = function(options){ /* Verify an empty collection wasn't passed - Fixes #6976 */ if ( !this.length ) { return this; } /* Initialise the date picker. */ if (!$.datepicker.initialized) { $(document).mousedown($.datepicker._checkExternalClick); $.datepicker.initialized = true; } /* Append datepicker main container to body if not exist. */ if ($("#"+$.datepicker._mainDivId).length === 0) { $("body").append($.datepicker.dpDiv); } var otherArgs = Array.prototype.slice.call(arguments, 1); if (typeof options === "string" && (options === "isDisabled" || options === "getDate" || options === "widget")) { return $.datepicker["_" + options + "Datepicker"]. apply($.datepicker, [this[0]].concat(otherArgs)); } if (options === "option" && arguments.length === 2 && typeof arguments[1] === "string") { return $.datepicker["_" + options + "Datepicker"]. apply($.datepicker, [this[0]].concat(otherArgs)); } return this.each(function() { typeof options === "string" ? $.datepicker["_" + options + "Datepicker"]. apply($.datepicker, [this].concat(otherArgs)) : $.datepicker._attachDatepicker(this, options); }); }; $.datepicker = new Datepicker(); // singleton instance $.datepicker.initialized = false; $.datepicker.uuid = new Date().getTime(); $.datepicker.version = "1.11.1"; var datepicker = $.datepicker; })); /* * jQuery Mobile: jQuery UI Datepicker Monkey Patch * http://salman-w.blogspot.com/2014/03/jquery-ui-datepicker-for-jquery-mobile.html */ (function() { // use a jQuery Mobile icon on trigger button $.datepicker._triggerClass += " ui-btn ui-btn-right ui-icon-carat-d ui-btn-icon-notext ui-corner-all"; // replace jQuery UI CSS classes with jQuery Mobile CSS classes in the generated HTML $.datepicker._generateHTML_old = $.datepicker._generateHTML; $.datepicker._generateHTML = function(inst) { return $("<div></div>").html(this._generateHTML_old(inst)) .find(".ui-datepicker-header").removeClass("ui-widget-header ui-helper-clearfix").addClass("ui-bar-inherit").end() .find(".ui-datepicker-prev").addClass("ui-btn ui-btn-left ui-icon-carat-l ui-btn-icon-notext").end() .find(".ui-datepicker-next").addClass("ui-btn ui-btn-right ui-icon-carat-r ui-btn-icon-notext").end() .find(".ui-icon.ui-icon-circle-triangle-e, .ui-icon.ui-icon-circle-triangle-w").replaceWith(function() { return this.childNodes; }).end() .find("span.ui-state-default").removeClass("ui-state-default").addClass("ui-btn").end() .find("a.ui-state-default.ui-state-active").removeClass("ui-state-default ui-state-highlight ui-priority-secondary ui-state-active").addClass("ui-btn ui-btn-active").end() .find("a.ui-state-default").removeClass("ui-state-default ui-state-highlight ui-priority-secondary").addClass("ui-btn").end() .find(".ui-datepicker-buttonpane").removeClass("ui-widget-content").end() .find(".ui-datepicker-current").removeClass("ui-state-default ui-priority-secondary").addClass("ui-btn ui-btn-inline ui-mini").end() .find(".ui-datepicker-close").removeClass("ui-state-default ui-priority-primary").addClass("ui-btn ui-btn-inline ui-mini").end() .html(); }; // replace jQuery UI CSS classes with jQuery Mobile CSS classes on the datepicker div, unbind mouseover and mouseout events on the datepicker div $.datepicker._newInst_old = $.datepicker._newInst; $.datepicker._newInst = function(target, inline) { var inst = this._newInst_old(target, inline); if (inst.dpDiv.hasClass("ui-widget")) { inst.dpDiv.removeClass("ui-widget ui-widget-content ui-helper-clearfix").addClass(inline ? "ui-content" : "ui-content ui-overlay-shadow ui-body-a").unbind("mouseover mouseout"); } return inst; }; })();
shihjay2/nosh-core
public/js/mobile.js
JavaScript
agpl-3.0
243,263
var hook = require("../lib/resources/hook"); var hooks = require("hook.io-hooks"); var bodyParser = require('body-parser'); var mergeParams = require('merge-params'); var config = require('../config'); var themes = require('../lib/resources/themes'); var hooks = require('hook.io-hooks'); module['exports'] = function view (opts, callback) { var req = opts.request, res = opts.response; var $ = this.$, self = this; if (!req.isAuthenticated()) { req.session.redirectTo = "/new"; return res.redirect('/login'); } var user = req.session.user; var boot = { owner: user }; bodyParser()(req, res, function bodyParsed(){ mergeParams(req, res, function(){}); var params = req.resource.params; var gist = params.gist; if (req.method === "POST") { if (params.name.length === 0) { return res.end('Hook name is required!'); } // do not recreate hooks that already exist with that name params.owner = user || "Marak"; // hardcode Marak for testing if (typeof params.theme === 'string' && params.theme.length === 0) { delete params.theme; } if (typeof params.presenter === 'string' && params.presenter.length === 0) { delete params.presenter; } var query = { name: params.name, owner: req.session.user }; return hook.find(query, function(err, results){ if (results.length > 0) { var h = results[0]; return res.end('Hook already exists ' + '/' + h.owner + "/" + h.name); //return res.redirect('/' + h.owner + "/" + h.name + "?alreadyExists=true"); } params.cron = params.cronString; if (params.hookSource === "editor") { delete params.gist; params.source = params.codeEditor; } // TODO: filter params for only specified resource fields? return hook.create(params, function(err, result){ if (err) { return callback(null, err.message); } var h = result; req.hook = h; if (params.hookSource === "editor") { // the source of the hook is coming from the code editor return res.redirect('/' + h.owner + "/" + h.name + ""); } else { // the source of the hook is coming from a github gist opts.gist = gist; opts.req = opts.request; opts.res = opts.response; // fetch the hook from github and check if it has a schema / theme // if so, attach it to the hook document // TODO: can we remove this? it seems like this logic should be in the Hook.runHook execution chain... hook.fetchHookSourceCode(opts, function(err, code){ if (err) { return opts.res.end(err.message); } hook.attemptToRequireUntrustedHook(opts, function(err, _module){ if (err) { return opts.res.end(err.message) } h.mschema = _module.schema; h.theme = _module.theme; h.presenter = _module.presenter; h.save(function(){ // redirect to new hook friendly page return res.redirect('/' + h.owner + "/" + h.name + ""); //return callback(null, JSON.stringify(result, true, 2)); }); }); }); } }); }); } if (typeof req.session.gistLink === 'string') { // todo: after created, unset gistSource so it doesn't keep popping up $('.gist').attr('value', req.session.gistLink); } else { $('.gistStatus').remove(); } var services = hooks.services; var examples = {}; // pull out helloworld examples for every langauge hook.languages.forEach(function(l){ examples[l] = services['examples-' + l + '-helloworld']; }); boot.examples = examples; /* for (var e in examples) { for (var code in examples[e]) { // $('.services').append(examples[e][code]); } } */ self.parent.components.themeSelector.present({}, function(err, html){ var el = $('.themeSelector') el.html(html); var out = $.html(); out = out.replace('{{hook}}', JSON.stringify(boot, true, 2)); callback(null, out); }) }); };
joshgillies/hook.io
view/new.js
JavaScript
agpl-3.0
4,408
'use strict'; /** * @ngdoc directive * @name FlyveMDM.directive:loggedUserMenu * @description * # loggedUserMenu */ angular.module('FlyveMDM') .directive('loggedUserMenu', function () { return { templateUrl: 'views/loggedusermenu.html', restrict: 'E', link: function postLink(scope) { scope.opened = false; scope.fabModOpened = false; angular.element(document.querySelector('nav > ul.menu')).css({ }); scope.$watch('fabModOpened', function (opened) { if (opened) { angular.element(document.querySelector('nav > ul.menu')).removeClass('fab-usermenu-closed'); } else { angular.element(document.querySelector('nav > ul.menu')).addClass('fab-usermenu-closed'); } }); }, scope: {}, controller: function ($scope, AuthProvider) { var handleClickOutside = function () { $scope.$apply(function () { $scope.forceClose(); }); }; $scope.toggleOpened = function ($event) { $event.stopPropagation(); $scope.opened = !$scope.opened; if ($scope.opened) { angular.element(document.querySelector('html')).on('click', handleClickOutside); } }; $scope.forceClose = function () { $scope.opened = false; angular.element(document.querySelector('html')).off('click', handleClickOutside); return true; }; $scope.disconnect = function () { AuthProvider.logout().then(function () { AuthProvider.showLogin(); }); }; $scope.$on('$destroy', function () { angular.element(document.querySelector('html')).off('click', handleClickOutside); }); } }; });
flyve-mdm/flyve-mdm-web-ui
app/scripts/directives/loggedusermenu.js
JavaScript
agpl-3.0
1,817
import React from 'react'; import reactCSS from 'reactcss'; import { Swatch } from 'react-color/lib/components/common'; export const SwatchesColor = ({ color, onClick = () => {}, onSwatchHover, first, last, active, }) => { const styles = reactCSS( { default: { color: { width: '40px', height: '24px', cursor: 'pointer', background: color, marginBottom: '1px', }, check: { fill: '#fff', marginLeft: '8px', display: 'none', }, }, first: { color: { overflow: 'hidden', borderRadius: '2px 2px 0 0', }, }, last: { color: { overflow: 'hidden', borderRadius: '0 0 2px 2px', }, }, active: { check: { display: 'block', }, }, 'color-#FFFFFF': { color: { boxShadow: 'inset 0 0 0 1px #ddd', }, check: { fill: '#333', }, }, transparent: { check: { fill: '#333', }, }, }, { first, last, active, 'color-#FFFFFF': color === '#FFFFFF', transparent: color === 'transparent', }, ); return ( <Swatch color={color} style={styles.color} onClick={onClick} onHover={onSwatchHover} focusStyle={{ boxShadow: `0 0 4px ${color}` }} > <div style={styles.check}> <svg style={{ width: '24px', height: '24px' }} viewBox="0 0 24 24"> <path d="M21,7L9,19L3.5,13.5L4.91,12.09L9,16.17L19.59,5.59L21,7Z" /> </svg> </div> </Swatch> ); }; export default SwatchesColor;
zapcoop/vertex
vertex_ui/src/components/ColorPicker/Swatches/SwatchesColor.js
JavaScript
agpl-3.0
1,740
function handleRace(data_races) { var ch_race; var ch_side; for (var ra in data_races.races) { if (data_races.races[ra].id === character_data.race) { ch_race = data_races.races[ra].name; ch_side = data_races.races[ra].side; } else { } } document.querySelector('div.info_image span.rac').textContent = ch_race; //$('div.info_image span.rac').text(ch_race); //document.querySelector('div.info_image div.sid').textContent = ch_side; //$('div.info_image div.sid').text(ch_side); } function handleClass(data_classes) { var ch_class; for (var cl in data_classes.classes) { if (data_classes.classes[cl].id === character_data.class) { ch_class = data_classes.classes[cl].name; } else { } } document.querySelector('div.info_image span.clss'). textContent = ch_class; //$('div.info_image span.clss').text(ch_class); } var character_data; function fetch_char(data) { character_data = data; // fetch image - card format var region = document.querySelector('input[name=region]:checked').value; var str = data.thumbnail; var pieces = []; pieces = str.split('-a'); var card = 'http://' + region + '.battle.net/static-render/' + region + '/' + pieces[0] + '-card.jpg'; // type of images: -avarar, -card, -profilemain, -inset document.querySelector('div.info_image').style.backgroundImage = 'url("' + card + '")'; // character data var ch_name = data.name; document.querySelector('div.info_image span.titl').textContent = ''; for (var tit in data.titles) { if (data.titles[tit].selected) { var my_title = data.titles[tit].name; my_title = my_title.replace('%s', ''); document.querySelector('div.info_image span.titl').textContent = my_title; } } document.querySelector('div.info_image span.nam').textContent = ch_name; url = 'http://' + region + '.battle.net/api/wow/data/character/races'; jsonp_request(url, 'handleRace'); url2 = 'http://' + region + '.battle.net/api/wow/data/character/classes'; jsonp_request(url2, 'handleClass'); var ch_gender = (data.gender === 0) ? 'Male' : 'Female'; var ch_level = data.level; document.querySelector('div.info_image span.levl').textContent = ch_level; var ch_guild = (data.guild) ? data.guild.name : ''; document.querySelector('div.info_image div.gld').textContent = ch_guild; var ch_server = data.realm; document.querySelector('div.info_image div.srv').textContent = ch_server; var ch_achiv = data.achievementPoints; document.querySelector('div.info_image div.achiv').innerHTML = ('<div class="achiv_icon"></div> ' + ch_achiv); // create character history var history_li = document.createElement('li'); history_li.dataset.name = ch_name; history_li.dataset.server = ch_server; history_li.dataset.region = region; history_li.innerHTML = '<aside>' + '<img src="' + 'http://' + region + '.battle.net/static-render/' + region + '/' + data.thumbnail + '"></img>' + '</aside>' + '<p>' + ch_name + '</p>' + '<p>' + ch_server + ' - ' + region.toUpperCase() + '</p>'; document.querySelector('ul.history').insertBefore(history_li, document.querySelector('ul.history').firstChild); // recall character form history [].forEach.call(document.querySelectorAll('ul.history > li'), function(li) { li.addEventListener('click', function() { document.querySelector('input[name=region][value=' + this.dataset.region + ']').checked = true; document.querySelector('input[name=server_name]').value = this.dataset.server; document.querySelector('input[name=char_name]').value = this.dataset.name; }); }); } // ON CLICK FUNCTION TO FETCH CHARACTER PETS (function() { document.getElementById('char_button').addEventListener('click', function() { var region = document.querySelector('input[name=region]:checked').value; var server_name = document.querySelector('input[name=server_name]').value; var char_name = document.querySelector('input[name=char_name]').value; var url = 'http://' + region + '.battle.net/api/wow/character/' + server_name + '/' + char_name + '?fields=guild,titles'; jsonp_request(url, 'fetch_char'); document.getElementById('general_panel').style.display = 'block'; document.getElementById('home_panel').style.display = 'none'; }); })(); //////////////////////////////////
daingun/mobile-armory
js/general.js
JavaScript
agpl-3.0
4,549
/* * Copyright 2015 Trim-marks Inc. * * This file is part of Vivliostyle UI. * * Vivliostyle UI is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Vivliostyle UI is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Vivliostyle UI. If not, see <http://www.gnu.org/licenses/>. */ import vivliostyle from "../../../src/vivliostyle"; import PageViewMode from "../../../src/models/page-view-mode"; import ViewerOptions from "../../../src/models/viewer-options"; import ZoomOptions from "../../../src/models/zoom-options"; import urlParameters from "../../../src/stores/url-parameters"; import vivliostyleMock from "../../mock/models/vivliostyle"; describe("ViewerOptions", function () { let history, location; vivliostyleMock(); beforeEach(function () { history = urlParameters.history; urlParameters.history = {}; location = urlParameters.location; }); afterEach(function () { urlParameters.history = history; urlParameters.location = location; }); describe("constructor", function () { it("retrieves parameters from URL", function () { urlParameters.location = { href: "http://example.com#spread=true" }; let options = new ViewerOptions(); expect(options.pageViewMode()).toEqual(PageViewMode.SPREAD); urlParameters.location = { href: "http://example.com#spread=false" }; options = new ViewerOptions(); expect(options.pageViewMode()).toBe(PageViewMode.SINGLE_PAGE); urlParameters.location = { href: "http://example.com#spread=auto" }; options = new ViewerOptions(); expect(options.pageViewMode()).toBe(PageViewMode.AUTO_SPREAD); }); it("copies parameters from the argument", function () { const other = new ViewerOptions(); other.pageViewMode(PageViewMode.SINGLE_PAGE); other.fontSize(20); other.zoom(ZoomOptions.createFromZoomFactor(1.2)); const options = new ViewerOptions(other); expect(options.pageViewMode()).toBe(PageViewMode.SINGLE_PAGE); expect(options.fontSize()).toBe(20); expect(options.zoom().zoom).toBe(1.2); expect(options.zoom().fitToScreen).toBe(false); }); }); it("write spread option back to URL when update if it is constructed with no argument", function () { urlParameters.location = { href: "http://example.com#spread=true" }; let options = new ViewerOptions(); options.pageViewMode(PageViewMode.SINGLE_PAGE); expect(urlParameters.location.href).toBe("http://example.com#spread=false"); options.pageViewMode(PageViewMode.SPREAD); expect(urlParameters.location.href).toBe("http://example.com#spread=true"); // options.pageViewMode(PageViewMode.AUTO_SPREAD); // expect(urlParameters.location.href).toBe("http://example.com#spread=auto"); // not write back if it is constructed with another ViewerOptions const other = new ViewerOptions(); other.pageViewMode(PageViewMode.SINGLE_PAGE); other.fontSize(20); other.zoom(ZoomOptions.createFromZoomFactor(1.2)); options = new ViewerOptions(other); options.pageViewMode(PageViewMode.SPREAD); expect(urlParameters.location.href).toBe("http://example.com#spread=false"); }); describe("copyFrom", function () { it("copies parameters from the argument to itself", function () { const options = new ViewerOptions(); options.pageViewMode(PageViewMode.SPREAD); options.fontSize(10); options.zoom(ZoomOptions.createFromZoomFactor(1.4)); const other = new ViewerOptions(); other.pageViewMode(PageViewMode.SINGLE_PAGE); other.fontSize(20); other.zoom(ZoomOptions.createFromZoomFactor(1.2)); options.copyFrom(other); expect(options.pageViewMode()).toBe(PageViewMode.SINGLE_PAGE); expect(options.fontSize()).toBe(20); expect(options.zoom().zoom).toBe(1.2); expect(options.zoom().fitToScreen).toBe(false); }); }); describe("toObject", function () { it("converts parameters to an object", function () { const options = new ViewerOptions(); options.pageViewMode(PageViewMode.SPREAD); options.fontSize(20); options.zoom(ZoomOptions.createFromZoomFactor(1.2)); expect(options.toObject()).toEqual({ fontSize: 20, pageViewMode: vivliostyle.viewer.PageViewMode.SPREAD, zoom: 1.2, fitToScreen: false, renderAllPages: true, }); }); }); });
vivliostyle/vivliostyle.js
packages/viewer/test/spec/models/viewer-options-spec.js
JavaScript
agpl-3.0
4,890
/**we have all * @fileoverview * Profile 1/overview and 2/completing * @todo * - package.json * * @version 1 * @copyright ISCPIF-CNRS 2016 * @author romain.loth@iscpif.fr * * @requires comex_user_shared, comex_lib_elts * * NB The uinfo variable should be set to template's user.json_info value. */ // 3 exposed vars for inline js controls var teamCityDiv = document.getElementById('lab_locname_div') var otherInstDiv = document.getElementById('other_inst_div') var otherInstTypeInput = document.getElementById('other_inst_type') // reselecting current_user's info choices function setupSavedItems(uinfo) { // (date and menu values are set up here // but normal text vals are set up via html template, // pic and middle_name are set below from a separate function, // and multi text inputs are set up via form init... fixable to harmonize) for (var i in cmxClt.COLS) { var colType = cmxClt.COLS[i][3] if (colType == 'd' || colType == 'm') { var colName = cmxClt.COLS[i][0] var chosenV = uinfo[colName] // special case if (colName == 'inst_type' && uinfo.insts && uinfo.insts.length) { chosenV = uinfo.insts[0].inst_type } // console.log('setupSavedItems', colName, '('+colType+')' , 'with', chosenV) // if the value is none => there's nothing to do if (chosenV != undefined && chosenV != null) { var tgtElt = document.getElementById(colName) if (tgtElt != null) { // d <=> convert to YY/MM/DD from iso string YYYY-MM-DD if (colType == 'd') { // console.log('setting date', colName, 'with', chosenV) tgtElt.value = chosenV.replace(/-/g,'/') tgtElt.dispatchEvent(new CustomEvent('change')) } // m <=> select saved menus if (colType == 'm') { // console.log('setting menu', colName, 'with', chosenV) var myOption = tgtElt.querySelector(`option[value="${chosenV}"]`) // normal case if (myOption) { tgtElt.selectedIndex = myOption.index tgtElt.dispatchEvent(new CustomEvent('change')) } // this case is really just for inst_type right now else if (tgtElt.querySelector(`option[value="other"]`)) { console.log('setting menu option other for', colName, 'with', chosenV) tgtElt.selectedIndex = tgtElt.querySelector(`option[value="other"]`).index tgtElt.dispatchEvent(new CustomEvent('change')) var relatedFreeTxt = document.getElementById('other_'+colName) if (relatedFreeTxt) { relatedFreeTxt.value = chosenV relatedFreeTxt.dispatchEvent(new CustomEvent('change')) } } // fallback case else { var optionOthers = console.warn(`setupSavedItems: couldn't find option: ${chosenV} for select element: ${colName}`) } } } else { console.warn("setupSavedItems: couldn't find element: "+colName) } } } } } // also pre-setup for images var picShow = document.getElementById('show_pic') if (uinfo.pic_src) { cmxClt.uform.showPic(uinfo.pic_src) } // initialize form controllers var theUForm = cmxClt.uform.Form( // id "comex_profile_form", // onkeyup function completionAsYouGo, // other params { 'multiTextinputs': [{'id':'keywords', 'prevals': uinfo.keywords, 'minEntries': 3 }, {'id':'hashtags', 'prevals': uinfo.hashtags, 'color': "#23A", 'minEntries': 3 }] } ) var deleteUser = document.getElementById('delete_user') deleteUser.checked = false setupSavedItems(uinfo) // monitor inst label (if any), so if label changes => reset inst_type (if any) var instLabelInput = document.getElementById('inst_label') var instTypeInput = document.getElementById('inst_type') var instLabelPreviousVal = instLabelInput.value instLabelInput.onblur = function () { if (instTypeInput.value) { if (instLabelPreviousVal != "" && ( !instLabelInput.value || (instLabelInput.value != instLabelPreviousVal))) { // we reset all inst_type block instTypeInput.value = '' otherInstDiv.style.display='none'; otherInstTypeInput.value=''; } } instLabelPreviousVal = instLabelInput.value // NB don't use uinfo because user may have already changed the form } instTypeInput.onblur = function() { instLabelPreviousVal = instLabelInput.value } // open middlename if there is one if (uinfo.middle_name != null && uinfo.middle_name != "" && uinfo.middle_name != "None") { console.log("showing midname for profile") cmxClt.uform.displayMidName() } // main validation function // ------------------------ function completionAsYouGo() { theUForm.elMainMessage.style.display = 'block' theUForm.elMainMessage.innerHTML = "Checking the answers..." var diagnosticParams = {'fixResidue': true, 'ignore': ['email']} cmxClt.uform.simpleValidateAndMessage(theUForm, diagnosticParams) // timestamp is done server-side } // run first check on existing profile data pre-filled by the template completionAsYouGo() // set up a "Your data was saved" modal box (tied to the SUBMIT button) function addAndShowModal(someHtmlContent) { // create and add modal cmxClt.elts.box.addGenericBox( 'save_info', 'Profile update', someHtmlContent, function(){window.location.reload()} ) // show modal var saveInfoModal = document.getElementById('save_info') saveInfoModal.style.display = 'block' saveInfoModal.style.opacity = 1 } function submitAndModal() { var formdat = theUForm.asFormData(); var postUrl = "/services/user/profile/" if (window.fetch) { fetch(postUrl, { method: 'POST', headers: {'X-Requested-With': 'MyFetchRequest'}, body: formdat, credentials: "same-origin" // <= allows our req to have id cookie }) .then(function(response) { if(response.ok) { response.text().then( function(bodyText) { // console.log("Profile POST was OK, showing answer") addAndShowModal(bodyText) }) } else { response.text().then( function(bodyText) { console.log("Profile POST failed, aborting and showing message") addAndShowModal("<h4>Profile POST server error:</h4>"+bodyText) }) } }) .catch(function(error) { console.warn('fetch error:'+error.message); }); } // also possible using old-style jquery ajax else { $.ajax({ contentType: false, // <=> multipart processData: false, // <=> multipart data: formdat, type: 'POST', url: postUrl, success: function(data) { addAndShowModal(data) }, error: function(result) { console.warn('jquery ajax error with result', result) } }); } } console.log("profile controllers load OK")
moma/comex2
static/js/comex_page_profile_controllers.js
JavaScript
agpl-3.0
8,065
const express = require('express'); const feedr = require('feedr').create(); const router = express.Router(); router.get('/', (req, res) => { feedr.readFeed('https://blog.schul-cloud.org/rss', { requestOptions: { timeout: 2000 }, }, (err, data) => { let blogFeed; try { blogFeed = data.rss.channel[0].item .filter((item) => (item['media:content'] || []).length && (item.link || []).length) .slice(0, 3) .map((e) => { const date = new Date(e.pubDate); const locale = 'en-us'; const month = date.toLocaleString(locale, { month: 'long' }); e.pubDate = `${date.getDate()}. ${month}`; e.description = e.description.join(' '); e.url = e.link[0]; e.img = { src: e['media:content'][0].$.url, alt: e.title, }; return e; }); } catch (e) { blogFeed = []; } res.send({ blogFeed, }); }); }); module.exports = router;
schul-cloud/schulcloud-client
controllers/blog.js
JavaScript
agpl-3.0
906
/* test/auth_route_spec.js -- test Authentication helper * Copyright 2014 Sergei Ianovich * * Licensed under AGPL-3.0 or later, see LICENSE * Process Control Service Web Interface */ var expect = require('expect.js'); var Routes = require('../routes/_auth'); var User = require('../models/user'); describe('Authentication helper', function() { describe("#authenticate", function() { describe("when request for not html page", function() { it("should send 401 if session is not inited", function(done) { var req = { session: {}, url: "someurl", headers: {accept: 'application/json'} }, res = { send: function(code) { expect(code).to.eql(401); done(); }}; Routes.authenticate(req, res, null); }); it("should send 401 if user is not found", function(done) { var req = { session: { operator: 2220 }, headers: {accept: 'application/json'} }, res = { send: function(code) { expect(code).to.eql(401); done(); }}; Routes.authenticate(req, res, null); }); }); describe("when request for html page", function() { it("should redirect to signin if session is not inited", function(done) { var req = { session: {}, url: "someurl", headers: {accept: 'application/html'} }, res = { redirect: function(url) { expect(url).to.eql("/signin"); done(); }}; Routes.authenticate(req, res, null); }); it("should reload if user is not found", function(done) { var req = { session: { operator: 2220 }, headers: {accept: 'application/html'} }, res = { redirect: function(url) { expect(url).to.eql('/signin'); done(); }}; Routes.authenticate(req, res, null); }); }); it("should assign operator", function(done) { var user = null; var userAttrs = { name: "Example User", email: "user@example.com", password: 'password', confirmation: 'password', }; (new User(userAttrs)).save(function(err, user) { var req = { session: { operator: user.email } }, res = { locals: { } }, next = function() { expect(res.locals.operator.toJSON()).to.eql(user.toJSON()); expect(req.operator.toJSON()).to.eql(user.toJSON()); done(); }; Routes.authenticate(req, res, next); }); }); }); });
yanovich/pcs-web
test/auth_routes_test.js
JavaScript
agpl-3.0
2,558
/** * Model for Devices */ Ext.define('FHEM.model.DeviceModel', { extend: 'Ext.data.Model', fields: [ { name: 'DEVICE', type: 'text' } ] });
joergps/SmartLogistics
fhem/www/frontend/www/frontend/app/model/DeviceModel.js
JavaScript
agpl-3.0
198
/* Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'image2', 'sq', { alt: 'Tekst Alternativ', btnUpload: 'Dërgo në server', captioned: 'Captioned image', // MISSING captionPlaceholder: 'Caption', // MISSING infoTab: 'Informacione mbi Fotografinë', lockRatio: 'Mbyll Racionin', menu: 'Karakteristikat e Fotografisë', pathName: 'foto', pathNameCaption: 'caption', // MISSING resetSize: 'Rikthe Madhësinë', resizer: 'Click and drag to resize', // MISSING title: 'Karakteristikat e Fotografisë', uploadTab: 'Ngarko', urlMissing: 'Mungon URL e burimit të fotografisë.', altMissing: 'Alternative text is missing.' // MISSING } );
afshinnj/php-mvc
assets/framework/ckeditor/plugins/image2/lang/sq.js
JavaScript
agpl-3.0
790
/* * This file is part of huborcid. * * huborcid is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * huborcid is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with huborcid. If not, see <http://www.gnu.org/licenses/>. */ // GamePad API // https://dvcs.w3.org/hg/gamepad/raw-file/default/gamepad.html // By Eric Bidelman // FF has Gamepad API support only in special builds, but not in any release (even behind a flag) // Their current implementation has no way to feature detect, only events to bind to. // http://www.html5rocks.com/en/tutorials/doodles/gamepad/#toc-featuredetect // but a patch will bring them up to date with the spec when it lands (and they'll pass this test) // https://bugzilla.mozilla.org/show_bug.cgi?id=690935 Modernizr.addTest('gamepads', !!Modernizr.prefixed('getGamepads', navigator));
Cineca/OrcidHub
src/main/webapp/bower_components/modernizr/feature-detects/gamepad.js
JavaScript
agpl-3.0
1,299
'use strict'; // Load modules const i18n = require('../services/i18n'); const fs = require('fs'); var dateFormat = require('dateformat'); const Remarkable = require('remarkable'); const path = require('path'); const logger = require('../services/logger'); const config = require('../config/config'); const _ = require('lodash'); // Setup const md = new Remarkable({ html: true }); exports.toId = (input) => { return input.replace(/ /g, ''); }; exports.clientConfig = () => { return JSON.stringify({ baseUrl: process.env.REACT_BASEURL || config.react.baseUrl, clientSecret: process.env.REACT_CLIENT_SECRET || config.react.clientSecret, clientId: process.env.REACT_CLIENT_ID || config.react.clientId }); }; exports.cloudinaryConfig = () => JSON.stringify({ cloud_name: config.cloudinary.cloud_name, api_key: config.cloudinary.api_key }); exports.transform = function (parameters, url) { if (!url) { return; } let newUrl; if (!url.includes('cloudinary')) { // cannot transform images that are not from cloudinary var myRegexp = /w_(\d+)/g; var match = myRegexp.exec(parameters); newUrl = 'https://images.break-out.org/' + match[1] + 'x,q80/' + url; return newUrl; } else { newUrl = url.replace(/image\/upload\/.*\//, `image/upload/${parameters}/`); return newUrl; } }; exports.transformVideo = function (parameters, url) { if (!url) { return; } let newUrl; if (!url.includes('cloudinary')) { // cannot transform images that are not from cloudinary return url; } else { newUrl = url.replace(/video\/upload\/.*\//, `video/upload/${parameters}/`); return newUrl; } }; exports.stringify = (obj) => { if (!obj) { return false; } return JSON.stringify(obj); }; exports.thumbnail = (videoUrl, ctx) => { try { if (videoUrl.includes('breakoutmedia.blob.core.windows.net')) { // this video is served from our old azure blob storage where // we can't just change the extension to get a thumbnail // Instead we do nothing and have a black "thumbnail" return ''; } // replace the ending of the video with .png. This will use cloudinary // to automatically generate a thumbnail based on the video url for us return videoUrl.substr(0, videoUrl.lastIndexOf('.')) + '.png'; } catch (err) { logger.error(`Error parsing thumbnail url for url '${videoUrl}'`); } }; function changeExtension(videoUrl, newExtension) { try { if (videoUrl.includes('breakoutmedia.blob.core.windows.net')) { // this video is served from our old azure blob storage where return videoUrl; } // replace the ending of the video with .png. This will use cloudinary // to automatically generate a thumbnail based on the video url for us return videoUrl.substr(0, videoUrl.lastIndexOf('.')) + '.' + newExtension; } catch (err) { logger.error(`Error changing extension to ${newExtension} for url '${videoUrl}'`); } } exports.changeExtension = changeExtension; exports.transformVideoAndExtension = (format, extension, videoUrl, ctx) => { let newUrl = changeExtension(videoUrl, extension); return exports.transformVideo(format, newUrl, ctx); }; /** * Concatenates first and second. * @param first * @param second */ exports.concat = (first, second) => first + second; /** * Returns true if v1 == v2. * @param v1 * @param v2 * @param options * @returns {*} */ exports.ifCond = function (v1, v2, options) { if (v1 === v2) { return options.fn(this); } return options.inverse(this); }; exports.weakIfCond = function (v1, v2, options) { if (v1 == v2) { return options.fn(this); } return options.inverse(this); }; exports.fixed = function (v1, options) { let number = new Number(options.fn(this)); return number.toFixed(v1); }; exports.isEven = function (context) { if ((context.data.index % 2) === 0) { return context.fn(this); } else { return context.inverse(this); } }; exports.isOdd = function (context) { if ((context.data.index % 2) !== 0) { return context.fn(this); } else { return context.inverse(this); } }; exports.isLast = function (context) { if (context.data.last) { return context.fn(this); } else { return context.inverse(this); } }; /** * Render markdown from content/mdFileName to html * @param mdFileName * @returns rendered html */ exports.markdown = function renderMarkdown(mdFileName, context) { const rawMd = loadFileContent(mdFileName); const html = md.render(rawMd); return html; }; exports.date = function makeDate(timestamp, context) { return new Date(timestamp); }; exports.beautifuldate = function makeDate(timestamp, context) { if (timestamp == null) { return 'No Date Available'; } let date = new Date(timestamp); let beautifuldate = dateFormat(date, 'dS mmmm, h:MM TT'); return beautifuldate; }; exports.md = function renderMarkdown(rawMd, context) { const html = md.render(rawMd); return html; }; exports.contentfulImage = function (imageObject, clazz, id, context) { clazz = (clazz != null) ? clazz : ''; id = (id != null) ? id : ''; const url = imageObject.fields.file.url; const alt = (imageObject.fields.description != null) ? imageObject.fields.description : ''; return `<img src="${url}" alt="${alt}" class="${clazz}" id="${id}"/>`; }; function loadFileContent(mdFileName) { const path = getFilepath(mdFileName); return fs.readFileSync(path, 'utf-8'); } function getFilepath(mdFileName) { const contentFolderPath = path.resolve('content/'); return `${contentFolderPath}/${mdFileName}.md`; } /** * Tries to find the matching translation for the language the browser sent us. * @param text * @param options * @private */ exports.__ = (text, options) => { if (!options.data.root.language) { throw 'You did not pass the language to handlebars!'; } const view = options.data.exphbs.view; let viewArr = []; if (view) { if (view.indexOf('\\') > -1) { viewArr = view.split('\\'); } else { viewArr = view.split('/'); } } if (text.indexOf('.') > -1) { viewArr = text.split('.'); text = viewArr.pop(); } else if (!view) { logger.error(`Could not parse view in ${options.data.exphbs}`); } return i18n.translate(viewArr[viewArr.length - 1].toUpperCase(), text.toUpperCase(), options.data.root.language); }; exports.ifOr = function (v1, v2, options) { if (v1 || v2) { return options.fn(this); } return options.inverse(this); }; /* eslint-disable no-console */ exports.debug = function (optionalValue) { console.log('Current Context'); console.log('===================='); console.log(this); if (optionalValue) { console.log('Value'); console.log('===================='); console.log(optionalValue); } }; /*eslint-enable no-console */ exports.json = function (context) { return JSON.stringify(context); }; exports.getAtIndex = function (array, index) { return array[index]; }; /** * Calculate a 32 bit FNV-1a hash * Found here: https://gist.github.com/vaiorabbit/5657561 * Ref.: http://isthe.com/chongo/tech/comp/fnv/ * * @param {string} str the input value * @param {boolean} [asString=false] set to true to return the hash value as * 8-digit hex string instead of an integer * @param {integer} [seed] optionally pass the hash of the previous chunk * @returns {integer | string} */ exports.hash = (str, seed) => { /*jshint bitwise:false */ var i, l, hval = (seed === undefined) ? 0x811c9dc5 : seed; for (i = 0, l = str.length; i < l; i++) { hval ^= str.charCodeAt(i); hval += (hval << 1) + (hval << 4) + (hval << 7) + (hval << 8) + (hval << 24); } // Convert to 8 digit hex string return ('0000000' + (hval >>> 0).toString(16)).substr(-8); }; exports.relativeTime = function (timestamp) { function leftPad(zahlen) { let string = '00' + zahlen; return string.substring(string.length - 2); } const MONTHS = ['Januar', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember']; let dO = new Date((timestamp + (60 * 60 * 2)) * 1000); // TODO: Hack for timezone! Fix this in 2018 let now = new Date(Date.now() + 60 * 60 * 2 * 1000); let difference = now - dO.getTime(); if (difference < 60 * 1000) { return 'Gerade eben'; } else if (difference < 60 * 60 * 1000) { return `vor ${Math.floor(difference / 60 / 1000)} Minuten`; } else if (difference < 60 * 60 * 24 * 1000) { return `vor ${Math.floor(difference / 60 / 60 / 1000)} Stunden`; } else { return `am ${dO.getDate()}. ${MONTHS[dO.getMonth()]} um ${dO.getHours()}:${leftPad(dO.getMinutes())}`; } }; exports.length = function (array) { return array.length; }; exports.strColor = (str) => { if (!str) { return 'gray'; } var hash = 0; for (let i = 0; i < str.length; i++) { hash = str.charCodeAt(i) + ((hash << 5) - hash); } var colour = '#'; for (let i = 0; i < 3; i++) { var value = (hash >> (i * 8)) & 0xFF; colour += ('00' + value.toString(16)).substr(-2); } return colour; }; exports.round = (amount) => { return Math.round(parseFloat(amount)).toString().replace(/\B(?=(\d{3})+(?!\d))/g, '.'); }; exports.roundWithoutFormat = (amount) => { return Math.round(parseFloat(amount)); }; exports.addOne = (amount) => { return (parseFloat(amount) + 1); }; exports.prettyLocation = (location) => { //Check if it exists. if (!location) return ''; var locString = ''; //Check for best Level if (location.hasOwnProperty('LOCALITY')) { locString = location.LOCALITY; } else if (location.hasOwnProperty('ADMINISTRATIVE_AREA_LEVEL_3')) { locString = location.ADMINISTRATIVE_AREA_LEVEL_3; } else if (location.hasOwnProperty('ADMINISTRATIVE_AREA_LEVEL_2')) { locString = location.ADMINISTRATIVE_AREA_LEVEL_2; } else if (location.hasOwnProperty('ADMINISTRATIVE_AREA_LEVEL_1')) { locString = location.ADMINISTRATIVE_AREA_LEVEL_1; } if (location.hasOwnProperty('COUNTRY')) { if (locString !== '') { locString += ', '; } locString += location.COUNTRY; } if (locString !== '') { locString = ' in ' + locString; } return locString; }; exports.challengeHasProof = (status) => { return status === 'WITH_PROOF'; }; exports.isOlderTenMinutes = (date, context) => { if ((new Date(date * 1000 + 10 * 60 * 1000).getTime() < new Date().getTime())) { return context.fn(this); } else { return context.inverse(this); } }; exports.isNewerTenMinutes = (date, context) => { if ((new Date(date * 1000 + 10 * 60 * 1000).getTime() > new Date().getTime())) { return context.fn(this); } else { return context.inverse(this); } }; exports.displayCurrency = (amount, context) => Number(amount).toFixed(2); /** * This handlebars helper will render a block in the handlerbars file if the config value is true * * Example: * * {{#isEnabled 'printHeadline.enabled'}} <h1>I am a headline </h1> {{/isEnabled}} * * @param key The config key to look up * @param context Handlebars context * @returns {string} Either the block to be rendered or an empty string */ exports.isEnabled = function (key, context) { const value = _.get(config, key); if (value === true) { return context.fn(this); } else if (value === false) { return ''; } else { throw new Error(`Found value '${value}' for config key '${key}'. Expected boolean value`); } }; /** * Returns the value for a key from the config file * * Example: {{config 'backend.accessToken'}} will render the accessToken into the handlebars file * * @param key The config key to look up * @param context Handlebars context * @returns {*} The value found for the given key */ exports.config = function (key, context) { const value = _.get(config, key); if (value) { return value; } else { throw new Error(`Couldn't find value for key '${key}' in configuration`); } };
BreakOutEvent/breakout-frontend
src/server/services/helpers.js
JavaScript
agpl-3.0
12,022
define(function(require) { 'use strict'; var _ = require('underscore'); var PIXI = require('pixi'); var ArrowView = require('common/v3/pixi/view/arrow'); var Constants = require('constants'); var EFieldDetectorArrowView = ArrowView.extend({ initialize: function(options) { options = _.extend({ label: 'An Arrow', tailWidth: 8, headWidth: 20, headLength: 20, fillColor: Constants.EFieldDetectorView.DISPLAY_COLOR }, options); this.label = options.label; this.model = new ArrowView.ArrowViewModel({ originX: 0, originY: 0, targetX: 0, targetY: 0, minLength: null }); this.scale = 1; this.value = 0; ArrowView.prototype.initialize.apply(this, [ options ]); }, initGraphics: function() { ArrowView.prototype.initGraphics.apply(this, arguments); var textStyle = { font: '11px Helvetica Neue', fill: Constants.EFieldDetectorView.DISPLAY_COLOR }; var label = new PIXI.Text(this.label, textStyle); var value = new PIXI.Text('10 V/m', textStyle); label.resolution = this.getResolution(); value.resolution = this.getResolution(); value.y = 12; this.text = new PIXI.Container(); this.text.addChild(label); this.text.addChild(value); this.displayObject.addChild(this.text); this.labelText = label; this.valueText = value; this.update(); this.drawArrow(); }, update: function() { var length = this.value * this.scale; this.model.set('targetY', this.model.get('originY') + length); this.updateText(); }, updateText: function(defaultDirection) { var length = this.value * this.scale; if (length === 0 && !defaultDirection) this.text.y = Math.round(-this.text.height / 2); else if (length > 0 || (defaultDirection && defaultDirection < 0)) this.text.y = Math.round(-this.text.height + 4); else this.text.y = 4; this.labelText.x = Math.round(-this.labelText.width / 2); this.valueText.x = Math.round(-this.valueText.width / 2); this.valueText.text = Math.abs(Math.round(this.value)) + ' V/m'; }, setScale: function(scale) { this.scale = scale; this.update(); }, setValue: function(value) { this.value = value; this.update(); }, alignTextAbove: function() { this.updateText(-1); }, alignTextBelow: function() { this.updateText(1); }, centerOn: function(x, y) { this.model.centerOn(x, y); this.updateText(); }, moveToY: function(y) { this.model.moveTo(this.model.get('originX'), y); }, getTotalHeight: function() { return this.displayObject.height; }, getArrowHeight: function() { return Math.abs(Math.round(this.value)); }, getTextHeight: function() { return this.text.height; }, getOriginY: function() { return this.model.get('originY'); }, getTargetY: function() { return this.model.get('targetY'); }, showValue: function() { this.valueText.visible = true; }, hideValue: function() { this.valueText.visible = false; } }); return EFieldDetectorArrowView; });
Connexions/simulations
capacitor-lab/src/js/views/e-field-detector-arrow.js
JavaScript
agpl-3.0
3,929
import * as R from 'ramda'; import { getPatchPath } from 'xod-project'; import { isAmong } from 'xod-func-tools'; import { def } from './types'; import { CHANGE_TYPES } from './constants'; const isEqualPatchPaths = def( 'isEqualPatchPaths :: Patch -> Patch -> Boolean', R.useWith(R.equals, [getPatchPath, getPatchPath]) ); const createPatchChange = def( 'createPatchChange :: AnyChangeType -> Patch -> AnyPatchChange', (changeType, patch) => R.compose( R.when( () => changeType === CHANGE_TYPES.ADDED || changeType === CHANGE_TYPES.MODIFIED, R.assoc('data', patch) ), R.applySpec({ path: getPatchPath, changeType: R.always(changeType), }) )(patch) ); export const calculateAdded = def( 'calculateAdded :: [Patch] -> [Patch] -> [AddedPatchChange]', R.compose( R.map(createPatchChange(CHANGE_TYPES.ADDED)), R.flip(R.differenceWith(isEqualPatchPaths)) ) ); export const calculateModified = def( 'calculateModified :: [Patch] -> [Patch] -> [ModifiedPatchChange]', (before, after) => { const beforeIds = R.map(getPatchPath, before); return R.compose( R.map(createPatchChange(CHANGE_TYPES.MODIFIED)), R.difference(R.__, before), R.filter(R.compose(isAmong(beforeIds), getPatchPath)) )(after); } ); export const calculateDeleted = def( 'calculateDeleted :: [Patch] -> [Patch] -> [DeletedPatchChange]', R.compose( R.map(createPatchChange(CHANGE_TYPES.DELETED)), R.differenceWith(isEqualPatchPaths) ) ); export const calculateDiff = def( 'calculateDiff :: [Patch] -> [Patch] -> [AnyPatchChange]', R.converge(R.unapply(R.unnest), [ calculateAdded, calculateModified, calculateDeleted, ]) );
xodio/xod
packages/xod-fs/src/patchDiff.js
JavaScript
agpl-3.0
1,762
import 'mad/model/model'; import 'mad/model/serializer/cake_serializer'; /** * @inherits {mad.Model} * @parent index * * The GroupUser model * * @constructor * Creates a groupUser * @param {array} options * @return {passbolt.model.GroupUser} */ var GroupUser = passbolt.model.GroupUser = mad.Model.extend('passbolt.model.GroupUser', /** @static */ { /* ************************************************************** */ /* MODEL DEFINITION */ /* ************************************************************** */ validateRules: { }, attributes: { id: 'string', group_id: 'string', user_id: 'string', User: 'passbolt.model.User.model', Group: 'passbolt.model.Group.model' }, membershipType: { 0 : __('Member'), 1 : __('Group manager') }, /* ************************************************************** */ /* CRUD FUNCTION */ /* ************************************************************** */ /** * Create a new groupUser * @param {array} attrs Attributes of the new groupUser * @return {jQuery.Deferred) */ create : function (attrs, success, error) { var self = this; var params = mad.model.serializer.CakeSerializer.to(attrs, this); return mad.net.Ajax.request({ url: APP_URL + 'groupsUsers', type: 'POST', params: params, success: success, error: error }).pipe(function (data, textStatus, jqXHR) { // pipe the result to convert cakephp response format into can format // else the new attribute are not well placed var def = $.Deferred(); def.resolveWith(this, [mad.model.serializer.CakeSerializer.from(data, self)]); return def; }); }, /** * Destroy a groupUser following the given parameter * @params {string} id the id of the instance to remove * @return {jQuery.Deferred) */ destroy : function (id, success, error) { var params = {id:id}; return mad.net.Ajax.request({ url: APP_URL + 'groupsUsers/{id}', type: 'DELETE', params: params, success: success, error: error }); }, /** * Find a groupUser following the given parameter * @param {array} params Optional parameters * @return {jQuery.Deferred) */ findOne: function (params, success, error) { params.children = params.children || false; return mad.net.Ajax.request({ url: APP_URL + 'groupsUsers/{id}.json', type: 'GET', params: params, success: success, error: error }); }, /** * Find a bunch of groupsUsers following the given parameters * @param {array} params Optional parameters * @return {jQuery.Deferred) */ findAll: function (params, success, error) { return mad.net.Ajax.request({ url: APP_URL + 'groupsUsers.json', type: 'GET', params: params, success: success, error: error }); }, update : function(id, attrs, success, error) { var self = this; // remove not desired attributes delete attrs.created; delete attrs.modified; // format data as expected by cakePHP var params = mad.model.serializer.CakeSerializer.to(attrs, this); // add the root of the params, it will be used in the url template params.id = id; return mad.net.Ajax.request({ url: APP_URL + 'groupsUsers/{id}', type: 'PUT', params: params, success: success, error: error }).pipe(function (data, textStatus, jqXHR) { // pipe the result to convert cakephp response format into can format var def = $.Deferred(); def.resolveWith(this, [mad.model.serializer.CakeSerializer.from(data, self)]); return def; }); } }, /** @prototype */ { }); export default GroupUser;
et304383/passbolt_api
app/webroot/js/app/model/group_user.js
JavaScript
agpl-3.0
3,555
// Xiongxiong // Bearer token codec // AGPLv3 or later // Copyright (c) 2014, 2015 Genome Research Limited var crypto = require('crypto'); module.exports = function(/* privateKey, lifetime, algorithm OR hash */) { var privateKey, lifetime, algorithm, xiongxiong; // Parse arguments if (arguments.length) { // Try to get options from hash first, then fallback to positional // and finally, where appropriate, to defaults privateKey = arguments[0].privateKey || arguments[0]; lifetime = parseInt(arguments[0].lifetime || arguments[1], 10) || 3600; algorithm = arguments[0].algorithm || arguments[2] || 'sha1'; // Private key must be a string or a buffer if (!(typeof privateKey == 'string' || privateKey instanceof Buffer)) { throw new TypeError('Invalid arguments: Private key must be a string or buffer'); } } else { // Need at least a private key throw new Error('No private key specified'); } var getHMAC = (function() { // Check algorithm is supported if (crypto.getHashes().indexOf(algorithm) < 0) { throw new Error('Unsupported hash algorithm \'' + algorithm + '\''); } return function(message) { var hmac = crypto.createHmac(algorithm, privateKey); hmac.setEncoding('base64'); hmac.end(message); return hmac.read(); }; })(); // Return value xiongxiong = { encode: function(data, callback) { // Flatten array if (Array.isArray(data)) { data = data.join(':'); } if (typeof data != 'string') { callback(new TypeError('Invalid arguments: Seed data must be a string or array of strings'), null); } else { // Create a 48-bit salt crypto.randomBytes(6, function(err, salt) { if (err) { callback(err, null); } else { var expiration = Math.floor(Date.now() / 1000) + lifetime, message = [data, expiration, salt.toString('base64')].join(':'), // Generate HMAC of data:expiration:salt password = getHMAC(message); // Return token and basic authentication pair callback(null, Object.freeze({ expiration: expiration, // Unix epoch accessToken: (new Buffer([message, password].join(':'))).toString('base64'), basicLogin: (new Buffer(message)).toString('base64'), basicPassword: password })); } }); } }, decode: function(/* bearer/basic auth data */) { var output = {}; switch (arguments.length) { case 1: // Split bearer token and decode as basic auth var accessToken = (new Buffer(arguments[0], 'base64')).toString().split(':'); var basicPassword = accessToken.pop(), basicLogin = (new Buffer(accessToken.join(':'))).toString('base64'); output = this.decode(basicLogin, basicPassword); break; case 2: // Basic authentication data var basicLogin = (new Buffer(arguments[0], 'base64')).toString(), extracted = basicLogin.split(':'), basicPassword = arguments[1]; // Pass the salt extracted.pop(); // Expiration is penultimate element // n.b., JavaScript Date in ms, hence x1000 on Unix epoch Object.defineProperty(output, 'expiration', { configurable: false, writable: false, enumerable: true, value: new Date(parseInt(extracted.pop(), 10) * 1000) }); // Convert to string if we only have one element remaining Object.defineProperty(output, 'data', { configurable: false, writable: false, enumerable: true, value: extracted.length == 1 ? extracted[0] : extracted, }); // Validity check Object.defineProperty(output, 'valid', { configurable: false, enumerable: true, get: (function() { if (basicPassword == getHMAC(basicLogin)) { return function() { // Match: Valid until expiration return Date.now() <= this.expiration; }; } else { // No match: Invalid return function() { return false; } } })() }); break; default: Object.defineProperty(output, 'valid', { configurable: false, writable: false, enumerable: true, value: false }); break; } return Object.freeze(output); } }; // Set aliases (legacy API) xiongxiong.create = xiongxiong.encode; xiongxiong.extract = xiongxiong.decode; return Object.freeze(xiongxiong); };
wtsi-hgi/xiongxiong
index.js
JavaScript
agpl-3.0
5,003
//{block name="backend/create_backend_order/controller/main"} // Ext.define('Shopware.apps.SwagBackendOrder.controller.Main', { /** * extends from the standard ExtJs Controller */ extend: 'Ext.app.Controller', snippets: { error: { customer: '{s namespace="backend/swag_backend_order/view/main" name="swagbackendorder/error/customer"}Please select a customer.{/s}', billing: '{s namespace="backend/swag_backend_order/view/main" name="swagbackendorder/error/billing"}Please select a billing address.{/s}', payment: '{s namespace="backend/swag_backend_order/view/main" name="swagbackendorder/error/payment"}Please select a payment method.{/s}', shippingArt: '{s namespace="backend/swag_backend_order/view/main" name="swagbackendorder/error/shipping_art"}Please select a shipping art.{/s}', positions: '{s namespace="backend/swag_backend_order/view/main" name="swagbackendorder/error/positions"}Please add positions.{/s}', textInvalidArticle: '{s namespace="backend/swag_backend_order/view/main" name="swagbackendorder/error/invalid_article"}Invalid article: {/s}', invalidArticleTitle: '{s namespace="backend/swag_backend_order/view/main" name="swagbackendorder/error/invalid_article_title"}Error!{/s}', instanceText: '{s namespace="backend/swag_backend_order/view/main" name="swagbackendorder/error/instanceText"}You can not create more than one order at the same time.{/s}', instanceTitle: '{s namespace="backend/swag_backend_order/view/main" name="swagbackendorder/error/instanceTitle"}Erro!{/s}', title: '{s namespace="backend/swag_backend_order/view/main" name="swagbackendorder/error/title"}Error! Couldn\'t create order{/s}', mailTitle: '{s namespace="backend/swag_backend_order/view/main" name="swagbackendorder/error/mail_title"}Error! Couldn\'t send mail{/s}' }, success: { text: '{s namespace="backend/swag_backend_order/view/main" name="swagbackendorder/success/text"}Order was created successfully. Ordernumber: {/s}', title: '{s namespace="backend/swag_backend_order/view/main" name="swagbackendorder/success/title"}Success!{/s}' }, title: '{s namespace="backend/swag_backend_order/view/main" name="swagbackendorder/title/selected_user"}Create order for{/s}' }, /** * A template method that is called when your application boots. * It is called before the Application's launch function is executed * so gives a hook point to run any code before your Viewport is created. * * @return void */ init: function () { var me = this; //checks if a window is already open var createOrderWindow = Ext.getCmp('swagBackendOrderWindow'); if (createOrderWindow instanceof Ext.window.Window) { Ext.Msg.alert(me.snippets.error.instanceTitle, me.snippets.error.instanceText); return; } me.control({ 'createbackendorder-customer-billing': { selectBillingAddress: me.onSelectBillingAddress }, 'createbackendorder-customer-shipping': { selectShippingAddress: me.onSelectShippingAddress, selectBillingAsShippingAddress: me.onSelectBillingAsShippingAddress, calculateTax: me.onCalculateTax }, 'createbackendorder-customer-payment': { selectPayment: me.onSelectPayment }, 'createbackendorder-additional': { changeAttrField: me.onChangeAttrField, changeDesktopType: me.onChangeDesktopType }, 'createbackendorder-customersearch': { selectCustomer: me.onSelectCustomer }, 'createbackendorder-toolbar': { openCustomer: me.onOpenCustomer, createCustomer: me.onCreateCustomer, changeCurrency: me.onChangeCurrency, changeCustomer: me.onChangeCustomer, changeLanguage: me.onChangeLanguage }, 'createbackendorder-mainwindow': { createOrder: me.onCreateOrder }, 'createbackendorder-shippingcosts': { addShippingCosts: me.onAddShippingCosts }, 'createbackendorder-position-grid': { openArticle: me.onOpenArticle, articleNameSelect: me.onArticleSelect, articleNumberSelect: me.onArticleSelect, cancelEdit: me.onCancelEdit }, 'createbackendorder-totalcostsoverview': { calculateTax: me.onCalculateTax, changeNetCheckbox: me.onChangeNetCheckbox } }); me.getPluginConfig(); /** * holds the actual orderData */ me.orderModel = Ext.create('Shopware.apps.SwagBackendOrder.model.CreateBackendOrder', {}); me.orderAttributeModel = Ext.create('Shopware.apps.SwagBackendOrder.model.OrderAttribute', {}); me.createBackendOrderStore = me.subApplication.getStore('CreateBackendOrder'); me.orderModel.set('currencyFactor', 1); me.currencyStore = me.subApplication.getStore('Currency').load(); //passed a user id if (typeof me.subApplication.params !== 'undefined') { if (me.subApplication.params.userId) { me.onSelectCustomer(null, me.subApplication.params.userId); } } /** * initializes the window */ me.window = me.getView('main.Window').create({ id: 'swagBackendOrderWindow', subApplication: me.subApplication, orderModel: me.orderModel, createBackendOrderStore: me.createBackendOrderStore }).show(); me.callParent(arguments); }, /** * creates the order */ onCreateOrder: function (positionsGridContainer, modus) { var me = this, errmsg = ""; me.modus = modus; me.window.disable(true); /** * get the grid component for the position listing */ me.positionsGrid = positionsGridContainer.getComponent('positionsGrid'); /** * checks if all required fields was setted */ var customerStore = me.subApplication.getStore('Customer'); if (customerStore.count() > 0) { if (me.orderModel.get('billingAddressId') == 0) { errmsg += me.snippets.error.billing + '<br>'; } if (me.orderModel.get('paymentId') == 0) { errmsg += me.snippets.error.payment + '<br>'; } if (me.orderModel.get('dispatchId') == 0) { errmsg += me.snippets.error.shippingArt + '<br>'; } } else { errmsg += me.snippets.error.customer + '<br>'; } var positionsStore = me.positionsGrid.getStore(); if (positionsStore.count() == 0) { errmsg += me.snippets.error.positions + '<br>' } if (errmsg.length > 0) { me.window.enable(true); Shopware.Notification.createGrowlMessage(me.snippets.error.title, errmsg); return; } //gets the positionModel which belongs to the actual orderModel var positionOrderStore = me.orderModel.position(); if (positionOrderStore.count() > 0) { positionOrderStore.removeAll(); } //iterates the created positions and adds every record to the positionModel positionsStore.each( function (record) { positionOrderStore.add(record); } ); var orderAttributeStore = me.orderModel.orderAttribute(); orderAttributeStore.add(me.orderAttributeModel); /** * sends the request to the php controller */ me.orderModel.set('total', me.totalCostsModel.get('total')); me.orderModel.set('totalWithoutTax', me.totalCostsModel.get('totalWithoutTax')); me.createBackendOrderStore.sync({ success: function (response) { me.orderId = response.proxy.reader.rawData.orderId; me.ordernumber = response.proxy.reader.rawData.ordernumber; me.mailErrorMessage = response.proxy.reader.rawData.mail; switch (me.modus) { case 'new': me.window.close(); if (response.proxy.reader.rawData.mail) { Shopware.Notification.createGrowlMessage(me.snippets.error.mailTitle, me.mailErrorMessage); } Shopware.Notification.createGrowlMessage(me.snippets.success.title, me.snippets.success.text + me.ordernumber); Shopware.app.Application.addSubApplication({ name: 'Shopware.apps.SwagBackendOrder', action: 'detail' }); break; case 'close': me.window.close(); break; case 'detail': if (me.orderId > 0) { Shopware.app.Application.addSubApplication({ name: 'Shopware.apps.Order', action: 'detail', params: { orderId: me.orderId } }); } if (response.proxy.reader.rawData.mail) { Shopware.Notification.createGrowlMessage(me.snippets.error.mailTitle, me.mailErrorMessage); } Shopware.Notification.createGrowlMessage(me.snippets.success.title, me.snippets.success.text + ' - ' + me.ordernumber); me.window.close(); break; default: break; } }, failure: function (response) { var article = response.proxy.reader.rawData.article; if (article || article == "") { Shopware.Notification.createGrowlMessage(me.snippets.error.title, me.snippets.error.textInvalidArticle + ' ' + article); } else { Shopware.Notification.createGrowlMessage(me.snippets.error.title, response.proxy.reader.rawData.message); } me.window.enable(true); } }); }, /** * event which is fired by the shipping combobox and the number fields * * @param shippingCosts * @param shippingCostsNet * @param dispatchId * @param shippingCostsFields */ onAddShippingCosts: function (shippingCosts, shippingCostsNet, dispatchId, shippingCostsFields) { var me = this; if (shippingCostsFields !== undefined) { me.shippingCostsFields = shippingCostsFields; shippingCosts = me.calculateCurrency(shippingCosts); shippingCostsNet = me.calculateCurrency(shippingCostsNet); shippingCostsFields[0].setValue(shippingCosts); shippingCostsFields[1].setValue(shippingCostsNet); } me.orderModel.set('shippingCosts', shippingCosts); me.orderModel.set('shippingCostsNet', shippingCostsNet); if (me.orderModel.get('dispatchId') != undefined && me.orderModel.get('dispatchId') != dispatchId) { me.orderModel.set('dispatchId', dispatchId); } me.createBackendOrderStore.add(me.orderModel); me.totalCostsModel = me.subApplication.getStore('TotalCosts').getAt(0); me.totalCostsModel.set('shippingCosts', shippingCosts); }, /** * selects the correct billing address and updates it to the default address * * @param record * @param billing */ onSelectBillingAddress: function (record, billing) { var me = this; record = record[0].data; Ext.Ajax.request({ url: '{url action="setBillingAddress"}', params: { salutation: record.salutation, company: record.company, firstName: record.firstName, lastName: record.lastName, city: record.city, zipCode: record.zipCode, countyId: record.countryId, phone: record.phone, street: record.street, vatId: record.vatId, additionalAddressLine1: record.additionalAddressLine1, additionalAddressLine2: record.additionalAddressLine2, department: record.department, userId: me.customerStore.getAt(0).get('id') }, success: function (response) { var responseObj = Ext.JSON.decode(response.responseText); me.orderModel.set('billingAddressId', responseObj.billingAddressId); } }); }, /** * selects the correct shipping address and updates it to the default address * * @param record false for no selected record, otherwise a single data model */ onSelectShippingAddress: function (record) { var me = this; if (record === false) { // No shipping address selected. var EMPTY_SHIPPING_ADDRESS_ID = 0; // Magic constant me.orderModel.set('shippingAddressId', EMPTY_SHIPPING_ADDRESS_ID); return; } record = record.data; Ext.Ajax.request({ url: '{url action="setShippingAddress"}', params: { salutation: record.salutation, company: record.company, firstName: record.firstName, lastName: record.lastName, city: record.city, zipCode: record.zipCode, countyId: record.countryId, street: record.street, additionalAddressLine1: record.additionalAddressLine1, additionalAddressLine2: record.additionalAddressLine2, department: record.department, userId: me.customerStore.getAt(0).get('id') }, success: function (response) { var responseObj = Ext.JSON.decode(response.responseText); me.orderModel.set('shippingAddressId', responseObj.shippingAddressId); } }); }, /** * fired when the user selects a payment * sets the payment in the orderModel * * @param record */ onSelectPayment: function (record) { var me = this; me.orderModel.set('paymentId', record[0].data.id); }, /** * Event will be fired when the user search for an article number in the row editor * and selects an article in the drop down menu. * * @param [object] editor - Ext.grid.plugin.RowEditing * @param [string] value - Value of the Ext.form.field.Trigger * @param [object] record - Selected record */ onArticleSelect: function (editor, value, record) { var me = this; var columns = editor.editor.items.items, updateButton = editor.editor.floatingButtons.items.items[0]; updateButton.setDisabled(true); //sends a request to get the price for the customer group Ext.Ajax.request({ url: '{url action="getCustomerGroupPriceByOrdernumber"}', params: { ordernumber: record.get('number'), customerId: me.orderModel.get('customerId') }, success: function (response) { var responseObj = Ext.JSON.decode(response.responseText); var result = responseObj.data; var price = 0; if (responseObj.success == true) { price = me.calculateCurrency(result.price); } else { price = me.calculateCurrency(record.get('price')); } if (me.orderModel.get('net')) { price = me.calculateNetPrice(price, record.get('tax')); } /** * columns[0] -> selected * columns[1] -> articlenumber * columns[2] -> articlename * columns[3] -> quantity * columns[4] -> price * columns[5] -> total * columns[6] -> tax * columns[7] -> instock */ columns[1].setValue(record.get('number')); columns[2].setValue(record.get('name')); columns[3].setValue(1); columns[4].setValue(price); columns[7].setValue(record.get('inStock')); var taxComboStore = columns[6].store; var valueField = columns[6].valueField; var displayField = columns[6].displayField; var recordNumber = taxComboStore.findExact(valueField, record.get('taxId'), 0); var displayValue = taxComboStore.getAt(recordNumber).data[displayField]; columns[6].setValue(record.get('taxRate')); columns[6].setRawValue(displayValue); columns[6].selectedIndex = recordNumber; updateButton.setDisabled(false); } }); }, /** * Event listener method which is fired when the user cancel the row editing in the position grid * on the detail page. If the edited record is a new position, the position will be removed. * * @param grid * @param eOpts */ onCancelEdit: function (grid, eOpts) { var record = eOpts.record, store = eOpts.store; if (!(record instanceof Ext.data.Model) || !(store instanceof Ext.data.Store)) { return; } if (record.get('articleId') === 0 && record.get('articleNumber') === '') { store.remove(record); } }, /** * fires only when a new value was selected from the drop down menu to select the correct customer by his id * * @param newValue * @param customerId */ onSelectCustomer: function (newValue, customerId) { var me = this; me.customerStore = me.subApplication.getStore('Customer').load({ params: { searchParam: customerId } }); me.customerStore.on('load', function () { if (Ext.isObject(me.customerStore)) { me.orderModel.set('customerId', customerId); me.customerSelected = true; if (typeof me.customerStore.getAt(0) === 'undefined') { return; } var billingModel = me.customerStore.getAt(0).billing().getAt(0); var title = me.snippets.title + ' ' + billingModel.get('firstName') + ' ' + billingModel.get('lastName'); if (billingModel.get('number')) { title += ' - ' + billingModel.get('number'); } if (billingModel.get('company')) { title += ' - ' + billingModel.get('company'); } me.window.setTitle(title); } }); }, /** * opens an article from the positions grid * * @param record */ onOpenArticle: function (record) { Shopware.app.Application.addSubApplication({ name: 'Shopware.apps.Article', action: 'detail', params: { articleId: record.get('articleId') } }); }, /** * opens the selected customer */ onOpenCustomer: function () { var me = this, customerId = me.subApplication.getStore('Customer').getAt(0).get('id'); Shopware.app.Application.addSubApplication({ name: 'Shopware.apps.Customer', action: 'detail', params: { customerId: customerId } }); }, /** * @param createGuest */ onCreateCustomer: function (createGuest) { var me = this, email = '', guest = false; if (createGuest) { email = me.validationMail; guest = true; } Shopware.app.Application.addSubApplication({ name: 'Shopware.apps.Customer', action: 'detail', params: { guest: guest, email: email } }); }, /** * calculates the new price for another currency * * @param comboBox * @param newValue * @param oldValue * @param eOpts */ onChangeCurrency: function (comboBox, newValue, oldValue, eOpts) { var me = this, shippingCosts = 0, shippingCostsNet = 0; me.orderModel.set('currencyId', newValue); var currencyIndex = me.currencyStore.findExact('id', newValue); var newCurrency = me.currencyStore.getAt(currencyIndex); newCurrency.set('selected', 1); if (oldValue !== undefined) { currencyIndex = me.currencyStore.findExact('id', oldValue); var oldCurrency = me.currencyStore.getAt(currencyIndex); oldCurrency.set('selected', 0); } var positionJsonString = ''; if (me.positionStore instanceof Ext.data.Store) { var positionArray = []; me.positionStore.each(function (record) { positionArray.push(record.data); }); positionJsonString = Ext.JSON.encode(positionArray); } Ext.Ajax.request({ url: '{url action="calculateCurrency"}', params: { positions: positionJsonString, oldCurrencyId: oldValue, newCurrencyId: newValue, shippingCosts: me.orderModel.get('shippingCosts'), shippingCostsNet: me.orderModel.get('shippingCostsNet') }, success: function (response) { var responseObj = Ext.JSON.decode(response.responseText).data; if (typeof responseObj === 'undefined') { return; } for (var i = 0; i < responseObj.positions.length; i++) { var position = me.positionStore.getAt(i); position.set('price', responseObj.positions[i].price); position.set('total', responseObj.positions[i].total); } me.orderModel.set('shippingCosts', responseObj.shippingCosts); me.orderModel.set('shippingCostsNet', responseObj.shippingCostsNet); if (me.shippingCostsFields !== undefined) { me.shippingCostsFields[0].setValue(me.orderModel.get('shippingCosts')); me.shippingCostsFields[1].setValue(me.orderModel.get('shippingCostsNet')); } } }); }, /** * @param price * @returns */ calculateCurrency: function (price) { var me = this; var index = me.currencyStore.findExact('selected', 1); price = price * me.currencyStore.getAt(index).get('factor'); return price; }, /** * saves the attribute fields in the correct store field * * @param field * @param newValue * @param oldValue */ onChangeAttrField: function (field, newValue, oldValue) { var me = this; switch (field.name) { case 'attr1TxtBox': me.orderAttributeModel.set('attribute1', field.getValue()); break; case 'attr2TxtBox': me.orderAttributeModel.set('attribute2', field.getValue()); break; case 'attr3TxtBox': me.orderAttributeModel.set('attribute3', field.getValue()); break; case 'attr4TxtBox': me.orderAttributeModel.set('attribute4', field.getValue()); break; case 'attr5TxtBox': me.orderAttributeModel.set('attribute5', field.getValue()); break; case 'attr6TxtBox': me.orderAttributeModel.set('attribute6', field.getValue()); break; default: break; } me.subApplication.getStore("OrderAttribute").add(me.orderAttributeModel); }, /** * event fires when the desktop type combox changes the data index * * @param comboBox * @param newValue */ onChangeDesktopType: function (comboBox, newValue) { var me = this; var desktopType = comboBox.findRecordByValue(newValue); me.orderModel.set('desktopType', desktopType.data.name); }, /** * reads the plugin configuration */ getPluginConfig: function () { var me = this; Ext.Ajax.request({ url: '{url action=getPluginConfig}', success: function (response, opts) { var pluginConfigObj = Ext.decode(response.responseText); me.validationMail = pluginConfigObj.data.validationMail; me.desktopTypes = pluginConfigObj.data.desktopTypes; me.subApplication.getStore('DesktopTypes').loadData(me.desktopTypes, false); } }); }, /** * deselects the shipping address */ onSelectBillingAsShippingAddress: function () { var me = this; me.orderModel.set('shippingAddressId', null); }, /** * calculates the tax costs for every tax rate and the shipping tax */ onCalculateTax: function () { var me = this; me.positionStore = me.subApplication.getStore('Position'); me.totalCostsStore = me.subApplication.getStore('TotalCosts'); me.totalCostsModel = me.totalCostsStore.getAt(0); var positionArray = []; me.positionStore.each(function (record) { positionArray.push(record.data); }); var positionJsonString = Ext.JSON.encode(positionArray); Ext.Ajax.request({ url: '{url action="calculateTax"}', params: { positions: positionJsonString, shippingCosts: me.orderModel.get('shippingCosts'), net: me.orderModel.get('net') }, success: function (response) { var totalCostsJson = Ext.JSON.decode(response.responseText); var record = totalCostsJson.data; me.totalCostsModel.beginEdit(); try { me.totalCostsModel.set('totalWithoutTax', record.totalWithoutTax); me.totalCostsModel.set('sum', record.sum); me.totalCostsModel.set('total', record.total); me.totalCostsModel.set('shippingCosts', record.shippingCosts); me.totalCostsModel.set('shippingCostsNet', record.shippingCostsNet); me.totalCostsModel.set('taxSum', record.taxSum); } finally { me.totalCostsModel.endEdit(); } me.orderModel.set('shippingCostsNet', record.shippingCostsNet); } }); }, /** * * @param value * @param taxRate * @returns number */ calculateNetPrice: function (value, taxRate) { taxRate = parseInt(taxRate); return value / ((100 + taxRate) / 100); }, /** * resets all setted data which belongs to the customer which was selected by the user */ onChangeCustomer: function () { var me = this; me.orderModel.set('billingAddressId', null); me.orderModel.set('shippingAddressId', null); me.orderModel.set('shippingCosts', null); me.orderModel.set('shippingCostsNet', null); me.orderModel.set('paymentId', null); }, /** * calculates the new prices and sets the net flag to true * @param net */ onChangeNetCheckbox: function (net) { var me = this; me.orderModel.set('net', net); if (me.totalCostsModel) { me.totalCostsModel.set('net', net); } var positionStore = me.subApplication.getStore('Position'); if (!(positionStore instanceof Ext.data.Store)) return; var positionArray = []; positionStore.each(function (record) { positionArray.push(record.data); }); var positionJsonString = Ext.JSON.encode(positionArray); /** * ajax request to calculate the new prices */ Ext.Ajax.request({ url: '{url action="changedNetBox"}', params: { positions: positionJsonString, net: net }, success: function (response) { var responseObj = Ext.JSON.decode(response.responseText); var positions = responseObj.data; for (var index = 0; index < positionStore.count(); index++) { var actualPosition = positionStore.getAt(index); actualPosition.beginEdit(); try { actualPosition.set('price', positions[index].price); actualPosition.set('total', positions[index].total); } finally { actualPosition.endEdit(); } } } }); }, /** * changes the actual language for the confirmation mail * * @param languageShopId */ onChangeLanguage: function (languageShopId) { var me = this; me.orderModel.set('languageShopId', languageShopId); } }); // //{/block}
GerDner/luck-docker
engine/Shopware/Plugins/Default/Backend/SwagBackendOrder/Views/backend/swag_backend_order/controller/main.js
JavaScript
agpl-3.0
30,375
// Generated by CoffeeScript 1.7.1 var Application, Manifest, americano; americano = require('americano-cozy'); Manifest = require('../lib/manifest').Manifest; module.exports = Application = americano.getModel('Application', { name: String, displayName: String, description: String, slug: String, state: String, isStoppable: { type: Boolean, "default": false }, date: { type: Date, "default": Date.now }, icon: String, iconPath: String, git: String, errormsg: String, branch: String, port: Number, permissions: Object, password: String, homeposition: Object, widget: String, version: String, needsUpdate: { type: Boolean, "default": false }, _attachments: Object }); Application.all = function(params, callback) { return Application.request("bySlug", params, callback); }; Application.destroyAll = function(params, callback) { return Application.requestDestroy("all", params, callback); }; Application.prototype.checkForUpdate = function(callback) { var manifest, setFlag; setFlag = (function(_this) { return function() { _this.needsUpdate = true; return _this.save(function(err) { if (err) { return callback(err); } else { return callback(null, true); } }); }; })(this); if (this.needsUpdate) { return callback(null, false); } else { manifest = new Manifest(); return manifest.download(this, (function(_this) { return function(err) { var repoVersion; if (err) { return callback(err); } else { repoVersion = manifest.getVersion(); if (repoVersion == null) { return callback(null, false); } else if (_this.version == null) { return setFlag(); } else if (_this.version !== repoVersion) { return setFlag(); } else { return callback(null, false); } } }; })(this)); } }; Application.prototype.getHaibuDescriptor = function() { var descriptor; descriptor = { user: this.slug, name: this.slug, domain: "127.0.0.1", repository: { type: "git", url: this.git }, scripts: { start: "server.coffee" }, password: this.password }; if ((this.branch != null) && this.branch !== "null") { descriptor.repository.branch = this.branch; } return descriptor; };
goofy-bz/cozy-home
build/server/models/application.js
JavaScript
agpl-3.0
2,446
OC.L10N.register( "files_sharing", { "Server to server sharing is not enabled on this server" : "Ο διαμοιρασμός μεταξύ διακομιστών δεν έχει ενεργοποιηθεί σε αυτόν το διακομιστή", "The mountpoint name contains invalid characters." : "Το όνομα σημείου προσάρτησης περιέχει μη έγκυρους χαρακτήρες.", "Not allowed to create a federated share with the same user server" : "Δεν είναι επιτρεπτή η δημιουργία ομόσπονδου διαμοιρασμού με τον ίδιο διακομιστή χρήστη", "Invalid or untrusted SSL certificate" : "Μη έγκυρο ή μη έμπιστο πιστοποιητικό SSL", "Could not authenticate to remote share, password might be wrong" : "Δεν ήταν δυνατή η πιστοποίηση στο απομακρυσμένο διαμοιρασμένο στοιχείο, μπορεί να είναι λάθος ο κωδικός πρόσβασης", "Storage not valid" : "Μη έγκυρος αποθηκευτικός χώρος", "Couldn't add remote share" : "Αδυναμία προσθήκης απομακρυσμένου κοινόχρηστου φακέλου", "Shared with you" : "Διαμοιρασμένα με εσάς", "Shared with others" : "Διαμοιρασμένα με άλλους", "Shared by link" : "Διαμοιρασμένα μέσω συνδέσμου", "Anonymous upload" : "Ανώνυμη μεταφόρτωση", "Click to select files or use drag & drop to upload" : "Κάντε κλικ για να επιλέξετε αρχεία ή χρησιμοποιήστε drag & drop για μεταφόρτωση", "Uploaded files" : "Μεταφόρτωση αρχείων", "Uploading..." : "Μεταφόρτωση...", "Nothing shared with you yet" : "Κανένα αρχείο δεν έχει διαμοιραστεί ακόμα με εσάς.", "Files and folders others share with you will show up here" : "Τα αρχεία και οι φάκελοι που άλλοι διαμοιράζονται με εσάς θα εμφανιστούν εδώ", "Nothing shared yet" : "Δεν έχει διαμοιραστεί τίποτα μέχρι στιγμής", "Files and folders you share will show up here" : "Τα αρχεία και οι φάκελοι που διαμοιράζεστε θα εμφανιστούν εδώ", "No shared links" : "Κανένας διαμοιρασμένος σύνδεσμος", "Files and folders you share by link will show up here" : "Τα αρχεία και οι φάκελοι που διαμοιράζεστε μέσω συνδέσμου θα εμφανιστούνε εδώ", "Do you want to add the remote share {name} from {owner}@{remote}?" : "Θέλετε να προσθέσουμε τον απομακρυσμένο κοινόχρηστο φάκελο {name} από {owner}@{remote}?", "Remote share" : "Απομακρυσμένος κοινόχρηστος φάκελος", "Remote share password" : "Κωδικός πρόσβασης απομακρυσμένου κοινόχρηστου φακέλου", "Cancel" : "Άκυρο", "Add remote share" : "Προσθήκη απομακρυσμένου κοινόχρηστου φακέλου", "You can upload into this folder" : "Μπορείτε να μεταφορτώσετε σε αυτόν τον φάκελο", "No ownCloud installation (7 or higher) found at {remote}" : "Δεν βρέθηκε εγκατάστση ownCloud (7 ή νεώτερη) στο {remote}", "Invalid ownCloud url" : "Άκυρη url ownCloud ", "Share" : "Διαμοιράστε", "No expiration date set" : "Δεν καθορίστηκε ημερομηνία λήξης", "Shared by" : "Διαμοιράστηκε από", "Sharing" : "Διαμοιρασμός", "Share API is disabled" : "Ο διαμοιρασμός ΑΡΙ είναι απενεργοποιημένος", "Wrong share ID, share doesn't exist" : "Εσφαλμένη διαδρομή, το αρχείο/ο φάκελος δεν υπάρχει", "Could not delete share" : "Αδυναμία διαγραφής διαμοιρασμένου", "Please specify a file or folder path" : "Παρακαλώ καθορίστε την διαδρομή του αρχείου ή του φακέλου", "Wrong path, file/folder doesn't exist" : "Εσφαλμένη διαδρομή, το αρχείο/ο φάκελος δεν υπάρχει", "Cannot remove all permissions" : "Δεν είναι δυνατή η κατάργηση όλων των δικαιωμάτων", "Please specify a valid user" : "Παρακαλώ καθορίστε έγκυρο χρήστη", "Group sharing is disabled by the administrator" : "O διαμοιρασμός μεταξύ της ιδίας ομάδας έχει απενεργοποιηθεί από το διαχειρηστή", "Please specify a valid group" : "Παρακαλώ καθορίστε μια έγκυρη ομάδα", "Public link sharing is disabled by the administrator" : "Ο δημόσιος διαμοιρασμός συνδέσμου έχει απενεργοποιηθεί από τον διαχειριστή", "Public upload disabled by the administrator" : "Η δημόσια μεταφόρτωση έχει απενεργοποιηθεί από τον διαχειριστή", "Public upload is only possible for publicly shared folders" : "Η δημόσια μεταφόρτωση είναι δυνατή μόνο για δημόσια διαμοιρασμένους φακέλους", "Invalid date, date format must be YYYY-MM-DD" : "Μη έγκυρη ημερομηνία, η μορφή ημερομηνίας πρέπει να είναι YYYY-MM-DD", "Sharing %s failed because the back end does not allow shares from type %s" : "Αποτυχία διαμοιρασμού %s γιατί το σύστημα δεν υποστηρίζει διαμοιρασμό τύπου %s", "Unknown share type" : "Άγνωστος τύπος διαμοιρασμού", "Not a directory" : "Δεν είναι κατάλογος", "Could not lock path" : "Αδυναμία κλειδώματος της διαδρομής", "Can't change permissions for public share links" : "Δεν μπορούν να γίνουν αλλαγές δικαιοδοσίας για δημόσιο διαμοιρασμό συνδέσμων", "Wrong or no update parameter given" : "Δόθηκε λανθασμένη ή χωρίς αναβάθμιση παράμετρος", "Cannot increase permissions" : "Τα δικαιώματα είναι περιορισμένα ", "A file or folder has been <strong>shared</strong>" : "Ένα αρχείο ή φάκελος <strong>διαμοιράστηκε</strong>", "A file or folder was shared from <strong>another server</strong>" : "Ένα αρχείο ή φάκελος διαμοιράστηκε από <strong>έναν άλλο διακομιστή</strong>", "A public shared file or folder was <strong>downloaded</strong>" : "Ένα δημόσια διαμοιρασμένο αρχείο ή φάκελος <strong>ελήφθη</strong>", "You received a new remote share %2$s from %1$s" : "Λάβατε ένα νέο απομακρυσμένο κοινόχρηστο %2$s από %1$s", "You received a new remote share from %s" : "Λάβατε ένα νέο απομακρυσμένο κοινόχρηστο φάκελο από %s", "%1$s accepted remote share %2$s" : "Ο %1$s αποδέχθηκε τον απομακρυσμένο φάκελο %2$s", "%1$s declined remote share %2$s" : "Ο %1$s απέρριψε το απομακρυσμένο κοινόχρηστο %2$s", "%1$s unshared %2$s from you" : "Ο %1$s αναίρεσε το διαμοιρασμό του %2$s με εσάς", "Public shared folder %1$s was downloaded" : "Ο δημόσιος διαμοιρασμένος φάκελος %1$s ελήφθη", "Public shared file %1$s was downloaded" : "Το δημόσιο διαμοιρασμένο αρχείο %1$s ελήφθη", "You shared %1$s with %2$s" : "Διαμοιραστήκατε το %1$s με %2$s", "%2$s shared %1$s with %3$s" : "Ο %2$s διαμοιράστηκε το %1$s με %3$s", "You removed the share of %2$s for %1$s" : "Έχετε αφαιρέσει το διαμοιρασμό του %2$s για %1$s", "%2$s removed the share of %3$s for %1$s" : "Ο %2$s έχει αφαιρέσει τον διαμοιασμό του %3$s για %1$s", "You shared %1$s with group %2$s" : "Διαμοιραστήκατε %1$s με την ομάδα %2$s", "%2$s shared %1$s with group %3$s" : "Ο %2$s διαμοιράστηκε το %1$s με την ομάδα %3$s", "You removed the share of group %2$s for %1$s" : "Έχετε αφαιρέσει το διαμοιρασμό της ομάδας %2$s για %1$s", "%2$s removed the share of group %3$s for %1$s" : "Ο %2$s αφαίρεσε τον διαμοιρασμό της ομάδας %3$s για %1$s", "%2$s shared %1$s via link" : "Ο %2$s διαμοιράστηκε το %1$s μέσω συνδέσμου", "You shared %1$s via link" : "Μοιραστήκατε το %1$s μέσω συνδέσμου", "You removed the public link for %1$s" : "Αφαιρέσατε δημόσιο σύνδεσμο για %1$s", "%2$s removed the public link for %1$s" : "Ο %2$s αφαίρεση τον δημόσιο σύνδεσμο για %1$s", "Your public link for %1$s expired" : "Έληξε ο δημόσιος σύνδεσμος για %1$s", "The public link of %2$s for %1$s expired" : "Έληξε ο δημόσιος σύνδεσμος του %2$s για %1$s", "%2$s shared %1$s with you" : "Ο %2$s διαμοιράστηκε το %1$s με εσάς", "%2$s removed the share for %1$s" : "Ο %2$s αφαίρεση το κοινόχρηστο για %1$s", "Downloaded via public link" : "Μεταφορτώθηκε μέσω δημόσιου συνδέσμου", "Shared with %2$s" : "Διαμοιράστηκε με %2$s", "Shared with %3$s by %2$s" : "Διαμοιράστηκε με %3$s από %2$s", "Removed share for %2$s" : "Αφαίρεση διαμοιρασμού για %2$s", "%2$s removed share for %3$s" : "Ο %2$s αφαίρεσε τον διαμοιρασμό για %3$s", "Shared with group %2$s" : "Διαμοιράστηκε με την ομάδα %2$s", "Shared with group %3$s by %2$s" : "Διαμοιράστηκε με την ομάδα %3$s από %2$s", "Removed share of group %2$s" : "Αφαίρεση κοινόχρηστου από την ομάδα %2$s", "%2$s removed share of group %3$s" : "Ο/Η %2$s κατήργησε την κοινή χρήση της ομάδας %3$s", "Shared via link by %2$s" : "Διαμοιράστηκε μέσω συνδέσμου από %2$s", "Shared via public link" : "Διαμοιράστηκε μέσω δημόσιου συνδέσμου", "Removed public link" : "Αφαιρέθηκε ο δημόσιος σύνδεσμος", "%2$s removed public link" : "Ο/Η %2$s κατήργησε τον δημόσιο σύνδεσμο", "Public link expired" : "Έληξε ο δημόσιος σύνδεσμος", "Public link of %2$s expired" : "Έληξε ο δημόσιος σύνδεσμος του %2$s", "Shared by %2$s" : "Διαμοιράστηκε από %2$s", "Shares" : "Κοινόχρηστοι φάκελοι", "This share is password-protected" : "Αυτός ο κοινόχρηστος φάκελος προστατεύεται με κωδικό", "The password is wrong. Try again." : "Εσφαλμένος κωδικός πρόσβασης. Προσπαθήστε ξανά.", "Password" : "Κωδικός πρόσβασης", "No entries found in this folder" : "Δεν βρέθηκαν καταχωρήσεις σε αυτόν το φάκελο", "Name" : "Όνομα", "Share time" : "Χρόνος διαμοιρασμού", "Expiration date" : "Ημερομηνία λήξης", "Sorry, this link doesn’t seem to work anymore." : "Συγγνώμη, αυτός ο σύνδεσμος μοιάζει να μην ισχύει πια.", "Reasons might be:" : "Οι λόγοι μπορεί να είναι:", "the item was removed" : "το αντικείμενο απομακρύνθηκε", "the link expired" : "ο σύνδεσμος έληξε", "sharing is disabled" : "ο διαμοιρασμός απενεργοποιήθηκε", "For more info, please ask the person who sent this link." : "Για περισσότερες πληροφορίες, παρακαλώ ρωτήστε το άτομο που σας έστειλε αυτόν τον σύνδεσμο.", "%s is publicly shared" : "Το %s είναι κοινόχρηστο δημοσίως", "Add to your ownCloud" : "Προσθήκη στο ownCloud σου", "Download" : "Λήψη", "Download %s" : "Λήψη %s", "Direct link" : "Άμεσος σύνδεσμος" }, "nplurals=2; plural=(n != 1);");
jacklicn/owncloud
apps/files_sharing/l10n/el.js
JavaScript
agpl-3.0
13,441
o2.xApplication.ConfigDesigner.options = { "multitask": true, "executable": false }; o2.xDesktop.requireApp("ConfigDesigner", "Script", null, false); o2.require("o2.xDesktop.UserData", null, false); o2.xApplication.ConfigDesigner.Main = new Class({ Extends: o2.xApplication.Common.Main, Implements: [Options, Events], options: { "style": "default", "name": "ConfigDesigner", "icon": "icon.png", "title": o2.xApplication.ConfigDesigner.LP.title, "appTitle": o2.xApplication.ConfigDesigner.LP.title, "id": "node_127.0.0.1.json", "actions": null, "category": null, "portalData": null }, onQueryLoad: function(){ this.actions = o2.Actions.load("x_program_center"); this.lp = o2.xApplication.ConfigDesigner.LP; this.addEvent("queryClose", function(e){ if (this.explorer){ this.explorer.reload(); } }.bind(this)); }, loadApplication: function(callback){ this.createNode(); if (!this.options.isRefresh){ this.maxSize(function(){ this.openScript(); }.bind(this)); }else{ this.openScript(); } if (callback) callback(); }, createNode: function(){ this.content.setStyle("overflow", "hidden"); this.node = new Element("div", { "styles": {"width": "100%", "height": "100%", "overflow": "hidden"} }).inject(this.content); }, getApplication:function(callback){ if (callback) callback(); }, openScript: function(){ this.getApplication(function(){ this.loadNodes(); this.loadScriptListNodes(); this.loadContentNode(function(){ this.loadProperty(); // this.loadTools(); this.resizeNode(); this.addEvent("resize", this.resizeNode.bind(this)); this.loadScript(); if (this.toolbarContentNode){ this.setScrollBar(this.toolbarContentNode, null, { "V": {"x": 0, "y": 0}, "H": {"x": 0, "y": 0} }); this.setScrollBar(this.propertyDomArea, null, { "V": {"x": 0, "y": 0}, "H": {"x": 0, "y": 0} }); } }.bind(this)); }.bind(this)); }, loadNodes: function(){ this.scriptListNode = new Element("div", { "styles": this.css.scriptListNode }).inject(this.node); this.propertyNode = new Element("div", { "styles": this.css.propertyNode }).inject(this.node); this.contentNode = new Element("div", { "styles": this.css.contentNode }).inject(this.node); }, //loadScriptList------------------------------- loadScriptListNodes: function(){ this.scriptListTitleNode = new Element("div", { "styles": this.css.scriptListTitleNode, "text": o2.xApplication.ConfigDesigner.LP.scriptLibrary }).inject(this.scriptListNode); this.scriptListResizeNode = new Element("div", {"styles": this.css.scriptListResizeNode}).inject(this.scriptListNode); this.scriptListAreaSccrollNode = new Element("div", {"styles": this.css.scriptListAreaSccrollNode}).inject(this.scriptListNode); this.scriptListAreaNode = new Element("div", {"styles": this.css.scriptListAreaNode}).inject(this.scriptListAreaSccrollNode); this.loadScriptListResize(); this.loadScriptList(); }, setScroll: function(){ o2.require("o2.widget.ScrollBar", function(){ this.listScrollBar = new o2.widget.ScrollBar(this.scriptListAreaSccrollNode, { "style":"xDesktop_Message", "where": "before", "indent": false, "distance": 100, "friction": 6, "axis": {"x": false, "y": true} }); }.bind(this)); }, loadScriptListResize: function(){ // var size = this.propertyNode.getSize(); // var position = this.propertyResizeBar.getPosition(); this.scriptListResize = new Drag(this.scriptListResizeNode,{ "snap": 1, "onStart": function(el, e){ var x = (Browser.name=="firefox") ? e.event.clientX : e.event.x; var y = (Browser.name=="firefox") ? e.event.clientY : e.event.y; el.store("position", {"x": x, "y": y}); var size = this.scriptListAreaSccrollNode.getSize(); el.store("initialWidth", size.x); }.bind(this), "onDrag": function(el, e){ var x = (Browser.name=="firefox") ? e.event.clientX : e.event.x; // var y = e.event.y; var bodySize = this.content.getSize(); var position = el.retrieve("position"); var initialWidth = el.retrieve("initialWidth").toFloat(); var dx = x.toFloat() - position.x.toFloat(); var width = initialWidth+dx; if (width> bodySize.x/2) width = bodySize.x/2; if (width<40) width = 40; this.contentNode.setStyle("margin-left", width+1); this.scriptListNode.setStyle("width", width); }.bind(this) }); }, loadScriptList: function() { this.actions.ConfigAction.getList(function( json ){ data = json.data; var config = JSON.parse(data.config); this.config = config; for (var key in config) { if(key.indexOf("node_")>-1){ this.options.id = key; } this.createListScriptItem(key,config[key]); } this.setScroll(); }.bind(this), null, false); }, createListScriptItem: function(id, name){ var _self = this; var listScriptItem = new Element("div", {"styles": this.css.listScriptItem}).inject(this.scriptListAreaNode, "bottom"); var listScriptItemIcon = new Element("div", {"styles": this.css.listScriptItemIcon}).inject(listScriptItem); var listScriptItemText = new Element("div", {"styles": this.css.listScriptItemText, "text":id.replace(".json","")+" ("+name+")" }).inject(listScriptItem); listScriptItem.store("script", {id:id,name:name}); listScriptItem.addEvents({ "dblclick": function(e){_self.loadScriptByData(this, e);}, "mouseover": function(){if (_self.currentListScriptItem!=this) this.setStyles(_self.css.listScriptItem_over);}, "mouseout": function(){if (_self.currentListScriptItem!=this) this.setStyles(_self.css.listScriptItem);} }); this.listScriptItemMove(listScriptItem); }, createScriptListCopy: function(node){ var copyNode = node.clone().inject(this.node); copyNode.position({ "relativeTo": node, "position": "upperLeft", "edge": "upperLeft" }); var size = copyNode.getSize(); copyNode.setStyles({ "width": ""+size.x+"px", "height": ""+size.y+"px", "z-index": 50001, }); return copyNode; }, listDragEnter: function(dragging, inObj){ var markNode = inObj.retrieve("markNode"); if (!markNode){ var size = inObj.getSize(); markNode = new Element("div", {"styles": this.css.dragListItemMark}).inject(this.node); markNode.setStyles({ "width": ""+size.x+"px", "height": ""+size.y+"px", "position": "absolute", "background-color": "#666", "z-index": 50000, "opacity": 0.3 // "border": "2px solid #ffba00" }); markNode.position({ "relativeTo": inObj, "position": "upperLeft", "edge": "upperLeft" }); var y = markNode.getStyle("top").toFloat()-1; var x = markNode.getStyle("left").toFloat()-2; markNode.setStyles({ "left": ""+x+"px", "top": ""+y+"px", }); inObj.store("markNode", markNode); } }, listDragLeave: function(dragging, inObj){ var markNode = inObj.retrieve("markNode"); if (markNode) markNode.destroy(); inObj.eliminate("markNode"); }, listScriptItemMove: function(node){ var iconNode = node.getFirst(); iconNode.addEvent("mousedown", function(e){ var script = node.retrieve("script"); if (script.id!=this.scriptTab.showPage.script.data.id){ var copyNode = this.createScriptListCopy(node); var droppables = [this.designNode, this.propertyDomArea]; var listItemDrag = new Drag.Move(copyNode, { "droppables": droppables, "onEnter": function(dragging, inObj){ this.listDragEnter(dragging, inObj); }.bind(this), "onLeave": function(dragging, inObj){ this.listDragLeave(dragging, inObj); }.bind(this), "onDrag": function(e){ //nothing }.bind(this), "onDrop": function(dragging, inObj){ if (inObj){ this.addIncludeScript(script); this.listDragLeave(dragging, inObj); copyNode.destroy(); }else{ copyNode.destroy(); } }.bind(this), "onCancel": function(dragging){ copyNode.destroy(); }.bind(this) }); listItemDrag.start(e); } }.bind(this)); }, addIncludeScript: function(script){ var currentScript = this.scriptTab.showPage.script; if (currentScript.data.dependScriptList.indexOf(script.name)==-1){ currentScript.data.dependScriptList.push(script.name); this.addIncludeToList(script.name); } }, addIncludeToList: function(name){ this.actions.getScriptByName(name, this.application.id, function(json){ var script = json.data; var includeScriptItem = new Element("div", {"styles": this.css.includeScriptItem}).inject(this.propertyIncludeListArea); var includeScriptItemAction = new Element("div", {"styles": this.css.includeScriptItemAction}).inject(includeScriptItem); var includeScriptItemText = new Element("div", {"styles": this.css.includeScriptItemText}).inject(includeScriptItem); includeScriptItemText.set("text", script.name+" ("+script.alias+")"); includeScriptItem.store("script", script); var _self = this; includeScriptItemAction.addEvent("click", function(){ var node = this.getParent(); var script = node.retrieve("script"); if (script){ _self.scriptTab.showPage.script.data.dependScriptList.erase(script.name); } node.destroy(); }); }.bind(this), function(){ this.scriptTab.showPage.script.data.dependScriptList.erase(name); }.bind(this)); }, loadScriptByData: function(node, e){ var script = node.retrieve("script"); var scriptName = script.name; var openNew = true; for (var i = 0; i<this.scriptTab.pages.length; i++){ if (script.id==this.scriptTab.pages[i].script.data.id){ this.scriptTab.pages[i].showTabIm(); openNew = false; break; } } if (openNew){ this.loadScriptData(script.id, function(data){ data.name = scriptName; var script = new o2.xApplication.ConfigDesigner.Script(this, data); script.load(); }.bind(this), true); } }, //loadContentNode------------------------------ loadContentNode: function(toolbarCallback, contentCallback){ this.contentToolbarNode = new Element("div#contentToolbarNode", { "styles": this.css.contentToolbarNode }).inject(this.contentNode); this.loadContentToolbar(toolbarCallback); this.editContentNode = new Element("div", { "styles": this.css.editContentNode }).inject(this.contentNode); this.loadEditContent(function(){ // if (this.designDcoument) this.designDcoument.body.setStyles(this.css.designBody); if (this.designNode) this.designNode.setStyles(this.css.designNode); if (contentCallback) contentCallback(); }.bind(this)); }, loadContentToolbar: function(callback){ this.getFormToolbarHTML(function(toolbarNode){ var spans = toolbarNode.getElements("span"); spans.each(function(item, idx){ var img = item.get("MWFButtonImage"); if (img){ item.set("MWFButtonImage", this.path+""+this.options.style+"/toolbar/"+img); } }.bind(this)); $(toolbarNode).inject(this.contentToolbarNode); o2.require("o2.widget.Toolbar", function(){ this.toolbar = new o2.widget.Toolbar(toolbarNode, {"style": "ProcessCategory"}, this); this.toolbar.load(); var _self = this; //this.styleSelectNode = toolbarNode.getElement("select"); //this.styleSelectNode.addEvent("change", function(){ // _self.changeEditorStyle(this); //}); this.styleSelectNode = toolbarNode.getElement("select[MWFnodetype='theme']"); this.styleSelectNode.addEvent("change", function(){ _self.changeEditorStyle(this); }); this.fontsizeSelectNode = toolbarNode.getElement("select[MWFnodetype='fontSize']"); this.fontsizeSelectNode.addEvent("change", function(){ _self.changeFontSize(this); }); this.editorSelectNode = toolbarNode.getElement("select[MWFnodetype='editor']"); this.editorSelectNode.addEvent("change", function(){ _self.changeEditor(this); }); this.monacoStyleSelectNode = toolbarNode.getElement("select[MWFnodetype='monaco-theme']"); this.monacoStyleSelectNode.addEvent("change", function(){ _self.changeEditorStyle(this); }); if (callback) callback(); }.bind(this)); }.bind(this)); }, changeEditor: function(node){ var idx = node.selectedIndex; var value = node.options[idx].value; if (!o2.editorData){ o2.editorData = { "javascriptEditor": { "monaco_theme": "vs", "theme": "tomorrow", "fontSize" : "12px" } }; } o2.editorData.javascriptEditor["editor"] = value; o2.UD.putData("editor", o2.editorData); this.scriptTab.pages.each(function(page){ var editor = page.script.editor; if (editor) editor.changeEditor(value); }.bind(this)); if (value=="ace"){ this.monacoStyleSelectNode.hide(); this.styleSelectNode.show(); }else{ this.monacoStyleSelectNode.show(); this.styleSelectNode.hide(); } }, changeFontSize: function(node){ var idx = node.selectedIndex; var value = node.options[idx].value; //var editorData = null; this.scriptTab.pages.each(function(page){ //if (!editorData) editorData = page.invoke.editor.editorData; var editor = page.script.editor; if (editor) editor.setFontSize(value); }.bind(this)); //if (!editorData) editorData = o2.editorData; //editorData.javainvokeEditor.theme = value; if (!o2.editorData){ o2.editorData = { "javascriptEditor": { "monaco_theme": "vs", "theme": "tomorrow", "fontSize" : "12px" } }; } o2.editorData.javascriptEditor["fontSize"] = value; o2.UD.putData("editor", o2.editorData); }, changeEditorStyle: function(node){ var idx = node.selectedIndex; var value = node.options[idx].value; //var editorData = null; this.scriptTab.pages.each(function(page){ //if (!editorData) editorData = page.script.editor.editorData; var editor = page.script.editor; if (editor) editor.setTheme(value); }.bind(this)); //if (!editorData) editorData = o2.editorData; //editorData.javascriptEditor.theme = value; if (!o2.editorData){ o2.editorData = { "javascriptEditor": { "monaco_theme": "vs", "theme": "tomorrow", "fontSize" : "12px" } }; } if (o2.editorData.javascriptEditor.editor === "monaco"){ o2.editorData.javascriptEditor.monaco_theme = value; }else{ o2.editorData.javascriptEditor.theme = value; } o2.UD.putData("editor", o2.editorData); }, getFormToolbarHTML: function(callback){ var toolbarUrl = this.path+this.options.style+"/toolbars.html"; var r = new Request.HTML({ url: toolbarUrl, method: "get", onSuccess: function(responseTree, responseElements, responseHTML, responseJavaScript){ var toolbarNode = responseTree[0]; if (callback) callback(toolbarNode); }.bind(this), onFailure: function(xhr){ this.notice("request portalToolbars error: "+xhr.responseText, "error"); }.bind(this) }); r.send(); }, maxOrReturnEditor: function(){ if (!this.isMax){ this.designNode.inject(this.node); this.designNode.setStyles({ "position": "absolute", "width": "100%", "height": "100%", "top": "0px", "margin": "0px", "left": "0px" }); this.scriptTab.pages.each(function(page){ page.script.setAreaNodeSize(); }); this.isMax = true; }else{ this.isMax = false; this.designNode.inject(this.editContentNode); this.designNode.setStyles(this.css.designNode); this.designNode.setStyles({ "position": "static" }); this.resizeNode(); this.scriptTab.pages.each(function(page){ page.script.setAreaNodeSize(); }); } }, loadEditContent: function(callback){ this.designNode = new Element("div", { "styles": this.css.designNode }).inject(this.editContentNode); o2.require("o2.widget.Tab", function(){ this.scriptTab = new o2.widget.Tab(this.designNode, {"style": "script"}); this.scriptTab.load(); }.bind(this), false); //o2.require("o2.widget.ScrollBar", function(){ // new o2.widget.ScrollBar(this.designNode, {"distance": 100}); //}.bind(this)); }, //loadProperty------------------------ loadProperty: function(){ this.propertyTitleNode = new Element("div", { "styles": this.css.propertyTitleNode, "text": o2.xApplication.ConfigDesigner.LP.property }).inject(this.propertyNode); this.propertyResizeBar = new Element("div", { "styles": this.css.propertyResizeBar }).inject(this.propertyNode); this.loadPropertyResize(); this.propertyContentNode = new Element("div", { "styles": this.css.propertyContentNode }).inject(this.propertyNode); this.propertyDomArea = new Element("div", { "styles": this.css.propertyDomArea }).inject(this.propertyContentNode); this.propertyDomPercent = 0.3; this.propertyContentResizeNode = new Element("div", { "styles": this.css.propertyContentResizeNode }).inject(this.propertyContentNode); this.propertyContentArea = new Element("div", { "styles": this.css.propertyContentArea }).inject(this.propertyContentNode); this.loadPropertyContentResize(); this.setPropertyContent(); this.setIncludeNode(); }, setIncludeNode: function(){ this.includeTitleNode = new Element("div", {"styles": this.css.includeTitleNode}).inject(this.propertyDomArea); this.includeTitleActionNode = new Element("div", {"styles": this.css.includeTitleActionNode}).inject(this.includeTitleNode); this.includeTitleTextNode = new Element("div", {"styles": this.css.includeTitleTextNode, "text": this.lp.include}).inject(this.includeTitleNode); this.includeTitleActionNode.addEvent("click", function(){ this.addInclude(); }.bind(this)); this.propertyIncludeListArea = new Element("div", { "styles": {"overflow": "hidden"} }).inject(this.propertyDomArea); }, addInclude: function(){ }, setPropertyContent: function(){ var node = new Element("div", {"styles": this.css.propertyItemTitleNode, "text": this.lp.id+":"}).inject(this.propertyContentArea); this.propertyIdNode = new Element("div", {"styles": this.css.propertyTextNode, "text": ""}).inject(this.propertyContentArea); node = new Element("div", {"styles": this.css.propertyItemTitleNode, "text": this.lp.name+":"}).inject(this.propertyContentArea); this.propertyNameNode = new Element("div", {"styles": this.css.propertyTextNode, "text": ""}).inject(this.propertyContentArea); node = new Element("div", {"styles": this.css.propertyItemTitleNode, "text": this.lp.node+":"}).inject(this.propertyContentArea); this.propertyServerNode = new Element("select", {"styles": this.css.propertyTextNode}).inject(this.propertyContentArea); o2.Actions.load("x_program_center").CommandAction.getNodeInfoList( function( json ){ var nodeList = json.data.nodeList; if(nodeList.length>1){ new Element("option", {"value": "*", "text": "*"}).inject(this.propertyServerNode); } nodeList.each(function (node) { new Element("option", { "value": node.node.nodeAgentPort, "text": node.nodeAddress }).inject(this.propertyServerNode); }.bind(this)); }.bind(this),null, false ); node = new Element("div", {"styles": this.css.propertyItemTitleNode, "text": this.lp.description+":"}).inject(this.propertyContentArea); this.propertyDescriptionNode = new Element("div", {"styles": this.css.propertyTextNode, "text": ""}).inject(this.propertyContentArea); }, loadPropertyResize: function(){ // var size = this.propertyNode.getSize(); // var position = this.propertyResizeBar.getPosition(); this.propertyResize = new Drag(this.propertyResizeBar,{ "snap": 1, "onStart": function(el, e){ var x = (Browser.name=="firefox") ? e.event.clientX : e.event.x; var y = (Browser.name=="firefox") ? e.event.clientY : e.event.y; el.store("position", {"x": x, "y": y}); var size = this.propertyNode.getSize(); el.store("initialWidth", size.x); }.bind(this), "onDrag": function(el, e){ var x = (Browser.name=="firefox") ? e.event.clientX : e.event.x; // var y = e.event.y; var bodySize = this.content.getSize(); var position = el.retrieve("position"); var initialWidth = el.retrieve("initialWidth").toFloat(); var dx = position.x.toFloat()-x.toFloat(); var width = initialWidth+dx; if (width> bodySize.x/2) width = bodySize.x/2; if (width<40) width = 40; this.contentNode.setStyle("margin-right", width+1); this.propertyNode.setStyle("width", width); }.bind(this) }); }, loadPropertyContentResize: function(){ this.propertyContentResize = new Drag(this.propertyContentResizeNode, { "snap": 1, "onStart": function(el, e){ var x = (Browser.name=="firefox") ? e.event.clientX : e.event.x; var y = (Browser.name=="firefox") ? e.event.clientY : e.event.y; el.store("position", {"x": x, "y": y}); var size = this.propertyDomArea.getSize(); el.store("initialHeight", size.y); }.bind(this), "onDrag": function(el, e){ var size = this.propertyContentNode.getSize(); // var x = e.event.x; var y = (Browser.name=="firefox") ? e.event.clientY : e.event.y; var position = el.retrieve("position"); var dy = y.toFloat()-position.y.toFloat(); var initialHeight = el.retrieve("initialHeight").toFloat(); var height = initialHeight+dy; if (height<40) height = 40; if (height> size.y-40) height = size.y-40; this.propertyDomPercent = height/size.y; this.setPropertyContentResize(); }.bind(this) }); }, setPropertyContentResize: function(){ var size = this.propertyContentNode.getSize(); var resizeNodeSize = this.propertyContentResizeNode.getSize(); var height = size.y-resizeNodeSize.y; var domHeight = this.propertyDomPercent*height; var contentHeight = height-domHeight; this.propertyDomArea.setStyle("height", ""+domHeight+"px"); this.propertyContentArea.setStyle("height", ""+contentHeight+"px"); }, //resizeNode------------------------------------------------ resizeNode: function(){ if (!this.isMax){ var nodeSize = this.node.getSize(); this.contentNode.setStyle("height", ""+nodeSize.y+"px"); this.propertyNode.setStyle("height", ""+nodeSize.y+"px"); var contentToolbarMarginTop = this.contentToolbarNode.getStyle("margin-top").toFloat(); var contentToolbarMarginBottom = this.contentToolbarNode.getStyle("margin-bottom").toFloat(); var allContentToolberSize = this.contentToolbarNode.getComputedSize(); var y = nodeSize.y - allContentToolberSize.totalHeight - contentToolbarMarginTop - contentToolbarMarginBottom; this.editContentNode.setStyle("height", ""+y+"px"); if (this.designNode){ var designMarginTop = this.designNode.getStyle("margin-top").toFloat(); var designMarginBottom = this.designNode.getStyle("margin-bottom").toFloat(); y = nodeSize.y - allContentToolberSize.totalHeight - contentToolbarMarginTop - contentToolbarMarginBottom - designMarginTop - designMarginBottom; this.designNode.setStyle("height", ""+y+"px"); } titleSize = this.propertyTitleNode.getSize(); titleMarginTop = this.propertyTitleNode.getStyle("margin-top").toFloat(); titleMarginBottom = this.propertyTitleNode.getStyle("margin-bottom").toFloat(); titlePaddingTop = this.propertyTitleNode.getStyle("padding-top").toFloat(); titlePaddingBottom = this.propertyTitleNode.getStyle("padding-bottom").toFloat(); y = titleSize.y+titleMarginTop+titleMarginBottom+titlePaddingTop+titlePaddingBottom; y = nodeSize.y-y; this.propertyContentNode.setStyle("height", ""+y+"px"); this.propertyResizeBar.setStyle("height", ""+y+"px"); this.setPropertyContentResize(); titleSize = this.scriptListTitleNode.getSize(); titleMarginTop = this.scriptListTitleNode.getStyle("margin-top").toFloat(); titleMarginBottom = this.scriptListTitleNode.getStyle("margin-bottom").toFloat(); titlePaddingTop = this.scriptListTitleNode.getStyle("padding-top").toFloat(); titlePaddingBottom = this.scriptListTitleNode.getStyle("padding-bottom").toFloat(); nodeMarginTop = this.scriptListAreaSccrollNode.getStyle("margin-top").toFloat(); nodeMarginBottom = this.scriptListAreaSccrollNode.getStyle("margin-bottom").toFloat(); y = titleSize.y+titleMarginTop+titleMarginBottom+titlePaddingTop+titlePaddingBottom+nodeMarginTop+nodeMarginBottom; y = nodeSize.y-y; this.scriptListAreaSccrollNode.setStyle("height", ""+y+"px"); this.scriptListResizeNode.setStyle("height", ""+y+"px"); } }, //loadForm------------------------------------------ loadScript: function(){ //this.scriptTab.addTab(node, title); this.getScriptData(this.options.id, function(data){ data.name = this.config[this.options.id]; this.script = new o2.xApplication.ConfigDesigner.Script(this, data); this.script.load(); }.bind(this)); }, getScriptData: function(id, callback){ this.loadScriptData(id, callback); }, loadScriptData: function(id, callback, notSetTile){ this.actions.ConfigAction.open({fileName:id}, function(json){ if (json){ var data = json.data; data.id = id; data.text = data.fileContent; if (callback) callback(data); } }.bind(this)); }, saveScript: function(){ if (this.scriptTab.showPage){ var script = this.scriptTab.showPage.script; script.save(function(){ if (script==this.script){ var name = script.data.name; this.setTitle(o2.xApplication.ConfigDesigner.LP.title + "-"+name); this.options.desktopReload = true; this.options.id = script.data.id; } }.bind(this)); } }, saveDictionaryAs: function(){ this.dictionary.saveAs(); }, dictionaryExplode: function(){ this.dictionary.explode(); }, dictionaryImplode: function(){ this.dictionary.implode(); } });
o2oa/o2oa
o2web/source/x_component_ConfigDesigner/Main.js
JavaScript
agpl-3.0
31,320
define(function(require) { 'use strict'; var _ = require('underscore'); var PIXI = require('pixi'); var PixiView = require('common/v3/pixi/view'); var Colors = require('common/colors/colors'); var Vector2 = require('common/math/vector2'); var Constants = require('constants'); var GUIDE_FILL_COLOR = Colors.parseHex(Constants.RaysView.GUIDE_FILL_COLOR); var GUIDE_LINE_COLOR = Colors.parseHex(Constants.RaysView.GUIDE_LINE_COLOR); var Assets = require('assets'); /** * Draws all the rays coming from points on the source object. * There are three different ray modes and an off mode. */ var RaysView = PixiView.extend({ /** * Initializes the new RaysView. */ initialize: function(options) { this.mvt = options.mvt; this.simulation = this.model; this.mode = RaysView.MARGINAL_RAYS this.virtualImageVisible = false; this.secondPointVisible = false; this.virtualRayColor = Colors.parseHex(RaysView.VIRTUAL_RAY_COLOR); this.sourcePointColor = Colors.parseHex(RaysView.POINT_1_COLOR); this.targetPointColor = Colors.parseHex(RaysView.POINT_2_COLOR); // Cached objects this._sourcePoint = new Vector2(); this._targetPoint = new Vector2(); this.initGraphics(); this.updateMVT(this.mvt); // Listen for changes in the source object this.listenTo(this.simulation.sourceObject, 'change:position', this.drawPoint1Rays); this.listenTo(this.simulation.sourceObject, 'change:secondPoint', this.drawPoint2Rays); // Listen for changes in the lens this.listenTo(this.simulation.lens, 'change:position', this.drawAllRays); this.listenTo(this.simulation.lens, 'change:focalLength', this.drawAllRays); this.listenTo(this.simulation.lens, 'change:diameter', this.drawAllRays); this.listenTo(this.simulation.lens, 'change:diameter change:position', this.updateGuidePositions); }, /** * Initializes all the graphics */ initGraphics: function() { this.sourcePointRays = new PIXI.Graphics(); this.targetPointRays = new PIXI.Graphics(); this.topGuide = new PIXI.Container(); this.bottomGuide = new PIXI.Container(); this.displayObject.addChild(this.sourcePointRays); this.displayObject.addChild(this.targetPointRays); this.displayObject.addChild(this.topGuide); this.displayObject.addChild(this.bottomGuide); this.topGuide.leftGuide = new PIXI.Graphics(); this.topGuide.rightGuide = new PIXI.Graphics(); this.bottomGuide.leftGuide = new PIXI.Graphics(); this.bottomGuide.rightGuide = new PIXI.Graphics(); this.topGuide.addChild(this.topGuide.leftGuide); this.topGuide.addChild(this.topGuide.rightGuide); this.bottomGuide.addChild(this.bottomGuide.leftGuide); this.bottomGuide.addChild(this.bottomGuide.rightGuide); this.hideGuides(); }, /** * Draws all the rays according to the current mode. */ drawAllRays: function() { this.drawPoint1Rays(); this.drawPoint2Rays(); }, /** * Draws the rays coming from the source object's position * according to the current mode. */ drawPoint1Rays: function() { this._sourcePoint.set(this.mvt.modelToView(this.simulation.sourceObject.get('position'))); this._targetPoint.set(this.mvt.modelToView(this.simulation.targetImage.get('position'))); this.drawRays(this.sourcePointRays, this.sourcePointColor, this._sourcePoint, this._targetPoint); }, /** * Draws the rays coming from the source object's second * point according to the current mode. */ drawPoint2Rays: function() { if (this.secondPointVisible) { this._sourcePoint.set(this.mvt.modelToView(this.simulation.sourceObject.get('secondPoint'))); this._targetPoint.set(this.mvt.modelToView(this.simulation.targetImage.get('secondPoint'))); this.drawRays(this.targetPointRays, this.targetPointColor, this._sourcePoint, this._targetPoint); } else this.targetPointRays.clear(); }, /** * Draws a specific set of rays onto the specified graphics * object with the specified color from point 1 through * the lens to point 2. */ drawRays: function(graphics, color, sourcePoint, targetPoint) { graphics.clear(); graphics.lineStyle(RaysView.LINE_WIDTH, color, RaysView.LINE_ALPHA); var Ax = sourcePoint.x; var Ay = sourcePoint.y; var Bx = this.mvt.modelToViewX(this.simulation.lens.get('position').x); var By = this.mvt.modelToViewY(this.simulation.lens.get('position').y); var Cx = targetPoint.x; var Cy = targetPoint.y; // Radius of lens minus a bit so marginal ray hits inside lens var h = Math.abs(this.mvt.modelToViewDeltaY(this.simulation.lens.get('diameter'))) / 2 - RaysView.LENS_TIP_OFFSET; // Length of the ray (enough to go off the screen) var R = 1000; // Rotate the guides var topGuideTheta = Math.atan((Ay - By + h) / (Bx - Ax)); var bottomGuideTheta = Math.atan((Ay - By - h) / (Bx - Ax)); this.topGuide.rotation = -topGuideTheta; this.bottomGuide.rotation = -bottomGuideTheta; // Used to store slope of line towards C var m, m1, m2; // TODO: make guides // Note: Skipping "blur spot" of the algorithm for now because I don't // understand what it does and don't think it's used anymore var objectLensDistance = this.getObjectLensDistance(); var virtualImage = this.simulation.targetImage.isVirtualImage(); // Draw different rays depending on the mode if (this.mode === RaysView.MARGINAL_RAYS && objectLensDistance > 0) { if (!virtualImage) { graphics.moveTo(Ax, Ay); graphics.lineTo(Bx, By); // Cannot draw line directly to C since it may be at infinity. m = (Cy - By) / (Cx - Bx); graphics.lineTo(Bx + R, By + (m * R)); graphics.moveTo(Ax, Ay); graphics.lineTo(Bx, By + h); m = (Cy - (By + h)) / (Cx - Bx); graphics.lineTo(Bx + R, By + h + (m * R)); graphics.moveTo(Ax, Ay); graphics.lineTo(Bx, By - h); m = (Cy - (By - h)) / (Cx - Bx); graphics.lineTo(Bx + R, By - h + (m * R)); } else { graphics.moveTo(Ax, Ay); graphics.lineTo(Bx, By); m = (By - Cy) / (Bx - Cx); graphics.lineTo(Bx + R, By + (m * R)); graphics.moveTo(Ax, Ay); graphics.lineTo(Bx, By + h); m = ((By + h) - Cy) / (Bx - Cx); graphics.lineTo(Bx + R, By + h + (m * R)); graphics.moveTo(Ax, Ay); graphics.lineTo(Bx, By - h); m = ((By - h) - Cy) / (Bx - Cx); graphics.lineTo(Bx + R, By - h + (m * R)); // Draw virtual marginal rays if (this.virtualImageVisible && Cx > -5 * R) { // Last condition needed to prevent problems that occur when image at infinity graphics.lineStyle(RaysView.LINE_WIDTH, this.virtualRayColor, RaysView.LINE_ALPHA); graphics.moveTo(Ax, Ay); graphics.lineTo(Cx, Cy); graphics.moveTo(Bx, By+ h); graphics.lineTo(Cx, Cy); graphics.moveTo(Bx, By - h); graphics.lineTo(Cx, Cy); } } } else if (this.mode === RaysView.PRINCIPAL_RAYS && objectLensDistance > 0) { var f = this.mvt.modelToViewDeltaX(this.simulation.lens.get('focalLength')); graphics.moveTo(Ax, Ay); graphics.lineTo(Bx, By); m = (By - Ay) / (Bx - Ax); graphics.lineTo(Bx + R, By + (m * R)); graphics.moveTo(Ax, Ay); graphics.lineTo(Bx, Ay); m2 = (By - Ay) / f; graphics.lineTo(Bx + R, Ay + (m2 * R)); graphics.moveTo(Ax, Ay); m1 = (By - Ay) / (Bx - f - Ax); graphics.lineTo(Bx, By + (m1 * f)); graphics.lineTo(Bx + R, By + (m1 * f)); // Draw principal virtual rays if (this.virtualImageVisible && virtualImage) { graphics.lineStyle(RaysView.LINE_WIDTH, this.virtualRayColor, RaysView.LINE_ALPHA); graphics.moveTo(Ax, Ay); graphics.lineTo(Cx, Cy); graphics.moveTo(Bx, Cy); graphics.lineTo(Cx, Cy); graphics.moveTo(Bx, Ay); graphics.lineTo(Cx, Cy); } } else if (this.mode === RaysView.MANY_RAYS) { var N = 25; // Number of rays var deltaTheta = 180 / N; // Degrees between adjacent arrays var degToRad = Math.PI / 180; var bottomTheta = Math.atan((Ay-By-h) / (Bx-Ax)) * 180 / Math.PI; var topTheta = Math.atan((Ay-By+h) / (Bx-Ax)) * 180 / Math.PI; var bottomSlope = (Ay-By-h) / (Bx-Ax); var topSlope = (Ay-By+h) / (Bx-Ax); for (var i = 5; i < (N - 5); i++) { m = Math.tan(degToRad * (90 - i * deltaTheta)); if (m > bottomSlope && m < topSlope) { graphics.moveTo(Ax, Ay); graphics.lineStyle(RaysView.LINE_WIDTH, color, RaysView.LINE_ALPHA); graphics.lineTo(Bx, Ay - m * (Bx - Ax)); m2 = (Cy - (Ay - m * (Bx - Ax))) / (Cx - Bx); graphics.lineTo(Bx + R, Ay - m * (Bx - Ax) + m2 * R); if (Cx < Ax && this.virtualImageVisible && Cx > -5 * R) { graphics.moveTo(Bx, Ay - m * (Bx - Ax)); graphics.lineStyle(RaysView.LINE_WIDTH, this.virtualRayColor, 0.6); graphics.lineTo(Cx, Cy); } } else { graphics.moveTo(Ax, Ay); graphics.lineStyle(RaysView.LINE_WIDTH, color, RaysView.LINE_ALPHA); graphics.lineTo(Ax + R, Ay - m * R); } } } }, /** * Draws the guides in their unrotated state */ drawGuides: function() { this.drawGuide(this.topGuide, RaysView.GUIDE_ANGLE); this.drawGuide(this.bottomGuide, -RaysView.GUIDE_ANGLE); }, drawGuide: function(guide, angle) { var width = this.mvt.modelToViewDeltaX(RaysView.GUIDE_WIDTH); var height = this.mvt.modelToViewDeltaX(RaysView.GUIDE_HEIGHT); guide.leftGuide.clear(); guide.leftGuide.lineStyle(RaysView.GUIDE_LINE_WIDTH, GUIDE_LINE_COLOR, RaysView.GUIDE_LINE_ALPHA); guide.leftGuide.beginFill(GUIDE_FILL_COLOR, RaysView.GUIDE_FILL_ALPHA); guide.leftGuide.drawRect(0, -height / 2, width, height); guide.leftGuide.endFill(); guide.leftGuide.rotation = Math.PI; guide.rightGuide.clear(); guide.rightGuide.lineStyle(RaysView.GUIDE_LINE_WIDTH, GUIDE_LINE_COLOR, RaysView.GUIDE_LINE_ALPHA); guide.rightGuide.beginFill(GUIDE_FILL_COLOR, RaysView.GUIDE_FILL_ALPHA); guide.rightGuide.drawRect(0, -height / 2, width, height); guide.rightGuide.endFill(); guide.rightGuide.beginFill(GUIDE_FILL_COLOR, RaysView.GUIDE_FILL_ALPHA); guide.rightGuide.drawCircle(0, 0, height * 0.7); guide.rightGuide.endFill(); guide.rightGuide.rotation = Math.PI - angle; }, getObjectLensDistance: function() { return this.simulation.lens.get('position').x - this.simulation.sourceObject.get('position').x; }, /** * Updates the model-view-transform and anything that * relies on it. */ updateMVT: function(mvt) { this.mvt = mvt; this.drawGuides(); this.drawAllRays(); this.updateGuidePositions(); }, /** * Makes sure the guides stay on either end of the lens. */ updateGuidePositions: function() { var lensX = this.mvt.modelToViewX(this.simulation.lens.get('position').x); var lensY = this.mvt.modelToViewY(this.simulation.lens.get('position').y); var lensDiameter = this.mvt.modelToViewDeltaX(this.simulation.lens.get('diameter')); this.topGuide.x = lensX; this.topGuide.y = lensY - lensDiameter / 2 + RaysView.LENS_TIP_OFFSET; this.bottomGuide.x = lensX; this.bottomGuide.y = lensY + lensDiameter / 2 - RaysView.LENS_TIP_OFFSET; }, /** * Sets the mode that dictates what kinds of rays we draw. */ setMode: function(mode) { this.mode = mode; this.drawAllRays(); }, /** * Shows rays for second point */ showSecondPoint: function() { this.secondPointVisible = true; this.drawAllRays(); }, hideSecondPoint: function() { this.secondPointVisible = false; this.drawAllRays(); }, showVirtualImage: function() { this.virtualImageVisible = true; this.drawAllRays(); }, hideVirtualImage: function() { this.virtualImageVisible = false; this.drawAllRays(); }, showGuides: function() { this.topGuide.visible = true; this.bottomGuide.visible = true; }, hideGuides: function() { this.topGuide.visible = false; this.bottomGuide.visible = false; } }, Constants.RaysView); return RaysView; });
Connexions/simulations
geometric-optics/src/js/views/rays.js
JavaScript
agpl-3.0
15,136
function P(x, y) { return { x: x, y: y }; } function MapAnimFactory(type, args) { let func = null, glitched = false, origArgs = [...args]; switch(type) { case "sw": func = StandardWalk; break; case "dw": func = DiffWalk; break; case "as": func = AnimSeries; break; case "ds": func = DirAnimSeries; break; case "la": func = LineAnim; break; case "ft": func = SoloTile; break; } this.Get = function() { if(game.glitch === undefined && glitched) { glitched = false; args = [...origArgs]; } else if(game.glitch && !glitched) { glitched = true; switch(type) { case "sw": { const big = args[2]; args[0] = Range(0, big ? 10: 26) - 4; args[1] = Range(0, big ? 9 : 23) - 5; break; } case "dw": { const big = args[3]; args[0] = Range(0, big ? 10: 26) - 4; args[1] = Range(0, big ? 9 : 23) - args[2]; break; } case "as": { const big = args[1]; for(let j = 0; j < posArrs[i].length; j++) { args[0][j] = P(Range(0, big ? 10 : 26), Range(0, (big ? 9 : 23))); } } case "ds": { const big = args[1]; for(let i = 0; i < posArrs.length; i++) { for(let j = 0; j < posArrs[i].length; j++) { args[0][i][j] = P(Range(0, big ? 10 : 26), Range(0, (big ? 9 : 23))); } } } case "la": { const big = args[3]; args[0] = Range(0, big ? 10 : 26); args[1] = Range(0, big ? 9 : 23) - args[2]; break; } case "ft": { const big = args[2]; args[0] = Range(0, big ? 10: 26); args[1] = Range(0, big ? 9 : 23); } } } return new func(...args); }; } function MapAnim(big, fps) { fps = fps || 6; big = big || false; this.sheet = big ? "mapCharBig" : "mapChar"; this.width = big ? 32 : 16; this.height = big ? 40 : 20; this.big = big; this.lastRan = +new Date(); this.frameRate = GetFrameRate(fps); this.state = 0; } function StandardWalk(topx, topy, big, fps) { MapAnim.call(this, big, fps); let lastDir = -1; this.getFrame = function(pos, dir, moving) { let frame = 0; const curTime = +new Date(); const update = (curTime - this.lastRan) >= this.frameRate; if(dir === undefined) { dir = lastDir; } if(dir !== lastDir) { this.state = 0; lastDir = dir; } else if(moving) { if(update) { this.state = (this.state + 1) % 4; this.lastRan = curTime; } frame = 1 + (this.state === 3 ? 1 : this.state); } else { this.state = 0; } return { sheet: this.sheet, sx: topx + lastDir, sy: topy + frame, other: this.other, pos: pos, dir: dir, big: this.big, w: this.width, h: this.height }; } } StandardWalk.prototype = Object.create(MapAnim.prototype); StandardWalk.prototype.constructor = MapAnim; function DiffWalk(topx, topy, sheetlen, big, fps) { MapAnim.call(this, big, fps); let lastDir = -1; this.getFrame = function(pos, dir, moving) { const curTime = +new Date(); const update = (curTime - this.lastRan) >= this.frameRate; if(dir === undefined) { dir = lastDir; } if(dir !== lastDir) { this.state = 0; lastDir = dir; } else if(moving) { if(update) { this.state = (this.state + 1) % sheetlen; this.lastRan = curTime; } } else { this.state = 0; } return { sheet: this.sheet, sx: topx + lastDir, sy: topy + this.state, pos: pos, dir: dir, big: this.big, w: this.width, h: this.height }; } } DiffWalk.prototype = Object.create(MapAnim.prototype); DiffWalk.prototype.constructor = MapAnim; function AnimSeries(posArr, big, fps) { MapAnim.call(this, big, fps); const sheetlen = posArr.length; this.getFrame = function(pos, dir, moving) { const curTime = +new Date(); const update = (curTime - this.lastRan) >= this.frameRate; if(update) { this.state = (this.state + 1) % sheetlen; this.lastRan = curTime; } const frameInfo = posArr[this.state]; return { sheet: this.sheet, sx: frameInfo.x, sy: frameInfo.y, pos: pos, dir: dir, big: this.big, w: this.width, h: this.height }; } } AnimSeries.prototype = Object.create(MapAnim.prototype); AnimSeries.prototype.constructor = MapAnim; function DirAnimSeries(posArrs, big, fps) { MapAnim.call(this, big, fps); let lastDir = -1; const sheetLens = []; for(let i = 0; i < posArrs.length; i++) { sheetLens.push(posArrs[i].length); } this.getFrame = function(pos, dir, moving) { const curTime = +new Date(); const update = (curTime - this.lastRan) >= this.frameRate; if(dir === undefined) { dir = lastDir; } if(dir !== lastDir) { this.state = 0; lastDir = dir; } else if(moving) { if(update) { this.state = (this.state + 1) % sheetLens[lastDir]; this.lastRan = curTime; } } else { this.state = 0; } const frameInfo = posArrs[lastDir][this.state]; return { sheet: this.sheet, sx: frameInfo.x, sy: frameInfo.y, pos: pos, dir: dir, big: this.big, w: this.width, h: this.height }; } } DirAnimSeries.prototype = Object.create(MapAnim.prototype); DirAnimSeries.prototype.constructor = MapAnim; function LineAnim(topx, topy, sheetlen, big, fps) { MapAnim.call(this, big, fps); this.getFrame = function(pos, dir, moving) { if(moving) { const curTime = +new Date(); const update = (curTime - this.lastRan) >= this.frameRate; if(update) { this.state = (this.state + 1) % sheetlen; this.lastRan = curTime; } } else { this.state = 0; } return { sheet: this.sheet, sx: topx, sy: topy + this.state, pos: pos, dir: dir, big: this.big, w: this.width, h: this.height }; } } LineAnim.prototype = Object.create(MapAnim.prototype); LineAnim.prototype.constructor = MapAnim; function SoloTile(topx, topy, big, layer) { MapAnim.call(this, big, 1); this.getFrame = function(pos, dir) { return { sheet: this.sheet, sx: topx, sy: topy, layer: layer, pos: pos, dir: dir, big: this.big, w: this.width, h: this.height }; } } SoloTile.prototype = Object.create(MapAnim.prototype); SoloTile.prototype.constructor = MapAnim; function SlightlyWiderSoloTile(topx, topy, big, layer) { MapAnim.call(this, big, 1); this.getFrame = function(pos, dir) { return { sheet: this.sheet, sx: topx, sy: topy, layer: layer, pos: pos, dir: dir, big: this.big, w: this.width, h: this.height, other: { slightlyWider: true } }; } } SlightlyWiderSoloTile.prototype = Object.create(MapAnim.prototype); SlightlyWiderSoloTile.prototype.constructor = MapAnim; const PlAnim = a => { a.sheet = "mapPlayer"; return a }; const plAnims = { "walk": PlAnim(new StandardWalk(0, 0)), "carrywalk": PlAnim(new StandardWalk(0, 0)), "run": PlAnim(new StandardWalk(0, 4)), "crouchR": PlAnim(new SoloTile(4, 0)), "crouchL": PlAnim(new SoloTile(6, 1)), "water1": PlAnim(new SlightlyWiderSoloTile(4, 1)), "water2": PlAnim(new SlightlyWiderSoloTile(4, 2)), "think": PlAnim(new SoloTile(4, 3)), "read": PlAnim(new SoloTile(6, 0)), "shock1": PlAnim(new SoloTile(6, 2)), "shock2": PlAnim(new SoloTile(6, 3)), "hidden": PlAnim(new SoloTile(5, 0)), }; plAnims.carrywalk.width = 20; plAnims.carrywalk.height = 25; plAnims.carrywalk.sheet = "mapPlayerHelp"; plAnims.carrywalk.other = { bigBoy: true }; const Ft = (x, y, big, layer) => new MapAnimFactory("ft", [x, y, big, layer]); const mafs = { // General "Beehive": Ft(15, 6), "BeeQueen": new MapAnimFactory("as", [[P(12, 4), P(12, 5), P(12, 6), P(12, 7)]]), "TruckL": Ft(4, 0, true), "TruckR": Ft(5, 0, true), "Chest0": Ft(14, 11), "Chest1": Ft(15, 11), "Kaboom": new MapAnimFactory("as", [[P(5, 8), P(6, 8), P(9, 8), P(10, 8), P(10, 9)], true, 20]), "Smonk": new MapAnimFactory("la", [26, 11, 2]), // Init Farm "Nath1": new MapAnimFactory("sw", [0, 0]), "Nath2": new MapAnimFactory("la", [4, 2, 2]), "Nath3": new MapAnimFactory("la", [5, 2, 2]), "Iii1": Ft(4, 0), "Iii2": Ft(4, 1), "Iii3": new MapAnimFactory("la", [5, 0, 2]), "Iii4": new MapAnimFactory("la", [6, 1, 2]), "Iii5": Ft(6, 0), // Produce Stand "Beck1": new MapAnimFactory("la", [7, 0, 2]), "Beck2": new MapAnimFactory("la", [10, 2, 2]), "Beck3": new MapAnimFactory("as", [[P(8, 1), P(8, 2), P(8,3), P(8, 2)]]), "Beck4": new MapAnimFactory("la", [10, 0, 2]), "Beck5": Ft(9, 0), "Beck6": new MapAnimFactory("as", [[P(9, 1), P(9, 2), P(9, 3), P(9, 2)]]), "Beck7": new MapAnimFactory("as", [[P(11, 1), P(11, 2), P(11, 3), P(11, 2)]]), "BeckBike": Ft(7, 2), "BeckTut": Ft(7, 3), "EggF0": Ft(14, 7), "EggF1": Ft(14, 4), "EggF2": Ft(14, 5), "EggF3": Ft(14, 6), // The Farm "Robo1": new MapAnimFactory("sw", [12, 0]), "Boss1": new MapAnimFactory("sw", [0, 0, true]), "Dead1": new MapAnimFactory("la", [10, 6, 2, true, 12]), // Nathan on the Farm "NOTF0": new MapAnimFactory("la", [9, 0, 7, true]), "NOTF1": new MapAnimFactory("la", [10, 0, 3, true]), "NOTF2": Ft(10, 3, true), // First Village "Dean": new MapAnimFactory("dw", [16, 0, 2]), "June": new MapAnimFactory("dw", [16, 2, 2]), "Aiko": new MapAnimFactory("dw", [16, 4, 2]), "Tanner": new MapAnimFactory("dw", [16, 6, 2]), "Skunk": new MapAnimFactory("sw", [28, 16]), // The Forest "GoldMush": Ft(15, 4), "CarrotBag": Ft(15, 7), "Fishfriend": new MapAnimFactory("dw", [4, 6, 2]), "HatchedGold": Ft(19, 10), "Lime": new MapAnimFactory("dw", [8, 4, 2, false, 2]), "LimeTalk": new MapAnimFactory("dw", [8, 6, 2, false, 6]), "Rabbit": new MapAnimFactory("la", [4, 6, 2]), "RabbitTalk": new MapAnimFactory("la", [5, 6, 2]), "RabbitClean": Ft(27, 10), "RabbitCleanTalk": new MapAnimFactory("la", [27, 10, 2]), "Turky": new MapAnimFactory("dw", [4, 4, 2]), "TurkyEgg": Ft(15, 5), "Bearbo": Ft(0, 2, true), "Mowz": new MapAnimFactory("dw", [0, 4, 2]), "Sqorl": new MapAnimFactory("dw", [0, 6, 2]), // Below Village "Robo2": new MapAnimFactory("sw", [4, 8]), "Mole": new MapAnimFactory("la", [28, 12, 2]), "MoleSoup": new MapAnimFactory("la", [28, 14, 2]), "TV": new MapAnimFactory("as", [[P(30, 14), P(31, 14)], false, 2]), // Research Lab "RAPBATTLE": new MapAnimFactory("la", [3, 10, 2]), "RAPSprout": Ft(6, 3), "Chair1": Ft(3, 8), "Chair2": Ft(3, 9), "DrJeff1": new MapAnimFactory("la", [8, 8, 2]), "DrJeff2": new MapAnimFactory("la", [8, 10, 2]), "DrJeff3": new MapAnimFactory("la", [26, 0, 2]), "DrJeff4": Ft(26, 2), "Switch0": Ft(0, 8), "Switch0d": Ft(0, 9), "Door0": Ft(0, 10), "Door0d": Ft(0, 11), "Switch1": Ft(1, 8), "Switch1d": Ft(1, 9), "Door1": Ft(1, 10), "Door1d": Ft(1, 11), "Switch2": Ft(2, 8), "Switch2d": Ft(2, 9), "Door2": Ft(2, 10), "Door2d": Ft(2, 11), "CalcotteCage0": Ft(29, 15), "CalcotteCage1": Ft(30, 15), "CalcotteCage2": Ft(31, 15), // Bridge "Worker": new MapAnimFactory("sw", [9, 8]), "WorkerTalk": new MapAnimFactory("ds", [[[P(9, 8), P(13, 10)], [P(10, 8), P(14, 10)], [P(11, 8), P(15, 10)], [P(12, 8), P(16, 10)]]]), "BWorker": new MapAnimFactory("dw", [13, 8, 2]), "Cow1": Ft(10, 4, true), "Cow2": Ft(10, 5, true), "CCJog": new MapAnimFactory("as", [[P(29, 12), P(29, 13), P(29, 14), P(29, 13)]]), "CCDrink": new MapAnimFactory("as", [[P(30, 12), P(30, 13)], false, 1]), "HazardVert": Ft(0, 1, true), "LogTop": Ft(4, 1, true), "LogBottom": Ft(4, 2, true), "ConstructionShop": Ft(19, 11), "SadConstr": new MapAnimFactory("la", [27, 0, 2]), "SadConstrRun": new MapAnimFactory("ds", [[[P(27, 5), P(27, 6), P(27, 7), P(27, 6)], [P(27, 2), P(27, 3), P(27, 4), P(27, 3)]]]), // Underwater "Fishy": new MapAnimFactory("dw", [4, 12, 2]), "Monky": new MapAnimFactory("dw", [4, 14, 2]), "Kelp1": new MapAnimFactory("la", [17, 8, 2]), "Kelp2": new MapAnimFactory("la", [18, 8, 2]), "Vase1": Ft(19, 8), "Vase2": Ft(19, 9), "PirateMonk": new MapAnimFactory("la", [17, 10, 2]), "ChestX": Ft(13, 11), "PirateRice": Ft(18, 10), "PirateGMO": Ft(18, 11), "ShipL": Ft(1, 1, true), "ShipM": Ft(2, 1, true), "ShipR": Ft(3, 1, true), "SeaMonCorpse": Ft(2, 8, true), "SeaMonL": Ft(1, 2, true), "SeaMonM": new MapAnimFactory("la", [2, 2, 2, true]), "SeaMonR": Ft(3, 2, true), "SeaMon2L": Ft(1, 3, true), "SeaMon2M": new MapAnimFactory("la", [1, 8, 2, true]), "SeaMon2R": Ft(3, 3, true), "Waterfall": new MapAnimFactory("dw", [0, 12, 4]), "WaterfallEnd": new MapAnimFactory("dw", [0, 16, 4]), "Rock": Ft(16, 11), // Fake Farm "Jef": new MapAnimFactory("sw", [8, 12]), "JefTalkR": new MapAnimFactory("as", [[P(11, 12), P(12, 12)]]), "JefTalkS": new MapAnimFactory("as", [[P(10, 12), P(12, 13)]]), "Chicky": new MapAnimFactory("sw", [13, 12]), "Pig": new MapAnimFactory("dw", [3, 16, 2]), "Mower": new MapAnimFactory("dw", [4, 16, 2]), "Golem": Ft(4, 18), "TruckFuck": Ft(4, 3, true), "FTV": new MapAnimFactory("la", [5, 1, 2, true]), "FTVOff": Ft(5, 3, true), "Hotbox": Ft(4, 19), "Outlet1": Ft(5, 18), "Outlet2": Ft(5, 19), "FFDoor1": Ft(6, 18), "FFDoor2": Ft(6, 19), "Zap": new MapAnimFactory("la", [7, 18, 2]), "HOUSEKEEPER": Ft(16, 16), "Tire1": Ft(12, 14), "Tire2": Ft(12, 15), "HOUSEKEEPERTalk": new MapAnimFactory("as", [[P(16, 17), P(16, 18), P(16, 19), P(16, 18)]]), "Crouton": Ft(17, 12), "CroutonTalk": new MapAnimFactory("as", [[P(17, 12), P(18, 12), P(19, 12)]]), // South City "Capo": new MapAnimFactory("la", [31, 12, 2]), "Mobsty1": new MapAnimFactory("sw", [8, 16]), "Mobsty2": new MapAnimFactory("dw", [12, 18, 2]), "Skumpy1": new MapAnimFactory("la", [15, 16, 2]), "Skumpy2": new MapAnimFactory("la", [13, 16, 2]), "Skumpy3": new MapAnimFactory("la", [14, 16, 2]), "Skumpy4": new MapAnimFactory("la", [12, 16, 2]), "BarL": Ft(18, 15), "BarM": Ft(19, 15), "MobstyOut": Ft(17, 15), "MobstyHurt": new MapAnimFactory("la", [26, 3, 2]), "Pigeon1": new MapAnimFactory("la", [17, 13, 2]), "Pigeon2": new MapAnimFactory("la", [18, 13, 2]), "DoggyBags": Ft(6, 3, true), "Abuelita": new MapAnimFactory("la", [19, 13, 2]), "AbuelitaThrow": new MapAnimFactory("la", [26, 15, 2, false, 1]), "ChurchTip": Ft(8, 0), "FountainUL": new MapAnimFactory("as", [[P(3, 8), P(7, 8)], true]), "FountainUR": new MapAnimFactory("as", [[P(4, 8), P(8, 8)], true]), "FountainLLL": new MapAnimFactory("as", [[P(2, 9), P(6, 9)], true]), "FountainLML": new MapAnimFactory("as", [[P(3, 9), P(7, 9)], true]), "FountainLMR": new MapAnimFactory("as", [[P(4, 9), P(8, 9)], true]), "FountainLRR": new MapAnimFactory("as", [[P(5, 9), P(9, 9)], true]), // North City "Car1": new MapAnimFactory("dw", [0, 4, 2, true]), "Car2": new MapAnimFactory("dw", [4, 4, 2, true]), "Car3": new MapAnimFactory("dw", [0, 6, 2, true]), "Car4": new MapAnimFactory("dw", [4, 6, 2, true]), "St12": Ft(7, 0, true), "St13": Ft(7, 1, true), "St14": Ft(7, 2, true), "Cop": new MapAnimFactory("sw", [20, 0]), "CopStand": new MapAnimFactory("dw", [20, 4, 1]), "CopTalk": new MapAnimFactory("as", [[P(22, 4), P(23, 4)]]), "DelivTruck": new MapAnimFactory("dw", [20, 5, 2]), "Vendo": new MapAnimFactory("dw", [20, 7, 2]), "HoverNernd": new MapAnimFactory("dw", [20, 11, 2]), "Stand": new MapAnimFactory("dw", [20, 9, 1]), "Robber": new MapAnimFactory("dw", [20, 10, 1]), "CaughtRobber": Ft(17, 16), "NerdMech": Ft(0, 3, true), "Nernd1": new MapAnimFactory("dw", [20, 13, 2]), "Nernd2": new MapAnimFactory("dw", [20, 15, 2]), "GirlNernd": new MapAnimFactory("dw", [20, 17, 2]), "FishNernd": new MapAnimFactory("dw", [20, 19, 2]), "Mailman": new MapAnimFactory("la", [19, 16, 2]), "GamerCorpse": Ft(19, 18), "ATM": Ft(19, 19), "Mush1": new MapAnimFactory("la", [17, 17, 2]), "Mush2": new MapAnimFactory("la", [18, 16, 2]), "Mush3": Ft(18, 18), "Mush4": Ft(18, 19), "Mush5": Ft(17, 19), "HHolerGuy": new MapAnimFactory("la", [4, 20, 2]), "Barnt": new MapAnimFactory("la", [3, 21, 2]), "Danny": new MapAnimFactory("la", [0, 22, 2]), "Hole": Ft(4, 22), "CoverL": Ft(2, 22), "CoverM": Ft(3, 20), "CoverR": Ft(2, 23), "LavaLamp": new MapAnimFactory("la", [26, 5, 6]), "Keycard": Ft(2, 20), "Dweeb1": Ft(1, 22), "Dweeb2": Ft(1, 23), "Dweeb3": Ft(2, 21), "PCL": Ft(13, 6), "PCR": Ft(13, 7), "PCRbeef": Ft(11, 0), // HQ 1 "Newbot": new MapAnimFactory("sw", [5, 20]), "Trendy1": new MapAnimFactory("dw", [10, 20, 2]), "Trendy2": new MapAnimFactory("dw", [10, 22, 2]), "Receptionist": new MapAnimFactory("la", [9, 22, 2]), "Fuzuru": new MapAnimFactory("la", [24, 0, 3]), "Hungy": new MapAnimFactory("la", [10, 20, 2]), "Food2": Ft(3, 23), "HQChairL": Ft(9, 20), "HQChairR": Ft(9, 21), "RollerBob": new MapAnimFactory("dw", [14, 20, 2]), "MacL": Ft(13, 4), "MacR": Ft(13, 5), "FriendPCL": Ft(27, 8), "FriendPCR": Ft(27, 9), // HQ 2 "RollerStart": new MapAnimFactory("sw", [20, 21]), "RollerEnd": new MapAnimFactory("dw", [14, 22, 2]), "TechRock": new MapAnimFactory("sw", [18, 20]), "TechRockPressed": new MapAnimFactory("sw", [18, 21]), "BuffNerd": new MapAnimFactory("dw", [18, 22, 2]), // HQ 3 "HazardL": Ft(6, 0, true), "HazardR": Ft(6, 1, true), "PodBaby1": new MapAnimFactory("la", [1, 20, 2]), "PodBaby2": new MapAnimFactory("la", [22, 22, 2]), "PodBaby3": new MapAnimFactory("la", [23, 22, 2]), "HurtWorker": new MapAnimFactory("la", [0, 20, 2]), "Chungus0": Ft(24, 23), "Chungus1": Ft(24, 22), "TheMonster": Ft(6, 2, true, "foreground"), // HQ 4 "Prophet1": Ft(24, 6), "Prophet2": Ft(24, 7), "Prophet3": Ft(24, 8), "Prophet4": Ft(24, 9), "Convince2": Ft(24, 5), "LotusBees": new MapAnimFactory("la", [24, 3, 2]), // HQ 5 "BeckBack1": Ft(26, 17), "BeckBack2": new MapAnimFactory("la", [26, 18, 2]), "BeckBack3": new MapAnimFactory("la", [26, 20, 2]), "BeckBack4": new MapAnimFactory("la", [26, 22, 2]), // HQ 6 "BeckCry1": new MapAnimFactory("la", [25, 15, 2]), "BeckCry2": new MapAnimFactory("la", [25, 17, 2]), "FBBack": Ft(24, 10), "FBSide": Ft(24, 11), "FBFront": new MapAnimFactory("la", [24, 12, 2]), "FBLook": new MapAnimFactory("la", [24, 14, 2]), "FBMad": new MapAnimFactory("la", [26, 13, 2]), "FBChair": Ft(24, 16), "FBGrab": Ft(24, 17), "FBToss": Ft(24, 18), "FBPush1": Ft(24, 19), "FBPush2": Ft(25, 19), "FBStand": new MapAnimFactory("la", [24, 20, 2]), "FBTable": Ft(7, 3, true), "FBTableFlip": new MapAnimFactory("la", [8, 0, 8, true, 24]), "FBBtn1": Ft(25, 20), "FBBtn2": Ft(25, 21), "FBBtn3": Ft(25, 22), "FBBtn4": Ft(25, 23), "FloorFlip0": Ft(25, 0), "FloorFlip1": Ft(25, 1), "FloorFlip2": Ft(25, 2), "FloorFlip3": Ft(25, 3), "FloorFlip4": Ft(25, 4), "FloorFlip5": Ft(25, 5), "FloorFlip6": Ft(25, 6), "FloorFlip7": Ft(25, 7), "FloorFlip8": Ft(25, 8), "FloorFlip9": Ft(25, 9), "FloorFlip10": Ft(25, 10), "FloorFlip11": Ft(25, 11), "FloorFlip12": Ft(25, 12), "FloorFlip13": Ft(25, 13), "FloorFlip14": Ft(25, 14), // The Cave "RopeTop": Ft(27, 12), "RopeFade": Ft(27, 13), "RopeSign": Ft(27, 14), "RopeBottom": Ft(27, 15), "HealingStation": Ft(27, 16), "FOE": new MapAnimFactory("la", [27, 17, 4]), "FOEbig": new MapAnimFactory("la", [0, 8, 2, true, 3]), // Post-Game "Carlos": new MapAnimFactory("dw", [28, 0, 2]), "CoopPainter": new MapAnimFactory("la", [27, 21, 2]), "IGGirl1": new MapAnimFactory("dw", [28, 2, 2]), "IGGirl2": new MapAnimFactory("dw", [28, 4, 2]), "IGWorker1": new MapAnimFactory("dw", [28, 6, 2]), "IGWorker2": new MapAnimFactory("dw", [28, 8, 2]), "IGWorker3": new MapAnimFactory("dw", [28, 10, 2]), "Garlic": Ft(12, 19), "Apple": Ft(15, 19), "Corn": Ft(28, 23) };
HauntedBees/Farming-Fantasy
js/animation/mapAnims.js
JavaScript
agpl-3.0
20,858
'use strict'; angular.module('BattleShipApp.directives', []). directive('appVersion', ['version', function (version) { return function (scope, elm, attrs) { elm.text(version); }; }]);
msavencov/academy.battleship
Academy.BattleShip.Web/App/directives.js
JavaScript
agpl-3.0
221
define('jst/ExternalTools/ExternalToolsCollectionView', ["compiled/handlebars_helpers"], function (Handlebars) { var template = Handlebars.template, templates = Handlebars.templates = Handlebars.templates || {}; templates['ExternalTools/ExternalToolsCollectionView'] = template(function (Handlebars,depth0,helpers,partials,data) { helpers = helpers || Handlebars.helpers; var foundHelper, self=this; return "<table class=\"table table-striped\">\n <thead>\n <tr>\n <th>Name</th>\n <th>Extensions</th>\n <th>&nbsp;</th>\n </tr>\n </thead>\n <tbody class=\"collectionViewItems\"></tbody>\n</table>\n<div class=\"paginatedLoadingIndicator\" style=\"display: none\"></div>\n";}); return templates['ExternalTools/ExternalToolsCollectionView']; });
owly/canvassy
public/javascripts/jst/ExternalTools/ExternalToolsCollectionView.js
JavaScript
agpl-3.0
787
import React from 'react'; import Head from '../components/head'; import '../styles/custom.css'; const Resume = () => ( <div className="resume-page"> <Head /> <iframe frameBorder="0" className="resume-frame" src="https://souvik.me/resume.pdf"></iframe> <style jsx>{` .resume-frame { width: 100%; height: 100%; min-height: 100%; display: block; } .resume-page { width: 100%; height: 100vh; } `}</style> </div> ); export default Resume;
souvik1997/website
frontend/pages/resume.js
JavaScript
agpl-3.0
572
/* This file is part of Aaron Rest Server. Aaron Rest Server is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Aaron Rest Server is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Aaron Rest Server. If not, see <http://www.gnu.org/licenses/>. */ 'use strict'; var util = require('util'); var permissionLog = util.debuglog('permission'); var config = require('../config'); var pool = null; function updatePermissions(req, res) { permissionLog('update request!'); pool.getConnection(function(err, connection) { if(err) { console.error(err); return res.send(500, new Error('mysql')); } var post = {}; if(typeof req.params.email !== 'string') { console.error('updatePermissions: invalid-input-data'); return res.send(400, new Error('invalid-input-data')); } else if(!config.r.email.test(req.params.email)) { console.error('updatePermissions: invalid-input-formatting'); return res.send(400, new Error('invalid-input-formatting')); } /*if(Object.keys(post).length === 0) { console.error('updatePermissions: invalid-input-data'); return res.send(400, new Error('no-data-inputted')); }*/ return res.send(500, new Error('not implemented yet!')); // TODO - not implemented yet! var query = connection.query(';', [], function(err, results) { connection.release(); if(err) { console.error(err, query.sql); return res.send(500, new Error('mysql')); } console.log(results); res.send(200, {message: 'success'}); }); }); } function getPermissions(req, res) { permissionLog('get request!'); pool.getConnection(function(err, connection) { if(err) { console.error(err); return res.send(500, new Error('mysql')); } var query = connection.query( 'SELECT p.*, ghp.* '+ 'FROM users u '+ 'INNER JOIN users_has_groups uhg ON u.user_id = uhg.users_user_id '+ 'INNER JOIN groups g ON g.group_id = uhg.groups_group_id '+ 'INNER JOIN groups_has_permissions ghp ON g.group_id = ghp.groups_group_id '+ 'INNER JOIN permissions p ON p.permission_id = ghp.permissions_permission_id '+ 'INNER JOIN permissions_has_applications pha ON p.permission_id = pha.permissions_permission_id '+ 'INNER JOIN applications a ON a.application_shortname = pha.applications_application_shortname '+ 'WHERE user_email = ?;', [req.params.email], function(err, results) { connection.release(); if(err) { console.error(err, query.sql); return res.send(500, new Error('mysql')); } console.log(results); res.send(200, {data: 'here'}); } ); }); } function activateRoute(server, mysqlPool, checkAuth) { pool = mysqlPool; server.post('/permissions/user/:email', checkAuth, updatePermissions); server.get('/permissions/user/:email', checkAuth, getPermissions); } module.exports.activateRoute = activateRoute;
ldbib/aaron-rest-server
routes/permissions.js
JavaScript
agpl-3.0
3,450
var assert = require('assert') , FeedParser = require('../') , feedparser = new FeedParser() , feed = __dirname + '/feeds/unknown-namespace.atom' , meta = {} , articles = {} ; describe('feedparser', function(){ describe('nondefaultnamespace Test case 3: default namespace Atom; XHTML namespace mapped to a prefix; FooML namespace default in the namespace DIV', function(){ before(function(done){ feedparser.parseFile(feed, function (error, _meta, _articles) { assert.ifError(error); meta = _meta; articles = _articles; done(); }); }); describe('article', function(){ it('should have the expected title', function() { assert.equal(articles[0].title, 'This entry contains XHTML-looking markup that is not XHTML'); }); it('should have the expected description', function(){ assert.ok(articles[0].description.match(/^<h:div xmlns="http:\/\/hsivonen.iki.fi\/FooML">/)); assert.ok(articles[0].description.match(/<h:li>This is an XHTML list item./)); assert.ok(articles[0].description.match(/<li>This is not an XHTML list item./)); }); }); }); describe('nondefaultnamespace using static methods Test case 3: default namespace Atom; XHTML namespace mapped to a prefix; FooML namespace default in the namespace DIV', function(){ before(function(done){ FeedParser.parseFile(feed, function (error, _meta, _articles) { assert.ifError(error); meta = _meta; articles = _articles; done(); }); }); describe('article', function(){ it('should have the expected title', function() { assert.equal(articles[0].title, 'This entry contains XHTML-looking markup that is not XHTML'); }); it('should have the expected description', function(){ assert.ok(articles[0].description.match(/^<h:div xmlns="http:\/\/hsivonen.iki.fi\/FooML">/)); assert.ok(articles[0].description.match(/<h:li>This is an XHTML list item./)); assert.ok(articles[0].description.match(/<li>This is not an XHTML list item./)); }); }); }); });
mariuz/atom-reader
tests/node_modules/feedparser/test/nondefaultNamespaces-05.js
JavaScript
agpl-3.0
2,141
OC.L10N.register( "files", { "Storage is temporarily not available" : "Lagring är tillfälligt inte tillgänglig", "Storage invalid" : "Lagring ogiltig", "Unknown error" : "Okänt fel", "File could not be found" : "Fil kunde inte hittas", "Move or copy" : "Flytta eller kopiera", "Download" : "Hämta", "Delete" : "Ta bort", "Home" : "Hem", "Close" : "Stäng", "Favorites" : "Favoriter", "Could not create folder \"{dir}\"" : "Kunde inte skapa mapp \"{dir}\"", "This will stop your current uploads." : "Detta kommer att stoppa nuvarande uppladdningar.", "Upload cancelled." : "Uppladdning avbruten.", "Processing files …" : "Bearbetar filer ...", "…" : "...", "Unable to upload {filename} as it is a directory or has 0 bytes" : "Kan inte ladda upp {filename} eftersom den antingen är en mapp eller har 0 bytes.", "Not enough free space, you are uploading {size1} but only {size2} is left" : "Inte tillräckligt med ledigt utrymme, du laddar upp {size1} men endast {size2} finns kvar.", "Target folder \"{dir}\" does not exist any more" : "Målmapp \"{dir}\" existerar inte mer", "Not enough free space" : "Inte tillräckligt med ledigt utrymme", "An unknown error has occurred" : "Ett okänt fel uppstod", "Uploading …" : "Laddar upp ..", "{loadedSize} of {totalSize} ({bitrate})" : "{loadedSize} av {totalSize} ({bitrate})", "Uploading that item is not supported" : "Uppladdning av det här objektet stöds inte", "Target folder does not exist any more" : "Målmapp existerar inte längre", "Operation is blocked by access control" : "Operationen blockeras av åtkomstkontroll", "Error when assembling chunks, status code {status}" : "Fel vid ihopsättning av bitarna: statuskod: {status}", "Actions" : "Åtgärder", "Rename" : "Byt namn", "Copy" : "Kopiera", "Choose target folder" : "Välj målmapp", "Open" : "Öppna", "Delete file" : "Ta bort fil", "Delete folder" : "Ta bort mapp", "Disconnect storage" : "Koppla bort lagring", "Leave this share" : "Lämna denna delning", "Could not load info for file \"{file}\"" : "Kunde inte läsa in information för filen \"{file}\"", "Files" : "Filer", "Details" : "Detaljer", "Select" : "Välj", "Pending" : "Väntar", "Unable to determine date" : "Misslyckades avgöra datum", "This operation is forbidden" : "Denna operation är förbjuden", "This directory is unavailable, please check the logs or contact the administrator" : "Denna katalog är inte tillgänglig, vänligen kontrollera loggarna eller kontakta administratören", "Could not move \"{file}\", target exists" : "Kunde inte flytta \"{file}\", filen existerar redan", "Could not move \"{file}\"" : "Kunde inte flytta \"{file}\"", "copy" : "kopia", "Could not copy \"{file}\", target exists" : "Kunde inte kopiera \"{file}\", filen existerar redan", "Could not copy \"{file}\"" : "Kunde inte kopiera \"{file}\"", "Copied {origin} inside {destination}" : "Kopierade {origin} till {destination}", "Copied {origin} and {nbfiles} other files inside {destination}" : "Kopierade {origin} och {nbfiles} andra filer i {destination}", "{newName} already exists" : "{newName} existerar redan", "Could not rename \"{fileName}\", it does not exist any more" : "Kunde inte döpa om \"{fileName}\", filen existerar inte mer", "The name \"{targetName}\" is already used in the folder \"{dir}\". Please choose a different name." : "Namnet \"{targetName}\" används redan i mappen \"{dir}\". Vänligen välj ett annat namn.", "Could not rename \"{fileName}\"" : "Kan inte döpa om \"{fileName}\"", "Could not create file \"{file}\"" : "Kunde inte skapa fil \"{fileName}\"", "Could not create file \"{file}\" because it already exists" : "Kunde inte skapa fil \"{file}\" därför att den redan existerar", "Could not create folder \"{dir}\" because it already exists" : "Kunde inte skapa \"{dir}\" därför att den redan existerar", "Could not fetch file details \"{file}\"" : "Kunde inte hämta filinformation \"{file}\"", "Error deleting file \"{fileName}\"." : "Fel när \"{fileName}\" skulle raderas.", "No search results in other folders for {tag}{filter}{endtag}" : "Inga sökresultat i andra mappar för {tag}{filter}{endtag}", "Enter more than two characters to search in other folders" : "Ange mer än två tecken för att söka i andra mappar", "Name" : "Namn", "Size" : "Storlek", "Modified" : "Ändrad", "_%n folder_::_%n folders_" : ["%n mapp","%n mappar"], "_%n file_::_%n files_" : ["%n fil","%n filer"], "{dirs} and {files}" : "{dirs} och {files}", "_including %n hidden_::_including %n hidden_" : ["inkluderar %n gömd","inkluderar %n gömda"], "You don’t have permission to upload or create files here" : "Du har inte tillåtelse att ladda upp eller skapa filer här", "_Uploading %n file_::_Uploading %n files_" : ["Laddar upp %n fil","Laddar upp %n filer"], "New" : "Ny", "Select file range" : "Välj filintervall", "{used} of {quota} used" : "{used} av {quota} använt", "{used} used" : "{used} använt", "\"{name}\" is an invalid file name." : "\"{name}\" är ett ogiltigt filnamn.", "File name cannot be empty." : "Filnamn kan inte vara tomt.", "\"/\" is not allowed inside a file name." : "\"/\" är inte tillåtet i ett filnamn.", "\"{name}\" is not an allowed filetype" : "\"{name}\" är inte en tillåten filtyp", "Storage of {owner} is full, files can not be updated or synced anymore!" : "Lagring av {owner} är full, filer kan inte uppdateras eller synkroniseras längre!", "Your storage is full, files can not be updated or synced anymore!" : "Ditt lagringsutrymme är fullt, filer kan inte längre uppdateras eller synkroniseras!", "Storage of {owner} is almost full ({usedSpacePercent}%)." : "Lagring av {owner} är nästan full ({usedSpacePercent}%).", "Your storage is almost full ({usedSpacePercent}%)." : "Ditt lagringsutrymme är nästan fullt ({usedSpacePercent}%).", "_matches '{filter}'_::_match '{filter}'_" : ["matchar '{filter}'","matcha '{filter}'"], "View in folder" : "Utforska i mapp", "Copied!" : "Kopierad!", "Copy direct link (only works for users who have access to this file/folder)" : "Kopiera direktlänk (fungerar endast för användare som har åtkomst till denna fil eller mapp)", "Path" : "Sökväg", "_%n byte_::_%n bytes_" : ["%n bytes","%n bytes"], "Favorited" : "Favoriserad", "Favorite" : "Favorit", "You can only favorite a single file or folder at a time" : "Du kan bara favoritmarkera en fil eller mapp åt gången", "New folder" : "Ny mapp", "Upload file" : "Ladda upp fil", "Recent" : "Senaste", "Not favorited" : "Inte favoriserade", "Remove from favorites" : "Ta bort från favoriter", "Add to favorites" : "Lägg till i favoriter", "An error occurred while trying to update the tags" : "Ett fel uppstod när uppdatera taggarna", "Added to favorites" : "Lades till i favoriter", "Removed from favorites" : "Togs bort från favoriter", "You added {file} to your favorites" : "Du la till {file} till dina favoriter", "You removed {file} from your favorites" : "Du tog bort {file} från dina favoriter", "File changes" : "Filändringar", "Created by {user}" : "Skapad av {user}", "Changed by {user}" : "Ändrad av {user}", "Deleted by {user}" : "Raderad av {user}", "Restored by {user}" : "Återställd av {user}", "Renamed by {user}" : "Filnamn ändrat av {user}", "Moved by {user}" : "Flyttad av {user}", "\"remote user\"" : "\"extern användare\"", "You created {file}" : "Du skapade {file}", "You created an encrypted file in {file}" : "Du skapade en krypterad fil i {file}", "{user} created {file}" : "{user} skapade {file}", "{user} created an encrypted file in {file}" : "{user} skapade en krypterad fil i {file}", "{file} was created in a public folder" : "{file} skapades i en offentlig mapp", "You changed {file}" : "Du ändrade {file}", "You changed an encrypted file in {file}" : "Du ändrade en krypterad fil i {file}", "{user} changed {file}" : "{user} ändrade {file}", "{user} changed an encrypted file in {file}" : "{user} ändrade en krypterad fil i {file}", "You deleted {file}" : "Du tog bort {file}", "You deleted an encrypted file in {file}" : "Du tog bort en krypterad fil i {file}", "{user} deleted {file}" : "{user} tog bort {file}", "{user} deleted an encrypted file in {file}" : "{user} tog bort en krypterad fil i {file}", "You restored {file}" : "Du återställde {file}", "{user} restored {file}" : "{user} återställde {file}", "You renamed {oldfile} to {newfile}" : "Du ändrade filnamn {oldfile} till {newfile}", "{user} renamed {oldfile} to {newfile}" : "{user} ändrade filnamn {oldfile} till {newfile}", "You moved {oldfile} to {newfile}" : "Du flyttade {oldfile} till {newfile}", "{user} moved {oldfile} to {newfile}" : "{user} flyttade {oldfile} till {newfile}", "A file has been added to or removed from your <strong>favorites</strong>" : "En fil har lagts till eller tagits bort från dina <strong>favoriter</strong>", "A file or folder has been <strong>changed</strong>" : "En ny fil eller mapp har blivit <strong>ändrad</strong>", "A favorite file or folder has been <strong>changed</strong>" : "En favorit-fil eller mapp har blivit <strong>ändrad</strong>", "All files" : "Alla filer", "Unlimited" : "Obegränsad", "Upload (max. %s)" : "Ladda upp (högst %s)", "Accept" : "Acceptera", "Reject" : "Avvisa", "Incoming ownership transfer from {user}" : "Inkommande ägaröverföring från {user}", "Do you want to accept {path}?\n\nNote: The transfer process after accepting may take up to 1 hour." : "Vill du acceptera {path}?\n\nNotera: Överföringen kan efter att du accepterat ta upp till 1 timme.", "Ownership transfer failed" : "Ägarskapsöverföring misslyckades", "Your ownership transfer of {path} to {user} failed." : "Din ägaröverföring av {path} till {user} misslyckades.", "The ownership transfer of {path} from {user} failed." : "Din ägaröverföring av {path} från {user} misslyckades.", "Ownership transfer done" : "Ägarskapsöverföring klar", "Your ownership transfer of {path} to {user} has completed." : "Din ägaröverföring av {path} till {user} är klar.", "The ownership transfer of {path} from {user} has completed." : "Ägaröverföringen av {path} från {user} är klar.", "in %s" : "om %s", "File Management" : "Filhantering", "Transfer ownership of a file or folder" : "Överför ägarskap till en fil eller mapp", "Choose file or folder to transfer" : "Välj fil eller mapp att överföra", "Change" : "Ändra", "New owner" : "Ny ägare", "Search users" : "Sök användare", "Choose a file or folder to transfer" : "Välj en fil eller mapp att överföra", "Transfer" : "Överför", "Transfer {path} to {userid}" : "Överför {path} till {userid}", "Invalid path selected" : "Ogiltig sökväg vald", "Ownership transfer request sent" : "Förfrågan om ägaröverföring skickad", "Cannot transfer ownership of a file or folder you don't own" : "Det går inte att överföra ägarskap till en fil eller mapp som du inte äger", "Tags" : "Taggar", "Unable to change the favourite state of the file" : "Kan inte ändra filens favoritstatus", "Error while loading the file data" : "Fel vid inläsning av fildata", "%s used" : "%s använt", "%s%% of %s used" : "%s%% av %s använt", "%1$s of %2$s used" : "%1$s av %2$s använt", "Settings" : "Inställningar", "Show hidden files" : "Visa dolda filer", "WebDAV" : "WebDAV", "Use this address to access your Files via WebDAV" : "Använd denna adress för att komma åt dina filer med WebDAV", "Toggle grid view" : "Växla rutnätsvy", "No files in here" : "Inga filer kunde hittas", "Upload some content or sync with your devices!" : "Ladda upp innehåll eller synkronisera med dina enheter!", "No entries found in this folder" : "Inget innehåll hittades i denna mapp", "Select all" : "Välj allt", "Upload too large" : "För stor uppladdning", "The files you are trying to upload exceed the maximum size for file uploads on this server." : "Filerna du försöker ladda upp överstiger den maximala storleken för filöverföringar på servern.", "No favorites yet" : "Inga favoriter ännu", "Files and folders you mark as favorite will show up here" : "Filer och mappar markerade som favoriter kommer att visas här", "Deleted files" : "Borttagna filer", "Shares" : "Delningar", "Shared with others" : "Delad med andra", "Shared with you" : "Delad med dig", "Shared by link" : "Delad via länk", "Deleted shares" : "Borttagna delningar", "Pending shares" : "Väntande delningar", "Text file" : "Textfil", "New text file.txt" : "Ny textfil.txt", "Unshare" : "Sluta dela", "This group folder is full, files can not be updated or synced anymore!" : "Denna gruppmapp är full, filer kan inte uppdateras eller synkroniseras längre!", "This external storage is full, files can not be updated or synced anymore!" : "Denna externa lagring är full, filer kan inte uppdateras eller synkroniseras längre!", "Storage of {owner} is almost full ({usedSpacePercent}%)" : "Lagring av {owner} är nästan full ({usedSpacePercent}%)", "This group folder is almost full ({usedSpacePercent}%)" : "Denna gruppmapp är nästan full ({usedSpacePercent}%)", "This external storage is almost full ({usedSpacePercent}%)" : "Denna externa lagring är nästan full ({usedSpacePercent}%)", "Your storage is almost full ({usedSpacePercent}%)" : "Ditt lagringsutrymme är nästan fullt ({usedSpacePercent}%)", "A file or folder has been <strong>changed</strong> or <strong>renamed</strong>" : "En fil har blivit <strong>ändrad</strong> eller <strong>bytt namn</strong>", "A new file or folder has been <strong>created</strong>" : "En ny fil eller mapp har blivit <strong>skapad</strong>", "A file or folder has been <strong>deleted</strong>" : "En fil eller mapp har <strong>tagits bort</strong>", "Limit notifications about creation and changes to your <strong>favorite files</strong> <em>(Stream only)</em>" : "Begränsa aviseringar om skapande och ändringar till dina <strong>favoritfiler</strong> <em>(Endast i flödet)</em>", "A file or folder has been <strong>restored</strong>" : "En fil eller mapp har <strong>återställts</strong>", "Cannot transfter ownership of a file or folder you don't own" : "Det går inte att överföra ägarskap till en fil eller mapp som du inte äger", "Use this address to <a href=\"%s\" target=\"_blank\" rel=\"noreferrer noopener\">access your Files via WebDAV</a>" : "Använd denna adress för att <a href=\"%s\" target=\"_blank\" rel=\"noreferrer noopener\">komma åt dina filer med WebDAV</a>" }, "nplurals=2; plural=(n != 1);");
andreas-p/nextcloud-server
apps/files/l10n/sv.js
JavaScript
agpl-3.0
15,263
function mainPlayer() { this.x = 100; this.y = 200; this.d = "u"; // "d", "l", "r", and combinations? this.sword = false; this.walking = false; this.bomb = false; this.bow = false; this.keyFrameRow = 0; this.keyFrame = 0; this.keyFrameN = 4; this.updateFrameN = 2; this.updateFrameDelay = 0; this.swordType = "eagle"; this.speaking = false; this.text = ""; this.displayq = []; this.walkq = []; //this.walkQueue = 0; this.walkFlag = { "left" : false, "right" : false, "up":false, "down":false, "leftq":0, "rightq":0, "upq":0, "downq":0 }; this.walkKey = ["up", "right", "down", "left"]; this.walkLookup = { "up" : 0, "right" : 1, "down":2, "left":3 }; this.walkTransitionDelay = 2; this.walkDisplayQ = []; this.dx = 12; this.dy = 12; this.img_w = 16; this.img_h = 16; this.img_x = 0; this.img_y = 0; this.world_w = 64; this.world_h = 64; //this.swordReady = true; this.bombReady = true; this.bowReady = true; this.swordKeyState = "idle"; // "fire", "warm" this.bombKeyState = "idle"; // "fire", "warm" this.bowKeyState = "idle"; // "fire", "warm" this.swordKeyEvent = false; this.swordDelayN = 3; this.swordDelay = 0; this.bombEvent = false; // 0 is right. past StepN/2 is below // so ccw // this.bowStep = 0; //this.bowStepN = 32; this.bowStepN = 16; this.bow_da = 2.0*Math.PI/this.bowStepN; this.bowActive = false; this.bowEvent = "idle"; this.bowTurnDelay = 0; this.bowTurnDelayN = 1; this.displayq.push({ "d":"down", "t":-1 }); this.inputEvent = {}; this.state = "idle"; //SWORD STATE this.swordKeyUp = true; this.swordJitterX = 0; this.swordJitterY = 0; } mainPlayer.prototype.init = function(x, y, d) { this.x = x; this.y = y; this.d = d; } mainPlayer.prototype.actualDirection = function() { var n = this.displayq.length; return this.displayq[n-1].d; } mainPlayer.prototype.resetDisplayDirection = function(d) { this.displayq = [{"d":d, "t":5 }]; } mainPlayer.prototype.addToWalkq = function(d) { for (var i=0; i<this.walkq.length; i++) { if (this.walkq.d == d) { return; } } this.walkq.push({ "d":d, "t":5 }); } mainPlayer.prototype.displayDirectionTick = function() { if (this.displayq.length>1) { this.displayq[0].t--; if (this.displayq[0].t<0) { this.displayq.shift(); } } } mainPlayer.prototype.updateDisplayDirection = function() { var curdir = this.currentWalkDirection(); if (curdir == "stop") { this.displayDirectionTick(); console.log(">>>", this.displayq); return; } var n = this.displayq.length; if (curdir != this.displayq[n-1].d) { var old_dir = this.displayq[n-1].d; this.displayq = []; var dl = this.walkTransitionDelay; // 'up' just looks better to me, don't know why... // if ((old_dir == "left") && (curdir == "right")) { this.displayq.push({ "d":"up", "t":dl }); } else if ((old_dir == "right") && (curdir == "left")) { this.displayq.push({ "d":"up", "t":dl }); } else if ((old_dir == "up") && (curdir == "down")) { this.displayq.push({ "d":"right", "t":dl }); } else if ((old_dir == "down") && (curdir == "up")) { this.displayq.push({ "d":"left", "t":dl }); } this.displayq.push({ "d":curdir, "t":-1 }); } this.displayDirectionTick(); } mainPlayer.prototype.updateWalkingFrame = function() { if (this.updateFrameDelay==0) { this.keyFrame++; if (this.keyFrame >= this.keyFrameN) { this.keyFrame=0; } this.updateFrameDelay = this.updateFrameN-1; } else { this.updateFrameDelay--; } } // walking, bow and sword are mutually exclusive // bomb is a modifier to walking. // mainPlayer.prototype.update = function() { g_painter.dirty_flag = true; for (var ev in this.inputEvent) { //if (!this.inputEvent[ev]) { continue; } if (ev == "swordKeyDown") { if ((this.state == "swordAttack") || (this.state == "bow")) { continue; } if (!this.swordReady()) { continue; } if (!this.swordKeyUp) { continue; } console.log("attack!"); this.swordAttack(); //var curdir = this.currentWalkDirection(); var curdir = this.actualDirection(); this.resetDisplayDirection(curdir); console.log("??", curdir); continue; } if (ev == "swordKeyUp") { this.swordKeyUp = true; continue; } if (ev == "bowKeyDown") { continue; } if (ev == "bowKeyUp") { continue; } if (ev == "upKeyDown") { if (!this.walkFlag["up"]) { this.addToWalkq("up"); } this.walkFlag["up"] = true; continue; } if (ev == "upKeyUp") { this.walkFlag["up"] = false; continue; } if (ev == "downKeyDown") { if (!this.walkFlag["down"]) { this.addToWalkq("down"); } this.walkFlag["down"] = true; continue; } if (ev == "downKeyUp") { this.walkFlag["down"] = false; continue; } if (ev == "leftKeyDown") { if (!this.walkFlag["left"]) { this.addToWalkq("left"); } this.walkFlag["left"] = true; continue; } if (ev == "leftKeyUp") { this.walkFlag["left"] = false; continue; } if (ev == "rightKeyDown") { if (!this.walkFlag["right"]) { this.addToWalkq("right"); } this.walkFlag["right"] = true; continue; } if (ev == "rightKeyUp") { this.walkFlag["right"] = false; continue; } console.log("ev", ev); } //console.log("state:", this.state); this.inputEvent = {}; // initial processing of input is done. // if (this.state == "idle") { if (this.walkFlag["up"] || this.walkFlag["down"] || this.walkFlag["left"] || this.walkFlag["right"]) { this.state = "walking"; this._updateWalkQueue(); this.updateWalkingFrame(); } this.updateDisplayDirection(); return; } if (this.state == "walking") { var xy = this.dxdy(); this.x += xy[0]; this.y += xy[1]; this.updateWalkingFrame(); if (this.walkFlag["up"] || this.walkFlag["down"] || this.walkFlag["left"] || this.walkFlag["right"]) { this.state = "walking"; this._updateWalkQueue(); } else { this.state = "idle"; } this.updateDisplayDirection(); return; } if (this.state == "swordAttack") { if (this.swordDelay==0) { this.swordRetract(); if (this.walkFlag["up"] || this.walkFlag["down"] || this.walkFlag["left"] || this.walkFlag["right"]) { this.state = "walking"; this._updateWalkQueue(); } else { this.state = "idle"; } } else { this.swordDelay--; } return; } } mainPlayer.prototype.swordAttack = function() { //DEBUG console.log("sword attack"); this.sword = true; this.swordDelay = this.swordDelayN-1; this.state = "swordAttack"; this.swordKeyUp = false; var jx = 5; var jy = 5; var curdir = this.actualDirection(); if (curdir == "up") { this.swordJitterX = Math.floor((Math.random()-0.3)*jx) this.swordJitterY = Math.floor((Math.random()+1)*jy) } else if (curdir == "down") { this.swordJitterX = Math.floor((Math.random()-0.5)*jx) this.swordJitterY = Math.floor((Math.random()-1)*jy) } else if (curdir == "right") { this.swordJitterX = Math.floor((Math.random()-1)*jx) this.swordJitterY = Math.floor((Math.random()-0.5)*jy) } else if (curdir == "left") { this.swordJitterX = Math.floor((Math.random()+1)*jx) this.swordJitterY = Math.floor((Math.random()-0.5)*jy) } } mainPlayer.prototype.swordRetract = function() { this.sword = false; } mainPlayer.prototype.bombPrepare = function() { console.log("bomb prepare"); this.bomb = true; } mainPlayer.prototype.bombThrow = function() { console.log("bomb throw"); this.bomb = false; } mainPlayer.prototype.keyDownTransition = function(s) { if (s == "idle") { return "fire"; } if (s == "fire") { return "warm"; } if (s == "warm") { return "warm"; } return "fire"; } // keyDown events only set flags that will be polled // by the 'update' function. No state other than // setting the flags should happen here. // mainPlayer.prototype.keyDown = function(code) { // 'z', bomb // if (code == 90) { this.inputEvent["bombKeyDown"] = true; } // 'x', sword // if (code == 88) { this.inputEvent["swordKeyDown"] = true; } // 'c', bow // if (code == 67) { //this.bowActive = true; this.inputEvent["bowKeyDown"] = true; } // left // if (code==37) { this.inputEvent["leftKeyDown"] = true; } // up // else if (code == 38) { this.inputEvent["upKeyDown"] = true; } // right // else if (code == 39) { this.inputEvent["rightKeyDown"] = true; } // down // else if (code == 40) { this.inputEvent["downKeyDown"] = true; } } // keyUp events only set flags that will be polled // by the 'update' function. No state other than // setting the flags should happen here. // mainPlayer.prototype.keyUp = function(code) { // 'x', sword // if (code == 88) { this.inputEvent["swordKeyUp"] = true; } // 'z', bomb // if (code == 90) { this.inputEvent["bombKeyUp"] = true; } // 'c', bow // if (code == 67) { this.inputEvent["bowKeyUp"] = true; } // left // if (code==37) { this.inputEvent["leftKeyUp"] = true; } // up // else if (code == 38) { this.inputEvent["upKeyUp"] = true; } // right // else if (code == 39) { this.inputEvent["rightKeyUp"] = true; } // down // else if (code == 40) { this.inputEvent["downKeyUp"] = true; } } mainPlayer.prototype._updateWalkQueue= function() { var newq = []; for (var i=0; i<this.walkq.length; i++) { var key = this.walkq[i].d; if (this.walkFlag[key]) { newq.push(this.walkq[i]); } } this.walkq = newq; } // returns text direction // mainPlayer.prototype.currentWalkDirection = function() { var kr = -1; var n = this.walkq.length-1; if (n>=0) { kr = this.walkLookup[this.walkq[n].d]; } if (kr<0) { return "stop"; } return this.walkKey[kr]; } // returns text direction // mainPlayer.prototype.dxdy = function() { var dx = this.dx; var dy = this.dy; var xy = { "up":[0,-dy], "right":[dx,0], "down":[0,dy], "left":[-dx,0], "stop":[0,0] }; var d = this.currentWalkDirection(); return xy[d]; } // returns text direction // mainPlayer.prototype.sword_dxdy = function() { var dx = this.swordJitterX; var dy = this.swordJitterY; return [dx,dy]; var xy = { "up":[dx,-dy], "right":[dx,dy], "down":[dx,dy], "left":[-dx,dy], "stop":[0,0] }; var d = this.currentWalkDirection(); return xy[d]; } mainPlayer.prototype.stopWalking = function() { this.walking = false; } mainPlayer.prototype.swordReady = function() { if (this.swordDelay==0) {return true; } return false; } mainPlayer.prototype.swordUpdate = function() { if (this.swordDelay>0) { this.swordDelay--; } else { this.swordDelay=0; } } mainPlayer.prototype.currentDisplayDirection = function() { var a = "up"; if (this.displayq.length>0) { a = this.displayq[0].d; } return a; } mainPlayer.prototype.draw = function() { var kf = this.keyFrame; var d = this.currentDisplayDirection(); var kr = this.walkLookup[d]; var imgx = kf*16; var imgy = kr*16; if (this.sword) { imgy = 4*16; imgx = kr*16; } if (!this.bow) { //g_imgcache.draw_s("noether", imgx, imgy, 16, 16, this.x, this.y, this.world_w, this.world_h); } if ((this.state == "idle") || (this.state == "walking")) { g_imgcache.draw_s("noether", imgx, imgy, 16, 16, this.x, this.y, this.world_w, this.world_h); } if (this.sword) { var a = 0.0; var ix = 0; var iy = 0; var di = this.currentDisplayDirection(); if (di == "up") { a = -Math.PI/2.0; iy=-16; } else if (di == "right") { a = 0.0; ix = 16; } else if (di == "down") { a = Math.PI/2.0; iy = 16; //ix = 16; } else if (di == "left") { a = Math.PI; ix = -16; } ix *= 4; iy *= 4; var s_dxy = this.sword_dxdy(); ix += s_dxy[0]; iy += s_dxy[1]; // tree sword //g_imgcache.draw_s("item", 0, 0, 16, 16, this.x+ix, this.y+iy, this.world_w, this.world_h, a); // zephyr sword //g_imgcache.draw_s("item", 16, 0, 16, 16, this.x+ix, this.y+iy, this.world_w, this.world_h, a); // falcon sword //g_imgcache.draw_s("item", 32, 0, 16, 16, this.x+ix, this.y+iy, this.world_w, this.world_h, a); // eagle sword g_imgcache.draw_s("item", 48, 0, 16, 16, this.x+ix, this.y+iy, this.world_w, this.world_h, a); // hammer //g_imgcache.draw_s("item", 64 , 0, 16, 16, this.x+ix, this.y+iy, this.world_w, this.world_h, a); // amythist wand //g_imgcache.draw_s("item", 112, 0, 16, 16, this.x+ix, this.y+iy, this.world_w, this.world_h, a); // emerald wand //g_imgcache.draw_s("item", 0, 16, 16, 16, this.x+ix, this.y+iy, this.world_w, this.world_h, a); // ank wand //g_imgcache.draw_s("item", 16, 16, 16, 16, this.x+ix, this.y+iy, this.world_w, this.world_h, a); // bomb //ix = 0; //iy = -4*8; //a = 0; //g_imgcache.draw_s("item", 80, 16, 16, 16, this.x+ix, this.y+iy, this.world_w, this.world_h, a); g_imgcache.draw_s("noether", imgx, imgy, 16, 16, this.x, this.y, this.world_w, this.world_h); } if (this.bomb) { var ix = 0, iy = -8; var di = this.currentDisplayDirection(); if (di == "up") { ix = 0; iy = -8; } else if (di == "right") { ix = -2; } else if (di == "down") { ix = -1; iy = -10; } else if (di == "left") { ix = 2; } ix *= 4; iy *= 4; g_imgcache.draw_s("item", 80, 16, 16, 16, this.x+ix, this.y+iy, this.world_w, this.world_h); } if (this.bow) { var imx = this.bowStep*2*16; g_imgcache.draw_s("rotbow", imx, 0, 16, 16, this.x, this.y, this.world_w, this.world_h); } else { //var imx = kr *8 *16; //g_imgcache.draw_s("rotbow", imx, 0, 16, 16, this.x, this.y, this.world_w, this.world_h); } }
abetusk/dolor
html/js/game/.save/cp3/main_player.js
JavaScript
agpl-3.0
14,224
$(document).ready(function() { // Hide GNU-cat $('#loading').hide(); // jQuery cycle plugin usage for screenshot slideshow $('.slideshow').cycle({ fx: 'fade', speed: 1000, timeout: 6000, }); // Show GNU-cat when the submit button is pressed $('input#submit').click(function() { $('#loading').fadeIn(1000); }); // Assign account form fields to variables // (was doing this to do some logic with the below keyup function // to make it so that a field did not react to a master form change if // it was altered by the user. Unfortunately, the JS cannot seem to react // quickly enough to handle anything but slow typing. May attempt rewrite // later. var master_field = $('input#master'); var ohloh_field = $('input#ohloh'); var coderwall_field = $('input#coderwall'); // Have master account input field update all other field master_field.keyup(function () { ohloh_field.val($(this).val()); coderwall_field.val($(this).val()); }); }); $(window).on('unload', function() { // Re-hide GNU-cat when we leave. $('loading').hide(); });
FOSSRIT/charsheet
charsheet/static/js/home.js
JavaScript
agpl-3.0
1,178
/* Copyright (c) 2010, Yahoo! Inc. All rights reserved. Code licensed under the BSD License: http://developer.yahoo.com/yui/license.html version: 3.3.0 build: 3167 */ YUI.add("lang/datatype-date-format_fi",function(a){a.Intl.add("datatype-date-format","fi",{"a":["su","ma","ti","ke","to","pe","la"],"A":["sunnuntaina","maanantaina","tiistaina","keskiviikkona","torstaina","perjantaina","lauantaina"],"b":["tammikuuta","helmikuuta","maaliskuuta","huhtikuuta","toukokuuta","kesäkuuta","heinäkuuta","elokuuta","syyskuuta","lokakuuta","marraskuuta","joulukuuta"],"B":["tammikuuta","helmikuuta","maaliskuuta","huhtikuuta","toukokuuta","kesäkuuta","heinäkuuta","elokuuta","syyskuuta","lokakuuta","marraskuuta","joulukuuta"],"c":"%a %d. %b %Y %k.%M.%S %Z","p":["AP.","IP."],"P":["ap.","ip."],"x":"%d.%m.%Y","X":"%k.%M.%S"});},"3.3.0");
RajkumarSelvaraju/FixNix_CRM
jssource/src_files/include/javascript/yui3/build/datatype/lang/datatype-date-format_fi.js
JavaScript
agpl-3.0
839
(function($){ $.fn.extend({ renderChart: function() { return this.each(function() { var $chart = $(this); if ($chart.children().length > 0) return; var data = $.parseJSON($chart.html()); var saveHTML = $chart.html(); $chart.html('').show().parent(); var chartID = 'chart' + $.fluxx.visualizations.counter++; if (data) { var $card; if (typeof $chart.fluxxCard == 'function') { $card = $chart.fluxxCard(); } else { $card = $('#hand'); } if (data.hasOwnProperty('class')) $card.fluxxCardDetail().addClass(data['class']); if (data.hasOwnProperty('width')) $card.fluxxCardDetail().width(data.width); $chart.html("").append('<div id="' + chartID + '"></div>'); $.jqplot.config.enablePlugins = true; if (data.type == 'bar') { if (!data.seriesDefaults) data.seriesDefaults = {}; data.seriesDefaults.renderer = $.jqplot.BarRenderer; } if (data.series) { $.each(data.series, function(i, s) { if (s.renderer) { s.renderer = eval(s.renderer); } }); } if (data.axes && data.axes.xaxis && data.axes.xaxis.ticks.length > 0 && !$.isArray(data.axes.xaxis.ticks[0])) data.axes.xaxis.renderer = $.jqplot.CategoryAxisRenderer; var error = false; try { plot = $.jqplot(chartID, data.data, { axesDefaults: { tickRenderer: $.jqplot.CanvasAxisTickRenderer , tickOptions: { fontSize: '10pt' } }, title: {show: false}, width: $chart.css('width'), stackSeries: data.stackSeries, // grid:{background:'#fefbf3', borderWidth:2.5}, grid:{background:'#ffffff', borderWidth:0, gridLineColor: '#ffffff', shadow: false}, seriesDefaults: data.seriesDefaults, axes: data.axes, series: data.series }); } catch(e) { // $.fluxx.log('error', e); $chart.html('<h4>No data available</h4>').height(50).css({"text-align": "center"}); error = true; } if (!error) { var legend = {}; $.each(plot.series, function(index, key) { legend[key.label] = key; }); var $table = $('.legend table.legend-table', $card); if ($table.hasClass('single-row-legend')) { $table.find('.category').each(function () { var $cat = $(this); var l = legend[$.trim($cat.text())]; if (l) $cat.prepend('<span class="legend-color-swatch" style="background-color: ' + l.color + '"/>'); }); } else { $table.find('tr').each(function() { var $td = $('td:first', $(this)); if ($td.length) { var l = legend[$.trim($td.text())]; if (l) $td.prepend('<span class="legend-color-swatch" style="background-color: ' + l.color + '"/>'); } }) .hover(function(e) { var $td = $('td:first', $(this)); if (legend[$.trim($td.text())]) legend[$.trim($td.text())].canvas._elem.css('opacity', '.5'); }, function(e) { var $td = $('td:first', $(this)); if (legend[$.trim($td.text())]) legend[$.trim($td.text())].canvas._elem.css('opacity', '1'); }); } } } }); } }); $.extend(true, { fluxx: { visualizations: { counter: 0 } } }); })(jQuery);
ritchiea/fluxx_engine
public/javascripts/src/fluxx.visualizations.js
JavaScript
agpl-3.0
3,923