<commit_before>(function (Q, $) {
/**
 * @module Q-tools
 */

/**
 * Implements lazy-loading for various types of elements.
 * By default, has implementations for "img" and "Q_tool" selectors.
 * The "Q_tool" handler only works with tools whose elements have a "data-q-lazyload" attribute .
 * Note that the elements must have a stable, nonzero width height set in the CSS even
 * if they are empty, otherwise they might not be lazy-loaded, and they might
 * thrash back and forth if removed.
 * @class Q lazyload
 * @constructor
 * @param {Object} [options] Override various options for this tool
 * @param {Array} [options.handle] Set this to
 * @param {Object} [options.handlers] You can modify the defaults by passing an object
 *    that looks like {handlerName: { selector: String, entering: Function, exiting: Function, preparing: Function}}
 *    Function "entering" receives (element, intersectionObserverEntry)
 *    Function "exiting" receives (element, intersectionObserverEntry)
 *    Function "preparing" receives (element) and is used the first time to prepare the element
 *    Both functions must return true if the element was modified.
 * @param {Object} [observerOptions] Override any options to pass to IntersectionObserver
 * @return {Q.Tool}
 */
Q.Tool.define('Q/lazyload', function (options) {

	var tool = this;
	var state = this.state;

	var Elp = Element.prototype;

	if (!window.IntersectionObserver) {
		console.warn("Q/lazyload tool: need to use IntersectionObserver polyfill");
		return; // do nothing, this is an older browser
	}

	// Observe whatever is on the page already
	tool.observer = _createObserver(tool, tool.element);
	tool.findAndObserve(tool.element, false);

	// Override innerHTML

	var originalSet = Object.getOwnPropertyDescriptor(Elp, 'innerHTML').set;
	var originalGet = Object.getOwnPropertyDescriptor(Elp, 'innerHTML').get;

	Object.defineProperty(Elp, 'innerHTML', {
		set: function (html) {
			var element = document.createElement('div');
			originalSet.call(element, html);
			var found = false;
			Q.each(state.handlers, function (name, info) {
				var elements = element.querySelectorAll
					? Array.from(element.querySelectorAll(info.selector))
					: [];
				if (elements.length) {
					found = true;
					return false;
				}
			});
			if (!found) {
				html = originalGet.call(element);
			}
			originalSet.call(this, html);
			if (found) {
				tool.findAndObserve(this, true);
			}
			return html;
		},
		get: originalGet
	});

	Q.each(['insertBefore', 'appendChild'], function (i, fn) {
		var orig = Elp[fn];
		Elp[fn] = function (element) {
			if (!element) {
				return;
			}
			tool.findAndObserve(element, true);
			return orig.apply(this, arguments);
		};
	});

},

{
	root: null,
	handlers: {
		img: {
			selector: 'img',
			entering: function (img, entry) {
				function _loaded() {
					img.addClass('Q_lazy_loaded');
				}
				var src = img.getAttribute('data-lazyload-src');
				if (src) {
					img.setAttribute('src', Q.url(src));
					img.removeAttribute('data-lazyload-src');
					img.addClass('Q_lazy_load');
					if (img.complete) {
						_loaded();
					}
					img.addEventListener('load', _loaded);
				}
				return true;
			},
			exiting: function (img) {
				// no need to do anything
				return true;
			},
			preparing: function (img, beingInsertedIntoDOM) {
				if (!beingInsertedIntoDOM) {
					return true; // too late anyway, browser will load image
				}
				var src = img.getAttribute('src');
				if (src && src.substr(0, 5) !== 'data:'
				&& !img.hasAttribute('data-lazyload-src')) {
					img.setAttribute('data-lazyload-src', Q.url(src));
					img.setAttribute('src', Q.url(
						Q.getObject('Q.images.lazyload.loadingSrc')
						|| "{{Q}}/img/throbbers/transparent.gif"
					));
				}
				return true;
			}
		},
		tool: {
			selector: '.Q_tool',
			entering: function (element, entry) {
				if (element.hasAttribute('data-q-lazyload')
				&& (!element.Q || !element.Q.tool)) {
					element.addClass('Q_lazy_load');
					Q.activate(element, function () {
						element.addClass('Q_lazy_loaded');
					}, {}, true);
					return true;
				}
			},
			exiting: function (element, entry) {
				if (element.hasAttribute('data-q-lazyload')
				&& element.Q.tool) {
					Q.Tool.remove(element);
					element.removeClass('Q_lazy_loading');
					element.removeClass('Q_lazy_loaded');
					if (this.state.handlers.tool.exitingRemoveHTML) {
						element.innerHTML = '';
					}
				}
				return true;
			},
			preparing: function (element) {
				return true;
			},
			exitingRemoveHTML: true
		}
	},
	observerOptions: {
		root: null,
		rootMargin: '0px',
		threshold: 0
	}
},

{
	findAndObserve: function (container, beingInsertedIntoDOM) {
		var tool = this;
		var found = [];
		Q.each(tool.state.handlers, function (name, info) {
			var elements = container.querySelectorAll
				? Array.from(container.querySelectorAll(info.selector))
				: [];
			if (container.matches && container.matches(info.selector)) {
				elements.push(container);
			}
			Q.each(elements, function (i, element) {
				if (info.preparing.call(tool, element, beingInsertedIntoDOM) === true) {
					found.push(element);
					tool.observer.observe(element);
				}
			});
		});
		return found;
	}
});

function _createObserver(tool, container) {
	return new IntersectionObserver(function (entries, observer) {
		Q.each(entries, function (i, entry) {
			Q.each(tool.state.handlers, function (name, info) {
				if (entry.target.matches && entry.target.matches(info.selector)) {
					if (entry.isIntersecting) {
						info.entering.call(tool, entry.target, entry);
					} else  {
						var rect = entry.target.getBoundingClientRect();
						if (rect.width > 0 && rect.height > 0) {
							// also covers !document.body.contains(entry.target)
							info.exiting.call(tool, entry.target, entry);
						} // otherwise it might get a false positive
					}
				}
			});
		});
	}, tool.state.observerOptions);
}

})(Q, jQuery);<commit_msg>Restoring previous commit<commit_after>(function (Q, $) {
/**
 * @module Q-tools
 */

/**
 * Implements lazy-loading for various types of elements.
 * By default, has implementations for "img" and "Q_tool" selectors.
 * The "Q_tool" handler only works with tools whose elements have a "data-q-lazyload" attribute .
 * Note that the elements must have a stable, nonzero width height set in the CSS even
 * if they are empty, otherwise they might not be lazy-loaded, and they might
 * thrash back and forth if removed.
 * @class Q lazyload
 * @constructor
 * @param {Object} [options] Override various options for this tool
 * @param {Array} [options.handle] Set this to
 * @param {Object} [options.handlers] You can modify the defaults by passing an object
 *    that looks like {handlerName: { selector: String, entering: Function, exiting: Function, preparing: Function}}
 *    Function "entering" receives (element, intersectionObserverEntry)
 *    Function "exiting" receives (element, intersectionObserverEntry)
 *    Function "preparing" receives (element) and is used the first time to prepare the element
 *    Both functions must return true if the element was modified.
 * @param {Object} [observerOptions] Override any options to pass to IntersectionObserver
 * @return {Q.Tool}
 */
Q.Tool.define('Q/lazyload', function (options) {

	var tool = this;
	var state = this.state;

	var Elp = Element.prototype;

	if (!window.IntersectionObserver) {
		console.warn("Q/lazyload tool: need to use IntersectionObserver polyfill");
		return; // do nothing, this is an older browser
	}

	// Observe whatever is on the page already
	tool.observer = _createObserver(tool, tool.element);
	tool.findAndObserve(tool.element, false);

	// Override innerHTML

	var originalSet = Object.getOwnPropertyDescriptor(Elp, 'innerHTML').set;
	var originalGet = Object.getOwnPropertyDescriptor(Elp, 'innerHTML').get;

	Object.defineProperty(Elp, 'innerHTML', {
		set: function (html) {
			var element = document.createElement('div');
			originalSet.call(element, html);
			var found = false;
			Q.each(state.handlers, function (name, info) {
				var elements = element.querySelectorAll
					? Array.from(element.querySelectorAll(info.selector))
					: [];
				if (elements.length) {
					found = true;
					return false;
				}
			});
			if (found) {
				html = originalGet.call(element);
			}
			originalSet.call(this, html);
			if (found) {
				tool.findAndObserve(this, true);
			}
			return html;
		},
		get: originalGet
	});

	Q.each(['insertBefore', 'appendChild'], function (i, fn) {
		var orig = Elp[fn];
		Elp[fn] = function (element) {
			if (!element) {
				return;
			}
			tool.findAndObserve(element, true);
			return orig.apply(this, arguments);
		};
	});

},

{
	root: null,
	handlers: {
		img: {
			selector: 'img',
			entering: function (img, entry) {
				function _loaded() {
					img.addClass('Q_lazy_loaded');
				}
				var src = img.getAttribute('data-lazyload-src');
				if (src) {
					img.setAttribute('src', Q.url(src));
					img.removeAttribute('data-lazyload-src');
					img.addClass('Q_lazy_load');
					if (img.complete) {
						_loaded();
					}
					img.addEventListener('load', _loaded);
				}
				return true;
			},
			exiting: function (img) {
				// no need to do anything
				return true;
			},
			preparing: function (img, beingInsertedIntoDOM) {
				if (!beingInsertedIntoDOM) {
					return true; // too late anyway, browser will load image
				}
				var src = img.getAttribute('src');
				if (src && src.substr(0, 5) !== 'data:'
				&& !img.hasAttribute('data-lazyload-src')) {
					img.setAttribute('data-lazyload-src', Q.url(src));
					img.setAttribute('src', Q.url(
						Q.getObject('Q.images.lazyload.loadingSrc')
						|| "{{Q}}/img/throbbers/transparent.gif"
					));
				}
				return true;
			}
		},
		tool: {
			selector: '.Q_tool',
			entering: function (element, entry) {
				if (element.hasAttribute('data-q-lazyload')
				&& (!element.Q || !element.Q.tool)) {
					element.addClass('Q_lazy_load');
					Q.activate(element, function () {
						element.addClass('Q_lazy_loaded');
					}, {}, true);
					return true;
				}
			},
			exiting: function (element, entry) {
				if (element.hasAttribute('data-q-lazyload')
				&& element.Q.tool) {
					Q.Tool.remove(element);
					element.removeClass('Q_lazy_loading');
					element.removeClass('Q_lazy_loaded');
					if (this.state.handlers.tool.exitingRemoveHTML) {
						element.innerHTML = '';
					}
				}
				return true;
			},
			preparing: function (element) {
				return true;
			},
			exitingRemoveHTML: true
		}
	},
	observerOptions: {
		root: null,
		rootMargin: '0px',
		threshold: 0
	}
},

{
	findAndObserve: function (container, beingInsertedIntoDOM) {
		var tool = this;
		var found = [];
		Q.each(tool.state.handlers, function (name, info) {
			var elements = container.querySelectorAll
				? Array.from(container.querySelectorAll(info.selector))
				: [];
			if (container.matches && container.matches(info.selector)) {
				elements.push(container);
			}
			Q.each(elements, function (i, element) {
				if (info.preparing.call(tool, element, beingInsertedIntoDOM) === true) {
					found.push(element);
					tool.observer.observe(element);
				}
			});
		});
		return found;
	}
});

function _createObserver(tool, container) {
	return new IntersectionObserver(function (entries, observer) {
		Q.each(entries, function (i, entry) {
			Q.each(tool.state.handlers, function (name, info) {
				if (entry.target.matches && entry.target.matches(info.selector)) {
					if (entry.isIntersecting) {
						info.entering.call(tool, entry.target, entry);
					} else  {
						var rect = entry.target.getBoundingClientRect();
						if (rect.width > 0 && rect.height > 0) {
							// also covers !document.body.contains(entry.target)
							info.exiting.call(tool, entry.target, entry);
						} // otherwise it might get a false positive
					}
				}
			});
		});
	}, tool.state.observerOptions);
}

})(Q, jQuery);<|endoftext|>


<commit_before>#!/usr/bin/env node
var child_process = require('child_process');

function log(msg) {
	process.stdout.write(msg + '\n');
}

module.exports = function(context) {
	var fs = context.requireCordovaModule('fs');
	var path = context.requireCordovaModule('path');
	var deferral = context.requireCordovaModule('q').defer();
	var XmlHelpers = context.requireCordovaModule("cordova-lib/src/util/xml-helpers");
	var et = context.requireCordovaModule('elementtree');

	var configFile = path.join(context.opts.projectRoot, 'config.xml');
	var xml = XmlHelpers.parseElementtreeSync(configFile);

	var addHook = function() {
		var getParent = function(tag, name) {
			var list = xml.findall(tag);
			var ios;
			list.forEach(function(e) {
				if (e.get('name') === name) ios = e;
			});
			log('Found platform(name=ios): ' + ios);
			if (!ios) {
				log('Creating tag: ' + tag + '(name=' + name + ')');
				ios = et.Element(tag, {name: name});
				xml.getroot().append(ios);
			}
			return ios;
		}
		var script_path = path.join(path.dirname(context.scriptLocation), 'add-bridging_header.rb');
		var child = et.Element('hook', {type: "after_prepare", src: script_path});
		getParent('platform', 'ios').append(child);

		fs.writeFileSync(configFile, xml.write({indent: 4}), 'utf-8');
	}

	var cocoapods = function() {
		var target;
		xml.findall('preference').forEach(function(e) {
			if (e.get('name') === 'deployment-target') target = e.get('value');
		});
		if (!target) target = "8.0";

		var podfile = path.join(context.opts.projectRoot, 'platforms', 'ios', 'Podfile');
		fs.writeFileSync(file_path, "platform :ios,'" + target + "'\n\n");
	}

	var main = function() {
		log("################################ Start preparing");
		addHook();
		cocoapods();
		log("################################ Finish preparing\n");
		deferral.resolve();
	}
	main();
	return deferral.promise;
};
<commit_msg>変数名を修正<commit_after>#!/usr/bin/env node
var child_process = require('child_process');

function log(msg) {
	process.stdout.write(msg + '\n');
}

module.exports = function(context) {
	var fs = context.requireCordovaModule('fs');
	var path = context.requireCordovaModule('path');
	var deferral = context.requireCordovaModule('q').defer();
	var XmlHelpers = context.requireCordovaModule("cordova-lib/src/util/xml-helpers");
	var et = context.requireCordovaModule('elementtree');

	var configFile = path.join(context.opts.projectRoot, 'config.xml');
	var xml = XmlHelpers.parseElementtreeSync(configFile);

	var addHook = function() {
		var getParent = function(tag, name) {
			var list = xml.findall(tag);
			var ios;
			list.forEach(function(e) {
				if (e.get('name') === name) ios = e;
			});
			log('Found platform(name=ios): ' + ios);
			if (!ios) {
				log('Creating tag: ' + tag + '(name=' + name + ')');
				ios = et.Element(tag, {name: name});
				xml.getroot().append(ios);
			}
			return ios;
		}
		var script_path = path.join(path.dirname(context.scriptLocation), 'add-bridging_header.rb');
		var child = et.Element('hook', {type: "after_prepare", src: script_path});
		getParent('platform', 'ios').append(child);

		fs.writeFileSync(configFile, xml.write({indent: 4}), 'utf-8');
	}

	var cocoapods = function() {
		var target;
		xml.findall('preference').forEach(function(e) {
			if (e.get('name') === 'deployment-target') target = e.get('value');
		});
		if (!target) target = "8.0";

		var podfile = path.join(context.opts.projectRoot, 'platforms', 'ios', 'Podfile');
		fs.writeFileSync(podfile, "platform :ios,'" + target + "'\n\n");
	}

	var main = function() {
		log("################################ Start preparing");
		addHook();
		cocoapods();
		log("################################ Finish preparing\n");
		deferral.resolve();
	}
	main();
	return deferral.promise;
};
<|endoftext|>


<commit_before>{
	"translatorID":"c159dcfe-8a53-4301-a499-30f6549c340d",
	"translatorType":4,
	"label":"DOI",
	"creator":"Simon Kornblith",
	"target":null,
	"minVersion":"1.0.10",
	"maxVersion":"",
	"priority":300,
	"browserSupport":"gcs",
	"inRepository":true,
	"lastUpdated":"2011-06-23 08:58:22"
}

var items = {};
var selectArray = {};

// builds a list of DOIs
function getDOIs(doc) {
	// TODO Detect DOIs more correctly.
	// The actual rules for DOIs are very lax-- but we're more strict.
	// Specifically, we should allow space characters, and all Unicode
	// characters except for control characters. Here, we're cheating
	// by not allowing ampersands, to fix an issue with getting DOIs
	// out of URLs.
	// Description at: http://www.doi.org/handbook_2000/appendix_1.html#A1-4
	const DOIre = /\b(10\.[\w.]+\/[^\s&]+)\.?\b/igm;
	const DOIXPath = "//text()[contains(., '10.')]";

	DOIre.lastMatch = 0;
	var DOIs = [];

	var node, m;
	var results = doc.evaluate(DOIXPath, doc, null, XPathResult.ANY_TYPE, null);
	while(node = results.iterateNext()) {
		while(m = DOIre.exec(node.nodeValue)) {
			var DOI = m[1];
			if(DOI.substr(-1) == ")" && DOI.indexOf("(") == -1) {
				DOI = DOI.substr(0, DOI.length-1);
			}
			// only add new DOIs
			if(DOIs.indexOf(DOI) == -1) {
				DOIs.push(DOI);
			}
		}
	}

	return DOIs;
}

function detectWeb(doc, url) {
	const blacklistRe = /^https?:\/\/[^/]*google\.com/i;

	if(!blacklistRe.test(url)) {
		var DOIs = getDOIs(doc);
		if(DOIs.length) {
			return DOIs.length == 1 ? "journalArticle" : "multiple";
		}
	}
	return false;
}

function retrieveNextDOI(DOIs, doc) {
	if(DOIs.length) {
		// retrieve DOI
		var DOI = DOIs.shift();
		var translate = Zotero.loadTranslator("search");
		translate.setTranslator("11645bd1-0420-45c1-badb-53fb41eeb753");
		var item = {"itemType":"journalArticle", "DOI":DOI};
		translate.setSearch(item);
		// don't save when item is done
		translate.setHandler("itemDone", function(translate, item) {
			item.repository = "CrossRef";
			items[DOI] = item;
			selectArray[DOI] = item.title;
		});
		translate.setHandler("done", function(translate) {
			retrieveNextDOI(DOIs, doc);
		});
		translate.translate();
	} else {
		// all DOIs retrieved now
		// check to see if there is more than one DOI
		var numDOIs = 0;
		for(var DOI in selectArray) {
			numDOIs++;
			if(numDOIs == 2) break;
		}
		if(numDOIs == 0) {
			throw "DOI Translator: could not find DOI";
		} else if(numDOIs == 1) {
			// do we want to add URL of the page?
			items[DOI].url = doc.location.href;
			items[DOI].attachments = [{document:doc}];
			items[DOI].complete();
		} else {
			selectArray = Zotero.selectItems(selectArray);
			for(var DOI in selectArray) {
				items[DOI].complete();
			}
		}
		Zotero.done();
	}
}

function doWeb(doc, url) {
	var DOIs = getDOIs(doc);
	// retrieve full items asynchronously
	Zotero.wait();
	retrieveNextDOI(DOIs, doc);
}
<commit_msg>Also add tests to DOI translator<commit_after>var items = {};
var selectArray = {};

// builds a list of DOIs
function getDOIs(doc) {
	// TODO Detect DOIs more correctly.
	// The actual rules for DOIs are very lax-- but we're more strict.
	// Specifically, we should allow space characters, and all Unicode
	// characters except for control characters. Here, we're cheating
	// by not allowing ampersands, to fix an issue with getting DOIs
	// out of URLs.
	// Description at: http://www.doi.org/handbook_2000/appendix_1.html#A1-4
	const DOIre = /\b(10\.[\w.]+\/[^\s&]+)\.?\b/igm;
	const DOIXPath = "//text()[contains(., '10.')]";

	DOIre.lastMatch = 0;
	var DOIs = [];

	var node, m;
	var results = doc.evaluate(DOIXPath, doc, null, XPathResult.ANY_TYPE, null);
	while(node = results.iterateNext()) {
		while(m = DOIre.exec(node.nodeValue)) {
			var DOI = m[1];
			if(DOI.substr(-1) == ")" && DOI.indexOf("(") == -1) {
				DOI = DOI.substr(0, DOI.length-1);
			}
			// only add new DOIs
			if(DOIs.indexOf(DOI) == -1) {
				DOIs.push(DOI);
			}
		}
	}

	return DOIs;
}

function detectWeb(doc, url) {
	const blacklistRe = /^https?:\/\/[^/]*google\.com/i;

	if(!blacklistRe.test(url)) {
		var DOIs = getDOIs(doc);
		if(DOIs.length) {
			return DOIs.length == 1 ? "journalArticle" : "multiple";
		}
	}
	return false;
}

function retrieveNextDOI(DOIs, doc) {
	if(DOIs.length) {
		// retrieve DOI
		var DOI = DOIs.shift();
		var translate = Zotero.loadTranslator("search");
		translate.setTranslator("11645bd1-0420-45c1-badb-53fb41eeb753");
		var item = {"itemType":"journalArticle", "DOI":DOI};
		translate.setSearch(item);
		// don't save when item is done
		translate.setHandler("itemDone", function(translate, item) {
			item.repository = "CrossRef";
			items[DOI] = item;
			selectArray[DOI] = item.title;
		});
		translate.setHandler("done", function(translate) {
			retrieveNextDOI(DOIs, doc);
		});
		translate.translate();
	} else {
		// all DOIs retrieved now
		// check to see if there is more than one DOI
		var numDOIs = 0;
		for(var DOI in selectArray) {
			numDOIs++;
			if(numDOIs == 2) break;
		}
		if(numDOIs == 0) {
			throw "DOI Translator: could not find DOI";
		} else if(numDOIs == 1) {
			// do we want to add URL of the page?
			items[DOI].url = doc.location.href;
			items[DOI].attachments = [{document:doc}];
			items[DOI].complete();
		} else {
			selectArray = Zotero.selectItems(selectArray);
			for(var DOI in selectArray) {
				items[DOI].complete();
			}
		}
		Zotero.done();
	}
}

function doWeb(doc, url) {
	var DOIs = getDOIs(doc);
	// retrieve full items asynchronously
	Zotero.wait();
	retrieveNextDOI(DOIs, doc);
}

/** BEGIN TEST CASES **/
var testCases = [
	{
		"type": "web",
		"url": "http://www.crossref.org/help/Content/01_About_DOIs/What_is_a_DOI.htm",
		"items": [
			{
				"itemType": "journalArticle",
				"creators": [
					{
						"creatorType": "author",
						"firstName": "J",
						"lastName": "Mou"
					}
				],
				"notes": [],
				"tags": [],
				"seeAlso": [],
				"attachments": [
					{
						"document": false
					}
				],
				"publicationTitle": "Journal of Molecular Biology",
				"volume": "248",
				"ISSN": "00222836",
				"date": "1995-5-5",
				"pages": "507-512",
				"DOI": "10.1006/jmbi.1995.0238",
				"url": "http://www.crossref.org/help/Content/01_About_DOIs/What_is_a_DOI.htm",
				"title": "Atomic Force Microscopy of Cholera Toxin B-oligomers Bound to Bilayers of Biologically Relevant Lipids",
				"libraryCatalog": "CrossRef"
			}
		]
	},
	{
		"type": "web",
		"url": "http://blog.apastyle.org/apastyle/digital-object-identifier-doi/",
		"items": "multiple"
	}
]
/** END TEST CASES **/<|endoftext|>


<commit_before>/*
 * Copyright 2016 e-UCM (http://www.e-ucm.es/)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * This project has received funding from the European Union's Horizon
 * 2020 research and innovation programme under grant agreement No 644187.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0 (link is external)
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

'use strict';

/**
 * This file issues the needed requests to set up the default kibana index. *
 */

var Path = require('path');
var config = require(Path.resolve(__dirname, '../config.js'));
var elasticsearch = require('elasticsearch');

var defaultKibanaIndexValue = config.kibana.defaultIndex;

var esClient = new elasticsearch.Client({
    host: config.elasticsearch.uri,
    api: '5.0'
});

esClient.ping({
    // Ping usually has a 3000ms timeout
    requestTimeout: 3000
}, function (error) {
    if (error) {
        console.trace('elasticsearch cluster is down!');
    } else {
        console.log('Successfully connected to elasticsearch: ' + config.elasticsearch.uri);
        setupDefaultKibanaIndex();
    }
});

var setupDefaultKibanaIndex = function () {
    esClient.search({
        index: '.kibana',
        type: 'config'
    }, function (error, response) {
        if (!error) {
            if (response.hits) {
                var hits = response.hits.hits;
                if (hits.length < 1) {

                    console.log('Did not configure kibana default index, continuing anyway!');
                    return process.exit(0);
                }

                esClient.index({
                    index: '.kibana',
                    type: 'index-pattern',
                    id: defaultKibanaIndexValue,
                    body: {
                        title: defaultKibanaIndexValue,
                        timeFieldName: 'timestamp',
                        fields: '[]'
                    }
                }, function (error, response) {
                    if (!error) {
                        esClient.index({
                            index: defaultKibanaIndexValue,
                            type: 'empty',
                            id: null,
                            body: {timestamp: new Date()}
                        }, function (error, response) {
                            if (!error) {
                                for (var i = 0; i < hits.length; ++i) {

                                    var appData = hits[i];
                                    if (!appData._source.defaultIndex) {
                                        appData._source.defaultIndex = defaultKibanaIndexValue;
                                        addDefaultIndex(appData);
                                    }
                                }

                            } else {
                                return handleError(error);
                            }
                        });

                    } else {
                        return handleError(error);
                    }
                });

            }
        } else {
            return handleError(error);
        }
    });
};

var addDefaultIndex = function(appData) {
    esClient.index({
        index: '.kibana',
        type: 'config',
        id: appData._id,
        body: appData._source
    }, function (error, response) {
        if (!error) {

            console.log('Default Kibana Index setup complete for', appData._id);
        } else {
            return handleError(error);
        }
    });
};

var handleError = function(error) {
    console.error(error);
    console.error('Could not connect to ElasticsearchDB!');
    console.log('Did not configure kibana default index, continuing anyway!');
    process.exit(0);
};
<commit_msg>Default _template location geo_point<commit_after>/*
 * Copyright 2016 e-UCM (http://www.e-ucm.es/)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * This project has received funding from the European Union's Horizon
 * 2020 research and innovation programme under grant agreement No 644187.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0 (link is external)
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

'use strict';

/**
 * This file issues the needed requests to set up the default kibana index. *
 */

var Path = require('path');
var request = require('request');
var config = require(Path.resolve(__dirname, '../config.js'));
var elasticsearch = require('elasticsearch');

var defaultKibanaIndexValue = config.kibana.defaultIndex;

request({
    uri: config.elasticsearch.uri + '/_templates/geopoint',
    method: 'PUT',
    body: {
      'order': 0,
      'template': '*',
      'settings': {},
      'mappings': {
        '_default_': {
          'properties': {
          	'ext': {
          		'type': 'object',
          		'properties': {
		            'location': {
		              'type': 'geo_point'
		            }
          		}
          	}
          }
        }
      }
    },
    json: true
}, function (err, httpResponse, body) {
    if (err) {
        console.error(err);
        console.log('Did not setup default Elasticsearch geopoint _template!');
    }

    console.log('Success setting up geopoint elasticsearch _template');
});

var esClient = new elasticsearch.Client({
    host: config.elasticsearch.uri,
    api: '5.0'
});

esClient.ping({
    // Ping usually has a 3000ms timeout
    requestTimeout: 3000
}, function (error) {
    if (error) {
        console.trace('elasticsearch cluster is down!');
    } else {
        console.log('Successfully connected to elasticsearch: ' + config.elasticsearch.uri);
        setupDefaultKibanaIndex();
    }
});

var setupDefaultKibanaIndex = function () {
    esClient.search({
        index: '.kibana',
        type: 'config'
    }, function (error, response) {
        if (!error) {
            if (response.hits) {
                var hits = response.hits.hits;
                if (hits.length < 1) {

                    console.log('Did not configure kibana default index, continuing anyway!');
                    return process.exit(0);
                }

                esClient.index({
                    index: '.kibana',
                    type: 'index-pattern',
                    id: defaultKibanaIndexValue,
                    body: {
                        title: defaultKibanaIndexValue,
                        timeFieldName: 'timestamp',
                        fields: '[]'
                    }
                }, function (error, response) {
                    if (!error) {
                        esClient.index({
                            index: defaultKibanaIndexValue,
                            type: 'empty',
                            id: null,
                            body: {timestamp: new Date()}
                        }, function (error, response) {
                            if (!error) {
                                for (var i = 0; i < hits.length; ++i) {

                                    var appData = hits[i];
                                    if (!appData._source.defaultIndex) {
                                        appData._source.defaultIndex = defaultKibanaIndexValue;
                                        addDefaultIndex(appData);
                                    }
                                }

                            } else {
                                return handleError(error);
                            }
                        });

                    } else {
                        return handleError(error);
                    }
                });

            }
        } else {
            return handleError(error);
        }
    });
};

var addDefaultIndex = function(appData) {
    esClient.index({
        index: '.kibana',
        type: 'config',
        id: appData._id,
        body: appData._source
    }, function (error, response) {
        if (!error) {

            console.log('Default Kibana Index setup complete for', appData._id);
        } else {
            return handleError(error);
        }
    });
};

var handleError = function(error) {
    console.error(error);
    console.error('Could not connect to ElasticsearchDB!');
    console.log('Did not configure kibana default index, continuing anyway!');
    process.exit(0);
};
<|endoftext|>


<commit_before>import Ember from 'ember';
import WidgetApplication from 'ember-eureka/widget-application';

export default WidgetApplication.extend({
    currentRouteName: Ember.computed.alias('application.currentRouteName'),

    menuItems: function() {
        var items = this.get('config.items');
        if (!items)  {

            var application = this.get('application');
            var modelTypesList = Ember.keys(Ember.get(application.config, 'structure.models'));
            items = Ember.A();
            var currentRouteName = this.get('currentRouteName');
            var item, route, isActive;

            modelTypesList.forEach(function(modelType) {
                route = modelType.dasherize();
                isActive = currentRouteName.split('.')[0] === route;

                item = Ember.Object.create({
                    label: modelType,
                    route: modelType.dasherize(),
                    isActive: isActive
                });

                items.pushObject(item);
            });
        }
        return items;
    }.property('config.items.[]', 'application', 'currentRouteName')
});
<commit_msg>keep up with new eureka<commit_after>import Ember from 'ember';
import WidgetApplication from 'ember-eureka/widget-application';

export default WidgetApplication.extend({

    menuItems: function() {

        var currentRouteName = this.get('currentRouteName');

        var items = this.get('config.items');
        if (!items)  {

            items = Ember.A();
            var models = this.get('currentController.appConfig.structure.models');

            var item, isActive, dasherizedModelType;
            Ember.keys(models).forEach(function(modelType) {

                // if the model has no view, skip it
                if (!Ember.get(models, modelType+'.views.collection.index')) {
                    return;
                }

                dasherizedModelType = modelType.dasherize();
                isActive = currentRouteName.split('.')[1] === dasherizedModelType;

                item = Ember.Object.create({
                    label: modelType,
                    route: 'eureka.'+dasherizedModelType,
                    isActive: isActive
                });

                items.pushObject(item);
            });

        } else {
            items = items.map(function(item) {
                item.isActive = currentRouteName === item.route;
                return item;
            });
        }

        return items;
    }.property('config.items.[]', 'currentRouteName')
});
<|endoftext|>


<commit_before>var uuid = 1;

class EmberComponent {
  constructor() {
    this.elementId = 'e6-components-' + (uuid++);
    this.isComponent = true;
  }

  trigger() {
    console.log('trigger', arguments);
  }

  static proto() {
  	return this.prototype;
  }

  static create() {
  	return new this(...arguments);
  }
}

EmberComponent.isComponentFactory = true;

export default EmberComponent;
<commit_msg>Fix typo in elementId.<commit_after>var uuid = 1;

class EmberComponent {
  constructor() {
    this.elementId = 'es6-components-' + (uuid++);
    this.isComponent = true;
  }

  trigger() {
    console.log('trigger', arguments);
  }

  static proto() {
  	return this.prototype;
  }

  static create() {
  	return new this(...arguments);
  }
}

EmberComponent.isComponentFactory = true;

export default EmberComponent;
<|endoftext|>


<commit_before>export { default as authenticated } from './-lib/authenticated';
export { default as JWT } from './-lib/jwt';
<commit_msg>fix: failed to export unauthenticated decorator<commit_after>export { default as authenticated } from './-lib/authenticated';
export { default as unauthenticated } from './-lib/unauthenticated';
export { default as JWT } from './-lib/jwt';
<|endoftext|>


<commit_before>(function($) {
    $.pfire = function(element, options) {
        var defaults = {
            'gravity':              .5,
            // Colors for particles?
            'colors':               'global',
            // Trail life
            'trail':                0.05,
            // Update Speed
            'fps':                  16,
            'color': {
                'r':                Math.random()*255>>0,
                'g':                Math.random()*255>>0,
                'b':                Math.random()*255>>0,
            },
            'max_velocity':         2,
            'velocity_multiplier':  1,
            'in_air_height':        50,
            'W':                    undefined,
            'H':                    undefined,
            'particles':            undefined
        }

        var plugin = this;

        plugin.settings = {}

        var $element = $(element),  // reference to the jQuery version of DOM element the plugin is attached to
             element = element;        // reference to the actual DOM element

        plugin.init = function() {
            plugin.settings = $.extend({}, defaults, options);

            if (!plugin.settings.W)
                plugin.settings.W = $element.width;
            if (!plugin.settings.H)
                plugin.settings.H = $element.height;

            plugin.updateSize(plugin.settings.W, plugin.settings.H);

            plugin.particles = [];
            plugin.ctx = element.getContext("2d");

            // Init some settings
            plugin.setGravity();

            // Clear canvas
            plugin.ctx.globalCompositeOperation = "destination-over";
            plugin.ctx.fillStyle = "rgba(0, 0, 0, 1)";
            plugin.ctx.fillRect(0, 0, plugin.settings.W, plugin.settings.H);

            if (plugin.settings.particles)
                plugin.addParticles(plugin.settings.particles);

            // Start rendering
            plugin.interval = setInterval(function() { plugin.draw(); }, plugin.settings.fps);

            $element.click(function(e){
                var target = event.target || event.srcElement;
                x = event.pageX - target.offsetLeft;
                y = event.pageY - target.offsetTop;
                plugin.starburst(x, y);
            })

        }

        plugin.addParticle = function() {
            plugin.particles.push(new plugin.particle(plugin));
            plugin.settings.particles += 1;
        }

        plugin.addParticles = function(count) {
            for(var i = 0; i < count; i++)
                plugin.addParticle();
            plugin.settings.particles += count;
        }

        plugin.setParticles = function(count) {
            while (plugin.particles.length > count)
                plugin.particles.pop();
            while (plugin.particles.length < count)
                plugin.addParticle();

            plugin.settings.particles = count;
        }

        plugin.draw = function() {
            plugin.ctx.globalCompositeOperation = "darker";
            plugin.ctx.fillStyle = "rgba(0, 0, 0, "+plugin.settings.trail+")";
            plugin.ctx.fillRect(0, 0, plugin.settings.W, plugin.settings.H);

            plugin.ctx.globalCompositeOperation = "lighter";

            var inair = 0;

            for(var t = 0; t < plugin.particles.length; t++)
            {
                var p = plugin.particles[t];
                p.draw(plugin.ctx);
                p.move();
                p.updateColor();

                if (t == 0)
                    plugin.settings.color = p.color;

                if (p.y < plugin.settings.H - plugin.settings.in_air_height)
                    inair = 1;
            }

            if (inair == 0) {
                if (Math.random() * 2>>0 == 0)
                    plugin.starburst();
                else
                    plugin.randomize();
            }
        }

        plugin.starburst = function(x, y) {
            if (!x)
                x = Math.random() * plugin.settings.W>>0;
            if (!y)
                y = Math.random() * plugin.settings.H>>0;
            d = 0;
            di = 360 / plugin.particles.length;

            for(var t = 0; t < plugin.particles.length; t++) {
                var p = plugin.particles[t];
                p.x = x;
                p.y = y;
                p.direction = d;
                d += di;
                p.setVelocity(Math.random() * 2);
            }
        }

        plugin.randomize = function() {
            for(var t = 0; t < plugin.particles.length; t++) {
                var p = plugin.particles[t];
                p.x = Math.random() * plugin.settings.W>>0;
                p.y = Math.random() * plugin.settings.H>>0;
                p.direction = Math.random() * 360;
                p.setVelocity(Math.random() * 2);
            }
        }

        plugin.updateSize = function(W, H) {
            element.style.width = W+"px";
            element.style.height = H+"px";

            W *= window.devicePixelRatio;
            H *= window.devicePixelRatio;

            plugin.settings.W = W;
            plugin.settings.H = H;

            element.width = W;
            element.height = H;
        }

        plugin.setGravity = function(gravity) {
            if (gravity)
                plugin.settings.gravity = gravity;
            plugin.settings.gpf = plugin.settings.gravity / (1000 / plugin.settings.fps);
        }

        plugin.particle = function(plugin) {
            this.x = Math.random()*plugin.settings.W>>0;
            this.y = Math.random()*plugin.settings.H>>0;

            // Degree of direction
            // 0-360
            this.direction = Math.random()*360>>0;

            this.color = {
                'r': Math.random()*255>>0,
                'g': Math.random()*255>>0,
                'b': Math.random()*255>>0,
            }

            this.size = 2 * window.devicePixelRatio;

            // Speed
            this.setVelocity = function(velocity) {
                this.velocity = velocity;
                this.vx = this.velocity * Math.cos(this.direction);
                this.vy = this.velocity * Math.sin(this.direction);
            }

            this.setVelocity(1);

            this.getColor = function() {
                if (plugin.settings.colors == 'global')
                    return "rgba("+plugin.settings.color.r+", "+plugin.settings.color.g+", "+plugin.settings.color.b+", 0.5)";
                else
                    return "rgba("+this.color.r+", "+this.color.g+", "+this.color.b+", 0.5)";
            }

            this.move = function() {
                this.x += this.vx * plugin.settings.velocity_multiplier;
                this.y += this.vy * plugin.settings.velocity_multiplier;

                this.vy += plugin.settings.gpf;

                if (this.x < 0) {
                    this.x = Math.abs(this.x);
                    this.vx *= -0.75;
                    this.direction = (2*270-this.direction-180);
                }
                if (this.x > plugin.settings.W) {
                    this.x = plugin.settings.W - (this.x - plugin.settings.W);
                    this.vx *= -0.75;
                    this.direction = (2*90-this.direction-180);
                }

                if (this.y < 0) {
                    this.y = Math.abs(this.y);
                    this.vy *= -0.75;
                    this.direction = (2*180-this.direction-180);
                }
                if (this.y > plugin.settings.H) {
                    this.y = plugin.settings.H - (this.y - plugin.settings.H);
                    this.vy *= -0.75;
                    this.direction = (2*0-this.direction-180);
                }

                if (this.direction < 0) {
                    this.direction += 360;
                }
                if (this.direction > 360) {
                    this.direction %= 360;
                }

                if (this.vx > plugin.settings.max_velocity)
                    this.vx = plugin.settings.max_velocity;
                if (this.vx < 0-plugin.settings.max_velocity)
                    this.vx = 0-plugin.settings.max_velocity;

                if (this.vy > plugin.settings.max_velocity)
                    this.vy = plugin.settings.max_velocity;
                if (this.vy < 0-plugin.settings.max_velocity)
                    this.vy = 0-plugin.settings.max_velocity;
            }

            this.draw = function(ctx) {
                ctx.beginPath();
                var gradient = ctx.createRadialGradient(this.x, this.y, 0, this.x, this.y, this.size);
                gradient.addColorStop(0, this.getColor());
                gradient.addColorStop(1, "black");

                ctx.fillStyle = gradient;
                ctx.arc(this.x, this.y, this.size, Math.PI*2, false);
                ctx.fill();
            }

            this.updateColor = function() {
                if (Math.random()*3>>0)
                    this.color.r = this.color.r + (Math.random()*7>>0)-3;

                if (Math.random()*3>>0)
                    this.color.g = this.color.g + (Math.random()*7>>0)-3;

                if (Math.random()*3>>0)
                    this.color.b = this.color.b + (Math.random()*7>>0)-3;

                if (this.color.r < 90) {
                    this.color.r = 90;
                }
                if (this.color.r > 255) {
                    this.color.r = 255;
                }

                if (this.color.g < 90) {
                    this.color.g = 90;
                }
                if (this.color.g > 255) {
                    this.color.g = 255;
                }

                if (this.color.g < 90) {
                    this.color.g = 90;
                }
                if (this.color.g > 255) {
                    this.color.g = 255;
                }
            }
        }

        plugin.init();
    }

    // add the plugin to the jQuery.fn object
    $.fn.pfire = function(options) {
        return this.each(function() {
            if (undefined == $(this).data('pfire')) {
                var plugin = new $.pfire(this, options);
                $(this).data('pfire', plugin);
            }
        });
    }
})(jQuery);
<commit_msg>JS Hints cleanly with /*jshint forin:true, noarg:true, noempty:true, eqeqeq:true, strict:true, undef:true, unused:true, curly:true, browser:true, jquery:true, indent:4, maxerr:50 */<commit_after>(function($) {
    'use strict';
    $.pfire = function(element, options) {
        var defaults = {
            'gravity':              0.5,
            // Colors for particles?
            'colors':               'global',
            // Trail life
            'trail':                0.05,
            // Update Speed
            'fps':                  16,
            'color': {
                'r':                (Math.random() * 255) >> 0,
                'g':                (Math.random() * 255) >> 0,
                'b':                (Math.random() * 255) >> 0
            },
            'max_velocity':         2,
            'velocity_multiplier':  1,
            'in_air_height':        50,
            'W':                    undefined,
            'H':                    undefined,
            'particles':            undefined
        };

        var plugin = this;

        plugin.settings = {};

        var $element = $(element);

        plugin.init = function() {
            plugin.settings = $.extend({}, defaults, options);

            if (!plugin.settings.W) {
                plugin.settings.W = $element.width;
            }
            if (!plugin.settings.H) {
                plugin.settings.H = $element.height;
            }

            plugin.updateSize(plugin.settings.W, plugin.settings.H);

            plugin.particles = [];
            plugin.ctx = element.getContext("2d");

            // Init some settings
            plugin.setGravity();

            // Clear canvas
            plugin.ctx.globalCompositeOperation = "destination-over";
            plugin.ctx.fillStyle = "rgba(0, 0, 0, 1)";
            plugin.ctx.fillRect(0, 0, plugin.settings.W, plugin.settings.H);

            if (plugin.settings.particles) {
                plugin.addParticles(plugin.settings.particles);
            }

            // Start rendering
            plugin.interval = setInterval(function() { plugin.draw(); }, plugin.settings.fps);

            $element.click(function(event) {
                var target = event.target || event.srcElement;
                var x = event.pageX - target.offsetLeft;
                var y = event.pageY - target.offsetTop;
                plugin.starburst(x, y);
            });

        };

        plugin.addParticle = function() {
            plugin.particles.push(new plugin.particle(plugin));
            plugin.settings.particles += 1;
        };

        plugin.addParticles = function(count) {
            for(var i = 0; i < count; i++) {
                plugin.addParticle();
            }
            plugin.settings.particles += count;
        };

        plugin.setParticles = function(count) {
            while (plugin.particles.length > count) {
                plugin.particles.pop();
            }
            while (plugin.particles.length < count) {
                plugin.addParticle();
            }

            plugin.settings.particles = count;
        };

        plugin.draw = function() {
            plugin.ctx.globalCompositeOperation = "darker";
            plugin.ctx.fillStyle = "rgba(0, 0, 0, "+plugin.settings.trail+")";
            plugin.ctx.fillRect(0, 0, plugin.settings.W, plugin.settings.H);

            plugin.ctx.globalCompositeOperation = "lighter";

            var inair = 0;

            for(var t = 0; t < plugin.particles.length; t++)
            {
                var p = plugin.particles[t];
                p.draw(plugin.ctx);
                p.move();
                p.updateColor();

                if (t === 0) {
                    plugin.settings.color = p.color;
                }

                if (p.y < plugin.settings.H - plugin.settings.in_air_height) {
                    inair = 1;
                }
            }

            if (inair === 0) {
                if (Math.random() * 2>>0 === 0) {
                    plugin.starburst();
                }
                else {
                    plugin.randomize();
                }
            }
        };

        plugin.starburst = function(x, y) {
            if (!x) {
                x = Math.random() * plugin.settings.W>>0;
            }
            if (!y) {
                y = Math.random() * plugin.settings.H>>0;
            }
            var d = 0;
            var di = 360 / plugin.particles.length;

            for(var t = 0; t < plugin.particles.length; t++) {
                var p = plugin.particles[t];
                p.x = x;
                p.y = y;
                p.direction = d;
                d += di;
                p.setVelocity(Math.random() * 2);
            }
        };

        plugin.randomize = function() {
            for(var t = 0; t < plugin.particles.length; t++) {
                var p = plugin.particles[t];
                p.x = Math.random() * plugin.settings.W>>0;
                p.y = Math.random() * plugin.settings.H>>0;
                p.direction = Math.random() * 360;
                p.setVelocity(Math.random() * 2);
            }
        };

        plugin.updateSize = function(W, H) {
            element.style.width = W+"px";
            element.style.height = H+"px";

            W *= window.devicePixelRatio;
            H *= window.devicePixelRatio;

            plugin.settings.W = W;
            plugin.settings.H = H;

            element.width = W;
            element.height = H;
        };

        plugin.setGravity = function(gravity) {
            if (gravity) {
                plugin.settings.gravity = gravity;
            }
            plugin.settings.gpf = plugin.settings.gravity / (1000 / plugin.settings.fps);
        };

        plugin.particle = function(plugin) {
            this.x = Math.random()*plugin.settings.W>>0;
            this.y = Math.random()*plugin.settings.H>>0;

            // Degree of direction
            // 0-360
            this.direction = Math.random()*360>>0;

            this.color = {
                'r': Math.random()*255>>0,
                'g': Math.random()*255>>0,
                'b': Math.random()*255>>0,
            };

            this.size = 2 * window.devicePixelRatio;

            // Speed
            this.setVelocity = function(velocity) {
                this.velocity = velocity;
                this.vx = this.velocity * Math.cos(this.direction);
                this.vy = this.velocity * Math.sin(this.direction);
            };

            this.setVelocity(1);

            this.getColor = function() {
                if (plugin.settings.colors === 'global') {
                    return "rgba("+plugin.settings.color.r+", "+plugin.settings.color.g+", "+plugin.settings.color.b+", 0.5)";
                }
                else {
                    return "rgba("+this.color.r+", "+this.color.g+", "+this.color.b+", 0.5)";
                }
            };

            this.move = function() {
                this.x += this.vx * plugin.settings.velocity_multiplier;
                this.y += this.vy * plugin.settings.velocity_multiplier;

                this.vy += plugin.settings.gpf;

                if (this.x < 0) {
                    this.x = Math.abs(this.x);
                    this.vx *= -0.75;
                    this.direction = (2*270-this.direction-180);
                }
                if (this.x > plugin.settings.W) {
                    this.x = plugin.settings.W - (this.x - plugin.settings.W);
                    this.vx *= -0.75;
                    this.direction = (2*90-this.direction-180);
                }

                if (this.y < 0) {
                    this.y = Math.abs(this.y);
                    this.vy *= -0.75;
                    this.direction = (2*180-this.direction-180);
                }
                if (this.y > plugin.settings.H) {
                    this.y = plugin.settings.H - (this.y - plugin.settings.H);
                    this.vy *= -0.75;
                    this.direction = (2*0-this.direction-180);
                }

                if (this.direction < 0) {
                    this.direction += 360;
                }
                if (this.direction > 360) {
                    this.direction %= 360;
                }

                if (this.vx > plugin.settings.max_velocity) {
                    this.vx = plugin.settings.max_velocity;
                }
                if (this.vx < 0-plugin.settings.max_velocity) {
                    this.vx = 0-plugin.settings.max_velocity;
                }

                if (this.vy > plugin.settings.max_velocity) {
                    this.vy = plugin.settings.max_velocity;
                }
                if (this.vy < 0-plugin.settings.max_velocity) {
                    this.vy = 0-plugin.settings.max_velocity;
                }
            };

            this.draw = function(ctx) {
                ctx.beginPath();
                var gradient = ctx.createRadialGradient(this.x, this.y, 0, this.x, this.y, this.size);
                gradient.addColorStop(0, this.getColor());
                gradient.addColorStop(1, "black");

                ctx.fillStyle = gradient;
                ctx.arc(this.x, this.y, this.size, Math.PI*2, false);
                ctx.fill();
            };

            this.updateColor = function() {
                if (Math.random()*3>>0) {
                    this.color.r = this.color.r + (Math.random()*7>>0)-3;
                }

                if (Math.random()*3>>0) {
                    this.color.g = this.color.g + (Math.random()*7>>0)-3;
                }

                if (Math.random()*3>>0) {
                    this.color.b = this.color.b + (Math.random()*7>>0)-3;
                }

                if (this.color.r < 90) {
                    this.color.r = 90;
                }
                if (this.color.r > 255) {
                    this.color.r = 255;
                }

                if (this.color.g < 90) {
                    this.color.g = 90;
                }
                if (this.color.g > 255) {
                    this.color.g = 255;
                }

                if (this.color.g < 90) {
                    this.color.g = 90;
                }
                if (this.color.g > 255) {
                    this.color.g = 255;
                }
            };
        };

        plugin.init();
    };

    // add the plugin to the jQuery.fn object
    $.fn.pfire = function(options) {
        return this.each(function() {
            if (undefined === $(this).data('pfire')) {
                var plugin = new $.pfire(this, options);
                $(this).data('pfire', plugin);
            }
        });
    };
})(jQuery);
<|endoftext|>


<commit_before><commit_msg>Update phina.js<commit_after><|endoftext|>


<commit_before>require([
  "libs/text", // part of require js
  "//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js",
  "libs/ejs_production"
  ],
    function(until)
    {
      require([
      "//ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/jquery-ui.min.js",
      "libs/jquery.form"]);

      $.getJSON("api/phoxy", function(data)
      {
        phoxy.config = data;
        requirejs.config({baseUrl: phoxy.Config()['js_dir']});

        $('script[phoxy]').each(function()
        {
          phoxy.ApiRequest($(this).attr("phoxy"));
        });
      });
    }
  );

function PhoxyHashChangeCallback()
{
  if (phoxy.ChangeHash(location.hash))
    phoxy.ApiRequest(phoxy.hash);
}

var phoxy =
{
  loaded : false,
  hash : false,
  Load : function( )
    {
      this.loaded = true;
      var hash = location.hash.substring(1);
      if (hash.length)
        phoxy.ApiRequest(hash);
      $(window).bind('hashchange', PhoxyHashChangeCallback);
    }
  ,
  Defer : function(callback, time)
  {
    if (time == undefined)
      time = 0;
    var th = this;
    setTimeout(function()
    {
      callback.call(th);
    }, time);
  }
  ,
  WaitFor : function(callback_condition, callback, timeout, check_every)
    {
      var
        check_timeout = 60, // 1 minute for render to complete
        check_delay = 500; // check every 500ms

      if (timeout != undefined)
        check_timeout = timeout;
      if (check_every != undefined)
        check_delay = check_every;

      var func = function()
      {
        if (!callback_condition())
          return;
        callback();
      }
      if (callback_condition())
        return func();

      function WaitAndCallCountDown( i )
      {
        if (i <= 0)
          return func();

        phoxy.Defer(function()
        {
          if (callback_condition())
            i = 0;
          WaitAndCallCountDown(i - 1);
        }, check_delay);
      }

      WaitAndCallCountDown(check_timeout * 1000 / check_delay);
    }
  ,
  Appeared : function(jquery_selector, callback, timeout, call_delay)
    {
      function Div()
      {
        return $(phoxy.OptimiseSelector(jquery_selector));
      }
      function IsDivAppeared()
      {
        return Div()[0] != undefined;
      }

      phoxy.WaitFor(IsDivAppeared, function()
      {
        phoxy.Defer.call(Div(), callback, call_delay);
      }, timeout);
    }
  ,
  Disappeared : function(jquery_selector, callback, timeout, call_delay)
    {
      function IsDivDisappeared()
      {
        return $(phoxy.OptimiseSelector(jquery_selector))[0] == undefined;
      }

      phoxy.WaitFor(IsDivDisappeared, function()
      {
        phoxy.Defer(callback, call_delay);
      }, timeout);
    }
  ,
  GenerateUniqueID : function()
    {
      var ret = "";
      var dictonary = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

      for (var i = 0; i < 10; i++)
        ret += dictonary.charAt(Math.floor(Math.random() * dictonary.length));

      return ret;
    }
  ,
  DeferRender : function (ejs, data, rendered_callback)
    {
      function GetElementCode( el )
      {
        return $(el).wrapAll('

').parent().html();
      }

      var id = phoxy.GenerateUniqueID();
      var div = GetElementCode($('
').attr('id', id).attr("data-debug_comment", "Staged for defer loading. Will be anigilated soon."));

      var func;

      if (typeof(data) == 'undefined')
      { // single param call
        if (typeof(ejs) == 'object')
        { // called as constructed object
          func = function()
          {
            ejs.result = id;
            phoxy.ApiAnswer(ejs, rendered_callback);
          };
        }
        else
        { // called as phoxy rpc
          func = function()
          {
            phoxy.AJAX(ejs, function( ata, callback)
            {
              data.result = id;
              phoxy.ApiAnswer(data, callback);
            }, [rendered_callback]);
          };
        }
      }
      else
      { // called as design submodule (only ejs string and that data)
        func = function()
        {
          phoxy.ApiAnswer({design : ejs, "data" : data, replace : id}, rendered_callback);
        };
      }

      phoxy.Appeared('#' + id, func);
      return div;
    }
  ,
  ChangeHash : function (hash)
    {
      var t;
      t = hash.split(location.origin)[1];
      if (t !== undefined)
        hash = t;
      var t = hash.split('#')[1];
      if (t !== undefined)
        hash = t;
      var ret = phoxy.hash != hash;
      phoxy.hash = hash;
      location.hash = hash;
      return ret;
    }
  ,
  Reset : function (url)
    {
      if (url == true || url == "true")
        location.reload();
      var parts = url.split('#');
      if (parts[1] == undefined)
        phoxy.ChangeHash('');
      else
        phoxy.ChangeHash("#" + parts[1]);
      var host = parts[0];
      if (host.length)
        location = host;
      else
        location.reload(parts[0]);
    }
  ,
  Render : function (design, result, data)
    {
      if (data === undefined)
        data = {};

      var html = new EJS({'url' : design}).render(data);
      if (result != undefined && result != '')
        $("#" + result).replaceWith(html);
      return html;
    }
  ,
  ApiAnswer : function( answer, callback )
    {
      if (answer.hash !== undefined)
      {
        if (answer.hash === null)
          answer.hash = "";
        this.ChangeHash(answer.hash);
      }
      if (answer.error)
      {
        alert(answer.error);
        if (answer.reset !== undefined)
          phoxy.Reset(answer.reset);
        return;
      }
      if (answer.reset !== undefined)
        phoxy.Reset(answer.reset);
      if (answer.script)
      {
        require(answer.script,
          function()
          {
            phoxy.ScriptsLoaded(answer, callback);
          }
        );
      }
      else
        phoxy.ScriptsLoaded(answer, callback);
    }
  ,
  ScriptsLoaded : function( answer, callback )
    {
      function ScriptsFiresUp()
      {
        if (answer.routeline !== undefined)
          window[answer.routeline](answer.data);
        if (callback)
          callback(answer.data);
        if (!phoxy.loaded)
          phoxy.Load();
      }
      if (answer.design === undefined)
        return ScriptsFiresUp();

      var id = phoxy.GenerateUniqueID();
      var render_id = id;

      var element =
        $('
')
        .attr('id', id)
        .attr('data-debug_comment', "Staged for render. Will be anigilated soon.");

      var url = phoxy.Config()['ejs_dir'] + "/" + answer.design;
      phoxy.ForwardDownload(url + ".ejs", function()
      {
        if (answer.replace === undefined)
          if (answer.result === undefined)
            $('body').append(element);
          else
            $('#' + answer.result).html(element);
        else
          render_id = answer.replace;

        phoxy.Render(
          url,
          render_id,
          answer.data);

        phoxy.Disappeared('#' + id, ScriptsFiresUp);
      });
    }
  ,
  ForwardDownload : function( url, callback )
  {
    $.get(url, callback);
  }
  ,
  AJAX : function( url, callback, params )
    {
      $(function()
      {
        $.getJSON(phoxy.Config()['api_dir'] + "/" + url, function(data)
          {
            if (params == undefined)
              params = [];
            params.unshift(data);
            callback.apply(this, params);
          });
      });
    }
  ,
  ApiRequest : function( url, callback )
    {
      if (callback == undefined)
        phoxy.AJAX(url, phoxy.ApiAnswer);
      else
        phoxy.AJAX(url, phoxy.ApiAnswer, [callback]);
    }
  ,
  MenuCall : function( url, callback )
    {
        $(function()
        {
          $.getJSON(phoxy.Config()['api_dir'] + "/" + url, function(data)
          {
            phoxy.ChangeHash(url);
            phoxy.ApiAnswer(data, callback);
          });
        });
    }
  ,
  Config : function()
    {
      return this.config;
    }
  ,
  OptimiseSelector : function( str )
    { // http://learn.jquery.com/performance/optimize-selectors/
      if (typeof(str) != 'string')
        return str;

      var last_id_tag = str.lastIndexOf('#');
      if (last_id_tag > 0)
        str = str.substr(last_id_tag);
      var elements = str.split(" ");
      var ret = $(elements[0]);
      var i = 0;
      while (++i < elements.length)
        if (elements[i].length != 0)
          ret = ret.find(elements[i]);
      return ret;
    }
}
<commit_msg>Speedup first catch on DeferRender and Cached design<commit_after>require([
  "libs/text", // part of require js
  "//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js",
  "libs/ejs_production"
  ],
    function(until)
    {
      require([
      "//ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/jquery-ui.min.js",
      "libs/jquery.form"]);

      $.getJSON("api/phoxy", function(data)
      {
        phoxy.config = data;
        requirejs.config({baseUrl: phoxy.Config()['js_dir']});

        $('script[phoxy]').each(function()
        {
          phoxy.ApiRequest($(this).attr("phoxy"));
        });
      });
    }
  );

function PhoxyHashChangeCallback()
{
  if (phoxy.ChangeHash(location.hash))
    phoxy.ApiRequest(phoxy.hash);
}

var phoxy =
{
  loaded : false,
  hash : false,
  Load : function( )
    {
      this.loaded = true;
      var hash = location.hash.substring(1);
      if (hash.length)
        phoxy.ApiRequest(hash);
      $(window).bind('hashchange', PhoxyHashChangeCallback);
    }
  ,
  Defer : function(callback, time)
  {
    if (time == undefined)
      time = 0;
    var th = this;
    setTimeout(function()
    {
      callback.call(th);
    }, time);
  }
  ,
  WaitFor : function(callback_condition, callback, timeout, check_every)
    {
      var
        check_timeout = 60, // 1 minute for render to complete
        check_delay = 500; // check every 500ms

      if (timeout != undefined)
        check_timeout = timeout;
      if (check_every != undefined)
        check_delay = check_every;

      var func = function()
      {
        if (!callback_condition())
          return;
        callback();
      }
      if (callback_condition())
        return func();

      function WaitAndCallCountDown( i )
      {
        if (i <= 0)
          return func();

        phoxy.Defer(function()
        {
          if (callback_condition())
            i = 0;
          WaitAndCallCountDown(i - 1);
        }, check_delay);
      }

      WaitAndCallCountDown(check_timeout * 1000 / check_delay);
    }
  ,
  Appeared : function(jquery_selector, callback, timeout, call_delay)
    {
      function Div()
      {
        return $(phoxy.OptimiseSelector(jquery_selector));
      }
      function IsDivAppeared()
      {
        return Div()[0] != undefined;
      }

      phoxy.Defer(function()
      {
        phoxy.WaitFor(IsDivAppeared, function()
        {
          phoxy.Defer.call(Div(), callback, call_delay);
        }, timeout)
      });
    }
  ,
  Disappeared : function(jquery_selector, callback, timeout, call_delay)
    {
      function IsDivDisappeared()
      {
        return $(phoxy.OptimiseSelector(jquery_selector))[0] == undefined;
      }

      phoxy.Defer(function()
      {
        phoxy.WaitFor(IsDivDisappeared, function()
        {
          phoxy.Defer(callback, call_delay);
        }, timeout);
      });
    }
  ,
  GenerateUniqueID : function()
    {
      var ret = "";
      var dictonary = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

      for (var i = 0; i < 10; i++)
        ret += dictonary.charAt(Math.floor(Math.random() * dictonary.length));

      return ret;
    }
  ,
  DeferRender : function (ejs, data, rendered_callback)
    {
      function GetElementCode( el )
      {
        return $(el).wrapAll('

').parent().html();
      }

      var id = phoxy.GenerateUniqueID();
      var div = GetElementCode($('
').attr('id', id).attr("data-debug_comment", "Staged for defer loading. Will be anigilated soon."));

      var func;

      if (typeof(data) == 'undefined')
      { // single param call
        if (typeof(ejs) == 'object')
        { // called as constructed object
          func = function()
          {
            ejs.result = id;
            phoxy.ApiAnswer(ejs, rendered_callback);
          };
        }
        else
        { // called as phoxy rpc
          func = function()
          {
            phoxy.AJAX(ejs, function( ata, callback)
            {
              data.result = id;
              phoxy.ApiAnswer(data, callback);
            }, [rendered_callback]);
          };
        }
      }
      else
      { // called as design submodule (only ejs string and that data)
        func = function()
        {
          phoxy.ApiAnswer({design : ejs, "data" : data, replace : id}, rendered_callback);
        };
      }

      phoxy.Appeared('#' + id, func);
      return div;
    }
  ,
  ChangeHash : function (hash)
    {
      var t;
      t = hash.split(location.origin)[1];
      if (t !== undefined)
        hash = t;
      var t = hash.split('#')[1];
      if (t !== undefined)
        hash = t;
      var ret = phoxy.hash != hash;
      phoxy.hash = hash;
      location.hash = hash;
      return ret;
    }
  ,
  Reset : function (url)
    {
      if (url == true || url == "true")
        location.reload();
      var parts = url.split('#');
      if (parts[1] == undefined)
        phoxy.ChangeHash('');
      else
        phoxy.ChangeHash("#" + parts[1]);
      var host = parts[0];
      if (host.length)
        location = host;
      else
        location.reload(parts[0]);
    }
  ,
  Render : function (design, result, data)
    {
      if (data === undefined)
        data = {};

      var html = new EJS({'url' : design}).render(data);
      if (result != undefined && result != '')
        $("#" + result).replaceWith(html);
      return html;
    }
  ,
  ApiAnswer : function( answer, callback )
    {
      if (answer.hash !== undefined)
      {
        if (answer.hash === null)
          answer.hash = "";
        this.ChangeHash(answer.hash);
      }
      if (answer.error)
      {
        alert(answer.error);
        if (answer.reset !== undefined)
          phoxy.Reset(answer.reset);
        return;
      }
      if (answer.reset !== undefined)
        phoxy.Reset(answer.reset);
      if (answer.script)
      {
        require(answer.script,
          function()
          {
            phoxy.ScriptsLoaded(answer, callback);
          }
        );
      }
      else
        phoxy.ScriptsLoaded(answer, callback);
    }
  ,
  ScriptsLoaded : function( answer, callback )
    {
      function ScriptsFiresUp()
      {
        if (answer.routeline !== undefined)
          window[answer.routeline](answer.data);
        if (callback)
          callback(answer.data);
        if (!phoxy.loaded)
          phoxy.Load();
      }
      if (answer.design === undefined)
        return ScriptsFiresUp();

      var id = phoxy.GenerateUniqueID();
      var render_id = id;

      var element =
        $('
')
        .attr('id', id)
        .attr('data-debug_comment', "Staged for render. Will be anigilated soon.");

      var url = phoxy.Config()['ejs_dir'] + "/" + answer.design;
      phoxy.ForwardDownload(url + ".ejs", function()
      {
        if (answer.replace === undefined)
          if (answer.result === undefined)
            $('body').append(element);
          else
            $('#' + answer.result).html(element);
        else
          render_id = answer.replace;

        phoxy.Render(
          url,
          render_id,
          answer.data);

        phoxy.Disappeared('#' + id, ScriptsFiresUp);
      });
    }
  ,
  ForwardDownload : function( url, callback )
  {
    $.get(url, callback);
  }
  ,
  AJAX : function( url, callback, params )
    {
      $(function()
      {
        $.getJSON(phoxy.Config()['api_dir'] + "/" + url, function(data)
          {
            if (params == undefined)
              params = [];
            params.unshift(data);
            callback.apply(this, params);
          });
      });
    }
  ,
  ApiRequest : function( url, callback )
    {
      if (callback == undefined)
        phoxy.AJAX(url, phoxy.ApiAnswer);
      else
        phoxy.AJAX(url, phoxy.ApiAnswer, [callback]);
    }
  ,
  MenuCall : function( url, callback )
    {
        $(function()
        {
          $.getJSON(phoxy.Config()['api_dir'] + "/" + url, function(data)
          {
            phoxy.ChangeHash(url);
            phoxy.ApiAnswer(data, callback);
          });
        });
    }
  ,
  Config : function()
    {
      return this.config;
    }
  ,
  OptimiseSelector : function( str )
    { // http://learn.jquery.com/performance/optimize-selectors/
      if (typeof(str) != 'string')
        return str;

      var last_id_tag = str.lastIndexOf('#');
      if (last_id_tag > 0)
        str = str.substr(last_id_tag);
      var elements = str.split(" ");
      var ret = $(elements[0]);
      var i = 0;
      while (++i < elements.length)
        if (elements[i].length != 0)
          ret = ret.find(elements[i]);
      return ret;
    }
}
<|endoftext|>


<commit_before>requirejs.config({
    waitSeconds: 60
});

require([
  "libs/text", // part of require js
  "//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js",
  "libs/ejs_production"
  ],
    function(until)
    {
      require([
      "//ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/jquery-ui.min.js",
      "libs/jquery.form"]);

      $.getJSON("api/phoxy", function(data)
      {
        phoxy.config = data;
        requirejs.config({baseUrl: phoxy.Config()['js_dir']});

        $('script[phoxy]').each(function()
        {
          phoxy.ApiRequest($(this).attr("phoxy"));
        });
      });
    }
  );

function PhoxyHashChangeCallback()
{
  if (phoxy.ChangeHash(location.hash))
    phoxy.ApiRequest(phoxy.hash);
}

var phoxy =
{
  loaded : false,
  hash : false,
  Load : function( )
    {
      this.loaded = true;
      var hash = location.hash.substring(1);
      phoxy.ApiRequest(hash);
      this.hash = hash;
      $(window).bind('hashchange', PhoxyHashChangeCallback);
    }
  ,
  Defer : function(callback, time)
  {
    if (time == undefined)
      time = 0;
    var th = this;
    setTimeout(function()
    {
      callback.call(th);
    }, time);
  }
  ,
  WaitFor : function(callback_condition, callback, timeout, check_every)
    {
      var
        check_timeout = 60, // 1 minute for render to complete
        check_delay = 500; // check every 500ms

      if (timeout != undefined)
        check_timeout = timeout;
      if (check_every != undefined)
        check_delay = check_every;

      var func = function()
      {
        if (!callback_condition())
          return;
        callback();
      }
      if (callback_condition())
        return func();

      function WaitAndCallCountDown( i )
      {
        if (i <= 0)
          return func();

        phoxy.Defer(function()
        {
          if (callback_condition())
            i = 0;
          WaitAndCallCountDown(i - 1);
        }, check_delay);
      }

      WaitAndCallCountDown(check_timeout * 1000 / check_delay);
    }
  ,
  Appeared : function(jquery_selector, callback, timeout, call_delay)
    {
      function Div()
      {
        return $(phoxy.OptimiseSelector(jquery_selector));
      }
      function IsDivAppeared()
      {
        return Div()[0] != undefined;
      }

      phoxy.Defer(function()
      {
        phoxy.WaitFor(IsDivAppeared, function()
        {
          phoxy.Defer.call(Div(), callback, call_delay);
        }, timeout)
      });
    }
  ,
  Disappeared : function(jquery_selector, callback, timeout, call_delay)
    {
      function IsDivDisappeared()
      {
        return $(phoxy.OptimiseSelector(jquery_selector))[0] == undefined;
      }

      phoxy.Defer(function()
      {
        phoxy.WaitFor(IsDivDisappeared, function()
        {
          phoxy.Defer(callback, call_delay);
        }, timeout);
      });
    }
  ,
  GenerateUniqueID : function()
    {
      var ret = "";
      var dictonary = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

      for (var i = 0; i < 10; i++)
        ret += dictonary.charAt(Math.floor(Math.random() * dictonary.length));

      return ret;
    }
  ,
  PrepareCanvas : function(tag)
    {
      if (tag == undefined)
        tag = '
';
      function GetElementCode( el )
      {
        return $(el).wrapAll('

').parent().html();
      }

      var id =  phoxy.GenerateUniqueID();
      var obj = $(tag).attr('id', id);
      var div = GetElementCode(obj);

      return { id: id, obj: obj, html: div };
    }
  ,
  DeferRender : function (ejs, data, rendered_callback, tag)
    {
      console.log("phoxy.DeferRender", arguments);
      if (tag == undefined)
        tag = '<defer_render>';
      var canvas = phoxy.PrepareCanvas(tag);
      var id = canvas.id;

      phoxy.Fancy(ejs, data, function(html)
      {
        phoxy.Appeared('#' + id, function()
        {
          $(this).replaceWith(html);
        });
      });

      return canvas.html;
    }
  ,
  Fancy : function(design, data, callback)
    {
      console.log("phoxy.Fancy", arguments);

      var func;
      var callback = arguments[2];
      if (typeof(callback) == 'undefined')
        callback = function (){};
      var design = arguments[0];

      if (typeof(data) == 'undefined')
      { // single param call
        if (typeof(design) == 'undefined')
          return callback(undefined);
        if (typeof(design) == 'object')
        {
          var obj = arguments[0];
          // Maybe its wrong. Maybe i should ignore other params
          var design = obj.design;
          var data = obj.data;
          if (typeof(data) == 'undefined')
            data = {};
          delete obj.design;
          delete obj.data;
          delete obj.result;
          delete obj.replace;

          phoxy.ApiAnswer(obj, function()
          {
            phoxy.Fancy(design, data, callback);
          });
        }
        else
        { /* Called as RPC
            PARAMS:
              [0] - string with RPC command
            NOTE:
              target commands ignored.
              result will be rendered in this div.
           */
          var rpc = arguments[0];
          phoxy.AJAX(rpc, function(data, callback)
          {
            phoxy.Fancy(data, undefined, callback);
          }, [callback]);
        }
        return;
      }

      var data = arguments[1];
      function DataLoadedCallback(data)
      {
        if (typeof(data) == 'undefined')
          data = {};
        phoxy.Fancy(design, data, callback);
      }

      if (typeof(data) == 'function')
      { /* Get data as function callback */
        data(DataLoadedCallback);
      }
      else if (typeof(data) == 'string')
      { /* Download data with RPC */
        phoxy.AJAX(data, function(json)
        {
          DataLoadedCallback(json.data);
        });
      }
      else
      { /* Data loaded */
        var html;
        if (design != undefined)
          html = phoxy.Render(phoxy.Config()['ejs_dir'] + "/" + design, undefined, data);
        callback(html, data);
      }
    }
  ,
  ChangeHash : function (hash)
    {
      var t;
      t = hash.split(location.origin)[1];
      if (t !== undefined)
        hash = t;
      var t = hash.split('#')[1];
      if (t !== undefined)
        hash = t;
      var ret = phoxy.hash != hash;
      phoxy.hash = hash;
      location.hash = hash;
      return ret;
    }
  ,
  Reset : function (url)
    {
      if (url == true)
        location.reload();
      var parts = url.split('#');
      if (parts[1] == undefined)
        phoxy.ChangeHash('');
      else
        phoxy.ChangeHash("#" + parts[1]);
      var host = parts[0];
      if (host.length)
        location = host;
      else
        location.reload(parts[0]);
    }
  ,
  Render : function (design, result, data)
    {
      if (data === undefined)
        data = {};

      console.log("phoxy.Render", arguments);
      var html;
      if (design.search(".ejs") == -1)
        design += ".ejs";
      if (!phoxy.ForwardDownload(design))
        html = new EJS({'url' : design}).render(data);
      else
        html = new EJS({'text' : phoxy.ForwardDownload(design, true)}).render(data);
      if (result != undefined && result != '')
        $("#" + result).replaceWith(html);
      return html;
    }
  ,
  ApiAnswer : function( answer, callback )
    {
      if (answer.hash !== undefined)
      {
        if (answer.hash === null)
          answer.hash = "";
        this.ChangeHash(answer.hash);
      }
      if (answer.error)
      {
        alert(answer.error);
        if (answer.reset !== undefined)
          phoxy.Reset(answer.reset);
        return;
      }
      if (answer.reset !== undefined)
        phoxy.Reset(answer.reset);

      function Before()
      {
        function AfterBefore(_answer)
        {
          if (_answer !== undefined)
            answer = _answer;
          phoxy.ScriptsLoaded(answer, callback);
        }
        if (answer.before !== undefined)
          window[answer.before](answer, AfterBefore);
        else
          AfterBefore();
      }

      if (answer.script)
        require(answer.script, Before);
      else
        Before();
    }
  ,
  ScriptsLoaded : function( answer, callback )
    {
      function ScriptsFiresUp()
      {
        if (answer.routeline !== undefined)
          window[answer.routeline](answer);
        if (callback)
          callback(answer.data);
        if (!phoxy.loaded)
          phoxy.Load();
      }
      if (answer.design === undefined)
        return ScriptsFiresUp();

      var canvas = phoxy.PrepareCanvas('<render>');
      var id = canvas.id;
      var render_id = id;

      var element = canvas.obj;

      var url = phoxy.Config()['ejs_dir'] + "/" + answer.design;
      phoxy.ForwardDownload(url + ".ejs", function()
      {
        if (answer.replace === undefined)
          if (answer.result === undefined)
            $('body').append(element);
          else
            $('#' + answer.result).html(element);
        else
          render_id = answer.replace;

        phoxy.Render(
          url,
          render_id,
          answer.data);

        phoxy.Disappeared('#' + id, ScriptsFiresUp);
      });
    }
  ,
  ForwardDownload : function( url, callback_or_true_for_return )
  {
    if (typeof(storage) === "undefined")
      storage = {};

    if (callback_or_true_for_return === true)
      return storage[url];

    function AddToLocalStorage(data)
    {
      storage[url] = data;
      if (typeof(callback_or_true_for_return) == 'function')
        callback_or_true_for_return(data);
    }

    if (storage[url] != undefined)
    {
      if (typeof(callback_or_true_for_return) == 'function')
        callback_or_true_for_return(storage[url]);
      return true;
    }

    $.get(url, AddToLocalStorage);
    return false;
  }
  ,
  AJAX : function( url, callback, params )
    {
      console.log("phoxy.AJAX", arguments);
      $(function()
      {
        $.getJSON(phoxy.Config()['api_dir'] + "/" + url, function(data)
          {
            if (params == undefined)
              params = [];
            params.unshift(data);
            callback.apply(this, params);
          });
      });
    }
  ,
  ApiRequest : function( url, callback )
    {
      if (callback == undefined)
        phoxy.AJAX(url, phoxy.ApiAnswer);
      else
        phoxy.AJAX(url, phoxy.ApiAnswer, [callback]);
    }
  ,
  MenuCall : function( url, callback )
    {
        $(function()
        {
          $.getJSON(phoxy.Config()['api_dir'] + "/" + url, function(data)
          {
            phoxy.ChangeHash(url);
            phoxy.ApiAnswer(data, callback);
          });
        });
    }
  ,
  Config : function()
    {
      return this.config;
    }
  ,
  OptimiseSelector : function( str )
    { // http://learn.jquery.com/performance/optimize-selectors/
      if (typeof(str) != 'string')
        return str;

      var last_id_tag = str.lastIndexOf('#');
      if (last_id_tag > 0)
        str = str.substr(last_id_tag);
      var elements = str.split(" ");
      var ret = $(elements[0]);
      var i = 0;
      while (++i < elements.length)
        if (elements[i].length != 0)
          ret = ret.find(elements[i]);
      return ret;
    }
}
<commit_msg>Fix fancy bugs<commit_after>requirejs.config({
    waitSeconds: 60
});

require([
  "libs/text", // part of require js
  "//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js",
  "libs/ejs_production"
  ],
    function(until)
    {
      require([
      "//ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/jquery-ui.min.js",
      "libs/jquery.form"]);

      $.getJSON("api/phoxy", function(data)
      {
        phoxy.config = data;
        requirejs.config({baseUrl: phoxy.Config()['js_dir']});

        $('script[phoxy]').each(function()
        {
          phoxy.ApiRequest($(this).attr("phoxy"));
        });
      });
    }
  );

function PhoxyHashChangeCallback()
{
  if (phoxy.ChangeHash(location.hash))
    phoxy.ApiRequest(phoxy.hash);
}

var phoxy =
{
  loaded : false,
  hash : false,
  Load : function( )
    {
      this.loaded = true;
      var hash = location.hash.substring(1);
      phoxy.ApiRequest(hash);
      this.hash = hash;
      $(window).bind('hashchange', PhoxyHashChangeCallback);
    }
  ,
  Defer : function(callback, time)
  {
    if (time == undefined)
      time = 0;
    var th = this;
    setTimeout(function()
    {
      callback.call(th);
    }, time);
  }
  ,
  WaitFor : function(callback_condition, callback, timeout, check_every)
    {
      var
        check_timeout = 60, // 1 minute for render to complete
        check_delay = 500; // check every 500ms

      if (timeout != undefined)
        check_timeout = timeout;
      if (check_every != undefined)
        check_delay = check_every;

      var func = function()
      {
        if (!callback_condition())
          return;
        callback();
      }
      if (callback_condition())
        return func();

      function WaitAndCallCountDown( i )
      {
        if (i <= 0)
          return func();

        phoxy.Defer(function()
        {
          if (callback_condition())
            i = 0;
          WaitAndCallCountDown(i - 1);
        }, check_delay);
      }

      WaitAndCallCountDown(check_timeout * 1000 / check_delay);
    }
  ,
  Appeared : function(jquery_selector, callback, timeout, call_delay)
    {
      function Div()
      {
        return $(phoxy.OptimiseSelector(jquery_selector));
      }
      function IsDivAppeared()
      {
        return Div()[0] != undefined;
      }

      phoxy.Defer(function()
      {
        phoxy.WaitFor(IsDivAppeared, function()
        {
          phoxy.Defer.call(Div(), callback, call_delay);
        }, timeout)
      });
    }
  ,
  Disappeared : function(jquery_selector, callback, timeout, call_delay)
    {
      function IsDivDisappeared()
      {
        return $(phoxy.OptimiseSelector(jquery_selector))[0] == undefined;
      }

      phoxy.Defer(function()
      {
        phoxy.WaitFor(IsDivDisappeared, function()
        {
          phoxy.Defer(callback, call_delay);
        }, timeout);
      });
    }
  ,
  GenerateUniqueID : function()
    {
      var ret = "";
      var dictonary = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

      for (var i = 0; i < 10; i++)
        ret += dictonary.charAt(Math.floor(Math.random() * dictonary.length));

      return ret;
    }
  ,
  PrepareCanvas : function(tag)
    {
      if (tag == undefined)
        tag = '
';
      function GetElementCode( el )
      {
        return $(el).wrapAll('

').parent().html();
      }

      var id =  phoxy.GenerateUniqueID();
      var obj = $(tag).attr('id', id);
      var div = GetElementCode(obj);

      return { id: id, obj: obj, html: div };
    }
  ,
  DeferRender : function (ejs, data, rendered_callback, tag)
    {
      console.log("phoxy.DeferRender", arguments);
      if (tag == undefined)
        tag = '<defer_render>';
      var canvas = phoxy.PrepareCanvas(tag);
      var id = canvas.id;

      phoxy.Fancy(ejs, data, function(html)
      {
        phoxy.Appeared('#' + id, function()
        {
          $(this).replaceWith(html);
          rendered_callback(ejs, data);
        });
      });

      return canvas.html;
    }
  ,
  Fancy : function(design, data, callback)
    {
      console.log("phoxy.Fancy", arguments);

      var func;
      var callback = arguments[2];
      if (typeof(callback) == 'undefined')
        callback = function (){};
      var design = arguments[0];

      if (typeof(data) == 'undefined')
      { // single param call
        if (typeof(design) == 'undefined')
          return callback(undefined, undefined);
        if (typeof(design) == 'object')
        {
          var obj = arguments[0];
          // Maybe its wrong. Maybe i should ignore other params
          var design = obj.design;
          var data = obj.data;
          if (typeof(data) == 'undefined')
            data = {};
          delete obj.design;
          delete obj.data;
          delete obj.result;
          delete obj.replace;

          phoxy.ApiAnswer(obj, function()
          {
            phoxy.Fancy(design, data, callback);
          });
        }
        else
        { /* Called as RPC
            PARAMS:
              [0] - string with RPC command
            NOTE:
              target commands ignored.
              result will be rendered in this div.
           */
          var rpc = arguments[0];
          phoxy.AJAX(rpc, function(data, callback)
          {
            phoxy.Fancy(data, undefined, callback);
          }, [callback]);
        }
        return;
      }

      var data = arguments[1];
      function DataLoadedCallback(data)
      {
        if (typeof(data) == 'undefined')
          data = {};
        phoxy.Fancy(design, data, callback);
      }

      if (typeof(data) == 'function')
      { /* Get data as function callback */
        data(DataLoadedCallback);
      }
      else if (typeof(data) == 'string')
      { /* Download data with RPC */
        phoxy.AJAX(data, function(json)
        {
          DataLoadedCallback(json.data);
        });
      }
      else
      { /* Data loaded */
        var html;
        if (design != undefined)
          html = phoxy.Render(phoxy.Config()['ejs_dir'] + "/" + design, undefined, data);
        callback(html, data);
      }
    }
  ,
  ChangeHash : function (hash)
    {
      var t;
      t = hash.split(location.origin)[1];
      if (t !== undefined)
        hash = t;
      var t = hash.split('#')[1];
      if (t !== undefined)
        hash = t;
      var ret = phoxy.hash != hash;
      phoxy.hash = hash;
      location.hash = hash;
      return ret;
    }
  ,
  Reset : function (url)
    {
      if (url == true)
        location.reload();
      var parts = url.split('#');
      if (parts[1] == undefined)
        phoxy.ChangeHash('');
      else
        phoxy.ChangeHash("#" + parts[1]);
      var host = parts[0];
      if (host.length)
        location = host;
      else
        location.reload(parts[0]);
    }
  ,
  Render : function (design, result, data)
    {
      if (data === undefined)
        data = {};

      console.log("phoxy.Render", arguments);
      var html;
      if (design.search(".ejs") == -1)
        design += ".ejs";
      if (!phoxy.ForwardDownload(design))
        html = new EJS({'url' : design}).render(data);
      else
        html = new EJS({'text' : phoxy.ForwardDownload(design, true)}).render(data);
      if (result != undefined && result != '')
        $("#" + result).replaceWith(html);
      return html;
    }
  ,
  ApiAnswer : function( answer, callback )
    {
      if (answer.hash !== undefined)
      {
        if (answer.hash === null)
          answer.hash = "";
        this.ChangeHash(answer.hash);
      }
      if (answer.error)
      {
        alert(answer.error);
        if (answer.reset !== undefined)
          phoxy.Reset(answer.reset);
        return;
      }
      if (answer.reset !== undefined)
        phoxy.Reset(answer.reset);

      function Before()
      {
        function AfterBefore(_answer)
        {
          if (_answer !== undefined)
            answer = _answer;
          phoxy.ScriptsLoaded(answer, callback);
        }
        if (answer.before !== undefined)
          window[answer.before](answer, AfterBefore);
        else
          AfterBefore();
      }

      if (answer.script)
        require(answer.script, Before);
      else
        Before();
    }
  ,
  ScriptsLoaded : function( answer, callback )
    {
      function ScriptsFiresUp()
      {
        if (answer.routeline !== undefined)
          window[answer.routeline](answer);
        if (callback)
          callback(answer.data);
        if (!phoxy.loaded)
          phoxy.Load();
      }
      if (answer.design === undefined)
        return ScriptsFiresUp();

      var canvas = phoxy.PrepareCanvas('<render>');
      var id = canvas.id;
      var render_id = id;

      var element = canvas.obj;

      var url = phoxy.Config()['ejs_dir'] + "/" + answer.design;
      phoxy.ForwardDownload(url + ".ejs", function()
      {
        if (answer.replace === undefined)
          if (answer.result === undefined)
            $('body').append(element);
          else
            $('#' + answer.result).html(element);
        else
          render_id = answer.replace;

        phoxy.Render(
          url,
          render_id,
          answer.data);

        phoxy.Disappeared('#' + id, ScriptsFiresUp);
      });
    }
  ,
  ForwardDownload : function( url, callback_or_true_for_return )
  {
    if (typeof(storage) === "undefined")
      storage = {};

    if (callback_or_true_for_return === true)
      return storage[url];

    function AddToLocalStorage(data)
    {
      storage[url] = data;
      if (typeof(callback_or_true_for_return) == 'function')
        callback_or_true_for_return(data);
    }

    if (storage[url] != undefined)
    {
      if (typeof(callback_or_true_for_return) == 'function')
        callback_or_true_for_return(storage[url]);
      return true;
    }

    $.get(url, AddToLocalStorage);
    return false;
  }
  ,
  AJAX : function( url, callback, params )
    {
      console.log("phoxy.AJAX", arguments);
      $(function()
      {
        $.getJSON(phoxy.Config()['api_dir'] + "/" + url, function(data)
          {
            if (params == undefined)
              params = [];
            params.unshift(data);
            callback.apply(this, params);
          });
      });
    }
  ,
  ApiRequest : function( url, callback )
    {
      if (callback == undefined)
        phoxy.AJAX(url, phoxy.ApiAnswer);
      else
        phoxy.AJAX(url, phoxy.ApiAnswer, [callback]);
    }
  ,
  MenuCall : function( url, callback )
    {
        $(function()
        {
          $.getJSON(phoxy.Config()['api_dir'] + "/" + url, function(data)
          {
            phoxy.ChangeHash(url);
            phoxy.ApiAnswer(data, callback);
          });
        });
    }
  ,
  Config : function()
    {
      return this.config;
    }
  ,
  OptimiseSelector : function( str )
    { // http://learn.jquery.com/performance/optimize-selectors/
      if (typeof(str) != 'string')
        return str;

      var last_id_tag = str.lastIndexOf('#');
      if (last_id_tag > 0)
        str = str.substr(last_id_tag);
      var elements = str.split(" ");
      var ret = $(elements[0]);
      var i = 0;
      while (++i < elements.length)
        if (elements[i].length != 0)
          ret = ret.find(elements[i]);
      return ret;
    }
}
<|endoftext|>