<commit_before>var React = window.React = require('react'),
    classNames = require('classnames'),
    mountNode = document.getElementById("app");
var ReactDOM = require('react-dom');

var MetroCardCalculator = React.createClass({
        updateInputs: function(value) {
            this.setState({
                amountOnCard: value.amount,
                farePrice: value.fare
            });
        },
        getInitialState: function() {
            return ({
                amountOnCard: 0,
                farePrice: 2.75
            });
        },
        render: function() {
            return
<InputForm updateInputs = {this.updateInputs}/>

<ComputationTable farePrice={this.state.farePrice} amountOnCard={this.state.amountOnCard}/>
;
        }
    });

    var InputForm = React.createClass({
        handleChange: function() {
          var amount = this.refs.amountOnCard.value;
          var fare = this.refs.farePrice.value;
          this.props.updateInputs({amount: amount, fare: fare});
        },
        getDefaultProps: function () {
            return {
                defaultAmountOnCard: 0,
                defaultFarePrice: 2.75
            };
        },
        render: function () {
            return
<form>

            <input defaultValue={this.props.defaultAmountOnCard} ref='amountOnCard' id='amountOnCard' onChange={this.handleChange} type="number" className="validate"/>
            Current Amount on Card

            <input defaultValue = {this.props.defaultFarePrice} ref='farePrice' id='farePrice' onChange = {this.handleChange} type="number" className="validate"/>
            Fare Price

            </form>
;
        }
    });

    var ComputationTable = React.createClass({
        calculateFareTable: function(amount, fare, bonus) {
            var rows = [];
            var minAdd = (fare*2).toFixed(2);
            var minTotal = (amount*1 + fare*2*(1+bonus)).toFixed(2);
            var minRides = Math.floor(minTotal /
                fare);
            var minRemainder = (minTotal % fare).toFixed(2);
            for (var i = minRides; i < minRides + 20; i++) {
                var neededAdd = ((i * fare - amount) / (1 + bonus));
                var allowableAdd = (Math.ceil(neededAdd * 20) / 20 < 5.50 ? 5.50 : Math.ceil(neededAdd * 20) / 20).toFixed(2);

                var total = ((allowableAdd * (1 + bonus)) + amount * 1).toFixed(2);
                var rides = Math.floor(total / fare);
                var remainder = (total % fare).toFixed(2);

                rows.push({
                    rides: rides,
                    add: allowableAdd,
                    total: total,
                    remainder: remainder
                });
            }
            return (rows);
        },
        render: function() {
            var rows = this.calculateFareTable(this.props.amountOnCard, this.props.farePrice, .11);

            return (

  For this many rides 	Add this amount	  Leaving a remainder of 	Total Amount

 {
                    rows.map(function(row, i) {
                        var classes = classNames({
                          'teal': row.remainder < 0.01,
                          'z-depth-3': row.remainder < 0.01,
                          'red': row.remainder > 0.05
                        });
                        return (

                                     {row.rides}
                                     {row.add}
                                     {row.remainder}
                                     {row.total}

            );})}

);
        }
    });

ReactDOM.render(<MetroCardCalculator /> , mountNode);
<commit_msg>fixed problem with decimals<commit_after>var React = window.React = require('react'),
    classNames = require('classnames'),
    mountNode = document.getElementById("app");
var ReactDOM = require('react-dom');

var MetroCardCalculator = React.createClass({
        updateInputs: function(value) {
          if ('amount' in value) {
            this.setState({
                amountOnCard: value.amount,
            });
          }
          if ('fare' in value) {
            this.setState({
                farePrice: value.fare,
            });
          }
        },
        getInitialState: function() {
            return ({
                amountOnCard: 0,
                farePrice: 2.75
            });
        },
        render: function() {
            return
<InputForm updateInputs = {this.updateInputs}/>

<ComputationTable farePrice={this.state.farePrice} amountOnCard={this.state.amountOnCard}/>
;
        }
    });

    var InputForm = React.createClass({
        handleAmountChange: function(e) {
          this.props.updateInputs({amount: e.target.value});
        },
        handleFareChange: function(e) {
          this.props.updateInputs({fare: e.target.value});
        },
        getDefaultProps: function () {
            return {
                defaultAmountOnCard: 0,
                defaultFarePrice: 2.75
            };
        },
        render: function () {
            return
<form>

            <input ref='amountOnCard' id='amountOnCard' onChange={this.handleAmountChange} type="number" min="0" step="0.01"/>
            Current Amount on Card

            <input defaultValue = {this.props.defaultFarePrice} ref='farePrice' id='farePrice' onChange = {this.handleFareChange} type="number" min="0" step=".01" className="validate"/>
            Fare Price

            </form>
;
        }
    });

    var ComputationTable = React.createClass({
        calculateFareTable: function(amount, fare, bonus) {
            var rows = [];
            var minAdd = (fare*2).toFixed(2);
            var minTotal = (amount*1 + fare*2*(1+bonus)).toFixed(2);
            var minRides = Math.floor(minTotal /
                fare);
            var minRemainder = (minTotal % fare).toFixed(2);
            for (var i = minRides; i < minRides + 20; i++) {
                var neededAdd = ((i * fare - amount) / (1 + bonus));
                var allowableAdd = (Math.ceil(neededAdd * 20) / 20 < 5.50 ? 5.50 : Math.ceil(neededAdd * 20) / 20).toFixed(2);

                var total = ((allowableAdd * (1 + bonus)) + amount * 1).toFixed(2);
                var rides = Math.floor(total / fare);
                var remainder = (total % fare).toFixed(2);

                rows.push({
                    rides: rides,
                    add: allowableAdd,
                    total: total,
                    remainder: remainder
                });
            }
            return (rows);
        },
        render: function() {
            var rows = this.calculateFareTable(this.props.amountOnCard, this.props.farePrice, .11);

            return (

For this many rides	Add this amount	 Leaving a remainder of 	Total Amount

 {
                    rows.map(function(row, i) {
                        var classes = classNames({
                          'teal': row.remainder < 0.01,
                          'z-depth-3': row.remainder < 0.01,
                          'red': row.remainder > 0.05
                        });
                        return (

                                     {row.rides}
                                     {row.add}
                                     {row.remainder}
                                     {row.total}

            );})}

);
        }
    });

ReactDOM.render(<MetroCardCalculator /> , mountNode);
<|endoftext|>


<commit_before>/*
 * SERVER - The Server
 */
var express = require('express'),
	device = require('../lib/device.js'),
	redirect = require('express-redirect'),
	bodyParser = require('body-parser'),
	cookieParser = require('cookie-parser'),
	methodOverride = require('method-override'),
	errorHandler = require('errorhandler');

/*
 * CONFIGS - The Configurations
 */
config = require('../configs/server.js');
var configs = config.configs,
	server_prefix = configs.server_prefix || 'CORE';

/*
 * SERVICES - The Services
 */
var services = require('../routes/services'); // it seems that we have to start each required file as its own var

/*
 * SERVER - The Server used for shutdown etc
 * See: https://www.exratione.com/2011/07/running-a-nodejs-server-as-a-service-using-forever/
 */
var server = express();
// Port
if(typeof configs.server_port === 'undefined'){
	var server_port = process.env.PORT || 11080;
}
else {
	var server_port = configs.server_port;
}
server.listen(server_port);
console.log(server_prefix + " - Node Version: " + process.version);
console.log(server_prefix + " - Express server listening on port %d", server_port);
console.log(server_prefix + " - To shutdown server gracefully type: node prepareForStop.js");

server.get('/prepareForShutdown', function(req, res) {
	if(req.connection.remoteAddress == "127.0.0.1"
		|| req.socket.remoteAddress == "127.0.0.1"
		// 0.4.7 oddity in https only
		|| req.connection.socket.remoteAddress == "127.0.0.1")
	{
		managePreparationForShutdown(function() {
			// don't complete the connection until the preparation is done.
			res.statusCode = 200;
			res.end();
		});
	}
	else {
		res.statusCode = 500;
		res.end();
	}
});

var managePreparationForShutdown = function(callback) {
	// perform all the cleanup and other operations needed prior to shutdown,
	// but do not actually shutdown. Call the callback function only when
	// these operations are actually complete.
	try {
		app_server.close();
		console.log(server_prefix + " - Shutdown app successful.");
	}
	catch(ex) {
		console.log(server_prefix + " - Shutdown app failed.");
		console.log(ex);
	}
	try {
		api_server.close();
		console.log(server_prefix + " - Shutdown api successful.");
	}
	catch(ex) {
		console.log(server_prefix + " - Shutdown api failed.");
		console.log(ex);
	}
	console.log(server_prefix + " - All preparations for shutdown completed.");
	callback();
};

/*
 * APP - The Application
 */
var app = express();
// Port
if(typeof configs.app_port === 'undefined'){
	var app_port = process.env.PORT || 4000;
}
else {
	var app_port = configs.app_port;
}
// App List
if(typeof configs.app_list === 'undefined'){
	var app_list = {};
}
else {
	var app_list = configs.app_list;
}
/*
 * API - The Application Programming Interface
 */
var api = express();
// Port
if(typeof configs.api_port === 'undefined'){
	var api_port = app_port+1 || 4001;
}
else {
	var api_port = configs.api_port;
}
// Api List
if(typeof configs.api_list === 'undefined'){
	var api_list = {};
}
else {
	var api_list = configs.api_list;
}
// Action List
if(typeof configs.action_list === 'undefined'){
	var action_list = {};
}
else {
	var action_list = configs.action_list;
}
// Model List
if(typeof configs.model_list === 'undefined'){
	var model_list = {};
}
else {
	var model_list = configs.model_list;
}
// Format List
if(typeof configs.format_list === 'undefined'){
	var format_list = {};
}
else {
	var format_list = configs.format_list;
}
// API All
api.all('*', function(req, res, next){
  if (!req.get('Origin')) return next();
  // use "*" here to accept any origin
  res.set('Access-Control-Allow-Origin', '*');  // Accepts requests coming from anyone, replace '*' by configs.allowedHost to restrict it
  res.set('Access-Control-Allow-Methods', 'GET, PUT, POST, DELETE');
  res.set('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type');
  res.set('X-Powered-By', 'Express');
  res.set('Content-Type', 'application/json; charset=utf8');
  // res.set('Access-Control-Allow-Max-Age', 3600);
  if ('OPTIONS' == req.method) return res.send(200);
  next();
});
// API Post
api.post('/login', function(req, res){
  console.log(req.body);
  res.send(201);
});
/*
 * APP DEVELOPMENT
 *
 * .bash_profile contains
 * NODE_ENV=development
 *
 * or start server as follows
 * NODE_ENV=development node server.js
 *
 * on Windows use
 * set NODE_ENV=development
 * check with
 * echo %NODE_ENV%
 */
if('development' == app.settings.env){
	console.log(server_prefix + " - Using development configurations");
	app.set('view engine', 'ejs');
	app.set('view options', { layout: true });
	app.set('views', __dirname + '/../public');
	/*
	 * bodyParser() is the composition of three middlewares:
	 * - json: parses application/json request bodies
	 * - urlencoded: parses x-ww.form-urlencoded request bodies
	 * - multipart: parses multipart/form-data request bodies
	 */
    app.use(bodyParser()); // pull information from html in POST
    app.use(methodOverride());
    app.use(cookieParser());
    app.use(device.capture());
    app.enableDeviceHelpers();
    app.enableViewRouting();
    app.use('/resources', express.static(__dirname + '/../public/resources'));
    app.use('/app', express.static(__dirname + '/../public/app'));
    app.use(express.static(__dirname + '/../public')); // Fall back to this as a last resort
    app.use(errorHandler({ dumpExceptions: true, showStack: true })); // specific for development
};
/*
 * APP PRODUCTION
 *
 * .bash_profile contains
 * NODE_ENV=production
 *
 * or start server as follows
 * NODE_ENV=production node server.js
 *
 * on Windows use
 * set NODE_ENV=production
 * check with
 * echo %NODE_ENV%
 */
if('production' == app.settings.env){
	console.log(server_prefix + " - Using production configurations");
	app.set('view engine', 'ejs');
	app.set('view options', { layout: true });
	app.set('views', __dirname + '/../public');
	/*
	 * bodyParser() is the composition of three middlewares:
	 * - json: parses application/json request bodies
	 * - urlencoded: parses x-ww.form-urlencoded request bodies
	 * - multipart: parses multipart/form-data request bodies
	 */
    app.use(bodyParser()); // pull information from html in POST
    app.use(methodOverride());
    app.use(cookieParser());
    app.use(device.capture());
    app.enableDeviceHelpers();
    app.enableViewRouting();
    app.use('/resources', express.static(__dirname + '/../public/resources'));
    app.use('/app', express.static(__dirname + '/../public/app'));
    app.use(express.static(__dirname + '/../public')); // Fall back to this as a last resort
    app.use(errorHandler({ dumpExceptions: false, showStack: false })); // specific for production
};

app.all('*', function(req, res, next){
  if (!req.get('Origin')) return next();
  // use "*" here to accept any origin
  res.set('Access-Control-Allow-Origin', '*'); // Accepts requests coming from anyone, replace '*' by configs.allowedHosts to restrict it
  res.set('Access-Control-Allow-Methods', 'GET, PUT, POST');
  res.set('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type');
  // res.set('Access-Control-Allow-Max-Age', 3600);
  if ('OPTIONS' == req.method) return res.send(200);
  next();
});

if(typeof configs.title === 'undefined'){
	var title = 'Untitled';
}
else {
	var title = configs.title;
}

if(typeof configs.access_control_allow_origin === 'undefined'){
	var access_control_allow_origin = '*';
}
else {
	var access_control_allow_origin = configs.access_control_allow_origin;
}

if(typeof configs.web_root === 'undefined'){
	var web_root = '';
}
else {
	var web_root = configs.web_root;
}

if(typeof configs.host === 'undefined'){
	var host = req.host;
}
else {
	var host = configs.host;
}
// routing to pages
app.get('/', function(req, res) {
	// Distinguish based on an optional key-value parameter in the request url (e.g. '/?app=calculator')
	var app = 'page'; // default
	var app_name = ''; // default
	// Update app_name variable here with value from 'app' key (e.g. app=calculator) sets app to 'calculator'
	if(req.query.app) {
		app_name = req.query.app;
		var app_not_found = true; // default to true
		// Lookup app in app list, if found set not_found to false
		for (key in app_list) {
			if(key == app_name) {
				app_name = key;
				app_not_found = false;
				break;
			}
		}//eof for
		if(app_not_found) {
			console.log(server_prefix + " - App requested, but not found: " + app_name);
			app = 'not_found';
		}
	}
	console.log(server_prefix + " - App requested: " + app_name);
	// Distinguish based on an optional key-value parameter in the request url (e.g. '/?view=0')
	var view = 0; // default
	var views = 'views';
	var view_index = 0; // default
	// Update view_index variable here with value from 'view' key (e.g. view=0) sets view to 0
	if(req.query.view) {
		view_index = req.query.view;
		var view_not_found = true; // default to true
		// Lookup view in app list, if found set not_found to false
		for (key in app_list) {
			if(key == app_name) {
				app_name = key;
				app_value = app_list[key];
				for(key in app_value) {
					if(key == views) {
						views = key;
						views_value = app_value[key];
						for(key in views_value) {
							if(key == view_index) {
								view_not_found = false;
								break;
							}
						}
					}
				}
			}
		}//eof for
		if(view_not_found) {
			console.log(server_prefix + " - View requested, but not found: " + view_index);
			view = 'not_found';
		}
	}
	console.log(server_prefix + " - View requested: " + view_index);
	if(typeof configs.css_file_location === 'undefined') {
		var css_file_location = 'css/style.css';
	}
	else {
		var css_file_location = configs.css_file_location;
		// replace the css file name by the app name, if provided
		if(typeof app_name === 'undefined'){
			// continue without replacement
		}
		else {
			css_file_location = css_file_location.replace('style', app_name);
		}
	}
    res.render(app, { title: title, css_file_location: css_file_location, access_control_allow_origin: access_control_allow_origin, host: host, web_root: web_root, app_name: app_name, view_index: view_index, layout: false });
});

var app_server = app.listen(app_port, function() {
	console.log(server_prefix + " - Express app server listening on port %d in %s mode", app_port, app.settings.env);
});

var api_server = api.listen(api_port, function() {
	console.log(server_prefix + " - Express api server listening on port %d in %s mode", api_port, api.settings.env);
});
<commit_msg>Updated<commit_after>/*
 * SERVER - The Server
 */
var express = require('express'),
	device = require('../lib/device.js'),
	redirect = require('express-redirect'),
	bodyParser = require('body-parser'),
	cookieParser = require('cookie-parser'),
	methodOverride = require('method-override'),
	errorHandler = require('errorhandler');

/*
 * CONFIGS - The Configurations
 */
config = require('../configs/server.js');
var configs = config.configs,
	server_prefix = configs.server_prefix || 'CORE';

/*
 * SERVICES - The Services
 */
var services = require('../routes/services'); // it seems that we have to start each required file as its own var

/*
 * SERVER - The Server used for shutdown etc
 * See: https://www.exratione.com/2011/07/running-a-nodejs-server-as-a-service-using-forever/
 */
var server = express();
// Port
if(typeof configs.server_port === 'undefined'){
	var server_port = process.env.PORT || 11080;
}
else {
	var server_port = configs.server_port;
}
server.listen(server_port);
console.log(server_prefix + " - Node Version: " + process.version);
console.log(server_prefix + " - Express server listening on port %d", server_port);
console.log(server_prefix + " - To shutdown server gracefully type: node prepareForStop.js");

server.get('/prepareForShutdown', function(req, res) {
	if(req.connection.remoteAddress == "127.0.0.1"
		|| req.socket.remoteAddress == "127.0.0.1"
		// 0.4.7 oddity in https only
		|| req.connection.socket.remoteAddress == "127.0.0.1")
	{
		managePreparationForShutdown(function() {
			// don't complete the connection until the preparation is done.
			res.statusCode = 200;
			res.end();
		});
	}
	else {
		res.statusCode = 500;
		res.end();
	}
});

var managePreparationForShutdown = function(callback) {
	// perform all the cleanup and other operations needed prior to shutdown,
	// but do not actually shutdown. Call the callback function only when
	// these operations are actually complete.
	try {
		app_server.close();
		console.log(server_prefix + " - Shutdown app successful.");
	}
	catch(ex) {
		console.log(server_prefix + " - Shutdown app failed.");
		console.log(ex);
	}
	try {
		api_server.close();
		console.log(server_prefix + " - Shutdown api successful.");
	}
	catch(ex) {
		console.log(server_prefix + " - Shutdown api failed.");
		console.log(ex);
	}
	console.log(server_prefix + " - All preparations for shutdown completed.");
	callback();
};

/*
 * APP - The Application
 */
var app = express();
// Port
if(typeof configs.app_port === 'undefined'){
	var app_port = process.env.PORT || 4000;
}
else {
	var app_port = configs.app_port;
}
// App List
if(typeof configs.app_list === 'undefined'){
	var app_list = {};
}
else {
	var app_list = configs.app_list;
}
/*
 * API - The Application Programming Interface
 */
var api = express();
// Port
if(typeof configs.api_port === 'undefined'){
	var api_port = app_port+1 || 4001;
}
else {
	var api_port = configs.api_port;
}
// Api List
if(typeof configs.api_list === 'undefined'){
	var api_list = {};
}
else {
	var api_list = configs.api_list;
}
// Action List
if(typeof configs.action_list === 'undefined'){
	var action_list = {};
}
else {
	var action_list = configs.action_list;
}
// Model List
if(typeof configs.model_list === 'undefined'){
	var model_list = {};
}
else {
	var model_list = configs.model_list;
}
// Format List
if(typeof configs.format_list === 'undefined'){
	var format_list = {};
}
else {
	var format_list = configs.format_list;
}
// API All
api.all('*', function(req, res, next){
  if (!req.get('Origin')) return next();
  // use "*" here to accept any origin
  res.set('Access-Control-Allow-Origin', '*');  // Accepts requests coming from anyone, replace '*' by configs.allowedHost to restrict it
  res.set('Access-Control-Allow-Methods', 'GET, PUT, POST, DELETE');
  res.set('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type');
  res.set('X-Powered-By', 'Express');
  res.set('Content-Type', 'application/json; charset=utf8');
  // res.set('Access-Control-Allow-Max-Age', 3600);
  if ('OPTIONS' == req.method) return res.send(200);
  next();
});
// API Post
api.post('/login', function(req, res){
  console.log(req.body);
  res.send(201);
});
/*
 * APP DEVELOPMENT
 *
 * .bash_profile contains
 * NODE_ENV=development
 *
 * or start server as follows
 * NODE_ENV=development node server.js
 *
 * on Windows use
 * set NODE_ENV=development
 * check with
 * echo %NODE_ENV%
 */
if('development' == app.settings.env){
	console.log(server_prefix + " - Using development configurations");
	app.set('view engine', 'ejs');
	app.set('view options', { layout: true });
	app.set('views', __dirname + '/../public');
	/*
	 * bodyParser() is the composition of three middlewares:
	 * - json: parses application/json request bodies
	 * - urlencoded: parses x-ww.form-urlencoded request bodies
	 * - multipart: parses multipart/form-data request bodies
	 */
    app.use(bodyParser()); // pull information from html in POST
    app.use(methodOverride());
    app.use(cookieParser());
    app.use(device.capture());
    app.enableDeviceHelpers();
    app.enableViewRouting();
    app.use('/resources', express.static(__dirname + '/../public/resources'));
    app.use('/app', express.static(__dirname + '/../public/app'));
    app.use('/tests', express.static(__dirname + '/../tests'));
    app.use(express.static(__dirname + '/../public')); // Fall back to this as a last resort
    app.use(errorHandler({ dumpExceptions: true, showStack: true })); // specific for development
};
/*
 * APP PRODUCTION
 *
 * .bash_profile contains
 * NODE_ENV=production
 *
 * or start server as follows
 * NODE_ENV=production node server.js
 *
 * on Windows use
 * set NODE_ENV=production
 * check with
 * echo %NODE_ENV%
 */
if('production' == app.settings.env){
	console.log(server_prefix + " - Using production configurations");
	app.set('view engine', 'ejs');
	app.set('view options', { layout: true });
	app.set('views', __dirname + '/../public');
	/*
	 * bodyParser() is the composition of three middlewares:
	 * - json: parses application/json request bodies
	 * - urlencoded: parses x-ww.form-urlencoded request bodies
	 * - multipart: parses multipart/form-data request bodies
	 */
    app.use(bodyParser()); // pull information from html in POST
    app.use(methodOverride());
    app.use(cookieParser());
    app.use(device.capture());
    app.enableDeviceHelpers();
    app.enableViewRouting();
    app.use('/resources', express.static(__dirname + '/../public/resources'));
    app.use('/app', express.static(__dirname + '/../public/app'));
    app.use('/tests', express.static(__dirname + '/../tests'));
    app.use(express.static(__dirname + '/../public')); // Fall back to this as a last resort
    app.use(errorHandler({ dumpExceptions: false, showStack: false })); // specific for production
};

app.all('*', function(req, res, next){
  if (!req.get('Origin')) return next();
  // use "*" here to accept any origin
  res.set('Access-Control-Allow-Origin', '*'); // Accepts requests coming from anyone, replace '*' by configs.allowedHosts to restrict it
  res.set('Access-Control-Allow-Methods', 'GET, PUT, POST');
  res.set('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type');
  // res.set('Access-Control-Allow-Max-Age', 3600);
  if ('OPTIONS' == req.method) return res.send(200);
  next();
});

if(typeof configs.title === 'undefined'){
	var title = 'Untitled';
}
else {
	var title = configs.title;
}

if(typeof configs.access_control_allow_origin === 'undefined'){
	var access_control_allow_origin = '*';
}
else {
	var access_control_allow_origin = configs.access_control_allow_origin;
}

if(typeof configs.web_root === 'undefined'){
	var web_root = '';
}
else {
	var web_root = configs.web_root;
}

if(typeof configs.host === 'undefined'){
	var host = req.host;
}
else {
	var host = configs.host;
}
// routing to tests, use before pages
app.get('/tests/', function(req, res) {
	// Distinguish based on an optional key-value parameter in the request url (e.g. '/tests/?app=calculator')
	var app = 'test'; // default
    res.render(app, { title: title, access_control_allow_origin: access_control_allow_origin, host: host, web_root: web_root, layout: false });
});
// routing to pages
app.get('/', function(req, res) {
	// Distinguish based on an optional key-value parameter in the request url (e.g. '/?app=calculator')
	var app = 'page'; // default
	var app_name = ''; // default
	// Update app_name variable here with value from 'app' key (e.g. app=calculator) sets app to 'calculator'
	if(req.query.app) {
		app_name = req.query.app;
		var app_not_found = true; // default to true
		// Lookup app in app list, if found set not_found to false
		for (key in app_list) {
			if(key == app_name) {
				app_name = key;
				app_not_found = false;
				break;
			}
		}//eof for
		if(app_not_found) {
			console.log(server_prefix + " - App requested, but not found: " + app_name);
			app = 'not_found';
		}
	}
	console.log(server_prefix + " - App requested: " + app_name);
	// Distinguish based on an optional key-value parameter in the request url (e.g. '/?view=0')
	var view = 0; // default
	var views = 'views';
	var view_index = 0; // default
	// Update view_index variable here with value from 'view' key (e.g. view=0) sets view to 0
	if(req.query.view) {
		view_index = req.query.view;
		var view_not_found = true; // default to true
		// Lookup view in app list, if found set not_found to false
		for (key in app_list) {
			if(key == app_name) {
				app_name = key;
				app_value = app_list[key];
				for(key in app_value) {
					if(key == views) {
						views = key;
						views_value = app_value[key];
						for(key in views_value) {
							if(key == view_index) {
								view_not_found = false;
								break;
							}
						}
					}
				}
			}
		}//eof for
		if(view_not_found) {
			console.log(server_prefix + " - View requested, but not found: " + view_index);
			view = 'not_found';
		}
	}
	console.log(server_prefix + " - View requested: " + view_index);
	if(typeof configs.css_file_location === 'undefined') {
		var css_file_location = 'css/style.css';
	}
	else {
		var css_file_location = configs.css_file_location;
		// replace the css file name by the app name, if provided
		if(typeof app_name === 'undefined'){
			// continue without replacement
		}
		else {
			css_file_location = css_file_location.replace('style', app_name);
		}
	}
    res.render(app, { title: title, css_file_location: css_file_location, access_control_allow_origin: access_control_allow_origin, host: host, web_root: web_root, app_name: app_name, view_index: view_index, layout: false });
});

var app_server = app.listen(app_port, function() {
	console.log(server_prefix + " - Express app server listening on port %d in %s mode", app_port, app.settings.env);
});

var api_server = api.listen(api_port, function() {
	console.log(server_prefix + " - Express api server listening on port %d in %s mode", api_port, api.settings.env);
});
<|endoftext|>


<commit_before>'use strict';

angular.module('anyfetchFrontApp', [
  'ngCookies',
  'ngResource',
  'ngRoute',
  'anyfetchFrontApp.filters',
  'anyfetchFrontApp.gravatarDirective',
  'anyfetchFrontApp.snippetDirective',
  'anyfetchFrontApp.authenticationService',
  'anyfetchFrontApp.documentService',
  'anyfetchFrontApp.providerService'
])
  .config(function ($routeProvider, $sceProvider, $httpProvider) {

    // Disable templating HTML protection for Mustache
    $sceProvider.enabled(false);

    // Routing
    $routeProvider
      .when('/', {
        templateUrl: 'views/main.html',
        controller: 'MainCtrl'
      })
      .when('/login', {
        templateUrl: 'views/login.html',
        controller: 'LoginCtrl'
      })
      .otherwise({
        redirectTo: '/'
      });

    // // Redirection to the login page if request is unauthorized
    // var interceptor = function($location, $q) {
    //   function success(response) {
    //     return response;
    //   }

    //   function error(response) {
    //     if(response.status === 401) {
    //       $location.path('/login');
    //       return $q.reject(response);
    //     }
    //     else {
    //       return $q.reject(response);
    //     }
    //   }

    //   return function(promise) {
    //     return promise.then(success, error);
    //   };
    // };
    // $httpProvider.responseInterceptors.push(interceptor);
  })
  .run(function (AuthService, $route, $q, $location, $rootScope) {

    var bootstrapApp = function() {
        var deferred = $q.defer();

        // Watch if the current user is connected
        AuthService.isLoggedin()
          .then(function(user) {
            deferred.resolve(user);
          }, function() {
            $location.path('/login');
            deferred.resolve();
          });

        return deferred.promise;
      };

    angular.forEach($route.routes,function(value, key) {
      if(key !== '/login' || key !== '/login/') {
        $route.routes[key].resolve = {};
        $route.routes[key].resolve.currentUser = bootstrapApp;
      }
    });

    $rootScope.$on('$viewContentLoaded', function () {
      $(document).foundation();
    });
  });
<commit_msg>New provider style<commit_after>'use strict';

angular.module('anyfetchFrontApp', [
  'ngCookies',
  'ngResource',
  'ngRoute',
  'anyfetchFrontApp.filters',
  'anyfetchFrontApp.gravatarDirective',
  'anyfetchFrontApp.snippetDirective',
  'anyfetchFrontApp.authenticationService',
  'anyfetchFrontApp.documentService',
  'anyfetchFrontApp.providerService'
])
  .config(function ($routeProvider, $sceProvider, $httpProvider) {

    // Disable templating HTML protection for Mustache
    $sceProvider.enabled(false);

    // Routing
    $routeProvider
      .when('/', {
        templateUrl: 'views/main.html',
        controller: 'MainCtrl'
      })
      .when('/login', {
        templateUrl: 'views/login.html',
        controller: 'LoginCtrl'
      })
      .otherwise({
        redirectTo: '/'
      });

    // Redirection to the login page if request is unauthorized
    var interceptor = ['$location', '$q', function($location, $q) {
      function success(response) {
        return response;
      }

      function error(response) {
        if(response.status === 401) {
          $location.path('/login');
          return $q.reject(response);
        }
        else {
          return $q.reject(response);
        }
      }

      return function(promise) {
        return promise.then(success, error);
      };
    }];
    $httpProvider.responseInterceptors.push(interceptor);
  })
  .run(function (AuthService, $route, $q, $location, $rootScope) {

    var bootstrapApp = function() {
        var deferred = $q.defer();

        // Watch if the current user is connected
        AuthService.isLoggedin()
          .then(function(user) {
            deferred.resolve(user);
          }, function() {
            $location.path('/login');
            deferred.resolve();
          });

        return deferred.promise;
      };

    angular.forEach($route.routes,function(value, key) {
      if(key !== '/login' || key !== '/login/') {
        $route.routes[key].resolve = {};
        $route.routes[key].resolve.currentUser = bootstrapApp;
      }
    });

    $rootScope.$on('$viewContentLoaded', function () {
      $(document).foundation();
    });
  });
<|endoftext|>


<commit_before>
// All units in SI (seconds, pixels, meters etc) unless otherwise noted.

var canvas = document.getElementById("a");
canvas.width *= window.devicePixelRatio; // high-dpi adjustment
canvas.height *= window.devicePixelRatio;
var pixRat = window.devicePixelRatio;
var c = canvas.getContext("2d");

var rand = function(min, max) {
    return Math.random() * (max - min) + min;
};
var w = canvas.width;
var h = canvas.height;

// Constants
var obstacleHoleSize = 70;

var state = {
    gameover: false,
    pos: {
        x: w/2,
        y: h/2,
    },
    obstacle: {
        halfWidth: 10*pixRat,
        speed: 3,
        spacing: 1 - 0.22,
    },
    obstacles: {}
};

// var oneObstacle = {x: 270, holePos: 0.7, holeSize: 0.3};
state.obstacles[0] = randObstacle();

var prevTime = 0;

function draw(t) {
    if (state.gameover) {
      drawGameover();
    } else {
      c.clearRect(0,0,w,h);
      c.fillStyle = "#FF00EE";
      c.fillRect(state.pos.x -10, state.pos.y -10, 20, 20);

      for(var k in state.obstacles) {
        drawObstacle(getObstacleCorners(state.obstacles[k]));
      }

      c.font = "12pt Arial";
      c.fillStyle = "#000";
      c.fillText(t - state.startTime, 10, 10);
    }
}

function update(t, dt) {

  if ( (state.gameover) && key.space()) newGame();
  else if (checkIfPlayerIntersect()) state.gameover = true;
  else if (outOfBounds(state.pos)) state.gameover = true;
  else if (key.up()) state.pos.y -= 3;
  else if (key.left()) state.pos.x -= 3;
  else if (key.down()) state.pos.y += 3;
  else if (key.right()) state.pos.x += 3;

  for(var k in state.obstacles) {
    if (state.obstacles[k].x < 0) delete(state.obstacles[k]);
  }
  loopObstacles(function(obst) {obst.x -= state.obstacle.speed;});
  if (rightMost() < (w * state.obstacle.spacing)) addObstacle(t);

}

function randObstacle() {
  return {x: w + state.obstacle.halfWidth, holePos: rand(0.2,0.7), holeSize: rand(75, 400)};
}

function addObstacle(t) {
  state.obstacles[t] = randObstacle();
}

function loopObstacles(fn) {
  for(var k in state.obstacles) {
    fn(state.obstacles[k]);
  }
}

function noOfObst() {
  var no = 0;
  loopObstacles(function() {no++;});
  return no;
}

function rightMost() {
  maxX = 0;
  loopObstacles(function(obst) {if (obst.x > maxX) maxX = obst.x;});
  return maxX;
}

function drawObstacle(obstacle) {
  c.fillStyle = "#060";
  var top = obstacle.top;
  var bot = obstacle.bottom;

  c.fillRect(top[0], top[1], state.obstacle.halfWidth*2, top[3]); // top
  c.fillRect(bot[0], bot[1], state.obstacle.halfWidth*2, bot[3]); // bottom
}

// Corners return a simple array [left, top, right, bottom]
function getObstacleCorners(obst) {
  var halfWidth = state.obstacle.halfWidth;

  return {
    top: [obst.x - halfWidth, 0, obst.x + halfWidth, obst.holePos*h - obst.holeSize/2],
    bottom: [obst.x - halfWidth, obst.holePos*h + obst.holeSize/2, obst.x + halfWidth, h],
  };
}

function getPlayerCorners() {
  return [state.pos.x -10, state.pos.y -10, state.pos.x +10, state.pos.y +10];
}

function intersect(a, b) {
  return (a[0] <= b[2] &&
          b[0] <= a[2] &&
          a[1] <= b[3] &&
          b[1] <= a[3])
}

function checkIfPlayerIntersect() {
  var intersects = false;
  for(var k in state.obstacles) {
    var obs = getObstacleCorners(state.obstacles[k])
    intersects = intersects || intersect(obs.top, getPlayerCorners()) ||
                               intersect(obs.bottom, getPlayerCorners())
  }
  return intersects;
}

function newGame() {
  c.clearRect(0,0,w,h);
  c.fillStyle = "#FF00EE";
  state.gameover = false;
  state.pos = {
        x: w/2,
        y: h/2,
    },
  state.obstacles = {};
  addObstacle(1);

  state.startTime = null;
}

function drawGameover() {
  c.clearRect(0,0,w,h);
  c.fillStyle = "#333";
  c.fillRect(0, 0, w, h);

  c.font = "48pt Arial";
  c.fillStyle = "#F11";
  c.fillText("Game Over", w/4, h/2);

  c.font = "24pt Times";
  c.fillStyle = "#FF1";
  c.fillText("Press space for new game.", w/4, 2*h/3);
}

function outOfBounds(p) {
  return ((p.x < 0) ||  (p.x > w) || (p.y < 0) || (p.y > h));
}

// ----- play --------------------------

function render(time) {
    if (state.startTime === null) state.startTime = time;
    var deltaTime = time - prevTime;
    prevTime = time;

    update(time, deltaTime);
    draw(time);
    animId = requestAnimationFrame(render);
}

newGame();
var animId = requestAnimationFrame(render);

// ----- keys ---------------------------

var key = {
  _pressed: {},

  LEFT: 37,
  UP: 38,
  RIGHT: 39,
  DOWN: 40,

  isDown: function(keyCode) {
    return this._pressed[keyCode];
  },

  onKeydown: function(event) {
    this._pressed[event.keyCode] = true;
  },

  onKeyup: function(event) {
    delete this._pressed[event.keyCode];
  },

  left: function() {return key.isDown(key.LEFT)},
  up: function() {return key.isDown(key.UP)},
  right: function() {return key.isDown(key.RIGHT)},
  down: function() {return key.isDown(key.DOWN)},
  space: function() {return key.isDown(32)},
};

window.addEventListener('keyup', function(event) { key.onKeyup(event); }, false);
window.addEventListener('keydown', function(event) { key.onKeydown(event); }, false);<commit_msg>Comments and sourcefile clean-up. Divided the main .js file into lgical sections.<commit_after>/* Flappy Summer Internship (Resumé game)
 * Karl Jakob Larsson Spring 2014
 * MIT License
 */

/* ---- TODO ----
 * Physics (Gravity!!!)
 * High score
 * Graphics
 * Sound
 */

// All units in SI (seconds, pixels, meters etc) unless otherwise noted.

// ---- Init????asasgasd???lize ----

var canvas = document.getElementById("a");
canvas.width *= window.devicePixelRatio; // high-dpi adjustment
canvas.height *= window.devicePixelRatio;

// --- Convinience ----

var pixRat = window.devicePixelRatio;
var c = canvas.getContext("2d");

var rand = function(min, max) {
    return Math.random() * (max - min) + min;
};
var w = canvas.width;
var h = canvas.height;

// ---- Setup ----

var state = {
    gameover: false,
    pos: {
        x: w/2,
        y: h/2,
    },
    obstacle: {
        halfWidth: 10*pixRat,
        speed: 3,
        spacing: 1 - 0.22,
    },
    obstacles: {}
};

// var oneObstacle = {x: 270, holePos: 0.7, holeSize: 0.3};
state.obstacles[0] = randObstacle();

var prevTime = 0;

// ---- Main game-functions ----

function draw(t) {
    if (state.gameover) {
      drawGameover();
    } else {
      c.clearRect(0,0,w,h);
      c.fillStyle = "#FF00EE";
      c.fillRect(state.pos.x -10, state.pos.y -10, 20, 20);

      for(var k in state.obstacles) {
        drawObstacle(getObstacleCorners(state.obstacles[k]));
      }

      c.font = "12pt Arial";
      c.fillStyle = "#000";
      c.fillText(t - state.startTime, 10, 10);
    }
}

function update(t, dt) {

  // Check the gamestate
  if ( (state.gameover) && key.space()) newGame();
  else if (checkIfPlayerIntersect()) state.gameover = true;
  else if (outOfBounds(state.pos)) state.gameover = true;

  // Input
  if (key.up()) state.pos.y -= 3;
  if (key.left()) state.pos.x -= 3;
  if (key.down()) state.pos.y += 3;
  if (key.right()) state.pos.x += 3;

  // The Obstacles
  for(var k in state.obstacles) {
    if (state.obstacles[k].x < 0) delete(state.obstacles[k]);
  }
  loopObstacles(function(obst) {obst.x -= state.obstacle.speed;});
  if (rightMost() < (w * state.obstacle.spacing)) addObstacle(t);

}

// ---- Obstacle functions ----
function randObstacle() {
  return {x: w + state.obstacle.halfWidth, holePos: rand(0.2,0.7), holeSize: rand(75, 400)};
}

function addObstacle(t) {
  state.obstacles[t] = randObstacle();
}

function loopObstacles(fn) {
  for(var k in state.obstacles) {
    fn(state.obstacles[k]);
  }
}

function noOfObst() {
  var no = 0;
  loopObstacles(function() {no++;});
  return no;
}

function rightMost() {
  maxX = 0;
  loopObstacles(function(obst) {if (obst.x > maxX) maxX = obst.x;});
  return maxX;
}

function drawObstacle(obstacle) {
  c.fillStyle = "#060";
  var top = obstacle.top;
  var bot = obstacle.bottom;

  c.fillRect(top[0], top[1], state.obstacle.halfWidth*2, top[3]); // top
  c.fillRect(bot[0], bot[1], state.obstacle.halfWidth*2, bot[3]); // bottom
}

// Corners return a simple array [left, top, right, bottom] for the top and bottom rect.
function getObstacleCorners(obst) {
  var halfWidth = state.obstacle.halfWidth;

  return {
    top: [obst.x - halfWidth, 0, obst.x + halfWidth, obst.holePos*h - obst.holeSize/2],
    bottom: [obst.x - halfWidth, obst.holePos*h + obst.holeSize/2, obst.x + halfWidth, h],
  };
}

// ---- Intersection functions ----

function getPlayerCorners() {
  return [state.pos.x -10, state.pos.y -10, state.pos.x +10, state.pos.y +10];
}

function intersect(a, b) {
  return (a[0] <= b[2] &&
          b[0] <= a[2] &&
          a[1] <= b[3] &&
          b[1] <= a[3])
}

function checkIfPlayerIntersect() {
  var intersects = false;
  for(var k in state.obstacles) {
    var obs = getObstacleCorners(state.obstacles[k])
    intersects = intersects || intersect(obs.top, getPlayerCorners()) ||
                               intersect(obs.bottom, getPlayerCorners())
  }
  return intersects;
}

function outOfBounds(p) {
  return ((p.x < 0) ||  (p.x > w) || (p.y < 0) || (p.y > h));
}

// ---- Gamestate functions ----

function newGame() {
  c.clearRect(0,0,w,h);
  c.fillStyle = "#FF00EE";
  state.gameover = false;
  state.pos = {
        x: w/2,
        y: h/2,
    },
  state.obstacles = {};
  addObstacle(1);

  state.startTime = null;
}

// ---- Drawing functions ----

function drawGameover() {
  c.clearRect(0,0,w,h);
  c.fillStyle = "#333";
  c.fillRect(0, 0, w, h);

  c.font = "48pt Arial";
  c.fillStyle = "#F11";
  c.fillText("Game Over", w/4, h/2);

  c.font = "24pt Times";
  c.fillStyle = "#FF1";
  c.fillText("Press space for new game.", w/4, 2*h/3);
}

// ---- Run! ----

function render(time) {
    if (state.startTime === null) state.startTime = time;
    var deltaTime = time - prevTime;
    prevTime = time;

    update(time, deltaTime);
    draw(time);
    animId = requestAnimationFrame(render);
}

newGame();
var animId = requestAnimationFrame(render);

// ---- Input handler ----

var key = {
  _pressed: {},

  LEFT: 37,
  UP: 38,
  RIGHT: 39,
  DOWN: 40,

  isDown: function(keyCode) {
    return this._pressed[keyCode];
  },

  onKeydown: function(event) {
    this._pressed[event.keyCode] = true;
  },

  onKeyup: function(event) {
    delete this._pressed[event.keyCode];
  },

  left: function() {return key.isDown(key.LEFT)},
  up: function() {return key.isDown(key.UP)},
  right: function() {return key.isDown(key.RIGHT)},
  down: function() {return key.isDown(key.DOWN)},
  space: function() {return key.isDown(32)},
};

window.addEventListener('keyup', function(event) { key.onKeyup(event); }, false);
window.addEventListener('keydown', function(event) { key.onKeydown(event); }, false);<|endoftext|>


<commit_before>window.Bootsy = (function(){

  var Bootsy = {caretBookmark: false, unsavedChanges: false, editor: false, editorOptions: {}, eventCallbacks: {'loaded': []}, triggeredEvents: []};

  Bootsy.translations = {
    en: {
      alert_unsaved: 'You have unsaved changes.'
    }
  };

  Bootsy.on = function(eventName, callback){
    Bootsy.eventCallbacks[eventName].push(callback);
  };

  Bootsy.trigger = function(eventName){
    var callbacks = Bootsy.eventCallbacks[eventName];
    for(i in callbacks){
      callbacks[i]();
    }
    Bootsy.triggeredEvents.push(eventName);
  };

  Bootsy.after = function(eventName, callback){
    if(Bootsy.triggeredEvents.indexOf(eventName) != -1){
      callback();
    }else{
      Bootsy.on(eventName, callback);
    }
  };

  Bootsy.progressBar = function(element){
    element.find('div.modal-body').html('

');
  };

  Bootsy.refreshGallery = function(element){
    element.find('a.refresh_btn').show().click();
  };

  Bootsy.openImageGallery = function(editor){
    editor.currentView.element.focus(false);
    Bootsy.caretBookmark = editor.composer.selection.getBookmark();
    $('#bootsy_image_gallery').modal('show');
  };

  Bootsy.insertImage = function(image, editor){
    $('#bootsy_image_gallery').modal('hide');
    editor.currentView.element.focus();
    if (Bootsy.caretBookmark) {
      editor.composer.selection.setBookmark(Bootsy.caretBookmark);
      Bootsy.caretBookmark = null;
    }
    editor.composer.commands.exec("insertImage", image);
  }

  Bootsy.alertUnsavedChanges = function(){
    if(Bootsy.unsavedChanges){
      return Bootsy.translations[Bootsy.locale].alert_unsaved;
    }
  };

  Bootsy.ready = function(){
    if($('textarea.bootsy_text_area').length > 0){
      Bootsy.locale = $('textarea.bootsy_text_area').attr('data-bootsy-locale') || $('html').attr('lang') || 'en';

      var templates = {
        customCommand: function(locale, options) {
          var size = (options && options.size) ? ' btn-'+options.size : '';
          return "
" +
            "" +
          "
";
        },
      };

      Bootsy.editorOptions = {
        parserRules: {
          classes: {
            "wysiwyg-color-silver" : 1,
            "wysiwyg-color-gray" : 1,
            "wysiwyg-color-white" : 1,
            "wysiwyg-color-maroon" : 1,
            "wysiwyg-color-red" : 1,
            "wysiwyg-color-purple" : 1,
            "wysiwyg-color-fuchsia" : 1,
            "wysiwyg-color-green" : 1,
            "wysiwyg-color-lime" : 1,
            "wysiwyg-color-olive" : 1,
            "wysiwyg-color-yellow" : 1,
            "wysiwyg-color-navy" : 1,
            "wysiwyg-color-blue" : 1,
            "wysiwyg-color-teal" : 1,
            "wysiwyg-color-aqua" : 1,
            "wysiwyg-color-orange" : 1,
            "wysiwyg-float-left": 1,
            "wysiwyg-float-right": 1
          },

          tags: {
            "b":  {},
            "i":  {},
            "br": {},
            "ol": {},
            "ul": {},
            "li": {},
            "h1": {},
            "h2": {},
            "h3": {},
            "small": {},
            "p": {},
            "blockquote": {},
            "u": 1,
            "cite": {
              "check_attributes": {
                "title": "alt"
              }
            },
            "img": {
              "check_attributes": {
                "width": "numbers",
                "alt": "alt",
                "src": "src",
                "height": "numbers"
              },
              "add_class": {
                "align": "align_img"
              }
            },
            "a":  {
              set_attributes: {
                target: "_blank",
                rel:    "nofollow"
              },
              check_attributes: {
                href:   "url" // important to avoid XSS
              }
            },
            "span": 1,
            "div": 1,
            // to allow save and edit files with code tag hacks
            "code": 1,
            "pre": 1,

            //skomputer additions
            "em", {},
            "table": {},
            "th": {},
            "tr": {},
            "td": {},
            "strong" : {}
          }
        },
        color: true,
        locale: Bootsy.locale,
        customTemplates: templates
      };

      Bootsy.editorOptions.stylesheets = ["/assets/bootsy/bootsy.css"];

      if($('textarea.bootsy_text_area').attr('data-bootsy-image') == 'false'){
        Bootsy.editorOptions.image = false;
      }else{

        if($('textarea.bootsy_text_area').attr('data-bootsy-uploader') != 'false'){
          Bootsy.editorOptions.image = false;
          Bootsy.editorOptions.customCommand = true;
          Bootsy.editorOptions.customCommandCallback = Bootsy.openImageGallery;

          element = $('#bootsy_image_gallery');

          element.parents('form').after(element);

          element.on('click', 'a.refresh_btn', function(e){
            $(this).hide();
            Bootsy.progressBar(element);
          });

          element.find('a.destroy_btn').click(function(e){
            Bootsy.progressBar(element);
          });

          element.modal({show: false});
          element.on('shown', function(){
            Bootsy.refreshGallery(element);
          });

          element.on('hide', function() {
            Bootsy.editor.currentView.element.focus();
          });

          element.on('click.dismiss.modal', '[data-dismiss="modal"]', function(e) {
            e.stopPropagation();
          });

          element.on('click', 'ul.dropdown-menu a.insert', function(e){
            var imagePrefix = "/"+$(this).attr('data-image-size')+"_";
            if($(this).attr('data-image-size') == 'original'){
              imagePrefix = '/';
            }
            var img = $(this).parents('li.dropdown').find('img');
            var obj = {
              src: img.attr('src').replace("/thumb_", imagePrefix),
              alt: img.attr('alt').replace("Thumb_", "")
            };

            obj.align = $(this).attr('data-position');

            Bootsy.insertImage(obj, Bootsy.editor);
          });
        }
      }

      if($('textarea.bootsy_text_area').attr('data-bootsy-font-styles') == 'false') Bootsy.editorOptions['font-styles'] = false;
      if($('textarea.bootsy_text_area').attr('data-bootsy-emphasis') == 'false') Bootsy.editorOptions.emphasis = false;
      if($('textarea.bootsy_text_area').attr('data-bootsy-lists') == 'false') Bootsy.editorOptions.lists = false;
      if($('textarea.bootsy_text_area').attr('data-bootsy-html') == 'true') Bootsy.editorOptions.html = true;
      if($('textarea.bootsy_text_area').attr('data-bootsy-link') == 'false') Bootsy.editorOptions.link = false;
      if($('textarea.bootsy_text_area').attr('data-bootsy-color') == 'false') Bootsy.editorOptions.color = false;

      Bootsy.editor = $('textarea.bootsy_text_area').wysihtml5(Bootsy.editorOptions).data("wysihtml5").editor;

      if($('textarea.bootsy_text_area').attr('data-bootsy-alert-unsaved') != 'false'){
        window.onbeforeunload = Bootsy.alertUnsavedChanges;
      }

      Bootsy.editor.on("change", function(){
        Bootsy.unsavedChanges = true;
      });

      $('textarea.bootsy_text_area').closest('form').submit(function(e){
        Bootsy.unsavedChanges = false;
        return true;
      });

      Bootsy.trigger('loaded');
    }
  };

  return Bootsy;
}).call(this);

$(Bootsy.ready);<commit_msg>fixed typo in parser rules<commit_after>window.Bootsy = (function(){

  var Bootsy = {caretBookmark: false, unsavedChanges: false, editor: false, editorOptions: {}, eventCallbacks: {'loaded': []}, triggeredEvents: []};

  Bootsy.translations = {
    en: {
      alert_unsaved: 'You have unsaved changes.'
    }
  };

  Bootsy.on = function(eventName, callback){
    Bootsy.eventCallbacks[eventName].push(callback);
  };

  Bootsy.trigger = function(eventName){
    var callbacks = Bootsy.eventCallbacks[eventName];
    for(i in callbacks){
      callbacks[i]();
    }
    Bootsy.triggeredEvents.push(eventName);
  };

  Bootsy.after = function(eventName, callback){
    if(Bootsy.triggeredEvents.indexOf(eventName) != -1){
      callback();
    }else{
      Bootsy.on(eventName, callback);
    }
  };

  Bootsy.progressBar = function(element){
    element.find('div.modal-body').html('

');
  };

  Bootsy.refreshGallery = function(element){
    element.find('a.refresh_btn').show().click();
  };

  Bootsy.openImageGallery = function(editor){
    editor.currentView.element.focus(false);
    Bootsy.caretBookmark = editor.composer.selection.getBookmark();
    $('#bootsy_image_gallery').modal('show');
  };

  Bootsy.insertImage = function(image, editor){
    $('#bootsy_image_gallery').modal('hide');
    editor.currentView.element.focus();
    if (Bootsy.caretBookmark) {
      editor.composer.selection.setBookmark(Bootsy.caretBookmark);
      Bootsy.caretBookmark = null;
    }
    editor.composer.commands.exec("insertImage", image);
  }

  Bootsy.alertUnsavedChanges = function(){
    if(Bootsy.unsavedChanges){
      return Bootsy.translations[Bootsy.locale].alert_unsaved;
    }
  };

  Bootsy.ready = function(){
    if($('textarea.bootsy_text_area').length > 0){
      Bootsy.locale = $('textarea.bootsy_text_area').attr('data-bootsy-locale') || $('html').attr('lang') || 'en';

      var templates = {
        customCommand: function(locale, options) {
          var size = (options && options.size) ? ' btn-'+options.size : '';
          return "
" +
            "" +
          "
";
        },
      };

      Bootsy.editorOptions = {
        parserRules: {
          classes: {
            "wysiwyg-color-silver" : 1,
            "wysiwyg-color-gray" : 1,
            "wysiwyg-color-white" : 1,
            "wysiwyg-color-maroon" : 1,
            "wysiwyg-color-red" : 1,
            "wysiwyg-color-purple" : 1,
            "wysiwyg-color-fuchsia" : 1,
            "wysiwyg-color-green" : 1,
            "wysiwyg-color-lime" : 1,
            "wysiwyg-color-olive" : 1,
            "wysiwyg-color-yellow" : 1,
            "wysiwyg-color-navy" : 1,
            "wysiwyg-color-blue" : 1,
            "wysiwyg-color-teal" : 1,
            "wysiwyg-color-aqua" : 1,
            "wysiwyg-color-orange" : 1,
            "wysiwyg-float-left": 1,
            "wysiwyg-float-right": 1
          },

          tags: {
            "b":  {},
            "i":  {},
            "br": {},
            "ol": {},
            "ul": {},
            "li": {},
            "h1": {},
            "h2": {},
            "h3": {},
            "small": {},
            "p": {},
            "blockquote": {},
            "u": 1,
            "cite": {
              "check_attributes": {
                "title": "alt"
              }
            },
            "img": {
              "check_attributes": {
                "width": "numbers",
                "alt": "alt",
                "src": "src",
                "height": "numbers"
              },
              "add_class": {
                "align": "align_img"
              }
            },
            "a":  {
              set_attributes: {
                target: "_blank",
                rel:    "nofollow"
              },
              check_attributes: {
                href:   "url" // important to avoid XSS
              }
            },
            "span": 1,
            "div": 1,
            // to allow save and edit files with code tag hacks
            "code": 1,
            "pre": 1,

            //skomputer additions
            "em": {},
            "table": {},
            "th": {},
            "tr": {},
            "td": {},
            "strong" : {}
          }
        },
        color: true,
        locale: Bootsy.locale,
        customTemplates: templates
      };

      Bootsy.editorOptions.stylesheets = ["/assets/bootsy/bootsy.css"];

      if($('textarea.bootsy_text_area').attr('data-bootsy-image') == 'false'){
        Bootsy.editorOptions.image = false;
      }else{

        if($('textarea.bootsy_text_area').attr('data-bootsy-uploader') != 'false'){
          Bootsy.editorOptions.image = false;
          Bootsy.editorOptions.customCommand = true;
          Bootsy.editorOptions.customCommandCallback = Bootsy.openImageGallery;

          element = $('#bootsy_image_gallery');

          element.parents('form').after(element);

          element.on('click', 'a.refresh_btn', function(e){
            $(this).hide();
            Bootsy.progressBar(element);
          });

          element.find('a.destroy_btn').click(function(e){
            Bootsy.progressBar(element);
          });

          element.modal({show: false});
          element.on('shown', function(){
            Bootsy.refreshGallery(element);
          });

          element.on('hide', function() {
            Bootsy.editor.currentView.element.focus();
          });

          element.on('click.dismiss.modal', '[data-dismiss="modal"]', function(e) {
            e.stopPropagation();
          });

          element.on('click', 'ul.dropdown-menu a.insert', function(e){
            var imagePrefix = "/"+$(this).attr('data-image-size')+"_";
            if($(this).attr('data-image-size') == 'original'){
              imagePrefix = '/';
            }
            var img = $(this).parents('li.dropdown').find('img');
            var obj = {
              src: img.attr('src').replace("/thumb_", imagePrefix),
              alt: img.attr('alt').replace("Thumb_", "")
            };

            obj.align = $(this).attr('data-position');

            Bootsy.insertImage(obj, Bootsy.editor);
          });
        }
      }

      if($('textarea.bootsy_text_area').attr('data-bootsy-font-styles') == 'false') Bootsy.editorOptions['font-styles'] = false;
      if($('textarea.bootsy_text_area').attr('data-bootsy-emphasis') == 'false') Bootsy.editorOptions.emphasis = false;
      if($('textarea.bootsy_text_area').attr('data-bootsy-lists') == 'false') Bootsy.editorOptions.lists = false;
      if($('textarea.bootsy_text_area').attr('data-bootsy-html') == 'true') Bootsy.editorOptions.html = true;
      if($('textarea.bootsy_text_area').attr('data-bootsy-link') == 'false') Bootsy.editorOptions.link = false;
      if($('textarea.bootsy_text_area').attr('data-bootsy-color') == 'false') Bootsy.editorOptions.color = false;

      Bootsy.editor = $('textarea.bootsy_text_area').wysihtml5(Bootsy.editorOptions).data("wysihtml5").editor;

      if($('textarea.bootsy_text_area').attr('data-bootsy-alert-unsaved') != 'false'){
        window.onbeforeunload = Bootsy.alertUnsavedChanges;
      }

      Bootsy.editor.on("change", function(){
        Bootsy.unsavedChanges = true;
      });

      $('textarea.bootsy_text_area').closest('form').submit(function(e){
        Bootsy.unsavedChanges = false;
        return true;
      });

      Bootsy.trigger('loaded');
    }
  };

  return Bootsy;
}).call(this);

$(Bootsy.ready);<|endoftext|>


<commit_before>/**
 * Provides client-side equivalent to `Controller::add_notification()`.
 * Usage:
 *
 *     $.add_notification('My notification.');
 */
jQuery.add_notification = function (msg) {
	var notices = $.cookie ('elefant_notification');
	if (notices !== null) {
		msg = notices + '|' + msg;
	}
	$.cookie ('elefant_notification', msg, {path: '/'});
};

/**
 * Adds a confirmation to a link and turns its `data-*` properties
 * into a `POST` request. Usage:
 *
 *     Delete
 */
jQuery.confirm_and_post = function (el, msg) {
	if (window.event) {
		window.event.preventDefault ();
	}

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

	var $el = $(el),
		params = $el.data ()
		url = $el.attr ('href'),
		$form = $('<form>')
			.attr ('method', 'post')
			.attr ('action', url);

	$.each (params, function (name, value) {
		$('<input type="hidden">')
			.attr ('name', name)
			.attr ('value', value)
			.appendTo ($form);
	});

	$form.appendTo ('body');
	$form.submit ();
	return false;
};

$(function () {
	var sliding_up = false;
	$('body').append ('

');
	$.get ('/admin/head/links', function (res) {
		$('#admin-logo').attr ('src', res.logo).attr ('alt', res.name);
		$('#admin-links').append (res.links);
		$('#admin-tools').hover (function () {
			if (! sliding_up) {
				$('#admin-tools-list').slideDown ('fast').show ();
			}
			$(this).parent ().hover (
				function () {},
				function () {
					sliding_up = true;
					$('#admin-tools-list').slideUp ('slow', function () {
						sliding_up = false;
					});
				}
			);
		})
	});
	$('.admin-options a').hover (
		function () {
			this.tip = this.title;
			$(this).append (
				'

' +
				'
' + this.tip + '

'
			);
			this.title = '';
			$('.admin-tooltip').fadeIn (100);
		},
		function () {
			$('.admin-tooltip').fadeOut (100);
			$('.admin-tooltip').remove ();
			this.title = this.tip;
		}
	);

	// check for and display elefant updates if available
	if (! $.cookie ('elefant_update_checked')) {
		var major_minor = $.elefant_version.replace (/\.[0-9]+$/, '');
		$.getJSON ('http://www.elefantcms.com/updates/check.php?v=' + major_minor + '&callback=?', function (res) {
			if (res.latest > $.elefant_version) {
				$('#admin-bar>a').append ('Update Available: ' + res.latest + '');
			}
		});
		$.cookie ('elefant_update_checked', 1, { expires: 1, path: '/' });
	}

	var jgrowl_interval = function () {
		var notice = $.cookie ('elefant_notification'),
			msglist = [],
			i = 0;

		$.cookie ('elefant_notification', null, {path: '/'});

		if (notice !== null) {
			msglist = notice.split ('|');
			for (i = 0; i < msglist.length; i++) {
				if (msglist[i].length > 0) {
					$.jGrowl (msglist[i].replace (/\+/g, ' '));
				}
			}
		}
		// clear notices
		setTimeout (jgrowl_interval, 1000);
	}

	jgrowl_interval ();
});
<commit_msg>Added $.expanded_section() for building expandable forms<commit_after>/**
 * Provides client-side equivalent to `Controller::add_notification()`.
 * Usage:
 *
 *     $.add_notification('My notification.');
 */
jQuery.add_notification = function (msg) {
	var notices = $.cookie ('elefant_notification');
	if (notices !== null) {
		msg = notices + '|' + msg;
	}
	$.cookie ('elefant_notification', msg, {path: '/'});
};

/**
 * Adds a confirmation to a link and turns its `data-*` properties
 * into a `POST` request. Usage:
 *
 *     Delete
 */
jQuery.confirm_and_post = function (el, msg) {
	if (window.event) {
		window.event.preventDefault ();
	}

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

	var $el = $(el),
		params = $el.data ()
		url = $el.attr ('href'),
		$form = $('<form>')
			.attr ('method', 'post')
			.attr ('action', url);

	$.each (params, function (name, value) {
		$('<input type="hidden">')
			.attr ('name', name)
			.attr ('value', value)
			.appendTo ($form);
	});

	$form.appendTo ('body');
	$form.submit ();
	return false;
};

/**
 * Turns a section of a form into an expandable/collapsible section.
 * Usage:
 *
 *
{"Extra options"}

 *

 *
 *

 *
 *
 */
jQuery.expanded_section = function (options) {
	var defaults = {
		header: '#expanded-header',
		section: '#expanded-section',
		arrowClass: 'arrow',
		arrowOffClass: 'arrow-off',
		visible: false
	};

	var options = $.extend (defaults, options),
		header = $(options.header),
		section = $(options.section);

	if (options.visible) {
		header.prepend ('');
		section.css ('display', 'block');
	} else {
		header.prepend ('');
		section.css ('display', 'none');
	}

	header
		.hover (
			function () {
				$(this).css ('cursor', 'pointer');
			},
			function () {
				$(this).css ('cursor', 'default');
			}
		)
		.click (
			function (evt) {
				if (section.css ('display') === 'none') {
					section.slideDown ('fast', function () {
						window.scrollTo (0, 1000);
					});
					header.children ('span.' + options.arrowClass).removeClass (options.arrowOffClass);
				} else {
					section.slideUp ('fast', function () {
						section.css ('display', 'none');
					});
					header.children ('span.' + options.arrowClass).addClass (options.arrowOffClass);
				}
			}
		);
};

$(function () {
	var sliding_up = false;
	$('body').append ('

');
	$.get ('/admin/head/links', function (res) {
		$('#admin-logo').attr ('src', res.logo).attr ('alt', res.name);
		$('#admin-links').append (res.links);
		$('#admin-tools').hover (function () {
			if (! sliding_up) {
				$('#admin-tools-list').slideDown ('fast').show ();
			}
			$(this).parent ().hover (
				function () {},
				function () {
					sliding_up = true;
					$('#admin-tools-list').slideUp ('slow', function () {
						sliding_up = false;
					});
				}
			);
		})
	});
	$('.admin-options a').hover (
		function () {
			this.tip = this.title;
			$(this).append (
				'

' +
				'
' + this.tip + '

'
			);
			this.title = '';
			$('.admin-tooltip').fadeIn (100);
		},
		function () {
			$('.admin-tooltip').fadeOut (100);
			$('.admin-tooltip').remove ();
			this.title = this.tip;
		}
	);

	// check for and display elefant updates if available
	if (! $.cookie ('elefant_update_checked')) {
		var major_minor = $.elefant_version.replace (/\.[0-9]+$/, '');
		$.getJSON ('http://www.elefantcms.com/updates/check.php?v=' + major_minor + '&callback=?', function (res) {
			if (res.latest > $.elefant_version) {
				$('#admin-bar>a').append ('Update Available: ' + res.latest + '');
			}
		});
		$.cookie ('elefant_update_checked', 1, { expires: 1, path: '/' });
	}

	var jgrowl_interval = function () {
		var notice = $.cookie ('elefant_notification'),
			msglist = [],
			i = 0;

		$.cookie ('elefant_notification', null, {path: '/'});

		if (notice !== null) {
			msglist = notice.split ('|');
			for (i = 0; i < msglist.length; i++) {
				if (msglist[i].length > 0) {
					$.jGrowl (msglist[i].replace (/\+/g, ' '));
				}
			}
		}
		// clear notices
		setTimeout (jgrowl_interval, 1000);
	}

	jgrowl_interval ();
});
<|endoftext|>


<commit_before>var Event = Event || {};

Event.Header = function(params) {
    this.name = '';
    this.range_from = '';
    this.range_to = '';
    this.status = '';

    this.$title = $('#title-competition-name');
    this.$range = $('#title-competition-range');
    this.$table_edit_controls = $('#edit-table-commands');
    this.$event_edit_commands = $('#edit-event-commands')

    ///////////////////////////////////////////
    // Templates
    this.fa_fw = _.template([
        '',
            '',
        ''
    ].join('\n'));

    this.edit_event = _.template([
        '',
            '',
            I18n.t('general.edit'),
        ''
    ].join('\n'));

    this.edit_commands = _.template([
         '
',
            '<button class="btn btn-default button-add-class">',
                '',
                'Class',
            '</button>',
            '<button class="btn btn-default button-add-competitor">',
                '',
                'Competitor',
            '</button>',
            '
',
                '<button class="btn btn-default" data-toggle="dropdown">',
                    '',
                    'Round',
                    '',
                '</button>',
                '
',
                    '
<%= I18n.t("disciplines.distance") %>
',
                    '
<%= I18n.t("disciplines.time") %>
',
                    '
<%= I18n.t("disciplines.speed") %>
',
                '
',
            '
',
         '
'
    ].join('\n'));

    ///////////////////////////////////////////////////////////////////////////
    // Initialization
    //
    $.extend(this, params);
    this.init();
}

Event.Header.prototype = {
    init: function() {
        var can_manage = window.Competition.can_manage;
        if (can_manage) {
            this.render_edit_controls();
            this.bind_events();
        }
    },

    render_edit_controls: function () {
        this.$event_edit_commands.append(this.edit_event());

        this.$table_edit_controls.append(this.edit_commands());
        this.$table_edit_controls.addClass('top-buffer');
    },

    render: function() {
        this.$title.text(this.name);
        this.$range.text(
            I18n.t('events.show.comp_window')
            + ' ' Competition.range_from
            + ' - ' + Competition.range_to
            + ' ' + I18n.t('units.m')
        );
    },

    bind_events: function() {
        $('.button-add-class')
            .on('click', this.on_button_add_class_click.bind(this));
        $('.button-add-competitor')
            .on('click', this.on_button_add_competitor_click.bind(this));
        $('.add-distance-round')
            .on('click', this.on_button_add_distance_round_click.bind(this));
        $('.add-speed-round')
            .on('click', this.on_button_add_speed_round_click.bind(this));
        $('.add-time-round')
            .on('click', this.on_button_add_time_round_click.bind(this));
        $('.edit-event')
            .on('click', this.on_link_edit_event_click.bind(this));
    },

    on_button_add_class_click: function(e) {
        e.preventDefault();
        var new_section = new Event.Section;
        new_section.open_form();
    },

    on_button_add_competitor_click: function(e) {
        e.preventDefault();
        var new_competitor = new Event.Competitor;
        new_competitor.open_form();
    },

    on_button_add_distance_round_click: function(e) {
        e.preventDefault();
        new Event.Round({discipline: 'distance'}).save();
    },

    on_button_add_speed_round_click: function(e) {
        e.preventDefault()
        new Event.Round({discipline: 'speed'}).save();
    },

    on_button_add_time_round_click: function(e) {
        e.preventDefault()
        new Event.Round({discipline: 'time'}).save();
    },

    on_link_edit_event_click: function(e) {
        e.preventDefault()
        window.Competition.open_form(e);
    },
}
<commit_msg>hotfix<commit_after>var Event = Event || {};

Event.Header = function(params) {
    this.name = '';
    this.range_from = '';
    this.range_to = '';
    this.status = '';

    this.$title = $('#title-competition-name');
    this.$range = $('#title-competition-range');
    this.$table_edit_controls = $('#edit-table-commands');
    this.$event_edit_commands = $('#edit-event-commands')

    ///////////////////////////////////////////
    // Templates
    this.fa_fw = _.template([
        '',
            '',
        ''
    ].join('\n'));

    this.edit_event = _.template([
        '',
            '',
            I18n.t('general.edit'),
        ''
    ].join('\n'));

    this.edit_commands = _.template([
         '
',
            '<button class="btn btn-default button-add-class">',
                '',
                'Class',
            '</button>',
            '<button class="btn btn-default button-add-competitor">',
                '',
                'Competitor',
            '</button>',
            '
',
                '<button class="btn btn-default" data-toggle="dropdown">',
                    '',
                    'Round',
                    '',
                '</button>',
                '
',
                    '
<%= I18n.t("disciplines.distance") %>
',
                    '
<%= I18n.t("disciplines.time") %>
',
                    '
<%= I18n.t("disciplines.speed") %>
',
                '
',
            '
',
         '
'
    ].join('\n'));

    ///////////////////////////////////////////////////////////////////////////
    // Initialization
    //
    $.extend(this, params);
    this.init();
}

Event.Header.prototype = {
    init: function() {
        var can_manage = window.Competition.can_manage;
        if (can_manage) {
            this.render_edit_controls();
            this.bind_events();
        }
    },

    render_edit_controls: function () {
        this.$event_edit_commands.append(this.edit_event());

        this.$table_edit_controls.append(this.edit_commands());
        this.$table_edit_controls.addClass('top-buffer');
    },

    render: function() {
        this.$title.text(this.name);
        this.$range.text(
            I18n.t('events.show.comp_window')
            + ' ' + Competition.range_from
            + ' - ' + Competition.range_to
            + ' ' + I18n.t('units.m')
        );
    },

    bind_events: function() {
        $('.button-add-class')
            .on('click', this.on_button_add_class_click.bind(this));
        $('.button-add-competitor')
            .on('click', this.on_button_add_competitor_click.bind(this));
        $('.add-distance-round')
            .on('click', this.on_button_add_distance_round_click.bind(this));
        $('.add-speed-round')
            .on('click', this.on_button_add_speed_round_click.bind(this));
        $('.add-time-round')
            .on('click', this.on_button_add_time_round_click.bind(this));
        $('.edit-event')
            .on('click', this.on_link_edit_event_click.bind(this));
    },

    on_button_add_class_click: function(e) {
        e.preventDefault();
        var new_section = new Event.Section;
        new_section.open_form();
    },

    on_button_add_competitor_click: function(e) {
        e.preventDefault();
        var new_competitor = new Event.Competitor;
        new_competitor.open_form();
    },

    on_button_add_distance_round_click: function(e) {
        e.preventDefault();
        new Event.Round({discipline: 'distance'}).save();
    },

    on_button_add_speed_round_click: function(e) {
        e.preventDefault()
        new Event.Round({discipline: 'speed'}).save();
    },

    on_button_add_time_round_click: function(e) {
        e.preventDefault()
        new Event.Round({discipline: 'time'}).save();
    },

    on_link_edit_event_click: function(e) {
        e.preventDefault()
        window.Competition.open_form(e);
    },
}
<|endoftext|>


<commit_before>/***
@title:
Colour Picker

@version:
2.0

@author:
Andreas Lagerkvist

@date:
2008-09-16

@url:
http://andreaslagerkvist.com/jquery/colour-picker/

@license:
http://creativecommons.org/licenses/by/3.0/

@copyright:
2008 Andreas Lagerkvist (andreaslagerkvist.com)

@requires:
jquery, jquery.colourPicker.css

@does:
Turns a drop-down (select-element) full of colours into a colour-picker-dialogue.

@howto:
jQuery('select[name="colour"]').colourPicker({ico: 'my-icon.gif', title: 'Select a colour from the list'}); Would replace the select with 'my-icon.gif' which, when clicked, would open a dialogue with the title 'Select a colour from the list'.

You can use this PHP-function to generate a list of "web-safe" colours:

[code]
function gwsc() {
	$cs = array('00', '33', '66', '99', 'CC', 'FF');

	for($i=0; $i<6; $i++) {
		for($j=0; $j<6; $j++) {
			for($k=0; $k<6; $k++) {
				$c = $cs[$i] .$cs[$j] .$cs[$k];
				echo "<option value=\"$c\">#$c</option>\n";
			}
		}
	}
}
[/code]

Use it like this: <select name="colour"><?php gwsc(); ?></select>.

@exampleHTML:

		Pick a colour

		<select name="colour_1">
			<option value="ffffff">White</option>
			<option value="ff0000">Red</option>
			<option value="00ff00">Green</option>
			<option value="0000ff">Blue</option>
			<option value="000000">Black</option>
		</select>

		And one more

		<select name="colour_2">
			<option value="ffffff">White</option>
			<option value="ff0000">Red</option>
			<option value="00ff00">Green</option>
			<option value="0000ff">Blue</option>
			<option value="000000">Black</option>
		</select>

@exampleJS:
jQuery('#jquery-colour-picker-example select').colourPicker({ico: '/aFramework/Styles/__common/gfx/jquery.colourPicker.gif'});
***/
jQuery.fn.colourPicker = function(conf) {
	// Config for plug
	var config = jQuery.extend({
		ID:			'colour-picker',	// ID of colour-picker container
		ico:		'ico.gif',			// SRC to colour-picker icon
		title:		'Pick a colour',	// Default dialogue title
		inputBG:	true,				// Whether to change the input's background to the selected colour's
		speed:		500					// Speed of dialogue-animation
	}, conf);

	// Inverts a hex-colour
	var hexInvert = function(hex) {
		return 'ffffff'; // Todo...

		var r = hex.substr(0, 2);
		var g = hex.substr(2, 2);
		var b = hex.substr(4, 2);
	};

	// Add the colour-picker dialogue if not added
	var colourPicker = jQuery('#' +config.ID);

	if(!colourPicker.length) {
		colourPicker = jQuery('

').appendTo(document.body).hide();

		// Remove the colour-picker if you click outside it (on body)
		jQuery(document.body).click(function(event) {
			if(!(jQuery(event.target).is('#' +config.ID) || jQuery(event.target).parents('#' +config.ID).length)) {
				colourPicker.hide(config.speed);
			}
		});
	}

	// For every select passed to the plug-in
	return this.each(function() {
		// Insert icon and input
		var select	= jQuery(this);
		var icon	= jQuery('').insertAfter(select);
		var input	= jQuery('<input type="text" name="' +select.attr('name') +'" size="6" />').insertAfter(select);
		var iconPos = icon.offset();
		var loc		= '';

		// Build a list of colours based on the colours in the select
		jQuery('option', select).each(function() {
			var option	= jQuery(this);
			var hex		= option.val();
			var title	= option.text();

			loc += '
' +title +'
';
		});

		// Remove select
		select.remove();

		// When you click the icon
		icon.click(function() {
			// Show the colour-picker next to the icon and fill it with the colours in the select that used to be there
			colourPicker.html('
' +config.title +'

' +loc +'
').css({position: 'absolute', left: iconPos.left +'px', top: iconPos.top +'px'}).show(config.speed);

			// When you click a colour in the colour-picker
			jQuery('a', colourPicker).click(function() {
				// The hex is stored in the link's rel-attribute
				var hex = jQuery(this).attr('rel');

				input.val(hex);

				// If user wants to, change the input's BG to reflect the newly selected colour
				if(config.inputBG) {
					input.css({background: '#' +hex, color: '#' +hexInvert(hex)});
				}

				// Hide the colour-picker and return false
				colourPicker.hide(config.speed);

				return false;
			});

			return false;
		});
	});
};<commit_msg>Improve documentation<commit_after>/***
@title:
Colour Picker

@version:
2.0

@author:
Andreas Lagerkvist

@date:
2008-09-16

@url:
http://andreaslagerkvist.com/jquery/colour-picker/

@license:
http://creativecommons.org/licenses/by/3.0/

@copyright:
2008 Andreas Lagerkvist (andreaslagerkvist.com)

@requires:
jquery, jquery.colourPicker.css, jquery.colourPicker.gif

@does:
Turns a drop-down (select-element) full of colours into a colour-picker-widget.

@howto:
jQuery('select[name="colour"]').colourPicker({ico: 'my-icon.gif', title: 'Select a colour from the list'}); Would replace the select with 'my-icon.gif' which, when clicked, would open a dialogue with the title 'Select a colour from the list'.

You can close the colour-picker without selecting a colour by clicking anywhere outside the colour-picker box.

Here's a handy PHP-function to generate a list of "web-safe" colours:

[code]
function gwsc() {
	$cs = array('00', '33', '66', '99', 'CC', 'FF');

	for($i=0; $i<6; $i++) {
		for($j=0; $j<6; $j++) {
			for($k=0; $k<6; $k++) {
				$c = $cs[$i] .$cs[$j] .$cs[$k];
				echo "<option value=\"$c\">#$c</option>\n";
			}
		}
	}
}
[/code]

Use it like this: <select name="colour"><?php gwsc(); ?></select>.

@exampleHTML:

		Pick a colour

		<select name="colour_1">
			<option value="ffffff">White</option>
			<option value="ff0000">Red</option>
			<option value="00ff00">Green</option>
			<option value="0000ff">Blue</option>
			<option value="000000">Black</option>
		</select>

		And one more

		<select name="colour_2">
			<option value="ffffff">White</option>
			<option value="ff0000">Red</option>
			<option value="00ff00">Green</option>
			<option value="0000ff">Blue</option>
			<option value="000000">Black</option>
		</select>

@exampleJS:
jQuery('#jquery-colour-picker-example select').colourPicker({ico: '/aFramework/Styles/__common/gfx/jquery.colourPicker.gif'});
***/
jQuery.fn.colourPicker = function(conf) {
	// Config for plug
	var config = jQuery.extend({
		ID:			'colour-picker',	// ID of colour-picker container
		ico:		'ico.gif',			// SRC to colour-picker icon
		title:		'Pick a colour',	// Default dialogue title
		inputBG:	true,				// Whether to change the input's background to the selected colour's
		speed:		500					// Speed of dialogue-animation
	}, conf);

	// Inverts a hex-colour
	var hexInvert = function(hex) {
		return 'ffffff'; // Todo...

		var r = hex.substr(0, 2);
		var g = hex.substr(2, 2);
		var b = hex.substr(4, 2);
	};

	// Add the colour-picker dialogue if not added
	var colourPicker = jQuery('#' +config.ID);

	if(!colourPicker.length) {
		colourPicker = jQuery('

').appendTo(document.body).hide();

		// Remove the colour-picker if you click outside it (on body)
		jQuery(document.body).click(function(event) {
			if(!(jQuery(event.target).is('#' +config.ID) || jQuery(event.target).parents('#' +config.ID).length)) {
				colourPicker.hide(config.speed);
			}
		});
	}

	// For every select passed to the plug-in
	return this.each(function() {
		// Insert icon and input
		var select	= jQuery(this);
		var icon	= jQuery('').insertAfter(select);
		var input	= jQuery('<input type="text" name="' +select.attr('name') +'" size="6" />').insertAfter(select);
		var loc		= '';

		// Build a list of colours based on the colours in the select
		jQuery('option', select).each(function() {
			var option	= jQuery(this);
			var hex		= option.val();
			var title	= option.text();

			loc += '
' +title +'
';
		});

		// Remove select
		select.remove();

		var iconPos = icon.offset();

		// When you click the icon
		icon.click(function() {
			// Show the colour-picker next to the icon and fill it with the colours in the select that used to be there
			colourPicker.html('
' +config.title +'

' +loc +'
').css({position: 'absolute', left: iconPos.left +'px', top: iconPos.top +'px'}).show(config.speed);

			// When you click a colour in the colour-picker
			jQuery('a', colourPicker).click(function() {
				// The hex is stored in the link's rel-attribute
				var hex = jQuery(this).attr('rel');

				input.val(hex);

				// If user wants to, change the input's BG to reflect the newly selected colour
				if(config.inputBG) {
					input.css({background: '#' +hex, color: '#' +hexInvert(hex)});
				}

				// Hide the colour-picker and return false
				colourPicker.hide(config.speed);

				return false;
			});

			return false;
		});
	});
};<|endoftext|>


<commit_before>Travis.Helpers.Urls = {
  urlCurrent: function() {
    return '#!/' + this.getSlug();
  }.property('slug'),
  urlBuilds: function() {
    return '#!/' + this.getSlug() + '/builds';
  }.property('slug'),
  urlBuild: function() {
    return '#!/' + this.getSlug() + '/builds/' + this.get('id');
  }.property('slug'),
  urlLastBuild: function() {
    return '#!/' + this.getSlug() + '/builds/' + this.get('lastBuildId');
  }.property('slug'),
  urlGithubRepository: function() {
    return 'http://github.com/' + this.getSlug();
  }.property('commit'),
  urlGithubCommit: function() {
    return 'http://github.com/' + this.getSlug() + '/commit/' + this.get('commit');
  }.property('commit'),
  urlGithubWatchers: function() {
    return 'http://github.com/' + this.getSlug() + '/watchers';
  }.property('commit'),
  urlGithubNetwork: function() {
    return 'http://github.com/' + this.getSlug() + '/network';
  }.property('commit'),
  urlAuthor: function() {
    return 'mailto:' + this.get('author_email');
  }.property('author_email'),
  urlCommitter: function() {
    return 'mailto:' + this.get('committer_email');
  }.property('committer_email'),
  getSlug: function() {
    return this.getPath('repository.slug') || this.get('slug');
  }
}
<commit_msg>urlLastBuild property must depend on the lastBuildId<commit_after>Travis.Helpers.Urls = {
  urlCurrent: function() {
    return '#!/' + this.getSlug();
  }.property('slug'),

  urlBuilds: function() {
    return '#!/' + this.getSlug() + '/builds';
  }.property('slug'),

  urlBuild: function() {
    return '#!/' + this.getSlug() + '/builds/' + this.get('id');
  }.property('slug'),

  urlLastBuild: function() {
    return '#!/' + this.getSlug() + '/builds/' + this.get('lastBuildId');
  }.property('slug', 'lastBuildId'),

  urlGithubRepository: function() {
    return 'http://github.com/' + this.getSlug();
  }.property('commit'),

  urlGithubCommit: function() {
    return 'http://github.com/' + this.getSlug() + '/commit/' + this.get('commit');
  }.property('commit'),

  urlGithubWatchers: function() {
    return 'http://github.com/' + this.getSlug() + '/watchers';
  }.property('commit'),

  urlGithubNetwork: function() {
    return 'http://github.com/' + this.getSlug() + '/network';
  }.property('commit'),

  urlAuthor: function() {
    return 'mailto:' + this.get('author_email');
  }.property('author_email'),

  urlCommitter: function() {
    return 'mailto:' + this.get('committer_email');
  }.property('committer_email'),

  getSlug: function() {
    return this.getPath('repository.slug') || this.get('slug');
  }
}
<|endoftext|>


<commit_before>(function() {
  'use strict';

  angular
    .module('sslv2App', [
      'ui.router',
      'ui.bootstrap',
      'ui.mask',
      'ngCookies',
      'ui.gravatar',
      'angular-confirm',
      'ngIdle',
      'ngSanitize',
      'ngTagsInput',
      'ui.multiselect',
      'fsm',
      'ui.codemirror',
      'angularMoment',
      'pascalprecht.translate',
      'tmh.dynamicLocale',
      'easypiechart',

    ])
    .factory('headerInjector', [function() {
      var headerInjector = {
        request: function(config) {
          config.headers['X-Cbo-Client-Url'] = 'http://demo.ssl.s360.is';
          return config;
        }
      };
      return headerInjector;
    }])
    .config(configFunction)
    .run(runFunction);

  configFunction.$inject = ['$httpProvider','$urlRouterProvider','gravatarServiceProvider','KeepaliveProvider','IdleProvider','$locationProvider','$translateProvider','tmhDynamicLocaleProvider'];

  function configFunction($httpProvider,$urlRouterProvider,gravatarServiceProvider,KeepaliveProvider,IdleProvider,$locationProvider,$translateProvider,tmhDynamicLocaleProvider) {
      tmhDynamicLocaleProvider.localeLocationPattern('bower_components/angular-i18n/angular-locale_{{locale}}.js');
      $translateProvider.useMissingTranslationHandlerLog();
      $translateProvider.useSanitizeValueStrategy('sanitize');
      $translateProvider.useStaticFilesLoader({
          prefix: 'resources/locale-',
          suffix: '.json'
      });
      $translateProvider.preferredLanguage('en_US');
      $translateProvider.useLocalStorage();
      $translateProvider.useMissingTranslationHandlerLog();
    $urlRouterProvider.otherwise("/login");
    $httpProvider.defaults.headers.common = {};
    $httpProvider.defaults.headers.get = {};
    $httpProvider.defaults.headers.post = {};
    $httpProvider.defaults.headers.put = {};
    $httpProvider.defaults.headers.patch = {};
    $httpProvider.defaults.headers.common['Content-Type'] = 'application/x-www-form-urlencoded';
    $httpProvider.defaults.headers.common.Accept = '*/*';
    //$httpProvider.interceptors.push('headerInjector');
    $httpProvider.defaults.timeout = 15000;
    gravatarServiceProvider.defaults = {
      size     : 50,
      "default": 'mm'
    };
      $httpProvider.interceptors.push(function ($q,ProfileService,$location) {
          return {
              'response': function (response) {
                  if (response.status === 401) {
                      sessionStorage.clear();
                      ProfileService.clear();
                      $location.path('/login');
                  }
                  return response || $q.when(response);
              },
              'responseError': function (rejection) {
                  if (rejection.status === 401) {
                      sessionStorage.clear();
                      ProfileService.clear();
                      $location.path('/login');
                  }
                  return $q.reject(rejection);
              }
          };
      });
    // IdleProvider.idle(5); // in seconds
    // IdleProvider.timeout(10); // in seconds
    // KeepaliveProvider.interval(1); // in seconds
  }

  runFunction.$inject = ['$rootScope', '$state', 'RESOURCES','$cookies','Idle','PROTECTED_PATHS'];

  function runFunction($rootScope, $state, RESOURCES,$cookies,Idle,PROTECTED_PATHS) {
    // Idle.watch();
    $rootScope.$on('$stateChangeError',
      function(event, toState, toParams, fromState, fromParams, error) {

        if (error === "AUTH_REQUIRED") {
          $state.go('login');
        }

      });
    // $rootScope.$on('IdleStart', function() {
    //     console.log("idle start");
    // });
    // $rootScope.$on('IdleEnd', function() {
    //     console.log("idleEnd");
    // });
    //  $rootScope.$on('Keepalive', function() {
    //     console.log("keepalive");
    // });

    //   $rootScope.$on('IdleTimeout', function() {
    //   console.log("timeout");
    //   });
    //   $rootScope.$on('IdleWarn', function(e, countdown) {
    //     console.log("idle warn");
    // });

      $rootScope.$on('$stateNotFound',
        function(event, unfoundState, fromState, fromParams){
          console.log(unfoundState);
        })

    $rootScope.$on('$stateChangeStart',
      function(event, toState, toParams, fromState, fromParams, options) {
      var profile;
          if(sessionStorage.getItem('id') === null){
            profile = {
              is_authenticated:false
            }
          }else{
            profile = $cookies.getObject(sessionStorage.getItem('id'));
          }
              if(toState.name !== 'login' && toState.name !== 'forgot' && toState.name !== 'reset' && toState.name !=='submission'){
                  localStorage.setItem('path',toState.name);
              }

              // for(var key in localStorage){
              //     switch (key){
              //         case "id":
              //             localStorage.removeItem(key)
              //             break;
              //         case "student_id":
              //             localStorage.removeItem(key)
              //             break;
              //     }
              // }
              if(typeof toParams === 'object'){
                  _.forEach(toParams,function (v,k) {
                      localStorage.setItem(k,v);
                  })
              }

        if(toState.name !== "dashboard" && toState.name !== "login" && toState.name !== "forgot"){
            $rootScope.currentURL = toState.name.replace('dashboard.','') + '-page';
        }else{
            $rootScope.currentURL = toState.name.replace('/','') + '-page';
        }
        if (!profile.is_authenticated && pathIsProtected(toState.url)) {
          event.preventDefault();
          $state.go('login', {}, {reload: true});
        }

      });

    function pathIsProtected(path) {
      return PROTECTED_PATHS.indexOf(path) !== -1;
    }

  }

})();
<commit_msg>modify code for handling interceptor in local environtment<commit_after>(function() {
  'use strict';

  angular
    .module('sslv2App', [
      'ui.router',
      'ui.bootstrap',
      'ui.mask',
      'ngCookies',
      'ui.gravatar',
      'angular-confirm',
      'ngIdle',
      'ngSanitize',
      'ngTagsInput',
      'ui.multiselect',
      'fsm',
      'ui.codemirror',
      'angularMoment',
      'pascalprecht.translate',
      'tmh.dynamicLocale',
      'easypiechart',

    ])
    .factory('headerInjector', headerInjector)
    .config(configFunction)
    .run(runFunction);

  headerInjector.$inject = ['RESOURCES'];

  function headerInjector(RESOURCES) {
      var headerInjector = {
          request: function(config) {
              config.headers['X-Cbo-Client-Url'] = RESOURCES.LOCAL;
              return config;
          }
      };
      return headerInjector;
  }

  configFunction.$inject = ['$httpProvider','$urlRouterProvider','gravatarServiceProvider','KeepaliveProvider','IdleProvider','$locationProvider','$translateProvider','tmhDynamicLocaleProvider','RESOURCES'];

  function configFunction($httpProvider,$urlRouterProvider,gravatarServiceProvider,KeepaliveProvider,IdleProvider,$locationProvider,$translateProvider,tmhDynamicLocaleProvider,RESOURCES) {
      tmhDynamicLocaleProvider.localeLocationPattern('bower_components/angular-i18n/angular-locale_{{locale}}.js');
      $translateProvider.useMissingTranslationHandlerLog();
      $translateProvider.useSanitizeValueStrategy('sanitize');
      $translateProvider.useStaticFilesLoader({
          prefix: 'resources/locale-',
          suffix: '.json'
      });
      $translateProvider.preferredLanguage('en_US');
      $translateProvider.useLocalStorage();
      $translateProvider.useMissingTranslationHandlerLog();
    $urlRouterProvider.otherwise("/login");
    $httpProvider.defaults.headers.common = {};
    $httpProvider.defaults.headers.get = {};
    $httpProvider.defaults.headers.post = {};
    $httpProvider.defaults.headers.put = {};
    $httpProvider.defaults.headers.patch = {};
    $httpProvider.defaults.headers.common['Content-Type'] = 'application/x-www-form-urlencoded';
    $httpProvider.defaults.headers.common.Accept = '*/*';
    if(RESOURCES.LOCAL !== ""){
        $httpProvider.interceptors.push('headerInjector');
    }
    $httpProvider.defaults.timeout = 15000;
    gravatarServiceProvider.defaults = {
      size     : 50,
      "default": 'mm'
    };
      $httpProvider.interceptors.push(function ($q,ProfileService,$location) {
          return {
              'response': function (response) {
                  if (response.status === 401) {
                      sessionStorage.clear();
                      ProfileService.clear();
                      $location.path('/login');
                  }
                  return response || $q.when(response);
              },
              'responseError': function (rejection) {
                  if (rejection.status === 401) {
                      sessionStorage.clear();
                      ProfileService.clear();
                      $location.path('/login');
                  }
                  return $q.reject(rejection);
              }
          };
      });
    // IdleProvider.idle(5); // in seconds
    // IdleProvider.timeout(10); // in seconds
    // KeepaliveProvider.interval(1); // in seconds
  }

  runFunction.$inject = ['$rootScope', '$state', 'RESOURCES','$cookies','Idle','PROTECTED_PATHS'];

  function runFunction($rootScope, $state, RESOURCES,$cookies,Idle,PROTECTED_PATHS) {
    // Idle.watch();
    $rootScope.$on('$stateChangeError',
      function(event, toState, toParams, fromState, fromParams, error) {

        if (error === "AUTH_REQUIRED") {
          $state.go('login');
        }

      });
    // $rootScope.$on('IdleStart', function() {
    //     console.log("idle start");
    // });
    // $rootScope.$on('IdleEnd', function() {
    //     console.log("idleEnd");
    // });
    //  $rootScope.$on('Keepalive', function() {
    //     console.log("keepalive");
    // });

    //   $rootScope.$on('IdleTimeout', function() {
    //   console.log("timeout");
    //   });
    //   $rootScope.$on('IdleWarn', function(e, countdown) {
    //     console.log("idle warn");
    // });

      $rootScope.$on('$stateNotFound',
        function(event, unfoundState, fromState, fromParams){
          console.log(unfoundState);
        })

    $rootScope.$on('$stateChangeStart',
      function(event, toState, toParams, fromState, fromParams, options) {
      var profile;
          if(sessionStorage.getItem('id') === null){
            profile = {
              is_authenticated:false
            }
          }else{
            profile = $cookies.getObject(sessionStorage.getItem('id'));
          }
              if(toState.name !== 'login' && toState.name !== 'forgot' && toState.name !== 'reset' && toState.name !=='submission'){
                  localStorage.setItem('path',toState.name);
              }

              // for(var key in localStorage){
              //     switch (key){
              //         case "id":
              //             localStorage.removeItem(key)
              //             break;
              //         case "student_id":
              //             localStorage.removeItem(key)
              //             break;
              //     }
              // }
              if(typeof toParams === 'object'){
                  _.forEach(toParams,function (v,k) {
                      localStorage.setItem(k,v);
                  })
              }

        if(toState.name !== "dashboard" && toState.name !== "login" && toState.name !== "forgot"){
            $rootScope.currentURL = toState.name.replace('dashboard.','') + '-page';
        }else{
            $rootScope.currentURL = toState.name.replace('/','') + '-page';
        }
        if (!profile.is_authenticated && pathIsProtected(toState.url)) {
          event.preventDefault();
          $state.go('login', {}, {reload: true});
        }

      });

    function pathIsProtected(path) {
      return PROTECTED_PATHS.indexOf(path) !== -1;
    }

  }

})();
<|endoftext|>