<commit_before>/* jshint node: true */

module.exports = function(environment) {
  var ENV = {
    modulePrefix: 'flowerpot',
    environment: environment,
    contentSecurityPolicy: { 'connect-src': "'self' https://auth.firebase.com wss://*.firebaseio.com" },
    firebase: 'https://' + process.env.FIREBASE_APP_NAME + '.firebaseio.com',
    torii: {
      sessionServiceName: 'session'
    },
    baseURL: '/',
    locationType: 'auto',
    EmberENV: {
      FEATURES: {
        // Here you can enable experimental features on an ember canary build
        // e.g. 'with-controller': true
      }
    },

    APP: {},

    featureFlags: {
      'show-index': true,
      'use-firebase': false,
      // Here you can pass flags/options to your application instance
      // when it is created
    }
  };

  if (environment === 'development') {
    // ENV.APP.LOG_RESOLVER = true;
    // ENV.APP.LOG_ACTIVE_GENERATION = true;
    // ENV.APP.LOG_TRANSITIONS = true;
    // ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
    // ENV.APP.LOG_VIEW_LOOKUPS = true;
  }

  if (environment === 'test') {
    // Testem prefers this...
    ENV.baseURL = '/';
    ENV.locationType = 'none';

    // keep test console output quieter
    ENV.APP.LOG_ACTIVE_GENERATION = false;
    ENV.APP.LOG_VIEW_LOOKUPS = false;

    ENV.APP.rootElement = '#ember-testing';
    ENV.featureFlags['show-index'] = false;

  }

  if (environment === 'production') {
    ENV.featureFlags['show-index'] = true;
    ENV.featureFlags['use-firebase'] = true;
  }

  return ENV;
};
<commit_msg>make sure firebase is explicitly disabled in test environment<commit_after>/* jshint node: true */

module.exports = function(environment) {
  var ENV = {
    modulePrefix: 'flowerpot',
    environment: environment,
    contentSecurityPolicy: { 'connect-src': "'self' https://auth.firebase.com wss://*.firebaseio.com" },
    firebase: 'https://' + process.env.FIREBASE_APP_NAME + '.firebaseio.com',
    torii: {
      sessionServiceName: 'session'
    },
    baseURL: '/',
    locationType: 'auto',
    EmberENV: {
      FEATURES: {
        // Here you can enable experimental features on an ember canary build
        // e.g. 'with-controller': true
      }
    },

    APP: {},

    featureFlags: {
      'show-index': true,
      'use-firebase': false,
      // Here you can pass flags/options to your application instance
      // when it is created
    }
  };

  if (environment === 'development') {
    // ENV.APP.LOG_RESOLVER = true;
    // ENV.APP.LOG_ACTIVE_GENERATION = true;
    // ENV.APP.LOG_TRANSITIONS = true;
    // ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
    // ENV.APP.LOG_VIEW_LOOKUPS = true;
  }

  if (environment === 'test') {
    // Testem prefers this...
    ENV.baseURL = '/';
    ENV.locationType = 'none';

    // keep test console output quieter
    ENV.APP.LOG_ACTIVE_GENERATION = false;
    ENV.APP.LOG_VIEW_LOOKUPS = false;

    ENV.APP.rootElement = '#ember-testing';
    ENV.featureFlags['show-index'] = false;
    ENV.featureFlags['use-firebase'] = false;
  }

  if (environment === 'production') {
    ENV.featureFlags['show-index'] = true;
    ENV.featureFlags['use-firebase'] = true;
  }

  return ENV;
};
<|endoftext|>


<commit_before>/**
 * @author sunag / http://www.sunag.com.br/
 */

import { Node } from '../../core/Node.js';
import { ColorNode } from '../../inputs/ColorNode.js';
import { FloatNode } from '../../inputs/FloatNode.js';

function PhongNode() {

	Node.call( this );

	this.color = new ColorNode( 0xEEEEEE );
	this.specular = new ColorNode( 0x111111 );
	this.shininess = new FloatNode( 30 );

}

PhongNode.prototype = Object.create( Node.prototype );
PhongNode.prototype.constructor = PhongNode;
PhongNode.prototype.nodeType = "Phong";

PhongNode.prototype.build = function ( builder ) {

	var code;

	builder.define( 'PHONG' );

	builder.requires.lights = true;

	if ( builder.isShader( 'vertex' ) ) {

		var position = this.position ? this.position.parseAndBuildCode( builder, 'v3', { cache: 'position' } ) : undefined;

		builder.mergeUniform( THREE.UniformsUtils.merge( [

			THREE.UniformsLib.fog,
			THREE.UniformsLib.lights

		] ) );

		builder.addParsCode( [
			"varying vec3 vViewPosition;",

			"#ifndef FLAT_SHADED",

			"	varying vec3 vNormal;",

			"#endif",

			//"#include <encodings_pars_fragment>", // encoding functions
			"#include <fog_pars_vertex>",
			"#include <morphtarget_pars_vertex>",
			"#include <skinning_pars_vertex>",
			"#include <shadowmap_pars_vertex>",
			"#include <logdepthbuf_pars_vertex>",
			"#include <clipping_planes_pars_vertex>"
		].join( "\n" ) );

		var output = [
			"#include <beginnormal_vertex>",
			"#include <morphnormal_vertex>",
			"#include <skinbase_vertex>",
			"#include <skinnormal_vertex>",
			"#include <defaultnormal_vertex>",

			"#ifndef FLAT_SHADED", // normal computed with derivatives when FLAT_SHADED

			"	vNormal = normalize( transformedNormal );",

			"#endif",

			"#include <begin_vertex>"
		];

		if ( position ) {

			output.push(
				position.code,
				position.result ? "transformed = " + position.result + ";" : ''
			);

		}

		output.push(
			"	#include <morphtarget_vertex>",
			"	#include <skinning_vertex>",
			"	#include <project_vertex>",
			"	#include <fog_vertex>",
			"	#include <logdepthbuf_vertex>",
			"	#include <clipping_planes_vertex>",

			"	vViewPosition = - mvPosition.xyz;",

			"	#include <worldpos_vertex>",
			"	#include <shadowmap_vertex>",
			"	#include <fog_vertex>"
		);

		code = output.join( "\n" );

	} else {

		// parse all nodes to reuse generate codes

		this.color.parse( builder, { slot: 'color' } );
		this.specular.parse( builder );
		this.shininess.parse( builder );

		if ( this.alpha ) this.alpha.parse( builder );

		if ( this.normal ) this.normal.parse( builder );
		if ( this.normalScale && this.normal ) this.normalScale.parse( builder );

		if ( this.light ) this.light.parse( builder, { cache: 'light' } );

		if ( this.ao ) this.ao.parse( builder );
		if ( this.ambient ) this.ambient.parse( builder );
		if ( this.shadow ) this.shadow.parse( builder );
		if ( this.emissive ) this.emissive.parse( builder, { slot: 'emissive' } );

		if ( this.environment ) this.environment.parse( builder, { slot: 'environment' } );
		if ( this.environmentAlpha && this.environment ) this.environmentAlpha.parse( builder );

		// build code

		var color = this.color.buildCode( builder, 'c', { slot: 'color' } );
		var specular = this.specular.buildCode( builder, 'c' );
		var shininess = this.shininess.buildCode( builder, 'f' );

		var alpha = this.alpha ? this.alpha.buildCode( builder, 'f' ) : undefined;

		var normal = this.normal ? this.normal.buildCode( builder, 'v3' ) : undefined;
		var normalScale = this.normalScale && this.normal ? this.normalScale.buildCode( builder, 'v2' ) : undefined;

		var light = this.light ? this.light.buildCode( builder, 'v3', { cache: 'light' } ) : undefined;

		var ao = this.ao ? this.ao.buildCode( builder, 'f' ) : undefined;
		var ambient = this.ambient ? this.ambient.buildCode( builder, 'c' ) : undefined;
		var shadow = this.shadow ? this.shadow.buildCode( builder, 'c' ) : undefined;
		var emissive = this.emissive ? this.emissive.buildCode( builder, 'c', { slot: 'emissive' } ) : undefined;

		var environment = this.environment ? this.environment.buildCode( builder, 'c', { slot: 'environment' } ) : undefined;
		var environmentAlpha = this.environmentAlpha && this.environment ? this.environmentAlpha.buildCode( builder, 'f' ) : undefined;

		builder.requires.transparent = alpha != undefined;

		builder.addParsCode( [
			"#include <fog_pars_fragment>",
			"#include <bsdfs>",
			"#include <lights_pars_begin>",
			"#include <lights_phong_pars_fragment>",
			"#include <shadowmap_pars_fragment>",
			"#include <logdepthbuf_pars_fragment>"
		].join( "\n" ) );

		var output = [
			// prevent undeclared normal
			"#include <normal_fragment_begin>",

			// prevent undeclared material
			"	BlinnPhongMaterial material;",

			color.code,
			"	vec3 diffuseColor = " + color.result + ";",
			"	ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );",

			"#include <logdepthbuf_fragment>",

			specular.code,
			"	vec3 specular = " + specular.result + ";",

			shininess.code,
			"	float shininess = max( 0.0001, " + shininess.result + " );",

			"	float specularStrength = 1.0;" // Ignored in MaterialNode ( replace to specular )
		];

		if ( alpha ) {

			output.push(
				alpha.code,
				'#ifdef ALPHATEST',

				'if ( ' + alpha.result + ' <= ALPHATEST ) discard;',

				'#endif'
			);

		}

		if ( normal ) {

			output.push(
				normal.code,
				'normal = ' + normal.result + ';'
			);

		}

		// optimization for now

		output.push( 'material.diffuseColor = ' + ( light ? 'vec3( 1.0 )' : 'diffuseColor' ) + ';' );

		output.push(
			// accumulation
			'material.specularColor = specular;',
			'material.specularShininess = shininess;',
			'material.specularStrength = specularStrength;',

			"#include <lights_fragment_begin>",
			"#include <lights_fragment_end>"
		);

		if ( light ) {

			output.push(
				light.code,
				"reflectedLight.directDiffuse = " + light.result + ";"
			);

			// apply color

			output.push(
				"reflectedLight.directDiffuse *= diffuseColor;",
				"reflectedLight.indirectDiffuse *= diffuseColor;"
			);

		}

		if ( ao ) {

			output.push(
				ao.code,
				"reflectedLight.indirectDiffuse *= " + ao.result + ";"
			);

		}

		if ( ambient ) {

			output.push(
				ambient.code,
				"reflectedLight.indirectDiffuse += " + ambient.result + ";"
			);

		}

		if ( shadow ) {

			output.push(
				shadow.code,
				"reflectedLight.directDiffuse *= " + shadow.result + ";",
				"reflectedLight.directSpecular *= " + shadow.result + ";"
			);

		}

		if ( emissive ) {

			output.push(
				emissive.code,
				"reflectedLight.directDiffuse += " + emissive.result + ";"
			);

		}

		output.push( "vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular;" );

		if ( environment ) {

			output.push( environment.code );

			if ( environmentAlpha ) {

				output.push(
					environmentAlpha.code,
					"outgoingLight = mix( outgoingLight, " + environment.result + ", " + environmentAlpha.result + " );"
				);

			} else {

				output.push( "outgoingLight = " + environment.result + ";" );

			}

		}
		/*
		switch( builder.material.combine ) {

			case THREE.ENVMAP_BLENDING_MULTIPLY:

				//output.push( "vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular;" );
				//outgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );

				break;

		}
	*/
		if ( alpha ) {

			output.push( "gl_FragColor = vec4( outgoingLight, " + alpha.result + " );" );

		} else {

			output.push( "gl_FragColor = vec4( outgoingLight, 1.0 );" );

		}

		output.push(
			"#include <premultiplied_alpha_fragment>",
			"#include <tonemapping_fragment>",
			"#include <encodings_fragment>",
			"#include <fog_fragment>"
		);

		code = output.join( "\n" );

	}

	return code;

};

PhongNode.prototype.copy = function ( source ) {

	Node.prototype.copy.call( this, source );

	// vertex

	if ( source.position ) this.position = source.position;

	// fragment

	this.color = source.color;
	this.specular = source.specular;
	this.shininess = source.shininess;

	if ( source.alpha ) this.alpha = source.alpha;

	if ( source.normal ) this.normal = source.normal;

	if ( source.light ) this.light = source.light;
	if ( source.shadow ) this.shadow = source.shadow;

	if ( source.ao ) this.ao = source.ao;

	if ( source.emissive ) this.emissive = source.emissive;
	if ( source.ambient ) this.ambient = source.ambient;

	if ( source.environment ) this.environment = source.environment;
	if ( source.environmentAlpha ) this.environmentAlpha = source.environmentAlpha;

};

PhongNode.prototype.toJSON = function ( meta ) {

	var data = this.getJSONNode( meta );

	if ( ! data ) {

		data = this.createJSONNode( meta );

		// vertex

		if ( this.position ) data.position = this.position.toJSON( meta ).uuid;

		// fragment

		data.color = this.color.toJSON( meta ).uuid;
		data.specular = this.specular.toJSON( meta ).uuid;
		data.shininess = this.shininess.toJSON( meta ).uuid;

		if ( this.alpha ) data.alpha = this.alpha.toJSON( meta ).uuid;

		if ( this.normal ) data.normal = this.normal.toJSON( meta ).uuid;

		if ( this.light ) data.light = this.light.toJSON( meta ).uuid;

		if ( this.ao ) data.ao = this.ao.toJSON( meta ).uuid;
		if ( this.ambient ) data.ambient = this.ambient.toJSON( meta ).uuid;
		if ( this.shadow ) data.shadow = this.shadow.toJSON( meta ).uuid;
		if ( this.emissive ) data.emissive = this.emissive.toJSON( meta ).uuid;

		if ( this.environment ) data.environment = this.environment.toJSON( meta ).uuid;
		if ( this.environmentAlpha ) data.environmentAlpha = this.environmentAlpha.toJSON( meta ).uuid;

	}

	return data;

};

export { PhongNode };
<commit_msg>unused normalScale<commit_after>/**
 * @author sunag / http://www.sunag.com.br/
 */

import { Node } from '../../core/Node.js';
import { ColorNode } from '../../inputs/ColorNode.js';
import { FloatNode } from '../../inputs/FloatNode.js';

function PhongNode() {

	Node.call( this );

	this.color = new ColorNode( 0xEEEEEE );
	this.specular = new ColorNode( 0x111111 );
	this.shininess = new FloatNode( 30 );

}

PhongNode.prototype = Object.create( Node.prototype );
PhongNode.prototype.constructor = PhongNode;
PhongNode.prototype.nodeType = "Phong";

PhongNode.prototype.build = function ( builder ) {

	var code;

	builder.define( 'PHONG' );

	builder.requires.lights = true;

	if ( builder.isShader( 'vertex' ) ) {

		var position = this.position ? this.position.parseAndBuildCode( builder, 'v3', { cache: 'position' } ) : undefined;

		builder.mergeUniform( THREE.UniformsUtils.merge( [

			THREE.UniformsLib.fog,
			THREE.UniformsLib.lights

		] ) );

		builder.addParsCode( [
			"varying vec3 vViewPosition;",

			"#ifndef FLAT_SHADED",

			"	varying vec3 vNormal;",

			"#endif",

			//"#include <encodings_pars_fragment>", // encoding functions
			"#include <fog_pars_vertex>",
			"#include <morphtarget_pars_vertex>",
			"#include <skinning_pars_vertex>",
			"#include <shadowmap_pars_vertex>",
			"#include <logdepthbuf_pars_vertex>",
			"#include <clipping_planes_pars_vertex>"
		].join( "\n" ) );

		var output = [
			"#include <beginnormal_vertex>",
			"#include <morphnormal_vertex>",
			"#include <skinbase_vertex>",
			"#include <skinnormal_vertex>",
			"#include <defaultnormal_vertex>",

			"#ifndef FLAT_SHADED", // normal computed with derivatives when FLAT_SHADED

			"	vNormal = normalize( transformedNormal );",

			"#endif",

			"#include <begin_vertex>"
		];

		if ( position ) {

			output.push(
				position.code,
				position.result ? "transformed = " + position.result + ";" : ''
			);

		}

		output.push(
			"	#include <morphtarget_vertex>",
			"	#include <skinning_vertex>",
			"	#include <project_vertex>",
			"	#include <fog_vertex>",
			"	#include <logdepthbuf_vertex>",
			"	#include <clipping_planes_vertex>",

			"	vViewPosition = - mvPosition.xyz;",

			"	#include <worldpos_vertex>",
			"	#include <shadowmap_vertex>",
			"	#include <fog_vertex>"
		);

		code = output.join( "\n" );

	} else {

		// parse all nodes to reuse generate codes

		this.color.parse( builder, { slot: 'color' } );
		this.specular.parse( builder );
		this.shininess.parse( builder );

		if ( this.alpha ) this.alpha.parse( builder );

		if ( this.normal ) this.normal.parse( builder );

		if ( this.light ) this.light.parse( builder, { cache: 'light' } );

		if ( this.ao ) this.ao.parse( builder );
		if ( this.ambient ) this.ambient.parse( builder );
		if ( this.shadow ) this.shadow.parse( builder );
		if ( this.emissive ) this.emissive.parse( builder, { slot: 'emissive' } );

		if ( this.environment ) this.environment.parse( builder, { slot: 'environment' } );
		if ( this.environmentAlpha && this.environment ) this.environmentAlpha.parse( builder );

		// build code

		var color = this.color.buildCode( builder, 'c', { slot: 'color' } );
		var specular = this.specular.buildCode( builder, 'c' );
		var shininess = this.shininess.buildCode( builder, 'f' );

		var alpha = this.alpha ? this.alpha.buildCode( builder, 'f' ) : undefined;

		var normal = this.normal ? this.normal.buildCode( builder, 'v3' ) : undefined;

		var light = this.light ? this.light.buildCode( builder, 'v3', { cache: 'light' } ) : undefined;

		var ao = this.ao ? this.ao.buildCode( builder, 'f' ) : undefined;
		var ambient = this.ambient ? this.ambient.buildCode( builder, 'c' ) : undefined;
		var shadow = this.shadow ? this.shadow.buildCode( builder, 'c' ) : undefined;
		var emissive = this.emissive ? this.emissive.buildCode( builder, 'c', { slot: 'emissive' } ) : undefined;

		var environment = this.environment ? this.environment.buildCode( builder, 'c', { slot: 'environment' } ) : undefined;
		var environmentAlpha = this.environmentAlpha && this.environment ? this.environmentAlpha.buildCode( builder, 'f' ) : undefined;

		builder.requires.transparent = alpha != undefined;

		builder.addParsCode( [
			"#include <fog_pars_fragment>",
			"#include <bsdfs>",
			"#include <lights_pars_begin>",
			"#include <lights_phong_pars_fragment>",
			"#include <shadowmap_pars_fragment>",
			"#include <logdepthbuf_pars_fragment>"
		].join( "\n" ) );

		var output = [
			// prevent undeclared normal
			"#include <normal_fragment_begin>",

			// prevent undeclared material
			"	BlinnPhongMaterial material;",

			color.code,
			"	vec3 diffuseColor = " + color.result + ";",
			"	ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );",

			"#include <logdepthbuf_fragment>",

			specular.code,
			"	vec3 specular = " + specular.result + ";",

			shininess.code,
			"	float shininess = max( 0.0001, " + shininess.result + " );",

			"	float specularStrength = 1.0;" // Ignored in MaterialNode ( replace to specular )
		];

		if ( alpha ) {

			output.push(
				alpha.code,
				'#ifdef ALPHATEST',

				'if ( ' + alpha.result + ' <= ALPHATEST ) discard;',

				'#endif'
			);

		}

		if ( normal ) {

			output.push(
				normal.code,
				'normal = ' + normal.result + ';'
			);

		}

		// optimization for now

		output.push( 'material.diffuseColor = ' + ( light ? 'vec3( 1.0 )' : 'diffuseColor' ) + ';' );

		output.push(
			// accumulation
			'material.specularColor = specular;',
			'material.specularShininess = shininess;',
			'material.specularStrength = specularStrength;',

			"#include <lights_fragment_begin>",
			"#include <lights_fragment_end>"
		);

		if ( light ) {

			output.push(
				light.code,
				"reflectedLight.directDiffuse = " + light.result + ";"
			);

			// apply color

			output.push(
				"reflectedLight.directDiffuse *= diffuseColor;",
				"reflectedLight.indirectDiffuse *= diffuseColor;"
			);

		}

		if ( ao ) {

			output.push(
				ao.code,
				"reflectedLight.indirectDiffuse *= " + ao.result + ";"
			);

		}

		if ( ambient ) {

			output.push(
				ambient.code,
				"reflectedLight.indirectDiffuse += " + ambient.result + ";"
			);

		}

		if ( shadow ) {

			output.push(
				shadow.code,
				"reflectedLight.directDiffuse *= " + shadow.result + ";",
				"reflectedLight.directSpecular *= " + shadow.result + ";"
			);

		}

		if ( emissive ) {

			output.push(
				emissive.code,
				"reflectedLight.directDiffuse += " + emissive.result + ";"
			);

		}

		output.push( "vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular;" );

		if ( environment ) {

			output.push( environment.code );

			if ( environmentAlpha ) {

				output.push(
					environmentAlpha.code,
					"outgoingLight = mix( outgoingLight, " + environment.result + ", " + environmentAlpha.result + " );"
				);

			} else {

				output.push( "outgoingLight = " + environment.result + ";" );

			}

		}
		/*
		switch( builder.material.combine ) {

			case THREE.ENVMAP_BLENDING_MULTIPLY:

				//output.push( "vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular;" );
				//outgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );

				break;

		}
	*/
		if ( alpha ) {

			output.push( "gl_FragColor = vec4( outgoingLight, " + alpha.result + " );" );

		} else {

			output.push( "gl_FragColor = vec4( outgoingLight, 1.0 );" );

		}

		output.push(
			"#include <premultiplied_alpha_fragment>",
			"#include <tonemapping_fragment>",
			"#include <encodings_fragment>",
			"#include <fog_fragment>"
		);

		code = output.join( "\n" );

	}

	return code;

};

PhongNode.prototype.copy = function ( source ) {

	Node.prototype.copy.call( this, source );

	// vertex

	if ( source.position ) this.position = source.position;

	// fragment

	this.color = source.color;
	this.specular = source.specular;
	this.shininess = source.shininess;

	if ( source.alpha ) this.alpha = source.alpha;

	if ( source.normal ) this.normal = source.normal;

	if ( source.light ) this.light = source.light;
	if ( source.shadow ) this.shadow = source.shadow;

	if ( source.ao ) this.ao = source.ao;

	if ( source.emissive ) this.emissive = source.emissive;
	if ( source.ambient ) this.ambient = source.ambient;

	if ( source.environment ) this.environment = source.environment;
	if ( source.environmentAlpha ) this.environmentAlpha = source.environmentAlpha;

};

PhongNode.prototype.toJSON = function ( meta ) {

	var data = this.getJSONNode( meta );

	if ( ! data ) {

		data = this.createJSONNode( meta );

		// vertex

		if ( this.position ) data.position = this.position.toJSON( meta ).uuid;

		// fragment

		data.color = this.color.toJSON( meta ).uuid;
		data.specular = this.specular.toJSON( meta ).uuid;
		data.shininess = this.shininess.toJSON( meta ).uuid;

		if ( this.alpha ) data.alpha = this.alpha.toJSON( meta ).uuid;

		if ( this.normal ) data.normal = this.normal.toJSON( meta ).uuid;

		if ( this.light ) data.light = this.light.toJSON( meta ).uuid;

		if ( this.ao ) data.ao = this.ao.toJSON( meta ).uuid;
		if ( this.ambient ) data.ambient = this.ambient.toJSON( meta ).uuid;
		if ( this.shadow ) data.shadow = this.shadow.toJSON( meta ).uuid;
		if ( this.emissive ) data.emissive = this.emissive.toJSON( meta ).uuid;

		if ( this.environment ) data.environment = this.environment.toJSON( meta ).uuid;
		if ( this.environmentAlpha ) data.environmentAlpha = this.environmentAlpha.toJSON( meta ).uuid;

	}

	return data;

};

export { PhongNode };
<|endoftext|>


<commit_before>/**
 * PHPR Post
 *
 * This object is used for communicating with AJAX handlers in PHPR.
 *
 * Usage:
 *
 * $.phpr.post('user:on_login', { data: {username:'', password:''}  });
 *
 * $.phpr.post('user:on_login').send({ data: {username:'', password:''}  });
 *
 * $.phpr.post('user:on_login').data({username:'', password:''}).send();
 *
 *
 * Usage with form:
 *
 * $('#myform').phpr().post('user:on_login', { data: {username:'', password:''}  });
 *
 * $.phpr.post('user:on_login').form('#myform').data({username:'', password:''}).send();
 *
 *
 * Usage with PHPR.validate:
 *
 * $('#myform').phpr().form()
 *   .defineFields(function(){
 *     this.defineField('username').required('What is your username?');
 *     this.defineField('password').required('You must enter a password!');
 *   })
 *   .validate()
 *   .post('user:on_signup', { success: function(){ alert('You are now logged in!'); }  });
 *
 */

(function($) {

	PHPR.postDefaults = {
		action: 'core:on_null',
		data: {},
		update: {},
		success: null, // On Success
		error: null, // On Failure
		complete: null, // On Complete
		afterUpdate: null, // On After Update
		beforeSend: null, // On Before Send
		selectorMode: true,
		lock: true,
		alert: null,
		confirm: null,
		evalScripts: true,
		execScriptsOnFail: true,
		loadIndicator: { show: true },
		customIndicator: null,
		animation: function(element, html) { element.html(html); }
	};

	PHPR.post = function(handler, context) {

		var o = {},
			_deferred = $.Deferred(),
			_handler = handler,
			_context = context || {},
			_data = {},
			_update = {},
			_form = null,
			_events = {
				beforeSend: [],
				afterUpdate: []
			};

		o.requestObj = null;
		o.indicatorObj = null;

		//
		// Services
		//

		o.form = function(element) {
			o.setFormElement(element);
			return this;
		}

		o.success = function(func) {
			_deferred.done(func);
			return this;
		}

		o.error = function(func) {
			_deferred.fail(func);
			return this;
		}

		o.complete = function(func) {
			_deferred.always(func);
			return this;
		}

		o.handler = o.action = function(value) {
			_handler = handler;
			return this;
		}

		o.confirm = function(value) {
			_context.confirm = value;
			return this;
		}

		o.alert = function(value) {
			_context.alert = value;
			return this;
		}

		o.beforeSend = function(value) {
			if ($.isArray(_events.beforeSend))
				_events.beforeSend.push(value);
			else
				_events.beforeSend = value;

			return this;
		}

		o.afterUpdate = function(func) {
			if ($.isArray(_events.afterUpdate))
				_events.afterUpdate.push(value);
			else
				_events.afterUpdate = value;

			return this;
		}

		o.update = function(element, partial) {
			if (partial)
				_update[element] = partial;
			else
				_update = element;
			return this;
		}

		o.data = function(field, value) {
			if (typeof field == "object")
				_data = field;
			else if (typeof value != "undefined")
				_data[field] = value;
			return this;
		}

		o.queue = function(value) {
			_context.lock = !value;
			return this;
		}

		o.loadIndicator = function(data) {
			if (typeof data == "boolean")
				_context.loadIndicator = { show: data };
			else
				_context.loadIndicator = $.extend(true, _context.loadIndicator, data);
			return this;
		}

		//
		// Options
		//

		o.setDefaultOptions = function(defaultOptions) {
			PHPR.postDefaults = $.extend(true, PHPR.postDefaults, defaultOptions);
		}

		o.setOption = function(option, value) {
			_context[option] = value;
			return this;
		}

		o.getOption = function(option) {
			return _context[option];
		}

		o.buildOptions = function(context) {
			context = $.extend(true, {}, PHPR.postDefaults, _context, context);

			if (_handler)
				context.action = _handler;

			// Build partials to update
			if (typeof context.update == 'object' && typeof _update == 'object')
				context.update = $.extend(true, context.update, _update);
			else if (typeof _update == 'string')
				context.update = _update;

			return _context = context;
		}

		o.buildPostData = function(context) {
			if (context.data instanceof jQuery)
				context.data = o.serializeElement(context.data);

			context.data = $.extend(true, context.data, _data);

			if (_form)
				context.data = $.extend(true, context.data, o.serializeElement(_form));

			return _context = context;
		}

		//
		// Form Element
		//

		o.setFormElement = function(form) {
			form = (!form) ? jQuery('<form></form>') : form;
			form = (form instanceof jQuery) ? form : jQuery(form);
			form = (form.is('form')) ? form : form.closest('form');
			form = (form.attr('id')) ? form : form.attr('id', 'form-element');
			_form = form;
			return this;
		}

		o.getFormElement = function() {
			return _form;
		}

		o.getFormUrl = function() {
			return (_form) ? _form.attr('action') : location.pathname;
		}

		o.serializeElement = function(element) {
			var params = {};

			$.each(element.serializeArray(), function(index, value) {
				if (value.name.substr(value.name.length - 2, 2) === '[]') {
					var name = value.name.substr(0, value.name.length - 2);

					if (!params[name]) {
						params[name] = [];
					}

					params[name].push(value.value);
				}
				else {
					params[value.name] = value.value;
				}
			});

			return params;
		}

		//
		// Send request
		//

		o.send = function(context) {
			context = o.buildOptions(context);

			if (context.beforeSend)
				_execute_event('beforeSend');

			context = o.buildPostData(context);

			if (context.alert)
				alert(context.alert);

			if (context.confirm && !o.popupConfirm(context))
				return;

			// Show loading indicator
			if (context.loadIndicator.show) {
				if (_form)
					context.loadIndicator.element = _form;

				o.indicatorObj = (context.customIndicator)
					? context.customIndicator(context.loadIndicator)
					: PHPR.indicator(context.loadIndicator);

				o.indicatorObj.show();
			}

			// Execute javascript after partials have loaded
			var tmpOptions = $.extend(true, {}, context, { evalScripts: false });

			// Prepare the request
			o.requestObj = new PHPR.request(o.getFormUrl(), context.action, tmpOptions);
			o.requestObj.postObj = o;

			// On Complete
			o.requestObj.always(o.onComplete);

			// On Success
			o.requestObj.done(o.onSuccess);

			// On Failure
			o.requestObj.fail(o.onFailure);

			// Execute the request
			o.requestObj.send();
			return false;
		}

		o.onComplete = function(requestObj) {
			_context.complete && _context.complete(requestObj);

			$(PHPR).trigger('complete.post', [requestObj]);
		}

		o.onSuccess = function(requestObj) {

			// Hide loading indicator
			if (_context.loadIndicator.show && o.indicatorObj && (_context.customIndicator || _context.loadIndicator.hideOnSuccess)) {
				o.indicatorObj.hide();
			}

			o.updatePartials();

			_context.success && _context.success(requestObj);

			if (_context.evalScripts)
				$.globalEval(requestObj.javascript);

			$(PHPR).trigger('success.post', [requestObj]);
			$(window).trigger('onAfterAjaxUpdateGlobal');
		}

		o.onFailure = function(requestObj) {

			// Hide loading indicator
			if (_context.loadIndicator.show && o.indicatorObj) {
				o.indicatorObj.hide();
			}

			if (_context.error && !_context.error(requestObj))
				return;

			if (requestObj.errorMessage)
				o.popupError(requestObj);

			$(PHPR).trigger('error.post', [requestObj]);
		}

		//
		// Behaviors
		//

		o.popupError = function(requestObj) {
			alert(requestObj.errorMessage);
		}

		o.popupConfirm = function(postObj) {
			return confirm(postObj.confirm);
		}

		//
		// Update partials
		//

		o.updatePartials = function() {
			if (/window.location=/.test(o.requestObj.javascript))
				return;

			if ($.isArray(_context.update) || _context.update == 'multi')
				o.updatePartialsMulti();
			else
				o.updatePartialsSingle();

			if (_context.afterUpdate)
				_execute_event('afterUpdate');
		}

		o.updatePartialsSingle = function() {
			var element = null;
			if (_context.update instanceof jQuery)
				element = _context.update;
			else
				element = $(_context.update);

			if (element && element.length) {
				element.html(o.requestObj.html);
				$(window).trigger('onAfterAjaxUpdate', element);
			}
		}

		o.updatePartialsMulti = function() {
			var oHtml = o.requestObj.html,
				pattern = />>[^<>]*<</g,
				patches = oHtml.match(pattern) || [],
				updateElements = [];

			for (var i = 0, l = patches.length; i < l; ++i) {
				var index = oHtml.indexOf(patches[i]) + patches[i].length;

				var html = (i < patches.length-1)
					? oHtml.slice(index, oHtml.indexOf(patches[i+1]))
					: oHtml.slice(index);

				var id = patches[i].slice(2, patches[i].length-2);

				if (id) {
					var element;

					if (_context.selectorMode)
						element = $(id);
					else
						element = $('#' + id);

					if (!_context.animation(element, html))
						element.html(html);

					updateElements.push(element);
				}
			}

			$.each(updateElements, function(k, v) {
				$(window).trigger('onAfterAjaxUpdate', v);
			});
		}

		//
		// Internals
		//

		var _execute_event = function(eventName, params) {
			var eventObj;

			// Fire chained in events
			eventObj = _events[eventName];

			if ($.isArray(eventObj)) {
				$.each(eventObj, function(index, func){
					if (typeof func == 'function')
						func();
				});
			}
			else if (typeof eventObj == 'function') {
				eventObj();
			}

			// Fire contextual event
			eventObj = _context[eventName];
			if (eventObj && typeof eventObj == 'function') {
				eventObj();
			}
		}

		// Extend the post object with DOM
		o = $.extend(true, o, PHPR.post);

		// (This creates too much unpredictability)
		// If the second parameter is present, then automatically fire the request
		// if (options)
		// 	return o.send();

		// Promote the post object with a promise
		return _deferred.promise(o);
	}

})(jQuery);
<commit_msg>Post events should stack.<commit_after>/**
 * PHPR Post
 *
 * This object is used for communicating with AJAX handlers in PHPR.
 *
 * Usage:
 *
 * $.phpr.post('user:on_login', { data: {username:'', password:''}  });
 *
 * $.phpr.post('user:on_login').send({ data: {username:'', password:''}  });
 *
 * $.phpr.post('user:on_login').data({username:'', password:''}).send();
 *
 *
 * Usage with form:
 *
 * $('#myform').phpr().post('user:on_login', { data: {username:'', password:''}  });
 *
 * $.phpr.post('user:on_login').form('#myform').data({username:'', password:''}).send();
 *
 *
 * Usage with PHPR.validate:
 *
 * $('#myform').phpr().form()
 *   .defineFields(function(){
 *     this.defineField('username').required('What is your username?');
 *     this.defineField('password').required('You must enter a password!');
 *   })
 *   .validate()
 *   .post('user:on_signup', { success: function(){ alert('You are now logged in!'); }  });
 *
 */

(function($) {

	PHPR.postDefaults = {
		action: 'core:on_null',
		data: {},
		update: {},
		success: null, // On Success
		error: null, // On Failure
		complete: null, // On Complete
		afterUpdate: null, // On After Update
		beforeSend: null, // On Before Send
		selectorMode: true,
		lock: true,
		alert: null,
		confirm: null,
		evalScripts: true,
		execScriptsOnFail: true,
		loadIndicator: { show: true },
		customIndicator: null,
		animation: function(element, html) { element.html(html); }
	};

	PHPR.post = function(handler, context) {

		var o = {},
			_deferred = $.Deferred(),
			_handler = handler,
			_context = context || {},
			_data = {},
			_update = {},
			_form = null,
			_events = {
				beforeSend: [],
				complete: [],
				success: [],
				error: [],
				afterUpdate: []
			};

		o.requestObj = null;
		o.indicatorObj = null;

		//
		// Services
		//

		o.form = function(element) {
			o.setFormElement(element);
			return this;
		}

		o.handler = o.action = function(value) {
			_handler = handler;
			return this;
		}

		o.confirm = function(value) {
			_context.confirm = value;
			return this;
		}

		o.alert = function(value) {
			_context.alert = value;
			return this;
		}

		o.success = function(func) {
			if ($.isArray(_events.success))
				_events.success.push(func);
			else
				_events.success = func;

			return this;
		}

		o.error = function(func) {
			if ($.isArray(_events.error))
				_events.error.push(func);
			else
				_events.error = func;

			return this;
		}

		o.complete = function(func) {
			if ($.isArray(_events.complete))
				_events.complete.push(func);
			else
				_events.complete = func;

			return this;
		}

		o.beforeSend = function(func) {
			if ($.isArray(_events.beforeSend))
				_events.beforeSend.push(func);
			else
				_events.beforeSend = func;

			return this;
		}

		o.afterUpdate = function(func) {
			if ($.isArray(_events.afterUpdate))
				_events.afterUpdate.push(func);
			else
				_events.afterUpdate = func;

			return this;
		}

		o.update = function(element, partial) {
			if (partial)
				_update[element] = partial;
			else
				_update = element;
			return this;
		}

		o.data = function(field, value) {
			if (typeof field == "object")
				_data = field;
			else if (typeof value != "undefined")
				_data[field] = value;
			return this;
		}

		o.queue = function(value) {
			_context.lock = !value;
			return this;
		}

		o.loadIndicator = function(data) {
			if (typeof data == "boolean")
				_context.loadIndicator = { show: data };
			else
				_context.loadIndicator = $.extend(true, _context.loadIndicator, data);
			return this;
		}

		//
		// Options
		//

		o.setDefaultOptions = function(defaultOptions) {
			PHPR.postDefaults = $.extend(true, PHPR.postDefaults, defaultOptions);
		}

		o.setOption = function(option, value) {
			_context[option] = value;
			return this;
		}

		o.getOption = function(option) {
			return _context[option];
		}

		o.buildOptions = function(context) {
			context = $.extend(true, {}, PHPR.postDefaults, _context, context);

			if (_handler)
				context.action = _handler;

			// Build partials to update
			if (typeof context.update == 'object' && typeof _update == 'object')
				context.update = $.extend(true, context.update, _update);
			else if (typeof _update == 'string')
				context.update = _update;

			return _context = context;
		}

		o.buildPostData = function(context) {
			if (context.data instanceof jQuery)
				context.data = o.serializeElement(context.data);

			context.data = $.extend(true, context.data, _data);

			if (_form)
				context.data = $.extend(true, context.data, o.serializeElement(_form));

			return _context = context;
		}

		//
		// Form Element
		//

		o.setFormElement = function(form) {
			form = (!form) ? jQuery('<form></form>') : form;
			form = (form instanceof jQuery) ? form : jQuery(form);
			form = (form.is('form')) ? form : form.closest('form');
			form = (form.attr('id')) ? form : form.attr('id', 'form-element');
			_form = form;
			return this;
		}

		o.getFormElement = function() {
			return _form;
		}

		o.getFormUrl = function() {
			return (_form) ? _form.attr('action') : location.pathname;
		}

		o.serializeElement = function(element) {
			var params = {};

			$.each(element.serializeArray(), function(index, value) {
				if (value.name.substr(value.name.length - 2, 2) === '[]') {
					var name = value.name.substr(0, value.name.length - 2);

					if (!params[name]) {
						params[name] = [];
					}

					params[name].push(value.value);
				}
				else {
					params[value.name] = value.value;
				}
			});

			return params;
		}

		//
		// Send request
		//

		o.send = function(context) {
			context = o.buildOptions(context);

			// On Before Send
			_execute_event('beforeSend');

			context = o.buildPostData(context);

			if (context.alert)
				alert(context.alert);

			if (context.confirm && !o.popupConfirm(context))
				return;

			// Show loading indicator
			if (context.loadIndicator.show) {
				if (_form)
					context.loadIndicator.element = _form;

				o.indicatorObj = (context.customIndicator)
					? context.customIndicator(context.loadIndicator)
					: PHPR.indicator(context.loadIndicator);

				o.indicatorObj.show();
			}

			// Execute javascript after partials have loaded
			var tmpOptions = $.extend(true, {}, context, { evalScripts: false });

			// Prepare the request
			o.requestObj = new PHPR.request(o.getFormUrl(), context.action, tmpOptions);
			o.requestObj.postObj = o;

			// On Complete
			o.requestObj.always(o.onComplete);

			// On Success
			o.requestObj.done(o.onSuccess);

			// On Failure
			o.requestObj.fail(o.onFailure);

			// Execute the request
			o.requestObj.send();
			return false;
		}

		o.onComplete = function(requestObj) {
			// On Complete
			_execute_event('complete', [requestObj]);
		}

		o.onSuccess = function(requestObj) {
			// Hide loading indicator
			if (_context.loadIndicator.show && o.indicatorObj && (_context.customIndicator || _context.loadIndicator.hideOnSuccess)) {
				o.indicatorObj.hide();
			}

			// On Success
			_execute_event('success', [requestObj]);

			// Update partials
			o.updatePartials();

			if (_context.evalScripts)
				$.globalEval(requestObj.javascript);

			$(window).trigger('onAfterAjaxUpdateGlobal');
		}

		o.onFailure = function(requestObj) {

			// Hide loading indicator
			if (_context.loadIndicator.show && o.indicatorObj) {
				o.indicatorObj.hide();
			}

			// On Error/Failure
			if (!_execute_event('error', [requestObj]))
				return;

			if (requestObj.errorMessage)
				o.popupError(requestObj);
		}

		//
		// Behaviors
		//

		o.popupError = function(requestObj) {
			alert(requestObj.errorMessage);
		}

		o.popupConfirm = function(postObj) {
			return confirm(postObj.confirm);
		}

		//
		// Update partials
		//

		o.updatePartials = function() {
			if (/window.location=/.test(o.requestObj.javascript))
				return;

			if ($.isArray(_context.update) || _context.update == 'multi')
				o.updatePartialsMulti();
			else
				o.updatePartialsSingle();

			// On After Update
			_execute_event('afterUpdate');
		}

		o.updatePartialsSingle = function() {
			var element = null;
			if (_context.update instanceof jQuery)
				element = _context.update;
			else
				element = $(_context.update);

			if (element && element.length) {
				element.html(o.requestObj.html);
				$(window).trigger('onAfterAjaxUpdate', element);
			}
		}

		o.updatePartialsMulti = function() {
			var oHtml = o.requestObj.html,
				pattern = />>[^<>]*<</g,
				patches = oHtml.match(pattern) || [],
				updateElements = [];

			for (var i = 0, l = patches.length; i < l; ++i) {
				var index = oHtml.indexOf(patches[i]) + patches[i].length;

				var html = (i < patches.length-1)
					? oHtml.slice(index, oHtml.indexOf(patches[i+1]))
					: oHtml.slice(index);

				var id = patches[i].slice(2, patches[i].length-2);

				if (id) {
					var element;

					if (_context.selectorMode)
						element = $(id);
					else
						element = $('#' + id);

					if (!_context.animation(element, html))
						element.html(html);

					updateElements.push(element);
				}
			}

			$.each(updateElements, function(k, v) {
				$(window).trigger('onAfterAjaxUpdate', v);
			});
		}

		//
		// Internals
		//

		var _execute_event = function(eventName, params) {
			var eventObj,
				result = true;

			// Fire chained in events
			eventObj = _events[eventName];

			if ($.isArray(eventObj)) {
				$.each(eventObj, function(index, func){
					if (typeof func == 'function') {
						if (func.apply(o, params) === false)
							result = false;
					}
				});
			}
			else if (typeof eventObj == 'function') {
				if (eventObj.apply(o, params) === false)
					result = false;
			}

			// Fire contextual event
			eventObj = _context[eventName];
			if (eventObj && typeof eventObj == 'function') {
				if (eventObj.apply(o, params) === false)
					result = false;
			}

			// Trigger jQ event (success.post, error.post, etc)
			$(PHPR).trigger(eventName + '.post', params);

			return result;
		}

		// Extend the post object with DOM
		o = $.extend(true, o, PHPR.post);

		// (This creates too much unpredictability)
		// If the second parameter is present, then automatically fire the request
		// if (options)
		// 	return o.send();

		// Promote the post object with a promise
		return _deferred.promise(o);
	}

})(jQuery);
<|endoftext|>


<commit_before>var h = require('mutant/h')
var computed = require('mutant/computed')
var nest = require('depnest')
var extend = require('xtend')

exports.needs = nest({
  'message.html': {
    decorate: 'reduce',
    layout: 'first',
    markdown: 'first'
  },
  'keys.sync.id': 'first',
  'profile.html.person': 'first',
  'about.obs.name': 'first',
  'blob.sync.url': 'first'
})

exports.gives = nest('message.html.render')

exports.create = function (api) {
  return nest('message.html.render', function about (msg, opts) {
    if (msg.value.content.type !== 'about') return
    if (!msg.value.content.about) return

    var c = msg.value.content
    var self = msg.value.author === c.about
    var content = []

    if (c.name) {
      var target = api.profile.html.person(c.about, c.name)
      content.push(computed([self, api.about.obs.name(c.about), c.name], (self, a, b) => {
        if (self) {
          return ['self identifies as "', target, '"']
        } else if (a === b) {
          return ['identified ', api.profile.html.person(c.about)]
        } else {
          return ['identifies ', api.profile.html.person(c.about), ' as "', target, '"']
        }
      }))
    }

    if (c.image) {
      if (!content.length) {
        var imageAction = self ? 'self assigned a display image' : ['assigned a display image to ', api.profile.html.person(c.about)]
        content.push(imageAction)
      }

      content.push(h('a AboutImage', {
        href: c.about
      }, [
        h('img', {src: api.blob.sync.url(c.image)})
      ]))
    }

    var elements = []

    if (content.length) {
      var element = api.message.html.layout(msg, extend({
        content, layout: 'mini'
      }, opts))
      elements.push(api.message.html.decorate(element, { msg }))
    }

    if (c.description) {
      elements.push(api.message.html.decorate(api.message.html.layout(msg, extend({
        content: [
          self ? 'self assigned a description' : ['assigned a description to ', api.profile.html.person(c.about)],
          api.message.html.markdown(c.description)
        ],
        layout: 'mini'
      }, opts)), { msg }))
    }

    return elements
  })
}
<commit_msg>filter broken about messages from being rendered<commit_after>var h = require('mutant/h')
var computed = require('mutant/computed')
var nest = require('depnest')
var extend = require('xtend')
var ref = require('ssb-ref')

exports.needs = nest({
  'message.html': {
    decorate: 'reduce',
    layout: 'first',
    markdown: 'first'
  },
  'keys.sync.id': 'first',
  'profile.html.person': 'first',
  'about.obs.name': 'first',
  'blob.sync.url': 'first'
})

exports.gives = nest('message.html.render')

exports.create = function (api) {
  return nest('message.html.render', function about (msg, opts) {
    if (msg.value.content.type !== 'about') return
    if (!ref.isFeed(msg.value.content.about)) return

    var c = msg.value.content
    var self = msg.value.author === c.about
    var content = []

    if (c.name) {
      var target = api.profile.html.person(c.about, c.name)
      content.push(computed([self, api.about.obs.name(c.about), c.name], (self, a, b) => {
        if (self) {
          return ['self identifies as "', target, '"']
        } else if (a === b) {
          return ['identified ', api.profile.html.person(c.about)]
        } else {
          return ['identifies ', api.profile.html.person(c.about), ' as "', target, '"']
        }
      }))
    }

    if (c.image) {
      if (!content.length) {
        var imageAction = self ? 'self assigned a display image' : ['assigned a display image to ', api.profile.html.person(c.about)]
        content.push(imageAction)
      }

      content.push(h('a AboutImage', {
        href: c.about
      }, [
        h('img', {src: api.blob.sync.url(c.image)})
      ]))
    }

    var elements = []

    if (content.length) {
      var element = api.message.html.layout(msg, extend({
        content, layout: 'mini'
      }, opts))
      elements.push(api.message.html.decorate(element, { msg }))
    }

    if (c.description) {
      elements.push(api.message.html.decorate(api.message.html.layout(msg, extend({
        content: [
          self ? 'self assigned a description' : ['assigned a description to ', api.profile.html.person(c.about)],
          api.message.html.markdown(c.description)
        ],
        layout: 'mini'
      }, opts)), { msg }))
    }

    return elements
  })
}
<|endoftext|>


<commit_before>'use strict';

/*
* When adding names to the namespace, ensure that they are added in alphabetical order according to alias (namespace key).
*/

var ns = [];

ns.push({
	'alias': 'SECONDS_IN_DAY',
	'path': '@stdlib/time/constants/seconds-in-day',
	'value': require( '@stdlib/time/constants/seconds-in-day' ),
	'type': 'number',
	'related': []
});

ns.push({
	'alias': 'SECONDS_IN_HOUR',
	'path': '@stdlib/time/constants/seconds-in-hour',
	'value': require( '@stdlib/time/constants/seconds-in-hour' ),
	'type': 'number',
	'related': []
});

ns.push({
	'alias': 'SECONDS_IN_MINUTE',
	'path': '@stdlib/time/constants/seconds-in-minute',
	'value': require( '@stdlib/time/constants/seconds-in-minute' ),
	'type': 'number',
	'related': []
});

ns.push({
	'alias': 'SECONDS_IN_WEEK',
	'path': '@stdlib/time/constants/seconds-in-week',
	'value': require( '@stdlib/time/constants/seconds-in-week' ),
	'type': 'number',
	'related': []
});

ns.push({
	'alias': 'setReadOnly',
	'path': '@stdlib/utils/define-read-only-property',
	'value': require( '@stdlib/utils/define-read-only-property' ),
	'type': 'Function',
	'related': []
});

ns.push({
	'alias': 'startsWith',
	'path': '@stdlib/string/starts-with',
	'value': require( '@stdlib/string/starts-with' ),
	'type': 'Function',
	'related': [
		'@stdlib/string/ends-with'
	]
});

ns.push({
	'alias': 'stdin',
	'path': '@stdlib/utils/read-stdin',
	'value': require( '@stdlib/utils/read-stdin' ),
	'type': 'Function',
	'related': []
});

// EXPORTS //

module.exports = ns;
<commit_msg>Update namespace<commit_after>'use strict';

/*
* When adding names to the namespace, ensure that they are added in alphabetical order according to alias (namespace key).
*/

var ns = [];

ns.push({
	'alias': 'SECONDS_IN_DAY',
	'path': '@stdlib/time/constants/seconds-in-day',
	'value': require( '@stdlib/time/constants/seconds-in-day' ),
	'type': 'number',
	'related': []
});

ns.push({
	'alias': 'SECONDS_IN_HOUR',
	'path': '@stdlib/time/constants/seconds-in-hour',
	'value': require( '@stdlib/time/constants/seconds-in-hour' ),
	'type': 'number',
	'related': []
});

ns.push({
	'alias': 'SECONDS_IN_MINUTE',
	'path': '@stdlib/time/constants/seconds-in-minute',
	'value': require( '@stdlib/time/constants/seconds-in-minute' ),
	'type': 'number',
	'related': []
});

ns.push({
	'alias': 'SECONDS_IN_WEEK',
	'path': '@stdlib/time/constants/seconds-in-week',
	'value': require( '@stdlib/time/constants/seconds-in-week' ),
	'type': 'number',
	'related': []
});

ns.push({
	'alias': 'setReadOnly',
	'path': '@stdlib/utils/define-read-only-property',
	'value': require( '@stdlib/utils/define-read-only-property' ),
	'type': 'Function',
	'related': []
});

ns.push({
	'alias': 'startsWith',
	'path': '@stdlib/string/starts-with',
	'value': require( '@stdlib/string/starts-with' ),
	'type': 'Function',
	'related': [
		'@stdlib/string/ends-with'
	]
});

// EXPORTS //

module.exports = ns;
<|endoftext|>


<commit_before>/* eslint-env node */

module.exports = function(environment) {
    const authorizationType = 'cookie';

    const ENV = {
        modulePrefix: 'preprint-service',
        appName: 'Preprints',
        environment: environment,
        rootURL: '/',
        locationType: 'auto',
        authorizationType: authorizationType,
        sentryDSN: 'http://test@localhost/80' || process.env.SENTRY_DSN,
        'ember-simple-auth': {
            authorizer: `authorizer:osf-${authorizationType}`,
            authenticator: `authenticator:osf-${authorizationType}`
        },
        providerAssetsURL: process.env.PROVIDER_ASSETS_URL || 'https://staging-cdn.osf.io/preprints-assets/',
        // path to local preprint provider assets (relative to public/assets/)
        providerAssetsPath: 'osf-assets/files/preprints-assets',
        EmberENV: {
            FEATURES: {
                // Here you can enable experimental features on an ember canary build
                // e.g. 'with-controller': true
            }
        },
        APP: {
            // Here you can pass flags/options to your application instance
            // when it is created
        },
        SHARE: {
            baseUrl: process.env.SHARE_BASE_URL || 'https://staging-share.osf.io/',
            searchUrl: process.env.SHARE_SEARCH_URL || 'https://staging-share.osf.io/api/v2/search/creativeworks/_search'
        },
        moment: {
            outputFormat: 'YYYY-MM-DD hh:mm a'
        },
        PREPRINTS: {
            defaultProvider: 'osf',
            // Logos are needed for open graph sharing meta tags (Facebook, LinkedIn, etc) and must be at least 200x200
            providers: [
                // OSF must be the first provider
                {
                    id: 'osf',
                    logoSharing: {
                        path: '/assets/img/provider_logos/osf-dark.png',
                        type: 'image/png',
                        width: 363,
                        height: 242
                    },
                    permissionLanguage: 'no_trademark'
                },
                {
                    id: 'engrxiv',
                    permissionLanguage: 'arxiv_non_endorsement'
                },
                {
                    id: 'socarxiv',
                    permissionLanguage: 'arxiv_trademark_license'
                },
                {
                    id: 'psyarxiv',
                    permissionLanguage: 'arxiv_trademark_license'
                },
                {
                    id: 'bitss',
                    permissionLanguage: 'no_trademark'
                },
                {
                    id: 'scielo',
                    permissionLanguage: 'no_trademark'
                },
                {
                    id: 'agrixiv',
                    permissionLanguage: 'arxiv_non_endorsement'
                },
                {
                    id: 'lawarxiv',
                    permissionLanguage: 'arxiv_non_endorsement'
                },
                {
                    id: 'focusarchive',
                    permissionLanguage: 'no_trademark'
                },
                {
                    id: 'paleorxiv',
                    permissionLanguage: 'arxiv_non_endorsement'
                },
                {
                    id: 'mindrxiv',
                    permissionLanguage: 'arxiv_non_endorsement'
                },
                {
                    id: 'lissa',
                    permissionLanguage: 'no_trademark'
                },
                {
                    id: 'sportrxiv',
                    permissionLanguage: 'no_trademark'
                },
                {
                    id: 'thesiscommons',
                    permissionLanguage: 'no_trademark'
                },
                {
                    id: 'asu',
                    permissionLanguage: 'no_trademark'
                }
            ],
        },
        i18n: {
            defaultLocale: 'en'
        },
        metricsAdapters: [
            {
                name: 'GoogleAnalytics',
                environments: [process.env.KEEN_ENVIRONMENT] || ['production'],
                config: {
                    id: process.env.GOOGLE_ANALYTICS_ID
                }
            },
            {
                name: 'Keen',
                environments: [process.env.KEEN_ENVIRONMENT] || ['production'],
                config: {
                    private: {
                        projectId: process.env.PREPRINTS_PRIVATE_PROJECT_ID,
                        writeKey: process.env.PREPRINTS_PRIVATE_WRITE_KEY
                    },
                    public: {
                        projectId: process.env.PREPRINTS_PUBLIC_PROJECT_ID,
                        writeKey: process.env.PREPRINTS_PUBLIC_WRITE_KEY
                    }
                }
            },

        ],
        FB_APP_ID: process.env.FB_APP_ID,
        whiteListedProviders: [
            'arXiv',
            'bioRxiv',
            'Cogprints',
            'PeerJ',
            'Research Papers in Economics',
            'Preprints.org'
        ].map(item => item.toLowerCase()),
    };

    if (environment === 'development') {
        // ENV.APP.LOG_RESOLVER = true;
        // ENV.APP.LOG_ACTIVE_GENERATION = true;
        // ENV.APP.LOG_TRANSITIONS = true;
        // ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
        // ENV.APP.LOG_VIEW_LOOKUPS = true;

        ENV.metricsAdapters[0].config.cookieDomain = 'none';
    }

    if (environment === 'test') {
        // Testem prefers this...
        ENV.baseURL = '/';
        ENV.locationType = 'none';

        // keep test console output quieter
        ENV.APP.LOG_ACTIVE_GENERATION = false;
        ENV.APP.LOG_VIEW_LOOKUPS = false;

        ENV.APP.rootElement = '#ember-testing';

        // Don't make external requests during unit test
        // TODO: Provide mocks for all components with manual AJAX calls in the future.
        ENV.SHARE.baseUrl = '/nowhere';
        ENV.SHARE.searchUrl = '/nowhere';
        ENV.OSF = {};
        ENV.OSF.shareSearchUrl = '/nowhere';

        ENV.metricsAdapters[0].config.cookieDomain = 'none'
    }

    if (environment === 'production') {
        ENV.sentryDSN = process.env.SENTRY_DSN || 'https://2f0a61d03b99480ea11e259edec18bd9@sentry.cos.io/45';
        ENV.ASSET_SUFFIX = process.env.GIT_COMMIT || 'git_commit_env_not_set';
    } else {
        // Fallback to throwaway defaults if the environment variables are not set
        ENV.metricsAdapters[0].config.id = ENV.metricsAdapters[0].config.id || 'UA-84580271-1';
        ENV.FB_APP_ID = ENV.FB_APP_ID || '1039002926217080';
    }

    return ENV;
};
<commit_msg>Added note in config/environment.js about setting providerAssetsURL to 'local'<commit_after>/* eslint-env node */

module.exports = function(environment) {
    const authorizationType = 'cookie';

    const ENV = {
        modulePrefix: 'preprint-service',
        appName: 'Preprints',
        environment: environment,
        rootURL: '/',
        locationType: 'auto',
        authorizationType: authorizationType,
        sentryDSN: 'http://test@localhost/80' || process.env.SENTRY_DSN,
        'ember-simple-auth': {
            authorizer: `authorizer:osf-${authorizationType}`,
            authenticator: `authenticator:osf-${authorizationType}`
        },
        // Set to 'local' to use local assets at providerAssetsPath.
        providerAssetsURL: process.env.PROVIDER_ASSETS_URL || 'https://staging-cdn.osf.io/preprints-assets/',
        // path to local preprint provider assets (relative to public/assets/)
        providerAssetsPath: 'osf-assets/files/preprints-assets',
        EmberENV: {
            FEATURES: {
                // Here you can enable experimental features on an ember canary build
                // e.g. 'with-controller': true
            }
        },
        APP: {
            // Here you can pass flags/options to your application instance
            // when it is created
        },
        SHARE: {
            baseUrl: process.env.SHARE_BASE_URL || 'https://staging-share.osf.io/',
            searchUrl: process.env.SHARE_SEARCH_URL || 'https://staging-share.osf.io/api/v2/search/creativeworks/_search'
        },
        moment: {
            outputFormat: 'YYYY-MM-DD hh:mm a'
        },
        PREPRINTS: {
            defaultProvider: 'osf',
            // Logos are needed for open graph sharing meta tags (Facebook, LinkedIn, etc) and must be at least 200x200
            providers: [
                // OSF must be the first provider
                {
                    id: 'osf',
                    logoSharing: {
                        path: '/assets/img/provider_logos/osf-dark.png',
                        type: 'image/png',
                        width: 363,
                        height: 242
                    },
                    permissionLanguage: 'no_trademark'
                },
                {
                    id: 'engrxiv',
                    permissionLanguage: 'arxiv_non_endorsement'
                },
                {
                    id: 'socarxiv',
                    permissionLanguage: 'arxiv_trademark_license'
                },
                {
                    id: 'psyarxiv',
                    permissionLanguage: 'arxiv_trademark_license'
                },
                {
                    id: 'bitss',
                    permissionLanguage: 'no_trademark'
                },
                {
                    id: 'scielo',
                    permissionLanguage: 'no_trademark'
                },
                {
                    id: 'agrixiv',
                    permissionLanguage: 'arxiv_non_endorsement'
                },
                {
                    id: 'lawarxiv',
                    permissionLanguage: 'arxiv_non_endorsement'
                },
                {
                    id: 'focusarchive',
                    permissionLanguage: 'no_trademark'
                },
                {
                    id: 'paleorxiv',
                    permissionLanguage: 'arxiv_non_endorsement'
                },
                {
                    id: 'mindrxiv',
                    permissionLanguage: 'arxiv_non_endorsement'
                },
                {
                    id: 'lissa',
                    permissionLanguage: 'no_trademark'
                },
                {
                    id: 'sportrxiv',
                    permissionLanguage: 'no_trademark'
                },
                {
                    id: 'thesiscommons',
                    permissionLanguage: 'no_trademark'
                },
                {
                    id: 'asu',
                    permissionLanguage: 'no_trademark'
                }
            ],
        },
        i18n: {
            defaultLocale: 'en'
        },
        metricsAdapters: [
            {
                name: 'GoogleAnalytics',
                environments: [process.env.KEEN_ENVIRONMENT] || ['production'],
                config: {
                    id: process.env.GOOGLE_ANALYTICS_ID
                }
            },
            {
                name: 'Keen',
                environments: [process.env.KEEN_ENVIRONMENT] || ['production'],
                config: {
                    private: {
                        projectId: process.env.PREPRINTS_PRIVATE_PROJECT_ID,
                        writeKey: process.env.PREPRINTS_PRIVATE_WRITE_KEY
                    },
                    public: {
                        projectId: process.env.PREPRINTS_PUBLIC_PROJECT_ID,
                        writeKey: process.env.PREPRINTS_PUBLIC_WRITE_KEY
                    }
                }
            },

        ],
        FB_APP_ID: process.env.FB_APP_ID,
        whiteListedProviders: [
            'arXiv',
            'bioRxiv',
            'Cogprints',
            'PeerJ',
            'Research Papers in Economics',
            'Preprints.org'
        ].map(item => item.toLowerCase()),
    };

    if (environment === 'development') {
        // ENV.APP.LOG_RESOLVER = true;
        // ENV.APP.LOG_ACTIVE_GENERATION = true;
        // ENV.APP.LOG_TRANSITIONS = true;
        // ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
        // ENV.APP.LOG_VIEW_LOOKUPS = true;

        ENV.metricsAdapters[0].config.cookieDomain = 'none';
    }

    if (environment === 'test') {
        // Testem prefers this...
        ENV.baseURL = '/';
        ENV.locationType = 'none';

        // keep test console output quieter
        ENV.APP.LOG_ACTIVE_GENERATION = false;
        ENV.APP.LOG_VIEW_LOOKUPS = false;

        ENV.APP.rootElement = '#ember-testing';

        // Don't make external requests during unit test
        // TODO: Provide mocks for all components with manual AJAX calls in the future.
        ENV.SHARE.baseUrl = '/nowhere';
        ENV.SHARE.searchUrl = '/nowhere';
        ENV.OSF = {};
        ENV.OSF.shareSearchUrl = '/nowhere';

        ENV.metricsAdapters[0].config.cookieDomain = 'none'
    }

    if (environment === 'production') {
        ENV.sentryDSN = process.env.SENTRY_DSN || 'https://2f0a61d03b99480ea11e259edec18bd9@sentry.cos.io/45';
        ENV.ASSET_SUFFIX = process.env.GIT_COMMIT || 'git_commit_env_not_set';
    } else {
        // Fallback to throwaway defaults if the environment variables are not set
        ENV.metricsAdapters[0].config.id = ENV.metricsAdapters[0].config.id || 'UA-84580271-1';
        ENV.FB_APP_ID = ENV.FB_APP_ID || '1039002926217080';
    }

    return ENV;
};
<|endoftext|>


<commit_before>/* vi:si:et:sw=4:sts=4:ts=4 */

'use strict';
(function() {

    klp.init = function() {
        klp.accordion.init();
        klp.router = new KLPRouter();
        klp.router.init();
        initSelect2();
        loadData();
        //get JS query params from URL

    }

    function initSelect2() {
        $('#select2search').select2({
            placeholder: 'Search for schools and boundaries',
            minimumInputLength: 3,
            ajax: {
                url: "/api/v1/search",
                quietMillis: 300,
                allowClear: true,
                data: function(term, page) {
                    return {
                        text: term,
                        geometry: 'yes'
                    };
                },
                results: function(data, page) {
                    var searchResponse = {
                        results: [{
                            text: "Pre-Schools",
                            children: makeResults(data.pre_schools.features, 'school')
                        }, {
                            text: "Primary Schools",
                            children: makeResults(data.primary_schools.features, 'school')
                        }, {
                            text: "Boundaries",
                            children: makeResults(data.boundaries.features, 'boundary')
                        }]
                    };
                    return {
                        results: searchResponse.results
                    };
                }
            }
        });
        $('#select2search').on("change", function(choice) {
            console.log(choice);
        });
    }

    function makeResults(array, type) {
        var schoolDistrictMap = {
            'primaryschool': 'Primary School',
            'preschool': 'Preschool'
        };
        return _(array).map(function(obj) {
            var name = obj.properties.name;
            if (type === 'boundary') {
                if (obj.properties.type === 'district') {
                    name = obj.properties.name + ' - ' + schoolDistrictMap[obj.properties.school_type] + ' ' + obj.properties.type;
                } else {
                    name = obj.properties.name + ' - ' + obj.properties.type;
                }
            }

            obj.entity_type = type;
            return {
                id: obj.properties.id,
                text: _.str.titleize(name),
                data: obj
            };
        });
    }

    function loadData() {
        var params = klp.router.getHash().queryParams;
        var metaURL = "stories/meta/"; //FIXME: enter API url
        var $metaXHR = klp.api.do(metaURL, params);

        $metaXHR.done(function(data) {
            console.log("summary data", data);
            renderSummary(data);
        });

        //TODO: do some loading behaviour
        // $xhr.done(function(data) {
        //     renderPage(data);
        // });
    }

    function renderPage(data) {
        // Chartist charts get rendered here
        var data_respondent = {
            labels: ['Parents', 'Teachers', 'Community', 'Staff', 'Volunteers', 'Others'],
            series: [
                [80, 200, 100, 80, 200, 100]
            ]
        };

        renderBarChart('#chart_respondent', data_respondent);
        var data_ivrs = {
            labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul'],
            series: [
                [500, 1200, 1000, 700, 540, 1030, 360]
            ]
        };

        renderBarChart('#chart_ivrs', data_ivrs);

        //Binary graphs generated here
        renderSummary({});
        renderFeatured({});
        renderIvrs({});
        renderSurvey({});
        renderWeb({});
        renderComparison({});

    }

    function renderBarChart(elementId, data) {
        var options = {
            axisX: {
                showGrid: false
            },
            axisY: {
                showGrid: false
            }
        };

        var chart_element = Chartist.Bar(elementId, data, options).on('draw', function(data) {
            if (data.type === 'bar') {
                data.element.attr({
                    style: 'stroke-width: 20px'
                });
            }
        });
    }

    function renderSummary(data) {
        var tplTopSummary = swig.compile($('#tpl-topSummary').html());
        var tplCountSummary = swig.compile($('#tpl-countSummary').html());
        var topSummaryHTML = tplTopSummary(data);
        $('#topSummary').html(topSummaryHTML);

        var summaries = {
            'ivrs': [{
                'label': 'Schools',
                'count': data.total.schools
            }, {
                'label': 'Schools with Stories',
                'count': data.ivrs.schools
            }, {
                'label': 'Calls received',
                'count': data.ivrs.stories
            }, {
                'label': 'Academic Year',
                'count': '2015-2016'
            }],
            'survey': [{
                'label': 'Schools',
                'count': data.total.schools
            }, {
                'label': 'Schools with Stories',
                'count': data.community.schools
            }, {
                'label': 'Stories',
                'count': data.community.stories
            }, {
                'label': 'Academic Year',
                'count': '2015-2016'
            }],
            'web': [{
                'label': 'Schools',
                'count': data.total.schools
            }, {
                'label': 'Schools with Stories',
                'count': data.web.schools
            }, {
                'label': 'Verified Stories',
                'count': data.web.verified_stories
            }, {
                'label': 'Academic Year',
                'count': '2015-2016'
            }]
        };
        var html = tplCountSummary({
            'summary': summaries['ivrs']
        });
        $('#ivrssummary').html(html);
        html = tplCountSummary({
            'summary': summaries['survey']
        });
        $('#surveysummary').html(html);
        html = tplCountSummary({
            'summary': summaries['web']
        });
        $('#websummary').html(html);
    }

    function renderFeatured(data) {
        var tplPercentGraph = swig.compile($('#tpl-percentGraph').html());

        var questions = [{
            'question': 'IVRS: How many schools had all teachers present on the Day of Visit?',
            'score': 440,
            'total': 1000,
            'percent': 44
        }, {
            'question': 'IVRS: How many schools had classes being conducted?',
            'score': 260,
            'total': 1000,
            'percent': 26
        }, {
            'question': 'Surveys: How many schools had functional toilets?',
            'score': 300,
            'total': 1000,
            'percent': 30
        }, {
            'question': 'Surveys: How many schools had drinking water?',
            'score': 440,
            'total': 1000,
            'percent': 44
        }];

        var html = ''
        for (var pos in questions) {
            html = html + tplPercentGraph(questions[pos]);
        }
        $('#quicksummary').html(html);
    }

    function renderIvrs(data) {
        var tplGradeGraph = swig.compile($('#tpl-gradeGraph').html());
        var tplPercentGraph = swig.compile($('#tpl-percentGraph').html());
        //define your data
        var grades = [{
            'value': 'A',
            'score': 440,
            'total': 1000,
            'percent': 44,
            'color': 'green-leaf'
        }, {
            'value': 'B',
            'score': 260,
            'total': 1000,
            'percent': 26,
            'color': 'orange-mild'
        }, {
            'value': 'C',
            'score': 300,
            'total': 1000,
            'percent': 30,
            'color': 'pink-salmon'
        }];

        var html = ''
        for (var pos in grades) {
            html = html + "
" + tplGradeGraph(grades[pos]) + "
";
        }
        $('#ivrsgrades').html(html);

        var questions = [{
            'question': 'How many schools were open on the day of visit?',
            'score': 440,
            'total': 1000,
            'percent': 44
        }, {
            'question': 'In how many schools was the Headmaster present?',
            'score': 260,
            'total': 1000,
            'percent': 26
        }, {
            'question': 'In how many schools were the toilets in good condition?',
            'score': 300,
            'total': 1000,
            'percent': 30
        }];

        html = ''
        for (var pos in questions) {
            html = html + tplPercentGraph(questions[pos]);
        }
        $('#ivrsquestions').html(html);
    }

    function renderSurvey(data) {
        var tplPercentGraph = swig.compile($('#tpl-percentGraph').html());

        var questions = [{
            'question': 'How many schools are the teachers regular?',
            'score': 440,
            'total': 1000,
            'percent': 44
        }, {
            'question': 'How many schools have sufficient teachers?',
            'score': 260,
            'total': 1000,
            'percent': 26
        }, {
            'question': 'In how many schools are teachers taking classes regularly?',
            'score': 300,
            'total': 1000,
            'percent': 30
        }, {
            'question': 'How many schools have children getting academic attenction?',
            'score': 440,
            'total': 1000,
            'percent': 44
        }, {
            'question': 'In how many schools are SDMC members involved?',
            'score': 260,
            'total': 1000,
            'percent': 26
        }, {
            'question': 'In how many schools are there no concerns about Mid-day Meals?',
            'score': 300,
            'total': 1000,
            'percent': 30
        }];

        var html = "
";
        for (var pos in questions) {
            if (pos == questions.length / 2) {
                html = html + "

";
            }
            html = html + tplPercentGraph(questions[pos]);
        }
        html = html + "
";
        $('#surveyquestions').html(html);
    }

    function renderWeb(data) {
        var tplPercentGraph = swig.compile($('#tpl-percentGraph').html());

        var questions = [{
            'question': 'Where there was evidence of a Mid-day meal served:',
            'score': 440,
            'total': 1000,
            'percent': 44
        }, {
            'question': 'Where 50% of children enrolled in the school were present:',
            'score': 260,
            'total': 1000,
            'percent': 26
        }, {
            'question': 'Where all the teachers for all classes were present:',
            'score': 300,
            'total': 1000,
            'percent': 30
        }];

        var html = ''
        for (var pos in questions) {
            html = html + "
" + tplPercentGraph(questions[pos]) + "
";
        }
        $('#webquestions').html(html);

        var tplColorText = swig.compile($('#tpl-colorText').html());

        var facilities = [{
            'facility': 'All weather pucca building',
            'icon': ['fa fa-university'],
            'percent': 44
        }, {
            'facility': 'Playground',
            'icon': ['fa fa-futbol-o'],
            'percent': 45
        }, {
            'facility': 'Drinking Water',
            'icon': ['fa  fa-tint'],
            'percent': 54
        }, {
            'facility': 'Library',
            'icon': ['fa fa-book'],
            'percent': 64
        }, {
            'facility': 'Toilets',
            'icon': ['fa fa-male', 'fa fa-female'],
            'percent': 74
        }, {
            'facility': 'Secure Boundary Wall',
            'icon': ['fa fa-circle-o-notch'],
            'percent': 34
        }];

        var html = ''
        for (var pos in facilities) {
            html = html + tplColorText(facilities[pos]);
        }
        $('#webfacilities').html(html);

    }

    function renderComparison(data) {
        var tplCompareTable = swig.compile($('#tpl-compareTable').html());

        var neighbours = [{
            'name': 'Bangalore North',
            'schools': 1000,
            'stories': 440,
            'needs_volunteer': 'Playground',
            'needs_community': 'Playground',
            'ivrs': 500
        }, {
            'name': 'Bangalore South',
            'schools': 1000,
            'stories': 540,
            'needs_volunteer': 'Drinking Water',
            'needs_community': 'Mid-day Meals',
            'ivrs': 600
        }, {
            'name': 'Bangalore Central',
            'schools': 1000,
            'stories': 640,
            'needs_volunteer': 'Drinking Water',
            'needs_community': 'Playground',
            'ivrs': 600
        }, {
            'name': 'Bangalore Rural',
            'schools': 1000,
            'stories': 740,
            'needs_volunteer': 'Playground',
            'needs_community': 'Mid-day Meals',
            'ivrs': 600
        }];

        var html = tplCompareTable({
            'neighbours': neighbours
        });
        $('#comparison').html(html);

    }

})();<commit_msg>IVRS volumes and respondent charts<commit_after>/* vi:si:et:sw=4:sts=4:ts=4 */

'use strict';
(function() {

    klp.init = function() {
        klp.accordion.init();
        klp.router = new KLPRouter();
        klp.router.init();
        initSelect2();
        loadData();
        //get JS query params from URL

    }

    function initSelect2() {
        $('#select2search').select2({
            placeholder: 'Search for schools and boundaries',
            minimumInputLength: 3,
            ajax: {
                url: "/api/v1/search",
                quietMillis: 300,
                allowClear: true,
                data: function(term, page) {
                    return {
                        text: term,
                        geometry: 'yes'
                    };
                },
                results: function(data, page) {
                    var searchResponse = {
                        results: [{
                            text: "Pre-Schools",
                            children: makeResults(data.pre_schools.features, 'school')
                        }, {
                            text: "Primary Schools",
                            children: makeResults(data.primary_schools.features, 'school')
                        }, {
                            text: "Boundaries",
                            children: makeResults(data.boundaries.features, 'boundary')
                        }]
                    };
                    return {
                        results: searchResponse.results
                    };
                }
            }
        });
        $('#select2search').on("change", function(choice) {
            console.log(choice);
        });
    }

    function makeResults(array, type) {
        var schoolDistrictMap = {
            'primaryschool': 'Primary School',
            'preschool': 'Preschool'
        };
        return _(array).map(function(obj) {
            var name = obj.properties.name;
            if (type === 'boundary') {
                if (obj.properties.type === 'district') {
                    name = obj.properties.name + ' - ' + schoolDistrictMap[obj.properties.school_type] + ' ' + obj.properties.type;
                } else {
                    name = obj.properties.name + ' - ' + obj.properties.type;
                }
            }

            obj.entity_type = type;
            return {
                id: obj.properties.id,
                text: _.str.titleize(name),
                data: obj
            };
        });
    }

    function loadData() {
        var params = klp.router.getHash().queryParams;
        var metaURL = "stories/meta/"; //FIXME: enter API url
        var $metaXHR = klp.api.do(metaURL, params);

        $metaXHR.done(function(data) {
            console.log("summary data", data);
            renderSummary(data);
            renderRespondentChart(data);
        });

        var detailURL = "stories/details/";
        var $detailXHR = klp.api.do(detailURL, params);

        $detailXHR.done(function(data) {
            console.log("detail data", data);
            renderFeatured(data);
            renderIVRS(data);
            renderSurvey(data);
            renderWeb(data);
            //renderComparison(data);
        });

        var volumeURL = "stories/volume/";
        var $volumeXHR = klp.api.do(volumeURL, params);
        $volumeXHR.done(function(data) {
            renderIVRSVolumeChart(data);
        });

        //TODO: do some loading behaviour

    }

    function renderRespondentChart(data) {
        var labels = _.keys(data.respondents);
        var values = _.values(data.respondents);
        //console.log(labels, values);
        var data_respondent = {
            labels: labels,
            series: [
                values
            ]
        };

        renderBarChart('#chart_respondent', data_respondent);

    }

    function renderIVRSVolumeChart(data) {
        var labels = _.keys(data.volumes);
        var values = _.values(data.volumes);
        var data_ivrs = {
            labels: labels,
            series: [
                values
            ]
        };
        renderBarChart('#chart_ivrs', data_ivrs);
    }

    function renderBarChart(elementId, data) {
        var options = {
            axisX: {
                showGrid: false
            },
            axisY: {
                showGrid: false
            }
        };

        var chart_element = Chartist.Bar(elementId, data, options).on('draw', function(data) {
            if (data.type === 'bar') {
                data.element.attr({
                    style: 'stroke-width: 20px'
                });
            }
        });
    }

    function renderSummary(data) {
        var tplTopSummary = swig.compile($('#tpl-topSummary').html());
        var tplCountSummary = swig.compile($('#tpl-countSummary').html());
        var topSummaryHTML = tplTopSummary(data);
        $('#topSummary').html(topSummaryHTML);

        var summaries = {
            'ivrs': [{
                'label': 'Schools',
                'count': data.total.schools
            }, {
                'label': 'Schools with Stories',
                'count': data.ivrs.schools
            }, {
                'label': 'Calls received',
                'count': data.ivrs.stories
            }, {
                'label': 'Academic Year',
                'count': '2015-2016'
            }],
            'survey': [{
                'label': 'Schools',
                'count': data.total.schools
            }, {
                'label': 'Schools with Stories',
                'count': data.community.schools
            }, {
                'label': 'Stories',
                'count': data.community.stories
            }, {
                'label': 'Academic Year',
                'count': '2015-2016'
            }],
            'web': [{
                'label': 'Schools',
                'count': data.total.schools
            }, {
                'label': 'Schools with Stories',
                'count': data.web.schools
            }, {
                'label': 'Verified Stories',
                'count': data.web.verified_stories
            }, {
                'label': 'Academic Year',
                'count': '2015-2016'
            }]
        };
        var html = tplCountSummary({
            'summary': summaries['ivrs']
        });
        $('#ivrssummary').html(html);
        html = tplCountSummary({
            'summary': summaries['survey']
        });
        $('#surveysummary').html(html);
        html = tplCountSummary({
            'summary': summaries['web']
        });
        $('#websummary').html(html);
    }

    function renderFeatured(data) {
        var tplPercentGraph = swig.compile($('#tpl-percentGraph').html());

        var questions = [{
            'question': 'IVRS: How many schools had all teachers present on the Day of Visit?',
            'score': 440,
            'total': 1000,
            'percent': 44
        }, {
            'question': 'IVRS: How many schools had classes being conducted?',
            'score': 260,
            'total': 1000,
            'percent': 26
        }, {
            'question': 'Surveys: How many schools had functional toilets?',
            'score': 300,
            'total': 1000,
            'percent': 30
        }, {
            'question': 'Surveys: How many schools had drinking water?',
            'score': 440,
            'total': 1000,
            'percent': 44
        }];

        var html = ''
        for (var pos in questions) {
            html = html + tplPercentGraph(questions[pos]);
        }
        $('#quicksummary').html(html);
    }

    function renderIVRS(data) {
        var tplGradeGraph = swig.compile($('#tpl-gradeGraph').html());
        var tplPercentGraph = swig.compile($('#tpl-percentGraph').html());
        //define your data
        var grades = [{
            'value': 'A',
            'score': 440,
            'total': 1000,
            'percent': 44,
            'color': 'green-leaf'
        }, {
            'value': 'B',
            'score': 260,
            'total': 1000,
            'percent': 26,
            'color': 'orange-mild'
        }, {
            'value': 'C',
            'score': 300,
            'total': 1000,
            'percent': 30,
            'color': 'pink-salmon'
        }];

        var html = ''
        for (var pos in grades) {
            html = html + "
" + tplGradeGraph(grades[pos]) + "
";
        }
        $('#ivrsgrades').html(html);

        var questions = [{
            'question': 'How many schools were open on the day of visit?',
            'score': 440,
            'total': 1000,
            'percent': 44
        }, {
            'question': 'In how many schools was the Headmaster present?',
            'score': 260,
            'total': 1000,
            'percent': 26
        }, {
            'question': 'In how many schools were the toilets in good condition?',
            'score': 300,
            'total': 1000,
            'percent': 30
        }];

        html = ''
        for (var pos in questions) {
            html = html + tplPercentGraph(questions[pos]);
        }
        $('#ivrsquestions').html(html);
    }

    function renderSurvey(data) {
        var tplPercentGraph = swig.compile($('#tpl-percentGraph').html());

        var questions = [{
            'question': 'How many schools are the teachers regular?',
            'score': 440,
            'total': 1000,
            'percent': 44
        }, {
            'question': 'How many schools have sufficient teachers?',
            'score': 260,
            'total': 1000,
            'percent': 26
        }, {
            'question': 'In how many schools are teachers taking classes regularly?',
            'score': 300,
            'total': 1000,
            'percent': 30
        }, {
            'question': 'How many schools have children getting academic attenction?',
            'score': 440,
            'total': 1000,
            'percent': 44
        }, {
            'question': 'In how many schools are SDMC members involved?',
            'score': 260,
            'total': 1000,
            'percent': 26
        }, {
            'question': 'In how many schools are there no concerns about Mid-day Meals?',
            'score': 300,
            'total': 1000,
            'percent': 30
        }];

        var html = "
";
        for (var pos in questions) {
            if (pos == questions.length / 2) {
                html = html + "

";
            }
            html = html + tplPercentGraph(questions[pos]);
        }
        html = html + "
";
        $('#surveyquestions').html(html);
    }

    function renderWeb(data) {
        var tplPercentGraph = swig.compile($('#tpl-percentGraph').html());

        var questions = [{
            'question': 'Where there was evidence of a Mid-day meal served:',
            'score': 440,
            'total': 1000,
            'percent': 44
        }, {
            'question': 'Where 50% of children enrolled in the school were present:',
            'score': 260,
            'total': 1000,
            'percent': 26
        }, {
            'question': 'Where all the teachers for all classes were present:',
            'score': 300,
            'total': 1000,
            'percent': 30
        }];

        var html = ''
        for (var pos in questions) {
            html = html + "
" + tplPercentGraph(questions[pos]) + "
";
        }
        $('#webquestions').html(html);

        var tplColorText = swig.compile($('#tpl-colorText').html());

        var facilities = [{
            'facility': 'All weather pucca building',
            'icon': ['fa fa-university'],
            'percent': 44
        }, {
            'facility': 'Playground',
            'icon': ['fa fa-futbol-o'],
            'percent': 45
        }, {
            'facility': 'Drinking Water',
            'icon': ['fa  fa-tint'],
            'percent': 54
        }, {
            'facility': 'Library',
            'icon': ['fa fa-book'],
            'percent': 64
        }, {
            'facility': 'Toilets',
            'icon': ['fa fa-male', 'fa fa-female'],
            'percent': 74
        }, {
            'facility': 'Secure Boundary Wall',
            'icon': ['fa fa-circle-o-notch'],
            'percent': 34
        }];

        var html = ''
        for (var pos in facilities) {
            html = html + tplColorText(facilities[pos]);
        }
        $('#webfacilities').html(html);

    }

    function renderComparison(data) {
        var tplCompareTable = swig.compile($('#tpl-compareTable').html());

        var neighbours = [{
            'name': 'Bangalore North',
            'schools': 1000,
            'stories': 440,
            'needs_volunteer': 'Playground',
            'needs_community': 'Playground',
            'ivrs': 500
        }, {
            'name': 'Bangalore South',
            'schools': 1000,
            'stories': 540,
            'needs_volunteer': 'Drinking Water',
            'needs_community': 'Mid-day Meals',
            'ivrs': 600
        }, {
            'name': 'Bangalore Central',
            'schools': 1000,
            'stories': 640,
            'needs_volunteer': 'Drinking Water',
            'needs_community': 'Playground',
            'ivrs': 600
        }, {
            'name': 'Bangalore Rural',
            'schools': 1000,
            'stories': 740,
            'needs_volunteer': 'Playground',
            'needs_community': 'Mid-day Meals',
            'ivrs': 600
        }];

        var html = tplCompareTable({
            'neighbours': neighbours
        });
        $('#comparison').html(html);

    }

})();<|endoftext|>