<commit_before>var _ = require('isa.js')

var regexes = {
	number: /^-?(?:\d+|\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/,
	digits: /^\d+$/,
	integer: /^-?\d+$/,
	alphanum: /^\w+$/,
	password: /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z\u00C0-\u017F!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~]{8,32}$/,
	name: /^[a-zA-Z\u00C0-\u017F]+\.?\s?[a-zA-Z\u00C0-\u017F]+[.,-]?\.?\s?[a-zA-Z\u00C0-\u017F]+[.,-]?$/,
	nameExt: /^[a-zA-Z0-9\u00C0-\u017F]+\.?\s?[a-zA-Z0-9\u00C0-\u017F]+[.,-]?\.?\s?[a-zA-Z0-9\u00C0-\u017F]+[.,-]?$/,
	address: /^[a-zA-Z\u00C0-\u017F0-9-.,/\s]+$/,
	email: /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i,
	url: new RegExp('(https?:\\/\\/)?(www\\.)?[-a-zA-Z0-9@:%._\\+~#=]{2,256}\\.[a-z]{2,4}\\b([-a-zA-Z0-9@:%_\\+.~#?&//=]*)', 'i'),
	dateIso: /^(\d{4})\D?(0[1-9]|1[0-2])\D?([12]\d|0[1-9]|3[01])$/,
	phone: /^((\+\d{1,3}(-| )?\(?\d\)?(-| )?\d{1,5})|(\(?\d{2,6}\)?))(-| )?(\d{3,4})(-| )?(\d{4})(( x| ext)\d{1,5}){0,1}$/
}

let props = [
	'required', 'minlength',
	'maxlength', 'length',
	'element', 'greater', 'min',
	'less', 'max',
	'range', 'pattern', 'equalto', 'before',
	'after', 'type', 'notblank'
]

var Vindication = {
	requiredFn: function ( object, cvalue ) {
		return !cvalue || object || _.isNumber(object) || _.isBoolean(object)
	},
	minlengthFn: function ( object, cvalue ) {
		return object && object.length >= cvalue
	},
	maxlengthFn: function ( object, cvalue ) {
		return !object || object.length <= cvalue
	},
	lengthFn: function ( object, cvalue ) {
		if ( _.isString(cvalue) ) {
			cvalue = JSON.parse( cvalue )
		}
		return this.minlengthFn( object, cvalue[ 0 ] ) && this.maxlengthFn( object, cvalue[ 1 ] )
	},
	elementFn: function ( object, cvalue ) {
		return Array.isArray(cvalue) && cvalue.indexOf( object ) !== -1
	},
	greaterFn: function ( object, cvalue ) {
		return _.isNumber(object) && object > cvalue
	},
	minFn: function ( object, cvalue ) {
		return _.isNumber(object) && object >= cvalue
	},
	lessFn: function ( object, cvalue ) {
		return _.isNumber(object) && object < cvalue
	},
	maxFn: function ( object, cvalue ) {
		return _.isNumber(object) && object <= cvalue
	},
	rangeFn: function ( object, cvalue ) {
		return _.isNumber(object) && object >= cvalue[ 0 ] && object <= cvalue[ 1 ]
	},
	patternFn: function ( object, cvalue ) {
		return new RegExp( cvalue ).test( object )
	},
	equaltoFn: function ( object, cvalue ) {
		return object === cvalue
	},
	notblankFn: function ( object, cvalue ) {
		return !cvalue || this.minlengthFn( object, 1 )
	},
	beforeFn: function ( object, cvalue ) {
		return this.maxFn( object.getTime ? object.getTime() : object, cvalue.getTime ? cvalue.getTime() : cvalue )
	},
	afterFn: function ( object, cvalue ) {
		return this.minFn( object.getTime ? object.getTime() : object, cvalue.getTime ? cvalue.getTime() : cvalue )
	},
	typeFn: function ( object, cvalue ) {
		if (cvalue === 'function')
			return _.isFunction( object )
		else if (cvalue === 'string')
			return _.isString( object )
		else if (cvalue === 'array')
			return Array.isArray( object )
		else if (cvalue === 'number')
			return typeof ( object ) !== 'undefined' && object !== null && _.isNumber( object )

		var regExp = regexes[ cvalue ]
		if (!regExp) return false

		let exists = typeof ( object ) !== 'undefined' && object !== null
		if (!exists) return false

		return regExp.test( _.isString( object ) ? object : object + '' )
	},
	_checkConstraints: function ( root, object, constraints, context, options ) {
		var self = this
		if ( _.isFunction( constraints ) ) {
			if ( !constraints.call( context, object ) )
				return 'This value seems to be invalid:' + ' ' + object
		}
		else if ( _.isArray( constraints ) ) {
			var vals = []
			constraints.forEach(function ( constraint ) {
				var val = self.checkConstraints(root, object, constraint, context, options)
				if ( val )
					vals.push( val )
			} )
			return vals.length === 0 ? null : vals[0]
		}
		else {
			if ( options.ignores )
				for ( var idx = 0; idx < options.ignores.length; ++idx )
					if ( constraints[ options.ignores[idx] ] )
						return null
			if ( constraints.condition && !constraints.condition.call( context, object ) )
				return null
			if ( constraints.convert )
				object = constraints.convert.call( context, object, root )
			if ( (typeof object === 'undefined' || (object === '') || (object === null)) && !constraints.required )
				return null
			for (var key in constraints) {
				if ( key !== 'message' && key !== 'condition' && key !== 'type' ) {
					var constraint = constraints[key]
					if ( !constraint.condition || constraint.condition.call( context, object ) ) {
						if (!self[ key + 'Fn' ])
							return 'This constraint is invalid: ' + key
						var resp = self[ key + 'Fn' ](object, constraint.params || constraint) ? null : (constraints.message || 'This value seems to be invalid:') + ' ' + object
						if ( resp )
							return resp
					}
				}
			}
			if (constraints.type)
				return self.typeFn(object, constraints.type) ? null : 'This value seems to be invalid: ' + object
		}
		return null
	},
	checkConstraints: function ( root, object, constraints, context, options ) {
		try {
			return this._checkConstraints( root, object, constraints, context, options )
		}
		catch (err) {
			console.error(err, object, constraints)
		}
	},
	walk: function ( root, object, constraints, context, options ) {
		var self = this, res
		if ( (typeof (object) === 'undefined' || object === null) && constraints ) {
			return self.checkConstraints( root, object, constraints, context, options )
		}
		else if ( _.isString( object ) ) {
			return self.checkConstraints( root, object, constraints, context, options )
		}
		else if ( _.isBoolean( object ) ) {
			return self.checkConstraints( root, object, constraints, context, options )
		}
		else if ( _.isNumber( object ) ) {
			return self.checkConstraints( root, object, constraints, context, options )
		}
		else if ( _.isDate( object ) ) {
			return self.checkConstraints( root, object, constraints, context, options )
		}
		else if ( _.isRegExp( object ) ) {
			return null
		}
		else if ( Array.isArray( object ) ) {
			res = []
			if ( constraints._validator ) {
				var obj = self.checkConstraints( root, object, constraints._validator, context, options )
				if ( obj )
					res.push( obj )
			}
			object.forEach(function (element) {
				var result = self.walk( root, element, constraints, context, options )
				if ( result )
					res.push( result )
			})
			return res.length === 0 ? null : res
		}
		else if ( _.isFunction( object ) ) {
			return self.checkConstraints( root, constraints && constraints.type === 'function' ? object : object.call( context ), constraints, context, options )
		}
		else if ( _.isObject( object ) ) {
			if ( _.isFunction( constraints ) ) {
				return self.checkConstraints( root, object, constraints, context, options )
			}
			else {
				res = {}
				if ( constraints._validator ) {
					return self.checkConstraints( root, object, constraints._validator, context, options )
				}
				else {
					let keys = Object.keys( options.sourceBased ? object : constraints )
					if ( keys.find( (key) => { return props.includes( key ) } ) ) return null
					for (let key of keys) {
						if ( key && constraints[key] ) {
							var n = object[key]
							var result = self.walk( root, n, constraints[key], context, options )
							if ( result )
								res[key] = result
						}
					}
				}
				return Object.keys(res).length === 0 ? null : res
			}
		}
		return null
	}
}

function collectContraint (constraints, chain) {
	var ref = constraints
	for ( var i = 0; i < chain.length && ref; ++i )
		ref = ref[ chain[i] ]
	return ref
}

module.exports = {
	changeRegex: function (name, regex) {
		regexes[ name ] = regex
	},
	validateValue: function (value, path, constraints, context, options) {
		var constraint = collectContraint( constraints, path.split('.') )
		return Vindication.walk( value, value, constraint || {}, context || value, options || {} )
	},
	validate: function (object, constraints, context, options) {
		return Vindication.walk( object, object, constraints || {}, context || object, options || {} )
	},
	validateAll: function (objects, constraints, context, options) {
		if ( !Array.isArray( objects ) ) return this.validate( objects, constraints, context )
		var res = []
		objects.forEach(function (object) {
			res.push( Vindication.walk( object, object, constraints || {}, context || object, options || {} ) )
		})
		return res
	},
	validateByProto: function (object, prototype, options = {}) {
		if (!prototype) return true
		if (!object) throw new Error('Object seem to be empty')

		let protoKeys = Object.keys( prototype )
		for (let protoKey of protoKeys)
			if ( !object.hasOwnProperty( protoKey ) )
				throw new Error('Property is missing: ' + protoKey)

		let addKeys = Object.keys( object ).filter( (key) => { return !protoKeys.includes(key) } )
		if (addKeys.length > 0)
			throw new Error('Additional properties detected: ' + addKeys.join(', ') )
		return true
	},
	pick: function (object, predicate) {
		return _.pick( object, predicate )
	}

}
<commit_msg>small number fixes<commit_after>var _ = require('isa.js')

var regexes = {
	numeric: /^-?(?:\d+|\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/,
	digits: /^\d+$/,
	integer: /^-?\d+$/,
	alphanum: /^\w+$/,
	password: /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z\u00C0-\u017F!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~]{8,32}$/,
	name: /^[a-zA-Z\u00C0-\u017F]+\.?\s?[a-zA-Z\u00C0-\u017F]+[.,-]?\.?\s?[a-zA-Z\u00C0-\u017F]+[.,-]?$/,
	nameExt: /^[a-zA-Z0-9\u00C0-\u017F]+\.?\s?[a-zA-Z0-9\u00C0-\u017F]+[.,-]?\.?\s?[a-zA-Z0-9\u00C0-\u017F]+[.,-]?$/,
	address: /^[a-zA-Z\u00C0-\u017F0-9-.,/\s]+$/,
	email: /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i,
	url: new RegExp('(https?:\\/\\/)?(www\\.)?[-a-zA-Z0-9@:%._\\+~#=]{2,256}\\.[a-z]{2,4}\\b([-a-zA-Z0-9@:%_\\+.~#?&//=]*)', 'i'),
	dateIso: /^(\d{4})\D?(0[1-9]|1[0-2])\D?([12]\d|0[1-9]|3[01])$/,
	phone: /^((\+\d{1,3}(-| )?\(?\d\)?(-| )?\d{1,5})|(\(?\d{2,6}\)?))(-| )?(\d{3,4})(-| )?(\d{4})(( x| ext)\d{1,5}){0,1}$/
}

let props = [
	'required', 'minlength',
	'maxlength', 'length',
	'element', 'greater', 'min',
	'less', 'max',
	'range', 'pattern', 'equalto', 'before',
	'after', 'type', 'notblank'
]

var Vindication = {
	requiredFn: function ( object, cvalue ) {
		return !cvalue || object || _.isNumber(object) || _.isBoolean(object)
	},
	minlengthFn: function ( object, cvalue ) {
		return object && object.length >= cvalue
	},
	maxlengthFn: function ( object, cvalue ) {
		return !object || object.length <= cvalue
	},
	lengthFn: function ( object, cvalue ) {
		if ( _.isString(cvalue) ) {
			cvalue = JSON.parse( cvalue )
		}
		return this.minlengthFn( object, cvalue[ 0 ] ) && this.maxlengthFn( object, cvalue[ 1 ] )
	},
	elementFn: function ( object, cvalue ) {
		return Array.isArray(cvalue) && cvalue.indexOf( object ) !== -1
	},
	greaterFn: function ( object, cvalue ) {
		return _.isNumber(object) && object > cvalue
	},
	minFn: function ( object, cvalue ) {
		return _.isNumber(object) && object >= cvalue
	},
	lessFn: function ( object, cvalue ) {
		return _.isNumber(object) && object < cvalue
	},
	maxFn: function ( object, cvalue ) {
		return _.isNumber(object) && object <= cvalue
	},
	rangeFn: function ( object, cvalue ) {
		return _.isNumber(object) && object >= cvalue[ 0 ] && object <= cvalue[ 1 ]
	},
	patternFn: function ( object, cvalue ) {
		return new RegExp( cvalue ).test( object )
	},
	equaltoFn: function ( object, cvalue ) {
		return object === cvalue
	},
	notblankFn: function ( object, cvalue ) {
		return !cvalue || this.minlengthFn( object, 1 )
	},
	beforeFn: function ( object, cvalue ) {
		return this.maxFn( object.getTime ? object.getTime() : object, cvalue.getTime ? cvalue.getTime() : cvalue )
	},
	afterFn: function ( object, cvalue ) {
		return this.minFn( object.getTime ? object.getTime() : object, cvalue.getTime ? cvalue.getTime() : cvalue )
	},
	typeFn: function ( object, cvalue ) {
		if (cvalue === 'function')
			return _.isFunction( object )
		else if (cvalue === 'string')
			return _.isString( object )
		else if (cvalue === 'array')
			return Array.isArray( object )
		else if (cvalue === 'number')
			return typeof ( object ) !== 'undefined' && object !== null && _.isNumber( object )

		var regExp = regexes[ cvalue ]
		if (!regExp) return false

		let exists = typeof ( object ) !== 'undefined' && object !== null
		if (!exists) return false

		return regExp.test( _.isString( object ) ? object : object + '' )
	},
	_checkConstraints: function ( root, object, constraints, context, options ) {
		var self = this
		if ( _.isFunction( constraints ) ) {
			if ( !constraints.call( context, object ) )
				return 'This value seems to be invalid:' + ' ' + object
		}
		else if ( _.isArray( constraints ) ) {
			var vals = []
			constraints.forEach(function ( constraint ) {
				var val = self.checkConstraints(root, object, constraint, context, options)
				if ( val )
					vals.push( val )
			} )
			return vals.length === 0 ? null : vals[0]
		}
		else {
			if ( options.ignores )
				for ( var idx = 0; idx < options.ignores.length; ++idx )
					if ( constraints[ options.ignores[idx] ] )
						return null
			if ( constraints.condition && !constraints.condition.call( context, object ) )
				return null
			if ( constraints.convert )
				object = constraints.convert.call( context, object, root )
			if ( (typeof object === 'undefined' || (object === '') || (object === null)) && !constraints.required )
				return null
			for (var key in constraints) {
				if ( key !== 'message' && key !== 'condition' && key !== 'type' ) {
					var constraint = constraints[key]
					if ( !constraint.condition || constraint.condition.call( context, object ) ) {
						if (!self[ key + 'Fn' ])
							return 'This constraint is invalid: ' + key
						var resp = self[ key + 'Fn' ](object, constraint.params || constraint) ? null : (constraints.message || 'This value seems to be invalid:') + ' ' + object
						if ( resp )
							return resp
					}
				}
			}
			if (constraints.type)
				return self.typeFn(object, constraints.type) ? null : 'This value seems to be invalid: ' + object
		}
		return null
	},
	checkConstraints: function ( root, object, constraints, context, options ) {
		try {
			return this._checkConstraints( root, object, constraints, context, options )
		}
		catch (err) {
			console.error(err, object, constraints)
		}
	},
	walk: function ( root, object, constraints, context, options ) {
		var self = this, res
		if ( (typeof (object) === 'undefined' || object === null) && constraints ) {
			return self.checkConstraints( root, object, constraints, context, options )
		}
		else if ( _.isString( object ) ) {
			return self.checkConstraints( root, object, constraints, context, options )
		}
		else if ( _.isBoolean( object ) ) {
			return self.checkConstraints( root, object, constraints, context, options )
		}
		else if ( _.isNumber( object ) ) {
			return self.checkConstraints( root, object, constraints, context, options )
		}
		else if ( _.isDate( object ) ) {
			return self.checkConstraints( root, object, constraints, context, options )
		}
		else if ( _.isRegExp( object ) ) {
			return null
		}
		else if ( Array.isArray( object ) ) {
			res = []
			if ( constraints._validator ) {
				var obj = self.checkConstraints( root, object, constraints._validator, context, options )
				if ( obj )
					res.push( obj )
			}
			object.forEach(function (element) {
				var result = self.walk( root, element, constraints, context, options )
				if ( result )
					res.push( result )
			})
			return res.length === 0 ? null : res
		}
		else if ( _.isFunction( object ) ) {
			return self.checkConstraints( root, constraints && constraints.type === 'function' ? object : object.call( context ), constraints, context, options )
		}
		else if ( _.isObject( object ) ) {
			if ( _.isFunction( constraints ) ) {
				return self.checkConstraints( root, object, constraints, context, options )
			}
			else {
				res = {}
				if ( constraints._validator ) {
					return self.checkConstraints( root, object, constraints._validator, context, options )
				}
				else {
					let keys = Object.keys( options.sourceBased ? object : constraints )
					if ( keys.find( (key) => { return props.includes( key ) } ) ) return null
					for (let key of keys) {
						if ( key && constraints[key] ) {
							var n = object[key]
							var result = self.walk( root, n, constraints[key], context, options )
							if ( result )
								res[key] = result
						}
					}
				}
				return Object.keys(res).length === 0 ? null : res
			}
		}
		return null
	}
}

function collectContraint (constraints, chain) {
	var ref = constraints
	for ( var i = 0; i < chain.length && ref; ++i )
		ref = ref[ chain[i] ]
	return ref
}

module.exports = {
	changeRegex: function (name, regex) {
		regexes[ name ] = regex
	},
	validateValue: function (value, path, constraints, context, options) {
		var constraint = collectContraint( constraints, path.split('.') )
		return Vindication.walk( value, value, constraint || {}, context || value, options || {} )
	},
	validate: function (object, constraints, context, options) {
		return Vindication.walk( object, object, constraints || {}, context || object, options || {} )
	},
	validateAll: function (objects, constraints, context, options) {
		if ( !Array.isArray( objects ) ) return this.validate( objects, constraints, context )
		var res = []
		objects.forEach(function (object) {
			res.push( Vindication.walk( object, object, constraints || {}, context || object, options || {} ) )
		})
		return res
	},
	validateByProto: function (object, prototype, options = {}) {
		if (!prototype) return true
		if (!object) throw new Error('Object seem to be empty')

		let protoKeys = Object.keys( prototype )
		for (let protoKey of protoKeys)
			if ( !object.hasOwnProperty( protoKey ) )
				throw new Error('Property is missing: ' + protoKey)

		let addKeys = Object.keys( object ).filter( (key) => { return !protoKeys.includes(key) } )
		if (addKeys.length > 0)
			throw new Error('Additional properties detected: ' + addKeys.join(', ') )
		return true
	},
	pick: function (object, predicate) {
		return _.pick( object, predicate )
	}

}
<|endoftext|>


<commit_before><commit_msg>refactoring Translate.js, step1<commit_after><|endoftext|>


<commit_before>import React, { Component } from 'react';
import { DAYS_OF_WEEK } from '../utils/constants';
import '../styles/NewLocation.css';
import Location from '../model/Location';
import HappyHour from '../model/HappyHour';

const initialState = {
  inputs: {
    day: '',
    startingHour: '',
    endingHour: '',
    drinkSpecials: '',
    foodSpecials: ''
  },
  uploaded: ''
};

export class NewLocation extends Component {
  constructor(props) {
    super();
    this.state = initialState;
    this.updateInput = this.updateInput.bind(this);
    this.submitForm = this.submitForm.bind(this);
  }

  updateInput(e, key) {
    this.setState({
      inputs: Object.assign({}, this.state.inputs, { [key]: e.target.value })
    });
  }

  submitForm() {
    const { activeLocation } = this.props;

    const location = new Location(
      this.props.activeLocation,
      'website',
      'phone_number',
      2
    );

    this.postRequest('api/v1/locations', location).then(locationResponse => {
      const location = locationResponse.data[0];
      const happyHourInput = new HappyHour(location.id, this.state.inputs);
      return this.postRequest(
        'api/v1/happyhours',
        happyHourInput
      ).then(happyHourResponse => {
        this.setState(
          Object.assign({}, initialState, { uploaded: location.name })
        );
        this.resetLocation();
      });
    });
  }

  postRequest(endpoint, content) {
    const { token } = this.props;
    const body = Object.assign(content, token);

    return fetch(endpoint, {
      headers: {
        'Content-Type': 'application/json'
      },
      method: 'POST',
      body: JSON.stringify(body)
    }).then(res => res.json());
  }

  componentDidMount() {
    this.props.generateToken();
  }

  resetLocation() {
    setTimeout(() => {
      this.setState({ uploaded: '' });
    }, 5000);
  }

  render() {
    if (!this.props.activeLocation) {
      return
Not here yet
;
    }
    const { name, rating, vicinity } = this.props.activeLocation;

    const disabled =
      Object.keys(this.state.inputs).findIndex(
        key => this.state.inputs[key].length < 1
      ) >= 0;

    return (

          {this.state.uploaded} was uploaded.

{name}

          There are no happy hours listed for this location.

Add Happy Hour Information

Day

            <select className="day" onChange={e => this.updateInput(e, 'day')}>
              <option>Day of the Week</option>
              <option value="mon">Monday</option>
              <option value="tue">Tuesday</option>
              <option value="wed">Wednesday</option>
              <option value="thu">Thursday</option>
              <option value="fri">Friday</option>
              <option value="sat">Saturday</option>
              <option value="sun">Sunday</option>
            </select>

            Start Time
            <select
              className="start"
              onChange={e => this.updateInput(e, 'startingHour')}
            >
              <option>-- Start Time --</option>
              <option>01:00</option>
              <option>02:00</option>
              <option>03:00</option>
              <option>04:00</option>
              <option>05:00</option>
              <option>06:00</option>
              <option>07:00</option>
              <option>08:00</option>
              <option>09:00</option>
              <option>10:00</option>
              <option>11:00</option>
              <option>12:00</option>
              <option>13:00</option>
              <option>14:00</option>
              <option>15:00</option>
              <option>16:00</option>
              <option>17:00</option>
              <option>18:00</option>
              <option>19:00</option>
              <option>20:00</option>
              <option>21:00</option>
              <option>22:00</option>
              <option>23:00</option>
              <option>24:00</option>
            </select>

            End Time
            <select
              className="end"
              onChange={e => this.updateInput(e, 'endingHour')}
            >
              <option>-- End Time --</option>
              <option>01:00</option>
              <option>02:00</option>
              <option>03:00</option>
              <option>04:00</option>
              <option>05:00</option>
              <option>06:00</option>
              <option>07:00</option>
              <option>08:00</option>
              <option>09:00</option>
              <option>10:00</option>
              <option>11:00</option>
              <option>12:00</option>
              <option>13:00</option>
              <option>14:00</option>
              <option>15:00</option>
              <option>16:00</option>
              <option>17:00</option>
              <option>18:00</option>
              <option>19:00</option>
              <option>20:00</option>
              <option>21:00</option>
              <option>22:00</option>
              <option>23:00</option>
              <option>24:00</option>
            </select>

Drink Specials

            <textarea
              className="drink-specials"
              type="text"
              value={this.state.drinkSpecials}
              placeholder="Describe Drink Specials"
              onChange={e => this.updateInput(e, 'drinkSpecials')}
            />

Food Specials

            <textarea
              className="food-specials"
              type="text"
              value={this.state.foodSpecials}
              placeholder="Describe Food Specials"
              onChange={e => this.updateInput(e, 'foodSpecials')}
            />

          <button
            className="submit-hours"
            onClick={() => this.submitForm()}
            disabled={disabled}
          >
            Submit
          </button>

    );
  }
}
<commit_msg>fix / in post request<commit_after>import React, { Component } from 'react';
import { DAYS_OF_WEEK } from '../utils/constants';
import '../styles/NewLocation.css';
import Location from '../model/Location';
import HappyHour from '../model/HappyHour';

const initialState = {
  inputs: {
    day: '',
    startingHour: '',
    endingHour: '',
    drinkSpecials: '',
    foodSpecials: ''
  },
  uploaded: ''
};

export class NewLocation extends Component {
  constructor(props) {
    super();
    this.state = initialState;
    this.updateInput = this.updateInput.bind(this);
    this.submitForm = this.submitForm.bind(this);
  }

  updateInput(e, key) {
    this.setState({
      inputs: Object.assign({}, this.state.inputs, { [key]: e.target.value })
    });
  }

  submitForm() {
    const { activeLocation } = this.props;

    const location = new Location(
      this.props.activeLocation,
      'website',
      'phone_number',
      2
    );

    this.postRequest('/api/v1/locations', location).then(locationResponse => {
      const location = locationResponse.data[0];
      const happyHourInput = new HappyHour(location.id, this.state.inputs);
      return this.postRequest(
        'api/v1/happyhours',
        happyHourInput
      ).then(happyHourResponse => {
        this.setState(
          Object.assign({}, initialState, { uploaded: location.name })
        );
        this.resetLocation();
      });
    });
  }

  postRequest(endpoint, content) {
    const { token } = this.props;
    const body = Object.assign(content, token);

    return fetch(endpoint, {
      headers: {
        'Content-Type': 'application/json'
      },
      method: 'POST',
      body: JSON.stringify(body)
    }).then(res => res.json());
  }

  componentDidMount() {
    this.props.generateToken();
  }

  resetLocation() {
    setTimeout(() => {
      this.setState({ uploaded: '' });
    }, 5000);
  }

  render() {
    if (!this.props.activeLocation) {
      return
Not here yet
;
    }
    const { name, rating, vicinity } = this.props.activeLocation;

    const disabled =
      Object.keys(this.state.inputs).findIndex(
        key => this.state.inputs[key].length < 1
      ) >= 0;

    return (

          {this.state.uploaded} was uploaded.

{name}

          There are no happy hours listed for this location.

Add Happy Hour Information

Day

            <select className="day" onChange={e => this.updateInput(e, 'day')}>
              <option>Day of the Week</option>
              <option value="mon">Monday</option>
              <option value="tue">Tuesday</option>
              <option value="wed">Wednesday</option>
              <option value="thu">Thursday</option>
              <option value="fri">Friday</option>
              <option value="sat">Saturday</option>
              <option value="sun">Sunday</option>
            </select>

            Start Time
            <select
              className="start"
              onChange={e => this.updateInput(e, 'startingHour')}
            >
              <option>-- Start Time --</option>
              <option>01:00</option>
              <option>02:00</option>
              <option>03:00</option>
              <option>04:00</option>
              <option>05:00</option>
              <option>06:00</option>
              <option>07:00</option>
              <option>08:00</option>
              <option>09:00</option>
              <option>10:00</option>
              <option>11:00</option>
              <option>12:00</option>
              <option>13:00</option>
              <option>14:00</option>
              <option>15:00</option>
              <option>16:00</option>
              <option>17:00</option>
              <option>18:00</option>
              <option>19:00</option>
              <option>20:00</option>
              <option>21:00</option>
              <option>22:00</option>
              <option>23:00</option>
              <option>24:00</option>
            </select>

            End Time
            <select
              className="end"
              onChange={e => this.updateInput(e, 'endingHour')}
            >
              <option>-- End Time --</option>
              <option>01:00</option>
              <option>02:00</option>
              <option>03:00</option>
              <option>04:00</option>
              <option>05:00</option>
              <option>06:00</option>
              <option>07:00</option>
              <option>08:00</option>
              <option>09:00</option>
              <option>10:00</option>
              <option>11:00</option>
              <option>12:00</option>
              <option>13:00</option>
              <option>14:00</option>
              <option>15:00</option>
              <option>16:00</option>
              <option>17:00</option>
              <option>18:00</option>
              <option>19:00</option>
              <option>20:00</option>
              <option>21:00</option>
              <option>22:00</option>
              <option>23:00</option>
              <option>24:00</option>
            </select>

Drink Specials

            <textarea
              className="drink-specials"
              type="text"
              value={this.state.drinkSpecials}
              placeholder="Describe Drink Specials"
              onChange={e => this.updateInput(e, 'drinkSpecials')}
            />

Food Specials

            <textarea
              className="food-specials"
              type="text"
              value={this.state.foodSpecials}
              placeholder="Describe Food Specials"
              onChange={e => this.updateInput(e, 'foodSpecials')}
            />

          <button
            className="submit-hours"
            onClick={() => this.submitForm()}
            disabled={disabled}
          >
            Submit
          </button>

    );
  }
}
<|endoftext|>


<commit_before>import React from 'react'
import Relay from 'react-relay'
import {BernieColors, BernieText} from './styles/bernie-css'
import {Paper, Slider, Toggle, Styles} from 'material-ui'
import GCForm from './forms/GCForm'
import Form from 'react-formal'
import EventPreview from './EventPreview'
import MutationHandler from './MutationHandler'
import CreateFastFwdRequest from '../mutations/CreateFastFwdRequest'
import yup from 'yup'
import MuiThemeProvider from 'material-ui/lib/MuiThemeProvider'
import {BernieTheme} from './styles/bernie-theme';

const publicEventsRootUrl = 'https://secure.berniesanders.com/page/event/detail/'

class FastFwdForm extends React.Component {
  styles = {
    detailsContainer: {
      float: 'left',
      marginTop: '1rem',
      padding: 10,
      width: '50%'
    },

    formContainer: {
      float: 'left',
      width: '40%',
      padding: 15,
      marginTop: 15,
      marginLeft: '2rem',
      border: 'solid 1px ' + BernieColors.lightGray
    },

    pageContainer: {
      marginLeft: '7rem',
      marginTop: '1rem'
    }
  }

  state = {
    testMode: false,
    recipientLimit: null
  }

  render() {

    if (!this.props.event)
      return

Invalid Event

This event does not exist. If you've just recently created your event.
                this error may resolve itself in a short period of time. It's also
                possible your event was deleted. Please email help@berniesanders.com if you need help.

    let event_type_name = 'volunteer event';

    if(this.props.event.eventType.name.toLowerCase().indexOf('phone bank') > -1){
      event_type_name = 'phone bank party'
    }

    if(this.props.event.eventType.name.toLowerCase().indexOf('barnstorm') > -1){
      event_type_name = 'Barnstorm event'
    }

    let defaultHostMessage = this.props.event.fastFwdRequest ? this.props.event.fastFwdRequest.hostMessage :
                            "Hello, neighbors!\n\nI'm hosting a " + event_type_name +
                            " and I need a few more Bernie supporters " +
                            "to attend to make this event a big success. " +
                            "Will you please attend my event?\n\n" +
                            publicEventsRootUrl + this.props.event.eventIdObfuscated + "\n\n" +
                            "Thank you,\n\n" +
                            (this.props.event.host ? this.props.event.host.firstName: "")

    let formSchema = yup.object({
      hostMessage: yup.string().default(this.props.event.hostMessage || defaultHostMessage).required(),
    })

    return (
      <MuiThemeProvider muiTheme={Styles.getMuiTheme(BernieTheme)}>

          <MutationHandler ref='mutationHandler'
                           successMessage='Your request has been saved. We will review it and send it out to volunteers in your area ASAP!'
                           mutationClass={CreateFastFwdRequest}
                           mutationName='createFastFwdRequest'
                           onSuccess={() => {
                              setTimeout(() => {
                                location.href = 'https://go.berniesanders.com/page/content/volunteer-hub/';
                              }, 9000)
                         }} />

            Fast Fwd: Send a message to bring volunteers to your event

Your Event Details:

            <EventPreview event={this.props.event} />

          <Paper zDepth={2} style={this.styles.formContainer}>
            <GCForm
              schema={formSchema}
              defaultValue={formSchema.default()}
              value = {this.state.model}
              onChange={ model => {
                this.setState({ model })
              }}
              onSubmit={(formValues) => {
                this.refs.mutationHandler.send({
                  eventId: this.props.event.id,
                  ...formValues
                })
              }}
            >

Author a message below about your event and why people should come out.
                We'll forward it on to potential attendees in your area.

              <Form.Field
                name='hostMessage'
                multiLine={true}
                rows={12}
                label="Message From Host"
              />

              <Form.Button type='submit' label='Submit' fullWidth={true} />
            </GCForm>
          </Paper>

      </MuiThemeProvider>
    )
  }
}

export default Relay.createContainer(FastFwdForm, {
  fragments: {
    currentUser: () => Relay.QL`
      fragment on User {
        id
        email
      }
    `,
    event: () => Relay.QL`
      fragment on Event {
        attendeesCount
        attendeeVolunteerMessage
        attendeeVolunteerShow
        fastFwdRequest{
          hostMessage
        }
        capacity
        contactPhone
        createDate
        description
        duration
        eventIdObfuscated
        eventType {
          id
          name
        }
        flagApproval
        host {
          id
          firstName
          lastName
          email
        }
        hostReceiveRsvpEmails
        id
        isSearchable
        latitude
        localTimezone
        localUTCOffset
        longitude
        name
        nearbyPeople {
          id
          firstName
          lastName
          email
        }
        publicPhone
        rsvpEmailReminderHours
        rsvpUseReminderEmail
        startDate
        venueAddr1
        venueAddr2
        venueCity
        venueCountry
        venueDirections
        venueName
        venueState
        venueZip
      }
    `
  }
})
<commit_msg>Make inputs fullwidth + more style changes<commit_after>import React from 'react'
import Relay from 'react-relay'
import {BernieColors, BernieText} from './styles/bernie-css'
import {Paper, Slider, Toggle, Styles} from 'material-ui'
import GCForm from './forms/GCForm'
import Form from 'react-formal'
import EventPreview from './EventPreview'
import MutationHandler from './MutationHandler'
import CreateFastFwdRequest from '../mutations/CreateFastFwdRequest'
import yup from 'yup'
import MuiThemeProvider from 'material-ui/lib/MuiThemeProvider'
import {BernieTheme} from './styles/bernie-theme'

const publicEventsRootUrl = 'https://secure.berniesanders.com/page/event/detail/'

class FastFwdForm extends React.Component {
  styles = {
    detailsContainer: {
      float: 'left',
      padding: '1em',
      paddingLeft: 0,
      width: '55%',
    },

    formContainer: {
      float: 'left',
      width: '40%',
      padding: '1em',
      marginTop: 15,
      marginLeft: '2rem',
      border: 'solid 1px ' + BernieColors.lightGray
    },

    pageContainer: {
      margin: '0 auto',
      padding: '3em',
      maxWidth: 1300
    }
  }

  state = {
    testMode: false,
    recipientLimit: null
  }

  render() {

    if (!this.props.event)
      return

Invalid Event

This event does not exist. If you've just recently created your event.
                this error may resolve itself in a short period of time. It's also
                possible your event was deleted. Please email help@berniesanders.com if you need help.

    let event_type_name = 'volunteer event';

    if(this.props.event.eventType.name.toLowerCase().indexOf('phone bank') > -1){
      event_type_name = 'phone bank party'
    }

    if(this.props.event.eventType.name.toLowerCase().indexOf('barnstorm') > -1){
      event_type_name = 'Barnstorm event'
    }

    let defaultHostMessage = this.props.event.fastFwdRequest ? this.props.event.fastFwdRequest.hostMessage :
                            "Hello, neighbors!\n\nI'm hosting a " + event_type_name +
                            " and I need a few more Bernie supporters " +
                            "to attend to make this event a big success. " +
                            "Will you please attend my event?\n\n" +
                            publicEventsRootUrl + this.props.event.eventIdObfuscated + "\n\n" +
                            "Thank you,\n\n" +
                            (this.props.event.host ? this.props.event.host.firstName: "")

    let formSchema = yup.object({
      hostMessage: yup.string().default(this.props.event.hostMessage || defaultHostMessage).required(),
    })

    return (
      <MuiThemeProvider muiTheme={Styles.getMuiTheme(BernieTheme)}>

          <MutationHandler ref='mutationHandler'
                           successMessage='Your request has been saved. We will review it and send it out to volunteers in your area ASAP!'
                           mutationClass={CreateFastFwdRequest}
                           mutationName='createFastFwdRequest'
                           onSuccess={() => {
                              setTimeout(() => {
                                location.href = 'https://go.berniesanders.com/page/content/volunteer-hub/';
                              }, 9000)
                         }} />

            Fast Fwd: Send a message to bring volunteers to your event

Your Event Details:

            <EventPreview event={this.props.event} />

          <Paper style={this.styles.formContainer}>
            <GCForm
              schema={formSchema}
              defaultValue={formSchema.default()}
              value = {this.state.model}
              onChange={ model => {
                this.setState({ model })
              }}
              onSubmit={(formValues) => {
                this.refs.mutationHandler.send({
                  eventId: this.props.event.id,
                  ...formValues
                })
              }}
            >

Author a message below about your event and why people should come out.
                We'll forward it on to potential attendees in your area.

              <Form.Field
                name='hostMessage'
                multiLine={true}
                rows={12}
                fullWidth={true}
                label="Message From Host"
              />

              <Form.Button type='submit' label='Submit' fullWidth={true} />
            </GCForm>
          </Paper>

      </MuiThemeProvider>
    )
  }
}

export default Relay.createContainer(FastFwdForm, {
  fragments: {
    currentUser: () => Relay.QL`
      fragment on User {
        id
        email
      }
    `,
    event: () => Relay.QL`
      fragment on Event {
        attendeesCount
        attendeeVolunteerMessage
        attendeeVolunteerShow
        fastFwdRequest{
          hostMessage
        }
        capacity
        contactPhone
        createDate
        description
        duration
        eventIdObfuscated
        eventType {
          id
          name
        }
        flagApproval
        host {
          id
          firstName
          lastName
          email
        }
        hostReceiveRsvpEmails
        id
        isSearchable
        latitude
        localTimezone
        localUTCOffset
        longitude
        name
        nearbyPeople {
          id
          firstName
          lastName
          email
        }
        publicPhone
        rsvpEmailReminderHours
        rsvpUseReminderEmail
        startDate
        venueAddr1
        venueAddr2
        venueCity
        venueCountry
        venueDirections
        venueName
        venueState
        venueZip
      }
    `
  }
})
<|endoftext|>


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

// create config
var config = JSON.parse(process.env.config);

// create paths
var paths = {MONO_ROOT: path.normalize(__dirname + '/../../')};
paths.LIB_ROOT = paths.MONO_ROOT + 'lib/';
paths.CLIENT_ROOT = paths.LIB_ROOT + 'client/';
paths.USERS_ROOT = paths.MONO_ROOT + 'users/';
paths.PROJECT_ROOT = paths.USERS_ROOT + config.owner + '/projects/' + config.id + '/';
paths.SERVER_ROOT = paths.LIB_ROOT + 'project/';
paths.MODULE_ROOT = paths.PROJECT_ROOT + 'mono_modules/';
paths.PUBLIC_ROOT = paths.PROJECT_ROOT + config.publicDir + '/';
paths.TEMPLATE_ROOT = paths.PROJECT_ROOT + config.templateDir + '/';
paths.MIDDLEWARE = paths.LIB_ROOT + 'middleware/';
paths.MODULE = paths.LIB_ROOT + 'module/';
paths.MODELS = paths.LIB_ROOT + 'models/';
paths.VIEWS = paths.LIB_ROOT + 'views/';

// TOOD get this config from project settings
config.store = {
    storesCollection: 'm_stores',
    // TODO change to project_ when admin gets installed
    //systemDbPrefix: 'project_',
    systemDbPrefix: 'app_',
    systemStoreName: 'system',
    systemAdapter: "mongodb",
    systemConfig: {
        host: 'localhost',
        port: '27017',
        // TODO change to project_ when admin gets installed
        //name: 'project_' + config.id,
        name: 'app_' + config.id,
        user: config.owner,
        pass: config.apiKey
    }
};

// extend js functionality
require(paths.LIB_ROOT + 'utils/extend');

// add paths to config
config.paths = paths;

module.exports = config;
<commit_msg>updated mongodb database name config<commit_after>var path = require('path');

// create config
var config = JSON.parse(process.env.config);

// create paths
var paths = {MONO_ROOT: path.normalize(__dirname + '/../../')};
paths.LIB_ROOT = paths.MONO_ROOT + 'lib/';
paths.CLIENT_ROOT = paths.LIB_ROOT + 'client/';
paths.USERS_ROOT = paths.MONO_ROOT + 'users/';
paths.PROJECT_ROOT = paths.USERS_ROOT + config.owner + '/projects/' + config.id + '/';
paths.SERVER_ROOT = paths.LIB_ROOT + 'project/';
paths.MODULE_ROOT = paths.PROJECT_ROOT + 'mono_modules/';
paths.PUBLIC_ROOT = paths.PROJECT_ROOT + config.publicDir + '/';
paths.TEMPLATE_ROOT = paths.PROJECT_ROOT + config.templateDir + '/';
paths.MIDDLEWARE = paths.LIB_ROOT + 'middleware/';
paths.MODULE = paths.LIB_ROOT + 'module/';
paths.MODELS = paths.LIB_ROOT + 'models/';
paths.VIEWS = paths.LIB_ROOT + 'views/';

// TOOD get this config from project settings
config.store = {
    storesCollection: 'm_stores',
    // TODO change to project_ when admin gets installed
    //systemDbPrefix: 'project_',
    systemDbPrefix: 'app_',
    systemStoreName: 'system',
    systemAdapter: "mongodb",
    systemConfig: {
        host: 'localhost',
        port: '27017',
        // TODO change to project_ when admin gets installed
        //name: 'project_' + config.id,
        database: 'app_' + config.id,
        user: config.owner,
        pass: config.apiKey
    }
};

// extend js functionality
require(paths.LIB_ROOT + 'utils/extend');

// add paths to config
config.paths = paths;

module.exports = config;
<|endoftext|>


<commit_before>/** @babel */
/** @jsx jsxDOM */

/**
 * Copyright 2016-present PlatformIO Plus <contact@pioplus.com>
 *
 * License: https://pioplus.com/license.html
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 */

import { BaseView, FilteredList, jsxDOM } from '../view';
import { CompositeDisposable, TextEditor } from 'atom';
import { getRecentProjects, removeRecentProject, synchronizeRecentProjects } from './util';

import fuzzaldrin from 'fuzzaldrin-plus';
import path from 'path';

export default class RecentProjects extends BaseView {

  constructor() {
    synchronizeRecentProjects(atom.project.getPaths());
    super(...arguments);
    this.disposables = new CompositeDisposable();
    this.disposables.add(atom.project.onDidChangePaths((projectPaths) => {
      synchronizeRecentProjects(projectPaths);
      this.update();
    }));
  }

  render() {
    return (

        <RecentProjectsView items={ getRecentProjects() } />

    );
  }

  destroy() {
    this.disposables.dispose();
    return super.destroy();
  }

}

class RecentProjectsView extends FilteredList {

  get filterEditor() {
    return this.refs.filterEditor;
  }

  onDidFilter() {
    this.update();
  }

  getItems() {
    if (!this.props.hasOwnProperty('items')) {
      return [];
    }
    if (!this.refs) {
      return this.props.items;
    }
    const query = this.filterEditor.getText();
    return query ? fuzzaldrin.filter(this.props.items, query) : this.props.items;
  }

  onDidRemove(item) {
    removeRecentProject(item);
    this.props.items = this.props.items.filter(_item => _item !== item);
    this.update();
  }

  onDidSelect(item) {
    atom.project.addPath(item);
  }

  render() {
    const items = this.getItems();
    return (
      <atom-panel>
        <TextEditor ref='filterEditor' mini={ true } placeholderText='Filter projects' />
        { !items.length ? (

              No recent projects

          ) : ('') }

            { items.map((item) => (
                <RecentProjectItem item={ item } onselect={ () => this.onDidSelect(item) } onremove={ () => this.onDidRemove(item) } />
              )) }

      </atom-panel>
    );
  }

}

class RecentProjectItem extends BaseView {

  constructor(props) {
    super(props);
    this.disposable = atom.tooltips.add(
      this.refs.removeItem, {
        title: 'Remove project from history'
      }
    );
  }

  onRemoveHandler(event) {
    event.stopPropagation();
    this.props.onremove();
  }

  onMouseOverHandler(event) {
    event.stopPropagation();
    const element = this.refs.removeItem;
    element.classList.add('icon-remove-close');
  }

  onMouseOutHandler(event) {
    event.stopPropagation();
    const element = this.refs.removeItem;
    element.classList.remove('icon-remove-close');
  }

  render() {
    return (

 this.onMouseOverHandler(e) }
        onmouseout={ (e) => this.onMouseOutHandler(e) }>

 this.onRemoveHandler(e) }>

          { path.basename(this.props.item) }

          { this.props.item }

    );
  }

  destroy() {
    this.disposable.dispose();
    super.destroy();
  }
}
<commit_msg>Remove project from Atom Tree View if it was deleted from Recent Projects<commit_after>/** @babel */
/** @jsx jsxDOM */

/**
 * Copyright 2016-present PlatformIO Plus <contact@pioplus.com>
 *
 * License: https://pioplus.com/license.html
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 */

import { BaseView, FilteredList, jsxDOM } from '../view';
import { CompositeDisposable, TextEditor } from 'atom';
import { getRecentProjects, removeRecentProject, synchronizeRecentProjects } from './util';

import fuzzaldrin from 'fuzzaldrin-plus';
import path from 'path';

export default class RecentProjects extends BaseView {

  constructor() {
    synchronizeRecentProjects(atom.project.getPaths());
    super(...arguments);
    this.disposables = new CompositeDisposable();
    this.disposables.add(atom.project.onDidChangePaths((projectPaths) => {
      synchronizeRecentProjects(projectPaths);
      this.update();
    }));
  }

  render() {
    return (

        <RecentProjectsView items={ getRecentProjects() } />

    );
  }

  destroy() {
    this.disposables.dispose();
    return super.destroy();
  }

}

class RecentProjectsView extends FilteredList {

  get filterEditor() {
    return this.refs.filterEditor;
  }

  onDidFilter() {
    this.update();
  }

  getItems() {
    if (!this.props.hasOwnProperty('items')) {
      return [];
    }
    if (!this.refs) {
      return this.props.items;
    }
    const query = this.filterEditor.getText();
    return query ? fuzzaldrin.filter(this.props.items, query) : this.props.items;
  }

  onDidRemove(item) {
    removeRecentProject(item);
    atom.project.removePath(item);
    this.props.items = this.props.items.filter(_item => _item !== item);
    this.update();
  }

  onDidSelect(item) {
    atom.project.addPath(item);
  }

  render() {
    const items = this.getItems();
    return (
      <atom-panel>
        <TextEditor ref='filterEditor' mini={ true } placeholderText='Filter projects' />
        { !items.length ? (

              No recent projects

          ) : ('') }

            { items.map((item) => (
                <RecentProjectItem item={ item } onselect={ () => this.onDidSelect(item) } onremove={ () => this.onDidRemove(item) } />
              )) }

      </atom-panel>
    );
  }

}

class RecentProjectItem extends BaseView {

  constructor(props) {
    super(props);
    this.disposable = atom.tooltips.add(
      this.refs.removeItem, {
        title: 'Remove project from history'
      }
    );
  }

  onRemoveHandler(event) {
    event.stopPropagation();
    this.props.onremove();
  }

  onMouseOverHandler(event) {
    event.stopPropagation();
    const element = this.refs.removeItem;
    element.classList.add('icon-remove-close');
  }

  onMouseOutHandler(event) {
    event.stopPropagation();
    const element = this.refs.removeItem;
    element.classList.remove('icon-remove-close');
  }

  render() {
    return (

 this.onMouseOverHandler(e) }
        onmouseout={ (e) => this.onMouseOutHandler(e) }>

 this.onRemoveHandler(e) }>

          { path.basename(this.props.item) }

          { this.props.item }

    );
  }

  destroy() {
    this.disposable.dispose();
    super.destroy();
  }
}
<|endoftext|>


<commit_before>import React from 'react'
import Relay from 'react-relay'
import {BernieColors, BernieText} from './styles/bernie-css'
import {Paper, Slider, Toggle, Styles} from 'material-ui'
import GCForm from './forms/GCForm'
import Form from 'react-formal'
import EventPreview from './EventPreview'
import MutationHandler from './MutationHandler'
import CreateFastFwdRequest from '../mutations/CreateFastFwdRequest'
import yup from 'yup'
import MuiThemeProvider from 'material-ui/lib/MuiThemeProvider'
import {BernieTheme} from './styles/bernie-theme';

const publicEventsRootUrl = 'https://secure.berniesanders.com/page/event/detail/'

class FastFwdForm extends React.Component {
  styles = {
    detailsContainer: {
      float: 'left',
      marginTop: '1rem',
      padding: 10,
      width: 480
    },

    formContainer: {
      float: 'left',
      width: 380,
      paddingLeft: 15,
      paddingRight: 15,
      paddingTop: 15,
      paddingBottom: 15,
      marginTop: 15,
      marginLeft: '2rem',
      border: 'solid 1px ' + BernieColors.lightGray
    },

    pageContainer: {
      marginLeft: '7rem',
      marginTop: '1rem'
    }
  }

  state = {
    testMode: false,
    recipientLimit: null
  }

  render() {

    if (!this.props.event)
      return

Invalid Event

This event does not exist. If you've just recently created your event.
                this error may resolve itself in a short period of time. It's also
                possible your event was deleted. Please email help@berniesanders.com if you need help.

    let event_type_name = 'volunteer event';

    if(this.props.event.eventType.name.toLowerCase().indexOf('phone bank') > -1){
      event_type_name = 'phone bank party'
    }

    if(this.props.event.eventType.name.toLowerCase().indexOf('barnstorm') > -1){
      event_type_name = 'Barnstorm event'
    }

    let defaultHostMessage = this.props.event.fastFwdRequest ? this.props.event.fastFwdRequest.hostMessage :
                            "Hello, neighbors!\n\nI'm hosting a " + event_type_name +
                            " and I need a few more Bernie supporters " +
                            "to attend to make this event a big success. " +
                            "Will you please attend my event?\n\n" +
                            publicEventsRootUrl + this.props.event.eventIdObfuscated + "\n\n" +
                            "Thank you,\n\n" +
                            (this.props.event.host ? this.props.event.host.firstName: "")

    let formSchema = yup.object({
      hostMessage: yup.string().default(this.props.event.hostMessage || defaultHostMessage).required(),
    })

    return (
      <MuiThemeProvider muiTheme={Styles.getMuiTheme(BernieTheme)}>

          <MutationHandler ref='mutationHandler'
                           successMessage='Your message has been saved.'
                           mutationClass={CreateFastFwdRequest}
                           mutationName='createFastFwdRequest' />

            Fast Fwd: Send a message to bring volunteers to your event

          <Paper zDepth={1} style={this.styles.detailsContainer}>

Your Event Details:

            <EventPreview event={this.props.event} />
          </Paper>

          <Paper zDepth={2} style={this.styles.formContainer}>
            <GCForm
              schema={formSchema}
              defaultValue={formSchema.default()}
              value = {this.state.model}
              onChange={ model => {
                this.setState({ model })
              }}
              onSubmit={(formValues) => {
                this.refs.mutationHandler.send({
                  eventId: this.props.event.id,
                  ...formValues
                })
              }}
            >

Author a message below about your event and why people should come out.
                We'll forward it on to potential attendees in your area.

              <Form.Field
                name='hostMessage'
                multiLine={true}
                rows={12}
                label="Message From Host"
              />

              <Form.Button type='submit' label='Submit' fullWidth={true} />
            </GCForm>
          </Paper>

      </MuiThemeProvider>
    )
  }
}

export default Relay.createContainer(FastFwdForm, {
  fragments: {
    currentUser: () => Relay.QL`
      fragment on User {
        id
        email
      }
    `,
    event: () => Relay.QL`
      fragment on Event {
        attendeesCount
        attendeeVolunteerMessage
        attendeeVolunteerShow
        fastFwdRequest{
          hostMessage
        }
        capacity
        contactPhone
        createDate
        description
        duration
        eventIdObfuscated
        eventType {
          id
          name
        }
        flagApproval
        host {
          id
          firstName
          lastName
          email
        }
        hostReceiveRsvpEmails
        id
        isSearchable
        latitude
        localTimezone
        localUTCOffset
        longitude
        name
        nearbyPeople {
          id
          firstName
          lastName
          email
        }
        publicPhone
        rsvpEmailReminderHours
        rsvpUseReminderEmail
        startDate
        venueAddr1
        venueAddr2
        venueCity
        venueCountry
        venueDirections
        venueName
        venueState
        venueZip
      }
    `
  }
})
<commit_msg>Better messaging on submit & redirect them to the organizing hub.<commit_after>import React from 'react'
import Relay from 'react-relay'
import {BernieColors, BernieText} from './styles/bernie-css'
import {Paper, Slider, Toggle, Styles} from 'material-ui'
import GCForm from './forms/GCForm'
import Form from 'react-formal'
import EventPreview from './EventPreview'
import MutationHandler from './MutationHandler'
import CreateFastFwdRequest from '../mutations/CreateFastFwdRequest'
import yup from 'yup'
import MuiThemeProvider from 'material-ui/lib/MuiThemeProvider'
import {BernieTheme} from './styles/bernie-theme';

const publicEventsRootUrl = 'https://secure.berniesanders.com/page/event/detail/'

class FastFwdForm extends React.Component {
  styles = {
    detailsContainer: {
      float: 'left',
      marginTop: '1rem',
      padding: 10,
      width: 480
    },

    formContainer: {
      float: 'left',
      width: 380,
      paddingLeft: 15,
      paddingRight: 15,
      paddingTop: 15,
      paddingBottom: 15,
      marginTop: 15,
      marginLeft: '2rem',
      border: 'solid 1px ' + BernieColors.lightGray
    },

    pageContainer: {
      marginLeft: '7rem',
      marginTop: '1rem'
    }
  }

  state = {
    testMode: false,
    recipientLimit: null
  }

  render() {

    if (!this.props.event)
      return

Invalid Event

This event does not exist. If you've just recently created your event.
                this error may resolve itself in a short period of time. It's also
                possible your event was deleted. Please email help@berniesanders.com if you need help.

    let event_type_name = 'volunteer event';

    if(this.props.event.eventType.name.toLowerCase().indexOf('phone bank') > -1){
      event_type_name = 'phone bank party'
    }

    if(this.props.event.eventType.name.toLowerCase().indexOf('barnstorm') > -1){
      event_type_name = 'Barnstorm event'
    }

    let defaultHostMessage = this.props.event.fastFwdRequest ? this.props.event.fastFwdRequest.hostMessage :
                            "Hello, neighbors!\n\nI'm hosting a " + event_type_name +
                            " and I need a few more Bernie supporters " +
                            "to attend to make this event a big success. " +
                            "Will you please attend my event?\n\n" +
                            publicEventsRootUrl + this.props.event.eventIdObfuscated + "\n\n" +
                            "Thank you,\n\n" +
                            (this.props.event.host ? this.props.event.host.firstName: "")

    let formSchema = yup.object({
      hostMessage: yup.string().default(this.props.event.hostMessage || defaultHostMessage).required(),
    })

    return (
      <MuiThemeProvider muiTheme={Styles.getMuiTheme(BernieTheme)}>

          <MutationHandler ref='mutationHandler'
                           successMessage='Your request has been saved. We will review it and send it out to volunteers in your area ASAP!'
                           mutationClass={CreateFastFwdRequest}
                           mutationName='createFastFwdRequest'
                           onSuccess={() => {
                              setTimeout(() => {
                                location.href = 'https://go.berniesanders.com/page/content/volunteer-hub/';
                              }, 9000)
                         }} />

            Fast Fwd: Send a message to bring volunteers to your event

          <Paper zDepth={1} style={this.styles.detailsContainer}>

Your Event Details:

            <EventPreview event={this.props.event} />
          </Paper>

          <Paper zDepth={2} style={this.styles.formContainer}>
            <GCForm
              schema={formSchema}
              defaultValue={formSchema.default()}
              value = {this.state.model}
              onChange={ model => {
                this.setState({ model })
              }}
              onSubmit={(formValues) => {
                this.refs.mutationHandler.send({
                  eventId: this.props.event.id,
                  ...formValues
                })
              }}
            >

Author a message below about your event and why people should come out.
                We'll forward it on to potential attendees in your area.

              <Form.Field
                name='hostMessage'
                multiLine={true}
                rows={12}
                label="Message From Host"
              />

              <Form.Button type='submit' label='Submit' fullWidth={true} />
            </GCForm>
          </Paper>

      </MuiThemeProvider>
    )
  }
}

export default Relay.createContainer(FastFwdForm, {
  fragments: {
    currentUser: () => Relay.QL`
      fragment on User {
        id
        email
      }
    `,
    event: () => Relay.QL`
      fragment on Event {
        attendeesCount
        attendeeVolunteerMessage
        attendeeVolunteerShow
        fastFwdRequest{
          hostMessage
        }
        capacity
        contactPhone
        createDate
        description
        duration
        eventIdObfuscated
        eventType {
          id
          name
        }
        flagApproval
        host {
          id
          firstName
          lastName
          email
        }
        hostReceiveRsvpEmails
        id
        isSearchable
        latitude
        localTimezone
        localUTCOffset
        longitude
        name
        nearbyPeople {
          id
          firstName
          lastName
          email
        }
        publicPhone
        rsvpEmailReminderHours
        rsvpUseReminderEmail
        startDate
        venueAddr1
        venueAddr2
        venueCity
        venueCountry
        venueDirections
        venueName
        venueState
        venueZip
      }
    `
  }
})
<|endoftext|>


<commit_before>/*global define*/
define([
        './defaultValue',
        './defined',
        './DeveloperError',
        './Cartesian3',
        './Intersect',
        './Matrix3',
    ], function(
        defaultValue,
        defined,
        DeveloperError,
        Cartesian3,
        Intersect,
        Matrix3) {
    "use strict";

    /**
     * Creates an instance of an ObjectOrientedBoundingBox.
     * @alias ObjectOrientedBoundingBox
     * @constructor
     *
     * @see BoundingSphere
     */
    var ObjectOrientedBoundingBox = function() {
        this.transformMatrix;
        this.transformedPosition;
        this.extent;
    };

    /**
     * Computes an instance of an ObjectOrientedBoundingBox of the given positions. The box is determined //TODO
     * @memberof ObjectOrientedBoundingBox
     *
     * @param {Array} positions List of points that the bounding box will enclose.  Each point must have a x, y, and z properties.
     * @param {ObjectOrientedBoundingBox} [result] The object onto which to store the result.
     * @return {ObjectOrientedBoundingBox} The modified result parameter or a new ObjectOrientedBoundingBox instance if one was not provided.
     *
     * @example
     * // Compute an object oriented bounding box enclosing two points.
     * var box = ObjectOrientedBoundingBox.fromPoints([new Cartesian3(2, 0, 0), new Cartesian3(-2, 0, 0)]);
     */
    ObjectOrientedBoundingBox.fromPoints = function(positions, result) {
        if (!defined(result)) {
            result = new ObjectOrientedBoundingBox();
            result.transformMatrix = new Matrix3();
            result.transformedPosition = new Cartesian3();
            result.extent = new Cartesian3();
        }

        if (!defined(positions) || positions.length === 0) {
            return result;
        }

        var meanPoint = new Cartesian3();

        var length = positions.length;
        for ( var i = 0; i < length; i++) {
            var p = positions[i];
            meanPoint = Cartesian3.add(meanPoint, Cartesian3.multiplyByScalar(p, 1/length));
        }
        var exx=0.0;
        var exy=0.0;
        var exz=0.0;
        var eyy=0.0;
        var eyz=0.0;
        var ezz=0.0;

        for ( var i = 0; i < length; i++) {
            var p = positions[i];
            exx += p.x*p.x - meanPoint.x*meanPoint.x;
            exy += p.x*p.y - meanPoint.x*meanPoint.y;
            exz += p.x*p.z - meanPoint.x*meanPoint.z;
            eyy += p.y*p.y - meanPoint.y*meanPoint.y;
            eyz += p.y*p.z - meanPoint.y*meanPoint.z;
            ezz += p.z*p.z - meanPoint.z*meanPoint.z;
        }

        var covarianceMatrix = new Matrix3(exx,exy,exz,exy,eyy,eyz,exz,eyz,ezz);

        var eigenDecomposition = Matrix3.getEigenDecomposition(covarianceMatrix);
        var unitaryMatrix = eigenDecomposition.unitary;

        //eigenvectors of covMatrix
        var v1 = Matrix3.getColumn(unitaryMatrix, 0, v1);
        var v2 = Matrix3.getColumn(unitaryMatrix, 1, v2);
        var v3 = Matrix3.getColumn(unitaryMatrix, 2, v3);

        //normalized eigenvectors
        var r = Cartesian3.normalize(v1, r);
        var u = Cartesian3.normalize(v2, u);
        var f = Cartesian3.normalize(v3, f);

        result.transformMatrix = new Matrix3(r.x, u.x, f.x, r.y, u.y, f.y, r.z, u.z, f.z);

        var p = positions[0];
        var tempPoint = new Cartesian3(Cartesian3.dot(r, p), Cartesian3.dot(u, p), Cartesian3.dot(f, p));
        var maxPoint = tempPoint;
        var minPoint = tempPoint;

        for ( var i = 1; i < length; i++) {
            p = positions[i];
            tempPoint = new Cartesian3(Cartesian3.dot(r, p), Cartesian3.dot(u, p), Cartesian3.dot(f, p));
            minPoint = Cartesian3.getMinimumByComponent(minPoint, tempPoint);
            maxPoint = Cartesian3.getMaximumByComponent(maxPoint, tempPoint);
        }

        var center = new Cartesian3((minPoint.x+maxPoint.x)*0.5, (minPoint.y+maxPoint.y)*0.5, (minPoint.z+maxPoint.z)*0.5);

        result.transformedPosition = new Cartesian3(Cartesian3.dot(Matrix3.getRow(result.transformMatrix, 0), center), Cartesian3.dot(Matrix3.getRow(result.transformMatrix, 1), center), Cartesian3.dot(Matrix3.getRow(result.transformMatrix, 2), center))

        result.extent = new Cartesian3((maxPoint.x-minPoint.x)*0.5, (maxPoint.y-minPoint.y)*0.5, (maxPoint.z-minPoint.z)*0.5);

        return result;
    };

    /**
     * Get the describing points of the ObjectOrientedBoundingBox.
     * @memberof ObjectOrientedBoundingBox
     *
     * @param {ObjectOrientedBoundingBox} box The bounding box.
     * @param {Cartesian3} [result] The object onto which to store the resulting points.
     * @return {Cartesian3} The object onto which to store the resulting points.
     */
    ObjectOrientedBoundingBox.getDescribingPoints = function(box, result) {
        if (!defined(box)) {
            return undefined;
        }

        if (!defined(result)) {
          var result = [];
        }

        var r = Matrix3.getColumn(box.transformMatrix, 0, r);
        var u = Matrix3.getColumn(box.transformMatrix, 1, u);
        var f = Matrix3.getColumn(box.transformMatrix, 2, f);

        var point = Cartesian3.add(Cartesian3.add(Cartesian3.add(box.transformedPosition,Cartesian3.multiplyByScalar(r, box.extent.x*(-1))),Cartesian3.multiplyByScalar(u, box.extent.y*(-1))),Cartesian3.multiplyByScalar(f, box.extent.z*(-1)));
        result.push(point);
        point = Cartesian3.add(Cartesian3.add(Cartesian3.add(box.transformedPosition,Cartesian3.multiplyByScalar(r, box.extent.x*(1))),Cartesian3.multiplyByScalar(u, box.extent.y*(-1))),Cartesian3.multiplyByScalar(f, box.extent.z*(-1)));
        result.push(point);
        point = Cartesian3.add(Cartesian3.add(Cartesian3.add(box.transformedPosition,Cartesian3.multiplyByScalar(r, box.extent.x*(1))),Cartesian3.multiplyByScalar(u, box.extent.y*(-1))),Cartesian3.multiplyByScalar(f, box.extent.z*(1)));
        result.push(point);
        point = Cartesian3.add(Cartesian3.add(Cartesian3.add(box.transformedPosition,Cartesian3.multiplyByScalar(r, box.extent.x*(-1))),Cartesian3.multiplyByScalar(u, box.extent.y*(-1))),Cartesian3.multiplyByScalar(f, box.extent.z*(1)));
        result.push(point);
        point = Cartesian3.add(Cartesian3.add(Cartesian3.add(box.transformedPosition,Cartesian3.multiplyByScalar(r, box.extent.x*(-1))),Cartesian3.multiplyByScalar(u, box.extent.y*(1))),Cartesian3.multiplyByScalar(f, box.extent.z*(-1)));
        result.push(point);
        point = Cartesian3.add(Cartesian3.add(Cartesian3.add(box.transformedPosition,Cartesian3.multiplyByScalar(r, box.extent.x*(1))),Cartesian3.multiplyByScalar(u, box.extent.y*(1))),Cartesian3.multiplyByScalar(f, box.extent.z*(-1)));
        result.push(point);
        point = Cartesian3.add(Cartesian3.add(Cartesian3.add(box.transformedPosition,Cartesian3.multiplyByScalar(r, box.extent.x*(1))),Cartesian3.multiplyByScalar(u, box.extent.y*(1))),Cartesian3.multiplyByScalar(f, box.extent.z*(1)));
        result.push(point);
        point = Cartesian3.add(Cartesian3.add(Cartesian3.add(box.transformedPosition,Cartesian3.multiplyByScalar(r, box.extent.x*(-1))),Cartesian3.multiplyByScalar(u, box.extent.y*(1))),Cartesian3.multiplyByScalar(f, box.extent.z*(1)));
        result.push(point);

        return result;
    };

    /**
     * Duplicates a ObjectOrientedBoundingBox instance. //TODO
     * @memberof ObjectOrientedBoundingBox
     *
     * @param {ObjectOrientedBoundingBox} box The bounding box to duplicate.
     * @param {ObjectOrientedBoundingBox} [result] The object onto which to store the result.
     * @return {ObjectOrientedBoundingBox} The modified result parameter or a new ObjectOrientedBoundingBox instance if none was provided. (Returns undefined if box is undefined)
     */
    ObjectOrientedBoundingBox.clone = function(box, result) {
        if (!defined(box)) {
            return undefined;
        }

        if (!defined(result)) {
           var result = new ObjectOrientedBoundingBox();
        }

        result.transformMatrix = box.transformMatrix;
        result.transformedPosition = box.transformedPosition;
        result.extent = box.extent;

        return result;
    };

    /**
     * Compares the provided ObjectOrientedBoundingBox componentwise and returns
     * true if they are equal, false otherwise.
     * @memberof ObjectOrientedBoundingBox
     *
     * @param {ObjectOrientedBoundingBox} [left] The first ObjectOrientedBoundingBox.
     * @param {ObjectOrientedBoundingBox} [right] The second ObjectOrientedBoundingBox.
     * @return {Boolean} true if left and right are equal, false otherwise.
     */
    ObjectOrientedBoundingBox.equals = function(left, right) {
        return (left === right) ||
               ((defined(left)) &&
                (defined(right)) &&
                Cartesian3.equals(left.transformedPosition, right.transformedPosition) &&
                Matrix3.equals(left.transformMatrix, right.transformMatrix) &&
                Cartesian3.equals(left.extent, right.extent));
    };

    var intersectScratch = new Cartesian3();
    /**
     * Determines which side of a plane a box is located. //TODO
     * @memberof ObjectOrientedBoundingBox
     *
     * @param {ObjectOrientedBoundingBox} box The bounding box to test.
     * @param {Cartesian4} plane The coefficients of the plane in the form ax + by + cz + d = 0
     *                           where the coefficients a, b, c, and d are the components x, y, z, and w
     *                           of the {Cartesian4}, respectively.
     * @return {Intersect} {Intersect.INSIDE} if the entire box is on the side of the plane the normal is pointing,
     *                     {Intersect.OUTSIDE} if the entire box is on the opposite side, and {Intersect.INTERSETING}
     *                     if the box intersects the plane.
     *
     * @exception {DeveloperError} box is required.
     * @exception {DeveloperError} plane is required.
     */
    ObjectOrientedBoundingBox.intersect = function(box, plane) {
        if (!defined(box)) {
            throw new DeveloperError('box is required.');
        }

        if (!defined(plane)) {
            throw new DeveloperError('plane is required.');
        }

        return undefined;
    };

    /**
     * Duplicates this ObjectOrientedBoundingBox instance.
     * @memberof ObjectOrientedBoundingBox
     *
     * @param {ObjectOrientedBoundingBox} [result] The object onto which to store the result.
     * @return {ObjectOrientedBoundingBox} The modified result parameter or a new ObjectOrientedBoundingBox instance if one was not provided.
     */
    ObjectOrientedBoundingBox.prototype.clone = function(result) {
        return ObjectOrientedBoundingBox.clone(this, result);
    };

    /**
     * Determines which side of a plane this box is located.
     * @memberof ObjectOrientedBoundingBox
     *
     * @param {Cartesian4} plane The coefficients of the plane in the form ax + by + cz + d = 0
     *                           where the coefficients a, b, c, and d are the components x, y, z, and w
     *                           of the {Cartesian4}, respectively.
     * @return {Intersect} {Intersect.INSIDE} if the entire box is on the side of the plane the normal is pointing,
     *                     {Intersect.OUTSIDE} if the entire box is on the opposite side, and {Intersect.INTERSETING}
     *                     if the box intersects the plane.
     *
     * @exception {DeveloperError} plane is required.
     */
    ObjectOrientedBoundingBox.prototype.intersect = function(plane) {
        return ObjectOrientedBoundingBox.intersect(this, plane);
    };

    /**
     * Compares this ObjectOrientedBoundingBox against the provided ObjectOrientedBoundingBox componentwise and returns
     * true if they are equal, false otherwise.
     * @memberof ObjectOrientedBoundingBox
     *
     * @param {ObjectOrientedBoundingBox} [right] The right hand side ObjectOrientedBoundingBox.
     * @return {Boolean} true if they are equal, false otherwise.
     */
    ObjectOrientedBoundingBox.prototype.equals = function(right) {
        return ObjectOrientedBoundingBox.equals(this, right);
    };

    return ObjectOrientedBoundingBox;
});
<commit_msg>Optional parameters fixed.<commit_after>/*global define*/
define([
        './defaultValue',
        './defined',
        './DeveloperError',
        './Cartesian3',
        './Intersect',
        './Matrix3',
    ], function(
        defaultValue,
        defined,
        DeveloperError,
        Cartesian3,
        Intersect,
        Matrix3) {
    "use strict";

    /**
     * Creates an instance of an ObjectOrientedBoundingBox.
     * @alias ObjectOrientedBoundingBox
     * @constructor
     *
     * @param {Cartesian3} [transformMatrix=Matrix3.IDENTITY] The transformation matrix, to rotate the box to the right position.
     * @param {Cartesian3} [transformedPosition=Cartesian3.ZERO] The position of the box.
     * @param {Cartesian3} [extent=Cartesian3.ZERO] The scale of the box.
     *
     * @see BoundingSphere
     */
    var ObjectOrientedBoundingBox = function(transformMatrix, transformedPosition, extent) {
        /**
         * The transformation matrix, to rotate the box to the right position.
         * @type {Matrix3}
         * @default {@link Matrix3.IDENTITY}
         */
        this.transformMatrix = Matrix3.clone(defaultValue(transformMatrix, Matrix3.IDENTITY));
        /**
         * The position of the box.
         * @type {Cartesian3}
         * @default {@link Cartesian3.ZERO}
         */
        this.transformedPosition = Cartesian3.clone(defaultValue(transformedPosition, Cartesian3.ZERO));
        /**
         * The scale of the box.
         * @type {Cartesian3}
         * @default {@link Cartesian3.ZERO}
         */
        this.extent = Cartesian3.clone(defaultValue(extent, Cartesian3.ZERO));
    };

    /**
     * Computes an instance of an ObjectOrientedBoundingBox of the given positions. The box is determined //TODO
     * @memberof ObjectOrientedBoundingBox
     *
     * @param {Array} positions List of points that the bounding box will enclose.  Each point must have a x, y, and z properties.
     * @param {ObjectOrientedBoundingBox} [result] The object onto which to store the result.
     * @return {ObjectOrientedBoundingBox} The modified result parameter or a new ObjectOrientedBoundingBox instance if one was not provided.
     *
     * @example
     * // Compute an object oriented bounding box enclosing two points.
     * var box = ObjectOrientedBoundingBox.fromPoints([new Cartesian3(2, 0, 0), new Cartesian3(-2, 0, 0)]);
     */
    ObjectOrientedBoundingBox.fromPoints = function(positions, result) {
        if (!defined(result)) {
            result = new ObjectOrientedBoundingBox();
            result.transformMatrix = new Matrix3();
            result.transformedPosition = new Cartesian3();
            result.extent = new Cartesian3();
        }

        if (!defined(positions) || positions.length === 0) {
            return result;
        }

        var meanPoint = new Cartesian3();

        var length = positions.length;
        for ( var i = 0; i < length; i++) {
            var p = positions[i];
            meanPoint = Cartesian3.add(meanPoint, Cartesian3.multiplyByScalar(p, 1/length));
        }
        var exx=0.0;
        var exy=0.0;
        var exz=0.0;
        var eyy=0.0;
        var eyz=0.0;
        var ezz=0.0;

        for ( var i = 0; i < length; i++) {
            var p = positions[i];
            exx += p.x*p.x - meanPoint.x*meanPoint.x;
            exy += p.x*p.y - meanPoint.x*meanPoint.y;
            exz += p.x*p.z - meanPoint.x*meanPoint.z;
            eyy += p.y*p.y - meanPoint.y*meanPoint.y;
            eyz += p.y*p.z - meanPoint.y*meanPoint.z;
            ezz += p.z*p.z - meanPoint.z*meanPoint.z;
        }

        var covarianceMatrix = new Matrix3(exx,exy,exz,exy,eyy,eyz,exz,eyz,ezz);

        var eigenDecomposition = Matrix3.getEigenDecomposition(covarianceMatrix);
        var unitaryMatrix = eigenDecomposition.unitary;

        //eigenvectors of covMatrix
        var v1 = Matrix3.getColumn(unitaryMatrix, 0, v1);
        var v2 = Matrix3.getColumn(unitaryMatrix, 1, v2);
        var v3 = Matrix3.getColumn(unitaryMatrix, 2, v3);

        //normalized eigenvectors
        var r = Cartesian3.normalize(v1, r);
        var u = Cartesian3.normalize(v2, u);
        var f = Cartesian3.normalize(v3, f);

        result.transformMatrix = new Matrix3(r.x, u.x, f.x, r.y, u.y, f.y, r.z, u.z, f.z);

        var p = positions[0];
        var tempPoint = new Cartesian3(Cartesian3.dot(r, p), Cartesian3.dot(u, p), Cartesian3.dot(f, p));
        var maxPoint = tempPoint;
        var minPoint = tempPoint;

        for ( var i = 1; i < length; i++) {
            p = positions[i];
            tempPoint = new Cartesian3(Cartesian3.dot(r, p), Cartesian3.dot(u, p), Cartesian3.dot(f, p));
            minPoint = Cartesian3.getMinimumByComponent(minPoint, tempPoint);
            maxPoint = Cartesian3.getMaximumByComponent(maxPoint, tempPoint);
        }

        var center = new Cartesian3((minPoint.x+maxPoint.x)*0.5, (minPoint.y+maxPoint.y)*0.5, (minPoint.z+maxPoint.z)*0.5);

        result.transformedPosition = new Cartesian3(Cartesian3.dot(Matrix3.getRow(result.transformMatrix, 0), center), Cartesian3.dot(Matrix3.getRow(result.transformMatrix, 1), center), Cartesian3.dot(Matrix3.getRow(result.transformMatrix, 2), center))

        result.extent = new Cartesian3((maxPoint.x-minPoint.x)*0.5, (maxPoint.y-minPoint.y)*0.5, (maxPoint.z-minPoint.z)*0.5);

        return result;
    };

    /**
     * Get the describing points of the ObjectOrientedBoundingBox.
     * @memberof ObjectOrientedBoundingBox
     *
     * @param {ObjectOrientedBoundingBox} box The bounding box.
     * @param {Cartesian3} [result] The object onto which to store the resulting points.
     * @return {Cartesian3} The object onto which to store the resulting points.
     */
    ObjectOrientedBoundingBox.getDescribingPoints = function(box, result) {
        if (!defined(box)) {
            return undefined;
        }

        if (!defined(result)) {
          var result = [];
        }

        var r = Matrix3.getColumn(box.transformMatrix, 0, r);
        var u = Matrix3.getColumn(box.transformMatrix, 1, u);
        var f = Matrix3.getColumn(box.transformMatrix, 2, f);

        var point = Cartesian3.add(Cartesian3.add(Cartesian3.add(box.transformedPosition,Cartesian3.multiplyByScalar(r, box.extent.x*(-1))),Cartesian3.multiplyByScalar(u, box.extent.y*(-1))),Cartesian3.multiplyByScalar(f, box.extent.z*(-1)));
        result.push(point);
        point = Cartesian3.add(Cartesian3.add(Cartesian3.add(box.transformedPosition,Cartesian3.multiplyByScalar(r, box.extent.x*(1))),Cartesian3.multiplyByScalar(u, box.extent.y*(-1))),Cartesian3.multiplyByScalar(f, box.extent.z*(-1)));
        result.push(point);
        point = Cartesian3.add(Cartesian3.add(Cartesian3.add(box.transformedPosition,Cartesian3.multiplyByScalar(r, box.extent.x*(1))),Cartesian3.multiplyByScalar(u, box.extent.y*(-1))),Cartesian3.multiplyByScalar(f, box.extent.z*(1)));
        result.push(point);
        point = Cartesian3.add(Cartesian3.add(Cartesian3.add(box.transformedPosition,Cartesian3.multiplyByScalar(r, box.extent.x*(-1))),Cartesian3.multiplyByScalar(u, box.extent.y*(-1))),Cartesian3.multiplyByScalar(f, box.extent.z*(1)));
        result.push(point);
        point = Cartesian3.add(Cartesian3.add(Cartesian3.add(box.transformedPosition,Cartesian3.multiplyByScalar(r, box.extent.x*(-1))),Cartesian3.multiplyByScalar(u, box.extent.y*(1))),Cartesian3.multiplyByScalar(f, box.extent.z*(-1)));
        result.push(point);
        point = Cartesian3.add(Cartesian3.add(Cartesian3.add(box.transformedPosition,Cartesian3.multiplyByScalar(r, box.extent.x*(1))),Cartesian3.multiplyByScalar(u, box.extent.y*(1))),Cartesian3.multiplyByScalar(f, box.extent.z*(-1)));
        result.push(point);
        point = Cartesian3.add(Cartesian3.add(Cartesian3.add(box.transformedPosition,Cartesian3.multiplyByScalar(r, box.extent.x*(1))),Cartesian3.multiplyByScalar(u, box.extent.y*(1))),Cartesian3.multiplyByScalar(f, box.extent.z*(1)));
        result.push(point);
        point = Cartesian3.add(Cartesian3.add(Cartesian3.add(box.transformedPosition,Cartesian3.multiplyByScalar(r, box.extent.x*(-1))),Cartesian3.multiplyByScalar(u, box.extent.y*(1))),Cartesian3.multiplyByScalar(f, box.extent.z*(1)));
        result.push(point);

        return result;
    };

    /**
     * Duplicates a ObjectOrientedBoundingBox instance. //TODO
     * @memberof ObjectOrientedBoundingBox
     *
     * @param {ObjectOrientedBoundingBox} box The bounding box to duplicate.
     * @param {ObjectOrientedBoundingBox} [result] The object onto which to store the result.
     * @return {ObjectOrientedBoundingBox} The modified result parameter or a new ObjectOrientedBoundingBox instance if none was provided. (Returns undefined if box is undefined)
     */
    ObjectOrientedBoundingBox.clone = function(box, result) {
        if (!defined(box)) {
            return undefined;
        }

        if (!defined(result)) {
           var result = new ObjectOrientedBoundingBox();
        }

        result.transformMatrix = box.transformMatrix;
        result.transformedPosition = box.transformedPosition;
        result.extent = box.extent;

        return result;
    };

    /**
     * Compares the provided ObjectOrientedBoundingBox componentwise and returns
     * true if they are equal, false otherwise.
     * @memberof ObjectOrientedBoundingBox
     *
     * @param {ObjectOrientedBoundingBox} [left] The first ObjectOrientedBoundingBox.
     * @param {ObjectOrientedBoundingBox} [right] The second ObjectOrientedBoundingBox.
     * @return {Boolean} true if left and right are equal, false otherwise.
     */
    ObjectOrientedBoundingBox.equals = function(left, right) {
        return (left === right) ||
               ((defined(left)) &&
                (defined(right)) &&
                Cartesian3.equals(left.transformedPosition, right.transformedPosition) &&
                Matrix3.equals(left.transformMatrix, right.transformMatrix) &&
                Cartesian3.equals(left.extent, right.extent));
    };

    var intersectScratch = new Cartesian3();
    /**
     * Determines which side of a plane a box is located. //TODO
     * @memberof ObjectOrientedBoundingBox
     *
     * @param {ObjectOrientedBoundingBox} box The bounding box to test.
     * @param {Cartesian4} plane The coefficients of the plane in the form ax + by + cz + d = 0
     *                           where the coefficients a, b, c, and d are the components x, y, z, and w
     *                           of the {Cartesian4}, respectively.
     * @return {Intersect} {Intersect.INSIDE} if the entire box is on the side of the plane the normal is pointing,
     *                     {Intersect.OUTSIDE} if the entire box is on the opposite side, and {Intersect.INTERSETING}
     *                     if the box intersects the plane.
     *
     * @exception {DeveloperError} box is required.
     * @exception {DeveloperError} plane is required.
     */
    ObjectOrientedBoundingBox.intersect = function(box, plane) {
        if (!defined(box)) {
            throw new DeveloperError('box is required.');
        }

        if (!defined(plane)) {
            throw new DeveloperError('plane is required.');
        }

        return undefined;
    };

    /**
     * Duplicates this ObjectOrientedBoundingBox instance.
     * @memberof ObjectOrientedBoundingBox
     *
     * @param {ObjectOrientedBoundingBox} [result] The object onto which to store the result.
     * @return {ObjectOrientedBoundingBox} The modified result parameter or a new ObjectOrientedBoundingBox instance if one was not provided.
     */
    ObjectOrientedBoundingBox.prototype.clone = function(result) {
        return ObjectOrientedBoundingBox.clone(this, result);
    };

    /**
     * Determines which side of a plane this box is located.
     * @memberof ObjectOrientedBoundingBox
     *
     * @param {Cartesian4} plane The coefficients of the plane in the form ax + by + cz + d = 0
     *                           where the coefficients a, b, c, and d are the components x, y, z, and w
     *                           of the {Cartesian4}, respectively.
     * @return {Intersect} {Intersect.INSIDE} if the entire box is on the side of the plane the normal is pointing,
     *                     {Intersect.OUTSIDE} if the entire box is on the opposite side, and {Intersect.INTERSETING}
     *                     if the box intersects the plane.
     *
     * @exception {DeveloperError} plane is required.
     */
    ObjectOrientedBoundingBox.prototype.intersect = function(plane) {
        return ObjectOrientedBoundingBox.intersect(this, plane);
    };

    /**
     * Compares this ObjectOrientedBoundingBox against the provided ObjectOrientedBoundingBox componentwise and returns
     * true if they are equal, false otherwise.
     * @memberof ObjectOrientedBoundingBox
     *
     * @param {ObjectOrientedBoundingBox} [right] The right hand side ObjectOrientedBoundingBox.
     * @return {Boolean} true if they are equal, false otherwise.
     */
    ObjectOrientedBoundingBox.prototype.equals = function(right) {
        return ObjectOrientedBoundingBox.equals(this, right);
    };

    return ObjectOrientedBoundingBox;
});
<|endoftext|>


<commit_before><commit_msg>Added Debug class<commit_after><|endoftext|>