<commit_before>/*jslint browser: true */
/*global  $, console */
var semtag = semtag || {};

semtag.ancestors = function (el, callback, nodes) {
	'use strict';
	nodes = nodes || [];
	if (el.parentNode) {
		nodes.push(el);
		semtag.ancestors(el.parentNode, callback, nodes);
	} else {
		if (typeof callback === 'function') {
			callback(null, nodes);
		}
	}
	return nodes;
};

semtag.hasAncestorWithClass = function (el, className) {
	'use strict';
	var hasAncestor;
	semtag.ancestors(el.parentNode, function (err, ancestors) {
		var i,
			classRegExp = new RegExp('(^|\b)' + className + '(\b|$)');
		for (i = 0; i < ancestors.length; i += 1) {
			if (ancestors[i].className.match(classRegExp)) {
				hasAncestor =  ancestors[i];
			}
		}
	});
	return hasAncestor;
};

semtag.wantedSense = function (sense) {
	'use strict';
	return sense.source !== "DBPedia";
};

semtag.extendTag = function (el, options) {
	'use strict';
	var	i,
		attr,
		data;
	el.id = options.id;
	if (options.classes) {
		for (i = 0; i < options.classes.length || 0; i += 1) {
			el.classList.add(options.classes[i]);
		}
	}
	for (attr in options.attr) {
		if (options.attr.hasOwnProperty(attr)) {
			el.setAttribute(attr, options.attr[attr]);
		}
	}
	for (data in options.data) {
		if (options.data.hasOwnProperty(data)) {
			el.dataset[data] = options.data[data];
		}
	}
	return el;
};

semtag.buildTag = function (type, options) {
	'use strict';
	var el;
	if (typeof type === 'object') {
		options = type;
		type = 'div';
	}
	options = options || {};
	el = semtag.extendTag(document.createElement(type), options);

	return el;
};

semtag.getId = function (content) {
	'use strict';
	var id,
		baseString,
		counter = 1;
	baseString = 'semtag-' + content.replace(/ /g, '_') + '-';
	id =  baseString + counter;
	while (document.getElementById(id)) {
		counter += 1;
		id =  baseString + counter;
	}
	return id;
};

semtag.removeSense = function (sense) {
	'use strict';
	var taggedNode,
		taggedNodeParent,
		content;
	taggedNode = sense.parentNode;
	taggedNodeParent = taggedNode.parentNode;
	content = document.createTextNode(taggedNode.textContent);
	taggedNodeParent.replaceChild(content, taggedNode);
};

semtag.decideEndpoint = function (source) {
	"use strict";
	if (source === 'schema_org' || source === 'WordNet') {
		return '/wn/best-fit/';
	}
	if (source === 'DBPedia') {
		return 'dbp/best-fit/';
	}
};

semtag.prefixes = {
	'sumo': 'http://www.ontologyportal.org/SUMO.owl# ',
	'schema': 'http://schema.org/'
};

semtag.ensurePrefixes = function () {
	'use strict';
	var prefixes = document.body.getAttribute('prefix') || '',
		prefix;
	for (prefix in semtag.prefixes) {
		if (semtag.prefixes.hasOwnProperty(prefix)) {
			if (prefixes.indexOf(prefix + ':') === -1) {
				prefixes += ' ' + prefix + ': ' + semtag.prefixes[prefix];
			}
		}
	}
	document.body.setAttribute('prefix', prefixes);
};

semtag.addSenses = function (url, callback) {
	'use strict';
	$.getJSON(url, function (json) {
		var senses = [],
			sense = '',
			i,
			sensesString = '';
		semtag.ensurePrefixes();
		if (json.sumo) {
			for (i = 0; i < json.sumo.length; i += 1) {
				if (senses.indexOf(json.sumo[i]) === -1) {
					senses.push(json.sumo[i]);
					sense += " sumo:" + json.sumo[i];
				}
			}
		}
		if (json.schema_dot_org) {
			for (i = 0; i < json.sumo.length; i += 1) {
				if (senses.indexOf(json.schema_dot_org[i]) === -1) {
					senses.push(json.schema_dot_org[i]);
					sense += " schema:" + json.schema_dot_org[i];
				}
			}
		}
		if (json.sumo || json.schema_dot_org) {
			sensesString += senses.join(', ');
		}
		callback(sensesString, sense);
	});
};

semtag.wordSenseClicked = function (wordSense, options) {
	'use strict';
	options = options || {};
	var toTag	= document.getElementById('toTag'),
		content = options.text || toTag.textContent,
		id		= semtag.getId(content),
		about	= options.about || document.URL + '#' + id,
		sense	= options.wordSense || wordSense.getAttribute('id'),
		endpoint = semtag.decideEndpoint(wordSense.dataset.source),
		wnId = sense.substring(sense.lastIndexOf('/') + 1),
		removeIcon;

	semtag.addSenses(endpoint + wnId, function (senses, sense) {
		toTag = semtag.extendTag(toTag,
			{
				'id': id,
				'attr': {
					'title': content + ", meaning: " + senses,
					'typeof': sense,
					'about': about
				},
				classes: ['tagged']
			});
	});
	removeIcon = semtag.buildTag('img', {
		'id': id,
		'attr': {'src': '/images/remove.png',
				'alt': 'X'},
		'classes': ['removeIcon']
	});
	toTag.appendChild(removeIcon);
	$('.removeIcon').unbind('click');
	$('.removeIcon').click(function () {
		semtag.removeSense(this);
	});
	$('#' + id).tooltip();
};

semtag.buildWordSenseList = function (sensList) {
	'use strict';
	var sensCount = sensList.length,
		senses = [],
		list = document.getElementById('senses'),
		i,
		el;
	for (i = 0; i < sensCount; i += 1) {
		if (semtag.wantedSense(sensList[i])) {
			el = semtag.buildTag('li', {
				'id': sensList[i].senseid,
				'data': {
					'source': sensList[i].source
				},
				'classes': ['word-sense']
			});
			el.innerText = sensList[i].explanation;
			senses.push(el.outerHTML);
		}
	}
	list.innerHTML = senses.join(' ');
	return list;
};

semtag.resetDYM = function () {
	'use strict';
	semtag.senses.innerHTML = "";
};

semtag.displayHeader = function (word) {
	'use strict';
	semtag.word.innerText =  word;
	semtag.header.style.display = '';
	semtag.input.style.display = '';
};

semtag.buildDidYouMeanTable = function (json, tableId) {
	'use strict';
	var didYouMean,
		word;
	didYouMean = document.getElementById(tableId);
	word = document.getElementById('toTag').textContent;
	semtag.displayHeader(json.word);
	didYouMean.appendChild(semtag.buildWordSenseList(json.senses));
	$('.word-sense').click(function () {
		semtag.wordSenseClicked(this);
		semtag.header.style.display = 'none';
		semtag.input.style.display = 'none';
		semtag.senses.innerHTML = '';
	});
	$('#sidebar li:nth-child(2) a:first').tab('show'); // Selector for "Meanings pane"
};
semtag.sw = function (term) {
	'use strict';
	term = term.replace(/ /g, '_'); // Replaces inner white space with underscores
	$.getJSON('/lex',
		{
			word: term
		}, function (data) {
			semtag.buildDidYouMeanTable(data, 'dym', term);
		});
};
semtag.surround = function (range, className) {
	'use strict';
	var fragment = range.extractContents(),
		tag = document.createElement("span");
	tag.setAttribute("id", className);
	tag.appendChild(fragment);
	range.insertNode(tag);
};
semtag.resetToTag = function (id, callback) {
	'use strict';
	var toRemove,
		parent,
		contents;
	toRemove = document.getElementById(id);
	if (toRemove) {
		contents = toRemove.childNodes[0];
		parent = toRemove.parentNode;
		if (contents) {
			parent.replaceChild(contents, toRemove);
		} else {
			parent.removeChild(toRemove);
		}
	}
	callback();
};
$('#content').mouseup(function () {
	'use strict';
	var range = window.getSelection().getRangeAt(0),
		text = range.toString().replace(/^\s*|\s*$/g, ''); // Remove leading and trailing whitespace.
	if (!(semtag.hasAncestorWithClass(range.startContainer, 'tagged')
			|| semtag.hasAncestorWithClass(range.endContainer, 'tagged'))) {
		if (range && text.length > 0) {
			if (text.length > 50) {
				$('header .container').append(
					'
'
						+ '<button type="button" class="close" data-dismiss="alert">×</button>'
						+ 'Warning! Selections should be less than 50 letters.'
						+ '
'
				);
			} else {
				semtag.resetToTag('toTag', function () {
					semtag.surround(range, 'toTag');
					semtag.sw(text);
					document.getSelection().addRange(range);
				});
			}
		} else if (range.startContainer === range.endContainer) {
			if (
				(range.commonAncestorContainer.nodeName === 'A'
					&&
					range.commonAncestorContainer.childNodes[0].nodeName === 'IMG'
				)
					||
					range.commonAncestorContainer.nodeName === 'IMG'
			) {
				semtag.resetToTag('toTag', function () {
					semtag.surround(range, 'toTag');
					semtag.sw("Image");
					document.getSelection().addRange(range);
				});
			}
		}
	}
});<commit_msg>Added ability to add properties to types<commit_after>/*jslint browser: true */
/*global  $, console */
var semtag = semtag || {};

semtag.ancestors = function (el, callback, nodes) {
	'use strict';
	nodes = nodes || [];
	if (el.parentNode) {
		nodes.push(el);
		semtag.ancestors(el.parentNode, callback, nodes);
	} else {
		if (typeof callback === 'function') {
			callback(null, nodes);
		}
	}
	return nodes;
};

semtag.addProperties = function (el) {
	'use strict';
	var properties = el.find('.property'),
		count = properties.length,
		i,
		j,
		parent = el.parent(),
		elementProperties;
	for (i = 0; i < count; i += 1) {
		if (properties[i].value) {
			elementProperties = parent.find('.tagged .property[property="' + properties[i].getAttribute('name')  + '"]');
			for (j = 0; j < elementProperties.length; j += 1) {
				elementProperties[j].setAttribute('content', properties[i].value);
			}
		}
	}
	$('.tagged').popover('hide');
};
/**
* Is called by a tagged term.
* If property is already set, the function should keep this value as default
* @return {String} inputList, HTML list of possible properties the term can have, and inputs for setting the value.
*/
semtag.buildPropertyInputList = function () {
	'use strict';
	var inputList = '
',
		self = this,
		i,
		el,
		value,
		count = self.childNodes.length;
	for (i = 0; i < count; i += 1) {
		el = self.childNodes[i];
		if (el.className && el.className.match(/(^|\b)property(\b|$)/)) {
			if (el.dataset.range === 'Text' || el.dataset.range === 'URL') {
				value = el.getAttribute('content') || '';
				inputList += '
';
				inputList += '' + el.getAttribute('property') + ': ';
				inputList += '<input class="property right" name="'
					+ el.getAttribute('property') + '" type="text" class="right" value="'
					+ value + '" placeholder="' + el.dataset.range + '"/>';
				inputList += '
';
			}
		}
	}
	inputList += '<input class="right submit" type="submit" value="Go" />
';
	return inputList;
};

semtag.typeProperties = function (types, callback) {
	'use strict';
	var properties = [],
		type,
		i,
		push = function (data) {
			var type;
			for (type in data) {
				if (data.hasOwnProperty(type)) {
					if (properties.indexOf(data[type]) === -1) {
						if (data[type].indexOf('Text') !== -1 || data[type].indexOf('URL') !== -1) {
							properties.push({'property': 'schema:' + type, 'range': data[type]});
						}
					}
				}
			}
			if (i === types.length) {
				callback(properties);
			}
		};
	types = types.split(' ');
	for (i = 1; i < types.length; i += 1) {
		if (types[i].match(/^schema:/)) {
			type = types[i].substring(7);
			$.getJSON('/properties/' + type, push);
		}
	}
};

semtag.hasAncestorWithClass = function (el, className) {
	'use strict';
	var hasAncestor;
	semtag.ancestors(el.parentNode, function (err, ancestors) {
		var i,
			classRegExp = new RegExp('(^|\b)' + className + '(\b|$)');
		for (i = 0; i < ancestors.length; i += 1) {
			if (ancestors[i].className.match(classRegExp)) {
				hasAncestor =  ancestors[i];
			}
		}
	});
	return hasAncestor;
};

semtag.wantedSense = function (sense) {
	'use strict';
	return sense.source !== "DBPedia";
};

semtag.extendTag = function (el, options) {
	'use strict';
	var	i,
		attr,
		data;
	if (options.id) {
		el.id = options.id;
	}
	if (options.classes) {
		if (typeof options.classes === 'string') {
			options.classes = [options.classes];
		}
		for (i = 0; i < options.classes.length || 0; i += 1) {
			el.classList.add(options.classes[i]);
		}
	}
	for (attr in options.attr) {
		if (options.attr.hasOwnProperty(attr)) {
			el.setAttribute(attr, options.attr[attr]);
		}
	}
	for (data in options.data) {
		if (options.data.hasOwnProperty(data)) {
			el.dataset[data] = options.data[data];
		}
	}
	return el;
};

semtag.buildTag = function (type, options) {
	'use strict';
	var el;
	if (typeof type === 'object') {
		options = type;
		type = 'div';
	}
	options = options || {};
	el = semtag.extendTag(document.createElement(type), options);

	return el;
};

semtag.getId = function (content) {
	'use strict';
	var id,
		baseString,
		counter = 1;
	baseString = 'semtag-' + content.replace(/ /g, '_') + '-';
	id =  baseString + counter;
	while (document.getElementById(id)) {
		counter += 1;
		id =  baseString + counter;
	}
	return id;
};

semtag.removeSense = function (sense) {
	'use strict';
	var taggedNode,
		taggedNodeParent,
		content;
	taggedNode = sense.parentNode;
	taggedNodeParent = taggedNode.parentNode;
	content = document.createTextNode(taggedNode.textContent);
	taggedNodeParent.replaceChild(content, taggedNode);
};

semtag.decideEndpoint = function (source) {
	"use strict";
	if (source === 'schema_org' || source === 'WordNet') {
		return '/wn/best-fit/';
	}
	if (source === 'DBPedia') {
		return 'dbp/best-fit/';
	}
};

semtag.prefixes = {
	'sumo': 'http://www.ontologyportal.org/SUMO.owl# ',
	'schema': 'http://schema.org/'
};

semtag.ensurePrefixes = function () {
	'use strict';
	var prefixes = document.body.getAttribute('prefix') || '',
		prefix;
	for (prefix in semtag.prefixes) {
		if (semtag.prefixes.hasOwnProperty(prefix)) {
			if (prefixes.indexOf(prefix + ':') === -1) {
				prefixes += ' ' + prefix + ': ' + semtag.prefixes[prefix];
			}
		}
	}
	document.body.setAttribute('prefix', prefixes);
};

semtag.addSenses = function (url, callback) {
	'use strict';
	$.getJSON(url, function (json) {
		var senses = [],
			sense = '',
			i,
			sensesString = '';
		semtag.ensurePrefixes();
		if (json.sumo) {
			for (i = 0; i < json.sumo.length; i += 1) {
				if (senses.indexOf(json.sumo[i]) === -1) {
					senses.push(json.sumo[i]);
					sense += " sumo:" + json.sumo[i];
				}
			}
		}
		if (json.schema_dot_org) {
			for (i = 0; i < json.sumo.length; i += 1) {
				if (senses.indexOf(json.schema_dot_org[i]) === -1) {
					senses.push(json.schema_dot_org[i]);
					sense += " schema:" + json.schema_dot_org[i];
				}
			}
		}
		if (json.sumo || json.schema_dot_org) {
			sensesString += senses.join(', ');
		}
		callback(sensesString, sense);
	});
};

semtag.wordSenseClicked = function (wordSense, options) {
	'use strict';
	options = options || {};
	var toTag	= document.getElementById('toTag'),
		content = options.text || toTag.textContent,
		id		= semtag.getId(content),
		about	= options.about || document.URL + '#' + id,
		sense	= options.wordSense || wordSense.getAttribute('id'),
		endpoint = semtag.decideEndpoint(wordSense.dataset.source),
		wnId = sense.substring(sense.lastIndexOf('/') + 1),
		removeIcon,
		jQueryId = '#' + id;

	semtag.addSenses(endpoint + wnId, function (senses, sense) {
		toTag = semtag.extendTag(toTag,
			{
				'id': id,
				'attr': {
					'typeof': sense,
					'about': about
				},
				classes: ['tagged']
			});
		$(jQueryId).tooltip({title: content + ", meaning: " + senses}).popover({placement: 'bottom', html: true, title: '
Properties:
', content: semtag.buildPropertyInputList});
		semtag.typeProperties(sense, function (properties) {
			var i,
				property;
			for (i = 0; i < properties.length; i += 1) {
				property = semtag.buildTag('span', {'classes': 'property', 'attr' : { 'property': properties[i].property}, 'data' : {'range': properties[i].range.join(" ")}});
				toTag.appendChild(property);
			}
		});
	});
	removeIcon = semtag.buildTag('img', {
		'id': id,
		'attr': {'src': '/images/remove.png',
				'alt': 'X'},
		'classes': ['removeIcon']
	});
	toTag.appendChild(removeIcon);
	$('.removeIcon').unbind('click');
	$('.removeIcon').click(function () {
		semtag.removeSense(this);
	});
};

semtag.buildWordSenseList = function (sensList) {
	'use strict';
	var sensCount = sensList.length,
		senses = [],
		list = document.getElementById('senses'),
		i,
		el;
	for (i = 0; i < sensCount; i += 1) {
		if (semtag.wantedSense(sensList[i])) {
			el = semtag.buildTag('li', {
				'id': sensList[i].senseid,
				'data': {
					'source': sensList[i].source
				},
				'classes': ['word-sense']
			});
			el.innerText = sensList[i].explanation;
			senses.push(el.outerHTML);
		}
	}
	list.innerHTML = senses.join(' ');
	return list;
};

semtag.resetDYM = function () {
	'use strict';
	semtag.senses.innerHTML = "";
};

semtag.displayHeader = function (word) {
	'use strict';
	semtag.word.innerText =  word;
	semtag.header.style.display = '';
	semtag.input.style.display = '';
};

semtag.buildDidYouMeanTable = function (json, tableId) {
	'use strict';
	var didYouMean,
		word;
	didYouMean = document.getElementById(tableId);
	word = document.getElementById('toTag').textContent;
	semtag.displayHeader(json.word);
	didYouMean.appendChild(semtag.buildWordSenseList(json.senses));
	$('.word-sense').click(function () {
		semtag.wordSenseClicked(this);
		semtag.header.style.display = 'none';
		semtag.input.style.display = 'none';
		semtag.senses.innerHTML = '';
	});
	$('#sidebar li:nth-child(2) a:first').tab('show'); // Selector for "Meanings pane"
};
semtag.sw = function (term) {
	'use strict';
	term = term.replace(/ /g, '_'); // Replaces inner white space with underscores
	$.getJSON('/lex',
		{
			word: term
		}, function (data) {
			semtag.buildDidYouMeanTable(data, 'dym', term);
		});
};
semtag.surround = function (range, className) {
	'use strict';
	var fragment = range.extractContents(),
		tag = document.createElement("span");
	tag.setAttribute("id", className);
	tag.appendChild(fragment);
	range.insertNode(tag);
};
semtag.resetToTag = function (id, callback) {
	'use strict';
	var toRemove,
		parent,
		contents;
	toRemove = document.getElementById(id);
	if (toRemove) {
		contents = toRemove.childNodes[0];
		parent = toRemove.parentNode;
		if (contents) {
			parent.replaceChild(contents, toRemove);
		} else {
			parent.removeChild(toRemove);
		}
	}
	callback();
};
$('#content').mouseup(function () {
	'use strict';
	var range,
		text;
	if (window.getSelection().rangeCount > 0) {
		range = window.getSelection().getRangeAt(0);
		text = range.toString().replace(/^\s*|\s*$/g, ''); // Remove leading and trailing whitespace.
		if (!(semtag.hasAncestorWithClass(range.startContainer, 'tagged')
				|| semtag.hasAncestorWithClass(range.endContainer, 'tagged'))) {
			if (range && text.length > 0) {
				if (text.length > 50) {
					$('header .container').append(
						'
'
							+ '<button type="button" class="close" data-dismiss="alert">×</button>'
							+ 'Warning! Selections should be less than 50 letters.'
							+ '
'
					);
				} else {
					semtag.resetToTag('toTag', function () {
						semtag.surround(range, 'toTag');
						semtag.sw(text);
						document.getSelection().addRange(range);
					});
				}
			} else if (range.startContainer === range.endContainer) {
				if (
					(range.commonAncestorContainer.nodeName === 'A'
						&&
						range.commonAncestorContainer.childNodes[0].nodeName === 'IMG'
					)
						||
						range.commonAncestorContainer.nodeName === 'IMG'
				) {
					semtag.resetToTag('toTag', function () {
						semtag.surround(range, 'toTag');
						semtag.sw("Image");
						document.getSelection().addRange(range);
					});
				}
			}
		}
	}
});<|endoftext|>


<commit_before>!function(){var e=Handlebars.template,n=Handlebars.templates=Handlebars.templates||{};n.about=e(function(e,n,t,i,a){return this.compilerInfo=[4,">= 1.0.0"],t=this.merge(t,e.helpers),a=a||{},'
\n
\n\n
\n
Maven
\n
\n        ma·ven noun \\ˈmā-vən\\\n
\n
one who is experienced or knowledgeable; an expert.
\n
\n\n
\n      Node Mavens is a place to show your appreciation for the experts of the\n      node community. This is not a contest, rather a way to show some\n      appreciation for people that have helped you by sharing their expertise.\n
\n\n
\n\n
\n      Check out the\n      source.\n
\n
\n      Built with all the love in the world by\n      @fiveisprime in\n      Cincinnati, Ohio.\n
\n
\n
\n'}),n.index=e(function(e,n,t,i,a){return this.compilerInfo=[4,">= 1.0.0"],t=this.merge(t,e.helpers),a=a||{},'
\n
\n    \n    \n
Node Mavens
\n
Who inspires you?
\n
\n        Let the world know about the node experts who inspire you and drive you\n        to become a better developer person.\n
\n    \n    \n
\n      About\n
\n
\n      Spread Love\n
\n    \n
\n
\n

\n

\n

\n'}),n.love=e(function(e,n,t,i,a){return this.compilerInfo=[4,">= 1.0.0"],t=this.merge(t,e.helpers),a=a||{},'<form class="cenetered">\n
\n    Let\'s hear it! Who made your day today?\n
\n

\n  <input type="text" name="username" value="" placeholder="GitHub Username">\n  <input type="submit" value="Send" class="btn accent">\n</form>\n'})}();<commit_msg>Compiled assets.<commit_after>!function(){var e=Handlebars.template,n=Handlebars.templates=Handlebars.templates||{};n.about=e(function(e,n,t,a,i){return this.compilerInfo=[4,">= 1.0.0"],t=this.merge(t,e.helpers),i=i||{},'
\n
\n\n
\n
Maven
\n
\n        ma·ven noun \\ˈmā-vən\\\n
\n
one who is experienced or knowledgeable; an expert.
\n
\n\n
\n      Node Mavens is a place to show your appreciation for the experts of the\n      node community. This is not a contest, rather a way to show some\n      appreciation for people that have helped you by sharing their expertise.\n
\n\n
\n\n
\n      Check out the\n      source.\n
\n
\n      Built with all the love in the world by\n      @fiveisprime in\n      Cincinnati, OH.\n
\n
\n
\n'}),n.index=e(function(e,n,t,a,i){return this.compilerInfo=[4,">= 1.0.0"],t=this.merge(t,e.helpers),i=i||{},'
\n
\n    \n    \n
Node Mavens
\n
Who inspires you?
\n
\n        Let the world know about the node experts who inspire you and drive you\n        to become a better developer person.\n
\n    \n    \n
\n      About\n
\n
\n      Spread Love\n
\n    \n
\n
\n

\n

\n

\n'}),n.love=e(function(e,n,t,a,i){return this.compilerInfo=[4,">= 1.0.0"],t=this.merge(t,e.helpers),i=i||{},'<form class="cenetered">\n
\n    Let\'s hear it! Who made your day today?\n
\n

\n  <input type="text" name="username" value="" placeholder="GitHub Username">\n  <input type="submit" value="Send" class="btn accent">\n</form>\n'})}();<|endoftext|>


<commit_before>function update_menu_text(source_id,fadein) {
    var sections = $('section_menu_items');
    var source = $(source_id);
    if (fadein) {
        sections.hide();
    }
    sections.update(source.innerHTML);
    if (fadein) {
        Effect.Appear('section_menu_items',{duration:0.3});
    }
}

function select_menu_item(section_id) {
    update_menu_text(section_id,false);
}

// handle the width of the search box according to the width of the screen
Event.observe(window,"resize", function() {
    set_searchbox_width();
});
document.observe("dom:loaded",function() {
    set_searchbox_width();
});

function set_searchbox_width() {
    if (document.viewport.getWidth()<=1180) {
        $(search_query).style.width="19em";
    }
    else {
        $(search_query).style.width="30em";
    }
    $(search_query).show();
}<commit_msg>fixed silly javascript error for IE (Chrome is too forgiving)<commit_after>function update_menu_text(source_id,fadein) {
    var sections = $('section_menu_items');
    var source = $(source_id);
    if (fadein) {
        sections.hide();
    }
    sections.update(source.innerHTML);
    if (fadein) {
        Effect.Appear('section_menu_items',{duration:0.3});
    }
}

function select_menu_item(section_id) {
    update_menu_text(section_id,false);
}

// handle the width of the search box according to the width of the screen
Event.observe(window,"resize", function() {
    set_searchbox_width();
});
document.observe("dom:loaded",function() {
    set_searchbox_width();
});

function set_searchbox_width() {
    if (document.viewport.getWidth()<=1180) {
        $("search_query").style.width="19em";
    }
    else {
        $("search_query").style.width="30em";
    }
    $("search_query").show();
}<|endoftext|>


<commit_before>var artHeight=0.01;
var art_values=d3.values(dat.articles)
art_values.sort(function(a, b) {
	al=a.titre.split(" ")
	bl=b.titre.split(" ")
	if (parseInt(al[0]) != parseInt(bl[0])) return parseInt(al[0]) - parseInt(bl[0])
	else if(al.length>0) return 1
    else return al[1] - b[1];
});

var stages=computeStages()
var columns=stages.length
var sections=computeSections()
var maxy=0;
console.log("stages",stages)
console.log("sections", sections)
setCoordinates();

var margin = {
	top : 10,
	right : 10,
	bottom : 20,
	left : 0
}, width = $("#viz").width(), height = 800 - margin.top - margin.bottom;

var svg = d3.select("#viz").append("svg").attr("width", "100%" ).attr("height", maxy+200).append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");

var layer = svg.selectAll(".layer").data(art_values).enter().append("g").attr("class", function(d,i) {return "layer"+" "+"n_"+i})
.attr("transform", function(d,i) {
	return "translate(0,"+parseInt(findSection(d.section))*10+")"
	});

//Define lines layer
var lines = layer.append("g").selectAll("line").data(function(d) {
	return d.steps;
}).enter();

//Define rects layer
var rect = layer.selectAll("rect").data(function(d) {
	return d.steps;
}).enter();

//ADD THE RECTANGLES
var myrects = rect.append("rect")
	.filter(function(d) {
		if (d.length>0) return true;
				else return false;
	})
	.style("fill","#fff")
	.style("stroke", "#ccc")
	.style("stroke-width",1)
	.style("fill", function(d) {
		if(d.diff=="none") return '#fff';
		else if(d.diff=="add") return '#4cefb6';
		else if(d.diff=="rem") return '#f45a5a';
		else if(d.diff=="both") return '#eee';
	})
	.attr("y", function(d) {
		return d.y;
	})
	.attr("x", function(d) {
		//console.log(layer.data())
		return (findStage(d.id_step))*width/columns+10;
	})
	.attr("height", function(d) {

		return (d.length*artHeight);
	})
	.attr("width", width/columns-20)
	.attr("opacity", 1.0)
	.on("click", function (d) {
		console.log(d)

		//STYLE OF CLICKED ELEMENT AND ROW
		//Reset Colors
		myrects.style("fill", function(d) {
		if(d.diff=="none") return '#fff';
		else if(d.diff=="add") return '#4cefb6';
		else if(d.diff=="rem") return '#f45a5a';
		else if(d.diff=="both") return '#eee';
		});

		//Color the elements in same group
		datum=d3.select(this.parentNode)
		d3.selectAll(datum[0][0].childNodes)
		.style("fill","#DAD1CB");

		d3.select(this).style("fill","#716259");

		//add text
		$("#law-title").text(datum.datum().titre);
		$(".text p").text(d.text)

		});

//ADD THE LINES
		lines
		.append("line")
		.filter(function(d,i) {
				datum=d3.select(this.parentNode).datum()

				if (d.length>0 && !d.last && datum.steps[i+1].length>0) return true;
				else return false;
		})
		.attr("x1", function(d){

			return (1+findStage(d.id_step))*width/columns-10
		})
		.attr("y1", function(d){
			return d.y+(d.length*artHeight)/2
		})
		.attr("x2", function(d,i){

			datum=d3.select(this.parentNode).datum()
			if (i+1<datum.steps.length) return (1+findStage(d.id_step))*width/columns+10
			else return null
		})
		.attr("y2", function(d,i){
			datum=d3.select(this.parentNode).datum()
			if (i+1<datum.steps.length) return datum.steps[i+1].y+(datum.steps[i+1].length*artHeight)/2
			else return null
		})
		.style("stroke", "#f2f2f2")
		.style("stroke-width",1);

addLabels();

//SETS COORDINATES FOR THE RECTANGLES
function setCoordinates() {

section="";

$.each(d3.values(art_values), function( index, value ) {

	changed = false
	if (value.section!=section) {
		section=value.section;
		changed=true;
	}

  $.each(value.steps, function( st_ind, step ) {
  	if(index==0) {
  		art_values[index].steps[st_ind]['y'] = 0;
  	}
  	else {
  		lasty=findLast(index-1,art_values[index].steps[st_ind]['id_step'])
  		if (lasty) {
  			art_values[index].steps[st_ind]['y'] = lasty.y + lasty.length*artHeight
  			if(art_values[index].steps[st_ind]['y']+art_values[index].steps[st_ind]['length']*artHeight>maxy) maxy = art_values[index].steps[st_ind]['y']+art_values[index].steps[st_ind]['length']*artHeight
  		}
  		else {
  			art_values[index].steps[st_ind]['y']=0
  		}
  	}
  	if(st_ind+1==value.steps.length) step.last=true
  	if(findStage(step.id_step)==0 && st_ind==0 && changed) {
  		value.first=true
  	}
  })
});
}

//FIND THE ABOVE RECTANGLE - RECURSIVE
function findLast(i1,i2) {

	if(i1<0) {
		return null;
	}
	ret=null;
	$.each(art_values[i1].steps, function( st_ind, step ) {
	if(step.id_step==i2) {
		ret=step;
		return false;
		}
	});
	if(ret) return ret
	else return findLast(i1-1,i2)
}

//Adds the labels
function addLabels() {
	layer.each(function(d, i) {
		if(d.first) {
			curry=d.steps[0].y
			$(".labels").append("

Section "+d.section +"

")
		}
	})
}

//Computes the stages involved in the law creation
function computeStages() {

	stag=[]

	art_values.forEach(function(e, i) {
		var st=d3.nest()
		.key(function(d) { return d.id_step; })
		//.entries(e.steps)
		.map(e.steps, d3.map);
		//console.log(d3.keys(st))
		d3.keys(st).forEach (function(f, i) {
			if(stag.indexOf(f)<0) stag.push(f)
		})
	})
	return stag
}

//finds a stage in the stages array
function findStage(s) {

	for(st in stages) {

		if (encodeURI(s)==encodeURI(stages[st]).substring(3)) {
			return parseInt(st)
		}
	}
	return -1
}

//computes the sections of the current law
function computeSections() {

		var se=d3.nest()
		.key(function(d) { return d.section; })
		//.entries(e.steps)
		.map(art_values,d3.map);
		return se.keys()
}

//finds a section in the sections array
function findSection(s) {
	res= sections.indexOf(s);
	return res
}
<commit_msg>Add possibility to zoom on articles boxes for test purpose.<commit_after>var artHeight=0.01;
var art_values=d3.values(dat.articles)
art_values.sort(function(a, b) {
	al=a.titre.split(" ")
	bl=b.titre.split(" ")
	if (parseInt(al[0]) != parseInt(bl[0])) return parseInt(al[0]) - parseInt(bl[0])
	else if(al.length>0) return 1
    else return al[1] - b[1];
});

var stages=computeStages()
var columns=stages.length
var sections=computeSections()
var maxy=0;
console.log("stages",stages)
console.log("sections", sections)
setCoordinates();

function zoom() {
  svg.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
}

var margin = {
	top : 10,
	right : 10,
	bottom : 20,
	left : 0
}, width = $("#viz").width(), height = 800 - margin.top - margin.bottom;

var svg = d3.select("#viz").append("svg").attr("width", "100%" ).attr("height", maxy+200).append("g").call(d3.behavior.zoom().scaleExtent([1, 8]).on("zoom", zoom)).attr("transform", "translate(" + margin.left + "," + margin.top + ")");

var layer = svg.selectAll(".layer").data(art_values).enter().append("g").attr("class", function(d,i) {return "layer"+" "+"n_"+i})
.attr("transform", function(d,i) {
	return "translate(0,"+parseInt(findSection(d.section))*10+")"
	});

//Define lines layer
var lines = layer.append("g").selectAll("line").data(function(d) {
	return d.steps;
}).enter();

//Define rects layer
var rect = layer.selectAll("rect").data(function(d) {
	return d.steps;
}).enter();

//ADD THE RECTANGLES
var myrects = rect.append("rect")
	.filter(function(d) {
		if (d.length>0) return true;
				else return false;
	})
	.style("fill","#fff")
	.style("stroke", "#ccc")
	.style("stroke-width",1)
	.style("fill", function(d) {
		if(d.diff=="none") return '#fff';
		else if(d.diff=="add") return '#4cefb6';
		else if(d.diff=="rem") return '#f45a5a';
		else if(d.diff=="both") return '#eee';
	})
	.attr("y", function(d) {
		return d.y;
	})
	.attr("x", function(d) {
		//console.log(layer.data())
		return (findStage(d.id_step))*width/columns+10;
	})
	.attr("height", function(d) {

		return (d.length*artHeight);
	})
	.attr("width", width/columns-20)
	.attr("opacity", 1.0)
	.on("click", function (d) {
		console.log(d)

		//STYLE OF CLICKED ELEMENT AND ROW
		//Reset Colors
		myrects.style("fill", function(d) {
		if(d.diff=="none") return '#fff';
		else if(d.diff=="add") return '#4cefb6';
		else if(d.diff=="rem") return '#f45a5a';
		else if(d.diff=="both") return '#eee';
		});

		//Color the elements in same group
		datum=d3.select(this.parentNode)
		d3.selectAll(datum[0][0].childNodes)
		.style("fill","#DAD1CB");

		d3.select(this).style("fill","#716259");

		//add text
		$("#law-title").text(datum.datum().titre);
		$(".text p").text(d.text)

		});

//ADD THE LINES
		lines
		.append("line")
		.filter(function(d,i) {
				datum=d3.select(this.parentNode).datum()

				if (d.length>0 && !d.last && datum.steps[i+1].length>0) return true;
				else return false;
		})
		.attr("x1", function(d){

			return (1+findStage(d.id_step))*width/columns-10
		})
		.attr("y1", function(d){
			return d.y+(d.length*artHeight)/2
		})
		.attr("x2", function(d,i){

			datum=d3.select(this.parentNode).datum()
			if (i+1<datum.steps.length) return (1+findStage(d.id_step))*width/columns+10
			else return null
		})
		.attr("y2", function(d,i){
			datum=d3.select(this.parentNode).datum()
			if (i+1<datum.steps.length) return datum.steps[i+1].y+(datum.steps[i+1].length*artHeight)/2
			else return null
		})
		.style("stroke", "#f2f2f2")
		.style("stroke-width",1);

addLabels();

//SETS COORDINATES FOR THE RECTANGLES
function setCoordinates() {

section="";

$.each(d3.values(art_values), function( index, value ) {

	changed = false
	if (value.section!=section) {
		section=value.section;
		changed=true;
	}

  $.each(value.steps, function( st_ind, step ) {
  	if(index==0) {
  		art_values[index].steps[st_ind]['y'] = 0;
  	}
  	else {
  		lasty=findLast(index-1,art_values[index].steps[st_ind]['id_step'])
  		if (lasty) {
  			art_values[index].steps[st_ind]['y'] = lasty.y + lasty.length*artHeight
  			if(art_values[index].steps[st_ind]['y']+art_values[index].steps[st_ind]['length']*artHeight>maxy) maxy = art_values[index].steps[st_ind]['y']+art_values[index].steps[st_ind]['length']*artHeight
  		}
  		else {
  			art_values[index].steps[st_ind]['y']=0
  		}
  	}
  	if(st_ind+1==value.steps.length) step.last=true
  	if(findStage(step.id_step)==0 && st_ind==0 && changed) {
  		value.first=true
  	}
  })
});
}

//FIND THE ABOVE RECTANGLE - RECURSIVE
function findLast(i1,i2) {

	if(i1<0) {
		return null;
	}
	ret=null;
	$.each(art_values[i1].steps, function( st_ind, step ) {
	if(step.id_step==i2) {
		ret=step;
		return false;
		}
	});
	if(ret) return ret
	else return findLast(i1-1,i2)
}

//Adds the labels
function addLabels() {
	layer.each(function(d, i) {
		if(d.first) {
			curry=d.steps[0].y
			$(".labels").append("

Section "+d.section +"

")
		}
	})
}

//Computes the stages involved in the law creation
function computeStages() {

	stag=[]

	art_values.forEach(function(e, i) {
		var st=d3.nest()
		.key(function(d) { return d.id_step; })
		//.entries(e.steps)
		.map(e.steps, d3.map);
		//console.log(d3.keys(st))
		d3.keys(st).forEach (function(f, i) {
			if(stag.indexOf(f)<0) stag.push(f)
		})
	})
	return stag
}

//finds a stage in the stages array
function findStage(s) {

	for(st in stages) {

		if (encodeURI(s)==encodeURI(stages[st]).substring(3)) {
			return parseInt(st)
		}
	}
	return -1
}

//computes the sections of the current law
function computeSections() {

		var se=d3.nest()
		.key(function(d) { return d.section; })
		//.entries(e.steps)
		.map(art_values,d3.map);
		return se.keys()
}

//finds a section in the sections array
function findSection(s) {
	res= sections.indexOf(s);
	return res
}
<|endoftext|>


<commit_before>var child_process = require('child_process');
var path = require("path");
var fs = require("fs");
var JsonUtil = require("../www/js/shared/JsonUtil.js");

(function(exports) {
    ///////////////////////// private instance variables
    var started = new Date();

    ////////////////// constructor
    function firenodejs(images, firesight, measure, mesh_rest, firekue_rest, options) {
        var that = this;

        options = options || {};

        if ((that.images = images) == null) throw new Error("images is required");
        if ((that.measure = measure) == null) throw new Error("measure is required");
        if ((that.firesight = firesight) == null) throw new Error("firesight is required");
        if ((that.firestep = images.firestep) == null) throw new Error("firestep is required");
        if ((that.camera = images.camera) == null) throw new Error("camera is required");;
        if ((that.mesh_rest = mesh_rest) == null) throw new Error("mesh_rest is required");;
        if ((that.firekue_rest = firekue_rest) == null) throw new Error("firekue_rest is required");;
        that.verbose = options.verbose;
        that.port = options.port || 80;
        that.modelPath = options.modelPath || '/var/firenodejs/firenodejs.json';
        that.model = {};
        that.version = options.version;
        that.models = {
            firestep: that.firestep.model,
            images: that.images.model,
            firesight: that.firesight.model,
            measure: that.measure.model,
            mesh: that.mesh_rest.model,
            firekue_rest: that.firekue_rest.model,
            camera: that.camera.syncModel(),
            firenodejs: that.model,
        };
        that.services = {
            firestep: that.firestep,
            images: that.images,
            firesight: that.firesight,
            measure: that.measure,
            mesh: that.mesh_rest,
            firekue_rest: that.firekue_rest,
            camera: that.camera,
            firenodejs: that,
        };
        try {
            console.log("INFO\t: loading existing firenodejs model from:" + that.modelPath);
            var models = JSON.parse(fs.readFileSync(that.modelPath));
            if (that.upgradeModels(models)) {
                that.saveModels(models);
            }
            var bakPath = that.modelPath+".bak";
            console.log("INFO\t: saving model backup:", bakPath);
            that.saveModels(models, bakPath);
            that.syncModels(models);
        } catch (e) {
            if (e.code === 'ENOENT') {
                console.log("INFO\t: created new firenodejs model archival file:" + that.modelPath);
            } else {
                var msg = "Could not read saved firenodejs file:" + e.message;
                console.log("ERROR\t:", msg);
                try {
                    var bakPath = that.modelPath+".bak";
                    console.log("INFO\t: attempting to restore from backup:", bakPath);
                    var models = JSON.parse(fs.readFileSync(bakPath));
                    if (that.upgradeModels(models)) {
                        that.saveModels(models);
                    }
                    that.syncModels(models);
                } catch (e) {
                    console.log("ERROR\t: Could not read firenodejs backup file.");
                    console.log("TRY\t: Delete file and retry:" + that.modelPath);
                    throw e;
                }
            }
        }
        console.log("INFO\t: updating " + that.modelPath);
        that.syncModels({
            firenodejs: {
                started: started.toString()
            }
        });

        return that;
    }

    firenodejs.prototype.saveModels = function(models, path) {
        var that = this;
        path = path || that.modelPath;
        var s = JSON.stringify(models, null, '  ') + '\n';
        fs.writeFile(path, s, function(err) {
            if (err instanceof Error) {
                console.log("ERROR\t: could not write " + path, err);
                throw err;
            }
            that.verbose && console.log("INFO\t: firenodejs.saveModels() saved to:" + path);
        });
    }
    firenodejs.prototype.setPort = function(port) {
        var that = this;
        that.port = port;
        that.services.firekue_rest.setPort(port);
    }
    firenodejs.prototype.upgradeModels_0_11 = function(models) {
        console.log("INFO\t: Upgrading firestep model to 0.11");
        if (models.firestep.rest.hasOwnProperty("startup")) {
            // Startup initialization replaced by beforeReset string
            if (!JsonUtil.isEmpty(models.firestep.rest.startup)) {
                try {
                    var br = JSON.parse(models.firestep.rest.startup.json);
                    if (br instanceof Array) {
                        if (br.length > 0 && br[br.length - 1].hasOwnProperty("mpo")) {
                            br = br.slice(0, br.length - 1);
                        }
                        if (br.length > 0 && br[br.length - 1].hasOwnProperty("hom")) {
                            br = br.slice(0, br.length - 1);
                        }
                    }
                    models.firestep.rest.beforeReset = br;
                    upgraded = true;
                } catch (e) {
                    // ignore invalid json
                }
            }
            delete models.firestep.rest.startup;
        }

        // presentation info should not be archived
        var marks = models.firestep.rest.marks;
        for (var i = 0; i < marks.length; i++) {
            var mark = marks[i];
            delete mark.title;
            delete mark.icon;
            delete mark.class;
        }

        models.firenodejs.version = {
            major: 0,
            minor: 11,
            patch: 0
        };
    }

    firenodejs.prototype.upgradeModels = function(models) {
        var that = this;
        var upgraded = false;
        var version = models.firenodejs.version;
        var vMajMin = Number(version.major + "." + version.minor);
        vMajMin < 0.11 && that.upgradeModels_0_11(models);
        return upgraded;
    }

    firenodejs.prototype.syncModels = function(delta) {
        var that = this;
        if (delta) {
            var keys = Object.keys(delta);
            for (var i = keys.length; i-- > 0;) {
                var key = keys[i];
                if (that.services.hasOwnProperty(key)) {
                    var svc = that.services[key];
                    var serviceDelta = delta[key];
                    if (serviceDelta) {
                        if (typeof svc.syncModel === "function") {
                            that.verbose && console.log("INFO\t: firenodejs.syncModels() delegate sync:" + key, JSON.stringify(serviceDelta));
                            svc.syncModel(serviceDelta);
                        } else {
                            that.verbose && console.log("INFO\t: firenodejs.syncModels() default sync:" + key, JSON.stringify(serviceDelta));
                            if (svc.model) {
                                JsonUtil.applyJson(svc.model, serviceDelta);
                            }
                        }
                    }
                }
            }
            that.model.version = JSON.parse(JSON.stringify(that.version));
            that.saveModels(that.models);
        }
        var now = new Date();
        var msElapsed = now.getTime() - started.getTime();
        that.model.uptime = msElapsed / 1000;
        return that.models;
    }
    firenodejs.prototype.isAvailable = function() {
        var that = this;
        var result = false;
        result = result || that.camera.isAvailable();
        result = result || that.firestep.isAvailable();
        result = result || that.images.isAvailable();
        result = result || that.firesight.isAvailable();
        result = result || that.measure.isAvailable();
        result = result || that.mesh_rest.isAvailable();
        result = result || that.firekue_rest.isAvailable();
        return result;
    }

    module.exports = exports.firenodejs = firenodejs;
})(typeof exports === "object" ? exports : (exports = {}));
<commit_msg>backup file fix<commit_after>var child_process = require('child_process');
var path = require("path");
var fs = require("fs");
var JsonUtil = require("../www/js/shared/JsonUtil.js");

(function(exports) {
    ///////////////////////// private instance variables
    var started = new Date();

    ////////////////// constructor
    function firenodejs(images, firesight, measure, mesh_rest, firekue_rest, options) {
        var that = this;

        options = options || {};

        if ((that.images = images) == null) throw new Error("images is required");
        if ((that.measure = measure) == null) throw new Error("measure is required");
        if ((that.firesight = firesight) == null) throw new Error("firesight is required");
        if ((that.firestep = images.firestep) == null) throw new Error("firestep is required");
        if ((that.camera = images.camera) == null) throw new Error("camera is required");;
        if ((that.mesh_rest = mesh_rest) == null) throw new Error("mesh_rest is required");;
        if ((that.firekue_rest = firekue_rest) == null) throw new Error("firekue_rest is required");;
        that.verbose = options.verbose;
        that.port = options.port || 80;
        that.modelPath = options.modelPath || '/var/firenodejs/firenodejs.json';
        that.model = {};
        that.version = options.version;
        that.models = {
            firestep: that.firestep.model,
            images: that.images.model,
            firesight: that.firesight.model,
            measure: that.measure.model,
            mesh: that.mesh_rest.model,
            firekue_rest: that.firekue_rest.model,
            camera: that.camera.syncModel(),
            firenodejs: that.model,
        };
        that.services = {
            firestep: that.firestep,
            images: that.images,
            firesight: that.firesight,
            measure: that.measure,
            mesh: that.mesh_rest,
            firekue_rest: that.firekue_rest,
            camera: that.camera,
            firenodejs: that,
        };
        try {
            console.log("INFO\t: loading existing firenodejs model from:" + that.modelPath);
            var models = JSON.parse(fs.readFileSync(that.modelPath));
            var bakPath = that.modelPath+".bak";
            console.log("INFO\t: saving model backup:", bakPath);
            that.saveModels(models, bakPath);
            if (that.upgradeModels(models)) {
                that.saveModels(models);
            }
            that.syncModels(models);
        } catch (e) {
            if (e.code === 'ENOENT') {
                console.log("INFO\t: created new firenodejs model archival file:" + that.modelPath);
            } else {
                var msg = "Could not read saved firenodejs file:" + e.message;
                console.log("ERROR\t:", msg);
                try {
                    var bakPath = that.modelPath+".bak";
                    console.log("INFO\t: attempting to restore from backup:", bakPath);
                    var models = JSON.parse(fs.readFileSync(bakPath));
                    if (that.upgradeModels(models)) {
                        that.saveModels(models);
                    }
                    that.syncModels(models);
                } catch (e) {
                    console.log("ERROR\t: Could not read firenodejs backup file.");
                    console.log("TRY\t: Delete file and retry:" + that.modelPath);
                    throw e;
                }
            }
        }
        console.log("INFO\t: updating " + that.modelPath);
        that.syncModels({
            firenodejs: {
                started: started.toString()
            }
        });

        return that;
    }

    firenodejs.prototype.saveModels = function(models, path) {
        var that = this;
        path = path || that.modelPath;
        var s = JSON.stringify(models, null, '  ') + '\n';
        fs.writeFile(path, s, function(err) {
            if (err instanceof Error) {
                console.log("ERROR\t: could not write " + path, err);
                throw err;
            }
            that.verbose && console.log("INFO\t: firenodejs.saveModels() saved to:" + path);
        });
    }
    firenodejs.prototype.setPort = function(port) {
        var that = this;
        that.port = port;
        that.services.firekue_rest.setPort(port);
    }
    firenodejs.prototype.upgradeModels_0_11 = function(models) {
        console.log("INFO\t: Upgrading firestep model to 0.11");
        if (models.firestep.rest.hasOwnProperty("startup")) {
            // Startup initialization replaced by beforeReset string
            if (!JsonUtil.isEmpty(models.firestep.rest.startup)) {
                try {
                    var br = JSON.parse(models.firestep.rest.startup.json);
                    if (br instanceof Array) {
                        if (br.length > 0 && br[br.length - 1].hasOwnProperty("mpo")) {
                            br = br.slice(0, br.length - 1);
                        }
                        if (br.length > 0 && br[br.length - 1].hasOwnProperty("hom")) {
                            br = br.slice(0, br.length - 1);
                        }
                    }
                    models.firestep.rest.beforeReset = br;
                    upgraded = true;
                } catch (e) {
                    // ignore invalid json
                }
            }
            delete models.firestep.rest.startup;
        }

        // presentation info should not be archived
        var marks = models.firestep.rest.marks;
        for (var i = 0; i < marks.length; i++) {
            var mark = marks[i];
            delete mark.title;
            delete mark.icon;
            delete mark.class;
        }

        models.firenodejs.version = {
            major: 0,
            minor: 11,
            patch: 0
        };
    }

    firenodejs.prototype.upgradeModels = function(models) {
        var that = this;
        var upgraded = false;
        var version = models.firenodejs.version;
        var vMajMin = Number(version.major + "." + version.minor);
        vMajMin < 0.11 && that.upgradeModels_0_11(models);
        return upgraded;
    }

    firenodejs.prototype.syncModels = function(delta) {
        var that = this;
        if (delta) {
            var keys = Object.keys(delta);
            for (var i = keys.length; i-- > 0;) {
                var key = keys[i];
                if (that.services.hasOwnProperty(key)) {
                    var svc = that.services[key];
                    var serviceDelta = delta[key];
                    if (serviceDelta) {
                        if (typeof svc.syncModel === "function") {
                            that.verbose && console.log("INFO\t: firenodejs.syncModels() delegate sync:" + key, JSON.stringify(serviceDelta));
                            svc.syncModel(serviceDelta);
                        } else {
                            that.verbose && console.log("INFO\t: firenodejs.syncModels() default sync:" + key, JSON.stringify(serviceDelta));
                            if (svc.model) {
                                JsonUtil.applyJson(svc.model, serviceDelta);
                            }
                        }
                    }
                }
            }
            that.model.version = JSON.parse(JSON.stringify(that.version));
            that.saveModels(that.models);
        }
        var now = new Date();
        var msElapsed = now.getTime() - started.getTime();
        that.model.uptime = msElapsed / 1000;
        return that.models;
    }
    firenodejs.prototype.isAvailable = function() {
        var that = this;
        var result = false;
        result = result || that.camera.isAvailable();
        result = result || that.firestep.isAvailable();
        result = result || that.images.isAvailable();
        result = result || that.firesight.isAvailable();
        result = result || that.measure.isAvailable();
        result = result || that.mesh_rest.isAvailable();
        result = result || that.firekue_rest.isAvailable();
        return result;
    }

    module.exports = exports.firenodejs = firenodejs;
})(typeof exports === "object" ? exports : (exports = {}));
<|endoftext|>


<commit_before>/**
 * Saves the state of the given element. Must implement an action for
 * any element that can be saved.
 *
 * @param event
 * @param ui
 */
function saveState(event, ui)
{
	if ($(event.target).hasClass('questions-list') ||
		$(event.target).attr('name') == 'to-page')
	{
		$('body').addClass('loading');
		$('.tabs ul:first li').addClass('ui-state-default');

		var $questionnaireId = window.location.href.match(/\/id\/(\d{1,})/)[1].toString();
		var $pages = $('ul.sortable');

		$pages.each(function($key, $val) {
			var $page = $($val);
			var $data = $page.sortable('serialize') + '&page=' + (parseInt($key) + 1);
			$.post(baseUrl + '/questionnaire/order', $data, function() {
				if ($key == ($pages.length - 1)) $('body').removeClass('loading');
			});
		});
	}

	else if (1 == 1 ||
			event.target.id === 'repository-questions' ||
			event.target.id === 'less' ||
			event.target.id === 'more' ||
			event.target.id === 'subquestions')
	{
		console.log(event);
		return;
		$('body').addClass('loading');

		var $action = $elm.closest('form').attr('action');
		var $qqId = $action.match(/\/id\/(\d{1,})/)[1].toString();

		var $list = $('#subquestions');
		var $data = $list.sortable('serialize') + '&cols=' + $('#cols').val() + '&parent=' + $qqId;
		$.post(baseUrl + '/questionnaire-question/save-state', $data, function() {
			$('body').removeClass('loading');
		});
	}
}

function makeTabsSortable()
{
//	return $('ul.sortable').sortable({
//		handle: 'div.handle',
//		revert: 'invalid',
//		accept: 'li.question',
//		start: function(event, ui) {
//			$(ui.helper).css({
//				width: '16px',
//				height: '16px',
//				overflow: 'hidden'
//			});
//		},
//		update: function(event, ui) {
//			saveState(event, ui);
//		}
//	}).disableSelection();
}

function makeTabsDroppable($tabs)
{
	var $tabItems = $('ul:first li', $tabs);
	return $tabItems.droppable({
		activeClass: 'ui-state-default',
		hoverClass: 'ui-state-hover',
		accept: 'ul.sortable li',
		drop: function(event, ui) {
			var $item = $(this);
			var $list = $item.find('ul');
			var $draggable = ui.draggable.clone();
			ui.draggable.remove();
			$list.append('
' + $draggable.html() + '
');
		}
	});
}

function makeQuestionsDroppable($tabs)
{
	return $('li.question').droppable({
		activeClass: 'ui-state-default',
		hoverClass: 'ui-state-hover',
		accept: 'ul.sortable li',
		drop: function(event, ui) {
			var $item = $(this);
			var $list = $($item.find('a').attr('href')).find('ul.sortable');
			var $draggable = ui.draggable.clone();
			ui.draggable.remove();
			$list.prepend($('
' + $draggable.html() + '
'));
			$tabs.tabs('select', $tabItems.index($item));
		}
	});
}

function updateAnswersTab()
{
	if ($('#answers-useAnswerPossibilityGroup').is(':checked')) {
		$('#answers-answerPossibilityGroup_id').removeAttr('disabled');
		$('#answers-collectionPresentationType').removeAttr('disabled');
	} else {
		$('#answers-answerPossibilityGroup_id').attr('disabled', 'disabled');
		$('#answers-collectionPresentationType').attr('disabled', 'disabled');
	}
}

function updateValidationTab()
{
	if ($('#answers-useAnswerPossibilityGroup').is(':checked')) {
		$('#dialog #validation #filters-element input[type="checkbox"]').attr('disabled', 'disabled');
		$('#dialog #validation #validators-element input[type="checkbox"]').attr('disabled', 'disabled');
	} else {
		$('#dialog #validation #filters-element input[type="checkbox"]').removeAttr('disabled');
		$('#dialog #validation #validators-elementinput[type="checkbox"]').removeAttr('disabled');
	}
}

function updateColWidth(action)
{
	/* get and update current number of columns */
	$cols = $('#cols').val();
	if ($cols == 'NaN') $cols = 1;
	if (action == 'less' && $cols > 1) {
		$cols--;
	} else if (action == 'more' && $cols < $('#dialog #group ul#subquestions li').length) {
		$cols++;
	}
	$('#cols').val($cols);

	/* calculate and set new column width */
	$containerWidth = parseInt($('#dialog').width()) - 65;
	$newWidth = parseInt($containerWidth / $cols) - (5 * $cols);
	$.each($('#dialog #group ul#subquestions li'), function($i, $elm) {
		$($elm).width($newWidth);
	});
}

/**
 * Initialises the tab for editing sub-questions
 */
function initTabSubquestions()
{
	var $list = $('#dialog #group ul#subquestions');

	updateColWidth();

	$('#dialog #group #less').click(function() {
		updateColWidth('less');
		saveState($list);
		return false;
	});

	$('#dialog #group #more').click(function() {
		updateColWidth('more');
		saveState($list);
		return false;
	});

	$('#dialog #group ul#subquestions').sortable({
		update: function(event, ui) {
			saveState($list);
		}
	});

	$('#dialog #group ul#subquestions li a.delete').click(function() {
		$(this).closest('li').remove();
		saveState($list);
		return false;
	});
}

/**
 * Initialises the tab for editing answer-possibilities
 */
function initTabAnswerPossibilities()
{
	updateAnswersTab();
	$('#answers-useAnswerPossibilityGroup').change(function() {
		updateAnswersTab();
	});
}

/**
 * Initialises the tab for validation settings
 */
function initTabValidation()
{
	updateValidationTab();
	$('#answers-useAnswerPossibilityGroup').change(function() {
		updateValidationTab();
	});
}

function postOpenDialog(response) {

	/* tabs */
	$('.tabs').tabs();

	/* init tab sub-questions */
	if ($('#dialog #group').length > 0) {
		initTabSubquestions();
	}

	/* init tab answer-possibilities */
	if ($('#dialog #answer').length > 0) {
		initTabAnswerPossibilities();
		initTabValidation();
	}

	/* add questionnaire id to the form */
	var $questionnaireId = window.location.href.match(/id\/(\d{1,})/)[1];
	$('<input type="hidden" id="questionnaire_id" name="questionnaire_id" value="' + $questionnaireId + '" />').appendTo('#dialog form');

	/* initialize filter */
	initFilter();

//	$.each($('#dialog input[type="text"]'), function($key, $val) {
//		var $elm = $($val);
//		var $name = $elm.attr('name');
//		$elm.autocomplete({
//			source: baseUrl + '/question/autocomplete/element/' + $name,
//			select: function(event, ui) {
//
//				/* replace the value by the label */
//				$(this).val(ui.item.label);
//
//				/* add question id to the form */
//				if ($('#dialog form input#question_id').length == 0) {
//					$('<input type="hidden" id="question_id" name="question_id" value="' + ui.item.value + '" />').appendTo('#dialog form');
//				} else {
//					$('#dialog form input#question_id').val(ui.item.value);
//				}
//
//				return false;
//			}
//		});
//	});

	/* hide repository questions list */
	$('#repository-questions').hide();

	/* add action to 'add subquestion' link */
	$('#group a.add').toggle(function() {
		$('#repository-questions').show();
		return false;
	}, function() {
		$('#repository-questions').hide();
		return false;
	});

	/* make repository questions list selectable */
	$('#repository-questions').selectable({
		/* add event to selection of a subquestion */
		selected: function(event, ui) {
			var $list = $('#subquestions');
			/* make sortable */
			$list.sortable();
			/* append selected subquestion to list */
			$(ui.selected)
				.removeClass('ui-widget-content')
				.removeClass('ui-selectee')
				.removeClass('ui-selected')
				.addClass('ui-state-default')
				.prepend('')
				.appendTo($list);
			if ($list.find('li').length == 1) {
				$(ui.selected).css({width: '100%'});
			} else {
				$(ui.selected).css({width: $list.find('li:first').width() + 'px'});
			}
			/* save current state of the list */
			saveState($(this));
		}
	});
}

function addPage() {
	// get page tabs
	var $tabs = $('div.tabs');
	// calculate new page id
	var $newPageId = $tabs.tabs('length') + 1;
	// create new page by cloning
	var $newPage = $('#page-1').clone();

	// assign id to new page
	$newPage.attr('id', 'page-' + $newPageId);
	// remove cloned questions list
	$('ul.sortable li', $newPage).remove();
	// append page
	$newPage.appendTo($tabs);

	// add tabs functionality to new page
	$tabs.tabs('add', '#' + 'page-' + $newPageId, 'pagina ' + $newPageId);
	// select the newly added page
	$tabs.tabs('select', $tabs.tabs('length') - 1);

	// reset sortable and droppable
	makeTabsSortable();
	makeTabsDroppable($tabs);

	return false;
}

$(function() {

//	var $tabs = $('.tabs');
//	makeTabsSortable();
//	var $tabItems = makeTabsDroppable($tabs);

	// add event to add-page button
	$('.add_page').click(function() {
		addPage();
	});

	// event for moving question to other page
	$('select[name="to-page"]').change(function(event, ui) {
		var question = $(this).closest('li.question');
		var newPage = $('div#page-' + $(this).val());
		// move question to selected page
		$('ul.questions-list', newPage).append(question);
		question.removeClass('hover').removeClass('ui-state-highlight');
		saveState(event, ui);
		return false;
	});

	// hide form for editing questionnaire title if no errors
	if ($('form#Webenq_Form_Questionnaire_Edit ul.errors').length == 0) {
		$('form#Webenq_Form_Questionnaire_Edit').hide();
	}

	// show form for editing title when edit-buttons is clicked
	$('a#edit_title').toggle(function() {
		$('form#Webenq_Form_Questionnaire_Edit').show('slow');
		return false;
	}, function() {
		$('form#Webenq_Form_Questionnaire_Edit').hide('slow');
		return false;
	});
});<commit_msg>[4710] fix: nieuwe pagina ook toevoegen aan "to-page" select boxes<commit_after>/**
 * Saves the state of the given element. Must implement an action for
 * any element that can be saved.
 *
 * @param event
 * @param ui
 */
function saveState(event, ui)
{
	if ($(event.target).hasClass('questions-list') ||
		$(event.target).attr('name') == 'to-page')
	{
		$('body').addClass('loading');
		$('.tabs ul:first li').addClass('ui-state-default');

		var $questionnaireId = window.location.href.match(/\/id\/(\d{1,})/)[1].toString();
		var $pages = $('ul.sortable');

		$pages.each(function($key, $val) {
			var $page = $($val);
			var $data = $page.sortable('serialize') + '&page=' + (parseInt($key) + 1);
			$.post(baseUrl + '/questionnaire/order', $data, function() {
				if ($key == ($pages.length - 1)) $('body').removeClass('loading');
			});
		});
	}

	else if (event.target.id === 'repository-questions' ||
			event.target.id === 'less' ||
			event.target.id === 'more' ||
			event.target.id === 'subquestions')
	{
		console.log(event);
		return;

		$('body').addClass('loading');

		var $action = $elm.closest('form').attr('action');
		var $qqId = $action.match(/\/id\/(\d{1,})/)[1].toString();

		var $list = $('#subquestions');
		var $data = $list.sortable('serialize') + '&cols=' + $('#cols').val() + '&parent=' + $qqId;
		$.post(baseUrl + '/questionnaire-question/save-state', $data, function() {
			$('body').removeClass('loading');
		});
	}
}

function makeTabsSortable()
{
//	return $('ul.sortable').sortable({
//		handle: 'div.handle',
//		revert: 'invalid',
//		accept: 'li.question',
//		start: function(event, ui) {
//			$(ui.helper).css({
//				width: '16px',
//				height: '16px',
//				overflow: 'hidden'
//			});
//		},
//		update: function(event, ui) {
//			saveState(event, ui);
//		}
//	}).disableSelection();
}

function makeTabsDroppable($tabs)
{
	var $tabItems = $('ul:first li', $tabs);
	return $tabItems.droppable({
		activeClass: 'ui-state-default',
		hoverClass: 'ui-state-hover',
		accept: 'ul.sortable li',
		drop: function(event, ui) {
			var $item = $(this);
			var $list = $item.find('ul');
			var $draggable = ui.draggable.clone();
			ui.draggable.remove();
			$list.append('
' + $draggable.html() + '
');
		}
	});
}

function makeQuestionsDroppable($tabs)
{
	return $('li.question').droppable({
		activeClass: 'ui-state-default',
		hoverClass: 'ui-state-hover',
		accept: 'ul.sortable li',
		drop: function(event, ui) {
			var $item = $(this);
			var $list = $($item.find('a').attr('href')).find('ul.sortable');
			var $draggable = ui.draggable.clone();
			ui.draggable.remove();
			$list.prepend($('
' + $draggable.html() + '
'));
			$tabs.tabs('select', $tabItems.index($item));
		}
	});
}

function updateAnswersTab()
{
	if ($('#answers-useAnswerPossibilityGroup').is(':checked')) {
		$('#answers-answerPossibilityGroup_id').removeAttr('disabled');
		$('#answers-collectionPresentationType').removeAttr('disabled');
	} else {
		$('#answers-answerPossibilityGroup_id').attr('disabled', 'disabled');
		$('#answers-collectionPresentationType').attr('disabled', 'disabled');
	}
}

function updateValidationTab()
{
	if ($('#answers-useAnswerPossibilityGroup').is(':checked')) {
		$('#dialog #validation #filters-element input[type="checkbox"]').attr('disabled', 'disabled');
		$('#dialog #validation #validators-element input[type="checkbox"]').attr('disabled', 'disabled');
	} else {
		$('#dialog #validation #filters-element input[type="checkbox"]').removeAttr('disabled');
		$('#dialog #validation #validators-elementinput[type="checkbox"]').removeAttr('disabled');
	}
}

function updateColWidth(action)
{
	/* get and update current number of columns */
	$cols = $('#cols').val();
	if ($cols == 'NaN') $cols = 1;
	if (action == 'less' && $cols > 1) {
		$cols--;
	} else if (action == 'more' && $cols < $('#dialog #group ul#subquestions li').length) {
		$cols++;
	}
	$('#cols').val($cols);

	/* calculate and set new column width */
	$containerWidth = parseInt($('#dialog').width()) - 65;
	$newWidth = parseInt($containerWidth / $cols) - (5 * $cols);
	$.each($('#dialog #group ul#subquestions li'), function($i, $elm) {
		$($elm).width($newWidth);
	});
}

/**
 * Initialises the tab for editing sub-questions
 */
function initTabSubquestions()
{
	var $list = $('#dialog #group ul#subquestions');

	updateColWidth();

	$('#dialog #group #less').click(function() {
		updateColWidth('less');
		saveState($list);
		return false;
	});

	$('#dialog #group #more').click(function() {
		updateColWidth('more');
		saveState($list);
		return false;
	});

	$('#dialog #group ul#subquestions').sortable({
		update: function(event, ui) {
			saveState($list);
		}
	});

	$('#dialog #group ul#subquestions li a.delete').click(function() {
		$(this).closest('li').remove();
		saveState($list);
		return false;
	});
}

/**
 * Initialises the tab for editing answer-possibilities
 */
function initTabAnswerPossibilities()
{
	updateAnswersTab();
	$('#answers-useAnswerPossibilityGroup').change(function() {
		updateAnswersTab();
	});
}

/**
 * Initialises the tab for validation settings
 */
function initTabValidation()
{
	updateValidationTab();
	$('#answers-useAnswerPossibilityGroup').change(function() {
		updateValidationTab();
	});
}

function postOpenDialog(response) {

	/* tabs */
	$('.tabs').tabs();

	/* init tab sub-questions */
	if ($('#dialog #group').length > 0) {
		initTabSubquestions();
	}

	/* init tab answer-possibilities */
	if ($('#dialog #answer').length > 0) {
		initTabAnswerPossibilities();
		initTabValidation();
	}

	/* add questionnaire id to the form */
	var $questionnaireId = window.location.href.match(/id\/(\d{1,})/)[1];
	$('<input type="hidden" id="questionnaire_id" name="questionnaire_id" value="' + $questionnaireId + '" />').appendTo('#dialog form');

	/* initialize filter */
	initFilter();

//	$.each($('#dialog input[type="text"]'), function($key, $val) {
//		var $elm = $($val);
//		var $name = $elm.attr('name');
//		$elm.autocomplete({
//			source: baseUrl + '/question/autocomplete/element/' + $name,
//			select: function(event, ui) {
//
//				/* replace the value by the label */
//				$(this).val(ui.item.label);
//
//				/* add question id to the form */
//				if ($('#dialog form input#question_id').length == 0) {
//					$('<input type="hidden" id="question_id" name="question_id" value="' + ui.item.value + '" />').appendTo('#dialog form');
//				} else {
//					$('#dialog form input#question_id').val(ui.item.value);
//				}
//
//				return false;
//			}
//		});
//	});

	/* hide repository questions list */
	$('#repository-questions').hide();

	/* add action to 'add subquestion' link */
	$('#group a.add').toggle(function() {
		$('#repository-questions').show();
		return false;
	}, function() {
		$('#repository-questions').hide();
		return false;
	});

	/* make repository questions list selectable */
	$('#repository-questions').selectable({
		/* add event to selection of a subquestion */
		selected: function(event, ui) {
			var $list = $('#subquestions');
			/* make sortable */
			$list.sortable();
			/* append selected subquestion to list */
			$(ui.selected)
				.removeClass('ui-widget-content')
				.removeClass('ui-selectee')
				.removeClass('ui-selected')
				.addClass('ui-state-default')
				.prepend('')
				.appendTo($list);
			if ($list.find('li').length == 1) {
				$(ui.selected).css({width: '100%'});
			} else {
				$(ui.selected).css({width: $list.find('li:first').width() + 'px'});
			}
			/* save current state of the list */
			saveState($(this));
		}
	});
}

function addPage()
{
	// get page tabs
	var $tabs = $('div.tabs');
	// calculate new page id
	var $newPageId = $tabs.tabs('length') + 1;
	// create new page by cloning
	var $newPage = $('#page-1').clone();

	// assign id to new page
	$newPage.attr('id', 'page-' + $newPageId);
	// remove cloned questions list
	$('ul.sortable li', $newPage).remove();
	// append page
	$newPage.appendTo($tabs);

	// add tabs functionality to new page
	$tabs.tabs('add', '#' + 'page-' + $newPageId, 'pagina ' + $newPageId);
	// select the newly added page
	$tabs.tabs('select', $tabs.tabs('length') - 1);
	// append the new page to all questions' change-page-select-elements
	$('select[name="to-page"]').append('<option label="' + $newPageId + '" value="' + $newPageId + '">' + $newPageId + '</option');

	// make new page's question list sortable
	$('.questions-list', $newPage).sortable({
		placeholder: 'ui-state-highlight',
		update: function(event, ui) {
			saveState(event, ui);
		}
	}).disableSelection();

	// reset sortable and droppable
//	makeTabsSortable();
//	makeTabsDroppable($tabs);

	return false;
}

$(function() {

//	var $tabs = $('.tabs');
//	makeTabsSortable();
//	var $tabItems = makeTabsDroppable($tabs);

	// add event to add-page button
	$('.add_page').click(function() {
		addPage();
	});

	// event for moving question to other page
	$('select[name="to-page"]').change(function(event, ui) {
		var question = $(this).closest('li.question');
		var newPage = $('div#page-' + $(this).val());
		// move question to selected page
		$('ul.questions-list', newPage).append(question);
		question.removeClass('hover').removeClass('ui-state-highlight');
		saveState(event, ui);
		return false;
	});

	// hide form for editing questionnaire title if no errors
	if ($('form#Webenq_Form_Questionnaire_Edit ul.errors').length == 0) {
		$('form#Webenq_Form_Questionnaire_Edit').hide();
	}

	// show form for editing title when edit-buttons is clicked
	$('a#edit_title').toggle(function() {
		$('form#Webenq_Form_Questionnaire_Edit').show('slow');
		return false;
	}, function() {
		$('form#Webenq_Form_Questionnaire_Edit').hide('slow');
		return false;
	});
});<|endoftext|>


<commit_before>var margin = {top: 20, right: 20, bottom: 30, left: 140},
  width = 760 - margin.left - margin.right,
  height = 500 - margin.top - margin.bottom;

var color = d3.scale.category20();

var force = d3.layout.force()
    .charge(-80)
    .linkDistance(200)
    .friction(0.9)
    .size([width, height]);

var forceSvg = d3.select("div#chord_chart").append("svg")
    .attr("width", width)
    .attr("height", height);

var forceListSvg = d3.select('div#force_list').append('svg')
    .attr('width', 200)
    .attr('height', 2000)
    .append('g')
      .attr("transform", "translate(" + margin.right + "," + margin.top + ")");;

var node_drag = d3.behavior.drag()
    .on("dragstart", dragstart)
    .on("drag", dragmove)
    .on("dragend", dragend);
    function dragstart(d, i) {
        force.stop() // stops the force auto positioning before you start dragging
    }
    function dragmove(d, i) {
        d.px += d3.event.dx;
        d.py += d3.event.dy;
        d.x += d3.event.dx;
        d.y += d3.event.dy;
    }
    function dragend(d, i) {
        d.fixed = true; // of course set the node to fixed so the force doesn't include the node in its auto positioning stuff
        force.resume();
    }
    function releasenode(d) {
        d.fixed = false; // of course set the node to fixed so the force doesn't include the node in its auto positioning stuff
        //force.resume();
    };

d3.csv("cooccurrenceMatrixData.csv", function(data){

  totallist = [];
  for (i=0; i<data.length; i++){
    if ($.inArray(data[i].word1, totallist) < 0){
      totallist.push(data[i].word1);
    }
    if ($.inArray(data[i].word2, totallist) < 0){
      totallist.push(data[i].word2);
    }
  }
  selectedList = ['pm','school','mandarin','up','chinese','strike','new',
    'bomb','blast','attack','die'];

  function prepData(selectedList){

    data1 = $.map(data, function(element){
      return ($.inArray(element.word1,selectedList)>-1?element:null);
    });
    data = $.map(data1, function(element){
      return ($.inArray(element.word2,selectedList)>-1?element:null);
    });

    graphDict = {};
    graphDict['nodes'] = [];
    graphDict['links'] = [];
    entrylist = [];
    for (i=0; i<data.length; i++){
      if ($.inArray(data[i].word1, entrylist) < 0){
        dict = {};
        dict['name'] = data[i].word1
        dict['group'] = 0
        graphDict['nodes'].push(dict)
        entrylist.push(data[i].word1);
      };
      if ($.inArray(data[i].word2, entrylist) < 0){
        dict = {};
        dict['name'] = data[i].word2
        dict['group'] = 0
        graphDict['nodes'].push(dict)
        entrylist.push(data[i].word2);
      };
      dict = {};
      dict['source'] = entrylist.indexOf(data[i].word1);
      dict['target'] = entrylist.indexOf(data[i].word2);
      dict['value'] = +data[i].size
      graphDict['links'].push(dict);
    };
    return graphDict;
  }

  var term_label = forceListSvg.selectAll('.force_item')
        .data(totallist)
        .enter()
      .append('text')
        .attr('class', 'force_item')
        .attr("x", 50)
        .attr("y", function(d,i){ return i+"9px"; })
        .style("text-anchor", "middle")
        .style("font-size", "15px")
        .style("fill", "#53565A")
        .transition()
        .duration(750)
        //.style('fill', function(d){ return line_color(d.term); })
        .text(function(d){ return d; });

  data = prepData(selectedList);
  console.log(data);

  drawGraph(data);

  function drawGraph(graph){
    force
      .nodes(graph.nodes)
      .links(graph.links)
      .start();

    var graphMin = d3.min(graph.links, function(d){ return d.size; });
    var graphMax = d3.max(graph.links, function(d){ return d.size; });

    var fill = d3.scale.ordinal()
        .domain([graphMin, graphMax])
        .range(["#f7fcfd","#e5f5f9","#ccece6","#99d8c9","#66c2a4",
          "#41ae76","#238b45","#006d2c","#00441b"]);

    var div = d3.select('div#chord_chart').append('div')
            .attr('class', 'tooltip')
            .style('opacity', 0);

    var link = forceSvg.selectAll(".link")
        .data(graph.links);

    link
      .enter().append("line")
        .attr("class", "link")
        .style('stroke-width', 1)
        .style('stroke', function(d){ return fill(d.value); });
        //.style("stroke-width", function(d) { return Math.sqrt(d.value); });

    link
      .transition()
      .duration(400)
      .attr("class", "link")
      .style('stroke-width', 1)
      .style('stroke', function(d){ return fill(d.value); });

    var node = forceSvg.selectAll(".node")
        .data(graph.nodes);

    node
      .enter().append("circle")
        .attr("class", "node")
        .attr("r", 5)
        .style("fill", function(d) { return color(d.group); })
        .on('dblclick', releasenode)
        .on('click', connectedNodes)
        .call(node_drag);
        //.call(force.drag);

    node
      .transition()
      .duration(400)
      .attr("class", "node")
      .attr("r", 5)
      .style("fill", function(d) { return color(d.group); })
      .on('dblclick', releasenode)
      .on('click', connectedNodes)
      .call(node_drag);

    node
        .on('mouseover', function(d,i,j){
            d3.select(this).transition().duration(600)
              .attr('r', 8).style('opacity', 1);
            div.transition()
              .duration(500)
              .style('opacity', 1);
            div.html(d.name)
              .style('left', '300px')
              .style('top', '10px');
              //.style('left', (d3.event.pageX) + 10 + "px")
              //.style('top', (d3.event.pageY) + 2 + "px")
              //.style('color', line_color(used_data[j].term));
        })
        .on('mouseout', function(d){
            d3.select(this).transition().duration(600)
              .attr('r', 5).style('opacity', 1);
            div.transition()
              .duration(500)
              .style('opacity', 0);
        });

    node.append("title")
        .text(function(d) { return d.name; });

    force.on("tick", function() {
      link.attr("x1", function(d) { return d.source.x; })
          .attr("y1", function(d) { return d.source.y; })
          .attr("x2", function(d) { return d.target.x; })
          .attr("y2", function(d) { return d.target.y; });

      node.attr("cx", function(d) { return d.x; })
          .attr("cy", function(d) { return d.y; });
    });

/*
    var k = 0;
    while ((force.alpha() > 1e-2) && (k < 150)) {
        force.tick(),
        k = k + 1;
    }
*/
    //Toggle stores whether the highlighting is on
  var toggle = 0;

  //Create an array logging what is connected to what
  var linkedByIndex = {};
  for (i = 0; i < graph.nodes.length; i++) {
      linkedByIndex[i + "," + i] = 1;
  };
  graph.links.forEach(function (d) {
      linkedByIndex[d.source.index + "," + d.target.index] = 1;
  });

  //This function looks up whether a pair are neighbours
  function neighboring(a, b) {
      return linkedByIndex[a.index + "," + b.index];
  }

  function connectedNodes() {

    if (toggle == 0) {
        //Reduce the opacity of all but the neighbouring nodes
        d = d3.select(this).node().__data__;
        node.style("opacity", function (o) {
            return neighboring(d, o) | neighboring(o, d) ? 1 : 0.1;
        });

        link.style("opacity", function (o) {
            return d.index==o.source.index | d.index==o.target.index ? 1 : 0.1;
        });

        //Reduce the op

        toggle = 1;
    } else {
        //Put them back to opacity=1
        node.style("opacity", 1);
        link.style("opacity", 1);
        toggle = 0;
    }

  }
  }

});

/*
d3.json("newsGraph.json", function(error, graph) {
  testGraph = JSON.parse(JSON.stringify(graph))

  selectedList = ['up','police','china','labor','union'];
  selectedData1 = $.map(testGraph.nodes, function(element){
      return ($.inArray(element.name,selectedList)>-1?element:null);
    });

  selectedData2 = $.map(testGraph.links, function(element){
      return ($.inArray(element['name1'],selectedList)>-1?element:null);
    });

  selectedData3 = $.map(selectedData2, function(element){
      return ($.inArray(element.name2,selectedList)>-1?element:null);
    });

  new_graph = {};
  new_graph['nodes'] = graph.nodes;
  new_graph['links'] = selectedData3;

  //drawGraph(graph, selectedData1, selectedData3);
  drawGraph(graph);

});
*/

<commit_msg>update data<commit_after>var margin = {top: 20, right: 20, bottom: 30, left: 140},
  width = 760 - margin.left - margin.right,
  height = 500 - margin.top - margin.bottom;

var color = d3.scale.category20();

var force = d3.layout.force()
    .charge(-80)
    .linkDistance(200)
    .friction(0.9)
    .size([width, height]);

var forceSvg = d3.select("div#chord_chart").append("svg")
    .attr("width", width)
    .attr("height", height);

var forceListSvg = d3.select('div#force_list').append('svg')
    .attr('width', 200)
    .attr('height', 2000)
    .append('g')
      .attr("transform", "translate(" + margin.right + "," + margin.top + ")");;

var node_drag = d3.behavior.drag()
    .on("dragstart", dragstart)
    .on("drag", dragmove)
    .on("dragend", dragend);
    function dragstart(d, i) {
        force.stop() // stops the force auto positioning before you start dragging
    }
    function dragmove(d, i) {
        d.px += d3.event.dx;
        d.py += d3.event.dy;
        d.x += d3.event.dx;
        d.y += d3.event.dy;
    }
    function dragend(d, i) {
        d.fixed = true; // of course set the node to fixed so the force doesn't include the node in its auto positioning stuff
        force.resume();
    }
    function releasenode(d) {
        d.fixed = false; // of course set the node to fixed so the force doesn't include the node in its auto positioning stuff
        //force.resume();
    };

d3.csv("cooccurrenceMatrixData.csv", function(data){

  totallist = [];
  for (i=0; i<data.length; i++){
    if ($.inArray(data[i].word1, totallist) < 0){
      totallist.push(data[i].word1);
    }
    if ($.inArray(data[i].word2, totallist) < 0){
      totallist.push(data[i].word2);
    }
  }
  selectedList = ['pm','school','mandarin','up','chinese','strike','new',
    'bomb','blast','attack','die'];

  function prepData(selectedList){

    data1 = $.map(data, function(element){
      return ($.inArray(element.word1,selectedList)>-1?element:null);
    });
    data = $.map(data1, function(element){
      return ($.inArray(element.word2,selectedList)>-1?element:null);
    });

    graphDict = {};
    graphDict['nodes'] = [];
    graphDict['links'] = [];
    entrylist = [];
    for (i=0; i<data.length; i++){
      if ($.inArray(data[i].word1, entrylist) < 0){
        dict = {};
        dict['name'] = data[i].word1
        dict['group'] = 0
        graphDict['nodes'].push(dict)
        entrylist.push(data[i].word1);
      };
      if ($.inArray(data[i].word2, entrylist) < 0){
        dict = {};
        dict['name'] = data[i].word2
        dict['group'] = 0
        graphDict['nodes'].push(dict)
        entrylist.push(data[i].word2);
      };
      dict = {};
      dict['source'] = entrylist.indexOf(data[i].word1);
      dict['target'] = entrylist.indexOf(data[i].word2);
      dict['value'] = +data[i].size
      graphDict['links'].push(dict);
    };
    return graphDict;
  };

  var term_label = forceListSvg.selectAll('.force_item')
        .data(totallist)
        .enter()
      .append('text')
        .attr('class', 'force_item')
        .attr("x", 50)
        .attr("y", function(d,i){ return i+"9px"; })
        .style("text-anchor", "middle")
        .style("font-size", "15px")
        .style("fill", "#53565A")
        .transition()
        .duration(750)
        //.style('fill', function(d){ return line_color(d.term); })
        .text(function(d){ return d; });

  data = prepData(selectedList);
  console.log(data);

  drawGraph(data);

  function drawGraph(graph){
    force
      .nodes(graph.nodes)
      .links(graph.links)
      .start();

    var graphMin = d3.min(graph.links, function(d){ return d.size; });
    var graphMax = d3.max(graph.links, function(d){ return d.size; });

    var fill = d3.scale.ordinal()
        .domain([graphMin, graphMax])
        .range(["#f7fcfd","#e5f5f9","#ccece6","#99d8c9","#66c2a4",
          "#41ae76","#238b45","#006d2c","#00441b"]);

    var div = d3.select('div#chord_chart').append('div')
            .attr('class', 'tooltip')
            .style('opacity', 0);

    var link = forceSvg.selectAll(".link")
        .data(graph.links);

    link
      .enter().append("line")
        .attr("class", "link")
        .style('stroke-width', 1)
        .style('stroke', function(d){ return fill(d.value); });
        //.style("stroke-width", function(d) { return Math.sqrt(d.value); });

    link
      .transition()
      .duration(400)
      .attr("class", "link")
      .style('stroke-width', 1)
      .style('stroke', function(d){ return fill(d.value); });

    var node = forceSvg.selectAll(".node")
        .data(graph.nodes);

    node
      .enter().append("circle")
        .attr("class", "node")
        .attr("r", 5)
        .style("fill", function(d) { return color(d.group); })
        .on('dblclick', releasenode)
        .on('click', connectedNodes)
        .call(node_drag);
        //.call(force.drag);

    node
      .transition()
      .duration(400)
      .attr("class", "node")
      .attr("r", 5)
      .style("fill", function(d) { return color(d.group); })
      .on('dblclick', releasenode)
      .on('click', connectedNodes)
      .call(node_drag);

    node
        .on('mouseover', function(d,i,j){
            d3.select(this).transition().duration(600)
              .attr('r', 8).style('opacity', 1);
            div.transition()
              .duration(500)
              .style('opacity', 1);
            div.html(d.name)
              .style('left', '300px')
              .style('top', '10px');
              //.style('left', (d3.event.pageX) + 10 + "px")
              //.style('top', (d3.event.pageY) + 2 + "px")
              //.style('color', line_color(used_data[j].term));
        })
        .on('mouseout', function(d){
            d3.select(this).transition().duration(600)
              .attr('r', 5).style('opacity', 1);
            div.transition()
              .duration(500)
              .style('opacity', 0);
        });

    node.append("title")
        .text(function(d) { return d.name; });

    force.on("tick", function() {
      link.attr("x1", function(d) { return d.source.x; })
          .attr("y1", function(d) { return d.source.y; })
          .attr("x2", function(d) { return d.target.x; })
          .attr("y2", function(d) { return d.target.y; });

      node.attr("cx", function(d) { return d.x; })
          .attr("cy", function(d) { return d.y; });
    });

});

  //Toggle stores whether the highlighting is on
  var toggle = 0;

  //Create an array logging what is connected to what
  var linkedByIndex = {};
  for (i = 0; i < graph.nodes.length; i++) {
      linkedByIndex[i + "," + i] = 1;
  };
  graph.links.forEach(function (d) {
      linkedByIndex[d.source.index + "," + d.target.index] = 1;
  });

  //This function looks up whether a pair are neighbours
  function neighboring(a, b) {
      return linkedByIndex[a.index + "," + b.index];
  }

  function connectedNodes() {

    if (toggle == 0) {
        //Reduce the opacity of all but the neighbouring nodes
        d = d3.select(this).node().__data__;
        node.style("opacity", function (o) {
            return neighboring(d, o) | neighboring(o, d) ? 1 : 0.1;
        });

        link.style("opacity", function (o) {
            return d.index==o.source.index | d.index==o.target.index ? 1 : 0.1;
        });

        //Reduce the op

        toggle = 1;
    } else {
        //Put them back to opacity=1
        node.style("opacity", 1);
        link.style("opacity", 1);
        toggle = 0;
    }
  }

/*
d3.json("newsGraph.json", function(error, graph) {
  testGraph = JSON.parse(JSON.stringify(graph))

  selectedList = ['up','police','china','labor','union'];
  selectedData1 = $.map(testGraph.nodes, function(element){
      return ($.inArray(element.name,selectedList)>-1?element:null);
    });

  selectedData2 = $.map(testGraph.links, function(element){
      return ($.inArray(element['name1'],selectedList)>-1?element:null);
    });

  selectedData3 = $.map(selectedData2, function(element){
      return ($.inArray(element.name2,selectedList)>-1?element:null);
    });

  new_graph = {};
  new_graph['nodes'] = graph.nodes;
  new_graph['links'] = selectedData3;

  //drawGraph(graph, selectedData1, selectedData3);
  drawGraph(graph);

});
*/

<|endoftext|>