<commit_before>var JSONLoader = require('./JSON');
function JsonTreeSceneLoader( manager) {
	this.manager = manager;
};

var getURLParam = require('urlparams').getParam;

var LOAD_UNAVAILABLE = -1,
	LOAD_AVAILABLE = 0,
	LOADING = 1,
	LOADED = 2;

var p = JsonTreeSceneLoader.prototype = {
	totalLoading: 0,
	totalLoaded: 0,
	objectsByPath: undefined,
	objectPaths: undefined,
	geometries: undefined,
	objectsWaitingForGeometriesByGeometryPaths: undefined,
	loadersByGeometryPaths: undefined,
	load: function (path, pathGeometries, onSceneLoad, onObjectLoad, onMeshLoad, onComplete, stream) {
		this.path = path;
		this.stream = stream;
		this.debug = true;
		this.pathBase = path.substring(0, path.lastIndexOf('/')+1);
		path = this.pathCropBase(path);
		this.pathGeometries = pathGeometries;
		this.onSceneLoad = onSceneLoad;
		this.onObjectLoad = onObjectLoad;
		this.onComplete = onComplete;
		this.onMeshLoad = onMeshLoad;
		this.objectsByPath = {};
		this.geometries = {};
		this.cancelling = [];
		this.objectPaths = [];
		this.objectsWaitingForGeometriesByGeometryPaths = {};
		this.loadersByGeometryPaths = {};
		this.threeGeometryJSONLoader = new THREE.JSONLoader();
		this.threeObjectJSONLoader = new THREE.ObjectLoader();
		this.hierarchyRecieved = this.hierarchyRecieved.bind(this);
		this.geometryRecieved = this.geometryRecieved.bind(this);
		this.showByName = this.showByName.bind(this);
		this.hideByName = this.hideByName.bind(this);
		this.childError = this.childError.bind(this);
		JSONLoader.load(this.pathBase + path, this.hierarchyRecieved, this.childError);
		this.totalLoading++;
	},

	hierarchyRecieved: function(jsonData, path) {
		this.root = new THREE.Object3D();
		for(var childName in jsonData) {
			this.root.add(this.createObject(jsonData[childName], path + '/' + childName));
		}
		this.onSceneLoad({scene: this.root});
		this.onComplete();
	},

	childError: function(xhr) {
		var cancelIndex = this.cancelling.indexOf(xhr);
		if(cancelIndex != -1) {
			console.log('geometry load cancelled!');
			this.cancelling.splice(cancelIndex, 1);
		} else {
			throw('error loading');
		}
		// throw(xhr);
	},

	geometryRecieved: function(jsonData, path) {
		path = this.pathCropGeometries(path);
		path = path.substring(0, path.lastIndexOf('.json'));
		// console.log(jsonData);
		if(this.debug) console.log('loaded', path);

		var geometry = this.threeGeometryJSONLoader.parse(jsonData).geometry;
		this.integrateGeometry(geometry, path);
		this.incrementAndCheckLoad();
	},

	integrateGeometry: function(geometry, path) {
		// console.log('integrate geometry', path);
		this.geometries[path] = geometry;
		var objectsToPromote = this.objectsWaitingForGeometriesByGeometryPaths[path];
		if(objectsToPromote) {
			for (var i = objectsToPromote.length - 1; i >= 0; i--) {
				var object = objectsToPromote[i];
				var mesh = this.promoteObjectToMesh(object, geometry);
				mesh.loadStatus = LOADED;
				if(object.geometryLoadCompleteCallback) {
					object.geometryLoadCompleteCallback();
					delete object.geometryLoadCompleteCallback;
				}
				delete this.loadersByGeometryPaths[object.geometryName];
				delete object.geometryName;
				// this.isolationTest(mesh);
			};
		}
		delete this.objectsWaitingForGeometriesByGeometryPaths[path];
	},

	loadGeometryOf: function(object, callback) {
		// object.add(new THREE.Mesh(new THREE.SphereGeometry(10)));
		var geometryName = object.geometryName;
		if(this.debug) console.log('loading', geometryName);
		var geometryPath = this.pathGeometries + geometryName;
		var geometry = this.geometries[geometryName];
		if(geometry) {
			object = this.promoteObjectToMesh(object, geometry);
			object.loadStatus = LOADED;
			return false;
		} else {
			if(!this.objectsWaitingForGeometriesByGeometryPaths[geometryName]) {
				object.geometryLoadCompleteCallback = callback;
				this.objectsWaitingForGeometriesByGeometryPaths[geometryName] = [object];
				loader = JSONLoader.load(geometryPath + '.json', this.geometryRecieved, this.childError);
				this.loadersByGeometryPaths[geometryName] = loader;
				return true;
				// this.totalLoading++;
			} else {
				this.objectsWaitingForGeometriesByGeometryPaths[geometryName].push(object);
				return false;
			}
		}
	},

	cancelLoadGeometryOf: function(object) {
		// object.add(new THREE.Mesh(new THREE.SphereGeometry(10)));
		var geometryName = object.geometryName;
		if(this.debug) console.log('cancelling', geometryName);
		var geometryPath = this.pathGeometries + geometryName;
		var objectsWaitingForGeometry = this.objectsWaitingForGeometriesByGeometryPaths[geometryName]
		if(objectsWaitingForGeometry) {
			for (var i = objectsWaitingForGeometry.length - 1; i >= 0; i--) {
				var objectWaiting = objectsWaitingForGeometry.splice(i, 1)[0];
				delete objectWaiting.geometryLoadCompleteCallback;
			};
		}
		delete this.objectsWaitingForGeometriesByGeometryPaths[geometryName];
		this.cancelling.push(this.loadersByGeometryPaths[geometryName]);
		this.loadersByGeometryPaths[geometryName].abort();
		delete this.loadersByGeometryPaths[geometryName];
	},

	storeObject: function(path, object) {
		this.objectsByPath[path] = object;
		this.objectPaths.push(path);

		//fix the alias for notFound
		var slices = path.split('/');
		if(slices[slices.length-1].indexOf("notFound") != -1){
			slices[slices.length-1] = "notFound";
		}
		path = slices.join('/');

		this.objectsByPath[path] = object;
		this.objectPaths.push(path);
	},

	createObject: function(jsonData, path) {
		var object = this.threeObjectJSONLoader.parseObject(jsonData);
		while(object.children.length > 0) object.remove(object.children[0]);	//I only want the object
		object.path = path;
		object.materialName = jsonData.material;
		this.storeObject(path, object);
		var name = path.substring(path.lastIndexOf('/')+1, path.length);
		object.name = name;

		for(var childName in jsonData.children) {
			object.add(this.createObject(jsonData.children[childName], path + '/' + childName));
		}

		var geometryName = jsonData.geometry;
		if(geometryName) {
			object.loadStatus = LOAD_AVAILABLE;
			object.geometryName = geometryName;

			this.decorateObjectWithJITGeometryAPI(object);

		} else {
			object.loadStatus = LOAD_UNAVAILABLE;
		}

		if(jsonData.quaternion) {
			object.quaternion.x = jsonData.quaternion[0];
			object.quaternion.y = jsonData.quaternion[1];
			object.quaternion.z = jsonData.quaternion[2];
			object.quaternion.w = jsonData.quaternion[3];
		}
		this.onObjectLoad(object);
		if(object.loadStatus === undefined) throw new Error('wtf');
		return object;
	},

	promoteObjectToMesh: function(object, geometry) {
		var mesh = new THREE.Mesh(geometry);
		mesh.path = object.path;
		mesh.name = object.name;
		var parent = object.parent;
		mesh.materialName = object.materialName;
		mesh.position.copy(object.position);
		mesh.scale.copy(object.scale);
		mesh.rotation.x = object.rotation.x;
		mesh.rotation.y = object.rotation.y;
		mesh.rotation.z = object.rotation.z;
		if(parent) {
			parent.remove(object);
			parent.add(mesh);
		} else {
			throw new Error('wtf');
		}

		for (var i = object.children.length - 1; i >= 0; i--) {
			mesh.add(object.children[i]);
		};
		var path = object.path;
		this.storeObject(path, mesh);

		if(object === this.root) {
			this.root = mesh;
		}

		this.decorateObjectWithJITGeometryAPI(mesh);
		this.onMeshLoad(mesh);
		return mesh;
	},

	incrementAndCheckLoad: function() {
		this.totalLoaded++;
		if(this.totalLoading == this.totalLoaded && !this.stream) {
			this.onSceneLoad({scene: this.root});
		}
	},

	pathCropBase: function(path) {
		return path.substring(this.pathBase.length, path.length);
	},

	pathCropGeometries: function(path) {
		return path.substring(this.pathGeometries.length, path.length);
	},

	notFound: function(name) {
		console.log(name, 'does not exist');
		if(name) {
			var slices = name.split('/');
			slices[slices.length-1] = 'notFound';
			name = slices.join('/');
		} else {
			name = 'notFound'
		}
		return this.objectsByPath[this.path + '/' + name];
	},

	showByName: function(name, recursive, childrenOnly) {
		this.setVisibilityByName(name, true, recursive, childrenOnly);
	},

	hideByName: function(name, recursive, childrenOnly) {
		this.setVisibilityByName(name, false, recursive, childrenOnly);
	},

	setVisibilityByName: function(name, state, recursive, childrenOnly) {
		var object = this.getObjectByName(name);
		if(!object) {
			object = this.notFound(name);
		}
		if(object) {
			if(!childrenOnly) {
				object.visible = state;
			}
			// if(state, console.log(name));
			if(recursive) {
				object.traverse(function(obj) {
					if(obj === object) return;
					obj.visible = state;
				});
			}
		}
	},

	loadByName: function(name, recursive, callback) {
		var object = this.getObjectByName(name);
		var loading = 0;
		var _this = this;
		function progressCallback() {
			loading--;
			if(_this.debug) console.log(name, 'remaining geometries to load:', loading);
			if(loading === 0) {
				if(callback) {
					callback();
				}
			}
		}
		if(!object) {
			object = this.notFound(name);
		}
		if(object) {
			if(object.load) {
				loading += object.load(progressCallback) ? 1 : 0;
			}
			if(recursive) {
				object.traverse(function(obj) {
					if(obj.load) {
						loading += obj.load(progressCallback) ? 1 : 0;
					}
				});
			}
			console.log('geometries to load:', loading)
			if(loading == 0) {
				callback();
			}
		}
	},

	cancelLoadByName: function(name, recursive, callback) {
		throw new Error('Not implemented yet');
	},

	checkIfLoadedByName: function(name, recursive) {
		var object = this.getObjectByName(name);
		var loaded = object.loadStatus == LOADED || object.loadStatus == LOAD_UNAVAILABLE;
		if(loaded && recursive) {
			object.traverse(function(obj) {
				if(obj.loadStatus != LOADED && obj.loadStatus != LOAD_UNAVAILABLE) {
					loaded = loaded && false;
					throw new Error('wtf');
				}
			})
		}
		return loaded;
	},

	decorateObjectWithJITGeometryAPI: function(object){
		var _this = this;
		object.targetVisiblility = object.visible;
		object.load = function(callback) {
			if(object.loadStatus === LOAD_AVAILABLE) {
				object.loadStatus = LOADING;
				return _this.loadGeometryOf(object, callback);
			}
			return false;
		};
		object.unload = function(callback) {
			throw new Error('not implemented yet');
		};
		object.cancelLoad = function(callback) {
			throw new Error('not implemented yet');
		};
	},

	getObjectByName: function(name) {
		var objPath = this.path + '/' + name;
		return this.objectsByPath[objPath];
	}
}

module.exports = JsonTreeSceneLoader;<commit_msg>bugfixing<commit_after>var JSONLoader = require('./JSON');
function JsonTreeSceneLoader( manager) {
	this.manager = manager;
};

var getURLParam = require('urlparams').getParam;

var SHOULDNT_EVEN_EXIST = -2,
	LOAD_UNAVAILABLE = -1,
	LOAD_AVAILABLE = 0,
	LOADING = 1,
	LOADED = 2;

var p = JsonTreeSceneLoader.prototype = {
	totalLoading: 0,
	totalLoaded: 0,
	objectsByPath: undefined,
	objectPaths: undefined,
	geometries: undefined,
	objectsWaitingForGeometriesByGeometryPaths: undefined,
	loadersByGeometryPaths: undefined,
	load: function (path, pathGeometries, onSceneLoad, onObjectLoad, onMeshLoad, onComplete, stream) {
		this.path = path;
		this.stream = stream;
		this.debug = false;
		this.pathBase = path.substring(0, path.lastIndexOf('/')+1);
		path = this.pathCropBase(path);
		this.pathGeometries = pathGeometries;
		this.onSceneLoad = onSceneLoad;
		this.onObjectLoad = onObjectLoad;
		this.onComplete = onComplete;
		this.onMeshLoad = onMeshLoad;
		this.objectsByPath = {};
		this.geometries = {};
		this.cancelling = [];
		this.objectPaths = [];
		this.objectsWaitingForGeometriesByGeometryPaths = {};
		this.loadersByGeometryPaths = {};
		this.threeGeometryJSONLoader = new THREE.JSONLoader();
		this.threeObjectJSONLoader = new THREE.ObjectLoader();
		this.hierarchyRecieved = this.hierarchyRecieved.bind(this);
		this.geometryRecieved = this.geometryRecieved.bind(this);
		this.showByName = this.showByName.bind(this);
		this.hideByName = this.hideByName.bind(this);
		this.childError = this.childError.bind(this);
		JSONLoader.load(this.pathBase + path, this.hierarchyRecieved, this.childError);
		this.totalLoading++;
	},

	hierarchyRecieved: function(jsonData, path) {
		this.root = new THREE.Object3D();
		for(var childName in jsonData) {
			this.root.add(this.createObject(jsonData[childName], path + '/' + childName));
		}
		this.onSceneLoad({scene: this.root});
		this.onComplete();
	},

	childError: function(xhr) {
		var cancelIndex = this.cancelling.indexOf(xhr);
		if(cancelIndex != -1) {
			console.log('geometry load cancelled!');
			this.cancelling.splice(cancelIndex, 1);
		} else {
			throw('error loading');
		}
		// throw(xhr);
	},

	geometryRecieved: function(jsonData, path) {
		path = this.pathCropGeometries(path);
		path = path.substring(0, path.lastIndexOf('.json'));
		// console.log(jsonData);
		if(this.debug) console.log('loaded', path);

		var geometry = this.threeGeometryJSONLoader.parse(jsonData).geometry;
		this.integrateGeometry(geometry, path);
		this.incrementAndCheckLoad();
	},

	integrateGeometry: function(geometry, path) {
		if(this.debug) console.log('integrate geometry', path);
		this.geometries[path] = geometry;
		var objectsToPromote = this.objectsWaitingForGeometriesByGeometryPaths[path];
		if(objectsToPromote) {
			for (var i = objectsToPromote.length - 1; i >= 0; i--) {
				var object = objectsToPromote[i];
				var mesh = this.promoteObjectToMesh(object, geometry);
				if(object.geometryLoadCompleteCallback) {
					// if(i != 0) debugger;
					object.geometryLoadCompleteCallback();
					delete object.geometryLoadCompleteCallback;
				}
				delete this.loadersByGeometryPaths[object.geometryName];
				delete object.geometryName;
				// this.isolationTest(mesh);
			};
		}
		delete this.objectsWaitingForGeometriesByGeometryPaths[path];
	},

	loadGeometryOf: function(object, callback) {
		// object.add(new THREE.Mesh(new THREE.SphereGeometry(10)));
		var geometryName = object.geometryName;
		var geometryPath = this.pathGeometries + geometryName;
		var geometry = this.geometries[geometryName];
		if(this.debug) console.log('REQUEST', geometryName);
		if(geometry) {
			if(this.debug) console.log('reusing', geometryName);
			object = this.promoteObjectToMesh(object, geometry);
			return false;
		} else {
			if(!this.objectsWaitingForGeometriesByGeometryPaths[geometryName]) {
				if(this.debug) console.log('loading', geometryName);
				object.geometryLoadCompleteCallback = callback;
				this.objectsWaitingForGeometriesByGeometryPaths[geometryName] = [object];
				loader = JSONLoader.load(geometryPath + '.json', this.geometryRecieved, this.childError);
				this.loadersByGeometryPaths[geometryName] = loader;
				return true;
				// this.totalLoading++;
			} else {
				if(this.debug) console.log('waiting for', geometryName);
				this.objectsWaitingForGeometriesByGeometryPaths[geometryName].push(object);
				object.loadStatus = LOADING;
				return false;
			}
		}
	},

	cancelLoadGeometryOf: function(object) {
		// object.add(new THREE.Mesh(new THREE.SphereGeometry(10)));
		var geometryName = object.geometryName;
		if(this.debug) console.log('cancelling', geometryName);
		var geometryPath = this.pathGeometries + geometryName;
		var objectsWaitingForGeometry = this.objectsWaitingForGeometriesByGeometryPaths[geometryName]
		if(objectsWaitingForGeometry) {
			for (var i = objectsWaitingForGeometry.length - 1; i >= 0; i--) {
				var objectWaiting = objectsWaitingForGeometry.splice(i, 1)[0];
				delete objectWaiting.geometryLoadCompleteCallback;
			};
		}
		delete this.objectsWaitingForGeometriesByGeometryPaths[geometryName];
		this.cancelling.push(this.loadersByGeometryPaths[geometryName]);
		this.loadersByGeometryPaths[geometryName].abort();
		delete this.loadersByGeometryPaths[geometryName];
	},

	storeObject: function(path, object) {
		this.objectsByPath[path] = object;
		this.objectPaths.push(path);

		//fix the alias for notFound
		var slices = path.split('/');
		if(slices[slices.length-1].indexOf("notFound") != -1){
			slices[slices.length-1] = "notFound";
		}
		path = slices.join('/');

		this.objectsByPath[path] = object;
		this.objectPaths.push(path);
	},

	createObject: function(jsonData, path) {
		var object = this.threeObjectJSONLoader.parseObject(jsonData);
		while(object.children.length > 0) object.remove(object.children[0]);	//I only want the object
		object.path = path;
		object.materialName = jsonData.material;
		this.storeObject(path, object);
		var name = path.substring(path.lastIndexOf('/')+1, path.length);
		object.name = name;

		for(var childName in jsonData.children) {
			object.add(this.createObject(jsonData.children[childName], path + '/' + childName));
		}

		var geometryName = jsonData.geometry;
		if(geometryName) {
			object.loadStatus = LOAD_AVAILABLE;
			object.geometryName = geometryName;

			this.decorateObjectWithJITGeometryAPI(object);

		} else {
			object.loadStatus = LOAD_UNAVAILABLE;
		}

		if(jsonData.quaternion) {
			object.quaternion.x = jsonData.quaternion[0];
			object.quaternion.y = jsonData.quaternion[1];
			object.quaternion.z = jsonData.quaternion[2];
			object.quaternion.w = jsonData.quaternion[3];
		}
		this.onObjectLoad(object);
		return object;
	},

	promoteObjectToMesh: function(object, geometry) {
		var mesh = new THREE.Mesh(geometry);
		mesh.path = object.path;
		mesh.name = object.name;
		var parent = object.parent;
		object.loadStatus = SHOULDNT_EVEN_EXIST;
		mesh.loadStatus = LOADED;
		mesh.materialName = object.materialName;
		mesh.position.copy(object.position);
		mesh.scale.copy(object.scale);
		mesh.rotation.x = object.rotation.x;
		mesh.rotation.y = object.rotation.y;
		mesh.rotation.z = object.rotation.z;
		if(parent) {
			parent.remove(object);
			parent.add(mesh);
		} else {
			throw new Error('wtf');
		}

		for (var i = object.children.length - 1; i >= 0; i--) {
			mesh.add(object.children[i]);
		};
		var path = object.path;
		this.storeObject(path, mesh);

		if(object === this.root) {
			this.root = mesh;
		}

		this.decorateObjectWithJITGeometryAPI(mesh);
		this.onMeshLoad(mesh);
		return mesh;
	},

	incrementAndCheckLoad: function() {
		this.totalLoaded++;
		if(this.totalLoading == this.totalLoaded && !this.stream) {
			this.onSceneLoad({scene: this.root});
		}
	},

	pathCropBase: function(path) {
		return path.substring(this.pathBase.length, path.length);
	},

	pathCropGeometries: function(path) {
		return path.substring(this.pathGeometries.length, path.length);
	},

	notFound: function(name) {
		console.log(name, 'does not exist');
		if(name) {
			var slices = name.split('/');
			slices[slices.length-1] = 'notFound';
			name = slices.join('/');
		} else {
			name = 'notFound'
		}
		return this.objectsByPath[this.path + '/' + name];
	},

	showByName: function(name, recursive, childrenOnly) {
		this.setVisibilityByName(name, true, recursive, childrenOnly);
	},

	hideByName: function(name, recursive, childrenOnly) {
		this.setVisibilityByName(name, false, recursive, childrenOnly);
	},

	setVisibilityByName: function(name, state, recursive, childrenOnly) {
		var object = this.getObjectByName(name);
		if(!object) {
			object = this.notFound(name);
		}
		if(object) {
			if(!childrenOnly) {
				object.visible = state;
			}
			// if(state, console.log(name));
			if(recursive) {
				object.traverse(function(obj) {
					if(obj === object) return;
					obj.visible = state;
				});
			}
		}
	},

	loadByName: function(name, recursive, callback) {
		var object = this.getObjectByName(name);
		var loading = 0;
		var _this = this;
		function progressCallback() {
			loading--;
			if(_this.debug) console.log(name, 'remaining geometries to load:', loading);
			if(loading === 0) {
				if(callback) {
					callback();
				}
			}
		}
		if(!object) {
			object = this.notFound(name);
		}
		if(object) {
			if(object.load) {
				loading += object.load(progressCallback) ? 1 : 0;
			}
			if(recursive) {
				object.traverse(function(obj) {
					if(object === obj) return;
					if(obj.load) {
						loading += obj.load(progressCallback) ? 1 : 0;
					}
				});
			}
			if(this.debug) console.log('geometries to load:', loading)
			if(loading == 0 && callback) {
				callback();
			}
		}
	},

	cancelLoadByName: function(name, recursive, callback) {
		throw new Error('Not implemented yet');
	},

	checkIfLoadedByName: function(name, recursive) {
		var object = this.getObjectByName(name);
		var loaded = object.loadStatus == LOADED || object.loadStatus == LOAD_UNAVAILABLE;
		if(loaded && recursive) {
			object.traverse(function(obj) {
				if(obj.loadStatus != LOADED && obj.loadStatus != LOAD_UNAVAILABLE) {
					loaded = loaded && false;
					throw new Error('wtf');
				}
			})
		}
		return loaded;
	},

	decorateObjectWithJITGeometryAPI: function(object){
		var _this = this;
		object.load = function(callback) {
			if(object.loadStatus === LOAD_AVAILABLE) {
				object.loadStatus = LOADING;
				return _this.loadGeometryOf(object, callback);
			}
			return false;
		};
		object.unload = function(callback) {
			throw new Error('not implemented yet');
		};
		object.cancelLoad = function(callback) {
			throw new Error('not implemented yet');
		};
	},

	getObjectByName: function(name) {
		var objPath = this.path + '/' + name;
		return this.objectsByPath[objPath];
	}
}

module.exports = JsonTreeSceneLoader;<|endoftext|>


<commit_before>var Resource = require('resource-loader').Resource,
    core = require('../core'),
    extras = require('../extras'),
    path = require('path');

function parse(resource, texture) {
    var data = {};
    var info = resource.data.getElementsByTagName('info')[0];
    var common = resource.data.getElementsByTagName('common')[0];

    data.font = info.getAttribute('face');
    data.size = parseInt(info.getAttribute('size'), 10);
    data.lineHeight = parseInt(common.getAttribute('lineHeight'), 10);
    data.chars = {};

    //parse letters
    var letters = resource.data.getElementsByTagName('char');

    for (var i = 0; i < letters.length; i++)
    {
        var charCode = parseInt(letters[i].getAttribute('id'), 10);

        var textureRect = new core.Rectangle(
            parseInt(letters[i].getAttribute('x'), 10) + texture.frame.x,
            parseInt(letters[i].getAttribute('y'), 10) + texture.frame.y,
            parseInt(letters[i].getAttribute('width'), 10),
            parseInt(letters[i].getAttribute('height'), 10)
        );

        data.chars[charCode] = {
            xOffset: parseInt(letters[i].getAttribute('xoffset'), 10),
            yOffset: parseInt(letters[i].getAttribute('yoffset'), 10),
            xAdvance: parseInt(letters[i].getAttribute('xadvance'), 10),
            kerning: {},
            texture: new core.Texture(texture.baseTexture, textureRect)

        };
    }

    //parse kernings
    var kernings = resource.data.getElementsByTagName('kerning');
    for (i = 0; i < kernings.length; i++)
    {
        var first = parseInt(kernings[i].getAttribute('first'), 10);
        var second = parseInt(kernings[i].getAttribute('second'), 10);
        var amount = parseInt(kernings[i].getAttribute('amount'), 10);

        data.chars[second].kerning[first] = amount;
    }

    resource.bitmapFont = data;

    // I'm leaving this as a temporary fix so we can test the bitmap fonts in v3
    // but it's very likely to change
    extras.BitmapText.fonts[data.font] = data;
}

module.exports = function ()
{
    return function (resource, next)
    {
        // skip if no data or not xml data
        if (!resource.data || !resource.isXml)
        {
            return next();
        }

        // skip if not bitmap font data, using some silly duck-typing
        if (
            resource.data.getElementsByTagName('page').length === 0 ||
            resource.data.getElementsByTagName('info').length === 0 ||
            resource.data.getElementsByTagName('info')[0].getAttribute('face') === null
            )
        {
            return next();
        }

        var xmlUrl = path.dirname(resource.url);

        if (xmlUrl === '.') {
            xmlUrl = '';
        }

        if (this.baseUrl && xmlUrl) {
            // if baseurl has a trailing slash then add one to xmlUrl so the replace works below
            if (this.baseUrl.charAt(this.baseUrl.length - 1) === '/') {
                xmlUrl += '/';
            }

            // remove baseUrl from xmlUrl
            xmlUrl = xmlUrl.replace(this.baseUrl, '');
        }

        // if there is an xmlUrl now, it needs a trailing slash. Ensure that it does if the string isn't empty.
        if (xmlUrl && xmlUrl.charAt(xmlUrl.length - 1) !== '/') {
            xmlUrl += '/';
        }
        var textureUrl = xmlUrl + resource.data.getElementsByTagName('page')[0].getAttribute('file');
        if (core.utils.TextureCache[textureUrl]) {
            //reuse existing texture
            parse(resource, core.utils.TextureCache[textureUrl]);
            next();
        }
        else {
            var loadOptions = {
                crossOrigin: resource.crossOrigin,
                loadType: Resource.LOAD_TYPE.IMAGE
            };
            // load the texture for the font
            this.add(resource.name + '_image', textureUrl, loadOptions, function (res) {
                parse(resource, res.texture);
                next();
            });
        }
    };
};
<commit_msg>BitmapFonts respect useFilenamesForTextures.<commit_after>var Resource = require('resource-loader').Resource,
    core = require('../core'),
    extras = require('../extras'),
    path = require('path');

function parse(resource, texture) {
    var data = {};
    var info = resource.data.getElementsByTagName('info')[0];
    var common = resource.data.getElementsByTagName('common')[0];

    data.font = info.getAttribute('face');
    data.size = parseInt(info.getAttribute('size'), 10);
    data.lineHeight = parseInt(common.getAttribute('lineHeight'), 10);
    data.chars = {};

    //parse letters
    var letters = resource.data.getElementsByTagName('char');

    for (var i = 0; i < letters.length; i++)
    {
        var charCode = parseInt(letters[i].getAttribute('id'), 10);

        var textureRect = new core.Rectangle(
            parseInt(letters[i].getAttribute('x'), 10) + texture.frame.x,
            parseInt(letters[i].getAttribute('y'), 10) + texture.frame.y,
            parseInt(letters[i].getAttribute('width'), 10),
            parseInt(letters[i].getAttribute('height'), 10)
        );

        data.chars[charCode] = {
            xOffset: parseInt(letters[i].getAttribute('xoffset'), 10),
            yOffset: parseInt(letters[i].getAttribute('yoffset'), 10),
            xAdvance: parseInt(letters[i].getAttribute('xadvance'), 10),
            kerning: {},
            texture: new core.Texture(texture.baseTexture, textureRect)

        };
    }

    //parse kernings
    var kernings = resource.data.getElementsByTagName('kerning');
    for (i = 0; i < kernings.length; i++)
    {
        var first = parseInt(kernings[i].getAttribute('first'), 10);
        var second = parseInt(kernings[i].getAttribute('second'), 10);
        var amount = parseInt(kernings[i].getAttribute('amount'), 10);

        data.chars[second].kerning[first] = amount;
    }

    resource.bitmapFont = data;

    // I'm leaving this as a temporary fix so we can test the bitmap fonts in v3
    // but it's very likely to change
    extras.BitmapText.fonts[data.font] = data;
}

module.exports = function ()
{
    return function (resource, next)
    {
        // skip if no data or not xml data
        if (!resource.data || !resource.isXml)
        {
            return next();
        }

        // skip if not bitmap font data, using some silly duck-typing
        if (
            resource.data.getElementsByTagName('page').length === 0 ||
            resource.data.getElementsByTagName('info').length === 0 ||
            resource.data.getElementsByTagName('info')[0].getAttribute('face') === null
            )
        {
            return next();
        }

        var xmlUrl = path.dirname(resource.url);

        if (xmlUrl === '.') {
            xmlUrl = '';
        }

        if (this.baseUrl && xmlUrl) {
            // if baseurl has a trailing slash then add one to xmlUrl so the replace works below
            if (this.baseUrl.charAt(this.baseUrl.length - 1) === '/') {
                xmlUrl += '/';
            }

            // remove baseUrl from xmlUrl
            xmlUrl = xmlUrl.replace(this.baseUrl, '');
        }

        // if there is an xmlUrl now, it needs a trailing slash. Ensure that it does if the string isn't empty.
        if (xmlUrl && xmlUrl.charAt(xmlUrl.length - 1) !== '/') {
            xmlUrl += '/';
        }
        var textureUrl = xmlUrl + resource.data.getElementsByTagName('page')[0].getAttribute('file');
        var id = textureUrl;
        if(core.utils.useFilenamesForTextures)
        {
            id = core.utils.getFilenameFromUrl(id);
        }
        if (core.utils.TextureCache[id]) {
            //reuse existing texture
            parse(resource, core.utils.TextureCache[id]);
            next();
        }
        else {
            var loadOptions = {
                crossOrigin: resource.crossOrigin,
                loadType: Resource.LOAD_TYPE.IMAGE
            };
            // load the texture for the font
            this.add(resource.name + '_image', textureUrl, loadOptions, function (res) {
                parse(resource, res.texture);
                next();
            });
        }
    };
};
<|endoftext|>


<commit_before>function updateHiddenDate(elt)
{
    elt = $(elt);
    if (elt.value.length >= 10) {
        day = elt.value.substring(0,2);
        month = elt.value.substring(3,5);
        year = elt.value.substring(6,10);
        elt.up().down("input.date-selector-hidden").value = year + "-" + month + "-" + day;
    }

    if (elt.value.length == 0) {
        elt.up().down("input.date-selector-hidden").value = "";
    }
}

function updateHiddenDateTime(elt)
{
    elt = $(elt);
    if (elt.value.length >= 16) {
        day = elt.value.substring(0,2);
        month = elt.value.substring(3,5);
        year = elt.value.substring(6,10);
        hour = elt.value.substring(11,13);
        minute = elt.value.substring(14,16);
        elt.up().down("input.datetime-selector-hidden").value = year + "-" + month + "-" + day + " " + hour + ":" + minute;
    }

    if (elt.value.length == 0) {
        elt.up().down("input.datetime-selector-hidden").value = "";
    }
}

function onDateCalendarUpdate(calendar, date) {
    $(calendar.params.displayArea).value = calendar.date.print("%d/%m/%Y");
    $(calendar.params.inputField).value = calendar.date.print("%Y-%m-%d %H:%M:%S");
    if ($(calendar).dateClicked)
    {
        $(calendar).destroy();
    }
}

function onDatetimeCalendarUpdate(calendar, date) {
    $(calendar.params.displayArea).value = calendar.date.print("%d/%m/%Y %H:%M");
    $(calendar.params.inputField).value = calendar.date.print("%Y-%m-%d %H:%M:%S");
//    if ($(calendar).dateClicked)
//    {
//        $(calendar).destroy();
//    }
}

function onDateFieldBlur(elt)
{
    if (!isValidDateString($(elt).value) && $(elt).value != "")
    {
        alert("La date entrée n'est pas valide.\n Exemple : 09/01/2009")
        $(elt).value = "";
        elt.up().down("input.date-selector-hidden").value = "";
    }
}

function onDateTimeFieldBlur(elt)
{
    if (!isValidDateTimeString($(elt).value) && $(elt).value != "")
    {
        alert("La date entrée n'est pas valide.\n Exemple : 09/01/2009 13:45")
        $(elt).value = "";
        elt.up().down("input.datetime-selector-hidden").value = "";
    }
}

function isValidDateString(str)
{
    return(/^\d{2}\/\d{2}\/\d{4}$/.test(str))
}

function isValidDateTimeString(str)
{
    return(/^\d{2}\/\d{2}\/\d{4}\s\d{2}:\d{2}$/.test(str))
}

function setupCalendarFor(inputFieldId, displayFieldId, showTime)
{
    if (showTime)
    {
        Calendar.setup({
            inputField : inputFieldId,
            align : "bR",
            ifFormat : "%Y-%m-%d %H:%M",
            displayArea : displayFieldId,
            daFormat : "%d/%m/%Y %H:%M",
            showsTime : true,
            showOthers : true,
            onSelect : onDatetimeCalendarUpdate,
            button: displayFieldId + "_img"
        });
    }
    else
    {
        Calendar.setup({
            inputField : inputFieldId,
            align : "bR",
            ifFormat : "%Y-%m-%d %H:%M",
            displayArea : displayFieldId,
            daFormat : "%d/%m/%Y",
            showsTime : false,
            showOthers : true,
            onSelect : onDateCalendarUpdate,
            button: displayFieldId + "_img"
        });
    }
}
<commit_msg>Possibilité de saisir des dates partielles<commit_after>function updateHiddenDate(elt)
{
    elt = $(elt);
    if (elt.value.length >= 10) {
        day = elt.value.substring(0,2);
        month = elt.value.substring(3,5);
        year = elt.value.substring(6,10);
        elt.up().down("input.date-selector-hidden").value = year + "-" + month + "-" + day;
    }

    if (elt.value.length == 0) {
        elt.up().down("input.date-selector-hidden").value = "";
    }
}

function updateHiddenDateTime(elt)
{
    elt = $(elt);
    if (elt.value.length >= 16) {
        day = elt.value.substring(0,2);
        month = elt.value.substring(3,5);
        year = elt.value.substring(6,10);
        hour = elt.value.substring(11,13);
        minute = elt.value.substring(14,16);
        elt.up().down("input.datetime-selector-hidden").value = year + "-" + month + "-" + day + " " + hour + ":" + minute;
    }

    if (elt.value.length == 0) {
        elt.up().down("input.datetime-selector-hidden").value = "";
    }
}

function onDateCalendarUpdate(calendar, date) {
    $(calendar.params.displayArea).value = calendar.date.print("%d/%m/%Y");
    $(calendar.params.inputField).value = calendar.date.print("%Y-%m-%d %H:%M:%S");
    if ($(calendar).dateClicked)
    {
        $(calendar).destroy();
    }
}

function onDatetimeCalendarUpdate(calendar, date) {
    $(calendar.params.displayArea).value = calendar.date.print("%d/%m/%Y %H:%M");
    $(calendar.params.inputField).value = calendar.date.print("%Y-%m-%d %H:%M:%S");
}

function onDateFieldBlur(elt)
{
    completeDateStringFor(elt);

    if (!isValidDateString($(elt).value) && $(elt).value != "")
    {
        alert("La date entrée n'est pas valide.\n Exemple : 09/01/2009")
        $(elt).value = "";
        elt.up().down("input.date-selector-hidden").value = "";
    }
}

function onDateTimeFieldBlur(elt)
{
    if (!isValidDateTimeString($(elt).value) && $(elt).value != "")
    {
        alert("La date entrée n'est pas valide.\n Exemple : 09/01/2009 13:45")
        $(elt).value = "";
        elt.up().down("input.datetime-selector-hidden").value = "";
    }
}

function isValidDateString(str)
{
    return(/^\d{2}\/\d{2}\/\d{4}$/.test(str))
}

function isValidDateTimeString(str)
{
    return(/^\d{2}\/\d{2}\/\d{4}\s\d{2}:\d{2}$/.test(str))
}

function setupCalendarFor(inputFieldId, displayFieldId, showTime)
{
    if (showTime)
    {
        Calendar.setup({
            inputField : inputFieldId,
            align : "bR",
            ifFormat : "%Y-%m-%d %H:%M",
            displayArea : displayFieldId,
            daFormat : "%d/%m/%Y %H:%M",
            showsTime : true,
            showOthers : true,
            onSelect : onDatetimeCalendarUpdate,
            button: displayFieldId + "_img"
        });
    }
    else
    {
        Calendar.setup({
            inputField : inputFieldId,
            align : "bR",
            ifFormat : "%Y-%m-%d %H:%M",
            displayArea : displayFieldId,
            daFormat : "%d/%m/%Y",
            showsTime : false,
            showOthers : true,
            onSelect : onDateCalendarUpdate,
            button: displayFieldId + "_img"
        });
    }
}

function completeDateStringFor(elt)
{
    elt = $(elt);

    if (!isValidDateString(elt.value) && (/^\d{1,2}\/\d{1,2}(\/\d{1,4})?$/.test(elt.value)))
    {
        parts = elt.value.split(/\//);
        completed = "";

        if (parts[0].length == 1) {
            completed = "0" + parts[0] + "/";
        }

        if (parts[1].length == 1) {
            completed = completed + "0" + parts[1] + "/";
        }

        if ((parts.length == 2) || ((parts.length == 3) && (parts[2].length == 0))){
            completed = completed + (new Date()).getFullYear().toString();
        }
        else if ((parts.length == 3) && (parts[2].length > 0))  {
            completed = completed + (2000 + parseInt(parts[2])).toString();
        }

        elt.value = completed;
    }
}<|endoftext|>


<commit_before>// K is a constant that attenuates the diminishing return formula,
// giving lower damage reduction on higher difficulties.
export const ULDIR_K = [
  null, // unknown difficulty
  6300, // LFR --- using world K
  null, // unknown
  7736.4, // Normal
  8467.2, // Heroic
  9311.4, // Mythic
];

export const MPLUS_K = 8467.2;

export const BOD_K = [
  null,
  8467.2, // LFR
  null,
  9311.4,  // Normal
  10275.3, // Heroic
  11390.4, // Mythic
];

export function diminish(stat, K) {
  return stat / (stat + K);
}

export function lookupK(fight) {
    if(fight.size === 5) {
      return MPLUS_K;
    } else {
      return BOD_K[fight.difficulty];
    }
}
<commit_msg>lint error<commit_after>// K is a constant that attenuates the diminishing return formula,
// giving lower damage reduction on higher difficulties.
export const ULDIR_K = [
  null, // unknown difficulty
  6300, // LFR --- using world K
  null, // unknown
  7736.4, // Normal
  8467.2, // Heroic
  9311.4, // Mythic
];

export const MPLUS_K = 8467.2;

export const BOD_K = [
     null,
   8467.2, // LFR
     null,
   9311.4, // Normal
  10275.3, // Heroic
  11390.4, // Mythic
];

export function diminish(stat, K) {
  return stat / (stat + K);
}

export function lookupK(fight) {
    if(fight.size === 5) {
      return MPLUS_K;
    } else {
      return BOD_K[fight.difficulty];
    }
}
<|endoftext|>


<commit_before>/**
 * Copyright 2015 Solinea, Inc.
 *
 * Licensed under the Solinea Software License Agreement (goldstone),
 * Version 1.0 (the "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at:
 *
 *     http://www.solinea.com/goldstone/LICENSE.pdf
 *
 * 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 expressed or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var TenantSettingsPageView = GoldstoneBaseView.extend({

    defaults: {},

    initialize: function(options) {
        this.options = options || {};
        this.defaults = _.clone(this.defaults);
        this.el = options.el;
        this.render();
        this.getTenantSettings();
        this.addHandlers();
    },

    addHandlers: function() {
        var self = this;

        // add listener to settings form submission button
        $('.tenant-settings-form').on('submit', function(e) {
            // prevens page jump upon pressing submit button
            e.preventDefault();

            // if there is no selected tenant, prevent ability to submit form
            if ($('#formTenantId').text() === '') {
                self.dataErrorMessage('Must select tenant from list above');
                return;
            }

            // trim inputs to prevent leading/trailing spaces
            self.trimInputField('[name="name"]');
            self.trimInputField('[name="owner"]');
            self.trimInputField('[name="owner_contact"]');
            var tenandId = $('#formTenantId').text();

            // email fields seem to have native .trim() support

            // 4th argument informs what will be appeneded to screen upon success
            self.submitRequest('PUT', '/tenants/' + tenandId, $(this).serialize(), 'Tenant settings');
        });
    },

    drawDataTable: function(json) {

        var self = this;

        // make a dataTable
        var location = '#tenants-single-rsrc-table';
        var oTable;
        var keys = Object.keys(json);
        var data = _.map(keys, function(k) {
            var item = json[k];
            return [item.name, item.owner, item.owner_contact, item.uuid];
        });

        if ($.fn.dataTable.isDataTable(location)) {
            oTable = $(location).DataTable();
            oTable.clear().rows.add(data).draw();
        } else {
            var oTableParams = {
                "data": data,
                "autoWidth": true,
                "info": false,
                "paging": true,
                "searching": true,
                "columns": [{
                    "title": "Tenant"
                }, {
                    "title": "Owner's Username"
                }, {
                    "title": "Owner Contact"
                }, {
                    "title": "Tenant Id"
                }]
            };
            oTable = $(location).DataTable(oTableParams);
        }

        // IMPORTANT: failure to remove click listeners before appending new ones
        // will continue to create additional listeners and memory leaks.
        $("#tenants-single-rsrc-table tbody").off();

        // add click listeners to pass data values to Update Tenant Settings form.
        $("#tenants-single-rsrc-table tbody").on('click', 'tr', function() {
            var row = oTable.row(this).data();

            $(self.el).find('[name="name"]').val(row[0]);
            $(self.el).find('[name="owner"]').val(row[1]);
            $(self.el).find('[name="owner_contact"]').val(row[2]);
            $(self.el).find('#formTenantId').text(row[3]);

            self.clearDataErrorMessage();
        });
    },

    getTenantSettings: function() {
        var self = this;

        $.get('/tenants')
            .done(function(result) {

                if (result.results) {
                    self.drawDataTable(result.results);
                }
            })
            .fail(function(fail) {
                goldstone.raiseInfo('Could not load tenant settings', true);
            });
    },

    // abstracted to work for multiple forms, and append the correct
    // message upon successful form submission
    submitRequest: function(type, url, data, message) {
        var self = this;

        // Upon clicking the submit button, the serialized
        // user input is sent via type (POST/PUT/etc).
        // If successful, invoke "done". If not, invoke "fail"

        $.ajax({
            type: type,
            url: url,
            data: data,
        })
            .done(function(success) {
                goldstone.raiseInfo(message + ' update successful');
            })
            .fail(function(fail) {
                try {
                    goldstone.raiseInfo(fail.responseJSON.non_field_errors[0], true);
                } catch (e) {
                    goldstone.raiseInfo(fail.responseText + e, true);
                }
            })
            .always(function() {
                self.getTenantSettings();
                self.clearDataErrorMessage();
            });
    },

    render: function() {
        this.$el.html(this.template());
        this.dataErrorMessage('Select Tenant from table above to edit');
        return this;
    },

    trimInputField: function(selector) {

        // remove leading/trailing spaces
        var trimmedContent = $(selector).val().trim();
        $(selector).val(trimmedContent);
    },

    template: _.template('' +

        // dataTable
        '
' +
        '
' +
        '
 Tenants' +
        '
' +
        '
' +
        '
' +

        '
' +
        '

' +
        '
' +
        // end data table

        '
' +
        '
' +

        // update settings form
        '
' +
        '<form class="tenant-settings-form">' +
        '
Update Tenant Settings
' +
        '

' +
        'Tenant name' +
        '<input name="name" type="text" class="form-control" placeholder="Tenant name" required>' +
        'Owner name' +
        '<input name="owner" type="text" class="form-control" placeholder="Username of owner" required>' +
        'Owner contact' +
        '<input name="owner_contact" type="email" class="form-control" placeholder="Owner email address">' +
        '

Tenant Id: select from above
' +
        '
<button name="submit" class="btn btn-lg btn-primary btn-block" type="submit">Update</button>' +
        '</form>' +
        '
' +

        // close divs for row/container
        '
' +
        '
'

    )

});
<commit_msg>Use dataErrorMessage div in settings form, rather than page-level raiseInfo div for settings related feedback.<commit_after>/**
 * Copyright 2015 Solinea, Inc.
 *
 * Licensed under the Solinea Software License Agreement (goldstone),
 * Version 1.0 (the "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at:
 *
 *     http://www.solinea.com/goldstone/LICENSE.pdf
 *
 * 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 expressed or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var TenantSettingsPageView = GoldstoneBaseView.extend({

    defaults: {},

    initialize: function(options) {
        this.options = options || {};
        this.defaults = _.clone(this.defaults);
        this.el = options.el;
        this.render();
        this.getTenantSettings();
        this.addHandlers();
    },

    addHandlers: function() {
        var self = this;

        // add listener to settings form submission button
        $('.tenant-settings-form').on('submit', function(e) {
            // prevens page jump upon pressing submit button
            e.preventDefault();

            // if there is no selected tenant, prevent ability to submit form
            if ($('#formTenantId').text() === '') {
                self.dataErrorMessage('Must select tenant from list above');
                return;
            }

            // trim inputs to prevent leading/trailing spaces
            self.trimInputField('[name="name"]');
            self.trimInputField('[name="owner"]');
            self.trimInputField('[name="owner_contact"]');
            var tenandId = $('#formTenantId').text();

            // email fields seem to have native .trim() support

            // 4th argument informs what will be appeneded to screen upon success
            self.submitRequest('PUT', '/tenants/' + tenandId, $(this).serialize(), 'Tenant settings');
        });
    },

    drawDataTable: function(json) {

        var self = this;

        // make a dataTable
        var location = '#tenants-single-rsrc-table';
        var oTable;
        var keys = Object.keys(json);
        var data = _.map(keys, function(k) {
            var item = json[k];
            return [item.name, item.owner, item.owner_contact, item.uuid];
        });

        if ($.fn.dataTable.isDataTable(location)) {
            oTable = $(location).DataTable();
            oTable.clear().rows.add(data).draw();
        } else {
            var oTableParams = {
                "data": data,
                "autoWidth": true,
                "info": false,
                "paging": true,
                "searching": true,
                "columns": [{
                    "title": "Tenant"
                }, {
                    "title": "Owner's Username"
                }, {
                    "title": "Owner Contact"
                }, {
                    "title": "Tenant Id"
                }]
            };
            oTable = $(location).DataTable(oTableParams);
        }

        // IMPORTANT: failure to remove click listeners before appending new ones
        // will continue to create additional listeners and memory leaks.
        $("#tenants-single-rsrc-table tbody").off();

        // add click listeners to pass data values to Update Tenant Settings form.
        $("#tenants-single-rsrc-table tbody").on('click', 'tr', function() {
            var row = oTable.row(this).data();

            $(self.el).find('[name="name"]').val(row[0]);
            $(self.el).find('[name="owner"]').val(row[1]);
            $(self.el).find('[name="owner_contact"]').val(row[2]);
            $(self.el).find('#formTenantId').text(row[3]);

            self.clearDataErrorMessage();
        });
    },

    getTenantSettings: function() {
        var self = this;

        $.get('/tenants')
            .done(function(result) {

                if (result.results) {
                    self.drawDataTable(result.results);
                }
            })
            .fail(function(fail) {
                goldstone.raiseInfo('Could not load tenant settings', true);
            });
    },

    // abstracted to work for multiple forms, and append the correct
    // message upon successful form submission
    submitRequest: function(type, url, data, message) {
        var self = this;

        // Upon clicking the submit button, the serialized
        // user input is sent via type (POST/PUT/etc).
        // If successful, invoke "done". If not, invoke "fail"

        $.ajax({
            type: type,
            url: url,
            data: data,
        })
            .done(function(success) {
                self.dataErrorMessage(message + ' update successful');
            })
            .fail(function(fail) {
                try {
                    self.dataErrorMessage(fail.responseJSON.non_field_errors[0]);
                } catch (e) {
                    self.dataErrorMessage(fail.responseText + e);
                }
                self.clearDataErrorMessage();
            })
            .always(function() {
                self.getTenantSettings();
            });
    },

    render: function() {
        this.$el.html(this.template());
        this.dataErrorMessage('Select Tenant from table above to edit');
        return this;
    },

    trimInputField: function(selector) {

        // remove leading/trailing spaces
        var trimmedContent = $(selector).val().trim();
        $(selector).val(trimmedContent);
    },

    template: _.template('' +

        // dataTable
        '
' +
        '
' +
        '
 Tenants' +
        '
' +
        '
' +
        '
' +

        '
' +
        '

' +
        '
' +
        // end data table

        '
' +
        '
' +

        // update settings form
        '
' +
        '<form class="tenant-settings-form">' +
        '
Update Tenant Settings
' +
        '

' +
        'Tenant name' +
        '<input name="name" type="text" class="form-control" placeholder="Tenant name" required>' +
        'Owner name' +
        '<input name="owner" type="text" class="form-control" placeholder="Username of owner" required>' +
        'Owner contact' +
        '<input name="owner_contact" type="email" class="form-control" placeholder="Owner email address">' +
        '

Tenant Id: select from above
' +
        '
<button name="submit" class="btn btn-lg btn-primary btn-block" type="submit">Update</button>' +
        '</form>' +
        '
' +

        // close divs for row/container
        '
' +
        '
'

    )

});
<|endoftext|>


<commit_before>var storageChange="Google.com";
function convertURL(url){
    console.log(url)
    url = url.replace(/%20/g,"+")
    var uri = /\?q\=([0-9a-zA-Z-._~:\/?#[\]@!$'()*+,;=%]*)($|(\&))/.exec(url)[1]
    console.log(url)
    console.log(uri)

    var match = /^((go\+to\+)|(open\+up\+))([0-9a-zA-Z-._~:\/?#[\]@!$'()*+,;=%]*\.[a-z]+)/i.exec(uri)
    console.log(match)
    if(match){
        return "http://" + match[4]
    }
    if(url.search("search?q=go%20to%20")!=-1){
        return "http://" + url.substring(url.search('=')+11, url.search('&'));
    }
    if(storageChange=="Google.com"){
        return url.replace("www.bing.com/search", "www.google.com/search");
    }
    if(storageChange=="DuckDuckGo.com"){
        return url.replace("www.bing.com/search", "www.duckduckgo.com");
    }
    if(storageChange=="Ask.com"){
        return url.replace(/.*:\/\/www.bing.com\/search/, "http://www.ask.com/web");
    }
    if(storageChange=="Yahoo.com"){
        return url.replace("www.bing.com/search?q", "search.yahoo.com/search?p");
    }
    if(storageChange=="Aol.com"){
        return url.replace(/.*:\/\/www.bing.com\/search/, "http://search.aol.com/aol/search");
    }
    if(storageChange=="Wow.com"){
        return url.replace(/.*:\/\/www.bing.com/, "http://us.wow.com");
    }
    return url.replace("www.bing.com/search", "www.google.com/search");
}
chrome.storage.sync.get('search_engine', function (obj) {
        console.log('myKey', obj);
        storageChange=obj['search_engine'];
});

chrome.storage.onChanged.addListener(function(changes, namespace) {
    storageChange = changes['search_engine']['newValue'];
    console.log(storageChange);
});

chrome.webRequest.onBeforeRequest.addListener(function(details) {
   	console.log(storageChange);

    return { redirectUrl: convertURL(details.url)};
}, {urls: ["*://www.bing.com/search*"]}, ["blocking"]);

// Redirect to welcome.html on install
chrome.runtime.onInstalled.addListener(function(details){
    if(details.reason == "install"){
        chrome.tabs.create({url: "html/options.html?newinstall=yes"});
    }else if(details.reason == "update"){
        var thisVersion = chrome.runtime.getManifest().version;
        console.log("Updated from " + details.previousVersion + " to " + thisVersion + "!");
    }
});
// Fallback when Chrome is not already running
chrome.runtime.onMessage.addListener(onMessage);
function onMessage(request, sender, callback) {
    if (request.action == "convertURL") {
        callback(convertURL(request.url));
    }
    return true;
}
<commit_msg>Open up to open<commit_after>var storageChange="Google.com";
function convertURL(url){
    console.log(url)
    url = url.replace(/%20/g,"+")
    var uri = /\?q\=([0-9a-zA-Z-._~:\/?#[\]@!$'()*+,;=%]*)($|(\&))/.exec(url)[1]
    console.log(url)
    console.log(uri)

    var match = /^((go\+to\+)|(open\+))([0-9a-zA-Z-._~:\/?#[\]@!$'()*+,;=%]*\.[a-z]+)/i.exec(uri)
    console.log(match)
    if(match){
        return "http://" + match[4]
    }
    if(url.search("search?q=go%20to%20")!=-1){
        return "http://" + url.substring(url.search('=')+11, url.search('&'));
    }
    if(storageChange=="Google.com"){
        return url.replace("www.bing.com/search", "www.google.com/search");
    }
    if(storageChange=="DuckDuckGo.com"){
        return url.replace("www.bing.com/search", "www.duckduckgo.com");
    }
    if(storageChange=="Ask.com"){
        return url.replace(/.*:\/\/www.bing.com\/search/, "http://www.ask.com/web");
    }
    if(storageChange=="Yahoo.com"){
        return url.replace("www.bing.com/search?q", "search.yahoo.com/search?p");
    }
    if(storageChange=="Aol.com"){
        return url.replace(/.*:\/\/www.bing.com\/search/, "http://search.aol.com/aol/search");
    }
    if(storageChange=="Wow.com"){
        return url.replace(/.*:\/\/www.bing.com/, "http://us.wow.com");
    }
    return url.replace("www.bing.com/search", "www.google.com/search");
}
chrome.storage.sync.get('search_engine', function (obj) {
        console.log('myKey', obj);
        storageChange=obj['search_engine'];
});

chrome.storage.onChanged.addListener(function(changes, namespace) {
    storageChange = changes['search_engine']['newValue'];
    console.log(storageChange);
});

chrome.webRequest.onBeforeRequest.addListener(function(details) {
   	console.log(storageChange);

    return { redirectUrl: convertURL(details.url)};
}, {urls: ["*://www.bing.com/search*"]}, ["blocking"]);

// Redirect to welcome.html on install
chrome.runtime.onInstalled.addListener(function(details){
    if(details.reason == "install"){
        chrome.tabs.create({url: "html/options.html?newinstall=yes"});
    }else if(details.reason == "update"){
        var thisVersion = chrome.runtime.getManifest().version;
        console.log("Updated from " + details.previousVersion + " to " + thisVersion + "!");
    }
});
// Fallback when Chrome is not already running
chrome.runtime.onMessage.addListener(onMessage);
function onMessage(request, sender, callback) {
    if (request.action == "convertURL") {
        callback(convertURL(request.url));
    }
    return true;
}
<|endoftext|>


<commit_before>/* global EventEmitter */

var app = app || {};

app.ServerHub = (function() {
    var self = this;

    self.serverUrl = "http://appdrawing.apphb.com";

    self.drawingHub = $.hubConnection(self.serverUrl);
    self.drawingHubProxy = self.drawingHub.createHubProxy("drawingHub");
    self.isConnected = false;
    self.ee = new EventEmitter();

    self.drawLine = function(startX, startY, endX, endY, lineWidth, lineColor) {
        self.drawingHubProxy.invoke("drawLine", {
            initialPosition: {x: startX, y: startY},
            endPosition: {x: endX, y: endY},
            width: lineWidth,
            color: lineColor
        });
    };

    self.start = function(canvasId) {
        self.drawingHub.qs = {canvasId: canvasId};
        self.drawingHub.start().done(self.onConnected);
        console.log("connecting to: " + canvasId);
    };

    self.stop = function() {
        if (self.isConnected) {
            self.drawingHub.stop();
        }
    };

    self.addListener = function(event, callback) {
        self.ee.addListener(event, callback);
    };

    self.onConnected = function() {
        self.isConnected = true;
    };

    self.drawingHubProxy.on("drawLine", function(line) {
        self.ee.emitEvent("drawLine", [line]);
    });

    self.drawingHubProxy.on("setInitialState", function(lines) {
        self.ee.emitEvent("setInitialState", [lines]);
    });

    self.drawingHubProxy.on("updateUsersInCanvas", function(totalUsers) {
        self.ee.emitEvent("updateUsersInCanvas", [totalUsers]);
    });

    return {
        drawLine: self.drawLine,
        start: self.start,
        stop: self.stop,
        addListener: self.addListener
    };
})();<commit_msg>Remove debug message.<commit_after>/* global EventEmitter */

var app = app || {};

app.ServerHub = (function() {
    var self = this;

    self.serverUrl = "http://appdrawing.apphb.com";

    self.drawingHub = $.hubConnection(self.serverUrl);
    self.drawingHubProxy = self.drawingHub.createHubProxy("drawingHub");
    self.isConnected = false;
    self.ee = new EventEmitter();

    self.drawLine = function(startX, startY, endX, endY, lineWidth, lineColor) {
        self.drawingHubProxy.invoke("drawLine", {
            initialPosition: {x: startX, y: startY},
            endPosition: {x: endX, y: endY},
            width: lineWidth,
            color: lineColor
        });
    };

    self.start = function(canvasId) {
        self.drawingHub.qs = {canvasId: canvasId};
        self.drawingHub.start().done(self.onConnected);
    };

    self.stop = function() {
        if (self.isConnected) {
            self.drawingHub.stop();
        }
    };

    self.addListener = function(event, callback) {
        self.ee.addListener(event, callback);
    };

    self.onConnected = function() {
        self.isConnected = true;
    };

    self.drawingHubProxy.on("drawLine", function(line) {
        self.ee.emitEvent("drawLine", [line]);
    });

    self.drawingHubProxy.on("setInitialState", function(lines) {
        self.ee.emitEvent("setInitialState", [lines]);
    });

    self.drawingHubProxy.on("updateUsersInCanvas", function(totalUsers) {
        self.ee.emitEvent("updateUsersInCanvas", [totalUsers]);
    });

    return {
        drawLine: self.drawLine,
        start: self.start,
        stop: self.stop,
        addListener: self.addListener
    };
})();<|endoftext|>


<commit_before>
function disableAddComment() {
    jQuery("#thecomment .addCommentButton").attr('disabled', true);
}
function isAddCommentFormValid() {
    var isValid = (jQuery.trim(jQuery("#thecomment .commentContent").val()) != '');
    if (!isValid) {
        isValid = jQuery.trim(CKEDITOR.instances.messageContent.getData()) != '';
    }

    if (isValid) {
        jQuery('#thecomment .errorMsg').hide();
    }
    else {
        jQuery('#thecomment .errorMsg').show();
    }
    return isValid;
}

function editComment(messageId, url){
    var comment = extractText('message_' + messageId);
    $('#message_' + messageId).empty();
    var formContent = '<form method="post" action="' + url + '">';
    formContent += '<textarea id="text_' + messageId + '" name="comment" style="width: 100%; height: 150px;"></textarea>';
    formContent += '<input name="messageId" type="hidden" value="' + messageId + '"/>';
    formContent += '
Save
';
    formContent += '</form>';
    $('#message_' + messageId).append(formContent);
    $('#message_' + messageId).next().remove();

    $('#text_'+messageId).text(comment);
}

function extractText(elementId) {
    var html = jQuery('#' + elementId).html();
    html = html.replace(new RegExp('

', 'g'), '"')
        .replace(new RegExp('
', 'g'), '"')
        .replace(new RegExp('
', 'g'), '"');

    console.log("html: " + html);

    jQuery('#' + elementId).html(html);
    console.log("text: " + jQuery('#' + elementId).text());
    var text = jQuery('#' + elementId).text().replace(new RegExp('" ', 'g'), '\n').replace(new RegExp('"', 'g'), '\n');

    // Fix weird leading white space browser behaviour
    if (text.charAt(0) == " ") {
        return text.substring(1);
    } else {
        return text;
    }
}

/**
 Update add this urls to messages
 **/
jQuery(function() {
    if ($("#messageContent").length > 0) {
        var baseLocation = window.location.toString();
        if (baseLocation.indexOf("#") >= 0) {
            baseLocation = baseLocation.substring(0, baseLocation.indexOf("#"));
        }
        jQuery(".message_add_this").each(function() {
            var self = jQuery(this);
            self.attr("addthis:url", baseLocation + self.attr("data-hash"));
        });

        //restore comment content from a previously set cookie.
        if ($("#messageContent").val() == "" && $.cookie("proposal-comment-body")) {
            $("#messageContent").val($.cookie("proposal-comment-body"));
        }

        //submit button functionality for adding new comments
        $("#addCommentButton").click(function() {
            //save the comment in a cookie, in case the user is not logged in
            $.cookie("proposal-comment-body", $("#messageContent").val(), {path: "/"});

            if ($(this).attr("data-is-deferred") == "true") {
                deferUntilLogin();
            } else {
                if (! window.isAddCommentFormValid()) {
                    return false;
                }
                window.disableAddComment();
                $('#addCommentForm').submit();
            }
        });
    }
});<commit_msg>Added rich text editor to edit function<commit_after>
function disableAddComment() {
    jQuery("#thecomment .addCommentButton").attr('disabled', true);
}
function isAddCommentFormValid() {
    var isValid = (jQuery.trim(jQuery("#thecomment .commentContent").val()) != '');
    if (!isValid) {
        isValid = jQuery.trim(CKEDITOR.instances.messageContent.getData()) != '';
    }

    if (isValid) {
        jQuery('#thecomment .errorMsg').hide();
    }
    else {
        jQuery('#thecomment .errorMsg').show();
    }
    return isValid;
}

function editComment(messageId, url){
    var comment = jQuery('#' + 'message_' + messageId).html(); //extractText('message_' + messageId);
    $('#message_' + messageId).empty();
    var formContent = '<form method="post" action="' + url + '">';
    formContent += '<textarea class="rte" id="text_' + messageId + '" name="comment" style="width: 100%; height: 150px;"></textarea>';
    formContent += '<input name="messageId" type="hidden" value="' + messageId + '"/>';
    formContent += '
Save
';
    formContent += '</form>';
    $('#message_' + messageId).append(formContent);
    $('#message_' + messageId).next().remove();

    $('#text_'+messageId).html(comment);
    initializeTextEditors();
}

function extractText(elementId) {
    var html = jQuery('#' + elementId).html();
    html = html.replace(new RegExp('

', 'g'), '"')
        .replace(new RegExp('
', 'g'), '"')
        .replace(new RegExp('
', 'g'), '"');

    console.log("html: " + html);

    jQuery('#' + elementId).html(html);
    console.log("text: " + jQuery('#' + elementId).text());
    var text = jQuery('#' + elementId).text().replace(new RegExp('" ', 'g'), '\n').replace(new RegExp('"', 'g'), '\n');

    // Fix weird leading white space browser behaviour
    if (text.charAt(0) == " ") {
        return text.substring(1);
    } else {
        return text;
    }
}

/**
 Update add this urls to messages
 **/
jQuery(function() {
    if ($("#messageContent").length > 0) {
        var baseLocation = window.location.toString();
        if (baseLocation.indexOf("#") >= 0) {
            baseLocation = baseLocation.substring(0, baseLocation.indexOf("#"));
        }
        jQuery(".message_add_this").each(function() {
            var self = jQuery(this);
            self.attr("addthis:url", baseLocation + self.attr("data-hash"));
        });

        //restore comment content from a previously set cookie.
        if ($("#messageContent").val() == "" && $.cookie("proposal-comment-body")) {
            $("#messageContent").val($.cookie("proposal-comment-body"));
        }

        //submit button functionality for adding new comments
        $("#addCommentButton").click(function() {
            //save the comment in a cookie, in case the user is not logged in
            $.cookie("proposal-comment-body", $("#messageContent").val(), {path: "/"});

            if ($(this).attr("data-is-deferred") == "true") {
                deferUntilLogin();
            } else {
                if (! window.isAddCommentFormValid()) {
                    return false;
                }
                window.disableAddComment();
                $('#addCommentForm').submit();
            }
        });
    }
});<|endoftext|>


<commit_before>/*
*   Required Props:
*   dbReference: string,
*   labelText: string,
*   route: string
*/

import React, {Component} from 'react'
import { withRouter } from 'react-router-dom'
import Button from 'muicss/lib/react/button'
import {base} from '../../config/constants'

class deleteAndRouteButton extends Component {

  delete() {
    base
      .remove(this.props.dbReference)
      .then(() => {
        this.props.history.push(this.props.route)
      })
      .catch(error => {
        //handle error
      });
  }

  render() {
    return (
      <Button onClick={this
        .delete
        .bind(this)} variant="raised">
        {this.props.labelText}
      </Button>
    )
  }
}

export default withRouter(deleteAndRouteButton)<commit_msg>added M-UI<commit_after>/*
*   Required Props:
*   dbReference: string,
*   labelText: string,
*   route: string
*/

import React, {Component} from 'react'
import { withRouter } from 'react-router-dom'
import {base} from '../../config/constants'
import RaisedButton from 'material-ui/RaisedButton'

class deleteAndRouteButton extends Component {

  delete() {
    base
      .remove(this.props.dbReference)
      .then(() => {
        this.props.history.push(this.props.route)
      })
      .catch(error => {
        //handle error
      });
  }

  render() {
    return (
      <RaisedButton
        onClick={this
        .delete
        .bind(this)}
        label={this.props.labelText}
      />
    )
  }
}

export default withRouter(deleteAndRouteButton)<|endoftext|>


<commit_before>/**
 * http://www.privacyidea.org
 * (c) cornelius kölbel, cornelius@privacyidea.org
 *
 * 2016-05-08 Cornelius Kölbel, <cornelius@privacyidea.org>
 *
 * This code is free software; you can redistribute it and/or
 * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
 * License as published by the Free Software Foundation; either
 * version 3 of the License, or any later version.
 *
 * This code is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU AFFERO GENERAL PUBLIC LICENSE for more details.
 *
 * You should have received a copy of the GNU Affero General Public
 * License along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */
myApp.controller("eventController", function($scope, $stateParams,
                                             $location, ConfigFactory) {
    if ($location.path() === "/config/events") {
        $location.path("/config/events/list");
    }

    // Get all events
    $scope.getEvents = function () {
        ConfigFactory.getEvents(function(data) {
            $scope.events = data.result.value;
            console.log("Fetched all events");
            console.log($scope.events);
        });
    };

    $scope.delEvent = function (eventid) {
        console.log("Deleting event " + eventid);
        ConfigFactory.delEvent(eventid, function(data) {
            console.log(data);
            $scope.getEvents();
        });
    };
    $scope.getEvents();
});

myApp.controller("eventDetailController", function($scope, $stateParams,
                                                    ConfigFactory, $state) {
    // init
    $scope.form = {};
    $scope.eventid = $stateParams.eventid;
    $scope.availableEvents = Array();
    $scope.opts = {};
    $scope.conds = {};
    $scope.actionCheckBox = {};
    $scope.conditionCheckBox = {};

    $scope.getEvent = function () {
        ConfigFactory.getEvent($scope.eventid, function(event) {
            console.log("Fetching single event " + $scope.eventid);
            console.log("=== Result value 1:");
            console.log(event.result.value);
            // first we need to fetch the action-list:
            ConfigFactory.getHandlerActions(event.result.value[0].handlermodule,
                function(actions){
                    $scope.handlerOptions = actions.result.value;
                    $scope.handlerActions = Object.keys($scope.handlerOptions);
                    $scope.form = event.result.value[0];
                    // tick the checked events
                    for (var i=0; i<$scope.availableEvents.length; i++) {
                       var name = $scope.availableEvents[i].name;
                        if ($scope.form.event.indexOf(name) >= 0) {
                            $scope.availableEvents[i].ticked = true;
                        }
                    }
                    // set the options
                    $scope.actionChanged();
                    $scope.opts = event.result.value[0].options;
                    // set bool options, which are marked as "1" to true
                    angular.forEach($scope.opts, function(value, opt){
                        // We need to check if $scope.form.action[opt]
                        // exist. Since if the handler was changed, there
                        // could be an option of another handler type, which
                        // is not available anymore.
                        if ($scope.handlerOptions[$scope.form.action][opt] &&
                            $scope.handlerOptions[$scope.form.action][opt].type === "bool" && value === "1") {
                            $scope.opts[opt] = true;
                        }
                    });
                    // get the configured conditions
                    $scope.conds = event.result.value[0].conditions;
                    angular.forEach($scope.conds, function(value, cond){
                        console.log("[Condition] " + cond + ": " + value);
                        $scope.conditionCheckBox[cond] = true;
                    });
                    // get the available conditions
                    $scope.getHandlerConditions();
                });
        });
    };

    $scope.getAvailableEvents = function () {
        ConfigFactory.getEvent("available", function(data) {
            console.log("getting available events");
            var events = data.result.value;
            $scope.availableEvents = Array();
            angular.forEach(events, function(event) {
                $scope.availableEvents.push({"name": event})
            });
            console.log($scope.availableEvents);
        });
    };

    $scope.getHandlerModules = function () {
        ConfigFactory.getEvent("handlermodules", function(data) {
            console.log("getting handlermodules");
            $scope.handlermodules = data.result.value;
            console.log($scope.handlermodules );
        });
    };

    $scope.createEvent = function () {
        // This is called to save the event handler
        $scope.form.id = $scope.eventid;
        var events = Array();
        // transform the event options to form parameters
        for (var option in $scope.opts) {
            if ($scope.opts.hasOwnProperty(option)) {
                $scope.form["option." + option] = $scope.opts[option];
            }
        }
        // push all ticked events
        angular.forEach($scope.selectedEvents, function(event){
            if (event.ticked === true) {
                events.push(event.name);
            }
        });
        $scope.form.event = events.join(",");
        console.log("saving events " + $scope.form.event);
        // Add the activated conditions
        $scope.form.conditions = {};
        angular.forEach($scope.conditionCheckBox, function(activated, value){
            if (activated===true) {
                if (typeof $scope.conds[value] === "object") {
                    // push all ticked values
                    var multivalue = Array();
                    angular.forEach($scope.conds[value], function(mval){
                        if (mval.ticked === true) {
                            multivalue.push(mval.name);
                        }
                    });
                    $scope.form.conditions[value] = multivalue.join(",")
                } else {
                    $scope.form.conditions[value] = $scope.conds[value];
                }
            }
        });
        ConfigFactory.setEvent($scope.form, function() {
            $state.go("config.events.list");
        });
        $('html,body').scrollTop(0);
    };

    $scope.getHandlerActions = function () {
        console.log("getting handler actions for " + $scope.form.handlermodule);
        ConfigFactory.getHandlerActions($scope.form.handlermodule,
            function(actions){
                $scope.handlerOptions = actions.result.value;
                $scope.handlerActions = Object.keys($scope.handlerOptions);
                console.log($scope.handlerActions);
                console.log($scope.form);
            });
    };

    $scope.getHandlerConditions = function () {
        console.log("getting handler conditions for " + $scope.form.handlermodule);
        ConfigFactory.getHandlerConditions($scope.form.handlermodule,
            function (conditions) {
                $scope.handlerConditions = conditions.result.value;
                // tick selected handlerConditions, if type===multi
                angular.forEach($scope.handlerConditions, function(condition, name){
                     if (condition.type === "multi" && Object.keys($scope.conds).indexOf(name) >= 0) {
                        console.log("The multi condition " + name + " is" +
                            " configured! We need to tick the values.");
                        var tickedConditions = $scope.conds[name].split(",");
                        // Now we iterate over the possible values of this
                        // condition
                        var possibleValues = $scope.handlerConditions[name].value;
                        for (var i=0; i<possibleValues.length; i++) {
                            console.log("check " + possibleValues[i].name);
                            if (tickedConditions.indexOf(
                                $scope.handlerConditions[name].value[i].name) >= 0) {
                                $scope.handlerConditions[name].value[i].ticked = true;
                            }
                        }
                    }
                });
            });
    };

    $scope.handlerModuleChanged = function () {
        $scope.getHandlerActions();
        $scope.getHandlerConditions();
    };

    $scope.actionChanged = function () {
        $scope.options = $scope.handlerOptions[$scope.form.action];
    };

    $scope.getAvailableEvents();
    $scope.getHandlerModules();
    if ($scope.eventid) {
        $scope.getEvent();
    }

});
<commit_msg>remove superflous console log<commit_after>/**
 * http://www.privacyidea.org
 * (c) cornelius kölbel, cornelius@privacyidea.org
 *
 * 2016-05-08 Cornelius Kölbel, <cornelius@privacyidea.org>
 *
 * This code is free software; you can redistribute it and/or
 * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
 * License as published by the Free Software Foundation; either
 * version 3 of the License, or any later version.
 *
 * This code is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU AFFERO GENERAL PUBLIC LICENSE for more details.
 *
 * You should have received a copy of the GNU Affero General Public
 * License along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */
myApp.controller("eventController", function($scope, $stateParams,
                                             $location, ConfigFactory) {
    if ($location.path() === "/config/events") {
        $location.path("/config/events/list");
    }

    // Get all events
    $scope.getEvents = function () {
        ConfigFactory.getEvents(function(data) {
            $scope.events = data.result.value;
            console.log("Fetched all events");
            console.log($scope.events);
        });
    };

    $scope.delEvent = function (eventid) {
        console.log("Deleting event " + eventid);
        ConfigFactory.delEvent(eventid, function(data) {
            console.log(data);
            $scope.getEvents();
        });
    };
    $scope.getEvents();
});

myApp.controller("eventDetailController", function($scope, $stateParams,
                                                    ConfigFactory, $state) {
    // init
    $scope.form = {};
    $scope.eventid = $stateParams.eventid;
    $scope.availableEvents = Array();
    $scope.opts = {};
    $scope.conds = {};
    $scope.actionCheckBox = {};
    $scope.conditionCheckBox = {};

    $scope.getEvent = function () {
        ConfigFactory.getEvent($scope.eventid, function(event) {
            console.log("Fetching single event " + $scope.eventid);
            // first we need to fetch the action-list:
            ConfigFactory.getHandlerActions(event.result.value[0].handlermodule,
                function(actions){
                    $scope.handlerOptions = actions.result.value;
                    $scope.handlerActions = Object.keys($scope.handlerOptions);
                    $scope.form = event.result.value[0];
                    // tick the checked events
                    for (var i=0; i<$scope.availableEvents.length; i++) {
                       var name = $scope.availableEvents[i].name;
                        if ($scope.form.event.indexOf(name) >= 0) {
                            $scope.availableEvents[i].ticked = true;
                        }
                    }
                    // set the options
                    $scope.actionChanged();
                    $scope.opts = event.result.value[0].options;
                    // set bool options, which are marked as "1" to true
                    angular.forEach($scope.opts, function(value, opt){
                        // We need to check if $scope.form.action[opt]
                        // exist. Since if the handler was changed, there
                        // could be an option of another handler type, which
                        // is not available anymore.
                        if ($scope.handlerOptions[$scope.form.action][opt] &&
                            $scope.handlerOptions[$scope.form.action][opt].type === "bool" && value === "1") {
                            $scope.opts[opt] = true;
                        }
                    });
                    // get the configured conditions
                    $scope.conds = event.result.value[0].conditions;
                    angular.forEach($scope.conds, function(value, cond){
                        console.log("[Condition] " + cond + ": " + value);
                        $scope.conditionCheckBox[cond] = true;
                    });
                    // get the available conditions
                    $scope.getHandlerConditions();
                });
        });
    };

    $scope.getAvailableEvents = function () {
        ConfigFactory.getEvent("available", function(data) {
            console.log("getting available events");
            var events = data.result.value;
            $scope.availableEvents = Array();
            angular.forEach(events, function(event) {
                $scope.availableEvents.push({"name": event})
            });
            console.log($scope.availableEvents);
        });
    };

    $scope.getHandlerModules = function () {
        ConfigFactory.getEvent("handlermodules", function(data) {
            console.log("getting handlermodules");
            $scope.handlermodules = data.result.value;
            console.log($scope.handlermodules );
        });
    };

    $scope.createEvent = function () {
        // This is called to save the event handler
        $scope.form.id = $scope.eventid;
        var events = Array();
        // transform the event options to form parameters
        for (var option in $scope.opts) {
            if ($scope.opts.hasOwnProperty(option)) {
                $scope.form["option." + option] = $scope.opts[option];
            }
        }
        // push all ticked events
        angular.forEach($scope.selectedEvents, function(event){
            if (event.ticked === true) {
                events.push(event.name);
            }
        });
        $scope.form.event = events.join(",");
        console.log("saving events " + $scope.form.event);
        // Add the activated conditions
        $scope.form.conditions = {};
        angular.forEach($scope.conditionCheckBox, function(activated, value){
            if (activated===true) {
                if (typeof $scope.conds[value] === "object") {
                    // push all ticked values
                    var multivalue = Array();
                    angular.forEach($scope.conds[value], function(mval){
                        if (mval.ticked === true) {
                            multivalue.push(mval.name);
                        }
                    });
                    $scope.form.conditions[value] = multivalue.join(",")
                } else {
                    $scope.form.conditions[value] = $scope.conds[value];
                }
            }
        });
        ConfigFactory.setEvent($scope.form, function() {
            $state.go("config.events.list");
        });
        $('html,body').scrollTop(0);
    };

    $scope.getHandlerActions = function () {
        console.log("getting handler actions for " + $scope.form.handlermodule);
        ConfigFactory.getHandlerActions($scope.form.handlermodule,
            function(actions){
                $scope.handlerOptions = actions.result.value;
                $scope.handlerActions = Object.keys($scope.handlerOptions);
                console.log($scope.handlerActions);
                console.log($scope.form);
            });
    };

    $scope.getHandlerConditions = function () {
        console.log("getting handler conditions for " + $scope.form.handlermodule);
        ConfigFactory.getHandlerConditions($scope.form.handlermodule,
            function (conditions) {
                $scope.handlerConditions = conditions.result.value;
                // tick selected handlerConditions, if type===multi
                angular.forEach($scope.handlerConditions, function(condition, name){
                     if (condition.type === "multi" && Object.keys($scope.conds).indexOf(name) >= 0) {
                        console.log("The multi condition " + name + " is" +
                            " configured! We need to tick the values.");
                        var tickedConditions = $scope.conds[name].split(",");
                        // Now we iterate over the possible values of this
                        // condition
                        var possibleValues = $scope.handlerConditions[name].value;
                        for (var i=0; i<possibleValues.length; i++) {
                            console.log("check " + possibleValues[i].name);
                            if (tickedConditions.indexOf(
                                $scope.handlerConditions[name].value[i].name) >= 0) {
                                $scope.handlerConditions[name].value[i].ticked = true;
                            }
                        }
                    }
                });
            });
    };

    $scope.handlerModuleChanged = function () {
        $scope.getHandlerActions();
        $scope.getHandlerConditions();
    };

    $scope.actionChanged = function () {
        $scope.options = $scope.handlerOptions[$scope.form.action];
    };

    $scope.getAvailableEvents();
    $scope.getHandlerModules();
    if ($scope.eventid) {
        $scope.getEvent();
    }

});
<|endoftext|>


<commit_before>'use strict';

let person = function ($q, NpolarApiResource) {
  'ngInject';

  let Person = NpolarApiResource.resource({ path: '/person', resource: 'Person' });
  let query = { 'fields': 'first_name,last_name,organisation,email', 'variant': 'array', 'limit': 200 };

  return {
    template: require('./person.html'),
    controller($scope) {
      'ngInject';

      $scope.firstName = $scope.field.fields.find(field => field.id === 'first_name');
      $scope.lastName = $scope.field.fields.find(field => field.id === 'last_name');
      $scope.organisation = $scope.field.fields.find(field => field.id === 'organisation');
      $scope.email = $scope.field.fields.find(field => field.id === 'email');

      $scope.querySearch = function (searchText, field) {
        let deferred = $q.defer();
        let fullQuery = Object.assign({}, query, { q: searchText });
        Person.array(fullQuery, response => {
          let fieldFilteredMatches = response.filter(person => {
            return (person[field] || '').toLowerCase().indexOf(searchText.toLowerCase()) === 0;
          });
          deferred.resolve(fieldFilteredMatches);
        }, err => { deferred.reject(); });
        return deferred.promise;
      };

      $scope.onSelect = function(person) {
        $scope.firstName.value = person.first_name;
        $scope.lastName.value = person.last_name;
        $scope.organisation.value = person.organisation;
        $scope.email.value = person.email;
      };

      $scope.otherFields = $scope.field.fields.filter(field => !['first_name', 'last_name', 'email', 'id', 'organisation'].includes(field.id));
    }
  };
};

module.exports = person;
<commit_msg>Show org<commit_after>'use strict';

let person = function ($q, NpolarApiResource) {
  'ngInject';

  // rolesList
  let Person = NpolarApiResource.resource({ path: '/person', resource: 'Person' });
  let query = { 'fields': 'first_name,last_name,organisation,email', 'variant': 'array', 'limit': 200 };

  return {
    template: require('./person.html'),
    controller($scope) {
      'ngInject';

      $scope.firstName = $scope.field.fields.find(field => field.id === 'first_name');
      $scope.lastName = $scope.field.fields.find(field => field.id === 'last_name');
      $scope.organisation = $scope.field.fields.find(field => field.id === 'organisation');
      $scope.email = $scope.field.fields.find(field => field.id === 'email');

      $scope.querySearch = function (searchText, field) {
        let deferred = $q.defer();
        let fullQuery = Object.assign({}, query, { q: searchText });
        Person.array(fullQuery, response => {
          let fieldFilteredMatches = response.filter(person => {
            return (person[field] || '').toLowerCase().indexOf(searchText.toLowerCase()) === 0;
          });
          deferred.resolve(fieldFilteredMatches);
        }, err => { deferred.reject(); });
        return deferred.promise;
      };

      $scope.onSelect = function(person) {
        $scope.firstName.value = person.first_name;
        $scope.lastName.value = person.last_name;
        $scope.organisation.value = person.organisation;
        $scope.email.value = person.email;
      };

      $scope.otherFields = $scope.field.fields.filter(field => !['first_name', 'last_name', 'email', 'id'].includes(field.id));
    }
  };
};

module.exports = person;
<|endoftext|>


<commit_before>import React from 'react';
import LinkButton from "../LinkButton/LinkButton";
import classes from "./LoginButtonSet.module.css"

const LoginButtonSet = props => {

    return (

            <LinkButton inverted>What is sGonks?</LinkButton>
            <LinkButton>Sign in</LinkButton>

    )
}

export default LoginButtonSet;<commit_msg>Add fetch function to login button set<commit_after>import React from "react"
import LinkButton from "../LinkButton/LinkButton"
import classes from "./LoginButtonSet.module.css"

const LoginButtonSet = (props) => {
  const fetchUserData = () => {
    fetch("./authentication")
      .then((response) => (response.json()))
      .then((data) => {
        console.log(data)
      })
  }

  return (

      <LinkButton inverted>What is sGonks?</LinkButton>
      <LinkButton onClick={() => fetchUserData()} to="/page">Sign in</LinkButton>

  )
}

export default LoginButtonSet
<|endoftext|>


<commit_before>'use strict'

var isProd = (process.env.NODE_ENV === 'production')

module.exports = {
  API_ROOT: isProd
    ? 'https://gwi-beers.herokuapp.com/api/'
    : 'http://localhost:8085/api/',
  COOKIE_PREFIX: 'pro_',
  ENABLE_DEBUG_OVERLAY: !isProd
}
<commit_msg>adjusted domain for digitalocean dokku container<commit_after>'use strict'

var isProd = (process.env.NODE_ENV === 'production')

module.exports = {
  API_ROOT: isProd
    ? 'https://beers.app.gwildu.me/api/'
    : 'http://localhost:8085/api/',
  COOKIE_PREFIX: 'pro_',
  ENABLE_DEBUG_OVERLAY: !isProd
}
<|endoftext|>


<commit_before>
/* Module-specific javascript can be placed here */

$(document).ready(function() {
	$('#et_save').unbind('click').click(function() {
		if (!$(this).hasClass('inactive')) {
			disableButtons();

			<?php if (isset($elements)) { foreach ($elements as $element) {
				foreach ($element['fields'] as $field) {
					if ($field['type'] == 'EyeDraw' && @$field['extra_report']) {?>
			if ($('#<?php echo $element['class_name']?>_<?php echo $field['name']?>2').length >0) {
				$('#<?php echo $element['class_name']?>_<?php echo $field['name']?>2').val(ed_drawing_edit_<?php echo $field['eyedraw_class']?>.report());
			}
					<?php }
				}
			} }?>

			return true;
		}
		return false;
	});

	$('#et_cancel').unbind('click').click(function() {
		if (!$(this).hasClass('inactive')) {
			disableButtons();

			if (m = window.location.href.match(/\/update\/[0-9]+/)) {
				window.location.href = window.location.href.replace('/update/','/view/');
			} else {
				window.location.href = baseUrl+'/patient/episodes/'+et_patient_id;
			}
		}
		return false;
	});

	$('#et_deleteevent').unbind('click').click(function() {
		if (!$(this).hasClass('inactive')) {
			disableButtons();
			$('#deleteForm').submit();
		}
		return false;
	});

	$('#et_canceldelete').unbind('click').click(function() {
		if (!$(this).hasClass('inactive')) {
			disableButtons();

			if (m = window.location.href.match(/\/delete\/[0-9]+/)) {
				window.location.href = window.location.href.replace('/delete/','/view/');
			} else {
				window.location.href = baseUrl+'/patient/episodes/'+et_patient_id;
			}
		}
		return false;
	});

	$('select.populate_textarea').unbind('change').change(function() {
		if ($(this).val() != '') {
			var cLass = $(this).parent().parent().parent().attr('class');
			var el = $('#'+cLass+'_'+$(this).attr('id'));
			var currentText = el.text();
			var newText = $(this).children('option:selected').text();

			if (currentText.length == 0) {
				el.text(ucfirst(newText));
			} else {
				el.text(currentText+', '+newText);
			}
		}
	});
});

function ucfirst(str) { str += ''; var f = str.charAt(0).toUpperCase(); return f + str.substr(1); }

function eDparameterListener(_drawing) {
	if (_drawing.selectedDoodle != null) {
		// handle event
	}
}
<commit_msg>fixed dropdown text selection bug<commit_after>
/* Module-specific javascript can be placed here */

$(document).ready(function() {
	$('#et_save').unbind('click').click(function() {
		if (!$(this).hasClass('inactive')) {
			disableButtons();

			<?php if (isset($elements)) { foreach ($elements as $element) {
				foreach ($element['fields'] as $field) {
					if ($field['type'] == 'EyeDraw' && @$field['extra_report']) {?>
			if ($('#<?php echo $element['class_name']?>_<?php echo $field['name']?>2').length >0) {
				$('#<?php echo $element['class_name']?>_<?php echo $field['name']?>2').val(ed_drawing_edit_<?php echo $field['eyedraw_class']?>.report());
			}
					<?php }
				}
			} }?>

			return true;
		}
		return false;
	});

	$('#et_cancel').unbind('click').click(function() {
		if (!$(this).hasClass('inactive')) {
			disableButtons();

			if (m = window.location.href.match(/\/update\/[0-9]+/)) {
				window.location.href = window.location.href.replace('/update/','/view/');
			} else {
				window.location.href = baseUrl+'/patient/episodes/'+et_patient_id;
			}
		}
		return false;
	});

	$('#et_deleteevent').unbind('click').click(function() {
		if (!$(this).hasClass('inactive')) {
			disableButtons();
			$('#deleteForm').submit();
		}
		return false;
	});

	$('#et_canceldelete').unbind('click').click(function() {
		if (!$(this).hasClass('inactive')) {
			disableButtons();

			if (m = window.location.href.match(/\/delete\/[0-9]+/)) {
				window.location.href = window.location.href.replace('/delete/','/view/');
			} else {
				window.location.href = baseUrl+'/patient/episodes/'+et_patient_id;
			}
		}
		return false;
	});

	$('select.populate_textarea').unbind('change').change(function() {
		if ($(this).val() != '') {
			var cLass = $(this).parent().parent().parent().attr('class').match(/Element.*/);
			var el = $('#'+cLass+'_'+$(this).attr('id'));
			var currentText = el.text();
			var newText = $(this).children('option:selected').text();

			if (currentText.length == 0) {
				el.text(ucfirst(newText));
			} else {
				el.text(currentText+', '+newText);
			}
		}
	});
});

function ucfirst(str) { str += ''; var f = str.charAt(0).toUpperCase(); return f + str.substr(1); }

function eDparameterListener(_drawing) {
	if (_drawing.selectedDoodle != null) {
		// handle event
	}
}
<|endoftext|>


<commit_before>/**
	_moon.Dialog_ is a [moon.Popup](#moon.Popup) with a title, a subtitle, a
	message, and an area for additional controls.
*/
enyo.kind({
	name: "moon.Dialog",
	kind: moon.Popup,
	//* @protected
	classes: "moon-dialog",
	//* @public
	published: {
		//* The title string for the dialog
		title: "",
		//* The subtitle string for the dialog
		subTitle: "",
		//* The message for the dialog
		message: "",
		//* When true, the title text will be converted to locale-safe uppercasing
		titleUpperCase: true
	},
	//* @protected
	mixins: ["moon.MarqueeSupport"],
	marqueeOnSpotlight: false,
	marqueeOnHover: true,
	marqueeOnRender: true,
	marqueeOnRenderDelay: 5000,
	tools: [
		{
			layoutKind: "FittableColumnsLayout",
			components: [
				{fit: true, components: [
					{name: "title", kind: "moon.MarqueeText", classes: "moon-header-font moon-popup-header-text moon-dialog-title"},
					{name: "subTitle", classes: "moon-dialog-sub-title"}
				]},
				{name: "client", classes: "moon-dialog-client"}
			]
		},
		{kind: "moon.Divider", classes: "moon-dialog-divider"},
		{name: "message", kind:"moon.BodyText", classes: "moon-dialog-content"},
		{name: "spotlightDummy", spotlight:false}
	],
	create: function() {
		this.inherited(arguments);
		this.titleChanged();
		this.subTitleChanged();
		this.messageChanged();
	},
	//* @protected
	titleChanged: function() {
		var title = this.getTitle();
		this.$.title.setContent( this.getTitleUpperCase() ? enyo.toUpperCase(title) : title );
	},
	titleUpperCaseChanged: function() {
		this.titleChanged();
	},
	subTitleChanged: function() {
		this.$.subTitle.setContent(this.subTitle);
	},
	messageChanged: function() {
		this.$.message.setContent(this.message);
	}
});<commit_msg>BHV-685: Remove unnecessary comment<commit_after>/**
	_moon.Dialog_ is a [moon.Popup](#moon.Popup) with a title, a subtitle, a
	message, and an area for additional controls.
*/
enyo.kind({
	name: "moon.Dialog",
	kind: moon.Popup,
	//* @protected
	classes: "moon-dialog",
	//* @public
	published: {
		//* The title string for the dialog
		title: "",
		//* The subtitle string for the dialog
		subTitle: "",
		//* The message for the dialog
		message: "",
		//* When true, the title text will be converted to locale-safe uppercasing
		titleUpperCase: true
	},
	//* @protected
	mixins: ["moon.MarqueeSupport"],
	marqueeOnSpotlight: false,
	marqueeOnHover: true,
	marqueeOnRender: true,
	marqueeOnRenderDelay: 5000,
	tools: [
		{
			layoutKind: "FittableColumnsLayout",
			components: [
				{fit: true, components: [
					{name: "title", kind: "moon.MarqueeText", classes: "moon-header-font moon-popup-header-text moon-dialog-title"},
					{name: "subTitle", classes: "moon-dialog-sub-title"}
				]},
				{name: "client", classes: "moon-dialog-client"}
			]
		},
		{kind: "moon.Divider", classes: "moon-dialog-divider"},
		{name: "message", kind:"moon.BodyText", classes: "moon-dialog-content"},
		{name: "spotlightDummy", spotlight:false}
	],
	create: function() {
		this.inherited(arguments);
		this.titleChanged();
		this.subTitleChanged();
		this.messageChanged();
	},
	titleChanged: function() {
		var title = this.getTitle();
		this.$.title.setContent( this.getTitleUpperCase() ? enyo.toUpperCase(title) : title );
	},
	titleUpperCaseChanged: function() {
		this.titleChanged();
	},
	subTitleChanged: function() {
		this.$.subTitle.setContent(this.subTitle);
	},
	messageChanged: function() {
		this.$.message.setContent(this.message);
	}
});<|endoftext|>