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 |
|---|---|---|---|---|---|
/*
***** BEGIN LICENSE BLOCK *****
Copyright © 2009 Center for History and New Media
George Mason University, Fairfax, Virginia, USA
http://zotero.org
This file is part of Zotero.
Zotero 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.
Zotero 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 Zotero. If not, see <http://www.gnu.org/licenses/>.
***** END LICENSE BLOCK *****
*/
Zotero.Ingester = new function() {
this.importHandler = function(string, uri) {
var frontWindow = Components.classes["@mozilla.org/embedcomp/window-watcher;1"].
getService(Components.interfaces.nsIWindowWatcher).activeWindow;
if (Zotero.locked) {
frontWindow.Zotero_Browser.progress.changeHeadline(Zotero.getString("ingester.scrapeError"));
var desc = Zotero.localeJoin([
Zotero.getString('general.operationInProgress'), Zotero.getString('general.operationInProgress.waitUntilFinishedAndTryAgain')
]);
frontWindow.Zotero_Browser.progress.addDescription(desc);
frontWindow.Zotero_Browser.progress.show();
frontWindow.Zotero_Browser.progress.startCloseTimer(8000);
return;
}
// attempt to import through Zotero.Translate
var translation = new Zotero.Translate("import");
translation.setLocation(uri);
translation.setString(string);
frontWindow.Zotero_Browser.progress.show();
var libraryID = null;
var collection = null;
try {
libraryID = frontWindow.ZoteroPane.getSelectedLibraryID();
collection = frontWindow.ZoteroPane.getSelectedCollection();
} catch(e) {}
translation.setHandler("itemDone", function(obj, item) { frontWindow.Zotero_Browser.itemDone(obj, item, collection) });
translation.setHandler("done", function(obj, item) { frontWindow.Zotero_Browser.finishScraping(obj, item, collection) });
// attempt to retrieve translators
var translators = translation.getTranslators();
if(!translators.length) {
// we lied. we can't really translate this file.
frontWindow.Zotero_Browser.progress.close();
throw "No translator found for handled RIS or Refer file"
}
// translate using first available
translation.setTranslator(translators[0]);
translation.translate(libraryID);
}
}
Zotero.OpenURL = new function() {
this.resolve = resolve;
this.discoverResolvers = discoverResolvers;
this.createContextObject = createContextObject;
this.parseContextObject = parseContextObject;
/*
* Returns a URL to look up an item in the OpenURL resolver
*/
function resolve(itemObject) {
var co = createContextObject(itemObject, Zotero.Prefs.get("openURL.version"));
if(co) {
var base = Zotero.Prefs.get("openURL.resolver");
// Add & if there's already a ?
var splice = base.indexOf("?") == -1 ? "?" : "&";
return base + splice + co;
}
return false;
}
/*
* Queries OCLC's OpenURL resolver registry and returns an address and version
*/
function discoverResolvers() {
var req = Components.classes["@mozilla.org/xmlextras/xmlhttprequest;1"].createInstance();
req.open("GET", "http://worldcatlibraries.org/registry/lookup?IP=requestor", false);
req.send(null);
if(!req.responseXML) {
throw "Could not access resolver registry";
}
var resolverArray = new Array();
var resolvers = req.responseXML.getElementsByTagName("resolver");
for(var i=0; i<resolvers.length; i++) {
var resolver = resolvers[i];
var name = resolver.parentNode.getElementsByTagName("institutionName");
if(!name.length) {
continue;
}
name = name[0].textContent;
var url = resolver.getElementsByTagName("baseURL");
if(!url.length) {
continue;
}
url = url[0].textContent;
if(resolver.getElementsByTagName("Z39.88-2004").length > 0) {
var version = "1.0";
} else if(resolver.getElementsByTagName("OpenUrl 0.1").length > 0) {
var version = "0.1";
} else {
continue;
}
resolverArray.push({name:name, url:url, version:version});
}
return resolverArray;
}
/*
* Generates an OpenURL ContextObject from an item
*/
function createContextObject(item, version) {
if(item.toArray) {
item = item.toArray();
}
var identifiers = new Array();
if(item.DOI) {
identifiers.push("info:doi/"+item.DOI);
}
if(item.ISBN) {
identifiers.push("urn:isbn:"+item.ISBN);
}
// encode ctx_ver (if available) and identifiers
// TODO identifiers may need to be encoded as follows:
// rft_id=info:doi/<the-url-encoded-doi>
// rft_id=http://<the-rest-of-the-url-encoded-url>
if(version == "0.1") {
var co = "";
for each(identifier in identifiers) {
co += "&id="+escape(identifier);
}
} else {
var co = "url_ver=Z39.88-2004&ctx_ver=Z39.88-2004";
for each(identifier in identifiers) {
co += "&rft_id="+escape(identifier);
}
}
// encode genre and item-specific data
if(item.itemType == "journalArticle") {
if(version == "0.1") {
co += "&genre=article";
} else {
co += "&rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Ajournal&rft.genre=article";
}
if(item.title) co += _mapTag(item.title, "atitle", version)
if(item.publicationTitle) co += _mapTag(item.publicationTitle, (version == "0.1" ? "title" : "jtitle"), version)
if(item.journalAbbreviation) co += _mapTag(item.journalAbbreviation, "stitle", version);
if(item.volume) co += _mapTag(item.volume, "volume", version);
if(item.issue) co += _mapTag(item.issue, "issue", version);
} else if(item.itemType == "book" || item.itemType == "bookSection") {
if(version == "0.1") {
co += "&genre=book";
} else {
co += "&rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Abook";
}
if(item.itemType == "book") {
co += "&rft.genre=book";
if(item.title) co += _mapTag(item.title, (version == "0.1" ? "title" : "btitle"), version);
} else {
co += "&rft.genre=bookitem";
if(item.title) co += _mapTag(item.title, "atitle", version)
if(item.publicationTitle) co += _mapTag(item.publicationTitle, (version == "0.1" ? "title" : "btitle"), version);
}
if(item.place) co += _mapTag(item.place, "place", version);
if(item.publisher) co += _mapTag(item.publisher, "publisher", version)
if(item.edition) co += _mapTag(item.edition, "edition", version);
if(item.series) co += _mapTag(item.series, "series", version);
} else if(item.itemType == "thesis" && version == "1.0") {
co += "&rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Adissertation";
if(item.title) co += _mapTag(item.title, "title", version);
if(item.publisher) co += _mapTag(item.publisher, "inst", version);
if(item.type) co += _mapTag(item.type, "degree", version);
} else if(item.itemType == "patent" && version == "1.0") {
co += "&rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Apatent";
if(item.title) co += _mapTag(item.title, "title", version);
if(item.assignee) co += _mapTag(item.assignee, "assignee", version);
if(item.patentNumber) co += _mapTag(item.patentNumber, "number", version);
if(item.issueDate) {
co += _mapTag(Zotero.Date.strToISO(item.issueDate), "date", version);
}
} else {
return false;
}
if(item.creators && item.creators.length) {
// encode first author as first and last
var firstCreator = item.creators[0];
if(item.itemType == "patent") {
co += _mapTag(firstCreator.firstName, "invfirst", version);
co += _mapTag(firstCreator.lastName, "invlast", version);
} else {
if(firstCreator.isInstitution) {
co += _mapTag(firstCreator.lastName, "aucorp", version);
} else {
co += _mapTag(firstCreator.firstName, "aufirst", version);
co += _mapTag(firstCreator.lastName, "aulast", version);
}
}
// encode subsequent creators as au
for each(creator in item.creators) {
co += _mapTag((creator.firstName ? creator.firstName+" " : "")+creator.lastName, (item.itemType == "patent" ? "inventor" : "au"), version);
}
}
if(item.date) {
co += _mapTag(Zotero.Date.strToISO(item.date), (item.itemType == "patent" ? "appldate" : "date"), version);
}
if(item.pages) co += _mapTag(item.pages, "pages", version);
if(item.ISBN) co += _mapTag(item.ISBN, "isbn", version);
if(item.ISSN) co += _mapTag(item.ISSN, "issn", version);
if(version == "0.1") {
// chop off leading & sign if version is 0.1
co = co.substr(1);
}
return co;
}
/*
* Generates an item in the format returned by item.fromArray() given an
* OpenURL version 1.0 contextObject
*
* accepts an item array to fill, or creates and returns a new item array
*/
function parseContextObject(co, item) {
if(!item) {
var item = new Array();
item.creators = new Array();
}
var coParts = co.split("&");
// get type
for each(var part in coParts) {
if(part.substr(0, 12) == "rft_val_fmt=") {
var format = decodeURIComponent(part.substr(12));
if(format == "info:ofi/fmt:kev:mtx:journal") {
item.itemType = "journalArticle";
break;
} else if(format == "info:ofi/fmt:kev:mtx:book") {
if(Zotero.inArray("rft.genre=bookitem", coParts)) {
item.itemType = "bookSection";
} else if(Zotero.inArray("rft.genre=conference", coParts) || Zotero.inArray("rft.genre=proceeding", coParts)) {
item.itemType = "conferencePaper";
} else if(Zotero.inArray("rft.genre=report", coParts)) {
item.itemType = "report";
} else {
item.itemType = "book";
}
break;
} else if(format == "info:ofi/fmt:kev:mtx:dissertation") {
item.itemType = "thesis";
break;
} else if(format == "info:ofi/fmt:kev:mtx:patent") {
item.itemType = "patent";
break;
} else if(format == "info:ofi/fmt:kev:mtx:dc") {
item.itemType = "webpage";
break;
}
}
}
if(!item.itemType) {
return false;
}
var pagesKey = "";
// keep track of "aucorp," "aufirst," "aulast"
var complexAu = new Array();
for each(var part in coParts) {
var keyVal = part.split("=");
var key = keyVal[0];
var value = decodeURIComponent(keyVal[1].replace(/\+|%2[bB]/g, " "));
if(!value) {
continue;
}
if(key == "rft_id") {
var firstEight = value.substr(0, 8).toLowerCase();
if(firstEight == "info:doi") {
item.DOI = value.substr(9);
} else if(firstEight == "urn:isbn") {
item.ISBN = value.substr(9);
} else if(value.match(/^https?:\/\//)) {
item.url = value;
item.accessDate = "";
}
} else if(key == "rft.btitle") {
if(item.itemType == "book" || item.itemType == "conferencePaper" || item.itemType == "report") {
item.title = value;
} else if(item.itemType == "bookSection") {
item.publicationTitle = value;
}
} else if(key == "rft.atitle" && (item.itemType == "journalArticle" ||
item.itemType == "bookSection")) {
item.title = value;
} else if(key == "rft.jtitle" && item.itemType == "journalArticle") {
item.publicationTitle = value;
} else if(key == "rft.stitle" && item.itemType == "journalArticle") {
item.journalAbbreviation = value;
} else if(key == "rft.title") {
if(item.itemType == "journalArticle" || item.itemType == "bookSection") {
item.publicationTitle = value;
} else {
item.title = value;
}
} else if(key == "rft.date") {
if(item.itemType == "patent") {
item.issueDate = value;
} else {
item.date = value;
}
} else if(key == "rft.volume") {
item.volume = value;
} else if(key == "rft.issue") {
item.issue = value;
} else if(key == "rft.pages") {
pagesKey = key;
item.pages = value;
} else if(key == "rft.spage") {
if(pagesKey != "rft.pages") {
// make pages look like start-end
if(pagesKey == "rft.epage") {
if(value != item.pages) {
item.pages = value+"-"+item.pages;
}
} else {
item.pages = value;
}
pagesKey = key;
}
} else if(key == "rft.epage") {
if(pagesKey != "rft.pages") {
// make pages look like start-end
if(pagesKey == "rft.spage") {
if(value != item.pages) {
item.pages = item.pages+"-"+value;
}
} else {
item.pages = value;
}
pagesKey = key;
}
} else if(key == "rft.issn" || (key == "rft.eissn" && !item.ISSN)) {
item.ISSN = value;
} else if(key == "rft.aulast" || key == "rft.invlast") {
var lastCreator = complexAu[complexAu.length-1];
if(complexAu.length && !lastCreator.lastName && !lastCreator.institutional) {
lastCreator.lastName = value;
} else {
complexAu.push({lastName:value, creatorType:(key == "rft.aulast" ? "author" : "inventor")});
}
} else if(key == "rft.aufirst" || key == "rft.invfirst") {
var lastCreator = complexAu[complexAu.length-1];
if(complexAu.length && !lastCreator.firstName && !lastCreator.institutional) {
lastCreator.firstName = value;
} else {
complexAu.push({firstName:value, creatorType:(key == "rft.aufirst" ? "author" : "inventor")});
}
} else if(key == "rft.au" || key == "rft.creator" || key == "rft.contributor" || key == "rft.inventor") {
if(key == "rft.contributor") {
var type = "contributor";
} else if(key == "rft.inventor") {
var type = "inventor";
} else {
var type = "author";
}
if(value.indexOf(",") !== -1) {
item.creators.push(Zotero.Utilities.prototype.cleanAuthor(value, type, true));
} else {
item.creators.push(Zotero.Utilities.prototype.cleanAuthor(value, type, false));
}
} else if(key == "rft.aucorp") {
complexAu.push({lastName:value, isInstitution:true});
} else if(key == "rft.isbn" && !item.ISBN) {
item.ISBN = value;
} else if(key == "rft.pub" || key == "rft.publisher") {
item.publisher = value;
} else if(key == "rft.place") {
item.place = value;
} else if(key == "rft.edition") {
item.edition = value;
} else if(key == "rft.series") {
item.series = value;
} else if(item.itemType == "thesis") {
if(key == "rft.inst") {
item.publisher = value;
} else if(key == "rft.degree") {
item.type = value;
}
} else if(item.itemType == "patent") {
if(key == "rft.assignee") {
item.assignee = value;
} else if(key == "rft.number") {
item.patentNumber = value;
} else if(key == "rft.appldate") {
item.date = value;
}
} else if(format == "info:ofi/fmt:kev:mtx:dc") {
if(key == "rft.identifier") {
if(value.length > 8) { // we could check length separately for
// each type, but all of these identifiers
// must be > 8 characters
if(value.substr(0, 5) == "ISBN ") {
item.ISBN = value.substr(5);
} else if(value.substr(0, 5) == "ISSN ") {
item.ISSN = value.substr(5);
} else if(value.substr(0, 8) == "urn:doi:") {
item.DOI = value.substr(4);
} else if(value.substr(0, 7) == "http://" || value.substr(0, 8) == "https://") {
item.url = value;
}
}
} else if(key == "rft.description") {
item.abstractNote = value;
} else if(key == "rft.rights") {
item.rights = value;
} else if(key == "rft.language") {
item.language = value;
} else if(key == "rft.subject") {
item.tags.push(value);
} else if(key == "rft.type") {
if(Zotero.ItemTypes.getID(value)) item.itemType = value;
} else if(key == "rft.source") {
item.publicationTitle = value;
}
}
}
// combine two lists of authors, eliminating duplicates
for each(var au in complexAu) {
var pushMe = true;
for each(var pAu in item.creators) {
// if there's a plain author that is close to this author (the
// same last name, and the same first name up to a point), keep
// the plain author, since it might have a middle initial
if(pAu.lastName == au.lastName &&
(pAu.firstName == au.firstName == "" ||
(pAu.firstName.length >= au.firstName.length &&
pAu.firstName.substr(0, au.firstName.length) == au.firstName))) {
pushMe = false;
break;
}
}
if(pushMe) item.creators.push(au);
}
return item;
}
/*
* Used to map tags for generating OpenURL contextObjects
*/
function _mapTag(data, tag, version) {
if(data) {
if(version == "0.1") {
return "&"+tag+"="+encodeURIComponent(data);
} else {
return "&rft."+tag+"="+encodeURIComponent(data);
}
} else {
return "";
}
}
} | nikolasco/zotero-oac | chrome/content/zotero/xpcom/ingester.js | JavaScript | gpl-3.0 | 16,919 |
wash.post_processor = {};
| chrisallenlane/wash | lib/js/wash.post-processor.js | JavaScript | gpl-3.0 | 26 |
'use strict'
const Key = require('interface-datastore').Key
const debug = require('debug')
const log = debug('repo:version')
const versionKey = new Key('version')
module.exports = (store) => {
return {
/**
* Check if a version file exists.
*
* @param {function(Error, bool)} callback
* @returns {void}
*/
exists (callback) {
store.has(versionKey, callback)
},
/**
* Get the current version.
*
* @param {function(Error, number)} callback
* @returns {void}
*/
get (callback) {
store.get(versionKey, (err, buf) => {
if (err) {
return callback(err)
}
callback(null, parseInt(buf.toString().trim(), 10))
})
},
/**
* Set the version of the repo, writing it to the underlying store.
*
* @param {number} version
* @param {function(Error)} callback
* @returns {void}
*/
set (version, callback) {
store.put(versionKey, new Buffer(String(version)), callback)
},
/**
* Check the current version, and return an error on missmatch
* @param {number} expected
* @param {function(Error)} callback
* @returns {void}
*/
check (expected, callback) {
this.get((err, version) => {
if (err) {
return callback(err)
}
log('comparing version: %s and %s', version, expected)
if (version !== expected) {
return callback(new Error(`version mismatch: expected v${expected}, found v${version}`))
}
callback()
})
}
}
}
| js0p/sprouts | node_modules/ipfs-repo/src/version.js | JavaScript | gpl-3.0 | 1,585 |
/*
* Abricotine - Markdown Editor
* Copyright (c) 2015 Thomas Brouard
* Licensed under GNU-GPLv3 <http://www.gnu.org/licenses/gpl.html>
*/
var constants = require.main.require("./constants"),
files = require.main.require("./files"),
fs = require("fs"),
langmap = require("langmap"),
Menu = require("electron").Menu,
pathModule = require("path"),
spellchecker = require('spellchecker'),
sysDictionaries = spellchecker.getAvailableDictionaries();
function getConfig (config, key) {
if (config && typeof config.get === "function") {
return config.get(key) || false;
}
return false;
}
function preprocessTemplate (abrApp, element, config, abrWin) {
if (element.constructor !== Array) {
return;
}
var sendCommand = abrApp.execCommand.bind(abrApp),
replaceAttributes = function (item) {
if (item.condition) {
delete item.condition;
}
if (item.labelKey) {
var newLabel = abrApp.localizer.get(item.labelKey);
if (newLabel !== null) {
item.label = abrApp.localizer.get(item.labelKey);
}
delete item.labelKey;
}
if (item.command) {
item.click = (function (command, parameters) {
return function () { sendCommand(command, parameters); };
})(item.command, item.parameters);
item.id = item.command;
delete item.command;
delete item.parameters;
}
if (item.type === "checkbox" && typeof item.checked === "string") {
item.checked = getConfig(config, item.checked);
}
if (!item.permanent && !abrWin) {
item.enabled = false;
delete item.permanent;
}
if (item.submenu) {
if (item.id === "spelling") {
item.submenu = spellingMenuGenerator(item.submenu, config);
}
if (item.id === "tasks") {
item.submenu = tasksMenuGenerator(item.submenu, config);
}
if (item.id === "exportHtml") {
item.submenu = assetsMenuGenerator(item.submenu, constants.path.templatesDir, "template.json", "exportHtml");
}
if (item.id === "themes") {
var checkId = getConfig(config, "theme");
item.submenu = assetsMenuGenerator(item.submenu, constants.path.themesDir, "theme.json", "loadTheme", "radio", checkId);
}
preprocessTemplate(abrApp, item.submenu, config, abrWin);
}
return item;
};
// Process menuItem
for (var i=0; i<element.length; i++) {
var el = element[i],
hiddenWithThisConfig = el.condition && !getConfig(config, el.condition),
hiddenWithThisPlatform = el.platform && el.platform.indexOf(process.platform) === -1;
if (hiddenWithThisConfig || hiddenWithThisPlatform) {
// Remove elements that should not be displayed (config --debug or platform-specific menuItems)
element.splice(i, 1);
i--;
} else {
// Process attributes
replaceAttributes(el);
}
}
return element;
}
// Generate spelling menu template (before preprocesssing)
function spellingMenuGenerator (submenu, config) {
// Get language name for its code
function getLangName (code) {
code = code.replace("_", "-");
return typeof langmap[code] !== "undefined" ? langmap[code].nativeName : null;
}
// Get a language menuItem
function getLangMenu (lang, path, config) {
var label = getLangName(lang);
if (!label) return null;
var isConfigLang = getConfig(config, "spellchecker:active") && getConfig(config, "spellchecker:language") === lang;
radioChecked = radioChecked || isConfigLang;
return {
label: label,
type: "radio",
checked: isConfigLang,
command: "setDictionary",
parameters: path ? [lang, path] : [lang]
};
}
// Get hunspell dictionaries path
// Search the dict dir in abricotine config folder
// Returns an object { "en_US": "path/to/en_US", etc. }
function getHunspellDictionaries () {
var dicts = {},
paths = [
constants.path.dictionaries
],
subdirs;
for (var i=0; i<paths.length; i++) {
subdirs = files.getDirectories(paths[i]);
for (var j=0; j<subdirs.length; j++) {
dicts[subdirs[j]] = pathModule.join(paths[i], subdirs[j]);
}
}
return dicts;
}
var radioChecked = false,
langMenu;
if (sysDictionaries.length !== 0) {
// System builtin dictionaries
for (var i=0; i<sysDictionaries.length; i++) {
langMenu = getLangMenu(sysDictionaries[i], null, config);
if (langMenu) submenu.push(langMenu);
}
} else {
// Hunspell dictionaries
var hunspellDictionaries = getHunspellDictionaries();
if (hunspellDictionaries.length !== 0) {
for (var lang in hunspellDictionaries) {
langMenu = getLangMenu(lang, hunspellDictionaries[lang], config);
if (langMenu) submenu.push(langMenu);
if (getConfig(config, "spellchecker:language") === lang) {
config.set("spellchecker:src", hunspellDictionaries[lang]); // This src config key is used for init the spellchecker in abrDoc (renderer)
}
}
}
}
// Check the "Disabled" menu if no radio has been checked
submenu[0].checked = !radioChecked;
return submenu;
}
// Generate tasks menu template (before preprocesssing)
function tasksMenuGenerator (submenu, config) {
var tasks = getConfig(config, "tasks") || [];
var submenu = tasks.reduce(function (res, task) {
if (task.name && task.exec) {
res.push({
label: task.name,
command: "runTask",
parameters: task.exec
});
}
return res;
}, []);
return submenu;
}
// Generate menu template (before preprocesssing)
function assetsMenuGenerator (submenu, dirPath, jsonName, command, menuType, checkId) {
// Get a menu item
function getTemplateMenu (id) {
var itemPath = pathModule.join(dirPath, id),
itemInfos = (function (itemPath) {
var jsonPath = pathModule.join(itemPath, "/", jsonName);
try {
var str = fs.readFileSync(jsonPath, "utf-8"); // TODO: async
return JSON.parse(str);
} catch (err) {
return {};
}
})(itemPath);
var menuItem = {
label: itemInfos.label || itemInfos.name || id,
command: command,
accelerator: itemInfos.accelerator,
parameters: id
};
if (menuType === "checkbox" || menuType === "radio") {
menuItem.type = menuType;
menuItem.checked = (checkId && checkId === id);
}
return menuItem;
}
// Walk in dir and find items
var subdirs = files.getDirectories(dirPath);
for (var i in subdirs) {
submenu.push(getTemplateMenu(subdirs[i]));
}
return submenu;
}
// Electron's menu wrapper
function AbrMenu (abrApp, abrWin, menuTemplate, config) {
this.abrWin = abrWin;
var cloneTemplate = JSON.parse(JSON.stringify(menuTemplate)); // Electron modifies the template while building the menu so we need to clone it before
var preprocessedMenuTemplate = preprocessTemplate(abrApp, cloneTemplate, config, abrWin);
this.menu = Menu.buildFromTemplate(preprocessedMenuTemplate);
}
AbrMenu.prototype = {
findItem: function (id) {
function doFindItem (menu, id) {
var items = menu.items,
menuItem;
for (var i=0; i <items.length; i++) {
if (items[i].submenu) {
menuItem = doFindItem(items[i].submenu, id);
} else {
menuItem = items[i].id === id ? items[i] : undefined;
}
if (menuItem) {
return menuItem;
}
}
}
return doFindItem(this, id);
},
popup: function () {
var win = this.abrWin.browserWindow;
this.menu.popup(win);
},
attach: function () {
// FIXME: use win.setMenu(menu) for Linux and Windows instead
Menu.setApplicationMenu(this.menu);
}
};
module.exports = AbrMenu;
| brrd/Abricotine | app/abr-menu.js | JavaScript | gpl-3.0 | 8,904 |
angular.module('MyApp').service('PostMessageService', function(Account,$state) {
this.init = function(portname) {
if(arguments.length > 0) {
this.port = chrome.runtime.connect({name: portname});
}
};
this.sendGesture = function(gestureName, opt) {
this.port.postMessage({
"gesture": gestureName,
"options": opt
});
};
var self = this;
this.gesture = {
showIframe: function(option) {
self.sendGesture("showIframe", option);
},
hideIframe: function(option) {
self.sendGesture("hideIframe",option);
},
showAlert: function(message, type) {
if (!type) type = 'warning';
self.sendGesture("showAlert", {message: message, type: type});
},windowRefresh: function(option) {
self.sendGesture("windowRefresh", option);
},setChannelId: function(channelId) {
self.sendGesture("setChannelId", channelId);
}
};
this.getProfile = function() {
Account.getProfile().success(function(data) {
orgExists = data.orgexists;
if (orgExists == 'false') {
$state.go('createOrg', {}, {reload: true});
}else{
self.gesture.windowRefresh();
}
}).error(function(error) {
console.log('getProfile: ' + error.message);
});
};
this.navigateToCreateOrg = function() {
userData = Account.getUserData();
if(userData == undefined){
this.getProfile();
}else{
if (userData.orgexists == 'false') {
$state.go('createOrg', {}, {reload: true});
}else{
self.gesture.windowRefresh();
}
}
}
});
| Backfeed/Backfeed-Slack-Client | extension/contentScript/app/js/contentServices/postMessageService.js | JavaScript | gpl-3.0 | 1,539 |
PAYPAL.namespace("widget");
if (typeof YUD == "undefined" || typeof YUE == "undefined") {
YUD = YAHOO.util.Dom;
YUE = YAHOO.util.Event;
}
PAYPAL.widget.hideShow = {
exclusiveMode: false,
mouseOverMode: false,
containers: '',
links: new Array(),
cancelButtons: new Array(),
init: function() {
this.containers = YUD.getElementsByClassName("hideShow");
for (var i = 0; i < this.containers.length; i++) {
if (!(YUD.hasClass(this.containers[i], "opened"))) {
YUD.addClass(this.containers[i], "hide");
}
var reg = new RegExp("#" + this.containers[i].id);
checkHrefs = function(el) {
return (el.getAttribute("href").match(reg));
}
this.links = YUD.getElementsBy(checkHrefs, "a");
this.cancelButtons = YUD.getElementsByClassName("closer", "*", this.containers[i]);
this.containers[i].hideShowLinks = this.links;
this.containers[i].cancelButtons = this.cancelButtons;
for (var j = 0; j < this.links.length; j++) {
this.links[j].hideShowContainer = this.containers[i];
if (!(YUD.hasClass(this.containers[i], "opened")) && YUD.hasClass(this.links[j], "opened")) {
this.links[j].wasOpened = true;
YUD.removeClass(this.links[j], "opened");
}
if (this.mouseOverMode) {
YUE.addListener(this.links[j], 'mouseover', PAYPAL.widget.hideShow.toggleHideShow);
} else {
YUE.addListener(this.links[j], 'click', PAYPAL.widget.hideShow.toggleHideShow);
}
}
if (this.cancelButtons.length > 0) {
for (var k = 0; k < this.cancelButtons.length; k++) {
this.cancelButtons[k].hideShowContainer = this.containers[i];
YUE.addListener(this.cancelButtons[k], 'click', PAYPAL.widget.hideShow.toggleHideShow);
}
}
}
},
hide: function(obj) {
YUD.addClass(obj, "hide");
YUD.removeClass(obj, "opened");
if (obj && obj.hideShowLinks) {
for (var i = 0; i < obj.hideShowLinks.length; i++) {
if (YUD.hasClass(obj.hideShowLinks[i], "opened")) {
YUD.removeClass(obj.hideShowLinks[i], "opened");
obj.hideShowLinks[i].wasOpened = true;
}
}
}
},
show: function(obj) {
if (this.exclusiveMode) {
for (var i = 0; i < this.containers.length; i++) {
this.hide(this.containers[i]);
}
}
YUD.removeClass(obj, "accessAid");
YUD.removeClass(obj, "hide");
YUD.addClass(obj, "opened")
if (obj && obj.hideShowLinks) {
for (var i = 0; i < obj.hideShowLinks.length; i++) {
if (obj.hideShowLinks[i].wasOpened) {
YUD.addClass(obj.hideShowLinks[i], "opened");
obj.hideShowLinks[i].wasOpened = false;
}
}
}
var buttons = YUD.getElementsBy(function(elem) {
return (elem.wasSubmit)
}, "*", obj);
for (var i = 0; i < buttons.length; i++) {
buttons[i].disabled = false;
buttons[i].wasSubmit = false;
}
},
toggleHideShow: function(e) {
YUE.preventDefault(e);
var anchor = this;
var div = anchor.hideShowContainer;
var ignoreClick = false;
if (PAYPAL.widget.hideShow.mouseOverMode) {
for (var i = 0; i < div.cancelButtons.length; i++) {
if (div.cancelButtons[i] === anchor) {
ignoreClick = true;
}
}
} else {
ignoreClick = false;
}
if (YUD.hasClass(div, "opened") && PAYPAL.widget.hideShow.mouseOverMode && !ignoreClick) {} else if (YUD.hasClass(div, "opened")) {
PAYPAL.widget.hideShow.hide(div);
} else {
PAYPAL.widget.hideShow.show(div);
}
}
}
YUE.onDOMReady(PAYPAL.widget.hideShow.init);
var onAccordionComplete = new YAHOO.util.CustomEvent('onAccordionComplete');
PAYPAL.widget.Accordion = {
toggleReady: null,
allowMultiple: false,
animate: true,
animDelayShow: 0.9,
animDelayHide: 0.8,
firstRun: true,
init: function() {
var header, body, i, autoShow;
var accordions = YUD.getElementsByClassName('accordion');
if (!accordions) {
return;
}
YUD.addClass(accordions, 'dynamic');
for (i = 0; i < accordions.length; i++) {
boxes = YUD.getElementsByClassName('box', '', accordions[i]);
for (i = 0; i < boxes.length; i++) {
header = YUD.getElementsByClassName('header', 'div', boxes[i])[0];
body = YUD.getElementsByClassName('body', 'div', boxes[i])[0];
body.defaultHeight = body.offsetHeight;
YUD.setStyle(body, 'width', body.offsetWidth);
header.content = body;
if (YUD.hasClass(boxes[i], 'defaultOpen')) {
autoShow = header.content;
}
YUE.addListener(header, 'mousedown', PAYPAL.widget.Accordion.toggle);
YUE.addListener(header, 'mouseover', function(e) {
YUD.addClass(this, 'hover');
});
YUE.addListener(header, 'mouseout', function(e) {
YUD.removeClass(this, 'hover');
});
}
if (autoShow) {
PAYPAL.widget.Accordion.show(autoShow);
}
}
},
toggle: function(body) {
if (this.content) body = this.content;
var accordion = PAYPAL.widget.Accordion;
accordion.toggleReady = (accordion.toggleReady === null) ? true : accordion.toggleReady;
if (YUD.hasClass(body.parentNode, 'open') && accordion.toggleReady) {
body.defaultHeight = body.offsetHeight;
accordion.toggleReady = false;
accordion.hide(body);
} else if (accordion.toggleReady) {
accordion.toggleReady = false;
accordion.show(body);
}
},
toggleCustom: function() {
var body = this.getEl();
var box = body.parentNode;
box.open = box.open ? false : true;
if (!box.open) {
YUD.removeClass(box, 'open');
} else {
YUD.setStyle(body, 'height', 'auto');
}
PAYPAL.widget.Accordion.toggleReady = true;
if (!PAYPAL.widget.Accordion.firstRun) {
onAccordionComplete.fire(true);
} else {
PAYPAL.widget.Accordion.firstRun = false;
}
var browsername = navigator.appName.toLowerCase();
if (browsername == "microsoft internet explorer") {
body.style.filter = "";
}
},
show: function(body) {
if (!PAYPAL.widget.Accordion.allowMultiple) {
PAYPAL.widget.Accordion.hideAll();
}
YUD.addClass(body.parentNode, 'open');
if (PAYPAL.widget.Accordion.animate) {
var attributes = {
height: {
from: 0,
to: body.defaultHeight
},
opacity: {
from: 0,
to: 1
}
};
var anim = new YAHOO.util.Anim(body, attributes, PAYPAL.widget.Accordion.animDelayShow, YAHOO.util.Easing.backOut);
anim.animate();
anim.onComplete.subscribe(PAYPAL.widget.Accordion.toggleCustom);
} else {
var box = body.parentNode;
box.open = box.open ? false : true;
if (!box.open) {
YUD.removeClass(box, 'open');
} else {
YUD.setStyle(body, 'height', 'auto');
}
PAYPAL.widget.Accordion.toggleReady = true;
if (!PAYPAL.widget.Accordion.firstRun) {
onAccordionComplete.fire(true);
} else {
PAYPAL.widget.Accordion.firstRun = false;
}
}
},
hide: function(body) {
if (PAYPAL.widget.Accordion.animate) {
var attributes = {
height: {
from: body.defaultHeight,
to: 0
},
opacity: {
from: 1,
to: 0
}
};
var anim = new YAHOO.util.Anim(body, attributes, PAYPAL.widget.Accordion.animDelayHide, YAHOO.util.Easing.easeBoth);
anim.animate();
anim.onComplete.subscribe(PAYPAL.widget.Accordion.toggleCustom);
} else {
var box = body.parentNode;
box.open = box.open ? false : true;
if (!box.open) {
YUD.removeClass(box, 'open');
} else {
YUD.setStyle(body, 'height', 'auto');
}
PAYPAL.widget.Accordion.toggleReady = true;
if (!PAYPAL.widget.Accordion.firstRun) {
onAccordionComplete.fire(true);
} else {
PAYPAL.widget.Accordion.firstRun = false;
}
}
},
hideAll: function() {
var boxes = YUD.getElementsByClassName('box');
for (i = 0; i < boxes.length; i++) {
if (YUD.hasClass(boxes[i], 'open')) {
var body = boxes[i].getElementsByTagName('div')[1];
PAYPAL.widget.Accordion.hide(body);
}
}
},
toggleAccordion: function(nodeClass) {
var box = YUD.getElementsByClassName(nodeClass);
if (box[0]) {
var body = box[0].getElementsByTagName('div')[0];
PAYPAL.widget.Accordion.toggle(body);
}
},
reedIsOpen: function(nodeClass) {
var node = YUD.getElementsByClassName(nodeClass);
if (node[0]) {
return (YUD.hasClass(node[0], 'open')) ? true : false;
} else {
return false;
}
}
};
PAYPAL.namespace("Merchant.ButtonDesigner");
onPricePerOption = new YAHOO.util.CustomEvent('onPricePerOption');
onDropdownPriceChange = new YAHOO.util.CustomEvent('onDropdownPriceChange');
onItemDetailsChange = new YAHOO.util.CustomEvent('onItemDetailsChange');
YUD = YAHOO.util.Dom;
YUE = YAHOO.util.Event;
PPW = PAYPAL.widget;
wHideShow = PAYPAL.widget.hideShow;
PAYPAL.Merchant.ButtonDesigner.Master = {
timeOut: 13,
sessionLightbox: null,
init: function() {
PPW.Accordion.init();
var header = document.getElementById("headline");
if (header) {
header = header.getElementsByTagName("h2");
YUD.removeClass(header, 'accessAid');
}
var content = document.getElementById("jsContent");
YUD.removeClass(content, 'accessAid');
var links = YUD.getElementsByClassName('submitPage', '', content);
var linksLen = links.length;
for (var i = 0; i < linksLen; i++) {
YUE.on(links[i], 'click', BD_MASTER.submitLink);
}
BD_STEP1.init();
BD_CBUTTON.init();
setTimeout("BD_MASTER.showTimeout()", (BD_MASTER.timeOut * 60 * 1000));
YUE.on("timeoutSubmit", 'click', BD_MASTER.submitTimeout);
YUE.on("timeoutCancel", 'click', BD_MASTER.submitTimeout);
if (document.getElementById('pageLoadMsg')) {
YUD.addClass('pageLoadMsg', 'accessAid');
}
},
showTimeout: function() {
BD_MASTER.sessionLightbox = new PAYPAL.util.Lightbox("timeoutLightbox");
BD_MASTER.sessionLightbox.show();
},
submitTimeout: function(e) {
YUE.preventDefault(e);
var form = document.getElementById("buttonDesignerForm");
if (!form) {
form = document.getElementById("secondaryButtonsForm");
}
var fakeSubmit = document.getElementById("fakeSubmit");
if (this.getAttribute('name') == "timeout_session") {
fakeSubmit.setAttribute('value', "timeout_session");
fakeSubmit.setAttribute('name', "timeout_session");
} else {
fakeSubmit.setAttribute('value', "cancel_timeout_session");
fakeSubmit.setAttribute('name', "cancel_timeout_session");
}
form.submit();
BD_MASTER.sessionLightbox.close();
},
fadeOut: function(obj) {
function fade(ele) {
if (!YUD.hasClass(ele, "fadedOut")) {
YUD.addClass(ele, "fadedOut");
}
var tags = ele.getElementsByTagName("input");
if (tags.length > 0) {
disableFields(tags);
}
tags = ele.getElementsByTagName("textarea");
if (tags.length > 0) {
disableFields(tags);
}
tags = ele.getElementsByTagName("select");
if (tags.length > 0) {
disableFields(tags);
}
tags = ele.getElementsByTagName("button");
if (tags.length > 0) {
disableFields(tags);
}
function disableFields(inputs) {
var inputsLen = inputs.length;
for (j = 0; j < inputsLen; j++) {
inputs[j].disabled = true;
}
}
ele.faded = true;
}
if (obj && obj !== 'undefined') {
if (obj instanceof Array) {
var objLen = obj.length;
for (var i = 0; i < objLen; i++) {
fade(obj[i]);
}
} else {
fade(obj);
}
}
},
fadeIn: function(obj) {
function unFade(ele) {
if (arguments.length > 1) {
var reEnableFields = arguments[1];
} else {
var reEnableFields = true;
}
if (YUD.hasClass(ele, "fadedOut")) {
YUD.removeClass(ele, "fadedOut");
}
if (reEnableFields) {
var tags = ele.getElementsByTagName("input");
if (tags.length > 0) {
enableFields(tags);
}
tags = ele.getElementsByTagName("textarea");
if (tags.length > 0) {
enableFields(tags);
}
tags = ele.getElementsByTagName("select");
if (tags.length > 0) {
enableFields(tags);
}
tags = ele.getElementsByTagName("button");
if (tags.length > 0) {
enableFields(tags);
}
}
function enableFields(inputs) {
var inputsLen = inputs.length;
for (var j = 0; j < inputsLen; j++) {
inputs[j].disabled = false;
}
}
ele.faded = false;
}
if (obj && obj !== 'undefined') {
if (arguments.length > 1) {
var reEnableFields = arguments[1];
} else {
var reEnableFields = true;
}
if (obj instanceof Array) {
var objLen = obj.length;
for (var i = 0; i < objLen; i++) {
unFade(obj[i]);
}
} else {
unFade(obj, reEnableFields);
}
}
},
disableLink: function(ele) {
ele.onclick = function(e) {
YUE.preventDefault(e);
}
},
enableLink: function(ele) {
ele.onclick = null;
},
toggleFade: function(ele) {
try {
if ((ele.faded && ele.faded == true) || YUD.hasClass(ele, "fadedOut")) {
BD_MASTER.fadeIn(ele);
} else {
BD_MASTER.fadeOut(ele);
}
} catch (e) {}
},
submitLink: function(e) {
YUE.preventDefault(e);
var form = document.getElementById('buttonDesignerForm');
var fakeField = document.getElementById('fakeSubmit');
var onBoardingCmd = document.getElementById('onboarding_cmd');
fakeField.name = getCmd(this.href);
fakeField.value = this.innerHTML;
if (YUD.hasClass(this, 'loginSubmit')) {
onBoardingCmd.value = 'login';
} else if (YUD.hasClass(this, 'signupSubmit')) {
onBoardingCmd.value = 'signup';
} else if (YUD.hasClass(this, 'upgradeSubmit')) {
onBoardingCmd.value = 'upgrade';
} else if (YUD.hasClass(this, 'loginSavedSubmit')) {
onBoardingCmd.value = 'login-to-saved';
}
form.submit();
function getCmd(str) {
if (str.match("cmd") != null) {
str = str.split('?')[1];
str = str.split('&');
var strLen = str.length;
for (var i = 0; i < strLen; i++) {
if (str[i].match("cmd") != null) {
return str[i].split('=')[1];
}
}
return false;
} else {
return false;
}
}
return false;
},
selectOnFocusIn: function() {
try {
var eSrc = window.event.srcElement;
if (eSrc) {
eSrc.tmpIndex = eSrc.selectedIndex;
}
} catch (e) {
HandleError(e, false);
}
},
selectOnFocus: function() {
try {
var eSrc = window.event.srcElement;
if (eSrc) {
eSrc.selectedIndex = eSrc.tmpIndex;
}
} catch (e) {
HandleError(e, false);
}
},
loadScript: function(src) {
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = src;
head.appendChild(script);
},
isArray: function(obj) {
return testObject && !(testObject.propertyIsEnumerable('length')) && typeof testObject === 'object' && typeof testObject.length === 'number';
},
isFunction: function(a) {
return typeof a == 'function';
},
isNull: function(a) {
return typeof a == 'object' && !a;
},
isNumber: function(a) {
return typeof a == 'number' && isFinite(a);
},
isObject: function(a) {
return (typeof a == 'object' && a) || isFunction(a);
}
};
PAYPAL.Merchant.ButtonDesigner.StepOne = {
buttonTypeIds: ['products', 'services', 'subscriptions', 'donations', 'gift_certs'],
overrideMsgShown: false,
activeButtonType: '',
frequencyDOM: {},
currencySymbol: '$',
init: function() {
var stepOne = document.getElementById("stepOne");
if (stepOne) {
this.show('accordionContainer');
var fades = YUD.getElementsByClassName("fadedOut", '', stepOne);
BD_MASTER.fadeOut(fades);
var inputs = stepOne.getElementsByTagName('input');
var inputsLen = inputs.length;
for (var i = 0; i < inputsLen; i++) {
var inputType = inputs[i].type.toLowerCase();
if (inputType == "radio" || inputType == "checkbox") {
YUE.on(inputs[i], 'click', this.itemDetailsChangeHandler);
} else {
if (inputType.toLowerCase() == "text") {
YUE.on(inputs[i], 'keydown', this.captureEnter);
}
YUE.on(inputs[i], 'change', this.itemDetailsChangeHandler);
}
}
var selects = stepOne.getElementsByTagName('select');
var selectsLen = selects.length;
for (var i = 0; i < selectsLen; i++) {
YUE.on(selects[i], 'change', this.itemDetailsChangeHandler);
}
var shippingType = document.getElementById('itemFlatShippingType');
var shippingWeight = YUD.getElementsByClassName('itemWeight', 'div', stepOne)[0];
if (shippingType && shippingType.checked) {
BD_MASTER.fadeOut(shippingWeight);
}
this.frequencyDOM = YUD.getElementsByClassName('ddpOptionFrequency', 'select', 'optionsPriceContainer')[0];
if (this.frequencyDOM) {
this.frequencyDOM = this.frequencyDOM.cloneNode(true);
}
YUE.addListener('subscriptionBillingAmountCurrency', 'change', function() {
BD_STEP1.currencySymbol = this.options[this.selectedIndex].title;
BD_STEP1.currencyCode = this.value;
});
onItemDetailsChange.subscribe(this.itemDetailsChangeSubscriber);
onItemDetailsChange.subscribe(BD_CBUTTON.updateCustomizeButtonSection);
onItemDetailsChange.subscribe(BD_CBUTTON.dropdownCurrencyChange);
onPricePerOption.subscribe(this.priceOptionSubscriber);
onAccordionComplete.subscribe(this.accordionSubscriber);
this.itemDetailsChangeHandler();
}
},
donationDropDownChange: function(e) {
var selectedTypeValue = document.getElementById("buttonType");
if (selectedTypeValue.options[selectedTypeValue.selectedIndex].value == 'donations') {
var content = document.getElementById("jsContent");
YUD.replaceClass(content, 'show', 'hide');
var header = document.getElementById("headline");
header = header.getElementsByTagName("h2");
YUD.replaceClass(header, 'show', 'hide');
var pageLoadMsg = document.getElementById("pageLoadMsg");
YUD.replaceClass(pageLoadMsg, 'accessAid', 'show');
var redirectUrl = document.getElementById("donateUrl").value;
window.location = redirectUrl;
}
},
itemDetailsChangeHandler: function(e) {
var stepOne = document.getElementById("stepOne");
var changeElements = [];
if (!e) {
var bType = document.getElementById('buttonType');
var buttonType = bType.options[bType.selectedIndex].value;
var subButtonTypes = YUD.getElementsByClassName('subButtonType', '', stepOne);
var selectedSubButtonType = null;
if (subButtonTypes.length > 0) {
var subButtonTypesLen = subButtonTypes.length;
for (var i = 0; i < subButtonTypesLen; i++) {
if (subButtonTypes[i].checked) {
selectedSubButtonType = subButtonTypes[i].value;
}
}
}
changeElements.eventTarget = bType;
changeElements.button_type = buttonType;
changeElements.sub_button_type = selectedSubButtonType;
} else {
var elTarget = YUE.getTarget(e);
if (elTarget.nodeName.toLowerCase() == "input") {
changeElements[elTarget.name] = elTarget.value;
} else if (elTarget.nodeName.toLowerCase() == "select") {
var selectedVal = elTarget.options[elTarget.selectedIndex].value;
changeElements[elTarget.name] = selectedVal;
}
if (elTarget.value == "products" || elTarget.value == "services") {
if (elTarget.value == 'products') {
document.getElementById('radioAddToCartButton').checked = true;
document.getElementById('radioAddToCartButton').click();
} else {
document.getElementById('radioBuyNowButton').checked = true;
document.getElementById('radioBuyNowButton').click();
}
var subButtonTypes = YUD.getElementsByClassName('subButtonType', '', stepOne);
if (subButtonTypes.length > 0) {
var subButtonTypesLen = subButtonTypes.length;
for (var i = 0; i < subButtonTypesLen; i++) {
if (subButtonTypes[i].checked) {
changeElements.sub_button_type = subButtonTypes[i].value;
}
}
}
} else if (elTarget.name == 'sub_button_type') {
var buttonType = document.getElementById('buttonType');
var selectedVal = buttonType.options[buttonType.selectedIndex].value;
changeElements.button_type = selectedVal;
}
changeElements.eventTarget = elTarget;
}
if (changeElements.button_type == 'payment_plan' || changeElements.button_type == 'auto_billing') {
var content = document.getElementById("jsContent");
YUD.replaceClass(content, 'show', 'hide');
var header = document.getElementById("headline");
header = header.getElementsByTagName("h2");
YUD.replaceClass(header, 'show', 'hide');
var pageLoadMsg = document.getElementById("pageLoadMsg");
YUD.replaceClass(pageLoadMsg, 'accessAid', 'show');
var fakeField = document.getElementById('fakeSubmit');
var cmd = document.getElementById('cmd');
cmd.value = '_button-designer';
fakeField.name = 'factory_type';
fakeField.value = changeElements.button_type;
document.getElementById('customImageUrl').value = '';
this.form.submit();
}
onItemDetailsChange.fire(changeElements);
},
itemDetailsChangeSubscriber: function(type, obj) {
var eventTarget = obj[0].eventTarget;
if (obj[0].button_type) {
var stepOne = document.getElementById('stepOne');
var productItemPrice = YUD.getElementsByClassName('products pricing', '', stepOne)[0];
var donationItemPrice = YUD.getElementsByClassName('contributionAmount', '', stepOne)[0].parentNode;
if (obj[0].button_type != BD_STEP1.activeButtonType) {
var buttonTypeIdsLen = BD_STEP1.buttonTypeIds.length;
for (var i = 0; i < buttonTypeIdsLen; i++) {
var currentButtonType = BD_STEP1.buttonTypeIds[i];
if (obj[0].button_type == currentButtonType) {
BD_STEP1.prevButtonType = BD_STEP1.activeButtonType;
BD_STEP1.activeButtonType = currentButtonType;
switch (currentButtonType) {
case 'products':
case 'services':
BD_MASTER.fadeOut(donationItemPrice);
BD_MASTER.fadeIn(productItemPrice);
BD_STEP1.show('products');
BD_STEP1.updateProductOptions();
if (BD_STEP1.prevButtonType == 'subscriptions') {
var dropdownPrice = document.getElementById("dropdownPrice");
if (dropdownPrice.checked) {
dropdownPrice.click();
}
}
break;
case 'subscriptions':
BD_STEP1.show('subscriptions');
if (BD_STEP1.prevButtonType == 'products' || BD_STEP1.prevButtonType == 'services') {
var dropdownPrice = document.getElementById("dropdownPrice");
if (dropdownPrice.checked) {
dropdownPrice.click();
}
}
break;
case 'donations':
BD_MASTER.fadeOut(productItemPrice);
BD_MASTER.fadeIn(donationItemPrice);
BD_STEP1.show('donations');
break;
case 'gift_certs':
BD_STEP1.show('gift_certs');
break;
}
} else {
BD_STEP1.hide(currentButtonType);
}
}
}
}
if (obj[0].item_price_currency || obj[0].ddp_option_currency) {
var currencyCode = (obj[0].item_price_currency) ? obj[0].item_price_currency : obj[0].ddp_option_currency;
var currencyLabels = YUD.getElementsByClassName('currencyLabel', '', "stepOne");
var currencyLabelsLen = currencyLabels.length;
for (var i = 0; i < currencyLabelsLen; i++) {
currencyLabels[i].innerHTML = currencyCode;
}
var currencySelects = YUD.getElementsByClassName('currencySelect', '', "stepOne");
var currencySelectsLen = currencySelects.length;
for (var i = 0; i < currencySelectsLen; i++) {
if (currencySelects[i] != eventTarget.id) {
var currencyOptionsLen = currencySelects[i].options.length;
for (var j = 0; j < currencyOptionsLen; j++) {
if (currencySelects[i].options[j].value == currencyCode) {
currencySelects[i].options[j].selected = true;
}
}
}
}
}
if (obj[0].product_id) {
var itemID = document.getElementById('itemID');
itemID.value = obj[0].product_id;
}
if (obj[0].item_shipping_type || obj[0].item_tax_type) {
BD_STEP1.updateProductOptions();
}
if (obj[0].subscription_id) {
var subscriptionID = document.getElementById('subscriptionID');
subscriptionID.value = obj[0].subscription_id;
}
if (obj[0].subscriptions_offer_trial) {
if (eventTarget.checked) {
BD_STEP1.show('trialOfferOptions');
} else {
BD_STEP1.hide('trialOfferOptions');
}
}
if (obj[0].subscriptions_offer_another_trial) {
if (eventTarget.checked && eventTarget.value == 1) {
BD_STEP1.show('secondTrialOfferOptions');
} else {
BD_STEP1.hide('secondTrialOfferOptions');
}
}
if (obj[0].donation_type) {
if (obj[0].donation_type == 'fixed') {
BD_STEP1.show('fixedDonationAmountContainer');
BD_STEP1.hide('donationAmountContainer');
} else {
BD_STEP1.hide('fixedDonationAmountContainer');
BD_STEP1.show('donationAmountContainer');
}
}
if (obj[0].gc_amount_type) {
if (obj[0].gc_amount_type == 'custom') {
BD_STEP1.hide('gcFixedAmountContainer');
} else {
BD_STEP1.show('gcFixedAmountContainer');
}
}
},
accordionSubscriber: function(args) {
var y = YUD.getY('stepOne') - 18;
window.scrollTo(0, y);
},
priceOptionSubscriber: function(type, obj) {
var stepOne = document.getElementById("stepOne");
var itemPriceContainer = YUD.getElementsByClassName('products pricing', '', stepOne)[0];
var buttonType = document.getElementById('buttonType');
this.activeButtonType = buttonType.options[buttonType.selectedIndex].value;
if (this.activeButtonType == 'subscriptions') {
itemPriceContainer = document.getElementById('rbFixedAmount');
}
if (this.activeButtonType == "products" || this.activeButtonType == "services" || this.activeButtonType == "subscriptions") {
if (obj[0].hideItemPrice) {
wHideShow.hide(itemPriceContainer);
} else {
wHideShow.show(itemPriceContainer);
}
if (obj[0].disableItemPrice) {
BD_MASTER.fadeOut(itemPriceContainer);
} else {
BD_MASTER.fadeIn(itemPriceContainer);
}
}
var optionsPriceContainer = document.getElementById("optionsPriceContainer");
var ddpOptionCurrency = YUD.getElementsByClassName('ddpOptionCurrency', '', optionsPriceContainer);
var ddpOptionFrequency = YUD.getElementsByClassName('ddpOptionFrequency', '', optionsPriceContainer);
if (this.activeButtonType == 'subscriptions' && document.getElementById("dropdownPrice").checked) {
YUD.replaceClass(ddpOptionCurrency, 'show', 'hide');
for (i = 0, ln = ddpOptionFrequency.length; i < ln; i++) {
ddpOptionFrequency[i].disabled = false;
YUD.removeClass(ddpOptionFrequency[i], 'hide')
}
} else {
YUD.replaceClass(ddpOptionCurrency, 'hide', 'show');
for (i = 0, ln = ddpOptionFrequency.length; i < ln; i++) {
ddpOptionFrequency[i].disabled = true;
YUD.addClass(ddpOptionFrequency[i], 'hide')
}
}
},
updateProductOptions: function() {
var itemSavedShippingType = document.getElementById('itemSavedShippingType');
var itemShippingAmount = document.getElementById('itemFlatShippingAmount');
var itemWeight = YUD.getElementsByClassName('itemWeight')[0];
var itemSavedTaxRate = document.getElementById('itemSavedTaxRate');
var itemTaxRate = document.getElementById('itemTaxRate');
if (itemSavedTaxRate) {
if (itemSavedTaxRate.checked) {
itemTaxRate.disabled = true;
} else {
itemTaxRate.disabled = false;
}
}
if (itemSavedShippingType) {
if (itemSavedShippingType.checked) {
BD_MASTER.fadeIn(itemWeight);
itemShippingAmount.disabled = true;
itemWeight.focus();
} else {
BD_MASTER.fadeOut(itemWeight);
itemShippingAmount.disabled = false;
}
}
},
buildGiftCertificatePreview: function() {
var secureServer = document.getElementById("secureServerName").value;
var logoURL = document.getElementById('giftCertificateLogoURL').value;
var shopURL = document.getElementById('giftCertificateShopURL').value;
var gcColor = document.getElementById('gcBackgroundColor');
var gcColor = gcColor.options[gcColor.selectedIndex].value;
var gcTheme = document.getElementById('gcBackgroundTheme');
var gcTheme = gcTheme.options[gcTheme.selectedIndex].value;
var url = 'https://' + secureServer + '/cgi-bin/webscr?cmd=xpt/Incentive/popup/PiePrintableMerchGC&code=oegc';
if (YUD.getElementsByClassName('gcBackgroundType')[0].checked == true) {
url += '&style_color=' + gcColor;
} else if (YUD.getElementsByClassName('gcBackgroundType')[1].checked == true) {
url += '&style_theme=' + gcTheme;
} else {
url += '&style_color=BLU';
}
url += '&logo_image_custom=' + logoURL;
url += '&url_custom=' + shopURL;
window.open(url, null, 'scrollbars,resizable,toolbar,status,width=640,height=480,left=50,top=50');
},
hide: function(elClass) {
var stepOne = document.getElementById("stepOne");
var elements = YUD.getElementsByClassName(elClass, '', stepOne);
var elementsLen = elements.length;
for (var i = 0; i < elementsLen; i++) {
if (!YUD.hasClass(elements[i], 'accessAid')) {
YUD.addClass(elements, 'accessAid');
}
if (YUD.hasClass(elements[i], 'accessAid')) {
BD_MASTER.fadeOut(elements[i]);
}
}
},
show: function(elClass) {
var stepOne = document.getElementById("stepOne");
var elements = YUD.getElementsByClassName(elClass, '', stepOne);
var elementsLen = elements.length;
for (var i = 0; i < elementsLen; i++) {
if (YUD.hasClass(elements[i], 'accessAid')) {
YUD.removeClass(elements[i], 'accessAid');
BD_MASTER.fadeIn(elements[i]);
}
}
},
captureEnter: function(e) {
var keyPressed = e.charCode || e.keyCode;
var target = e.target || e.srcElement;
var validElements = /INPUT/i;
var omitElements = /SUBMIT|IMAGE/i;
if ((keyPressed == 13) && (validElements.test(target.nodeName)) && (!omitElements.test(target.type))) {
YUE.preventDefault(e);
}
}
};
YUE.addListener('buttonType', 'change', PAYPAL.Merchant.ButtonDesigner.StepOne.donationDropDownChange);
PAYPAL.Merchant.ButtonDesigner.CustomizeButton = {
numOptionsPrice: 0,
numOptions1: 0,
numOptions2: 0,
numOptions3: 0,
numOptions4: 0,
activeDropdown: 0,
activeTextfield: 0,
buttonType: "",
ddPriceStructure: new Object,
ddStructure: new Array(),
tfStructure: new Array(),
optionCounter: 0,
init: function() {
var dropdownPrice = document.getElementById("dropdownPrice");
if (dropdownPrice) {
YUE.addListener(dropdownPrice, 'click', this.showDropdownPrice, this);
}
var dropdown = document.getElementById("dropdown");
if (dropdown) {
YUE.addListener(dropdown, 'click', this.showDropdown, this);
}
var textfield = document.getElementById("textfield");
if (textfield) {
YUE.addListener(textfield, 'click', this.showTextfield, this);
}
var addOptionPrice = document.getElementById("addOptionPrice");
if (addOptionPrice) {
YUE.addListener(addOptionPrice, 'click', this.addNewOptionPrice, this);
}
var removeOptionPrice = document.getElementById("removeOptionPrice");
if (removeOptionPrice) {
YUE.addListener(removeOptionPrice, 'click', this.removeOptionsPrice, this);
}
var saveOptionPrice = document.getElementById("saveOptionPrice");
if (saveOptionPrice) {
YUE.addListener(saveOptionPrice, 'click', this.saveDropdownPrice, this);
}
var cancelOptionPrice = document.getElementById("cancelOptionPrice");
if (cancelOptionPrice) {
YUE.addListener(cancelOptionPrice, 'click', this.cancelPricePerOption, this);
}
var editDropdownPrice = document.getElementById("editDropdownPrice");
if (editDropdownPrice) {
YUE.addListener(editDropdownPrice, 'click', this.editDropdownPrice, this);
}
var deleteDropdownPrice = document.getElementById("deleteDropdownPrice");
if (deleteDropdownPrice) {
YUE.addListener(deleteDropdownPrice, 'click', this.deleteDropdownPrice, this);
}
var addOption = YUD.getElementsByClassName("addOption");
if (addOption) {
YUE.addListener(addOption, 'click', this.addNewOption, this);
}
var saveOption = YUD.getElementsByClassName("saveOption");
if (saveOption) {
YUE.addListener(saveOption, 'click', this.saveDropdown, this);
}
var cancelOption = YUD.getElementsByClassName("cancelOption");
if (cancelOption) {
YUE.addListener(cancelOption, 'click', this.cancelOption, this);
}
var editDropdown = YUD.getElementsByClassName("editDropdown");
if (editDropdown) {
YUE.addListener(editDropdown, 'click', this.editDropdown, this);
}
var deleteDropdown = YUD.getElementsByClassName("deleteDropdown");
if (deleteDropdown) {
YUE.addListener(deleteDropdown, 'click', this.deleteDropdown, this);
}
var addNewDropdown = document.getElementById("addNewDropdown");
if (addNewDropdown) {
YUE.addListener(addNewDropdown, 'click', this.addNewDropdown, this);
}
var saveTextfield = YUD.getElementsByClassName("saveTextfield");
if (saveTextfield) {
YUE.addListener(saveTextfield, 'click', this.saveTextfield, this);
}
var editTextfield = YUD.getElementsByClassName("editTextfield");
if (editTextfield) {
YUE.addListener(editTextfield, 'click', this.editTextfield, this);
}
var deleteTextfield = YUD.getElementsByClassName("deleteTextfield");
if (deleteTextfield) {
YUE.addListener(deleteTextfield, 'click', this.deleteTextfield, this);
}
var cancelTextfield = YUD.getElementsByClassName("cancelTextfield");
if (cancelTextfield) {
YUE.addListener(cancelTextfield, 'click', this.cancelTextfield, this);
}
var addNewTextfield = document.getElementById("addNewTextfield");
if (addNewTextfield) {
YUE.addListener(addNewTextfield, 'click', this.addNewTextfield, this);
}
var buttonAppLink = document.getElementById("buttonAppLink");
if (buttonAppLink) {
YUE.addListener(buttonAppLink, 'click', this.toggleButtonAppSection, this);
}
var paypalButton = document.getElementById("paypalButton");
if (paypalButton) {
YUE.addListener(paypalButton, 'click', this.showPaypalButtonSection, this);
}
var customButton = document.getElementById("customButton");
if (customButton) {
YUE.addListener(customButton, 'click', this.showCustomButtonSection, this);
}
var smallButton = document.getElementById("smallButton");
if (smallButton) {
YUE.addListener(smallButton, 'click', this.displaySmallImage, this);
}
var ccLogos = document.getElementById("ccLogos");
if (ccLogos) {
YUE.addListener(ccLogos, 'click', this.displayCCImage, this);
}
var buttonTextBuyNow = document.getElementById("buttonTextBuyNow");
if (buttonTextBuyNow) {
YUE.addListener(buttonTextBuyNow, 'change', this.updateImageText);
}
var buttonTextSubscribe = document.getElementById("buttonTextSubscribe");
if (buttonTextSubscribe) {
YUE.addListener(buttonTextSubscribe, 'change', this.updateImageText);
}
var selectCountryLanguage = document.getElementById("selectCountryLanguage");
if (selectCountryLanguage) {
YUE.addListener(selectCountryLanguage, 'change', this.updateButtonCountry, this);
}
var country_code = document.getElementById("country_code");
var readOnlyLabel = YUD.getElementsByClassName("readOnlyLabel");
if (readOnlyLabel) {
YUE.addListener(readOnlyLabel, 'focus', this.makeFieldReadOnly, this);
}
var createButton = document.getElementById("createButton");
if (createButton) {
YUE.addListener(createButton, 'click', this.saveDropdownsAndSubmit, this);
}
var accordionTabs = YUD.getElementsByClassName("header");
if (accordionTabs) {
YUE.addListener(accordionTabs, 'click', this.saveDropdowns, this);
}
var exampleLink = YUD.getElementsByClassName("exampleLink");
if (exampleLink) {
YUE.addListener(exampleLink, 'click', this.createPopupImage, this);
}
var defCurrency = YUD.getElementsByClassName("ddpOptionCurrency", "select", "dropdownPriceSection");
if (defCurrency) {
YUE.addListener(defCurrency, 'change', this.updateCurrency, this);
}
this.createDropdownPriceStructure();
this.createDropdownStructure();
this.createTextfieldStructure();
var test = YUD.getElementsByClassName("savedDropdownSection");
var testLen = test.length;
var cnt = 0;
for (var i = 0; i < testLen; i++) {
if (YUD.hasClass(test[i], "opened")) cnt++;
}
this.numDropdowns = cnt;
},
showDropdownPrice: function() {
var dropdownPriceSection = document.getElementById("dropdownPriceSection");
var previewDropdownPriceSection = document.getElementById("previewDropdownPriceSection");
var savedDropdownPriceSection = document.getElementById("savedDropdownPriceSection");
var savedDropdownPrice = document.getElementById("savedDropdownPrice");
if (this.checked) {
if (dropdownPriceSection) {
var allInputs = dropdownPriceSection.getElementsByTagName("input");
var allInputsLen = allInputs.length;
for (var i = 0; i < allInputsLen; i++) {
allInputs[i].disabled = false;
}
var allInputs = dropdownPriceSection.getElementsByTagName("select");
var allInputsLen = allInputs.length;
for (var i = 0; i < allInputsLen; i++) {
allInputs[i].disabled = false;
}
onPricePerOption.fire({
hideItemPrice: false,
disableItemPrice: true
});
BD_CBUTTON.displayAddOptionPriceLink();
var options = YUD.getElementsByClassName("optionRow", "p", "dropdownPriceSection");
if (options.length == 0) {
for (var i = 0; i < 3; i++) {
BD_CBUTTON.createNewPriceOption();
}
}
var optionPrices = YUD.getElementsByClassName("ddpOptionPrice", "input", "dropdownPriceSection");
var itemPriceField = document.getElementById("itemPrice");
if (itemPriceField) {
var itemPrice = itemPriceField.value;
var optionPricesLen = optionPrices.length;
for (var i = 0; i < optionPricesLen; i++) {
if (optionPrices[i].value == "") {
optionPrices[i].value = itemPrice;
}
}
}
BD_CBUTTON.updateCurrency();
wHideShow.show(dropdownPriceSection);
}
BD_CBUTTON.updateOptionsPricePreview();
if (previewDropdownPriceSection) {
wHideShow.show(previewDropdownPriceSection);
}
} else {
if (dropdownPriceSection) {
wHideShow.hide(dropdownPriceSection);
var allInputs = dropdownPriceSection.getElementsByTagName("input");
var allInputsLen = allInputs.length;
for (var i = 0; i < allInputsLen; i++) {
allInputs[i].disabled = true;
}
}
if (previewDropdownPriceSection) {
wHideShow.hide(previewDropdownPriceSection);
}
if (savedDropdownPriceSection) {
savedDropdownPrice.innerHTML = "";
wHideShow.hide(savedDropdownPriceSection);
}
BD_CBUTTON.buildDropdownInfo(0);
onPricePerOption.fire({
hideItemPrice: false,
disableItemPrice: false
});
}
},
showDropdown: function() {
if (this.checked) {
var dropdownSection = document.getElementById("dropdownSection1");
var previewDropdownSection = document.getElementById("previewDropdownSection1");
var savedDropdownSection = document.getElementById("savedDropdownSection1");
if (dropdownSection) {
wHideShow.show(dropdownSection);
BD_CBUTTON.activeDropdown = 1;
var allInputs = dropdownSection.getElementsByTagName("input");
var allInputsLen = allInputs.length;
for (var i = 0; i < allInputsLen; i++) {
allInputs[i].disabled = false;
}
BD_CBUTTON.displayAddOptionLink();
}
BD_CBUTTON.recreateOptionsPreview(1);
if (previewDropdownSection) {
wHideShow.show(previewDropdownSection);
}
} else {
for (var ddNum = 1; ddNum < 5; ddNum++) {
var dropdownSection = document.getElementById("dropdownSection" + ddNum);
var previewDropdownSection = document.getElementById("previewDropdownSection" + ddNum);
var savedDropdownSection = document.getElementById("savedDropdownSection" + ddNum);
var savedDropdown = document.getElementById("savedDropdown" + ddNum);
var addNewDropdownSection = document.getElementById("addNewDropdownSection");
if (dropdownSection) {
wHideShow.hide(dropdownSection);
}
if (previewDropdownSection) {
wHideShow.hide(previewDropdownSection);
}
if (savedDropdownSection) {
var allInputs = dropdownSection.getElementsByTagName("input");
var allInputsLen = allInputs.length;
for (var i = 0; i < allInputsLen; i++) {
allInputs[i].disabled = true;
}
savedDropdown.innerHTML = "";
wHideShow.hide(savedDropdownSection);
}
}
if (addNewDropdownSection) {
wHideShow.hide(addNewDropdownSection);
}
BD_CBUTTON.buildDropdownInfo(0);
}
},
showTextfield: function() {
if (this.checked) {
var textfieldSection = document.getElementById("textfieldSection1");
var previewTextfieldSection = document.getElementById("previewTextfieldSection1");
var savedTextfieldSection = document.getElementById("savedTextfieldSection1");
if (textfieldSection) {
wHideShow.show(textfieldSection);
BD_CBUTTON.activeTextfield = 1;
var allInputs = textfieldSection.getElementsByTagName("input");
var allInputsLen = allInputs.length;
for (var i = 0; i < allInputsLen; i++) {
allInputs[i].disabled = false;
}
}
if (previewTextfieldSection) {
wHideShow.show(previewTextfieldSection);
}
BD_CBUTTON.createTextfieldStructure();
} else {
for (var tfNum = 1; tfNum < 3; tfNum++) {
var textfieldSection = document.getElementById("textfieldSection" + tfNum);
var previewTextfieldSection = document.getElementById("previewTextfieldSection" + tfNum);
var savedTextfieldSection = document.getElementById("savedTextfieldSection" + tfNum);
var addNewTextfieldSection = document.getElementById("addNewTextfieldSection");
var textfieldTitle = YAHOO.util.Dom.get("textfieldTitle" + tfNum);
var savedTextfield = YAHOO.util.Dom.get("savedTextfield" + tfNum);
var previewTextfieldTitle = YAHOO.util.Dom.get("previewTextfieldTitle" + tfNum);
if (textfieldSection) {
wHideShow.hide(textfieldSection);
textfieldTitle.value = "";
var allInputs = textfieldSection.getElementsByTagName("input");
var allInputsLen = allInputs.length;
for (var i = 0; i < allInputsLen; i++) {
allInputs[i].disabled = true;
}
}
if (previewTextfieldSection) {
wHideShow.hide(previewTextfieldSection);
previewTextfieldTitle.innerHTML = YAHOO.util.Dom.get("titleStr").value;
}
if (savedTextfieldSection) {
wHideShow.hide(savedTextfieldSection);
savedTextfield.innerHTML = "";
}
}
if (addNewTextfieldSection) {
wHideShow.hide(addNewTextfieldSection);
}
}
},
showPaypalButtonSection: function() {
var paypalButtonSection = document.getElementById("paypalButtonSection");
var customButtonSection = document.getElementById("customButtonSection");
var previewImageSection = YUD.getElementsByClassName("previewImageSection")[0];
var previewCustomImageSection = YUD.getElementsByClassName("previewCustomImageSection")[0];
if (this.checked) {
wHideShow.hide(customButtonSection);
wHideShow.show(paypalButtonSection);
wHideShow.show(previewImageSection);
wHideShow.hide(previewCustomImageSection);
}
},
showCustomButtonSection: function() {
var paypalButtonSection = document.getElementById("paypalButtonSection");
var customButtonSection = document.getElementById("customButtonSection");
var previewImageSection = YUD.getElementsByClassName("previewImageSection")[0];
var previewCustomImageSection = YUD.getElementsByClassName("previewCustomImageSection")[0];
if (this.checked) {
wHideShow.hide(paypalButtonSection);
wHideShow.show(customButtonSection);
wHideShow.hide(previewImageSection);
wHideShow.show(previewCustomImageSection);
}
},
toggleButtonAppSection: function(e) {
YUE.preventDefault(e);
var buttonAppSection = document.getElementById("buttonAppSection");
var customizeButtonSection = YUD.getElementsByClassName("customizeButtonSection")[0];
var borderBox = YUD.getElementsByClassName("borderBox")[0];
if (YUD.hasClass(this, "collapsed")) {
YUD.removeClass(this, "collapsed");
YUD.addClass(this, "expanded");
if (!(document.getElementById("paypalButton").checked || document.getElementById("customButton").checked)) {
document.getElementById("paypalButton").checked = true;
}
if (BD_CBUTTON.buttonType == "gift_certs" || BD_CBUTTON.buttonType == "donations") {
YUD.removeClass(borderBox, "heightFix");
}
wHideShow.show(buttonAppSection);
} else if (YUD.hasClass(this, "expanded")) {
YUD.removeClass(this, "expanded");
YUD.addClass(this, "collapsed");
if (BD_CBUTTON.buttonType == "gift_certs" || BD_CBUTTON.buttonType == "donations") {
YUD.addClass(borderBox, "heightFix");
}
wHideShow.hide(buttonAppSection);
}
},
saveDropdownPrice: function(e) {
YUE.preventDefault(e);
BD_CBUTTON.saveOptionPrice();
},
saveOptionPrice: function() {
var buttonType = document.getElementById('buttonType');
buttonType = buttonType.options[buttonType.selectedIndex].value;
var optionsPriceDropdown = document.getElementById("optionsPriceDropdown");
var dropdownPriceSection = document.getElementById("dropdownPriceSection");
var savedDropdownPriceSection = document.getElementById("savedDropdownPriceSection");
var previewDropdownPriceSection = document.getElementById("previewDropdownPriceSection");
var optionsPriceContainer = document.getElementById("optionsPriceContainer");
var options = YUD.getElementsByClassName("optionRow", "p", "dropdownPriceSection");
var optionNames = YUD.getElementsByClassName("ddpOptionName", "input", "dropdownPriceSection");
var optionPrices = YUD.getElementsByClassName("ddpOptionPrice", "input", "dropdownPriceSection");
var testDropdowns = [];
if (buttonType != 'subscriptions') {
var defCurrency = YUD.getElementsByClassName("ddpOptionCurrency", "select", "dropdownPriceSection")[0];
if (defCurrency.options) {
var defCurrencyValue = defCurrency.options[defCurrency.selectedIndex].value;
}
}
optionNames = YUD.getElementsByClassName("ddpOptionName", "input", "dropdownPriceSection");
optionPrices = YUD.getElementsByClassName("ddpOptionPrice", "input", "dropdownPriceSection");
var optionsLen = options.length;
for (var i = 0; i < optionsLen; i++) {
if ((optionNames[i].value == null || optionNames[i].value == "") && (optionPrices[i].value == null || optionPrices[i].value == "")) {
optionsPriceContainer.removeChild(optionNames[i].parentNode);
}
}
if (buttonType != 'subscriptions') {
options = YUD.getElementsByClassName("optionRow", "p", "dropdownPriceSection");
if (options.length > 0) {
var oldOptionCurrency = YUD.getElementsByClassName("ddpOptionCurrency", "", "dropdownPriceSection")[0];
if (oldOptionCurrency.nodeName != "SELECT") {
options[0].removeChild(oldOptionCurrency);
var optionCurrency = document.createElement("select");
optionCurrency.setAttribute("class", "ddpOptionCurrency");
optionCurrency.setAttribute("className", "ddpOptionCurrency");
YUE.addListener(optionCurrency, 'change', BD_CBUTTON.updateCurrency, this);
var itemCurrencyOpts = YUD.getElementsByClassName("currencySelect", "select", "")[0];
var itemCurrencyOptsLen = itemCurrencyOpts.options.length;
for (var i = 0; i < itemCurrencyOptsLen; i++) {
var opt = new Option(itemCurrencyOpts.options[i].text, itemCurrencyOpts.options[i].value);
optionCurrency.options[i] = opt;
if (optionCurrency.options[i].value == defCurrencyValue) {
optionCurrency.options[i].selected = true;
}
}
options[0].appendChild(optionCurrency);
}
}
}
BD_CBUTTON.displayAddOptionPriceLink();
wHideShow.hide(dropdownPriceSection);
if (BD_CBUTTON.numOptionsPrice == 0) {
document.getElementById("dropdownPrice").checked = false;
}
if (BD_CBUTTON.numOptionsPrice == 0) {
if (previewDropdownPriceSection) {
wHideShow.hide(previewDropdownPriceSection);
}
} else {
BD_CBUTTON.updateOptionsPricePreview();
}
if (BD_CBUTTON.numOptionsPrice != 0) {
document.getElementById("savedDropdownPrice").innerHTML = "";
var ddTitle = document.getElementById("dropdownPriceTitle").value;
if (ddTitle != "") {
ddTitle = BD_CBUTTON.escapeText(ddTitle);
document.getElementById("savedDropdownPrice").innerHTML = ddTitle + ": ";
}
options = YUD.getElementsByClassName("optionRow", "p", "dropdownPriceSection");
optionNames = YUD.getElementsByClassName("ddpOptionName", "input", "dropdownPriceSection");
optionPrices = YUD.getElementsByClassName("ddpOptionPrice", "input", "dropdownPriceSection");
if (buttonType == 'subscriptions') {
optionFrequency = YUD.getElementsByClassName("ddpOptionFrequency", "select", "dropdownPriceSection");
subscriptionBillingAmountCurrency = document.getElementById('subscriptionBillingAmountCurrency');
optionCurrencyCode = subscriptionBillingAmountCurrency.options[subscriptionBillingAmountCurrency.selectedIndex].value;
optionCurrencySymbol = subscriptionBillingAmountCurrency.options[subscriptionBillingAmountCurrency.selectedIndex].title;
BD_STEP1.currencySymbol = subscriptionBillingAmountCurrency.options[subscriptionBillingAmountCurrency.selectedIndex].title;
}
var optionsLen = options.length;
for (var i = 0; i < optionsLen; i++) {
var optName = optionNames[i].value;
var optPrice = optionPrices[i].value;
var optPriceHTMLEsc = PAYPAL.util.escapeHTML(optPrice);
if (buttonType == 'subscriptions') {
var optFrequency = optionFrequency[i].options[optionFrequency[i].selectedIndex].text;
}
if (i != 0) {
if (optName != "") {
if (buttonType == 'subscriptions') {
document.getElementById("savedDropdownPrice").innerHTML = document.getElementById("savedDropdownPrice").innerHTML + " | ";
} else {
document.getElementById("savedDropdownPrice").innerHTML = document.getElementById("savedDropdownPrice").innerHTML + ", ";
}
}
}
optName = BD_CBUTTON.escapeText(optName);
if (buttonType == 'subscriptions') {
optFrequency = BD_CBUTTON.escapeText(optFrequency);
document.getElementById("savedDropdownPrice").innerHTML = document.getElementById("savedDropdownPrice").innerHTML + optName + ": " + optionCurrencySymbol + optPriceHTMLEsc + " " + optionCurrencyCode + " - " + optFrequency;
} else {
document.getElementById("savedDropdownPrice").innerHTML = document.getElementById("savedDropdownPrice").innerHTML + optName;
}
}
wHideShow.show(savedDropdownPriceSection);
}
if (BD_CBUTTON.numOptionsPrice == 0) {
onPricePerOption.fire({
hideItemPrice: false,
disableItemPrice: false
});
} else {
onPricePerOption.fire({
hideItemPrice: true,
disableItemPrice: false
});
}
BD_CBUTTON.buildDropdownInfo(0);
BD_CBUTTON.createDropdownPriceStructure();
},
cancelPricePerOption: function(e) {
YUE.preventDefault(e);
var buttonType = document.getElementById('buttonType');
var activeButtonType = buttonType.options[buttonType.selectedIndex].value;
var dropdownPriceSection = document.getElementById("dropdownPriceSection");
var previewDropdownPriceSection = document.getElementById("previewDropdownPriceSection");
var savedDropdownPriceSection = document.getElementById("savedDropdownPriceSection");
var savedDropdownPrice = document.getElementById("savedDropdownPrice");
var optionsPriceContainer = document.getElementById("optionsPriceContainer");
var dropdownPrice = document.getElementById("dropdownPrice");
options = YUD.getElementsByClassName("optionRow", "p", "dropdownPriceSection");
var optionsLen = options.length;
var optionFrequency = BD_STEP1.frequencyDOM.cloneNode(true);
if (activeButtonType == 'subscriptions') {
YUD.removeClass(optionFrequency, 'hide');
optionFrequency.disabled = false;
} else {
YUD.addClass(optionFrequency, 'hide');
optionFrequency.disabled = true;
}
if (dropdownPriceSection) {
for (var a = 0; a < optionsLen; a++) {
optionsPriceContainer.removeChild(options[a]);
}
}
document.getElementById("dropdownPriceTitle").value = BD_CBUTTON.ddPriceStructure.title;
var ddPriceStructureLen = BD_CBUTTON.ddPriceStructure.options.length;
for (var j = 0; j < ddPriceStructureLen; j++) {
var optionsPriceContainer = document.getElementById("optionsPriceContainer");
var addOptionPrice = document.getElementById("addOptionPrice");
var parent = document.createElement("p");
parent.setAttribute("class", "optionRow col-md-9");
parent.setAttribute("className", "optionRow col-md-9");
parent.setAttribute("id", BD_CBUTTON.ddPriceStructure.options[j].optionId);
var optionName = document.createElement("input");
optionName.setAttribute("type", "text");
var nm = "ddp_option_name";
optionName.setAttribute("name", nm);
optionName.setAttribute("class", "ddpOptionName form-control");
optionName.setAttribute("className", "ddpOptionName form-control");
optionName.setAttribute("value", BD_CBUTTON.ddPriceStructure.options[j].optionName);
optionName.setAttribute("maxlength", "64");
parent.appendChild(optionName);
var optionPrice = document.createElement("input");
optionPrice.setAttribute("type", "text");
var nm = "ddp_option_price";
optionPrice.setAttribute("name", nm);
optionPrice.setAttribute("class", "ddpOptionPrice form-control");
optionPrice.setAttribute("className", "ddpOptionPrice form-control");
optionPrice.setAttribute("value", BD_CBUTTON.ddPriceStructure.options[j].optionPrice);
parent.appendChild(optionPrice);
if (j == 0) {
BD_CBUTTON.numOptionsPrice = 0;
}
if (BD_CBUTTON.numOptionsPrice == 0) {
var optionCurrency = document.createElement("select");
if (activeButtonType == 'subscriptions') {
optionCurrency.setAttribute("class", "ddpOptionCurrency hide");
optionCurrency.setAttribute("className", "ddpOptionCurrency hide");
} else {
optionCurrency.setAttribute("class", "ddpOptionCurrency");
optionCurrency.setAttribute("className", "ddpOptionCurrency");
}
YUE.addListener(optionCurrency, 'change', BD_CBUTTON.updateCurrency, this);
var itemCurrencyOpts = YUD.getElementsByClassName("currencySelect", "select", "")[0];
var itemCurrencyOptsLen = itemCurrencyOpts.options.length;
for (var i = 0; i < itemCurrencyOptsLen; i++) {
optionCurrency.options[i] = new Option(itemCurrencyOpts.options[i].text, itemCurrencyOpts.options[i].value);
if (itemCurrencyOpts.options[i].value == BD_CBUTTON.ddPriceStructure.options[j].optionCurrency) {
optionCurrency.options[i].selected = true;
}
}
parent.appendChild(optionCurrency);
} else {
var optionCurrency = document.createElement("label");
if (activeButtonType == 'subscriptions') {
optionCurrency.setAttribute("class", "ddpOptionCurrency hide");
optionCurrency.setAttribute("className", "ddpOptionCurrency hide");
} else {
optionCurrency.setAttribute("class", "ddpOptionCurrency");
optionCurrency.setAttribute("className", "ddpOptionCurrency");
}
var defCurrency = YUD.getElementsByClassName("ddpOptionCurrency", "select", "dropdownPriceSection")[0];
if (defCurrency.options) {
var defCurrencyValue = defCurrency.options[defCurrency.selectedIndex].value;
optionCurrency.setAttribute("innerHTML", defCurrencyValue);
}
parent.appendChild(optionCurrency);
}
var optionFreq = document.createElement("select");
optionFreq.setAttribute("class", "subscriptions ddpOptionFrequency");
optionFreq.setAttribute("className", "subscriptions ddpOptionFrequency");
var optionFreqOptsLen = optionFrequency.options.length;
for (var i = 0; i < optionFreqOptsLen; i++) {
optionFreq.options[i] = new Option(optionFrequency.options[i].text, optionFrequency.options[i].value);
if (optionFreq.options[i].value == 'M') {
optionFreq.options[i].selected = true;
}
}
if (activeButtonType != 'subscriptions') {
optionFreq.setAttribute("class", "ddpOptionFrequency hide");
optionFreq.setAttribute("className", "ddpOptionFrequency hide");
} else {
optionFreq.setAttribute("class", "ddpOptionFrequency");
optionFreq.setAttribute("className", "ddpOptionFrequency");
}
parent.appendChild(optionFreq);
optionsPriceContainer.appendChild(parent);
BD_CBUTTON.updateCurrency();
BD_CBUTTON.displayAddOptionPriceLink();
}
if (dropdownPriceSection) {
wHideShow.hide(dropdownPriceSection);
if (savedDropdownPrice.innerHTML == "" && dropdownPrice.checked) {
dropdownPrice.click();
}
}
if (previewDropdownPriceSection) {
(savedDropdownPrice.innerHTML == "") ? wHideShow.hide(previewDropdownPriceSection): wHideShow.show(previewDropdownPriceSection);
}
if (savedDropdownPriceSection) {
(savedDropdownPrice.innerHTML == "") ? wHideShow.hide(savedDropdownPriceSection): wHideShow.show(savedDropdownPriceSection);
}
var removeOption = document.getElementById("removeOptionPrice");
wHideShow.show(removeOption);
},
removeOptionsPrice: function(e) {
YUE.preventDefault(e);
var linkParent = BD_CBUTTON.getParent(this);
var menuList = BD_CBUTTON.getPreviousSibling(linkParent);
var optionList = YUD.getElementsByClassName("optionRow", "p", menuList.id);
if (BD_CBUTTON.numOptionsPrice > 1) {
menuList.removeChild(optionList[BD_CBUTTON.numOptionsPrice - 1]);
BD_CBUTTON.numOptionsPrice--;
if (BD_CBUTTON.numOptionsPrice == 1) {
wHideShow.hide(this);
}
if (BD_CBUTTON.numOptionsPrice == 9) {
var addOption = document.getElementById("addOptionPrice");
wHideShow.show(addOption);
}
}
},
getParent: function(el) {
do {
el = el.parentNode;
} while (el && el.nodeType != 1);
return el;
},
getPreviousSibling: function(el) {
do {
el = el.previousSibling;
} while (el && el.nodeType != 1);
return el;
},
addNewOptionPrice: function(e) {
YUE.preventDefault(e);
BD_CBUTTON.createNewPriceOption();
if (BD_CBUTTON.numOptionsPrice == 2) {
var removeOption = document.getElementById("removeOptionPrice");
wHideShow.show(removeOption);
}
},
createNewPriceOption: function(opt) {
var buttonType = document.getElementById('buttonType');
var buttonTypeValue = buttonType.options[buttonType.selectedIndex].value;
if (BD_CBUTTON.numOptionsPrice < 10) {
var optionsPriceContainer = document.getElementById("optionsPriceContainer");
var addOptionPrice = document.getElementById("addOptionPrice");
var parent = document.createElement("p");
parent.setAttribute("class", "optionRow clearfix");
parent.setAttribute("className", "optionRow clearfix");
var optionName = document.createElement("input");
optionName.setAttribute("type", "text");
var nm = "ddp_option_name";
optionName.setAttribute("name", nm);
optionName.setAttribute("class", "ddpOptionName form-control");
optionName.setAttribute("className", "ddpOptionName form-control");
optionName.setAttribute("maxlength", "64");
optionName.setAttribute("value", document.getElementById("optionStr").value + " " + (BD_CBUTTON.numOptionsPrice + 1));
parent.appendChild(optionName);
var optionPrice = document.createElement("input");
optionPrice.setAttribute("type", "text");
var nm = "ddp_option_price";
optionPrice.setAttribute("name", nm);
optionPrice.setAttribute("class", "ddpOptionPrice form-control");
optionPrice.setAttribute("className", "ddpOptionPrice form-control");
parent.appendChild(optionPrice);
if (BD_CBUTTON.numOptionsPrice == 0) {
var optionCurrency = document.createElement("select");
optionCurrency.setAttribute("class", "ddpOptionCurrency");
optionCurrency.setAttribute("className", "ddpOptionCurrency");
YUE.addListener(optionCurrency, 'change', BD_CBUTTON.updateCurrency, this);
var itemCurrencyOpts = YUD.getElementsByClassName("currencySelect", "select", "")[0];
var itemCurrencyOptsLen = itemCurrencyOpts.options.length;
for (var i = 0; i < itemCurrencyOptsLen; i++) {
optionCurrency.options[i] = new Option(itemCurrencyOpts.options[i].text, itemCurrencyOpts.options[i].value);
if (itemCurrencyOpts.options[i].selected) {
optionCurrency.options[i].selected = true;
}
}
if (buttonTypeValue == 'subscriptions') {
YUD.addClass(optionCurrency, 'hide');
}
parent.appendChild(optionCurrency);
} else {
var optionCurrency = document.createElement("label");
if (buttonTypeValue == 'subscriptions') {
optionCurrency.setAttribute("class", "ddpOptionCurrency hide");
optionCurrency.setAttribute("className", "ddpOptionCurrency hide");
} else {
optionCurrency.setAttribute("class", "ddpOptionCurrency show");
optionCurrency.setAttribute("className", "ddpOptionCurrency show");
}
var defCurrency = YUD.getElementsByClassName("ddpOptionCurrency", "select", "dropdownPriceSection")[0];
if (defCurrency.options) {
var defCurrencyValue = defCurrency.options[defCurrency.selectedIndex].value;
optionCurrency.setAttribute("innerHTML", defCurrencyValue);
}
if (buttonTypeValue == 'subscriptions') {
YUD.addClass(optionCurrency, 'hide');
}
parent.appendChild(optionCurrency);
}
var optionFrequency = BD_STEP1.frequencyDOM.cloneNode(true);
if (buttonTypeValue == 'subscriptions') {
YUD.removeClass(optionFrequency, 'hide');
optionFrequency.disabled = false;
} else {
YUD.addClass(optionFrequency, 'hide');
optionFrequency.disabled = true;
}
parent.appendChild(optionFrequency);
optionsPriceContainer.appendChild(parent);
BD_CBUTTON.updateCurrency();
}
BD_CBUTTON.displayAddOptionPriceLink();
},
editDropdownPrice: function(e) {
YUE.preventDefault(e);
var dropdownPriceSection = document.getElementById("dropdownPriceSection");
var previewDropdownPriceSection = document.getElementById("previewDropdownPriceSection");
var savedDropdownPriceSection = document.getElementById("savedDropdownPriceSection");
if (dropdownPriceSection) {
wHideShow.show(dropdownPriceSection);
var labels = YUD.getElementsByClassName("optionNameLbl", "label", "dropdownPriceSection");
wHideShow.show(labels[0]);
labels = YUD.getElementsByClassName("optionPriceLbl", "label", "dropdownPriceSection");
wHideShow.show(labels[0]);
BD_CBUTTON.displayAddOptionPriceLink();
}
if (previewDropdownPriceSection) {
wHideShow.show(previewDropdownPriceSection);
}
if (savedDropdownPriceSection) {
wHideShow.hide(savedDropdownPriceSection);
}
},
deleteDropdownPrice: function(e) {
YUE.preventDefault(e);
var dropdownPriceSection = document.getElementById("dropdownPriceSection");
var previewDropdownPriceSection = document.getElementById("previewDropdownPriceSection");
var savedDropdownPriceSection = document.getElementById("savedDropdownPriceSection");
var savedDropdownPrice = document.getElementById("savedDropdownPrice");
var optionsPriceContainer = document.getElementById("optionsPriceContainer");
var options = YUD.getElementsByClassName("optionRow", "p", "dropdownPriceSection");
var optionsLen = options.length;
if (dropdownPriceSection) {
for (var i = 0; i < optionsLen; i++) {
optionsPriceContainer.removeChild(options[i]);
BD_CBUTTON.numOptionsPrice--;
}
document.getElementById("dropdownPriceTitle").value = "";
wHideShow.hide(dropdownPriceSection);
}
BD_CBUTTON.buildDropdownInfo(0);
if (savedDropdownPriceSection) {
savedDropdownPrice.innerHTML = "";
wHideShow.hide(savedDropdownPriceSection);
}
if (previewDropdownPriceSection) {
wHideShow.hide(previewDropdownPriceSection);
}
document.getElementById("dropdownPrice").checked = false;
onPricePerOption.fire({
hideItemPrice: false,
disableItemPrice: false
});
},
updateOptionsPricePreview: function() {
var optionsPriceDropdown = document.getElementById("optionsPriceDropdown");
var options = YUD.getElementsByClassName("optionRow", "p", "dropdownPriceSection");
var optionNames = YUD.getElementsByClassName("ddpOptionName", "input", "dropdownPriceSection");
var optionPrices = YUD.getElementsByClassName("ddpOptionPrice", "input", "dropdownPriceSection");
var optionFrequency = YUD.getElementsByClassName("ddpOptionFrequency", "select", "dropdownPriceSection");
var optionsLen = options.length;
optionsPriceDropdown.length = 0;
for (var i = 0; i < optionsLen; i++) {
var opt = document.createElement("option");
optionsPriceDropdown.options[i] = opt;
if (BD_STEP1.activeButtonType == 'subscriptions') {
var curr = document.getElementById('subscriptionBillingAmountCurrency');
BD_STEP1.currencySymbol = curr.options[curr.selectedIndex].title;
BD_STEP1.currencyCode = curr.options[curr.selectedIndex].value;
var frequencyTxt = document.getElementById('frequencyTxt');
if (frequencyTxt.childNodes[0].nodeType == '1') {
frequencyTxt = frequencyTxt.childNodes[0].innerHTML;
} else {
frequencyTxt = frequencyTxt.innerHTML;
}
optionsPriceDropdown.options[i].text = optionNames[i].value + " - " + ((optionPrices[i].value == null || optionPrices[i].value == "") ? "$ x.xx" + " " + frequencyTxt : (BD_STEP1.currencySymbol + optionPrices[i].value + ' ' + BD_STEP1.currencyCode + ' ' + optionFrequency[i].options[optionFrequency[i].selectedIndex].text));
} else {
var curr = document.getElementById('BillingAmountCurrency');
BD_STEP1.currencySymbol = curr.options[curr.selectedIndex].title;
BD_STEP1.currencyCode = curr.options[curr.selectedIndex].value;
optionsPriceDropdown.options[i].text = optionNames[i].value + " " + ((optionPrices[i].value == null || optionPrices[i].value == "") ? "$x.xx " + BD_STEP1.currencyCode : BD_STEP1.currencySymbol + optionPrices[i].value + ' ' + BD_STEP1.currencyCode);
}
}
var ddTitle = document.getElementById("dropdownPriceTitle").value;
ddTitle = BD_CBUTTON.escapeText(ddTitle);
document.getElementById("previewDropdownPriceTitle").innerHTML = ddTitle;
},
displayAddOptionPriceLink: function() {
var options = YUD.getElementsByClassName("optionRow", "p", "dropdownPriceSection");
var addOptionPrice = document.getElementById("addOptionPrice");
BD_CBUTTON.numOptionsPrice = options.length;
if (BD_CBUTTON.numOptionsPrice < 10) {
addOptionPrice.innerHTML = document.getElementById("addOptionStr").value;
wHideShow.show(addOptionPrice);
} else {
wHideShow.hide(addOptionPrice);
}
},
createDropdownPriceStructure: function() {
BD_CBUTTON.ddPriceStructure = new Object;
var options = YUD.getElementsByClassName("optionRow", "p", "dropdownPriceSection");
var optionsLen = options.length;
var optionNames = YUD.getElementsByClassName("ddpOptionName", "input", "dropdownPriceSection");
var optionPrices = YUD.getElementsByClassName("ddpOptionPrice", "input", "dropdownPriceSection");
var buttonType = document.getElementById('buttonType');
var activeButtonType = buttonType.options[buttonType.selectedIndex].value;
var optionFrequency = YUD.getElementsByClassName("ddpOptionFrequency", "select", "dropdownPriceSection");
var optionCurrencies = YUD.getElementsByClassName("ddpOptionCurrency", "", "dropdownPriceSection");
if (optionsLen != 0) {
var temp = new Array();
for (var j = 0; j < optionsLen; j++) {
var optionObj = new Object;
optionObj.optionName = optionNames[j].value;
optionObj.optionPrice = optionPrices[j].value;
optionObj.optionFrequency = optionFrequency[j].options[optionFrequency[j].selectedIndex].text;
optionObj.optionCurrency = optionCurrencies[j].value;
optionObj.optionId = options[j].id;
temp[j] = optionObj;
BD_CBUTTON.numOptionsPrice++;
}
var dropdownObj = {
title: document.getElementById("dropdownPriceTitle").value,
options: temp
};
};
BD_CBUTTON.ddPriceStructure = dropdownObj;
},
saveDropdown: function(e) {
YUE.preventDefault(e);
switch (this.parentNode.parentNode.id) {
case "dropdownSection1":
var ddNum = 1;
break;
case "dropdownSection2":
var ddNum = 2;
break;
case "dropdownSection3":
var ddNum = 3;
break;
case "dropdownSection4":
var ddNum = 4;
break;
}
BD_CBUTTON.activeDropdown = ddNum;
BD_CBUTTON.saveOption();
},
saveOption: function() {
var dropdownSection = document.getElementById("dropdownSection" + BD_CBUTTON.activeDropdown);
var savedDropdownSection = document.getElementById("savedDropdownSection" + BD_CBUTTON.activeDropdown);
var savedDropdown = document.getElementById("savedDropdown" + BD_CBUTTON.activeDropdown);
var dropdownTitle = YUD.getElementsByClassName("dropdownTitle", "input", "dropdownSection" + BD_CBUTTON.activeDropdown)[0];
var previewDropdownTitle = YUD.getElementsByClassName("previewDropdownTitle", "label", "previewDropdownSection" + BD_CBUTTON.activeDropdown)[0];
var addNewDropdownSection = document.getElementById("addNewDropdownSection");
var dropdown = document.getElementById("dropdown");
var addOption = document.getElementById("addOption" + BD_CBUTTON.activeDropdown);
var options = YUD.getElementsByClassName("dropdown", "p", "dropdownSection" + BD_CBUTTON.activeDropdown);
var optionNames = YUD.getElementsByClassName("ddOptionName", "input", "dropdownSection" + BD_CBUTTON.activeDropdown);
var optionsContainer = document.getElementById("optionsContainer" + BD_CBUTTON.activeDropdown);
var optionsLen = options.length;
for (var i = 0; i < optionsLen; i++) {
if (optionNames[i].value == null || optionNames[i].value == "") {
optionsContainer.removeChild(optionNames[i].parentNode);
}
}
var options = YUD.getElementsByClassName("dropdown", "p", "dropdownSection" + BD_CBUTTON.activeDropdown);
if (options.length == 0) {
dropdownTitle.value = "";
}
wHideShow.hide(dropdownSection);
BD_CBUTTON.updateOptionsPreview();
BD_CBUTTON.updateSavedOptions();
BD_CBUTTON.displayAddOptionLink();
BD_CBUTTON.getDropdownCount();
if (BD_CBUTTON.activeDropdown == 0) {
wHideShow.hide(addNewDropdownSection);
if (dropdown.checked) {
dropdown.click();
}
for (var i = 0; i < 3; i++) {
var parent = document.createElement("p");
parent.setAttribute("class", "optionRow dropdown col-md-9");
parent.setAttribute("className", "optionRow dropdown col-md-9");
var optionName = document.createElement("input");
optionName.setAttribute("type", "text");
var nm = "dd" + i + "_option_name";
optionName.setAttribute("name", nm);
optionName.setAttribute("class", "ddOptionName text form-control");
optionName.setAttribute("className", "ddOptionName text form-control");
optionName.setAttribute("value", document.getElementById("optionStr").value + " " + (i + 1));
optionName.setAttribute("maxlength", "64");
parent.appendChild(optionName);
optionsContainer.appendChild(parent);
}
} else {
BD_CBUTTON.displayAddDropdownLink();
}
BD_CBUTTON.buildDropdownInfo(0);
BD_CBUTTON.createDropdownStructure();
},
cancelOption: function(e) {
YUE.preventDefault(e);
switch (this.parentNode.parentNode.id) {
case "dropdownSection1":
var ddNum = 1;
break;
case "dropdownSection2":
var ddNum = 2;
break;
case "dropdownSection3":
var ddNum = 3;
break;
case "dropdownSection4":
var ddNum = 4;
break;
}
var dropdownSection = document.getElementById("dropdownSection" + ddNum);
var previewDropdownSection = document.getElementById("previewDropdownSection" + ddNum);
var savedDropdownSection = document.getElementById("savedDropdownSection" + ddNum);
var savedDropdown = document.getElementById("savedDropdown" + ddNum);
var addNewDropdownSection = document.getElementById("addNewDropdownSection");
var optionsContainer = document.getElementById("optionsContainer" + ddNum);
var options = YUD.getElementsByClassName("dropdown", "p", "dropdownSection" + ddNum);
var optionsLen = options.length;
var dropdown = document.getElementById("dropdown");
for (var a = 0; a < optionsLen; a++) {
optionsContainer.removeChild(options[a]);
}
YUD.getElementsByClassName("dropdownTitle", "input", dropdownSection)[0].value = BD_CBUTTON.ddStructure[ddNum - 1].title;
var tempOptions = BD_CBUTTON.ddStructure[ddNum - 1].options;
var tempOptionsLen = tempOptions.length;
for (var j = 0; j < tempOptionsLen; j++) {
var parent = document.createElement("p");
parent.setAttribute("class", "optionRow dropdown col-md-9");
parent.setAttribute("className", "optionRow dropdown col-md-9");
parent.setAttribute("id", tempOptions[j].optionId);
var optionName = document.createElement("input");
optionName.setAttribute("type", "text");
var nm = "dd" + (ddNum) + "_option_name";
optionName.setAttribute("name", nm);
optionName.setAttribute("class", "ddOptionName text form-control");
optionName.setAttribute("className", "ddOptionName text form-control");
optionName.setAttribute("value", tempOptions[j].optionName);
optionName.setAttribute("maxlength", "64");
parent.appendChild(optionName);
optionsContainer.appendChild(parent);
}
if (dropdownSection) {
wHideShow.hide(dropdownSection);
}
if (BD_CBUTTON.ddStructure[ddNum - 1].saved) {
if (previewDropdownSection) {
(savedDropdown.innerHTML == "") ? wHideShow.hide(previewDropdownSection): wHideShow.show(previewDropdownSection);
}
if (savedDropdownSection) {
(savedDropdown.innerHTML == "") ? wHideShow.hide(savedDropdownSection): wHideShow.show(savedDropdownSection);
}
} else {
if (previewDropdownSection) {
wHideShow.hide(previewDropdownSection);
}
if (savedDropdownSection) {
wHideShow.hide(savedDropdownSection);
}
}
BD_CBUTTON.getDropdownCount();
if (BD_CBUTTON.activeDropdown == 0) {
wHideShow.hide(addNewDropdownSection);
if (dropdown.checked) {
dropdown.click();
}
} else {
BD_CBUTTON.displayAddDropdownLink();
}
},
displayAddOptionLink: function() {
var options = YUD.getElementsByClassName("dropdown", "p", "dropdownSection" + BD_CBUTTON.activeDropdown);
var addOption = YUD.getElementsByClassName("addOption", "", "dropdownSection" + BD_CBUTTON.activeDropdown)[0];
switch (BD_CBUTTON.activeDropdown) {
case 1:
BD_CBUTTON.numOptions1 = options.length;
if (BD_CBUTTON.numOptions1 < 10) {
addOption.innerHTML = document.getElementById("addOptionStr").value + " " + (BD_CBUTTON.numOptions1 + 1);
wHideShow.show(addOption);
} else {
wHideShow.hide(addOption);
}
break;
case 2:
BD_CBUTTON.numOptions2 = options.length;
if (BD_CBUTTON.numOptions2 < 10) {
addOption.innerHTML = document.getElementById("addOptionStr").value + " " + (BD_CBUTTON.numOptions2 + 1);
wHideShow.show(addOption);
} else {
wHideShow.hide(addOption);
}
break;
case 3:
BD_CBUTTON.numOptions3 = options.length;
if (BD_CBUTTON.numOptions3 < 10) {
addOption.innerHTML = document.getElementById("addOptionStr").value + " " + (BD_CBUTTON.numOptions3 + 1);
wHideShow.show(addOption);
} else {
wHideShow.hide(addOption);
}
break;
case 4:
BD_CBUTTON.numOptions4 = options.length;
if (BD_CBUTTON.numOptions4 < 10) {
addOption.innerHTML = document.getElementById("addOptionStr").value + " " + (BD_CBUTTON.numOptions4 + 1);
wHideShow.show(addOption);
} else {
wHideShow.hide(addOption);
}
break;
}
},
addNewOption: function(e) {
YUE.preventDefault(e);
switch (this.parentNode.parentNode.id) {
case "dropdownSection1":
var ddNum = 1;
break;
case "dropdownSection2":
var ddNum = 2;
break;
case "dropdownSection3":
var ddNum = 3;
break;
case "dropdownSection4":
var ddNum = 4;
break;
}
BD_CBUTTON.activeDropdown = ddNum;
var optionsContainer = document.getElementById("optionsContainer" + BD_CBUTTON.activeDropdown);
BD_CBUTTON.createNewOption(optionsContainer);
},
createNewOption: function(optionsContainer) {
var parent = document.createElement("p");
parent.setAttribute("class", "optionRow dropdown col-md-9");
parent.setAttribute("className", "optionRow dropdown col-md-9");
var optionName = document.createElement("input");
optionName.setAttribute("type", "text");
var nm = "dd" + BD_CBUTTON.activeDropdown + "_option_name";
optionName.setAttribute("name", nm);
optionName.setAttribute("class", "ddOptionName text form-control");
optionName.setAttribute("className", "ddOptionName text form-control");
optionName.setAttribute("maxlength", "64");
switch (BD_CBUTTON.activeDropdown) {
case 1:
if (BD_CBUTTON.numOptions1 < 10) {
BD_CBUTTON.numOptions1++;
optionName.setAttribute("value", document.getElementById("optionStr").value + " " + BD_CBUTTON.numOptions1);
parent.appendChild(optionName);
optionsContainer.appendChild(parent);
}
break;
case 2:
if (BD_CBUTTON.numOptions2 < 10) {
BD_CBUTTON.numOptions2++;
optionName.setAttribute("value", document.getElementById("optionStr").value + " " + BD_CBUTTON.numOptions2);
parent.appendChild(optionName);
optionsContainer.appendChild(parent);
}
break;
case 3:
if (BD_CBUTTON.numOptions3 < 10) {
BD_CBUTTON.numOptions3++;
optionName.setAttribute("value", document.getElementById("optionStr").value + " " + BD_CBUTTON.numOptions3);
parent.appendChild(optionName);
optionsContainer.appendChild(parent);
}
break;
case 4:
if (BD_CBUTTON.numOptions4 < 10) {
BD_CBUTTON.numOptions4++;
optionName.setAttribute("value", document.getElementById("optionStr").value + " " + BD_CBUTTON.numOptions4);
parent.appendChild(optionName);
optionsContainer.appendChild(parent);
}
break;
}
BD_CBUTTON.displayAddOptionLink();
},
editDropdown: function(e) {
YUE.preventDefault(e);
switch (this.parentNode.parentNode.id) {
case "savedDropdownSection1":
var ddNum = 1;
break;
case "savedDropdownSection2":
var ddNum = 2;
break;
case "savedDropdownSection3":
var ddNum = 3;
break;
case "savedDropdownSection4":
var ddNum = 4;
break;
}
var dropdownSection = document.getElementById("dropdownSection" + ddNum);
var previewDropdownSection = document.getElementById("previewDropdownSection" + ddNum);
var savedDropdownSection = document.getElementById("savedDropdownSection" + ddNum);
var addNewDropdownSection = document.getElementById("addNewDropdownSection");
BD_CBUTTON.activeDropdown = ddNum;
if (dropdownSection) {
wHideShow.show(dropdownSection);
var options = YUD.getElementsByClassName("dropdown", "p", "dropdownSection" + ddNum);
}
if (previewDropdownSection) {
wHideShow.show(previewDropdownSection);
}
if (savedDropdownSection) {
wHideShow.hide(savedDropdownSection);
}
if (addNewDropdownSection) {
wHideShow.hide(addNewDropdownSection);
}
BD_CBUTTON.displayAddOptionLink();
},
deleteDropdown: function(e) {
YUE.preventDefault(e);
switch (this.parentNode.parentNode.id) {
case "savedDropdownSection1":
var ddNum = 1;
break;
case "savedDropdownSection2":
var ddNum = 2;
break;
case "savedDropdownSection3":
var ddNum = 3;
break;
case "savedDropdownSection4":
var ddNum = 4;
break;
}
var dropdownSection = document.getElementById("dropdownSection" + ddNum);
var previewDropdownSection = document.getElementById("previewDropdownSection" + ddNum);
var savedDropdownSection = document.getElementById("savedDropdownSection" + ddNum);
var addNewDropdownSection = document.getElementById("addNewDropdownSection");
var dropdown = document.getElementById("dropdown");
var ddStructureLen = BD_CBUTTON.ddStructure.length + 1;
for (var i = 1; i < ddStructureLen; i++) {
if (i == ddNum) {
var dropdownSection = document.getElementById("dropdownSection" + i);
var optionsContainer = document.getElementById("optionsContainer" + i);
var options = YUD.getElementsByClassName("dropdown", "p", "dropdownSection" + i);
var optionsLen = options.length;
for (var aa = 0; aa < optionsLen; aa++) {
optionsContainer.removeChild(options[aa]);
}
YUD.getElementsByClassName("dropdownTitle", "input", "dropdownSection" + i)[0].value = "";
BD_CBUTTON.ddStructure.splice(i - 1, 1);
}
}
if (dropdownSection) {
wHideShow.hide(dropdownSection);
}
if (previewDropdownSection) {
wHideShow.hide(previewDropdownSection);
}
if (savedDropdownSection) {
wHideShow.hide(savedDropdownSection);
}
BD_CBUTTON.createDropdownStructure();
BD_CBUTTON.recreateDropdownSection();
BD_CBUTTON.recreateSavedSection();
BD_CBUTTON.addAllDropdowns();
BD_CBUTTON.createDropdownStructure(ddNum);
BD_CBUTTON.getDropdownCount();
if (BD_CBUTTON.activeDropdown == 0) {
wHideShow.hide(addNewDropdownSection);
if (dropdown.checked) {
dropdown.click();
}
} else {
BD_CBUTTON.displayAddDropdownLink();
}
BD_CBUTTON.buildDropdownInfo(ddNum);
for (var i = 1; i <= 4; i++) {
var savedDropdownSection = document.getElementById('savedDropdownSection' + i);
if (!YUD.hasClass(savedDropdownSection, "opened")) {
var dropdownSection = document.getElementById("dropdownSection" + i);
var inputs = dropdownSection.getElementsByTagName("input");
var inputsLen = inputs.length;
for (var j = 0; j < inputsLen; j++) {
inputs[j].disabled = true;
}
}
}
},
recreateDropdownSection: function() {
var ddStructureLen = BD_CBUTTON.ddStructure.length + 1;
for (var i = 1; i < ddStructureLen; i++) {
var dropdownSection = document.getElementById("dropdownSection" + i);
var optionsContainer = document.getElementById("optionsContainer" + i);
var options = YUD.getElementsByClassName("dropdown", "p", "dropdownSection" + i);
var optionsLen = options.length;
for (var a = 0; a < optionsLen; a++) {
optionsContainer.removeChild(options[a]);
}
wHideShow.hide(dropdownSection);
YUD.getElementsByClassName("dropdownTitle", "input", dropdownSection)[0].value = BD_CBUTTON.ddStructure[i - 1].title;
var tempOptions = BD_CBUTTON.ddStructure[i - 1].options;
var tempOptionsLen = tempOptions.length;
for (var j = 0; j < tempOptionsLen; j++) {
var parent = document.createElement("p");
parent.setAttribute("class", "optionRow dropdown col-md-9");
parent.setAttribute("className", "optionRow dropdown col-md-9");
parent.setAttribute("id", tempOptions[j].optionId);
var optionName = document.createElement("input");
optionName.setAttribute("type", "text");
var nm = "dd" + i + "_option_name";
optionName.setAttribute("name", nm);
optionName.setAttribute("class", "ddOptionName text form-control");
optionName.setAttribute("className", "ddOptionName text form-control");
optionName.setAttribute("value", tempOptions[j].optionName);
optionName.setAttribute("maxlength", "64");
parent.appendChild(optionName);
optionsContainer.appendChild(parent);
}
}
},
updateSavedOptions: function(ddNum) {
var savedDropdownSection = document.getElementById("savedDropdownSection" + BD_CBUTTON.activeDropdown);
var savedDropdown = document.getElementById("savedDropdown" + BD_CBUTTON.activeDropdown);
var dropdownTitle = YUD.getElementsByClassName("dropdownTitle", "input", "dropdownSection" + BD_CBUTTON.activeDropdown)[0];
var previewDropdownTitle = YUD.getElementsByClassName("previewDropdownTitle", "label", "previewDropdownSection" + BD_CBUTTON.activeDropdown)[0];
var options = YUD.getElementsByClassName("dropdown", "p", "dropdownSection" + BD_CBUTTON.activeDropdown);
var optionNames = YUD.getElementsByClassName("ddOptionName", "input", "dropdownSection" + BD_CBUTTON.activeDropdown);
savedDropdown.innerHTML = "";
if (dropdownTitle.value != "") {
savedDropdown.innerHTML = previewDropdownTitle.innerHTML + ": ";
}
options = YUD.getElementsByClassName("dropdown", "p", "dropdownSection" + BD_CBUTTON.activeDropdown);
optionNames = YUD.getElementsByClassName("ddOptionName", "input", "dropdownSection" + BD_CBUTTON.activeDropdown);
var optionsLen = options.length;
if (optionsLen != 0) {
for (var i = 0; i < optionsLen; i++) {
var optName = optionNames[i].value;
optName = BD_CBUTTON.escapeText(optName);
if (i != 0) {
if (optName != "") {
document.getElementById("savedDropdown" + BD_CBUTTON.activeDropdown).innerHTML = document.getElementById("savedDropdown" + BD_CBUTTON.activeDropdown).innerHTML + ", ";
}
}
document.getElementById("savedDropdown" + BD_CBUTTON.activeDropdown).innerHTML = document.getElementById("savedDropdown" + BD_CBUTTON.activeDropdown).innerHTML + optName;
}
wHideShow.show(savedDropdownSection);
}
},
updateOptionsPreview: function() {
var optionsDropdown = document.getElementById("optionsDropdown" + BD_CBUTTON.activeDropdown);
var options = YUD.getElementsByClassName("dropdown", "p", "dropdownSection" + BD_CBUTTON.activeDropdown);
var optionNames = YUD.getElementsByClassName("ddOptionName", "input", "dropdownSection" + BD_CBUTTON.activeDropdown);
var dropdownTitle = YUD.getElementsByClassName("dropdownTitle", "input", "dropdownSection" + BD_CBUTTON.activeDropdown)[0];
var previewDropdownTitle = YUD.getElementsByClassName("previewDropdownTitle", "label", "previewDropdownSection" + BD_CBUTTON.activeDropdown)[0];
var previewDropdownSection = document.getElementById("previewDropdownSection" + BD_CBUTTON.activeDropdown);
var optionsLen = options.length;
if (optionsLen == 0) {
wHideShow.hide(previewDropdownSection);
} else {
optionsDropdown.length = 0;
for (var i = 0; i < optionsLen; i++) {
if (optionNames[i].value != null && optionNames[i].value != "") {
var opt = document.createElement("option");
optionsDropdown.options[i] = opt;
optionsDropdown.options[i].text = optionNames[i].value;
}
}
previewDropdownTitle.innerHTML = BD_CBUTTON.escapeText(dropdownTitle.value);
}
},
displayAddDropdownLink: function() {
BD_CBUTTON.getDropdownCount();
var addNewDropdownSection = document.getElementById("addNewDropdownSection");
if (addNewDropdownSection) {
if (BD_CBUTTON.activeDropdown != 4) {
var dds = YUD.getElementsByClassName("dropdownSection");
var ddsLen = dds.length;
var ddsCnt = 0;
for (var i = 0; i < ddsLen; i++) {
if (YUD.hasClass(dds[i], "opened")) ddsCnt++;
}
if (ddsCnt == 0) {
wHideShow.show(addNewDropdownSection);
}
} else {
wHideShow.hide(addNewDropdownSection);
}
}
},
addNewDropdown: function(e) {
YUE.preventDefault(e);
BD_CBUTTON.getDropdownCount();
BD_CBUTTON.numDropdowns++;
BD_CBUTTON.activeDropdown++;
var dropdownSection = document.getElementById("dropdownSection" + BD_CBUTTON.activeDropdown);
var previewDropdownSection = document.getElementById("previewDropdownSection" + BD_CBUTTON.activeDropdown);
var optionsContainer = document.getElementById("optionsContainer" + BD_CBUTTON.activeDropdown);
if (dropdownSection) {
var allInputs = dropdownSection.getElementsByTagName("input");
var allInputsLen = allInputs.length;
if (allInputsLen <= 2) {
for (var i = 0; i < 3; i++) {
var parent = document.createElement("p");
parent.setAttribute("class", "optionRow dropdown col-md-9");
parent.setAttribute("className", "optionRow dropdown col-md-9");
var optionName = document.createElement("input");
optionName.setAttribute("type", "text");
var nm = "dd" + i + "_option_name";
optionName.setAttribute("name", nm);
optionName.setAttribute("class", "ddOptionName text form-control");
optionName.setAttribute("className", "ddOptionName text form-control");
optionName.setAttribute("value", document.getElementById("optionStr").value + " " + (i + 1));
optionName.setAttribute("maxlength", "64");
parent.appendChild(optionName);
optionsContainer.appendChild(parent);
}
BD_CBUTTON.createDropdownStructure();
}
for (var i = 0; i < allInputsLen; i++) {
allInputs[i].disabled = false;
}
wHideShow.show(dropdownSection);
}
if (previewDropdownSection) {
wHideShow.show(previewDropdownSection);
}
BD_CBUTTON.displayAddOptionLink();
var addNewDropdownSection = document.getElementById("addNewDropdownSection");
if (addNewDropdownSection) {
wHideShow.hide(addNewDropdownSection);
}
},
createDropdownStructure: function() {
BD_CBUTTON.ddStructure = new Array();
var count = 1;
for (var i = 1; i < 5; i++) {
var options = YUD.getElementsByClassName("optionRow", "p", "dropdownSection" + i);
var optionsLen = options.length;
var optionNames = YUD.getElementsByClassName("ddOptionName", "input", "dropdownSection" + i);
var dropdownSection = document.getElementById("dropdownSection" + i);
var savedDropdownSection = document.getElementById("savedDropdownSection" + i);
if (optionsLen != 0) {
var temp = new Array();
for (var j = 0; j < optionsLen; j++) {
var optionObj = new Object;
optionObj.optionName = optionNames[j].value;
optionObj.optionId = options[j].id;
temp[j] = optionObj;
}
var dropdownObj = {
ddNum: count,
title: YUD.getElementsByClassName("dropdownTitle", "input", "dropdownSection" + i)[0].value,
options: temp,
saved: ((YUD.hasClass(savedDropdownSection, "opened") ? true : false) || (YUD.hasClass(dropdownSection, "opened") ? true : false))
};
BD_CBUTTON.ddStructure.push(dropdownObj);
count++;
}
}
},
recreateSavedSection: function() {
var ddStructureLen = BD_CBUTTON.ddStructure.length;
for (var i = 0; i < ddStructureLen; i++) {
BD_CBUTTON.recreateOptionsPreview(i + 1);
if (BD_CBUTTON.ddStructure[i].saved) {
BD_CBUTTON.recreateSavedOptions(i, i + 1);
} else {
if (!(YUD.hasClass(document.getElementById("dropdownSection" + (i + 1)), "opened"))) {
wHideShow.hide(document.getElementById("savedDropdownSection" + (i + 1)));
wHideShow.hide(document.getElementById("previewDropdownSection" + (i + 1)));
}
}
}
for (var i = BD_CBUTTON.ddStructure.length; i < 4; i++) {
BD_CBUTTON.recreateOptionsPreview(i + 1);
wHideShow.hide(document.getElementById("savedDropdownSection" + (i + 1)));
wHideShow.hide(document.getElementById("previewDropdownSection" + (i + 1)));
}
},
recreateSavedOptions: function(ddNum, ddActive) {
var savedDropdownSection = document.getElementById("savedDropdownSection" + ddActive);
var savedDropdown = document.getElementById("savedDropdown" + ddActive);
var dropdownTitle = YUD.getElementsByClassName("dropdownTitle", "input", "dropdownSection" + ddActive)[0];
savedDropdown.innerHTML = "";
if (dropdownTitle.value != "") {
savedDropdown.innerHTML = BD_CBUTTON.escapeText(BD_CBUTTON.ddStructure[ddNum].title) + ": ";
}
options = BD_CBUTTON.ddStructure[ddNum].options;
var optionsLen = options.length;
for (var i = 0; i < optionsLen; i++) {
if (i != 0) {
if (options[i] != "") {
savedDropdown.innerHTML = savedDropdown.innerHTML + ", ";
}
}
savedDropdown.innerHTML = savedDropdown.innerHTML + BD_CBUTTON.escapeText(options[i].optionName);
}
wHideShow.show(savedDropdownSection);
},
recreateOptionsPreview: function(ddActive) {
var optionsDropdown = document.getElementById("optionsDropdown" + ddActive);
var options = YUD.getElementsByClassName("dropdown", "p", "dropdownSection" + ddActive);
var optionNames = YUD.getElementsByClassName("ddOptionName", "input", "dropdownSection" + ddActive);
var dropdownTitle = YUD.getElementsByClassName("dropdownTitle", "input", "dropdownSection" + ddActive)[0];
var previewDropdownTitle = YUD.getElementsByClassName("previewDropdownTitle", "label", "previewDropdownSection" + ddActive)[0];
var previewDropdownSection = document.getElementById("previewDropdownSection" + ddActive);
var optionsLen = options.length;
optionsDropdown.length = 0;
for (var i = 0; i < optionsLen; i++) {
if (optionNames[i].value != null && optionNames[i].value != "") {
var opt = document.createElement("option");
optionsDropdown.options[i] = opt;
optionsDropdown.options[i].text = optionNames[i].value;
}
}
previewDropdownTitle.innerHTML = BD_CBUTTON.escapeText(dropdownTitle.value);
wHideShow.show(previewDropdownSection);
},
addAllDropdowns: function() {
var ddStructureLen = BD_CBUTTON.ddStructure.length + 1;
for (var i = ddStructureLen; i < 5; i++) {
var dropdownSection = document.getElementById("dropdownSection" + i);
var optionsContainer = document.getElementById("optionsContainer" + i);
var options = YUD.getElementsByClassName("dropdown", "p", "dropdownSection" + i);
var optionsLen = options.length;
for (var a = 0; a < optionsLen; a++) {
optionsContainer.removeChild(options[a]);
}
YUD.getElementsByClassName("dropdownTitle", "input", dropdownSection)[0].value = "";
for (var j = 1; j < 4; j++) {
var parent = document.createElement("p");
parent.setAttribute("class", "optionRow dropdown col-md-9");
parent.setAttribute("className", "optionRow dropdown col-md-9");
var optionName = document.createElement("input");
optionName.setAttribute("type", "text");
var nm = "dd" + i + "_option_name";
optionName.setAttribute("name", nm);
optionName.setAttribute("class", "ddOptionName text form-control");
optionName.setAttribute("className", "ddOptionName text form-control");
optionName.setAttribute("value", document.getElementById("optionStr").value + " " + j);
optionName.setAttribute("maxlength", "64");
parent.appendChild(optionName);
optionsContainer.appendChild(parent);
}
var allInputs = dropdownSection.getElementsByTagName("input");
var allInputsLen = allInputs.length;
for (var i = 0; i < allInputsLen; i++) {
allInputs[i].disabled = true;
}
wHideShow.hide(dropdownSection);
}
},
getDropdownCount: function() {
var dds = YUD.getElementsByClassName("dropdownSection");
var ddsLen = dds.length;
var ddsCnt = 0;
var savedDds = YUD.getElementsByClassName("savedDropdownSection");
var savedDdsLen = savedDds.length;
var savedDdsCnt = 0;
for (var i = 0; i < ddsLen; i++) {
if (YUD.hasClass(dds[i], "opened")) ddsCnt++;
}
for (var i = 0; i < savedDdsLen; i++) {
if (YUD.hasClass(savedDds[i], "opened")) savedDdsCnt++;
}
BD_CBUTTON.activeDropdown = ddsCnt + savedDdsCnt;
},
saveTextfield: function(e) {
YUE.preventDefault(e);
switch (this.parentNode.parentNode.id) {
case "textfieldSection1":
var tfNum = 1;
break;
case "textfieldSection2":
var tfNum = 2;
break;
}
BD_CBUTTON.activeTextfield = tfNum;
var previewTextfieldTitle = document.getElementById("previewTextfieldTitle" + BD_CBUTTON.activeTextfield);
var textfieldSection = document.getElementById("textfieldSection" + BD_CBUTTON.activeTextfield);
var savedTextfieldSection = document.getElementById("savedTextfieldSection" + BD_CBUTTON.activeTextfield);
var savedTextfield = YUD.getElementsByClassName("savedTextfield", "label", "savedTextfieldSection" + BD_CBUTTON.activeTextfield)[0];
previewTextfieldTitle.innerHTML = BD_CBUTTON.escapeText(document.getElementById("textfieldTitle" + BD_CBUTTON.activeTextfield).value);
wHideShow.hide(textfieldSection);
savedTextfield.innerHTML = BD_CBUTTON.escapeText(document.getElementById("textfieldTitle" + BD_CBUTTON.activeTextfield).value);
wHideShow.show(savedTextfieldSection);
BD_CBUTTON.getTextfieldCount();
if (BD_CBUTTON.activeTextfield == 0) {
wHideShow.hide(addNewTextfieldSection);
if (textfield.checked) {
textfield.click();
}
} else {
BD_CBUTTON.displayAddTextfieldLink();
}
BD_CBUTTON.createTextfieldStructure();
},
cancelTextfield: function(e) {
YUE.preventDefault(e);
switch (this.parentNode.parentNode.id) {
case "textfieldSection1":
var tfNum = 1;
break;
case "textfieldSection2":
var tfNum = 2;
break;
}
var textfieldSection = document.getElementById("textfieldSection" + tfNum);
var previewTextfieldSection = document.getElementById("previewTextfieldSection" + tfNum);
var savedTextfieldSection = document.getElementById("savedTextfieldSection" + tfNum);
var savedTextfield = document.getElementById("savedTextfield" + tfNum);
var addNewTextfieldSection = document.getElementById("addNewTextfieldSection");
var textfield = document.getElementById("textfield");
document.getElementById("textfieldTitle" + tfNum).value = BD_CBUTTON.tfStructure[tfNum - 1];
if (textfieldSection) {
wHideShow.hide(textfieldSection);
var allInputs = textfieldSection.getElementsByTagName("input");
var allInputsLen = allInputs.length;
for (var i = 0; i < allInputsLen; i++) {
allInputs[i].disabled = true;
}
}
if (previewTextfieldSection) {
(savedTextfield.innerHTML == "") ? wHideShow.hide(previewTextfieldSection): wHideShow.show(previewTextfieldSection);
}
if (savedTextfieldSection) {
(savedTextfield.innerHTML == "") ? wHideShow.hide(savedTextfieldSection): wHideShow.show(savedTextfieldSection);
}
BD_CBUTTON.getTextfieldCount();
if (BD_CBUTTON.activeTextfield == 0) {
wHideShow.hide(addNewTextfieldSection);
if (textfield.checked) {
textfield.click();
}
} else {
BD_CBUTTON.displayAddTextfieldLink();
}
},
editTextfield: function(e) {
YUE.preventDefault(e);
switch (this.parentNode.parentNode.id) {
case "savedTextfieldSection1":
var tfNum = 1;
break;
case "savedTextfieldSection2":
var tfNum = 2;
break;
}
var textfieldSection = document.getElementById("textfieldSection" + tfNum);
var previewTextfieldSection = document.getElementById("previewTextfieldSection" + tfNum);
var savedTextfieldSection = document.getElementById("savedTextfieldSection" + tfNum);
BD_CBUTTON.activeTextfield = tfNum;
if (textfieldSection) {
wHideShow.show(textfieldSection);
var allInputs = textfieldSection.getElementsByTagName("input");
var allInputsLen = allInputs.length;
for (var i = 0; i < allInputsLen; i++) {
allInputs[i].disabled = false;
}
}
if (previewTextfieldSection) {
wHideShow.show(previewTextfieldSection);
}
if (savedTextfieldSection) {
wHideShow.hide(savedTextfieldSection);
}
var addNewTextfieldSection = document.getElementById("addNewTextfieldSection");
if (addNewTextfieldSection) {
wHideShow.hide(addNewTextfieldSection);
}
},
deleteTextfield: function(e) {
YUE.preventDefault(e);
switch (this.parentNode.parentNode.id) {
case "savedTextfieldSection1":
var tfNum = 1;
break;
case "savedTextfieldSection2":
var tfNum = 2;
break;
}
var textfieldSection = document.getElementById("textfieldSection" + tfNum);
var textfieldTitle = document.getElementById("textfieldTitle" + tfNum);
var previewTextfieldTitle = document.getElementById("previewTextfieldTitle" + tfNum);
var previewTextfieldSection = document.getElementById("previewTextfieldSection" + tfNum);
var savedTextfieldSection = document.getElementById("savedTextfieldSection" + tfNum);
var savedTextfield = document.getElementById("savedTextfield" + tfNum);
var addNewTextfieldSection = document.getElementById("addNewTextfieldSection");
var textfield = document.getElementById("textfield");
BD_CBUTTON.getTextfieldCount();
if (tfNum == 1 && BD_CBUTTON.activeTextfield == 2) {
var tmpTextfield = document.getElementById("textfieldTitle2");
var tmpTextfieldSection = document.getElementById("textfieldSection2");
var tmpPreviewTextfieldTitle = document.getElementById("previewTextfieldTitle2");
var tmpPreviewTextfieldSection = document.getElementById("previewTextfieldSection2");
var tmpSavedTextfieldSection = document.getElementById("savedTextfieldSection2");
var tmpSavedTextfield = document.getElementById("savedTextfield2");
if (tmpTextfield) {
textfieldTitle.value = tmpTextfield.value;
tmpTextfield.value = "";
if (tmpTextfieldSection) {
wHideShow.hide(tmpTextfieldSection);
var allInputs = tmpTextfieldSection.getElementsByTagName("input");
var allInputsLen = allInputs.length;
for (var i = 0; i < allInputsLen; i++) {
allInputs[i].disabled = true;
}
}
if (tmpPreviewTextfieldSection) {
tmpPreviewTextfieldTitle.innerHTML = document.getElementById("titleStr").value;
wHideShow.hide(tmpPreviewTextfieldSection);
}
if (tmpSavedTextfieldSection) {
tmpSavedTextfield.innerHTML = "";
wHideShow.hide(tmpSavedTextfieldSection);
}
previewTextfieldTitle.innerHTML = textfieldTitle.value;
savedTextfield.innerHTML = BD_CBUTTON.escapeText(textfieldTitle.value);
}
BD_CBUTTON.createTextfieldStructure();
} else {
if (textfieldSection) {
wHideShow.hide(textfieldSection);
textfieldTitle.value = "";
var allInputs = textfieldSection.getElementsByTagName("input");
var allInputsLen = allInputs.length;
for (var i = 0; i < allInputsLen; i++) {
allInputs[i].disabled = true;
}
previewTextfieldTitle.innerHTML = document.getElementById("titleStr").value;
}
if (previewTextfieldSection) {
wHideShow.hide(previewTextfieldSection);
}
if (savedTextfieldSection) {
savedTextfield.innerHTML = "";
wHideShow.hide(savedTextfieldSection);
}
}
BD_CBUTTON.getTextfieldCount();
if (BD_CBUTTON.activeTextfield == 0) {
wHideShow.hide(addNewTextfieldSection);
if (textfield.checked) {
textfield.click();
}
} else {
BD_CBUTTON.displayAddTextfieldLink();
}
},
displayAddTextfieldLink: function() {
BD_CBUTTON.getTextfieldCount();
var addNewTextfieldSection = document.getElementById("addNewTextfieldSection");
if (addNewTextfieldSection) {
if (BD_CBUTTON.activeTextfield != 2) {
var tfs = YUD.getElementsByClassName("textfieldSection");
var tfsLen = tfs.length;
var tfsCnt = 0;
for (var i = 0; i < tfsLen; i++) {
if (YUD.hasClass(tfs[i], "opened")) tfsCnt++;
}
if (tfsCnt == 0) {
wHideShow.show(addNewTextfieldSection);
}
} else {
wHideShow.hide(addNewTextfieldSection);
}
}
},
addNewTextfield: function(e) {
YUE.preventDefault(e);
BD_CBUTTON.getTextfieldCount();
BD_CBUTTON.numTextfields++;
BD_CBUTTON.activeTextfield++;
var textfieldSection = document.getElementById("textfieldSection" + BD_CBUTTON.activeTextfield);
var previewTextfieldSection = document.getElementById("previewTextfieldSection" + BD_CBUTTON.activeTextfield);
if (textfieldSection) {
var allInputs = textfieldSection.getElementsByTagName("input");
var allInputsLen = allInputs.length;
for (var i = 0; i < allInputsLen; i++) {
allInputs[i].disabled = false;
}
wHideShow.show(textfieldSection);
}
if (previewTextfieldSection) {
wHideShow.show(previewTextfieldSection);
}
BD_CBUTTON.createTextfieldStructure();
var addNewTextfieldSection = document.getElementById("addNewTextfieldSection");
if (addNewTextfieldSection) {
wHideShow.hide(addNewTextfieldSection);
}
},
createTextfieldStructure: function() {
BD_CBUTTON.tfStructure = new Array();
for (var i = 0; i < 2; i++) {
BD_CBUTTON.tfStructure[i] = document.getElementById("textfieldTitle" + (i + 1)).value;
}
},
getTextfieldCount: function() {
var tfs = YUD.getElementsByClassName("textfieldSection");
var tfsLen = tfs.length;
var tfsCnt = 0;
var savedTfs = YUD.getElementsByClassName("savedTextfieldSection");
var savedTfsLen = savedTfs.length;
var savedTfsCnt = 0;
for (var i = 0; i < tfsLen; i++) {
if (YUD.hasClass(tfs[i], "opened")) tfsCnt++;
}
for (var i = 0; i < savedTfsLen; i++) {
if (YUD.hasClass(savedTfs[i], "opened")) savedTfsCnt++;
}
BD_CBUTTON.activeTextfield = tfsCnt + savedTfsCnt;
},
updateCustomizeButtonSection: function(type, args) {
var locale = document.getElementById("langCode").value;
if (args[0].button_type) {
if (args[0].button_type == "services" || args[0].button_type == "products") {
BD_CBUTTON.buttonBasedChanges(args[0].button_type, args[0].sub_button_type, locale);
} else {
BD_CBUTTON.buttonBasedChanges(args[0].button_type, "", locale);
}
}
},
buttonBasedChanges: function(buttonType, subButtonType, langCode) {
var customizeButtonSection = YUD.getElementsByClassName("customizeButtonSection")[0];
var outerContainer = YUD.getElementsByClassName("outerContainer")[0];
var borderBox = YUD.getElementsByClassName("borderBox")[0];
var dropdownPrice = document.getElementById("dropdownPrice");
var dropdown = document.getElementById("dropdown");
var textfield = document.getElementById("textfield");
var addDropdownPrice = document.getElementById("addDropdownPrice");
var addDropdown = document.getElementById("addDropdown");
var dropDownLabelForSubscription = document.getElementById("dropDownLabelForSubscription");
var dropDownLabel = document.getElementById("dropDownLabel");
var addTextfield = document.getElementById("addTextfield");
var displayCcLogos = document.getElementById("displayCcLogos");
var textBuyNow = document.getElementById("textBuyNow");
var textSubscr = document.getElementById("textSubscr");
var displayCcLogos = document.getElementById("displayCcLogos");
var previewImage = document.getElementById("previewImage");
if (document.getElementById("paypalButton").checked) {
var previewImageSection = YUD.getElementsByClassName("previewImageSection")[0];
wHideShow.show(previewImageSection);
} else {
var previewCustomImageSection = YUD.getElementsByClassName("previewCustomImageSection")[0];
wHideShow.show(previewCustomImageSection);
}
if (dropdownPrice.checked) {
onPricePerOption.fire({
hideItemPrice: true,
disableItemPrice: false
});
} else {
onPricePerOption.fire({
hideItemPrice: false,
disableItemPrice: false
});
}
document.getElementById("buttonTextBuyNow").disabled = true;
document.getElementById("buttonTextSubscribe").disabled = true;
wHideShow.hide(textBuyNow);
wHideShow.hide(textSubscr);
BD_CBUTTON.buttonType = buttonType;
switch (buttonType) {
case "gift_certs":
if (YUD.hasClass(document.getElementById("buttonAppLink"), "expanded")) {
YUD.removeClass(borderBox, "heightFix");
} else {
YUD.addClass(borderBox, "heightFix");
}
YUD.setAttribute(outerContainer, 'id', 'sBox');
if (dropdownPrice.checked) {
dropdownPrice.click();
}
wHideShow.hide(addDropdownPrice);
if (dropdown.checked) {
dropdown.click();
}
wHideShow.hide(addDropdown);
wHideShow.hide(addDropdown);
if (textfield.checked) {
textfield.click();
}
wHideShow.hide(addTextfield);
wHideShow.show(displayCcLogos);
BD_CBUTTON.updateImage(langCode);
break;
case "subscriptions":
YUD.removeClass(customizeButtonSection, "heightFix");
YUD.removeClass(borderBox, "heightFix");
YUD.setAttribute(outerContainer, 'id', 'wideBox');
wHideShow.show(addDropdownPrice);
wHideShow.show(addDropdown);
wHideShow.hide(dropDownLabel);
wHideShow.show(dropDownLabelForSubscription);
BD_CBUTTON.getDropdownCount();
BD_CBUTTON.getTextfieldCount();
wHideShow.show(addDropdown);
wHideShow.show(addTextfield);
wHideShow.show(displayCcLogos);
document.getElementById("buttonTextBuyNow").disabled = true;
document.getElementById("buttonTextSubscribe").disabled = false;
wHideShow.show(textSubscr);
var buttonTextSubscribe = document.getElementById("buttonTextSubscribe");
BD_CBUTTON.buttonType = buttonTextSubscribe.options[buttonTextSubscribe.selectedIndex].value;
BD_CBUTTON.updateImage(langCode);
break;
case "donations":
if (YUD.hasClass(document.getElementById("buttonAppLink"), "expanded")) {
YUD.removeClass(borderBox, "heightFix");
} else {
YUD.addClass(borderBox, "heightFix");
}
YUD.setAttribute(outerContainer, 'id', 'sBox');
if (dropdownPrice.checked) {
dropdownPrice.click();
}
wHideShow.hide(addDropdownPrice);
if (dropdown.checked) {
dropdown.click();
}
wHideShow.hide(addDropdown);
if (textfield.checked) {
textfield.click();
}
wHideShow.hide(addTextfield);
wHideShow.show(displayCcLogos);
BD_CBUTTON.updateImage(langCode);
break;
case "services":
case "products":
YUD.removeClass(customizeButtonSection, "heightFix");
YUD.removeClass(borderBox, "heightFix");
YUD.setAttribute(outerContainer, 'id', 'sBox');
BD_CBUTTON.buttonType = subButtonType;
BD_CBUTTON.getDropdownCount();
BD_CBUTTON.getTextfieldCount();
wHideShow.show(addDropdownPrice);
wHideShow.show(addDropdown);
wHideShow.show(dropDownLabel);
wHideShow.hide(dropDownLabelForSubscription);
wHideShow.show(addTextfield);
wHideShow.show(displayCcLogos);
switch (subButtonType) {
case "buy_now":
document.getElementById("buttonTextBuyNow").disabled = false;
wHideShow.show(textBuyNow);
document.getElementById("buttonTextSubscribe").disabled = true;
var buttonTextBuyNow = document.getElementById("buttonTextBuyNow");
BD_CBUTTON.buttonType = buttonTextBuyNow.options[buttonTextBuyNow.selectedIndex].value;
break;
case "add_to_cart":
wHideShow.hide(displayCcLogos);
break;
}
BD_CBUTTON.updateImage(langCode);
break;
}
document.getElementById("buttonUrl").value = document.getElementById("previewImage").src;
},
displaySmallImage: function(e) {
var previewImage = document.getElementById("previewImage");
var ccLogos = document.getElementById("ccLogos");
var displayCcLogos = document.getElementById("displayCcLogos");
var locale = document.getElementById("langCode").value;
if (BD_CBUTTON.buttonType != "view_cart") {
if (imageUrls[locale]) {
if (this.checked) {
ccLogos.checked = false;
ccLogos.disabled = true;
switch (BD_CBUTTON.buttonType) {
case "gift_certs":
previewImage.src = imageUrls[locale].GiftCertificate.small;
break;
case "donations":
previewImage.src = imageUrls[locale].Donate.small;
break;
case "subscriptions":
previewImage.src = imageUrls[locale].Subscribe.small;
break;
case "buy_now":
previewImage.src = imageUrls[locale].BuyNow.small;
break;
case "pay_now":
previewImage.src = imageUrls[locale].PayNow.small;
break;
case "add_to_cart":
previewImage.src = imageUrls[locale].AddToCart.small;
break;
}
YUD.addClass(displayCcLogos, "inactiveChkBox");
} else {
switch (BD_CBUTTON.buttonType) {
case "gift_certs":
previewImage.src = imageUrls[locale].GiftCertificate.large;
break;
case "donations":
previewImage.src = imageUrls[locale].Donate.large;
break;
case "subscriptions":
previewImage.src = imageUrls[locale].Subscribe.large;
break;
case "buy_now":
previewImage.src = imageUrls[locale].BuyNow.large;
break;
case "pay_now":
previewImage.src = imageUrls[locale].PayNow.large;
break;
case "add_to_cart":
previewImage.src = imageUrls[locale].AddToCart.large;
break;
}
ccLogos.disabled = false;
YUD.removeClass(displayCcLogos, "inactiveChkBox");
}
}
}
},
displayCCImage: function(e) {
var previewImage = document.getElementById("previewImage");
var smallButton = document.getElementById("smallButton");
var flagInt = document.getElementById("flagInternational").disabled ? false : true;
var locale = flagInt ? "int" : document.getElementById("langCode").value;
if (imageUrls[locale]) {
if (this.checked) {
smallButton.checked = false;
switch (BD_CBUTTON.buttonType) {
case "gift_certs":
previewImage.src = imageUrls[locale].GiftCertificate.cc;
break;
case "donations":
previewImage.src = imageUrls[locale].Donate.cc;
break;
case "subscriptions":
previewImage.src = imageUrls[locale].Subscribe.cc;
break;
case "buy_now":
previewImage.src = imageUrls[locale].BuyNow.cc;
break;
case "pay_now":
previewImage.src = imageUrls[locale].PayNow.cc;
break;
}
} else {
switch (BD_CBUTTON.buttonType) {
case "gift_certs":
previewImage.src = imageUrls[locale].GiftCertificate.large;
break;
case "donations":
previewImage.src = imageUrls[locale].Donate.large;
break;
case "subscriptions":
previewImage.src = imageUrls[locale].Subscribe.large;
break;
case "buy_now":
previewImage.src = imageUrls[locale].BuyNow.large;
break;
case "pay_now":
previewImage.src = imageUrls[locale].PayNow.large;
break;
}
}
}
},
updateImageText: function() {
BD_CBUTTON.buttonType = this.options[this.selectedIndex].value;
BD_CBUTTON.updateImage(document.getElementById("langCode").value);
},
updateButtonCountry: function() {
var countryCode = document.getElementById("countryCode");
var langCode = document.getElementById("langCode");
var results = this.options[this.selectedIndex].value.split("_");
if (this.options[this.selectedIndex].text == "International") {
document.getElementById("flagInternational").disabled = false;
BD_CBUTTON.refreshCountry(results);
} else {
if ((results[1] == "GB") && (!document.getElementById("flagInternational").disabled)) {
document.getElementById("flagInternational").disabled = true;
BD_CBUTTON.refreshCountry(results);
} else {
document.getElementById("flagInternational").disabled = true;
if (countryCode.value != results[1]) {
BD_CBUTTON.refreshCountry(results);
} else {
if (langCode.value != results[0]) {
var locale = results[0];
langCode.value = locale;
BD_CBUTTON.updateImage(locale);
}
}
}
}
},
refreshCountry: function(results) {
var refreshCountryCode = document.createElement("input");
var countryCode = document.getElementById("countryCode");
refreshCountryCode.setAttribute("type", "hidden");
refreshCountryCode.setAttribute("name", "refresh_country_code");
refreshCountryCode.setAttribute("value", true);
var buttonDesignerForm = document.getElementById("buttonDesignerForm");
buttonDesignerForm.appendChild(refreshCountryCode);
countryCode.value = results[1];
var buttonDesignerForm = document.getElementById("buttonDesignerForm");
buttonDesignerForm.submit();
},
updateImage: function(locale) {
if (imageUrls[locale]) {
var smallButton = document.getElementById("smallButton");
var ccLogos = document.getElementById("ccLogos");
var previewImage = document.getElementById("previewImage");
var flagInt = document.getElementById("flagInternational").disabled ? false : true;
switch (BD_CBUTTON.buttonType) {
case "gift_certs":
if (smallButton.checked) {
previewImage.src = imageUrls[locale].GiftCertificate.small;
} else if (ccLogos.checked) {
if (flagInt) {
previewImage.src = imageUrls["int"].GiftCertificate.cc;
} else {
previewImage.src = imageUrls[locale].GiftCertificate.cc;
}
} else {
previewImage.src = imageUrls[locale].GiftCertificate.large;
}
break;
case "donations":
if (smallButton.checked) {
previewImage.src = imageUrls[locale].Donate.small;
} else if (ccLogos.checked) {
if (flagInt) {
previewImage.src = imageUrls["int"].Donate.cc;
} else {
previewImage.src = imageUrls[locale].Donate.cc;
}
} else {
previewImage.src = imageUrls[locale].Donate.large;
}
break;
case "subscriptions":
if (smallButton.checked) {
previewImage.src = imageUrls[locale].Subscribe.small;
} else if (ccLogos.checked) {
if (flagInt) {
previewImage.src = imageUrls["int"].Subscribe.cc;
} else {
previewImage.src = imageUrls[locale].Subscribe.cc;
}
} else {
previewImage.src = imageUrls[locale].Subscribe.large;
}
break;
case "buy_now":
if (smallButton.checked) {
previewImage.src = imageUrls[locale].BuyNow.small;
} else if (ccLogos.checked) {
if (flagInt) {
previewImage.src = imageUrls["int"].BuyNow.cc;
} else {
previewImage.src = imageUrls[locale].BuyNow.cc;
}
} else {
previewImage.src = imageUrls[locale].BuyNow.large;
}
break;
case "pay_now":
if (smallButton.checked) {
previewImage.src = imageUrls[locale].PayNow.small;
} else if (ccLogos.checked) {
if (flagInt) {
previewImage.src = imageUrls["int"].PayNow.cc;
} else {
previewImage.src = imageUrls[locale].PayNow.cc;
}
} else {
previewImage.src = imageUrls[locale].PayNow.large;
}
break;
case "add_to_cart":
if (smallButton.checked) {
previewImage.src = imageUrls[locale].AddToCart.small;
} else {
previewImage.src = imageUrls[locale].AddToCart.large;
}
break;
}
}
},
buildDropdownInfo: function(deletedDdNum) {
var dropdownInfo = new Array();
var dropdownPrice = document.getElementById("dropdownPrice");
var dropdown = document.getElementById("dropdown");
if (dropdownPrice.checked) {
var options = YUD.getElementsByClassName("optionRow", "p", "dropdownPriceSection");
var optionNames = YUD.getElementsByClassName("ddpOptionName", "input", "dropdownPriceSection");
var optionPrices = YUD.getElementsByClassName("ddpOptionPrice", "input", "dropdownPriceSection");
var optionCurrencies = YUD.getElementsByClassName("ddpOptionCurrency", "", "dropdownPriceSection");
var optionFrequency = YUD.getElementsByClassName("ddpOptionFrequency", "", "dropdownPriceSection");
var optionsLen = options.length;
var previewDropdownPriceSection = document.getElementById("previewDropdownPriceSection");
if (YUD.hasClass(previewDropdownPriceSection, "opened")) {
if (optionsLen != 0) {
var dropdownObj = {
ddName: document.getElementById("dropdownPriceTitle").getAttribute("name"),
title: document.getElementById("dropdownPriceTitle").value,
withPrice: true
};
for (var i = 0; i < optionsLen; i++) {
if (!options[i].getAttribute('id')) {
BD_CBUTTON.optionCounter++;
options[i].setAttribute('id', 'option_row_' + BD_CBUTTON.optionCounter);
}
var optionId = options[i].getAttribute('id').split('_')[2];
var optionObj = new Object;
optionObj.optionName = optionNames[i].value;
optionObj.price = optionPrices[i].value;
optionObj.currency = optionCurrencies[0].options[optionCurrencies[0].selectedIndex].value;
optionObj.frequency = optionFrequency[i].options[optionFrequency[i].selectedIndex].text;
dropdownObj[optionId] = optionObj;
}
dropdownInfo.push(dropdownObj);
}
}
}
if (dropdown.checked) {
for (var i = 1; i < 5; i++) {
var flag = (deletedDdNum != 0 && deletedDdNum == i) ? true : false;
var previewDropdownSection = document.getElementById("previewDropdownSection" + i);
if (YUD.hasClass(previewDropdownSection, "opened")) {
var options = YUD.getElementsByClassName("optionRow", "p", "dropdownSection" + i);
var optionNames = YUD.getElementsByClassName("ddOptionName", "input", "dropdownSection" + i);
var optionsLen = options.length;
if (optionsLen != 0) {
var dropdownObj = {
ddName: YUD.getElementsByClassName("dropdownTitle", "input", "dropdownSection" + i)[0].getAttribute("name"),
title: YUD.getElementsByClassName("dropdownTitle", "input", "dropdownSection" + i)[0].value,
deleted: flag,
withPrice: false
};
for (var j = 0; j < optionsLen; j++) {
if (!options[j].getAttribute('id')) {
BD_CBUTTON.optionCounter++;
options[j].setAttribute('id', 'option_row_' + BD_CBUTTON.optionCounter);
}
var optionId = options[j].getAttribute('id').split('_')[2];
var optionObj = new Object;
optionObj.optionName = optionNames[j].value;
optionObj.price = "";
optionObj.currency = "";
dropdownObj[optionId] = optionObj;
}
dropdownInfo.push(dropdownObj);
}
}
}
}
onDropdownPriceChange.fire({
dropdownInfo: dropdownInfo
});
},
saveDropdowns: function() {
var dropdownPriceSection = document.getElementById("dropdownPriceSection");
if (YUD.hasClass(dropdownPriceSection, "opened")) {
BD_CBUTTON.saveOptionPrice();
}
for (var i = 1; i < 5; i++) {
BD_CBUTTON.activeDropdown = i;
var dropdownSection = document.getElementById("dropdownSection" + i);
if (YUD.hasClass(dropdownSection, "opened")) {
BD_CBUTTON.saveOption();
}
var savedDropdownSection = document.getElementById("savedDropdownSection" + i);
if (YUD.hasClass(savedDropdownSection, "accessAid")) {
var allInputs = dropdownSection.getElementsByTagName("input");
var allInputsLen = allInputs.length;
for (var j = 0; j < allInputsLen; j++) {
allInputs[j].disabled = true;
}
}
}
},
saveDropdownsAndSubmit: function(e) {
if (BD_CBUTTON.buttonType != "view_cart") {
YUE.preventDefault(e);
BD_CBUTTON.saveDropdowns();
var buttonUrl = document.getElementById("buttonUrl");
buttonUrl.value = document.getElementById("previewImage").src;
var buttonDesignerForm = document.getElementById("buttonDesignerForm");
buttonDesignerForm.submit();
}
},
updateCurrency: function() {
var optionCurrencies = YUD.getElementsByClassName("ddpOptionCurrency", "label", "dropdownPriceSection");
var currencyLabels = YUD.getElementsByClassName("currencyLabel", "", "stepOne");
var defCurrency = YUD.getElementsByClassName("ddpOptionCurrency", "select", "dropdownPriceSection")[0];
var defCurrencyLen = defCurrency.options.length;
if (defCurrencyLen > 0) {
var defCurrencyValue = defCurrency.options[defCurrency.selectedIndex].value;
var optionCurrenciesLen = optionCurrencies.length;
var currencyLabelsLen = currencyLabels.length;
for (var i = 0; i < optionCurrenciesLen; i++) {
optionCurrencies[i].innerHTML = defCurrencyValue;
}
for (i = 0; i < currencyLabelsLen; i++) {
currencyLabels[i].innerHTML = defCurrencyValue;
}
var currencySelects = YUD.getElementsByClassName("currencySelect", "", "stepOne");
var currencySelectsLen = currencySelects.length;
for (i = 0; i < currencySelectsLen; i++) {
var currencyOptionsLen = currencySelects[i].options.length;
for (j = 0; j < currencyOptionsLen; j++) {
if (currencySelects[i].options[j].value == defCurrencyValue) {
currencySelects[i].options[j].selected = true;
}
}
}
}
},
dropdownCurrencyChange: function(type, args) {
var step1 = document.getElementById("stepOne");
if (args[0].item_price_currency) {
var currencyCode = args[0].item_price_currency;
var currencyElement = args[0].eventTarget;
var currencyLabels = YUD.getElementsByClassName('ddpOptionCurrency', 'label', step1);
var currencyLabelsLen = currencyLabels.length;
for (i = 0; i < currencyLabelsLen; i++) {
currencyLabels[i].innerHTML = currencyCode;
}
var currencySelects = YUD.getElementsByClassName('ddpOptionCurrency', 'select', '');
var currencySelectsLen = currencySelects.length;
for (i = 0; i < currencySelectsLen; i++) {
if (currencySelects[i] != currencyElement.id) {
var currencyOptionsLen = currencySelects[i].options.length;
for (j = 0; j < currencyOptionsLen; j++) {
if (currencySelects[i].options[j].value == currencyCode) {
currencySelects[i].options[j].selected = true;
}
}
}
}
BD_CBUTTON.createDropdownPriceStructure();
}
},
makeFieldReadOnly: function() {
this.blur();
},
escapeText: function(txt) {
var retTxt = txt;
var re = /</g;
retTxt = retTxt.replace(re, "<");
re = />/g;
retTxt = retTxt.replace(re, ">");
return retTxt;
}
};
BD_MASTER = PAYPAL.Merchant.ButtonDesigner.Master;
BD_STEP1 = PAYPAL.Merchant.ButtonDesigner.StepOne;
BD_CBUTTON = PAYPAL.Merchant.ButtonDesigner.CustomizeButton;
PAYPAL.util.Event.onDomReady(BD_MASTER.init);
PAYPAL.Merchant.ButtonDesigner.StepTwo = {
inventoryChecked: false,
PNLChecked: false,
dropDowns: null,
itemInfo: new Object,
buttonType: '',
currentDD: 0,
ddLightbox: null,
initialLoad: true,
byItem: true,
withPrice: false,
ddCount: 0,
ddData: new Object,
init: function() {
var stepTwo = document.getElementById("stepTwo");
if (!stepTwo) return;
var fades = YUD.getElementsByClassName("fadedOut", '', stepTwo);
BD_MASTER.fadeOut(fades);
YUE.addListener("enableHostedButtons", 'click', this.toggleOptions);
YUE.addListener("enableInventory", 'click', this.toggleTables);
YUE.addListener("enableProfitAndLoss", 'click', this.toggleTables);
YUE.addListener("trackByOption", 'click', this.trackByOption);
YUE.addListener("trackByItem", 'click', this.trackByItem);
YUE.addListener("chooseAnotherDropDown", 'click', this.chooseAnotherDropDown);
YUE.addListener("ddLightboxSubmit", 'click', this.pickDropDown);
YUE.addListener("enablePreOrder", 'click', this.enablePreOrder);
YUE.addListener("dontEnablePreOrder", 'click', this.dontEnablePreOrder);
onDropdownPriceChange.subscribe(this.updateDropdownData);
onItemDetailsChange.subscribe(this.itemDetailsChangeSubscriber);
try {
this.inventoryChecked = (document.getElementById("enableInventory") && document.getElementById("enableInventory").checked == true) ? true : false;
} catch (e) {}
try {
this.PNLChecked = (document.getElementById("enableProfitAndLoss") && document.getElementById("enableProfitAndLoss").checked == true) ? true : false;
} catch (e) {}
try {
this.byItem = (document.getElementById("trackByItem") && document.getElementById("trackByItem").checked == true) ? true : false;
} catch (e) {}
try {
this.withPrice = (document.getElementById("dropdownPrice") && document.getElementById("dropdownPrice").checked == true) ? true : false;
} catch (e) {}
if (this.inventoryChecked) {
try {
BD_MASTER.fadeIn(document.getElementById("soldOutOption"));
if (YUD.hasClass(document.getElementById("shoppingURL"), 'fadedOut')) {
BD_MASTER.fadeOut(document.getElementById("shoppingURL"));
}
} catch (e) {}
}
var currDDs = YUD.getElementsByClassName("currencySelect", 'select', "stepOne")[0];
this.itemInfo.currency = currDDs.options[currDDs.selectedIndex].value;
this.itemInfo.currency = (YUD.hasClass(stepTwo, 'reportingDisabled')) ? 'disabled' : this.itemInfo.currency;
BD_CBUTTON.buildDropdownInfo(0);
},
enablePreOrder: function(e) {
var soldOutURL = document.getElementById('shoppingURL');
BD_MASTER.fadeOut(soldOutURL);
},
dontEnablePreOrder: function(e) {
var soldOutURL = document.getElementById('shoppingURL');
BD_MASTER.fadeIn(soldOutURL);
},
pickDropDown: function(e) {
YUE.preventDefault(e);
var lightboxChoiceBody = document.getElementById("lightboxChoiceBody");
var options = YUD.getElementsByClassName("lbOption", "input", lightboxChoiceBody);
var optionsLen = options.length;
for (var i = 0; i < optionsLen; i++) {
if (options[i].checked) {
BD_STEP2.currentDD = parseInt(options[i].id.split('_')[1]);
}
}
var tempDD = BD_STEP2.dropDowns;
var curDD = BD_STEP2.currentDD;
for (var item in tempDD[curDD]) {
var isByOption = (item.price != '' || item.price != null || typeof item.price != 'undefined') ? true : false;
}
if (isByOption) {
BD_STEP2.trackByOption();
try {
document.getElementById('trackByOption').checked = true;
} catch (e) {}
} else {
BD_STEP2.trackByItem();
try {
document.getElementById('trackByItem').checked = true;
} catch (e) {}
}
BD_STEP2.ddLightbox.close();
},
saveInvData: function() {
var parentTable = document.getElementById("byOptionTableBody");
var rows = YUD.getElementsByClassName("inventory-table-row", "div", parentTable);
if (rows) {
var rowsLen = rows.length;
for (var i = 1; i < rowsLen; i++) {
var rowId = rows[i].getAttribute('id');
if (rowId != null) {
var inputs = rows[i].getElementsByTagName('input');
var inputsLen = inputs.length;
var selectedDropDown = rowId;
for (var j = 0; j < inputsLen; j++) {
if (!BD_STEP2.ddData[selectedDropDown]) {
BD_STEP2.ddData[selectedDropDown] = new Array;
}
if (!BD_STEP2.ddData[selectedDropDown][j]) {
BD_STEP2.ddData[selectedDropDown][j] = new Array;
}
BD_STEP2.ddData[selectedDropDown][j] = inputs[j].value;
}
}
}
}
},
updateDropdownData: function(e, obj) {
var ddi = obj[0].dropdownInfo;
var withPrice = false;
var ddlink = document.getElementById('chooseAnotherDropDown');
var byItemTable = document.getElementById('trackByItemTable');
var byItemTableBody = document.getElementById('byItemTableBody');
var byItem = document.getElementById('trackByItem');
var byOptionTable = document.getElementById('trackByOptionTable');
var byOptionTableBody = document.getElementById('byOptionTableBody');
BD_STEP2.saveInvData();
if (ddlink != null && ddi != '' && ddi.length != 0) {
BD_STEP2.ddCount = 0;
for (var item in ddi) {
if (ddi[item].withPrice) {
withPrice = true;
}
if (ddi[item].deleted) {
for (var subItem in ddi[item]) {
delete BD_STEP2.ddData[ddi[item].ddName + '_' + subItem]
}
}
}
if (!withPrice) {
while (!ddi[BD_STEP2.currentDD] && BD_STEP2.currentDD >= 0) {
BD_STEP2.currentDD--;
}
} else {
BD_STEP2.currentDD = 0;
}
for (var counter in ddi[BD_STEP2.currentDD]) {
if (counter != 'title' && counter != 'withPrice' && counter != 'ddName' && counter != 'deleted') {
BD_STEP2.ddCount++;
}
}
} else {
BD_STEP2.ddData = new Object;
}
BD_STEP2.dropDowns = ddi;
if (!BD_STEP2.initialLoad && document.getElementById('trackByOption')) {
if (withPrice) {
YUD.addClass(ddlink, 'accessAid');
BD_STEP2.withPrice = true;
}
if (ddi.length > 0) {
var inputs = byItemTableBody.getElementsByTagName('input');
var inputsLen = inputs.length;
var itemInv = false;
for (var i = 0; i < inputsLen; i++) {
if (inputs[i] && inputs[i].value != '' && inputs[i].value != null) {
itemInv = true;
}
}
if (document.getElementById('trackByItem').checked && (BD_STEP2.inventoryChecked || BD_STEP2.PNLChecked)) {
if (ddi.length > 1) {
try {
YUD.removeClass(ddlink, 'accessAid');
} catch (e) {}
} else {
try {
YUD.addClass(ddlink, 'accessAid');
} catch (e) {}
}
if (BD_STEP2.inventoryChecked || BD_STEP2.PNLChecked) {
BD_MASTER.fadeIn(byOptionTable);
YUD.removeClass(byOptionTable, 'accessAid');
BD_MASTER.fadeOut(byOptionTableBody);
}
} else {
try {
document.getElementById('trackByOption').checked = true;
} catch (e) {}
BD_STEP2.trackByOption();
if (BD_STEP2.inventoryChecked || BD_STEP2.PNLChecked) {
try {
BD_MASTER.fadeIn(byItemTable);
} catch (e) {}
if (!BD_STEP2.byItem) {
try {
BD_MASTER.fadeOut(byItemTableBody);
} catch (e) {}
}
}
if (ddi.length > 1) {
try {
YUD.removeClass(ddlink, 'accessAid');
} catch (e) {}
} else {
try {
YUD.addClass(ddlink, 'accessAid');
} catch (e) {}
}
BD_STEP2.withPrice = false;
YUD.removeClass(byOptionTable, 'accessAid');
}
} else {
try {
document.getElementById('trackByItem').checked = true;
} catch (e) {}
BD_STEP2.trackByItem();
try {
YUD.addClass(ddlink, 'accessAid');
} catch (e) {}
try {
BD_MASTER.fadeOut(byOptionTable);
YUD.addClass(byOptionTable, 'accessAid');
} catch (e) {}
BD_STEP2.withPrice = false;
}
} else {
var rows = YUD.getElementsByClassName("inventory-table-row", "div", byOptionTableBody);
if (rows[1] && rows[1].getAttribute('id')) {
if (!BD_STEP2.withPrice) {
var selectedDD = rows[1].getAttribute('id').split('_')[0];
BD_STEP2.currentDD = parseInt(selectedDD.charAt(selectedDD.length - 1)) - 1;
} else {
BD_STEP2.currentDD = 0;
}
var rowCounter = 1;
for (item in BD_STEP2.dropDowns[BD_STEP2.currentDD]) {
if (item != 'title' && item != 'withPrice' && item != 'ddName' && item != 'deleted') {
if (BD_STEP2.withPrice) {
try {
rows[rowCounter].setAttribute('id', 'dropdown_price_title_' + item);
} catch (e) {};
} else {
try {
rows[rowCounter].setAttribute('id', BD_STEP2.dropDowns[BD_STEP2.currentDD].ddName + '_' + item);
} catch (e) {};
}
rowCounter++;
}
}
}
BD_STEP2.initialLoad = false;
if (BD_STEP2.dropDowns.length > 1 && YUD.hasClass(ddlink, 'accessAid') && !withPrice) {
YUD.removeClass(ddlink, 'accessAid');
} else if (BD_STEP2.dropDowns.length > 0) {
YUD.removeClass(byOptionTable, 'accessAid');
} else {
YUD.addClass(byOptionTable, 'accessAid');
}
}
},
chooseAnotherDropDown: function(e) {
YUE.preventDefault(e);
var tempDD = BD_STEP2.dropDowns;
if (tempDD != null) {
if (BD_STEP2.ddLightbox == null) {
BD_STEP2.ddLightbox = new PAYPAL.util.Lightbox("ddLightbox");
}
var lightboxChoiceBody = document.getElementById("lightboxChoiceBody");
var labels = lightboxChoiceBody.getElementsByTagName('label');
while (lightboxChoiceBody.childNodes[0]) {
lightboxChoiceBody.removeChild(lightboxChoiceBody.lastChild);
}
var html = lightboxChoiceBody.innerHTML;
for (var item in tempDD) {
var subItems = new Array();
for (var subItem in tempDD[item]) {
if (subItem != 'title' && subItem != 'withPrice' && subItem != 'ddName' && subItem != 'deleted') {
subItems.push(tempDD[item][subItem].optionName);
}
}
var subItem = '(' + subItems.join(', ') + ')';
var title = tempDD[item].title;
if (title == 'undefined' || title == null || typeof title == 'undefined') {
title = '';
}
var checked = (item == BD_STEP2.currentDD) ? "checked" : "";
var escTitle = PAYPAL.util.escapeHTML(title);
var escsubItem = PAYPAL.util.escapeHTML(subItem);
html += "<label for='lbdd_" + item + "'><input type='radio' name='lightBoxSelection' class='lbOption' id='lbdd_" + item + "' " + checked + "/>" + escTitle + " " + escsubItem + "</label>";
}
lightboxChoiceBody.innerHTML = html;
BD_STEP2.ddLightbox.show();
}
},
trackByItem: function() {
BD_STEP2.byItem = true;
var parentTable = document.getElementById("byItemTableBody");
var optionsTable = document.getElementById("byOptionTableBody");
wHideShow.hide(optionsTable);
var rows = YUD.getElementsByClassName("inventory-table-row", "div", parentTable);
var rowsLen = rows.length;
if (rowsLen < 1) {
rows = YUD.getElementsByClassName("inventory-table-row", "div", optionsTable);
}
if (rowsLen > 0) {
var newRow = rows[rowsLen - 1].cloneNode(true);
var tempII = BD_STEP2.itemInfo;
var divs = newRow.getElementsByTagName('div');
var inputs = newRow.getElementsByTagName('input');
divs[0].innerHTML = ' ';
if ((tempII.currency == 'undefined' || tempII.currency == null) && BD_STEP2.itemInfo.currency != 'disabled') {
divs[divs.length - 1].innerHTML = '';
} else if (BD_STEP2.itemInfo.currency != 'disabled') {
divs[divs.length - 1].innerHTML = tempII.currency;
}
divs[0].innerHTML = ' ';
parentTable.appendChild(newRow);
for (var i = 1; i < rowsLen; i++) {
try {
parentTable.removeChild(rows[i]);
} catch (e) {}
}
BD_MASTER.fadeOut(optionsTable);
BD_MASTER.fadeIn(parentTable);
}
try {
if (BD_STEP2.inventoryChecked || BD_STEP2.PNLChecked) {
BD_MASTER.fadeIn(document.getElementById('trackByItemTable'));
BD_MASTER.fadeIn(parentTable);
var PNLItems = YUD.getElementsByClassName("PNLRelated", '', parentTable);
var invItems = YUD.getElementsByClassName("invRelated", '', parentTable);
if (BD_STEP2.inventoryChecked) {
BD_MASTER.fadeIn(invItems);
} else {
BD_MASTER.fadeOut(invItems);
}
if (BD_STEP2.PNLChecked) {
BD_MASTER.fadeIn(PNLItems);
} else {
BD_MASTER.fadeOut(PNLItems);
}
} else {
BD_MASTER.fadeOut(document.getElementById('trackByItemTable'));
}
wHideShow.show(parentTable);
} catch (e) {}
},
trackByOption: function() {
if (!BD_MASTER.isNumber(BD_STEP2.currentDD)) {
BD_STEP2.currentDD = 0;
}
BD_STEP2.byItem = false;
var parentTable = document.getElementById("byOptionTableBody");
var itemTable = document.getElementById("byItemTableBody");
var byOptionTable = document.getElementById('trackByOptionTable');
var tempDD = BD_STEP2.dropDowns;
var currentDD = BD_STEP2.currentDD;
if (tempDD != null && tempDD != '') {
BD_STEP2.ddCount = 0;
for (var counter in tempDD[BD_STEP2.currentDD]) {
if (counter != 'title' && counter != 'withPrice' && counter != 'ddName' && counter != 'deleted') {
BD_STEP2.ddCount++;
}
}
}
wHideShow.hide(itemTable);
if (!BD_STEP2.initialLoad) {
BD_STEP2.saveInvData();
}
rows = YUD.getElementsByClassName("inventory-table-row", "div", parentTable);
rowsLen = rows.length;
if (rowsLen < 2) {
var rows = YUD.getElementsByClassName("inventory-table-row", "div", itemTable);
var newRow = rows[1].cloneNode(true);
var inputs = newRow.getElementsByTagName('input');
var inputsLen = inputs.length;
for (var j = 0; j < inputsLen; j++) {
inputs[j].value = '';
inputs[j].disabled = false;
}
parentTable.appendChild(newRow);
}
rows = YUD.getElementsByClassName("inventory-table-row", "div", parentTable);
rowsLen = rows.length;
if (BD_STEP2.ddCount > (rowsLen - 1)) {
var createCount = BD_STEP2.ddCount - (rowsLen - 1);
for (var i = 0; i < createCount; i++) {
var newRow = rows[1].cloneNode(true);
var inputs = newRow.getElementsByTagName('input');
var inputsLen = inputs.length;
for (var j = 0; j < inputsLen; j++) {
inputs[j].value = '';
}
parentTable.appendChild(newRow);
}
}
rows = YUD.getElementsByClassName("inventory-table-row", "div", parentTable);
var rowIndex = 1;
for (var item in tempDD[currentDD]) {
if (item != 'title' && item != 'withPrice' && item != 'ddName' && item != 'deleted') {
var divs = rows[rowIndex].getElementsByTagName('div');
var inputs = rows[rowIndex].getElementsByTagName('input');
var inputsLen = inputs.length;
var rowId = tempDD[currentDD]['ddName'];
if (!BD_STEP2.initialLoad) {
var oldRowId = rows[rowIndex].getAttribute('id');
var newRowId = rowId + '_' + item;
if (oldRowId != newRowId) {
if (tempDD[currentDD]['deleted']) {
BD_STEP2.ddData[newRowId] = BD_STEP2.ddData[oldRowId];
}
rows[rowIndex].setAttribute('id', newRowId);
}
}
if (BD_STEP2.initialLoad) {
BD_STEP2.saveInvData();
}
for (var j = 0; j < inputsLen; j++) {
if (BD_STEP2.ddData[newRowId] && BD_STEP2.ddData[newRowId] != 'undefined') {
inputs[j].value = BD_STEP2.ddData[newRowId][j];
} else {
inputs[j].value = '';
}
}
if (tempDD[currentDD][item].optionName != '') {
if (tempDD[currentDD][item].optionName.length > 14) {
divs[0].innerHTML = tempDD[currentDD][item].optionName.substring(0, 14) + '...';
} else {
divs[0].innerHTML = tempDD[currentDD][item].optionName;
}
} else {
divs[0].innerHTML = ' ';
}
if (tempDD[currentDD][item].currency != '' && BD_STEP2.itemInfo.currency != 'disabled') {
divs[divs.length - 1].innerHTML = tempDD[currentDD][item].currency;
} else if (BD_STEP2.itemInfo.currency != 'disabled') {
divs[divs.length - 1].innerHTML = BD_STEP2.itemInfo.currency;
}
rowIndex++;
} else if (item == 'ddName') {
var selectedDropDown = document.getElementById("selectedDropDown");
selectedDropDown.setAttribute('value', tempDD[currentDD][item]);
}
}
if (!BD_STEP2.initialLoad) {
if (BD_STEP2.ddCount < (rowsLen - 1)) {
var diff = (rowsLen - 1) - BD_STEP2.ddCount;
for (var i = (rowsLen - 1); i > (rowsLen - 1 - diff); i--) {
parentTable.removeChild(rows[i]);
}
}
BD_MASTER.fadeOut(itemTable);
if (BD_STEP2.inventoryChecked || BD_STEP2.PNLChecked) {
BD_MASTER.fadeIn(parentTable);
BD_MASTER.fadeIn(byOptionTable);
}
YUD.removeClass(byOptionTable, 'accessAid');
var PNLItems = YUD.getElementsByClassName("PNLRelated", '', parentTable);
var invItems = YUD.getElementsByClassName("invRelated", '', parentTable);
var parentDisabled = YUD.hasClass(byOptionTable, 'fadedOut');
if (BD_STEP2.inventoryChecked) {
BD_MASTER.fadeIn(invItems);
} else {
if (!parentDisabled) {
BD_MASTER.fadeOut(invItems);
}
}
if (BD_STEP2.PNLChecked) {
BD_MASTER.fadeIn(PNLItems);
} else {
if (!parentDisabled) {
BD_MASTER.fadeOut(PNLItems);
}
}
if (parentDisabled) {
var kids = parentTable.getElementsByTagName('input');
var kidsLen = kids.length;
for (var i = 0; i < kidsLen; i++) {
if (!kids[i].disabled) {
kids[i].disabled = true;
}
}
}
} else {
BD_STEP2.initialLoad = false;
}
wHideShow.show(parentTable);
},
itemDetailsChangeSubscriber: function(e, obj) {
var invOpt = document.getElementById("inventoryOptions");
if (obj[0].button_type && invOpt != null) {
var invTable = document.getElementById("inventoryTable");
var soldOutOpt = document.getElementById("soldOutOption");
var productBasedHeading = document.getElementById("productBasedHeading");
var giftBasedHeading = document.getElementById("giftBasedHeading");
var urlInput = document.getElementById("shoppingURL");
var shoppingHead = document.getElementById("shoppingHead");
var shoppingPreOrder = document.getElementById("shoppingPreOrder");
var shoppingNoPreOrder = document.getElementById("dontEnablePreOrder");
var shoppingNoPreOrderLabel = document.getElementById("shoppingNoPreOrderLabel");
BD_STEP2.buttonType = obj[0].button_type;
switch (obj[0].button_type) {
case "gift_certs":
wHideShow.hide(shoppingNoPreOrderLabel);
wHideShow.hide(shoppingNoPreOrder);
wHideShow.hide(shoppingPreOrder);
wHideShow.hide(shoppingHead);
wHideShow.hide(invOpt);
wHideShow.hide(invTable);
wHideShow.hide(productBasedHeading);
wHideShow.hide(urlInput);
wHideShow.hide(soldOutOpt);
wHideShow.show(giftBasedHeading);
break;
case "donations":
wHideShow.hide(invOpt);
wHideShow.hide(invTable);
wHideShow.hide(soldOutOpt);
wHideShow.hide(productBasedHeading);
wHideShow.show(giftBasedHeading);
wHideShow.show(shoppingNoPreOrderLabel);
wHideShow.show(shoppingNoPreOrder);
wHideShow.show(shoppingPreOrder);
wHideShow.show(shoppingHead);
break;
default:
if (!YUD.hasClass(soldOutOpt, 'fadedOut')) {
BD_MASTER.fadeOut(soldOutOpt);
}
wHideShow.hide(giftBasedHeading);
wHideShow.show(shoppingNoPreOrderLabel);
wHideShow.show(shoppingNoPreOrder);
wHideShow.show(shoppingPreOrder);
wHideShow.show(shoppingHead);
wHideShow.show(urlInput);
wHideShow.show(productBasedHeading);
wHideShow.show(invOpt);
if (document.getElementById("enableHostedButtons").checked) {
BD_MASTER.fadeIn(invOpt);
}
wHideShow.show(invTable);
BD_MASTER.fadeIn(invTable);
BD_STEP2.toggleTables();
wHideShow.show(soldOutOpt);
break;
}
}
if ((obj[0].item_price_currency || obj[0].ddp_option_currency) && BD_STEP2.itemInfo.currency != 'disabled') {
var currencyCode = (obj[0].item_price_currency) ? obj[0].item_price_currency : obj[0].ddp_option_currency;
BD_STEP2.itemInfo.currency = currencyCode;
var fieldsToUpdate = YUD.getElementsByClassName('right-edge', 'div', 'inventoryTable');
var fieldsToUpdateLen = fieldsToUpdate.length;
for (var i = 0; i < fieldsToUpdateLen; i++) {
if (i != 0 && i != 2)
fieldsToUpdate[i].innerHTML = BD_STEP2.itemInfo.currency;
}
}
if (obj[0].product_name) {
var itemNameEsc = obj[0].product_name;
var itemName = PAYPAL.util.escapeHTML(itemNameEsc);
var itemLabel = document.getElementById("byItemLabel");
if (itemLabel != null) {
var itemLabelContent = itemLabel.innerHTML.split('-');
if (itemName.length > 40) {
itemName = itemName.substring(0, 40) + '...';
}
itemLabelContent = itemLabelContent[0] + ' - ' + itemName;
itemLabel.innerHTML = itemLabelContent;
BD_STEP2.itemInfo.itemName = itemName;
}
}
if (obj[0].product_id || obj[0].subscription_id) {
var itemId = YUD.getElementsByClassName('type-text', 'input', 'byItemTableBody')[0];
if (obj[0].subscription_id) {
try {
itemId.value = obj[0].subscription_id;
} catch (e) {}
} else if (obj[0].product_id) {
try {
itemId.value = obj[0].product_id;
} catch (e) {}
}
}
},
toggleOptions: function() {
var daddy = document.getElementById("inventoryOptions");
var checkbox = document.getElementById("enableHostedButtons");
var kiddies = YUD.getElementsBy(function(ele) {
return (ele.getAttribute("type") == "checkbox");
}, "input", daddy);
var kiddiesLen = kiddies.length;
for (var i = 0; i < kiddiesLen; i++) {
kiddies[i].checked = false;
if (kiddies[i].disabled) {
kiddies[i].disabled = false;
} else {
kiddies[i].disabled = true;
}
}
BD_MASTER.toggleFade(daddy);
BD_STEP2.toggleTables();
checkbox.blur();
},
toggleTables: function() {
var daddy = document.getElementById("inventoryTable");
var byItemTable = document.getElementById("trackByItemTable");
var byItemTableBody = document.getElementById("byItemTableBody");
var byOptionTable = document.getElementById("trackByOptionTable");
var byOptionTableBody = document.getElementById("byOptionTableBody");
var soldOutOption = document.getElementById("soldOutOption");
var soldOutURL = document.getElementById('shoppingURL');
var enablePreOrder = document.getElementById('enablePreOrder');
var PNLItems = YUD.getElementsByClassName("PNLRelated", '', daddy);
var invItems = YUD.getElementsByClassName("invRelated", '', daddy);
BD_STEP2.inventoryChecked = (document.getElementById("enableInventory").checked == true) ? true : false;
BD_STEP2.PNLChecked = (document.getElementById("enableProfitAndLoss") && document.getElementById("enableProfitAndLoss").checked == true) ? true : false;
try {
BD_STEP2.withPrice = (document.getElementById("dropdownPrice").checked == true) ? true : false;
} catch (e) {}
if (document.getElementById("enableHostedButtons").checked == false) {
BD_STEP2.inventoryChecked = false;
BD_STEP2.PNLChecked = false;
}
if (!BD_STEP2.inventoryChecked && !BD_STEP2.PNLChecked) {
BD_MASTER.fadeIn(PNLItems);
BD_MASTER.fadeIn(invItems);
BD_MASTER.fadeIn(byItemTableBody);
BD_MASTER.fadeOut(byItemTable);
BD_MASTER.fadeIn(byOptionTableBody);
BD_MASTER.fadeOut(byOptionTable);
if (BD_STEP2.buttonType == 'gift_certs' && document.getElementById("enableHostedButtons").checked == true) {
BD_MASTER.fadeIn(soldOutURL);
BD_MASTER.fadeIn(soldOutOption);
} else {
BD_MASTER.fadeOut(soldOutURL);
BD_MASTER.fadeOut(soldOutOption);
}
} else {
if (BD_STEP2.byItem) {
BD_MASTER.fadeIn(byItemTable);
BD_MASTER.fadeIn(byItemTableBody);
if (!YUD.hasClass(document.getElementById('chooseAnotherDropDown'), 'accessAid') || BD_STEP2.dropDowns.length > 0) {
BD_MASTER.fadeIn(byOptionTable);
YUD.removeClass(byOptionTable, 'accessAid');
} else if (BD_STEP2.dropDowns.length < 1) {
BD_MASTER.fadeOut(byOptionTable);
YUD.addClass(byOptionTable, 'accessAid');
}
BD_MASTER.fadeOut(byOptionTableBody);
PNLItems = YUD.getElementsByClassName("PNLRelated", '', byItemTable);
invItems = YUD.getElementsByClassName("invRelated", '', byItemTable);
} else {
BD_MASTER.fadeIn(byOptionTable);
YUD.removeClass(byOptionTable, 'accessAid');
BD_MASTER.fadeIn(byOptionTableBody);
BD_MASTER.fadeIn(byItemTable);
PNLItems = YUD.getElementsByClassName("PNLRelated", '', byOptionTable);
invItems = YUD.getElementsByClassName("invRelated", '', byOptionTable);
}
if (BD_STEP2.inventoryChecked) {
BD_MASTER.fadeIn(invItems);
BD_MASTER.fadeIn(soldOutOption);
if (enablePreOrder.checked) {
BD_MASTER.fadeOut(soldOutURL);
} else {
BD_MASTER.fadeIn(soldOutURL);
}
} else {
BD_MASTER.fadeOut(soldOutURL);
BD_MASTER.fadeOut(soldOutOption);
BD_MASTER.fadeOut(invItems);
}
if (BD_STEP2.PNLChecked) {
BD_MASTER.fadeIn(PNLItems);
} else {
BD_MASTER.fadeOut(PNLItems);
}
if (!BD_STEP2.byItem) {
BD_MASTER.fadeOut(byItemTableBody);
}
}
}
};
PAYPAL.Merchant.ButtonDesigner.StepThree = {
init: function() {
var stepThree = document.getElementById("stepThree");
if (!stepThree) return;
var noSpecialInstructions = document.getElementById('noSpecialInstructions');
YUE.addListener(noSpecialInstructions, 'click', this.hide);
var addSpecialInstructions = document.getElementById('addSpecialInstructions');
if (addSpecialInstructions) {
YUE.addListener(addSpecialInstructions, 'click', this.show);
}
var cancellationCheckbox = document.getElementById('cancellationCheckbox');
var cancellationRedirectURL = document.getElementById('cancellationRedirectURL');
YUE.addListener(cancellationCheckbox, 'change', this.toggleTextfield, cancellationRedirectURL, false);
var successfulCheckbox = document.getElementById('successfulCheckbox');
var successfulRedirectURL = document.getElementById('successfulRedirectURL');
YUE.addListener(successfulCheckbox, 'change', this.toggleTextfield, successfulRedirectURL, false);
var variablesTextarea = document.getElementById('variablesTextarea');
var addVariables = document.getElementById("addVariables");
YUE.addListener(variablesTextarea, 'keyup', this.checkCheckbox, addVariables, false);
onItemDetailsChange.subscribe(this.conditionalHides);
},
hide: function() {
var messageBoxContainer = document.getElementById('messageBoxContainer');
wHideShow.hide(messageBoxContainer);
},
show: function() {
var messageBoxContainer = document.getElementById('messageBoxContainer');
wHideShow.show(messageBoxContainer);
},
toggleTextfield: function(e, ElementId) {
var elTarget = YUE.getTarget(e);
ElementId.disabled = (elTarget.checked) ? false : true;
},
checkCheckbox: function(e, ElementId) {
var elTarget = YUE.getTarget(e);
ElementId.checked = (elTarget.value != '') ? true : false;
},
conditionalHides: function(type, args) {
if (args[0].button_type) {
var changeOrderQuantitiesContainer = document.getElementById('changeOrderQuantitiesContainer');
var specialInstructionsContainer = document.getElementById('specialInstructionsContainer');
var shippingAddressContainer = document.getElementById('shippingAddressContainer');
var cancellationRedirectURLContainer = document.getElementById('cancellationRedirectURLContainer');
var successfulRedirectURLContainer = document.getElementById('successfulRedirectURLContainer');
var addVariablesContainer = document.getElementById('addVariablesContainer');
if (args[0].button_type == 'view_cart' || args[0].button_type == 'unsubscribe') {
wHideShow.hide(changeOrderQuantitiesContainer);
wHideShow.hide(specialInstructionsContainer);
wHideShow.hide(shippingAddressContainer);
wHideShow.hide(cancellationRedirectURLContainer);
wHideShow.hide(successfulRedirectURLContainer);
wHideShow.hide(addVariablesContainer);
BD_STEP3.setInstructionsValue('0');
}
if (args[0].button_type == 'products' || args[0].button_type == 'donations' || args[0].button_type == 'services') {
if (args[0].button_type == 'donations' || args[0].sub_button_type == 'add_to_cart') {
wHideShow.hide(changeOrderQuantitiesContainer);
} else {
wHideShow.show(changeOrderQuantitiesContainer);
}
wHideShow.show(specialInstructionsContainer);
wHideShow.show(shippingAddressContainer);
wHideShow.show(cancellationRedirectURLContainer);
wHideShow.show(successfulRedirectURLContainer);
wHideShow.show(addVariablesContainer);
BD_STEP3.setInstructionsValue('0');
}
if (args[0].button_type == 'subscriptions') {
wHideShow.hide(changeOrderQuantitiesContainer);
wHideShow.hide(specialInstructionsContainer);
wHideShow.show(shippingAddressContainer);
wHideShow.show(cancellationRedirectURLContainer);
wHideShow.show(successfulRedirectURLContainer);
wHideShow.show(addVariablesContainer);
BD_STEP3.setInstructionsValue('1');
}
if (args[0].button_type == 'gift_certs') {
wHideShow.hide(changeOrderQuantitiesContainer);
wHideShow.hide(specialInstructionsContainer);
wHideShow.hide(shippingAddressContainer);
wHideShow.hide(cancellationRedirectURLContainer);
wHideShow.hide(successfulRedirectURLContainer);
wHideShow.show(addVariablesContainer);
BD_STEP3.setInstructionsValue('1');
}
}
},
setInstructionsValue: function(val) {
var addSpecialInstructions = document.getElementById('addSpecialInstructions');
if (addSpecialInstructions) {
addSpecialInstructions.value = val;
}
}
};
BD_STEP2 = PAYPAL.Merchant.ButtonDesigner.StepTwo;
BD_STEP3 = PAYPAL.Merchant.ButtonDesigner.StepThree;
BD_STEP2.init();
BD_STEP3.init(); | angelleye/paypal-wp-button-manager | admin/js/paypal-wp-button-manager-buttonDesigner.js | JavaScript | gpl-3.0 | 191,046 |
/*jshint esnext: true */
import httpLib from './http-lib.js';
export default function getSyncData(successCallback, errorCallback){
var protocolAndDomain = this.getUrl(),
syncPath = "/api/mobile/sync.php",
that = this;
if(!protocolAndDomain) return errorCallback({error:true});
if(!that.profile || !that.profile.username) return errorCallback({error:true, isLoggedIn:false});
this.setMobileUploadToken(that.generateUploadToken(), function(uploadToken){
httpLib.get(protocolAndDomain + syncPath, {token:uploadToken, username:that.profile.username}, successFrom(successCallback, errorCallback), failureFrom(errorCallback));
}, failureFrom(errorCallback));
function successFrom(successCallback, errorCallback){
return function(response){
var jsonResponse;
if(!response || !response.target || !response.target.response) return errorCallback({error:true, syncDataError:true});
try {
jsonResponse = JSON.parse(response.target.response);
} catch(e){
}
if(!jsonResponse || jsonResponse.fail) return errorCallback({error:true, noPermission:true, message:jsonResponse.fail, data:jsonResponse});
successCallback(jsonResponse);
};
}
function failureFrom(callback){
return function(response){
callback(response);
};
}
} | holloway/mahara-mobile | src/js/mahara-lib/get-sync-data.js | JavaScript | gpl-3.0 | 1,323 |
/*
* math.js
*/
var math=(function(){
const DNF=-1; //What to return in case of DNF
/*
* math:Init()
*/
function init(){
}
/*
* math:getMean(times)
* @param times Array of solves to get an mean of
* @returns mean of times, or -1 in case of DNF
*/
function getMean(times){
var cntdnf,cnttime,i,sum;
sum=0;
cntdnf=0;
cnttime=0;
for(i=0;i<times.length;++i){
if(times[i].zeit>0)
sum+=times[i].zeit;
else
cntdnf++;
cnttime++;
}
if(cntdnf>0){
return DNF;
}
return sum/(cnttime);
}
/*
* math:getAverage(times)
* @param times Array of solves to get an average of
* @returns average of times, or -1 in case of DNF
* @Todo remove best and worst 5%
*/
function getAverage(times){
var cntdnf,cnttime,sum,i;
cntdnf=0;
cnttime=0;
sum=0;
for(i=0;i<times.length;++i){
if(times[i].zeit>0)
sum+=times[i].zeit,
cnttime++;
else
cntdnf++;
}
if(cntdnf>times.length*0.05)
return DNF;
return sum/(cnttime);
}
/*
* math:getBest(times)
* @param times Array of solves
* @returns the best time
*/
function getBest(times){
var best=DNF,i;
for(i=0;i<times.length;++i)
if(times[i].zeit<best)
best=times[i].zeit;
return best;
}
/*
* math:getWorst(times)
* @param times Array of solves
* @returns the best time
*/
function getWorst(times){
var worst=DNF,i;
for(i=0;i<times.length;++i)
if(times[i].zeit>worst)
worst=times[i].zeit;
return worst;
}
/*
* math:getBestMean(times,off)
* @param times Array of all solves
* @param off Int average size
* @returns best mean of off of all given times
*/
function getBestMean(times,off){
var best=+Infinity,i,j,averageTimeList;
if(times.length<off)
return DNF;
for(i=off;i<times.length;++i){
averageTimeList=[];
for(j=0;j<off;++j)
averageTimeList.push(times[i-j]);
if(getAverage(averageTimeList)<best)
best=getAverage(averageTimeList);
}
return best==+Infinity?DNF:best;
}
/*
* math:format(time)
* @param time Int in milliseconds
* @returns formatted time as string
*/
function format(time) {
var useMilliseconds=true;
var bits,secs,mins,hours,s;
if(time<0)return"DNF";
time=Math.round(time/(useMilliseconds?1:10));
bits=time%(useMilliseconds?1000:100);
time=(time-bits)/(useMilliseconds?1000:100);
secs=time%60;
mins=((time-secs)/60)%60;
hours=(time-secs-60*mins)/3600;
s=""+bits;
//Fill 0s
if(bits<10)
s="0"+s;
if(bits<100&&useMilliseconds)
s="0"+s;
s=secs+"."+s;
//Fill 0s and append minutes if neccessary
if(secs<10&&(mins>0||hours>0))
s="0"+s;
if(mins>0||hours>0)
s=mins+":"+s;
if(mins<20&&hours>0)
s="0"+s;
if(hours>0)
s=hours+":"+s;
return s;
}
/*
* math:formatPenalty(solve)
* @param solve solve Object
* @returns formatted time as string
*/
function formatPenalty(solve){
var time=solve.zeit,ret,nrofPlus,i;
if(solve.penalty==-1)
return "DNF";
if(solve.penalty>0)
time+=solve.penalty;
ret=format(time);
if(solve.penalty/1000%2==0)
nrofPlus=solve.penalty/2000;
else
nrofPlus=(solve.penalty-1)/2000;
for(i=0;i<nrofPlus;++i)
ret+="+";
return ret;
}
/*
* math:algInvert(alg,type)
* @param alg String algorithm
* @return inverted alg
*/
function algInvert(alg){
var i,out=[];
alg=alg.split(" ");
for(i=0;i<alg.length;++i){
out.unshift(alg[i][alg[i].length-1]=="'"?alg[i][0]:alg[i]+"'");
}
return out.join(' ');
}
/*
* math:applyPenalty(time,p)
* @param time time in ms, <0 for DNF(-time)
* @param p Penalty in seconds, +seconds for adding, -seconds for removing, -1 for removing DNF, +1 for setting DNF
* @returns time + penalty p
*/
function applyPenalty(time,p){
if(time<0){
if(p==-1)
return -time;
return time;
}
if(p==1)
return -time;
if(p==-1)
return time;
return time+p*1000;
}
/*
* math:compressAlgorithm(alg)
* @param alg String algorithm, moves are spaceseperated
* @returns compressed Algorithm
*/
function compressAlgorithm(alg){
var mapping={
"R":"A",
"R'":"B",
"R2":"C",
"R2'":"D",
"F":"E",
"F'":"F",
"F2":"G",
"F2'":"H",
"U":"I",
"U'":"J",
"U2":"K",
"U2'":"L",
"B":"M",
"B'":"N",
"B2":"O",
"B2'":"P",
"D":"Q",
"D'":"R",
"D2":"S",
"D2'":"T",
"L":"U",
"L'":"V",
"L2":"W",
"L2'":"X",
"x":"Y",
"x'":"Z",
"x2":"a",
"x2'":"b",
"y":"c",
"y'":"d",
"y2":"e",
"y2'":"f",
"z":"g",
"z'":"h",
"z2":"i",
"z2'":"j"
}
alg=alg.split(" ");
for(var i=0;i<alg.length;++i)
alg[i]=mapping[alg[i]]||"k"+alg[i];
return alg.join("");
}
/*
* math:decompressAlgorithm(alg)
* @param alg String compressed algorithm
* @returns decompressed Algorithm
*/
function decompressAlgorithm(alg){
var mapping={
"A":"R",
"B":"R'",
"C":"R2",
"D":"R2'",
"E":"F",
"F":"F'",
"G":"F2",
"H":"F2'",
"I":"U",
"J":"U'",
"K":"U2",
"L":"U2'",
"M":"B",
"N":"B'",
"O":"B2",
"P":"B2'",
"Q":"D",
"R":"D'",
"S":"D2",
"T":"D2'",
"U":"L",
"V":"L'",
"W":"L2",
"X":"L2'",
"Y":"x",
"Z":"x'",
"a":"x2",
"b":"x2'",
"c":"y",
"d":"y'",
"e":"y2",
"f":"y2'",
"g":"z",
"h":"z'",
"i":"z2",
"j":"z2'"
}
alg=alg.split("");
for(var i=0;i<alg.length;++i)
alg[i]=mapping[alg[i]]||"";
return alg.join(" ");
}
return {
init:init,
mean:getMean,
average:getAverage,
best:getBest,
worst:getWorst,
bestMean:getBestMean,
format:format,
formatPenalty:formatPenalty,
algInvert:algInvert,
applyPenalty:applyPenalty,
compressAlgorithm:compressAlgorithm,
decompressAlgorithm:decompressAlgorithm
}
})();
| YTCuber/HTTimer | js/math.js | JavaScript | gpl-3.0 | 5,730 |
//------------------------------------------------------------------
//
// This is the text function that handles all of the game's
// required text ojects.
GAME.text = (function(graphics) {
'use strict';
//Initialize text objects
function initialize(spec) {
var that = {};
//Render the text object
that.render = function() {
graphics.drawText(spec);
};
that.update = function(elapsedTime) {
spec.elapsedTime += elapsedTime;
if(spec.elapsedTime > spec.maxTime) {
that.updateText('');
}
};
that.updateText = function(newText) {
spec.elapsedTime = 0;
spec.text = newText;
};
that.changeText = function(Text) {
spec.text = Text;
}
that.setPosition = function(x, y) {
spec.pos.x = x;
spec.pos.y = y;
};
that.setFont = function(font) {
spec.font = font;
};
that.toDefault = function() {
spec.text = spec.default.text;
spec.font = spec.default.font;
spec.fill = spec.default.fill;
spec.stroke = spec.default.stroke;
spec.pos.x = spec.default.pos.x;
spec.pos.y = spec.default.pos.y;
}
return that;
}
return {
initialize: initialize
};
}(GAME.graphics)); | JustinKent55/Castle-Defense | public/scripts/text.js | JavaScript | gpl-3.0 | 1,279 |
/**
* @license Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.md or http://ckeditor.com/license
*/
/**
* This file was added automatically by CKEditor builder.
* You may re-use it at any time to build CKEditor again.
*
* If you would like to build CKEditor online again
* (for example to upgrade), visit one the following links:
*
* (1) http://ckeditor.com/builder
* Visit online builder to build CKEditor from scratch.
*
* (2) http://ckeditor.com/builder/ba0d86b4a03f476b450cdf7d3057be62
* Visit online builder to build CKEditor, starting with the same setup as before.
*
* (3) http://ckeditor.com/builder/download/ba0d86b4a03f476b450cdf7d3057be62
* Straight download link to the latest version of CKEditor (Optimized) with the same setup as before.
*
* NOTE:
* This file is not used by CKEditor, you may remove it.
* Changing this file will not change your CKEditor configuration.
*/
var CKBUILDER_CONFIG = {
skin: 'moono',
preset: 'standard',
plugins : {
'a11yhelp' : 1,
'about' : 1,
'basicstyles' : 1,
'blockquote' : 1,
'clipboard' : 1,
'contextmenu' : 1,
'elementspath' : 1,
'enterkey' : 1,
'entities' : 1,
'filebrowser' : 1,
'floatingspace' : 1,
'format' : 1,
'horizontalrule' : 1,
'htmlwriter' : 1,
'image' : 1,
'indentlist' : 1,
'link' : 1,
'list' : 1,
'magicline' : 1,
'maximize' : 1,
'pastefromword' : 1,
'pastetext' : 1,
'removeformat' : 1,
'resize' : 1,
'scayt' : 1,
'showborders' : 1,
'sourcearea' : 1,
'specialchar' : 1,
'stylescombo' : 1,
'tab' : 1,
'table' : 1,
'tabletools' : 1,
'toolbar' : 1,
'undo' : 1,
'wsc' : 1,
'wysiwygarea' : 1
},
languages : {
'af' : 1,
'ar' : 1,
'bg' : 1,
'bn' : 1,
'bs' : 1,
'ca' : 1,
'cs' : 1,
'cy' : 1,
'da' : 1,
'de' : 1,
'de-ch' : 1,
'el' : 1,
'en' : 1,
'en-au' : 1,
'en-ca' : 1,
'en-gb' : 1,
'eo' : 1,
'es' : 1,
'et' : 1,
'eu' : 1,
'fa' : 1,
'fi' : 1,
'fo' : 1,
'fr' : 1,
'fr-ca' : 1,
'gl' : 1,
'gu' : 1,
'he' : 1,
'hi' : 1,
'hr' : 1,
'hu' : 1,
'id' : 1,
'is' : 1,
'it' : 1,
'ja' : 1,
'ka' : 1,
'km' : 1,
'ko' : 1,
'ku' : 1,
'lt' : 1,
'lv' : 1,
'mk' : 1,
'mn' : 1,
'ms' : 1,
'nb' : 1,
'nl' : 1,
'no' : 1,
'pl' : 1,
'pt' : 1,
'pt-br' : 1,
'ro' : 1,
'ru' : 1,
'si' : 1,
'sk' : 1,
'sl' : 1,
'sq' : 1,
'sr' : 1,
'sr-latn' : 1,
'sv' : 1,
'th' : 1,
'tr' : 1,
'tt' : 1,
'ug' : 1,
'uk' : 1,
'vi' : 1,
'zh' : 1,
'zh-cn' : 1
}
}; | MrDarkSkil/FlowTracker | admin/plugins/ckeditor/build-config.js | JavaScript | gpl-3.0 | 2,583 |
function geodir_click_search($this) {
//we delay this so other functions have a change to change setting before search
setTimeout(function() {
jQuery($this).parent().find('.geodir_submit_search').click();
}, 100);
}
function addToFavourite(post_id, action) {
var fav_url;
var ajax_action;
if (action == 'add') {
ajax_action = 'add';
} else {
ajax_action = 'remove';
}
jQuery.ajax({
url: geodir_all_js_msg.geodir_admin_ajax_url,
type: 'GET',
dataType: 'html',
data: {
action: 'geodir_ajax_action',
geodir_ajax: 'favorite',
ajax_action: ajax_action,
pid: post_id
},
timeout: 20000,
error: function() {
alert(geodir_all_js_msg.loading_listing_error_favorite);
},
success: function(html) {
jQuery('.favorite_property_' + post_id).html(html);
}
});
return false;
}
jQuery(document).ready(function($) {
if (geodir_all_js_msg.fa_rating) { // font awesome rating
jQuery('.gd-fa-rating').barrating({
theme: 'fontawesome-stars',
onSelect: function(value, text, event) {
if (geodir_all_js_msg.multirating) {
if (jQuery(this.$elem).closest('form').attr('id') == 'post') {
jQuery(this.$elem).closest('.br-theme-fontawesome-stars').parent().find('[name^=geodir_rating]').val(value);
} else {
jQuery(this.$elem).parent().parent().find('.geodir_reviewratings_current_rating').val(value);
}
} else {
jQuery("#geodir_overallrating").val(value);
}
}
});
} else { // default rating
jQuery('.gd_rating').jRating({
/** String vars **/
//bigStarsPath : geodir_all_js_msg.geodir_plugin_url+'/geodirectory-assets/images/stars.png',
bigStarsPath: geodir_all_js_msg.geodir_default_rating_star_icon,
smallStarsPath: geodir_all_js_msg.geodir_plugin_url + '/geodirectory-assets/images/small.png',
phpPath: geodir_all_js_msg.geodir_plugin_url + '/jRating.php',
type: 'big', // can be set to 'small' or 'big'
/** Boolean vars **/
step: true, // if true, mouseover binded star by star,
isDisabled: false,
showRateInfo: true,
canRateAgain: true,
/** Integer vars **/
length: 5, // number of star to display
decimalLength: 0, // number of decimals.. Max 3, but you can complete the function 'getNote'
rateMax: 5, // maximal rate - integer from 0 to 9999 (or more)
rateInfosX: -45, // relative position in X axis of the info box when mouseover
rateInfosY: 5, // relative position in Y axis of the info box when mouseover
nbRates: 100,
/** Functions **/
onSuccess: function(element, rate) {
jQuery('#geodir_overallrating').val(rate);
},
onTouchstart: function(element, rate) {
jQuery('#geodir_overallrating').val(rate);
},
onError: function() {
alert(geodir_all_js_msg.rating_error_msg);
}
});
}
jQuery('#geodir_location_prefix').attr('disabled', 'disabled');
jQuery('.button-primary').click(function() {
var error = false;
var characterReg = /^\s*[a-zA-Z0-9,\s]+\s*$/;
var listing_prefix = jQuery('#geodir_listing_prefix').val();
var location_prefix = jQuery('#geodir_location_prefix').val();
var listingurl_separator = jQuery('#geodir_listingurl_separator').val();
var detailurl_separator = jQuery('#geodir_detailurl_separator').val();
if (listing_prefix == '') {
alert(geodir_all_js_msg.listing_url_prefix_msg);
jQuery('#geodir_listing_prefix').focus();
error = true;
}
if (/^[a-z0-90\_9_-]*$/.test(listing_prefix) == false && listing_prefix != '') {
jQuery('#geodir_listing_prefix').focus();
alert(geodir_all_js_msg.invalid_listing_prefix_msg);
error = true;
}
/* Depreciated 1.4.6
if (location_prefix == '') {
alert(geodir_all_js_msg.location_url_prefix_msg);
jQuery('#geodir_location_prefix').focus();
error = true;
}
if (!characterReg.test(location_prefix) && location_prefix != '') {
alert(geodir_all_js_msg.invalid_location_prefix_msg);
jQuery('#geodir_location_prefix').focus();
error = true;
}
*/
if (error == true) {
return false;
} else {
return true;
}
});
jQuery('.map_post_type').click(function() {
var divshow = jQuery(this).val();
if (jQuery(this).is(':checked')) {
jQuery('#' + divshow + ' input').each(function() {
jQuery(this).attr('checked', 'checked');
});
} else {
jQuery('#' + divshow + ' input').each(function() {
jQuery(this).removeAttr('checked');
});
}
});
});
// fix for related accents search.
function gd_replace_accents (s) {
var chars = [{'base':'A', 'letters':/[\u0041\u24B6\uFF21\u00C0\u00C1\u00C2\u1EA6\u1EA4\u1EAA\u1EA8\u00C3\u0100\u0102\u1EB0\u1EAE\u1EB4\u1EB2\u0226\u01E0\u00C4\u01DE\u1EA2\u00C5\u01FA\u01CD\u0200\u0202\u1EA0\u1EAC\u1EB6\u1E00\u0104\u023A\u2C6F]/g},
{'base':'AA','letters':/[\uA732]/g},
{'base':'AE','letters':/[\u00C6\u01FC\u01E2]/g},
{'base':'AO','letters':/[\uA734]/g},
{'base':'AU','letters':/[\uA736]/g},
{'base':'AV','letters':/[\uA738\uA73A]/g},
{'base':'AY','letters':/[\uA73C]/g},
{'base':'B', 'letters':/[\u0042\u24B7\uFF22\u1E02\u1E04\u1E06\u0243\u0182\u0181]/g},
{'base':'C', 'letters':/[\u0043\u24B8\uFF23\u0106\u0108\u010A\u010C\u00C7\u1E08\u0187\u023B\uA73E]/g},
{'base':'D', 'letters':/[\u0044\u24B9\uFF24\u1E0A\u010E\u1E0C\u1E10\u1E12\u1E0E\u0110\u018B\u018A\u0189\uA779]/g},
{'base':'DZ','letters':/[\u01F1\u01C4]/g},
{'base':'Dz','letters':/[\u01F2\u01C5]/g},
{'base':'E', 'letters':/[\u0045\u24BA\uFF25\u00C8\u00C9\u00CA\u1EC0\u1EBE\u1EC4\u1EC2\u1EBC\u0112\u1E14\u1E16\u0114\u0116\u00CB\u1EBA\u011A\u0204\u0206\u1EB8\u1EC6\u0228\u1E1C\u0118\u1E18\u1E1A\u0190\u018E]/g},
{'base':'F', 'letters':/[\u0046\u24BB\uFF26\u1E1E\u0191\uA77B]/g},
{'base':'G', 'letters':/[\u0047\u24BC\uFF27\u01F4\u011C\u1E20\u011E\u0120\u01E6\u0122\u01E4\u0193\uA7A0\uA77D\uA77E]/g},
{'base':'H', 'letters':/[\u0048\u24BD\uFF28\u0124\u1E22\u1E26\u021E\u1E24\u1E28\u1E2A\u0126\u2C67\u2C75\uA78D]/g},
{'base':'I', 'letters':/[\u0049\u24BE\uFF29\u00CC\u00CD\u00CE\u0128\u012A\u012C\u0130\u00CF\u1E2E\u1EC8\u01CF\u0208\u020A\u1ECA\u012E\u1E2C\u0197]/g},
{'base':'J', 'letters':/[\u004A\u24BF\uFF2A\u0134\u0248]/g},
{'base':'K', 'letters':/[\u004B\u24C0\uFF2B\u1E30\u01E8\u1E32\u0136\u1E34\u0198\u2C69\uA740\uA742\uA744\uA7A2]/g},
{'base':'L', 'letters':/[\u004C\u24C1\uFF2C\u013F\u0139\u013D\u1E36\u1E38\u013B\u1E3C\u1E3A\u0141\u023D\u2C62\u2C60\uA748\uA746\uA780]/g},
{'base':'LJ','letters':/[\u01C7]/g},
{'base':'Lj','letters':/[\u01C8]/g},
{'base':'M', 'letters':/[\u004D\u24C2\uFF2D\u1E3E\u1E40\u1E42\u2C6E\u019C]/g},
{'base':'N', 'letters':/[\u004E\u24C3\uFF2E\u01F8\u0143\u00D1\u1E44\u0147\u1E46\u0145\u1E4A\u1E48\u0220\u019D\uA790\uA7A4]/g},
{'base':'NJ','letters':/[\u01CA]/g},
{'base':'Nj','letters':/[\u01CB]/g},
{'base':'O', 'letters':/[\u004F\u24C4\uFF2F\u00D2\u00D3\u00D4\u1ED2\u1ED0\u1ED6\u1ED4\u00D5\u1E4C\u022C\u1E4E\u014C\u1E50\u1E52\u014E\u022E\u0230\u00D6\u022A\u1ECE\u0150\u01D1\u020C\u020E\u01A0\u1EDC\u1EDA\u1EE0\u1EDE\u1EE2\u1ECC\u1ED8\u01EA\u01EC\u00D8\u01FE\u0186\u019F\uA74A\uA74C]/g},
{'base':'OI','letters':/[\u01A2]/g},
{'base':'OO','letters':/[\uA74E]/g},
{'base':'OU','letters':/[\u0222]/g},
{'base':'P', 'letters':/[\u0050\u24C5\uFF30\u1E54\u1E56\u01A4\u2C63\uA750\uA752\uA754]/g},
{'base':'Q', 'letters':/[\u0051\u24C6\uFF31\uA756\uA758\u024A]/g},
{'base':'R', 'letters':/[\u0052\u24C7\uFF32\u0154\u1E58\u0158\u0210\u0212\u1E5A\u1E5C\u0156\u1E5E\u024C\u2C64\uA75A\uA7A6\uA782]/g},
{'base':'S', 'letters':/[\u0053\u24C8\uFF33\u1E9E\u015A\u1E64\u015C\u1E60\u0160\u1E66\u1E62\u1E68\u0218\u015E\u2C7E\uA7A8\uA784]/g},
{'base':'T', 'letters':/[\u0054\u24C9\uFF34\u1E6A\u0164\u1E6C\u021A\u0162\u1E70\u1E6E\u0166\u01AC\u01AE\u023E\uA786]/g},
{'base':'TZ','letters':/[\uA728]/g},
{'base':'U', 'letters':/[\u0055\u24CA\uFF35\u00D9\u00DA\u00DB\u0168\u1E78\u016A\u1E7A\u016C\u00DC\u01DB\u01D7\u01D5\u01D9\u1EE6\u016E\u0170\u01D3\u0214\u0216\u01AF\u1EEA\u1EE8\u1EEE\u1EEC\u1EF0\u1EE4\u1E72\u0172\u1E76\u1E74\u0244]/g},
{'base':'V', 'letters':/[\u0056\u24CB\uFF36\u1E7C\u1E7E\u01B2\uA75E\u0245]/g},
{'base':'VY','letters':/[\uA760]/g},
{'base':'W', 'letters':/[\u0057\u24CC\uFF37\u1E80\u1E82\u0174\u1E86\u1E84\u1E88\u2C72]/g},
{'base':'X', 'letters':/[\u0058\u24CD\uFF38\u1E8A\u1E8C]/g},
{'base':'Y', 'letters':/[\u0059\u24CE\uFF39\u1EF2\u00DD\u0176\u1EF8\u0232\u1E8E\u0178\u1EF6\u1EF4\u01B3\u024E\u1EFE]/g},
{'base':'Z', 'letters':/[\u005A\u24CF\uFF3A\u0179\u1E90\u017B\u017D\u1E92\u1E94\u01B5\u0224\u2C7F\u2C6B\uA762]/g},
{'base':'a', 'letters':/[\u0061\u24D0\uFF41\u1E9A\u00E0\u00E1\u00E2\u1EA7\u1EA5\u1EAB\u1EA9\u00E3\u0101\u0103\u1EB1\u1EAF\u1EB5\u1EB3\u0227\u01E1\u00E4\u01DF\u1EA3\u00E5\u01FB\u01CE\u0201\u0203\u1EA1\u1EAD\u1EB7\u1E01\u0105\u2C65\u0250]/g},
{'base':'aa','letters':/[\uA733]/g},
{'base':'ae','letters':/[\u00E6\u01FD\u01E3]/g},
{'base':'ao','letters':/[\uA735]/g},
{'base':'au','letters':/[\uA737]/g},
{'base':'av','letters':/[\uA739\uA73B]/g},
{'base':'ay','letters':/[\uA73D]/g},
{'base':'b', 'letters':/[\u0062\u24D1\uFF42\u1E03\u1E05\u1E07\u0180\u0183\u0253]/g},
{'base':'c', 'letters':/[\u0063\u24D2\uFF43\u0107\u0109\u010B\u010D\u00E7\u1E09\u0188\u023C\uA73F\u2184]/g},
{'base':'d', 'letters':/[\u0064\u24D3\uFF44\u1E0B\u010F\u1E0D\u1E11\u1E13\u1E0F\u0111\u018C\u0256\u0257\uA77A]/g},
{'base':'dz','letters':/[\u01F3\u01C6]/g},
{'base':'e', 'letters':/[\u0065\u24D4\uFF45\u00E8\u00E9\u00EA\u1EC1\u1EBF\u1EC5\u1EC3\u1EBD\u0113\u1E15\u1E17\u0115\u0117\u00EB\u1EBB\u011B\u0205\u0207\u1EB9\u1EC7\u0229\u1E1D\u0119\u1E19\u1E1B\u0247\u025B\u01DD]/g},
{'base':'f', 'letters':/[\u0066\u24D5\uFF46\u1E1F\u0192\uA77C]/g},
{'base':'g', 'letters':/[\u0067\u24D6\uFF47\u01F5\u011D\u1E21\u011F\u0121\u01E7\u0123\u01E5\u0260\uA7A1\u1D79\uA77F]/g},
{'base':'h', 'letters':/[\u0068\u24D7\uFF48\u0125\u1E23\u1E27\u021F\u1E25\u1E29\u1E2B\u1E96\u0127\u2C68\u2C76\u0265]/g},
{'base':'hv','letters':/[\u0195]/g},
{'base':'i', 'letters':/[\u0069\u24D8\uFF49\u00EC\u00ED\u00EE\u0129\u012B\u012D\u00EF\u1E2F\u1EC9\u01D0\u0209\u020B\u1ECB\u012F\u1E2D\u0268\u0131]/g},
{'base':'j', 'letters':/[\u006A\u24D9\uFF4A\u0135\u01F0\u0249]/g},
{'base':'k', 'letters':/[\u006B\u24DA\uFF4B\u1E31\u01E9\u1E33\u0137\u1E35\u0199\u2C6A\uA741\uA743\uA745\uA7A3]/g},
{'base':'l', 'letters':/[\u006C\u24DB\uFF4C\u0140\u013A\u013E\u1E37\u1E39\u013C\u1E3D\u1E3B\u017F\u0142\u019A\u026B\u2C61\uA749\uA781\uA747]/g},
{'base':'lj','letters':/[\u01C9]/g},
{'base':'m', 'letters':/[\u006D\u24DC\uFF4D\u1E3F\u1E41\u1E43\u0271\u026F]/g},
{'base':'n', 'letters':/[\u006E\u24DD\uFF4E\u01F9\u0144\u00F1\u1E45\u0148\u1E47\u0146\u1E4B\u1E49\u019E\u0272\u0149\uA791\uA7A5]/g},
{'base':'nj','letters':/[\u01CC]/g},
{'base':'o', 'letters':/[\u006F\u24DE\uFF4F\u00F2\u00F3\u00F4\u1ED3\u1ED1\u1ED7\u1ED5\u00F5\u1E4D\u022D\u1E4F\u014D\u1E51\u1E53\u014F\u022F\u0231\u00F6\u022B\u1ECF\u0151\u01D2\u020D\u020F\u01A1\u1EDD\u1EDB\u1EE1\u1EDF\u1EE3\u1ECD\u1ED9\u01EB\u01ED\u00F8\u01FF\u0254\uA74B\uA74D\u0275]/g},
{'base':'oi','letters':/[\u01A3]/g},
{'base':'ou','letters':/[\u0223]/g},
{'base':'oo','letters':/[\uA74F]/g},
{'base':'p','letters':/[\u0070\u24DF\uFF50\u1E55\u1E57\u01A5\u1D7D\uA751\uA753\uA755]/g},
{'base':'q','letters':/[\u0071\u24E0\uFF51\u024B\uA757\uA759]/g},
{'base':'r','letters':/[\u0072\u24E1\uFF52\u0155\u1E59\u0159\u0211\u0213\u1E5B\u1E5D\u0157\u1E5F\u024D\u027D\uA75B\uA7A7\uA783]/g},
{'base':'s','letters':/[\u0073\u24E2\uFF53\u00DF\u015B\u1E65\u015D\u1E61\u0161\u1E67\u1E63\u1E69\u0219\u015F\u023F\uA7A9\uA785\u1E9B]/g},
{'base':'t','letters':/[\u0074\u24E3\uFF54\u1E6B\u1E97\u0165\u1E6D\u021B\u0163\u1E71\u1E6F\u0167\u01AD\u0288\u2C66\uA787]/g},
{'base':'tz','letters':/[\uA729]/g},
{'base':'u','letters':/[\u0075\u24E4\uFF55\u00F9\u00FA\u00FB\u0169\u1E79\u016B\u1E7B\u016D\u00FC\u01DC\u01D8\u01D6\u01DA\u1EE7\u016F\u0171\u01D4\u0215\u0217\u01B0\u1EEB\u1EE9\u1EEF\u1EED\u1EF1\u1EE5\u1E73\u0173\u1E77\u1E75\u0289]/g},
{'base':'v','letters':/[\u0076\u24E5\uFF56\u1E7D\u1E7F\u028B\uA75F\u028C]/g},
{'base':'vy','letters':/[\uA761]/g},
{'base':'w','letters':/[\u0077\u24E6\uFF57\u1E81\u1E83\u0175\u1E87\u1E85\u1E98\u1E89\u2C73]/g},
{'base':'x','letters':/[\u0078\u24E7\uFF58\u1E8B\u1E8D]/g},
{'base':'y','letters':/[\u0079\u24E8\uFF59\u1EF3\u00FD\u0177\u1EF9\u0233\u1E8F\u00FF\u1EF7\u1E99\u1EF5\u01B4\u024F\u1EFF]/g},
{'base':'z','letters':/[\u007A\u24E9\uFF5A\u017A\u1E91\u017C\u017E\u1E93\u1E95\u01B6\u0225\u0240\u2C6C\uA763]/g}];
for (var i=0; i < chars.length; i++) {
s = s.replace(chars[i].letters, chars[i].base);
}
return s;
}
jQuery(function($) {
try {
if (window.gdMaps == 'osm') {
$('input[name="post_address"]').autocomplete({
source: function(request, response) {
$.ajax({
url: (location.protocol === 'https:' ? 'https:' : 'http:') + '//nominatim.openstreetmap.org/search',
dataType: "json",
data: {
q: request.term,
format: 'json',
addressdetails: 1,
limit: 5
},
success: function(data, textStatus, jqXHR) {
jQuery('input[name="post_address"]').removeClass('ui-autocomplete-loading');
response(data);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
},
complete: function(jqXHR, textStatus) {
jQuery('input[name="post_address"]').removeClass('ui-autocomplete-loading');
}
});
},
autoFocus: true,
minLength: 1,
appendTo: jQuery('input[name="post_address"]').closest('.geodir_form_row'),
open: function(event, ui) {
jQuery('input[name="post_address"]').removeClass('ui-autocomplete-loading');
},
select: function(event, ui) {
item = gd_osm_parse_item(ui.item);
event.preventDefault();
$('input[name="post_address"]').val(item.display_address);
geocodeResponseOSM(item, true);
},
close: function(event, ui) {
jQuery('input[name="post_address"]').removeClass('ui-autocomplete-loading');
}
}).autocomplete("instance")._renderItem = function(ul, item) {
if (!ul.hasClass('gd-osm-results')) {
ul.addClass('gd-osm-results');
}
var label = item.display_name;
/*
item = gd_osm_parse_item(item);
if (item.display_address) {
label = gd_highlight(label, item.display_address, '<span class="gdOQ">', '</span>');
}
*/
if (label && this.term) {
label = gd_highlight(label, this.term);
}
return $("<li>").width($('input[name="post_address"]').outerWidth()).append('<i class="fa fa-map-marker"></i><span>' + label + '</span>').appendTo(ul);
};
}
} catch (e) {
}
$('#gd_make_duplicates').click(function() {
var $btn = $(this);
var $el = $(this).closest('.gd-duplicate-table');
var nonce = $(this).data('nonce');
var post_id = $(this).data('post-id');
var dups = [];
$.each($('input[name="gd_icl_dup[]"]:checked', $el), function() {
dups.push($(this).val());
});
if (!dups.length || !post_id) {
$('input[name="gd_icl_dup[]"]', $el).focus();
return false;
}
var data = {
action: 'geodir_ajax_action',
geodir_ajax: 'duplicate',
post_id: post_id,
dups: dups.join(','),
_nonce: nonce
};
jQuery.ajax({
url: geodir_all_js_msg.geodir_admin_ajax_url,
data: data,
type: 'POST',
cache: false,
dataType: 'json',
beforeSend: function(xhr) {
$('.fa-refresh', $el).show();
$btn.attr('disabled', 'disabled');
},
success: function(res, status, xhr) {
if (typeof res == 'object' && res) {
if (res.success) {
window.location.href = document.location.href;
return;
}
if (res.error) {
alert(res.error);
}
}
}
}).complete(function(xhr, status) {
$('.fa-refresh', $el).hide();
$btn.removeAttr('disabled');
})
});
});
jQuery(function(){
if (window.gdMaps === 'google') {
console.log('Google Maps API Loaded :)');
jQuery('body').addClass('gd-google-maps');
} else if (window.gdMaps === 'osm') {
console.log('Leaflet | OpenStreetMap API Loaded :)');
jQuery('body').addClass('gd-osm-gmaps');
} else {
console.log('Maps API Not Loaded :(');
jQuery('body').addClass('gd-no-gmaps');
}
});
var gdMaps = null
if ((window.gdSetMap=='google' || window.gdSetMap=='auto') && window.google && typeof google.maps!=='undefined') {
gdMaps = 'google';
} else if ((window.gdSetMap=='osm' || window.gdSetMap=='auto') && typeof L!=='undefined' && typeof L.version!=='undefined') {
gdMaps = 'osm';
}
window.gdMaps = window.gdMaps || gdMaps; | mistergiri/geodirectory | geodirectory-assets/js/on_document_load.js | JavaScript | gpl-3.0 | 19,171 |
var searchData=
[
['main',['main',['../principal_8cpp.html#ae66f6b31b5ad750f1fe042a706a4e3d4',1,'principal.cpp']]],
['mday',['mday',['../classfecha.html#a9c1dc50e5f5efcd3e30a981bfd495b1d',1,'fecha']]],
['min',['min',['../classfecha.html#a3875f28ff6e7c383923c80e86afaec2e',1,'fecha']]],
['mon',['mon',['../classfecha.html#a5c86be74f1215600f99798d54126ba16',1,'fecha']]]
];
| Nitrosito/ED | Practicas/Practica2/source/html/search/all_8.js | JavaScript | gpl-3.0 | 380 |
"use strict"; // I ♥ JS
// Let's Code
(function($, window, document) {
var adminPanel = $("#admin");
$("#menu-toggle").on("click", function(e) {
e.preventDefault();
adminPanel.toggleClass("toggled");
});
})(window.jQuery, window, window.document);
var AngularFireCartAdmin = angular.module('AngularFireCartAdmin', [
'ngRoute',
"firebase"
]).value('fbURL', 'https://mbulont.firebaseio.com/');
AngularFireCartAdmin.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: "app-admin/views/index.html",
controller: "DashboardCtrl"
})
.when('/products', {
templateUrl: "app-admin/views/products.html",
controller: "ProductsCtrl"
})
.when('/categories', {
templateUrl: "app-admin/views/categories.html",
controller: "CategoriesCtrl"
})
.when('/orders', {
templateUrl: "app-admin/views/orders.html",
controller: "OrdersCtrl"
})
.when('/orders/:id', {
templateUrl: "app-admin/views/order.html",
controller: "OrderCtrl"
})
.when('/customers', {
templateUrl: "app-admin/views/customers.html",
controller: "CustomersCtrl"
})
.when('/customers/:id', {
templateUrl: "app-admin/views/customer.html",
controller: "CustomerCtrl"
})
.when('/settings', {
templateUrl: "app-admin/views/settings.html",
controller: "SettingsCtrl"
})
.otherwise({
template: "404 : OOPS!"
});
});
| ariestiyansyah/mbulont | app-admin/main.js | JavaScript | gpl-3.0 | 1,809 |
var should = require('should')
var fixtures = require('node-fixtures')
var updateName = require('../src/1fixture')
describe('fixtures', function() {
it('should read the name of person 1 in users fixture', function() {
should(fixtures.users.p1.name).equal('Michael')
})
it('should read the name of person 2 in users fixture', function() {
should(fixtures.users.p2.name).equal('Viktoria')
})
it('should change the name of person 1 in users fixture', function() {
var result = updateName(fixtures.users.p1, 'Mike')
should(result).equal('Mike')
})
it('should change the name of person 2 in users fixture', function() {
var result = updateName(fixtures.users.p2, 'Viki')
should(result).equal('Viki')
})
})
| andorfermichael/MMT-B2014-Frontend-Development-1 | 07-tdd/test/1fixture.js | JavaScript | gpl-3.0 | 785 |
'use strict';
var winston = require('winston');
var express = require('express');
var bodyParser = require('body-parser');
var fs = require('fs');
var path = require('path');
var childProcess = require('child_process');
var less = require('less');
var async = require('async');
var uglify = require('uglify-es');
var nconf = require('nconf');
var Benchpress = require('benchpressjs');
var app = express();
var server;
var formats = [
winston.format.colorize(),
];
const timestampFormat = winston.format((info) => {
var dateString = new Date().toISOString() + ' [' + global.process.pid + ']';
info.level = dateString + ' - ' + info.level;
return info;
});
formats.push(timestampFormat());
formats.push(winston.format.splat());
formats.push(winston.format.simple());
winston.configure({
level: 'verbose',
format: winston.format.combine.apply(null, formats),
transports: [
new winston.transports.Console({
handleExceptions: true,
}),
new winston.transports.File({
filename: 'logs/webinstall.log',
handleExceptions: true,
}),
],
});
var web = module.exports;
var scripts = [
'node_modules/jquery/dist/jquery.js',
'public/vendor/xregexp/xregexp.js',
'public/vendor/xregexp/unicode/unicode-base.js',
'public/src/utils.js',
'public/src/installer/install.js',
];
var installing = false;
var success = false;
var error = false;
var launchUrl;
web.install = function (port) {
port = port || 4567;
winston.info('Launching web installer on port ' + port);
app.use(express.static('public', {}));
app.engine('tpl', function (filepath, options, callback) {
async.waterfall([
function (next) {
fs.readFile(filepath, 'utf-8', next);
},
function (buffer, next) {
Benchpress.compileParse(buffer.toString(), options, next);
},
], callback);
});
app.set('view engine', 'tpl');
app.set('views', path.join(__dirname, '../src/views'));
app.use(bodyParser.urlencoded({
extended: true,
}));
async.parallel([compileLess, compileJS, copyCSS, loadDefaults], function (err) {
if (err) {
winston.error(err);
}
setupRoutes();
launchExpress(port);
});
};
function launchExpress(port) {
server = app.listen(port, function () {
winston.info('Web installer listening on http://%s:%s', '0.0.0.0', port);
});
}
function setupRoutes() {
app.get('/', welcome);
app.post('/', install);
app.post('/launch', launch);
app.get('/ping', ping);
app.get('/sping', ping);
}
function ping(req, res) {
res.status(200).send(req.path === '/sping' ? 'healthy' : '200');
}
function welcome(req, res) {
var dbs = ['redis', 'mongo', 'postgres'];
var databases = dbs.map(function (databaseName) {
var questions = require('../src/database/' + databaseName).questions.filter(function (question) {
return question && !question.hideOnWebInstall;
});
return {
name: databaseName,
questions: questions,
};
});
var defaults = require('./data/defaults');
res.render('install/index', {
url: nconf.get('url') || (req.protocol + '://' + req.get('host')),
launchUrl: launchUrl,
skipGeneralSetup: !!nconf.get('url'),
databases: databases,
skipDatabaseSetup: !!nconf.get('database'),
error: error,
success: success,
values: req.body,
minimumPasswordLength: defaults.minimumPasswordLength,
installing: installing,
});
}
function install(req, res) {
if (installing) {
return welcome(req, res);
}
req.setTimeout(0);
installing = true;
var setupEnvVars = nconf.get();
for (var i in req.body) {
if (req.body.hasOwnProperty(i) && !process.env.hasOwnProperty(i)) {
setupEnvVars[i.replace(':', '__')] = req.body[i];
}
}
// Flatten any objects in setupEnvVars
const pushToRoot = function (parentKey, key) {
setupEnvVars[parentKey + '__' + key] = setupEnvVars[parentKey][key];
};
for (var j in setupEnvVars) {
if (setupEnvVars.hasOwnProperty(j) && typeof setupEnvVars[j] === 'object' && setupEnvVars[j] !== null && !Array.isArray(setupEnvVars[j])) {
Object.keys(setupEnvVars[j]).forEach(pushToRoot.bind(null, j));
delete setupEnvVars[j];
} else if (Array.isArray(setupEnvVars[j])) {
setupEnvVars[j] = JSON.stringify(setupEnvVars[j]);
}
}
winston.info('Starting setup process');
winston.info(setupEnvVars);
launchUrl = setupEnvVars.url;
var child = require('child_process').fork('app', ['--setup'], {
env: setupEnvVars,
});
child.on('close', function (data) {
installing = false;
success = data === 0;
error = data !== 0;
welcome(req, res);
});
}
function launch(req, res) {
res.json({});
server.close();
var child;
if (!nconf.get('launchCmd')) {
child = childProcess.spawn('node', ['loader.js'], {
detached: true,
stdio: ['ignore', 'ignore', 'ignore'],
});
console.log('\nStarting NodeBB');
console.log(' "./nodebb stop" to stop the NodeBB server');
console.log(' "./nodebb log" to view server output');
console.log(' "./nodebb restart" to restart NodeBB');
} else {
// Use launchCmd instead, if specified
child = childProcess.exec(nconf.get('launchCmd'), {
detached: true,
stdio: ['ignore', 'ignore', 'ignore'],
});
}
var filesToDelete = [
'installer.css',
'installer.min.js',
'bootstrap.min.css',
];
async.each(filesToDelete, function (filename, next) {
fs.unlink(path.join(__dirname, '../public', filename), next);
}, function (err) {
if (err) {
winston.warn('Unable to remove installer files');
}
child.unref();
process.exit(0);
});
}
function compileLess(callback) {
fs.readFile(path.join(__dirname, '../public/less/install.less'), function (err, style) {
if (err) {
return winston.error('Unable to read LESS install file: ', err);
}
less.render(style.toString(), function (err, css) {
if (err) {
return winston.error('Unable to compile LESS: ', err);
}
fs.writeFile(path.join(__dirname, '../public/installer.css'), css.css, callback);
});
});
}
function compileJS(callback) {
var code = '';
async.eachSeries(scripts, function (srcPath, next) {
fs.readFile(path.join(__dirname, '..', srcPath), function (err, buffer) {
if (err) {
return next(err);
}
code += buffer.toString();
next();
});
}, function (err) {
if (err) {
return callback(err);
}
try {
var minified = uglify.minify(code, {
compress: false,
});
if (!minified.code) {
return callback(new Error('[[error:failed-to-minify]]'));
}
fs.writeFile(path.join(__dirname, '../public/installer.min.js'), minified.code, callback);
} catch (e) {
callback(e);
}
});
}
function copyCSS(next) {
async.waterfall([
function (next) {
fs.readFile(path.join(__dirname, '../node_modules/bootstrap/dist/css/bootstrap.min.css'), 'utf8', next);
},
function (src, next) {
fs.writeFile(path.join(__dirname, '../public/bootstrap.min.css'), src, next);
},
], next);
}
function loadDefaults(next) {
var setupDefaultsPath = path.join(__dirname, '../setup.json');
fs.access(setupDefaultsPath, fs.constants.F_OK | fs.constants.R_OK, function (err) {
if (err) {
// setup.json not found or inaccessible, proceed with no defaults
return setImmediate(next);
}
winston.info('[installer] Found setup.json, populating default values');
nconf.file({
file: setupDefaultsPath,
});
next();
});
}
| akhoury/NodeBB | install/web.js | JavaScript | gpl-3.0 | 7,262 |
Schema = {};
TermSchema = new SimpleSchema({
term: {
type: String,
label: 'Término'
},
humanterm: {
type: String,
label: 'Término humano'
},
shuffle: {
type: Boolean,
label: 'Shuffle term?'
}
});
Schema.Dict = new SimpleSchema({
group: {
type: String,
label: 'Grupo',
},
name: {
type: String,
label: 'Nombre',
},
slug: {
type: String,
label: 'Slug (Url corta)',
optional: true
},
description: {
type: String,
label: 'Descripción',
optional: true
},
icon1: {
type: String,
label: 'Icono1',
optional: true
},
icon2: {
type: String,
label: 'Icono2',
optional: true
},
iconb1: {
type: String,
label: 'IconoB1',
optional: true
},
iconb2: {
type: String,
label: 'IconoB2',
optional: true
},
terms: {
type: [TermSchema],
label: 'Expresiones regulares',
optional: true
}
});
Dicts = new Meteor.Collection('dicts', {'idGeneration': 'MONGO'});
Dicts.attachSchema(Schema.Dict);
| CIECODE-Madrid/tipi | lib/models/dicts.js | JavaScript | gpl-3.0 | 1,183 |
var searchData=
[
['move_5fonly_5fallocation_5ftest_0',['move_only_allocation_test',['../d3/d67/MoveOnlyAllocationTestCore_8hpp.html#ae2b2913ae89b8818cd9ea2d68d43980b',1,'sequoia::testing']]],
['move_5fonly_5ftest_1',['move_only_test',['../de/d25/MoveOnlyTestCore_8hpp.html#a198c390bfabb54c797a6fcfe8dec09cd',1,'sequoia::testing']]]
];
| ojrosten/sequoia | docs/html/search/typedefs_1.js | JavaScript | gpl-3.0 | 340 |
/*
Copyright (C) 2016 PencilBlue, LLC
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/>.
*/
module.exports = function(pb) {
//pb dependencies
var util = pb.util;
/**
* Interface for importing topics from CSV
*/
function ImportTopics(){}
util.inherits(ImportTopics, pb.BaseAdminController);
//statics
var SUB_NAV_KEY = 'import_topics';
ImportTopics.prototype.render = function(cb) {
var self = this;
var tabs =
[
{
active: 'active',
href: '#topic_settings',
icon: 'file-text-o',
title: self.ls.get('LOAD_FILE')
}
];
var angularObjects = pb.ClientJs.getAngularObjects(
{
navigation: pb.AdminNavigation.get(self.session, ['content', 'topics'], self.ls, self.site),
pills: self.getAdminPills(SUB_NAV_KEY, self.ls, 'manage_topics'),
tabs: tabs
});
this.setPageName(this.ls.get('IMPORT_TOPICS'));
self.ts.registerLocal('angular_objects', new pb.TemplateValue(angularObjects, false));
this.ts.load('admin/content/topics/import_topics', function(err, result) {
cb({content: result});
});
};
ImportTopics.getSubNavItems = function(key, ls, data) {
return [{
name: 'manage_topics',
title: ls.get('IMPORT_TOPICS'),
icon: 'chevron-left',
href: '/admin/content/topics'
}, {
name: 'import_topics',
title: '',
icon: 'upload',
href: '/admin/content/topics/import'
}, {
name: 'new_topic',
title: '',
icon: 'plus',
href: '/admin/content/topics/new'
}];
};
//register admin sub-nav
pb.AdminSubnavService.registerFor(SUB_NAV_KEY, ImportTopics.getSubNavItems);
//exports
return ImportTopics;
};
| Whatsit2yaa/vast-tundra-84597 | plugins/pencilblue/controllers/admin/content/topics/import_topics.js | JavaScript | gpl-3.0 | 2,564 |
import { ApolloServer } from 'apollo-server-express';
import { importSchema } from 'graphql-import';
import { join } from 'path';
import resolvers from '../schema/resolvers';
async function configureGraphQL(app) {
const typeDefs = importSchema(join(__dirname, '..', 'schema', 'schema.graphql'));
const server = new ApolloServer({
typeDefs,
resolvers,
context: ({ req }) => ({
user: req.user,
token: req.headers.authorization,
identity: req.headers.identity ? JSON.parse(req.headers.identity) : {},
}),
playground: process.env.NODE_ENV !== 'production',
});
await server.start();
server.applyMiddleware({ app, path: '/api' });
}
export default { configureGraphQL };
| NERC-CEH/datalab | code/workspaces/client-api/src/config/graphql.js | JavaScript | gpl-3.0 | 718 |
describe('Test Nac Bar', function() {
var injector;
var element;
var scope;
var compiler;
var httpBackend;
beforeEach(function() {
injector = angular.injector(['myApp', 'ngMockE2E']);
intercepts = {};
injector.invoke(function($rootScope, $compile, $httpBackend) {
scope = $rootScope.$new();
compiler = $compile;
httpBackend = $httpBackend;
});
});
it('shows logged in users name', function(done) {
// Adding httpBackend passthrough for template request
// to make sure static file request didn't get blocked.
httpBackend.whenGET('/public/template.html').passThrough();
httpBackend.expectGET('/api/v1/me').respond({
user: { profile: {username: 'Johney' } }
});
element = compiler('<user-menu></user-menu>')(scope);
scope.$apply();
scope.$on('MyHttpController', function() {
httpBackend.flush();
assert.notEqual(element.find('.user').css('display'), 'none');
assert.equal(element.find('.user').text().trim(), 'Current User: Johney');
done();
});
});
}); | lufanbb/MEAN_RetailStore | Chpt3_Retail_Store_API/Angular/angular_test.js | JavaScript | gpl-3.0 | 1,020 |
//Date Editor
function DateCellEditor () {}
// gets called once before the renderer is used
DateCellEditor.prototype.init = function(params) {
// create the cell
this.eInput = document.createElement('input');
this.eInput.value = params.value;
// https://jqueryui.com/datepicker/
$(this.eInput).datepicker({
dateFormat: "dd/mm/yyyy",
changeMonth: true,
changeYear: true,
autoclose: true,
clearBtn: true
}).on('hide', function(e) {
params.stopEditing();
});
};
// gets called once when grid ready to insert the element
DateCellEditor.prototype.getGui = function() {
return this.eInput;
};
// focus and select can be done after the gui is attached
DateCellEditor.prototype.afterGuiAttached = function() {
this.eInput.focus();
this.eInput.select();
};
// returns the new value after editing
DateCellEditor.prototype.isCancelBeforeStart = function () {
return this.cancelBeforeStart;
};
// returns the new value after editing
DateCellEditor.prototype.getValue = function() {
return this.eInput.value;
};
// any cleanup we need to be done here
DateCellEditor.prototype.destroy = function() {
// but this example is simple, no cleanup, we could
// even leave this method out as it's optional
};
// if true, then this editor will appear in a popup
DateCellEditor.prototype.isPopup = function() {
// and we could leave this method out also, false is the default
return false;
};
| greenriver/hmis-warehouse | app/assets/javascripts/cohorts/editors/date_cell_editor.js | JavaScript | gpl-3.0 | 1,434 |
requirejs.onError = function (err) {
console.error(err);
};
window.onerror = function (err) {
console.error(err);
};
require(['src/config.js'],
function (config) {
require.config(config);
require(['ui/main'], function (main) {});
});
| TalesM/syntaxer | src/main.js | JavaScript | gpl-3.0 | 252 |
// This file is generated
P_locations_0 = [
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[]
]
Dwr.ScriptLoaded('dwr_db_P_locations_0.js');
| belissent/GrampsDynamicWebReport | reports/report_003/dwr_db_P_locations_0.js | JavaScript | gpl-3.0 | 3,647 |
/**
*
* The Scheduler UI.
* ================
*
* The scheduler supports two modes:
* 1. Editable mode - The user can drag-drop and resize sessions
* 2. Readonly mode - The sessions are displayed on the timeline, but cannot be edited.
*
* The Editable mode is turned on by default. To switch to Readonly mode, set the variable
* window.scheduler_readonly = true;
* Before including this file.
*
* -@niranjan94
*/
/**
* TIME CONFIGURATION & MANIPULATION
* =================================
*
* 48px === 15 minutes
* (Smallest unit of measurement is 15 minutes)
*
*/
var time = {
start: {
hours: 0,
minutes: 0
},
end: {
hours: 23,
minutes: 59
},
unit: {
minutes: 15,
pixels: 48,
count: 0
},
format: "YYYY-MM-DD HH:mm:ss"
};
window.dayLevelTime = {
start: {
hours: parseInt(time.start.hours),
minutes: parseInt(time.start.minutes)
},
end: {
hours: parseInt(time.end.hours),
minutes: parseInt(time.end.minutes)
}
};
//noinspection JSValidateTypes
/**
* @type {{id: number, start_time: moment.Moment, end_time: moment.Moment}}
*/
window.mainEvent = {};
/**
* Whether the scheduler is to be run in readonly mode or not.
* @returns {boolean}
*/
function isReadOnly() {
return !(_.isUndefined(window.scheduler_readonly) || _.isNull(window.scheduler_readonly) || window.scheduler_readonly !== true);
}
/**
* Convert minutes to pixels based on the time unit configuration
* @param {number} minutes The minutes that need to be converted to pixels
* @param {boolean} [forTop=false] Indicate whether top header compensation needs to be done
* @returns {number} The pixels
*/
function minutesToPixels(minutes, forTop) {
minutes = Math.abs(minutes);
if (forTop) {
return ((minutes / time.unit.minutes) * time.unit.pixels) + time.unit.pixels;
} else {
return (minutes / time.unit.minutes) * time.unit.pixels;
}
}
/**
* Convert pixels to minutes based on the time unit configuration
* @param {number} pixels The pixels that need to be converted to minutes
* @param {boolean} [fromTop=false] Indicate whether top header compensation needs to be done
* @returns {number} The minutes
*/
function pixelsToMinutes(pixels, fromTop) {
pixels = Math.abs(pixels);
if (fromTop) {
return ((pixels - time.unit.pixels) / time.unit.pixels) * time.unit.minutes;
} else {
return (pixels / time.unit.pixels) * time.unit.minutes;
}
}
/**
* IN-MEMORY DATA STORES
* =====================
*
* @type {Array}
*/
var days = [];
var tracks = [];
var sessionsStore = [];
var microlocationsStore = [];
var unscheduledStore = [];
/**
* jQuery OBJECT REFERENCES
* ========================
*
* @type {jQuery|HTMLElement}
*/
var $timeline = $("#timeline");
var $microlocations = $(".microlocation");
var $unscheduledSessionsList = $("#sessions-list");
var $microlocationsHolder = $("#microlocation-container");
var $unscheduledSessionsHolder = $unscheduledSessionsList;
var $noSessionsInfoBox = $("#no-sessions-info");
var $dayButtonsHolder = $("#date-change-btn-holder");
var $addMicrolocationForm = $('#add-microlocation-form');
var $timelineTable = $('table.timeline-table');
var $noSessionMessage = $('#no-session-message');
var $mobileTimeline = $("#mobile-timeline");
var $tracksTimeline = $("#tracks-timeline");
var $sessionViewHolder = $("#session-view-holder");
/**
* TEMPLATE STRINGS
* ================
*
* @type {string}
*/
var microlocationTemplate = $("#microlocation-template").html();
var sessionTemplate = $("#session-template").html();
var dayButtonTemplate = $("#date-change-button-template").html();
var mobileMicrolocationTemplate = $("#mobile-microlocation-template").html();
var mobileSessionTemplate = $("#mobile-session-template").html();
/**
* Data Getters
* ============
*
*/
/**
*
* @param {int|Object|jQuery} sessionRef Can be session ID, or session object or an existing session element from the target
* @param {jQuery} $searchTarget the target to search for the element
* @returns {Object} Returns object with session element and session object
*/
function getSessionFromReference(sessionRef, $searchTarget) {
var $sessionElement;
var session;
var newElement = false;
if (sessionRef instanceof jQuery) {
$sessionElement = sessionRef;
session = $sessionElement.data("session");
} else if (_.isObjectLike(sessionRef)) {
$sessionElement = $searchTarget.find(".session[data-session-id=" + sessionRef.id + "]");
// If it's a new session, create session element from template and initialize
if ($sessionElement.length === 0) {
$sessionElement = $(sessionTemplate);
$sessionElement.attr("data-session-id", sessionRef.id);
$sessionElement.attr("data-original-text", sessionRef.title);
$sessionElement.data("session", sessionRef);
newElement = true;
}
session = sessionRef;
} else if (_.isNumber(sessionRef)) {
$sessionElement = $searchTarget.find(".session[data-session-id=" + sessionRef + "]");
session = $sessionElement.data("session");
} else {
return false;
}
return {
$sessionElement: $sessionElement,
session: session,
newElement: newElement
};
}
/**
* UI MANIPULATION METHODS
* =======================
*
*/
/**
* Add a session to the timeline at the said position
* @param {int|Object|jQuery} sessionRef Can be session ID, or session object or an existing session element from the unscheduled list
* @param {Object} [position] Contains position information if the session is changed (microlocation-id and top)
* @param {boolean} [shouldBroadcast=true]
*/
function addSessionToTimeline(sessionRef, position, shouldBroadcast) {
var sessionRefObject;
if (_.isUndefined(position)) {
sessionRefObject = getSessionFromReference(sessionRef, $unscheduledSessionsHolder);
} else {
sessionRefObject = getSessionFromReference(sessionRef, $microlocationsHolder);
}
if (!sessionRefObject) {
logError("addSessionToTimeline", sessionRef);
return false;
}
if ((_.isNull(sessionRefObject.session.microlocation) || _.isNull(sessionRefObject.session.microlocation.id)) && isUndefinedOrNull(position)) {
addSessionToUnscheduled(sessionRefObject.$sessionElement);
return;
}
var oldMicrolocation = (_.isNull(sessionRefObject.session.microlocation) ? 0 : sessionRefObject.session.microlocation.id);
var newMicrolocation = null;
if (!isUndefinedOrNull(position)) {
sessionRefObject.session.top = position.top;
sessionRefObject.session.microlocation = {
id: position.microlocation_id,
name: position.microlocation_name
};
newMicrolocation = position.microlocation_id;
sessionRefObject.session = updateSessionTime(sessionRefObject.$sessionElement);
sessionRefObject.$sessionElement.data("session", sessionRefObject.session);
} else {
if (isUndefinedOrNull(shouldBroadcast) || shouldBroadcast) {
sessionRefObject.session = updateSessionTime(sessionRefObject.$sessionElement);
}
}
sessionRefObject.$sessionElement.css({
"-webkit-transform": "",
"transform": ""
}).removeData("x").removeData("y");
sessionRefObject.$sessionElement.removeClass("unscheduled").addClass("scheduled");
delete sessionRefObject.session.start_time.isReset;
delete sessionRefObject.session.end_time.isReset;
sessionRefObject.$sessionElement.data("temp-top", sessionRefObject.session.top);
sessionRefObject.$sessionElement.css("top", sessionRefObject.session.top + "px");
sessionRefObject.$sessionElement.css("height", minutesToPixels(sessionRefObject.session.duration) + "px");
$microlocationsHolder.find(".microlocation[data-microlocation-id=" + sessionRefObject.session.microlocation.id + "] > .microlocation-inner").append(sessionRefObject.$sessionElement);
updateSessionTimeOnTooltip(sessionRefObject.$sessionElement);
updateColor(sessionRefObject.$sessionElement, sessionRefObject.session.track);
var $mobileSessionElement = $(mobileSessionTemplate);
$mobileSessionElement.find('.time').text(sessionRefObject.session.start_time.format('hh:mm A'));
$mobileSessionElement.find('.event').text(sessionRefObject.session.title);
$mobileSessionElement.find('.event').attr("data-target", "#session-track-details"+sessionRefObject.session.id);
$mobileSessionElement.find('.session-track-details').attr("id", "session-track-details"+sessionRefObject.session.id);
$mobileSessionElement.find('.session-speakers').text("Speakers: ");
_.each(sessionRefObject.session.speakers, function(speaker) {
$mobileSessionElement.find('.session-speakers').append(speaker.name);
});
$mobileSessionElement.find('.session-description').html(sessionRefObject.session.short_abstract);
$mobileSessionElement.find('.session-location').html(sessionRefObject.session.microlocation.name+'<i class="fa fa-map-marker fa-fw"></i>');
updateColor($mobileSessionElement.find('.event'), sessionRefObject.session.track);
$mobileTimeline.find(".mobile-microlocation[data-microlocation-id=" + sessionRefObject.session.microlocation.id + "] > .mobile-sessions-holder").append($mobileSessionElement);
if(sessionRefObject.session.hasOwnProperty('track') && !_.isNull(sessionRefObject.session.track)) {
$tracksTimeline.find(".mobile-microlocation[data-track-id=" + sessionRefObject.session.track.id + "] > .mobile-sessions-holder").append($mobileSessionElement.clone());
}
if (isUndefinedOrNull(shouldBroadcast) || shouldBroadcast) {
if (!sessionRefObject.newElement) {
$(document).trigger({
type: "scheduling:change",
session: sessionRefObject.session
});
}
$(document).trigger({
type: "scheduling:recount",
microlocations: [oldMicrolocation, newMicrolocation]
});
}
_.remove(unscheduledStore, function (sessionTemp) {
return sessionTemp.id === sessionRefObject.session.id;
});
addInfoBox(sessionRefObject.$sessionElement, sessionRefObject.session);
sessionRefObject.$sessionElement.ellipsis().ellipsis();
}
/**
* Remove a session from the timeline and add it to the Unscheduled list or create a session element and add to Unscheduled list
* @param {int|Object|jQuery} sessionRef Can be session ID, or session object or an existing session element from the timeline
* @param {boolean} [isFiltering=false]
* @param {boolean} [shouldBroadcast=true]
*/
function addSessionToUnscheduled(sessionRef, isFiltering, shouldBroadcast) {
var session;
var sessionRefObject = getSessionFromReference(sessionRef, $microlocationsHolder);
if (!sessionRefObject) {
logError("addSessionToUnscheduled", sessionRef);
return false;
}
var oldMicrolocation = (_.isNull(sessionRefObject.session.microlocation) ? 0 : sessionRefObject.session.microlocation.id);
sessionRefObject.session.top = null;
sessionRefObject.session.duration = 30;
sessionRefObject.session.start_time.hours(0).minutes(0);
sessionRefObject.session.end_time.hours(0).minutes(0);
sessionRefObject.session.microlocation = null;
sessionRefObject.session.start_time.isReset = true;
sessionRefObject.session.end_time.isReset = true;
sessionRefObject.$sessionElement.data("session", sessionRefObject.session);
$unscheduledSessionsHolder.append(sessionRefObject.$sessionElement);
sessionRefObject.$sessionElement.addClass('unscheduled').removeClass('scheduled');
resetTooltip(sessionRefObject.$sessionElement);
sessionRefObject.$sessionElement.css({
"-webkit-transform": "",
"transform": "",
"background-color": "",
"height": "48px",
"top": ""
}).removeData("x").removeData("y");
updateColor(sessionRefObject.$sessionElement, sessionRefObject.session.track);
sessionRefObject.$sessionElement.ellipsis().ellipsis();
$noSessionsInfoBox.hide();
if (isUndefinedOrNull(isFiltering) || !isFiltering) {
if (isUndefinedOrNull(shouldBroadcast) || shouldBroadcast) {
if (!sessionRefObject.newElement) {
$(document).trigger({
type: "scheduling:change",
session: sessionRefObject.session
});
}
$(document).trigger({
type: "scheduling:recount",
microlocations: [oldMicrolocation]
});
}
unscheduledStore.push(sessionRefObject.session);
}
try {
setTimeout( function() {
$('.session.unscheduled').popover('hide');
}, 100);
}
catch(ignored) { }
}
/**
* Update the counter badge that displays the number of sessions under each microlocation
* @param {array} microlocationIds An array of microlocation IDs to recount
*/
function updateMicrolocationSessionsCounterBadges(microlocationIds) {
_.each(microlocationIds, function (microlocationId) {
var $microlocation = $microlocationsHolder.find(".microlocation[data-microlocation-id=" + microlocationId + "] > .microlocation-inner");
var sessionsCount = $microlocation.find(".session.scheduled").length;
$microlocation.find(".microlocation-header > .badge").text(sessionsCount);
});
}
/**
* Randomly generate and set a background color for an element
* @param {jQuery} $element the element to be colored
* @param [track]
*/
function updateColor($element, track) {
if(!_.isUndefined(track)) {
if(_.isNull(track)) {
Math.seedrandom('null');
} else {
Math.seedrandom(track.name+track.id);
if(!_.isNull(track.color) && !_.isEmpty(track.color)) {
$element.css("background-color", track.color.trim());
$element.css("background-color", track.color.trim());
return;
}
}
} else {
Math.seedrandom();
}
$element.css("background-color", palette.random("800"));
$element.css("background-color", palette.random("800"));
}
/**
* Move any overlapping session to the unscheduled list. To be run as soon as timeline is initialized.
*/
function removeOverlaps() {
var $sessionElements = $microlocationsHolder.find(".session.scheduled");
_.each($sessionElements, function ($sessionElement) {
$sessionElement = $($sessionElement);
var isColliding = isSessionOverlapping($sessionElement);
if (isColliding) {
addSessionToUnscheduled($sessionElement);
}
});
}
/**
* Check if a session is overlapping any other session
* @param {jQuery} $session The session
* @param {jQuery} [$microlocation] The microlocation to search in
* @returns {boolean|jQuery} If no overlap, return false. If overlaps, return the session that's beneath.
*/
function isSessionOverlapping($session, $microlocation) {
if (isUndefinedOrNull($microlocation)) {
$microlocation = $session.parent();
}
var $otherSessions = $microlocation.find(".session.scheduled");
var returnVal = false;
_.each($otherSessions, function ($otherSession) {
$otherSession = $($otherSession);
if (!$otherSession.is($session) && collision($otherSession, $session)) {
returnVal = $otherSession;
}
});
return returnVal;
}
/**
* Check if the session is within the timeline
* @param {jQuery} $sessionElement the session element to check
* @returns {boolean} Return true, if outside the boundary. Else, false.
*/
function isSessionRestricted($sessionElement) {
return !horizontallyBound($microlocations, $sessionElement, 0);
}
/**
* Check if the session element is over the timeline
* @param {jQuery} $sessionElement the session element to check
* @returns {boolean}
*/
function isSessionOverTimeline($sessionElement) {
try {
return collision($microlocations, $sessionElement);
} catch (e) {
return false;
}
}
/**
* Update the session's time on it's tooltip and display it.
* @param {jQuery} $sessionElement the target session element
*/
function updateSessionTimeOnTooltip($sessionElement) {
var topTime = moment.utc({hour: dayLevelTime.start.hours, minute: dayLevelTime.start.minutes});
var mins = pixelsToMinutes($sessionElement.outerHeight(false));
var topInterval = pixelsToMinutes($sessionElement.data("temp-top"), true);
var startTimeString = topTime.add(topInterval, 'm').format("LT");
var endTimeString = topTime.add(mins, "m").format("LT");
$sessionElement.tooltip('destroy').tooltip({
placement : 'top',
title : startTimeString + " to " + endTimeString
});
$sessionElement.tooltip("show");
}
/**
* Clear a tooltip on a session element.
* @param {jQuery} $sessionElement the target session element
*/
function resetTooltip($sessionElement) {
$sessionElement.tooltip("hide").tooltip({
placement : 'top',
title : ""
});
}
/**
* Update the session time and store to the session object
* @param {jQuery} $sessionElement The session element to update
* @param {object} [session] the session object to work on
* @returns {*}
*/
function updateSessionTime($sessionElement, session) {
var saveSession = false;
if (_.isUndefined(session)) {
session = $sessionElement.data("session");
saveSession = true;
}
var day = session.start_time.format("Do MMMM YYYY");
var dayIndex = _.indexOf(days, day);
var selectedDate = moment($('.date-change-btn.active').text(), "Do MMMM YYYY");
var topTime = moment.utc({hour: dayLevelTime.start.hours, minute: dayLevelTime.start.minutes});
var mins = pixelsToMinutes($sessionElement.outerHeight(false));
var topInterval = pixelsToMinutes($sessionElement.data("temp-top"), true);
var newStartTime = _.cloneDeep(topTime.add(topInterval, 'm'));
var newEndTime = topTime.add(mins, "m");
session.duration = mins;
session.start_time.date(selectedDate.date());
session.start_time.month(selectedDate.month());
session.start_time.year(selectedDate.year());
session.start_time.hours(newStartTime.hours());
session.start_time.minutes(newStartTime.minutes());
session.end_time.date(selectedDate.date());
session.end_time.month(selectedDate.month());
session.end_time.year(selectedDate.year());
session.end_time.hours(newEndTime.hours());
session.end_time.minutes(newEndTime.minutes());
_.each(sessionsStore[dayIndex], function (stored_session) {
if (stored_session.id === session.id) {
var index = sessionsStore[dayIndex].indexOf(session);
if (index > -1) {
sessionsStore[dayIndex].splice(index, 1);
}
var dayString = session.start_time.format("Do MMMM YYYY");
var dayIndex1 = _.indexOf(days, dayString);
if (_.isArray(sessionsStore[dayIndex1])) {
sessionsStore[dayIndex1].push(session);
} else {
sessionsStore[dayIndex1] = [session];
}
}
});
if (saveSession) {
$sessionElement.data("session", session);
}
return session;
}
/**
* Add info Box to the session element
* @param {jQuery} $sessionElement The session element to update
* @param {object} [session] the session object to work on
*/
function addInfoBox($sessionElement, session) {
if(isReadOnly()) {
$sessionElement.css('cursor', 'pointer');
}
$sessionElement.popover({
trigger: 'manual',
placement: 'bottom',
html: true,
title: session.title
});
var content = "";
if(!_.isNull(session.short_abstract)) {
content += "<strong>About the session:</strong> " + session.short_abstract + "<br><br>";
} else {
session.long_abstract = session.long_abstract.substr(0, 100);
content += "<strong>About the session:</strong> " + session.long_abstract + "<br><br>";
}
_.forEach(session.speakers, function(speaker, index) {
if(session.speakers.length === 1) {
content += "<strong>Speaker: </strong> " + speaker.name + "<br><br>";
} else {
content += "<strong>Speaker </strong> " + (parseInt(index, 10)+1) + "<strong> :</strong> " + speaker.name + "<br><br>";
}
if(speaker.short_biography) {
content += "<strong>About the Speaker: </strong><br>" + speaker.short_biography + "<br><br>";
} else {
session.speakers.long_biography = speaker.long_biography.substr(1, 100);
content += "<strong>About the Speaker: </strong><br>" + speaker.long_biography + "<br><br>";
}
});
if(!_.isNull(session.start_time)) {
content += "<strong>Start Time:</strong> " + session.start_time.format("HH:mm:ss") + "<br>";
}
if(!_.isNull(session.end_time)) {
content += "<strong>End Time:</strong> " + session.end_time.format("HH:mm:ss") + "<br>";
}
if(!_.isNull(session.track)) {
content += "<strong>Track:</strong> " + session.track.name + "<br>";
}
if(!_.isNull(session.microlocation)) {
content += "<strong>Room:</strong> " + session.microlocation.name + "<br>";
}
$sessionElement.attr("data-content", content);
}
/**
* Add a new microlocation to the timeline
* @param {object} microlocation The microlocation object containing the details of the microlocation
*/
function addMicrolocationToTimeline(microlocation) {
var $microlocationElement = $(microlocationTemplate);
$microlocationElement.attr("data-microlocation-id", microlocation.id);
$microlocationElement.attr("data-microlocation-name", microlocation.name);
$microlocationElement.find(".microlocation-header").html(microlocation.name + " <span class='badge'>0</span>");
$microlocationElement.find(".microlocation-inner").css("height", time.unit.count * time.unit.pixels + "px");
$microlocationsHolder.append($microlocationElement);
var $mobileMicrolocationElement = $(mobileMicrolocationTemplate);
$mobileMicrolocationElement.find('.name').text(microlocation.name);
$mobileMicrolocationElement.attr("data-microlocation-id", microlocation.id);
$mobileTimeline.append($mobileMicrolocationElement);
}
/**
* Generate timeunits for the timeline
*/
function generateTimeUnits() {
var start = moment.utc().hour(window.dayLevelTime.start.hours).minute(window.dayLevelTime.start.minutes).second(0);
var end = moment.utc().hour(window.dayLevelTime.end.hours).minute(window.dayLevelTime.end.minutes).second(0);
var $timeUnitsHolder = $(".timeunits");
$timeUnitsHolder.html('<div class="timeunit"></div>');
var timeUnitsCount = 1;
while (start <= end) {
var timeUnitDiv = $("<div class='timeunit'>" + start.format('HH:mm') + "</div>");
$timeUnitsHolder.append(timeUnitDiv);
start.add(time.unit.minutes, 'minutes');
timeUnitsCount++;
}
$microlocationsHolder.css("height", timeUnitsCount * time.unit.pixels);
time.unit.count = timeUnitsCount;
}
/**
*
*
*
*/
/**
* Initialize all the interactables necessary (drag-drop and resize)
*/
function initializeInteractables() {
$microlocations = $microlocationsHolder.find(".microlocation");
interact(".session")
.draggable({
// enable inertial throwing
inertia: false,
// enable autoScroll
autoScroll: {
margin: 50,
distance: 5,
interval: 10
},
restrict: {
restriction: ".draggable-holder"
},
// call this function on every dragmove event
onmove: function (event) {
var $sessionElement = $(event.target),
x = (parseFloat($sessionElement.data('x')) || 0) + event.dx,
y = (parseFloat($sessionElement.data('y')) || 0) + event.dy;
$sessionElement.css("-webkit-transform", "translate(" + x + "px, " + y + "px)");
$sessionElement.css("transform", "translate(" + x + "px, " + y + "px)");
$sessionElement.data('x', x);
$sessionElement.data('y', y);
$sessionElement.data("temp-top", roundOffToMultiple($sessionElement.offset().top - $(".microlocations.x1").offset().top));
if (isSessionOverTimeline($sessionElement)) {
updateSessionTimeOnTooltip($sessionElement);
} else {
resetTooltip($sessionElement);
}
},
// call this function on every dragend event
onend: function (event) {
}
});
interact(".session")
.resizable({
preserveAspectRatio: false,
enabled: true,
edges: {left: false, right: false, bottom: true, top: false}
})
.on("resizemove", function (event) {
if ($(event.target).hasClass("scheduled")) {
var target = event.target,
x = (parseFloat(target.getAttribute("data-x")) || 0),
y = (parseFloat(target.getAttribute("data-y")) || 0);
if(roundOffToMultiple(event.rect.height) < time.unit.pixels) {
target.style.height = time.unit.pixels + "px";
} else {
target.style.height = roundOffToMultiple(event.rect.height) + "px";
}
$(event.target).ellipsis();
updateSessionTimeOnTooltip($(event.target));
}
})
.on("resizeend", function (event) {
if ($(event.target).hasClass("scheduled")) {
var $sessionElement = $(event.target);
$(document).trigger({
type: "scheduling:change",
session: updateSessionTime($sessionElement)
});
}
});
interact(".microlocation-inner").dropzone({
// only accept elements matching this CSS selector
accept: ".session",
// Require a 75% element overlap for a drop to be possible
overlap: 0.50,
ondropactivate: function (event) {
$(event.target).addClass("drop-active");
},
ondragenter: function (event) {
$(event.target).addClass("drop-now");
},
ondragleave: function (event) {
$(event.target).removeClass("drop-now");
},
ondrop: function (event) {
var $sessionElement = $(event.relatedTarget);
var $microlocationDropZone = $(event.target);
$microlocationDropZone.removeClass("drop-active").removeClass("drop-now");
addSessionToTimeline($sessionElement, {
microlocation_id: parseInt($microlocationDropZone.parent().attr("data-microlocation-id")),
microlocation_name: $microlocationDropZone.parent().attr("data-microlocation-name"),
top: $sessionElement.data("temp-top")
});
var isColliding = isSessionOverlapping($sessionElement, $microlocationDropZone);
if (!isColliding) {
updateSessionTime($sessionElement);
} else {
createSnackbar("Session cannot be dropped onto another sessions.", "Try Again");
addSessionToUnscheduled($sessionElement);
}
},
ondropdeactivate: function (event) {
var $microlocationDropZone = $(event.target);
var $sessionElement = $(event.relatedTarget);
$microlocationDropZone.removeClass("drop-now").removeClass("drop-active");
if (!$sessionElement.hasClass("scheduled")) {
$sessionElement.css({
"-webkit-transform": "",
"transform": "",
"background-color": ""
}).removeData("x").removeData("y");
resetTooltip($sessionElement);
}
}
});
}
/**
* This callback called after sessions and microlocations are processed.
* @callback postProcessCallback
*/
/**
* Process the microlocations and sessions data loaded from the server into in-memory data stores
* @param {object} microlocations The microlocations json object
* @param {object} sessions The sessions json object
* @param {postProcessCallback} callback The post-process callback
*/
function processMicrolocationSession(microlocations, sessions, callback) {
_.each(sessions, function (session) {
if (session.state === 'accepted') {
session = _.cloneDeep(session);
var startTime = moment.utc(session.start_time);
var endTime = moment.utc(session.end_time);
if (startTime.isSame(mainEvent.start_time, "day")) {
window.dayLevelTime.start.hours = mainEvent.start_time.hours();
window.dayLevelTime.start.minutes = mainEvent.start_time.minutes();
}
var topTime = moment.utc({hour: dayLevelTime.start.hours, minute: dayLevelTime.start.minutes});
var duration = moment.duration(endTime.diff(startTime));
var top = minutesToPixels(moment.duration(moment.utc({
hour: startTime.hours(),
minute: startTime.minutes()
}).diff(topTime)).asMinutes(), true);
var now = window.mainEvent.start_time;
var end = window.mainEvent.end_time;
while(now.format('M/D/YYYY') <= end.format('M/D/YYYY')) {
days.push(now.format("Do MMMM YYYY"));
now.add('days', 1);
}
var dayString = startTime.format("Do MMMM YYYY"); // formatted as eg. 2nd May 2013
if (!_.includes(days, dayString)) {
days.push(dayString);
}
if(session.hasOwnProperty('track') && !_.isNull(session.track)) {
if (!_.some(tracks, session.track)) {
tracks.push(session.track);
}
}
session.start_time = startTime;
session.end_time = endTime;
session.duration = Math.abs(duration.asMinutes());
session.top = top;
var dayIndex = _.indexOf(days, dayString);
if (_.isArray(sessionsStore[dayIndex])) {
sessionsStore[dayIndex].push(session);
} else {
sessionsStore[dayIndex] = [session];
}
for (var index in days) {
if (_.isArray(unscheduledStore[index])) {
unscheduledStore[index].push(session);
} else {
unscheduledStore[index] = [session];
}
}
}
});
_.each(microlocations, function (microlocation) {
if (!_.includes(microlocationsStore, microlocation)) {
microlocationsStore.push(microlocation);
}
});
microlocationsStore = _.sortBy(microlocationsStore, "name");
loadDateButtons();
callback();
}
/**
* Load the date selection button onto the DOM
*/
function loadDateButtons() {
var sortedDays = days.sort();
_.each(sortedDays, function (day, index) {
var $dayButton = $(dayButtonTemplate);
if (index === 0) {
$dayButton.addClass("active");
}
$dayButton.text(day);
$dayButtonsHolder.append($dayButton);
});
loadMicrolocationsToTimeline(sortedDays[0]);
}
/**
* Load all the sessions of a given day into the timeline
* @param {string} day
*/
function loadMicrolocationsToTimeline(day) {
$timelineTable.show();
$noSessionMessage.hide();
$microlocationsHolder.find(".microlocation").show();
var parsedDay = moment.utc(day, "Do MMMM YYYY");
if (parsedDay.isSame(mainEvent.start_time, "day")) {
window.dayLevelTime.start.hours = mainEvent.start_time.hours();
window.dayLevelTime.start.minutes = mainEvent.start_time.minutes();
}
if (parsedDay.isSame(mainEvent.end_time, "day")) {
window.dayLevelTime.end.hours = mainEvent.end_time.hours();
window.dayLevelTime.end.minutes = mainEvent.end_time.minutes();
}
var least_hours = 24;
var max_hours = 0;
var max_minutes = 0;
var dayIndex = _.indexOf(days, day);
if (isReadOnly()) {
_.each(sessionsStore[dayIndex], function (session) {
// Add session elements, but do not broadcast.
if (!_.isNull(session.top) && !_.isNull(session.microlocation) && !_.isNull(session.microlocation.id) && !_.isNull(session.start_time) && !_.isNull(session.end_time) && !session.hasOwnProperty("isReset")) {
if (session.start_time.hours() < least_hours) {
least_hours = session.start_time.hours();
}
if (session.end_time.hours() > max_hours) {
max_hours= session.end_time.hours();
if (session.end_time.minutes() > max_minutes) {
max_minutes = session.end_time.minutes();
}
}
}
});
if (max_hours === 0) {
$timelineTable.hide();
$noSessionMessage.show();
}
window.dayLevelTime.start.hours = least_hours;
window.dayLevelTime.start.minutes = 0;
window.dayLevelTime.end.hours = max_hours + 2;
window.dayLevelTime.end.minutes = max_minutes;
var topTime = moment.utc({hour: dayLevelTime.start.hours, minute: dayLevelTime.start.minutes});
_.each(sessionsStore[dayIndex], function (session) {
var top = minutesToPixels(moment.duration(moment.utc({
hour: session.start_time.hours(),
minute: session.start_time.minutes()
}).diff(topTime)).asMinutes(), true);
session.top = top;
});
}
generateTimeUnits();
$microlocationsHolder.empty();
$unscheduledSessionsHolder.empty();
$mobileTimeline.empty();
$noSessionsInfoBox.show();
_.each(microlocationsStore, addMicrolocationToTimeline);
$tracksTimeline.html("");
_.each(tracks, function (track) {
if(!_.isNull(track)) {
var $trackElement = $(mobileMicrolocationTemplate);
$trackElement.find('.name').text(track.name);
$trackElement.attr("data-track-id", track.id);
$tracksTimeline.append($trackElement);
}
});
sessionsStore[dayIndex] = _.sortBy(sessionsStore[dayIndex], "start_time");
_.each(sessionsStore[dayIndex], function (session) {
// Add session elements, but do not broadcast.
if (!_.isNull(session.top) && !_.isNull(session.microlocation) && !_.isNull(session.microlocation.id) && !_.isNull(session.start_time) && !_.isNull(session.end_time) && !session.hasOwnProperty("isReset")) {
addSessionToTimeline(session, null, false);
}
});
_.each(unscheduledStore[dayIndex], function (session) {
// Add session elements, but do not broadcast.
if (!_.isNull(session.top) && !_.isNull(session.microlocation) && !_.isNull(session.microlocation.id) && !_.isNull(session.start_time) && !_.isNull(session.end_time) && !session.hasOwnProperty("isReset")) {
return true;
} else {
if (!isReadOnly()) {
addSessionToUnscheduled(session, false, false);
}
}
});
_.each($mobileTimeline.find('.mobile-microlocation'), function ($mobileMicrolocation) {
$mobileMicrolocation = $($mobileMicrolocation);
if ($mobileMicrolocation.find(".mobile-sessions-holder").children().length === 0) {
$mobileMicrolocation.remove();
}
});
_.each($tracksTimeline.find('.mobile-microlocation'), function ($mobileMicrolocation) {
$mobileMicrolocation = $($mobileMicrolocation);
if ($mobileMicrolocation.find(".mobile-sessions-holder").children().length === 0) {
$mobileMicrolocation.remove();
}
});
$microlocations = $microlocationsHolder.find(".microlocation");
$("[data-toggle=tooltip]").tooltip("hide");
if (isReadOnly()) {
_.each($microlocations, function ($microlocation) {
$microlocation = $($microlocation);
if ($microlocation.find('.microlocation-inner').children().length === 0) {
$microlocation.hide();
}
});
$('.edit-btn').hide();
$('.remove-btn').hide();
}
}
function loadData(eventId, callback) {
api.microlocations.get_microlocation_list({event_id: eventId}, function (microlocationsData) {
api.sessions.get_session_list({event_id: eventId}, function (sessionData) {
processMicrolocationSession(microlocationsData.obj, sessionData.obj, callback);
});
});
}
/**
* Initialize the timeline for a given event
* @param {int} eventId The event ID
*/
function initializeTimeline(eventId) {
initializeSwaggerClient(function () {
loadData(eventId, function () {
$(".flash-message-holder").hide();
$(".scheduler-holder").show();
$(".session").ellipsis();
if (!isReadOnly()) {
initializeInteractables();
} else {
$('.edit-btn').hide();
$('.remove-btn').hide();
}
$(".rooms-view").addClass('active');
$('.microlocation-container').css("width", $(".microlocations.x1").width() + "px");
$(document).trigger({
type: "scheduling:recount",
microlocations: _.map(microlocationsStore, 'id')
});
});
});
}
/**
* FUNCTIONS THAT ARE TRIGGERED BY EVENTS
* ======================================
*
*/
/**
* Hold the timeline microlocation headers in place while scroll
*/
$(".timeline").scroll(function () {
var cont = $(this);
var el = $(cont.find(".microlocation-inner")[0]);
var elementTop = el.position().top;
var pos = cont.scrollTop() + elementTop;
cont.find(".microlocation-header").css("top", pos + "px");
});
/**
* Handle unscheduled sessions search
*/
$("#sessions-search").valueChange(function (value) {
var filtered = [];
if (_.isEmpty(value) || value === "") {
filtered = unscheduledStore;
} else {
filtered = _.filter(unscheduledStore, function (session) {
return fuzzyMatch(session.title, value);
});
}
filtered = _.sortBy(filtered, "title");
filtered = _.uniqBy(filtered, "id");
$unscheduledSessionsHolder.html("");
if (filtered.length === 0) {
$(".no-sessions-info").show();
} else {
$(".no-sessions-info").hide();
_.each(filtered, function (session) {
addSessionToUnscheduled(session, true);
});
}
});
$addMicrolocationForm.submit(function (event) {
event.preventDefault();
var payload = {
"room": $addMicrolocationForm.find("input[name=room]").val(),
"latitude": parseFloat($addMicrolocationForm.find("input[name=latitude]").val()),
"name": $addMicrolocationForm.find("input[name=name]").val(),
"longitude": parseFloat($addMicrolocationForm.find("input[name=longitude]").val()),
"floor": parseInt($addMicrolocationForm.find("input[name=floor]").val())
};
api.microlocations.post_microlocation_list({event_id: mainEvent.id, payload: payload}, function (success) {
addMicrolocationToTimeline(success.obj);
$addMicrolocationForm.find(".modal").modal("hide");
$addMicrolocationForm.find("input, textarea").val("");
createSnackbar("Microlocation has been created successfully.");
}, function (error) {
logError('failed with the following: ' + error.statusText, error);
createSnackbar("An error occurred while creating microlocation.", "Try Again", function () {
$addMicrolocationForm.trigger("submit");
});
});
});
$(".export-png-button").click(function () {
html2canvas($timeline[0], {
onrendered: function (canvas) {
canvas.id = "generated-canvas";
canvas.toBlob(function (blob) {
saveAs(blob, "timeline.png");
});
}
});
});
/**
* Global document events for date change button, remove button and clear overlaps button
*/
$(document)
.on("click", ".date-change-btn", function () {
$(this).addClass("active").siblings().removeClass("active");
loadMicrolocationsToTimeline($(this).text());
})
.on("click", ".session.scheduled > .remove-btn", function () {
addSessionToUnscheduled($(this).parent());
})
.on("click", ".session.scheduled", function () {
try {
$('.session.scheduled').not(this).popover('hide');
$(this).popover('toggle');
} catch (ignored) { }
})
.on("click", ".session.scheduled > .edit-btn", function () {
var $sessionElement = $(this).parent();
var session = $sessionElement.data("session");
location.href = "/events/" + window.mainEvent.id + "/sessions/" + session.id + "/edit/";
})
.on("click", ".rooms-view", function(){
$dayButtonsHolder.show();
$timeline.removeClass('hidden');
$mobileTimeline.removeClass('hidden');
$tracksTimeline.addClass('hidden');
$sessionViewHolder.addClass('hidden');
$(this).addClass("active").siblings().removeClass("active");
})
.on("click", ".tracks-view", function(){
$dayButtonsHolder.show();
$timeline.addClass('hidden');
$mobileTimeline.addClass('hidden');
$tracksTimeline.removeClass('hidden');
$sessionViewHolder.addClass('hidden');
$(this).addClass("active").siblings().removeClass("active");
})
.on("click", ".sessions-view", function() {
$dayButtonsHolder.hide();
$sessionViewHolder.removeClass('hidden');
$timeline.addClass('hidden');
$mobileTimeline.addClass('hidden');
$tracksTimeline.addClass('hidden');
$(this).addClass("active").siblings().removeClass("active");
})
.on("click", ".clear-overlaps-button", removeOverlaps);
/**
* Initialize the Scheduler UI on document ready
*/
$(document).ready(function () {
window.mainEvent.id = parseInt($timeline.data("event-id"));
window.mainEvent.start_time = moment.utc($timeline.data("event-start"));
window.mainEvent.end_time = moment.utc($timeline.data("event-end"));
initializeTimeline(window.mainEvent.id);
});
$(document).on("scheduling:recount", function(e) {
var microlocations = _.cloneDeep(e.microlocations);
_.each(microlocations, function(microlocation_id){
var $microlocationColumn = $microlocationsHolder.find(".microlocation[data-microlocation-id=" + microlocation_id + "]");
$microlocationColumn.find(".microlocation-header").find(".badge").text($microlocationColumn.find(".session.scheduled").length)
});
});
$(document).on("scheduling:change", function (e) {
if (!isReadOnly()) {
// Make a deep clone of the session object
var session = _.cloneDeep(e.session);
var session_id = session.id;
// Format the payload to match API requirements
session.start_time = session.start_time.format(time.format);
session.end_time = session.end_time.format(time.format);
session.track_id = (_.isNull(session.track) || _.isNull(session.track.id)) ? null : session.track.id;
session.microlocation_id = (_.isNull(session.microlocation) || _.isNull(session.microlocation.id)) ? null : session.microlocation.id;
session.speaker_ids = _.map(session.speakers, 'id');
// Clean up the payload
delete session.language;
delete session.speakers;
delete session.microlocation;
delete session.duration;
delete session.top;
delete session.id;
api.sessions.put_session({
event_id: mainEvent.id,
session_id: session_id,
payload: session
}, function () {
createSnackbar("Changes have been saved.", "Dismiss", null, 1000);
}, function (error) {
logError('failed with the following: ' + error.statusText, error);
createSnackbar("An error occurred while saving the changes.", "Try Again", function () {
$(document).trigger({
type: "scheduling:change",
session: e.session
});
});
});
}
});
| Achint08/open-event-orga-server | app/static/js/events/scheduler.js | JavaScript | gpl-3.0 | 45,120 |
(function() {
'use strict';
angular
.module('otusjs.model.activity')
.service('otusjs.model.activity.CalendarRuleTestService', Service);
Service.$inject = [
'otusjs.model.activity.NumericRuleTestService',
'otusjs.utils.ImmutableDate'
];
function Service(NumericRuleTestService, ImmutableDate) {
var self = this;
var _runner = {};
self.name = 'CalendarRuleTestService';
/* Public Methods */
self.run = run;
function run(rule, answer) {
_polyfillIsInteger();
if (!rule.isMetadata && !answer) {
return false;
} else if (rule.isMetadata) {
return NumericRuleTestService.run(rule, answer);
} else {
var resultRegex = rule.answer.match(/^(\d{1,2})[\/](\d{1,2})[\/](\d{4})$/);
var immutableDate = createImmutableDate(resultRegex);
return _runner[rule.operator](immutableDate, answer);
}
}
_runner.equal = function(reference, answer) {
return answer.getTime() == reference.getTime();
};
_runner.notEqual = function(reference, answer) {
return answer.getTime() != reference.getTime();
};
_runner.greater = function(reference, answer) {
return answer.getTime() > reference.getTime();
};
_runner.greaterEqual = function(reference, answer) {
return answer.getTime() >= reference.getTime();
};
_runner.lower = function(reference, answer) {
return answer.getTime() < reference.getTime();
};
_runner.lowerEqual = function(reference, answer) {
return answer.getTime() <= reference.getTime();
};
function _polyfillIsInteger() {
Number.isInteger = Number.isInteger || function(value) {
return typeof value === "number" &&
isFinite(value) &&
Math.floor(value) === value;
};
}
function createImmutableDate(resultRegex) {
var immutableDate = new ImmutableDate();
immutableDate.resetDate();
immutableDate.setDate(resultRegex[1]);
immutableDate.setMonth(resultRegex[2] - 1);
immutableDate.setFullYear(resultRegex[3]);
immutableDate.setHours(0);
immutableDate.setMinutes(0);
immutableDate.setSeconds(0);
immutableDate.setMilliseconds(0);
return immutableDate;
}
}
}());
| ccem-dev/otus-model-js | app/activity/service/answer/calendar-rule-test-service.js | JavaScript | gpl-3.0 | 2,285 |
// load all the things we need
var LocalStrategy = require('passport-local').Strategy;
// load up the user model
var User = require('../routers/models/user');
// expose this function to our app using module.exports
module.exports = function(passport) {
// =========================================================================
// passport session setup ==================================================
// =========================================================================
// required for persistent login sessions
// passport needs ability to serialize and unserialize users out of session
// used to serialize the user for the session
passport.serializeUser(function(user, done) {
done(null, user._id);
});
// used to deserialize the user
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
done(err, user);
});
});
// =========================================================================
// LOCAL SIGNUP ============================================================
// =========================================================================
// we are using named strategies since we have one for login and one for signup
// by default, if there was no name, it would just be called 'local'
passport.use('local-signup', new LocalStrategy({
// by default, local strategy uses username and password, we will override with username
usernameField : 'username',
passwordField : 'password',
passReqToCallback : true // allows us to pass back the entire request to the callback
},
function(req, username, password, done) {
// find a user whose username is the same as the forms username
// we are checking to see if the user trying to login already exists
User.findOne({ 'local.username' : username }, function(err, user) {
// if there are any errors, return the error
if (err)
return done(err);
// check to see if theres already a user with that email
if (user) {
return done(null, false, req.flash('signupMessage', 'That email is already taken.'));
} else {
// if there is no user with that email
// create the user
var newUser = new User();
// set the user's local credentials
newUser.user.username = username;
newUser.user.password = newUser.generateHash(password); // use the generateHash function in our user model
// save the user
newUser.save(function(err) {
if (err)
throw err;
return done(null, newUser);
});
}
});
}));
// =========================================================================
// LOCAL LOGIN =============================================================
// =========================================================================
// we are using named strategies since we have one for login and one for signup
// by default, if there was no name, it would just be called 'local'
passport.use('local-login', new LocalStrategy({
passReqToCallback : true // allows us to pass back the entire request to the callback
},
function(req, username, password, done) { // callback with email and password from our form
// find a user whose email is the same as the forms email
// we are checking to see if the user trying to login already exists
User.findOne({ 'username' : username }, function(err, user) {
// if there are any errors, return the error before anything else
if (err)
return done(err);
// if no user is found, return the message
if (!user){
console.log('User Not Found with username '+username);
return done(null, false, req.flash('message', 'User Not found.'));
}
// if the user is found but the password is wrong
// if (!validPassword('admin')){
// console.log('Invalid Password');
// return done(null, false, req.flash('message', 'Invalid Password'));
// }
// all is well, return successful user
return done(null, user);
});
}));
};
| UnSpiraTive/radio | config/passport.old.js | JavaScript | gpl-3.0 | 4,480 |
import { useReducer } from 'react';
import { reducer } from './import-context-reducer';
export const Context = React.createContext();
export default function ImportContext( props ) {
const initialState = {
file: null,
},
[ data, dispatch ] = useReducer( reducer, initialState );
return (
<Context.Provider value={ { data, dispatch } }>
{ props.children }
</Context.Provider>
);
}
ImportContext.propTypes = {
children: PropTypes.object.isRequired,
};
| ramiy/elementor | core/app/modules/import-export/assets/js/context/import/import-context.js | JavaScript | gpl-3.0 | 470 |
/**
*
* @licstart The following is the entire license notice for the
* JavaScript code in this page.
*
* Copyright (C) 2014,2018 Rob Myers
*
*
* The JavaScript code in this page is free software: you can
* redistribute it and/or modify it under the terms of the GNU
* General Public License (GNU GPL) as published by the Free Software
* Foundation, either version 3 of the License, or (at your option)
* any later version. The code is distributed WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU GPL for more details.
*
* As additional permission under GNU GPL version 3 section 7, you
* may distribute non-source (e.g., minimized or compacted) forms of
* that code without the copy of the GNU GPL normally required by
* section 4, provided you include this license notice and a URL
* through which recipients can access the Corresponding Source.
*
* @licend The above is the entire license notice
* for the JavaScript code in this page.
*
*/
var DIV_1_255 = 1.0 / 255;
var DIV_255_8 = 255.0 / 8;
var DIV_255_4 = 255.0 / 4;
var DIV_1_16 = 1.0 / 16
// 8-8-4 256 colour RGB palette
var COLOUR_PALETTE_256 = Array();
for(var r = 0; r < 256; r += 32) {
for(var g = 0; g < 256; g += 32) {
for(var b = 0; b < 256; b += 64) {
//var rgb = b | (g << 8) | (r << 16);
//COLOUR_PALETTE_256.push('#' + rgb.toString(16));
COLOUR_PALETTE_256.push('rgb(' + r.toString() + ', '
+ g.toString() + ', ' +
+ b.toString() + ')');
}
}
}
var COLOUR_PALETTE_CGA = [
"#000000", "#0000AA", "#00AA00", "#00AAAA",
"#AA0000", "#AA00AA", "#AA5500", "#AAAAAA",
"#555555", "#5555FF", "#55FF55", "#55FFFF",
"#55FFFF", "#FF55FF", "#FFFF55", "#FFFFFF"
];
var COLOUR_PALETTE_WOW = [
// Doge colour, then HTML 4.01 colours
"#d9bd62", "silver", "gray", "black",
"red", "maroon", "yellow", "olive",
"lime", "green", "aqua", "teal",
"blue", "navy", "fuchsia", "purple"
];
var COLOUR_PALETTE_CRYSTAL = [
// 0ish, 10, 20, 40, ..., 240, 250, 256ish Lightness for Eth 3C3C3D
"#050505", "#0A0A0A", "#141414", "#282828",
"#3C3C3C", "#505050", "#646464", "#787878",
"#8C8C8C", "#A0A0A0", "#B4B4B4", "#C8C8C8",
"#DCDCDC", "#F0F0F0", "#FAFAFA", "#FEFEFE",
];
var GEOMETRIC_SHAPES = [
"⸱", // 0, dot (word separator)
"●", // 1, circle
"▬", // 2, horizontal bar
"▲", // 3, upward-pointing triangle
"■", // 4, square
"⬟", // 5, pentagon
"⬢", // 6, hexagon
"", // 7
"⯄" // 8, octagon
];
var bitValues = function(hash) {
var values = Array();
for (var i = 0; i < hash.length; i += 2) {
var element = parseInt(hash.substring(i, i + 2), 16);
values.push(element & 128 ? 1 : 0);
values.push(element & 64 ? 1 : 0);
values.push(element & 32 ? 1 : 0);
values.push(element & 16 ? 1 : 0);
values.push(element & 8 ? 1 : 0);
values.push(element & 2 ? 1 : 0);
values.push(element & 4 ? 1 : 0);
values.push(element & 1 ? 1 : 0);
}
return values;
};
var nibbleValues = function(hash) {
var values = Array();
for (var i = 0; i < hash.length; i += 2) {
var element = parseInt(hash.substring(i, i + 2), 16);
values.push(element & 0x0F);
values.push((element >> 4) & 0x0F);
}
return values;
};
var byteValues = function(hash) {
var values = Array();
for (var i = 0; i < hash.length; i += 2) {
var element = parseInt(hash.substring(i, i + 2), 16);
values.push(element);
}
return values;
};
var shortWordValues = function(hash) {
var values = Array();
for (var i = 0; i < hash.length; i += 4) {
var element = parseInt(hash.substring(i, i + 4), 16);
values.push(element);
}
return values;
};
var longWordValues = function(hash) {
var values = Array();
for (var i = 0; i < hash.length; i += 8) {
var element = parseInt(hash.substring(i, i + 8), 16);
values.push(element);
}
return values;
};
var monoColours = function(hash) {
var values = bitValues(hash);
var colours = Array();
values.forEach(function(value){
if(value) {
colours.push("black");
} else {
colours.push("white");
}
});
return colours;
};
var greyColours = function(hash) {
var values = byteValues(hash);
var colours = Array();
values.forEach(function(value){
var rgb = value | (value << 8) | (value << 16);
//colours.push('#' + rgb.toString(16));
colours.push('rgb(' + value.toString() + ', ' + value.toString() + ', '
+ value.toString() + ')');
});
return colours;
};
var hashToPaletteColours = function(hash, palette, scale) {
var values = byteValues(hash);
var colours = Array();
values.forEach(function(value){
colours.push(palette[Math.floor(value * scale)]);
});
return colours;
};
var eightBitPaletteColours = function(hash) {
return hashToPaletteColours(hash, COLOUR_PALETTE_256, 1);
};
var cgaPaletteColours = function(hash) {
return hashToPaletteColours(hash, COLOUR_PALETTE_CGA, 1 / (256 / 16));
};
var wowPaletteColours = function(hash) {
return hashToPaletteColours(hash, COLOUR_PALETTE_WOW, 1 / (256 / 16));
};
var crystalPaletteColours = function(hash) {
return hashToPaletteColours(hash, COLOUR_PALETTE_CRYSTAL, 1 / (256 / 16));
};
var rgbPaletteColours = function(hash) {
var values = wordValues(hash);
var colours = Array();
values.forEach(function(value){
var red = (value & 0xF800) >> 11;
var green = (value & 0x7E0) >> 5;
var blue = (value & 0x1F);
//var rgb = blue | (green << 8) | (red << 16);
//colours.push('#' + rgb.toString(16));
colours.push('rgb(' + red.toString() + ', ' + green.toString() + ', '
+ blue.toString() + ')');
});
return colours;
};
var cmykPaletteColours = function(hash) {
var colours = Array();
for (var i = 0; i < hash.length; i += 8) {
// In range 0..1
var cyan = DIV_1_255 * parseInt(hash.substring(i, i + 2), 16);
var magenta = DIV_1_255 * parseInt(hash.substring(i + 2, i + 4), 16);
var yellow = DIV_1_255 * parseInt(hash.substring(i + 4, i + 6), 16);
var key = DIV_1_255 * parseInt(hash.substring(i + 6, i + 8), 16);
// In range 0..255
var red = 255 * (1 - cyan) * (1 - key);
var green = 255 * (1 - magenta) * (1 - key);
var blue = 255 * (1 - yellow) * (1 - key);
//var rgb = blue | (green << 8) | (red << 16);
//colours.push('#' + rgb.toString(16));
colours.push('rgb(' + red.toString() + ', ' + green.toString() + ', '
+ blue.toString() + ')');
}
return colours;
};
var toDivs = function(colours, classID){
var row = ''
colours.forEach(function(colour){
row += '<div class="' + classID + '" style="background-color:' + colour
+ '"></div>'
});
return row;
};
var toStripesTable = function(colours, width, height){
var table = "<table width=\"" + width + "\" height=\"" + height + "\"><tr>";
table += toStripesTableRow(colours);
table += "</tr></table>";
return table;
};
var toBullets = function(colours) {
var row = '';
colours.forEach(function(colour){
row += "<span style=\"color:" + colour + "\">⬤</span>"
});
return row;
};
// Return normalized 4-bit co-ordinate pairs
var toCoordinates = function(hash) {
var nibbles = nibbleValues(hash);
var coords = [];
for(var i = 0; i < nibbles.length; i += 2) {
coords.push({x: nibbles[i] * DIV_1_16, y: nibbles[i + 1] * DIV_1_16});
}
return coords;
};
var transactionHashToUrl = function(hash) {
return 'https://blockchain.info/tx/' + hash;
};
var blockHashToUrl = function(hash) {
return 'https://blockchain.info/block-index/' + hash;
};
var transactionHashToA = function(hash) {
return '<a href="' + transactionHashToUrl(hash)
+ '" target="_blank" title="' + hash + '">';
};
var blockHashToA = function(hash) {
return '<a href="' + blockHashToUrl(hash)
+ '" target="_blank" title="' + hash + '">';
};
| robmyers/blockchain-aesthetics | shared-html5/js/representations.js | JavaScript | gpl-3.0 | 8,034 |
import DS from "ember-data";
import cardColor from "../utils/card-color";
export default DS.Model.extend({
databaseType: DS.belongsTo('database-type'),
permissions: DS.attr('string'),
isReady: DS.attr('boolean', {defaultValue: false}),
cardColor: function() {
return cardColor();
}.property()
});
| cznweb/genesis | app/models/database-user.js | JavaScript | gpl-3.0 | 325 |
/**
* @license Angular v5.2.5
* (c) 2010-2018 Google, Inc. https://angular.io/
* License: MIT
*/
import { EventEmitter, Injectable } from '@angular/core';
import { LocationStrategy } from '@angular/common';
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* A spy for {\@link Location} that allows tests to fire simulated location events.
*
* \@experimental
*/
class SpyLocation {
constructor() {
this.urlChanges = [];
this._history = [new LocationState('', '')];
this._historyIndex = 0;
/**
* \@internal
*/
this._subject = new EventEmitter();
/**
* \@internal
*/
this._baseHref = '';
/**
* \@internal
*/
this._platformStrategy = /** @type {?} */ ((null));
}
/**
* @param {?} url
* @return {?}
*/
setInitialPath(url) { this._history[this._historyIndex].path = url; }
/**
* @param {?} url
* @return {?}
*/
setBaseHref(url) { this._baseHref = url; }
/**
* @return {?}
*/
path() { return this._history[this._historyIndex].path; }
/**
* @param {?} path
* @param {?=} query
* @return {?}
*/
isCurrentPathEqualTo(path, query = '') {
const /** @type {?} */ givenPath = path.endsWith('/') ? path.substring(0, path.length - 1) : path;
const /** @type {?} */ currPath = this.path().endsWith('/') ? this.path().substring(0, this.path().length - 1) : this.path();
return currPath == givenPath + (query.length > 0 ? ('?' + query) : '');
}
/**
* @param {?} pathname
* @return {?}
*/
simulateUrlPop(pathname) {
this._subject.emit({ 'url': pathname, 'pop': true, 'type': 'popstate' });
}
/**
* @param {?} pathname
* @return {?}
*/
simulateHashChange(pathname) {
// Because we don't prevent the native event, the browser will independently update the path
this.setInitialPath(pathname);
this.urlChanges.push('hash: ' + pathname);
this._subject.emit({ 'url': pathname, 'pop': true, 'type': 'hashchange' });
}
/**
* @param {?} url
* @return {?}
*/
prepareExternalUrl(url) {
if (url.length > 0 && !url.startsWith('/')) {
url = '/' + url;
}
return this._baseHref + url;
}
/**
* @param {?} path
* @param {?=} query
* @return {?}
*/
go(path, query = '') {
path = this.prepareExternalUrl(path);
if (this._historyIndex > 0) {
this._history.splice(this._historyIndex + 1);
}
this._history.push(new LocationState(path, query));
this._historyIndex = this._history.length - 1;
const /** @type {?} */ locationState = this._history[this._historyIndex - 1];
if (locationState.path == path && locationState.query == query) {
return;
}
const /** @type {?} */ url = path + (query.length > 0 ? ('?' + query) : '');
this.urlChanges.push(url);
this._subject.emit({ 'url': url, 'pop': false });
}
/**
* @param {?} path
* @param {?=} query
* @return {?}
*/
replaceState(path, query = '') {
path = this.prepareExternalUrl(path);
const /** @type {?} */ history = this._history[this._historyIndex];
if (history.path == path && history.query == query) {
return;
}
history.path = path;
history.query = query;
const /** @type {?} */ url = path + (query.length > 0 ? ('?' + query) : '');
this.urlChanges.push('replace: ' + url);
}
/**
* @return {?}
*/
forward() {
if (this._historyIndex < (this._history.length - 1)) {
this._historyIndex++;
this._subject.emit({ 'url': this.path(), 'pop': true });
}
}
/**
* @return {?}
*/
back() {
if (this._historyIndex > 0) {
this._historyIndex--;
this._subject.emit({ 'url': this.path(), 'pop': true });
}
}
/**
* @param {?} onNext
* @param {?=} onThrow
* @param {?=} onReturn
* @return {?}
*/
subscribe(onNext, onThrow, onReturn) {
return this._subject.subscribe({ next: onNext, error: onThrow, complete: onReturn });
}
/**
* @param {?} url
* @return {?}
*/
normalize(url) { return /** @type {?} */ ((null)); }
}
SpyLocation.decorators = [
{ type: Injectable },
];
/** @nocollapse */
SpyLocation.ctorParameters = () => [];
class LocationState {
/**
* @param {?} path
* @param {?} query
*/
constructor(path, query) {
this.path = path;
this.query = query;
}
}
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* A mock implementation of {\@link LocationStrategy} that allows tests to fire simulated
* location events.
*
* \@stable
*/
class MockLocationStrategy extends LocationStrategy {
constructor() {
super();
this.internalBaseHref = '/';
this.internalPath = '/';
this.internalTitle = '';
this.urlChanges = [];
/**
* \@internal
*/
this._subject = new EventEmitter();
}
/**
* @param {?} url
* @return {?}
*/
simulatePopState(url) {
this.internalPath = url;
this._subject.emit(new _MockPopStateEvent(this.path()));
}
/**
* @param {?=} includeHash
* @return {?}
*/
path(includeHash = false) { return this.internalPath; }
/**
* @param {?} internal
* @return {?}
*/
prepareExternalUrl(internal) {
if (internal.startsWith('/') && this.internalBaseHref.endsWith('/')) {
return this.internalBaseHref + internal.substring(1);
}
return this.internalBaseHref + internal;
}
/**
* @param {?} ctx
* @param {?} title
* @param {?} path
* @param {?} query
* @return {?}
*/
pushState(ctx, title, path, query) {
this.internalTitle = title;
const /** @type {?} */ url = path + (query.length > 0 ? ('?' + query) : '');
this.internalPath = url;
const /** @type {?} */ externalUrl = this.prepareExternalUrl(url);
this.urlChanges.push(externalUrl);
}
/**
* @param {?} ctx
* @param {?} title
* @param {?} path
* @param {?} query
* @return {?}
*/
replaceState(ctx, title, path, query) {
this.internalTitle = title;
const /** @type {?} */ url = path + (query.length > 0 ? ('?' + query) : '');
this.internalPath = url;
const /** @type {?} */ externalUrl = this.prepareExternalUrl(url);
this.urlChanges.push('replace: ' + externalUrl);
}
/**
* @param {?} fn
* @return {?}
*/
onPopState(fn) { this._subject.subscribe({ next: fn }); }
/**
* @return {?}
*/
getBaseHref() { return this.internalBaseHref; }
/**
* @return {?}
*/
back() {
if (this.urlChanges.length > 0) {
this.urlChanges.pop();
const /** @type {?} */ nextUrl = this.urlChanges.length > 0 ? this.urlChanges[this.urlChanges.length - 1] : '';
this.simulatePopState(nextUrl);
}
}
/**
* @return {?}
*/
forward() { throw 'not implemented'; }
}
MockLocationStrategy.decorators = [
{ type: Injectable },
];
/** @nocollapse */
MockLocationStrategy.ctorParameters = () => [];
class _MockPopStateEvent {
/**
* @param {?} newUrl
*/
constructor(newUrl) {
this.newUrl = newUrl;
this.pop = true;
this.type = 'popstate';
}
}
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* @module
* @description
* Entry point for all public APIs of this package.
*/
// This file only reexports content of the `src` folder. Keep it that way.
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
/**
* Generated bundle index. Do not edit.
*/
export { SpyLocation, MockLocationStrategy };
//# sourceMappingURL=testing.js.map
| ricardo7227/DAW | Cliente/Codigo fuente/my-app/node_modules/@angular/common/esm2015/testing.js | JavaScript | gpl-3.0 | 9,141 |
var jugendstadtplanLogin = angular.module('jugendstadtplan.login', []);
jugendstadtplanLogin.service('LoginService', ['$window', 'jwtHelper', function($window, jwtHelper) {
var LoginService = {
authenticated: false,
traeger: null
};
LoginService.getToken = function(){
var token = $window.localStorage.getItem('jspToken');
if (token !== undefined) {
return token;
}
};
LoginService.setToken = function(token) {
$window.localStorage.setItem('jspToken', token);
};
LoginService.isTokenExpired = function() {
var token = this.getToken();
if (token) {
return jwtHelper.isTokenExpired(token);
}
return true;
};
LoginService.getJugendstadtplanUser = function() {
return this.traeger;
};
LoginService.setJugendstadtplanUser = function(user) {
this.traeger = user;
};
LoginService.isLoggedIn = function() {
return this.authenticated;
};
LoginService.login = function(token) {
this.authenticated = true;
this.setToken(token);
var decoded = jwtHelper.decodeToken(token);
this.setJugendstadtplanUser(decoded.traeger);
};
LoginService.logout = function() {
this.traeger = null;
this.authenticated = false;
$window.localStorage.removeItem('jspToken');
};
LoginService.init = function() {
var token = this.getToken();
if (token !== undefined) {
if (this.isTokenExpired()) {
this.logout();
} else {
this.login(token);
}
}
};
return LoginService;
}]); | KinderJugendringBonn/jugendstadtplan | public/src/common/resources/LoginService.js | JavaScript | gpl-3.0 | 1,703 |
$(document).ready(function() {
$("#top_menu ul:first a:first[title]").qtip({
style: {
border: {
width: 2,
radius: 3
},
color: "white",
name: "dark",
textAlign: "center",
tip: true
},
position: {
corner: {
target: "bottomRight",
tooltip: "topLeft"
}
}
});
$("#top_menu ul:first a:not(:first)[title]").qtip({
style: {
border: {
width: 2,
radius: 3
},
color: "white",
name: "dark",
textAlign: "center",
tip: true
},
position: {
corner: {
target: "bottomMiddle",
tooltip: "topMiddle"
}
}
});
$("#second_menu a[title], #search a[title], #resstats a[title]").qtip({
style: {
border: {
width: 2,
radius: 3
},
color: "white",
name: "dark",
textAlign: "center",
tip: true
},
position: {
corner: {
target: "bottomLeft",
tooltip: "topRight"
}
}
});
$("ul:not(.filetree) > li > *[title], a.show_resource_btn[title], a.copy_btn[title]").qtip({
style: {
border: {
width: 2,
radius: 3
},
color: "white",
name: "dark",
textAlign: "center",
tip: true
},
position: {
corner: {
target: "topMiddle",
tooltip: "bottomMiddle"
}
}
});
}); | gubi/Ninuxoo-2.0 | common/js/qtip-integration.js | JavaScript | gpl-3.0 | 1,215 |
Bitrix 16.5 Business Demo = ddb2b3408c8ec78011b8a33b22e404e9
Bitrix 17.0.9 Business Demo = f170b9520b1f41b89366598734f75838
| gohdan/DFC | known_files/hashes/bitrix/modules/sale/install/js/sale/admin/order_basket.map.js | JavaScript | gpl-3.0 | 124 |
module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
jshint: {
all: ['Gruntfile.js', 'src/**.js']
},
less: {
development: {
options: {
paths: ["style/less"]
},
files: {
"dist/style.css": "style/less/main.less"
}
},
},
copy: {
build: {
files: [
{ expand: true, cwd: 'src', src: ['**'], dest: 'build/' },
{ expand: true, cwd: 'lib', src: ['**'], dest: 'build/' }
]
},
dist: {
files: [
{ expand: true, cwd: 'build', src: [
'index.html',
'img.js',
'manifest.webapp',
], dest: 'dist/' },
{ expand: true, cwd:'bower_components', src: [
'building-blocks/{*.css,images/**,style/*.css,style/{buttons,confirm,drawer,headers,lists,srcolling,seekbars,status,progress_activity}/**/*.{css,png}}',
'zepto/zepto.min.js',
'gaia-icons/**'
], dest: 'dist/' },
{ expand: true, src: [
'icons/*.png',
'assets/**.png'
], dest: 'dist/' }
]
}
},
execute: {
target: {
src: ['src/kodijs/gen_js.js']
}
},
handlebars: {
compile: {
options: {
commonjs: true,
processName: function(filePath) {
var fname = filePath.split("/").slice(-1)[0].replace('-','_');
return fname.substr(0, fname.indexOf('.'));
}
},
files: {
'build/templates.js': 'src/views/*.hbs'
}
}
},
browserify: {
dist: {
files: {
'dist/app.js': ['build/app.js'],
},
options: {
alias: ['./bower_components/handlebars/handlebars.min.js:handlebars']
},
browserifyOptions: {
detectGlobals: false
}
}
},
uglify: {
options: {
banner: '/*! <%= pkg.name %> <%= grunt.template.today("yyyy-mm-dd") %> */\n'
},
build: {
src: 'build/<%= pkg.name %>.js',
dest: 'dist/<%= pkg.name %>.min.js'
}
},
watch: {
main: {
files: ['src/index.html', 'src/manifest.webapp'],
tasks: ['copy:build', 'browserify', 'copy:dist']
},
scripts: {
files: ['src/*.js', 'src/cards/*.js'],
tasks: ['jshint', 'copy:build', 'browserify', 'copy:dist']
},
apiscripts: {
files: ['src/kodijs/**'],
tasks: ['jshint', 'copy:build', 'execute', 'browserify', 'copy:dist']
},
templates: {
files: ['src/views/*.hbs'],
tasks: ['jshint', 'copy:build', 'handlebars', 'browserify', 'copy:dist']
},
less: {
files: ['style/**'],
tasks: ['less']
}
},
});
// Load the plugin that provides the "uglify" task.
//grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-browserify');
grunt.loadNpmTasks('grunt-execute');
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.loadNpmTasks('grunt-contrib-handlebars');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-less');
// Default task(s).
grunt.registerTask('default', ['jshint', 'copy:build', 'execute', 'handlebars', 'browserify', 'less', 'copy:dist']);
};
| soupytwist/Foxi | Gruntfile.js | JavaScript | gpl-3.0 | 3,441 |
vti_encoding:SR|utf8-nl
vti_timelastmodified:TW|14 Aug 2014 12:39:17 -0000
vti_extenderversion:SR|12.0.0.0
vti_author:SR|Office-PC\\Rafael
vti_modifiedby:SR|Office-PC\\Rafael
vti_timecreated:TR|01 Nov 2014 09:08:42 -0000
vti_backlinkinfo:VX|
vti_nexttolasttimemodified:TW|14 Aug 2014 12:39:17 -0000
vti_cacheddtm:TX|03 Nov 2015 21:06:21 -0000
vti_filesize:IR|10659
vti_syncofs_mydatalogger.de\:22/%2fvar/www/vhosts/s16851491.onlinehome-server.info/kaufreund.de:TW|14 Aug 2014 12:39:17 -0000
vti_syncwith_mydatalogger.de\:22/%2fvar/www/vhosts/s16851491.onlinehome-server.info/kaufreund.de:TW|03 Nov 2015 21:06:21 -0000
| Vitronic/kaufreund.de | admin/view/javascript/ckeditor/lang/_vti_cnf/pt.js | JavaScript | gpl-3.0 | 618 |
/*
A matrix is Toeplitz if every diagonal from top-left to bottom-right has the same element.
Now given an M x N matrix, return True if and only if the matrix is Toeplitz.
Example 1:
Input: matrix = [[1,2,3,4],[5,1,2,3],[9,5,1,2]]
Output: True
Explanation:
1234
5123
9512
In the above grid, the diagonals are "[9]", "[5, 5]", "[1, 1, 1]", "[2, 2, 2]", "[3, 3]", "[4]", and in each diagonal all elements are the same, so the answer is True.
Example 2:
Input: matrix = [[1,2],[2,2]]
Output: False
Explanation:
The diagonal "[1, 2]" has different elements.
Note:
matrix will be a 2D array of integers.
matrix will have a number of rows and columns in range [1, 20].
matrix[i][j] will be integers in range [0, 99].
*/
/**
* @param {number[][]} matrix
* @return {boolean}
*/
var isToeplitzMatrix = function(matrix) {
for(var i=0, leni=matrix.length;i<leni-1;i++){
for(var j=0, lenj=matrix[0].length;j<lenj-1;j++){
if( matrix[i][j] !== matrix[i+1][j+1] ){
return false;
}
}
}
return true;
};
//tags: Google
| matrixki/LeetCode | 766. Toeplitz Matrix.js | JavaScript | gpl-3.0 | 1,083 |
// ==UserScript==
// @name youkuantiads.uc.js
// @namespace YoukuAntiADs@harv.c
// @description 视频网站去黑屏
// @include chrome://browser/content/browser.xul
// @author harv.c
// @homepage http://haoutil.tk
// @version 1.6.1
// @updateUrl https://j.mozest.com/zh-CN/ucscript/script/92.meta.js
// @downloadUrl https://j.mozest.com/zh-CN/ucscript/script/92.uc.js
// ==/UserScript==
(function() {
// YoukuAntiADs, request observer
function YoukuAntiADs() {};
YoukuAntiADs.prototype = {
SITES: {
'youku_loader': {
'player': 'https://haoutil.googlecode.com/svn/trunk/player/testmod/loader.swf',
're': /http:\/\/static\.youku\.com(\/v[\d\.]+)?\/v\/swf\/loaders?\.swf/i
},
'youku_player': {
'player': 'https://haoutil.googlecode.com/svn/trunk/player/testmod/player.swf',
're': /http:\/\/static\.youku\.com(\/v[\d\.]+)?\/v\/swf\/q?player[^\.]*\.swf/i
},
'ku6': {
'player': 'https://haoutil.googlecode.com/svn/trunk/player/ku6.swf',
're': /http:\/\/player\.ku6cdn\.com\/default\/common\/player\/\d{12}\/player\.swf/i
},
'ku6_out': {
'player': 'https://haoutil.googlecode.com/svn/trunk/player/ku6_out.swf',
're': /http:\/\/player\.ku6cdn\.com\/default\/out\/\d{12}\/player\.swf/i
},
'iqiyi': {
'player0': 'https://haoutil.googlecode.com/svn/trunk/player/testmod/iqiyi_out.swf',
'player1': 'https://haoutil.googlecode.com/svn/trunk/player/testmod/iqiyi5.swf',
'player2': 'https://haoutil.googlecode.com/svn/trunk/player/testmod/iqiyi.swf',
're': /http:\/\/www\.iqiyi\.com\/player\/\d+\/player\.swf/i
},
'tudou': {
'player': 'https://haoutil.googlecode.com/svn/trunk/player/testmod/tudou.swf',
're': /http:\/\/js\.tudouui\.com\/.*portalplayer[^\.]*\.swf/i
},
'tudou_olc': {
'player': 'https://haoutil.googlecode.com/svn/trunk/player/testmod/olc_8.swf',
're': /http:\/\/js\.tudouui\.com\/.*olc[^\.]*\.swf/i
},
'tudou_sp': {
'player': 'https://haoutil.googlecode.com/svn/trunk/player/testmod/sp.swf',
're': /http:\/\/js\.tudouui\.com\/.*\/socialplayer[^\.]*\.swf/i
},
'letv': {
'player': 'https://haoutil.googlecode.com/svn/trunk/player/testmod/letv.swf',
're': /http:\/\/.*letv[\w]*\.com\/(hz|.*\/(?!(Live|seed))(S[\w]{2,3})?(?!Live)[\w]{4})Player[^\.]*\.swf/i
},
'letvskin': {
'player': 'http://player.letvcdn.com/p/201403/05/1456/newplayer/1/SLetvPlayer.swf',
're': /http:\/\/.*letv[\w]*\.com\/p\/\d+\/\d+\/(?!1456)\d*\/newplayer\/\d+\/SLetvPlayer\.swf/i
},
'pplive': {
'player': 'https://haoutil.googlecode.com/svn/trunk/player/pplive.swf',
're': /http:\/\/player\.pplive\.cn\/ikan\/.*\/player4player2\.swf/i
},
'pplive_live': {
'player': 'https://haoutil.googlecode.com/svn/trunk/player/pplive_live.swf',
're': /http:\/\/player\.pplive\.cn\/live\/.*\/player4live2\.swf/i
},
'sohu': {
'player': 'https://haoutil.googlecode.com/svn/trunk/player/testmod/sohu.swf',
're': /http:\/\/tv\.sohu\.com\/upload\/swf(\/p2p(\/yc)?)?\/\d+\/(main|playershell)\.swf/i
},
'pps': {
'player': 'https://haoutil.googlecode.com/svn/trunk/player/testmod/pps.swf',
're': /http:\/\/www\.iqiyi\.com\/player\/cupid\/.*\/pps[\w]+.swf/i
}
},
os: Cc['@mozilla.org/observer-service;1']
.getService(Ci.nsIObserverService),
init: function() {
var site = this.SITES['iqiyi'];
site['preHandle'] = function(aSubject) {
var wnd = this.getWindowForRequest(aSubject);
if(wnd) {
site['cond'] = [
!/(^((?!baidu|61|178).)*\.iqiyi\.com|pps\.tv)/i.test(wnd.self.location.host),
wnd.self.document.querySelector('span[data-flashplayerparam-flashurl]'),
true
];
if(!site['cond']) return;
for(var i = 0; i < site['cond'].length; i++) {
if(site['cond'][i]) {
if(site['player'] != site['player' + i]) {
site['player'] = site['player' + i];
site['storageStream'] = site['storageStream' + i] ? site['storageStream' + i] : null;
site['count'] = site['count' + i] ? site['count' + i] : null;
}
break;
}
}
}
};
site['callback'] = function() {
if(!site['cond']) return;
for(var i = 0; i < site['cond'].length; i++) {
if(site['player' + i] == site['player']) {
site['storageStream' + i] = site['storageStream'];
site['count' + i] = site['count'];
break;
}
}
};
},
// getPlayer, get modified player
getPlayer: function(site, callback) {
NetUtil.asyncFetch(site['player'], function(inputStream, status) {
var binaryOutputStream = Cc['@mozilla.org/binaryoutputstream;1']
.createInstance(Ci['nsIBinaryOutputStream']);
var storageStream = Cc['@mozilla.org/storagestream;1']
.createInstance(Ci['nsIStorageStream']);
var count = inputStream.available();
var data = NetUtil.readInputStreamToString(inputStream, count);
storageStream.init(512, count, null);
binaryOutputStream.setOutputStream(storageStream.getOutputStream(0));
binaryOutputStream.writeBytes(data, count);
site['storageStream'] = storageStream;
site['count'] = count;
if(typeof callback === 'function') {
callback();
}
});
},
getWindowForRequest: function(request){
if(request instanceof Ci.nsIRequest){
try{
if(request.notificationCallbacks){
return request.notificationCallbacks
.getInterface(Ci.nsILoadContext)
.associatedWindow;
}
} catch(e) {}
try{
if(request.loadGroup && request.loadGroup.notificationCallbacks){
return request.loadGroup.notificationCallbacks
.getInterface(Ci.nsILoadContext)
.associatedWindow;
}
} catch(e) {}
}
return null;
},
observe: function(aSubject, aTopic, aData) {
if(aTopic != 'http-on-examine-response') return;
var http = aSubject.QueryInterface(Ci.nsIHttpChannel);
var aVisitor = new HttpHeaderVisitor();
http.visitResponseHeaders(aVisitor);
if (!aVisitor.isFlash()) return;
for(var i in this.SITES) {
var site = this.SITES[i];
if(site['re'].test(http.URI.spec)) {
var fn = this, args = Array.prototype.slice.call(arguments);
if(typeof site['preHandle'] === 'function')
site['preHandle'].apply(fn, args);
if(!site['storageStream'] || !site['count']) {
http.suspend();
this.getPlayer(site, function() {
http.resume();
if(typeof site['callback'] === 'function')
site['callback'].apply(fn, args);
});
}
var newListener = new TrackingListener();
aSubject.QueryInterface(Ci.nsITraceableChannel);
newListener.originalListener = aSubject.setNewListener(newListener);
newListener.site = site;
break;
}
}
},
QueryInterface: function(aIID) {
if(aIID.equals(Ci.nsISupports) || aIID.equals(Ci.nsIObserver))
return this;
return Cr.NS_ERROR_NO_INTERFACE;
},
register: function() {
this.init();
this.os.addObserver(this, 'http-on-examine-response', false);
},
unregister: function() {
this.os.removeObserver(this, 'http-on-examine-response', false);
}
};
// TrackingListener, redirect youku player to modified player
function TrackingListener() {
this.originalListener = null;
this.site = null;
}
TrackingListener.prototype = {
onStartRequest: function(request, context) {
this.originalListener.onStartRequest(request, context);
},
onStopRequest: function(request, context) {
this.originalListener.onStopRequest(request, context, Cr.NS_OK);
},
onDataAvailable: function(request, context) {
this.originalListener.onDataAvailable(request, context, this.site['storageStream'].newInputStream(0), 0, this.site['count']);
}
};
function HttpHeaderVisitor() {
this._isFlash = false;
}
HttpHeaderVisitor.prototype = {
visitHeader: function(aHeader, aValue) {
if (aHeader.indexOf("Content-Type") !== -1) {
if (aValue.indexOf("application/x-shockwave-flash") !== -1) {
this._isFlash = true;
}
}
},
isFlash: function() {
return this._isFlash;
}
};
// register observer
var y = new YoukuAntiADs();
if(location == 'chrome://browser/content/browser.xul') {
y.register();
}
// unregister observer
window.addEventListener('unload', function() {
if(location == 'chrome://browser/content/browser.xul') {
y.unregister();
}
});
})();
| Harv/userChromeJS | youkuantiads.uc.js | JavaScript | gpl-3.0 | 10,871 |
const thirdPartyServices = require('../services/thirdparty');
// History state init (state that is reflected in the url)
const historyState = {};
// Map from querystring key to state key
const querystringMappings = {
countryCode: 'selectedZoneName',
datetime: 'customDate',
page: 'showPageState',
solar: 'solarEnabled',
remote: 'useRemoteEndpoint',
wind: 'windEnabled',
};
const reverseQuerystringMappings = {};
Object.keys(querystringMappings).forEach((k) => {
reverseQuerystringMappings[querystringMappings[k]] = k;
});
function appendQueryString(url, key, value) {
return (url === '?' ? url : url + '&') + key + '=' + value;
}
function getURL() {
let url = '?';
Object.keys(historyState).forEach((k) => {
url = appendQueryString(url, k, historyState[k]);
});
// '.' is not supported when serving from file://
return (url === '?' ? '?' : url);
}
function replace(key, value) {
if (value == null) {
delete historyState[key];
} else {
historyState[key] = value;
}
}
function updateHistoryFromState(applicationState) {
// `state` is the redux application state
Object.keys(querystringMappings).forEach((historyKey) => {
replace(historyKey, applicationState[querystringMappings[historyKey]]);
});
const url = getURL();
if (thirdPartyServices._ga) {
thirdPartyServices._ga.config({ page_path: url });
}
window.history.replaceState(historyState, '', url);
}
function getStateFromHistory() {
const result = {};
Object.keys(historyState).forEach((k) => {
result[querystringMappings[k]] = historyState[k];
});
return result;
}
// Parse initial history state
function parseInitial(arg) {
const querystrings = arg.replace('\?','').split('&');
const validKeys = Object.keys(querystringMappings);
querystrings.forEach((d) => {
const pair = d.split('=');
const [k, v] = pair;
if (!v) { return; }
if (validKeys.indexOf(k) !== -1) {
if (['true', 'false'].indexOf(v.toLowerCase()) !== -1) {
replace(k, v.toLowerCase() === 'true');
} else {
replace(k, v);
}
}
});
}
module.exports = {
getStateFromHistory,
updateHistoryFromState,
parseInitial,
querystringMappings,
};
| tmrowco/electricitymap | web/src/helpers/historystate.js | JavaScript | gpl-3.0 | 2,209 |
// Copyright 2017-2021, University of Colorado Boulder
/**
* The reward that is displayed when all levels have been correctly completed. For testing, the simulation can be run
* with the 'showRewardNodeEveryLevel' query parameter to show the reward each time a level is successfully completed.
*
* @author John Blanco
*/
import FaceNode from '../../../../scenery-phet/js/FaceNode.js';
import MathSymbolFont from '../../../../scenery-phet/js/MathSymbolFont.js';
import StarNode from '../../../../scenery-phet/js/StarNode.js';
import { Text } from '../../../../scenery/js/imports.js';
import RewardNode from '../../../../vegas/js/RewardNode.js';
import CoinTermTypeID from '../../common/enum/CoinTermTypeID.js';
import CoinNodeFactory from '../../common/view/CoinNodeFactory.js';
import expressionExchange from '../../expressionExchange.js';
// constants
const NUMBER_OF_NODES = 60;
const FACE_DIAMETER = 50;
const COIN_RADIUS = 22;
const STAR_OUTER_RADIUS = 20;
const STAR_INNER_RADIUS = STAR_OUTER_RADIUS / 2;
const VARIABLE_FONT = new MathSymbolFont( 36 );
class EERewardNode extends RewardNode {
constructor() {
// add nodes that look like smiley faces, stars, and variables
const nodes = [
new FaceNode( FACE_DIAMETER ),
new StarNode( { outerRadius: STAR_OUTER_RADIUS, innerRadius: STAR_INNER_RADIUS } ),
new Text( 'x', { font: VARIABLE_FONT } ),
new Text( 'y', { font: VARIABLE_FONT } ),
new Text( 'z', { font: VARIABLE_FONT } )
];
// add a node for each coin type
CoinTermTypeID.VALUES.forEach( coinTermTypeID => {
if ( coinTermTypeID !== CoinTermTypeID.CONSTANT ) {
nodes.push( CoinNodeFactory.createImageNode( coinTermTypeID, COIN_RADIUS, true ) );
}
} );
super( { nodes: RewardNode.createRandomNodes( nodes, NUMBER_OF_NODES ) } );
}
}
expressionExchange.register( 'EERewardNode', EERewardNode );
export default EERewardNode; | phetsims/expression-exchange | js/game/view/EERewardNode.js | JavaScript | gpl-3.0 | 1,929 |
Ext.define('App.app.model.Role', {
extend: 'Ext.data.Model',
fields: [
'ID',
'Code',
'Name',
'Sort',
'Status',
'Comment'
]
}); | tengge1/ExtApp | ExtApp/ExtApp.Web/app/app/model/Role.js | JavaScript | gpl-3.0 | 191 |
var app = angular.module('app', []);
app.config(function ($httpProvider) {
$httpProvider.defaults.transformRequest = function (data) {
if (data === undefined) {
return data;
}
return $.param(data);
};
$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;';
});
app.controller('MainCtrl', function ($scope, $http, $timeout, variableService) {
$scope.brightness = "255";
$scope.busy = false;
$scope.power = 1;
$scope.color = "#0000ff"
$scope.r = 0;
$scope.g = 0;
$scope.b = 255;
$scope.powerText = "On";
$scope.status = "Please enter your access token:";
$scope.disconnected = false;
$scope.accessToken = "";
$scope.isDeviceSelected = false;
$scope.patterns = [];
$scope.patternIndex = 0;
$scope.devices = [];
$scope.onSelectedDeviceChange = function() {
$scope.isDeviceSelected = $scope.device != null;
if($scope.device != null && $scope.device.connected == true)
$scope.connect();
}
$scope.onSelectedPatternChange = function() {
$scope.setPattern();
}
$scope.onSelectedColorChange = function() {
$scope.setColor();
}
$scope.getDevices = function () {
$scope.status = 'Getting devices...';
$http.get('https://api.particle.io/v1/devices?access_token=' + $scope.accessToken).
success(function (data, status, headers, config) {
if (data && data.length > 0) {
var deviceId = null;
if (Modernizr.localstorage) {
deviceId = localStorage["deviceId"];
}
for (var i = 0; i < data.length; i++) {
var device = data[i];
device.title = (device.connected == true ? "● " : "◌ ") + device.name;
device.status = device.connected == true ? "online" : "offline";
if (data[i].id == deviceId) {
$scope.device = data[i];
$scope.onSelectedDeviceChange();
}
}
$scope.devices = data;
if (!$scope.device)
$scope.device = data[0];
$scope.isDeviceSelected = $scope.device != null;
}
$scope.status = 'Loaded devices';
}).
error(function (data, status, headers, config) {
$scope.busy = false;
$scope.status = data.error_description;
});
}
if (Modernizr.localstorage) {
$scope.accessToken = localStorage["accessToken"];
if ($scope.accessToken && $scope.accessToken != "") {
$scope.status = "";
$scope.getDevices();
}
}
$scope.save = function () {
localStorage["accessToken"] = $scope.accessToken;
$scope.status = "Saved access token";
$scope.getDevices();
}
$scope.connect = function () {
// $scope.busy = true;
localStorage["deviceId"] = $scope.device.id;
variableService.getVariableValue("power", $scope.device.id, $scope.accessToken)
.then(function (response) {
$scope.power = response.data.result;
$scope.status = 'Loaded power';
})
.then(function (data) {
return variableService.getVariableValue("brightness", $scope.device.id, $scope.accessToken);
})
.then(function (response) {
$scope.brightness = response.data.result;
$scope.status = 'Loaded brightness';
})
.then(function (data) {
return variableService.getVariableValue("r", $scope.device.id, $scope.accessToken);
})
.then(function (response) {
$scope.r = response.data.return_value;
$scope.status = 'Loaded red';
})
.then(function (data) {
return variableService.getVariableValue("g", $scope.device.id, $scope.accessToken);
})
.then(function (response) {
$scope.g = response.data.return_value;
$scope.status = 'Loaded green';
})
.then(function (data) {
return variableService.getVariableValue("b", $scope.device.id, $scope.accessToken);
})
.then(function (response) {
$scope.b = response.data.return_value;
$scope.status = 'Loaded blue';
})
.then(function () {
$scope.getPatterns();
})
.then(function () {
$scope.getPatternIndex();
})
}
$scope.getPower = function () {
// $scope.busy = true;
$http.get('https://api.particle.io/v1/devices/' + $scope.device.id + '/power?access_token=' + $scope.accessToken).
success(function (data, status, headers, config) {
$scope.busy = false;
$scope.power = data.result;
}).
error(function (data, status, headers, config) {
$scope.busy = false;
$scope.status = data.error_description;
});
};
$scope.powerOn = function () {
// $scope.busy = true;
$http({
method: 'POST',
url: 'https://api.particle.io/v1/devices/' + $scope.device.id + '/variable',
data: { access_token: $scope.accessToken, args: "pwr:1" },
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).
success(function (data, status, headers, config) {
$scope.busy = false;
$scope.power = data.return_value;
$scope.status = $scope.power == 1 ? 'Turned on' : 'Turned off';
}).
error(function (data, status, headers, config) {
$scope.busy = false;
$scope.status = data.error_description;
});
};
$scope.powerOff = function () {
// $scope.busy = true;
$http({
method: 'POST',
url: 'https://api.particle.io/v1/devices/' + $scope.device.id + '/variable',
data: { access_token: $scope.accessToken, args: "pwr:0" },
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).
success(function (data, status, headers, config) {
$scope.busy = false;
$scope.power = data.return_value;
$scope.status = $scope.power == 1 ? 'Turned on' : 'Turned off';
}).
error(function (data, status, headers, config) {
$scope.busy = false;
$scope.status = data.error_description;
});
};
$scope.getBrightness = function () {
// $scope.busy = true;
$http.get('https://api.particle.io/v1/devices/' + $scope.device.id + '/brightness?access_token=' + $scope.accessToken).
success(function (data, status, headers, config) {
$scope.busy = false;
$scope.brightness = data.result;
}).
error(function (data, status, headers, config) {
$scope.busy = false;
$scope.status = data.error_description;
});
};
$scope.setBrightness = function ($) {
// $scope.busy = true;
$http({
method: 'POST',
url: 'https://api.particle.io/v1/devices/' + $scope.device.id + '/variable',
data: { access_token: $scope.accessToken, args: "brt:" + $scope.brightness },
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).
success(function (data, status, headers, config) {
$scope.busy = false;
$scope.brightness = data.return_value;
$scope.status = 'Brightness set';
}).
error(function (data, status, headers, config) {
$scope.busy = false;
$scope.status = data.error_description;
});
};
$scope.setColor = function ($) {
var rgb = $scope.hexToRgb();
$scope.r = rgb.r;
$scope.g = rgb.g;
$scope.b = rgb.b;
$scope.setR();
$scope.setG();
$scope.setB();
};
$scope.hexToRgb = function ($) {
var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec($scope.color);
return result ? {
r: parseInt(result[1], 16),
g: parseInt(result[2], 16),
b: parseInt(result[3], 16)
} : null;
}
$scope.setR = function ($) {
// $scope.busy = true;
$http({
method: 'POST',
url: 'https://api.particle.io/v1/devices/' + $scope.device.id + '/variable',
data: { access_token: $scope.accessToken, args: "r:" + $scope.r },
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).
success(function (data, status, headers, config) {
$scope.busy = false;
$scope.r = data.return_value;
$scope.status = 'Red set';
}).
error(function (data, status, headers, config) {
$scope.busy = false;
$scope.status = data.error_description;
});
};
$scope.setG = function ($) {
// $scope.busy = true;
$http({
method: 'POST',
url: 'https://api.particle.io/v1/devices/' + $scope.device.id + '/variable',
data: { access_token: $scope.accessToken, args: "g:" + $scope.g },
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).
success(function (data, status, headers, config) {
$scope.busy = false;
$scope.g = data.return_value;
$scope.status = 'Green set';
}).
error(function (data, status, headers, config) {
$scope.busy = false;
$scope.status = data.error_description;
});
};
$scope.setB = function ($) {
// $scope.busy = true;
$http({
method: 'POST',
url: 'https://api.particle.io/v1/devices/' + $scope.device.id + '/variable',
data: { access_token: $scope.accessToken, args: "b:" + $scope.b },
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).
success(function (data, status, headers, config) {
$scope.busy = false;
$scope.b = data.return_value;
$scope.status = 'Blue set';
}).
error(function (data, status, headers, config) {
$scope.busy = false;
$scope.status = data.error_description;
});
};
$scope.getPatternIndex = function () {
// $scope.busy = true;
$http.get('https://api.particle.io/v1/devices/' + $scope.device.id + '/patternIndex?access_token=' + $scope.accessToken).
success(function (data, status, headers, config) {
$scope.busy = false;
$scope.patternIndex = data.result;
$scope.pattern = $scope.patterns[$scope.patternIndex];
}).
error(function (data, status, headers, config) {
$scope.busy = false;
$scope.status = data.error_description;
});
};
$scope.getPatterns = function () {
// $scope.busy = true;
// get the pattern name list
var promise = $http.get('https://api.particle.io/v1/devices/' + $scope.device.id + '/patternNames?access_token=' + $scope.accessToken);
promise.then(
function (payload) {
var patternNames = JSON.parse(payload.data.result);
for(var i = 0; i < patternNames.length; i++) {
$scope.patterns.push({ index: i, name: patternNames[i] });
}
$scope.patternCount = patternNames.length;
$scope.status = 'Loaded patterns';
},
function (errorPayload) {
$scope.busy = false;
$scope.status = data.error_description;
});
};
$scope.setPattern = function () {
// $scope.busy = true;
var promise = $http({
method: 'POST',
url: 'https://api.particle.io/v1/devices/' + $scope.device.id + '/patternIndex',
data: { access_token: $scope.accessToken, args: $scope.pattern.index },
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
})
.then(
function (payload) {
$scope.busy = false;
$scope.status = 'Pattern set';
},
function (errorPayload) {
$scope.busy = false;
});
};
});
app.factory('variableService', function ($http) {
return {
getVariableValue: function (variableName, deviceId, accessToken) {
return $http({
method: 'GET',
url: 'https://api.particle.io/v1/devices/' + deviceId + '/' + variableName + '?access_token=' + accessToken,
});
},
getExtendedVariableValue: function (variableName, deviceId, accessToken) {
return $http({
method: 'POST',
url: 'https://api.particle.io/v1/devices/' + deviceId + '/varCursor',
data: { access_token: accessToken, args: variableName },
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});
}
}
});
| evilgeniuslabs/plasma | js/app.js | JavaScript | gpl-3.0 | 11,867 |
(function(w, $) {
// Carousel
jQuery(function($) {
$('.carousel').carousel({
interval: 5000,
keyboard: true
});
});
})(window, jQuery);
function errorForm(msg){
swal({
title: "Ups!",
text: msg,
type: "error",
timer: 4000,
animation: "pop",
confirmButtonText: "Vale"
});
}
function successProfile(msg){
swal({
title: "Yuju!",
text: msg,
type: "success",
timer: 4000,
animation: "pop",
confirmButtonText: "Vale"
});
}
function successLogOut(msg){
swal({
title: "¡Te echaremos de menos!",
text: msg,
type: "success",
timer: 4000,
animation: "pop",
confirmButtonText: "Vale"
});
}
function successUpLogged(){
swal({
title: "¡Gracias por enviar tu avispamiento!",
text: "Muchas gracias por tu colaboración ;)",
type: "success",
timer: 4000,
animation: "pop",
confirmButtonText: "Vale"
});
}
function successUp(msg){
swal({
title: "¡Gracias por enviar tu avispamiento!",
text: msg,
type: "info",
showCancelButton: true,
cancelButtonText: "No, gracias",
confirmButtonColor: "#55dd57",
confirmButtonText: "¡Registrarme! o Login",
closeOnConfirm: false,
closeOnCancel: false,
},
function(isConfirm){
if (isConfirm) {
window.location = '/login/';
}else {
swal({
title: "Puedes registrarte en cualquier otro momento",
text: "Muchas gracias por tu colaboración ;)",
type: "success",
timer: 4000,
confirmButtonText: "Vale",
},
function(isConfirm){
if (isConfirm) {
window.location = '/';
}
});
}
});
}
function successSendMessage(msg){
swal({
title: "¡Gracias por contactar con nosotros!",
text: msg,
type: "success",
timer: 4000,
animation: "pop",
confirmButtonText: "Vale"
});
} | CarlosTenorio/vespapp-web | src/js/main.js | JavaScript | gpl-3.0 | 1,968 |
(function() {
'use strict';
angular
.module('klaskApp')
.controller('UserManagementDeleteController', UserManagementDeleteController);
UserManagementDeleteController.$inject = ['$uibModalInstance', 'entity', 'User'];
function UserManagementDeleteController ($uibModalInstance, entity, User) {
var vm = this;
vm.user = entity;
vm.clear = clear;
vm.confirmDelete = confirmDelete;
function clear () {
$uibModalInstance.dismiss('cancel');
}
function confirmDelete (login) {
User.delete({login: login},
function () {
$uibModalInstance.close(true);
});
}
}
})();
| klask-io/klask-io | src/main/webapp/app/admin/user-management/user-management-delete-dialog.controller.js | JavaScript | gpl-3.0 | 739 |
canvas = document.getElementById('canvas');
ctx = canvas.getContext('2d');
var ball1 = new cel.Body({
x: 25,
y: 25,
size:15,
//mass:0,
type: 'circle'
});
var ball2 = new cel.Body({
x: 30,
y: 250,
size:15,
mass:0,
type: 'square'
});
var touching = false;
setInterval(function () {
if (!touching) {
touching = ball1.isTouching(ball2);
cel.clear(canvas, ctx);
ball1.update(ctx);
ball2.update(ctx);
ball1.y += 1;
ball2.y -= 1;
}
}, 10);
setTimeout(function () {
console.log(ball1, ball2);
}, 1000);
/*var ball = new cel.Body({
x: 25,
y: 25,
height: 25,
width: 10,
type: 'rect',
xV: 10,
yV: 5
});
console.log(ball);
setInterval(function () {
cel.clear(canvas, ctx);
ball.update(ctx);
}, 10);
setTimeout(function () {
console.log(ball);
ball.applyLinearForce(5, 5);
}, 1000);*/ | Firedrake969/celeritas.js | test/test.js | JavaScript | gpl-3.0 | 920 |
$(function () {
//初始化元素选择模态窗口
$("#ProductEditModal").modal({
show: false
}).on("shown.bs.modal", function () {
$.ajax({
type: "GET",
url: "/ProductMaintain/AjaxLoadEditProduct?ProductSysNo=" + ProductEdit.ProductSysNo,
dataType: "html",
success: function (data) {
$("#ProductEditModal").find(".modal-content").html(data);
$('.date-picker').datepicker({
dateFormat: 'yyyy-mm-dd',
rtl: Metronic.isRTL(),
orientation: "left",
autoclose: true,
language: "zh-CN"
});
$(".date-range").defaultDateRangePicker();
}
});
}).on("hide.bs.modal", function (e) {
$("#ProductEditModal").find(".modal-content").html("");
});
});
//商品编辑
var ProductEdit = {
CallbackFunction: null,
//商品编号
ProductSysNo: 0,
//打开编辑窗口
Open: function (productSysNo, callback) {
ProductEdit.CallbackFunction = callback;
ProductEdit.ProductSysNo = productSysNo;
$("#ProductEditModal").modal("show");
},
Save: function () {
var data = $.buildEntity($("#MaintainForm"));
var regNumber = /^[0-9]*$/;
var reg = /^\d{0,8}\.{0,1}(\d{1,2})?$/;
var strRegUrl = "^(https://|http://)"
+ "?(([0-9a-z_!~*'().&=+$%-]+: )?[0-9a-z_!~*'().&=+$%-]+@)?" //ftp的user@
+ "(([0-9]{1,3}.){3}[0-9]{1,3}" // IP形式的URL- 199.194.52.184
+ "|" // 允许IP和DOMAIN(域名)
+ "([0-9a-z_!~*'()-]+.)*" // 域名- www.
+ "([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]." // 二级域名
+ "[a-z]{2,6})" // first level domain- .com or .museum
+ "(:[0-9]{1,4})?" // 端口- :80
+ "((/?)|" // a slash isn't required if there is no file name
+ "(/[0-9a-z_!~*'().;?:@&=+$,%#-]+)+/?)$";
var regUrl = new RegExp(strRegUrl);
if ($.trim(data.ProductMode).length == 0) {
$.alert("请输入型号!");
return false;
}
if (!regNumber.test(data.Weight)) {
$.alert("重量必须输入大于等于0的整数!");
return false;
}
if (parseInt(data.Weight) <= 0)
{
$.alert("重量必须输入大于等于0的整数!");
return false;
}
if (!reg.test(data.Length)) {
$.alert("长度必须输入大于等于0的整数或者2位小数!");
return false;
}
if (!reg.test(data.Width)) {
$.alert("宽度必须输入大于等于0的整数或者2位小数!");
return false;
}
if (!reg.test(data.Height)) {
$.alert("高度必须输入大于等于0的整数或者2位小数!");
return false;
}
if ($.trim(data.ProductOutUrl).length > 0 && !regUrl.test(data.ProductOutUrl)) {
$.alert("请填写正确的网址,以http://开头!");
return false;
}
$.ajax({
url: "/ProductMaintain/AjaxSaveSingleProductInfo",
type: "POST",
dataType: "json",
data: { data: encodeURI(JSON.stringify(data)) },
beforeSend: function (XMLHttpRequest) {
$.showLoading();
},
success: function (data) {
if (!data.message) {
$.confirm("保存商品信息成功!", function () {
if (ProductEdit.CallbackFunction) {
$("#ProductEditModal").modal("hide");
ProductEdit.CallbackFunction();
}
else {
location.reload();
}
});
}
},
complete: function (XMLHttpRequest, textStatus) {
$.hideLoading();
}
});
}
} | ZeroOne71/ql | 03_SellerPortal/ECommerce.Web/Content/scripts/ProductMaintain/ProductEdit.js | JavaScript | gpl-3.0 | 4,232 |
Ext.namespace('go.modules.comments');
go.modules.comments.CommentsDetailPanel = Ext.extend(Ext.Panel, {
model_name: null,
title: t("Comments", "comments"),
collapsible: true,
titleCollapse: true,
stateId: "comments-detail",
initComponent: function () {
this.store = new GO.data.JsonStore({
url: GO.url('comments/comment/store'),
baseParams: {
task: 'comments',
limit: 10
},
fields: ['id', 'model_id', 'category_id', 'category_name', 'model_name', 'user_name', 'ctime', 'mtime', 'comments'],
remoteSort: true
});
go.modules.comments.CommentsDetailPanel.superclass.initComponent.call(this);
},
onLoad: function (dv) {
this.model_id = dv.model_id ? dv.model_id : dv.currentId //model_id is from old display panel
this.model_name = dv.model_name || dv.entity || dv.entityStore.entity.name;
this.removeAll();
this.store.load({
params: {
model_name: this.model_name,
model_id: this.model_id
},
callback: function() {
var me = this;
this.store.each(function(record) {
var readMore = new go.detail.ReadMore();
readMore.setText(record.get('comments'));
this.add({
xtype:"panel",
tbarCfg:{
style:'border-bottom:none;border-top:1px solid #E0E0E0;'
},
tbar:[
{
xtype:"tbtitle",
style:'font-size:'+dp(16)+'px; height:'+dp(14)+'px;',
text:t('{author} wrote at {date}').replace('{author}', record.get('user_name')).replace('{date}', record.get('ctime'))
},
'->',
{
iconCls: 'ic-more-vert',
menu:[
{
iconCls: "ic-edit",
text: t("Edit"),
handler: function () {
var dlg = GO.comments.showCommentDialog(record.get('id'), {
link_config: {
model_name: me.model_name,
model_id: me.model_id
}
});
dlg.on('hide', function(){
me.onLoad(me);
}, this, {single: true});
},
scope: this
},{
iconCls: "ic-delete",
text: t("Delete"),
handler: function () {
Ext.MessageBox.confirm(t("Confirm delete"), t("Are you sure you want to delete this item?"), function(btn) {
if(btn == 'yes') {
GO.request({
url:'comments/comment/delete',
params:{
id:record.get('id')
},
success: function(response, options, result){
if(!result.success){
alert(result.feedback);
}
me.onLoad(me);
},
scope:this
});
}
});
},
scope: this
}
]
}
],
items: [
// {
// xtype:'box',
// autoEl: 'h5',
// cls:'pad',
// html: '<div class="icons">'++'<a class="right show-on-hover"><i class="icon">delete</i></a></div>'
// },
readMore
]
});
}, this);
this.doLayout();
},
scope: this
});
}
});
| deependhulla/powermail-debian9 | files/rootdir/usr/local/src/groupoffice-6.3/modules/comments/CommentsDetailPanel.js | JavaScript | gpl-3.0 | 3,123 |
/* Copyright (C) 2012 Trackplus
* $Id$
*/
Ext.define('Ext.ux.LinkComponent', {
extend: 'Ext.Component',
alias: ['widget.linkcomponent'],
config:{
handler:null,
scope:null,
clsLink:'synopsis_blue',
label:'',
prefix:null,
suffix:null
},
initComponent: function(){
var me=this;
me.initHTML();
me.callParent();
me.addListener('afterrender',function(comp){
comp.getEl().addListener('click',me.elementClick,me);
},me);
},
initHTML:function(){
var me=this;
if(me.label!=null){
me.html='<a class="'+me.clsLink+'" href="javascript:void(0)">'+me.label+'</a>'
if(me.prefix!=null){
me.html=me.prefix+me.html;
}
if(me.suffix!=null){
me.html=me.html+me.suffix;
}
}else{
me.html='';
}
},
setLabel:function(label){
var me=this;
me.label=label;
me.initHTML();
me.update(me.html);
},
setClsLink:function(clsLink){
var me=this;
me.clsLink=clsLink;
me.initHTML();
me.update(me.html);
},
elementClick:function(e){
var me=this;
var match = e.getTarget().className.indexOf(me.clsLink)!=-1;
if(match){
if(me.handler!=null){
me.handler.call(me.scope||me);
}
e.stopEvent();
return false;
}
},
getMyLabel:function(){
var me=this;
return me.label;
}
});
| trackplus/Genji | src/main/webapp/js/ext/ux/LinkComponent.js | JavaScript | gpl-3.0 | 1,249 |
'use strict';
module.exports = function(sequelize, DataTypes) {
return sequelize.define('FeedbrowserCache', {
feed_url: {
type: DataTypes.TEXT,
allowNull: false
},
site_url: {
type: DataTypes.TEXT,
allowNull: false
},
title: {
type: DataTypes.TEXT,
allowNull: false
},
subscribers: {
type: DataTypes.INTEGER(11),
allowNull: false
}
}, {
tableName: 'ttrss_feedbrowser_cache'
});
};
| jchristi/syndicat | models/FeedbrowserCache.js | JavaScript | gpl-3.0 | 472 |
import KindAttributes from "../KindAttributes";
describe("backend/components/resource/form/KindAttributes", () => {
def("getModelValue", () => jest.fn(() => $resource.attributes.kind));
def("resource", () => factory("resource", { attributes: { kind: $kind } }));
def("root", () =>
$withFormContext(<KindAttributes />, {
sourceModel: $resource,
getModelValue: $getModelValue
})
);
[
"audio",
"document",
"file",
"image",
"interactive",
"link",
"pdf",
"presentation",
"spreadsheet",
"variants",
"video"
].forEach(kind => {
describe(`when the kind is ${kind}`, () => {
def("kind", () => kind);
it("matches the snapshot when rendered", () => {
expect(render($withApp($root)).html()).toMatchSnapshot();
});
});
});
});
| ManifoldScholar/manifold | client/src/backend/components/resource/form/__tests__/KindAttributes-test.js | JavaScript | gpl-3.0 | 829 |
"use strict";
ddcs.layout = ddcs.layout || {};
ddcs.layout.initialize = function() {
};
ddcs.layout.setDocumentColor = function(value){
var body = $('body');
body.css('background', 'linear-gradient(white, ' + value + ')');
body.css('background-repeat', 'no-repeat');
body.css('background-attachment', 'fixed');
};
| ThaumRystra/character-sheet-dnd5 | js/ddcs.layout.js | JavaScript | gpl-3.0 | 334 |
import {HLJob} from './base'
import { Formations} from "../formations";
import {MLRestJob} from "../ml/rest";
class HLRestJob extends HLJob {
constructor(entity, length, formatted) {
super();
this.entity = entity;
this.length = length;
this.done = false;
if (formatted) {
this.formation = new Formations.Rest();
} else {
this.formation = new Formations.Null();
}
}
assignMeJob(e) {
if (!this.commonStart()) {
e.resetNonHlJobs();
var newPos = this.formation.getPos(this.entity, e);
if (e.pos.distanceTo(newPos) > 0.1) {
e.pushJob(new MlMoveJob(e, newPos));
} else {
var dir = this.formation.getDir(this.entity, e);
e.pushJob(new MLRestJob(e, 5, dir));
}
}
}
}
export {HLRestJob}
| godrin/antargis.js | src/game/hl/rest.js | JavaScript | gpl-3.0 | 791 |
/*!
* Bootstrap v3.3.6 (http://getbootstrap.com)
* Copyright 2011-2015 Twitter, Inc.
* Licensed under the MIT license
*/
if(typeof jQuery==='undefined'){throw new Error('Bootstrap\'s JavaScript requires jQuery')}
+function($){'use strict';var version=$.fn.jquery.split(' ')[0].split('.')
if((version[0]<2&&version[1]<9)||(version[0]==1&&version[1]==9&&version[2]<1)||(version[0]>2)){throw new Error('Bootstrap\'s JavaScript requires jQuery version 1.9.1 or higher, but lower than version 3')}}(jQuery);+function($){'use strict';function transitionEnd(){var el=document.createElement('bootstrap')
var transEndEventNames={WebkitTransition:'webkitTransitionEnd',MozTransition:'transitionend',OTransition:'oTransitionEnd otransitionend',transition:'transitionend'}
for(var name in transEndEventNames){if(el.style[name]!==undefined){return{end:transEndEventNames[name]}}}
return false}
$.fn.emulateTransitionEnd=function(duration){var called=false
var $el=this
$(this).one('bsTransitionEnd',function(){called=true})
var callback=function(){if(!called)$($el).trigger($.support.transition.end)}
setTimeout(callback,duration)
return this}
$(function(){$.support.transition=transitionEnd()
if(!$.support.transition)return
$.event.special.bsTransitionEnd={bindType:$.support.transition.end,delegateType:$.support.transition.end,handle:function(e){if($(e.target).is(this))return e.handleObj.handler.apply(this,arguments)}}})}(jQuery);+function($){'use strict';var dismiss='[data-dismiss="alert"]'
var Alert=function(el){$(el).on('click',dismiss,this.close)}
Alert.VERSION='3.3.6'
Alert.TRANSITION_DURATION=150
Alert.prototype.close=function(e){var $this=$(this)
var selector=$this.attr('data-target')
if(!selector){selector=$this.attr('href')
selector=selector&&selector.replace(/.*(?=#[^\s]*$)/,'')}
var $parent=$(selector)
if(e)e.preventDefault()
if(!$parent.length){$parent=$this.closest('.alert')}
$parent.trigger(e=$.Event('close.bs.alert'))
if(e.isDefaultPrevented())return
$parent.removeClass('in')
function removeElement(){$parent.detach().trigger('closed.bs.alert').remove()}
$.support.transition&&$parent.hasClass('fade')?$parent.one('bsTransitionEnd',removeElement).emulateTransitionEnd(Alert.TRANSITION_DURATION):removeElement()}
function Plugin(option){return this.each(function(){var $this=$(this)
var data=$this.data('bs.alert')
if(!data)$this.data('bs.alert',(data=new Alert(this)))
if(typeof option=='string')data[option].call($this)})}
var old=$.fn.alert
$.fn.alert=Plugin
$.fn.alert.Constructor=Alert
$.fn.alert.noConflict=function(){$.fn.alert=old
return this}
$(document).on('click.bs.alert.data-api',dismiss,Alert.prototype.close)}(jQuery);+function($){'use strict';var Button=function(element,options){this.$element=$(element)
this.options=$.extend({},Button.DEFAULTS,options)
this.isLoading=false}
Button.VERSION='3.3.6'
Button.DEFAULTS={loadingText:'loading...'}
Button.prototype.setState=function(state){var d='disabled'
var $el=this.$element
var val=$el.is('input')?'val':'html'
var data=$el.data()
state+='Text'
if(data.resetText==null)$el.data('resetText',$el[val]())
setTimeout($.proxy(function(){$el[val](data[state]==null?this.options[state]:data[state])
if(state=='loadingText'){this.isLoading=true
$el.addClass(d).attr(d,d)}else if(this.isLoading){this.isLoading=false
$el.removeClass(d).removeAttr(d)}},this),0)}
Button.prototype.toggle=function(){var changed=true
var $parent=this.$element.closest('[data-toggle="buttons"]')
if($parent.length){var $input=this.$element.find('input')
if($input.prop('type')=='radio'){if($input.prop('checked'))changed=false
$parent.find('.active').removeClass('active')
this.$element.addClass('active')}else if($input.prop('type')=='checkbox'){if(($input.prop('checked'))!==this.$element.hasClass('active'))changed=false
this.$element.toggleClass('active')}
$input.prop('checked',this.$element.hasClass('active'))
if(changed)$input.trigger('change')}else{this.$element.attr('aria-pressed',!this.$element.hasClass('active'))
this.$element.toggleClass('active')}}
function Plugin(option){return this.each(function(){var $this=$(this)
var data=$this.data('bs.button')
var options=typeof option=='object'&&option
if(!data)$this.data('bs.button',(data=new Button(this,options)))
if(option=='toggle')data.toggle()
else if(option)data.setState(option)})}
var old=$.fn.button
$.fn.button=Plugin
$.fn.button.Constructor=Button
$.fn.button.noConflict=function(){$.fn.button=old
return this}
$(document).on('click.bs.button.data-api','[data-toggle^="button"]',function(e){var $btn=$(e.target)
if(!$btn.hasClass('btn'))$btn=$btn.closest('.btn')
Plugin.call($btn,'toggle')
if(!($(e.target).is('input[type="radio"]')||$(e.target).is('input[type="checkbox"]')))e.preventDefault()}).on('focus.bs.button.data-api blur.bs.button.data-api','[data-toggle^="button"]',function(e){$(e.target).closest('.btn').toggleClass('focus',/^focus(in)?$/.test(e.type))})}(jQuery);+function($){'use strict';var Carousel=function(element,options){this.$element=$(element)
this.$indicators=this.$element.find('.carousel-indicators')
this.options=options
this.paused=null
this.sliding=null
this.interval=null
this.$active=null
this.$items=null
this.options.keyboard&&this.$element.on('keydown.bs.carousel',$.proxy(this.keydown,this))
this.options.pause=='hover'&&!('ontouchstart'in document.documentElement)&&this.$element.on('mouseenter.bs.carousel',$.proxy(this.pause,this)).on('mouseleave.bs.carousel',$.proxy(this.cycle,this))}
Carousel.VERSION='3.3.6'
Carousel.TRANSITION_DURATION=600
Carousel.DEFAULTS={interval:5000,pause:'hover',wrap:true,keyboard:true}
Carousel.prototype.keydown=function(e){if(/input|textarea/i.test(e.target.tagName))return
switch(e.which){case 37:this.prev();break
case 39:this.next();break
default:return}
e.preventDefault()}
Carousel.prototype.cycle=function(e){e||(this.paused=false)
this.interval&&clearInterval(this.interval)
this.options.interval&&!this.paused&&(this.interval=setInterval($.proxy(this.next,this),this.options.interval))
return this}
Carousel.prototype.getItemIndex=function(item){this.$items=item.parent().children('.item')
return this.$items.index(item||this.$active)}
Carousel.prototype.getItemForDirection=function(direction,active){var activeIndex=this.getItemIndex(active)
var willWrap=(direction=='prev'&&activeIndex===0)||(direction=='next'&&activeIndex==(this.$items.length-1))
if(willWrap&&!this.options.wrap)return active
var delta=direction=='prev'?-1:1
var itemIndex=(activeIndex+delta)%this.$items.length
return this.$items.eq(itemIndex)}
Carousel.prototype.to=function(pos){var that=this
var activeIndex=this.getItemIndex(this.$active=this.$element.find('.item.active'))
if(pos>(this.$items.length-1)||pos<0)return
if(this.sliding)return this.$element.one('slid.bs.carousel',function(){that.to(pos)})
if(activeIndex==pos)return this.pause().cycle()
return this.slide(pos>activeIndex?'next':'prev',this.$items.eq(pos))}
Carousel.prototype.pause=function(e){e||(this.paused=true)
if(this.$element.find('.next, .prev').length&&$.support.transition){this.$element.trigger($.support.transition.end)
this.cycle(true)}
this.interval=clearInterval(this.interval)
return this}
Carousel.prototype.next=function(){if(this.sliding)return
return this.slide('next')}
Carousel.prototype.prev=function(){if(this.sliding)return
return this.slide('prev')}
Carousel.prototype.slide=function(type,next){var $active=this.$element.find('.item.active')
var $next=next||this.getItemForDirection(type,$active)
var isCycling=this.interval
var direction=type=='next'?'left':'right'
var that=this
if($next.hasClass('active'))return(this.sliding=false)
var relatedTarget=$next[0]
var slideEvent=$.Event('slide.bs.carousel',{relatedTarget:relatedTarget,direction:direction})
this.$element.trigger(slideEvent)
if(slideEvent.isDefaultPrevented())return
this.sliding=true
isCycling&&this.pause()
if(this.$indicators.length){this.$indicators.find('.active').removeClass('active')
var $nextIndicator=$(this.$indicators.children()[this.getItemIndex($next)])
$nextIndicator&&$nextIndicator.addClass('active')}
var slidEvent=$.Event('slid.bs.carousel',{relatedTarget:relatedTarget,direction:direction})
if($.support.transition&&this.$element.hasClass('slide')){$next.addClass(type)
$next[0].offsetWidth
$active.addClass(direction)
$next.addClass(direction)
$active.one('bsTransitionEnd',function(){$next.removeClass([type,direction].join(' ')).addClass('active')
$active.removeClass(['active',direction].join(' '))
that.sliding=false
setTimeout(function(){that.$element.trigger(slidEvent)},0)}).emulateTransitionEnd(Carousel.TRANSITION_DURATION)}else{$active.removeClass('active')
$next.addClass('active')
this.sliding=false
this.$element.trigger(slidEvent)}
isCycling&&this.cycle()
return this}
function Plugin(option){return this.each(function(){var $this=$(this)
var data=$this.data('bs.carousel')
var options=$.extend({},Carousel.DEFAULTS,$this.data(),typeof option=='object'&&option)
var action=typeof option=='string'?option:options.slide
if(!data)$this.data('bs.carousel',(data=new Carousel(this,options)))
if(typeof option=='number')data.to(option)
else if(action)data[action]()
else if(options.interval)data.pause().cycle()})}
var old=$.fn.carousel
$.fn.carousel=Plugin
$.fn.carousel.Constructor=Carousel
$.fn.carousel.noConflict=function(){$.fn.carousel=old
return this}
var clickHandler=function(e){var href
var $this=$(this)
var $target=$($this.attr('data-target')||(href=$this.attr('href'))&&href.replace(/.*(?=#[^\s]+$)/,''))
if(!$target.hasClass('carousel'))return
var options=$.extend({},$target.data(),$this.data())
var slideIndex=$this.attr('data-slide-to')
if(slideIndex)options.interval=false
Plugin.call($target,options)
if(slideIndex){$target.data('bs.carousel').to(slideIndex)}
e.preventDefault()}
$(document).on('click.bs.carousel.data-api','[data-slide]',clickHandler).on('click.bs.carousel.data-api','[data-slide-to]',clickHandler)
$(window).on('load',function(){$('[data-ride="carousel"]').each(function(){var $carousel=$(this)
Plugin.call($carousel,$carousel.data())})})}(jQuery);+function($){'use strict';var Collapse=function(element,options){this.$element=$(element)
this.options=$.extend({},Collapse.DEFAULTS,options)
this.$trigger=$('[data-toggle="collapse"][href="#'+element.id+'"],'+
'[data-toggle="collapse"][data-target="#'+element.id+'"]')
this.transitioning=null
if(this.options.parent){this.$parent=this.getParent()}else{this.addAriaAndCollapsedClass(this.$element,this.$trigger)}
if(this.options.toggle)this.toggle()}
Collapse.VERSION='3.3.6'
Collapse.TRANSITION_DURATION=350
Collapse.DEFAULTS={toggle:true}
Collapse.prototype.dimension=function(){var hasWidth=this.$element.hasClass('width')
return hasWidth?'width':'height'}
Collapse.prototype.show=function(){if(this.transitioning||this.$element.hasClass('in'))return
var activesData
var actives=this.$parent&&this.$parent.children('.panel').children('.in, .collapsing')
if(actives&&actives.length){activesData=actives.data('bs.collapse')
if(activesData&&activesData.transitioning)return}
var startEvent=$.Event('show.bs.collapse')
this.$element.trigger(startEvent)
if(startEvent.isDefaultPrevented())return
if(actives&&actives.length){Plugin.call(actives,'hide')
activesData||actives.data('bs.collapse',null)}
var dimension=this.dimension()
this.$element.removeClass('collapse').addClass('collapsing')[dimension](0).attr('aria-expanded',true)
this.$trigger.removeClass('collapsed').attr('aria-expanded',true)
this.transitioning=1
var complete=function(){this.$element.removeClass('collapsing').addClass('collapse in')[dimension]('')
this.transitioning=0
this.$element.trigger('shown.bs.collapse')}
if(!$.support.transition)return complete.call(this)
var scrollSize=$.camelCase(['scroll',dimension].join('-'))
this.$element.one('bsTransitionEnd',$.proxy(complete,this)).emulateTransitionEnd(Collapse.TRANSITION_DURATION)[dimension](this.$element[0][scrollSize])}
Collapse.prototype.hide=function(){if(this.transitioning||!this.$element.hasClass('in'))return
var startEvent=$.Event('hide.bs.collapse')
this.$element.trigger(startEvent)
if(startEvent.isDefaultPrevented())return
var dimension=this.dimension()
this.$element[dimension](this.$element[dimension]())[0].offsetHeight
this.$element.addClass('collapsing').removeClass('collapse in').attr('aria-expanded',false)
this.$trigger.addClass('collapsed').attr('aria-expanded',false)
this.transitioning=1
var complete=function(){this.transitioning=0
this.$element.removeClass('collapsing').addClass('collapse').trigger('hidden.bs.collapse')}
if(!$.support.transition)return complete.call(this)
this.$element
[dimension](0).one('bsTransitionEnd',$.proxy(complete,this)).emulateTransitionEnd(Collapse.TRANSITION_DURATION)}
Collapse.prototype.toggle=function(){this[this.$element.hasClass('in')?'hide':'show']()}
Collapse.prototype.getParent=function(){return $(this.options.parent).find('[data-toggle="collapse"][data-parent="'+this.options.parent+'"]').each($.proxy(function(i,element){var $element=$(element)
this.addAriaAndCollapsedClass(getTargetFromTrigger($element),$element)},this)).end()}
Collapse.prototype.addAriaAndCollapsedClass=function($element,$trigger){var isOpen=$element.hasClass('in')
$element.attr('aria-expanded',isOpen)
$trigger.toggleClass('collapsed',!isOpen).attr('aria-expanded',isOpen)}
function getTargetFromTrigger($trigger){var href
var target=$trigger.attr('data-target')||(href=$trigger.attr('href'))&&href.replace(/.*(?=#[^\s]+$)/,'')
return $(target)}
function Plugin(option){return this.each(function(){var $this=$(this)
var data=$this.data('bs.collapse')
var options=$.extend({},Collapse.DEFAULTS,$this.data(),typeof option=='object'&&option)
if(!data&&options.toggle&&/show|hide/.test(option))options.toggle=false
if(!data)$this.data('bs.collapse',(data=new Collapse(this,options)))
if(typeof option=='string')data[option]()})}
var old=$.fn.collapse
$.fn.collapse=Plugin
$.fn.collapse.Constructor=Collapse
$.fn.collapse.noConflict=function(){$.fn.collapse=old
return this}
$(document).on('click.bs.collapse.data-api','[data-toggle="collapse"]',function(e){var $this=$(this)
if(!$this.attr('data-target'))e.preventDefault()
var $target=getTargetFromTrigger($this)
var data=$target.data('bs.collapse')
var option=data?'toggle':$this.data()
Plugin.call($target,option)})}(jQuery);+function($){'use strict';var backdrop='.dropdown-backdrop'
var toggle='[data-toggle="dropdown"]'
var Dropdown=function(element){$(element).on('click.bs.dropdown',this.toggle)}
Dropdown.VERSION='3.3.6'
function getParent($this){var selector=$this.attr('data-target')
if(!selector){selector=$this.attr('href')
selector=selector&&/#[A-Za-z]/.test(selector)&&selector.replace(/.*(?=#[^\s]*$)/,'')}
var $parent=selector&&$(selector)
return $parent&&$parent.length?$parent:$this.parent()}
function clearMenus(e){if(e&&e.which===3)return
$(backdrop).remove()
$(toggle).each(function(){var $this=$(this)
var $parent=getParent($this)
var relatedTarget={relatedTarget:this}
if(!$parent.hasClass('open'))return
if(e&&e.type=='click'&&/input|textarea/i.test(e.target.tagName)&&$.contains($parent[0],e.target))return
$parent.trigger(e=$.Event('hide.bs.dropdown',relatedTarget))
if(e.isDefaultPrevented())return
$this.attr('aria-expanded','false')
$parent.removeClass('open').trigger($.Event('hidden.bs.dropdown',relatedTarget))})}
Dropdown.prototype.toggle=function(e){var $this=$(this)
if($this.is('.disabled, :disabled'))return
var $parent=getParent($this)
var isActive=$parent.hasClass('open')
clearMenus()
if(!isActive){if('ontouchstart'in document.documentElement&&!$parent.closest('.navbar-nav').length){$(document.createElement('div')).addClass('dropdown-backdrop').insertAfter($(this)).on('click',clearMenus)}
var relatedTarget={relatedTarget:this}
$parent.trigger(e=$.Event('show.bs.dropdown',relatedTarget))
if(e.isDefaultPrevented())return
$this.trigger('focus').attr('aria-expanded','true')
$parent.toggleClass('open').trigger($.Event('shown.bs.dropdown',relatedTarget))}
return false}
Dropdown.prototype.keydown=function(e){if(!/(38|40|27|32)/.test(e.which)||/input|textarea/i.test(e.target.tagName))return
var $this=$(this)
e.preventDefault()
e.stopPropagation()
if($this.is('.disabled, :disabled'))return
var $parent=getParent($this)
var isActive=$parent.hasClass('open')
if(!isActive&&e.which!=27||isActive&&e.which==27){if(e.which==27)$parent.find(toggle).trigger('focus')
return $this.trigger('click')}
var desc=' li:not(.disabled):visible a'
var $items=$parent.find('.dropdown-menu'+desc)
if(!$items.length)return
var index=$items.index(e.target)
if(e.which==38&&index>0)index--
if(e.which==40&&index<$items.length-1)index++
if(!~index)index=0
$items.eq(index).trigger('focus')}
function Plugin(option){return this.each(function(){var $this=$(this)
var data=$this.data('bs.dropdown')
if(!data)$this.data('bs.dropdown',(data=new Dropdown(this)))
if(typeof option=='string')data[option].call($this)})}
var old=$.fn.dropdown
$.fn.dropdown=Plugin
$.fn.dropdown.Constructor=Dropdown
$.fn.dropdown.noConflict=function(){$.fn.dropdown=old
return this}
$(document).on('click.bs.dropdown.data-api',clearMenus).on('click.bs.dropdown.data-api','.dropdown form',function(e){e.stopPropagation()}).on('click.bs.dropdown.data-api',toggle,Dropdown.prototype.toggle).on('keydown.bs.dropdown.data-api',toggle,Dropdown.prototype.keydown).on('keydown.bs.dropdown.data-api','.dropdown-menu',Dropdown.prototype.keydown)}(jQuery);+function($){'use strict';var Modal=function(element,options){this.options=options
this.$body=$(document.body)
this.$element=$(element)
this.$dialog=this.$element.find('.modal-dialog')
this.$backdrop=null
this.isShown=null
this.originalBodyPad=null
this.scrollbarWidth=0
this.ignoreBackdropClick=false
if(this.options.remote){this.$element.find('.modal-content').load(this.options.remote,$.proxy(function(){this.$element.trigger('loaded.bs.modal')},this))}}
Modal.VERSION='3.3.6'
Modal.TRANSITION_DURATION=300
Modal.BACKDROP_TRANSITION_DURATION=150
Modal.DEFAULTS={backdrop:true,keyboard:true,show:true}
Modal.prototype.toggle=function(_relatedTarget){return this.isShown?this.hide():this.show(_relatedTarget)}
Modal.prototype.show=function(_relatedTarget){var that=this
var e=$.Event('show.bs.modal',{relatedTarget:_relatedTarget})
this.$element.trigger(e)
if(this.isShown||e.isDefaultPrevented())return
this.isShown=true
this.checkScrollbar()
this.setScrollbar()
this.$body.addClass('modal-open')
this.escape()
this.resize()
this.$element.on('click.dismiss.bs.modal','[data-dismiss="modal"]',$.proxy(this.hide,this))
this.$dialog.on('mousedown.dismiss.bs.modal',function(){that.$element.one('mouseup.dismiss.bs.modal',function(e){if($(e.target).is(that.$element))that.ignoreBackdropClick=true})})
this.backdrop(function(){var transition=$.support.transition&&that.$element.hasClass('fade')
if(!that.$element.parent().length){that.$element.appendTo(that.$body)}
that.$element.show().scrollTop(0)
that.adjustDialog()
if(transition){that.$element[0].offsetWidth}
that.$element.addClass('in')
that.enforceFocus()
var e=$.Event('shown.bs.modal',{relatedTarget:_relatedTarget})
transition?that.$dialog.one('bsTransitionEnd',function(){that.$element.trigger('focus').trigger(e)}).emulateTransitionEnd(Modal.TRANSITION_DURATION):that.$element.trigger('focus').trigger(e)})}
Modal.prototype.hide=function(e){if(e)e.preventDefault()
e=$.Event('hide.bs.modal')
this.$element.trigger(e)
if(!this.isShown||e.isDefaultPrevented())return
this.isShown=false
this.escape()
this.resize()
$(document).off('focusin.bs.modal')
this.$element.removeClass('in').off('click.dismiss.bs.modal').off('mouseup.dismiss.bs.modal')
this.$dialog.off('mousedown.dismiss.bs.modal')
$.support.transition&&this.$element.hasClass('fade')?this.$element.one('bsTransitionEnd',$.proxy(this.hideModal,this)).emulateTransitionEnd(Modal.TRANSITION_DURATION):this.hideModal()}
Modal.prototype.enforceFocus=function(){$(document).off('focusin.bs.modal').on('focusin.bs.modal',$.proxy(function(e){if(this.$element[0]!==e.target&&!this.$element.has(e.target).length){this.$element.trigger('focus')}},this))}
Modal.prototype.escape=function(){if(this.isShown&&this.options.keyboard){this.$element.on('keydown.dismiss.bs.modal',$.proxy(function(e){e.which==27&&this.hide()},this))}else if(!this.isShown){this.$element.off('keydown.dismiss.bs.modal')}}
Modal.prototype.resize=function(){if(this.isShown){$(window).on('resize.bs.modal',$.proxy(this.handleUpdate,this))}else{$(window).off('resize.bs.modal')}}
Modal.prototype.hideModal=function(){var that=this
this.$element.hide()
this.backdrop(function(){that.$body.removeClass('modal-open')
that.resetAdjustments()
that.resetScrollbar()
that.$element.trigger('hidden.bs.modal')})}
Modal.prototype.removeBackdrop=function(){this.$backdrop&&this.$backdrop.remove()
this.$backdrop=null}
Modal.prototype.backdrop=function(callback){var that=this
var animate=this.$element.hasClass('fade')?'fade':''
if(this.isShown&&this.options.backdrop){var doAnimate=$.support.transition&&animate
this.$backdrop=$(document.createElement('div')).addClass('modal-backdrop '+animate).appendTo(this.$body)
this.$element.on('click.dismiss.bs.modal',$.proxy(function(e){if(this.ignoreBackdropClick){this.ignoreBackdropClick=false
return}
if(e.target!==e.currentTarget)return
this.options.backdrop=='static'?this.$element[0].focus():this.hide()},this))
if(doAnimate)this.$backdrop[0].offsetWidth
this.$backdrop.addClass('in')
if(!callback)return
doAnimate?this.$backdrop.one('bsTransitionEnd',callback).emulateTransitionEnd(Modal.BACKDROP_TRANSITION_DURATION):callback()}else if(!this.isShown&&this.$backdrop){this.$backdrop.removeClass('in')
var callbackRemove=function(){that.removeBackdrop()
callback&&callback()}
$.support.transition&&this.$element.hasClass('fade')?this.$backdrop.one('bsTransitionEnd',callbackRemove).emulateTransitionEnd(Modal.BACKDROP_TRANSITION_DURATION):callbackRemove()}else if(callback){callback()}}
Modal.prototype.handleUpdate=function(){this.adjustDialog()}
Modal.prototype.adjustDialog=function(){var modalIsOverflowing=this.$element[0].scrollHeight>document.documentElement.clientHeight
this.$element.css({paddingLeft:!this.bodyIsOverflowing&&modalIsOverflowing?this.scrollbarWidth:'',paddingRight:this.bodyIsOverflowing&&!modalIsOverflowing?this.scrollbarWidth:''})}
Modal.prototype.resetAdjustments=function(){this.$element.css({paddingLeft:'',paddingRight:''})}
Modal.prototype.checkScrollbar=function(){var fullWindowWidth=window.innerWidth
if(!fullWindowWidth){var documentElementRect=document.documentElement.getBoundingClientRect()
fullWindowWidth=documentElementRect.right-Math.abs(documentElementRect.left)}
this.bodyIsOverflowing=document.body.clientWidth<fullWindowWidth
this.scrollbarWidth=this.measureScrollbar()}
Modal.prototype.setScrollbar=function(){var bodyPad=parseInt((this.$body.css('padding-right')||0),10)
this.originalBodyPad=document.body.style.paddingRight||''
if(this.bodyIsOverflowing)this.$body.css('padding-right',bodyPad+this.scrollbarWidth)}
Modal.prototype.resetScrollbar=function(){this.$body.css('padding-right',this.originalBodyPad)}
Modal.prototype.measureScrollbar=function(){var scrollDiv=document.createElement('div')
scrollDiv.className='modal-scrollbar-measure'
this.$body.append(scrollDiv)
var scrollbarWidth=scrollDiv.offsetWidth-scrollDiv.clientWidth
this.$body[0].removeChild(scrollDiv)
return scrollbarWidth}
function Plugin(option,_relatedTarget){return this.each(function(){var $this=$(this)
var data=$this.data('bs.modal')
var options=$.extend({},Modal.DEFAULTS,$this.data(),typeof option=='object'&&option)
if(!data)$this.data('bs.modal',(data=new Modal(this,options)))
if(typeof option=='string')data[option](_relatedTarget)
else if(options.show)data.show(_relatedTarget)})}
var old=$.fn.modal
$.fn.modal=Plugin
$.fn.modal.Constructor=Modal
$.fn.modal.noConflict=function(){$.fn.modal=old
return this}
$(document).on('click.bs.modal.data-api','[data-toggle="modal"]',function(e){var $this=$(this)
var href=$this.attr('href')
var $target=$($this.attr('data-target')||(href&&href.replace(/.*(?=#[^\s]+$)/,'')))
var option=$target.data('bs.modal')?'toggle':$.extend({remote:!/#/.test(href)&&href},$target.data(),$this.data())
if($this.is('a'))e.preventDefault()
$target.one('show.bs.modal',function(showEvent){if(showEvent.isDefaultPrevented())return
$target.one('hidden.bs.modal',function(){$this.is(':visible')&&$this.trigger('focus')})})
Plugin.call($target,option,this)})}(jQuery);+function($){'use strict';var Tooltip=function(element,options){this.type=null
this.options=null
this.enabled=null
this.timeout=null
this.hoverState=null
this.$element=null
this.inState=null
this.init('tooltip',element,options)}
Tooltip.VERSION='3.3.6'
Tooltip.TRANSITION_DURATION=150
Tooltip.DEFAULTS={animation:true,placement:'top',selector:false,template:'<div class="tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>',trigger:'hover focus',title:'',delay:0,html:false,container:false,viewport:{selector:'body',padding:0}}
Tooltip.prototype.init=function(type,element,options){this.enabled=true
this.type=type
this.$element=$(element)
this.options=this.getOptions(options)
this.$viewport=this.options.viewport&&$($.isFunction(this.options.viewport)?this.options.viewport.call(this,this.$element):(this.options.viewport.selector||this.options.viewport))
this.inState={click:false,hover:false,focus:false}
if(this.$element[0]instanceof document.constructor&&!this.options.selector){throw new Error('`selector` option must be specified when initializing '+this.type+' on the window.document object!')}
var triggers=this.options.trigger.split(' ')
for(var i=triggers.length;i--;){var trigger=triggers[i]
if(trigger=='click'){this.$element.on('click.'+this.type,this.options.selector,$.proxy(this.toggle,this))}else if(trigger!='manual'){var eventIn=trigger=='hover'?'mouseenter':'focusin'
var eventOut=trigger=='hover'?'mouseleave':'focusout'
this.$element.on(eventIn+'.'+this.type,this.options.selector,$.proxy(this.enter,this))
this.$element.on(eventOut+'.'+this.type,this.options.selector,$.proxy(this.leave,this))}}
this.options.selector?(this._options=$.extend({},this.options,{trigger:'manual',selector:''})):this.fixTitle()}
Tooltip.prototype.getDefaults=function(){return Tooltip.DEFAULTS}
Tooltip.prototype.getOptions=function(options){options=$.extend({},this.getDefaults(),this.$element.data(),options)
if(options.delay&&typeof options.delay=='number'){options.delay={show:options.delay,hide:options.delay}}
return options}
Tooltip.prototype.getDelegateOptions=function(){var options={}
var defaults=this.getDefaults()
this._options&&$.each(this._options,function(key,value){if(defaults[key]!=value)options[key]=value})
return options}
Tooltip.prototype.enter=function(obj){var self=obj instanceof this.constructor?obj:$(obj.currentTarget).data('bs.'+this.type)
if(!self){self=new this.constructor(obj.currentTarget,this.getDelegateOptions())
$(obj.currentTarget).data('bs.'+this.type,self)}
if(obj instanceof $.Event){self.inState[obj.type=='focusin'?'focus':'hover']=true}
if(self.tip().hasClass('in')||self.hoverState=='in'){self.hoverState='in'
return}
clearTimeout(self.timeout)
self.hoverState='in'
if(!self.options.delay||!self.options.delay.show)return self.show()
self.timeout=setTimeout(function(){if(self.hoverState=='in')self.show()},self.options.delay.show)}
Tooltip.prototype.isInStateTrue=function(){for(var key in this.inState){if(this.inState[key])return true}
return false}
Tooltip.prototype.leave=function(obj){var self=obj instanceof this.constructor?obj:$(obj.currentTarget).data('bs.'+this.type)
if(!self){self=new this.constructor(obj.currentTarget,this.getDelegateOptions())
$(obj.currentTarget).data('bs.'+this.type,self)}
if(obj instanceof $.Event){self.inState[obj.type=='focusout'?'focus':'hover']=false}
if(self.isInStateTrue())return
clearTimeout(self.timeout)
self.hoverState='out'
if(!self.options.delay||!self.options.delay.hide)return self.hide()
self.timeout=setTimeout(function(){if(self.hoverState=='out')self.hide()},self.options.delay.hide)}
Tooltip.prototype.show=function(){var e=$.Event('show.bs.'+this.type)
if(this.hasContent()&&this.enabled){this.$element.trigger(e)
var inDom=$.contains(this.$element[0].ownerDocument.documentElement,this.$element[0])
if(e.isDefaultPrevented()||!inDom)return
var that=this
var $tip=this.tip()
var tipId=this.getUID(this.type)
this.setContent()
$tip.attr('id',tipId)
this.$element.attr('aria-describedby',tipId)
if(this.options.animation)$tip.addClass('fade')
var placement=typeof this.options.placement=='function'?this.options.placement.call(this,$tip[0],this.$element[0]):this.options.placement
var autoToken=/\s?auto?\s?/i
var autoPlace=autoToken.test(placement)
if(autoPlace)placement=placement.replace(autoToken,'')||'top'
$tip.detach().css({top:0,left:0,display:'block'}).addClass(placement).data('bs.'+this.type,this)
this.options.container?$tip.appendTo(this.options.container):$tip.insertAfter(this.$element)
this.$element.trigger('inserted.bs.'+this.type)
var pos=this.getPosition()
var actualWidth=$tip[0].offsetWidth
var actualHeight=$tip[0].offsetHeight
if(autoPlace){var orgPlacement=placement
var viewportDim=this.getPosition(this.$viewport)
placement=placement=='bottom'&&pos.bottom+actualHeight>viewportDim.bottom?'top':placement=='top'&&pos.top-actualHeight<viewportDim.top?'bottom':placement=='right'&&pos.right+actualWidth>viewportDim.width?'left':placement=='left'&&pos.left-actualWidth<viewportDim.left?'right':placement
$tip.removeClass(orgPlacement).addClass(placement)}
var calculatedOffset=this.getCalculatedOffset(placement,pos,actualWidth,actualHeight)
this.applyPlacement(calculatedOffset,placement)
var complete=function(){var prevHoverState=that.hoverState
that.$element.trigger('shown.bs.'+that.type)
that.hoverState=null
if(prevHoverState=='out')that.leave(that)}
$.support.transition&&this.$tip.hasClass('fade')?$tip.one('bsTransitionEnd',complete).emulateTransitionEnd(Tooltip.TRANSITION_DURATION):complete()}}
Tooltip.prototype.applyPlacement=function(offset,placement){var $tip=this.tip()
var width=$tip[0].offsetWidth
var height=$tip[0].offsetHeight
var marginTop=parseInt($tip.css('margin-top'),10)
var marginLeft=parseInt($tip.css('margin-left'),10)
if(isNaN(marginTop))marginTop=0
if(isNaN(marginLeft))marginLeft=0
offset.top+=marginTop
offset.left+=marginLeft
$.offset.setOffset($tip[0],$.extend({using:function(props){$tip.css({top:Math.round(props.top),left:Math.round(props.left)})}},offset),0)
$tip.addClass('in')
var actualWidth=$tip[0].offsetWidth
var actualHeight=$tip[0].offsetHeight
if(placement=='top'&&actualHeight!=height){offset.top=offset.top+height-actualHeight}
var delta=this.getViewportAdjustedDelta(placement,offset,actualWidth,actualHeight)
if(delta.left)offset.left+=delta.left
else offset.top+=delta.top
var isVertical=/top|bottom/.test(placement)
var arrowDelta=isVertical?delta.left*2-width+actualWidth:delta.top*2-height+actualHeight
var arrowOffsetPosition=isVertical?'offsetWidth':'offsetHeight'
$tip.offset(offset)
this.replaceArrow(arrowDelta,$tip[0][arrowOffsetPosition],isVertical)}
Tooltip.prototype.replaceArrow=function(delta,dimension,isVertical){this.arrow().css(isVertical?'left':'top',50*(1-delta/dimension)+'%').css(isVertical?'top':'left','')}
Tooltip.prototype.setContent=function(){var $tip=this.tip()
var title=this.getTitle()
$tip.find('.tooltip-inner')[this.options.html?'html':'text'](title)
$tip.removeClass('fade in top bottom left right')}
Tooltip.prototype.hide=function(callback){var that=this
var $tip=$(this.$tip)
var e=$.Event('hide.bs.'+this.type)
function complete(){if(that.hoverState!='in')$tip.detach()
that.$element.removeAttr('aria-describedby').trigger('hidden.bs.'+that.type)
callback&&callback()}
this.$element.trigger(e)
if(e.isDefaultPrevented())return
$tip.removeClass('in')
$.support.transition&&$tip.hasClass('fade')?$tip.one('bsTransitionEnd',complete).emulateTransitionEnd(Tooltip.TRANSITION_DURATION):complete()
this.hoverState=null
return this}
Tooltip.prototype.fixTitle=function(){var $e=this.$element
if($e.attr('title')||typeof $e.attr('data-original-title')!='string'){$e.attr('data-original-title',$e.attr('title')||'').attr('title','')}}
Tooltip.prototype.hasContent=function(){return this.getTitle()}
Tooltip.prototype.getPosition=function($element){$element=$element||this.$element
var el=$element[0]
var isBody=el.tagName=='BODY'
var elRect=el.getBoundingClientRect()
if(elRect.width==null){elRect=$.extend({},elRect,{width:elRect.right-elRect.left,height:elRect.bottom-elRect.top})}
var elOffset=isBody?{top:0,left:0}:$element.offset()
var scroll={scroll:isBody?document.documentElement.scrollTop||document.body.scrollTop:$element.scrollTop()}
var outerDims=isBody?{width:$(window).width(),height:$(window).height()}:null
return $.extend({},elRect,scroll,outerDims,elOffset)}
Tooltip.prototype.getCalculatedOffset=function(placement,pos,actualWidth,actualHeight){return placement=='bottom'?{top:pos.top+pos.height,left:pos.left+pos.width/2-actualWidth/2}:placement=='top'?{top:pos.top-actualHeight,left:pos.left+pos.width/2-actualWidth/2}:placement=='left'?{top:pos.top+pos.height/2-actualHeight/2,left:pos.left-actualWidth}:{top:pos.top+pos.height/2-actualHeight/2,left:pos.left+pos.width}}
Tooltip.prototype.getViewportAdjustedDelta=function(placement,pos,actualWidth,actualHeight){var delta={top:0,left:0}
if(!this.$viewport)return delta
var viewportPadding=this.options.viewport&&this.options.viewport.padding||0
var viewportDimensions=this.getPosition(this.$viewport)
if(/right|left/.test(placement)){var topEdgeOffset=pos.top-viewportPadding-viewportDimensions.scroll
var bottomEdgeOffset=pos.top+viewportPadding-viewportDimensions.scroll+actualHeight
if(topEdgeOffset<viewportDimensions.top){delta.top=viewportDimensions.top-topEdgeOffset}else if(bottomEdgeOffset>viewportDimensions.top+viewportDimensions.height){delta.top=viewportDimensions.top+viewportDimensions.height-bottomEdgeOffset}}else{var leftEdgeOffset=pos.left-viewportPadding
var rightEdgeOffset=pos.left+viewportPadding+actualWidth
if(leftEdgeOffset<viewportDimensions.left){delta.left=viewportDimensions.left-leftEdgeOffset}else if(rightEdgeOffset>viewportDimensions.right){delta.left=viewportDimensions.left+viewportDimensions.width-rightEdgeOffset}}
return delta}
Tooltip.prototype.getTitle=function(){var title
var $e=this.$element
var o=this.options
title=$e.attr('data-original-title')||(typeof o.title=='function'?o.title.call($e[0]):o.title)
return title}
Tooltip.prototype.getUID=function(prefix){do prefix+=~~(Math.random()*1000000)
while(document.getElementById(prefix))
return prefix}
Tooltip.prototype.tip=function(){if(!this.$tip){this.$tip=$(this.options.template)
if(this.$tip.length!=1){throw new Error(this.type+' `template` option must consist of exactly 1 top-level element!')}}
return this.$tip}
Tooltip.prototype.arrow=function(){return(this.$arrow=this.$arrow||this.tip().find('.tooltip-arrow'))}
Tooltip.prototype.enable=function(){this.enabled=true}
Tooltip.prototype.disable=function(){this.enabled=false}
Tooltip.prototype.toggleEnabled=function(){this.enabled=!this.enabled}
Tooltip.prototype.toggle=function(e){var self=this
if(e){self=$(e.currentTarget).data('bs.'+this.type)
if(!self){self=new this.constructor(e.currentTarget,this.getDelegateOptions())
$(e.currentTarget).data('bs.'+this.type,self)}}
if(e){self.inState.click=!self.inState.click
if(self.isInStateTrue())self.enter(self)
else self.leave(self)}else{self.tip().hasClass('in')?self.leave(self):self.enter(self)}}
Tooltip.prototype.destroy=function(){var that=this
clearTimeout(this.timeout)
this.hide(function(){that.$element.off('.'+that.type).removeData('bs.'+that.type)
if(that.$tip){that.$tip.detach()}
that.$tip=null
that.$arrow=null
that.$viewport=null})}
function Plugin(option){return this.each(function(){var $this=$(this)
var data=$this.data('bs.tooltip')
var options=typeof option=='object'&&option
if(!data&&/destroy|hide/.test(option))return
if(!data)$this.data('bs.tooltip',(data=new Tooltip(this,options)))
if(typeof option=='string')data[option]()})}
var old=$.fn.tooltip
$.fn.tooltip=Plugin
$.fn.tooltip.Constructor=Tooltip
$.fn.tooltip.noConflict=function(){$.fn.tooltip=old
return this}}(jQuery);+function($){'use strict';var Popover=function(element,options){this.init('popover',element,options)}
if(!$.fn.tooltip)throw new Error('Popover requires tooltip.js')
Popover.VERSION='3.3.6'
Popover.DEFAULTS=$.extend({},$.fn.tooltip.Constructor.DEFAULTS,{placement:'right',trigger:'click',content:'',template:'<div class="popover" role="tooltip"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>'})
Popover.prototype=$.extend({},$.fn.tooltip.Constructor.prototype)
Popover.prototype.constructor=Popover
Popover.prototype.getDefaults=function(){return Popover.DEFAULTS}
Popover.prototype.setContent=function(){var $tip=this.tip()
var title=this.getTitle()
var content=this.getContent()
$tip.find('.popover-title')[this.options.html?'html':'text'](title)
$tip.find('.popover-content').children().detach().end()[this.options.html?(typeof content=='string'?'html':'append'):'text'](content)
$tip.removeClass('fade top bottom left right in')
if(!$tip.find('.popover-title').html())$tip.find('.popover-title').hide()}
Popover.prototype.hasContent=function(){return this.getTitle()||this.getContent()}
Popover.prototype.getContent=function(){var $e=this.$element
var o=this.options
return $e.attr('data-content')||(typeof o.content=='function'?o.content.call($e[0]):o.content)}
Popover.prototype.arrow=function(){return(this.$arrow=this.$arrow||this.tip().find('.arrow'))}
function Plugin(option){return this.each(function(){var $this=$(this)
var data=$this.data('bs.popover')
var options=typeof option=='object'&&option
if(!data&&/destroy|hide/.test(option))return
if(!data)$this.data('bs.popover',(data=new Popover(this,options)))
if(typeof option=='string')data[option]()})}
var old=$.fn.popover
$.fn.popover=Plugin
$.fn.popover.Constructor=Popover
$.fn.popover.noConflict=function(){$.fn.popover=old
return this}}(jQuery);+function($){'use strict';function ScrollSpy(element,options){this.$body=$(document.body)
this.$scrollElement=$(element).is(document.body)?$(window):$(element)
this.options=$.extend({},ScrollSpy.DEFAULTS,options)
this.selector=(this.options.target||'')+' .nav li > a'
this.offsets=[]
this.targets=[]
this.activeTarget=null
this.scrollHeight=0
this.$scrollElement.on('scroll.bs.scrollspy',$.proxy(this.process,this))
this.refresh()
this.process()}
ScrollSpy.VERSION='3.3.6'
ScrollSpy.DEFAULTS={offset:10}
ScrollSpy.prototype.getScrollHeight=function(){return this.$scrollElement[0].scrollHeight||Math.max(this.$body[0].scrollHeight,document.documentElement.scrollHeight)}
ScrollSpy.prototype.refresh=function(){var that=this
var offsetMethod='offset'
var offsetBase=0
this.offsets=[]
this.targets=[]
this.scrollHeight=this.getScrollHeight()
if(!$.isWindow(this.$scrollElement[0])){offsetMethod='position'
offsetBase=this.$scrollElement.scrollTop()}
this.$body.find(this.selector).map(function(){var $el=$(this)
var href=$el.data('target')||$el.attr('href')
var $href=/^#./.test(href)&&$(href)
return($href&&$href.length&&$href.is(':visible')&&[[$href[offsetMethod]().top+offsetBase,href]])||null}).sort(function(a,b){return a[0]-b[0]}).each(function(){that.offsets.push(this[0])
that.targets.push(this[1])})}
ScrollSpy.prototype.process=function(){var scrollTop=this.$scrollElement.scrollTop()+this.options.offset
var scrollHeight=this.getScrollHeight()
var maxScroll=this.options.offset+scrollHeight-this.$scrollElement.height()
var offsets=this.offsets
var targets=this.targets
var activeTarget=this.activeTarget
var i
if(this.scrollHeight!=scrollHeight){this.refresh()}
if(scrollTop>=maxScroll){return activeTarget!=(i=targets[targets.length-1])&&this.activate(i)}
if(activeTarget&&scrollTop<offsets[0]){this.activeTarget=null
return this.clear()}
for(i=offsets.length;i--;){activeTarget!=targets[i]&&scrollTop>=offsets[i]&&(offsets[i+1]===undefined||scrollTop<offsets[i+1])&&this.activate(targets[i])}}
ScrollSpy.prototype.activate=function(target){this.activeTarget=target
this.clear()
var selector=this.selector+
'[data-target="'+target+'"],'+
this.selector+'[href="'+target+'"]'
var active=$(selector).parents('li').addClass('active')
if(active.parent('.dropdown-menu').length){active=active.closest('li.dropdown').addClass('active')}
active.trigger('activate.bs.scrollspy')}
ScrollSpy.prototype.clear=function(){$(this.selector).parentsUntil(this.options.target,'.active').removeClass('active')}
function Plugin(option){return this.each(function(){var $this=$(this)
var data=$this.data('bs.scrollspy')
var options=typeof option=='object'&&option
if(!data)$this.data('bs.scrollspy',(data=new ScrollSpy(this,options)))
if(typeof option=='string')data[option]()})}
var old=$.fn.scrollspy
$.fn.scrollspy=Plugin
$.fn.scrollspy.Constructor=ScrollSpy
$.fn.scrollspy.noConflict=function(){$.fn.scrollspy=old
return this}
$(window).on('load.bs.scrollspy.data-api',function(){$('[data-spy="scroll"]').each(function(){var $spy=$(this)
Plugin.call($spy,$spy.data())})})}(jQuery);+function($){'use strict';var Tab=function(element){this.element=$(element)
}
Tab.VERSION='3.3.6'
Tab.TRANSITION_DURATION=150
Tab.prototype.show=function(){var $this=this.element
var $ul=$this.closest('ul:not(.dropdown-menu)')
var selector=$this.data('target')
if(!selector){selector=$this.attr('href')
selector=selector&&selector.replace(/.*(?=#[^\s]*$)/,'')}
if($this.parent('li').hasClass('active'))return
var $previous=$ul.find('.active:last a')
var hideEvent=$.Event('hide.bs.tab',{relatedTarget:$this[0]})
var showEvent=$.Event('show.bs.tab',{relatedTarget:$previous[0]})
$previous.trigger(hideEvent)
$this.trigger(showEvent)
if(showEvent.isDefaultPrevented()||hideEvent.isDefaultPrevented())return
var $target=$(selector)
this.activate($this.closest('li'),$ul)
this.activate($target,$target.parent(),function(){$previous.trigger({type:'hidden.bs.tab',relatedTarget:$this[0]})
$this.trigger({type:'shown.bs.tab',relatedTarget:$previous[0]})})}
Tab.prototype.activate=function(element,container,callback){var $active=container.find('> .active')
var transition=callback&&$.support.transition&&($active.length&&$active.hasClass('fade')||!!container.find('> .fade').length)
function next(){$active.removeClass('active').find('> .dropdown-menu > .active').removeClass('active').end().find('[data-toggle="tab"]').attr('aria-expanded',false)
element.addClass('active').find('[data-toggle="tab"]').attr('aria-expanded',true)
if(transition){element[0].offsetWidth
element.addClass('in')}else{element.removeClass('fade')}
if(element.parent('.dropdown-menu').length){element.closest('li.dropdown').addClass('active').end().find('[data-toggle="tab"]').attr('aria-expanded',true)}
callback&&callback()}
$active.length&&transition?$active.one('bsTransitionEnd',next).emulateTransitionEnd(Tab.TRANSITION_DURATION):next()
$active.removeClass('in')}
function Plugin(option){return this.each(function(){var $this=$(this)
var data=$this.data('bs.tab')
if(!data)$this.data('bs.tab',(data=new Tab(this)))
if(typeof option=='string')data[option]()})}
var old=$.fn.tab
$.fn.tab=Plugin
$.fn.tab.Constructor=Tab
$.fn.tab.noConflict=function(){$.fn.tab=old
return this}
var clickHandler=function(e){e.preventDefault()
Plugin.call($(this),'show')}
$(document).on('click.bs.tab.data-api','[data-toggle="tab"]',clickHandler).on('click.bs.tab.data-api','[data-toggle="pill"]',clickHandler)}(jQuery);+function($){'use strict';var Affix=function(element,options){this.options=$.extend({},Affix.DEFAULTS,options)
this.$target=$(this.options.target).on('scroll.bs.affix.data-api',$.proxy(this.checkPosition,this)).on('click.bs.affix.data-api',$.proxy(this.checkPositionWithEventLoop,this))
this.$element=$(element)
this.affixed=null
this.unpin=null
this.pinnedOffset=null
this.checkPosition()}
Affix.VERSION='3.3.6'
Affix.RESET='affix affix-top affix-bottom'
Affix.DEFAULTS={offset:0,target:window}
Affix.prototype.getState=function(scrollHeight,height,offsetTop,offsetBottom){var scrollTop=this.$target.scrollTop()
var position=this.$element.offset()
var targetHeight=this.$target.height()
if(offsetTop!=null&&this.affixed=='top')return scrollTop<offsetTop?'top':false
if(this.affixed=='bottom'){if(offsetTop!=null)return(scrollTop+this.unpin<=position.top)?false:'bottom'
return(scrollTop+targetHeight<=scrollHeight-offsetBottom)?false:'bottom'}
var initializing=this.affixed==null
var colliderTop=initializing?scrollTop:position.top
var colliderHeight=initializing?targetHeight:height
if(offsetTop!=null&&scrollTop<=offsetTop)return'top'
if(offsetBottom!=null&&(colliderTop+colliderHeight>=scrollHeight-offsetBottom))return'bottom'
return false}
Affix.prototype.getPinnedOffset=function(){if(this.pinnedOffset)return this.pinnedOffset
this.$element.removeClass(Affix.RESET).addClass('affix')
var scrollTop=this.$target.scrollTop()
var position=this.$element.offset()
return(this.pinnedOffset=position.top-scrollTop)}
Affix.prototype.checkPositionWithEventLoop=function(){setTimeout($.proxy(this.checkPosition,this),1)}
Affix.prototype.checkPosition=function(){if(!this.$element.is(':visible'))return
var height=this.$element.height()
var offset=this.options.offset
var offsetTop=offset.top
var offsetBottom=offset.bottom
var scrollHeight=Math.max($(document).height(),$(document.body).height())
if(typeof offset!='object')offsetBottom=offsetTop=offset
if(typeof offsetTop=='function')offsetTop=offset.top(this.$element)
if(typeof offsetBottom=='function')offsetBottom=offset.bottom(this.$element)
var affix=this.getState(scrollHeight,height,offsetTop,offsetBottom)
if(this.affixed!=affix){if(this.unpin!=null)this.$element.css('top','')
var affixType='affix'+(affix?'-'+affix:'')
var e=$.Event(affixType+'.bs.affix')
this.$element.trigger(e)
if(e.isDefaultPrevented())return
this.affixed=affix
this.unpin=affix=='bottom'?this.getPinnedOffset():null
this.$element.removeClass(Affix.RESET).addClass(affixType).trigger(affixType.replace('affix','affixed')+'.bs.affix')}
if(affix=='bottom'){this.$element.offset({top:scrollHeight-height-offsetBottom})}}
function Plugin(option){return this.each(function(){var $this=$(this)
var data=$this.data('bs.affix')
var options=typeof option=='object'&&option
if(!data)$this.data('bs.affix',(data=new Affix(this,options)))
if(typeof option=='string')data[option]()})}
var old=$.fn.affix
$.fn.affix=Plugin
$.fn.affix.Constructor=Affix
$.fn.affix.noConflict=function(){$.fn.affix=old
return this}
$(window).on('load',function(){$('[data-spy="affix"]').each(function(){var $spy=$(this)
var data=$spy.data()
data.offset=data.offset||{}
if(data.offsetBottom!=null)data.offset.bottom=data.offsetBottom
if(data.offsetTop!=null)data.offset.top=data.offsetTop
Plugin.call($spy,data)})})}(jQuery); | zerossB/CadastroTest-Python | static/gen/app.js | JavaScript | gpl-3.0 | 46,949 |
var class_m_s_lane_changer =
[
[ "ChangeElem", "d9/d57/struct_m_s_lane_changer_1_1_change_elem.html", "d9/d57/struct_m_s_lane_changer_1_1_change_elem" ],
[ "Changer", "d6/dad/class_m_s_lane_changer.html#a4ed01f2879bd6324a4aee0da7fc08f9c", null ],
[ "ChangerIt", "d6/dad/class_m_s_lane_changer.html#ade04b430597e0c9feeb30584602f5ba7", null ],
[ "ConstChangerIt", "d6/dad/class_m_s_lane_changer.html#aa6a44b8d8ce5ff5bc51bd75c6a7ee0c6", null ],
[ "MSLaneChanger", "d6/dad/class_m_s_lane_changer.html#aced2f93d7ae4a86ec0ed667301b7e1b4", null ],
[ "~MSLaneChanger", "d6/dad/class_m_s_lane_changer.html#a029308f9845167ba63650cc84109a6bb", null ],
[ "MSLaneChanger", "d6/dad/class_m_s_lane_changer.html#a11ac428a570526d47d12cbad6de737ae", null ],
[ "MSLaneChanger", "d6/dad/class_m_s_lane_changer.html#a09daf403a5aaeceff2497c69f596eb13", null ],
[ "change", "d6/dad/class_m_s_lane_changer.html#a32db42f629c7b0348ddcf9a3ad23606d", null ],
[ "change2left", "d6/dad/class_m_s_lane_changer.html#acba339201ac57a1b77f834ca3dcd1260", null ],
[ "change2right", "d6/dad/class_m_s_lane_changer.html#a4044f68342c096a838dd1aa7845dfb39", null ],
[ "findCandidate", "d6/dad/class_m_s_lane_changer.html#aa4506750a0609dc248edc1d8fefa1305", null ],
[ "getRealFollower", "d6/dad/class_m_s_lane_changer.html#ae41c71dd78b6136b96cf5341586478fc", null ],
[ "getRealLeader", "d6/dad/class_m_s_lane_changer.html#a916606e1d063f9fa2bc469026ede94e0", null ],
[ "getRealThisLeader", "d6/dad/class_m_s_lane_changer.html#a4f69e13c5f8198042674ce94610b7c30", null ],
[ "initChanger", "d6/dad/class_m_s_lane_changer.html#a28042dd37d62b7327759abdc327d31fe", null ],
[ "laneChange", "d6/dad/class_m_s_lane_changer.html#a23e4454fdaea74f27746298a6a007017", null ],
[ "operator=", "d6/dad/class_m_s_lane_changer.html#abfae23456ad3cfffd17625272c71df90", null ],
[ "overlapWithHopped", "d6/dad/class_m_s_lane_changer.html#a2b926432fdb7eb4139d2028ae2e50945", null ],
[ "registerUnchanged", "d6/dad/class_m_s_lane_changer.html#ac3056e8a93dc8800147abda73ea6c5c2", null ],
[ "startChange", "d6/dad/class_m_s_lane_changer.html#a1b89d83b8468a8533da29e6db303d95c", null ],
[ "updateChanger", "d6/dad/class_m_s_lane_changer.html#afc430d90d8748e9878eafd01de6578df", null ],
[ "updateLanes", "d6/dad/class_m_s_lane_changer.html#ac3e91b3ae5c593a41948ffaf68d0e340", null ],
[ "veh", "d6/dad/class_m_s_lane_changer.html#a8658b516e8005abcc6275a954519d81d", null ],
[ "vehInChanger", "d6/dad/class_m_s_lane_changer.html#a62fffe749d176c3facd85b00f64cb30d", null ],
[ "myAllowsSwap", "d6/dad/class_m_s_lane_changer.html#a8d0f3bafd834bf8778b8efb82e1f2394", null ],
[ "myCandi", "d6/dad/class_m_s_lane_changer.html#ac8b89e8e2eb21e8bc4417b7862adc2d1", null ],
[ "myChanger", "d6/dad/class_m_s_lane_changer.html#a84bd2cf57b619cf79ff6fd7d11d1b167", null ]
]; | cathyyul/sumo-0.18 | docs/doxygen/d6/dad/class_m_s_lane_changer.js | JavaScript | gpl-3.0 | 2,901 |
SL.app.Page = class Page {
constructor() {
this.content = document.getElementById('content');
this.id = null;
this.params = null;
/**
* @type Controller
*/
this.controller = null;
this.local = null;
/**
* @type Footer
*/
this.footer = null;
/**
* @type Header
*/
this.header = null;
/**
* @type Loader
*/
this.loader = null;
this.isTransitionning = false;
this.isContentReady = false;
this.loader = new SL.manager.Loader();
this.tl = null;
/**
* @type Loading
*/
this.loading = null;
this.w = 0;
this.h = 0;
this.mousex = 0;
this.mousey = 0;
this.cookie = SL.main.lang.name === "fr" ? new SL.partial.CookiePolicy() : null;
}
addListeners() {
$(window).on(EVENT.resize, this.resize);
$(document).on(EVENT.mousemove, this.mousemove);
document.addEventListener(EVENT.touchmove, this.touchmove, false);
requestAnimationFrame(SL.main.page.loop);
}
loop() {
if (SL.main.page.controller)SL.main.page.controller.loop();
if (SL.main.page.header && SL.main.page.header.loop)SL.main.page.header.loop();
requestAnimationFrame(SL.main.page.loop);
}
mousemove(e) {
SL.main.page.mousex = e.clientX;
SL.main.page.mousey = e.clientY;
}
touchmove(e) {
SL.main.page.mousex = e.touches[0].clientX;
SL.main.page.mousey = e.touches[0].clientY;
}
resize() {
SL.main.page.w = document.documentElement.clientWidth;
SL.main.page.h = document.documentElement.clientHeight;
if (SL.main.page.controller)SL.main.page.controller.resize(SL.main.page.w, SL.main.page.h);
if (SL.main.page.header && SL.main.page.header.resize)SL.main.page.header.resize(SL.main.page.w, SL.main.page.h);
}
init() {
this.addListeners();
this.footer = new SL.partial.Footer();
this.header = new SL.partial.Header();
this.loading = null;//new SL.partial.Loading();
this.loader = null;//new SL.app.Loader();
this.setCurrent();
}
setCurrent() {
this.id = SL.main.route.current.id;
this.params = SL.main.route.current.params;
this.local = SL.main.route.current.local;
this.header.onChangePage();
this.setController();
}
setController() {
if (!this.controller) {
this.controller = new SL.controller[SL.main.route.current.controller.js](SL.main.route.current.id);
this.controller.init();
this.isContentReady = true;
this.transitionIn();
} else {
this.isContentReady = false;
this.transitionOut();
}
}
progress() {
//console.log(loaded);
SL.main.page.loading.setPercent(SL.main.page.loader.loaded);
}
complete() {
SL.main.page.loading.setPercent(100);
SL.main.page.loading.hide();
SL.main.page.transitionIn();
}
checkContent() {
var currentClass = this.content.querySelector("div").className;
if (currentClass.indexOf(SL.main.route.current.id) === -1) {
this.setCurrent();
}
}
transitionIn() {
if (this.isTransitionning)return;
this.resize();
this.isTransitionning = true;
TweenLite.to("#content", 0.4, {
opacity: 1, ease: Quad.easeOut, onComplete: function () {
SL.main.page.isTransitionning = false;
SL.main.page.checkContent();
SL.main.page.resize();
}
});
this.controller.show();
}
transitionOut() {
if (this.isTransitionning)return;
SL.main.page.isTransitionning = true;
TweenLite.to("#content", 0.4, {opacity: 0, ease: Quad.easeOut, onComplete: SL.main.page.transitionOutComplete});
this.controller.hide();
SL.util.Scroll.easeTo(0, 0);
}
transitionOutComplete() {
SL.main.page.isTransitionning = false;
SL.main.page.controller.clean();
SL.util.File.getPage(SL.main.path.getCurrent(), SL.main.page.onGetPage, SL.main.page);
}
onGetPage(response) {
if (response) {
this.isContentReady = true;
this.contact.hide();
this.content.innerHTML = response;
this.controller = new SL.controller[SL.main.route.current.controller.js](SL.main.route.current.id);
this.controller.init();
this.transitionIn();
} else {
SL.util.File.getPage(SL.main.path.getBase() + "page404", SL.main.page.onGetPage, SL.main.page);
}
}
load() {
SL.main.page.loading.reset();
SL.main.page.loading.show(SL.main.page.onload);
}
onload() {
SL.main.page.loader.loadContent(SL.main.page.progress, SL.main.page.complete);
}
show() {
if (this.isTransitionning || !this.isContentReady)return;
this.transitionIn();
}
}; | gingifruden/troisdai | dev/default/js/app/Page.js | JavaScript | gpl-3.0 | 5,182 |
import { withRouter } from 'react-router-dom'
import { graphql, gql } from 'react-apollo'
import Voting from './Voting'
const queryQuestions = gql`
query feedback($id: String!, $type: String!) {
feedback(id: $id, type: $type){
feedback {
feedbackId
dashboardId
votingId
resultId
questions {
questionId
question
options {
optionId
votes
label
}
status
}
}
error
}
}
`
const queryConfig = {
options: ownProps => ({
variables: {
id: ownProps.match.params.pollId,
type: 'votingId',
},
}),
}
const mutation = gql`
mutation updateVote($voteInput: UpdateVoteInput!) {
updateVote(input: $voteInput) {
feedback {
feedbackId
dashboardId
votingId
resultId
questions {
question
options {
optionId
label
votes
}
status
questionId
}
}
error
}
}
`
const mutateOptions = {
props: ({ mutate }) => ({
submit: ({ questionId, optionId }) => mutate({
variables: {
voteInput: {
questionId,
optionId,
},
},
}),
}),
}
const withMutate = graphql(mutation, mutateOptions)
const VotingWithQuery = graphql(queryQuestions, queryConfig)(withRouter(Voting))
const VotingWithMutation = withMutate(VotingWithQuery)
export default VotingWithMutation
| cityofsurrey/polltal-app | src/Voting/Voting.data.js | JavaScript | gpl-3.0 | 1,579 |
/*
Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution and you may not use the same element twice.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
*/
/**
* @param {number[]} numbers
* @param {number} target
* @return {number[]}
*/
var twoSum = function(numbers, target) {
var results = [];
var left = 0, right = numbers.length -1;
while( left<right ){
var addUp = numbers[left] + numbers[right];
if(addUp == target){
results.push(left+1, right+1);
return results;
}
else if(addUp > target){
right--;
}
else{
left++;
}
}
return results;
};
//tags: Amazon, Microsoft
| matrixki/LeetCode | 167. Two Sum II - Input array is sorted.js | JavaScript | gpl-3.0 | 1,088 |
import GraphQLJSON from 'graphql-type-json';
import {
GraphQLObjectType,
GraphQLNonNull,
GraphQLString,
GraphQLFloat,
GraphQLBoolean,
GraphQLID
} from 'graphql';
import templateType from './template';
import userType from './user';
import TemplateModel from '../../models/template';
import UserModel from '../../models/user';
const schemaType = new GraphQLObjectType({
name: 'Schema',
fields: {
_id: {
type: new GraphQLNonNull(GraphQLID)
},
title: {
type: GraphQLString
},
slug: {
type: GraphQLString
},
type: {
type: GraphQLString
},
publicReadable: {
type: GraphQLBoolean
},
publicWritable: {
type: GraphQLBoolean
},
date: {
type: GraphQLFloat,
resolve: ({date}) => (date && date.getTime())
},
updatedDate: {
type: GraphQLFloat,
resolve: ({updatedDate}) => (updatedDate && updatedDate.getTime())
},
updatedBy: {
type: userType,
resolve: (schema) => UserModel.findById(schema.updatedBy).exec()
},
createdBy: {
type: userType,
resolve: (schema) => UserModel.findById(schema.createdBy).exec()
},
properties: {
type: GraphQLJSON
},
template: {
type: templateType,
async resolve ({template}) {
return await TemplateModel.findById(template).exec();
}
}
}
});
export default schemaType;
| relax/relax | lib/server/graphql/types/schema.js | JavaScript | gpl-3.0 | 1,415 |
'use strict';
if (process.env.NODE_ENV === 'production')
require('newrelic');
const PORT = process.env.PORT || 3333;
const os = require('os'),
https = require('https'),
express = require('express'),
fs = require('fs'),
RoutesConfig = require('./config/routes.conf'),
DBConfig = require('./config/db.conf'),
Routes = require('./routes/index'),
app = express();
/****** USE ******/
RoutesConfig.init(app);
DBConfig.init(function(err){ console.log(err); gracefulShutdown(); });
Routes.init(app, express.Router());
/****** SERVER INIT ******/
const opts = {
key: fs.readFileSync(__dirname + '/cert/server.key'),
cert: fs.readFileSync(__dirname + '/cert/server.crt')
}
var server = https.createServer(opts, app)
.listen(PORT, () => {
console.log(`up and running @: ${os.hostname()} on port: ${PORT}`);
console.log(`enviroment: ${process.env.NODE_ENV}`);
});
/****** GRACEFULLY CLOSE (NO FUNCA -> GULP) ******/
if (process.platform === "win32") {
require("readline")
.createInterface({
input: process.stdin,
output: process.stdout
})
.on("SIGINT", function () {
process.emit("SIGINT");
});
}
var gracefulShutdown = function(){
console.log("Exiting server");
//DBConfig.close();
server.close(function(){
process.exit();
});
};
process.on("SIGINT", function(){
gracefulShutdown();
});
process.on("SIGTERM", function(){
gracefulShutdown();
});
| francoa/process-monitoring | server/server.js | JavaScript | gpl-3.0 | 1,464 |
var searchData=
[
['hitbox',['Hitbox',['../class_hitbox.html',1,'Hitbox'],['../class_hitbox.html#acb9da54b168b9e457b01387ba4ddfe02',1,'Hitbox::Hitbox(float x, float y, int width, int length)'],['../class_hitbox.html#a999b0be8486978b3dd7bcd001c7c3c03',1,'Hitbox::Hitbox()']]],
['hitbox_2ecpp',['Hitbox.cpp',['../_hitbox_8cpp.html',1,'']]],
['hitbox_2eh',['Hitbox.h',['../_hitbox_8h.html',1,'']]],
['hitboxwidth',['hitboxWidth',['../class_actor.html#aabe02701e21e0271928ef83c7da7d779',1,'Actor']]]
];
| CPSC2720SpaceInvaders/GameCodeProduction | html/search/all_7.js | JavaScript | gpl-3.0 | 507 |
import {
LOADING_CONTACT_PAGE_CONTENT,
RECEIVE_CONTACT_PAGE_CONTENT,
CONTACT_FORM_SENT,
CONTACT_FORM_RESET,
CONTACT_FORM_ERROR,
SENDING_FORM
} from './actions';
const initialState = {
loaded: false,
sent: false,
error: false,
sending: false,
content: {}
};
export default (state = initialState, action) => {
switch (action.type) {
case LOADING_CONTACT_PAGE_CONTENT:
return {...state, loaded: action.loaded}
case RECEIVE_CONTACT_PAGE_CONTENT:
return {...state, loaded: action.loaded, content: action.content}
case CONTACT_FORM_SENT:
case CONTACT_FORM_RESET:
case CONTACT_FORM_ERROR:
return {...state, sent: action.sent, sending: action.sending, error: action.error}
case SENDING_FORM:
return {...state, sending: action.sending}
default:
return state
}
}
| benceg/dani | src/containers/Contact/reducers.js | JavaScript | gpl-3.0 | 839 |
'use strict';
var chai = require('chai');
var expect = require('chai').expect;
var express = require('express');
var randomstring = require('randomstring');
var sinon = require('sinon');
var MasterWAMPServer = require('wamp-socket-cluster/MasterWAMPServer');
var config = require('../../../config.json');
var failureCodes = require('../../../api/ws/rpc/failureCodes');
var wsRPC = require('../../../api/ws/rpc/wsRPC').wsRPC;
var transport = require('../../../api/ws/transport');
var System = require('../../../modules/system');
describe('ClientRPCStub', function () {
var validWSServerIp = '127.0.0.1';
var validWSServerPort = 5000;
var validClientRPCStub;
var socketClusterMock;
before(function () {
socketClusterMock = {
on: sinon.spy()
};
wsRPC.setServer(new MasterWAMPServer(socketClusterMock));
// Register RPC
var transportModuleMock = {internal: {}, shared: {}};
transport(transportModuleMock);
// Now ClientRPCStub should contain all methods names
validClientRPCStub = wsRPC.getClientRPCStub(validWSServerIp, validWSServerPort);
});
describe('should contain remote procedure', function () {
it('updatePeer', function () {
expect(validClientRPCStub).to.have.property('updatePeer');
});
it('blocksCommon', function () {
expect(validClientRPCStub).to.have.property('blocksCommon');
});
it('height', function () {
expect(validClientRPCStub).to.have.property('height');
});
it('getTransactions', function () {
expect(validClientRPCStub).to.have.property('getTransactions');
});
it('getSignatures', function () {
expect(validClientRPCStub).to.have.property('getSignatures');
});
it('status', function () {
expect(validClientRPCStub).to.have.property('list');
});
it('postBlock', function () {
expect(validClientRPCStub).to.have.property('postBlock');
});
it('postSignatures', function () {
expect(validClientRPCStub).to.have.property('postSignatures');
});
it('postTransactions', function () {
expect(validClientRPCStub).to.have.property('postTransactions');
});
});
it('should not contain randomProcedure', function () {
expect(validClientRPCStub).not.to.have.property('randomProcedure');
});
describe('RPC call', function () {
var minVersion = '0.0.0';
var validHeaders;
beforeEach(function () {
validHeaders = {
port: 5000,
nethash: config.nethash,
version: minVersion,
nonce: randomstring.generate(16),
height: 1
};
System.setHeaders(validHeaders);
});
describe('with valid headers', function () {
it('should call a RPC callback with response', function (done) {
validClientRPCStub.status(function (err, response) {
expect(response).not.to.be.empty;
done();
});
});
it('should call a RPC callback without an error as null', function (done) {
validClientRPCStub.status(function (err) {
expect(err).to.be.null;
done();
});
});
});
describe('with invalid headers', function () {
beforeEach(function () {
wsRPC.clientsConnectionsMap = {};
validClientRPCStub = wsRPC.getClientRPCStub(validWSServerIp, validWSServerPort);
});
it('without port should call RPC callback with INVALID_HEADERS error', function (done) {
delete validHeaders.port;
System.setHeaders(validHeaders);
validClientRPCStub.status(function (err) {
expect(err).to.have.property('code').equal(failureCodes.INVALID_HEADERS);
expect(err).to.have.property('description').equal('#/port: Expected type integer but found type not-a-number');
done();
});
});
it('with valid port as string should call RPC callback without an error', function (done) {
validHeaders.port = validHeaders.port.toString();
System.setHeaders(validHeaders);
validClientRPCStub.status(function (err) {
expect(err).to.be.null;
done();
});
});
it('with too short nonce should call RPC callback with INVALID_HEADERS error', function (done) {
validHeaders.nonce = 'TOO_SHORT';
System.setHeaders(validHeaders);
validClientRPCStub.status(function (err) {
expect(err).to.have.property('code').equal(failureCodes.INVALID_HEADERS);
expect(err).to.have.property('description').equal('#/nonce: String is too short (9 chars), minimum 16');
done();
});
});
it('with too long nonce should call RPC callback with INVALID_HEADERS error', function (done) {
validHeaders.nonce = 'NONCE_LONGER_THAN_16_CHARS';
System.setHeaders(validHeaders);
validClientRPCStub.status(function (err) {
expect(err).to.have.property('code').equal(failureCodes.INVALID_HEADERS);
expect(err).to.have.property('description').equal('#/nonce: String is too long (26 chars), maximum 16');
done();
});
});
it('without nonce should call RPC callback with INVALID_HEADERS error', function (done) {
delete validHeaders.nonce;
System.setHeaders(validHeaders);
validClientRPCStub.status(function (err) {
expect(err).to.have.property('code').equal(failureCodes.INVALID_HEADERS);
expect(err).to.have.property('description').equal('#/: Missing required property: nonce');
done();
});
});
it('without nethash should call RPC callback with INVALID_HEADERS error', function (done) {
delete validHeaders.nethash;
System.setHeaders(validHeaders);
validClientRPCStub.status(function (err) {
expect(err).to.have.property('code').equal(failureCodes.INVALID_HEADERS);
expect(err).to.have.property('description').equal('#/: Missing required property: nethash');
done();
});
});
it('without height should call RPC callback with INVALID_HEADERS error', function (done) {
delete validHeaders.height;
System.setHeaders(validHeaders);
validClientRPCStub.status(function (err) {
expect(err).to.have.property('code').equal(failureCodes.INVALID_HEADERS);
expect(err).to.have.property('description').equal('#/height: Expected type integer but found type not-a-number');
done();
});
});
it('without version should call RPC callback with INVALID_HEADERS error', function (done) {
delete validHeaders.version;
System.setHeaders(validHeaders);
validClientRPCStub.status(function (err) {
expect(err).to.have.property('code').equal(failureCodes.INVALID_HEADERS);
expect(err).to.have.property('description').equal('#/: Missing required property: version');
done();
});
});
});
});
describe('when reaching', function () {
describe('not reachable server', function () {
before(function () {
var invalisServerIp = '1.1.1.1';
var invalisServerPort = 1111;
validClientRPCStub = wsRPC.getClientRPCStub(invalisServerIp, invalisServerPort);
});
it('should call RPC callback with CONNECTION_TIMEOUT error', function (done) {
validClientRPCStub.status(function (err) {
expect(err).to.have.property('code').equal(failureCodes.CONNECTION_TIMEOUT);
expect(err).to.have.property('message').equal(failureCodes.errorMessages[failureCodes.CONNECTION_TIMEOUT]);
done();
});
});
});
describe('not existing server', function () {
before(function () {
var validServerIp = '127.0.0.1';
var invalisServerPort = 1111;
validClientRPCStub = wsRPC.getClientRPCStub(validServerIp, invalisServerPort);
});
it('should call RPC callback with HANDSHAKE_ERROR error', function (done) {
validClientRPCStub.status(function (err) {
expect(err).to.have.property('code').equal(failureCodes.HANDSHAKE_ERROR);
expect(err).to.have.property('message').equal(failureCodes.errorMessages[failureCodes.HANDSHAKE_ERROR]);
done();
});
});
});
});
});
| reasonthearchitect/lisk | test/api/transport/transport.client.js | JavaScript | gpl-3.0 | 7,697 |
import React, { PropTypes } from 'react';
const Main = ({ children }) => (
<main role="main" className="content">
{children}
</main>
);
Main.propTypes = {
children: PropTypes.any.isRequired,
};
export default Main;
| jamesmcewan/jmce-react | app/components/modules/Main/Main.js | JavaScript | gpl-3.0 | 228 |
import store from "../../store";
import React, { Component } from "react";
import { easyComp } from "react-easy-state";
import { AgGridReact } from "ag-grid-react";
// import { Transition } from "semantic-ui-react";
class CorrelationTable extends Component {
onGridReady = params => {
this.gridApi = params.api;
this.columnApi = params.columnApi;
// this.gridApi.sizeColumnsToFit();
};
render() {
let numQsorts = store.getState("numQsorts");
let widthVal = 152 + 75 * numQsorts;
if (widthVal > window.innerWidth - 100) {
widthVal = window.innerWidth - 100;
}
widthVal = widthVal + "px";
let gridColDefs = store.getState("gridColDefs");
let gridRowData = store.getState("gridRowData");
let showCorrelationMatrix = store.getState("showCorrelationMatrix");
const {onGridReady} = this;
if (showCorrelationMatrix) {
return (
<div>
<p style={ { fontWeight: "normal", marginTop: 15, textAlign: "left" } }>
Click the table headers to re-sort by column (low-to-high, high-to-low, original sort).
</p>
<div style={ { width: widthVal } } className="ag-fresh">
<AgGridReact columnDefs={ gridColDefs } rowData={ gridRowData } onGridReady={ onGridReady } domLayout={ "autoHeight" } enableSorting={ true }
/>
</div>
</div>
);
} else {
return null;
}
}
}
export default easyComp(CorrelationTable);
| shawnbanasick/ken-q-analysis | src/S2-corr/CorrelationTable/CorrelationTable.js | JavaScript | gpl-3.0 | 1,471 |
(function () {
var offlinePages = /^\/(index|about|schedule|location).htm$/;
var hideLinksThatRequireOnline = function () {
var allNavLinks = document.querySelectorAll("nav.page-nav a");
for (var i = 0; i < allNavLinks.length; i++) {
var href = allNavLinks[i].getAttribute("href");
if (!offlinePages.test(href)) {
allNavLinks[i].style.display = "none";
}
}
};
var showLinks = function () {
var allNavLinks = document.querySelectorAll("nav.page-nav a");
for (var i = 0; i < allNavLinks.length; i++) {
allNavLinks[i].style.display = "";
}
};
if (!navigator.onLine) {
hideLinksThatRequireOnline();
}
document.body.onoffline = hideLinksThatRequireOnline;
document.body.ononline = showLinks;
// Error fetching appcache.manifest: so we are probably offline
applicationCache.addEventListener("error", hideLinksThatRequireOnline, false);
} ());
// SIG // Begin signature block
// SIG // MIIaaAYJKoZIhvcNAQcCoIIaWTCCGlUCAQExCzAJBgUr
// SIG // DgMCGgUAMGcGCisGAQQBgjcCAQSgWTBXMDIGCisGAQQB
// SIG // gjcCAR4wJAIBAQQQEODJBs441BGiowAQS9NQkAIBAAIB
// SIG // AAIBAAIBAAIBADAhMAkGBSsOAwIaBQAEFF+G8yNjMx2D
// SIG // c+ohYQ/rvroogpMsoIIVLzCCBJkwggOBoAMCAQICEzMA
// SIG // AACdHo0nrrjz2DgAAQAAAJ0wDQYJKoZIhvcNAQEFBQAw
// SIG // eTELMAkGA1UEBhMCVVMxEzARBgNVBAgTCldhc2hpbmd0
// SIG // b24xEDAOBgNVBAcTB1JlZG1vbmQxHjAcBgNVBAoTFU1p
// SIG // Y3Jvc29mdCBDb3Jwb3JhdGlvbjEjMCEGA1UEAxMaTWlj
// SIG // cm9zb2Z0IENvZGUgU2lnbmluZyBQQ0EwHhcNMTIwOTA0
// SIG // MjE0MjA5WhcNMTMwMzA0MjE0MjA5WjCBgzELMAkGA1UE
// SIG // BhMCVVMxEzARBgNVBAgTCldhc2hpbmd0b24xEDAOBgNV
// SIG // BAcTB1JlZG1vbmQxHjAcBgNVBAoTFU1pY3Jvc29mdCBD
// SIG // b3Jwb3JhdGlvbjENMAsGA1UECxMETU9QUjEeMBwGA1UE
// SIG // AxMVTWljcm9zb2Z0IENvcnBvcmF0aW9uMIIBIjANBgkq
// SIG // hkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuqRJbBD7Ipxl
// SIG // ohaYO8thYvp0Ka2NBhnScVgZil5XDWlibjagTv0ieeAd
// SIG // xxphjvr8oxElFsjAWCwxioiuMh6I238+dFf3haQ2U8pB
// SIG // 72m4aZ5tVutu5LImTXPRZHG0H9ZhhIgAIe9oWINbSY+0
// SIG // 39M11svZMJ9T/HprmoQrtyFndNT2eLZhh5iUfCrPZ+kZ
// SIG // vtm6Y+08Tj59Auvzf6/PD7eBfvT76PeRSLuPPYzIB5Mc
// SIG // 87115PxjICmfOfNBVDgeVGRAtISqN67zAIziDfqhsg8i
// SIG // taeprtYXuTDwAiMgEPprWQ/grZ+eYIGTA0wNm2IZs7uW
// SIG // vJFapniGdptszUzsErU4RwIDAQABo4IBDTCCAQkwEwYD
// SIG // VR0lBAwwCgYIKwYBBQUHAwMwHQYDVR0OBBYEFN5R3Bvy
// SIG // HkoFPxIcwbzDs2UskQWYMB8GA1UdIwQYMBaAFMsR6MrS
// SIG // tBZYAck3LjMWFrlMmgofMFYGA1UdHwRPME0wS6BJoEeG
// SIG // RWh0dHA6Ly9jcmwubWljcm9zb2Z0LmNvbS9wa2kvY3Js
// SIG // L3Byb2R1Y3RzL01pY0NvZFNpZ1BDQV8wOC0zMS0yMDEw
// SIG // LmNybDBaBggrBgEFBQcBAQROMEwwSgYIKwYBBQUHMAKG
// SIG // Pmh0dHA6Ly93d3cubWljcm9zb2Z0LmNvbS9wa2kvY2Vy
// SIG // dHMvTWljQ29kU2lnUENBXzA4LTMxLTIwMTAuY3J0MA0G
// SIG // CSqGSIb3DQEBBQUAA4IBAQAqpPfuwMMmeoNiGnicW8X9
// SIG // 7BXEp3gT0RdTKAsMAEI/OA+J3GQZhDV/SLnP63qJoc1P
// SIG // qeC77UcQ/hfah4kQ0UwVoPAR/9qWz2TPgf0zp8N4k+R8
// SIG // 1W2HcdYcYeLMTmS3cz/5eyc09lI/R0PADoFwU8GWAaJL
// SIG // u78qA3d7bvvQRooXKDGlBeMWirjxSmkVXTP533+UPEdF
// SIG // Ha7Ki8f3iB7q/pEMn08HCe0mkm6zlBkB+F+B567aiY9/
// SIG // Wl6EX7W+fEblR6/+WCuRf4fcRh9RlczDYqG1x1/ryWlc
// SIG // cZGpjVYgLDpOk/2bBo+tivhofju6eUKTOUn10F7scI1C
// SIG // dcWCVZAbtVVhMIIEwzCCA6ugAwIBAgITMwAAACs5MkjB
// SIG // sslI8wAAAAAAKzANBgkqhkiG9w0BAQUFADB3MQswCQYD
// SIG // VQQGEwJVUzETMBEGA1UECBMKV2FzaGluZ3RvbjEQMA4G
// SIG // A1UEBxMHUmVkbW9uZDEeMBwGA1UEChMVTWljcm9zb2Z0
// SIG // IENvcnBvcmF0aW9uMSEwHwYDVQQDExhNaWNyb3NvZnQg
// SIG // VGltZS1TdGFtcCBQQ0EwHhcNMTIwOTA0MjExMjM0WhcN
// SIG // MTMxMjA0MjExMjM0WjCBszELMAkGA1UEBhMCVVMxEzAR
// SIG // BgNVBAgTCldhc2hpbmd0b24xEDAOBgNVBAcTB1JlZG1v
// SIG // bmQxHjAcBgNVBAoTFU1pY3Jvc29mdCBDb3Jwb3JhdGlv
// SIG // bjENMAsGA1UECxMETU9QUjEnMCUGA1UECxMebkNpcGhl
// SIG // ciBEU0UgRVNOOkMwRjQtMzA4Ni1ERUY4MSUwIwYDVQQD
// SIG // ExxNaWNyb3NvZnQgVGltZS1TdGFtcCBTZXJ2aWNlMIIB
// SIG // IjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAprYw
// SIG // DgNlrlBahmuFn0ihHsnA7l5JB4XgcJZ8vrlfYl8GJtOL
// SIG // ObsYIqUukq3YS4g6Gq+bg67IXjmMwjJ7FnjtNzg68WL7
// SIG // aIICaOzru0CKsf6hLDZiYHA5YGIO+8YYOG+wktZADYCm
// SIG // DXiLNmuGiiYXGP+w6026uykT5lxIjnBGNib+NDWrNOH3
// SIG // 2thc6pl9MbdNH1frfNaVDWYMHg4yFz4s1YChzuv3mJEC
// SIG // 3MFf/TiA+Dl/XWTKN1w7UVtdhV/OHhz7NL5f5ShVcFSc
// SIG // uOx8AFVGWyiYKFZM4fG6CRmWgUgqMMj3MyBs52nDs9TD
// SIG // Ts8wHjfUmFLUqSNFsq5cQUlPtGJokwIDAQABo4IBCTCC
// SIG // AQUwHQYDVR0OBBYEFKUYM1M/lWChQxbvjsav0iu6nljQ
// SIG // MB8GA1UdIwQYMBaAFCM0+NlSRnAK7UD7dvuzK7DDNbMP
// SIG // MFQGA1UdHwRNMEswSaBHoEWGQ2h0dHA6Ly9jcmwubWlj
// SIG // cm9zb2Z0LmNvbS9wa2kvY3JsL3Byb2R1Y3RzL01pY3Jv
// SIG // c29mdFRpbWVTdGFtcFBDQS5jcmwwWAYIKwYBBQUHAQEE
// SIG // TDBKMEgGCCsGAQUFBzAChjxodHRwOi8vd3d3Lm1pY3Jv
// SIG // c29mdC5jb20vcGtpL2NlcnRzL01pY3Jvc29mdFRpbWVT
// SIG // dGFtcFBDQS5jcnQwEwYDVR0lBAwwCgYIKwYBBQUHAwgw
// SIG // DQYJKoZIhvcNAQEFBQADggEBAH7MsHvlL77nVrXPc9uq
// SIG // UtEWOca0zfrX/h5ltedI85tGiAVmaiaGXv6HWNzGY444
// SIG // gPQIRnwrc7EOv0Gqy8eqlKQ38GQ54cXV+c4HzqvkJfBp
// SIG // rtRG4v5mMjzXl8UyIfruGiWgXgxCLBEzOoKD/e0ds77O
// SIG // kaSRJXG5q3Kwnq/kzwBiiXCpuEpQjO4vImSlqOZNa5Us
// SIG // HHnsp6Mx2pBgkKRu/pMCDT8sJA3GaiaBUYNKELt1Y0Sq
// SIG // aQjGA+vizwvtVjrs73KnCgz0ANMiuK8icrPnxJwLKKCA
// SIG // yuPh1zlmMOdGFxjn+oL6WQt6vKgN/hz/A4tjsk0SAiNP
// SIG // LbOFhDvioUfozxUwggW8MIIDpKADAgECAgphMyYaAAAA
// SIG // AAAxMA0GCSqGSIb3DQEBBQUAMF8xEzARBgoJkiaJk/Is
// SIG // ZAEZFgNjb20xGTAXBgoJkiaJk/IsZAEZFgltaWNyb3Nv
// SIG // ZnQxLTArBgNVBAMTJE1pY3Jvc29mdCBSb290IENlcnRp
// SIG // ZmljYXRlIEF1dGhvcml0eTAeFw0xMDA4MzEyMjE5MzJa
// SIG // Fw0yMDA4MzEyMjI5MzJaMHkxCzAJBgNVBAYTAlVTMRMw
// SIG // EQYDVQQIEwpXYXNoaW5ndG9uMRAwDgYDVQQHEwdSZWRt
// SIG // b25kMR4wHAYDVQQKExVNaWNyb3NvZnQgQ29ycG9yYXRp
// SIG // b24xIzAhBgNVBAMTGk1pY3Jvc29mdCBDb2RlIFNpZ25p
// SIG // bmcgUENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB
// SIG // CgKCAQEAsnJZXBkwZL8dmmAgIEKZdlNsPhvWb8zL8epr
// SIG // /pcWEODfOnSDGrcvoDLs/97CQk4j1XIA2zVXConKriBJ
// SIG // 9PBorE1LjaW9eUtxm0cH2v0l3511iM+qc0R/14Hb873y
// SIG // NqTJXEXcr6094CholxqnpXJzVvEXlOT9NZRyoNZ2Xx53
// SIG // RYOFOBbQc1sFumdSjaWyaS/aGQv+knQp4nYvVN0UMFn4
// SIG // 0o1i/cvJX0YxULknE+RAMM9yKRAoIsc3Tj2gMj2QzaE4
// SIG // BoVcTlaCKCoFMrdL109j59ItYvFFPeesCAD2RqGe0VuM
// SIG // JlPoeqpK8kbPNzw4nrR3XKUXno3LEY9WPMGsCV8D0wID
// SIG // AQABo4IBXjCCAVowDwYDVR0TAQH/BAUwAwEB/zAdBgNV
// SIG // HQ4EFgQUyxHoytK0FlgByTcuMxYWuUyaCh8wCwYDVR0P
// SIG // BAQDAgGGMBIGCSsGAQQBgjcVAQQFAgMBAAEwIwYJKwYB
// SIG // BAGCNxUCBBYEFP3RMU7TJoqV4ZhgO6gxb6Y8vNgtMBkG
// SIG // CSsGAQQBgjcUAgQMHgoAUwB1AGIAQwBBMB8GA1UdIwQY
// SIG // MBaAFA6sgmBAVieX5SUT/CrhClOVWeSkMFAGA1UdHwRJ
// SIG // MEcwRaBDoEGGP2h0dHA6Ly9jcmwubWljcm9zb2Z0LmNv
// SIG // bS9wa2kvY3JsL3Byb2R1Y3RzL21pY3Jvc29mdHJvb3Rj
// SIG // ZXJ0LmNybDBUBggrBgEFBQcBAQRIMEYwRAYIKwYBBQUH
// SIG // MAKGOGh0dHA6Ly93d3cubWljcm9zb2Z0LmNvbS9wa2kv
// SIG // Y2VydHMvTWljcm9zb2Z0Um9vdENlcnQuY3J0MA0GCSqG
// SIG // SIb3DQEBBQUAA4ICAQBZOT5/Jkav629AsTK1ausOL26o
// SIG // SffrX3XtTDst10OtC/7L6S0xoyPMfFCYgCFdrD0vTLqi
// SIG // qFac43C7uLT4ebVJcvc+6kF/yuEMF2nLpZwgLfoLUMRW
// SIG // zS3jStK8cOeoDaIDpVbguIpLV/KVQpzx8+/u44YfNDy4
// SIG // VprwUyOFKqSCHJPilAcd8uJO+IyhyugTpZFOyBvSj3KV
// SIG // KnFtmxr4HPBT1mfMIv9cHc2ijL0nsnljVkSiUc356aNY
// SIG // Vt2bAkVEL1/02q7UgjJu/KSVE+Traeepoiy+yCsQDmWO
// SIG // mdv1ovoSJgllOJTxeh9Ku9HhVujQeJYYXMk1Fl/dkx1J
// SIG // ji2+rTREHO4QFRoAXd01WyHOmMcJ7oUOjE9tDhNOPXwp
// SIG // SJxy0fNsysHscKNXkld9lI2gG0gDWvfPo2cKdKU27S0v
// SIG // F8jmcjcS9G+xPGeC+VKyjTMWZR4Oit0Q3mT0b85G1NMX
// SIG // 6XnEBLTT+yzfH4qerAr7EydAreT54al/RrsHYEdlYEBO
// SIG // sELsTu2zdnnYCjQJbRyAMR/iDlTd5aH75UcQrWSY/1AW
// SIG // Lny/BSF64pVBJ2nDk4+VyY3YmyGuDVyc8KKuhmiDDGot
// SIG // u3ZrAB2WrfIWe/YWgyS5iM9qqEcxL5rc43E91wB+YkfR
// SIG // zojJuBj6DnKNwaM9rwJAav9pm5biEKgQtDdQCNbDPTCC
// SIG // BgcwggPvoAMCAQICCmEWaDQAAAAAABwwDQYJKoZIhvcN
// SIG // AQEFBQAwXzETMBEGCgmSJomT8ixkARkWA2NvbTEZMBcG
// SIG // CgmSJomT8ixkARkWCW1pY3Jvc29mdDEtMCsGA1UEAxMk
// SIG // TWljcm9zb2Z0IFJvb3QgQ2VydGlmaWNhdGUgQXV0aG9y
// SIG // aXR5MB4XDTA3MDQwMzEyNTMwOVoXDTIxMDQwMzEzMDMw
// SIG // OVowdzELMAkGA1UEBhMCVVMxEzARBgNVBAgTCldhc2hp
// SIG // bmd0b24xEDAOBgNVBAcTB1JlZG1vbmQxHjAcBgNVBAoT
// SIG // FU1pY3Jvc29mdCBDb3Jwb3JhdGlvbjEhMB8GA1UEAxMY
// SIG // TWljcm9zb2Z0IFRpbWUtU3RhbXAgUENBMIIBIjANBgkq
// SIG // hkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAn6Fssd/bSJIq
// SIG // fGsuGeG94uPFmVEjUK3O3RhOJA/u0afRTK10MCAR6wfV
// SIG // VJUVSZQbQpKumFwwJtoAa+h7veyJBw/3DgSY8InMH8sz
// SIG // JIed8vRnHCz8e+eIHernTqOhwSNTyo36Rc8J0F6v0LBC
// SIG // BKL5pmyTZ9co3EZTsIbQ5ShGLieshk9VUgzkAyz7apCQ
// SIG // MG6H81kwnfp+1pez6CGXfvjSE/MIt1NtUrRFkJ9IAEpH
// SIG // ZhEnKWaol+TTBoFKovmEpxFHFAmCn4TtVXj+AZodUAiF
// SIG // ABAwRu233iNGu8QtVJ+vHnhBMXfMm987g5OhYQK1HQ2x
// SIG // /PebsgHOIktU//kFw8IgCwIDAQABo4IBqzCCAacwDwYD
// SIG // VR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUIzT42VJGcArt
// SIG // QPt2+7MrsMM1sw8wCwYDVR0PBAQDAgGGMBAGCSsGAQQB
// SIG // gjcVAQQDAgEAMIGYBgNVHSMEgZAwgY2AFA6sgmBAVieX
// SIG // 5SUT/CrhClOVWeSkoWOkYTBfMRMwEQYKCZImiZPyLGQB
// SIG // GRYDY29tMRkwFwYKCZImiZPyLGQBGRYJbWljcm9zb2Z0
// SIG // MS0wKwYDVQQDEyRNaWNyb3NvZnQgUm9vdCBDZXJ0aWZp
// SIG // Y2F0ZSBBdXRob3JpdHmCEHmtFqFKoKWtTHNY9AcTLmUw
// SIG // UAYDVR0fBEkwRzBFoEOgQYY/aHR0cDovL2NybC5taWNy
// SIG // b3NvZnQuY29tL3BraS9jcmwvcHJvZHVjdHMvbWljcm9z
// SIG // b2Z0cm9vdGNlcnQuY3JsMFQGCCsGAQUFBwEBBEgwRjBE
// SIG // BggrBgEFBQcwAoY4aHR0cDovL3d3dy5taWNyb3NvZnQu
// SIG // Y29tL3BraS9jZXJ0cy9NaWNyb3NvZnRSb290Q2VydC5j
// SIG // cnQwEwYDVR0lBAwwCgYIKwYBBQUHAwgwDQYJKoZIhvcN
// SIG // AQEFBQADggIBABCXisNcA0Q23em0rXfbznlRTQGxLnRx
// SIG // W20ME6vOvnuPuC7UEqKMbWK4VwLLTiATUJndekDiV7uv
// SIG // WJoc4R0Bhqy7ePKL0Ow7Ae7ivo8KBciNSOLwUxXdT6uS
// SIG // 5OeNatWAweaU8gYvhQPpkSokInD79vzkeJkuDfcH4nC8
// SIG // GE6djmsKcpW4oTmcZy3FUQ7qYlw/FpiLID/iBxoy+cwx
// SIG // SnYxPStyC8jqcD3/hQoT38IKYY7w17gX606Lf8U1K16j
// SIG // v+u8fQtCe9RTciHuMMq7eGVcWwEXChQO0toUmPU8uWZY
// SIG // sy0v5/mFhsxRVuidcJRsrDlM1PZ5v6oYemIp76KbKTQG
// SIG // dxpiyT0ebR+C8AvHLLvPQ7Pl+ex9teOkqHQ1uE7FcSMS
// SIG // JnYLPFKMcVpGQxS8s7OwTWfIn0L/gHkhgJ4VMGboQhJe
// SIG // GsieIiHQQ+kr6bv0SMws1NgygEwmKkgkX1rqVu+m3pmd
// SIG // yjpvvYEndAYR7nYhv5uCwSdUtrFqPYmhdmG0bqETpr+q
// SIG // R/ASb/2KMmyy/t9RyIwjyWa9nR2HEmQCPS2vWY+45CHl
// SIG // tbDKY7R4VAXUQS5QrJSwpXirs6CWdRrZkocTdSIvMqgI
// SIG // bqBbjCW/oO+EyiHW6x5PyZruSeD3AWVviQt9yGnI5m7q
// SIG // p5fOMSn/DsVbXNhNG6HY+i+ePy5VFmvJE6P9MYIEpTCC
// SIG // BKECAQEwgZAweTELMAkGA1UEBhMCVVMxEzARBgNVBAgT
// SIG // Cldhc2hpbmd0b24xEDAOBgNVBAcTB1JlZG1vbmQxHjAc
// SIG // BgNVBAoTFU1pY3Jvc29mdCBDb3Jwb3JhdGlvbjEjMCEG
// SIG // A1UEAxMaTWljcm9zb2Z0IENvZGUgU2lnbmluZyBQQ0EC
// SIG // EzMAAACdHo0nrrjz2DgAAQAAAJ0wCQYFKw4DAhoFAKCB
// SIG // vjAZBgkqhkiG9w0BCQMxDAYKKwYBBAGCNwIBBDAcBgor
// SIG // BgEEAYI3AgELMQ4wDAYKKwYBBAGCNwIBFTAjBgkqhkiG
// SIG // 9w0BCQQxFgQUAp21QC1HryHrcb/SL3aCHhKw7XYwXgYK
// SIG // KwYBBAGCNwIBDDFQME6gJoAkAE0AaQBjAHIAbwBzAG8A
// SIG // ZgB0ACAATABlAGEAcgBuAGkAbgBnoSSAImh0dHA6Ly93
// SIG // d3cubWljcm9zb2Z0LmNvbS9sZWFybmluZyAwDQYJKoZI
// SIG // hvcNAQEBBQAEggEADHl0LccgIKDLTwaCCXw7nJt9m66T
// SIG // 6UbxSGPk3O7ky3kO22ywu0skVk8ZgIPdjutpqiL3IjSu
// SIG // 17itQZ7OGdwsH5NsliiEN1TRdnbMNQ1ngoKXkM2IhRQi
// SIG // d/TMA/qlD+9gdMmjKs+G7IX3L9YphOzxVOSqW1V3EdFf
// SIG // pYUyIQh4YL1Tjp7G4PlR/elKaKkA6a9hgaYTIOGLsLyv
// SIG // 8tFgR1eYovF0O8m/A+1Stz5hyX3Nzpr7g9HW5rUIDO53
// SIG // fxeDb6kEGN+f1J6d4T+zuMsR+XpxqoOxr4vSF2SRY4Lw
// SIG // j4JdQ2CO65jfJAjy3GSe6q0l3WBcHrcSifdUVVIa2ZGn
// SIG // J7oRCKGCAigwggIkBgkqhkiG9w0BCQYxggIVMIICEQIB
// SIG // ATCBjjB3MQswCQYDVQQGEwJVUzETMBEGA1UECBMKV2Fz
// SIG // aGluZ3RvbjEQMA4GA1UEBxMHUmVkbW9uZDEeMBwGA1UE
// SIG // ChMVTWljcm9zb2Z0IENvcnBvcmF0aW9uMSEwHwYDVQQD
// SIG // ExhNaWNyb3NvZnQgVGltZS1TdGFtcCBQQ0ECEzMAAAAr
// SIG // OTJIwbLJSPMAAAAAACswCQYFKw4DAhoFAKBdMBgGCSqG
// SIG // SIb3DQEJAzELBgkqhkiG9w0BBwEwHAYJKoZIhvcNAQkF
// SIG // MQ8XDTEyMTExNTAwMDgxNVowIwYJKoZIhvcNAQkEMRYE
// SIG // FDqzauuRIOaiLH6j/hMFCv8t5POBMA0GCSqGSIb3DQEB
// SIG // BQUABIIBADCwvhC4759J7HzG0wBtY+jBOPJKhgMubz+z
// SIG // 8MbW/P25lruRBGXkEXb2IRaWKuqdhAcqCCtjsva9VkKi
// SIG // Ewmmx/fhY5x6FZsCa0mgb18gqmK44pWsN0nEh/45UawD
// SIG // Nsz5lDXdfK3ImpRQ53CbgjNNF58ocNoo7fx8n5F+MYr5
// SIG // +TK1ERAZYk3+uFW+XXEsBjGyzHW8SId69KKjN3h5glAV
// SIG // YvdG3XQ7Qpq0VCIUbFbfBYovz/4QAVp41aDYeVw+0jt8
// SIG // 1VjIzIWTmeYnll5YB6MmPrH7vOpbX4YSqBZFVvfeCkFQ
// SIG // NZqUiu9ZIiOo8cXWWuHXnaPfDhsIiofOKGk5VkDYrZ4=
// SIG // End signature block
| theglue99/Interface480 | Classcontent/Mod13/Labfiles/Starter/Exercise 3/ContosoConf/scripts/offline.js | JavaScript | gpl-3.0 | 12,348 |
var self = {};
// ---- CONFIGURATION EXPORT ----
self.LOG_LEVEL = 'debug';
self.HOST_SETTINGS = {
MARKETPLACE_CORE: {
PROTOCOL: 'HTTP',
HOST: 'localhost',
PORT: 3002
},
OAUTH_SERVER_EXTERNAL: {
PROTOCOL: 'HTTP',
HOST: 'localhost',
PORT: 3005
},
OAUTH_SERVER_INTERNAL: {
PROTOCOL: 'HTTP',
HOST: 'localhost',
PORT: 3006
},
COUPON_SERVER: {
PROTOCOL: 'HTTP',
HOST: 'localhost',
PORT: 3010
}
};
self.OAUTH_CREDENTIALS = {
CLIENT_ID: 'adb4c297-45bd-437e-ac90-9179eea41744',
CLIENT_SECRET: 'IsSecret',
CALLBACK_URL: 'http://localhost:3004/auth/iuno/callback'
};
module.exports = self; | IUNO-TDM/JuiceMarketplaceWebsite | JuiceMarketplaceWebsite-app/config/config_docker.js | JavaScript | gpl-3.0 | 727 |
class Modal {
constructor(content) {
this._id = 'modal-' + Date.now()
this._content = content ? content : ''
this._dom = {}
this.setup()
}
get id() {
return this._id
}
get content() {
return this._content
}
set content(newContent) {
if (newContent) {
this._content = newContent
this.dom.contentWrapper.innerHTML = this.content
}
}
get dom() {
return this._dom
}
setup() {
document.body.insertAdjacentHTML(
'beforeend',
`<div class="modal__outer-wrapper"><div class="modal" id=${this.id}><div class="modal__content">${this.content}</div><button class="fa fa-times modal__btn-close">Close</button></div></div>`
)
let theModal = document.getElementById(this.id)
this._dom.outerWrapper = theModal.parentNode
this._dom.contentWrapper = theModal.children[0]
this._dom.btnClose = theModal.children[1]
let triggers = [this.dom.outerWrapper, this.dom.btnClose]
this.hide()
triggers.forEach((element) => {
element.addEventListener('click', (evt) => {
if (evt.target === element) {
this.hide()
}
}, false)
})
}
show() {
this.dom.outerWrapper.setAttribute('aria-hidden', 'false')
}
hide() {
this.dom.outerWrapper.setAttribute('aria-hidden', 'true')
}
}
export default Modal
| martincleto/webpack2-es6 | src/js/modules/modal.js | JavaScript | gpl-3.0 | 1,533 |
/*!
* Plugin process
*
* Wolf Page Builder 2.8.9
*/
/* jshint -W062 */
var WPBProcess=WPBProcess||{},WPB=WPB||{},WPBParams=WPBParams||{},console=console||{};WPBProcess=function(a){"use strict";return{/**
* Init UI
*/
init:function(){a(".wpb-process-container").length&&a(".wpb-process-container").each(function(){var b=a(this).parents(".wpb-section"),c=a(this).parents(".wpb-row"),d=b.css("background-color"),e=b.css("background-image"),f=b.hasClass("wpb-section-parallax"),g=b.find(".fa-stack"),h=a(this).find("ul li").length;a(this).addClass("wpb-process-"+h+"-elements"),"none"===e&&!f&&c.hasClass("wpb-row-standard-width")?g.css({"background-color":d}):a(this).addClass("wpb-process-no-line")})}}}(jQuery),function(a){"use strict";a(document).ready(function(){WPBProcess.init()})}(jQuery); | wolfthemes/wpb-test | assets/js/min/process.min.js | JavaScript | gpl-3.0 | 804 |
/*
jSmart Javascript template engine, a port of Smarty PHP to Javascript
https://github.com/miroshnikov/jsmart
Copyright 2011, Max Miroshnikov <miroshnikov at gmail dot com>
jSmart is licensed under the GNU Lesser General Public License
http://www.gnu.org/licenses/lgpl.html
*/
(function(){function J(a,c){for(var b=1;b<arguments.length;++b)for(var d in arguments[b])a[d]=arguments[b][d];return a}function O(a){var c=0,b;for(b in a)a.hasOwnProperty(b)&&c++;return c}function G(a,c){if(Array.prototype.indexOf)return a.indexOf(c);for(var b=0;b<a.length;++b)if(a[b]===c)return b;return-1}function P(a){return a.replace(/\\t/,"\t").replace(/\\n/,"\n").replace(/\\(['"\\])/g,"$1")}function E(a){return P(a.replace(/^['"](.*)['"]$/,"$1")).replace(/^\s+|\s+$/g,"")}function B(a,c){for(var b=
0,d=0,e=jSmart.prototype.left_delimiter,f=jSmart.prototype.right_delimiter,g=jSmart.prototype.auto_literal,l=/^\s*(.+)\s*$/i,l=a?RegExp("^\\s*("+a+")\\s*$","i"):l,k=0;k<c.length;++k)if(c.substr(k,e.length)==e)g&&k+1<c.length&&c.substr(k+1,1).match(/\s/)||(b||(c=c.slice(k),d+=parseInt(k),k=0),++b);else if(c.substr(k,f.length)==f&&!(g&&0<=k-1&&c.substr(k-1,1).match(/\s/))){if(!--b){var h=c.slice(e.length,k).replace(/[\r\n]/g," ").match(l);if(h)return h.index=d,h[0]=c.slice(0,k+f.length),h}0>b&&(b=0)}return null}
function Q(a,c,b){var d="",e=null,f=null,g=0;do{e&&(g+=e[0].length);e=B(a,b);if(!e)throw Error("Unclosed {"+c+"}");d+=b.slice(0,e.index);g+=e.index;b=b.slice(e.index+e[0].length);(f=B(c,d))&&(d=d.slice(f.index+f[0].length))}while(f);e.index=g;return e}function K(a,c,b,d){for(var e=0,f=B(b,d);f;f=B(b,d)){var g=B(a,d);if(!g||g.index>f.index)return f.index+=e,f;d=d.slice(g.index+g[0].length);e+=g.index+g[0].length;f=Q(c,a,d);d=d.slice(f.index+f[0].length);e+=f.index+f[0].length}return null}function R(a,
c){if("string"==typeof a)with({__code:a})with(H)with(c)try{return eval(__code)}catch(b){throw Error(b.message+" in \n"+a);}return a}function x(a,c,b){a.match(/\[\]$/)?b[a.replace(/\[\]$/,"")].push(c):b[a]=c}function r(a,c){for(var b=B("",a);b;b=B("",a)){b.index&&w(a.slice(0,b.index),c);a=a.slice(b.index+b[0].length);var d=b[1].match(/^\s*(\w+)(.*)$/);if(d){var e=d[1],d=2<d.length?d[2].replace(/^\s+|\s+$/g,""):"";if(e in F){var f=F[e],d=("parseParams"in f?f.parseParams:z)(d);"block"==f.type?(a=a.replace(/^\n/,
""),b=Q("/"+e,e+" +[^}]*",a),f.parse(d,c,a.slice(0,b.index)),a=a.slice(b.index+b[0].length)):(f.parse(d,c),"extends"==e&&(c=[]));a=a.replace(/^\n/,"")}else if(e in A){if(b=A[e],"block"==b.type?(b=Q("/"+e,e+" +[^}]*",a),d=z(d),f=a.slice(0,b.index),c.push({type:"plugin",name:e,params:d,subTree:r(f,[])}),a=a.slice(b.index+b[0].length)):"function"==b.type&&(b=z(d),c.push({type:"plugin",name:e,params:b})),"append"==e||"assign"==e||"capture"==e||"eval"==e||"include"==e)a=a.replace(/^\n/,"")}else F.expression.parse(b[1],
c)}else e=F.expression.parse(b[1],c),"build-in"==e.type&&"operator"==e.name&&"="==e.op&&(a=a.replace(/^\n/,""))}a&&w(a,c);return c}function w(a,c){if(w.parseEmbeddedVars)for(var b=/([$][\w@]+)|`([^`]*)`/,d=a.match(b);d;d=a.match(b))c.push({type:"text",data:a.slice(0,d.index)}),c.push(I(d[1]?d[1]:d[2]).tree),a=a.slice(d.index+d[0].length);c.push({type:"text",data:a});return c}function Y(a,c,b){c.__parsed.name=w(a,[])[0];b.push({type:"plugin",name:"__func",params:c});return b}function t(a,c,b,d){d.push({type:"build-in",
name:"operator",op:a,optype:c,precedence:b,params:{}})}function S(a,c,b){var d=c.token;b=[{type:"text",data:b.replace(/^(\w+)@(key|index|iteration|first|last|show|total)/gi,"$1__$2")}];for(var e=/^(?:\.|\s*->\s*|\[\s*)/,f=a.match(e);f;f=a.match(e)){c.token+=f[0];a=a.slice(f[0].length);var g={value:"",tree:[]};if(f[0].match(/\[/)){if(g=I(a))c.token+=g.value,b.push(g.tree),a=a.slice(g.value.length);if(f=a.match(/\s*\]/))c.token+=f[0],a=a.slice(f[0].length)}else{f=u.stop;u.stop=!0;if(T(a,g)){c.token+=
g.value;var l=g.tree[0];"plugin"==l.type&&"__func"==l.name&&(l.hasOwner=!0);b.push(l);a=a.slice(g.value.length)}else g=!1;u.stop=f}g||b.push({type:"text",data:""})}c.tree.push({type:"var",parts:b});c.value+=c.token.substr(d.length);U(c.token);return a}function U(a){}function u(a,c){if(!u.stop){var b=a.match(/^\|(\w+)/);if(b){c.value+=b[0];var d="default"==b[1]?"__defaultValue":"__"+b[1];a=a.slice(b[0].length).replace(/^\s+/,"");u.stop=!0;for(var b=[],e=a.match(/^\s*:\s*/);e;e=a.match(/^\s*:\s*/))c.value+=
a.slice(0,e[0].length),a=a.slice(e[0].length),e={value:"",tree:[]},T(a,e)?(c.value+=e.value,b.push(e.tree[0]),a=a.slice(e.value.length)):w("",b);u.stop=!1;b.unshift(c.tree.pop());c.tree.push(Y(d,{__parsed:b},[])[0]);u(a,c)}}}function T(a,c){if(!a)return!1;if(a.substr(0,jSmart.prototype.left_delimiter.length)==jSmart.prototype.left_delimiter){var b=B("",a);if(b)return c.token=b[0],c.value+=b[0],r(b[0],c.tree),u(a.slice(c.value.length),c),!0}for(b=0;b<L.length;++b)if(a.match(L[b].re))return c.token=
RegExp.lastMatch,c.value+=RegExp.lastMatch,L[b].parse(c,a.slice(c.token.length)),!0;return!1}function Z(a,c,b){var d=c[a];if("operator"==d.name&&d.precedence==b&&!d.params.__parsed){if("binary"==d.optype)return d.params.__parsed=[c[a-1],c[a+1]],c.splice(a-1,3,d),!0;if("post-unary"==d.optype)return d.params.__parsed=[c[a-1]],c.splice(a-1,2,d),!0;d.params.__parsed=[c[a+1]];c.splice(a,2,d)}return!1}function $(a){for(var c=0,c=0;c<a.length;++c)a[c]instanceof Array&&(a[c]=$(a[c]));for(var b=1;14>b;++b)if(2==
b||10==b)for(c=a.length;0<c;--c)c-=Z(c-1,a,b);else for(c=0;c<a.length;++c)c-=Z(c,a,b);return a[0]}function I(a){for(var c={value:"",tree:[]};T(a.slice(c.value.length),c););if(!c.tree.length)return!1;c.tree=$(c.tree);return c}function z(a,c,b){var d=a.replace(/\n/g," ").replace(/^\s+|\s+$/g,""),e=[];e.__parsed=[];a="";if(!d)return e;c||(c=/^\s+/,b=/^(\w+)\s*=\s*/);for(;d;){var f=null;if(b){var g=d.match(b);g&&(f=E(g[1]),a+=d.slice(0,g[0].length),d=d.slice(g[0].length))}g=I(d);if(!g)break;f?(e[f]=g.value,
e.__parsed[f]=g.tree):(e.push(g.value),e.__parsed.push(g.tree));a+=d.slice(0,g.value.length);d=d.slice(g.value.length);if(f=d.match(c))a+=d.slice(0,f[0].length),d=d.slice(f[0].length);else break}e.toString=function(){return a};return e}function y(a,c){var b=[],d;for(d in a.__parsed)if(a.__parsed.hasOwnProperty(d)){var e=p([a.__parsed[d]],c);"string"==typeof e&&e.match(/^[1-9]\d{0,14}$/)&&!isNaN(e)&&(e=parseInt(e,10));b[d]=e}b.__get=function(a,c,d){if(a in b&&"undefined"!=typeof b[a])return b[a];if("undefined"!=
typeof d&&"undefined"!=typeof b[d])return b[d];if(null===c)throw Error("The required attribute '"+a+"' is missing");return c};return b}function C(a,c,b){for(var d=c,e="",f=0;f<a.parts.length;++f){var g=a.parts[f];if("plugin"==g.type&&"__func"==g.name&&g.hasOwner)c.__owner=d,d=p([a.parts[f]],c),delete c.__owner;else{e=p([g],c);e in c.smarty.section&&"text"==g.type&&"smarty"!=p([a.parts[0]],c)&&(e=c.smarty.section[e].index);!e&&"undefined"!=typeof b&&d instanceof Array&&(e=d.length);"undefined"!=typeof b&&
f==a.parts.length-1&&(d[e]=b);if(!("object"==typeof d&&null!==d&&e in d)){if("undefined"==typeof b)return b;d[e]={}}d=d[e]}}return d}function p(a,c){for(var b="",d=0;d<a.length;++d){var e="",f=a[d];if("text"==f.type)e=f.data;else if("var"==f.type)e=C(f,c);else if("build-in"==f.type)e=F[f.name].process(f,c);else if("plugin"==f.type){var g=A[f.name];if("block"==g.type){var l={value:!0};for(g.process(y(f.params,c),"",c,l);l.value;)l.value=!1,e+=g.process(y(f.params,c),p(f.subTree,c),c,l)}else"function"==
g.type&&(e=g.process(y(f.params,c),c))}"boolean"==typeof e&&(e=e?"1":"");if(1==a.length)return e;b+=null!==e?e:"";if(c.smarty["continue"]||c.smarty["break"])break}return b}function aa(a,c,b){if(!b&&a in V)c=V[a];else{b=jSmart.prototype.getTemplate(a);if("string"!=typeof b)throw Error("No template for "+a);r(M(jSmart.prototype.filters_global.pre,ba(b.replace(/\r\n/g,"\n"))),c);V[a]=c}return c}function ba(a){for(var c="",b=a.match(/{\*/);b;b=a.match(/{\*/)){c+=a.slice(0,b.index);a=a.slice(b.index+b[0].length);
b=a.match(/\*}/);if(!b)throw Error("Unclosed {*");a=a.slice(b.index+b[0].length)}return c+a}function M(a,c){for(var b=0;b<a.length;++b)c=a[b](c);return c}var F={expression:{parse:function(a,c){var b=I(a);c.push({type:"build-in",name:"expression",expression:b.tree,params:z(a.slice(b.value.length).replace(/^\s+|\s+$/g,""))});return b.tree},process:function(a,c){var b=y(a.params,c),d=p([a.expression],c);if(0>G(b,"nofilter")){for(b=0;b<default_modifiers.length;++b){var e=default_modifiers[b];e.params.__parsed[0]=
{type:"text",data:d};d=p([e],c)}escape_html&&(d=H.__escape(d));d=M(varFilters,d);N.length&&(__t=function(){return d},d=p(N,c))}return d}},operator:{process:function(a,c){var b=y(a.params,c),d=b[0];if("binary"==a.optype){b=b[1];if("="==a.op)return C(a.params.__parsed[0],c,b),"";if(a.op.match(/(\+=|-=|\*=|\/=|%=)/)){d=C(a.params.__parsed[0],c);switch(a.op){case "+=":d+=b;break;case "-=":d-=b;break;case "*=":d*=b;break;case "/=":d/=b;break;case "%=":d%=b}return C(a.params.__parsed[0],c,d)}if(a.op.match(/div/))return"div"!=
a.op^0==d%b;if(a.op.match(/even/))return"even"!=a.op^0==d/b%2;if(a.op.match(/xor/))return(d||b)&&!(d&&b);switch(a.op){case "==":return d==b;case "!=":return d!=b;case "+":return d+b;case "-":return d-b;case "*":return d*b;case "/":return d/b;case "%":return d%b;case "&&":return d&&b;case "||":return d||b;case "<":return d<b;case "<=":return d<=b;case ">":return d>b;case ">=":return d>=b;case "===":return d===b;case "!==":return d!==b}}else{if("!"==a.op)return d instanceof Array?!d.length:!d;(b="var"==
a.params.__parsed[0].type)&&(d=C(a.params.__parsed[0],c));var e=d;if("pre-unary"==a.optype){switch(a.op){case "-":e=-d;break;case "++":e=++d;break;case "--":e=--d}b&&C(a.params.__parsed[0],c,d)}else{switch(a.op){case "++":d++;break;case "--":d--}C(a.params.__parsed[0],c,d)}return e}}},section:{type:"block",parse:function(a,c,b){var d=[],e=[];c.push({type:"build-in",name:"section",params:a,subTree:d,subTreeElse:e});(a=K("section [^}]+","/section","sectionelse",b))?(r(b.slice(0,a.index),d),r(b.slice(a.index+
a[0].length).replace(/^[\r\n]/,""),e)):r(b,d)},process:function(a,c){var b=y(a.params,c),d={};c.smarty.section[b.__get("name",null,0)]=d;var e=b.__get("show",!0);d.show=e;if(!e)return p(a.subTreeElse,c);var e=parseInt(b.__get("start",0)),f=b.loop instanceof Object?O(b.loop):isNaN(b.loop)?0:parseInt(b.loop),g=parseInt(b.__get("step",1)),b=parseInt(b.__get("max"));isNaN(b)&&(b=Number.MAX_VALUE);0>e?(e+=f,0>e&&(e=0)):e>=f&&(e=f?f-1:0);for(var l=0,k=e;0<=k&&k<f&&l<b;k+=g,++l);d.total=l;d.loop=l;for(var l=
0,h="",k=e;0<=k&&k<f&&l<b&&!c.smarty["break"];k+=g,++l)d.first=k==e,d.last=0>k+g||k+g>=f,d.index=k,d.index_prev=k-g,d.index_next=k+g,d.iteration=d.rownum=l+1,h+=p(a.subTree,c),c.smarty["continue"]=!1;c.smarty["break"]=!1;return l?h:p(a.subTreeElse,c)}},setfilter:{type:"block",parseParams:function(a){return[I("__t()|"+a).tree]},parse:function(a,c,b){c.push({type:"build-in",name:"setfilter",params:a,subTree:r(b,[])})},process:function(a,c){N=a.params;var b=p(a.subTree,c);N=[];return b}},"for":{type:"block",
parseParams:function(a){var c=a.match(/^\s*\$(\w+)\s*=\s*([^\s]+)\s*to\s*([^\s]+)\s*(?:step\s*([^\s]+))?\s*(.*)$/);if(!c)throw Error("Invalid {for} parameters: "+a);return z("varName='"+c[1]+"' from="+c[2]+" to="+c[3]+" step="+(c[4]?c[4]:"1")+" "+c[5])},parse:function(a,c,b){var d=[],e=[];c.push({type:"build-in",name:"for",params:a,subTree:d,subTreeElse:e});(a=K("for\\s[^}]+","/for","forelse",b))?(r(b.slice(0,a.index),d),r(b.slice(a.index+a[0].length),e)):r(b,d)},process:function(a,c){var b=y(a.params,
c),d=parseInt(b.__get("from")),e=parseInt(b.__get("to")),f=parseInt(b.__get("step"));isNaN(f)&&(f=1);var g=parseInt(b.__get("max"));isNaN(g)&&(g=Number.MAX_VALUE);for(var l=0,k="",d=Math.min(Math.ceil(((0<f?e-d:d-e)+1)/Math.abs(f)),g),e=parseInt(b.from);l<d&&!c.smarty["break"];e+=f,++l)c[b.varName]=e,k+=p(a.subTree,c),c.smarty["continue"]=!1;c.smarty["break"]=!1;l||(k=p(a.subTreeElse,c));return k}},"if":{type:"block",parse:function(a,c,b){var d=[],e=[];c.push({type:"build-in",name:"if",params:a,subTreeIf:d,
subTreeElse:e});(a=K("if\\s+[^}]+","/if","else[^}]*",b))?(r(b.slice(0,a.index),d),b=b.slice(a.index+a[0].length),(d=a[1].match(/^else\s*if(.*)/))?F["if"].parse(z(d[1]),e,b.replace(/^\n/,"")):r(b.replace(/^\n/,""),e)):r(b,d)},process:function(a,c){var b=y(a.params,c)[0];return!b||b instanceof Array&&!b.length||b instanceof Object&&!O(b)?p(a.subTreeElse,c):p(a.subTreeIf,c)}},foreach:{type:"block",parseParams:function(a){var c=a.match(/^\s*([$].+)\s*as\s*[$](\w+)\s*(=>\s*[$](\w+))?\s*$/i);c&&(a="from="+
c[1]+" item="+(c[4]||c[2]),c[4]&&(a+=" key="+c[2]));return z(a)},parse:function(a,c,b){var d=[],e=[];c.push({type:"build-in",name:"foreach",params:a,subTree:d,subTreeElse:e});(a=K("foreach\\s[^}]+","/foreach","foreachelse",b))?(r(b.slice(0,a.index),d),r(b.slice(a.index+a[0].length).replace(/^[\r\n]/,""),e)):r(b,d)},process:function(a,c){var b=y(a.params,c),d=b.from;"undefined"==typeof d&&(d=[]);"object"!=typeof d&&(d=[d]);var e=O(d);c[b.item+"__total"]=e;"name"in b&&(c.smarty.foreach[b.name]={},c.smarty.foreach[b.name].total=
e);var f="",g=0,l;for(l in d)if(d.hasOwnProperty(l)){if(c.smarty["break"])break;c[b.item+"__key"]=isNaN(l)?l:parseInt(l);"key"in b&&(c[b.key]=c[b.item+"__key"]);c[b.item]=d[l];c[b.item+"__index"]=parseInt(g);c[b.item+"__iteration"]=parseInt(g+1);c[b.item+"__first"]=0===g;c[b.item+"__last"]=g==e-1;"name"in b&&(c.smarty.foreach[b.name].index=parseInt(g),c.smarty.foreach[b.name].iteration=parseInt(g+1),c.smarty.foreach[b.name].first=0===g?1:"",c.smarty.foreach[b.name].last=g==e-1?1:"");++g;f+=p(a.subTree,
c);c.smarty["continue"]=!1}c.smarty["break"]=!1;c[b.item+"__show"]=0<g;b.name&&(c.smarty.foreach[b.name].show=0<g?1:"");return 0<g?f:p(a.subTreeElse,c)}},"function":{type:"block",parse:function(a,c,b){c=[];A[E(a.name?a.name:a[0])]={type:"function",subTree:c,defautParams:a,process:function(a,b){var c=y(this.defautParams,b);delete c.name;return p(this.subTree,J({},b,c,a))}};r(b,c)}},php:{type:"block",parse:function(a,c,b){}},"extends":{type:"function",parse:function(a,c){c.splice(0,c.length);aa(E(a.file?
a.file:a[0]),c)}},block:{type:"block",parse:function(a,c,b){c.push({type:"build-in",name:"block",params:a});a.append=0<=G(a,"append");a.prepend=0<=G(a,"prepend");a.hide=0<=G(a,"hide");a.hasChild=a.hasParent=!1;U=function(b){b.match(/^\s*[$]smarty.block.child\s*$/)&&(a.hasChild=!0);b.match(/^\s*[$]smarty.block.parent\s*$/)&&(a.hasParent=!0)};c=r(b,[]);U=function(a){};b=E(a.name?a.name:a[0]);b in D||(D[b]=[]);D[b].push({tree:c,params:a})},process:function(a,c){c.smarty.block.parent=c.smarty.block.child=
"";var b=E(a.params.name?a.params.name:a.params[0]);this.processBlocks(D[b],D[b].length-1,c);return c.smarty.block.child},processBlocks:function(a,c,b){if(!c&&a[c].params.hide)b.smarty.block.child="";else for(var d=!0,e=!1;0<=c;--c){if(a[c].params.hasParent){var f=b.smarty.block.child;b.smarty.block.child="";this.processBlocks(a,c-1,b);b.smarty.block.parent=b.smarty.block.child;b.smarty.block.child=f}var f=b.smarty.block.child,g=p(a[c].tree,b);b.smarty.block.child=f;a[c].params.hasChild?b.smarty.block.child=
g:d?b.smarty.block.child=g+b.smarty.block.child:e&&(b.smarty.block.child+=g);d=a[c].params.append;e=a[c].params.prepend}}},strip:{type:"block",parse:function(a,c,b){r(b.replace(/[ \t]*[\r\n]+[ \t]*/g,""),c)}},literal:{type:"block",parse:function(a,c,b){w(b,c)}},ldelim:{type:"function",parse:function(a,c){w(jSmart.prototype.left_delimiter,c)}},rdelim:{type:"function",parse:function(a,c){w(jSmart.prototype.right_delimiter,c)}},"while":{type:"block",parse:function(a,c,b){c.push({type:"build-in",name:"while",
params:a,subTree:r(b,[])})},process:function(a,c){for(var b="";y(a.params,c)[0]&&!c.smarty["break"];)b+=p(a.subTree,c),c.smarty["continue"]=!1;c.smarty["break"]=!1;return b}}},A={},H={},V={},D=null,W=null,N=[],L=[{re:/^\$([\w@]+)/,parse:function(a,c){u(S(c,a,RegExp.$1),a)}},{re:/^(true|false)/i,parse:function(a,c){w(a.token.match(/true/i)?"1":"",a.tree)}},{re:/^'([^'\\]*(?:\\.[^'\\]*)*)'/,parse:function(a,c){w(P(RegExp.$1),a.tree);u(c,a)}},{re:/^"([^"\\]*(?:\\.[^"\\]*)*)"/,parse:function(a,c){var b=
P(RegExp.$1),d=b.match(L[0].re);if(d){var e={token:d[0],tree:[]};S(b,e,d[1]);if(e.token.length==b.length){a.tree.push(e.tree[0]);return}}w.parseEmbeddedVars=!0;a.tree.push({type:"plugin",name:"__quoted",params:{__parsed:r(b,[])}});w.parseEmbeddedVars=!1;u(c,a)}},{re:/^(\w+)\s*[(]([)]?)/,parse:function(a,c){var b=RegExp.$1,d=z(RegExp.$2?"":c,/^\s*,\s*/);Y(b,d,a.tree);a.value+=d.toString();u(c.slice(d.toString().length),a)}},{re:/^\s*\(\s*/,parse:function(a,c){var b=[];a.tree.push(b);b.parent=a.tree;
a.tree=b}},{re:/^\s*\)\s*/,parse:function(a,c){a.tree.parent&&(a.tree=a.tree.parent)}},{re:/^\s*(\+\+|--)\s*/,parse:function(a,c){a.tree.length&&"var"==a.tree[a.tree.length-1].type?t(RegExp.$1,"post-unary",1,a.tree):t(RegExp.$1,"pre-unary",1,a.tree)}},{re:/^\s*(===|!==|==|!=)\s*/,parse:function(a,c){t(RegExp.$1,"binary",6,a.tree)}},{re:/^\s+(eq|ne|neq)\s+/i,parse:function(a,c){var b=RegExp.$1.replace(/ne(q)?/,"!=").replace(/eq/,"==");t(b,"binary",6,a.tree)}},{re:/^\s*!\s*/,parse:function(a,c){t("!",
"pre-unary",2,a.tree)}},{re:/^\s+not\s+/i,parse:function(a,c){t("!","pre-unary",2,a.tree)}},{re:/^\s*(=|\+=|-=|\*=|\/=|%=)\s*/,parse:function(a,c){t(RegExp.$1,"binary",10,a.tree)}},{re:/^\s*(\*|\/|%)\s*/,parse:function(a,c){t(RegExp.$1,"binary",3,a.tree)}},{re:/^\s+mod\s+/i,parse:function(a,c){t("%","binary",3,a.tree)}},{re:/^\s*(\+|-)\s*/,parse:function(a,c){a.tree.length&&"operator"!=a.tree[a.tree.length-1].name?t(RegExp.$1,"binary",4,a.tree):t(RegExp.$1,"pre-unary",4,a.tree)}},{re:/^\s*(<=|>=|<>|<|>)\s*/,
parse:function(a,c){t(RegExp.$1.replace(/<>/,"!="),"binary",5,a.tree)}},{re:/^\s+(lt|lte|le|gt|gte|ge)\s+/i,parse:function(a,c){var b=RegExp.$1.replace(/lt/,"<").replace(/l(t)?e/,"<=").replace(/gt/,">").replace(/g(t)?e/,">=");t(b,"binary",5,a.tree)}},{re:/^\s+(is\s+(not\s+)?div\s+by)\s+/i,parse:function(a,c){t(RegExp.$2?"div_not":"div","binary",7,a.tree)}},{re:/^\s+is\s+(not\s+)?(even|odd)(\s+by\s+)?\s*/i,parse:function(a,c){t(RegExp.$1?"odd"==RegExp.$2?"even":"even_not":"odd"==RegExp.$2?"even_not":
"even","binary",7,a.tree);RegExp.$3||w("1",a.tree)}},{re:/^\s*(&&)\s*/,parse:function(a,c){t(RegExp.$1,"binary",8,a.tree)}},{re:/^\s*(\|\|)\s*/,parse:function(a,c){t(RegExp.$1,"binary",9,a.tree)}},{re:/^\s+and\s+/i,parse:function(a,c){t("&&","binary",11,a.tree)}},{re:/^\s+xor\s+/i,parse:function(a,c){t("xor","binary",12,a.tree)}},{re:/^\s+or\s+/i,parse:function(a,c){t("||","binary",13,a.tree)}},{re:/^#(\w+)#/,parse:function(a,c){var b={token:"$smarty",tree:[]};S(".config."+RegExp.$1,b,"smarty");a.tree.push(b.tree[0]);
u(c,a)}},{re:/^\s*\[\s*/,parse:function(a,c){var b=z(c,/^\s*,\s*/,/^('[^'\\]*(?:\\.[^'\\]*)*'|"[^"\\]*(?:\\.[^"\\]*)*"|\w+)\s*=>\s*/);a.tree.push({type:"plugin",name:"__array",params:b});a.value+=b.toString();if(b=c.slice(b.toString().length).match(/\s*\]/))a.value+=b[0]}},{re:/^[\d.]+/,parse:function(a,c){w(a.token,a.tree);u(c,a)}},{re:/^\w+/,parse:function(a,c){w(a.token,a.tree);u(c,a)}}];jSmart=function(a){this.tree=[];this.tree.blocks={};this.scripts={};this.default_modifiers=[];this.filters=
{variable:[],post:[]};this.smarty={smarty:{block:{},"break":!1,capture:{},"continue":!1,counter:{},cycle:{},foreach:{},section:{},now:Math.floor((new Date).getTime()/1E3),"const":{},config:{},current_dir:"/",template:"",ldelim:jSmart.prototype.left_delimiter,rdelim:jSmart.prototype.right_delimiter,version:"2.9"}};D=this.tree.blocks;r(M(jSmart.prototype.filters_global.pre,ba((new String(a?a:"")).replace(/\r\n/g,"\n"))),this.tree)};jSmart.prototype.fetch=function(a){D=this.tree.blocks;W=this.scripts;
escape_html=this.escape_html;default_modifiers=jSmart.prototype.default_modifiers_global.concat(this.default_modifiers);this.data=J("object"==typeof a?a:{},this.smarty);varFilters=jSmart.prototype.filters_global.variable.concat(this.filters.variable);a=p(this.tree,this.data);jSmart.prototype.debugging&&A.debug.process([],this.data);return M(jSmart.prototype.filters_global.post.concat(this.filters.post),a)};jSmart.prototype.escape_html=!1;jSmart.prototype.registerPlugin=function(a,c,b){"modifier"==
a?H["__"+c]=b:A[c]={type:a,process:b}};jSmart.prototype.registerFilter=function(a,c){(this.tree?this.filters:jSmart.prototype.filters_global)["output"==a?"post":a].push(c)};jSmart.prototype.filters_global={pre:[],variable:[],post:[]};jSmart.prototype.configLoad=function(a,c,b){b=b?b:this.data;a=a.replace(/\r\n/g,"\n").replace(/^\s+|\s+$/g,"");for(var d=/^\s*(?:\[([^\]]+)\]|(?:(\w+)[ \t]*=[ \t]*("""|'[^'\\\n]*(?:\\.[^'\\\n]*)*'|"[^"\\\n]*(?:\\.[^"\\\n]*)*"|[^\n]*)))/m,e="",f=a.match(d);f;f=a.match(d)){a=
a.slice(f.index+f[0].length);if(f[1])e=f[1];else if((!e||e==c)&&"."!=e.substr(0,1))if('"""'==f[3]){var g=a.match(/"""/);g&&(b.smarty.config[f[2]]=a.slice(0,g.index),a=a.slice(g.index+g[0].length))}else b.smarty.config[f[2]]=E(f[3]);if(f=a.match(/\n+/))a=a.slice(f.index+f[0].length);else break}};jSmart.prototype.clearConfig=function(a){a?delete this.data.smarty.config[a]:this.data.smarty.config={}};jSmart.prototype.addDefaultModifier=function(a){a instanceof Array||(a=[a]);for(var c=0;c<a.length;++c){var b=
{value:"",tree:[0]};u("|"+a[c],b);(this.tree?this.default_modifiers:this.default_modifiers_global).push(b.tree[0])}};jSmart.prototype.default_modifiers_global=[];jSmart.prototype.getTemplate=function(a){throw Error("No template for "+a);};jSmart.prototype.getFile=function(a){throw Error("No file for "+a);};jSmart.prototype.getJavascript=function(a){throw Error("No Javascript for "+a);};jSmart.prototype.getConfig=function(a){throw Error("No config for "+a);};jSmart.prototype.auto_literal=!0;jSmart.prototype.left_delimiter=
"{";jSmart.prototype.right_delimiter="}";jSmart.prototype.debugging=!1;jSmart.prototype.registerPlugin("function","__array",function(a,c){var b=[],d;for(d in a)a.hasOwnProperty(d)&&a[d]&&"function"!=typeof a[d]&&(b[d]=a[d]);return b});jSmart.prototype.registerPlugin("function","__func",function(a,c){for(var b=[],d={},e=0;e<a.length;++e)b.push(a.name+"__p"+e),d[a.name+"__p"+e]=a[e];return R(("__owner"in c&&a.name in c.__owner?"__owner."+a.name:a.name)+"("+b.join(",")+")",J({},c,d))});jSmart.prototype.registerPlugin("function",
"__quoted",function(a,c){return a.join("")});jSmart.prototype.registerPlugin("function","break",function(a,c){c.smarty["break"]=!0;return""});jSmart.prototype.registerPlugin("function","continue",function(a,c){c.smarty["continue"]=!0;return""});jSmart.prototype.registerPlugin("function","call",function(a,c){var b=a.__get("name",null,0);delete a.name;var d=a.__get("assign",!1);delete a.assign;b=A[b].process(a,c);return d?(x(d,b,c),""):b});jSmart.prototype.registerPlugin("function","append",function(a,
c){var b=a.__get("var",null,0);b in c&&c[b]instanceof Array||(c[b]=[]);var d=a.__get("index",!1),e=a.__get("value",null,1);!1===d?c[b].push(e):c[b][d]=e;return""});jSmart.prototype.registerPlugin("function","assign",function(a,c){x(a.__get("var",null,0),a.__get("value",null,1),c);return""});jSmart.prototype.registerPlugin("block","capture",function(a,c,b,d){c&&(c=c.replace(/^\n/,""),b.smarty.capture[a.__get("name","default",0)]=c,"assign"in a&&x(a.assign,c,b),(a=a.__get("append",!1))&&(a in b?b[a]instanceof
Array&&b[a].push(c):b[a]=[c]));return""});jSmart.prototype.registerPlugin("function","eval",function(a,c){var b=[];r(a.__get("var","",0),b);b=p(b,c);return"assign"in a?(x(a.assign,b,c),""):b});jSmart.prototype.registerPlugin("function","include",function(a,c){var b=a.__get("file",null,0),d=J({},c,a);d.smarty.template=b;b=p(aa(b,[],0<=G(a,"nocache")),d);return"assign"in a?(x(a.assign,b,c),""):b});jSmart.prototype.registerPlugin("block","nocache",function(a,c,b,d){return c});jSmart.prototype.registerPlugin("block",
"javascript",function(a,c,b,d){b.$this=b;R(c,b);delete b.$this;return""});jSmart.prototype.registerPlugin("function","config_load",function(a,c){jSmart.prototype.configLoad(jSmart.prototype.getConfig(a.__get("file",null,0)),a.__get("section","",1),c);return""});jSmart.prototype.registerPlugin("modifier","defaultValue",function(a,c){return a&&"null"!=a&&"undefined"!=a?a:c?c:""});var m={window:"object"==typeof window?window:{document:{}}};String.prototype.fetch=function(a){return(new jSmart(this)).fetch(a)};
jSmart.prototype.registerPlugin("function","counter",function(a,c){var b=a.__get("name","default");if(b in c.smarty.counter){var d=c.smarty.counter[b];"start"in a?d.value=parseInt(a.start):(d.value=parseInt(d.value),d.skip=parseInt(d.skip),d.value="down"==d.direction?d.value-d.skip:d.value+d.skip);d.skip=a.__get("skip",d.skip);d.direction=a.__get("direction",d.direction);d.assign=a.__get("assign",d.assign)}else c.smarty.counter[b]={value:parseInt(a.__get("start",1)),skip:parseInt(a.__get("skip",1)),
direction:a.__get("direction","up"),assign:a.__get("assign",!1)};return c.smarty.counter[b].assign?(c[c.smarty.counter[b].assign]=c.smarty.counter[b].value,""):a.__get("print",!0)?c.smarty.counter[b].value:""});jSmart.prototype.registerPlugin("function","cycle",function(a,c){var b=a.__get("name","default"),d=a.__get("reset",!1);b in c.smarty.cycle||(c.smarty.cycle[b]={arr:[""],delimiter:a.__get("delimiter",","),index:0},d=!0);a.__get("delimiter",!1)&&(c.smarty.cycle[b].delimiter=a.delimiter);var e=
a.__get("values",!1);if(e){var f=[];if(e instanceof Object)for(nm in e)f.push(e[nm]);else f=e.split(c.smarty.cycle[b].delimiter);if(f.length!=c.smarty.cycle[b].arr.length||f[0]!=c.smarty.cycle[b].arr[0])c.smarty.cycle[b].arr=f,c.smarty.cycle[b].index=0,d=!0}a.__get("advance","true")&&(c.smarty.cycle[b].index+=1);if(c.smarty.cycle[b].index>=c.smarty.cycle[b].arr.length||d)c.smarty.cycle[b].index=0;return a.__get("assign",!1)?(x(a.assign,c.smarty.cycle[b].arr[c.smarty.cycle[b].index],c),""):a.__get("print",
!0)?c.smarty.cycle[b].arr[c.smarty.cycle[b].index]:""});jSmart.prototype.print_r=function(a,c){if(a instanceof Object){var b=(a instanceof Array?"Array["+a.length+"]":"Object")+"<br>",d;for(d in a)a.hasOwnProperty(d)&&(b+=c+" <strong>"+d+"</strong> : "+jSmart.prototype.print_r(a[d],c+" ")+"<br>");return b}return a};jSmart.prototype.registerPlugin("function","debug",function(a,c){"undefined"!=typeof dbgWnd&&dbgWnd.close();dbgWnd=window.open("","","width=680,height=600,resizable,scrollbars=yes");
var b="",d=0,e;for(e in c)b+="<tr class="+(++d%2?"odd":"even")+"><td><strong>"+e+"</strong></td><td>"+jSmart.prototype.print_r(c[e],"")+"</td></tr>";dbgWnd.document.write(" <html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en'> <head> \t <title>jSmart Debug Console</title> <style type='text/css'> table {width: 100%;} td {vertical-align:top;width: 50%;} .even td {background-color: #fafafa;} </style> </head> <body> <h1>jSmart Debug Console</h1> <h2>assigned template variables</h2> <table>"+
b+"</table> </body> </html> ");return""});jSmart.prototype.registerPlugin("function","fetch",function(a,c){var b=jSmart.prototype.getFile(a.__get("file",null,0));return"assign"in a?(x(a.assign,b,c),""):b});jSmart.prototype.registerPlugin("function","insert",function(a,c){var b={},d;for(d in a)a.hasOwnProperty(d)&&isNaN(d)&&a[d]&&"string"==typeof a[d]&&"name"!=d&&"assign"!=d&&"script"!=d&&(b[d]=a[d]);d="insert_";"script"in a&&(eval(jSmart.prototype.getJavascript(a.script)),
d="smarty_insert_");b=eval(d+a.__get("name",null,0))(b,c);return"assign"in a?(x(a.assign,b,c),""):b});jSmart.prototype.registerPlugin("function","html_checkboxes",function(a,c){var b=a.__get("type","checkbox"),d=a.__get("name",b);"checkbox"==b&&(d+="[]");var e=a.__get("values",a.options),f=a.__get("options",[]),g="options"in a,l;if(!g)for(l in a.output)f.push(a.output[l]);var k=a.__get("selected",!1),h=a.__get("separator",""),q=Boolean(a.__get("labels",!0)),n=[],X=0,v="";for(l in e)e.hasOwnProperty(l)&&
(v=q?"<label>":"",v+='<input type="'+b+'" name="'+d+'" value="'+(g?l:e[l])+'" ',k==(g?l:e[l])&&(v+='checked="checked" '),v+="/>"+f[g?l:X++],v+=q?"</label>":"",v+=h,n.push(v));return"assign"in a?(x(a.assign,n,c),""):n.join("\n")});jSmart.prototype.registerPlugin("function","html_image",function(a,c){var b=a.__get("file",null),d=a.__get("width",!1),e=a.__get("height",!1),f=a.__get("alt",""),g=a.__get("href",!1),l={file:1,width:1,height:1,alt:1,href:1,basedir:1,path_prefix:1},b='<img src="'+a.__get("path_prefix",
"")+b+'" alt="'+f+'"'+(d?' width="'+d+'"':"")+(e?' height="'+e+'"':""),k;for(k in a)a.hasOwnProperty(k)&&"string"==typeof a[k]&&(k in l||(b+=" "+k+'="'+a[k]+'"'));b+=" />";return g?'<a href="'+g+'">'+b+"</a>":b});jSmart.prototype.registerPlugin("function","html_options",function(a,c){var b=a.__get("values",a.options),d=a.__get("options",[]),e="options"in a,f;if(!e)for(f in a.output)d.push(a.output[f]);var g=a.__get("selected",!1);!g||g instanceof Array||(g=[g]);var l=[],k="",h=0;for(f in b)if(b.hasOwnProperty(f)){k=
'<option value="'+(e?f:b[f])+'"';if(g)for(h=0;h<g.length;++h)if(g[h]==(e?f:b[f])){k+=' selected="selected"';break}k+=">"+d[e?f:h++]+"</option>";l.push(k)}b=a.__get("name",!1);return(b?'<select name="'+b+'">\n'+l.join("\n")+"\n</select>":l.join("\n"))+"\n"});jSmart.prototype.registerPlugin("function","html_radios",function(a,c){a.type="radio";return A.html_checkboxes.process(a,c)});jSmart.prototype.registerPlugin("function","html_select_date",function(a,c){var b=a.__get("prefix","Date_"),d="January February March April May June July August September October November December".split(" "),
e;e=""+('<select name="'+b+'Month">\n');for(var f=0,f=0;f<d.length;++f)e+='<option value="'+f+'">'+d[f]+"</option>\n";e=e+"</select>\n"+('<select name="'+b+'Day">\n');for(f=0;31>f;++f)e+='<option value="'+f+'">'+f+"</option>\n";return e+="</select>\n"});jSmart.prototype.registerPlugin("function","html_table",function(a,c){var b=[],d;if(a.loop instanceof Array)b=a.loop;else for(d in a.loop)a.loop.hasOwnProperty(d)&&b.push(a.loop[d]);var e=a.__get("rows",!1),f=a.__get("cols",!1);f||(f=e?Math.ceil(b.length/
e):3);var g=[];if(isNaN(f)){if("object"==typeof f)for(d in f)f.hasOwnProperty(d)&&g.push(f[d]);else g=f.split(/\s*,\s*/);f=g.length}var e=e?e:Math.ceil(b.length/f),l=a.__get("inner","cols");d=a.__get("caption","");var k=a.__get("table_attr",'border="1"'),h=a.__get("th_attr",!1);h&&"object"!=typeof h&&(h=[h]);var q=a.__get("tr_attr",!1);q&&"object"!=typeof q&&(q=[q]);var n=a.__get("td_attr",!1);n&&"object"!=typeof n&&(n=[n]);for(var X=a.__get("trailpad"," "),v=a.__get("hdir","right"),m=a.__get("vdir",
"down"),p="",r=0;r<e;++r){for(var p=p+("<tr"+(q?" "+q[r%q.length]:"")+">\n"),t=0;t<f;++t)var u="cols"==l?("down"==m?r:e-1-r)*f+("right"==v?t:f-1-t):("right"==v?t:f-1-t)*e+("down"==m?r:e-1-r),p=p+("<td"+(n?" "+n[t%n.length]:"")+">"+(u<b.length?b[u]:X)+"</td>\n");p+="</tr>\n"}b="";if(g.length){b="\n<thead><tr>";for(e=0;e<g.length;++e)b+="\n<th"+(h?" "+h[e%h.length]:"")+">"+g["right"==v?e:g.length-1-e]+"</th>";b+="\n</tr></thead>"}return"<table "+k+">"+(d?"\n<caption>"+d+"</caption>":"")+b+"\n<tbody>\n"+
p+"</tbody>\n</table>\n"});jSmart.prototype.registerPlugin("function","include_javascript",function(a,c){var b=a.__get("file",null,0);if(a.__get("once",!0)&&b in W)return"";W[b]=!0;b=R(jSmart.prototype.getJavascript(b),{$this:c});return"assign"in a?(x(a.assign,b,c),""):b});jSmart.prototype.registerPlugin("function","include_php",function(a,c){return A.include_javascript.process(a,c)});m.rawurlencode=function(a){a=(a+"").toString();return encodeURIComponent(a).replace(/!/g,"%21").replace(/'/g,"%27").replace(/\(/g,
"%28").replace(/\)/g,"%29").replace(/\*/g,"%2A")};m.bin2hex=function(a){var c,b,d="",e;a+="";c=0;for(b=a.length;c<b;c++)e=a.charCodeAt(c).toString(16),d+=2>e.length?"0"+e:e;return d};m.ord=function(a){var c=a+"";a=c.charCodeAt(0);if(55296<=a&&56319>=a){if(1===c.length)return a;c=c.charCodeAt(1);return 1024*(a-55296)+(c-56320)+65536}return a};jSmart.prototype.registerPlugin("function","mailto",function(a,c){var b=a.__get("address",null),d=a.__get("encode","none"),e=a.__get("text",b),f=m.rawurlencode(a.__get("cc",
"")).replace("%40","@"),g=m.rawurlencode(a.__get("bcc","")).replace("%40","@"),l=m.rawurlencode(a.__get("followupto","")).replace("%40","@"),k=m.rawurlencode(a.__get("subject","")),h=m.rawurlencode(a.__get("newsgroups","")),q=a.__get("extra",""),b=b+(f?"?cc="+f:"")+(g?(f?"&":"?")+"bcc="+g:""),b=b+(k?(f||g?"&":"?")+"subject="+k:""),b=b+(h?(f||g||k?"&":"?")+"newsgroups="+h:""),b=b+(l?(f||g||k||h?"&":"?")+"followupto="+l:"");s='<a href="mailto:'+b+'" '+q+">"+e+"</a>";if("javascript"==d){s="document.write('"+
s+"');";e="";for(d=0;d<s.length;++d)e+="%"+m.bin2hex(s.substr(d,1));return'<script type="text/javascript">eval(unescape(\''+e+"'))\x3c/script>"}if("javascript_charcode"==d){e=[];for(d=0;d<s.length;++d)e.push(m.ord(s.substr(d,1)));return'<script type="text/javascript" language="javascript">\n\x3c!--\n{document.write(String.fromCharCode('+e.join(",")+"))}\n//--\x3e\n\x3c/script>\n"}if("hex"==d){if(b.match(/^.+\?.+$/))throw Error("mailto: hex encoding does not work with extra attributes. Try javascript.");
f="";for(d=0;d<b.length;++d)f=b.substr(d,1).match(/\w/)?f+("%"+m.bin2hex(b.substr(d,1))):f+b.substr(d,1);b="";for(d=0;d<e.length;++d)b+="&#x"+m.bin2hex(e.substr(d,1))+";";return'<a href="mailto:'+f+'" '+q+">"+b+"</a>"}return s});m.sprintf=function(){var a=arguments,c=0,b=function(a,b,c,d){c||(c=" ");b=a.length>=b?"":Array(1+b-a.length>>>0).join(c);return d?a+b:b+a},d=function(a,c,d,e,h,q){var n=e-a.length;0<n&&(a=d||!h?b(a,e,q,d):a.slice(0,c.length)+b("",n,"0",!0)+
a.slice(c.length));return a},e=function(a,c,e,k,h,q,n){a>>>=0;e=e&&a&&{2:"0b",8:"0",16:"0x"}[c]||"";a=e+b(a.toString(c),q||0,"0",!1);return d(a,e,k,h,n)};return a[c++].replace(/%%|%(\d+\$)?([-+\'#0 ]*)(\*\d+\$|\*|\d+)?(\.(\*\d+\$|\*|\d+))?([scboxXuideEfFgG])/g,function(f,g,l,k,h,q,n){var m,v;if("%%"===f)return"%";var p=!1;v="";var r=h=!1;m=" ";for(var t=l.length,u=0;l&&u<t;u++)switch(l.charAt(u)){case " ":v=" ";break;case "+":v="+";break;case "-":p=!0;break;case "'":m=l.charAt(u+1);break;case "0":h=
!0;m="0";break;case "#":r=!0}k=k?"*"===k?+a[c++]:"*"==k.charAt(0)?+a[k.slice(1,-1)]:+k:0;0>k&&(k=-k,p=!0);if(!isFinite(k))throw Error("sprintf: (minimum-)width must be finite");q=q?"*"===q?+a[c++]:"*"==q.charAt(0)?+a[q.slice(1,-1)]:+q:-1<"fFeE".indexOf(n)?6:"d"===n?0:void 0;g=g?a[g.slice(0,-1)]:a[c++];switch(n){case "s":return n=String(g),null!=q&&(n=n.slice(0,q)),d(n,"",p,k,h,m);case "c":return n=String.fromCharCode(+g),null!=q&&(n=n.slice(0,q)),d(n,"",p,k,h,void 0);case "b":return e(g,2,r,p,k,q,
h);case "o":return e(g,8,r,p,k,q,h);case "x":return e(g,16,r,p,k,q,h);case "X":return e(g,16,r,p,k,q,h).toUpperCase();case "u":return e(g,10,r,p,k,q,h);case "i":case "d":return m=+g||0,m=Math.round(m-m%1),f=0>m?"-":v,g=f+b(String(Math.abs(m)),q,"0",!1),d(g,f,p,k,h);case "e":case "E":case "f":case "F":case "g":case "G":return m=+g,f=0>m?"-":v,v=["toExponential","toFixed","toPrecision"]["efg".indexOf(n.toLowerCase())],n=["toString","toUpperCase"]["eEfFgG".indexOf(n)%2],g=f+Math.abs(m)[v](q),d(g,f,p,
k,h)[n]();default:return f}})};jSmart.prototype.registerPlugin("function","math",function(a,c){with(Math)with(a)var b=eval(a.__get("equation",null).replace(/pi\(\s*\)/g,"PI"));"format"in a&&(b=m.sprintf(a.format,b));return"assign"in a?(x(a.assign,b,c),""):b});jSmart.prototype.registerPlugin("modifier","wordwrap",function(a,c,b,d){c=c||80;b=b||"\n";a=(new String(a)).split("\n");for(var e=0;e<a.length;++e){for(var f=a[e],g="";f.length>c;){for(var l=0,k=f.slice(l).match(/\s+/);k&&l+k.index<=c;k=f.slice(l).match(/\s+/))l+=
k.index+k[0].length;l=l||(d?c:k?k.index+k[0].length:f.length);g+=f.slice(0,l).replace(/\s+$/,"");l<f.length&&(g+=b);f=f.slice(l)}a[e]=g+f}return a.join("\n")});jSmart.prototype.registerPlugin("block","textformat",function(a,c,b,d){if(!c)return"";c=new String(c);d=a.__get("wrap",80);var e=a.__get("wrap_char","\n"),f=a.__get("wrap_cut",!1),g=a.__get("indent_char"," "),l=a.__get("indent",0),k=Array(l+1).join(g),h=a.__get("indent_first",0),g=Array(h+1).join(g);"email"==a.__get("style","")&&(d=72);c=c.split("\n");
for(var q=0;q<c.length;++q){var n=c[q];n&&(n=n.replace(/^\s+|\s+$/,"").replace(/\s+/g," "),h&&(n=g+n),n=H.__wordwrap(n,d-l,e,f),l&&(n=n.replace(/^/mg,k)),c[q]=n)}d=c.join(e+e);return"assign"in a?(x(a.assign,d,b),""):d});jSmart.prototype.registerPlugin("modifier","capitalize",function(a,c){if("string"!=typeof a)return a;for(var b=RegExp(c?"[\\W\\d]+":"\\W+"),d=null,e="",d=a.match(b);d;d=a.match(b)){var f=a.slice(0,d.index),e=f.match(/\d/)?e+f:e+(f.charAt(0).toUpperCase()+f.slice(1)),e=e+a.slice(d.index,
d.index+d[0].length);a=a.slice(d.index+d[0].length)}return a.match(/\d/)?e+a:e+a.charAt(0).toUpperCase()+a.slice(1)});jSmart.prototype.registerPlugin("modifier","cat",function(a,c){c=c?c:"";return new String(a)+c});jSmart.prototype.registerPlugin("modifier","count",function(a,c){if(null===a||"undefined"===typeof a)return 0;if(a.constructor!==Array&&a.constructor!==Object)return 1;c=Boolean(c);var b,d=0;for(b in a)a.hasOwnProperty(b)&&(d++,c&&a[b]&&(a[b].constructor===Array||a[b].constructor===Object)&&
(d+=H.__count(a[b],!0)));return d});jSmart.prototype.registerPlugin("modifier","count_characters",function(a,c){a=new String(a);return c?a.length:a.replace(/\s/g,"").length});jSmart.prototype.registerPlugin("modifier","count_paragraphs",function(a){return(a=(new String(a)).match(/\n+/g))?a.length+1:1});jSmart.prototype.registerPlugin("modifier","count_sentences",function(a){return"string"==typeof a&&(a=a.match(/[^\s]\.(?!\w)/g))?a.length:0});jSmart.prototype.registerPlugin("modifier","count_words",
function(a){return"string"==typeof a&&(a=a.match(/\w+/g))?a.length:0});m.getenv=function(a){return this.php_js&&this.php_js.ENV&&this.php_js.ENV[a]?this.php_js.ENV[a]:!1};m.setlocale=function(a,c){var b="",d=[],e=0,e=this.window.document,f=function n(a){if(a instanceof RegExp)return RegExp(a);if(a instanceof Date)return new Date(a);var b={},c;for(c in a)b[c]="object"===typeof a[c]?n(a[c]):a[c];return b},g=function(a){return 1!==a?1:0},l=function(a){return 1<a?1:0};try{this.php_js=this.php_js||{}}catch(k){this.php_js=
{}}var h=this.php_js;h.locales||(h.locales={},h.locales.en={LC_COLLATE:function(a,b){return a==b?0:a>b?1:-1},LC_CTYPE:{an:/^[A-Za-z\d]+$/g,al:/^[A-Za-z]+$/g,ct:/^[\u0000-\u001F\u007F]+$/g,dg:/^[\d]+$/g,gr:/^[\u0021-\u007E]+$/g,lw:/^[a-z]+$/g,pr:/^[\u0020-\u007E]+$/g,pu:/^[\u0021-\u002F\u003A-\u0040\u005B-\u0060\u007B-\u007E]+$/g,sp:/^[\f\n\r\t\v ]+$/g,up:/^[A-Z]+$/g,xd:/^[A-Fa-f\d]+$/g,CODESET:"UTF-8",lower:"abcdefghijklmnopqrstuvwxyz",upper:"ABCDEFGHIJKLMNOPQRSTUVWXYZ"},LC_TIME:{a:"Sun Mon Tue Wed Thu Fri Sat".split(" "),
A:"Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),b:"Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec".split(" "),B:"January February March April May June July August September October November December".split(" "),c:"%a %d %b %Y %r %Z",p:["AM","PM"],P:["am","pm"],r:"%I:%M:%S %p",x:"%m/%d/%Y",X:"%r",alt_digits:"",ERA:"",ERA_YEAR:"",ERA_D_T_FMT:"",ERA_D_FMT:"",ERA_T_FMT:""},LC_MONETARY:{int_curr_symbol:"USD",currency_symbol:"$",mon_decimal_point:".",mon_thousands_sep:",",mon_grouping:[3],
positive_sign:"",negative_sign:"-",int_frac_digits:2,frac_digits:2,p_cs_precedes:1,p_sep_by_space:0,n_cs_precedes:1,n_sep_by_space:0,p_sign_posn:3,n_sign_posn:0},LC_NUMERIC:{decimal_point:".",thousands_sep:",",grouping:[3]},LC_MESSAGES:{YESEXPR:"^[yY].*",NOEXPR:"^[nN].*",YESSTR:"",NOSTR:""},nplurals:g},h.locales.en_US=f(h.locales.en),h.locales.en_US.LC_TIME.c="%a %d %b %Y %r %Z",h.locales.en_US.LC_TIME.x="%D",h.locales.en_US.LC_TIME.X="%r",h.locales.en_US.LC_MONETARY.int_curr_symbol="USD ",h.locales.en_US.LC_MONETARY.p_sign_posn=
1,h.locales.en_US.LC_MONETARY.n_sign_posn=1,h.locales.en_US.LC_MONETARY.mon_grouping=[3,3],h.locales.en_US.LC_NUMERIC.thousands_sep="",h.locales.en_US.LC_NUMERIC.grouping=[],h.locales.en_GB=f(h.locales.en),h.locales.en_GB.LC_TIME.r="%l:%M:%S %P %Z",h.locales.en_AU=f(h.locales.en_GB),h.locales.C=f(h.locales.en),h.locales.C.LC_CTYPE.CODESET="ANSI_X3.4-1968",h.locales.C.LC_MONETARY={int_curr_symbol:"",currency_symbol:"",mon_decimal_point:"",mon_thousands_sep:"",mon_grouping:[],p_cs_precedes:127,p_sep_by_space:127,
n_cs_precedes:127,n_sep_by_space:127,p_sign_posn:127,n_sign_posn:127,positive_sign:"",negative_sign:"",int_frac_digits:127,frac_digits:127},h.locales.C.LC_NUMERIC={decimal_point:".",thousands_sep:"",grouping:[]},h.locales.C.LC_TIME.c="%a %b %e %H:%M:%S %Y",h.locales.C.LC_TIME.x="%m/%d/%y",h.locales.C.LC_TIME.X="%H:%M:%S",h.locales.C.LC_MESSAGES.YESEXPR="^[yY]",h.locales.C.LC_MESSAGES.NOEXPR="^[nN]",h.locales.fr=f(h.locales.en),h.locales.fr.nplurals=l,h.locales.fr.LC_TIME.a="dim lun mar mer jeu ven sam".split(" "),
h.locales.fr.LC_TIME.A="dimanche lundi mardi mercredi jeudi vendredi samedi".split(" "),h.locales.fr.LC_TIME.b="jan f\u00e9v mar avr mai jun jui ao\u00fb sep oct nov d\u00e9c".split(" "),h.locales.fr.LC_TIME.B="janvier f\u00e9vrier mars avril mai juin juillet ao\u00fbt septembre octobre novembre d\u00e9cembre".split(" "),h.locales.fr.LC_TIME.c="%a %d %b %Y %T %Z",h.locales.fr.LC_TIME.p=["",""],h.locales.fr.LC_TIME.P=["",""],h.locales.fr.LC_TIME.x="%d.%m.%Y",h.locales.fr.LC_TIME.X="%T",h.locales.fr_CA=
f(h.locales.fr),h.locales.fr_CA.LC_TIME.x="%Y-%m-%d");h.locale||(h.locale="en_US",e.getElementsByTagNameNS&&e.getElementsByTagNameNS("http://www.w3.org/1999/xhtml","html")[0]?e.getElementsByTagNameNS("http://www.w3.org/1999/xhtml","html")[0].getAttributeNS&&e.getElementsByTagNameNS("http://www.w3.org/1999/xhtml","html")[0].getAttributeNS("http://www.w3.org/XML/1998/namespace","lang")?h.locale=e.getElementsByTagName("http://www.w3.org/1999/xhtml","html")[0].getAttributeNS("http://www.w3.org/XML/1998/namespace",
"lang"):e.getElementsByTagNameNS("http://www.w3.org/1999/xhtml","html")[0].lang&&(h.locale=e.getElementsByTagNameNS("http://www.w3.org/1999/xhtml","html")[0].lang):e.getElementsByTagName("html")[0]&&e.getElementsByTagName("html")[0].lang&&(h.locale=e.getElementsByTagName("html")[0].lang));h.locale=h.locale.replace("-","_");!(h.locale in h.locales)&&h.locale.replace(/_[a-zA-Z]+$/,"")in h.locales&&(h.locale=h.locale.replace(/_[a-zA-Z]+$/,""));h.localeCategories||(h.localeCategories={LC_COLLATE:h.locale,
LC_CTYPE:h.locale,LC_MONETARY:h.locale,LC_NUMERIC:h.locale,LC_TIME:h.locale,LC_MESSAGES:h.locale});if(null===c||""===c)c=this.getenv(a)||this.getenv("LANG");else if("[object Array]"===Object.prototype.toString.call(c))for(e=0;e<c.length;e++)if(c[e]in this.php_js.locales){c=c[e];break}else if(e===c.length-1)return!1;if("0"===c||0===c){if("LC_ALL"===a){for(b in this.php_js.localeCategories)d.push(b+"="+this.php_js.localeCategories[b]);return d.join(";")}return this.php_js.localeCategories[a]}if(!(c in
this.php_js.locales))return!1;if("LC_ALL"===a)for(b in this.php_js.localeCategories)this.php_js.localeCategories[b]=c;else this.php_js.localeCategories[a]=c;return c};m.strftime=function(a,c){this.php_js=this.php_js||{};this.setlocale("LC_ALL",0);for(var b=this.php_js,d=function(a,b,c){for("undefined"===typeof c&&(c=10);parseInt(a,10)<c&&1<c;c/=10)a=b.toString()+a;return a.toString()},e=b.locales[b.localeCategories.LC_TIME].LC_TIME,f={a:function(a){return e.a[a.getDay()]},A:function(a){return e.A[a.getDay()]},
b:function(a){return e.b[a.getMonth()]},B:function(a){return e.B[a.getMonth()]},C:function(a){return d(parseInt(a.getFullYear()/100,10),0)},d:["getDate","0"],e:["getDate"," "],g:function(a){return d(parseInt(this.G(a)/100,10),0)},G:function(a){var b=a.getFullYear(),c=parseInt(f.V(a),10);a=parseInt(f.W(a),10);a>c?b++:0===a&&52<=c&&b--;return b},H:["getHours","0"],I:function(a){a=a.getHours()%12;return d(0===a?12:a,0)},j:function(a){var b=a-new Date(""+a.getFullYear()+"/1/1 GMT"),b=b+6E4*a.getTimezoneOffset();
a=parseInt(b/6E4/60/24,10)+1;return d(a,0,100)},k:["getHours","0"],l:function(a){a=a.getHours()%12;return d(0===a?12:a," ")},m:function(a){return d(a.getMonth()+1,0)},M:["getMinutes","0"],p:function(a){return e.p[12<=a.getHours()?1:0]},P:function(a){return e.P[12<=a.getHours()?1:0]},s:function(a){return Date.parse(a)/1E3},S:["getSeconds","0"],u:function(a){a=a.getDay();return 0===a?7:a},U:function(a){var b=parseInt(f.j(a),10);a=6-a.getDay();b=parseInt((b+a)/7,10);return d(b,0)},V:function(a){var b=
parseInt(f.W(a),10),c=(new Date(""+a.getFullYear()+"/1/1")).getDay(),b=b+(4<c||1>=c?0:1);53===b&&4>(new Date(""+a.getFullYear()+"/12/31")).getDay()?b=1:0===b&&(b=f.V(new Date(""+(a.getFullYear()-1)+"/12/31")));return d(b,0)},w:"getDay",W:function(a){var b=parseInt(f.j(a),10);a=7-f.u(a);b=parseInt((b+a)/7,10);return d(b,0,10)},y:function(a){return d(a.getFullYear()%100,0)},Y:"getFullYear",z:function(a){a=a.getTimezoneOffset();var b=d(parseInt(Math.abs(a/60),10),0),c=d(a%60,0);return(0<a?"-":"+")+b+
c},Z:function(a){return a.toString().replace(/^.*\(([^)]+)\)$/,"$1")},"%":function(a){return"%"}},g="undefined"===typeof c?new Date:"object"===typeof c?new Date(c):new Date(1E3*c),l={c:"locale",D:"%m/%d/%y",F:"%y-%m-%d",h:"%b",n:"\n",r:"locale",R:"%H:%M",t:"\t",T:"%H:%M:%S",x:"locale",X:"locale"};a.match(/%[cDFhnrRtTxX]/);)a=a.replace(/%([cDFhnrRtTxX])/g,function(a,b){var c=l[b];return"locale"===c?e[b]:c});return a.replace(/%([aAbBCdegGHIjklmMpPsSuUVwWyYzZ%])/g,function(a,b){var c=f[b];return"string"===
typeof c?g[c]():"function"===typeof c?c(g):"object"===typeof c&&"string"===typeof c[0]?d(g[c[0]](),c[1]):b})};m.strtotime=function(a,c){function b(a){var b=a.split(" ");a=b[0];var c=b[1].substring(0,3),d=/\d+/.test(a),e=("last"===a?-1:1)*("ago"===b[2]?-1:1);d&&(e*=parseInt(a,10));if(l.hasOwnProperty(c)&&!b[1].match(/^mon(day|\.)?$/i))return f["set"+l[c]](f["get"+l[c]]()+e);if("wee"===c)return f.setDate(f.getDate()+7*e);if("next"===a||"last"===a)b=e,c=g[c],"undefined"!==typeof c&&(c-=f.getDay(),0===
c?c=7*b:0<c&&"last"===a?c-=7:0>c&&"next"===a&&(c+=7),f.setDate(f.getDate()+c));else if(!d)return!1;return!0}var d,e,f,g,l,k;if(!a)return!1;a=a.replace(/^\s+|\s+$/g,"").replace(/\s{2,}/g," ").replace(/[\t\r\n]/g,"").toLowerCase();if((d=a.match(/^(\d{1,4})([\-\.\/\:])(\d{1,2})([\-\.\/\:])(\d{1,4})(?:\s(\d{1,2}):(\d{2})?:?(\d{2})?)?(?:\s([A-Z]+)?)?$/))&&d[2]===d[4])if(1901<d[1])switch(d[2]){case "-":return 12<d[3]||31<d[5]?!1:new Date(d[1],parseInt(d[3],10)-1,d[5],d[6]||0,d[7]||0,d[8]||0,d[9]||0)/1E3;
case ".":return!1;case "/":return 12<d[3]||31<d[5]?!1:new Date(d[1],parseInt(d[3],10)-1,d[5],d[6]||0,d[7]||0,d[8]||0,d[9]||0)/1E3}else if(1901<d[5])switch(d[2]){case "-":return 12<d[3]||31<d[1]?!1:new Date(d[5],parseInt(d[3],10)-1,d[1],d[6]||0,d[7]||0,d[8]||0,d[9]||0)/1E3;case ".":return 12<d[3]||31<d[1]?!1:new Date(d[5],parseInt(d[3],10)-1,d[1],d[6]||0,d[7]||0,d[8]||0,d[9]||0)/1E3;case "/":return 12<d[1]||31<d[3]?!1:new Date(d[5],parseInt(d[1],10)-1,d[3],d[6]||0,d[7]||0,d[8]||0,d[9]||0)/1E3}else switch(d[2]){case "-":if(12<
d[3]||31<d[5]||70>d[1]&&38<d[1])return!1;e=0<=d[1]&&38>=d[1]?+d[1]+2E3:d[1];return new Date(e,parseInt(d[3],10)-1,d[5],d[6]||0,d[7]||0,d[8]||0,d[9]||0)/1E3;case ".":if(70<=d[5])return 12<d[3]||31<d[1]?!1:new Date(d[5],parseInt(d[3],10)-1,d[1],d[6]||0,d[7]||0,d[8]||0,d[9]||0)/1E3;if(60>d[5]&&!d[6]){if(23<d[1]||59<d[3])return!1;e=new Date;return new Date(e.getFullYear(),e.getMonth(),e.getDate(),d[1]||0,d[3]||0,d[5]||0,d[9]||0)/1E3}return!1;case "/":if(12<d[1]||31<d[3]||70>d[5]&&38<d[5])return!1;e=0<=
d[5]&&38>=d[5]?+d[5]+2E3:d[5];return new Date(e,parseInt(d[1],10)-1,d[3],d[6]||0,d[7]||0,d[8]||0,d[9]||0)/1E3;case ":":if(23<d[1]||59<d[3]||59<d[5])return!1;e=new Date;return new Date(e.getFullYear(),e.getMonth(),e.getDate(),d[1]||0,d[3]||0,d[5]||0)/1E3}if("now"===a)return null===c||isNaN(c)?(new Date).getTime()/1E3|0:c|0;if(!isNaN(d=Date.parse(a)))return d/1E3|0;f=c?new Date(1E3*c):new Date;g={sun:0,mon:1,tue:2,wed:3,thu:4,fri:5,sat:6};l={yea:"FullYear",mon:"Month",day:"Date",hou:"Hours",min:"Minutes",
sec:"Seconds"};d=a.match(RegExp("([+-]?\\d+\\s(years?|months?|weeks?|days?|hours?|minutes?|min|seconds?|sec|sunday|sun\\.?|monday|mon\\.?|tuesday|tue\\.?|wednesday|wed\\.?|thursday|thu\\.?|friday|fri\\.?|saturday|sat\\.?)|(last|next)\\s(years?|months?|weeks?|days?|hours?|minutes?|min|seconds?|sec|sunday|sun\\.?|monday|mon\\.?|tuesday|tue\\.?|wednesday|wed\\.?|thursday|thu\\.?|friday|fri\\.?|saturday|sat\\.?))(\\sago)?","gi"));if(!d)return!1;k=0;for(e=d.length;k<e;k++)if(!b(d[k]))return!1;return f.getTime()/
1E3};makeTimeStamp=function(a){if(!a)return Math.floor((new Date).getTime()/1E3);if(isNaN(a))return a=m.strtotime(a),-1==a||!1===a?Math.floor((new Date).getTime()/1E3):a;a=new String(a);return 14==a.length?Math.floor((new Date(a.substr(0,4),a.substr(4,2)-1,a.substr(6,2),a.substr(8,2),a.substr(10,2))).getTime()/1E3):parseInt(a)};jSmart.prototype.registerPlugin("modifier","date_format",function(a,c,b){return a?m.strftime(c?c:"%b %e, %Y",makeTimeStamp(a?a:b)):""});m.get_html_translation_table=function(a,
c){var b={},d={},e,f={},g={},l={},k={};f[0]="HTML_SPECIALCHARS";f[1]="HTML_ENTITIES";g[0]="ENT_NOQUOTES";g[2]="ENT_COMPAT";g[3]="ENT_QUOTES";l=isNaN(a)?a?a.toUpperCase():"HTML_SPECIALCHARS":f[a];k=isNaN(c)?c?c.toUpperCase():"ENT_COMPAT":g[c];if("HTML_SPECIALCHARS"!==l&&"HTML_ENTITIES"!==l)throw Error("Table: "+l+" not supported");b["38"]="&";"HTML_ENTITIES"===l&&(b["160"]=" ",b["161"]="¡",b["162"]="¢",b["163"]="£",b["164"]="¤",b["165"]="¥",b["166"]="¦",
b["167"]="§",b["168"]="¨",b["169"]="©",b["170"]="ª",b["171"]="«",b["172"]="¬",b["173"]="­",b["174"]="®",b["175"]="¯",b["176"]="°",b["177"]="±",b["178"]="²",b["179"]="³",b["180"]="´",b["181"]="µ",b["182"]="¶",b["183"]="·",b["184"]="¸",b["185"]="¹",b["186"]="º",b["187"]="»",b["188"]="¼",b["189"]="½",b["190"]="¾",b["191"]="¿",b["192"]="À",b["193"]="Á",
b["194"]="Â",b["195"]="Ã",b["196"]="Ä",b["197"]="Å",b["198"]="Æ",b["199"]="Ç",b["200"]="È",b["201"]="É",b["202"]="Ê",b["203"]="Ë",b["204"]="Ì",b["205"]="Í",b["206"]="Î",b["207"]="Ï",b["208"]="Ð",b["209"]="Ñ",b["210"]="Ò",b["211"]="Ó",b["212"]="Ô",b["213"]="Õ",b["214"]="Ö",b["215"]="×",b["216"]="Ø",b["217"]="Ù",b["218"]="Ú",b["219"]="Û",
b["220"]="Ü",b["221"]="Ý",b["222"]="Þ",b["223"]="ß",b["224"]="à",b["225"]="á",b["226"]="â",b["227"]="ã",b["228"]="ä",b["229"]="å",b["230"]="æ",b["231"]="ç",b["232"]="è",b["233"]="é",b["234"]="ê",b["235"]="ë",b["236"]="ì",b["237"]="í",b["238"]="î",b["239"]="ï",b["240"]="ð",b["241"]="ñ",b["242"]="ò",b["243"]="ó",b["244"]="ô",b["245"]="õ",
b["246"]="ö",b["247"]="÷",b["248"]="ø",b["249"]="ù",b["250"]="ú",b["251"]="û",b["252"]="ü",b["253"]="ý",b["254"]="þ",b["255"]="ÿ");"ENT_NOQUOTES"!==k&&(b["34"]=""");"ENT_QUOTES"===k&&(b["39"]="'");b["60"]="<";b["62"]=">";for(e in b)b.hasOwnProperty(e)&&(d[String.fromCharCode(e)]=b[e]);return d};m.htmlentities=function(a,c,b,d){var e=this.get_html_translation_table("HTML_ENTITIES",c);a=null==a?"":a+"";if(!e)return!1;c&&"ENT_QUOTES"===
c&&(e["'"]="'");d=null==d||!!d;c=RegExp("&(?:#\\d+|#x[\\da-f]+|[a-zA-Z][\\da-z]*);|["+Object.keys(e).join("").replace(/([()[\]{}\-.*+?^$|\/\\])/g,"\\$1")+"]","g");return a.replace(c,function(a){return 1<a.length?d?e["&"]+a.substr(1):a:e[a]})};jSmart.prototype.registerPlugin("modifier","escape",function(a,c,b,d){a=new String(a);b=b||"UTF-8";d="undefined"!=typeof d?Boolean(d):!0;switch(c||"html"){case "html":return d&&(a=a.replace(/&/g,"&")),a.replace(/</g,"<").replace(/>/g,">").replace(/'/g,
"'").replace(/"/g,""");case "htmlall":return m.htmlentities(a,3,b);case "url":return m.rawurlencode(a);case "urlpathinfo":return m.rawurlencode(a).replace(/%2F/g,"/");case "quotes":return a.replace(/(^|[^\\])'/g,"$1\\'");case "hex":c="";for(b=0;b<a.length;++b)c+="%"+m.bin2hex(a.substr(b,1));return c;case "hexentity":c="";for(b=0;b<a.length;++b)c+="&#x"+m.bin2hex(a.substr(b,1)).toUpperCase()+";";return c;case "decentity":c="";for(b=0;b<a.length;++b)c+="&#"+m.ord(a.substr(b,1))+";";return c;
case "mail":return a.replace(/@/g," [AT] ").replace(/[.]/g," [DOT] ");case "nonstd":c="";for(b=0;b<a.length;++b)d=m.ord(a.substr(b,1)),c=126<=d?c+("&#"+d+";"):c+a.substr(b,1);return c;case "javascript":return a.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(/"/g,'\\"').replace(/\r/g,"\\r").replace(/\n/g,"\\n").replace(/<\//g,"</")}return a});jSmart.prototype.registerPlugin("modifier","indent",function(a,c,b){a=new String(a);c=c?c:4;b=b?b:" ";for(var d="";c--;)d+=b;c=a.match(/\n+$/);return d+a.replace(/\n+$/,
"").replace(/\n/g,"\n"+d)+(c?c[0]:"")});jSmart.prototype.registerPlugin("modifier","lower",function(a){return(new String(a)).toLowerCase()});jSmart.prototype.registerPlugin("modifier","nl2br",function(a){return(new String(a)).replace(/\n/g,"<br />\n")});jSmart.prototype.registerPlugin("modifier","regex_replace",function(a,c,b){c=c.match(/^ *\/(.*)\/(.*) *$/);return(new String(a)).replace(RegExp(c[1],"g"+(1<c.length?c[2]:"")),b)});jSmart.prototype.registerPlugin("modifier","replace",function(a,c,b){if(!c)return a;
a=new String(a);c=new String(c);b=new String(b);for(var d="",e=-1,e=a.indexOf(c);0<=e;e=a.indexOf(c))d+=a.slice(0,e)+b,e+=c.length,a=a.slice(e);return d+a});jSmart.prototype.registerPlugin("modifier","spacify",function(a,c){c||(c=" ");return(new String(a)).replace(/(\n|.)(?!$)/g,"$1"+c)});jSmart.prototype.registerPlugin("modifier","string_format",function(a,c){return m.sprintf(c,a)});jSmart.prototype.registerPlugin("modifier","strip",function(a,c){c=c?c:" ";return(new String(a)).replace(/[\s]+/g,
c)});jSmart.prototype.registerPlugin("modifier","strip_tags",function(a,c){c=null==c?!0:c;return(new String(a)).replace(/<[^>]*?>/g,c?" ":"")});jSmart.prototype.registerPlugin("modifier","truncate",function(a,c,b,d,e){a=new String(a);c=c?c:80;b=null!=b?b:"...";if(a.length<=c)return a;c-=Math.min(c,b.length);if(e)return a.slice(0,Math.floor(c/2))+b+a.slice(a.length-Math.floor(c/2));d||(a=a.slice(0,c+1).replace(/\s+?(\S+)?$/,""));return a.slice(0,c)+b});jSmart.prototype.registerPlugin("modifier","upper",
function(a){return(new String(a)).toUpperCase()})})();
| quartz55/LBAW | proto/js/smart.min.js | JavaScript | gpl-3.0 | 54,804 |
/*
* Copyright (c) 2017 dtrouillet
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
(function() {
'use strict';
angular
.module('fayabankApp')
.directive('hasAuthority', hasAuthority);
hasAuthority.$inject = ['Principal'];
function hasAuthority(Principal) {
var directive = {
restrict: 'A',
link: linkFunc
};
return directive;
function linkFunc(scope, element, attrs) {
var authority = attrs.hasAuthority.replace(/\s+/g, '');
var setVisible = function () {
element.removeClass('hidden');
},
setHidden = function () {
element.addClass('hidden');
},
defineVisibility = function (reset) {
if (reset) {
setVisible();
}
Principal.hasAuthority(authority)
.then(function (result) {
if (result) {
setVisible();
} else {
setHidden();
}
});
};
if (authority.length > 0) {
defineVisibility(true);
scope.$watch(function() {
return Principal.isAuthenticated();
}, function() {
defineVisibility(true);
});
}
}
}
})();
| kms77/Fayabank | src/main/webapp/app/services/auth/has-authority.directive.js | JavaScript | gpl-3.0 | 2,988 |
var uploader=angular.module('ui.ng-uploader', [])
.directive('ngUploader', ['uploaderFactory','$log',function (uploaderFactory,$log) {
return {
//startUpload:uploaderFactory.startUpload,
data:uploaderFactory.data,
restrict: 'AEC',
template:'<div class="panel panel-info"><div class="panel-heading"><input class="btn btn-default" type="file" name="{{file.parameter}}" multiple/></div><div class="panel-body"><div ng-repeat="file in fileList" style="text-align:center;" class="bg-primary"><span>{{file.filename}}</span><button ng-click="erase(this)" type="button" class="close" aria-hidden="true">×</button><div class="progress"><div min-width="10%" class="progress-bar" role="progressbar" aria-valuenow="{{file.value}}" aria-valuemin="0" aria-valuemax="100" style="width: {{file.value}}%;">{{file.size}}/{{file.total}}</div></div></div><button class="btn btn-success" ng-click="startUpload()">Upload</button></div></div>',
link: function($scope, element, attrs) {
$scope.wtf;
$scope.fileList=[];
$scope.concurrency=(typeof attrs.concurrency=="undefined")?2:attrs.concurrency;
$scope.parameter=(typeof attrs.name=="undefined")?"file":attrs.name;
$scope.activeUploads=0;
$scope.getSize=function(bytes) {
var sizes = [ 'n/a', 'bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EiB', 'ZiB', 'YiB' ];
var i = +Math.floor(Math.log(bytes) / Math.log(1024));
return (bytes / Math.pow(1024, i)).toFixed(i ? 1 : 0) + ' ' + sizes[isNaN(bytes) ? 0 : i + 1];
}
element.find("input").bind("change", function(e) {
var files=e.target.files;
for ( var i = 0; i < files.length; i++) {
$scope.fileList.push({
parameter:$scope.parameter,
active:false,
filename:files[i].name,
file:files[i],
value:(0/files[i].size)*100,
size:0,
total:$scope.getSize(files[i].size)
});
}
$scope.$apply();
//$scope.startUpload();
});
$scope.erase=function(ele){
$log.info("file erased=");
$scope.fileList.splice( $scope.fileList.indexOf(ele), 1 );
};
$scope.onProgress=function(upload, loaded){
$log.info("progress="+loaded);
upload.value=(loaded/upload.file.size)*100;
upload.size=$scope.getSize(loaded);
$scope.$apply();
};
$scope.onCompleted=function(upload){
$log.info("file uploaded="+upload.filename);
$scope.activeUploads-=1;
$scope.fileList.splice( $scope.fileList.indexOf(upload), 1 );
$scope.$apply();
$scope.startUpload();
}
$scope.startUpload=function(){
$log.info("URL="+attrs.ngUploader);
//$log.info("Init Upload");
// $scope.concurrency=($scope.concurrency==undefined)?2:$scope.concurrency;
for(var i in $scope.fileList){
if ($scope.activeUploads === $scope.concurrency) {
break;
}
if($scope.fileList[i].active)
continue;
$scope.ajaxUpload($scope.fileList[i]);
}
};
$scope.ajaxUpload=function(upload) {
var xhr, formData, prop, data = "", key = "" || 'file', index;
//index = upload.count;
console.log('Beging upload: ' + upload.filename);
$scope.activeUploads+=1;
upload.active=true;
xhr = new window.XMLHttpRequest();
formData = new window.FormData();
xhr.open('POST', attrs.ngUploader);
// Triggered when upload starts:
xhr.upload.onloadstart = function() {
// File size is not reported during start!
console.log('Upload started: ' + upload.filename);
//methods.OnStart(upload.newname);
};
// Triggered many times during upload:
xhr.upload.onprogress = function(event) {
// console.dir(event);
if (!event.lengthComputable) { return; }
// Update file size because it might be bigger than reported by
// the fileSize:
console.log("File: " + index);
//methods.OnProgress(xhr,event.total, event.loaded, index, upload.newname,upload);
$scope.onProgress(upload, event.loaded);
};
// Triggered when upload is completed:
xhr.onload = function(event) {
console.log('Upload completed: ' + upload.filename+"|responseText:"+this.responseText+"|"+event.target.responseText);
$scope.onCompleted(upload);
};
// Triggered when upload fails:
xhr.onerror = function() {
console.log('Upload failed: ', upload.filename);
};
// Append additional data if provided:
if (data) {
for (prop in data) {
if (data.hasOwnProperty(prop)) {
console.log('Adding data: ' + prop + ' = ' + data[prop]);
formData.append(prop, data[prop]);
}
}
}
// Append file data:
formData.append(key, upload.file, upload.parameter);
// Initiate upload:
xhr.send(formData);
return xhr;
};
}
};
}]
).factory('uploaderFactory',function(){
return{
data:4454,
startUpload:function(){
alert("funcaaa");
}
};
}); | realtica/ng-uploader | src/ngUploader.js | JavaScript | gpl-3.0 | 5,288 |
/*******************************************************************************
uBlock Origin - a browser extension to block requests.
Copyright (C) 2017 Raymond Hill
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/}.
Home: https://github.com/gorhill/uBlock
*/
'use strict';
// For content pages
if ( typeof vAPI === 'object' ) { // >>>>>>>> start of HUGE-IF-BLOCK
/******************************************************************************/
/******************************************************************************/
vAPI.userStylesheet = {
added: new Set(),
removed: new Set(),
apply: function() {
if ( this.added.size === 0 && this.removed.size === 0 ) { return; }
vAPI.messaging.send('vapi-background', {
what: 'userCSS',
add: Array.from(this.added),
remove: Array.from(this.removed)
});
this.added.clear();
this.removed.clear();
},
add: function(cssText, now) {
if ( cssText === '' ) { return; }
this.added.add(cssText);
if ( now ) { this.apply(); }
},
remove: function(cssText, now) {
if ( cssText === '' ) { return; }
this.removed.add(cssText);
if ( now ) { this.apply(); }
}
};
/******************************************************************************/
vAPI.DOMFilterer = function() {
this.commitTimer = new vAPI.SafeAnimationFrame(this.commitNow.bind(this));
this.domIsReady = document.readyState !== 'loading';
this.disabled = false;
this.listeners = [];
this.filterset = new Set();
this.excludedNodeSet = new WeakSet();
this.addedCSSRules = new Set();
if ( this.domIsReady !== true ) {
document.addEventListener('DOMContentLoaded', () => {
this.domIsReady = true;
this.commit();
});
}
};
vAPI.DOMFilterer.prototype = {
reOnlySelectors: /\n\{[^\n]+/g,
// Here we will deal with:
// - Injecting low priority user styles;
// - Notifying listeners about changed filterset.
commitNow: function() {
this.commitTimer.clear();
var userStylesheet = vAPI.userStylesheet,
addedSelectors = [];
for ( var entry of this.addedCSSRules ) {
if (
this.disabled === false &&
entry.lazy &&
entry.injected === false
) {
userStylesheet.add(
entry.selectors + '\n{' + entry.declarations + '}'
);
}
addedSelectors.push(entry.selectors);
}
this.addedCSSRules.clear();
userStylesheet.apply();
if ( addedSelectors.length !== 0 ) {
this.triggerListeners('declarative', addedSelectors.join(',\n'));
}
},
commit: function(commitNow) {
if ( commitNow ) {
this.commitTimer.clear();
this.commitNow();
} else {
this.commitTimer.start();
}
},
addCSSRule: function(selectors, declarations, details) {
if ( selectors === undefined ) { return; }
var selectorsStr = Array.isArray(selectors)
? selectors.join(',\n')
: selectors;
if ( selectorsStr.length === 0 ) { return; }
if ( details === undefined ) { details = {}; }
var entry = {
selectors: selectorsStr,
declarations,
lazy: details.lazy === true,
injected: details.injected === true
};
this.addedCSSRules.add(entry);
this.filterset.add(entry);
if (
this.disabled === false &&
entry.lazy !== true &&
entry.injected !== true
) {
vAPI.userStylesheet.add(selectorsStr + '\n{' + declarations + '}');
}
this.commit();
},
addListener: function(listener) {
if ( this.listeners.indexOf(listener) !== -1 ) { return; }
this.listeners.push(listener);
},
removeListener: function(listener) {
var pos = this.listeners.indexOf(listener);
if ( pos === -1 ) { return; }
this.listeners.splice(pos, 1);
},
triggerListeners: function(type, selectors) {
var i = this.listeners.length;
while ( i-- ) {
this.listeners[i].onFiltersetChanged(type, selectors);
}
},
excludeNode: function(node) {
this.excludedNodeSet.add(node);
this.unhideNode(node);
},
unexcludeNode: function(node) {
this.excludedNodeSet.delete(node);
},
hideNode: function(node) {
if ( this.excludedNodeSet.has(node) ) { return; }
if ( this.hideNodeAttr === undefined ) { return; }
node.setAttribute(this.hideNodeAttr, '');
if ( this.hideNodeStyleSheetInjected === false ) {
this.hideNodeStyleSheetInjected = true;
this.addCSSRule(
'[' + this.hideNodeAttr + ']',
'display:none!important;'
);
}
},
unhideNode: function(node) {
if ( this.hideNodeAttr === undefined ) { return; }
node.removeAttribute(this.hideNodeAttr);
},
toggle: function(state) {
if ( state === undefined ) { state = this.disabled; }
if ( state !== this.disabled ) { return; }
this.disabled = !state;
var userStylesheet = vAPI.userStylesheet;
for ( var entry of this.filterset ) {
var rule = entry.selectors + '\n{' + entry.declarations + '}';
if ( this.disabled ) {
userStylesheet.remove(rule);
} else {
userStylesheet.add(rule);
}
}
userStylesheet.apply();
},
getAllDeclarativeSelectors_: function(all) {
let selectors = [];
for ( var entry of this.filterset ) {
if ( all === false && entry.internal ) { continue; }
selectors.push(entry.selectors);
}
var out = selectors.join(',\n');
if ( !all && this.hideNodeAttr !== undefined ) {
out = out.replace('[' + this.hideNodeAttr + ']', '')
.replace(/^,\n|\n,|,\n$/, '');
}
return out;
},
getFilteredElementCount: function() {
let selectors = this.getAllDeclarativeSelectors_(true);
return selectors.length !== 0
? document.querySelectorAll(selectors).length
: 0;
},
getAllDeclarativeSelectors: function() {
return this.getAllDeclarativeSelectors_(false);
}
};
/******************************************************************************/
/******************************************************************************/
} // <<<<<<<< end of HUGE-IF-BLOCK
| PeterDaveHello/uBlock | platform/webext/vapi-usercss.js | JavaScript | gpl-3.0 | 7,401 |
dojo.provide("dijit.form.CheckBox");
dojo.require("dijit.form.Button");
dojo.declare(
"dijit.form.CheckBox",
dijit.form.ToggleButton,
{
// summary:
// Same as an HTML checkbox, but with fancy styling.
//
// description:
// User interacts with real html inputs.
// On onclick (which occurs by mouse click, space-bar, or
// using the arrow keys to switch the selected radio button),
// we update the state of the checkbox/radio.
//
// There are two modes:
// 1. High contrast mode
// 2. Normal mode
// In case 1, the regular html inputs are shown and used by the user.
// In case 2, the regular html inputs are invisible but still used by
// the user. They are turned quasi-invisible and overlay the background-image.
templatePath: dojo.moduleUrl("dijit.form", "templates/CheckBox.html"),
baseClass: "dijitCheckBox",
// Value of "type" attribute for <input>
_type: "checkbox",
// value: Value
// equivalent to value field on normal checkbox (if checked, the value is passed as
// the value when form is submitted)
value: "on",
postCreate: function(){
dojo.setSelectable(this.inputNode, false);
this.setChecked(this.checked);
dijit.form.ToggleButton.prototype.postCreate.apply(this, arguments);
},
setChecked: function(/*Boolean*/ checked){
this.checked = checked;
if(dojo.isIE){
if(checked){ this.inputNode.setAttribute('checked', 'checked'); }
else{ this.inputNode.removeAttribute('checked'); }
}else{ this.inputNode.checked = checked; }
dijit.form.ToggleButton.prototype.setChecked.apply(this, arguments);
},
setValue: function(/*String*/ value){
if(value == null){ value = ""; }
this.inputNode.value = value;
dijit.form.CheckBox.superclass.setValue.call(this,value);
}
}
);
dojo.declare(
"dijit.form.RadioButton",
dijit.form.CheckBox,
{
// summary:
// Same as an HTML radio, but with fancy styling.
//
// description:
// Implementation details
//
// Specialization:
// We keep track of dijit radio groups so that we can update the state
// of all the siblings (the "context") in a group based on input
// events. We don't rely on browser radio grouping.
_type: "radio",
baseClass: "dijitRadio",
// This shared object keeps track of all widgets, grouped by name
_groups: {},
postCreate: function(){
// add this widget to _groups
(this._groups[this.name] = this._groups[this.name] || []).push(this);
dijit.form.CheckBox.prototype.postCreate.apply(this, arguments);
},
uninitialize: function(){
// remove this widget from _groups
dojo.forEach(this._groups[this.name], function(widget, i, arr){
if(widget === this){
arr.splice(i, 1);
return;
}
}, this);
},
setChecked: function(/*Boolean*/ checked){
// If I am being checked then have to deselect currently checked radio button
if(checked){
dojo.forEach(this._groups[this.name], function(widget){
if(widget != this && widget.checked){
widget.setChecked(false);
}
}, this);
}
dijit.form.CheckBox.prototype.setChecked.apply(this, arguments);
},
onClick: function(/*Event*/ e){
if(!this.checked){
this.setChecked(true);
}
}
}
);
| NESCent/plhdb | WebRoot/js/dijit/form/CheckBox.js | JavaScript | gpl-3.0 | 3,231 |
angapp.controller('ContPPT2', function($scope){
$scope.empatadas="0";
$scope.ganadas="0";
$scope.perdidas="0";
// $scope.eleccionMaquina="papel";
$scope.comenzar=function(){
numeroSecreto =Math.floor( Math.random()*3)+1;
//alert(numeroSecreto);
switch(numeroSecreto)
{
case 1:
$scope.eleccionMaquina="piedra";
break;
case 2:
$scope.eleccionMaquina="papel";
break;
case 3:
$scope.eleccionMaquina="tijera";
break;
}
}
$scope.verificar=function($eleccion){
$scope.eleccionHumano=$eleccion;
$scope.comenzar();
alert("la maquina selecciono: "+$scope.eleccionMaquina);
if($scope.eleccionHumano==$scope.eleccionMaquina)
{
alert("empate.");
$scope.empatadas++;
}
else{
if($scope.eleccionHumano=="papel")
{
if($scope.eleccionMaquina=="piedra")
{
alert("vos ganastes.");
$scope.ganadas++;
}
else
{
alert("ganó la Maquina.");
$scope.perdidas++;
}
}
if($scope.eleccionHumano=="piedra")
{
if($scope.eleccionMaquina=="tijera")
{
alert("vos ganastes.");
$scope.ganadas++;
}
else
{
alert("ganó la Maquina.");
$scope.perdidas++;
}
}
if($scope.eleccionHumano=="tijera")
{
if($scope.eleccionMaquina=="papel")
{
alert("vos ganastes.");
$scope.ganadas++;
}
else
{
alert("ganó la Maquina.");
$scope.perdidas++;
}
}
}
}
// $scope.papel=function(){
// // alert("hola");
// $scope.comenzar();
// alert("la maquina selecciono: "+$scope.eleccionMaquina);
// $scope.eleccionHumano="papel";
// if($scope.eleccionHumano==$scope.eleccionMaquina)
// {
// alert("empate.");
// $scope.empatadas++;
// }
// else if($scope.eleccionMaquina=="piedra")
// {
// alert("vos ganastes.");
// $scope.ganadas++;
// }
// else
// {
// alert("ganó la Maquina.");
// $scope.perdidas++;
// }
// }
// $scope.tijera=function(){
// // alert("hola");
// $scope.comenzar();
// alert("la maquina selecciono: "+$scope.eleccionMaquina);
// $scope.eleccionHumano="tijera";
// if($scope.eleccionHumano==$scope.eleccionMaquina)
// {
// alert("empate.");
// $scope.empatadas++;
// }
// else if($scope.eleccionMaquina=="papel")
// {
// alert("vos ganastes.");
// $scope.ganadas++;
// }
// else
// {
// alert("ganó la Maquina.");
// $scope.perdidas++;
// }
// }
// $scope.piedra=function(){
// // alert("hola");
// $scope.comenzar();
// alert("la maquina selecciono: "+$scope.eleccionMaquina);
// $scope.eleccionHumano="piedra";
// if($scope.eleccionHumano==$scope.eleccionMaquina)
// {
// alert("empate.");
// $scope.empatadas++;
// }
// else if($scope.eleccionMaquina=="tijera")
// {
// alert("vos ganastes.");
// $scope.ganadas++;
// }
// else
// {
// alert("ganó la Maquina.");
// $scope.perdidas++;
// }
// }
// $scope.papel();
}); | mlcaamano/TP1LAB4 | controladorPPT2.js | JavaScript | gpl-3.0 | 2,864 |
// Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
import sinon from 'sinon';
import 'sinon-as-promised';
import Personal from './personal';
const TEST_INFO = {
'0xfa64203C044691aA57251aF95f4b48d85eC00Dd5': {
name: 'test'
}
};
const TEST_LIST = ['0xfa64203C044691aA57251aF95f4b48d85eC00Dd5'];
function stubApi (accounts, info) {
const _calls = {
accountsInfo: [],
listAccounts: []
};
return {
_calls,
parity: {
accountsInfo: () => {
const stub = sinon.stub().resolves(info || TEST_INFO)();
_calls.accountsInfo.push(stub);
return stub;
}
},
eth: {
accounts: () => {
const stub = sinon.stub().resolves(accounts || TEST_LIST)();
_calls.listAccounts.push(stub);
return stub;
}
}
};
}
function stubLogging () {
return {
subscribe: sinon.stub()
};
}
describe('api/subscriptions/personal', () => {
let api;
let cb;
let logging;
let personal;
beforeEach(() => {
api = stubApi();
cb = sinon.stub();
logging = stubLogging();
personal = new Personal(cb, api, logging);
});
describe('constructor', () => {
it('starts the instance in a stopped state', () => {
expect(personal.isStarted).to.be.false;
});
});
describe('start', () => {
describe('info available', () => {
beforeEach(() => {
return personal.start();
});
it('sets the started status', () => {
expect(personal.isStarted).to.be.true;
});
it('calls parity_accountsInfo', () => {
expect(api._calls.accountsInfo.length).to.be.ok;
});
it('calls eth_accounts', () => {
expect(api._calls.listAccounts.length).to.be.ok;
});
it('updates subscribers', () => {
expect(cb.firstCall).to.have.been.calledWith('eth_accounts', null, TEST_LIST);
expect(cb.secondCall).to.have.been.calledWith('parity_accountsInfo', null, TEST_INFO);
});
});
describe('info not available', () => {
beforeEach(() => {
api = stubApi([], {});
personal = new Personal(cb, api, logging);
return personal.start();
});
it('sets the started status', () => {
expect(personal.isStarted).to.be.true;
});
it('calls personal_accountsInfo', () => {
expect(api._calls.accountsInfo.length).to.be.ok;
});
it('calls personal_listAccounts', () => {
expect(api._calls.listAccounts.length).to.be.ok;
});
});
});
});
| immartian/musicoin | js/src/api/subscriptions/personal.spec.js | JavaScript | gpl-3.0 | 3,180 |
angular.module('askApp')
.directive('ngTap', function() {
return function($scope, $element, $attributes) {
var tapped;
tapped = false;
$element.bind("click", function() {
if (!tapped) {
return $scope.$apply($attributes["ngTap"]);
}
});
$element.bind("touchstart", function(event) {
return tapped = true;
});
$element.bind("touchmove", function(event) {
tapped = false;
return event.stopImmediatePropagation();
});
return $element.bind("touchend", function() {
if (tapped) {
return $scope.$apply($attributes["ngTap"]);
}
});
};
}); | point97/hapifis | server/static/survey/assets/js/directives/tap.js | JavaScript | gpl-3.0 | 738 |
import Ember from 'ember';
import {
validator,
buildValidations
} from 'ember-cp-validations';
var Validations = buildValidations({
campaigntitle: [
validator('presence', true),
validator('length', {
max: 80,
})
],
shortdescription: [
validator('presence', true),
validator('format', {
type: 'name'
})
],
campaigncategory: [
validator('presence', true),
validator('format', {
type: 'name'
})
],
goalamount: [
validator('presence', true),
validator('format', {
regex:/^[0-9.]+$/,
type: 'number'
})
],
startproject: [
validator('presence', true),
validator('format', {
regex:/^[0-9/.]+$/,
type: 'number'
})
],
rewardtitle: [
validator('presence', true),
validator('format', {
regex: /^[A-Za-z/-/-_/ ]+$/
})
],
rewardamount: [
validator('presence', true),
validator('format', {
regex:/^[0-9.]+$/,
type: 'number'
})
],
rewarddescription: [
validator('presence', true),
validator('length', {
max: 160,
})
],
rewardtitle: [
validator('presence', true),
validator('format', {
regex: /^[A-Za-z/-/-_/ ]+$/
})
],
rewardamount: [
validator('presence', true),
validator('format', {
regex:/^[0-9.]+$/,
type: 'number'
})
],
rewarddescription: [
validator('presence', true),
validator('length', {
max: 160,
})
],
});
export default Ember.Controller.extend(Validations,{
showStartResponse: false,
isAddReward: false,
isSaveReward: false,
CampaignCategory: ['Education', 'Children', 'Animal Welfare','Environment','Film','Dance',],
actions: {
type: 'file',
upload: function(e) {
/*const reader = new FileReader();
const file = event.target.files[0];
let imageData;
// Note: reading file is async
reader.onload = () => {
imageData = reader.result;
this.set('data.image', imageData);
// additional logics as you wish
};
if (file) {
reader.readAsDataURL(file);
}*/
var inputFiles = e.target.files;
var imgFile = inputFiles[0];
var formData = new FormData();
formData.append('photo', imgFile);
Ember.$.ajax({
type: 'POST',
url: 'http://localhost:8082/start-campaign/img',
data: formData,
cache: false,
contentType: false,
processData: false,
success: function(data) {
console.log(data);
},
error: function(err) {
console.error(err)
}
})
},
videoupload: function(e) {
/* const reader = new FileReader();
const file = event.target.files[0];
let videoData;
// Note: reading file is async
reader.onload = () => {
videoData = reader.result;
this.set('data.video', videoData)
// additional logics as you wish
};
if (file) {
reader.readAsDataURL(file);
}*/
var inputFiles = e.target.files;
var videoFile = inputFiles[1];
var formData = new FormData();
formData.append('video', videoFile);
Ember.$.ajax({
type: 'POST',
url: 'http://localhost:8082/start-campaign/video',
data: formData,
cache: false,
contentType: false,
processData: false,
success: function(data) {
console.log(data);
},
error: function(err) {
console.error(err)
}
})
},
start: function(){
this.set('showStartResponse', true);
},
regOK: function() {
var mycontroller = this;
mycontroller.set('showRegResponse', false);
mycontroller.transitionToRoute('fund-raiser');
},
dismissModal: function() {
this.set('showStartResponse', false);
},
createCampaign: function() {
},
addRewards: function() {
this.transitionToRoute('addrewards');
},
saveRewards: function() {
var rewardtitle = this.get('rewardtitle');
var rewardamount = this.get('rewardamount');
var rewarddescription = this.get('rewarddescription');
//var deliveryDate = this.get('deliveryDate');
if (rewardtitle === null || rewardtitle === undefined || rewardtitle === "") {
this.set('rewardtitleerrormessage', "field cannot be empty")
//return;
}
if (rewardamount === null || rewardamount === undefined || rewardamount === "") {
this.set('rewardamounterrormessage', "field cannot be empty")
//return;
}
if (rewarddescription === null || rewarddescription === undefined || rewarddescription === "") {
this.set('rewarddescriptionerrormessage', "field cannot be empty")
return;
}
/* let {
rewardtitle,
rewardamount,
rewarddescription,
} = this.getProperties('rewardtitle','rewardamount','rewarddescription');*/
/*if (deliveryDate === null || deliveryDate === undefined || deliveryDate === "") {
this.set('dateerrormessage', "Date field cannot be empty")
return;
}*/
this.set('isAddReward', false);
this.toggleProperty('isSaveReward');
},
toggleModal1: function(e) {
var test = e;
console.log(test);
var campaigntitle = this.get('campaigntitle');
var chosen = this.get('selectedtypes');
var content = this.get('content');
var contents = this.get('contents');
var goalamount = this.get('goalamount');
var startdeliverydate = this.get('startdeliverydate');
var startproject = this.get('startproject');
var enddeliverydate = this.get('enddeliverydate');
if (campaigntitle === null || campaigntitle === undefined || campaigntitle === "") {
this.set('errormessage1', "field cannot be empty")
//this.toggleProperty('isShowingModal');
// return;
}
if (chosen === null || chosen === undefined) {
this.set('errormessage3', "field cannot be empty")
//this.toggleProperty('isShowingModal');
//return;
}
if (content === null || content === undefined || content === "") {
this.set('errormessage2', "field cannot be empty")
//this.toggleProperty('isShowingModal');
// return;
}
if (contents === null || contents === undefined || contents === "") {
this.set('errormessage4', "field cannot be empty")
//this.toggleProperty('isShowingModal');
//return;
}
if (goalamount === null || goalamount === undefined || goalamount === "") {
this.set('errormessage5', "field cannot be empty")
//this.toggleProperty('isShowingModal');
//return;
}
if (startdeliverydate === null || startdeliverydate === undefined || startdeliverydate === "") {
this.set('startdateerrormessage', "Date field cannot be empty")
//return;
}
if (startproject === null || startproject === undefined || startproject === "") {
this.set('startprojecterror', "field cannot be empty")
//return;
}
if (enddeliverydate === null || enddeliverydate === undefined || enddeliverydate === "") {
this.set('enddateerrormessage', "Date field cannot be empty")
//return;
}
if ((campaigntitle === null || campaigntitle === undefined || campaigntitle === "") ||
(chosen === null || chosen === undefined) ||
(content === null || content === undefined || content === "") ||
(contents === null || contents === undefined || contents === "") ||
(goalamount === null || goalamount === undefined || goalamount === "") ||
(startdeliverydate === null || startdeliverydate === undefined || startdeliverydate === "") ||
(startproject === null || startproject === undefined || startproject === "") ||
(enddeliverydate === null || enddeliverydate === undefined || enddeliverydate === "")){
this.toggleProperty('isShowingModal');
}
else{
let {
campaigntitle,
selectedtypes,
content,
contents,
img,
goalamount,
startdeliverydate,
startproject,
enddeliverydate,
rewardtitle,
rewardamount,
rewarddescription
} = this.getProperties('campaigntitle','selectedtypes','content','contents','goalamount','startdeliverydate','startproject','enddeliverydate','rewardtitle','rewardamount','rewarddescription');
// var startdeliverydate =this.get('startdeliverydate');
console.log(JSON.stringify(startdeliverydate));
// var inputFiles = [];
var inputFiles = e.target.files;
var imgFile = inputFiles;
var formData = new FormData();
formData.append('photo', imgFile);
console.log(JSON.stringify(formData));
var inputFiles = e.target.files;
var videoFile = inputFiles;
var myformData = new FormData();
myformData.append('video', videoFile);
var datastring={
"campaign_title":campaigntitle,
"campaign_category":selectedtypes,
"campaign_story":content,
"campaign_discription":content,
"campaign_image":JSON.stringify(formData),
"campaign_video":JSON.stringify(myformData),
"goal_amt":goalamount,
"project_start_date":JSON.stringify(startdeliverydate),
"initial_amount":startproject,
"campaign_end_date":JSON.stringify(enddeliverydate)
}
console.log(JSON.stringify(datastring));
var mycontroller = this;
var uid;
var message;
var mydata ;
//console.log(mydata);
return $.ajax({
url: "http://192.168.0.24:3010/createCampaign",
type: 'POST',
contentType:'application/json',
data:JSON.stringify(datastring),
success:function(response) {
console.log("abc");
console.log(JSON.stringify(response));
message=response.message.message;
console.log(response.message);
//mycontroller.set('uid',uid);
// mycontroller.set('message',message);
//mycontroller.toggleProperty('showRegResponse');
mycontroller.toggleProperty('isShowingModalss');
// mycontroller.set('loading_image_visibility', "hide");
},
error: function(result) {
console.log('DEBUG: GET Enquiries Failed');
//console.log('');
}
});
}
},
home:function(){
this.transitionToRoute('home');
window.location.reload(true);
},
/* home2:function(){
window.location.reload(true);
}*/
}
/*deliveryDate: Ember.computed(function () {
let date = new Date();
date.setDate(date.getDate() + 2);
return date;
})*/
}); | vikramviswanathan/CrowdFundingUI | app/controllers/start-campaign.js | JavaScript | gpl-3.0 | 12,393 |
/**
* A specialized floating Component that supports a drop status icon, {@link Ext.Layer} styles
* and auto-repair. This is the default drag proxy used by all Ext.dd components.
*/
Ext.define('Ext.dd.StatusProxy', {
extend: 'Ext.Component',
animRepair: false,
childEls: [
'ghost'
],
renderTpl: [
'<div class="' + Ext.baseCSSPrefix + 'dd-drop-icon" role="presentation"></div>' +
'<div id="{id}-ghost" class="' + Ext.baseCSSPrefix + 'dd-drag-ghost" role="presentation"></div>'
],
repairCls: Ext.baseCSSPrefix + 'dd-drag-repair',
ariaRole: 'presentation',
/**
* Creates new StatusProxy.
* @param {Object} [config] Config object.
*/
constructor: function(config) {
var me = this;
config = config || {};
Ext.apply(me, {
hideMode: 'visibility',
hidden: true,
floating: true,
id: me.id || Ext.id(),
cls: Ext.baseCSSPrefix + 'dd-drag-proxy ' + this.dropNotAllowed,
shadow: config.shadow || false,
renderTo: Ext.getDetachedBody()
});
me.callParent(arguments);
this.dropStatus = this.dropNotAllowed;
},
/**
* @cfg {String} dropAllowed
* The CSS class to apply to the status element when drop is allowed.
*/
dropAllowed : Ext.baseCSSPrefix + 'dd-drop-ok',
/**
* @cfg {String} dropNotAllowed
* The CSS class to apply to the status element when drop is not allowed.
*/
dropNotAllowed : Ext.baseCSSPrefix + 'dd-drop-nodrop',
/**
* Updates the proxy's visual element to indicate the status of whether or not drop is allowed
* over the current target element.
* @param {String} cssClass The css class for the new drop status indicator image
*/
setStatus : function(cssClass){
cssClass = cssClass || this.dropNotAllowed;
if (this.dropStatus != cssClass) {
this.el.replaceCls(this.dropStatus, cssClass);
this.dropStatus = cssClass;
}
},
/**
* Resets the status indicator to the default dropNotAllowed value
* @param {Boolean} clearGhost True to also remove all content from the ghost, false to preserve it
*/
reset : function(clearGhost){
var me = this,
clsPrefix = Ext.baseCSSPrefix + 'dd-drag-proxy ';
me.el.replaceCls(clsPrefix + me.dropAllowed, clsPrefix + me.dropNotAllowed);
me.dropStatus = me.dropNotAllowed;
if (clearGhost) {
me.ghost.setHtml('');
}
},
/**
* Updates the contents of the ghost element
* @param {String/HTMLElement} html The html that will replace the current innerHTML of the ghost element, or a
* DOM node to append as the child of the ghost element (in which case the innerHTML will be cleared first).
*/
update : function(html){
if (typeof html == "string") {
this.ghost.setHtml(html);
} else {
this.ghost.setHtml('');
html.style.margin = "0";
this.ghost.dom.appendChild(html);
}
var el = this.ghost.dom.firstChild;
if (el) {
Ext.fly(el).setStyle('float', 'none');
}
},
/**
* Returns the ghost element
* @return {Ext.dom.Element} el
*/
getGhost : function(){
return this.ghost;
},
/**
* Hides the proxy
* @param {Boolean} clear True to reset the status and clear the ghost contents,
* false to preserve them
*/
hide : function(clear) {
this.callParent();
if (clear) {
this.reset(true);
}
},
/**
* Stops the repair animation if it's currently running
*/
stop : function(){
if (this.anim && this.anim.isAnimated && this.anim.isAnimated()) {
this.anim.stop();
}
},
/**
* Force the Layer to sync its shadow and shim positions to the element
*/
sync : function(){
this.el.sync();
},
/**
* Causes the proxy to return to its position of origin via an animation.
* Should be called after an invalid drop operation by the item being dragged.
* @param {Number[]} xy The XY position of the element ([x, y])
* @param {Function} callback The function to call after the repair is complete.
* @param {Object} scope The scope (`this` reference) in which the callback function is executed.
* Defaults to the browser window.
*/
repair : function(xy, callback, scope) {
var me = this;
me.callback = callback;
me.scope = scope;
if (xy && me.animRepair !== false) {
me.el.addCls(me.repairCls);
me.el.hideUnders(true);
me.anim = me.el.animate({
duration: me.repairDuration || 500,
easing: 'ease-out',
to: {
x: xy[0],
y: xy[1]
},
stopAnimation: true,
callback: me.afterRepair,
scope: me
});
} else {
me.afterRepair();
}
},
// private
afterRepair : function() {
var me = this;
me.hide(true);
me.el.removeCls(me.repairCls);
if (typeof me.callback == "function") {
me.callback.call(me.scope || me);
}
delete me.callback;
delete me.scope;
}
});
| grgur/Sencha5-Finance | ext/src/dd/StatusProxy.js | JavaScript | gpl-3.0 | 5,507 |
'use strict';
describe('ase.views.recordtype: RelatedAddController', function () {
beforeEach(module('ase.mock.resources'));
beforeEach(module('ase.views.recordtype'));
var $controller;
var $httpBackend;
var $rootScope;
var $scope;
var Controller;
var ResourcesMock;
var recordSchema;
var recordSchemaId;
var recordSchemaIdUrl;
var recordSchemaUrl;
var recordType;
var recordTypeId;
var recordTypeIdUrl;
var StateMock = {
go: angular.noop
};
// Initialize the controller and a mock scope
beforeEach(inject(function (_$controller_, _$httpBackend_, _$rootScope_,
_ResourcesMock_) {
$controller = _$controller_;
$httpBackend = _$httpBackend_;
$rootScope = _$rootScope_;
$scope = $rootScope.$new();
ResourcesMock = _ResourcesMock_;
/* jshint camelcase: false */
recordSchema = {
schema: {
type: 'object',
title: '',
plural_title: '',
description: '',
properties: {},
definitions: {
'Accident Details': {
type: 'object',
title: 'Accident Details',
plural_title: 'Accident Details',
description: 'Details for Accident',
multiple: false,
properties: {},
definitions: {}
}
},
recordType: ResourcesMock.RecordType.uuid
}
};
/* jshint camelcase: true */
recordType = ResourcesMock.RecordType;
recordTypeId = recordType.uuid;
recordTypeIdUrl = new RegExp('api\/recordtypes\/' + recordTypeId);
recordSchemaId = ResourcesMock.RecordSchema.uuid;
recordSchemaIdUrl = new RegExp('api\/recordschemas\/' + recordSchemaId);
recordSchemaUrl = /\/api\/recordschemas\//;
}));
it('should add related content', function () {
$httpBackend.expectGET(recordTypeIdUrl).respond(200, recordType);
$httpBackend.expectPOST(recordSchemaUrl, recordSchema).respond(201);
$httpBackend.expectGET(recordSchemaIdUrl).respond(200, recordSchema);
Controller = $controller('RTRelatedAddController', {
$scope: $scope,
$stateParams: { uuid: recordTypeId },
$state: StateMock
});
$scope.$apply();
Controller.recordType = recordType.uuid;
Controller.currentSchema = recordSchema;
Controller.submitForm();
$scope.$apply();
$httpBackend.flush();
$httpBackend.verifyNoOutstandingRequest();
});
it('should switch view', function () {
$httpBackend.expectGET(recordTypeIdUrl).respond(200, recordType);
$httpBackend.expectPOST(recordSchemaUrl, recordSchema).respond(201);
$httpBackend.expectGET(recordSchemaIdUrl).respond(200, recordSchema);
spyOn(StateMock, 'go');
Controller = $controller('RTRelatedAddController', {
$scope: $scope,
$stateParams: { uuid: recordTypeId },
$state: StateMock
});
$scope.$apply();
Controller.recordType = recordType.uuid;
Controller.currentSchema = recordSchema;
Controller.submitForm();
$scope.$apply();
$httpBackend.flush();
$httpBackend.verifyNoOutstandingRequest();
expect(StateMock.go).toHaveBeenCalled();
});
});
| fungjj92/DRIVER | schema_editor/test/spec/views/recordtype/related-add-controller.spec.js | JavaScript | gpl-3.0 | 3,613 |
var React = require('react');
var ReactDOM = require('react-dom');
var Library = require('./library');
var WebSocket = require('./wsClient');
var config = require('./config');
var LoginDialog = require('./components/LoginDialog.jsx');
var LoadingScreen = require('./components/LoadingScreen.jsx');
var TopRightUI = require('./components/TopRightUI.jsx');
var NavBar = require('./components/NavBar.jsx');
var ControlPanel = require('./components/ControlPanel.jsx');
var SearchPanel = require('./components/SearchPanel.jsx');
var CallDialog = require('./components/CallDialog.jsx');
function App(canvas, defaultLocation) {
this.vl = new Library(this, canvas);
this.currentLocation = defaultLocation;
this.renderNavBar();
this.initWS();
}
App.prototype.constructor = App;
App.prototype.vl = null;
App.prototype.initWS = function () {
this.ws = new WebSocket(
function onConnected() {
this.navBar.setOnlineIndicator();
this.ws.joinAsUser(function () {
console.log('Joined as user');
});
}.bind(this),
function onDisconnected() {
this.navBar.setOfflineIndicator();
}.bind(this),
function onError(error) {
this.navBar.setOfflineIndicator();
}.bind(this)
);
this.ws.connect();
};
App.prototype.renderNavBar = function () {
ReactDOM.unmountComponentAtNode(document.getElementById('page-header'));
this.navBar = ReactDOM.render(React.createElement(NavBar, {
location: this.currentLocation,
onWarpTo: function (location) {
this.loadLocation(location);
}.bind(this),
onNavigation: function () {
this.renderControlPanel();
}.bind(this),
onChangeCamera: function () {
this.vl.switchViewMode();
}.bind(this),
onAbout: function () {
}.bind(this),
onCall: function () {
this.renderCallPanel();
}.bind(this),
onSearch: function (query) {
this.renderSearchPanel(query);
}.bind(this)
}), document.getElementById('page-header'));
};
App.prototype.renderControlPanel = function () {
ReactDOM.unmountComponentAtNode(document.getElementById('ui'));
this.controlPanel = ReactDOM.render(React.createElement(ControlPanel, {
location: this.currentLocation,
onNavigateTo: function (destination) {
console.log('Show me path to ' + destination);
this.vl.findPath(destination);
}.bind(this)
}), document.getElementById('ui'));
};
App.prototype.renderSearchPanel = function (query) {
ReactDOM.unmountComponentAtNode(document.getElementById('ui'));
this.searchPanel = ReactDOM.render(React.createElement(SearchPanel, {
search: query,
onCheckPath: function (book) {
return this.vl.findBookShelf(book);
}.bind(this),
onShowPath: function (shelf) {
this.vl.findPath(shelf);
}.bind(this)
}), document.getElementById('ui'));
};
App.prototype.renderLoginPanel = function () {
ReactDOM.unmountComponentAtNode(document.getElementById('ui'));
ReactDOM.render(React.createElement(LoginDialog, {
tundra: false,
onConnect: this.vl.onConnectedToServer.bind(this.vl),
onError: this.vl.onConnectionError.bind(this.vl),
onDisconnect: this.vl.onDisconnectedFromServer.bind(this.vl)
}), document.getElementById('ui'));
};
App.prototype.renderCallPanel = function () {
ReactDOM.unmountComponentAtNode(document.getElementById('ui'));
ReactDOM.render(React.createElement(CallDialog, {
startCall: this.ws.requestCall.bind(this.ws),
stopCall: this.ws.stopCall.bind(this.ws)
}), document.getElementById('ui'));
};
App.prototype.loadInitialLocation = function () {
ReactDOM.unmountComponentAtNode(document.getElementById('ui'));
var loading = ReactDOM.render(React.createElement(LoadingScreen), document.getElementById('ui'));
this.vl.loadLibrary(this.currentLocation,
function onProgress(loaded, total) {
var ratio = Math.round(loaded / total * 100);
if (ratio >= 100) {
loading.updateProgress(ratio, 'Setting things up');
}
else {
loading.updateProgress(ratio);
}
},
function onLoad() {
loading.hide();
this.vl.enableBlur();
this.renderLoginPanel();
}.bind(this)
);
};
App.prototype.loadLocation = function (location, asAvatar = false) {
this.currentLocation = location;
if (asAvatar) {
// Hide NavBar
this.navBar.hide();
}
else {
this.navBar.setCurrentLocation(this.currentLocation);
}
ReactDOM.unmountComponentAtNode(document.getElementById('ui'));
var loading = ReactDOM.render(React.createElement(LoadingScreen), document.getElementById('ui'));
this.vl.loadLibrary(location,
function onProgress(loaded, total) {
var ratio = Math.round(loaded / total * 100);
if (ratio >= 100) {
loading.updateProgress(ratio, 'Setting things up');
}
else {
loading.updateProgress(ratio);
}
},
function onLoad() {
loading.hide();
if (asAvatar) this.vl.switchViewMode();
}.bind(this)
);
}
module.exports = App;
| tosh823/vl16 | src/client/app.js | JavaScript | gpl-3.0 | 5,018 |
var searchData=
[
['location',['Location',['../classPowerUp.html#a3f782c5a32f79a41d00a759c42121a31',1,'PowerUp']]]
];
| isaaclacoba/tinman | doxygen/search/typedefs_3.js | JavaScript | gpl-3.0 | 120 |
$(document).ready(function() {
now = new Date("2014-12-08T14:37:11");
loadStateData()
loadRoomData();
replaceSVG();
loadFileLocally()
//loadFileFromServer();
data = [];
for (var i = 0; i < raw.feed.entry.length; i++) {
var surgeryRaw = raw.feed.entry[i];
if (surgeryRaw.gsx$details.$t == "TRUE") {
var surgery = {
"Name" : surgeryRaw.gsx$name.$t,
"Prename" : surgeryRaw.gsx$prename.$t,
"Birthdate" : surgeryRaw.gsx$birthdate.$t,
"Service" : surgeryRaw.gsx$service.$t,
"Case_Id" : surgeryRaw.gsx$caseid.$t,
"Surgery_Team" : surgeryRaw.gsx$surgeryteam.$t,
"Surgery_Room" : surgeryRaw.gsx$surgeryroom.$t,
"Current_State" : surgeryRaw.gsx$currentstate.$t,
"Starttime" : surgeryRaw.gsx$starttime.$t,
"Endtime" : surgeryRaw.gsx$endtime.$t,
"Patient_Id" : surgeryRaw.gsx$patientid.$t,
"Station" : surgeryRaw.gsx$station.$t,
"Station_Phone" : surgeryRaw.gsx$stationphone.$t,
"Station_Room" : surgeryRaw.gsx$stationroom.$t,
"Diagnosis" : surgeryRaw.gsx$diagnosis.$t,
"Risk" : surgeryRaw.gsx$risk.$t,
"Comment" : surgeryRaw.gsx$comment.$t,
"Timestamps" : [
surgeryRaw.gsx$state1timestamp.$t,
surgeryRaw.gsx$state2timestamp.$t,
surgeryRaw.gsx$state3timestamp.$t,
surgeryRaw.gsx$state4timestamp.$t,
surgeryRaw.gsx$state5timestamp.$t,
surgeryRaw.gsx$state6timestamp.$t,
surgeryRaw.gsx$state7timestamp.$t,
surgeryRaw.gsx$state8timestamp.$t,
surgeryRaw.gsx$state9timestamp.$t,
surgeryRaw.gsx$state10timestamp.$t,
surgeryRaw.gsx$state11timestamp.$t
],
"Details" : true
}
} else {
var surgery = {
"Name" : surgeryRaw.gsx$name.$t,
"Prename" : surgeryRaw.gsx$prename.$t,
"Birthdate" : surgeryRaw.gsx$birthdate.$t,
"Service" : surgeryRaw.gsx$service.$t,
"Case_Id" : surgeryRaw.gsx$caseid.$t,
"Surgery_Team" : surgeryRaw.gsx$surgeryteam.$t,
"Surgery_Room" : surgeryRaw.gsx$surgeryroom.$t,
"Current_State" : surgeryRaw.gsx$currentstate.$t,
"Starttime" : surgeryRaw.gsx$starttime.$t,
"Endtime" : surgeryRaw.gsx$endtime.$t,
"Details" : false
};
}
data.push(surgery);
}
// Scroll to schedule
var size = $("main").outerHeight();
$("main article").css("top", -1 * size);
});
function loadStateData() {
// Get json-file
var request = new XMLHttpRequest();
request.open("GET", "data/states.json", false);
request.send(null);
// Put json-file into an array
states = JSON.parse(request.responseText);
}
function replaceSVG() {
$('img.svg').each(function(){
var $img = jQuery(this);
var imgID = $img.attr('id');
var imgClass = $img.attr('class');
var imgURL = $img.attr('src');
jQuery.get(imgURL, function(data) {
// Get the SVG tag, ignore the rest
var $svg = jQuery(data).find('svg');
// Add replaced image's ID to the new SVG
if(typeof imgID !== 'undefined') {
$svg = $svg.attr('id', imgID);
}
// Add replaced image's classes to the new SVG
if(typeof imgClass !== 'undefined') {
$svg = $svg.attr('class', imgClass+' replaced-svg');
}
// Remove any invalid XML tags as per http://validator.w3.org
$svg = $svg.removeAttr('xmlns:a');
// Replace image with new SVG
$img.replaceWith($svg);
}, 'xml');
});
}
function loadRoomData() {
// Get json-file
var request = new XMLHttpRequest();
request.open("GET", "data/rooms.json", false);
request.send(null);
// Put json-file into an array
rooms = JSON.parse(request.responseText);
}
function loadFileFromServer() {
// Get json-file
var request = new XMLHttpRequest();
request.open("GET", "https://spreadsheets.google.com/feeds/list/1oiiPeRnUPX32MkmG8NFB0IauLrWtjoiEMQsE0sCRQ6I/od6/public/values?alt=json", false);
request.send(null);
// Put json-file into an array
raw = JSON.parse(request.responseText);
}
function loadFileLocally() {
// Get json-file
var request = new XMLHttpRequest();
request.open("GET", "data/surgeries.json", false);
request.send(null);
// Put json-file into an array
raw = JSON.parse(request.responseText);
}
| ChristophLabacher/OPMS-Surgery-Management-System | src/scripts/setup.js | JavaScript | gpl-3.0 | 4,074 |
#!/usr/bin/env node
/**
* @file Handles postinstall tasks.
*/
var fs = require('fs'),
path = require('path'),
childProcess = require('child_process'), // eslint-disable-line security/detect-child-process
chalk = require('chalk'),
bcryptPath = path.resolve('node_modules', 'bcrypt');
// eslint-disable-next-line no-process-env
if (process.platform === 'win32' && !process.env.APPVEYOR) { // the bcrypt issue is only prevalent on Microsoft Windows
console.info(chalk.blue.bold('Running on a Windows platform, installing bcryptjs instead of bcrypt'));
childProcess.exec('npm i bcryptjs', function () {
fs.rename(`${bcryptPath}s`, bcryptPath, function () {
console.info('bcryptjs has been installed to replace bcrypt');
});
});
}
| kunagpal/express-boilerplate | scripts/misc/postInstall.js | JavaScript | gpl-3.0 | 748 |
import { oneLine } from 'common-tags';
import { apiToMessage, i18n } from 'utils';
export const JS_SYNTAX_ERROR = {
code: 'JS_SYNTAX_ERROR',
message: i18n._('JavaScript syntax error'),
description: i18n._(oneLine`There is a JavaScript syntax error in your
code; validation cannot continue on this file.`),
};
export const EVENT_LISTENER_FOURTH = {
code: 'EVENT_LISTENER_FOURTH',
message: i18n._('addEventListener` called with truthy fourth argument.'),
description: i18n._(oneLine`When called with a truthy forth argument,
listeners can be triggered potentially unsafely by untrusted code. This
requires careful review.`),
};
export const CONTENT_SCRIPT_NOT_FOUND = {
code: 'CONTENT_SCRIPT_NOT_FOUND',
legacyCode: null,
message: i18n._('Content script file could not be found.'),
description: i18n._('Content script file could not be found'),
};
export const CONTENT_SCRIPT_EMPTY = {
code: 'CONTENT_SCRIPT_EMPTY',
legacyCode: null,
message: i18n._('Content script file name should not be empty.'),
description: i18n._('Content script file name should not be empty'),
};
export function _nonLiteralUri(method) {
return {
code: `${method}_NONLIT_URI`.toUpperCase(),
message: i18n._(`'${method}' called with a non-literal uri`),
description: i18n._(oneLine`Calling '${method}' with variable
parameters can result in potential security vulnerabilities if the
variable contains a remote URI. Consider using 'window.open' with
the 'chrome=no' flag.`),
};
}
export function _methodPassedRemoteUri(method) {
return {
code: `${method}_REMOTE_URI`.toUpperCase(),
message: i18n._(`'${method}' called with non-local URI`),
description: i18n._(oneLine`Calling '${method}' with a non-local
URI will result in the dialog being opened with chrome privileges.`),
};
}
export const OPENDIALOG_REMOTE_URI = _methodPassedRemoteUri('openDialog');
export const OPENDIALOG_NONLIT_URI = _nonLiteralUri('openDialog');
export const DANGEROUS_EVAL = {
code: 'DANGEROUS_EVAL',
message: null,
description: i18n._(oneLine`Evaluation of strings as code can lead to
security vulnerabilities and performance issues, even in the
most innocuous of circumstances. Please avoid using \`eval\` and the
\`Function\` constructor when at all possible.'`),
};
export const NO_IMPLIED_EVAL = {
code: 'NO_IMPLIED_EVAL',
message: null,
description: i18n._(oneLine`setTimeout, setInterval and execScript
functions should be called only with function expressions as their
first argument`),
};
export const UNEXPECTED_GLOGAL_ARG = {
code: 'UNEXPECTED_GLOGAL_ARG',
message: i18n._('Unexpected global passed as an argument'),
description: i18n._(oneLine`Passing a global as an argument
is not recommended. Please make this a var instead.`),
};
export const NO_DOCUMENT_WRITE = {
code: 'NO_DOCUMENT_WRITE',
message: i18n._('Use of document.write strongly discouraged.'),
description: i18n._(oneLine`document.write will fail in many
circumstances when used in extensions, and has potentially severe security
repercussions when used improperly. Therefore, it should not be used.`),
};
export const BANNED_LIBRARY = {
code: 'BANNED_LIBRARY',
message: i18n._('Banned 3rd-party JS library'),
description: i18n._(oneLine`Your add-on uses a JavaScript library we
consider unsafe. Read more: https://bit.ly/1TRIyZY`),
};
export const UNADVISED_LIBRARY = {
code: 'UNADVISED_LIBRARY',
message: i18n._('Unadvised 3rd-party JS library'),
description: i18n._(oneLine`Your add-on uses a JavaScript library we do
not recommend. Read more: https://bit.ly/1TRIyZY`),
};
export const KNOWN_LIBRARY = {
code: 'KNOWN_LIBRARY',
message: i18n._('Known JS library detected'),
description: i18n._(oneLine`JavaScript libraries are discouraged for
simple add-ons, but are generally accepted.`),
};
export const UNSAFE_DYNAMIC_VARIABLE_ASSIGNMENT = {
code: 'UNSAFE_VAR_ASSIGNMENT',
// Uses original message from eslint
message: null,
description: i18n._(oneLine`Due to both security and performance
concerns, this may not be set using dynamic values which have
not been adequately sanitized. This can lead to security issues or fairly
serious performance degradation.`),
};
export const UNSUPPORTED_API = {
code: 'UNSUPPORTED_API',
message: null,
messageFormat: i18n._('{{api}} is not supported'),
description: i18n._('This API has not been implemented by Firefox.'),
};
function deprecatedAPI(api) {
return {
code: apiToMessage(api),
message: i18n._(`"${api}" is deprecated or unimplemented`),
description: i18n._(oneLine`This API has been deprecated by Chrome
and has not been implemented by Firefox.`),
};
}
export const APP_GETDETAILS = deprecatedAPI('app.getDetails');
export const EXT_ONREQUEST = deprecatedAPI('extension.onRequest');
export const EXT_ONREQUESTEXTERNAL = deprecatedAPI(
'extension.onRequestExternal'
);
export const EXT_SENDREQUEST = deprecatedAPI('extension.sendRequest');
export const TABS_GETALLINWINDOW = deprecatedAPI('tabs.getAllInWindow');
export const TABS_GETSELECTED = deprecatedAPI('tabs.getSelected');
export const TABS_ONACTIVECHANGED = deprecatedAPI('tabs.onActiveChanged');
export const TABS_ONSELECTIONCHANGED = deprecatedAPI('tabs.onSelectionChanged');
export const TABS_SENDREQUEST = deprecatedAPI('tabs.sendRequest');
function temporaryAPI(api) {
return {
code: apiToMessage(api),
message: i18n._(`"${api}" can cause issues when loaded temporarily`),
description: i18n._(oneLine`This API can cause issues when loaded
temporarily using about:debugging in Firefox unless you specify
applications|browser_specific_settings > gecko > id in the manifest.
Please see: https://mzl.la/2hizK4a for more.`),
};
}
export const STORAGE_LOCAL = temporaryAPI('storage.local');
export const STORAGE_SYNC = temporaryAPI('storage.sync');
export const IDENTITY_GETREDIRECTURL = temporaryAPI('identity.getRedirectURL');
export const INCOMPATIBLE_API = {
code: 'INCOMPATIBLE_API',
message: null,
messageFormat: i18n._(
'{{api}} is not supported in Firefox version {{minVersion}}'
),
description: i18n._(
'This API is not implemented by the given minimum Firefox version'
),
};
export const ANDROID_INCOMPATIBLE_API = {
code: 'ANDROID_INCOMPATIBLE_API',
message: null,
messageFormat: i18n._(
'{{api}} is not supported in Firefox for Android version {{minVersion}}'
),
description: i18n._(
'This API is not implemented by the given minimum Firefox for Android version'
),
};
export const ESLINT_OVERWRITE_MESSAGE = {
'no-eval': DANGEROUS_EVAL,
'no-implied-eval': NO_IMPLIED_EVAL,
'no-new-func': DANGEROUS_EVAL,
'no-unsafe-innerhtml/no-unsafe-innerhtml': UNSAFE_DYNAMIC_VARIABLE_ASSIGNMENT,
'webextension-unsupported-api': UNSUPPORTED_API,
'webextension-api-compat': INCOMPATIBLE_API,
'webextension-api-compat-android': ANDROID_INCOMPATIBLE_API,
};
| mozilla/addons-validator | src/messages/javascript.js | JavaScript | mpl-2.0 | 7,036 |
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is JavaScript Engine testing utilities.
*
* The Initial Developer of the Original Code is
* Mozilla Foundation.
* Portions created by the Initial Developer are Copyright (C) 2006
* the Initial Developer. All Rights Reserved.
*
* Contributor(s): Biju
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
var gTestfile = 'regress-333541.js';
//-----------------------------------------------------------------------------
var BUGNUMBER = 333541;
var summary = '1..toSource()';
var actual = '';
var expect = '';
printBugNumber(BUGNUMBER);
printStatus (summary);
function a(){
return 1..toSource();
}
try
{
expect = 'function a() {\n return (1).toSource();\n}';
actual = a.toString();
compareSource(expect, actual, summary + ': 1');
}
catch(ex)
{
actual = ex + '';
reportCompare(expect, actual, summary + ': 1');
}
try
{
expect = 'function a() {return (1).toSource();}';
actual = a.toSource();
compareSource(expect, actual, summary + ': 2');
}
catch(ex)
{
actual = ex + '';
reportCompare(expect, actual, summary + ': 2');
}
expect = a;
actual = a.valueOf();
reportCompare(expect, actual, summary + ': 3');
try
{
expect = 'function a() {\n return (1).toSource();\n}';
actual = "" + a;
compareSource(expect, actual, summary + ': 4');
}
catch(ex)
{
actual = ex + '';
reportCompare(expect, actual, summary + ': 4');
}
function b(){
x=1..toSource();
x=1['a'];
x=1..a;
x=1['"a"'];
x=1["'a'"];
x=1['1'];
x=1["#"];
}
try
{
expect = "function b() {\n x = (1).toSource();\n" +
" x = (1).a;\n" +
" x = (1).a;\n" +
" x = (1)['\"a\"'];\n" +
" x = (1)[\'\\'a\\''];\n" +
" x = (1)['1'];\n" +
" x = (1)['#'];\n" +
"}";
actual = "" + b;
compareSource(expect, actual, summary + ': 5');
}
catch(ex)
{
actual = ex + '';
reportCompare(expect, actual, summary + ': 5');
}
| tmhorne/celtx | js/tests/js1_5/extensions/regress-333541.js | JavaScript | mpl-2.0 | 3,351 |
/* -*- Mode: javascript; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* 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/. */
/*
*
* Date: 21 January 2003
* SUMMARY: Regression test for bug 189898
* See http://bugzilla.mozilla.org/show_bug.cgi?id=189898
*
*/
//-----------------------------------------------------------------------------
var gTestfile = 'regress-189898.js';
var UBound = 0;
var BUGNUMBER = 189898;
var summary = 'Regression test for bug 189898';
var status = '';
var statusitems = [];
var actual = '';
var actualvalues = [];
var expect= '';
var expectedvalues = [];
status = inSection(1);
actual = 'XaXY'.replace('XY', '--')
expect = 'Xa--';
addThis();
status = inSection(2);
actual = '$a$^'.replace('$^', '--')
expect = '$a--';
addThis();
status = inSection(3);
actual = 'ababc'.replace('abc', '--')
expect = 'ab--';
addThis();
status = inSection(4);
actual = 'ababc'.replace('abc', '^$')
expect = 'ab^$';
addThis();
/*
* Same as above, but providing a regexp in the first parameter
* to String.prototype.replace() instead of a string.
*
* See http://bugzilla.mozilla.org/show_bug.cgi?id=83293
* for subtleties on this issue -
*/
status = inSection(5);
actual = 'XaXY'.replace(/XY/, '--')
expect = 'Xa--';
addThis();
status = inSection(6);
actual = 'XaXY'.replace(/XY/g, '--')
expect = 'Xa--';
addThis();
status = inSection(7);
actual = '$a$^'.replace(/\$\^/, '--')
expect = '$a--';
addThis();
status = inSection(8);
actual = '$a$^'.replace(/\$\^/g, '--')
expect = '$a--';
addThis();
status = inSection(9);
actual = 'ababc'.replace(/abc/, '--')
expect = 'ab--';
addThis();
status = inSection(10);
actual = 'ababc'.replace(/abc/g, '--')
expect = 'ab--';
addThis();
status = inSection(11);
actual = 'ababc'.replace(/abc/, '^$')
expect = 'ab^$';
addThis();
status = inSection(12);
actual = 'ababc'.replace(/abc/g, '^$')
expect = 'ab^$';
addThis();
//-----------------------------------------------------------------------------
test();
//-----------------------------------------------------------------------------
function addThis()
{
statusitems[UBound] = status;
actualvalues[UBound] = actual;
expectedvalues[UBound] = expect;
UBound++;
}
function test()
{
enterFunc('test');
printBugNumber(BUGNUMBER);
printStatus(summary);
for (var i=0; i<UBound; i++)
{
reportCompare(expectedvalues[i], actualvalues[i], statusitems[i]);
}
exitFunc ('test');
}
| mozilla/rhino | testsrc/tests/ecma_3/String/regress-189898.js | JavaScript | mpl-2.0 | 2,623 |
/* -*- Mode: javascript; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* 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/. */
var gTestfile = 'regress-349962.js';
//-----------------------------------------------------------------------------
var BUGNUMBER = 349962;
var summary = 'let variable bound to nested function expressions'
var actual = 'No Crash';
var expect = 'No Crash';
//-----------------------------------------------------------------------------
test();
//-----------------------------------------------------------------------------
function test()
{
enterFunc ('test');
printBugNumber(BUGNUMBER);
printStatus (summary);
(function() { let z = (function () { function a() { } })(); })()
reportCompare(expect, actual, summary);
exitFunc ('test');
}
| mozilla/rhino | testsrc/tests/js1_7/block/regress-349962.js | JavaScript | mpl-2.0 | 954 |
/**
* Created by slanska on 2016-10-04.
*/
"use strict";
var authentication = require('feathers-authentication/client');
/*
Tests directly on database (no http server involved).
Uses local SQLite database
*/
describe('DB access', function () {
it('load user admin using cache', function (done) {
});
it('load system admin using cache', function (done) {
});
});
//# sourceMappingURL=01_DBController.js.map | slanska/nauth2 | test/01_DBController.js | JavaScript | mpl-2.0 | 426 |
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
"use strict";
add_task(function*() {
info("Check that toggleable toolbars dropdown in always shown");
info("Remove all possible custom toolbars");
yield removeCustomToolbars();
info("Enter customization mode");
yield startCustomizing();
let toolbarsToggle = document.getElementById("customization-toolbar-visibility-button");
ok(toolbarsToggle, "The toolbars toggle dropdown exists");
ok(!toolbarsToggle.hasAttribute("hidden"),
"The toolbars toggle dropdown is displayed");
});
add_task(function* asyncCleanup() {
info("Exit customization mode");
yield endCustomizing();
});
| Yukarumya/Yukarum-Redfoxes | browser/components/customizableui/test/browser_1058573_showToolbarsDropdown.js | JavaScript | mpl-2.0 | 811 |
import mongoose from 'mongoose'
const URLSchema = mongoose.Schema({
urlid: {type: Number, required: true},
urllink: {type: String, required: true}
})
const UrlModel = mongoose.model('url', URLSchema)
export default UrlModel
| jonniebigodes/freecodecampApiChallenges | src/models/Urls.model.js | JavaScript | mpl-2.0 | 231 |
/*
* Copyright 2013-2014 Biz Tech (http://www.biztech.it). All rights reserved.
*
* 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/.
*
* Covered Software is provided under this License on an “as is” basis,
* without warranty of any kind, either expressed, implied, or statutory,
* including, without limitation, warranties that the Covered Software is
* free of defects, merchantable, fit for a particular purpose or non-infringing.
* The entire risk as to the quality and performance of the Covered Software is with You.
* Should any Covered Software prove defective in any respect, You (not any Contributor)
* assume the cost of any necessary servicing, repair, or correction.
* This disclaimer of warranty constitutes an essential part of this License.
* No use of any Covered Software is authorized under this License except under this disclaimer.
*
* Initial contributors: Luca Pazzaglia, Massimo Bonometto
*/
var bt = bt || {};
bt.Query = function(properties, olapCube) {
var defaults = {
cube: "",
dimensions: [],
measures: [],
pivotDimensions: [],
filters: [],
measuresOnColumns: true,
nonEmpty: {
columns: true,
rows: true
},
summary: {
grandTotal: true,
subTotals: true,
pivotGrandTotal: true,
pivotSubTotals: true,
position: "bottom"
},
orders: []
};
var myself = {};
var settings = $.extend({}, defaults, properties);
var history = [];
var hstFM = [];
var hstOM = [];
var definition = {
cube: settings.cube,
dimensions: settings.dimensions,
measures: settings.measures,
pivotDimensions: settings.pivotDimensions,
filters: settings.filters,
orders: settings.orders
}
var extMeasurePH = {
"$PercTot": {
"formula": "(§M/ SUM(§AllRowsSetNoTotals , §M))",
"caption": "§M %",
"format": "0.00%"
},
"$PercLastDim": {
"formula": "(§M/ SUM(§AllRowsSetNoLastDim , §M))",
"caption": "§M %",
"format": "0.00%"
}
}
var measuresAttr = [];
myself.loadMeasuresAttr = function() {
$.each(definition.measures, function(i, v) {
measuresAttr[i] = {};
if (v[1] != "") {
measuresAttr[i] = v[1].substring(0,1) == "$" ? extMeasurePH[v[1]] : JSON.parse(v[1]);
measuresAttr[i] = JSON.parse(JSON.stringify(measuresAttr[i]).replace(/§M/g,v[0]));
}
});
}
myself.loadMeasuresAttr();
myself.getMeasuresAttr = function() {
return measuresAttr;
}
// If a hierarchy is found in both filters and dimensions, it moves the filtered levels of that hierarchy from filters to dimensions
var normalizeDefinition = function() {
var hierarchiesInDimensions = $.map(definition.dimensions, function(e, i) { return (e[0].split("].[")[0] + "]").replace("]]", "]"); });
var hierarchiesInPivotDimensions = $.map(definition.pivotDimensions, function(e, i) { return (e[0].split("].[")[0] + "]").replace("]]", "]"); });
var newFilters = [];
$.each(definition.filters, function(i, f) {
var filterLevel = f[0];
var filterHierarchy = (filterLevel.split("].[")[0] + "]").replace("]]", "]");
if($.inArray(filterHierarchy, hierarchiesInDimensions) > -1) {
var filterLevelDepth = olapCube.getLevelDepth(filterLevel);
var index = -1;
var side = "";
$.each(definition.dimensions, function(i, d) {
var dimensionLevel = d[0];
if((filterLevel.split("].[")[0] + "]").replace("]]", "]") == (dimensionLevel.split("].[")[0] + "]").replace("]]", "]")) {
index = i;
dimensionLevelDepth = olapCube.getLevelDepth(dimensionLevel);
if(dimensionLevelDepth < filterLevelDepth)
side = "right";
else
side = "left";
}
});
index += side == "right" ? 1 : 0;
definition.dimensions.splice(index, 0, f);
}
else if($.inArray(filterHierarchy, hierarchiesInPivotDimensions) > -1) {
var filterLevelDepth = olapCube.getLevelDepth(filterLevel);
var index = -1;
var side = "";
$.each(definition.pivotDimensions, function(i, d) {
var dimensionLevel = d[0];
if(dimensionLevel != "MEASURES") {
if((filterLevel.split("].[")[0] + "]").replace("]]", "]") == (dimensionLevel.split("].[")[0] + "]").replace("]]", "]")) {
index = i;
dimensionLevelDepth = olapCube.getLevelDepth(dimensionLevel);
if(dimensionLevelDepth < filterLevelDepth)
side = "right";
else
side = "left";
}
}
});
index += side == "right" ? 1 : 0;
definition.pivotDimensions.splice(index, 0, f);
}
else {
newFilters.push(f);
}
});
definition.filters = newFilters;
}();
myself.validate = function(olapCube) {
// At least one dimension and one measure!
// No measures in filter!
// The same hierarchy can't be in two different axis!
// Levels of a same hierarchy have to be adjacent and in order of increasing depth!
// Only one "MEASURES" placeholder in pivot dimensions!
}
myself.getPlainFilter = function(levelQualifiedName) {
var result = "";
var lQn = levelQualifiedName;
var hQn = (lQn.split("].[")[0] + "]").replace("]]", "]");
var boundToDashboard = filtersMap.synchronizedByParameters;
var isCalculatedMember = lQn.indexOf("].[") < 0;
var level = isCalculatedMember ? filtersMap.hierarchies[hQn].calculatedMembers : filtersMap.hierarchies[hQn].levels[lQn];
if(level.filtered) {
var filterMode = level.filterMode + (level.uniqueNames ? "_un" : "");
var members = null;
if(boundToDashboard && level.synchronizedByParameters) {
var filterExpression = level.initialFilterExpression;
var param = filterExpression.replace(filterMode + ":", "");
var members = Dashboards.getParameterValue(param);
} else {
members = level.members;
}
result = filterMode + ":[" + ( $.isArray(members) ? members.join("],[") : members ) + "]";
}
return result;
}
var getMdxFilter = function(levelQualifiedName, hierarchyQualifiedName) {
var mdx = "";
var lQn = levelQualifiedName;
var hQn = !hierarchyQualifiedName ? (lQn.split("].[")[0] + "]").replace("]]", "]") : hierarchyQualifiedName;
var boundToDashboard = filtersMap.synchronizedByParameters;
var isCalculatedMember = lQn.indexOf("].[") < 0;
//var level = filtersMap.hierarchies[hQn].levels[lQn];
var level = isCalculatedMember ? filtersMap.hierarchies[hQn].calculatedMembers : filtersMap.hierarchies[hQn].levels[lQn];
if(level.filtered) {
var filterMode = level.filterMode;
var include = filterMode == "include";
var exclude = filterMode == "exclude";
var between = filterMode == "between";
var uniqueNames = level.uniqueNames;
if(uniqueNames) filterMode += "_un";
var members = null;
if(boundToDashboard && level.synchronizedByParameters) {
var filterExpression = level.initialFilterExpression;
var param = filterExpression.replace(filterMode + ":", "");
members = Dashboards.getParameterValue(param);
} else {
members = level.members;
}
if($.isArray(members)) {
members = $.map(members, function(e) {
return e.replace(/[']/g, "''");
});
} else {
members = members.replace(/[']/g, "''");
}
var separator = between ? " :" : ",";
if(uniqueNames) {
mdx = $.isArray(members) ? members.join(separator + " ") : members;
mdx = "{" + mdx + "}";
} else {
if(between) {
//mdx = "{Head(Filter({" + lQn + ".Members}, (" + lQn + ".CurrentMember.Name = \"" + members[0] + "\")), 1).Item(0) : Tail(Filter({" + lQn + ".Members}, (" + lQn + ".CurrentMember.Name = \"" + members[1] + "\")), 1).Item(0)}";
mdx = "Filter({" + lQn + ".Members}, (" + lQn + ".CurrentMember.Name >= \"" + members[0] + "\" AND " + lQn + ".CurrentMember.Name <= \"" + members[1] + "\"))";
} else {
mdx = $.isArray(members) ? members.join("\" OR " + lQn + ".CurrentMember.Name = \"") : members;
mdx = "Filter({" + lQn + ".Members}, (" + lQn + ".CurrentMember.Name = \"" + mdx + "\"))";
}
}
if(exclude)
mdx = "Except(" + lQn + ".Members, " + mdx + ")";
if(members.length == 0 || mdx.indexOf(".[]") > -1 || mdx.indexOf(".[All]") > -1 || mdx.indexOf("\"All\"") > -1)
mdx = "";
}
return mdx;
}
myself.getMdx = function() {
// Levels of a same hierarchy have to be adjacent and in order of increasing depth!
var dimensionHierarchies = [];
var pivotHierarchies = [];
var filterHierarchies = [];
var pivotHierarchyBeforeMeasures = "";
var addLevelToHierarchy = function(levelObj, hierarchyObjs) {
var hierarchyIndex = $.map(hierarchyObjs, function(hierarchy, index) {
if(hierarchy.name == levelObj.hierarchy)
return index;
});
if(hierarchyIndex.length > 0) {
hierarchyObjs[hierarchyIndex[0]].levels.push(levelObj);
} else {
hierarchyObjs.push({
name: levelObj.hierarchy,
levels: new Array(levelObj)
});
}
}
$.each(definition.dimensions, function(i, v) {
var qualifiedName = v[0];
var qnParts = qualifiedName.substring(1, qualifiedName.length -1).split("].[");
var hierarchy = qnParts[0];
var level = qnParts.length < 2 ? "" : qnParts[1];
addLevelToHierarchy({
hierarchy: hierarchy,
name: level,
qualifiedName: qualifiedName
}, dimensionHierarchies);
});
var previousHierarchyName = "";
$.each(definition.pivotDimensions, function(i, v) {
var qualifiedName = v[0];
if(qualifiedName == "MEASURES") {
pivotHierarchyBeforeMeasures = i == 0 ? "NONE" : previousHierarchyName;
} else {
var qnParts = qualifiedName.substring(1, qualifiedName.length -1).split("].[");
var hierarchy = qnParts[0];
var level = qnParts.length < 2 ? "" : qnParts[1];
addLevelToHierarchy({
hierarchy: hierarchy,
name: level,
qualifiedName: qualifiedName
}, pivotHierarchies);
previousHierarchyName = hierarchy;
}
});
var invalidHierarchies = $.map(dimensionHierarchies, function(e) {
return "[" + e.name + "]";
}).concat($.map(pivotHierarchies, function(e) {
return "[" + e.name + "]";
}));
//console.log(invalidHierarchies);
for(var key in filtersMap.hierarchies) {
if($.inArray(key, invalidHierarchies) < 0) {
var hierarchy = filtersMap.hierarchies[key];
var levels = hierarchy.levels;
$.each(hierarchy.order, function(i, v) {
if(levels[v].filtered) {
var qn = v;
var qnParts = qn.substring(1, qn.length -1).split("].[");
var h = qnParts[0];
var l = qnParts.length < 2 ? "" : qnParts[1];
addLevelToHierarchy({
hierarchy: h,
name: l,
qualifiedName: qn
}, filterHierarchies);
}
});
}
}
//console.log(filterHierarchies);
var getMdxCrossjoins = function(sets) {
var mdx = "";
if(sets.length > 0) {
var _sets = sets.slice();
if(_sets.length == 1) {
mdx = _sets[0];
} else {
mdx = "Crossjoin(" + _sets.shift() + ", " + getMdxCrossjoins(_sets) + ")";
}
}
return mdx;
}
var getMdxCrossjoinsNoLastDim = function(sets) {
var mdx = "";
if(sets.length > 0) {
var _sets = sets.slice();
if(_sets.length == 1) {
mdx = _sets[0];
} else {
mdx = "Crossjoin(" + _sets.shift() + ", " + getMdxCrossjoins(_sets) + ")";
}
}
return mdx;
}
var mdx = [];
mdx["members"] = [];
mdx["sets"] = [];
mdx["columns"] = "";
mdx["rows"] = "";
mdx["cube"] = definition.cube;
mdx["slicer"] = "";
var mdxSets = [];
var mdxSetsNoTotals = [];
var mdxTotalMembers = [];
var mdxAxis = "";
var mdxAxisNoTotals = "";
var mdxAxisNoTotalsNoLastDim = "";
$.each(dimensionHierarchies, function(i, hierarchy) {
var lastLevel = hierarchy.levels[hierarchy.levels.length-1];
if(settings.summary.grandTotal || settings.summary.subTotals) {
if(lastLevel.name == "") {
mdxTotalMembers.push("[" + lastLevel.hierarchy + "_" + lastLevel.name + "_Set]");
} else {
mdx["members"].push("member [" + hierarchy.name + "].[BT_TOTAL] as 'Aggregate([" + lastLevel.hierarchy + "_" + lastLevel.name + "_Set])'");
mdxTotalMembers.push("[" + hierarchy.name + "].[BT_TOTAL]");
}
}
var previousLevelName = [];
var previousLevelAllMembers = [];
$.each(hierarchy.levels, function(j, level) {
var mdxFilteredSet = getMdxFilter(level.qualifiedName, "[" + hierarchy.name + "]");
var mdxNamedSet = mdxFilteredSet == "" ? "{" + level.qualifiedName + ".Members}" : mdxFilteredSet;
if(j > 0) {
var mdxConditions = [];
$.each(previousLevelName, function(k, previousLevelName) {
if(!previousLevelAllMembers[k])
mdxConditions.push("(Exists(Ancestor([" + level.hierarchy + "].CurrentMember, [" + level.hierarchy + "].[" + previousLevelName + "]), [" + level.hierarchy + "_" + previousLevelName + "_Set]).Count > 0))");
});
if(mdxConditions.length > 0) {
mdxNamedSet = "Filter(" + mdxNamedSet + ", ";
mdxNamedSet += "((" + mdxConditions.join(" AND ") + "))";
mdxNamedSet += ")";
}
}
if(ordersMap.levels.hasOwnProperty(level.qualifiedName)) {
var order = ordersMap.levels[level.qualifiedName];
var by = order.by;
if(by == "name") {
by = level.qualifiedName + ".CurrentMember.Name";
}
var direction = order.dir;
mdxNamedSet = "Order(" + mdxNamedSet + ", " + by + ", " + direction + ")";
}
mdx["sets"].push("set [" + level.hierarchy + "_" + level.name + "_Set] as '" + mdxNamedSet + "'");
previousLevelName.push(level.name);
previousLevelAllMembers.push(mdxFilteredSet == "" ? true : false);
});
var mdxHierarchySet = "[" + lastLevel.hierarchy + "_" + lastLevel.name + "_Set]";
if(hierarchy.levels.length > 1)
mdxHierarchySet = "Descendants(" + mdxHierarchySet + ", " + lastLevel.qualifiedName + ", SELF)";
mdxSetsNoTotals.push(mdxHierarchySet);
if(settings.summary.subTotals && i > 0 && i == dimensionHierarchies.length - 1 && !ordersMap.axes.hasOwnProperty("dimensions")) {
if(settings.summary.position == "top")
mdxHierarchySet = "Union([" + hierarchy.name + "].[BT_TOTAL], " + mdxHierarchySet + ")";
else if(settings.summary.position == "bottom")
mdxHierarchySet = "Union(" + mdxHierarchySet + ", [" + hierarchy.name + "].[BT_TOTAL])";
}
mdxSets.push(mdxHierarchySet);
});
if(settings.summary.subTotals && !ordersMap.axes.hasOwnProperty("dimensions") && mdxSets.length > 2) {
var btTotals = mdxTotalMembers.slice();
mdxAxis = "{?}";
var i = 0;
for(i; i < mdxSets.length - 2; i++) {
btTotals.shift();
mdxAxis = mdxAxis.replace("{?}", "Crossjoin(" + mdxSets[i] + ", Union({?}, " + getMdxCrossjoins(btTotals) + "))");
}
mdxAxis = mdxAxis.replace("{?}", "Crossjoin(" + mdxSets[i] + ", " + mdxSets[i + 1] + ")");
} else {
mdxAxis = getMdxCrossjoins(mdxSets);
}
if(ordersMap.axes.hasOwnProperty("dimensions")) {
var order = ordersMap.axes.dimensions;
var by = order.by;
if(by.indexOf("[Measures].[") < 0)
by = by + ".CurrentMember.Name";
mdxAxis = "Order(" + mdxAxis + ", " + by + ", " + order.dir + ")";
}
if(settings.summary.grandTotal) {
if(settings.summary.position == "top")
mdxAxis = "Union(" + getMdxCrossjoins(mdxTotalMembers) + ", " + mdxAxis + ")";
else if(settings.summary.position == "bottom")
mdxAxis = "Union(" + mdxAxis + ", " + getMdxCrossjoins(mdxTotalMembers) + ")";
}
mdxAxisNoTotals = getMdxCrossjoins(mdxSetsNoTotals);
var mdxSetsNoTotalsNoLastDim = mdxSetsNoTotals.slice();
if (mdxSetsNoTotalsNoLastDim.length > 1)
mdxSetsNoTotalsNoLastDim.pop();
mdxAxisNoTotalsNoLastDim = getMdxCrossjoins(mdxSetsNoTotalsNoLastDim);
if(settings.measuresOnColumns)
mdx["rows"] = mdxAxis;
else
mdx["columns"] = mdxAxis;
var mdxMeasuresAsMembers="";
var mdxMeasuresSet = "{";
$.each(definition.measures, function(i, v) {
if (v[1].substring(0,1) == "") {
mdxMeasuresAsMembers += " Member [Measures].[Measure" + i + "] As '("+ v[0]+")'";
} else {
mdxMeasuresAsMembers += " Member [Measures].[Measure" + i + "] As '" + measuresAttr[i]["formula"] + "'";
if (typeof measuresAttr[i]["format"] !== "undefined" && measuresAttr[i]["format"] != "")
mdxMeasuresAsMembers += ", FORMAT_STRING='" + measuresAttr[i]["format"] + "' ";
}
if(i > 0) mdxMeasuresSet += ", ";
//mdxMeasuresSet += v[0];
mdxMeasuresSet += "[Measures].[Measure" + i + "]";
});
mdxMeasuresSet += "}";
if(ordersMap.levels.hasOwnProperty("[Measures]")) {
var order = ordersMap.levels["[Measures]"];
var by = order.by;
var direction = order.dir;
if(by == "name") {
mdxMeasuresSet = "Order(" + mdxMeasuresSet + ", [Measures].CurrentMember.Name, " + direction + ")";
}
}
mdx["sets"].push(mdxMeasuresAsMembers + " set [Measures_Set] as '" + mdxMeasuresSet + "'");
mdxSets = [];
mdxTotalMembers = [];
$.each(pivotHierarchies, function(i, hierarchy) {
var lastLevel = hierarchy.levels[hierarchy.levels.length-1];
if(settings.summary.pivotGrandTotal || settings.summary.pivotSubTotals) {
mdx["members"].push("member [" + hierarchy.name + "].[BT_TOTAL] as 'Aggregate([" + lastLevel.hierarchy + "_" + lastLevel.name + "_Set])'");
mdxTotalMembers.push("[" + hierarchy.name + "].[BT_TOTAL]");
}
var previousLevelName = [];
var previousLevelAllMembers = [];
$.each(hierarchy.levels, function(j, level) {
var mdxFilteredSet = getMdxFilter(level.qualifiedName, "[" + hierarchy.name + "]");
var mdxNamedSet = mdxFilteredSet == "" ? "{" + level.qualifiedName + ".Members}" : mdxFilteredSet;
if(j > 0) {
var mdxConditions = [];
$.each(previousLevelName, function(k, previousLevelName) {
if(!previousLevelAllMembers[k])
mdxConditions.push("(Exists(Ancestor([" + level.hierarchy + "].CurrentMember, [" + level.hierarchy + "].[" + previousLevelName + "]), [" + level.hierarchy + "_" + previousLevelName + "_Set]).Count > 0))");
});
if(mdxConditions.length > 0) {
mdxNamedSet = "Filter(" + mdxNamedSet + ", ";
mdxNamedSet += "((" + mdxConditions.join(" AND ") + "))";
mdxNamedSet += ")";
}
}
if(ordersMap.levels.hasOwnProperty(level.qualifiedName)) {
var order = ordersMap.levels[level.qualifiedName];
var by = order.by;
if(by == "name") {
by = level.qualifiedName + ".CurrentMember.Name";
}
var direction = order.dir;
mdxNamedSet = "Order(" + mdxNamedSet + ", " + by + ", " + direction + ")";
}
mdx["sets"].push("set [" + level.hierarchy + "_" + level.name + "_Set] as '" + mdxNamedSet + "'");
previousLevelName.push(level.name);
previousLevelAllMembers.push(mdxFilteredSet == "" ? true : false);
});
var mdxHierarchySet = "[" + lastLevel.hierarchy + "_" + lastLevel.name + "_Set]";
if(hierarchy.levels.length > 1)
mdxHierarchySet = "Descendants(" + mdxHierarchySet + ", " + lastLevel.qualifiedName + ", SELF)";
if(settings.summary.pivotSubTotals && (i > 0 || pivotHierarchyBeforeMeasures == "NONE") && i == pivotHierarchies.length - 1 && !ordersMap.axes.hasOwnProperty("measures")) {
if(settings.summary.position == "top")
mdxHierarchySet = "Union([" + hierarchy.name + "].[BT_TOTAL], " + mdxHierarchySet + ")";
else if(settings.summary.position == "bottom")
mdxHierarchySet = "Union(" + mdxHierarchySet + ", [" + hierarchy.name + "].[BT_TOTAL])";
}
mdxSets.push(mdxHierarchySet);
});
if(pivotHierarchyBeforeMeasures == "") {
mdxSets.push("[Measures_Set]");
mdxTotalMembers.push("[Measures_Set]");
}
else {
var measuresInsertionIndex = $.map(pivotHierarchies, function(hierarchy, index) {
if(hierarchy.name == pivotHierarchyBeforeMeasures)
return index + 1;
});
if(measuresInsertionIndex.length == 0 && pivotHierarchyBeforeMeasures == "NONE")
measuresInsertionIndex = [0]
mdxSets.splice(measuresInsertionIndex[0], 0, "[Measures_Set]");
mdxTotalMembers.splice(measuresInsertionIndex[0], 0, "[Measures_Set]");
}
if(definition.pivotDimensions.length > 0) {
if(settings.summary.pivotSubTotals && !ordersMap.axes.hasOwnProperty("measures") && mdxSets.length > 2) {
var btTotals = mdxTotalMembers.slice();
mdxAxis = "{?}";
var i = 0;
for(i; i < mdxSets.length - 2; i++) {
btTotals.shift();
mdxAxis = mdxAxis.replace("{?}", "Crossjoin(" + mdxSets[i] + ", Union({?}, " + getMdxCrossjoins(btTotals) + "))");
}
mdxAxis = mdxAxis.replace("{?}", "Crossjoin(" + mdxSets[i] + ", " + mdxSets[i + 1] + ")");
} else {
mdxAxis = getMdxCrossjoins(mdxSets);
}
if(ordersMap.axes.hasOwnProperty("measures")) {
var order = ordersMap.axes.measures;
var by = order.by;
if(by == "name")
by = "[Measures]";
by += ".CurrentMember.Name";
mdxAxis = "Order(" + mdxAxis + ", " + by + ", " + order.dir + ")";
}
if(settings.summary.pivotGrandTotal) {
if(settings.summary.position == "top")
mdxAxis = "Union(" + getMdxCrossjoins(mdxTotalMembers) + ", " + mdxAxis + ")";
else if(settings.summary.position == "bottom")
mdxAxis = "Union(" + mdxAxis + ", " + getMdxCrossjoins(mdxTotalMembers) + ")";
}
} else {
mdxAxis = "[Measures_Set]";
if(ordersMap.axes.hasOwnProperty("measures")) {
var order = ordersMap.axes.measures;
var by = order.by;
if(by == "name") {
by = "[Measures].CurrentMember.Name";
mdxAxis = "Order(" + mdxAxis + ", " + by + ", " + order.dir + ")";
}
}
}
if(settings.measuresOnColumns)
mdx["columns"] = mdxAxis;
else
mdx["rows"] = mdxAxis;
mdxSets = [];
mdxTotalMembers = [];
$.each(filterHierarchies, function(i, hierarchy) {
var previousLevelName = [];
var previousLevelAllMembers = [];
$.each(hierarchy.levels, function(j, level) {
var mdxFilteredSet = getMdxFilter(level.qualifiedName, "[" + hierarchy.name + "]");
var mdxNamedSet = mdxFilteredSet == "" ? "{" + level.qualifiedName + ".Members}" : mdxFilteredSet;
if(j > 0) {
var mdxConditions = [];
$.each(previousLevelName, function(k, previousLevelName) {
if(!previousLevelAllMembers[k])
mdxConditions.push("(Exists(Ancestor([" + level.hierarchy + "].CurrentMember, [" + level.hierarchy + "].[" + previousLevelName + "]), [" + level.hierarchy + "_" + previousLevelName + "_Set]).Count > 0))");
});
if(mdxConditions.length > 0) {
mdxNamedSet = "Filter(" + mdxNamedSet + ", ";
mdxNamedSet += "((" + mdxConditions.join(" AND ") + "))";
mdxNamedSet += ")";
}
}
mdx["sets"].push("set [" + level.hierarchy + "_" + level.name + "_Set] as '" + mdxNamedSet + "'");
previousLevelName.push(level.name);
previousLevelAllMembers.push(mdxFilteredSet == "" ? true : false);
});
if(!(previousLevelAllMembers.length == 1 && previousLevelAllMembers[0])) {
var levelSets = $.map(hierarchy.levels, function(level) {
return "[" + level.hierarchy + "_" + level.name + "_Set]";
});
var mdxHierarchySet = "{" + levelSets[levelSets.length - 1] + "}";
mdxSets.push(mdxHierarchySet);
}
});
mdx["slicer"] = getMdxCrossjoins(mdxSets);
var mdxQuery = "with ";
mdxQuery += mdx["sets"].join(" ") + " ";
mdxQuery += mdx["members"].join(" ") + " ";
mdxQuery += "select" + (settings.nonEmpty.columns ? " NON EMPTY" : "") + " " + mdx["columns"] + " on COLUMNS ";
if (mdx["rows"] != "")
mdxQuery += ", " + (settings.nonEmpty.rows ? " NON EMPTY" : "") + " " + mdx["rows"] + " on ROWS ";
mdxQuery += "from [" + mdx["cube"] + "]";
mdxQuery += mdx["slicer"] != "" ? " where (" + mdx["slicer"] + ")" : "";
// Replace Internal PlaceHolders
mdxQuery = mdxQuery.replace(/§AllRowsSetNoTotals/g, mdxAxisNoTotals);
mdxQuery = mdxQuery.replace(/§AllRowsSetNoLastDim/g, mdxAxisNoTotalsNoLastDim);
return mdxQuery;
}
myself.getLevelFilterMdx = function(level) {
var mdxQuery = myself.getMdx();
//mdxQuery = mdxQuery.replace("set [Measures_Set] as '{}'","member [Measures].[Unique Name] as '" + level + ".CurrentMember.UniqueName'");
//mdxQuery = mdxQuery.replace("NON EMPTY [Measures_Set]","NON EMPTY UNION([Measures].[Unique Name], [Measures].Members)");
mdxQuery = mdxQuery.replace("set [Measures_Set] as '{}'","member [Measures].[Unique Name] as 'IIf(([Measures].[Fact Count] IS EMPTY), NULL, " + level + ".CurrentMember.UniqueName)'");
mdxQuery = mdxQuery.replace("NON EMPTY [Measures_Set]","NON EMPTY [Measures].[Unique Name]");
return mdxQuery;
}
myself.putMeasuresOnColumns = function() {
settings.measuresOnColumns = true;
}
myself.putMeasuresOnRows = function() {
settings.measuresOnColumns = false;
}
myself.hasMeasuresOnColumns = function() {
return settings.measuresOnColumns;
}
myself.hasPivotDimensions = function() {
if(definition.pivotDimensions.length == 0 || (definition.pivotDimensions.length == 1 && definition.pivotDimensions[0][0] == "MEASURES"))
return false;
else
return true;
}
myself.getDimensionQualifiedNames = function() {
return $.map(definition.dimensions, function(i) {return i[0]});
}
myself.getPivotDimensionQualifiedNames = function() {
return $.map(definition.pivotDimensions, function(i) {return i[0]});
}
myself.getMeasureQualifiedNames = function() {
return $.map(definition.measures, function(i) {return i[0]});
}
myself.getFilterQualifiedNames = function() {
return $.map(definition.filters, function(i) {return i[0]});
}
myself.getDefinition = function() {
return $.extend(true, {}, definition);
}
myself.getCube = function() {
return definition.cube;
}
myself.setFilters = function(filters) {
myself.disableFilters();
definition.filters = filters;
initializeFiltersMap(definition.filters);
}
myself.disableFilters = function() {
for(var key in filtersMap.hierarchies) {
var hierarchy = filtersMap.hierarchies[key];
var levels = hierarchy.levels;
$.each(hierarchy.order, function(i, v) {
var level = levels[v];
if(level.filtered) {
level.filtered=false;
}
});
}
}
myself.getFilters = function(forFiltersFiltering) {
var filters = [];
var invalidHierarchies = [];
if (!forFiltersFiltering)
invalidHierarchies = $.map(myself.getDimensionQualifiedNames(), function(e) {
return (e.split("].[")[0] + "]").replace("]]", "]");
}).concat($.map(myself.getPivotDimensionQualifiedNames(), function(e) {
return (e.split("].[")[0] + "]").replace("]]", "]");
}));
var boundToDashboard = filtersMap.synchronizedByParameters;
for(var key in filtersMap.hierarchies) {
if($.inArray(key, invalidHierarchies) < 0) {
var hierarchy = filtersMap.hierarchies[key];
var levels = hierarchy.levels;
$.each(hierarchy.order, function(i, v) {
var level = levels[v];
if(level.filtered) {
var qn = v;
var filterMode = level.filterMode;
if(level.uniqueNames) filterMode += "_un";
var members = null;
if(boundToDashboard && level.synchronizedByParameters) {
var filterExpression = level.initialFilterExpression;
var param = filterExpression.replace(filterMode + ":", "");
var members = Dashboards.getParameterValue(param);
} else {
members = level.members;
}
if(members.length > 0) {
var plainFilter = filterMode + ":[" + ( $.isArray(members) ? members.join("],[") : members ) + "]";
var filter = [qn, plainFilter];
filters.push(filter);
}
}
});
}
}
return filters;
}
myself.getOrders = function() {
var orders = [];
if(ordersMap.axes.hasOwnProperty("dimensions")) {
var plainOrder = ordersMap.axes.dimensions.by + "::" + ordersMap.axes.dimensions.dir;
var order = ["D", plainOrder];
orders.push(order);
}
return orders;
}
myself.getDimensions = function() {
var dimensions = [];
$.each(definition.dimensions, function(i, v) {
var qn = v[0];
var arr = [qn, myself.getPlainFilter(qn)];
dimensions.push(arr);
});
return dimensions;
}
myself.getPivotDimensions = function() {
var pivotDimensions = [];
$.each(definition.pivotDimensions, function(i, v) {
var qn = v[0];
var fe = qn == "MEASURES" ? "" : myself.getPlainFilter(qn);
var arr = [qn, fe];
pivotDimensions.push(arr);
});
return pivotDimensions;
}
myself.getMeasures = function() {
return definition.measures;
}
myself.setMeasures = function(measures) {
definition.measures = measures;
}
myself.set = function(properties) {
$.extend(true, settings, properties);
}
myself.getSettings = function() {
return settings;
}
myself.isRemovable = function(qualifiedName, type) {
var removable = true;
if(type == "D") {
removable = definition.dimensions.length > 1;
if(removable) {
// prevent removing a dimension level if there is only one hierarchy in the axis
// and moving all the levels of this hierarchy in filters make this axis empty!
var hierarchies = _.uniq($.map(myself.getDimensionQualifiedNames(), function(e) {
return (e.split("].[")[0] + "]").replace("]]", "]");
}));
if(hierarchies.length == 1) {
if(filtersMap.hierarchies[hierarchies[0]].levels[qualifiedName].filtered)
removable = false;
}
}
}
else if(type == "M") {
removable = definition.measures.length > 1;
}
return removable;
}
myself.remove = function(qualifiedName, type, measurePos) {
var removedElements = undefined;
var hierarchy = (qualifiedName.split("].[")[0] + "]").replace("]]", "]");
var axis = [];
var axisQualifiedNames = [];
if(type == "D") {
axis = definition.dimensions;
axisQualifiedNames = myself.getDimensionQualifiedNames();
}
else if(type == "M") {
axis = definition.measures;
axisQualifiedNames = myself.getMeasureQualifiedNames();
}
else if(type == "P") {
axis = definition.pivotDimensions;
axisQualifiedNames = myself.getPivotDimensionQualifiedNames();
}
var index = -1;
var length = 0;
// also remove all other levels of the same hierarchy if the target level is filtered!
if(type != "M" && filtersMap.hierarchies[hierarchy].levels[qualifiedName].filtered) {
var hierarchies = $.map(axisQualifiedNames, function(e) {
return (e.split("].[")[0] + "]").replace("]]", "]");
});
var indexes = [];
$.each(hierarchies, function(i, v) {
if(v == hierarchy) indexes.push(i);
});
//console.log(indexes.toSource());
index = indexes[0];
length = indexes.length;
} else {
index = axisQualifiedNames.indexOf(qualifiedName);
if (type == "M")
index = measurePos;
length = 1;
}
if(index >= 0)
removedElements = axis.splice(index, length);
myself.clearSort(qualifiedName, (length > 1 ? true : false));
if (type == "M")
myself.loadMeasuresAttr();
}
myself.add = function(newQualifiedName, targetQualifiedName, position, type, measurePos) {
var hierarchy = (newQualifiedName.split("].[")[0] + "]").replace("]]", "]");
var axis = [];
var axisQualifiedNames = [];
if(type == "D") {
axis = definition.dimensions;
axisQualifiedNames = myself.getDimensionQualifiedNames();
}
else if(type == "M") {
axis = definition.measures;
axisQualifiedNames = myself.getMeasureQualifiedNames();
}
else if(type == "P") {
axis = definition.pivotDimensions;
if($.inArray("MEASURES", myself.getPivotDimensionQualifiedNames()) < 0)
axis.splice(0, 0, ["MEASURES", ""]);
axisQualifiedNames = myself.getPivotDimensionQualifiedNames();
}
var index = $.inArray(targetQualifiedName, axisQualifiedNames);
// also add all other levels of the same hierarchy if they are filtered and they aren't in the axis!
var hierarchies = $.map(axisQualifiedNames, function(e) {
return (e.split("].[")[0] + "]").replace("]]", "]");
});
if(type != "M" && $.inArray(hierarchy, hierarchies) < 0) {
var fmHierarchy = filtersMap.hierarchies[hierarchy];
var fmLevels = fmHierarchy.levels;
var elementsToInsert = [];
$.each(fmHierarchy.order, function(i, v) {
if(fmLevels[v].filtered || v == newQualifiedName)
elementsToInsert.push("[\"" + v + "\", \"\"]");
});
if(index >= 0) {
if(position == 1)
index++;
eval("axis.splice(index, 0, " + elementsToInsert.join(", ") + ")");
}
} else {
var elementToInsert = [newQualifiedName, ""];
if(type == 'M' && measurePos >= 0) {
if(position == 1)
measurePos++;
axis.splice(measurePos, 0, elementToInsert);
} else {
if(position == 1)
index++;
axis.splice(index, 0, elementToInsert);
}
}
if (type == "M")
myself.loadMeasuresAttr();
}
myself.isReplaceable = function(newQualifiedName, oldQualifiedName, type) {
var replaceable = true;
if(type != "M") {
var newHierarchy = (newQualifiedName.split("].[")[0] + "]").replace("]]", "]");
var oldHierarchy = (oldQualifiedName.split("].[")[0] + "]").replace("]]", "]");
if(newHierarchy == oldHierarchy && filtersMap.hierarchies[oldHierarchy].levels[oldQualifiedName].filtered)
replaceable = false;
}
return replaceable;
}
myself.replace = function(newQualifiedName, oldQualifiedName, position, type, measurePos) {
var hasNewPosition = position != null;
var closeQualifiedName = hasNewPosition ? position.level : oldQualifiedName;
var direction = hasNewPosition ? position.direction : 1;
var axis = [];
var axisQualifiedNames = [];
if(type == "D") {
axis = definition.dimensions;
axisQualifiedNames = myself.getDimensionQualifiedNames();
}
else if(type == "M") {
axis = definition.measures;
axisQualifiedNames = myself.getMeasureQualifiedNames();
}
else if(type == "P") {
axis = definition.pivotDimensions;
axisQualifiedNames = myself.getPivotDimensionQualifiedNames();
}
//console.log("Add " + newQualifiedName + " to the " + (direction == 1 ? "right of " : "left of ") + closeQualifiedName + ". Then remove " + oldQualifiedName);
myself.add(newQualifiedName, closeQualifiedName, direction, type, measurePos);
myself.remove(oldQualifiedName, type, measurePos);
if(type != "M") {
var newLevelHierarchy = (newQualifiedName.split("].[")[0] + "]").replace("]]", "]");
var oldLevelHierarchy = (oldQualifiedName.split("].[")[0] + "]").replace("]]", "]");
var closeLevelHierarchy = (closeQualifiedName.split("].[")[0] + "]").replace("]]", "]");
if(closeQualifiedName != oldQualifiedName && closeLevelHierarchy == oldLevelHierarchy && newLevelHierarchy != oldLevelHierarchy) {
// positioning correction
var headElements = [];
var tailElements = [];
var newHierarchyElements = [];
var oldHierarchyElements = [];
var newHierarchyFound = false;
$.each(axis, function(i, v) {
var l = v[0];
var h = (l.split("].[")[0] + "]").replace("]]", "]");
var e = "[\"" + l + "\", \"\"]";
if(h == oldLevelHierarchy) {
oldHierarchyElements.push(e);
}
else if(h == newLevelHierarchy) {
newHierarchyElements.push(e);
newHierarchyFound = true;
}
else {
if(!newHierarchyFound)
headElements.push(e);
else
tailElements.push(e);
}
});
var newAxis = headElements.concat(newHierarchyElements, oldHierarchyElements, tailElements);
eval("axis.splice(0, axis.length, " + newAxis.join(", ") + ")");
}
}
}
var filtersMap = {
synchronizedByParameters: true,
hierarchies: {}
};
if(olapCube && olapCube.getStructure()) {
var hierarchies = olapCube.getHierarchies();
$.each(hierarchies, function(i, v) {
var levels = {};
var order = [];
$.each(v.levels, function(j, w) {
var qualifiedName = w.qualifiedName;
levels[qualifiedName] = {
depth: w.depth,
initialFilterExpression: "",
synchronizedByParameters: false,
filterMode: "",
uniqueNames: false,
members: {},
filtered: false
}
order.push(qualifiedName);
//order[qualifiedName]={};
});
filtersMap.hierarchies[v.qualifiedName] = {
levels: levels,
order: order,
calculatedMembers: {
initialFilterExpression: "",
synchronizedByParameters: false,
filterMode: "",
//uniqueNames: false,
members: {},
filtered: false
}
}
});
}
var initializeFiltersMap = function(axis) {
if(olapCube && olapCube.getStructure()) {
$.each(axis, function(i, v) {
var lvlQn = v[0];
var fltExpr = v[1];
if(fltExpr != "") {
if(lvlQn.indexOf("].[") < 0) {
var hrcQn = lvlQn;
var synchronizedByParameters = fltExpr.indexOf("[") < 0;
var filterMode = synchronizedByParameters ? fltExpr.split(":")[0] : fltExpr.split(":[")[0];
var membersString = synchronizedByParameters ? "" : fltExpr.replace(filterMode + ":", "");
var calculatedMembers = filtersMap.hierarchies[hrcQn].calculatedMembers;
calculatedMembers.initialFilterExpression = fltExpr;
calculatedMembers.synchronizedByParameters = synchronizedByParameters;
//calculatedMembers.filterMode = filterMode;
calculatedMembers.filterMode = filterMode.replace("_un", "");
calculatedMembers.uniqueNames = filterMode.indexOf("_un") > -1;
calculatedMembers.members = synchronizedByParameters ? [] : membersString.substring(1, membersString.length - 1).split("],[");
calculatedMembers.filtered = true;
} else {
var hrcQn = lvlQn.split("].[")[0] + "]";
var levels = filtersMap.hierarchies[hrcQn].levels;
var synchronizedByParameters = fltExpr.indexOf("[") < 0;
var filterMode = synchronizedByParameters ? fltExpr.split(":")[0] : fltExpr.split(":[")[0];
var membersString = synchronizedByParameters ? "" : fltExpr.replace(filterMode + ":", "");
var level = filtersMap.hierarchies[hrcQn].levels[lvlQn];
level.initialFilterExpression = fltExpr;
level.synchronizedByParameters = synchronizedByParameters;
level.filterMode = filterMode.replace("_un", "");
level.uniqueNames = filterMode.indexOf("_un") > -1;
level.members = synchronizedByParameters ? [] : membersString.substring(1, membersString.length - 1).split("],[");
level.filtered = true;
}
}
});
}
}
initializeFiltersMap(definition.dimensions);
initializeFiltersMap(definition.pivotDimensions);
initializeFiltersMap(definition.filters);
myself.getFiltersMap = function() {
return filtersMap;
}
myself.forceFiltersMap = function(newFiltersMap) {
filtersMap = $.extend(true, {}, newFiltersMap);
}
myself.synchronizeFiltersWithParameters = function(state) {
filtersMap.synchronizedByParameters = state;
}
myself.isSynchronizedByParameters = function() {
return filtersMap.synchronizedByParameters;
}
myself.setFiltersMap = function(hierarchyQualifiedName, levelQualifiedName, filter) {
$.extend(filtersMap.hierarchies[hierarchyQualifiedName].levels[levelQualifiedName], filter);
}
var ordersMap = {
axes: {},
levels: {}
};
var initializeOrdersMap = function() {
$.each(definition.orders, function(i, v) {
var arg = v[0];
var valueParts = v[1].split("::");
var rule = {by: valueParts[0], dir: valueParts[1]};
if(arg == "D")
ordersMap.axes.dimensions = rule;
else if(arg == "M")
ordersMap.axes.measures = rule;
else
ordersMap.levels[arg] = rule;
});
}
initializeOrdersMap();
myself.getOrdersMap = function() {
return ordersMap;
}
myself.getSortDirection = function(target, qualifiedName) {
var direction = "";
if(target == "D") {
if(ordersMap.axes.hasOwnProperty("dimensions")) {
var order = ordersMap.axes.dimensions;
if(order.by == qualifiedName)
direction = order.dir;
}
}
else if(target == "M") {
if(ordersMap.axes.hasOwnProperty("measures")) {
var order = ordersMap.axes.measures;
if(order.by == qualifiedName)
direction = order.dir;
}
}
/*else {
}*/
return direction;
}
myself.sort = function(target, by, direction) {
var removeSort = by == "";
if(target == "D") {
if(removeSort)
delete ordersMap.axes.dimensions;
else
ordersMap.axes.dimensions = {by: by, dir: direction};
}
else if(target == "M") {
if(removeSort)
delete ordersMap.axes.measures;
else
ordersMap.axes.measures = {by: by, dir: direction};
}
}
myself.clearSort = function(qualifiedName, hierarchyRemoval) {
var hierarchy = (qualifiedName.split("].[")[0] + "]").replace("]]", "]");
if(ordersMap.axes.hasOwnProperty("dimensions") && (
(!hierarchyRemoval && ordersMap.axes.dimensions.by == qualifiedName) ||
(hierarchyRemoval && ordersMap.axes.dimensions.by.indexOf(hierarchy) == 0)
))
delete ordersMap.axes.dimensions;
else if(ordersMap.axes.hasOwnProperty("measures") && (
(!hierarchyRemoval && ordersMap.axes.measures.by == qualifiedName) ||
(hierarchyRemoval && ordersMap.axes.measures.by.indexOf(hierarchy) == 0)
))
delete ordersMap.axes.measures;
if(hierarchyRemoval) {
for(key in ordersMap.levels) {
if(key.indexOf(hierarchy) == 0)
delete ordersMap.levels[key];
}
} else {
if(ordersMap.levels.hasOwnProperty(qualifiedName))
delete ordersMap.levels[qualifiedName];
}
}
/*
* HISTORY
*/
myself.saveInHistory = function() {
var def = $.extend(true, {}, definition);
history.push(def);
var fm = $.extend(true, {}, filtersMap);
hstFM.push(fm);
var om = $.extend(true, {}, ordersMap);
hstOM.push(om);
}
myself.restoreHistoryFromSession = function(objName) {
history = JSON.parse(sessionStorage.getItem(objName));
if (history) {
sessionStorage.removeItem(objName);
hstFM = JSON.parse(sessionStorage.getItem(objName + "_FM"));
sessionStorage.removeItem(objName + "_FM");
hstOM = JSON.parse(sessionStorage.getItem(objName + "_OM"));
sessionStorage.removeItem(objName + "_OM");
} else {
history = [];
myself.saveInHistory()
}
};
myself.reset = function() {
definition = $.extend(true, {}, history[0]);
while (history.length > 1)
history.pop();
initializeFiltersMap(definition.dimensions);
initializeFiltersMap(definition.pivotDimensions);
initializeFiltersMap(definition.filters);
filtersMap.synchronizedByParameters = true;
initializeOrdersMap();
}
myself.restoreFromHistory = function() {
definition = history.pop();
filtersMap = hstFM.pop();
ordersMap = hstOM.pop();
myself.loadMeasuresAttr();
}
myself.stepBackHistory = function() {
history.pop();
hstFM.pop();
hstOM.pop();
myself.loadMeasuresAttr();
}
myself.hasHistory = function() {
return history.length > 1 ? true : false;
}
myself.getHistory = function() {
return JSON.stringify(history);
}
myself.getHstFM = function() {
return JSON.stringify(hstFM);
}
myself.getHstOM = function() {
return JSON.stringify(hstOM);
}
// History initialization
var urlQuery = getURLQuery();
urlQuery.hasOwnProperty("history") ? myself.restoreHistoryFromSession(urlQuery.history) : myself.saveInHistory();
return myself;
}
| biztech-it/BTable | BTable-common/resources/components/BTable/lib/bt.query.js | JavaScript | mpl-2.0 | 46,000 |
/* eslint-disable */
/**
* 该文件是为了按需加载,剔除掉了一些不需要的框架组件。
* 减少了编译支持库包大小
*
* 当需要更多组件依赖时,在该文件加入即可
*/
import Vue from 'vue'
import {
LocaleProvider,
Layout,
Input,
InputNumber,
Button,
Switch,
Radio,
Checkbox,
Select,
Card,
Form,
Row,
Col,
Modal,
Table,
Tabs,
Icon,
Badge,
Popover,
Dropdown,
List,
Avatar,
Breadcrumb,
Steps,
Spin,
Menu,
Drawer,
Tooltip,
Alert,
Tag,
Divider,
DatePicker,
TimePicker,
Upload,
Progress,
Skeleton,
Popconfirm,
message,
notification
} from 'ant-design-vue'
// import VueCropper from 'vue-cropper'
Vue.use(LocaleProvider)
Vue.use(Layout)
Vue.use(Input)
Vue.use(InputNumber)
Vue.use(Button)
Vue.use(Switch)
Vue.use(Radio)
Vue.use(Checkbox)
Vue.use(Select)
Vue.use(Card)
Vue.use(Form)
Vue.use(Row)
Vue.use(Col)
Vue.use(Modal)
Vue.use(Table)
Vue.use(Tabs)
Vue.use(Icon)
Vue.use(Badge)
Vue.use(Popover)
Vue.use(Dropdown)
Vue.use(List)
Vue.use(Avatar)
Vue.use(Breadcrumb)
Vue.use(Steps)
Vue.use(Spin)
Vue.use(Menu)
Vue.use(Drawer)
Vue.use(Tooltip)
Vue.use(Alert)
Vue.use(Tag)
Vue.use(Divider)
Vue.use(DatePicker)
Vue.use(TimePicker)
Vue.use(Upload)
Vue.use(Progress)
Vue.use(Skeleton)
Vue.use(Popconfirm)
// Vue.use(VueCropper)
Vue.use(notification)
Vue.prototype.$confirm = Modal.confirm
Vue.prototype.$message = message
Vue.prototype.$notification = notification
Vue.prototype.$info = Modal.info
Vue.prototype.$success = Modal.success
Vue.prototype.$error = Modal.error
Vue.prototype.$warning = Modal.warning | keel-hq/keel | ui/src/core/lazy_lib/components_use.js | JavaScript | mpl-2.0 | 1,623 |
/**
* @file configures and initializes the httpd, and sets up available routes
* @module httpd
*
* @license https://www.mozilla.org/MPL/2.0/ MPL-2.0
*
* @requires models
* @requires routes
* @requires research
*/
/*
require packages
*/
var express = require( 'express' );
var morgan = require( 'morgan' );
var helmet = require( 'helmet' );
var Habitat = require( 'habitat' );
var bodyParser = require( 'body-parser' );
var cookieParser = require( 'cookie-parser' );
var session = require( 'express-session' );
var csrf = require( 'csurf' );
var marked = require( 'marked' );
var moment = require( 'moment' );
var nunjucks = require( 'nunjucks' );
var debug = require( 'debug' );
/*
setup environment
*/
if( process.env.NODE_ENV !== 'testing' ) {
Habitat.load();
}
else {
Habitat.load( __dirname + '/.env-test' );
}
/**
* Environment manipulator.
*
* @type {Habitat}
*/
var env = new Habitat();
// drop package.json info into env
env.set( 'pkg', require( './package.json' ) );
// force init debug now we have the env loaded
debug.enable( env.get( 'debug' ) );
debug.useColors();
/*
setup debuggers
*/
var debugEnv = debug( 'env' );
var debugPersona = debug( 'persona' );
debugEnv( 'debug enabled' );
debugEnv( 'pkg.version: %s, env: %s', env.get( 'pkg' ).version, env.get( 'node_env' ) );
/*
setup server
*/
var app = express();
// static, public dir
app.use( express.static( __dirname + '/public' ) );
// work nicely with cookies
app.use( cookieParser() );
app.use( bodyParser.json() );
app.use( bodyParser.urlencoded( { extended: true } ) );
app.use( session({
secret: env.get( 'session_secret' ),
resave: env.get( 'session_resave' ) || false,
saveUninitialized: env.get( 'session_save_uninitialized' ) || false
}) );
// pretty print JSON ouput in development environments
if( env.get( 'node_env' ) !== 'production' ) {
app.set( 'json spaces', 2 );
}
// server security
app.use( helmet.xframe( 'sameorigin' ) );
app.use( helmet.hsts() );
app.use( helmet.nosniff() );
app.use( helmet.xssFilter() );
app.disable( 'x-powered-by' );
if( env.get( 'force_ssl' ) ) {
debugEnv( 'Attempting to force ssl connections' );
}
app.use( function( req, res, next ) {
if( env.get( 'force_ssl' ) ) {
if( req.headers[ 'x-forwarded-proto' ] && req.headers[ 'x-forwarded-proto' ] !== 'https' ) {
res.redirect( 'https://' + req.hostname + req.originalUrl );
return;
}
if( !req.secure && !req.headers[ 'x-forwarded-proto' ] ) {
res.redirect( 'https://' + req.hostname + req.originalUrl );
return;
}
}
next();
});
// persona login
require( 'express-persona' )( app, {
audience: env.get( 'persona_audience' )
});
debugPersona( env.get( 'persona_audience' ) );
if( process.env.NODE_ENV !== 'testing' ) {
// enable csrf protection on all non-GET/HEAD/OPTIONS routes with the
// excaption of persona verification/logout routes which have already
// been set up.
app.use( csrf() );
}
/*
setup http debug output
*/
if( debug( 'http' ).enabled ) {
debugEnv( 'using morgan for \033[0;37mhttp\033[0m debug notices' );
app.use( morgan( ' \033[0;37mhttp\033[0m :method :url :status +:response-time ms - :res[content-length] bytes' ) );
}
/*
setup nunjucks
*/
/**
* Configured Nunjucks environment.
* @type {Nunjucks.Environment}
*/
var nunjucksEnv = nunjucks.configure( 'views', {
autoescape: true,
watch: true
});
// add markdown support to nunjucks
nunjucksEnv.addFilter( 'markdown', function( str ) {
return nunjucksEnv.getFilter( 'safe' )( marked( str ) );
});
// add basic moment support to nunjucks
nunjucksEnv.addFilter( 'moment', function( str, format ) {
format = format || 'MMMM Do YYYY';
return moment( str ).format( format );
});
nunjucksEnv.addFilter( 'calendar', function( str ) {
return moment( str ).calendar();
});
nunjucksEnv.addFilter( 'relativeMoment', function( str ) {
return moment( str ).from( moment() );
});
// make nunjucks the default view renderer
nunjucksEnv.express( app );
/*
get models
*/
/**
* Database ORM instance
* @type {Object}
*/
var db = require( './models' )( env );
/*
routes
*/
/**
* Route handlers.
* @type {Object}
*/
var routes = require( './routes' )( env );
// keep sessions up to date no matter what.
app.use( routes.auth.updateSession );
// add useful variables + objects `res.locals`, such as the csrf token,
// session email (set by persona), and any user details.
app.use( function( req, res, next ) {
// disable csrf protection in test environment
if( process.env.NODE_ENV !== 'testing' ) {
res.locals.csrfToken = req.csrfToken();
}
res.locals.user = req.session.user;
res.locals.persona = req.session.email;
res.locals.cookies = req.cookies;
next();
});
// setup any research
require( './libs/research' )( app, env );
// healthcheck
app.get( '/healthcheck', routes.healthcheck );
// public web routes (ex. API)
app.get( '/', routes.public.index );
app.get( '/about', routes.public.about );
app.get( '/legal', routes.public.legal );
// user support
app.get( '/help/:page?', routes.help );
// user management
app.get( '/users', routes.auth.enforceAdmin, routes.users.users );
app.get( '/users/create', routes.users.create );
app.get( '/users/:id', routes.auth.enforce, routes.users.user );
app.get( '/users/:id/update', routes.auth.enforce, routes.users.update );
// topic management
app.get( '/topics', routes.auth.enforce, routes.topics.topics );
app.get( '/topics/create', routes.auth.enforce, routes.topics.create );
app.get( '/topics/:id', routes.auth.enforce, routes.topics.topic );
app.get( '/topics/:id/update', routes.auth.enforce, routes.topics.update );
// task management
app.get( '/tasks', routes.auth.enforce, routes.tasks.tasks );
app.get( '/tasks/create', routes.auth.enforce, routes.tasks.create );
app.get( '/tasks/:id', routes.auth.enforce, routes.tasks.task );
app.get( '/tasks/:id/update', routes.auth.enforce, routes.tasks.update );
// administration
app.all( '/admin*', routes.auth.enforceAdmin );
app.get( '/admin/email', routes.admin.email.get );
app.post( '/admin/email', routes.admin.email.post );
app.get( '/admin/users', routes.admin.users );
// create a new user (api)
app.post( '/api/users', routes.api.users.create );
/*
authenticated routes (any user)
*/
// enforce valid user for all routes now on
app.all( '/api*', routes.auth.enforce );
// api for specific user
app.get( '/api/users/:id', routes.api.users.get );
app.put( '/api/users/:id', routes.api.users.update );
app.delete( '/api/users/:id', routes.api.users.delete );
// api for specific users topics
app.get( '/api/users/:id/topics', routes.api.users.topics );
// api for specific topic
app.get( '/api/topics', routes.api.topics.list );
app.post( '/api/topics', routes.api.topics.create );
app.get( '/api/topics/:id', routes.api.topics.get );
app.put( '/api/topics/:id', routes.api.topics.update );
app.delete( '/api/topics/:id', routes.api.topics.delete );
// api for specific users tasks
app.get( '/api/users/:id/tasks', routes.api.users.tasks );
// api for specific topics tasks
app.get( '/api/topics/:id/tasks', routes.api.topics.tasks );
// api for specific task
app.get( '/api/tasks', routes.api.tasks.list );
app.post( '/api/tasks', routes.api.tasks.create );
app.get( '/api/tasks/:id', routes.api.tasks.get );
app.put( '/api/tasks/:id', routes.api.tasks.update );
app.delete( '/api/tasks/:id', routes.api.tasks.delete );
/*
authenticated routes (administrators)
*/
app.all( '/api*', routes.auth.enforceAdmin );
// api get list of all users
app.get( '/api/users', routes.api.users.list );
/*
handle 404 errors
*/
app.use( function( req, res ) {
routes.errors.notFound( req, res );
});
/*
setup db + launch server
*/
if( process.env.NODE_ENV !== 'testing' ) {
db.sequelize.sync( { force: env.get( 'db_force_sync' ) } ).complete( function( error ) {
if( error ) {
return console.error( error );
}
/**
* HTTP Server
* @return {http.server}
*/
var server = app.listen( env.get( 'port' ) || 3000, function() {
console.log( 'Now listening on port %d', server.address().port );
});
});
}
else {
/**
* Exported HTTP Server
* @type {http.server}
*/
module.exports = app.listen( env.get( 'port' ) );
}
| not-so-creative/eisenhower | server.js | JavaScript | mpl-2.0 | 8,294 |
/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
/* 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/. */
//-----------------------------------------------------------------------------
var BUGNUMBER = 452498;
var summary = 'TM: upvar2 regression tests';
var actual = '';
var expect = '';
//-----------------------------------------------------------------------------
test();
//-----------------------------------------------------------------------------
function test()
{
enterFunc ('test');
printBugNumber(BUGNUMBER);
printStatus (summary);
// ------- Comment #121 From Gary Kwong [:nth10sd]
// without -j
x = function() { return x; };
// Assertion failure: !(pn->pn_dflags & flag), at ../jsparse.h:651
reportCompare(expect, actual, summary);
exitFunc ('test');
}
| Yukarumya/Yukarum-Redfoxes | js/src/tests/js1_8_1/regress/regress-452498-121.js | JavaScript | mpl-2.0 | 944 |
module.exports = {
"env": {
"es6": true,
"browser": true,
"webextensions": true
},
"extends": "eslint:recommended",
"parserOptions": {
"ecmaVersion": 8,
"sourceType": "module"
},
"rules": {
"brace-style": ["error", "1tbs"],
"curly": ["error"],
"eqeqeq": ["error"],
"indent-legacy": ["error", 2],
"key-spacing": ["error"],
"keyword-spacing": ["error", {
"before": true,
"after": true
}
],
"no-console": [0],
"no-multi-spaces": ["error"],
"no-trailing-spaces": ["error"],
"no-var": ["error"],
"object-curly-spacing": ["error", "never"],
"prefer-template": ["error"],
"quotes": ["error", "double"],
"semi": ["error", "always"],
"space-before-blocks": ["error"]
}
};
| eoger/tabcenter-redux | .eslintrc.js | JavaScript | mpl-2.0 | 783 |
/**
* @constructor
* @augments ControlModel
*/
var IconModel = ControlModel.extend( {
defaults: _.defaults( {
value: null,
size: '',
focusable: false
}, ControlModel.prototype.defaults ),
/**
*
*/
initialize: function() {
ControlModel.prototype.initialize.apply( this, arguments );
}
} );
InfinniUI.IconModel = IconModel;
| InfinniPlatform/InfinniUI | app/controls/icon/iconModel.js | JavaScript | agpl-3.0 | 392 |
var hd2Module = new baseVoucher('hd2','hd2',[],'Hóa đơn bán hàng');
hd2Module.module.defaultValues ={
t_thue_nt:0,t_thue:0,thue_suat:0
}
hd2Module.defaultValues4Detail = {
sl_xuat:0,
ty_le_ck:0,
gia_von_nt:0,gia_von:0,
gia_ban_nt:0,gia_ban:0,
tien_nt:0,tien:0,
tien_ck_nt:0,tien_ck:0,
px_gia_dd:false,
tien_xuat_nt:0,tien_xuat:0
}
hd2Module.defaultCondition4Search = {tu_ngay:new Date(),den_ngay:new Date(),so_ct:'',dien_giai:'',ma_kh:''};
hd2Module.prepareCondition4Search = function($scope,vcondition){
return {
so_ct:{$regex:$scope.vcondition.so_ct,$options:'i'},
dien_giai:{$regex:$scope.vcondition.dien_giai,$options:'i'},
ma_kh:{$regex:$scope.vcondition.ma_kh,$options:'i'},
ngay_ct:{
$gte:dateTime2Date($scope.vcondition.tu_ngay),
$lte:dateTime2Date($scope.vcondition.den_ngay)
}
};
}
hd2Module.watchDetail = function(scope){
scope.$watch('dt_current.sl_xuat',function(newData){
if(newData!=undefined && scope.status.isOpened){
scope.dt_current.tien_xuat_nt = Math.round( scope.dt_current.sl_xuat * scope.dt_current.gia_von_nt,scope.round);
scope.dt_current.tien_nt = Math.round( scope.dt_current.sl_xuat * scope.dt_current.gia_ban_nt,scope.round);
scope.dt_current.tien_ck_nt = Math.round(scope.dt_current.tien_nt * scope.dt_current.ty_le_ck/100,scope.round);
scope.dt_current.tien = Math.round(scope.dt_current.tien_nt * scope.ngMasterData.ty_gia,0);
scope.dt_current.tien_ck = Math.round(scope.dt_current.tien_ck_nt * scope.ngMasterData.ty_gia,0);
scope.dt_current.tien_xuat = scope.dt_current.tien_xuat_nt;
}
});
scope.$watch('dt_current.gia_ban_nt',function(newData){
if(newData!=undefined && scope.status.isOpened){
scope.dt_current.tien_nt = Math.round( scope.dt_current.sl_xuat * scope.dt_current.gia_ban_nt,scope.round);
scope.dt_current.tien_ck_nt = Math.round(scope.dt_current.tien_nt * scope.dt_current.ty_le_ck/100,scope.round);
scope.dt_current.tien = Math.round(scope.dt_current.tien_nt * scope.ngMasterData.ty_gia,0);
scope.dt_current.tien_ck = Math.round(scope.dt_current.tien_ck_nt * scope.ngMasterData.ty_gia,0);
}
});
scope.$watch('dt_current.gia_ban',function(newData){
if(newData!=undefined && scope.status.isOpened){
scope.dt_current.tien = Math.round(scope.dt_current.gia_ban * scope.dt_current.sl_xuat,0);
scope.dt_current.tien_ck = Math.round(scope.dt_current.tien * scope.dt_current.ty_le_ck/100,0);
}
});
scope.$watch('dt_current.tien_nt',function(newData){
if(newData!=undefined && scope.status.isOpened){
scope.dt_current.tien_ck_nt = Math.round(scope.dt_current.tien_nt * scope.dt_current.ty_le_ck/100,scope.round);
scope.dt_current.tien = Math.round(scope.dt_current.tien_nt * scope.ngMasterData.ty_gia,0);
scope.dt_current.tien_ck = Math.round(scope.dt_current.tien_ck_nt * scope.ngMasterData.ty_gia,0);
}
});
scope.$watch('dt_current.tien',function(newData){
if(newData!=undefined && scope.status.isOpened){
scope.dt_current.tien_ck = Math.round(scope.dt_current.tien * scope.dt_current.ty_le_ck/100,0);
}
});
scope.$watch('dt_current.gia_von_nt',function(newData){
if(newData!=undefined && scope.status.isOpened){
scope.dt_current.gia_von =scope.dt_current.gia_von_nt;
scope.dt_current.tien_xuat_nt = Math.round( scope.dt_current.sl_xuat * scope.dt_current.gia_von_nt,scope.round);
scope.dt_current.tien_xuat = scope.dt_current.tien_xuat_nt;
}
});
scope.$watch('dt_current.ty_le_ck',function(newData){
if(newData!=undefined && scope.status.isOpened){
scope.dt_current.tien_ck_nt = Math.round(scope.dt_current.tien_nt * scope.dt_current.ty_le_ck/100,scope.round);
scope.dt_current.tien_ck = Math.round(scope.dt_current.tien_ck_nt * scope.ngMasterData.ty_gia,0);
}
});
scope.$watch('dt_current.tien_ck_nt',function(newData){
if(newData!=undefined && scope.status.isOpened){
scope.dt_current.tien_ck = Math.round(scope.dt_current.tien_ck_nt * scope.ngMasterData.ty_gia,0);
}
});
}
hd2Module.watchMaster = function(scope){
scope.$watch('data.ty_gia',function(newData){
if(scope.data){
if(newData!=undefined && scope.isDataLoaded){
angular.forEach(scope.data.details,function(r){
r.tien = Math.round(r.tien_hang_nt * newData,0);
r.tien_ck = Math.round(r.tien_ck_nt * newData,0);
r.tien_xuat = r.tien_xuat_nt;
});
scope.data.t_thue = Math.round(scope.data.t_thue_nt * newData,0)
}
}
});
scope.$watch('data.thue_suat',function(newData){
if(scope.data){
if(newData!=undefined && scope.isDataLoaded){
scope.data.t_thue_nt = Math.round((scope.data.t_tien_nt-scope.data.t_ck_nt) * scope.data.thue_suat/100,scope.round);
scope.data.t_thue = Math.round(scope.data.t_thue_nt * scope.data.ty_gia,0)
}
}
});
scope.$watch('data.t_tien_nt',function(newData){
if(scope.data){
if(newData!=undefined && scope.isDataLoaded){
scope.data.t_thue_nt = Math.round((scope.data.t_tien_nt-scope.data.t_ck_nt) * scope.data.thue_suat/100,scope.round);
scope.data.t_thue = Math.round(scope.data.t_thue_nt * scope.data.ty_gia,0)
}
}
});
scope.$watch('data.t_tien',function(newData){
if(scope.data){
if(newData!=undefined && scope.isDataLoaded){
scope.data.t_thue = Math.round((scope.data.t_tien-scope.data.t_ck) * scope.data.thue_suat/100,0);
}
}
});
}
hd2Module.module.setDataSource2Print = function($scope,service,config){
if(config.list){
for(var i=0;i< config.list.length;i++){
if(config.list[i].sel==true){
$scope.dataSource = config.list[i];
service.getSocai(id_app,$scope.dataSource._id).success(function(data){
$scope.dataSource.socai = data;
});
break;
}
}
}
} | Openroadvietnam/openaccounting | public/administrator/modules/vouchers/hd2/script.js | JavaScript | agpl-3.0 | 5,673 |
module.exports = require('./lib/ProxySession.js')('signOut')
| bazgu/front-node | lib/Page/Data/SignOut.js | JavaScript | agpl-3.0 | 61 |
define(function (require) {
'use strict';
var Backbone = require('backbone');
var Rectangle = require('common/math/rectangle');
/**
* Constants
*/
var Constants = require('constants');
/**
* A david statue that detects collisions with projectiles
*/
var David = Backbone.Model.extend({
defaults: {
x: Constants.David.DEFAULT_X,
y: Constants.GROUND_Y,
height: Constants.David.HEIGHT,
collisionEnabled: true,
naked: false
},
initialize: function(attributes, options) {
this._bounds = new Rectangle();
this.on('change:height change:x change:y', this.updateBounds);
this.updateBounds();
},
updateBounds: function() {
this._bounds.set(
David.BOUNDS_RELATIVE_TO_HEIGHT.x * this.get('height') + this.get('x'),
David.BOUNDS_RELATIVE_TO_HEIGHT.y * this.get('height') + this.get('y'),
David.BOUNDS_RELATIVE_TO_HEIGHT.w * this.get('height'),
David.BOUNDS_RELATIVE_TO_HEIGHT.h * this.get('height')
);
},
calculateCollision: function(projectile) {
var collision = this._bounds.overlaps(projectile.bounds());
if (collision) {
this.trigger('collide', this, projectile);
this.set('collisionEnabled', false);
this.set('naked', true);
}
return collision;
},
reset: function() {
this.set('collisionEnabled', true);
this.set('naked', false);
},
}, Constants.David);
return David;
});
| Connexions/simulations | projectile-motion/src/js/models/david.js | JavaScript | agpl-3.0 | 1,717 |
import { moduleFor, test } from 'ember-qunit';
moduleFor('service:session-account', 'Unit | Service | session-account', {
// Specify the other units that are required for this test.
// needs: ['service:foo']
});
// Replace this with your real tests.
test('it exists', function(assert) {
let service = this.subject();
assert.ok(service);
});
| Noteblox/client-ember | tests/unit/services/session-account-test.js | JavaScript | agpl-3.0 | 351 |
/*!
* Copyright (C) Ascensio System SIA 2012-2021. All rights reserved
*
* https://www.onlyoffice.com/
*
* Version: 0.0.0 (build:0)
*/
;(function(DocsAPI, window, document, undefined) {
/*
# Full #
config = {
type: 'desktop or mobile or embedded',
width: '100% by default',
height: '100% by default',
documentType: 'word' | 'cell' | 'slide',// deprecate 'text' | 'spreadsheet' | 'presentation',
token: <string> encrypted signature
document: {
title: 'document title',
url: 'document url'
fileType: 'document file type',
options: <advanced options>,
key: 'key',
vkey: 'vkey',
info: {
owner: 'owner name',
folder: 'path to document',
uploaded: '<uploaded date>',
sharingSettings: [
{
user: 'user name',
permissions: '<permissions>',
isLink: false
},
...
],
favorite: '<file is favorite>' // true/false/undefined (undefined - don't show fav. button)
},
permissions: {
edit: <can edit>, // default = true
download: <can download>, // default = true
reader: <can view in readable mode>,
review: <can review>, // default = edit
print: <can print>, // default = true
comment: <can comment in view mode> // default = edit,
modifyFilter: <can add, remove and save filter in the spreadsheet> // default = true
modifyContentControl: <can modify content controls in documenteditor> // default = true
fillForms: <can edit forms in view mode> // default = edit || review,
copy: <can copy data> // default = true,
editCommentAuthorOnly: <can edit your own comments only> // default = false
deleteCommentAuthorOnly: <can delete your own comments only> // default = false,
reviewGroups: ["Group1", ""] // current user can accept/reject review changes made by users from Group1 and users without a group. [] - use groups, but can't change any group's changes
commentGroups: { // {} - use groups, but can't view/edit/delete any group's comments
view: ["Group1", ""] // current user can view comments made by users from Group1 and users without a group.
edit: ["Group1", ""] // current user can edit comments made by users from Group1 and users without a group.
remove: ["Group1", ""] // current user can remove comments made by users from Group1 and users without a group.
}
}
},
editorConfig: {
actionLink: { // open file and scroll to data, used with onMakeActionLink or the onRequestSendNotify event
action: {
type: "bookmark", // or type="comment"
data: <bookmark name> // or comment id
}
},
mode: 'view or edit',
lang: <language code>,
location: <location>,
canCoAuthoring: <can coauthoring documents>,
canBackToFolder: <can return to folder> - deprecated. use "customization.goback" parameter,
createUrl: 'create document url',
sharingSettingsUrl: 'document sharing settings url',
fileChoiceUrl: 'source url', // for mail merge or image from storage
callbackUrl: <url for connection between sdk and portal>,
mergeFolderUrl: 'folder for saving merged file', // must be deprecated, use saveAsUrl instead
saveAsUrl: 'folder for saving files'
licenseUrl: <url for license>,
customerId: <customer id>,
region: <regional settings> // can be 'en-us' or lang code
user: {
id: 'user id',
name: 'user name',
group: 'group name' // for customization.reviewPermissions parameter
},
recent: [
{
title: 'document title',
url: 'document url',
folder: 'path to document',
},
...
],
templates: [
{
title: 'template name', // name - is deprecated
image: 'template icon url',
url: 'http://...'
},
...
],
customization: {
logo: {
image: url,
imageEmbedded: url,
url: http://...
},
customer: {
name: 'SuperPuper',
address: 'New-York, 125f-25',
mail: 'support@gmail.com',
www: 'www.superpuper.com',
info: 'Some info',
logo: ''
},
about: true,
feedback: {
visible: false,
url: http://...
},
goback: {
url: 'http://...',
text: 'Go to London',
blank: true,
requestClose: false // if true - goback send onRequestClose event instead opening url
},
reviewPermissions: {
"Group1": ["Group2"], // users from Group1 can accept/reject review changes made by users from Group2
"Group2": ["Group1", "Group2"] // users from Group2 can accept/reject review changes made by users from Group1 and Group2
"Group3": [""] // users from Group3 can accept/reject review changes made by users without a group
},
anonymous: { // set name for anonymous user
request: bool (default: true), // enable set name
label: string (default: "Guest") // postfix for user name
},
review: {
hideReviewDisplay: false, // hide button Review mode
hoverMode: false // true - show review balloons on mouse move, not on click on text
},
chat: true,
comments: true,
zoom: 100,
compactToolbar: false,
leftMenu: true,
rightMenu: true,
hideRightMenu: false, // hide or show right panel on first loading
toolbar: true,
statusBar: true,
autosave: true,
forcesave: false,
commentAuthorOnly: false, // must be deprecated. use permissions.editCommentAuthorOnly and permissions.deleteCommentAuthorOnly instead
showReviewChanges: false,
help: true,
compactHeader: false,
toolbarNoTabs: false,
toolbarHideFileName: false,
reviewDisplay: 'original', // original for viewer, markup for editor
spellcheck: true,
compatibleFeatures: false,
unit: 'cm' // cm, pt, inch,
mentionShare : true // customize tooltip for mention,
macros: true // can run macros in document
plugins: true // can run plugins in document
macrosMode: 'warn' // warn about automatic macros, 'enable', 'disable', 'warn',
trackChanges: undefined // true/false - open editor with track changes mode on/off,
hideRulers: false // hide or show rulers on first loading (presentation or document editor)
hideNotes: false // hide or show notes panel on first loading (presentation editor)
uiTheme: 'theme-dark' // set interface theme: id or default-dark/default-light
},
coEditing: {
mode: 'fast', // <coauthoring mode>, 'fast' or 'strict'. if 'fast' and 'customization.autosave'=false -> set 'customization.autosave'=true
change: true, // can change co-authoring mode
},
plugins: {
autostart: ['asc.{FFE1F462-1EA2-4391-990D-4CC84940B754}'],
pluginsData: [
"helloworld/config.json",
"chess/config.json",
"speech/config.json",
"clipart/config.json",
]
},
wopi: { // only for wopi
FileNameMaxLength: 250 // max filename length for rename, 250 by default
}
},
events: {
'onAppReady': <application ready callback>,
'onDocumentStateChange': <document state changed callback>
'onDocumentReady': <document ready callback>
'onRequestEditRights': <request rights for switching from view to edit>,
'onRequestHistory': <request version history>,// must call refreshHistory method
'onRequestHistoryData': <request version data>,// must call setHistoryData method
'onRequestRestore': <try to restore selected version>,
'onRequestHistoryClose': <request closing history>,
'onError': <error callback>,
'onWarning': <warning callback>,
'onInfo': <document open callback>,// send view or edit mode
'onOutdatedVersion': <outdated version callback>,// send when previous version is opened
'onDownloadAs': <download as callback>,// send url of downloaded file as a response for downloadAs method
'onRequestSaveAs': <try to save copy of the document>,
'onCollaborativeChanges': <co-editing changes callback>,// send when other user co-edit document
'onRequestRename': <try to rename document>,
'onMetaChange': // send when meta information changed
'onRequestClose': <request close editor>,
'onMakeActionLink': <request link to document with bookmark, comment...>,// must call setActionLink method
'onRequestUsers': <request users list for mentions>,// must call setUsers method
'onRequestSendNotify': //send when user is mentioned in a comment,
'onRequestInsertImage': <try to insert image>,// must call insertImage method
'onRequestCompareFile': <request file to compare>,// must call setRevisedFile method
'onRequestSharingSettings': <request sharing settings>,// must call setSharingSettings method
'onRequestCreateNew': <try to create document>,
}
}
# Embedded #
config = {
type: 'embedded',
width: '100% by default',
height: '100% by default',
documentType: 'word' | 'cell' | 'slide',// deprecate 'text' | 'spreadsheet' | 'presentation',
document: {
title: 'document title',
url: 'document url',
fileType: 'document file type',
key: 'key',
vkey: 'vkey'
},
editorConfig: {
licenseUrl: <url for license>,
customerId: <customer id>,
autostart: 'document', // action for app's autostart. for presentations default value is 'player'
embedded: {
embedUrl: 'url',
fullscreenUrl: 'url',
saveUrl: 'url',
shareUrl: 'url',
toolbarDocked: 'top or bottom'
}
},
events: {
'onAppReady': <application ready callback>,
'onBack': <back to folder callback>,
'onError': <error callback>,
'onDocumentReady': <document ready callback>,
'onWarning': <warning callback>
}
}
*/
// TODO: allow several instances on one page simultaneously
DocsAPI.DocEditor = function(placeholderId, config) {
var _self = this,
_config = config || {};
extend(_config, DocsAPI.DocEditor.defaultConfig);
_config.editorConfig.canUseHistory = _config.events && !!_config.events.onRequestHistory;
_config.editorConfig.canHistoryClose = _config.events && !!_config.events.onRequestHistoryClose;
_config.editorConfig.canHistoryRestore = _config.events && !!_config.events.onRequestRestore;
_config.editorConfig.canSendEmailAddresses = _config.events && !!_config.events.onRequestEmailAddresses;
_config.editorConfig.canRequestEditRights = _config.events && !!_config.events.onRequestEditRights;
_config.editorConfig.canRequestClose = _config.events && !!_config.events.onRequestClose;
_config.editorConfig.canRename = _config.events && !!_config.events.onRequestRename;
_config.editorConfig.canMakeActionLink = _config.events && !!_config.events.onMakeActionLink;
_config.editorConfig.canRequestUsers = _config.events && !!_config.events.onRequestUsers;
_config.editorConfig.canRequestSendNotify = _config.events && !!_config.events.onRequestSendNotify;
_config.editorConfig.mergeFolderUrl = _config.editorConfig.mergeFolderUrl || _config.editorConfig.saveAsUrl;
_config.editorConfig.canRequestSaveAs = _config.events && !!_config.events.onRequestSaveAs;
_config.editorConfig.canRequestInsertImage = _config.events && !!_config.events.onRequestInsertImage;
_config.editorConfig.canRequestMailMergeRecipients = _config.events && !!_config.events.onRequestMailMergeRecipients;
_config.editorConfig.canRequestCompareFile = _config.events && !!_config.events.onRequestCompareFile;
_config.editorConfig.canRequestSharingSettings = _config.events && !!_config.events.onRequestSharingSettings;
_config.editorConfig.canRequestCreateNew = _config.events && !!_config.events.onRequestCreateNew;
_config.frameEditorId = placeholderId;
_config.parentOrigin = window.location.origin;
var onMouseUp = function (evt) {
_processMouse(evt);
};
var _attachMouseEvents = function() {
if (window.addEventListener) {
window.addEventListener("mouseup", onMouseUp, false)
} else if (window.attachEvent) {
window.attachEvent("onmouseup", onMouseUp);
}
};
var _detachMouseEvents = function() {
if (window.removeEventListener) {
window.removeEventListener("mouseup", onMouseUp, false)
} else if (window.detachEvent) {
window.detachEvent("onmouseup", onMouseUp);
}
};
var _onAppReady = function() {
if (_config.type === 'mobile') {
document.body.onfocus = function(e) {
setTimeout(function(){
iframe.contentWindow.focus();
_sendCommand({
command: 'resetFocus',
data: {}
})
}, 10);
};
}
_attachMouseEvents();
if (_config.editorConfig) {
_init(_config.editorConfig);
}
if (_config.document) {
_openDocument(_config.document);
}
};
var _callLocalStorage = function(data) {
if (data.cmd == 'get') {
if (data.keys && data.keys.length) {
var af = data.keys.split(','), re = af[0];
for (i = 0; ++i < af.length;)
re += '|' + af[i];
re = new RegExp(re); k = {};
for (i in localStorage)
if (re.test(i)) k[i] = localStorage[i];
} else {
k = localStorage;
}
_sendCommand({
command: 'internalCommand',
data: {
type: 'localstorage',
keys: k
}
});
} else
if (data.cmd == 'set') {
var k = data.keys, i;
for (i in k) {
localStorage.setItem(i, k[i]);
}
}
};
var _onMessage = function(msg) {
if ( msg ) {
if ( msg.type === "onExternalPluginMessage" ) {
_sendCommand(msg);
} else if (msg.type === "onExternalPluginMessageCallback") {
postMessage(window.parent, msg);
} else
if ( msg.frameEditorId == placeholderId ) {
var events = _config.events || {},
handler = events[msg.event],
res;
if (msg.event === 'onRequestEditRights' && !handler) {
_applyEditRights(false, 'handler isn\'t defined');
} else if (msg.event === 'onInternalMessage' && msg.data && msg.data.type == 'localstorage') {
_callLocalStorage(msg.data.data);
} else {
if (msg.event === 'onAppReady') {
_onAppReady();
}
if (handler && typeof handler == "function") {
res = handler.call(_self, {target: _self, data: msg.data});
}
}
}
}
};
var _checkConfigParams = function() {
if (_config.document) {
if (!_config.document.url || ((typeof _config.document.fileType !== 'string' || _config.document.fileType=='') &&
(typeof _config.documentType !== 'string' || _config.documentType==''))) {
window.alert("One or more required parameter for the config object is not set");
return false;
}
var appMap = {
'text': 'docx',
'text-pdf': 'pdf',
'spreadsheet': 'xlsx',
'presentation': 'pptx',
'word': 'docx',
'cell': 'xlsx',
'slide': 'pptx'
}, app;
if (_config.documentType=='text' || _config.documentType=='spreadsheet' ||_config.documentType=='presentation')
console.warn("The \"documentType\" parameter for the config object must take one of the values word/cell/slide.");
if (typeof _config.documentType === 'string' && _config.documentType != '') {
app = appMap[_config.documentType.toLowerCase()];
if (!app) {
window.alert("The \"documentType\" parameter for the config object is invalid. Please correct it.");
return false;
} else if (typeof _config.document.fileType !== 'string' || _config.document.fileType == '') {
_config.document.fileType = app;
}
}
if (typeof _config.document.fileType === 'string' && _config.document.fileType != '') {
_config.document.fileType = _config.document.fileType.toLowerCase();
var type = /^(?:(xls|xlsx|ods|csv|xlst|xlsy|gsheet|xlsm|xlt|xltm|xltx|fods|ots)|(pps|ppsx|ppt|pptx|odp|pptt|ppty|gslides|pot|potm|potx|ppsm|pptm|fodp|otp)|(doc|docx|doct|odt|gdoc|txt|rtf|pdf|mht|htm|html|epub|djvu|xps|oxps|docm|dot|dotm|dotx|fodt|ott|fb2|xml))$/
.exec(_config.document.fileType);
if (!type) {
window.alert("The \"document.fileType\" parameter for the config object is invalid. Please correct it.");
return false;
} else if (typeof _config.documentType !== 'string' || _config.documentType == ''){
if (typeof type[1] === 'string') _config.documentType = 'cell'; else
if (typeof type[2] === 'string') _config.documentType = 'slide'; else
if (typeof type[3] === 'string') _config.documentType = 'word';
}
}
var type = /^(?:(pdf|djvu|xps|oxps))$/.exec(_config.document.fileType);
if (type && typeof type[1] === 'string') {
_config.editorConfig.canUseHistory = false;
}
if (!_config.document.title || _config.document.title=='')
_config.document.title = 'Unnamed.' + _config.document.fileType;
if (!_config.document.key) {
_config.document.key = 'xxxxxxxxxxxxxxxxxxxx'.replace(/[x]/g, function (c) {var r = Math.random() * 16 | 0; return r.toString(16);});
} else if (typeof _config.document.key !== 'string') {
window.alert("The \"document.key\" parameter for the config object must be string. Please correct it.");
return false;
}
if (_config.editorConfig.user && _config.editorConfig.user.id && (typeof _config.editorConfig.user.id == 'number')) {
_config.editorConfig.user.id = _config.editorConfig.user.id.toString();
console.warn("The \"id\" parameter for the editorConfig.user object must be a string.");
}
_config.document.token = _config.token;
}
return true;
};
(function() {
var result = /[\?\&]placement=(\w+)&?/.exec(window.location.search);
if (!!result && result.length) {
if (result[1] == 'desktop') {
_config.editorConfig.targetApp = result[1];
// _config.editorConfig.canBackToFolder = false;
if (!_config.editorConfig.customization) _config.editorConfig.customization = {};
_config.editorConfig.customization.about = false;
_config.editorConfig.customization.compactHeader = false;
}
}
})();
var target = document.getElementById(placeholderId),
iframe;
if (target && _checkConfigParams()) {
iframe = createIframe(_config);
if (iframe.src) {
var pathArray = iframe.src.split('/');
this.frameOrigin = pathArray[0] + '//' + pathArray[2];
}
target.parentNode && target.parentNode.replaceChild(iframe, target);
var _msgDispatcher = new MessageDispatcher(_onMessage, this);
}
/*
cmd = {
command: 'commandName',
data: <command specific data>
}
*/
var _destroyEditor = function(cmd) {
var target = document.createElement("div");
target.setAttribute('id', placeholderId);
if (iframe) {
_msgDispatcher && _msgDispatcher.unbindEvents();
_detachMouseEvents();
iframe.parentNode && iframe.parentNode.replaceChild(target, iframe);
}
};
var _sendCommand = function(cmd) {
if (iframe && iframe.contentWindow)
postMessage(iframe.contentWindow, cmd);
};
var _init = function(editorConfig) {
_sendCommand({
command: 'init',
data: {
config: editorConfig
}
});
};
var _openDocument = function(doc) {
_sendCommand({
command: 'openDocument',
data: {
doc: doc
}
});
};
var _showMessage = function(title, msg) {
msg = msg || title;
_sendCommand({
command: 'showMessage',
data: {
msg: msg
}
});
};
var _applyEditRights = function(allowed, message) {
_sendCommand({
command: 'applyEditRights',
data: {
allowed: allowed,
message: message
}
});
};
var _processSaveResult = function(result, message) {
_sendCommand({
command: 'processSaveResult',
data: {
result: result,
message: message
}
});
};
// TODO: remove processRightsChange, use denyEditingRights
var _processRightsChange = function(enabled, message) {
_sendCommand({
command: 'processRightsChange',
data: {
enabled: enabled,
message: message
}
});
};
var _denyEditingRights = function(message) {
_sendCommand({
command: 'processRightsChange',
data: {
enabled: false,
message: message
}
});
};
var _refreshHistory = function(data, message) {
_sendCommand({
command: 'refreshHistory',
data: {
data: data,
message: message
}
});
};
var _setHistoryData = function(data, message) {
_sendCommand({
command: 'setHistoryData',
data: {
data: data,
message: message
}
});
};
var _setEmailAddresses = function(data) {
_sendCommand({
command: 'setEmailAddresses',
data: {
data: data
}
});
};
var _setActionLink = function (data) {
_sendCommand({
command: 'setActionLink',
data: {
url: data
}
});
};
var _processMailMerge = function(enabled, message) {
_sendCommand({
command: 'processMailMerge',
data: {
enabled: enabled,
message: message
}
});
};
var _downloadAs = function(data) {
_sendCommand({
command: 'downloadAs',
data: data
});
};
var _setUsers = function(data) {
_sendCommand({
command: 'setUsers',
data: data
});
};
var _showSharingSettings = function(data) {
_sendCommand({
command: 'showSharingSettings',
data: data
});
};
var _setSharingSettings = function(data) {
_sendCommand({
command: 'setSharingSettings',
data: data
});
};
var _insertImage = function(data) {
_sendCommand({
command: 'insertImage',
data: data
});
};
var _setMailMergeRecipients = function(data) {
_sendCommand({
command: 'setMailMergeRecipients',
data: data
});
};
var _setRevisedFile = function(data) {
_sendCommand({
command: 'setRevisedFile',
data: data
});
};
var _setFavorite = function(data) {
_sendCommand({
command: 'setFavorite',
data: data
});
};
var _requestClose = function(data) {
_sendCommand({
command: 'requestClose',
data: data
});
};
var _processMouse = function(evt) {
var r = iframe.getBoundingClientRect();
var data = {
type: evt.type,
x: evt.x - r.left,
y: evt.y - r.top,
event: evt
};
_sendCommand({
command: 'processMouse',
data: data
});
};
var _grabFocus = function(data) {
setTimeout(function(){
_sendCommand({
command: 'grabFocus',
data: data
});
}, 10);
};
var _blurFocus = function(data) {
_sendCommand({
command: 'blurFocus',
data: data
});
};
var _serviceCommand = function(command, data) {
_sendCommand({
command: 'internalCommand',
data: {
command: command,
data: data
}
});
};
return {
showMessage : _showMessage,
processSaveResult : _processSaveResult,
processRightsChange : _processRightsChange,
denyEditingRights : _denyEditingRights,
refreshHistory : _refreshHistory,
setHistoryData : _setHistoryData,
setEmailAddresses : _setEmailAddresses,
setActionLink : _setActionLink,
processMailMerge : _processMailMerge,
downloadAs : _downloadAs,
serviceCommand : _serviceCommand,
attachMouseEvents : _attachMouseEvents,
detachMouseEvents : _detachMouseEvents,
destroyEditor : _destroyEditor,
setUsers : _setUsers,
showSharingSettings : _showSharingSettings,
setSharingSettings : _setSharingSettings,
insertImage : _insertImage,
setMailMergeRecipients: _setMailMergeRecipients,
setRevisedFile : _setRevisedFile,
setFavorite : _setFavorite,
requestClose : _requestClose,
grabFocus : _grabFocus,
blurFocus : _blurFocus
}
};
DocsAPI.DocEditor.defaultConfig = {
type: 'desktop',
width: '100%',
height: '100%',
editorConfig: {
lang: 'en',
canCoAuthoring: true,
customization: {
about: true,
feedback: false
}
}
};
DocsAPI.DocEditor.version = function() {
return '0.0.0';
};
MessageDispatcher = function(fn, scope) {
var _fn = fn,
_scope = scope || window,
eventFn = function(msg) {
_onMessage(msg);
};
var _bindEvents = function() {
if (window.addEventListener) {
window.addEventListener("message", eventFn, false)
}
else if (window.attachEvent) {
window.attachEvent("onmessage", eventFn);
}
};
var _unbindEvents = function() {
if (window.removeEventListener) {
window.removeEventListener("message", eventFn, false)
}
else if (window.detachEvent) {
window.detachEvent("onmessage", eventFn);
}
};
var _onMessage = function(msg) {
// TODO: check message origin
if (msg && window.JSON && _scope.frameOrigin==msg.origin ) {
try {
var msg = window.JSON.parse(msg.data);
if (_fn) {
_fn.call(_scope, msg);
}
} catch(e) {}
}
};
_bindEvents.call(this);
return {
unbindEvents: _unbindEvents
}
};
function getBasePath() {
var scripts = document.getElementsByTagName('script'),
match;
for (var i = scripts.length - 1; i >= 0; i--) {
match = scripts[i].src.match(/(.*)api\/documents\/api.js/i);
if (match) {
return match[1];
}
}
return "";
}
function getExtensionPath() {
if ("undefined" == typeof(extensionParams) || null == extensionParams["url"])
return null;
return extensionParams["url"] + "apps/";
}
function getAppPath(config) {
var extensionPath = getExtensionPath(),
path = extensionPath ? extensionPath : getBasePath(),
appMap = {
'text': 'documenteditor',
'text-pdf': 'documenteditor',
'spreadsheet': 'spreadsheeteditor',
'presentation': 'presentationeditor',
'word': 'documenteditor',
'cell': 'spreadsheeteditor',
'slide': 'presentationeditor'
},
app = appMap['word'];
if (typeof config.documentType === 'string') {
app = appMap[config.documentType.toLowerCase()];
} else
if (!!config.document && typeof config.document.fileType === 'string') {
var type = /^(?:(xls|xlsx|ods|csv|xlst|xlsy|gsheet|xlsm|xlt|xltm|xltx|fods|ots)|(pps|ppsx|ppt|pptx|odp|pptt|ppty|gslides|pot|potm|potx|ppsm|pptm|fodp|otp))$/
.exec(config.document.fileType);
if (type) {
if (typeof type[1] === 'string') app = appMap['cell']; else
if (typeof type[2] === 'string') app = appMap['slide'];
}
}
var userAgent = navigator.userAgent.toLowerCase(),
check = function(regex){ return regex.test(userAgent); },
isIE = !check(/opera/) && (check(/msie/) || check(/trident/) || check(/edge/)),
isChrome = !isIE && check(/\bchrome\b/),
isSafari_mobile = !isIE && !isChrome && check(/safari/) && (navigator.maxTouchPoints>0);
path += app + "/";
/*
path += (config.type === "mobile" || isSafari_mobile)
? "mobile"
: (config.type === "embedded")
? "embed"
: "main";
*/
path += "main";
var index = "/index.html";
if (config.editorConfig) {
var customization = config.editorConfig.customization;
if ( typeof(customization) == 'object' && ( customization.toolbarNoTabs ||
(config.editorConfig.targetApp!=='desktop') && (customization.loaderName || customization.loaderLogo))) {
index = "/index_loader.html";
} else if (config.editorConfig.mode == 'editdiagram' || config.editorConfig.mode == 'editmerge')
index = "/index_internal.html";
}
path += index;
return path;
}
function getAppParameters(config) {
var params = "?_dc=0";
if (config.editorConfig && config.editorConfig.lang)
params += "&lang=" + config.editorConfig.lang;
if (config.editorConfig && config.editorConfig.targetApp!=='desktop') {
if ( (typeof(config.editorConfig.customization) == 'object') && config.editorConfig.customization.loaderName) {
if (config.editorConfig.customization.loaderName !== 'none') params += "&customer=" + encodeURIComponent(config.editorConfig.customization.loaderName);
} else
params += "&customer=ONLYOFFICE";
if ( (typeof(config.editorConfig.customization) == 'object') && config.editorConfig.customization.loaderLogo) {
if (config.editorConfig.customization.loaderLogo !== '') params += "&logo=" + encodeURIComponent(config.editorConfig.customization.loaderLogo);
} else if ( (typeof(config.editorConfig.customization) == 'object') && config.editorConfig.customization.logo) {
if (config.type=='embedded' && config.editorConfig.customization.logo.imageEmbedded)
params += "&headerlogo=" + encodeURIComponent(config.editorConfig.customization.logo.imageEmbedded);
else if (config.type!='embedded' && config.editorConfig.customization.logo.image)
params += "&headerlogo=" + encodeURIComponent(config.editorConfig.customization.logo.image);
}
}
if (window.APP && window.APP.urlArgs) {
params += "&"+ window.APP.urlArgs;
}
if (config.editorConfig && (config.editorConfig.mode == 'editdiagram' || config.editorConfig.mode == 'editmerge'))
params += "&internal=true";
if (config.frameEditorId)
params += "&frameEditorId=" + config.frameEditorId;
if (config.editorConfig && config.editorConfig.mode == 'view' ||
config.document && config.document.permissions && (config.document.permissions.edit === false && !config.document.permissions.review ))
params += "&mode=view";
if (config.editorConfig && config.editorConfig.customization && !!config.editorConfig.customization.compactHeader)
params += "&compact=true";
if (config.editorConfig && config.editorConfig.customization && (config.editorConfig.customization.toolbar===false))
params += "&toolbar=false";
else if (config.document && config.document.permissions && (config.document.permissions.edit === false && config.document.permissions.fillForms ))
params += "&toolbar=true";
if (config.parentOrigin)
params += "&parentOrigin=" + config.parentOrigin;
if (config.editorConfig && config.editorConfig.customization && config.editorConfig.customization.uiTheme )
params += "&uitheme=" + config.editorConfig.customization.uiTheme;
return params;
}
function createIframe(config) {
var iframe = document.createElement("iframe");
iframe.src = getAppPath(config) + getAppParameters(config);
iframe.width = config.width;
iframe.height = config.height;
iframe.align = "top";
iframe.frameBorder = 0;
iframe.name = "frameEditor";
iframe.allowFullscreen = true;
iframe.setAttribute("allowfullscreen",""); // for IE11
iframe.setAttribute("onmousewheel",""); // for Safari on Mac
iframe.setAttribute("allow", "autoplay; camera; microphone; display-capture");
if (config.type == "mobile")
{
iframe.style.position = "fixed";
iframe.style.overflow = "hidden";
document.body.style.overscrollBehaviorY = "contain";
}
return iframe;
}
function postMessage(wnd, msg) {
if (wnd && wnd.postMessage && window.JSON) {
// TODO: specify explicit origin
wnd.postMessage(window.JSON.stringify(msg), "*");
}
}
function extend(dest, src) {
for (var prop in src) {
if (src.hasOwnProperty(prop)) {
if (typeof dest[prop] === 'undefined') {
dest[prop] = src[prop];
} else
if (typeof dest[prop] === 'object' &&
typeof src[prop] === 'object') {
extend(dest[prop], src[prop])
}
}
}
return dest;
}
})(window.DocsAPI = window.DocsAPI || {}, window, document);
| xwiki-labs/cryptpad | www/common/onlyoffice/v5/web-apps/apps/api/documents/api.js | JavaScript | agpl-3.0 | 40,934 |