<commit_before>"use strict"
function runAllTests(){
	// test_sample();
}

/*
	Template for a test, rename your test function and add it to runALlTests
*/
function test_sample(){
	/*
		Replace TEMPLATE with a short description of what your test is doing
	*/
	console.log("Testing: TEMPLATE")

	// print one of the results below
	console.log("Result: PASS");
	console.log("Result: FAIL");
}
<commit_msg>Added file upload, file save, editor and delete tests<commit_after>"use strict"
function runAllTests(){
	// test_sample();

	test_editor();
	test_save();
	test_upload();
}

/*
	Template for a test, rename your test function and add it to runALlTests
*/
function test_sample(){
	/*
		Replace TEMPLATE with a short description of what your test is doing
	*/
	console.log("Testing: TEMPLATE")

	// print one of the results below
	console.log("Result: PASS");
	console.log("Result: FAIL");
}

/*
	Test file upload: Creates a file, put the file contents into the editor and
	then checks if the editor and file contents are equal.
*/
function test_upload(){
	console.log("Testing: File Upload");
	var file = new File(["process simple { action a { requires { foo } provides { foo } }\
action b { requires { foo } provides { bar } } }"], "test.pml");

	var reader = new FileReader();
	var extension = file.name.split('.').pop();
	if (!file) {
		console.log("Result: FAIL");
	} else if (extension != "pml") {
		console.log("Result: FAIL");
	} else {
		reader.onload = function(e) {
			var expectedResults =reader.result;
			editor.session.doc.setValue(reader.result);
			var results = editor.getSession().getValue();
			if (expectedResults==results){
				console.log("Result: PASS");
			} else {
				console.log("Result: FAIL");
			}
			// close the file
			editor.session.doc.setValue('');
			document.getElementById('title').innerHTML = "PML Code Checker";
			closeFile = true;
		}
		reader.readAsText(file);
	}
}

/*
	Test editor: Check if editor source was loaded
*/
function test_editor(){
	var script = '';
	$('script').filter(function () {
    		if ($(this).attr('src') == "/static/src-noconflict/ace.js"){
			script= '/static/src-noconflict/ace.js';
		}

	});
	console.log("Testing: Editor");
	if(script=="/static/src-noconflict/ace.js"){
		console.log("Result: PASS");
	} else {
		console.log("Result: FAIL");
	}
}

/*
	Test file save: Create filename and code, save it.
	Get data from server and check if code is the same.
	Then delete the file and test if the file still exist.
*/
function test_save(){
	var name = 'testingFileSave';
	var testCode = "process simple { action a { requires { foo } provides { foo } }\
action b { requires { foo } provides { bar } } }";

	//save file
	$.ajax({
		type: "POST",
		data: { filename: name, code: testCode},
		url: "/upload"
	});

	//get file contents and compare
	var path = /uploads/ + name;
	jQuery.get(path, function(data) {
		console.log("Testing: File Save");
		if(data==testCode){
			console.log("Result: PASS");
		} else {
			console.log("Result: FAIL");
		}
	});

	// delete file
	path = /delete_item/ + name;
	jQuery.post(path);

	console.log("Testing: File Delete");
	if(!fileExist(name)){
		console.log("Result: PASS");
	} else {
		console.log("Result: FAIL");
	}
}
<|endoftext|>


<commit_before>import express from 'express';
const app = express();

/************************************************************
 *
 * Express routes for:
 *   - app.js
 *   - style.css
 *   - index.html
 *
 ************************************************************/

// Serve application file depending on environment
app.get('/app.js', (req, res) => {
  if (process.env.PRODUCTION) {
    res.sendFile(__dirname + '/build/app.js');
  } else {
    res.redirect('//localhost:9090/build/app.js');
  }
});

// Serve aggregate stylesheet depending on environment
app.get('/style.css', (req, res) => {
  if (process.env.PRODUCTION) {
    res.sendFile(__dirname + '/build/style.css');
  } else {
    res.redirect('//localhost:9090/build/style.css');
  }
});

// Serve index page
app.get('*', (req, res) => {
  res.sendFile(__dirname + '/build/index.html');
});

/*************************************************************
 *
 * Webpack Dev Server
 *
 * See: http://webpack.github.io/docs/webpack-dev-server.html
 *
 *************************************************************/

if (!process.env.PRODUCTION) {
  const webpack = require('webpack');
  const WebpackDevServer = require('webpack-dev-server');
  const config = require('./webpack.local.config');

  new WebpackDevServer(webpack(config), {
    publicPath: config.output.publicPath,
    hot: true,
    noInfo: true,
    historyApiFallback: true
  }).listen(9090, 'localhost', (err, result) => {
    if (err) {
      console.log(err);
    }
  });
}

/******************
 *
 * Express server
 *
 *****************/

const port = process.env.PORT || 8080;
const server = app.listen(port, () => {
  const host = server.address().address;
  const port = server.address().port;

  console.log('Essential React listening at http://%s:%s', host, port);
});
<commit_msg>heroku doesn't like es6<commit_after>var express = 'express';
const app = express();

/************************************************************
 *
 * Express routes for:
 *   - app.js
 *   - style.css
 *   - index.html
 *
 ************************************************************/

// Serve application file depending on environment
app.get('/app.js', (req, res) => {
  if (process.env.PRODUCTION) {
    res.sendFile(__dirname + '/build/app.js');
  } else {
    res.redirect('//localhost:9090/build/app.js');
  }
});

// Serve aggregate stylesheet depending on environment
app.get('/style.css', (req, res) => {
  if (process.env.PRODUCTION) {
    res.sendFile(__dirname + '/build/style.css');
  } else {
    res.redirect('//localhost:9090/build/style.css');
  }
});

// Serve index page
app.get('*', (req, res) => {
  res.sendFile(__dirname + '/build/index.html');
});

/*************************************************************
 *
 * Webpack Dev Server
 *
 * See: http://webpack.github.io/docs/webpack-dev-server.html
 *
 *************************************************************/

if (!process.env.PRODUCTION) {
  const webpack = require('webpack');
  const WebpackDevServer = require('webpack-dev-server');
  const config = require('./webpack.local.config');

  new WebpackDevServer(webpack(config), {
    publicPath: config.output.publicPath,
    hot: true,
    noInfo: true,
    historyApiFallback: true
  }).listen(9090, 'localhost', (err, result) => {
    if (err) {
      console.log(err);
    }
  });
}

/******************
 *
 * Express server
 *
 *****************/

const port = process.env.PORT || 8080;
const server = app.listen(port, () => {
  const host = server.address().address;
  const port = server.address().port;

  console.log('Essential React listening at http://%s:%s', host, port);
});
<|endoftext|>


<commit_before>'use strict'

console.log("Welcome to Chatcat");
<commit_msg>Complete lecture 31: add express application and base routing functionalities<commit_after>'use strict'

const express = require('express');
const app = express();

app.set('port', process.env.PORT || 3000);

app.get('/', (req, res, next) => {
  res.send('
Hello Express!
');
});

app.get('/dashboard', (req, res, next) => {
  res.send('
This is the dashboard page
');
});

app.listen(app.get('port'), () => {
  console.log('Chatchat running on port:' + app.get('port'));
});
<|endoftext|>


<commit_before>'use strict';

var t = new Date();

var pkg = require('./package.json');

var assert = require('assert');
var async = require('async');

var express = require('express');
var redis = require('redis');
var redisClient = redis.createClient();
var RedisStore = require('connect-redis')(express);
var init = require('./lib/init.js');

var view = require('./lib/view.js');
var error = require('./lib/error.js');

console.log('[%s]\nSystem started. Initializing system parameters.', t);

var server = module.exports = express();

server.configure(function () {
  server.set('env', pkg.production == true ? 'production': 'development');
  server.use(express.compress());
  server.use(express.bodyParser());
  server.use(express.cookieParser());
  server.use(express.session({store: new RedisStore({client: redisClient}), secret: 'SSIv4'}));
  server.use(express.static(__dirname + '/_static'));
  server.use(express.methodOverride());
  server.use(server.router);
  server.use(error.s404);
  server.use(error.s500);

  server.engine('html', view.__express);
  server.set('view engine', 'html');
  server.set('views', __dirname + '/views');
});

server.configure('development', function(){
  server.use(express.logger('dev'));
  server.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});

server.configure('production', function(){
  server.use(express.errorHandler());
});

init(server, function (err) {
  assert.equal(null, err);
  server.listen(80, function(){
    console.log("SFEI Systems booted in %d ms. [@port %d in %s mode]", new Date().getTime() - t.getTime(), 80, server.settings.env);
  });
});<commit_msg>Deprecating server.configure()<commit_after>'use strict';

var t = new Date();

var pkg = require('./package.json');

var assert = require('assert');
var async = require('async');

var express = require('express');
var redis = require('redis');
var redisClient = redis.createClient();
var RedisStore = require('connect-redis')(express);
var init = require('./lib/init.js');

var view = require('./lib/view.js');
var error = require('./lib/error.js');

console.log('[%s]\nSystem started. Initializing system parameters.', t);

var server = module.exports = express();

server.configure(function () {
  server.set('env', pkg.production == true ? 'production': 'development');
  if (pkg.production !== true)
    server.use(express.logger('dev'));
  server.use(express.compress());
  server.use(express.bodyParser());
  server.use(express.cookieParser());
  server.use(express.session({store: new RedisStore({client: redisClient}), secret: 'SSIv4'}));
  server.use(express.static(__dirname + '/_static'));
  server.use(express.methodOverride());
  server.use(server.router);
  server.use(error.s404);
  server.use(error.s500);

  server.engine('html', view.__express);
  server.set('view engine', 'html');
  server.set('views', __dirname + '/views');

  server.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});

init(server, function (err) {
  assert.equal(null, err);
  server.listen(80, function(){
    console.log("SFEI Systems booted in %d ms. [@port %d in %s mode]", new Date().getTime() - t.getTime(), 80, server.settings.env);
  });
});<|endoftext|>


<commit_before>import { Component, PropTypes } from "react";
import { connect } from "react-redux";
import { graphql } from "react-apollo";
import gql from "graphql-tag";

import {
  nav as navActions,
  modal as modalActions,
  give as giveActions,
  header as headerActions,
} from "../../../../store";

import Confirm from "./Confirm";
import Layout from "./Layout";

const ENTRIES_QUERY = gql`
  query GetTaggedContent($tagName: String!, $limit: Int, $includeChannels: [String]) {
    entries: taggedContent(
      tagName: $tagName,
      limit: $limit,
      includeChannels: $includeChannels
    ) {
      entryId: id
      title
      channelName
      status
      meta { summary, urlTitle }
      content { images(sizes: ["large"]) { fileName, fileType, fileLabel, url } }
    }
  }
`;

const withEntries = graphql(ENTRIES_QUERY, {
  name: "entries",
  options: {
    variables: {
      tagName: "giving",
      limit: 2,
      includeChannels: ["articles"],
    },
  },
});

const GET_SCHEDULE_TRANSACTION_QUERY = gql`
  query GetScheduleTransaction($scheduleTransactionId: ID!) {
    transaction: node(id: $scheduleTransactionId) {
      ... on ScheduledTransaction {
        numberOfPayments
        next
        end
        id: entityId
        reminderDate
        gateway
        start
        date
        details { amount, account { name, description } }
        payment { paymentType, accountNumber, id }
        schedule { value, description }
        transactions {
          id
          date
          status
          summary
          person { firstName, lastName, photo }
          details { id, amount, account { id, name } }
        }
      }
    }
  }
`;

const withGetScheduleTransaction = graphql(GET_SCHEDULE_TRANSACTION_QUERY, {
  options: ownProps => ({
    variables: { scheduleTransactionId: ownProps.params.id },
    forceFetch: true,
  }),
});

@connect()
@withEntries
@withGetScheduleTransaction
export default class Details extends Component {

  static propTypes = {
    dispatch: PropTypes.func.isRequired,
    data: PropTypes.shape({
      loading: PropTypes.bool,
      transaction: PropTypes.object,
    }),
    entries: PropTypes.object,
  }

  state = {
    isActive: true,
    removed: null,
  }

  componentWillMount() {
    this.props.dispatch(navActions.setLevel("BASIC_CONTENT"));
  }

  componentDidMount() {
    if (process.env.NATIVE) {
      const item = { title: "Schedule Details" };
      this.props.dispatch(headerActions.set(item));
    }
  }

  componentWillUnmount() {
    this.props.dispatch(navActions.setLevel("TOP"));
    if (this.state.removed) {
      this.props.dispatch(giveActions.deleteSchedule(this.state.removed));
    }
  }

  stop = (e) => {
    e.preventDefault();

    this.props.dispatch(modalActions.render(Confirm, {
      onFinished: () => {
        const { id, gateway } = this.props.data.transaction;

        this.setState({ isActive: false, removed: id });
        Meteor.call("give/schedule/cancel", { id, gateway }, () => {
        });
      },
    }));
  }

  render() {
    let complete = false;
    let { transaction } = this.props.data;
    if (!transaction) {
      transaction = false;
    }
    if (new Date(transaction.next) < new Date() && transaction.schedule.value === "One-Time") {
      complete = true;
    }

    const { entries, loading } = this.props.entries;

    return (
      <Layout
        stop={this.stop}
        schedule={transaction}
        ready={!this.props.data.loading}
        state={this.state}
        active={this.state.isActive}
        complete={complete}
        entries={entries}
        loadingEntries={loading}
      />
    );
  }
}
<commit_msg>fixing naming convention<commit_after>import { Component, PropTypes } from "react";
import { connect } from "react-redux";
import { graphql } from "react-apollo";
import gql from "graphql-tag";

import {
  nav as navActions,
  modal as modalActions,
  give as giveActions,
  header as headerActions,
} from "../../../../store";

import Confirm from "./Confirm";
import Layout from "./Layout";

const ENTRIES_QUERY = gql`
  query GetTaggedContent($tagName: String!, $limit: Int, $includeChannels: [String]) {
    entries: taggedContent(
      tagName: $tagName,
      limit: $limit,
      includeChannels: $includeChannels
    ) {
      entryId: id
      title
      channelName
      status
      meta { summary, urlTitle }
      content { images(sizes: ["large"]) { fileName, fileType, fileLabel, url } }
    }
  }
`;

const withEntries = graphql(ENTRIES_QUERY, {
  name: "entries",
  options: {
    variables: {
      tagName: "giving",
      limit: 2,
      includeChannels: ["articles"],
    },
  },
});

const SCHEDULE_TRANSACTION_QUERY = gql`
  query GetScheduleTransaction($scheduleTransactionId: ID!) {
    transaction: node(id: $scheduleTransactionId) {
      ... on ScheduledTransaction {
        numberOfPayments
        next
        end
        id: entityId
        reminderDate
        gateway
        start
        date
        details { amount, account { name, description } }
        payment { paymentType, accountNumber, id }
        schedule { value, description }
        transactions {
          id
          date
          status
          summary
          person { firstName, lastName, photo }
          details { id, amount, account { id, name } }
        }
      }
    }
  }
`;

const withScheduleTransaction = graphql(SCHEDULE_TRANSACTION_QUERY, {
  options: ownProps => ({
    variables: { scheduleTransactionId: ownProps.params.id },
    forceFetch: true,
  }),
});

@connect()
@withEntries
@withScheduleTransaction
export default class Details extends Component {

  static propTypes = {
    dispatch: PropTypes.func.isRequired,
    data: PropTypes.shape({
      loading: PropTypes.bool,
      transaction: PropTypes.object,
    }),
    entries: PropTypes.object,
  }

  state = {
    isActive: true,
    removed: null,
  }

  componentWillMount() {
    this.props.dispatch(navActions.setLevel("BASIC_CONTENT"));
  }

  componentDidMount() {
    if (process.env.NATIVE) {
      const item = { title: "Schedule Details" };
      this.props.dispatch(headerActions.set(item));
    }
  }

  componentWillUnmount() {
    this.props.dispatch(navActions.setLevel("TOP"));
    if (this.state.removed) {
      this.props.dispatch(giveActions.deleteSchedule(this.state.removed));
    }
  }

  stop = (e) => {
    e.preventDefault();

    this.props.dispatch(modalActions.render(Confirm, {
      onFinished: () => {
        const { id, gateway } = this.props.data.transaction;

        this.setState({ isActive: false, removed: id });
        Meteor.call("give/schedule/cancel", { id, gateway }, () => {
        });
      },
    }));
  }

  render() {
    let complete = false;
    let { transaction } = this.props.data;
    if (!transaction) {
      transaction = false;
    }
    if (new Date(transaction.next) < new Date() && transaction.schedule.value === "One-Time") {
      complete = true;
    }

    const { entries, loading } = this.props.entries;

    return (
      <Layout
        stop={this.stop}
        schedule={transaction}
        ready={!this.props.data.loading}
        state={this.state}
        active={this.state.isActive}
        complete={complete}
        entries={entries}
        loadingEntries={loading}
      />
    );
  }
}
<|endoftext|>


<commit_before>var express        = require('express');
var http           = require('http');
var https          = require('https');

var bodyParser     = require('body-parser');
var methodOverride = require('method-override');
var cookieParser   = require('cookie-parser');
var cors           = require('cors');
var passport       = require('passport');
var expressSession = require('express-session');
var fs             = require('fs');
var favicon        = require('serve-favicon');
var app            = express();

var colors         = require('./config/color');
var error          = require('./app/controllers/error');

// var
var ports = { http: 8080, https: 4433 };
var httpServer = null;
var httpsServer = null;
var credentials = { key: fs.readFileSync(__dirname + '/config/ssl/key.pem'), cert: fs.readFileSync(__dirname + '/config/ssl/cert.pem') };

// configuration ===========================================

// Recuperation des POST
// parse application/json
app.use(bodyParser.json());

// parse application/vnd.api+json as json
app.use(bodyParser.json({ type: 'application/vnd.api+json' }));

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }));

// read cookies (needed for auth)
app.use(cookieParser());

// accept cross domain
app.use(cors());

// override with the X-HTTP-Method-Override header in the request. simulate DELETE/PUT
app.use(methodOverride('X-HTTP-Method-Override'));

// favicon
app.use(express.static(__dirname + '/public'));
app.use(favicon(__dirname + '/public/favicon.ico'));

// auth
// init de session Passport
app.use(expressSession({
	secret: 'RANDOM',
	resave: true,
    saveUninitialized: true
}));
app.use(passport.initialize());
app.use(passport.session());

// routes ==================================================
require('./app/routes')(app, passport, error); // configure our routes
require('./config/passport')(passport);

// start app ===============================================
httpServer = http.createServer(function (req, res) {
	res.writeHead(301, { "Location": "https://" + req.headers['host'] + req.url });
	res.end();
}).listen(ports.http);

httpsServer = https.createServer(credentials, app).listen(ports.https);

// Affichage des infos
console.log(colors.info('RESTful API'));
console.log(colors.help('Port serveur HTTP (API) : ' + ports.http));
console.log(colors.help('Port serveur HTTPS (API) : ' + ports.https));

// expose app
exports = module.exports = app;<commit_msg>+- change ports<commit_after>var express        = require('express');
var http           = require('http');
var https          = require('https');

var bodyParser     = require('body-parser');
var methodOverride = require('method-override');
var cookieParser   = require('cookie-parser');
var cors           = require('cors');
var passport       = require('passport');
var expressSession = require('express-session');
var fs             = require('fs');
var favicon        = require('serve-favicon');
var app            = express();

var colors         = require('./config/color');
var error          = require('./app/controllers/error');

// var
var ports = { http: 80, https: 443 };
var httpServer = null;
var httpsServer = null;
var credentials = { key: fs.readFileSync(__dirname + '/config/ssl/key.pem'), cert: fs.readFileSync(__dirname + '/config/ssl/cert.pem') };

// configuration ===========================================

// Recuperation des POST
// parse application/json
app.use(bodyParser.json());

// parse application/vnd.api+json as json
app.use(bodyParser.json({ type: 'application/vnd.api+json' }));

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }));

// read cookies (needed for auth)
app.use(cookieParser());

// accept cross domain
app.use(cors());

// override with the X-HTTP-Method-Override header in the request. simulate DELETE/PUT
app.use(methodOverride('X-HTTP-Method-Override'));

// favicon
app.use(express.static(__dirname + '/public'));
app.use(favicon(__dirname + '/public/favicon.ico'));

// auth
// init de session Passport
app.use(expressSession({
	secret: 'RANDOM',
	resave: true,
    saveUninitialized: true
}));
app.use(passport.initialize());
app.use(passport.session());

// routes ==================================================
require('./app/routes')(app, passport, error); // configure our routes
require('./config/passport')(passport);

// start app ===============================================
httpServer = http.createServer(function (req, res) {
	res.writeHead(301, { "Location": "https://" + req.headers['host'] + req.url });
	res.end();
}).listen(ports.http);

httpsServer = https.createServer(credentials, app).listen(ports.https);

// Affichage des infos
console.log(colors.info('RESTful API'));
console.log(colors.help('Port serveur HTTP (API) : ' + ports.http));
console.log(colors.help('Port serveur HTTPS (API) : ' + ports.https));

// expose app
exports = module.exports = app;<|endoftext|>


<commit_before>/**
 * Copyright (c) 2015-present, Alejandro Mantilla <@AlejoJamC>.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree or translated in the assets folder.
 */

/**
 * Module dependencies
 */
var express = require('express');
var bodyParser = require('body-parser');
var session = require('express-session');
var passport = require('passport');
var jade = require('jade');
var routes = require('./routes/routes');
var Logger = require('./config/logger');
var logger = Logger.logger;

// Choose the environment of work
var environment = 'devLocal';
logger.info('Chose the work environment: ' + environment);
var config = require('./config/environment.json')[environment];
logger.info('API version: ' + config.version);

// Mongoose connection logger
var mongoDB = require('./config/mongodb');
mongoDB.setupMongoDB(config.nosqlDB);

// Create our express application
var app = express();

// Set view engine to jade
app.set('view engine', 'jade');

// Using body-parser in our application
// create application/json parser
app.use(bodyParser.json());
// create application/x-www-form-urlencoded parser
app.use(bodyParser.urlencoded({
  extended: true
}));

// Use express session support since OAuth2orize requires it
app.use(session({
  resave: true,
  saveUninitialized: true,
  secret: '1f u c4n r34d th1s u r34lly n33d t0 g37 l41d'
}));

// Set header 'X-Powered-By'
logger.info('API powered by: @AlejoJamC');
app.use(function (req, res, next) {
  res.set('X-Powered-By', 'Alejandro Mantilla < @AlejoJamC >');
  next();
});

// Use the passport package in our application
app.use(passport.initialize());

// Path to our public directory
app.use(express.static(__dirname + '/public'));

//ROUTER
//Create our Express router
var router  = express.Router();

// Setup all routes on express router
routes.setupRouter(router);

// Use our environment defined port or value on our config file /config/environment.json
var port = process.env.PORT || config.port;

// Register all our routes with a prefix: /api or /v1
// This poject is created to be hosted in a subdomain dedicated to authentication and authorization
// Example of an URL with the prefix: auth.happyauth.com/v0
app.use(config.version, router);

// Start the server
app.listen(port);
logger.info('API running on http://localhost:' + port + config.version + '/');<commit_msg>allowed CORS temp<commit_after>/**
 * Copyright (c) 2015-present, Alejandro Mantilla <@AlejoJamC>.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree or translated in the assets folder.
 */

/**
 * Module dependencies
 */
var express = require('express');
var bodyParser = require('body-parser');
var session = require('express-session');
var passport = require('passport');
var jade = require('jade');
var routes = require('./routes/routes');
var Logger = require('./config/logger');
var logger = Logger.logger;

// Choose the environment of work
var environment = 'devLocal';
logger.info('Chose the work environment: ' + environment);
var config = require('./config/environment.json')[environment];
logger.info('API version: ' + config.version);

// Mongoose connection logger
var mongoDB = require('./config/mongodb');
mongoDB.setupMongoDB(config.nosqlDB);

// Create our express application
var app = express();

// Set view engine to jade
app.set('view engine', 'jade');

// Using body-parser in our application
// create application/json parser
app.use(bodyParser.json());
// create application/x-www-form-urlencoded parser
app.use(bodyParser.urlencoded({
  extended: true
}));

// Use express session support since OAuth2orize requires it
app.use(session({
  resave: true,
  saveUninitialized: true,
  secret: '1f u c4n r34d th1s u r34lly n33d t0 g37 l41d'
}));

// Set header 'X-Powered-By'
logger.info('API powered by: @AlejoJamC');
app.use(function (req, res, next) {
  res.set('X-Powered-By', 'Alejandro Mantilla < @AlejoJamC >');
  next();
});

// Allow CORS
app.use(function(req, res, next) {
  res.header('Access-Control-Allow-Origin', 'http://localhost:7000');
  res.header('Access-Control-Allow-Methods', 'GET, POST');
  res.header('Access-Control-Allow-Headers', 'Authorization, Origin, X-Requested-With, Content-Type, Accept');
  next();
});

// Use the passport package in our application
app.use(passport.initialize());

// Path to our public directory
app.use(express.static(__dirname + '/public'));

//ROUTER
//Create our Express router
var router  = express.Router();

// Setup all routes on express router
routes.setupRouter(router);

// Use our environment defined port or value on our config file /config/environment.json
var port = process.env.PORT || config.port;

// Register all our routes with a prefix: /api or /v1
// This poject is created to be hosted in a subdomain dedicated to authentication and authorization
// Example of an URL with the prefix: auth.happyauth.com/v0
app.use(config.version, router);

// Start the server
app.listen(port);
logger.info('API running on http://localhost:' + port + config.version + '/');<|endoftext|>


<commit_before>var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var moment = require('moment');
var got = require('got');

var port = process.env.PORT || 8080;

var self = this;

this.messages = [];

app.use(express.static('wwwroot'));

app.get('/', function(req, res) {
    res.sendFile(__dirname + '/index.html');
});

app.get('/messages', function(req, res) {
    res.send(self.messages);
})

io.on('connection', function(socket) {
    io.emit('web', 'someone connected');

    socket.on('pi', function(msg) {
        saveMessage(msg);
        io.emit('web', 'Pi says ' + msg);
    });

    socket.on('distance-message', function(msg) {
        var dist = Math.round(msg)/100;
        var status = dist > 2.5 ? "lukket" :
            dist < 0.2 ? "åpen" : "limbo";
        io.emit('distance', {
            'status': status,
            'distance': dist
        });
    })

    socket.on('web message', function(msg) {
        io.emit('command', msg)
    })

    socket.on('disconnect', function() { });
});

function saveMessage(msg) {
    if (self.messages.length > 10) {
        self.messages.shift();
    }
    self.messages.push({
        time: moment().format('DD/MM/YYYY HH:mm'),
        message: msg
    });
}

http.listen(port, function() {
    console.log('listening on *:' + port);
});<commit_msg>distancen<commit_after>var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var moment = require('moment');
var got = require('got');

var port = process.env.PORT || 8080;

var self = this;

this.messages = [];

this.distances = [];

app.use(express.static('wwwroot'));

app.get('/', function(req, res) {
    res.sendFile(__dirname + '/index.html');
});

app.get('/messages', function(req, res) {
    res.send(self.messages);
})

io.on('connection', function(socket) {
    io.emit('web', 'someone connected');

    socket.on('pi', function(msg) {
        saveMessage(msg);
        io.emit('web', 'Pi says ' + msg);
    });

    socket.on('distance-message', function(msg) {
        pushDistance(msg);
        var dist = getAvgDistance();
        var status = dist > 2.5 ? "lukket" :
            dist < 0.2 ? "åpen" : "limbo";
        io.emit('distance', {
            'status': status,
            'distance': dist
        });
    })

    socket.on('web message', function(msg) {
        io.emit('command', msg)
    })

    socket.on('disconnect', function() { });
});

function getAvgDistance(){
    return self.distances.reduce(function(previousValue, currentValue, currentIndex, array) {
        return previousValue + currentValue;
    })/self.distances.length;
}

function pushDistance(dist){
    if (self.distances.length > 10) {
        self.distances.shift();
    }
    self.distances.push(dist);
}

function saveMessage(msg) {
    if (self.messages.length > 10) {
        self.messages.shift();
    }
    self.messages.push({
        time: moment().format('DD/MM/YYYY HH:mm'),
        message: msg
    });
}

http.listen(port, function() {
    console.log('listening on *:' + port);
});<|endoftext|>


<commit_before>//setup Dependencies
var express  = require('express'),
bodyParser   = require('body-parser'),
cookieParser = require('cookie-parser'),
csrf         = require('csurf'),
session      = require('express-session'),
state        = require('express-state'),
flash        = require('express-flash'),
cluster      = require('express-cluster'),
compression  = require('compression'),
hbs          = require('./lib/exphbs'),
routes       = require('./routes'),
middleware   = require('./middleware'),
config       = require('./config'),
utils        = require('./lib/utils'),
getEvents    = require('./lib/getEvents'),
getArrangements = require('./lib/getArrangements'),
port         = (process.env.PORT || 8000);

//Comment out the line below if you want to enable cluster support.
setupServer();

//Uncomment the line below if you want to enable cluster support.
//cluster(setupServer);

function setupServer (worker) {
    var app = express(),
        server = app.listen(port, function () {
            console.log("Baritones website is running on:" + server.address().port);
        }),
        router;

    //Setup Express App
    state.extend(app);
    app.engine(hbs.extname, hbs.engine);
    app.set('view engine', hbs.extname);
    app.enable('view cache');

    //Uncomment this if you want strict routing (ie: /foo will not resolve to /foo/)
    //app.enable('strict routing');

    //Change "App" to whatever your application's name is, or leave it like this.
    app.set('state namespace', 'BBs');

    //Create an empty Data object and expose it to the client. This
    //will be available on the client under App.Data.
    //This is just an example, so feel free to remove this.
    app.expose({}, 'Data');

    if (app.get('env') === 'development') {
      app.use(middleware.logger('tiny'));
    }

    // Set default views directory.
    app.set('views', config.dirs.views);

    router = express.Router({
        caseSensitive: app.get('case sensitive routing'),
        strict       : app.get('strict routing')
    });

    // Parse application/x-www-form-urlencoded
    app.use(bodyParser.urlencoded({ extended: false }));

    // Parse application/json
    app.use(bodyParser.json());

    // Parse cookies.
    app.use(cookieParser());

    // Session Handling
    app.use(session({secret: 'keyboard cat', resave: true, saveUninitialized: true}));

    // Flash Message Support
    app.use(flash());

    //GZip Support
    app.use(compression());

    // Specify the public directory.
    app.use(express.static(config.dirs.pub));

    app.use(csrf({cookie: true}));
    app.use(function(req, res, next) {
        var token = req.csrfToken();
        res.cookie('XSRF-TOKEN', token);
        res.locals._csrf = token;
        next();
    });

    app.use(function (err, req, res, next) {
    if (err.code !== 'EBADCSRFTOKEN') return next(err);
      console.log(err.code);
      // handle CSRF token errors here
      res.status(403);
      res.send('form tampered with');
    });

    // Use the router.
    app.use(router);

    ///////////////////////////////////////////
    //              Routes                   //
    ///////////////////////////////////////////

    /////// ADD ALL YOUR ROUTES HERE  /////////

    // The exposeTemplates() method makes the Handlebars templates that are inside /shared/templates/
    // available to the client.
    router.get('/', function (req, res) {
      res.locals.title = "Bearded Baritones";
      res.render('home');
    });

    router.get('/about', function (req, res) {
      res.locals.title = "About | Bearded Baritones";
      res.render('about');
    });

    router.get('/videos', function (req, res) {
      res.locals.title = "Videos | Bearded Baritones";
      res.render('videos');
    });

    router.get('/arrangements', function (req, res) {
      res.locals.title = "Arrangements | Bearded Baritones";
      getArrangements.getArrangements('data/arrangements.json', function (arrangements,err) {
        if (!err) {
          res.locals.arrangements = arrangements;
          res.render('arrangements');
        } else {
          res.render('500', {
            status: err.status || 500,
            error: err
          });
        }
      });
    });

    router.get('/appearances', function (req, res) {
      res.locals.title = "Appearances | Bearded Baritones";
      getEvents.getEvents('data' + '/appearances.xml', function (events, err) {
        if (!err) {
          res.locals.events = events;
          res.render('appearances');
        } else {
          res.render('500', {
            status: err.status || 500,
            error: err
          });
        }
      });
    });

    router.get('/photos', function (req, res) {
      utils.getImagesForPhotosPage(function(images, err) {
          if (!err) {
            res.locals.photos=images;
            res.locals.title = "Photos | Bearded Baritones";
            res.render('photos');
          } else {
            res.render('500', {
              status: err.status || 500,
              error: err
            });
          }
      });
    });

    router.get('/contact', function (req, res) {
      res.locals.title = "Contact | Bearded Baritones";
      res.render('contact');
    });

    router.post('/contact', function(req, res) {
      //Setup the email
      console.log(req.body);
        config.postmark.sendEmail({
            "From": "dan@ddajohnson.com",
            "To": "bearded.baritones@gmail.com",
            "Reply-To": "req.body.email",
            "Subject": "Contact Request From Bearded Baritones Website: " + req.body.name + "<" + req.body.email + ">",
            "TextBody": req.body.message,
        }, function(error, success) {
            if(error) {
                console.error("Unable to send via postmark: " + error.message);
                res.status(400).send(error.message);
                return;
            }
            res.status(200).send();
            console.info("Sent to postmark for delivery");
        });

});

    // Error handling middleware
    app.use(function(req, res, next){
        res.render('404', { status: 404, url: req.url });
    });

    app.use(function(err, req, res, next){
        res.render('500', {
            status: err.status || 500,
            error: err
        });
    });

    return server;
}

<commit_msg>Cleaned up comments and whitespace.<commit_after>//setup Dependencies
var express  = require('express'),
bodyParser   = require('body-parser'),
cookieParser = require('cookie-parser'),
csrf         = require('csurf'),
session      = require('express-session'),
state        = require('express-state'),
flash        = require('express-flash'),
cluster      = require('express-cluster'),
compression  = require('compression'),
hbs          = require('./lib/exphbs'),
routes       = require('./routes'),
middleware   = require('./middleware'),
config       = require('./config'),
utils        = require('./lib/utils'),
getEvents    = require('./lib/getEvents'),
getArrangements = require('./lib/getArrangements'),
port         = (process.env.PORT || 8000);

//Comment out the line below if you want to enable cluster support.
setupServer();

//Uncomment the line below if you want to enable cluster support.
//cluster(setupServer);

function setupServer (worker) {
    var app = express(),
        server = app.listen(port, function () {
            console.log("Baritones website is running on:" + server.address().port);
        }),
        router;

    //Setup Express App
    state.extend(app);
    app.engine(hbs.extname, hbs.engine);
    app.set('view engine', hbs.extname);
    app.enable('view cache');

    //Uncomment this if you want strict routing (ie: /foo will not resolve to /foo/)
    //app.enable('strict routing');

    app.set('state namespace', 'BBs');

    //Create an empty Data object and expose it to the client. This
    //will be available on the client under App.Data.
    //This is just an example, so feel free to remove this.
    app.expose({}, 'Data');

    if (app.get('env') === 'development') {
      app.use(middleware.logger('tiny'));
    }

    // Set default views directory.
    app.set('views', config.dirs.views);

    router = express.Router({
        caseSensitive: app.get('case sensitive routing'),
        strict       : app.get('strict routing')
    });

    // Parse application/x-www-form-urlencoded
    app.use(bodyParser.urlencoded({ extended: false }));

    // Parse application/json
    app.use(bodyParser.json());

    // Parse cookies.
    app.use(cookieParser());

    // Session Handling
    app.use(session({secret: 'keyboard cat', resave: true, saveUninitialized: true}));

    // Flash Message Support
    app.use(flash());

    //GZip Support
    app.use(compression());

    // Specify the public directory.
    app.use(express.static(config.dirs.pub));

    app.use(csrf({cookie: true}));
    app.use(function(req, res, next) {
        var token = req.csrfToken();
        res.cookie('XSRF-TOKEN', token);
        res.locals._csrf = token;
        next();
    });

    app.use(function (err, req, res, next) {
    if (err.code !== 'EBADCSRFTOKEN') return next(err);
      console.log(err.code);
      // handle CSRF token errors here
      res.status(403);
      res.send('form tampered with');
    });

    // Use the router.
    app.use(router);

    ///////////////////////////////////////////
    //              Routes                   //
    ///////////////////////////////////////////

    /////// ADD ALL YOUR ROUTES HERE  /////////

    // The exposeTemplates() method makes the Handlebars templates that are inside /shared/templates/
    // available to the client.
    router.get('/', function (req, res) {
      res.locals.title = "Bearded Baritones";
      res.render('home');
    });

    router.get('/about', function (req, res) {
      res.locals.title = "About | Bearded Baritones";
      res.render('about');
    });

    router.get('/videos', function (req, res) {
      res.locals.title = "Videos | Bearded Baritones";
      res.render('videos');
    });

    router.get('/arrangements', function (req, res) {
      res.locals.title = "Arrangements | Bearded Baritones";
      getArrangements.getArrangements('data/arrangements.json', function (arrangements,err) {
        if (!err) {
          res.locals.arrangements = arrangements;
          res.render('arrangements');
        } else {
          res.render('500', {
            status: err.status || 500,
            error: err
          });
        }
      });
    });

    router.get('/appearances', function (req, res) {
      res.locals.title = "Appearances | Bearded Baritones";
      getEvents.getEvents('data' + '/appearances.xml', function (events, err) {
        if (!err) {
          res.locals.events = events;
          res.render('appearances');
        } else {
          res.render('500', {
            status: err.status || 500,
            error: err
          });
        }
      });
    });

    router.get('/photos', function (req, res) {
      utils.getImagesForPhotosPage(function(images, err) {
          if (!err) {
            res.locals.photos=images;
            res.locals.title = "Photos | Bearded Baritones";
            res.render('photos');
          } else {
            res.render('500', {
              status: err.status || 500,
              error: err
            });
          }
      });
    });

    router.get('/contact', function (req, res) {
      res.locals.title = "Contact | Bearded Baritones";
      res.render('contact');
    });

    router.post('/contact', function(req, res) {
      //Setup the email
      console.log(req.body);
        config.postmark.sendEmail({
            "From": "dan@ddajohnson.com",
            "To": "bearded.baritones@gmail.com",
            "Reply-To": "req.body.email",
            "Subject": "Contact Request From Bearded Baritones Website: " + req.body.name + "<" + req.body.email + ">",
            "TextBody": req.body.message,
        }, function(error, success) {
            if(error) {
                console.error("Unable to send via postmark: " + error.message);
                res.status(400).send(error.message);
                return;
            }
            res.status(200).send();
            console.info("Sent to postmark for delivery");
        });
    });

    // Error handling middleware
    app.use(function(req, res, next){
        res.render('404', { status: 404, url: req.url });
    });

    app.use(function(err, req, res, next){
        res.render('500', {
            status: err.status || 500,
            error: err
        });
    });

    return server;
}

<|endoftext|>


<commit_before>
// Reference to the root of the Firebase database
var database = new Firebase("https://conquiz.firebaseio.com/");
// Reference to the google sheets of questions
var questionsLink = 'https://spreadsheets.google.com/feeds/list/1C1POJrIlpm1R3muE0ImmI_ifxpH_aEfPP-QSyl3o2Kg/1/public/basic?alt=json';
var question;
var rows;

$("#upload").click(function() { // If the user clicks on the input with the id="upload"
	var name = $("#nameInput").val();
	var text = $("#messageInput").val();
	if (name.length != 0 && text.length != 0) { // Don't upload if there's no information in the textboxes
		console.log(name.length);
		console.log(text.length);

		database.push({name: name, text: text}); // Push the data onto the database

	}else { // warns user of their empty textbox
		console.log("Please input values into the textbox");
	}
});

database.on('child_added', function(update) {
	question = {};
	var questionJSON = update.val();
	var question = new Question({
		id: '1',
		question: {Question: question['question']},
		answers: {correct: question['correct'], wa1: question['wa1'], wa2: question['wa2'], wa3: question['wa3']}
	})
	game.push("question", question);
});

// Get an update once the database has new data
// database.on('child_added', function(update) {
// 	questions = update.val();

// 	console.log("Successfully retrieve questions from database.");
// });

// database.on("child_added", function(update) { // Get an update once the database has new data
// 			console.log("Callback function: New data has been added to the database");
// 			var message = update.val();
// 			displayUpdate(message.name, message.text);
// });

function displayUpdate(name, text) {
	$("<div/>").text(text).prepend($("<em/>").text(name+": ")).appendTo($("#messageDiv"));
	$("#messageDiv")[0].scrollTop = $("#messageDiv")[0].scrollHeight;
};

// One time push to update the questions on firebase
function getData() {
    $.ajax({
        url: questionsLink,
        success: function(data){
            uploadFirebase(data);
        }
    });
}
// upload data to firebase
function uploadFirebase(data){
    var cells = data.feed.entry;
    rows = [];

    for (var i = 0; i < cells.length; i++){
        var rowObj = {};
        rowObj.timestamp = cells[i].title.$t;
        var rowCols = cells[i].content.$t.split(',');
        for (var j = 0; j < rowCols.length; j++){
            var keyVal = rowCols[j].split(':');
            rowObj[keyVal[0].trim()] = keyVal[1].trim();
        }
        rows.push(rowObj);
    }
    for (var i = 0; i < rows.length; i++) {
    	database.push({question: rows[i]['timestamp'], correct: rows[i]['correct'], wa1: rows[i]['wa1'], wa2: rows[i]['wa2'], wa3: rows[i]['wa3']});
    }
}

console.log('LOADED BACKEND');<commit_msg>fix errors<commit_after>
// Reference to the root of the Firebase database
var database = new Firebase("https://conquiz.firebaseio.com/");
// Reference to the google sheets of questions
var questionsLink = 'https://spreadsheets.google.com/feeds/list/1C1POJrIlpm1R3muE0ImmI_ifxpH_aEfPP-QSyl3o2Kg/1/public/basic?alt=json';
var question;
var rows;

$("#upload").click(function() { // If the user clicks on the input with the id="upload"
	var name = $("#nameInput").val();
	var text = $("#messageInput").val();
	if (name.length != 0 && text.length != 0) { // Don't upload if there's no information in the textboxes
		console.log(name.length);
		console.log(text.length);

		database.push({name: name, text: text}); // Push the data onto the database

	}else { // warns user of their empty textbox
		console.log("Please input values into the textbox");
	}
});

database.on('child_added', function(update) {
	question = {};
	var questionJSON = update.val();
	var question = new Question({
		id: '1',
		question: Question: question['question'],
		answers: "["+question['correct']+", "+question['wa1']+", "+question['wa2']+", "+question['wa3']+"]"
	});
	game.push("question", question);
});

// Get an update once the database has new data
// database.on('child_added', function(update) {
// 	questions = update.val();

// 	console.log("Successfully retrieve questions from database.");
// });

// database.on("child_added", function(update) { // Get an update once the database has new data
// 			console.log("Callback function: New data has been added to the database");
// 			var message = update.val();
// 			displayUpdate(message.name, message.text);
// });

function displayUpdate(name, text) {
	$("<div/>").text(text).prepend($("<em/>").text(name+": ")).appendTo($("#messageDiv"));
	$("#messageDiv")[0].scrollTop = $("#messageDiv")[0].scrollHeight;
};

// One time push to update the questions on firebase
function getData() {
    $.ajax({
        url: questionsLink,
        success: function(data){
            uploadFirebase(data);
        }
    });
}
// upload data to firebase
function uploadFirebase(data){
    var cells = data.feed.entry;
    rows = [];

    for (var i = 0; i < cells.length; i++){
        var rowObj = {};
        rowObj.timestamp = cells[i].title.$t;
        var rowCols = cells[i].content.$t.split(',');
        for (var j = 0; j < rowCols.length; j++){
            var keyVal = rowCols[j].split(':');
            rowObj[keyVal[0].trim()] = keyVal[1].trim();
        }
        rows.push(rowObj);
    }
    for (var i = 0; i < rows.length; i++) {
    	database.push({question: rows[i]['timestamp'], correct: rows[i]['correct'], wa1: rows[i]['wa1'], wa2: rows[i]['wa2'], wa3: rows[i]['wa3']});
    }
}

console.log('LOADED BACKEND');<|endoftext|>


<commit_before>/* This file is part of Indico.
 * Copyright (C) 2002 - 2016 European Organization for Nuclear Research (CERN).
 *
 * Indico is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 3 of the
 * License, or (at your option) any later version.
 *
 * Indico is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Indico; if not, see <http://www.gnu.org/licenses/>.
 */

(function(global) {
    'use strict';

    $(document).ready(function() {
        setupActionLinks();
        setupConfirmPopup();
        setupMathJax();
        setupSelectAllNone();
    });

    function setupSelectAllNone() {
        $('body').on('click', '[data-select-all]', function() {
            var selector = $(this).data('select-all');
            $(selector).filter(':not(:checked)').prop('checked', true).trigger('change');
        });

        $('body').on('click', '[data-select-none]', function() {
            var selector = $(this).data('select-none');
            $(selector).filter(':checked').prop('checked', false).trigger('change');
        });
    }

    function setupConfirmPopup() {
        $('body').on('click', '[data-confirm]:not(button[data-href]):not(input:button[data-href]):not(a[data-method][data-href]):not(a[data-ajax-dialog][data-href])', function() {
            var $this = $(this);
            confirmPrompt($(this).data('confirm'), $(this).data('title')).then(function() {
                var evt = $.Event('indico:confirmed');
                $this.trigger(evt);

                // Handle custom code
                if (evt.isDefaultPrevented()) {
                    return;
                }

                if ($this.is('form')) {
                    $this.submit();
                } else {
                    window.location = $this.attr('href');
                }
            });
            return false;
        });
    }

    function setupActionLinks() {
        var selectors = [
            'button[data-href][data-method]', 'input:button[data-href][data-method]', 'a[data-href][data-method]',
            'button[data-href][data-ajax-dialog]', 'input:button[data-href][data-ajax-dialog]', 'a[data-href][data-ajax-dialog]'
        ];
        $('body').on('click', selectors.join(', '), function(e) {
            e.preventDefault();
            var $this = $(this);
            if ($this.hasClass('disabled')) {
                return;
            }
            var url = $this.data('href');
            var method = ($this.data('method') || 'GET').toUpperCase();
            var params = $this.data('params') || {};
            var paramsSelector = $this.data('params-selector');
            var update = $this.data('update');
            var dialog = $this.data('ajax-dialog') !== undefined;
            var reload = $this.data('reload-after');
            if (!$.isPlainObject(params)) {
                throw new Error('Invalid params. Must be valid JSON if set.');
            }

            if (paramsSelector) {
                var fieldParams = {};
                $(paramsSelector).each(function() {
                    if (!(this.name in fieldParams)) {
                        fieldParams[this.name] = [];
                    }
                    fieldParams[this.name].push($(this).val());
                });
                params = $.extend({}, fieldParams, params);
            }

            function updateHtml(selector, html, triggeredBy) {
                var elem = $(selector);
                elem.html(html).trigger('indico:htmlUpdated', [triggeredBy]);
            }

            function handleHtmlUpdate(data, update, triggeredBy) {
                if (typeof update === 'string') {
                    updateHtml(update, data.html, triggeredBy);
                } else {
                    for (var key in update) {
                        if (!(key in data)) {
                            console.error('Invalid key: ' + key);
                        } else {
                            updateHtml(update[key], data[key], triggeredBy);
                        }
                    }
                }
            }

            function execute() {
                var evt = $.Event('indico:confirmed');
                $this.trigger(evt);

                // Handle custom code
                if (evt.isDefaultPrevented()) {
                    return;
                }

                // Handle AJAX dialog
                if (dialog) {
                    ajaxDialog({
                        trigger: $this,
                        url: url,
                        method: method,
                        data: params,
                        title: $this.data('title'),
                        subtitle: $this.data('subtitle'),
                        closeButton: $this.data('close-button'),
                        dialogClasses: $this.data('dialog-classes'),
                        hidePageHeader: $this.data('hide-page-header') !== undefined,
                        onClose: function(data, customData) {
                            if (data) {
                                handleFlashes(data, true, $this);
                                if (update) {
                                    handleHtmlUpdate(data, update, $this);
                                } else if (reload !== undefined && reload !== 'customData') {
                                    location.reload();
                                }
                            } else if (reload === 'customData' && customData) {
                                location.reload();
                            }
                        }
                    });
                    return;
                }

                // Handle html update
                if (update) {
                    $.ajax({
                        method: method,
                        url: url,
                        data: params,
                        error: handleAjaxError,
                        complete: IndicoUI.Dialogs.Util.progress(),
                        success: function(data) {
                            handleFlashes(data, true, $this);
                            handleHtmlUpdate(data, update, $this);
                        }
                    });
                    return;
                }

                // Handle normal GET/POST
                if (method === 'GET') {
                    location.href = build_url(url, params);
                } else if (method === 'POST') {
                    var form = $('<form>', {
                        action: url,
                        method: method
                    });
                    form.append($('<input>', {type: 'hidden', name: 'csrf_token', value: $('#csrf-token').attr('content')}));
                    $.each(params, function(key, value) {
                        form.append($('<input>', {type: 'hidden', name: key, value: value}));
                    });
                    form.appendTo('body').submit();
                }
            }

            var promptMsg = $this.data('confirm');
            var confirmed;
            if (!promptMsg) {
                confirmed = $.Deferred().resolve();
            } else {
                confirmed = confirmPrompt(promptMsg, $(this).data('title') || $T('Confirm action'));
            }
            confirmed.then(execute);
        });
    }

    function setupMathJax() {
        var $elems = $('.js-mathjax');
        if ($elems.length) {
            $elems.mathJax();
        }
    }
})(window);
<commit_msg>Show progress dialog when refreshing the page<commit_after>/* This file is part of Indico.
 * Copyright (C) 2002 - 2016 European Organization for Nuclear Research (CERN).
 *
 * Indico is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 3 of the
 * License, or (at your option) any later version.
 *
 * Indico is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Indico; if not, see <http://www.gnu.org/licenses/>.
 */

(function(global) {
    'use strict';

    $(document).ready(function() {
        setupActionLinks();
        setupConfirmPopup();
        setupMathJax();
        setupSelectAllNone();
    });

    function setupSelectAllNone() {
        $('body').on('click', '[data-select-all]', function() {
            var selector = $(this).data('select-all');
            $(selector).filter(':not(:checked)').prop('checked', true).trigger('change');
        });

        $('body').on('click', '[data-select-none]', function() {
            var selector = $(this).data('select-none');
            $(selector).filter(':checked').prop('checked', false).trigger('change');
        });
    }

    function setupConfirmPopup() {
        $('body').on('click', '[data-confirm]:not(button[data-href]):not(input:button[data-href]):not(a[data-method][data-href]):not(a[data-ajax-dialog][data-href])', function() {
            var $this = $(this);
            confirmPrompt($(this).data('confirm'), $(this).data('title')).then(function() {
                var evt = $.Event('indico:confirmed');
                $this.trigger(evt);

                // Handle custom code
                if (evt.isDefaultPrevented()) {
                    return;
                }

                if ($this.is('form')) {
                    $this.submit();
                } else {
                    window.location = $this.attr('href');
                }
            });
            return false;
        });
    }

    function setupActionLinks() {
        var selectors = [
            'button[data-href][data-method]', 'input:button[data-href][data-method]', 'a[data-href][data-method]',
            'button[data-href][data-ajax-dialog]', 'input:button[data-href][data-ajax-dialog]', 'a[data-href][data-ajax-dialog]'
        ];
        $('body').on('click', selectors.join(', '), function(e) {
            e.preventDefault();
            var $this = $(this);
            if ($this.hasClass('disabled')) {
                return;
            }
            var url = $this.data('href');
            var method = ($this.data('method') || 'GET').toUpperCase();
            var params = $this.data('params') || {};
            var paramsSelector = $this.data('params-selector');
            var update = $this.data('update');
            var dialog = $this.data('ajax-dialog') !== undefined;
            var reload = $this.data('reload-after');
            if (!$.isPlainObject(params)) {
                throw new Error('Invalid params. Must be valid JSON if set.');
            }

            if (paramsSelector) {
                var fieldParams = {};
                $(paramsSelector).each(function() {
                    if (!(this.name in fieldParams)) {
                        fieldParams[this.name] = [];
                    }
                    fieldParams[this.name].push($(this).val());
                });
                params = $.extend({}, fieldParams, params);
            }

            function updateHtml(selector, html, triggeredBy) {
                var elem = $(selector);
                elem.html(html).trigger('indico:htmlUpdated', [triggeredBy]);
            }

            function handleHtmlUpdate(data, update, triggeredBy) {
                if (typeof update === 'string') {
                    updateHtml(update, data.html, triggeredBy);
                } else {
                    for (var key in update) {
                        if (!(key in data)) {
                            console.error('Invalid key: ' + key);
                        } else {
                            updateHtml(update[key], data[key], triggeredBy);
                        }
                    }
                }
            }

            function execute() {
                var evt = $.Event('indico:confirmed');
                $this.trigger(evt);

                // Handle custom code
                if (evt.isDefaultPrevented()) {
                    return;
                }

                // Handle AJAX dialog
                if (dialog) {
                    ajaxDialog({
                        trigger: $this,
                        url: url,
                        method: method,
                        data: params,
                        title: $this.data('title'),
                        subtitle: $this.data('subtitle'),
                        closeButton: $this.data('close-button'),
                        dialogClasses: $this.data('dialog-classes'),
                        hidePageHeader: $this.data('hide-page-header') !== undefined,
                        onClose: function(data, customData) {
                            if (data) {
                                handleFlashes(data, true, $this);
                                if (update) {
                                    handleHtmlUpdate(data, update, $this);
                                } else if (reload !== undefined && reload !== 'customData') {
                                    IndicoUI.Dialogs.Util.progress();
                                    location.reload();
                                }
                            } else if (reload === 'customData' && customData) {
                                IndicoUI.Dialogs.Util.progress();
                                location.reload();
                            }
                        }
                    });
                    return;
                }

                // Handle html update
                if (update) {
                    $.ajax({
                        method: method,
                        url: url,
                        data: params,
                        error: handleAjaxError,
                        complete: IndicoUI.Dialogs.Util.progress(),
                        success: function(data) {
                            handleFlashes(data, true, $this);
                            handleHtmlUpdate(data, update, $this);
                        }
                    });
                    return;
                }

                // Handle normal GET/POST
                if (method === 'GET') {
                    location.href = build_url(url, params);
                } else if (method === 'POST') {
                    var form = $('<form>', {
                        action: url,
                        method: method
                    });
                    form.append($('<input>', {type: 'hidden', name: 'csrf_token', value: $('#csrf-token').attr('content')}));
                    $.each(params, function(key, value) {
                        form.append($('<input>', {type: 'hidden', name: key, value: value}));
                    });
                    form.appendTo('body').submit();
                }
            }

            var promptMsg = $this.data('confirm');
            var confirmed;
            if (!promptMsg) {
                confirmed = $.Deferred().resolve();
            } else {
                confirmed = confirmPrompt(promptMsg, $(this).data('title') || $T('Confirm action'));
            }
            confirmed.then(execute);
        });
    }

    function setupMathJax() {
        var $elems = $('.js-mathjax');
        if ($elems.length) {
            $elems.mathJax();
        }
    }
})(window);
<|endoftext|>


<commit_before>var moment = require('moment');

var System = {

    create: function(activityInstance, user, language, nation) {

        var now = moment();

        return {
            "User": {
                "HealthCareRole": user.startsWith("Patient") ? "Citizen" : "Physician",
                "HealthCareOrganization": {
                    "CodeValue": "fhirdemo",
                    "CodeSystem": {},
                    "CodeSystemVersion": {}
                },
                "HealthCareSpecialty": {
                    "CodeValue": {},
                    "CodeSystem": {},
                    "CodeSystemVersion": {}
                },
                "Language": {
                    "CodeValue": language,
                    "CodeSystem": "2.16.840.1.113883.6.99",
                    "CodeSystemVersion": {}
                },
                "Nation": {
                    "CodeValue": nation,
                    "CodeSystem": "ISO 3166-1",
                    "CodeSystemVersion": {}
                }
            },
            "Application": {
                "QueryID": activityInstance,
                "FeedbackType": "S",
                "CheckMoment": {
                    "CheckDate": now.format('YYYY-MM-DD'),
                    "CheckTime": now.format('HH:mm:ss')
                }
            }
        };
    }
};

module.exports = System;<commit_msg>Added some parameters for EBMeDS request<commit_after>var moment = require('moment');

var System = {

    create: function(activityInstance, user, language, nation) {

        var now = moment();

        return {
            "User": {
                "HealthCareRole": user.startsWith("Patient") ? "Citizen" : "Physician",
                "HealthCareOrganization": {
                    "CodeValue": "fhirdemo",
                    "CodeSystem": {},
                    "CodeSystemVersion": {}
                },
                "HealthCareSpecialty": {
                    "CodeValue": {},
                    "CodeSystem": {},
                    "CodeSystemVersion": {}
                },
                "Language": {
                    "CodeValue": language,
                    "CodeSystem": "2.16.840.1.113883.6.99",
                    "CodeSystemVersion": {}
                },
                "Nation": {
                    "CodeValue": nation,
                    "CodeSystem": "ISO 3166-1",
                    "CodeSystemVersion": {}
                }
            },
            "Application": {
                "QueryID": activityInstance,
                "DSSVersion": "EBMeDS Basic Interface v1.21",
                "FeedbackType": "S",
                "CheckMoment": {
                    "CheckDate": now.format('YYYY-MM-DD'),
                    "CheckTime": now.format('HH:mm:ss')
                },
                "EventTypes": {
                    "EventType": ["onOpenRecord"]
                }
            }
        };
    }
};

module.exports = System;<|endoftext|>


<commit_before>/**
 * Not type checking this file because flow doesn't like attaching
 * properties to Elements.
 */

import { looseEqual, looseIndexOf } from 'shared/util'
import { warn } from 'core/util/index'
import { isAndroid, isIE9 } from 'web/util/index'

const modelableTagRE = /^input|select|textarea|vue-component-[0-9]+(-[0-9a-zA-Z_\-]*)?$/

/* istanbul ignore if */
if (isIE9) {
  // http://www.matts411.com/post/internet-explorer-9-oninput/
  document.addEventListener('selectionchange', () => {
    const el = document.activeElement
    if (el && el.vmodel) {
      trigger(el, 'input')
    }
  })
}

export default {
  bind (el, binding, vnode) {
    if (process.env.NODE_ENV !== 'production') {
      if (!modelableTagRE.test(vnode.tag)) {
        warn(
          `v-model is not supported on element type: <${vnode.tag}>. ` +
          'If you are working with contenteditable, it\'s recommended to ' +
          'wrap a library dedicated for that purpose inside a custom component.',
          vnode.context
        )
      }
    }
    if (vnode.tag === 'select') {
      setSelected(el, binding, vnode.context)
    } else {
      if (!isAndroid) {
        el.addEventListener('compositionstart', onCompositionStart)
        el.addEventListener('compositionend', onCompositionEnd)
      }
      /* istanbul ignore if */
      if (isIE9) {
        el.vmodel = true
      }
    }
  },
  componentUpdated (el, binding, vnode) {
    if (vnode.tag === 'select') {
      setSelected(el, binding, vnode.context)
      // in case the options rendered by v-for have changed,
      // it's possible that the value is out-of-sync with the rendered options.
      // detect such cases and filter out values that no longer has a matchig
      // option in the DOM.
      const needReset = el.multiple
        ? binding.value.some(v => hasNoMatchingOption(v, el.options))
        : hasNoMatchingOption(binding.value, el.options)
      if (needReset) {
        trigger(el, 'change')
      }
    }
  }
}

function setSelected (el, binding, vm) {
  const value = binding.value
  const isMultiple = el.multiple
  if (isMultiple && !Array.isArray(value)) {
    process.env.NODE_ENV !== 'production' && warn(
      `<select multiple v-model="${binding.expression}"> ` +
      `expects an Array value for its binding, but got ${
        Object.prototype.toString.call(value).slice(8, -1)
      }`,
      vm
    )
    return
  }
  let selected, option
  for (let i = 0, l = el.options.length; i < l; i++) {
    option = el.options[i]
    if (isMultiple) {
      selected = looseIndexOf(value, getValue(option)) > -1
      if (option.selected !== selected) {
        option.selected = selected
      }
    } else {
      if (looseEqual(getValue(option), value)) {
        if (el.selectedIndex !== i) {
          el.selectedIndex = i
        }
        return
      }
    }
  }
  if (!isMultiple) {
    el.selectedIndex = -1
  }
}

function hasNoMatchingOption (value, options) {
  for (let i = 0, l = options.length; i < l; i++) {
    if (looseEqual(getValue(options[i]), value)) {
      return false
    }
  }
  return true
}

function getValue (option) {
  return '_value' in option
    ? option._value
    : option.value || option.text
}

function onCompositionStart (e) {
  e.target.composing = true
}

function onCompositionEnd (e) {
  e.target.composing = false
  trigger(e.target, 'input')
}

function trigger (el, type) {
  const e = document.createEvent('HTMLEvents')
  e.initEvent(type, true, true)
  el.dispatchEvent(e)
}
<commit_msg>no need to return text in getValue for v-model select (fix #3729)<commit_after>/**
 * Not type checking this file because flow doesn't like attaching
 * properties to Elements.
 */

import { looseEqual, looseIndexOf } from 'shared/util'
import { warn } from 'core/util/index'
import { isAndroid, isIE9 } from 'web/util/index'

const modelableTagRE = /^input|select|textarea|vue-component-[0-9]+(-[0-9a-zA-Z_\-]*)?$/

/* istanbul ignore if */
if (isIE9) {
  // http://www.matts411.com/post/internet-explorer-9-oninput/
  document.addEventListener('selectionchange', () => {
    const el = document.activeElement
    if (el && el.vmodel) {
      trigger(el, 'input')
    }
  })
}

export default {
  bind (el, binding, vnode) {
    if (process.env.NODE_ENV !== 'production') {
      if (!modelableTagRE.test(vnode.tag)) {
        warn(
          `v-model is not supported on element type: <${vnode.tag}>. ` +
          'If you are working with contenteditable, it\'s recommended to ' +
          'wrap a library dedicated for that purpose inside a custom component.',
          vnode.context
        )
      }
    }
    if (vnode.tag === 'select') {
      setSelected(el, binding, vnode.context)
    } else {
      if (!isAndroid) {
        el.addEventListener('compositionstart', onCompositionStart)
        el.addEventListener('compositionend', onCompositionEnd)
      }
      /* istanbul ignore if */
      if (isIE9) {
        el.vmodel = true
      }
    }
  },
  componentUpdated (el, binding, vnode) {
    if (vnode.tag === 'select') {
      setSelected(el, binding, vnode.context)
      // in case the options rendered by v-for have changed,
      // it's possible that the value is out-of-sync with the rendered options.
      // detect such cases and filter out values that no longer has a matchig
      // option in the DOM.
      const needReset = el.multiple
        ? binding.value.some(v => hasNoMatchingOption(v, el.options))
        : hasNoMatchingOption(binding.value, el.options)
      if (needReset) {
        trigger(el, 'change')
      }
    }
  }
}

function setSelected (el, binding, vm) {
  const value = binding.value
  const isMultiple = el.multiple
  if (isMultiple && !Array.isArray(value)) {
    process.env.NODE_ENV !== 'production' && warn(
      `<select multiple v-model="${binding.expression}"> ` +
      `expects an Array value for its binding, but got ${
        Object.prototype.toString.call(value).slice(8, -1)
      }`,
      vm
    )
    return
  }
  let selected, option
  for (let i = 0, l = el.options.length; i < l; i++) {
    option = el.options[i]
    if (isMultiple) {
      selected = looseIndexOf(value, getValue(option)) > -1
      if (option.selected !== selected) {
        option.selected = selected
      }
    } else {
      if (looseEqual(getValue(option), value)) {
        if (el.selectedIndex !== i) {
          el.selectedIndex = i
        }
        return
      }
    }
  }
  if (!isMultiple) {
    el.selectedIndex = -1
  }
}

function hasNoMatchingOption (value, options) {
  for (let i = 0, l = options.length; i < l; i++) {
    if (looseEqual(getValue(options[i]), value)) {
      return false
    }
  }
  return true
}

function getValue (option) {
  return '_value' in option
    ? option._value
    : option.value
}

function onCompositionStart (e) {
  e.target.composing = true
}

function onCompositionEnd (e) {
  e.target.composing = false
  trigger(e.target, 'input')
}

function trigger (el, type) {
  const e = document.createEvent('HTMLEvents')
  e.initEvent(type, true, true)
  el.dispatchEvent(e)
}
<|endoftext|>


<commit_before>
var http = require('http');
var path = require('path');

var async = require('async');

var express = require('express');

var WebSocketEvents = require("./websockets.js");
var wsserver = new WebSocketEvents({port: 8080,path:'/websocket/connection'});

var router = express();
var server = http.createServer(router);

router.post('/data/:id',function(req,res) {
   id=req.params.id;
   body=''
   res.on('data',function(chunk) {
       body+=chunk.toString();
   });
   res.on('end',function() {
       bodyjson=null;
       try {
           bodyjson=JSON.parse(body);
       } catch(err) {
           res.statusCode = 400;
           return res.end('error: ' + er.message);
       }
       async(wsserver.send_event(id,bodyjson));
       res.statusCode=204;
       res.end();
   })
});<commit_msg>server js added post handler<commit_after>
var http = require('http');
var path = require('path');

var async = require('async');

var express = require('express');

var WebSocketEvents = require("./websockets.js");
var wsserver = new WebSocketEvents({port: 8080,path:'/websocket/connection'});

var router = express();
var server = http.createServer(router);

function consumePostData(res) {
    var data = new Buffer();
    while(chunk=res.read()) data.write(chunk.toString());
    return data.toString();
}

router.post('/data/:id',function(req,res) {
   id=req.params.id;
   body=consumePostData(res);
    bodyjson=null;
    try {
       bodyjson=JSON.parse(body);
    } catch(err) {
       res.statusCode = 400;
       return res.end('error: ' + er.message);
    }
       async(wsserver.send_event(id,bodyjson));
       res.statusCode=204;
       res.end();
});

<|endoftext|>


<commit_before>'use strict';

var contains      = require('es5-ext/array/#/contains')
  , uniq          = require('es5-ext/array/#/uniq')
  , remove        = require('es5-ext/array/#/remove')
  , k             = require('es5-ext/function/k')
  , assign        = require('es5-ext/object/assign')
  , Set           = require('es6-set')
  , d             = require('d/d')
  , autoBind      = require('d/auto-bind')
  , makeElement   = require('dom-ext/document/#/make-element')
  , castAttribute = require('dom-ext/element/#/cast-attribute')
  , extend        = require('dom-ext/element/#/extend')
  , removeEl      = require('dom-ext/element/#/remove')
  , setPresenceEl = require('dom-ext/element/#/set-presence')
  , isAnchor     = require('dom-ext/html-anchor-element/is-html-anchor-element')
  , DOMInput      = require('../_controls/input')

  , getName = Object.getOwnPropertyDescriptor(DOMInput.prototype, 'name').get
  , Input;

module.exports = Input = function (document, type/*, options*/) {
	var options = arguments[2];
	this.items = [];
	this.removeButtons = [];
	this.make = makeElement.bind(document);
	this.type = type;
	options = this._resolveOptions(options);
	delete options.multiple;
	if (options.minInputsCount) {
		this.minInputsCount = options.minInputsCount >>> 0;
		delete options.minInputsCount;
	}
	if (options.addLabel) {
		this.addLabel = (typeof options.addLabel === 'function')
			? options.addLabel() : options.addLabel;
		delete options.addLabel;
	} else if (typeof this.addLabel === 'function') {
		this.addLabel = this.addLabel();
	}
	if (options.deleteLabel) {
		this.deleteLabel = (typeof options.deleteLabel === 'function') ?
				options.deleteLabel : k(options.deleteLabel);
		delete options.deleteLabel;
	}

	this.options = Object(options.item);
	this.options.dbOptions = options.dbOptions;
	this.options.control = Object(this.options.control);
	DOMInput.call(this, document, type, options);
	document.addEventListener('reset', this._onReset, false);
};

Input.prototype = Object.create(DOMInput.prototype, assign({
	_value: d(null),
	controlAttributes: d({}),
	minInputsCount: d(0),
	onChange: d(function () {
		var value, changed, valid, emitChanged, emitValid;
		value = this.value;
		changed = this.items.some(function (item) { return item.changed; });
		valid = this.items.every(function (item) { return item.valid;  });
		if (valid && this.required) valid = Boolean(value.length);

		if (this.changed !== changed) {
			this.changed = changed;
			emitChanged = true;
		}
		if (this.valid !== valid) {
			this.valid = valid;
			emitValid = true;
		}

		this.emit('change', value);
		if (emitChanged) this.emit('change:changed', this.changed);
		if (emitValid) this.emit('change:valid', this.valid);
	}),
	name: d.gs(getName, function (name) {
		this._name = name;
		name = this.name;
		this.items.forEach(function (input) { input.name = name; });
	}),
	inputValue: d.gs(function () {
		return uniq.call(this.items.map(function (item) { return item.value; })
			.filter(function (value) { return value != null; }));
	}, function (value) {
		var length, item, index = -1;
		if (value == null) value = new Set();
		this._value = value;
		value.forEach(function (value) {
			var item = this.items[++index];
			if (!item) item = this.addItem();
			item.index = index;
			item.value = value;
		}, this);

		length = value.size;
		while (this.items[length]) this.removeItem(this.items[length]);
		while (length < this.minInputsCount) {
			item = this.addItem();
			item.index = length++;
		}
	}),
	value: d.gs(function () { return this.inputValue; }, function (value) {
		this.inputValue = value;
	}),
	castControlAttribute: d(function (name, value) {
		this.options.control[name] = value;
		this.items.forEach(function (input) {
			input.castControlAttribute(name, value);
		});
		if (name === 'disabled') {
			if (this.addButton) setPresenceEl.call(this.addButton, !value);
			this.removeButtons.forEach(function (btn) {
				setPresenceEl.call(btn, !value);
			});
		}
	}),
	addLabel: d('Add'),
	deleteLabel: d(k('x')),
	_render: d(function () {
		var el = this.make;
		this.domList = el('ul');
		this.addButton = this.addLabel;
		if (isAnchor(this.addButton)) {
			castAttribute.call(this.addButton, 'onclick', this.addItem);
		} else {
			this.addButton = el('a', { onclick: this.addItem }, this.addButton);
		}
		this.dom = el('div', { class: 'dbjs multiple' }, this.domList,
			el('div', { class: 'controls' }, this.addButton));
	}),
	safeRemoveItem: d(function (input) {
		if (this.domList.childNodes.length <= this.minInputsCount) return;
		this.removeItem(input);
	}),
	removeItem: d(function (input) {
		if (!contains.call(this.items, input)) return;
		removeEl.call(input.listItem);
		remove.call(this.items, input);
		input.destroy();
		this.items.forEach(function (item, index) { item.index = index; });
		this.onChange();
	}),
	renderItem: d(function () {
		var el = this.make, dom, input, removeButton;
		input = this.type.toDOMInput(this.document, this.options);
		dom = el('li');
		removeButton = this.deleteLabel();
		if (isAnchor(removeButton)) {
			castAttribute.call(removeButton, 'onclick',
				this.safeRemoveItem.bind(this, input));
		} else {
			removeButton = el('a', { onclick: this.safeRemoveItem.bind(this, input) },
				removeButton);
		}
		extend.call(dom, input, removeButton);
		this.removeButtons.push(removeButton);
		if (this.options.control.disabled) setPresenceEl.call(removeButton, false);
		return { dom: dom, input: input };
	})
}, autoBind({
	addItem: d(function () {
		var data = this.renderItem(), input = data.input, dom = data.dom;
		if (this.name) input.name = this.name;
		input.index = this.items.length;
		input.parent = this;
		this.items.push(input);
		input.listItem = dom;
		input.on('change', this.onChange);
		this.domList.appendChild(dom);
		this.onChange();
		return input;
	}),
	_onReset: d(function (e) {
		var control = this.dom.getElementsByTagName('input')[0];
		if (!control) control = this.dom.getElementsByTagName('select')[0];
		if (!control) control = this.dom.getElementsByTagName('textarea')[0];
		if (!control) return;
		if (e.target !== control.form) return;
		this.inputValue = this._value;
	})
})));
<commit_msg>Update up to changes in es5-ext<commit_after>'use strict';

var contains      = require('es5-ext/array/#/contains')
  , uniq          = require('es5-ext/array/#/uniq')
  , remove        = require('es5-ext/array/#/remove')
  , constant      = require('es5-ext/function/constant')
  , assign        = require('es5-ext/object/assign')
  , Set           = require('es6-set')
  , d             = require('d/d')
  , autoBind      = require('d/auto-bind')
  , makeElement   = require('dom-ext/document/#/make-element')
  , castAttribute = require('dom-ext/element/#/cast-attribute')
  , extend        = require('dom-ext/element/#/extend')
  , removeEl      = require('dom-ext/element/#/remove')
  , setPresenceEl = require('dom-ext/element/#/set-presence')
  , isAnchor     = require('dom-ext/html-anchor-element/is-html-anchor-element')
  , DOMInput      = require('../_controls/input')

  , getName = Object.getOwnPropertyDescriptor(DOMInput.prototype, 'name').get
  , Input;

module.exports = Input = function (document, type/*, options*/) {
	var options = arguments[2];
	this.items = [];
	this.removeButtons = [];
	this.make = makeElement.bind(document);
	this.type = type;
	options = this._resolveOptions(options);
	delete options.multiple;
	if (options.minInputsCount) {
		this.minInputsCount = options.minInputsCount >>> 0;
		delete options.minInputsCount;
	}
	if (options.addLabel) {
		this.addLabel = (typeof options.addLabel === 'function')
			? options.addLabel() : options.addLabel;
		delete options.addLabel;
	} else if (typeof this.addLabel === 'function') {
		this.addLabel = this.addLabel();
	}
	if (options.deleteLabel) {
		this.deleteLabel = (typeof options.deleteLabel === 'function')
			? options.deleteLabel : constant(options.deleteLabel);
		delete options.deleteLabel;
	}

	this.options = Object(options.item);
	this.options.dbOptions = options.dbOptions;
	this.options.control = Object(this.options.control);
	DOMInput.call(this, document, type, options);
	document.addEventListener('reset', this._onReset, false);
};

Input.prototype = Object.create(DOMInput.prototype, assign({
	_value: d(null),
	controlAttributes: d({}),
	minInputsCount: d(0),
	onChange: d(function () {
		var value, changed, valid, emitChanged, emitValid;
		value = this.value;
		changed = this.items.some(function (item) { return item.changed; });
		valid = this.items.every(function (item) { return item.valid;  });
		if (valid && this.required) valid = Boolean(value.length);

		if (this.changed !== changed) {
			this.changed = changed;
			emitChanged = true;
		}
		if (this.valid !== valid) {
			this.valid = valid;
			emitValid = true;
		}

		this.emit('change', value);
		if (emitChanged) this.emit('change:changed', this.changed);
		if (emitValid) this.emit('change:valid', this.valid);
	}),
	name: d.gs(getName, function (name) {
		this._name = name;
		name = this.name;
		this.items.forEach(function (input) { input.name = name; });
	}),
	inputValue: d.gs(function () {
		return uniq.call(this.items.map(function (item) { return item.value; })
			.filter(function (value) { return value != null; }));
	}, function (value) {
		var length, item, index = -1;
		if (value == null) value = new Set();
		this._value = value;
		value.forEach(function (value) {
			var item = this.items[++index];
			if (!item) item = this.addItem();
			item.index = index;
			item.value = value;
		}, this);

		length = value.size;
		while (this.items[length]) this.removeItem(this.items[length]);
		while (length < this.minInputsCount) {
			item = this.addItem();
			item.index = length++;
		}
	}),
	value: d.gs(function () { return this.inputValue; }, function (value) {
		this.inputValue = value;
	}),
	castControlAttribute: d(function (name, value) {
		this.options.control[name] = value;
		this.items.forEach(function (input) {
			input.castControlAttribute(name, value);
		});
		if (name === 'disabled') {
			if (this.addButton) setPresenceEl.call(this.addButton, !value);
			this.removeButtons.forEach(function (btn) {
				setPresenceEl.call(btn, !value);
			});
		}
	}),
	addLabel: d('Add'),
	deleteLabel: d(constant('x')),
	_render: d(function () {
		var el = this.make;
		this.domList = el('ul');
		this.addButton = this.addLabel;
		if (isAnchor(this.addButton)) {
			castAttribute.call(this.addButton, 'onclick', this.addItem);
		} else {
			this.addButton = el('a', { onclick: this.addItem }, this.addButton);
		}
		this.dom = el('div', { class: 'dbjs multiple' }, this.domList,
			el('div', { class: 'controls' }, this.addButton));
	}),
	safeRemoveItem: d(function (input) {
		if (this.domList.childNodes.length <= this.minInputsCount) return;
		this.removeItem(input);
	}),
	removeItem: d(function (input) {
		if (!contains.call(this.items, input)) return;
		removeEl.call(input.listItem);
		remove.call(this.items, input);
		input.destroy();
		this.items.forEach(function (item, index) { item.index = index; });
		this.onChange();
	}),
	renderItem: d(function () {
		var el = this.make, dom, input, removeButton;
		input = this.type.toDOMInput(this.document, this.options);
		dom = el('li');
		removeButton = this.deleteLabel();
		if (isAnchor(removeButton)) {
			castAttribute.call(removeButton, 'onclick',
				this.safeRemoveItem.bind(this, input));
		} else {
			removeButton = el('a', { onclick: this.safeRemoveItem.bind(this, input) },
				removeButton);
		}
		extend.call(dom, input, removeButton);
		this.removeButtons.push(removeButton);
		if (this.options.control.disabled) setPresenceEl.call(removeButton, false);
		return { dom: dom, input: input };
	})
}, autoBind({
	addItem: d(function () {
		var data = this.renderItem(), input = data.input, dom = data.dom;
		if (this.name) input.name = this.name;
		input.index = this.items.length;
		input.parent = this;
		this.items.push(input);
		input.listItem = dom;
		input.on('change', this.onChange);
		this.domList.appendChild(dom);
		this.onChange();
		return input;
	}),
	_onReset: d(function (e) {
		var control = this.dom.getElementsByTagName('input')[0];
		if (!control) control = this.dom.getElementsByTagName('select')[0];
		if (!control) control = this.dom.getElementsByTagName('textarea')[0];
		if (!control) return;
		if (e.target !== control.form) return;
		this.inputValue = this._value;
	})
})));
<|endoftext|>