<commit_before>#!/usr/bin/env node

'use strict'

var utils = require('./utils'),
    fs = require('fs'),
    path = require('path'),
    esprima = require('esprima'),
    escodegen = require('escodegen'),
    ast = require('./ast'),
    q = require('q'),

    SRC_DIR = path.join( __dirname, 'src' ),
    EXERCISES_DIR = path.join( SRC_DIR, 'exercises' ),
    STARTER_REPO_DIR = path.join( SRC_DIR, 'starter_repo' ),
    REPO_TMP = path.join( STARTER_REPO_DIR, 'template' ),
    REPO_CONTENTS = path.join( STARTER_REPO_DIR, 'contents' ),
    RESOURCES_DIR_NAME = 'resources',

    GEN_DIR = path.join( __dirname, 'exercises' ),
    REPO_DIR_NAME = 'starting.git',
    MACHINES_FILE = path.join( __dirname, 'machines.js' ),
    VIEWERS_FILE = path.join( __dirname, 'viewers.js' ),
    REPOS_FILE = path.join( __dirname, 'repos.js' ),

    ANGLER_URL = 'http://localhost/hooks'

function createNewRepo( repoDir ) {
    var git = utils.git.bind.bind( utils.git, null, repoDir )

    return utils.cp( REPO_CONTENTS, repoDir )
    .then( utils.git.bind( null, __dirname, 'init', [ '--template=' + REPO_TMP, repoDir ] ) )
    .then( git( 'config', [ 'angler.url', ANGLER_URL ] ) )
    .then( git( 'config', [ 'receive.denyCurrentBranch', 'false' ] ) )
    .then( git( 'add', ':/' ) )
}

function createExerciseDir( exercise ) {
    // copy the exercise resources into the output dir
    var resourcesDir = path.join( EXERCISES_DIR, exercise, RESOURCES_DIR_NAME ),
        exerciseName = exercise.substring( exercise.indexOf('-') + 1 ),
        outputDir = path.join( GEN_DIR, exerciseName ),
        repoPath = path.join( outputDir, REPO_DIR_NAME ),

        pending = [
            q.nfcall( fs.stat, resourcesDir )
            .then( function() {
                // ugly. fix this
                return q.nfcall( fs.readdir, resourcesDir )
                .then( function( files ) {
                    return q.all( files.map( function( file ) {
                        return utils.cp( path.join( resourcesDir, file ), outputDir )
                    }) )
                })
            })
            .catch(function() {}),
            createNewRepo( repoPath )
        ]

    return q.all( pending )
}

// npm replaces all .gitignores with .npmignores on install. fix this.
function replaceNPMIgnores( src ) {
    return q.nfcall( fs.stat, src )
    .then( function( stats ) {
        if ( stats.isDirectory() ) {
            return q.nfcall( fs.readdir, src )
            .then( function( files ) {
                return q.all( files.map( function( file ) {
                    return replaceNPMIgnores( path.join( src, file ) )
                }) )
            })
        } else if ( path.basename( src ) === '.npmignore' ) {
            return q.nfcall( fs.rename, src, path.join( path.dirname( src ), '.gitignore' ) )
        }
    })
}

replaceNPMIgnores( SRC_DIR )
.then( utils.getExercises )
.done( function( exerciseConfs ) {
    return q.nfcall( fs.mkdir, GEN_DIR )
    .done( function() {
        var exercises = Object.keys( exerciseConfs ),
            orderRe = /^([0-9]+)-/,
            orderedExercises = exercises.filter( function( ex ) {
                    return orderRe.test( ex ) // hide unordered exercises
                }).sort( function( ex1, ex2 ) {
                    var getOrder = function( ex ) { return parseInt( orderRe.exec( ex )[1] ) },
                        ex1Order = getOrder( ex1 ),
                        ex2Order = getOrder( ex2 )
                    return ex1Order < ex2Order ? -1 : 1
                }).map( function( ex ) {
                    return ast.createLiteral( ex.substring( ex.indexOf('-') + 1 ) )
                }),
            machines = [],
            viewers = [ ast.createProperty( '_order', ast.createArray( orderedExercises ) ) ],
            repos = [],
            outputDir,
            writeMod = function( file, props ) {
                // outputs a node module that exports an object of submodules
                var mod = ast.createModule( null, ast.createObject( props ) )
                fs.writeFile( file, escodegen.generate( mod ) )
            }

        // split the configs
        exercises.forEach( function( exercise ) {
            require( exerciseConfs[ exercise ].path ) // check for syntax errors
            var exerciseName = exercise.substring( exercise.indexOf('-') + 1 ),
                confAst = esprima.parse( exerciseConfs[ exercise ].data ), // config's parse tree
                combinedScopeExprs = ast.getCombinedScopeExprs( confAst ), // defs at top of file
                confTrees = ast.getConfSubtrees( confAst ), // machine, viewer, repo
                mkConfSubmodule = function( confAst ) {
                    /* a submodule takes the following form:
                       function() {
                         var privateVars = 'go here'
                         return publicExport // usually an object
                       }
                     */
                    var submodule = ast.createSubmodule( combinedScopeExprs, confAst )
                    return ast.createProperty( exerciseName, submodule )
                }

            // make the output directory
            outputDir = path.join( GEN_DIR, exerciseName )
            q.nfcall( fs.mkdir, outputDir )
            .done( createExerciseDir.bind( null, exercise ) )

            machines.push( mkConfSubmodule( confTrees.machine ) )
            viewers.push( mkConfSubmodule( confTrees.viewer ) )
            repos.push( mkConfSubmodule( confTrees.repo || ast.createObject([]) ) )
        })

        // write out the split configs
        writeMod( MACHINES_FILE, machines )
        writeMod( VIEWERS_FILE, viewers )
        writeMod( REPOS_FILE, repos )
    })
})
<commit_msg>updated for Node 12; some error handling<commit_after>#!/usr/bin/env node

'use strict'

var utils = require('./utils'),
    fs = require('fs'),
    path = require('path'),
    esprima = require('esprima'),
    escodegen = require('escodegen'),
    ast = require('./ast'),
    q = require('q'),

    SRC_DIR = path.join( __dirname, 'src' ),
    EXERCISES_DIR = path.join( SRC_DIR, 'exercises' ),
    STARTER_REPO_DIR = path.join( SRC_DIR, 'starter_repo' ),
    REPO_TMP = path.join( STARTER_REPO_DIR, 'template' ),
    REPO_CONTENTS = path.join( STARTER_REPO_DIR, 'contents' ),
    RESOURCES_DIR_NAME = 'resources',

    GEN_DIR = path.join( __dirname, 'exercises' ),
    REPO_DIR_NAME = 'starting.git',
    MACHINES_FILE = path.join( __dirname, 'machines.js' ),
    VIEWERS_FILE = path.join( __dirname, 'viewers.js' ),
    REPOS_FILE = path.join( __dirname, 'repos.js' ),

    ANGLER_URL = 'http://localhost/hooks'

function createNewRepo( repoDir ) {
    var git = utils.git.bind.bind( utils.git, null, repoDir )

    return utils.cp( REPO_CONTENTS, repoDir )
    .then( utils.git.bind( null, __dirname, 'init', [ '--template=' + REPO_TMP, repoDir ] ) )
    .then( git( 'config', [ 'angler.url', ANGLER_URL ] ) )
    .then( git( 'config', [ 'receive.denyCurrentBranch', 'false' ] ) )
    .then( git( 'add', ':/' ) )
}

function createExerciseDir( exercise ) {
    // copy the exercise resources into the output dir
    var resourcesDir = path.join( EXERCISES_DIR, exercise, RESOURCES_DIR_NAME ),
        exerciseName = exercise.substring( exercise.indexOf('-') + 1 ),
        outputDir = path.join( GEN_DIR, exerciseName ),
        repoPath = path.join( outputDir, REPO_DIR_NAME ),

        pending = [
            q.nfcall( fs.stat, resourcesDir )
            .then( function() {
                // ugly. fix this
                return q.nfcall( fs.readdir, resourcesDir )
                .then( function( files ) {
                    return q.all( files.map( function( file ) {
                        return utils.cp( path.join( resourcesDir, file ), outputDir )
                    }) )
                })
            })
            .catch(function() {}),
            createNewRepo( repoPath )
        ]

    return q.all( pending )
}

// npm replaces all .gitignores with .npmignores on install. fix this.
function replaceNPMIgnores( src ) {
    return q.nfcall( fs.stat, src )
    .then( function( stats ) {
        if ( stats.isDirectory() ) {
            return q.nfcall( fs.readdir, src )
            .then( function( files ) {
                return q.all( files.map( function( file ) {
                    return replaceNPMIgnores( path.join( src, file ) )
                }) )
            })
        } else if ( path.basename( src ) === '.npmignore' ) {
            return q.nfcall( fs.rename, src, path.join( path.dirname( src ), '.gitignore' ) )
        }
    })
}

replaceNPMIgnores( SRC_DIR )
.then( utils.getExercises )
.done( function( exerciseConfs ) {
    return q.nfcall( fs.mkdir, GEN_DIR, { recursive: true })
    .done( function() {
        var exercises = Object.keys( exerciseConfs ),
            orderRe = /^([0-9]+)-/,
            orderedExercises = exercises.filter( function( ex ) {
                    return orderRe.test( ex ) // hide unordered exercises
                }).sort( function( ex1, ex2 ) {
                    var getOrder = function( ex ) { return parseInt( orderRe.exec( ex )[1] ) },
                        ex1Order = getOrder( ex1 ),
                        ex2Order = getOrder( ex2 )
                    return ex1Order < ex2Order ? -1 : 1
                }).map( function( ex ) {
                    return ast.createLiteral( ex.substring( ex.indexOf('-') + 1 ) )
                }),
            machines = [],
            viewers = [ ast.createProperty( '_order', ast.createArray( orderedExercises ) ) ],
            repos = [],
            outputDir,
            writeMod = function( file, props ) {
                // outputs a node module that exports an object of submodules
                var mod = ast.createModule( null, ast.createObject( props ) )
                fs.writeFile( file, escodegen.generate( mod ), (err) => { if (err) console.error(err); })
            }

        // split the configs
        exercises.forEach( function( exercise ) {
            require( exerciseConfs[ exercise ].path ) // check for syntax errors
            var exerciseName = exercise.substring( exercise.indexOf('-') + 1 ),
                confAst = esprima.parse( exerciseConfs[ exercise ].data ), // config's parse tree
                combinedScopeExprs = ast.getCombinedScopeExprs( confAst ), // defs at top of file
                confTrees = ast.getConfSubtrees( confAst ), // machine, viewer, repo
                mkConfSubmodule = function( confAst ) {
                    /* a submodule takes the following form:
                       function() {
                         var privateVars = 'go here'
                         return publicExport // usually an object
                       }
                     */
                    var submodule = ast.createSubmodule( combinedScopeExprs, confAst )
                    return ast.createProperty( exerciseName, submodule )
                }

            // make the output directory
            outputDir = path.join( GEN_DIR, exerciseName )
            q.nfcall( fs.mkdir, outputDir )
            .done( createExerciseDir.bind( null, exercise ) )

            machines.push( mkConfSubmodule( confTrees.machine ) )
            viewers.push( mkConfSubmodule( confTrees.viewer ) )
            repos.push( mkConfSubmodule( confTrees.repo || ast.createObject([]) ) )
        })

        // write out the split configs
        writeMod( MACHINES_FILE, machines )
        writeMod( VIEWERS_FILE, viewers )
        writeMod( REPOS_FILE, repos )
    })
})
<|endoftext|>


<commit_before>const settings = require('electron').remote.require('electron-settings');

function get_configs(){

	var configs = settings.get("configs");

	if (! configs){
		configs = {};
	}

	return configs;
}

// Y U NO WORK?

function set_named_config(name, config){

	var configs = get_configs();
	configs[name] = config;

	console.log("SET " + name);
	console.log(configs);

	settings.set("configs", configs);
}

function get_named_config(name){

	var configs = get_configs();
	return configs[name];
}

function remove_named_config(name){

	var configs = get_configs();
	del(configs[name]);

	settings.set("configs", configs);
}

function save_settings(){

	var api_key = document.getElementById("api_key");
	api_key = api_key.value;

	var endpoint = document.getElementById("endpoint");
	endpoint = endpoint.value;

	var name = document.getElementById("name");
	name = name.value;

	api_key = api_key.trim();
	endpoint = endpoint.trim();
	name = name.trim();

	// PLEASE VALIDATE ME HERE...

	var config = {
		"api_key": api_key,
		"endpoint": endpoint
	};

	set_named_config(name, config);

	var is_default = document.getElementById("default");

	if (is_default.checked){
		settings.set("default", name);
	}

	else if (settings.get("default") == name){
		settings.set("default", null);
	}

	else {}

	settings.set("current", name);

	reload_settings();
	return false;
}

function delete_settings(){

	var name = document.getElementById("name");
	name = name.value;

	var msg = "Are you sure you want to remove the API settings named '" + name + "' ?";

	if (! confirm(msg)){
		return false;
	}

	remove_named_config(name);
	reload_settings();
}

function load_settings(name){

	var config = get_named_config(name);
	console.log(name);
	console.log(config);

	var name_el = document.getElementById("name");
	name_el.setAttribute("disabled", "disabled");
	name_el.value = name;

	var endpoint_el = document.getElementById("endpoint");
	endpoint_el.value = config.endpoint;

	var key_el = document.getElementById("api_key");
	key_el.value = config.api_key;

	var is_default = document.getElementById("default");
	is_default.checked = (settings.get("default") == name) ? true : false;

	var delete_button = document.getElementById("settings-remove");
	delete_button.style.display = "inline";

	delete_button.onclick = function(){

		try {
			delete_settings();
		} catch (e) {
			console.log(e);
		}

		return false;
	};
}

function new_settings(){

	var name_el = document.getElementById("name");
	name_el.removeAttribute("disabled");
	name_el.value = "";

	var endpoint_el = document.getElementById("endpoint");
	endpoint_el.value = "";

	var key_el = document.getElementById("api_key");
	key_el.value = "";

	var is_default = document.getElementById("default");
	is_default.checked = false;
}

function reload_settings(){

	console.log("RELOAD");

	var configs = get_configs();
	var config_names = [];

	console.log(configs);
	for (name in configs){
		console.log(name);
		config_names.push(name);
	}

	config_names.sort();
	console.log(config_names);

	var default_config = settings.get("default");

	var count = config_names.length;

	var select = document.getElementById("settings-select");
	select.innerHTML = "";

	if (count) {

		for (var i=0; i < count; i++){

			var name = config_names[i];

			var option = document.createElement("option");
			option.setAttribute("value", name);
			option.appendChild(document.createTextNode(name));

			if (name == default_config){
				option.setAttribute("selected", "selected");
			}

			select.appendChild(option);
			select.onchange = function(e){

				var el = e.target;
				var name = el.options[el.selectedIndex].value;

				if (name == -1){
					new_settings();
					return;
				}

				load_settings(name);

				settings.set("current", name);
			};
		}

		var option = document.createElement("option");
		option.setAttribute("value", -1);
		option.appendChild(document.createTextNode("create new settings"));

		select.appendChild(option);
		select.style.display = "inline";

		if (default_config){
			load_settings(default_config);
		}

		else {
			load_settings(config_names[0]);
		}
	}

	else {

		var endpoint_el = document.getElementById("endpoint");
		var name_el = document.getElementById("name");

		endpoint_el.value = "https://whosonfirst-api.mapzen.com";
		name_el.value = "default";

		select.style.display = "none";
	}

	var save_button = document.getElementById("settings-save");
	save_button.onclick = function(){

		try {
			save_settings();
		} catch (e) {
			console.log(e);
		}

		return false;
	}
}

reload_settings();

// console.log(settings.getAll())
<commit_msg>make setting multiple configs work<commit_after>const settings = require('electron').remote.require('electron-settings');

function get_configs(){

	var configs = settings.get("configs");

	if (! configs){
		configs = {};
	}

	return configs;
}

function set_named_config(name, config){

	var configs = get_configs();
	configs[name] = config;

	// https://github.com/nathanbuchar/electron-settings/wiki/API-documentation#set

	for (k in config) {

		var path = [ "configs", name, k ];
		path = path.join(".");

		settings.set(path, config[k]);
	}
}

function get_named_config(name){

	var path = [ "configs", name ];
	path = path.join(".");

	return settings.get(path);
}

function remove_named_config(name){

	var configs = get_configs();
	del(configs[name]);

	var path = [ "configs", name ];
	path = path.join(".");

	settings.delete(path);
}

function save_settings(){

	var api_key = document.getElementById("api_key");
	api_key = api_key.value;

	var endpoint = document.getElementById("endpoint");
	endpoint = endpoint.value;

	var name = document.getElementById("name");
	name = name.value;

	api_key = api_key.trim();
	endpoint = endpoint.trim();
	name = name.trim();

	// PLEASE VALIDATE ME HERE...

	var config = {
		"api_key": api_key,
		"endpoint": endpoint
	};

	set_named_config(name, config);

	var is_default = document.getElementById("default");

	if (is_default.checked){
		settings.set("default", name);
	}

	else if (settings.get("default") == name){
		settings.set("default", null);
	}

	else {}

	settings.set("current", name);

	reload_settings();
	return false;
}

function delete_settings(){

	var name = document.getElementById("name");
	name = name.value;

	var msg = "Are you sure you want to remove the API settings named '" + name + "' ?";

	if (! confirm(msg)){
		return false;
	}

	remove_named_config(name);
	reload_settings();
}

function load_settings(name){

	var config = get_named_config(name);

	var name_el = document.getElementById("name");
	name_el.setAttribute("disabled", "disabled");
	name_el.value = name;

	var endpoint_el = document.getElementById("endpoint");
	endpoint_el.value = config.endpoint;

	var key_el = document.getElementById("api_key");
	key_el.value = config.api_key;

	var is_default = document.getElementById("default");
	is_default.checked = (settings.get("default") == name) ? true : false;

	var delete_button = document.getElementById("settings-remove");
	delete_button.style.display = "inline";

	delete_button.onclick = function(){

		try {
			delete_settings();
		} catch (e) {
			console.log(e);
		}

		return false;
	};
}

function new_settings(){

	var name_el = document.getElementById("name");
	name_el.removeAttribute("disabled");
	name_el.value = "";

	var endpoint_el = document.getElementById("endpoint");
	endpoint_el.value = "";

	var key_el = document.getElementById("api_key");
	key_el.value = "";

	var is_default = document.getElementById("default");
	is_default.checked = false;
}

function reload_settings(){

	var configs = get_configs();
	var config_names = [];

	for (name in configs){
		config_names.push(name);
	}

	config_names.sort();
	var count = config_names.length;

	var default_config = settings.get("default");

	var select = document.getElementById("settings-select");
	select.innerHTML = "";

	if (count) {

		for (var i=0; i < count; i++){

			var name = config_names[i];

			var option = document.createElement("option");
			option.setAttribute("value", name);
			option.appendChild(document.createTextNode(name));

			if (name == default_config){
				option.setAttribute("selected", "selected");
			}

			select.appendChild(option);
			select.onchange = function(e){

				var el = e.target;
				var name = el.options[el.selectedIndex].value;

				if (name == -1){
					new_settings();
					return;
				}

				load_settings(name);

				settings.set("current", name);
			};
		}

		var option = document.createElement("option");
		option.setAttribute("value", -1);
		option.appendChild(document.createTextNode("create new settings"));

		select.appendChild(option);
		select.style.display = "inline";

		if (default_config){
			load_settings(default_config);
		}

		else {
			load_settings(config_names[0]);
		}
	}

	else {

		var endpoint_el = document.getElementById("endpoint");
		var name_el = document.getElementById("name");

		endpoint_el.value = "https://whosonfirst-api.mapzen.com";
		name_el.value = "default";

		select.style.display = "none";
	}

	var save_button = document.getElementById("settings-save");
	save_button.onclick = function(){

		try {
			save_settings();
		} catch (e) {
			console.log(e);
		}

		return false;
	}
}

reload_settings();

// console.log(settings.getAll())
<|endoftext|>


<commit_before>/**
 * Copyright 2013 Bill McDowell
 *
 * This file is part of theMess (https://github.com/forkunited/theMess)
 *
 * Licensed under the Apache License, Version 2.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.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */
function TagSearchMenuItem(tagSearchMenu, currentUser, messStore, tag) {
	var that = this;

	this.MAX_NAME_LENGTH = 24;

	this.SELECT_STATE_SELECTED = 0;
	this.SELECT_STATE_UNSELECTED = 1;
	this.SELECT_STATE_SELECTING = 2;

	this.DOM_CLASS = 'tagSearchMenuItem';
	this.DOM_HIGHLIGHTED_CLASS = 'tagSearchMenuItemHighlighted';
	this.DOM_LEFT_CLASS = 'tagSearchMenuItemLeft';
	this.DOM_RIGHT_CLASS = 'tagSearchMenuItemRight';
	this.DOM_TEXT_CLASS = 'tagSearchMenuItemText';
	this.DOM_SUBTEXT_CLASS = 'tagSearchMenuItemSubtext';
	this.DOM_TEXT_SELECTED_CLASS = 'tagSearchMenuItemTextSelected';
	this.DOM_SUBTEXT_SELECTED_CLASS = 'tagSearchMenuItemSubtextSelected';
	this.DOM_OPTIONS_CLASS = 'tagSearchMenuItemOptions';
	this.DOM_DELETE_CLASS = 'tagSearchMenuItemDelete';
	this.DOM_SELECT_CLASS = 'tagSearchMenuItemSelect';
	this.DOM_SELECT_INPUT_CLASS = 'tagSearchMenuItemSelectInput';

	var element = document.createElement('div');
	var leftElement = document.createElement('div');
	var rightElement = document.createElement('div');
	var textElement = document.createElement('div');
	var subtextElement = document.createElement('div');
	var optionsElement = document.createElement('div');
	var deleteElement = document.createElement('div');
	var selectElement = document.createElement('div');
	var selectInputElement = document.createElement('input');
	var optionsLinkElement = document.createElement('a');
	var deleteLinkElement = document.createElement('a');

	var editable = false;
	var mainSelectable = false;
	var selectable = true;
	var mainSelected = false;
	var highlighted = false;
	var disabled = false;

	var selected = that.SELECT_STATE_UNSELECTED;

	var defaultColor = "";

	constructInterfaceElements();

	function constructInterfaceElements() {
		/* Set Attributes */
		element.setAttribute('class', that.DOM_CLASS);
		leftElement.setAttribute('class', that.DOM_LEFT_CLASS);
		rightElement.setAttribute('class', that.DOM_RIGHT_CLASS);
		textElement.setAttribute('class', that.DOM_TEXT_CLASS);
		subtextElement.setAttribute('class', that.DOM_SUBTEXT_CLASS);
		optionsElement.setAttribute('class', that.DOM_OPTIONS_CLASS);
		deleteElement.setAttribute('class', that.DOM_DELETE_CLASS);
		selectElement.setAttribute('class', that.DOM_SELECT_CLASS);
		selectInputElement.setAttribute('class', that.DOM_SELECT_INPUT_CLASS);

		element.setAttribute('id', that.DOM_CLASS + "_" + tag.id);
		leftElement.setAttribute('id', that.DOM_LEFT_CLASS + "_" + tag.id);
		rightElement.setAttribute('id', that.DOM_RIGHT_CLASS + "_" + tag.id);
		textElement.setAttribute('id', that.DOM_TEXT_CLASS + "_" + tag.id);
		subtextElement.setAttribute('id', that.DOM_SUBTEXT_CLASS + "_" + tag.id);
		optionsElement.setAttribute('id', that.DOM_OPTIONS_CLASS + "_" + tag.id);
		deleteElement.setAttribute('id', that.DOM_DELETE_CLASS + "_" + tag.id);
		selectElement.setAttribute('id', that.DOM_SELECT_CLASS + "_" + tag.id);
		selectInputElement.setAttribute('id', that.DOM_SELECT_INPUT_CLASS + "_" + tag.id);

		selectInputElement.setAttribute('type', 'checkbox');

		textElement.innerHTML = getTagName();

		subtextElement.innerHTML = ' (' + tag.creatorUserId + ')';
		deleteLinkElement.innerHTML = '[Delete]';
		optionsLinkElement.innerHTML = '[Edit]';

		/* Set up hierarchy */
		element.appendChild(leftElement);
		element.appendChild(rightElement);
		leftElement.appendChild(textElement);
		leftElement.appendChild(subtextElement);
		rightElement.appendChild(selectElement);
		rightElement.appendChild(optionsElement);
		rightElement.appendChild(deleteElement);
		optionsElement.appendChild(optionsLinkElement);
		selectElement.appendChild(selectInputElement);
		deleteElement.appendChild(deleteLinkElement);

		/* Set interactivity */
		element.onmouseover = elementMouseOverHandler;
		element.onmouseout = elementMouseOutHandler;
		element.onclick = elementClickHandler;
		optionsLinkElement.onclick = optionsLinkClickHandler;
		deleteLinkElement.onclick = deleteLinkClickHandler;
		selectInputElement.onclick = selectInputClickHandler;

		defaultColor = element.style.backgroundColor;
	}

	function getTagName() {
		if (tag.name.length <= that.MAX_NAME_LENGTH) {
			return tag.name;
		} else {
			return tag.name.substring(0, that.MAX_NAME_LENGTH - 3) + "...";
		}
	}

	/* Interactivity handlers */

	that.storeMessageHandler = function(message) {
		if (message.messageType == LocalStorageMessage.SELECT_TAG) {
			if (message.id == tag.id) {
				that.setSelecting();
			}
		} else if (message.messageType == LocalStorageMessage.DESELECT_TAG) {
			if (message.id == tag.id) {
				that.setUnselected();
			}
		} else if (message.messageType == LocalStorageMessage.RETRIEVE_ADD_TAG) {
			if (selected == that.SELECT_STATE_SELECTING && message.tag.id == tag.id) {
				tag = message.tag;
				that.setSelected();
			}
		} else if (message.messageType == LocalStorageMessage.FINISH_SAVE) {
			/* ? */
		} else if (message.messageType == LocalStorageMessage.START_SAVE) {
			if (editable)
				setDeletable();
		}
	}

	function elementMouseOverHandler() {
		that.setHighlighted();
	}

	function elementMouseOutHandler() {
		that.setUnhighlighted();
	}

	function elementClickHandler() {
		if (mainSelectable) {
			if (!mainSelected)
				that.setMainSelected();
		} else if (selectable) {
			if (selected != that.SELECT_STATE_SELECTED)
				messStore.selectTag(tag.id);
			else if (selected != that.SELECT_STATE_UNSELECTED)
				messStore.deselectTag(tag.id);
		}
	}

	function optionsLinkClickHandler() {
		tagSearchMenu.setTagEditMenu(tag);
	}

	function deleteLinkClickHandler() {
		textElement.innerHTML = 'Removing ' + getTagName() + '...';
		that.hideSubtext();
		tagSearchMenu.setTagEditMenu();

		messStore.removeTag(tag.id, true);
		if (selected == that.SELECT_STATE_SELECTED)
			messStore.deselectTag(tag.id);
		that.setUneditable();
	}

	function selectInputClickHandler() {
		if (selected == that.SELECT_STATE_SELECTED)
			messStore.deselectTag(tag.id);
		else
			messStore.selectTag(tag.id);
	}

	/* Getters and setters */

	this.getElement = function() {
		return element;
	}

	this.getTag = function() {
		return tag;
	}

	this.getSelected = function() {
		return selected;
	}

	this.setSelected = function() {
		if (disabled)
			return;

		if (!messStore.getTag(tag.id))
			return;

		that.showSubtext();
		that.setUnhighlighted();
		textElement.innerHTML = getTagName();

		var tagColor = messStore.getTagColor(tag.id);
		element.style.backgroundColor = tagColor;

		textElement.setAttribute('class', that.DOM_TEXT_SELECTED_CLASS);
		subtextElement.setAttribute('class', that.DOM_SUBTEXT_SELECTED_CLASS);

		selected = that.SELECT_STATE_SELECTED;
	}

	this.setUnselected = function() {
		if (disabled)
			return;

		that.setUnhighlighted();
		that.setUnmainSelected();
		textElement.innerHTML = getTagName();
		element.style.backgroundColor = defaultColor;

		textElement.setAttribute('class', that.DOM_TEXT_CLASS);
		subtextElement.setAttribute('class', that.DOM_SUBTEXT_CLASS);

		selected = that.SELECT_STATE_UNSELECTED;
	}

	this.setSelecting = function() {
		textElement.innerHTML = 'Selecting ' + getTagName() + '...';
		that.hideSubtext();
		selected = that.SELECT_STATE_SELECTING;
	}

	this.getMainSelected = function() {
		return mainSelected;
	}

	this.setMainSelected = function() {
		if (disabled)
			return;

		if (!mainSelectable || selected != that.SELECT_STATE_SELECTED)
			return;

		tagSearchMenu.setAllUnmainSelected();
		messStore.selectMainTag(tag.id);
		textElement.style.fontWeight = "bold";
		mainSelected = true;
	}

	this.setUnmainSelected = function() {
		if (disabled)
			return;

		if (!mainSelectable || selected != that.SELECT_STATE_SELECTED)
			return;
		if (mainSelected)
			messStore.selectMainTag(undefined);
		textElement.style.fontWeight = "normal";
		mainSelected = false;
	}

	this.setHighlighted = function() {
		if (disabled)
			return;

		if (selected != that.SELECT_STATE_UNSELECTED)
			return;
		element.setAttribute('class', that.DOM_HIGHLIGHTED_CLASS);
	}

	this.setUnhighlighted = function() {
		if (disabled)
			return;

		if (selected != that.SELECT_STATE_UNSELECTED)
			return;
		element.setAttribute('class', that.DOM_CLASS);
	}

	this.setEditable = function() {
		if (disabled)
			return;

		if (!tag.writeAccess)
			return;

		setDeletable();
		optionsElement.style.visibility = "visible";
		editable = true;
	}

	this.setUneditable = function() {
		if (disabled)
			return;

		setUndeletable();
		optionsElement.style.visibility = "hidden";
		editable = false;
	}

	this.setMainSelectable = function() {
		if (disabled)
			return;

		if (!tag.writeAccess || !selectable)
			return;

		selectInputElement.style.visibility = "visible";
		selectInputElement.checked = true;
		mainSelectable = true;
	}

	this.setUnmainSelectable = function() {
		if (disabled)
			return;

		selectInputElement.style.visibility = "hidden";
		mainSelectable = false;
	}

	this.setSelectable = function() {
		if (disabled)
			return;

		selectable = true;
	}

	this.setUnselectable = function() {
		if (disabled)
			return;

		selectable = false;
	}

	this.hideSubtext = function() {
		subtextElement.style.visibility = "hidden";
	}

	this.showSubtext = function() {
		subtextElement.style.visibility = "visible";
	}

	function setDeletable() {
		if (disabled)
			return;

		if (!tag.writeAccess || selected != that.SELECT_STATE_SELECTED || !messStore.getTag(tag.id) || messStore.getTag(tag.id).nodeCount != 0) {
			setUndeletable();
			return;
		}
		deleteElement.style.visibility = "visible";
	}

	function setUndeletable() {
		if (disabled)
			return;

		deleteElement.style.visibility = "hidden";
	}

	this.disable = function() {
		disabled = true;

		optionsElement.style.visibility = "hidden";
		deleteElement.style.visibility = "hidden";
		selectInputElement.style.visibility = "hidden";
	}

	this.enable = function() {
		disabled = false;
		if (editable)
			that.setEditable();
		if (mainSelectable)
			that.setMainSelectable();
	}

	/* Defaults */
	that.setUneditable();
	that.setUnmainSelectable();
	messStore.addLocalMessageHandler(that.storeMessageHandler);
}<commit_msg>Fixed tag name in tag menu<commit_after>/**
 * Copyright 2013 Bill McDowell
 *
 * This file is part of theMess (https://github.com/forkunited/theMess)
 *
 * Licensed under the Apache License, Version 2.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.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */
function TagSearchMenuItem(tagSearchMenu, currentUser, messStore, tag) {
	var that = this;

	this.MAX_NAME_LENGTH = 24;

	this.SELECT_STATE_SELECTED = 0;
	this.SELECT_STATE_UNSELECTED = 1;
	this.SELECT_STATE_SELECTING = 2;

	this.DOM_CLASS = 'tagSearchMenuItem';
	this.DOM_HIGHLIGHTED_CLASS = 'tagSearchMenuItemHighlighted';
	this.DOM_LEFT_CLASS = 'tagSearchMenuItemLeft';
	this.DOM_RIGHT_CLASS = 'tagSearchMenuItemRight';
	this.DOM_TEXT_CLASS = 'tagSearchMenuItemText';
	this.DOM_SUBTEXT_CLASS = 'tagSearchMenuItemSubtext';
	this.DOM_TEXT_SELECTED_CLASS = 'tagSearchMenuItemTextSelected';
	this.DOM_SUBTEXT_SELECTED_CLASS = 'tagSearchMenuItemSubtextSelected';
	this.DOM_OPTIONS_CLASS = 'tagSearchMenuItemOptions';
	this.DOM_DELETE_CLASS = 'tagSearchMenuItemDelete';
	this.DOM_SELECT_CLASS = 'tagSearchMenuItemSelect';
	this.DOM_SELECT_INPUT_CLASS = 'tagSearchMenuItemSelectInput';

	var element = document.createElement('div');
	var leftElement = document.createElement('div');
	var rightElement = document.createElement('div');
	var textElement = document.createElement('div');
	var subtextElement = document.createElement('div');
	var optionsElement = document.createElement('div');
	var deleteElement = document.createElement('div');
	var selectElement = document.createElement('div');
	var selectInputElement = document.createElement('input');
	var optionsLinkElement = document.createElement('a');
	var deleteLinkElement = document.createElement('a');

	var editable = false;
	var mainSelectable = false;
	var selectable = true;
	var mainSelected = false;
	var highlighted = false;
	var disabled = false;

	var selected = that.SELECT_STATE_UNSELECTED;

	var defaultColor = "";

	constructInterfaceElements();

	function constructInterfaceElements() {
		/* Set Attributes */
		element.setAttribute('class', that.DOM_CLASS);
		leftElement.setAttribute('class', that.DOM_LEFT_CLASS);
		rightElement.setAttribute('class', that.DOM_RIGHT_CLASS);
		textElement.setAttribute('class', that.DOM_TEXT_CLASS);
		subtextElement.setAttribute('class', that.DOM_SUBTEXT_CLASS);
		optionsElement.setAttribute('class', that.DOM_OPTIONS_CLASS);
		deleteElement.setAttribute('class', that.DOM_DELETE_CLASS);
		selectElement.setAttribute('class', that.DOM_SELECT_CLASS);
		selectInputElement.setAttribute('class', that.DOM_SELECT_INPUT_CLASS);

		element.setAttribute('id', that.DOM_CLASS + "_" + tag.id);
		leftElement.setAttribute('id', that.DOM_LEFT_CLASS + "_" + tag.id);
		rightElement.setAttribute('id', that.DOM_RIGHT_CLASS + "_" + tag.id);
		textElement.setAttribute('id', that.DOM_TEXT_CLASS + "_" + tag.id);
		subtextElement.setAttribute('id', that.DOM_SUBTEXT_CLASS + "_" + tag.id);
		optionsElement.setAttribute('id', that.DOM_OPTIONS_CLASS + "_" + tag.id);
		deleteElement.setAttribute('id', that.DOM_DELETE_CLASS + "_" + tag.id);
		selectElement.setAttribute('id', that.DOM_SELECT_CLASS + "_" + tag.id);
		selectInputElement.setAttribute('id', that.DOM_SELECT_INPUT_CLASS + "_" + tag.id);

		selectInputElement.setAttribute('type', 'checkbox');

		textElement.innerHTML = getTagName();

		subtextElement.innerHTML = ' (' + tag.creatorUserId + ')';
		deleteLinkElement.innerHTML = '[Delete]';
		optionsLinkElement.innerHTML = '[Edit]';

		/* Set up hierarchy */
		element.appendChild(leftElement);
		element.appendChild(rightElement);
		leftElement.appendChild(textElement);
		leftElement.appendChild(subtextElement);
		rightElement.appendChild(selectElement);
		rightElement.appendChild(optionsElement);
		rightElement.appendChild(deleteElement);
		optionsElement.appendChild(optionsLinkElement);
		selectElement.appendChild(selectInputElement);
		deleteElement.appendChild(deleteLinkElement);

		/* Set interactivity */
		element.onmouseover = elementMouseOverHandler;
		element.onmouseout = elementMouseOutHandler;
		element.onclick = elementClickHandler;
		optionsLinkElement.onclick = optionsLinkClickHandler;
		deleteLinkElement.onclick = deleteLinkClickHandler;
		selectInputElement.onclick = selectInputClickHandler;

		defaultColor = element.style.backgroundColor;
	}

	function getTagName(prefix) {
		var tagName = (prefix) ? prefix + tag.name : tag.name;
		if (tagName.length <= that.MAX_NAME_LENGTH) {
			return tagName;
		} else {
			return tagName.substring(0, that.MAX_NAME_LENGTH - 3) + "...";
		}
	}

	/* Interactivity handlers */

	that.storeMessageHandler = function(message) {
		if (message.messageType == LocalStorageMessage.SELECT_TAG) {
			if (message.id == tag.id) {
				that.setSelecting();
			}
		} else if (message.messageType == LocalStorageMessage.DESELECT_TAG) {
			if (message.id == tag.id) {
				that.setUnselected();
			}
		} else if (message.messageType == LocalStorageMessage.RETRIEVE_ADD_TAG) {
			if (selected == that.SELECT_STATE_SELECTING && message.tag.id == tag.id) {
				tag = message.tag;
				that.setSelected();
			}
		} else if (message.messageType == LocalStorageMessage.FINISH_SAVE) {
			/* ? */
		} else if (message.messageType == LocalStorageMessage.START_SAVE) {
			if (editable)
				setDeletable();
		}
	}

	function elementMouseOverHandler() {
		that.setHighlighted();
	}

	function elementMouseOutHandler() {
		that.setUnhighlighted();
	}

	function elementClickHandler() {
		if (mainSelectable) {
			if (!mainSelected)
				that.setMainSelected();
		} else if (selectable) {
			if (selected != that.SELECT_STATE_SELECTED)
				messStore.selectTag(tag.id);
			else if (selected != that.SELECT_STATE_UNSELECTED)
				messStore.deselectTag(tag.id);
		}
	}

	function optionsLinkClickHandler() {
		tagSearchMenu.setTagEditMenu(tag);
	}

	function deleteLinkClickHandler() {
		textElement.innerHTML = getTagName('Removing ');
		that.hideSubtext();
		tagSearchMenu.setTagEditMenu();

		messStore.removeTag(tag.id, true);
		if (selected == that.SELECT_STATE_SELECTED)
			messStore.deselectTag(tag.id);
		that.setUneditable();
	}

	function selectInputClickHandler() {
		if (selected == that.SELECT_STATE_SELECTED)
			messStore.deselectTag(tag.id);
		else
			messStore.selectTag(tag.id);
	}

	/* Getters and setters */

	this.getElement = function() {
		return element;
	}

	this.getTag = function() {
		return tag;
	}

	this.getSelected = function() {
		return selected;
	}

	this.setSelected = function() {
		if (disabled)
			return;

		if (!messStore.getTag(tag.id))
			return;

		that.showSubtext();
		that.setUnhighlighted();
		textElement.innerHTML = getTagName();

		var tagColor = messStore.getTagColor(tag.id);
		element.style.backgroundColor = tagColor;

		textElement.setAttribute('class', that.DOM_TEXT_SELECTED_CLASS);
		subtextElement.setAttribute('class', that.DOM_SUBTEXT_SELECTED_CLASS);

		selected = that.SELECT_STATE_SELECTED;
	}

	this.setUnselected = function() {
		if (disabled)
			return;

		that.setUnhighlighted();
		that.setUnmainSelected();
		textElement.innerHTML = getTagName();
		element.style.backgroundColor = defaultColor;

		textElement.setAttribute('class', that.DOM_TEXT_CLASS);
		subtextElement.setAttribute('class', that.DOM_SUBTEXT_CLASS);

		selected = that.SELECT_STATE_UNSELECTED;
	}

	this.setSelecting = function() {
		textElement.innerHTML = getTagName('Selecting ');
		that.hideSubtext();
		selected = that.SELECT_STATE_SELECTING;
	}

	this.getMainSelected = function() {
		return mainSelected;
	}

	this.setMainSelected = function() {
		if (disabled)
			return;

		if (!mainSelectable || selected != that.SELECT_STATE_SELECTED)
			return;

		tagSearchMenu.setAllUnmainSelected();
		messStore.selectMainTag(tag.id);
		textElement.style.fontWeight = "bold";
		mainSelected = true;
	}

	this.setUnmainSelected = function() {
		if (disabled)
			return;

		if (!mainSelectable || selected != that.SELECT_STATE_SELECTED)
			return;
		if (mainSelected)
			messStore.selectMainTag(undefined);
		textElement.style.fontWeight = "normal";
		mainSelected = false;
	}

	this.setHighlighted = function() {
		if (disabled)
			return;

		if (selected != that.SELECT_STATE_UNSELECTED)
			return;
		element.setAttribute('class', that.DOM_HIGHLIGHTED_CLASS);
	}

	this.setUnhighlighted = function() {
		if (disabled)
			return;

		if (selected != that.SELECT_STATE_UNSELECTED)
			return;
		element.setAttribute('class', that.DOM_CLASS);
	}

	this.setEditable = function() {
		if (disabled)
			return;

		if (!tag.writeAccess)
			return;

		setDeletable();
		optionsElement.style.visibility = "visible";
		editable = true;
	}

	this.setUneditable = function() {
		if (disabled)
			return;

		setUndeletable();
		optionsElement.style.visibility = "hidden";
		editable = false;
	}

	this.setMainSelectable = function() {
		if (disabled)
			return;

		if (!tag.writeAccess || !selectable)
			return;

		selectInputElement.style.visibility = "visible";
		selectInputElement.checked = true;
		mainSelectable = true;
	}

	this.setUnmainSelectable = function() {
		if (disabled)
			return;

		selectInputElement.style.visibility = "hidden";
		mainSelectable = false;
	}

	this.setSelectable = function() {
		if (disabled)
			return;

		selectable = true;
	}

	this.setUnselectable = function() {
		if (disabled)
			return;

		selectable = false;
	}

	this.hideSubtext = function() {
		subtextElement.style.visibility = "hidden";
	}

	this.showSubtext = function() {
		subtextElement.style.visibility = "visible";
	}

	function setDeletable() {
		if (disabled)
			return;

		if (!tag.writeAccess || selected != that.SELECT_STATE_SELECTED || !messStore.getTag(tag.id) || messStore.getTag(tag.id).nodeCount != 0) {
			setUndeletable();
			return;
		}
		deleteElement.style.visibility = "visible";
	}

	function setUndeletable() {
		if (disabled)
			return;

		deleteElement.style.visibility = "hidden";
	}

	this.disable = function() {
		disabled = true;

		optionsElement.style.visibility = "hidden";
		deleteElement.style.visibility = "hidden";
		selectInputElement.style.visibility = "hidden";
	}

	this.enable = function() {
		disabled = false;
		if (editable)
			that.setEditable();
		if (mainSelectable)
			that.setMainSelectable();
	}

	/* Defaults */
	that.setUneditable();
	that.setUnmainSelectable();
	messStore.addLocalMessageHandler(that.storeMessageHandler);
}<|endoftext|>


<commit_before>/**
 * Display a horizontal listing of clickable OSF4I logos (links to institution landing pages).
 */
'use strict';

var $ = require('jquery');
var m = require('mithril');
var utils = require('js/components/utils');
var required = utils.required;
var lodashChunk  = require('lodash.chunk');

var institutionComps = require('js/components/institution');
var carouselComps = require('js/components/carousel');

var Institution = institutionComps.InstitutionImg;
var Carousel = carouselComps.Carousel;
var CarouselRow = carouselComps.CarouselRow;

var CAROUSEL_WIDTH = 5;
var REDUCED_CAROUSEL_WIDTH = CAROUSEL_WIDTH - 1;
var COLUMN_WIDTH = Math.floor(12 / CAROUSEL_WIDTH);
var LOGO_WIDTH = '120px';

var InstitutionsPanel = {
    controller: function() {
        // Helper method to render logo link
        this.renderLogo = function(inst, opts) {
            var href = '/institutions/' + inst.id + '/';
            var columnWidth = COLUMN_WIDTH.toString();
            return m('.col-sm-' + columnWidth, {style: {'display':'inline-block', 'float':'none'}}, [
                m('a', {href: href, className: 'thumbnail', style: {'background': 'inherit', 'border': 'none'}},
                    [m.component(Institution,
                                {
                                    className: 'img-responsive',
                                    style: {'background-color': 'white'},
                                    name: inst.name,
                                    logoPath: inst.logoPath,
                                    muted: opts.muted,
                                })])
            ]);
        };
    },
    view: function(ctrl, opts) {
        var affiliated = required(opts, 'affiliatedInstitutions');
        var allInstitutions = required(opts, 'allInstitutions');

        var affiliatedIds = affiliated.map(function(inst) { return inst.id; });
        var unaffiliated = allInstitutions.filter(function(inst) {
            return $.inArray(inst.id, affiliatedIds) === -1;
        });

        var institutions = affiliated.concat(unaffiliated);
        var controls = institutions.length > CAROUSEL_WIDTH;
        if (controls && (12 % CAROUSEL_WIDTH) === 0 && CAROUSEL_WIDTH > REDUCED_CAROUSEL_WIDTH) {
            CAROUSEL_WIDTH = REDUCED_CAROUSEL_WIDTH;
        }

        var groupedInstitutions = lodashChunk(institutions, CAROUSEL_WIDTH);
        return m.component(Carousel, {controls: controls},
            groupedInstitutions.map(function(instGroup, idx) {
                var active = idx === 0;
                return m.component(CarouselRow, {active: active}, instGroup.map(function(inst) {return ctrl.renderLogo(inst, {}); }));
            })
        );
    }
};

module.exports = InstitutionsPanel;
<commit_msg>remove unused variable and increase carousel width to 6<commit_after>/**
 * Display a horizontal listing of clickable OSF4I logos (links to institution landing pages).
 */
'use strict';

var $ = require('jquery');
var m = require('mithril');
var utils = require('js/components/utils');
var required = utils.required;
var lodashChunk  = require('lodash.chunk');

var institutionComps = require('js/components/institution');
var carouselComps = require('js/components/carousel');

var Institution = institutionComps.InstitutionImg;
var Carousel = carouselComps.Carousel;
var CarouselRow = carouselComps.CarouselRow;

var CAROUSEL_WIDTH = 6;
var REDUCED_CAROUSEL_WIDTH = CAROUSEL_WIDTH - 1;
var COLUMN_WIDTH = Math.floor(12 / CAROUSEL_WIDTH);

var InstitutionsPanel = {
    controller: function() {
        // Helper method to render logo link
        this.renderLogo = function(inst, opts) {
            var href = '/institutions/' + inst.id + '/';
            var columnWidth = COLUMN_WIDTH.toString();
            return m('.col-sm-' + columnWidth, {style: {'display':'inline-block', 'float':'none'}}, [
                m('a', {href: href, className: 'thumbnail', style: {'background': 'inherit', 'border': 'none'}},
                    [m.component(Institution,
                                {
                                    className: 'img-responsive',
                                    style: {'background-color': 'white'},
                                    name: inst.name,
                                    logoPath: inst.logoPath,
                                    muted: opts.muted,
                                })])
            ]);
        };
    },
    view: function(ctrl, opts) {
        var affiliated = required(opts, 'affiliatedInstitutions');
        var allInstitutions = required(opts, 'allInstitutions');

        var affiliatedIds = affiliated.map(function(inst) { return inst.id; });
        var unaffiliated = allInstitutions.filter(function(inst) {
            return $.inArray(inst.id, affiliatedIds) === -1;
        });

        var institutions = affiliated.concat(unaffiliated);
        var controls = institutions.length > CAROUSEL_WIDTH;
        if (controls && (12 % CAROUSEL_WIDTH) === 0 && CAROUSEL_WIDTH > REDUCED_CAROUSEL_WIDTH) {
            CAROUSEL_WIDTH = REDUCED_CAROUSEL_WIDTH;
        }

        var groupedInstitutions = lodashChunk(institutions, CAROUSEL_WIDTH);
        return m.component(Carousel, {controls: controls},
            groupedInstitutions.map(function(instGroup, idx) {
                var active = idx === 0;
                return m.component(CarouselRow, {active: active}, instGroup.map(function(inst) {return ctrl.renderLogo(inst, {}); }));
            })
        );
    }
};

module.exports = InstitutionsPanel;
<|endoftext|>


<commit_before>var root = __dirname + "/../";
var path = require('path');
var net = require('net');
var util = require('util');
var fluent = require(path.join(root, 'lib/FluentLogger'));
var should = require('should');

var testPort = 24242;
var testHost = '127.0.0.1';

describe('FluentLogger', function() {
  var server;

  beforeEach(function(done) {
    server = new net.Server();
    server.listen(testPort, function() {
      done();
    });
  });

  afterEach(function(done) {
    try { server.close(); } catch(e) {}
    done();
  });

  describe('new instance', function() {
    it('should connect fluentd server', function(done) {
      server.on('connection', function(socket) {
        done();
      });
      new fluent.FluentLogger(testPort, testHost);
    });
  });

  describe('#post()', function() {
    var logger;

    it('should post log', function(done) {
      server.on('connection', function(socket) {
        socket.setEncoding('utf8');
        socket.on('data', function(data) {
          var json = JSON.parse(data);
          json[0].should.eql('test.fluent');
          json[1].should.be.a('number');
          json[2].should.eql({ foo: "bar" });
          done();
        });
      });

      logger = new fluent.FluentLogger(testPort, testHost);
      logger.post('test.fluent', { foo: "bar" });
    });
  });

  describe('retry feature', function() {
    beforeEach(function(done) {
      server.close();
      done();
    });

    it('should be retry if connection was broken', function(done) {
      this.timeout(10000);

      var logger = new fluent.FluentLogger(testPort, testHost);
      var count = 1;

      logger.on('retry', function() {
        util.print(count++);
      });

      logger.on('connect', function() {
        done();
      });

      setTimeout(function() {
        server.listen(testPort);
      }, 8000);
    });
  });

  describe('buffer feature', function() {
    beforeEach(function(done) {
      server.close();
      done();
    });

    it('should be push buffer if connection was broken', function(done) {
      var logger = new fluent.FluentLogger(testPort, testHost, { bufferSize: 100 });

      process.nextTick(function() {
        for (var i = 0; i < 10; i++) {
          logger.post('test.fluent', { foo: "bar" });
        }

        logger.head.should.eql(0);
        logger.tail.should.eql(10);
        logger.queues.length.should.eql(10);
        done();
      });
    });

    it('should be rotated buffer if number of post is greater than buffer size', function(done) {
      var logger = new fluent.FluentLogger(testPort, testHost, { bufferSize: 10 });

      process.nextTick(function() {
        for (var i = 0; i < 15; i++) {
          logger.post('test.fluent', { foo: "bar" });
        }
        logger.head.should.eql(6);
        logger.tail.should.eql(5);
        logger.queues.length.should.eql(10);
        done();
      });
    });
  });

  describe('flush buffer', function() {
    beforeEach(function(done) {
      server.close();
      done();
    });

    it('should be flushed buffer after reconnected', function(done) {
      this.timeout(10000);
      var logger = new fluent.FluentLogger(testPort, testHost);

      logger.on('connect', function() {
        logger.head.should.eql(0);
        logger.tail.should.eql(0);
        done();
      });

      process.nextTick(function() {
        for (var i = 0; i < 10; i++) {
          logger.post('test.fluent', { foo: "bar" });
        }

        server.listen(testPort, function () {});
      });
    });
  });
});
<commit_msg>Refactor unit test<commit_after>var root = __dirname + "/../";
var path = require('path');
var net = require('net');
var util = require('util');
var fluent = require(path.join(root, 'lib/FluentLogger'));
var should = require('should');

var testPort = 24242;
var testHost = '127.0.0.1';

describe('FluentLogger', function() {
  var server;

  beforeEach(function(done) {
    server = new net.Server();
    server.listen(testPort, function() {
      done();
    });
  });

  afterEach(function(done) {
    try { server.close(); } catch(e) {}
    done();
  });

  describe('new instance', function() {
    it('should connect fluentd server', function(done) {
      server.on('connection', function(socket) {
        done();
      });
      new fluent.FluentLogger(testPort, testHost);
    });
  });

  describe('#post()', function() {
    var logger;

    it('should post log', function(done) {
      server.on('connection', function(socket) {
        socket.setEncoding('utf8');
        socket.on('data', function(data) {
          var json = JSON.parse(data);
          json[0].should.eql('test.fluent');
          json[1].should.be.a('number');
          json[2].should.eql({ foo: "bar" });
          done();
        });
      });

      logger = new fluent.FluentLogger(testPort, testHost);
      logger.post('test.fluent', { foo: "bar" });
    });
  });

  describe('retry feature', function() {
    beforeEach(function(done) {
      server.close();
      done();
    });

    it('should be retry if connection was broken', function(done) {
      var logger = new fluent.FluentLogger(testPort, testHost);
      var count = 1;

      logger.on('connect', function() {
        done();
      });

      server.listen(testPort);
    });
  });

  describe('buffer feature', function() {
    beforeEach(function(done) {
      server.close();
      process.nextTick(function() {
        done();
      });
    });

    it('should be push buffer if connection was broken', function(done) {
      var logger = new fluent.FluentLogger(testPort, testHost, { bufferSize: 100 });

      for (var i = 0; i < 10; i++) {
        logger.post('test.fluent', { foo: "bar" });
      }

      logger.head.should.eql(0);
      logger.tail.should.eql(10);
      logger.queues.length.should.eql(10);
      done();
    });

    it('should be rotated buffer if number of post is greater than buffer size', function(done) {
      var logger = new fluent.FluentLogger(testPort, testHost, { bufferSize: 10 });

      for (var i = 0; i < 15; i++) {
        logger.post('test.fluent', { foo: "bar" });
      }

      logger.head.should.eql(6);
      logger.tail.should.eql(5);
      logger.queues.length.should.eql(10);
      done();
    });
  });

  describe('flush buffer', function() {
    beforeEach(function(done) {
      server.close();
      process.nextTick(function() {
        done();
      });
    });

    it('should be flushed buffer after reconnected', function(done) {
      var logger = new fluent.FluentLogger(testPort, testHost);

      logger.on('connect', function() {
        logger.head.should.eql(0);
        logger.tail.should.eql(0);
        done();
      });

      for (var i = 0; i < 10; i++) {
        logger.post('test.fluent', { foo: "bar" });
      }

      server.listen(testPort, function () {});
    });
  });
});
<|endoftext|>


<commit_before>/*jslint browser: true */
/* global define */

define([
	'underscore',
	'jquery',
	'bootstrap',
	'datetimepicker',
	'backbone.stickit',
	'module',
	'views/BaseView',
	'views/AlertView',
	'views/ConfirmationDialogView',
	'views/LoginDialogView',
	'views/BibliodataView',
	'views/LinksView',
	'views/ContributorsView',
	'views/SPNView',
	'views/CatalogingView',
	'views/GeospatialView',
	'hbs!hb_templates/publication'
], function(_, $, bootstrap, datetimepicker, Stickit, module, BaseView, AlertView, ConfirmationDialogView, LoginDialogView,
			BibliodataView, LinksView, ContributorsView, SPNView, CatalogingView, GeospatialView, hbTemplate) {
	"use strict";

	var view = BaseView.extend({

		events : {
			'click .reset-btn' : 'reloadPage',
			'click .release-btn' : 'releasePub',
			'click .save-btn' : 'savePub',
			'click .publish-btn' : 'publishPub',
			'click .delete-btn' : 'deletePub',
			'click .edit-tabs a' : 'showTab',
			'dp.change #display-date' : 'changeDisplayToPublicDate',
			'click .locked-pub-dialog-container .close-btn' : 'closeLockedDialog'
		},

		bindings : {
			'.validation-errors' : {
				observe : 'validationErrors',
				updateMethod : 'html',
				onGet : function(value) {
					if (value && _.isArray(value) && value.length > 0) {
						return '
' + JSON.stringify(value) + '
';
					}
					else {
						return '';
					}
				}
			},
			'#pub-id-div input' : 'id',
			'#pub-index-id-div input' : 'indexId',
			'#ipds-div input' : 'ipdsId',
			'#pub-display-to-public-div input' : {
				observe : 'displayToPublicDate',
				onGet : function(value) {
					if (value) {
						return value + ' ET';
					}
					else {
						return '';
					}
				}
			}
		},

		template : hbTemplate,

		render : function() {
			var self = this;
			console.log(this);
			BaseView.prototype.render.apply(this, arguments);
			this.updateIndexId(this.model, this.model.get('indexId'));
			// Set up datepicker
			this.$('#display-date').datetimepicker({
				format : 'YYYY-MM-DDTHH:mm:ss [E]T'
			});

			// Sets up the binding between DOM elements and the model //
			this.stickit();

			// Set the elements for child views and render if needed.
			this.alertView.setElement(this.$('.alert-container'));
			this.confirmationDialogView.setElement(this.$('.confirmation-dialog-container')).render();
			this.loginDialogView.setElement(this.$('.login-dialog-container')).render();

			this.$('[data-toggle="tooltip"]').tooltip({
				trigger : 'hover'
			});

			// Don't render tabs until the publication has been fetched.
			this.fetchPromise.done(function() {
				_.each(self.tabs, function (tab) {
					tab.view.setElement(tab.el).render();
					tab.view.$('[data-toggle="tooltip"]').tooltip({
						trigger : 'hover'
					});
				});

				// The tinymce have to be initialize sequentially
				self.tabs.bibliodata.view.initializeTinyMce().done(function() {
					self.tabs.spn.view.initializeTinyMce();
				});
			}).fail(function(jqXhr) {
				var $modal = self.$('.locked-pub-dialog-container .modal');
				var message;
				if (jqXhr.status === 409) {
					message = (jqXhr.responseJSON.validationErrors.length > 0) ? jqXhr.responseJSON.validationErrors[0].message : 'Unknown error'
					$modal.find('.modal-body').html(message + '. Click OK to return to the Search page');
					$modal.modal();
				}
				else {
					self.alertView.showDangerAlert('Can\'t retrieve the publication: ' + jqXhr.statusText);
				}
			});

			return this;
		},

		/*
		 * @param {Object} options
		 *     @prop {String} el - jquery selector where the view should be rendered
		 *     @prop {PublicationModel} model
		 */
		initialize : function(options) {
			BaseView.prototype.initialize.apply(this, arguments);
			this.context.indexId = this.model.get('indexId');
			this.context.previewUrl = module.config().previewUrl;
			this.listenTo(this.model, 'change:indexId', this.updateIndexId);
			this.listenTo(this.model, 'change:ipdsId', this._readOnlyControlIpds);

			if (this.model.isNew()) {
				this.fetchPromise = $.Deferred().resolve();
			}
			else {
				this.fetchPromise = this.model.fetch();
			}
			// Create child views
			this.alertView = new AlertView({
				el : '.alert-container'
			});
			this.confirmationDialogView = new ConfirmationDialogView({
				el : '.confirmation-dialog-container'
			});
			this.loginDialogView = new LoginDialogView({
				el : '.login-dialog-container'
			});

			this.tabs = {
				bibliodata : {
					el: '#bibliodata-pane',
					view: new BibliodataView({
						el: '#bibliodata-pane',
						model : this.model
					})
				},
				links : {
					el : '#links-pane',
					view : new LinksView({
						el : '#links-pane',
						collection : this.model.get('links')
					})
				},
				contributors : {
					el : '#contributors-pane',
					view : new ContributorsView({
						el : '#contributors-pane',
						model : this.model
					})
				},
				spn : {
					el : '#spn-pane',
					view : new SPNView({
						el : '#spn-pane',
						model : this.model
					})
				},
				cataloging : {
					el : '#cataloging-pane',
					view : new CatalogingView({
						el : '#cataloging-pane',
						model : this.model
					})
				},
				geospatial : {
					el : '#geospatial-pane',
					view : new GeospatialView({
						el : '#geospatial-pane',
						model : this.model
					})
				}

			};
		},

		remove : function() {
			this.alertView.remove();
			this.confirmationDialogView.remove();
			this.loginDialogView.remove();
			_.each(this.tabs, function(t) {
				t.view.remove();
			});
			BaseView.prototype.remove.apply(this, arguments);
			return this;
		},

		/*
		 * Updates the publication view when the publication id is updated.
		 * @param {PublicationModel} model
		 * @param {String} newId
		 */
		updateIndexId : function(model, newId) {
			if (newId) {
				this.$('#pub-preview-div').show();
				this.$('#pub-preview-div a').attr('href', this.context.previewUrl + newId);
			}
			else {
				this.$('#pub-preview-div').hide();
			}
		},

		reloadPage : function() {
			window.location.reload();
		},

		releasePub : function() {
			var self = this;
			this.model.release()
				.done(function() {
					self.returnToSearch();
				}).fail(function(jqXHR, error) {
					if (jqXHR.status === 401) {
						self.loginDialogView.show(function() {
							self.alertView.showWarningAlert('Please click Release to release the publication');
						});
					}
					else {
						self.alertView.showDangerAlert('Publication not released: ' + error);
					}
				});
		},

		savePub : function() {
			var self = this;
			var loadingDiv = this.$('.loading-indicator');
			var isNew = this.model.isNew();

			loadingDiv.show();

			return this.model.save({}, {
				contentType: 'application/json',
				headers: {
					'Accept': 'application/json'
				}
			})
				.done(function() {
					self.alertView.showSuccessAlert('The publication was successfully saved');
					if (isNew) {
						self.router.navigate('publication/' + self.model.get('id'));
					}
				})
				.fail(function(jqXhr, textStatus, error) {
					var response = jqXhr;
					if (jqXhr.status === 401) {
						self.loginDialogView.show(function() {
							self.alertView.showWarningAlert('Please click Save Changes to save the publication');
						});
					}
					else if (_.has(response, 'responseJSON') &&
						_.has(response.responseJSON, 'validationErrors') &&
						(response.responseJSON.validationErrors.length > 0)) {
						self.model.set('validationErrors', response.responseJSON.validationErrors);
						self.alertView.showDangerAlert('Publication not saved with validation errors');
					}
					else {
						self.alertView.showDangerAlert('Publication not saved: ' + error);
					}
				})
				.always(function() {
					loadingDiv.hide();
				});
		},

		publishPub : function() {
			var self = this;

			var callPublish = function() {
				var loadingDiv = self.$('.loading-indicator');
				loadingDiv.show();
				self.model.publish()
					.done(function() {
						self.returnToSearch();
					})
					.fail(function(jqXHR, error) {
						if (jqXHR.status === 401) {
							self.loginDialogView.show(function() {
								self.alertView.showWarningAlert('Please click Publish to publish the publication');
							});
						}
						else {
							self.alertView.showDangerAlert(error);
						}
					})
					.always(function() {
						loadingDiv.hide();
					});
			};

			this.savePub()
				.done(function() {
					self.confirmationDialogView.show('Are you sure you want to publish this publication?', callPublish);
				});
		},

		deletePub : function() {
			var self = this;

			var callDelete = function() {
				self.model.destroy({
					headers: {
						'Accept': 'application/json text/plain, */*'
					}
				})
					.done(function() {
						self.returnToSearch();
					})
					.fail(function(jqxhr) {
						if (jqxhr.status === 401) {
							self.loginDialogView.show(function() {
								self.alertView.showWarningAlert('Please clicke Delete to delete the publication');
							});
						}
						else {
							self.alertView.showDangerAlert('Publication not deleted with error: ' + jqxhr.statusText);
						}
					});

			};

			if (this.model.has('id')) {
				this.confirmationDialogView.show('Are you sure you want to delete this publication?', callDelete);
			}
			else {
				self.returnToSearch();
			}

		},

		returnToSearch : function() {
			this.router.navigate('search', {trigger: true});
		},

		showTab : function(ev) {
			ev.preventDefault();
			this.$('.edit-tabs').tab('show');
		},

		changeDisplayToPublicDate : function(ev) {
			if (ev.date) {
				this.model.set('displayToPublicDate', ev.date.format('YYYY-MM-DDTHH:mm:ss'));
			}
			else {
				this.model.unset('displayToPublicDate');
			}
		},

		closeLockedDialog : function(ev) {
			ev.preventDefault();
			window.location.assign(module.config().scriptRoot + '/manager');
		},

		_readOnlyControlIpds: function() {
			var $ipdsInput = this.$('#ipds-input');
			if (this.model.get('ipdsId')) {
				console.log('Readonly');
				$ipdsInput.prop('readonly', true);
			}
			else {
				$ipdsInput.prop('readonly', false);
			}
		}
	});

	return view;
});
<commit_msg>removed commentted code<commit_after>/*jslint browser: true */
/* global define */

define([
	'underscore',
	'jquery',
	'bootstrap',
	'datetimepicker',
	'backbone.stickit',
	'module',
	'views/BaseView',
	'views/AlertView',
	'views/ConfirmationDialogView',
	'views/LoginDialogView',
	'views/BibliodataView',
	'views/LinksView',
	'views/ContributorsView',
	'views/SPNView',
	'views/CatalogingView',
	'views/GeospatialView',
	'hbs!hb_templates/publication'
], function(_, $, bootstrap, datetimepicker, Stickit, module, BaseView, AlertView, ConfirmationDialogView, LoginDialogView,
			BibliodataView, LinksView, ContributorsView, SPNView, CatalogingView, GeospatialView, hbTemplate) {
	"use strict";

	var view = BaseView.extend({

		events : {
			'click .reset-btn' : 'reloadPage',
			'click .release-btn' : 'releasePub',
			'click .save-btn' : 'savePub',
			'click .publish-btn' : 'publishPub',
			'click .delete-btn' : 'deletePub',
			'click .edit-tabs a' : 'showTab',
			'dp.change #display-date' : 'changeDisplayToPublicDate',
			'click .locked-pub-dialog-container .close-btn' : 'closeLockedDialog'
		},

		bindings : {
			'.validation-errors' : {
				observe : 'validationErrors',
				updateMethod : 'html',
				onGet : function(value) {
					if (value && _.isArray(value) && value.length > 0) {
						return '
' + JSON.stringify(value) + '
';
					}
					else {
						return '';
					}
				}
			},
			'#pub-id-div input' : 'id',
			'#pub-index-id-div input' : 'indexId',
			'#ipds-div input' : 'ipdsId',
			'#pub-display-to-public-div input' : {
				observe : 'displayToPublicDate',
				onGet : function(value) {
					if (value) {
						return value + ' ET';
					}
					else {
						return '';
					}
				}
			}
		},

		template : hbTemplate,

		render : function() {
			var self = this;
			BaseView.prototype.render.apply(this, arguments);
			this.updateIndexId(this.model, this.model.get('indexId'));
			// Set up datepicker
			this.$('#display-date').datetimepicker({
				format : 'YYYY-MM-DDTHH:mm:ss [E]T'
			});

			// Sets up the binding between DOM elements and the model //
			this.stickit();

			// Set the elements for child views and render if needed.
			this.alertView.setElement(this.$('.alert-container'));
			this.confirmationDialogView.setElement(this.$('.confirmation-dialog-container')).render();
			this.loginDialogView.setElement(this.$('.login-dialog-container')).render();

			this.$('[data-toggle="tooltip"]').tooltip({
				trigger : 'hover'
			});

			// Don't render tabs until the publication has been fetched.
			this.fetchPromise.done(function() {
				_.each(self.tabs, function (tab) {
					tab.view.setElement(tab.el).render();
					tab.view.$('[data-toggle="tooltip"]').tooltip({
						trigger : 'hover'
					});
				});

				// The tinymce have to be initialize sequentially
				self.tabs.bibliodata.view.initializeTinyMce().done(function() {
					self.tabs.spn.view.initializeTinyMce();
				});
			}).fail(function(jqXhr) {
				var $modal = self.$('.locked-pub-dialog-container .modal');
				var message;
				if (jqXhr.status === 409) {
					message = (jqXhr.responseJSON.validationErrors.length > 0) ? jqXhr.responseJSON.validationErrors[0].message : 'Unknown error'
					$modal.find('.modal-body').html(message + '. Click OK to return to the Search page');
					$modal.modal();
				}
				else {
					self.alertView.showDangerAlert('Can\'t retrieve the publication: ' + jqXhr.statusText);
				}
			});

			return this;
		},

		/*
		 * @param {Object} options
		 *     @prop {String} el - jquery selector where the view should be rendered
		 *     @prop {PublicationModel} model
		 */
		initialize : function(options) {
			BaseView.prototype.initialize.apply(this, arguments);
			this.context.indexId = this.model.get('indexId');
			this.context.previewUrl = module.config().previewUrl;
			this.listenTo(this.model, 'change:indexId', this.updateIndexId);
			this.listenTo(this.model, 'change', this._readOnlyControlIpds);

			if (this.model.isNew()) {
				this.fetchPromise = $.Deferred().resolve();
			}
			else {
				this.fetchPromise = this.model.fetch();
			}
			// Create child views
			this.alertView = new AlertView({
				el : '.alert-container'
			});
			this.confirmationDialogView = new ConfirmationDialogView({
				el : '.confirmation-dialog-container'
			});
			this.loginDialogView = new LoginDialogView({
				el : '.login-dialog-container'
			});

			this.tabs = {
				bibliodata : {
					el: '#bibliodata-pane',
					view: new BibliodataView({
						el: '#bibliodata-pane',
						model : this.model
					})
				},
				links : {
					el : '#links-pane',
					view : new LinksView({
						el : '#links-pane',
						collection : this.model.get('links')
					})
				},
				contributors : {
					el : '#contributors-pane',
					view : new ContributorsView({
						el : '#contributors-pane',
						model : this.model
					})
				},
				spn : {
					el : '#spn-pane',
					view : new SPNView({
						el : '#spn-pane',
						model : this.model
					})
				},
				cataloging : {
					el : '#cataloging-pane',
					view : new CatalogingView({
						el : '#cataloging-pane',
						model : this.model
					})
				},
				geospatial : {
					el : '#geospatial-pane',
					view : new GeospatialView({
						el : '#geospatial-pane',
						model : this.model
					})
				}

			};
		},

		remove : function() {
			this.alertView.remove();
			this.confirmationDialogView.remove();
			this.loginDialogView.remove();
			_.each(this.tabs, function(t) {
				t.view.remove();
			});
			BaseView.prototype.remove.apply(this, arguments);
			return this;
		},

		/*
		 * Updates the publication view when the publication id is updated.
		 * @param {PublicationModel} model
		 * @param {String} newId
		 */
		updateIndexId : function(model, newId) {
			if (newId) {
				this.$('#pub-preview-div').show();
				this.$('#pub-preview-div a').attr('href', this.context.previewUrl + newId);
			}
			else {
				this.$('#pub-preview-div').hide();
			}
		},

		reloadPage : function() {
			window.location.reload();
		},

		releasePub : function() {
			var self = this;
			this.model.release()
				.done(function() {
					self.returnToSearch();
				}).fail(function(jqXHR, error) {
					if (jqXHR.status === 401) {
						self.loginDialogView.show(function() {
							self.alertView.showWarningAlert('Please click Release to release the publication');
						});
					}
					else {
						self.alertView.showDangerAlert('Publication not released: ' + error);
					}
				});
		},

		savePub : function() {
			var self = this;
			var loadingDiv = this.$('.loading-indicator');
			var isNew = this.model.isNew();

			var ipdsIdValue = this.$('#ipds-input').val();
			if (ipdsIdValue) {
				this.model.set('ipdsId', ipdsIdValue);
			}
			loadingDiv.show();

			return this.model.save({}, {
				contentType: 'application/json',
				headers: {
					'Accept': 'application/json'
				}
			})
				.done(function() {
					self.alertView.showSuccessAlert('The publication was successfully saved');
					if (isNew) {
						self.router.navigate('publication/' + self.model.get('id'));
					}
				})
				.fail(function(jqXhr, textStatus, error) {
					var response = jqXhr;
					if (jqXhr.status === 401) {
						self.loginDialogView.show(function() {
							self.alertView.showWarningAlert('Please click Save Changes to save the publication');
						});
					}
					else if (_.has(response, 'responseJSON') &&
						_.has(response.responseJSON, 'validationErrors') &&
						(response.responseJSON.validationErrors.length > 0)) {
						self.model.set('validationErrors', response.responseJSON.validationErrors);
						self.alertView.showDangerAlert('Publication not saved with validation errors');
					}
					else {
						self.alertView.showDangerAlert('Publication not saved: ' + error);
					}
				})
				.always(function() {
					loadingDiv.hide();
				});
		},

		publishPub : function() {
			var self = this;

			var callPublish = function() {
				var loadingDiv = self.$('.loading-indicator');
				loadingDiv.show();
				self.model.publish()
					.done(function() {
						self.returnToSearch();
					})
					.fail(function(jqXHR, error) {
						if (jqXHR.status === 401) {
							self.loginDialogView.show(function() {
								self.alertView.showWarningAlert('Please click Publish to publish the publication');
							});
						}
						else {
							self.alertView.showDangerAlert(error);
						}
					})
					.always(function() {
						loadingDiv.hide();
					});
			};

			this.savePub()
				.done(function() {
					self.confirmationDialogView.show('Are you sure you want to publish this publication?', callPublish);
				});
		},

		deletePub : function() {
			var self = this;

			var callDelete = function() {
				self.model.destroy({
					headers: {
						'Accept': 'application/json text/plain, */*'
					}
				})
					.done(function() {
						self.returnToSearch();
					})
					.fail(function(jqxhr) {
						if (jqxhr.status === 401) {
							self.loginDialogView.show(function() {
								self.alertView.showWarningAlert('Please clicke Delete to delete the publication');
							});
						}
						else {
							self.alertView.showDangerAlert('Publication not deleted with error: ' + jqxhr.statusText);
						}
					});

			};

			if (this.model.has('id')) {
				this.confirmationDialogView.show('Are you sure you want to delete this publication?', callDelete);
			}
			else {
				self.returnToSearch();
			}

		},

		returnToSearch : function() {
			this.router.navigate('search', {trigger: true});
		},

		showTab : function(ev) {
			ev.preventDefault();
			this.$('.edit-tabs').tab('show');
		},

		changeDisplayToPublicDate : function(ev) {
			if (ev.date) {
				this.model.set('displayToPublicDate', ev.date.format('YYYY-MM-DDTHH:mm:ss'));
			}
			else {
				this.model.unset('displayToPublicDate');
			}
		},

		closeLockedDialog : function(ev) {
			ev.preventDefault();
			window.location.assign(module.config().scriptRoot + '/manager');
		},

		_readOnlyControlIpds: function() {
			this.unstickit(this.model, {'#ipds-div input' : 'ipdsId'})
			var $ipdsInput = this.$('#ipds-input');
			if (this.model.get('ipdsId')) {
				$ipdsInput.prop('readonly', true);
			}
			else {
				$ipdsInput.prop('readonly', false);
			}
		}
	});

	return view;
});
<|endoftext|>


<commit_before>
var Setting = FormModel.extend({

	blankSchema: {
		requireViewInvite: false,
	    requirePostInvite: false,
	    requirePostsApproval: false,
	    title: '',
	    theme: '',
	    footerCode: '',
	    analyticsCode: '',
	    tlkioChannel: '',
	    mixpanelId: '',
	    clickyId:'',
	    proxinoKey: '',
	    goSquaredId: '',
		veroAPIKey: '',
		veroSecret: '',
		intercomId: '',
		logoUrl: '',
		logoHeight: '',
		logoWidth: '',
		scoreUpdateInterval: '',
		landingPageText: '',
		afterSignupText: '',
		notes: '',
	},

	init: function(options) {
		this._super(Settings, options);

		this.overwriteTitle('requireViewInvite', 'Require Invite to view?');
		this.overwriteTitle('requirePostInvite', 'Require Invite to post?');
		this.overwriteTitle('requirePostsApproval', 'Posts must be approved by admin?');
		this.overwriteTitle('title', 'Site Title');
		this.overwriteTitle('tlkioChannel', 'Tlk.io Channel');
		this.overwriteTitle('mixpanelId', 'Mixpanel ID');
		this.overwriteTitle('clickyId', 'Clicky ID');
		this.overwriteTitle('proxinoKey', 'Proxino key');
		this.overwriteTitle('goSquaredId', 'GoSquared ID');
		this.overwriteTitle('intercomId', 'Intercom ID');
		this.overwriteTitle('veroAPIKey', 'Vero API key');
		this.overwriteTitle('veroSecret', 'Vero secret');
		this.overwriteTitle('logoUrl', 'Logo URL');
		this.overwriteType('footerCode', 'textarea');
		this.overwriteType('analyticsCode', 'textarea');
		this.overwriteType('landingPageText', 'textarea');
		this.overwriteType('afterSignupText', 'textarea');
		this.overwriteType('notes', 'textarea');
		this.makeSelect('theme', ['Default', 'Ascndr', 'Telescope'])
	}
});
<commit_msg>simplified settings page<commit_after>
var Setting = FormModel.extend({

  blankSchema: {
    requireViewInvite: false,
    requirePostInvite: false,
    requirePostsApproval: false,
    scoreUpdateInterval: '',
    title: '',
    logoUrl: '',
    logoHeight: '',
    logoWidth: '',
    mixpanelId: '',
    clickyId:'',
    goSquaredId: '',
    footerCode: '',
    notes: '',
  },

  init: function(options) {
    this._super(Settings, options);
    this.overwriteTitle('requireViewInvite', 'Require Invite to view?');
    this.overwriteTitle('requirePostInvite', 'Require Invite to post?');
    this.overwriteTitle('requirePostsApproval', 'Posts must be approved by admin?');
    this.overwriteTitle('title', 'Site Title');
    this.overwriteTitle('tlkioChannel', 'Tlk.io Channel');
    this.overwriteTitle('mixpanelId', 'Mixpanel ID');
    this.overwriteTitle('clickyId', 'Clicky ID');
    this.overwriteTitle('proxinoKey', 'Proxino key');
    this.overwriteTitle('goSquaredId', 'GoSquared ID');
    this.overwriteTitle('intercomId', 'Intercom ID');
    this.overwriteTitle('veroAPIKey', 'Vero API key');
    this.overwriteTitle('veroSecret', 'Vero secret');
    this.overwriteTitle('logoUrl', 'Logo URL');
    this.overwriteType('footerCode', 'textarea');
    this.overwriteType('analyticsCode', 'textarea');
    this.overwriteType('landingPageText', 'textarea');
    this.overwriteType('afterSignupText', 'textarea');
    this.overwriteType('notes', 'textarea');
    this.makeSelect('theme', ['Default', 'Ascndr', 'Telescope'])
  }
});
<|endoftext|>


<commit_before>/*global THREE*/
/*exported Toroid*/
var Toroid = (function() {
  'use strict';

  /**
   * This geometry is akin to the inner half of a regular torus with the top
   * half extended to a circle.
   *
   * Cross-section example:
   *
   *    --------.        .--------
   *             \      /
   *              |    |
   *             /      \
   *          --'        '--
   *
   * Note the missing outer-half.
   */
  function Toroid( outerRadius, innerRadius, tube, radialSegments, tubularSegments, arc ) {
    THREE.Geometry.call( this );

    this.parameters = {
      outerRadius: outerRadius,
      innerRadius: innerRadius,
      tube: tube,
      radialSegments: radialSegments,
      tubularSegments: tubularSegments,
      arc: arc
    };

    outerRadius = outerRadius || 160;
    innerRadius = innerRadius || 100;
    tube = tube || 40;
    radialSegments = radialSegments || 8;
    tubularSegments = tubularSegments || 6;
    arc = arc || Math.PI * 2;

    var center = new THREE.Vector3();
    var uvs = [];
    var normals = [];

    var i, j;
    for ( j = 0; j <= radialSegments; j++ ) {
      for ( i = 0; i <= tubularSegments; i++ ) {
        var u = i / tubularSegments * arc;
        var v = j / radialSegments * Math.PI + ( 1 / 2 * Math.PI );

        center.x = innerRadius * Math.cos( u );
        center.y = innerRadius * Math.sin( u );

        var vertex = new THREE.Vector3();
        vertex.x = ( innerRadius + tube * Math.cos( v ) ) * Math.cos( u );
        vertex.y = ( innerRadius + tube * Math.cos( v ) ) * Math.sin( u );
        vertex.z = tube * Math.sin( v );

        if ( !j ) {
          vertex.x = ( outerRadius + tube * Math.cos( v ) ) * Math.cos( u );
          vertex.y = ( outerRadius + tube * Math.cos( v ) ) * Math.sin( u );
        }

        this.vertices.push( vertex );

        uvs.push( new THREE.Vector2( i / tubularSegments, j / radialSegments ) );

        if ( !j ) {
          normals.push( new THREE.Vector3( 0, 0, 1 ) );
        } else {
          normals.push( vertex.clone().sub( center ).normalize() );
        }
      }
    }

    for ( j = 1; j <= radialSegments; j++ ) {
      for ( i = 1; i <= tubularSegments; i++ ) {
        var a = ( tubularSegments + 1 ) * j + i - 1;
        var b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
        var c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
        var d = ( tubularSegments + 1 ) * j + i;

        var face = new THREE.Face3( a, b, d, [ normals[ a ].clone(), normals[ b ].clone(), normals[ d ].clone() ] );
        this.faces.push( face );
        this.faceVertexUvs[ 0 ].push( [ uvs[ a ].clone(), uvs[ b ].clone(), uvs[ d ].clone() ] );

        face = new THREE.Face3( b, c, d, [ normals[ b ].clone(), normals[ c ].clone(), normals[ d ].clone() ] );
        this.faces.push( face );
        this.faceVertexUvs[ 0 ].push( [ uvs[ b ].clone(), uvs[ c ].clone(), uvs[ d ].clone() ] );
      }
    }

    this.computeFaceNormals();
  }

  Toroid.prototype = Object.create( THREE.Geometry.prototype );

  return Toroid;

}) ();
<commit_msg>interstellar: Convert Toroid to ES2015 class.<commit_after>/* eslint comma-dangle: ["error", "always-multiline"] */
/* global THREE */
/* exported Toroid */

/**
 * This geometry is akin to the inner half of a regular torus with the top
 * half extended to a circle.
 *
 * Cross-section example:
 *
 *    --------.        .--------
 *             \      /
 *              |    |
 *             /      \
 *          --'        '--
 *
 * Note the missing outer-half.
 */
class Toroid extends THREE.Geometry {
  constructor(
    outerRadius = 160,
    innerRadius = 100,
    tube = 40,
    radialSegments = 8,
    tubularSegments = 6,
    arc = Math.PI * 2
  ) {
    super();

    this.parameters = {
      outerRadius,
      innerRadius,
      tube,
      radialSegments,
      tubularSegments,
      arc,
    };

    const center = new THREE.Vector3();
    const uvs = [];
    const normals = [];

    for ( let j = 0; j <= radialSegments; j++ ) {
      for ( let i = 0; i <= tubularSegments; i++ ) {
        const u = i / tubularSegments * arc;
        const v = j / radialSegments * Math.PI + ( 1 / 2 * Math.PI );

        center.x = innerRadius * Math.cos( u );
        center.y = innerRadius * Math.sin( u );

        const vertex = new THREE.Vector3();
        vertex.x = ( innerRadius + tube * Math.cos( v ) ) * Math.cos( u );
        vertex.y = ( innerRadius + tube * Math.cos( v ) ) * Math.sin( u );
        vertex.z = tube * Math.sin( v );

        if ( !j ) {
          vertex.x = ( outerRadius + tube * Math.cos( v ) ) * Math.cos( u );
          vertex.y = ( outerRadius + tube * Math.cos( v ) ) * Math.sin( u );
        }

        this.vertices.push( vertex );

        uvs.push( new THREE.Vector2( i / tubularSegments, j / radialSegments ) );

        if ( !j ) {
          normals.push( new THREE.Vector3( 0, 0, 1 ) );
        } else {
          normals.push( vertex.clone().sub( center ).normalize() );
        }
      }
    }

    for ( let j = 1; j <= radialSegments; j++ ) {
      for ( let i = 1; i <= tubularSegments; i++ ) {
        const a = ( tubularSegments + 1 ) * j + i - 1;
        const b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
        const c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
        const d = ( tubularSegments + 1 ) * j + i;

        let face = new THREE.Face3( a, b, d, [ normals[ a ].clone(), normals[ b ].clone(), normals[ d ].clone() ] );
        this.faces.push( face );
        this.faceVertexUvs[ 0 ].push( [ uvs[ a ].clone(), uvs[ b ].clone(), uvs[ d ].clone() ] );

        face = new THREE.Face3( b, c, d, [ normals[ b ].clone(), normals[ c ].clone(), normals[ d ].clone() ] );
        this.faces.push( face );
        this.faceVertexUvs[ 0 ].push( [ uvs[ b ].clone(), uvs[ c ].clone(), uvs[ d ].clone() ] );
      }
    }

    this.computeFaceNormals();
  }
}
<|endoftext|>


<commit_before>const gbxremote = require('gbxremote'),
    async = require('async');

class Nadeo extends require('./core') {
    constructor() {
        super();
        this.options.port = 2350;
        this.options.port_query = 5000;
        this.gbxclient = false;
    }

    reset() {
        super.reset();
        if(this.gbxclient) {
            this.gbxclient.terminate();
            this.gbxclient = false;
        }
    }

    run(state) {
        const cmds = [
            ['Connect'],
            ['Authenticate', this.options.login,this.options.password],
            ['GetStatus'], // 1
            ['GetPlayerList',500,0], // 2
            ['GetServerOptions'], // 3
            ['GetCurrentMapInfo'], // 4
            ['GetCurrentGameInfo'], // 5
            ['GetNextMapInfo'] // 6
        ];
        const results = [];

        async.eachSeries(cmds, (cmdset,c) => {
            const cmd = cmdset[0];
            const params = cmdset.slice(1);

            if(cmd === 'Connect') {
                const client = this.gbxclient = gbxremote.createClient(this.options.port_query,this.options.host, (err) => {
                    if(err) return this.fatal('GBX error '+JSON.stringify(err));
                    c();
                });
                client.on('error',() => {});
            } else {
                this.gbxclient.methodCall(cmd, params, (err, value) => {
                    if(err) return this.fatal('XMLRPC error '+JSON.stringify(err));
                    results.push(value);
                    c();
                });
            }
        }, () => {
            let gamemode = '';
            const igm = results[5].GameMode;
            if(igm === 0) gamemode="Rounds";
            if(igm === 1) gamemode="Time Attack";
            if(igm === 2) gamemode="Team";
            if(igm === 3) gamemode="Laps";
            if(igm === 4) gamemode="Stunts";
            if(igm === 5) gamemode="Cup";

            state.name = this.stripColors(results[3].Name);
            state.password = (results[3].Password !== 'No password');
            state.maxplayers = results[3].CurrentMaxPlayers;
            state.maxspectators = results[3].CurrentMaxSpectators;
            state.currmap_name = this.stripColors(results[4].Name);
            state.currmap_uid = results[4].UId;
            state.gametype = gamemode;
            state.mapcount = results[5].NbChallenge;
            state.nextmap_name = this.stripColors(results[6].Name);
            state.nextmap_uid = results[6].UId;

            for (const player of results[2]) {
                state.players.push({name:this.stripColors(player.Name)});
            }

            this.finish(state);
        });
    }

    stripColors(str) {
        return str.replace(/\$([0-9a-f][^\$]?[^\$]?|[^\$]?)/g,'');
    }
}

module.exports = Nadeo;
<commit_msg>removed player loop, enabled full playerlist output, and increased maxoutput on playerlist<commit_after>const gbxremote = require('gbxremote'),
    async = require('async');

class Nadeo extends require('./core') {
    constructor() {
        super();
        this.options.port = 2350;
        this.options.port_query = 5000;
        this.gbxclient = false;
    }

    reset() {
        super.reset();
        if(this.gbxclient) {
            this.gbxclient.terminate();
            this.gbxclient = false;
        }
    }

    run(state) {
        const cmds = [
            ['Connect'],
            ['Authenticate', this.options.login,this.options.password],
            ['GetStatus'], // 1
            ['GetPlayerList',10000,0], // 2
            ['GetServerOptions'], // 3
            ['GetCurrentMapInfo'], // 4
            ['GetCurrentGameInfo'], // 5
            ['GetNextMapInfo'] // 6
        ];
        const results = [];

        async.eachSeries(cmds, (cmdset,c) => {
            const cmd = cmdset[0];
            const params = cmdset.slice(1);

            if(cmd === 'Connect') {
                const client = this.gbxclient = gbxremote.createClient(this.options.port_query,this.options.host, (err) => {
                    if(err) return this.fatal('GBX error '+JSON.stringify(err));
                    c();
                });
                client.on('error',() => {});
            } else {
                this.gbxclient.methodCall(cmd, params, (err, value) => {
                    if(err) return this.fatal('XMLRPC error '+JSON.stringify(err));
                    results.push(value);
                    c();
                });
            }
        }, () => {
            let gamemode = '';
            const igm = results[5].GameMode;
            if(igm === 0) gamemode="Rounds";
            if(igm === 1) gamemode="Time Attack";
            if(igm === 2) gamemode="Team";
            if(igm === 3) gamemode="Laps";
            if(igm === 4) gamemode="Stunts";
            if(igm === 5) gamemode="Cup";

            state.name = this.stripColors(results[3].Name);
            state.password = (results[3].Password !== 'No password');
            state.maxplayers = results[3].CurrentMaxPlayers;
            state.maxspectators = results[3].CurrentMaxSpectators;
            state.currmap_name = this.stripColors(results[4].Name);
            state.currmap_uid = results[4].UId;
            state.gametype = gamemode;
            state.players = results[2];
            state.mapcount = results[5].NbChallenge;
            state.nextmap_name = this.stripColors(results[6].Name);
            state.nextmap_uid = results[6].UId;

            this.finish(state);
        });
    }

    stripColors(str) {
        return str.replace(/\$([0-9a-f][^\$]?[^\$]?|[^\$]?)/g,'');
    }
}

module.exports = Nadeo;
<|endoftext|>