<commit_before>/*
Copyright (C) 2013  Daniel Reid

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    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.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

function DotManager() {
	this.lists = {ALLDOTS:[]};
	this.spcLists = {};
	this.count = 0;
}

DotManager.prototype = {
//start public funcs
	add: function(dot) {//can send as list or single dot
		if (dot instanceof Array) {
			this.count += dot.length;
		} else {
			this.count ++;
		}
		this.execAllCombos(this.addFunc, dot);
	},
	remove: function(dot, deactivateDots) {//can send as list or single dot
		deactivateDots = deactiveDots === undefined ? true : deactivateDots;
		if (dot instanceof Array) {
			this.count -= dot.length;
			for (var dotIdx=0; dotIdx<dot.length;dotIdx++) {
				dot[dotIdx].kill(deactivateDots);
			}
		} else {
			this.count --;
			dot.kill(deactivateDots);
		}
	},
	removeByAttr: function(attr, val) {
		var dots = this.lists.ALLDOTS;
		for (var i=dots.length-1; i>=0; i--) {
			if (dots[i][attr] == val) dots[i].kill();
		}
	},
	changeDotSpc: function(dots, newSpcName) {//can send as list or single dot
		if (!(dots instanceof Array)) dots = [dots];
		var def = spcs[newSpcName];
		for (var dotIdx=0; dotIdx<dots.length; dotIdx++) {
			var dot = dots[dotIdx];
			var tempF = (dot.hF298 - (def.hF298 * 1000 / N) + dot.cv * (dot.temp() - 298.15)) / (def.cv / N) + 298.15;
			if (tempF > 0) {
				for (var parentListIdx=0; parentListIdx<dot.parentLists.length; parentListIdx++) {
					dot.parentLists[parentListIdx].splice(dot.parentLists[parentListIdx].indexOf(dot), 1);
				}
				dot.parentLists = [];
				dot.m = def.m;
				dot.r = def.r;
				dot.col = def.col;
				dot.spcName = def.spcName;
				dot.hF298 = def.hF298 * 1000 / N;
				dot.hVap298 = def.hVap298 * 1000 / N;
				dot.idNum = def.idNum;
				dot.cvKinetic = 1.5 * R / N;
				dot.cv = def.cv / N;
				dot.cp = dot.cv + R;
				dot.cpLiq = def.cpLiq / N;
				dot.spcVolLiq = def.spcVolLiq / N;
				dot.setTempNoReference(tempF);

				var newLists = this.getRelevantLists(dot);
				for (var newListIdx=0; newListIdx<newLists.length; newListIdx++) {
					dot.parentLists.push(newLists[newListIdx]);
					newLists[newListIdx].push(dot);
				}
			}
		}

	},
	changeDotWall: function(dots, newWallHandle) {
		var j, jj;
		if (!(dots instanceof Array)) dots = [dots];
		for (var i=0; i<dots.length; i++) {
			var dot = dots[i];
			dot.tag = newWallHandle;
			dot.returnTo = newWallHandle;
			for (j=0, jj=dot.parentLists.length; j<jj; j++) {
				dot.parentLists[j].splice(dot.parentLists[j].indexOf(dot), 1);
			}
			dot.parentLists = [];
			var newLists = this.getRelevantLists(dot);
			for (j=0, jj=newLists.length; j<jj; j++) {
				dot.parentLists.push(newLists[j]);
				newLists[j].push(dot);
			}
		}
	},
	addSpcs: function(name) {
		if (!this.lists[name]) {
			this.lists[name] = [];
			this.spcLists[name] = this.lists[name];
		}
		return this.lists[name];
	},
	removeByInfo: function(info) {
		if (info.spcName && info.tag) {
			this.execAllCombos(this.removeByNameAndTagFunc, info);
		} else if (info.spcName){
			this.execAllCombos(this.removeByNameFunc, info);
		} else if (info.tag) {
			this.execAllCombos(this.removeByTagFunc, info);
		} else {
			console.log('No useful info given to removeByInfo func in DotManager');
			console.trace();
		}
	},
	getWithLog: function(info) {
		var gotten = this.get(info);
		if (gotten) {
			return gotten
		} else {
			console.log('Bad species data');
			console.log(info);
		}
	},
	get: function(info) {
		return this.createIfNotExists(info);
		// if (info) {
			// if (info.spcName && info.tag) {
				// return this.lists[info.spcName + '-' + info.tag];
			// } else if (info.spcName) {
				// return this.lists[info.spcName];
			// } else if (info.tag) {
				// return this.lists[info.tag];
			// }
		// } else {
			// return this.lists.ALLDOTS;
		// }
	},
	clearAll: function() {
		for (var list in this.lists) {
			this.lists[list].splice(0, this.lists[list].length);
		}
	},
	createIfNotExists: function(info) {
		if (info) {
			if (info.spcName && info.tag) {
				return this.getByNameAndTag(info);
			} else if (info.spcName) {
				return this.getByName(info.spcName);
			} else if (info.tag) {
				return this.getByTag(info.tag);
			}
		} else {
			return this.lists.ALLDOTS;
		}
	},

//end public funcs
	addFunc: function(list, dot) {
		list.push(dot);
		dot.parentLists.push(list);
	},
	removeFunc: function(list, dot) {
		var idx = list.indexOf(dot);
		if (idx>-1) {
			list.splice(idx, 1);
			dot.parentLists.splice(dot.parentLists.indexOf(list), 1);
		} else {
			console.log('Tried to remove dot from global list of spcName ' + dot.spcName + ' and tag ' + dot.tag + '. Dot not present.');
			console.trace();
		}
	},
	removeByNameAndTagFunc: function(list, info) {
		for (var dotIdx=list.length-1; dotIdx>-1; dotIdx--) {
			if (list[dotIdx].spcName==info.spcName && list[dotIdx].tag==info.tag) {
				list[dotIdx].kill();
			}
		}
	},
	removeByNameFunc: function(list, info) {
		for (var dotIdx=list.length-1; dotIdx>-1; dotIdx--) {
			if (list[dotIdx].spcName==info.spcName) {
				list.splice(dotIdx, 1);
				list[dotIdx].kill();
			}
		}
	},
	removeByNameAndTagFunc: function(list, info) {
		for (var dotIdx=list.length-1; dotIdx>-1; dotIdx--) {
			if (list[dotIdx].tag==info.tag) {
				list.splice(dotIdx, 1);
				list[dotIdx].kill();
			}
		}
	},
	execAllCombos: function(listFunc, dot) {
		if (dot instanceof Array && dot.length) {
			var dots = dot;
			var info = {spcName: dots[0].spcName, tag: dots[0].tag};
		} else {
			var info = dot;
		}
		var lists = this.getRelevantLists(info);
		if (dots) {
			for (var dotIdx=0; dotIdx<dots.length; dotIdx++) {
				this.execFuncOnLists(listFunc, lists, dots[dotIdx]);
			}
		} else if (dot instanceof Dot) {
			this.execFuncOnLists(listFunc, lists, dot);
		}
	},
	execFuncOnLists: function(func, lists, dot) {
		dot.active = true;
		for (var listIdx=0; listIdx<lists.length; listIdx++) {
			func(lists[listIdx], dot);
		}
	},
	getRelevantLists: function(info) {
		var lists = [];
		lists.push(this.lists.ALLDOTS);
		if (info.spcName && info.tag) {
			lists.push(this.getByNameAndTag(info));
		}
		if (info.spcName) {
			lists.push(this.getByName(info.spcName));
		}
		if (info.tag) {
			lists.push(this.getByTag(info.tag));
		}
		return lists;
	},

	getByNameAndTag: function(info) {
		if (this.lists[info.spcName + '-' + info.tag]) {
			return this.lists[info.spcName + '-' + info.tag];
		} else if (spcs[info.spcName]) {
			this.lists[info.spcName + '-' + info.tag] = [];
			return this.lists[info.spcName + '-' + info.tag];
		} else {
			console.log('Tried to get bad spcName ' + spcName);
			console.trace();
		}
	},
	getByName: function(spcName) {
		if (this.lists[spcName]) {
			return this.lists[spcName];
		} else if (spcs[spcName]) {
			this.lists[spcName] = [];
			return this.lists[spcName];
		} else {
			console.log('Tried to get bad spcName ' + spcName);
			console.trace();
		}
	},
	getByTag: function(tag) {
		if (this.lists[tag]){
			return this.lists[tag];
		} else {
			this.lists[tag] = [];
			return this.lists[tag];
		}
	},

}<commit_msg>Solved the case of the undefined variable<commit_after>/*
Copyright (C) 2013  Daniel Reid

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    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.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

function DotManager() {
	this.lists = {ALLDOTS:[]};
	this.spcLists = {};
	this.count = 0;
}

DotManager.prototype = {
//start public funcs
	add: function(dot) {//can send as list or single dot
		if (dot instanceof Array) {
			this.count += dot.length;
		} else {
			this.count ++;
		}
		this.execAllCombos(this.addFunc, dot);
	},
	remove: function(dot, deactiveDots) {//can send as list or single dot
		deactivateDots = deactiveDots === undefined ? true : deactiveDots;
		if (dot instanceof Array) {
			this.count -= dot.length;
			for (var dotIdx=0; dotIdx<dot.length;dotIdx++) {
				dot[dotIdx].kill(deactivateDots);
			}
		} else {
			this.count --;
			dot.kill(deactivateDots);
		}
	},
	removeByAttr: function(attr, val) {
		var dots = this.lists.ALLDOTS;
		for (var i=dots.length-1; i>=0; i--) {
			if (dots[i][attr] == val) dots[i].kill();
		}
	},
	changeDotSpc: function(dots, newSpcName) {//can send as list or single dot
		if (!(dots instanceof Array)) dots = [dots];
		var def = spcs[newSpcName];
		for (var dotIdx=0; dotIdx<dots.length; dotIdx++) {
			var dot = dots[dotIdx];
			var tempF = (dot.hF298 - (def.hF298 * 1000 / N) + dot.cv * (dot.temp() - 298.15)) / (def.cv / N) + 298.15;
			if (tempF > 0) {
				for (var parentListIdx=0; parentListIdx<dot.parentLists.length; parentListIdx++) {
					dot.parentLists[parentListIdx].splice(dot.parentLists[parentListIdx].indexOf(dot), 1);
				}
				dot.parentLists = [];
				dot.m = def.m;
				dot.r = def.r;
				dot.col = def.col;
				dot.spcName = def.spcName;
				dot.hF298 = def.hF298 * 1000 / N;
				dot.hVap298 = def.hVap298 * 1000 / N;
				dot.idNum = def.idNum;
				dot.cvKinetic = 1.5 * R / N;
				dot.cv = def.cv / N;
				dot.cp = dot.cv + R;
				dot.cpLiq = def.cpLiq / N;
				dot.spcVolLiq = def.spcVolLiq / N;
				dot.setTempNoReference(tempF);

				var newLists = this.getRelevantLists(dot);
				for (var newListIdx=0; newListIdx<newLists.length; newListIdx++) {
					dot.parentLists.push(newLists[newListIdx]);
					newLists[newListIdx].push(dot);
				}
			}
		}

	},
	changeDotWall: function(dots, newWallHandle) {
		var j, jj;
		if (!(dots instanceof Array)) dots = [dots];
		for (var i=0; i<dots.length; i++) {
			var dot = dots[i];
			dot.tag = newWallHandle;
			dot.returnTo = newWallHandle;
			for (j=0, jj=dot.parentLists.length; j<jj; j++) {
				dot.parentLists[j].splice(dot.parentLists[j].indexOf(dot), 1);
			}
			dot.parentLists = [];
			var newLists = this.getRelevantLists(dot);
			for (j=0, jj=newLists.length; j<jj; j++) {
				dot.parentLists.push(newLists[j]);
				newLists[j].push(dot);
			}
		}
	},
	addSpcs: function(name) {
		if (!this.lists[name]) {
			this.lists[name] = [];
			this.spcLists[name] = this.lists[name];
		}
		return this.lists[name];
	},
	removeByInfo: function(info) {
		if (info.spcName && info.tag) {
			this.execAllCombos(this.removeByNameAndTagFunc, info);
		} else if (info.spcName){
			this.execAllCombos(this.removeByNameFunc, info);
		} else if (info.tag) {
			this.execAllCombos(this.removeByTagFunc, info);
		} else {
			console.log('No useful info given to removeByInfo func in DotManager');
			console.trace();
		}
	},
	getWithLog: function(info) {
		var gotten = this.get(info);
		if (gotten) {
			return gotten
		} else {
			console.log('Bad species data');
			console.log(info);
		}
	},
	get: function(info) {
		return this.createIfNotExists(info);
		// if (info) {
			// if (info.spcName && info.tag) {
				// return this.lists[info.spcName + '-' + info.tag];
			// } else if (info.spcName) {
				// return this.lists[info.spcName];
			// } else if (info.tag) {
				// return this.lists[info.tag];
			// }
		// } else {
			// return this.lists.ALLDOTS;
		// }
	},
	clearAll: function() {
		for (var list in this.lists) {
			this.lists[list].splice(0, this.lists[list].length);
		}
	},
	createIfNotExists: function(info) {
		if (info) {
			if (info.spcName && info.tag) {
				return this.getByNameAndTag(info);
			} else if (info.spcName) {
				return this.getByName(info.spcName);
			} else if (info.tag) {
				return this.getByTag(info.tag);
			}
		} else {
			return this.lists.ALLDOTS;
		}
	},

//end public funcs
	addFunc: function(list, dot) {
		list.push(dot);
		dot.parentLists.push(list);
	},
	removeFunc: function(list, dot) {
		var idx = list.indexOf(dot);
		if (idx>-1) {
			list.splice(idx, 1);
			dot.parentLists.splice(dot.parentLists.indexOf(list), 1);
		} else {
			console.log('Tried to remove dot from global list of spcName ' + dot.spcName + ' and tag ' + dot.tag + '. Dot not present.');
			console.trace();
		}
	},
	removeByNameAndTagFunc: function(list, info) {
		for (var dotIdx=list.length-1; dotIdx>-1; dotIdx--) {
			if (list[dotIdx].spcName==info.spcName && list[dotIdx].tag==info.tag) {
				list[dotIdx].kill();
			}
		}
	},
	removeByNameFunc: function(list, info) {
		for (var dotIdx=list.length-1; dotIdx>-1; dotIdx--) {
			if (list[dotIdx].spcName==info.spcName) {
				list.splice(dotIdx, 1);
				list[dotIdx].kill();
			}
		}
	},
	removeByNameAndTagFunc: function(list, info) {
		for (var dotIdx=list.length-1; dotIdx>-1; dotIdx--) {
			if (list[dotIdx].tag==info.tag) {
				list.splice(dotIdx, 1);
				list[dotIdx].kill();
			}
		}
	},
	execAllCombos: function(listFunc, dot) {
		if (dot instanceof Array && dot.length) {
			var dots = dot;
			var info = {spcName: dots[0].spcName, tag: dots[0].tag};
		} else {
			var info = dot;
		}
		var lists = this.getRelevantLists(info);
		if (dots) {
			for (var dotIdx=0; dotIdx<dots.length; dotIdx++) {
				this.execFuncOnLists(listFunc, lists, dots[dotIdx]);
			}
		} else if (dot instanceof Dot) {
			this.execFuncOnLists(listFunc, lists, dot);
		}
	},
	execFuncOnLists: function(func, lists, dot) {
		dot.active = true;
		for (var listIdx=0; listIdx<lists.length; listIdx++) {
			func(lists[listIdx], dot);
		}
	},
	getRelevantLists: function(info) {
		var lists = [];
		lists.push(this.lists.ALLDOTS);
		if (info.spcName && info.tag) {
			lists.push(this.getByNameAndTag(info));
		}
		if (info.spcName) {
			lists.push(this.getByName(info.spcName));
		}
		if (info.tag) {
			lists.push(this.getByTag(info.tag));
		}
		return lists;
	},

	getByNameAndTag: function(info) {
		if (this.lists[info.spcName + '-' + info.tag]) {
			return this.lists[info.spcName + '-' + info.tag];
		} else if (spcs[info.spcName]) {
			this.lists[info.spcName + '-' + info.tag] = [];
			return this.lists[info.spcName + '-' + info.tag];
		} else {
			console.log('Tried to get bad spcName ' + spcName);
			console.trace();
		}
	},
	getByName: function(spcName) {
		if (this.lists[spcName]) {
			return this.lists[spcName];
		} else if (spcs[spcName]) {
			this.lists[spcName] = [];
			return this.lists[spcName];
		} else {
			console.log('Tried to get bad spcName ' + spcName);
			console.trace();
		}
	},
	getByTag: function(tag) {
		if (this.lists[tag]){
			return this.lists[tag];
		} else {
			this.lists[tag] = [];
			return this.lists[tag];
		}
	},

}<|endoftext|>


<commit_before>import reactProps from 'react-attrs-map';

import MixinPropsFilter from '#_props-filter?raw';

const inputOnlyProps = reactProps('input');

export default Base => class extends Base {
    static get displayName() {
        return 'core: input';
    }

    static get mixins() {
        return [ MixinPropsFilter ];
    }

    constructor(props) {
        super(props);

        this.state = {
            value: props.value || '',
            focused: false,
            hovered: false
        };
    }

    componentWillReceiveProps({ value }) {
        if (this.props.value !== value) {
            this.setState({
                value
            });
        }
    }

    _onInputChange(e) {
        this.setState({
            value: e.target.value
        });

        if (this.props.onChange) {
            this.props.onChange(e);
        }
    }

    _onInputFocus(e) {
        this.setState({
            focused: true
        });

        if (this.props.onFocus) {
            this.props.onFocus(e);
        }
    }

    _onInputBlur(e) {
        this.setState({
            focused: false
        });

        if (this.props.onBlur) {
            this.props.onBlur(e);
        }
    }

    _onInputMouseEnter(e) {
        this.setState({
            hovered: true
        });

        if (this.props.onMouseEnter) {
            this.props.onMouseEnter(e);
        }
    }

    _onInputMouseLeave(e) {
        this.setState({
            hovered: false
        });

        if (this.props.onMouseLeave) {
            this.props.onMouseLeave(e);
        }
    }

    val() {
        return this.state.value;
    }

    render() {
        return {
            block: 'input',
            tag: 'label',
            mods: {
                focused: this.state.focused,
                hovered: this.state.hovered,
                disabled: this.props.disabled || false
            },
            props: this._propsExclude(inputOnlyProps),
            content: [
                {
                    elem: 'control',
                    tag: 'input',
                    props: {
                        type: 'text',
                        ...this._propsFrom(inputOnlyProps),
                        value: this.state.value,
                        onChange: ::this._onInputChange,
                        onFocus: ::this._onInputFocus,
                        onBlur: ::this._onInputBlur,
                        onMouseLeave: ::this._onInputMouseLeave,
                        onMouseEnter: ::this._onInputMouseEnter,
                        ref: 'control',
                        key: 'control'
                    }
                },
                ...[ this.props.children ]
            ]
        };
    }
};
<commit_msg>:heavy_plus_sign: `val(newValue)` for Input<commit_after>import reactProps from 'react-attrs-map';

import MixinPropsFilter from '#_props-filter?raw';

const inputOnlyProps = reactProps('input');

export default Base => class extends Base {
    static get displayName() {
        return 'core: input';
    }

    static get mixins() {
        return [ MixinPropsFilter ];
    }

    constructor(props) {
        super(props);

        this.state = {
            value: props.value || '',
            focused: false,
            hovered: false
        };
    }

    componentWillReceiveProps({ value }) {
        if (this.props.value !== value) {
            this.setState({
                value
            });
        }
    }

    _onInputChange(e) {
        this.setState({
            value: e.target.value
        });

        if (this.props.onChange) {
            this.props.onChange(e);
        }
    }

    _onInputFocus(e) {
        this.setState({
            focused: true
        });

        if (this.props.onFocus) {
            this.props.onFocus(e);
        }
    }

    _onInputBlur(e) {
        this.setState({
            focused: false
        });

        if (this.props.onBlur) {
            this.props.onBlur(e);
        }
    }

    _onInputMouseEnter(e) {
        this.setState({
            hovered: true
        });

        if (this.props.onMouseEnter) {
            this.props.onMouseEnter(e);
        }
    }

    _onInputMouseLeave(e) {
        this.setState({
            hovered: false
        });

        if (this.props.onMouseLeave) {
            this.props.onMouseLeave(e);
        }
    }

    val(newValue) {
        if (typeof newValue !== 'undefined') {
            this.setState({
                value: newValue
            });
        } else {
            return this.state.value;
        }
    }

    render() {
        return {
            block: 'input',
            tag: 'label',
            mods: {
                focused: this.state.focused,
                hovered: this.state.hovered,
                disabled: this.props.disabled || false
            },
            props: this._propsExclude(inputOnlyProps),
            content: [
                {
                    elem: 'control',
                    tag: 'input',
                    props: {
                        type: 'text',
                        ...this._propsFrom(inputOnlyProps),
                        value: this.state.value,
                        onChange: ::this._onInputChange,
                        onFocus: ::this._onInputFocus,
                        onBlur: ::this._onInputBlur,
                        onMouseLeave: ::this._onInputMouseLeave,
                        onMouseEnter: ::this._onInputMouseEnter,
                        ref: 'control',
                        key: 'control'
                    }
                },
                ...[ this.props.children ]
            ]
        };
    }
};
<|endoftext|>


<commit_before>import React, { PureComponent, PropTypes } from 'react';
import { M, InputGroup, LogoSpinner, Legend, Button, Option,
	ErrorMsg, ServerErrorMsg, DateOfBirth, Countries } from 'binary-components';
import { api } from '../_data/LiveData';
import storage from '../_store/storage';
import SecretQuestion from './SecretQuestion';

export default class UpgradeCard extends PureComponent {

	static contextTypes = {
		router: PropTypes.object.isRequired,
	}

	static propTypes = {
        residenceList: PropTypes.array,
	};

	constructor(props) {
		super(props);
		this.state = {
			progress: false,
			validatedOnce: '',
			salutation: 'Mr',
			firstName: '',
			lastName: '',
			residence: '',
			addressCity: '',
			addressLine1: '',
			phone: '',
			secretQuestion: '',
			secretAnswer: '',
		};
	}

	onEntryChange = e =>
        this.setState({ [e.target.id]: e.target.value });

	onFirstNameValid = firstName =>
		/^[a-zA-Z\s'.-]{2,30}$/.test(firstName);

	onLastNameValid = lastName =>
		/^[a-zA-Z\s'.-]{2,30}$/.test(lastName);

	onDayChange = e =>
		this.setState({ day: e.target.value });

	onMonthChange = e =>
		this.setState({ month: e.target.value });

	onYearChange = e =>
		this.setState({ year: e.target.value });

	onCountryChange = e =>
		this.setState({ residence: e.target.value });

	onStateChange = e =>
		this.setState({ addressState: e.target.value });

	onCityChange = e =>
		this.setState({ addressCity: e.target.value });

	onPostcodeChange = e =>
		this.setState({ addressPostcode: e.target.value });

	onAddressLine1Change = e =>
		this.setState({ addressLine1: e.target.value });

	onAddressLine2Change = e =>
		this.setState({ addressLine2: e.target.value });

	onPhoneChange = e =>
		this.setState({ phone: e.target.value });

	onSecretQuestionChange = e =>
		this.setState({ secretQuestion: e.target.value });

	onSecretAnswerChange = e =>
		this.setState({ secretAnswer: e.target.value });

	onTermsAndConditionsChanged = e =>
		this.setState({ termsAndConditions: e.target.value });

    onFormSubmit = e => {
        e.preventDefault();
        this.setState({
            validatedOnce: true,
        });
        if (this.allValid) {
            this.performUpgrade();
        }
    }

    performUpgrade = async () => {
        const { salutation, firstName, lastName, residence,
			addressLine1, addressLine2, addressCity, addressState,
			addressPostcode, secretQuestion, secretAnswer, phone } = this.state;

        try {
            this.setState({
                progress: true,
                serverError: false,
            });
            const response = await api.createRealAccount({
                salutation,
				first_name: firstName,
				last_name: lastName,
				date_of_birth: '1980-01-31',
				residence,
				address_line_1: addressLine1,
				address_line_2: addressLine2,
				address_city: addressCity,
				address_state: addressState,
				address_postcode: addressPostcode,
				phone,
				secret_question: secretQuestion,
				secret_answer: secretAnswer,
            });
			storage.setItem('account', JSON.stringify({ token: response.new_account_real.oauth_token }));
            window.location = '/';
        } catch (e) {
            this.setState({ serverError: e.error.error.message });
        } finally {
            this.setState({
                progress: false,
            });
        }
    }

	render() {
		const { firstName, lastName, residence, addressLine1, addressCity, secretQuestion, secretAnswer,
			phone, termsAndConditions, progress, serverError, validatedOnce } = this.state;
		const { residenceList } = this.props;

		const firstNameIsValid = firstName.length >= 2;
		const lastNameIsValid = lastName.length >= 2;
		const residenceIsValid = residence.length > 0;
		const addressCityIsValid = addressCity.length > 0;
		const addressLine1IsValid = addressLine1.length > 0;
		const phoneIsValid = phone.length >= 6;
		const secretQuestionIsValid = secretQuestion.length > 0;
		const secretAnswerIsValid = secretAnswer.length > 0;
		this.allValid = firstNameIsValid && lastNameIsValid && residenceIsValid &&
			addressCityIsValid && addressLine1IsValid && phoneIsValid &&
			secretQuestionIsValid && secretAnswerIsValid && termsAndConditions;

		return (

					<LogoSpinner spinning={progress} />

				{serverError && <ServerErrorMsg text={serverError} />}
				<form onSubmit={this.onFormSubmit}>
					<Legend text="Personal Information" />

						<select id="salutation" onChange={this.onEntryChange}>
							<Option value="Mr" text="Mr" />
							<Option value="Mrs" text="Mrs" />
							<Option value="Ms" text="Ms" />
							<Option value="Miss" text="Miss" />
						</select>
						<InputGroup
							id="firstName"
							placeholder="First Name"
							type="text"
							onChange={this.onEntryChange}
							maxLength="30"
						/>
						<InputGroup
							id="lastName"
							placeholder="Last Name"
							type="text"
							onChange={this.onEntryChange}
							maxLength="30"
						/>

					{validatedOnce && !(firstNameIsValid && lastNameIsValid) &&
						<ErrorMsg text="Enter your first and last name" />
					}

						<DateOfBirth
							onDayChange={this.onDayChange}
							onMonthChange={this.onMonthChange}
							onYearChange={this.onYearChange}
						/>

					<Legend text="Home Address" />

						<Countries onChange={this.onCountryChange} residenceList={residenceList} />
						<select onChange={this.onStateChange}>
							{[].map(x => (
								<option key={x.value} value={x.value}>{x.text}</option>
							))}
						</select>

					{validatedOnce && !residenceIsValid &&
						<ErrorMsg text="Choose your country" />
					}

						<InputGroup
							name="AddressTown"
							placeholder="Town/City"
							type="text"
							maxLength="35"
							onChange={this.onCityChange}
						/>
						<InputGroup
							name="AddressPostcode"
							placeholder="Postal Code / ZIP"
							type="text"
							maxLength="20"
							onChange={this.onPostcodeChange}
						/>

					{validatedOnce && !addressCityIsValid &&
						<ErrorMsg text="City must not be empty" />
					}

						<InputGroup
							name="Address1"
							placeholder="Address First Line"
							type="text"
							maxLength="70"
							onChange={this.onAddressLine1Change}
						/>

					{validatedOnce && !addressLine1IsValid &&
						<ErrorMsg text="Address must not be empty" />
					}

						<InputGroup
							name="Address2"
							placeholder="Address Second Line"
							type="text"
							maxLength="70"
							onChange={this.onAddressLine2Change}
						/>

						<InputGroup
							name="Tel"
							placeholder="Phone"
							type="tel"
							maxLength="35"
							onChange={this.onPhoneChange}
						/>

					{validatedOnce && !phoneIsValid &&
						<ErrorMsg text="Enter a valid phone number" />
					}
					<Legend text="Security" />

						<SecretQuestion onChange={this.onSecretQuestionChange} />
						<InputGroup
							name="secretanswer"
							placeholder="Answer To Secret Question"
							type="text"
							maxLength="50"
							onChange={this.onSecretAnswerChange}
						/>

					{validatedOnce && !secretQuestionIsValid &&
						<ErrorMsg text="Select a secret question" />
					}
					{validatedOnce && !secretAnswerIsValid &&
						<ErrorMsg text="Secret answer must be at least 4 characters" />
					}

							<input
								id="tnc"
								name="tnc"
								type="checkbox"
								onClick={this.onTermsAndConditionsChanged}
							/>
							<M m="I agree to the" />

								<M m="terms and conditions" />

					{validatedOnce && !termsAndConditions &&
						<ErrorMsg text="You need to agree to our Terms and Conditions" />
					}
					<Button disabled={progress || validatedOnce && !this.allValid} text="Open Account" />
				</form>

		);
	}
}
<commit_msg>Load states from server for selected country<commit_after>import React, { PureComponent, PropTypes } from 'react';
import { M, InputGroup, LogoSpinner, Legend, Button, Option,
	ErrorMsg, ServerErrorMsg, DateOfBirth, Countries } from 'binary-components';
import { api } from '../_data/LiveData';
import storage from '../_store/storage';
import SecretQuestion from './SecretQuestion';

export default class UpgradeCard extends PureComponent {

	static contextTypes = {
		router: PropTypes.object.isRequired,
	}

	static propTypes = {
        residenceList: PropTypes.array,
	};

	constructor(props) {
		super(props);
		this.state = {
			progress: false,
			validatedOnce: '',
			salutation: 'Mr',
			firstName: '',
			lastName: '',
			residence: '',
			addressCity: '',
			addressLine1: '',
			phone: '',
			secretQuestion: '',
			secretAnswer: '',
			statesList: [],
		};
	}

	onEntryChange = e =>
        this.setState({ [e.target.id]: e.target.value });

	onFirstNameValid = firstName =>
		/^[a-zA-Z\s'.-]{2,30}$/.test(firstName);

	onLastNameValid = lastName =>
		/^[a-zA-Z\s'.-]{2,30}$/.test(lastName);

	onDayChange = e =>
		this.setState({ day: e.target.value });

	onMonthChange = e =>
		this.setState({ month: e.target.value });

	onYearChange = e =>
		this.setState({ year: e.target.value });

	onCountryChange = e => {
		this.setState({ residence: e.target.value });
		api.getStatesForCountry(e.target.value).then(response =>
			this.setState({ statesList: response.states_list })
		);
	}

	onStateChange = e => {
		this.setState({ addressState: e.target.value });
	}

	onCityChange = e =>
		this.setState({ addressCity: e.target.value });

	onPostcodeChange = e =>
		this.setState({ addressPostcode: e.target.value });

	onAddressLine1Change = e =>
		this.setState({ addressLine1: e.target.value });

	onAddressLine2Change = e =>
		this.setState({ addressLine2: e.target.value });

	onPhoneChange = e =>
		this.setState({ phone: e.target.value });

	onSecretQuestionChange = e =>
		this.setState({ secretQuestion: e.target.value });

	onSecretAnswerChange = e =>
		this.setState({ secretAnswer: e.target.value });

	onTermsAndConditionsChanged = e =>
		this.setState({ termsAndConditions: e.target.value });

    onFormSubmit = e => {
        e.preventDefault();
        this.setState({
            validatedOnce: true,
        });
        if (this.allValid) {
            this.performUpgrade();
        }
    }

    performUpgrade = async () => {
        const { salutation, firstName, lastName, residence,
			addressLine1, addressLine2, addressCity, addressState,
			addressPostcode, secretQuestion, secretAnswer, phone } = this.state;

        try {
            this.setState({
                progress: true,
                serverError: false,
            });
            const response = await api.createRealAccount({
                salutation,
				first_name: firstName,
				last_name: lastName,
				date_of_birth: '1980-01-31',
				residence,
				address_line_1: addressLine1,
				address_line_2: addressLine2,
				address_city: addressCity,
				address_state: addressState,
				address_postcode: addressPostcode,
				phone,
				secret_question: secretQuestion,
				secret_answer: secretAnswer,
            });
			storage.setItem('account', JSON.stringify({ token: response.new_account_real.oauth_token }));
            window.location = '/';
        } catch (e) {
            this.setState({ serverError: e.error.error.message });
        } finally {
            this.setState({
                progress: false,
            });
        }
    }

	render() {
		const { firstName, lastName, residence, addressLine1, addressCity, secretQuestion, secretAnswer,
			phone, termsAndConditions, progress, serverError, validatedOnce, statesList } = this.state;
		const { residenceList } = this.props;

		const firstNameIsValid = firstName.length >= 2;
		const lastNameIsValid = lastName.length >= 2;
		const residenceIsValid = residence.length > 0;
		const addressCityIsValid = addressCity.length > 0;
		const addressLine1IsValid = addressLine1.length > 0;
		const phoneIsValid = phone.length >= 6;
		const secretQuestionIsValid = secretQuestion.length > 0;
		const secretAnswerIsValid = secretAnswer.length > 0;
		this.allValid = firstNameIsValid && lastNameIsValid && residenceIsValid &&
			addressCityIsValid && addressLine1IsValid && phoneIsValid &&
			secretQuestionIsValid && secretAnswerIsValid && termsAndConditions;

		return (

					<LogoSpinner spinning={progress} />

				{serverError && <ServerErrorMsg text={serverError} />}
				<form onSubmit={this.onFormSubmit}>
					<Legend text="Personal Information" />

						<select id="salutation" onChange={this.onEntryChange}>
							<Option value="Mr" text="Mr" />
							<Option value="Mrs" text="Mrs" />
							<Option value="Ms" text="Ms" />
							<Option value="Miss" text="Miss" />
						</select>
						<InputGroup
							id="firstName"
							placeholder="First Name"
							type="text"
							onChange={this.onEntryChange}
							maxLength="30"
						/>
						<InputGroup
							id="lastName"
							placeholder="Last Name"
							type="text"
							onChange={this.onEntryChange}
							maxLength="30"
						/>

					{validatedOnce && !(firstNameIsValid && lastNameIsValid) &&
						<ErrorMsg text="Enter your first and last name" />
					}

						<DateOfBirth
							onDayChange={this.onDayChange}
							onMonthChange={this.onMonthChange}
							onYearChange={this.onYearChange}
						/>

					<Legend text="Home Address" />

						<Countries onChange={this.onCountryChange} residenceList={residenceList} />
						<select onChange={this.onStateChange}>
							{statesList.map(x => (
								<option key={x.value} value={x.value}>{x.text}</option>
							))}
						</select>

					{validatedOnce && !residenceIsValid &&
						<ErrorMsg text="Choose your country" />
					}

						<InputGroup
							name="AddressTown"
							placeholder="Town/City"
							type="text"
							maxLength="35"
							onChange={this.onCityChange}
						/>
						<InputGroup
							name="AddressPostcode"
							placeholder="Postal Code / ZIP"
							type="text"
							maxLength="20"
							onChange={this.onPostcodeChange}
						/>

					{validatedOnce && !addressCityIsValid &&
						<ErrorMsg text="City must not be empty" />
					}

						<InputGroup
							name="Address1"
							placeholder="Address First Line"
							type="text"
							maxLength="70"
							onChange={this.onAddressLine1Change}
						/>

					{validatedOnce && !addressLine1IsValid &&
						<ErrorMsg text="Address must not be empty" />
					}

						<InputGroup
							name="Address2"
							placeholder="Address Second Line"
							type="text"
							maxLength="70"
							onChange={this.onAddressLine2Change}
						/>

						<InputGroup
							name="Tel"
							placeholder="Phone"
							type="tel"
							maxLength="35"
							onChange={this.onPhoneChange}
						/>

					{validatedOnce && !phoneIsValid &&
						<ErrorMsg text="Enter a valid phone number" />
					}
					<Legend text="Security" />

						<SecretQuestion onChange={this.onSecretQuestionChange} />
						<InputGroup
							name="secretanswer"
							placeholder="Answer To Secret Question"
							type="text"
							maxLength="50"
							onChange={this.onSecretAnswerChange}
						/>

					{validatedOnce && !secretQuestionIsValid &&
						<ErrorMsg text="Select a secret question" />
					}
					{validatedOnce && !secretAnswerIsValid &&
						<ErrorMsg text="Secret answer must be at least 4 characters" />
					}

							<input
								id="tnc"
								name="tnc"
								type="checkbox"
								onClick={this.onTermsAndConditionsChanged}
							/>
							<M m="I agree to the" />

								<M m="terms and conditions" />

					{validatedOnce && !termsAndConditions &&
						<ErrorMsg text="You need to agree to our Terms and Conditions" />
					}
					<Button disabled={progress || validatedOnce && !this.allValid} text="Open Account" />
				</form>

		);
	}
}
<|endoftext|>


<commit_before>"use strict";

// Like in all other modules in case this is the first lib loaded we have to define it:
var jQInit = jQInit || [];

/**
 * Module for initializing jQuery plugins
 *
 * In the beginning jQInit is an array of the form:
 * [ [ 'Module' [, 'Dependency', ... ], creator ], ... ]
 *
 * this will be converted by init to:
 *
 * jQInit.Module = { object returned by creatorFunction }
 *
 * The old array is stored as private _jQInit internally
 * ...
 */

// Like module pattern
var jQInit = (function( _jQInit ) {

	// Now here we have:
	//   jQInit: This having jQInit.Module the actual module
	//  _jQInit: The old array having the descriptions

	var $, jQInit = {

			// Push a new Module description
			push: function( description ) {
				_jQInit.push( description );
				onPush();
			},

			// Register an otherwise created module.
			// This is used for jqinit.loader.js to provide dependencies
			register: function( name, module ){
				jQInit[ name ] = module;
				onPush(); // Allow other modules to initialize
			}
		}
		;

	function createModule( modDesc ){

		// find name and creator
		var name = modDesc[ 0 ]; // first
		var creator = modDesc[ modDesc.length-1 ]; // last

		// collect dependencies
		var mods = []
		for( var i=2; i<modDesc.length-1; i++ ){
			var dep = jQInit[ modDesc[ i ] ];
			if( ! dep ) return false;
			mods.push( dep );
		}

		// jQuery is always first arg for creator
		mods.unshift( $ );

		// Call creator and store result in jQInit assoc.
		// An empty map is stored it nothing else is returned
		jQInit[ name ] = creator.apply( null, mods ) || {};

		return true;
	}

	function createModules() {

		var waiting,
			done = _jQInit;

		// All modules in array
		while( done.length ){

			done = [],
			waiting = [];

			while( _jQInit.length ){

				var modDesc = _jQInit.shift();

				var ok = createModule( modDesc );

				//console.debug( ok, modDesc );

				if( ok ) done.push( modDesc );
				else waiting.push( modDesc );
			}
			_jQInit = waiting;
		}
	}

	// Called for every new module loaded and pushed
	function onPush() {
		if( $ ) createModules();
	}

	// Called once when jQuery is loaded
	function onJQuery() {
		$ = window.jQuery;
		createModules();
	}

	// Poll to see if jQuery is ready
	function waitForJQuery() {

		if( window.jQuery ){
			onJQuery();
		} else {
			setTimeout( waitForJQuery, 20 );
		}
	}

	waitForJQuery();

	return jQInit;

} )( jQInit );
<commit_msg>Bugfix<commit_after>"use strict";

// Like in all other modules in case this is the first lib loaded we have to define it:
var jQInit = jQInit || [];

/**
 * Module for initializing jQuery plugins
 *
 * In the beginning jQInit is an array of the form:
 * [ [ 'Module' [, 'Dependency', ... ], creator ], ... ]
 *
 * this will be converted by init to:
 *
 * jQInit.Module = { object returned by creatorFunction }
 *
 * The old array is stored as private _jQInit internally
 * ...
 */

// Like module pattern
var jQInit = (function( _jQInit ) {

	// Now here we have:
	//   jQInit: This having jQInit.Module the actual module
	//  _jQInit: The old array having the descriptions

	var $, jQInit = {

			// Push a new Module description
			push: function( description ) {
				_jQInit.push( description );
				onPush();
			},

			// Register an otherwise created module.
			// This is used for jqinit.loader.js to provide dependencies
			register: function( name, module ){
				jQInit[ name ] = module;
				onPush(); // Allow other modules to initialize
			}
		}
		;

	function createModule( modDesc ){

		// find name and creator
		var name = modDesc[ 0 ]; // first
		var creator = modDesc[ modDesc.length-1 ]; // last

		// collect dependencies
		var mods = []
		for( var i=1; i<modDesc.length-1; i++ ){
			var dep = jQInit[ modDesc[ i ] ];
			if( ! dep ) return false;
			mods.push( dep );
		}

		// jQuery is always first arg for creator
		mods.unshift( $ );

		// Call creator and store result in jQInit assoc.
		// An empty map is stored it nothing else is returned
		jQInit[ name ] = creator.apply( null, mods ) || {};

		return true;
	}

	function createModules() {

		var waiting,
			done = _jQInit;

		// All modules in array
		while( done.length ){

			done = [],
			waiting = [];

			while( _jQInit.length ){

				var modDesc = _jQInit.shift();

				var ok = createModule( modDesc );

				//console.debug( ok, modDesc );

				if( ok ) done.push( modDesc );
				else waiting.push( modDesc );
			}
			_jQInit = waiting;
		}
	}

	// Called for every new module loaded and pushed
	function onPush() {
		if( $ ) createModules();
	}

	// Called once when jQuery is loaded
	function onJQuery() {
		$ = window.jQuery;
		createModules();
	}

	// Poll to see if jQuery is ready
	function waitForJQuery() {

		if( window.jQuery ){
			onJQuery();
		} else {
			setTimeout( waitForJQuery, 20 );
		}
	}

	waitForJQuery();

	return jQInit;

} )( jQInit );
<|endoftext|>


<commit_before>jQuery(document).ready(function($) {
    hashrouter(window.location.hash, '.firstactive');
    $(window).bind('hashchange', function() {
        hashrouter(window.location.hash);
    });

    $('.imgspread').click( function ( event ) {
        var img = $(this).find('img') ,
            src = img.attr('src') ,
            href = $(this).attr('href') ;

        img.attr('src', href ) ;
        $(this).attr('href', src ) ;
        event.preventDefault();
    });

    pooraccordion();
});

function pooraccordion(animate) {
    animate = typeof animate !== 'undefined' ? animate : true;
    jQuery('.poor-accordion').hide().prev()
        .css('cursor', 'pointer')
        .click(function() {
            if (true == animate) {
                jQuery(this).next().slideToggle();
            } else {
                jQuery(this).next().toggle();
            }
        }
    );
}

function hashrouter (hash, exception) {
    //hashspliter: prefill "GET parameter"-like value string to inputs

    if ( hash.indexOf('=') !== -1) { // #name=bob&city=springfield&color=green
        var pseudogets = hash.slice('1').split('&');
        for (var i = 0; i < pseudogets.length; i++) {

            var getkeyparam = pseudogets[i].split('=');
            var tagName =  jQuery( '#' + getkeyparam[0] ).prop('tagName'); // check type of html element

            switch ( tagName ) {
                case 'INPUT' :
                    hash2form( getkeyparam );
                break
            }
        }
    } else if ( hash.indexOf('/') !== -1 ) { // #loremipsum/lingues
        var pseudodirs = hash.slice('1').split('/') ;

        for (var i = 0; i < pseudodirs.length; i++) {
            var htmlid = '#' + pseudodirs[i] ;
            var tagName =  jQuery( htmlid ).prop('tagName'); // check type of html element

            // TODO numeric e.g. #/1

            switch ( tagName ) {
                case 'INPUT' :
                    $( htmlid ).attr("checked", true);
                    console.log(htmlid)
                break
                case 'P' :
                case 'DIV' :
                // TODO call this function tab accordeon
                    jQuery( htmlid ).show().click(); // click to use with jQuery UI Accordion etc
                break
            }
        }

    } else { // single value

        switch (hash) {
            case "#alert": // example
                alert('fork me at github.com/klml/usefulclassroomphrases');
            break;
            default:
            case "#":
                // poor mans tab
                //~ jQuery('.hashtagger > div, .hashtabber').not( exception ).hide();
                jQuery(hash).siblings().not( exception ).hide();
                jQuery(hash).show().click(); // click to use with jQuery UI Accordion etc
            break;
        }
    }
}

function hash2form ( getkeyparam ) {
                //~ console.log( getkeyparam );
    jQuery('#' + getkeyparam[0]).val( getkeyparam[1] ); // TODO varabler gesteltane
}

<commit_msg>consl log raus<commit_after>jQuery(document).ready(function($) {
    hashrouter(window.location.hash, '.firstactive');
    $(window).bind('hashchange', function() {
        hashrouter(window.location.hash);
    });

    $('.imgspread').click( function ( event ) {
        var img = $(this).find('img') ,
            src = img.attr('src') ,
            href = $(this).attr('href') ;

        img.attr('src', href ) ;
        $(this).attr('href', src ) ;
        event.preventDefault();
    });

    pooraccordion();
});

function pooraccordion(animate) {
    animate = typeof animate !== 'undefined' ? animate : true;
    jQuery('.poor-accordion').hide().prev()
        .css('cursor', 'pointer')
        .click(function() {
            if (true == animate) {
                jQuery(this).next().slideToggle();
            } else {
                jQuery(this).next().toggle();
            }
        }
    );
}

function hashrouter (hash, exception) {
    //hashspliter: prefill "GET parameter"-like value string to inputs

    if ( hash.indexOf('=') !== -1) { // #name=bob&city=springfield&color=green
        var pseudogets = hash.slice('1').split('&');
        for (var i = 0; i < pseudogets.length; i++) {

            var getkeyparam = pseudogets[i].split('=');
            var tagName =  jQuery( '#' + getkeyparam[0] ).prop('tagName'); // check type of html element

            switch ( tagName ) {
                case 'INPUT' :
                    hash2form( getkeyparam );
                break
            }
        }
    } else if ( hash.indexOf('/') !== -1 ) { // #loremipsum/lingues
        var pseudodirs = hash.slice('1').split('/') ;

        for (var i = 0; i < pseudodirs.length; i++) {
            var htmlid = '#' + pseudodirs[i] ;
            var tagName =  jQuery( htmlid ).prop('tagName'); // check type of html element

            // TODO numeric e.g. #/1

            switch ( tagName ) {
                case 'INPUT' :
                    $( htmlid ).attr("checked", true);
                break
                case 'P' :
                case 'DIV' :
                // TODO call this function tab accordeon
                    jQuery( htmlid ).show().click(); // click to use with jQuery UI Accordion etc
                break
            }
        }

    } else { // single value

        switch (hash) {
            case "#alert": // example
                alert('fork me at github.com/klml/usefulclassroomphrases');
            break;
            default:
            case "#":
                // poor mans tab
                //~ jQuery('.hashtagger > div, .hashtabber').not( exception ).hide();
                jQuery(hash).siblings().not( exception ).hide();
                jQuery(hash).show().click(); // click to use with jQuery UI Accordion etc
            break;
        }
    }
}

function hash2form ( getkeyparam ) {
    jQuery('#' + getkeyparam[0]).val( getkeyparam[1] ); // TODO varabler gesteltane
}

<|endoftext|>


<commit_before>jQuery(document).ready(function($) {
    hashrouter(window.location.hash, '.firstactive');
    $(window).bind('hashchange', function() {
        hashrouter(window.location.hash);
    });

    $('.imgspread').click( function ( event ) {
        var img = $(this).find('img') ,
            src = img.attr('src') ,
            href = $(this).attr('href') ;

        img.attr('src', href ) ;
        $(this).attr('href', src ) ;
        event.preventDefault();
    });

    pooraccordion();
});

function pooraccordion(animate) {
    animate = typeof animate !== 'undefined' ? animate : true;
    jQuery('.poor-accordion').hide().prev()
        .css('cursor', 'pointer')
        .click(function() {
            if (true == animate) {
                jQuery(this).next().slideToggle();
            } else {
                jQuery(this).next().toggle();
            }
        }
    );
}

function hashrouter (hash, exception) {
    //hashspliter: prefill "GET parameter"-like value string to inputs

    if ( hash.indexOf('=') !== -1) { // #name=bob&city=springfield&color=green
        var pseudogets = hash.slice('1').split('&');
        for (var i = 0; i < pseudogets.length; i++) {

            var getkeyparam = pseudogets[i].split('=');
            var tagName =  jQuery( '#' + getkeyparam[0] ).prop('tagName'); // check type of html element

            switch ( tagName ) {
                case 'INPUT' :
                    hash2form( getkeyparam );
                break
            }
        }
    } else if ( hash.indexOf('/') !== -1 ) { // #loremipsum/lingues
        var pseudodirs = hash.slice('1').split('/') ;

        for (var i = 0; i < pseudodirs.length; i++) {
            var htmlid = '#' + pseudodirs[i] ;
            var tagName =  jQuery( htmlid ).prop('tagName'); // check type of html element

            // TODO numeric e.g. #/1

            switch ( tagName ) {
                case 'INPUT' :
                    $( htmlid ).attr("checked", true);
                break
                case 'P' :
                case 'DIV' :
                // TODO call this function tab accordeon
                    jQuery( htmlid ).show().click(); // click to use with jQuery UI Accordion etc
                break
            }
        }

    } else { // single value

        switch (hash) {
            case "#alert": // example
                alert('fork me at github.com/klml/usefulclassroomphrases');
            break;
            default:
            case "#":
                // poor mans tab
                //~ jQuery('.hashtagger > div, .hashtabber').not( exception ).hide();
                jQuery(hash).siblings().not( exception ).hide();
                jQuery(hash).show().click(); // click to use with jQuery UI Accordion etc
            break;
        }
    }
}

function hash2form ( getkeyparam ) {
    jQuery('#' + getkeyparam[0]).val( getkeyparam[1] ); // TODO varabler gesteltane
}

<commit_msg>specfic hashtagger siblings hide non scoped elements<commit_after>jQuery(document).ready(function($) {
    hashrouter(window.location.hash, '.firstactive');
    $(window).bind('hashchange', function() {
        hashrouter(window.location.hash);
    });

    $('.imgspread').click( function ( event ) {
        var img = $(this).find('img') ,
            src = img.attr('src') ,
            href = $(this).attr('href') ;

        img.attr('src', href ) ;
        $(this).attr('href', src ) ;
        event.preventDefault();
    });

    pooraccordion();
});

function pooraccordion(animate) {
    animate = typeof animate !== 'undefined' ? animate : true;
    jQuery('.poor-accordion').hide().prev()
        .css('cursor', 'pointer')
        .click(function() {
            if (true == animate) {
                jQuery(this).next().slideToggle();
            } else {
                jQuery(this).next().toggle();
            }
        }
    );
}

function hashrouter (hash, exception) {
    //hashspliter: prefill "GET parameter"-like value string to inputs

    if ( hash.indexOf('=') !== -1) { // #name=bob&city=springfield&color=green
        var pseudogets = hash.slice('1').split('&');
        for (var i = 0; i < pseudogets.length; i++) {

            var getkeyparam = pseudogets[i].split('=');
            var tagName =  jQuery( '#' + getkeyparam[0] ).prop('tagName'); // check type of html element

            switch ( tagName ) {
                case 'INPUT' :
                    hash2form( getkeyparam );
                break
            }
        }
    } else if ( hash.indexOf('/') !== -1 ) { // #loremipsum/lingues
        var pseudodirs = hash.slice('1').split('/') ;

        for (var i = 0; i < pseudodirs.length; i++) {
            var htmlid = '#' + pseudodirs[i] ;
            var tagName =  jQuery( htmlid ).prop('tagName'); // check type of html element

            // TODO numeric e.g. #/1

            switch ( tagName ) {
                case 'INPUT' :
                    $( htmlid ).attr("checked", true);
                break
                case 'P' :
                case 'DIV' :
                // TODO call this function tab accordeon
                    jQuery( htmlid ).show().click(); // click to use with jQuery UI Accordion etc
                break
            }
        }

    } else { // single value

        switch (hash) {
            case "#alert": // example
                alert('fork me at github.com/klml/usefulclassroomphrases');
            break;
            default:
            case "#":
                // poor mans tab
                jQuery('.hashtagger > div, .hashtabber').not( exception ).hide();
                jQuery(hash).show().click(); // click to use with jQuery UI Accordion etc
            break;
        }
    }
}

function hash2form ( getkeyparam ) {
    jQuery('#' + getkeyparam[0]).val( getkeyparam[1] ); // TODO varabler gesteltane
}

<|endoftext|>


<commit_before>var alphabet = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L"];
var DefaultRawData = {
    Projects: {
        Values: [5000, 6000, 6000, 2000, 6000],
        Returns: [18, 14, 13, 10, 9]
    },
    vCompany: 12000,
    rCompany: [10, 13.25]
};
var DefaultData = MakeDataArray(DefaultRawData);
function FormatBox(type, id) {
    var CurrentValue = $('#' + id).val();
    var NewValue = parseFloat(CurrentValue.replace(/\s/g, ''));
    if (CurrentValue.length > 0 && isNaN(NewValue) === true) {
        $('#' + id).val('');
        $('#modal-label').text('Format');
        $('#modal-body').text('Ayoye, commence par écrire des chiffres...');
        $('#modal-button').text("J'ai compris!");
        $('#modalwindow').modal('show');
        return;
    }
    var ValueStr = String(NewValue);
    var SplitValue = ValueStr.split('.');
    var IntLength = SplitValue[0].length;
    var Decimals = parseFloat('0.' + SplitValue[1]);
    var Spaces = parseInt(IntLength / 3);
    var NumParts = [];
    for (var i = Spaces + 1; i > 0; i--) {
        StartLoc = IntLength - 3;
        NumParts[i] = SplitValue[0].substring(StartLoc, IntLength);
        IntLength = StartLoc;
    }
    var IntPart = NumParts.join(' ');
    var DecString = String(Decimals.toFixed(2));
    var DecPart = DecString.substring(2, 4);
    if (Decimals > 0) {
        var DispValue = IntPart + '.' + DecPart;
    } else {
        var DispValue = IntPart;
    }
    if (type === "d" && CurrentValue.length > 0) {
        $('#' + id).val(DispValue + " $");
    } else if (type === "p" && CurrentValue.length > 0) {
        if (parseInt(CurrentValue) >= 100) {
            $('#' + id).val('');
            $('#modal-label').text('Coût en capital');
            $('#modal-body').text('Ton shit est trop rentable bro!');
            $('#modal-button').text("J'ai compris!");
            $('#modalwindow').modal('show');

        } else {
            $('#' + id).val(DispValue + " %");
        }
    }
}
function AddLine() {
    var lastid = parseInt($('#ProjectsTable tr:last').data("projectid"));
    var newid = lastid + 1;
    if (newid >= 12) {
        $('#modal-label').text('Limite');
        $('#modal-body').text('Le nombre de projets est limité à 12. Sorry!');
        $('#modal-button').text("J'ai compris!");
        $('#modalwindow').modal('show');
    } else {
        $('#ProjectsTable tr:last').after('
' + alphabet[newid] + '
<input type="text" class="form-control investment textfield" id="I' + newid + '" onfocusout="FormatBox(\'d\',\'I' + newid + '\')" autocomplete="off">

<input type="text" class="form-control return textfield" id="R' + newid + '" onfocusout="FormatBox(\'p\',\'R' + newid + '\')" autocomplete="off">
<button class="btn btn-danger" onclick="RemoveLine()" id="remove' + newid + '"></button>
');
        $('#remove' + lastid).hide();
    }
}
function RemoveLine() {
    var lastid = parseInt($('#ProjectsTable tr:last').data("projectid"));
    var newid = lastid - 1;
    $('#ProjectsTable tr:last').remove();
    $('#remove' + newid).show();
}
function DataForm() {
    var ProjectValue = document.getElementsByClassName("investment");
    var ProjectReturn = document.getElementsByClassName("return");
    var ProjectValues = [];
    var ProjectReturns = [];
    for (i = 0; i < ProjectValue.length; i++) {
        ProjectValues[i] = parseFloat(ProjectValue[i].value.replace(/\s/g, '')) / 1000;
        ProjectReturns[i] = parseFloat(ProjectReturn[i].value);
    }
    var CompanyMaxInvestment = parseFloat(document.getElementById("MI").value.replace(/\s/g, '')) / 1000;
    var CompanyCCArray = [parseFloat(document.getElementById("CC1").value), parseFloat(document.getElementById("CC2").value)];
    var NewData = {
        Projects: {
            Values: ProjectValues,
            Returns: ProjectReturns
        },
        vCompany: CompanyMaxInvestment,
        rCompany: CompanyCCArray
    };
    return NewData
}
function MakeDataArray(dataArray) {
    var projectdata = [];
    var nbProjects = dataArray["Projects"]["Values"].length;
    var cost = 0;
    for (var i = 0; i <= nbProjects - 1; i++) {
        projectdata.push({
            "datagroup": "Project" + i,
            "financing": cost,
            "kcost": dataArray["Projects"]["Returns"][i],
            "type": "project",
            "label": alphabet[i]
        });
        cost = cost + dataArray["Projects"]["Values"][i];
        projectdata.push({
            "datagroup": "Project" + i,
            "financing": cost,
            "kcost": dataArray["Projects"]["Returns"][i],
            "type": "interp",
            "label": alphabet[i]
        });
        if (i > 0) {
            projectdata.push({
                "datagroup": "Interval" + i,
                "financing": cost - dataArray["Projects"]["Values"][i],
                "kcost": dataArray["Projects"]["Returns"][i - 1],
                "type": "interp"
            }, {
                "datagroup": "Interval" + i,
                "financing": cost - dataArray["Projects"]["Values"][i],
                "kcost": dataArray["Projects"]["Returns"][i],
                "type": "interp"
            });
        }
    }
    projectdata.push({
        "datagroup": "WACC1",
        "financing": 0,
        "kcost": dataArray["rCompany"][0],
        "type": "wacc",
        "label": "\u03C1 = " + dataArray["rCompany"][0] + "%"
    }, {
        "datagroup": "WACC1",
        "financing": dataArray["vCompany"],
        "kcost": dataArray["rCompany"][0],
        "type": "wacc"
    }, {
        "datagroup": "WACC2",
        "financing": dataArray["vCompany"],
        "kcost": dataArray["rCompany"][1],
        "type": "wacc",
        "label": "\u03C1 = " + dataArray["rCompany"][1] + "%"
    }, {
        "datagroup": "WACC2",
        "financing": cost,
        "kcost": dataArray["rCompany"][1],
        "type": "wacc"
    }, {
        "datagroup": "IntervalW",
        "financing": dataArray["vCompany"],
        "kcost": dataArray["rCompany"][0],
        "type": "interw",
    }, {
        "datagroup": "IntervalW",
        "financing": dataArray["vCompany"],
        "kcost": dataArray["rCompany"][1],
        "type": "interw",
    });
    var PercentValues = dataArray["Projects"]["Returns"].concat(dataArray["rCompany"]);
    var ScaleValues = {
        xMaxValue: cost + 10,
        yMaxValue: Math.max.apply(Math, PercentValues) + 1,
        yMinValue: Math.min.apply(Math, PercentValues) - 1
    };
    DataArrayConcat = {
        ProjectData: projectdata,
        ScaleValues: ScaleValues
    };
    return DataArrayConcat
}
function MakeGraph(data) {
    var viswidth = document.getElementById("visualisationspace").offsetWidth;
    var visheight = 500;
    var dataGroup = d3.nest().key(function (d) {
        return d.datagroup;
    }).entries(data["ProjectData"]);
    var vis = d3.select("#visualisation")
        , WIDTH = viswidth
        , HEIGHT = visheight
        , MARGINS = {
        top: 50,
        right: 20,
        bottom: 50,
        left: 50
    }
        , xScale = d3.scale.linear().range([MARGINS.left, WIDTH - MARGINS.right]).domain([0, data["ScaleValues"]["xMaxValue"]])
        , yScale = d3.scale.linear().range([HEIGHT - MARGINS.top, MARGINS.bottom]).domain([data["ScaleValues"]["yMinValue"], data["ScaleValues"]["yMaxValue"]])
        , xAxis = d3.svg.axis().scale(xScale)
        , yAxis = d3.svg.axis().scale(yScale).orient("left");
    vis.append("svg:g").attr("class", "x axis").attr("transform", "translate(0," + (HEIGHT - MARGINS.bottom) + ")").call(xAxis);
    vis.append("svg:g").attr("class", "y axis").attr("transform", "translate(" + (MARGINS.left) + ",0)").call(yAxis);
    var lineGen = d3.svg.line().x(function (d) {
        return xScale(d.financing);
    }).y(function (d) {
        return yScale(d.kcost);
    }).interpolate("basis");
    dataGroup.forEach(function (d, i) {
        if (d.values["0"]["type"] === "project" || d.values["0"]["type"] === "wacc") {
            if (d.values["0"]["type"] === "wacc") {
                vis.append('svg:path').attr('d', lineGen(d.values)).attr('stroke', '#ff0039').attr('stroke-width', 2).attr('fill', 'none');
            } else {
                vis.append('svg:path').attr('d', lineGen(d.values)).attr('stroke', '#2780e3').attr('stroke-width', 2).attr('fill', 'none');
            }
            var firstposition = parseInt(lineGen(d.values).split(",")["0"].substring(1));
            var position = lineGen(d.values).split(",")["1"].split("L");
            position.forEach(function () {
                var vertical = parseInt(position["0"]);
                var horizontal = parseInt(position["1"]);
                vis.append('text').attr("x", ((horizontal + firstposition) / 2)).attr("y", vertical - 5).text(d.values["0"]["label"]);
            });
        } else if (d.values["0"]["type"] === "interp") {
            vis.append('svg:path').attr('d', lineGen(d.values)).attr('stroke', '#3fb618').style("stroke-dasharray", ("3, 3")).attr('stroke-width', 2).attr('fill', 'none');
        } else if (d.values["0"]["type"] === "interw") {
            vis.append('svg:path').attr('d', lineGen(d.values)).attr('stroke', '#ff0039').style("stroke-dasharray", ("7, 7")).attr('stroke-width', 2).attr('fill', 'none');
        }
        vis.append('text').attr('x', viswidth / 2).attr('y', visheight - 5).text('Coût (Milliers $)');
        vis.append('text').attr("transform", "rotate(-90)").attr('x', -visheight / 2).attr('y', 15).style("text-anchor", "middle").text('Rendement espéré (%)');
    });
}
function CheckForm() {
    var CheckedForm = true;
    for (var i = document.getElementsByClassName('textfield').length - 1; i >= 0; i--) {
        var id = document.getElementsByClassName('textfield')[i].id;
        $('#' + id).parent('div').removeClass('has-warning has-feedback');
        $('#' + id).parent('div').find('span[class="glyphicon glyphicon-warning-sign form-control-feedback"]').remove();
    }
    for (var i = document.getElementsByClassName('textfield').length - 1; i >= 0; i--) {
        if (document.getElementsByClassName('textfield')[i].value.length === 0) {
            var id = document.getElementsByClassName('textfield')[i].id;
            $('#' + id).parent('div').addClass('has-warning has-feedback');
            $('#' + id).parent('div').append('');
            var CheckedForm = false;
        }
    }
    return CheckedForm;
}
function UpdateGraph() {
    if (CheckForm() === true) {
        var NewData = MakeDataArray(DataForm());
        d3.select("svg").remove();
        $('#visualisationspace').append('<svg id="visualisation" width="100%" height="500"></svg>');
        MakeGraph(NewData);
    } else {
        $('#modal-label').text('Données');
        $('#modal-body').text('Check ton shit bro! Il manque des infos!');
        $('#modal-button').text("J'ai compris!");
        $('#modalwindow').modal('show');
    }
}
function SaveGraph() {
    if (CheckForm() === true) {
        saveSvgAsPng(document.getElementById("visualisation"), "IOSChart.png");
    } else {
        $('#modal-label').text('Données');
        $('#modal-body').text('Check ton shit bro! Il manque des infos!');
        $('#modal-button').text("J'ai compris!");
        $('#modalwindow').modal('show');
    }
}<commit_msg>Corrected jaggy font<commit_after>var alphabet = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L"];
var DefaultRawData = {
    Projects: {
        Values: [5000, 6000, 6000, 2000, 6000],
        Returns: [18, 14, 13, 10, 9]
    },
    vCompany: 12000,
    rCompany: [10, 13.25]
};
var DefaultData = MakeDataArray(DefaultRawData);
function FormatBox(type, id) {
    var CurrentValue = $('#' + id).val();
    var NewValue = parseFloat(CurrentValue.replace(/\s/g, ''));
    if (CurrentValue.length > 0 && isNaN(NewValue) === true) {
        $('#' + id).val('');
        $('#modal-label').text('Format');
        $('#modal-body').text('Ayoye, commence par écrire des chiffres...');
        $('#modal-button').text("J'ai compris!");
        $('#modalwindow').modal('show');
        return;
    }
    var ValueStr = String(NewValue);
    var SplitValue = ValueStr.split('.');
    var IntLength = SplitValue[0].length;
    var Decimals = parseFloat('0.' + SplitValue[1]);
    var Spaces = parseInt(IntLength / 3);
    var NumParts = [];
    for (var i = Spaces + 1; i > 0; i--) {
        StartLoc = IntLength - 3;
        NumParts[i] = SplitValue[0].substring(StartLoc, IntLength);
        IntLength = StartLoc;
    }
    var IntPart = NumParts.join(' ');
    var DecString = String(Decimals.toFixed(2));
    var DecPart = DecString.substring(2, 4);
    if (Decimals > 0) {
        var DispValue = IntPart + '.' + DecPart;
    } else {
        var DispValue = IntPart;
    }
    if (type === "d" && CurrentValue.length > 0) {
        $('#' + id).val(DispValue + " $");
    } else if (type === "p" && CurrentValue.length > 0) {
        if (parseInt(CurrentValue) >= 100) {
            $('#' + id).val('');
            $('#modal-label').text('Coût en capital');
            $('#modal-body').text('C\'est trop rentable bro!');
            $('#modal-button').text("J'ai compris!");
            $('#modalwindow').modal('show');

        } else {
            $('#' + id).val(DispValue + " %");
        }
    }
}
function AddLine() {
    var lastid = parseInt($('#ProjectsTable tr:last').data("projectid"));
    var newid = lastid + 1;
    if (newid >= 12) {
        $('#modal-label').text('Limite');
        $('#modal-body').text('Le nombre de projets est limité à 12. Sorry!');
        $('#modal-button').text("J'ai compris!");
        $('#modalwindow').modal('show');
    } else {
        $('#ProjectsTable tr:last').after('
' + alphabet[newid] + '
<input type="text" class="form-control investment textfield" id="I' + newid + '" onfocusout="FormatBox(\'d\',\'I' + newid + '\')" autocomplete="off">

<input type="text" class="form-control return textfield" id="R' + newid + '" onfocusout="FormatBox(\'p\',\'R' + newid + '\')" autocomplete="off">
<button class="btn btn-danger" onclick="RemoveLine()" id="remove' + newid + '"></button>
');
        $('#remove' + lastid).hide();
    }
}
function RemoveLine() {
    var lastid = parseInt($('#ProjectsTable tr:last').data("projectid"));
    var newid = lastid - 1;
    $('#ProjectsTable tr:last').remove();
    $('#remove' + newid).show();
}
function DataForm() {
    var ProjectValue = document.getElementsByClassName("investment");
    var ProjectReturn = document.getElementsByClassName("return");
    var ProjectValues = [];
    var ProjectReturns = [];
    for (i = 0; i < ProjectValue.length; i++) {
        ProjectValues[i] = parseFloat(ProjectValue[i].value.replace(/\s/g, '')) / 1000;
        ProjectReturns[i] = parseFloat(ProjectReturn[i].value);
    }
    var CompanyMaxInvestment = parseFloat(document.getElementById("MI").value.replace(/\s/g, '')) / 1000;
    var CompanyCCArray = [parseFloat(document.getElementById("CC1").value), parseFloat(document.getElementById("CC2").value)];
    var NewData = {
        Projects: {
            Values: ProjectValues,
            Returns: ProjectReturns
        },
        vCompany: CompanyMaxInvestment,
        rCompany: CompanyCCArray
    };
    return NewData
}
function MakeDataArray(dataArray) {
    var projectdata = [];
    var nbProjects = dataArray["Projects"]["Values"].length;
    var cost = 0;
    for (var i = 0; i <= nbProjects - 1; i++) {
        projectdata.push({
            "datagroup": "Project" + i,
            "financing": cost,
            "kcost": dataArray["Projects"]["Returns"][i],
            "type": "project",
            "label": alphabet[i]
        });
        cost = cost + dataArray["Projects"]["Values"][i];
        projectdata.push({
            "datagroup": "Project" + i,
            "financing": cost,
            "kcost": dataArray["Projects"]["Returns"][i],
            "type": "interp",
            "label": alphabet[i]
        });
        if (i > 0) {
            projectdata.push({
                "datagroup": "Interval" + i,
                "financing": cost - dataArray["Projects"]["Values"][i],
                "kcost": dataArray["Projects"]["Returns"][i - 1],
                "type": "interp"
            }, {
                "datagroup": "Interval" + i,
                "financing": cost - dataArray["Projects"]["Values"][i],
                "kcost": dataArray["Projects"]["Returns"][i],
                "type": "interp"
            });
        }
    }
    projectdata.push({
        "datagroup": "WACC1",
        "financing": 0,
        "kcost": dataArray["rCompany"][0],
        "type": "wacc",
        "label": "\u03C1 = " + dataArray["rCompany"][0] + "%"
    }, {
        "datagroup": "WACC1",
        "financing": dataArray["vCompany"],
        "kcost": dataArray["rCompany"][0],
        "type": "wacc"
    }, {
        "datagroup": "WACC2",
        "financing": dataArray["vCompany"],
        "kcost": dataArray["rCompany"][1],
        "type": "wacc",
        "label": "\u03C1 = " + dataArray["rCompany"][1] + "%"
    }, {
        "datagroup": "WACC2",
        "financing": cost,
        "kcost": dataArray["rCompany"][1],
        "type": "wacc"
    }, {
        "datagroup": "IntervalW",
        "financing": dataArray["vCompany"],
        "kcost": dataArray["rCompany"][0],
        "type": "interw",
    }, {
        "datagroup": "IntervalW",
        "financing": dataArray["vCompany"],
        "kcost": dataArray["rCompany"][1],
        "type": "interw",
    });
    var PercentValues = dataArray["Projects"]["Returns"].concat(dataArray["rCompany"]);
    var ScaleValues = {
        xMaxValue: cost + 10,
        yMaxValue: Math.max.apply(Math, PercentValues) + 1,
        yMinValue: Math.min.apply(Math, PercentValues) - 1
    };
    DataArrayConcat = {
        ProjectData: projectdata,
        ScaleValues: ScaleValues
    };
    return DataArrayConcat
}
function MakeGraph(data) {
    var viswidth = document.getElementById("visualisationspace").offsetWidth;
    var visheight = 500;
    var dataGroup = d3.nest().key(function (d) {
        return d.datagroup;
    }).entries(data["ProjectData"]);
    var vis = d3.select("#visualisation")
        , WIDTH = viswidth
        , HEIGHT = visheight
        , MARGINS = {
        top: 50,
        right: 20,
        bottom: 50,
        left: 50
    }
        , xScale = d3.scale.linear().range([MARGINS.left, WIDTH - MARGINS.right]).domain([0, data["ScaleValues"]["xMaxValue"]])
        , yScale = d3.scale.linear().range([HEIGHT - MARGINS.top, MARGINS.bottom]).domain([data["ScaleValues"]["yMinValue"], data["ScaleValues"]["yMaxValue"]])
        , xAxis = d3.svg.axis().scale(xScale)
        , yAxis = d3.svg.axis().scale(yScale).orient("left");
    vis.append("svg:g").attr("class", "x axis").attr("transform", "translate(0," + (HEIGHT - MARGINS.bottom) + ")").call(xAxis);
    vis.append("svg:g").attr("class", "y axis").attr("transform", "translate(" + (MARGINS.left) + ",0)").call(yAxis);
    var lineGen = d3.svg.line().x(function (d) {
        return xScale(d.financing);
    }).y(function (d) {
        return yScale(d.kcost);
    }).interpolate("basis");
    dataGroup.forEach(function (d, i) {
        if (d.values["0"]["type"] === "project" || d.values["0"]["type"] === "wacc") {
            if (d.values["0"]["type"] === "wacc") {
                vis.append('svg:path').attr('d', lineGen(d.values)).attr('stroke', '#ff0039').attr('stroke-width', 2).attr('fill', 'none');
            } else {
                vis.append('svg:path').attr('d', lineGen(d.values)).attr('stroke', '#2780e3').attr('stroke-width', 2).attr('fill', 'none');
            }
            var firstposition = parseInt(lineGen(d.values).split(",")["0"].substring(1));
            var position = lineGen(d.values).split(",")["1"].split("L");
            position.forEach(function () {
                var vertical = parseInt(position["0"]);
                var horizontal = parseInt(position["1"]);
                vis.append('text').attr("x", ((horizontal + firstposition) / 2)).attr("y", vertical - 5).text(d.values["0"]["label"]);
            });
        } else if (d.values["0"]["type"] === "interp") {
            vis.append('svg:path').attr('d', lineGen(d.values)).attr('stroke', '#3fb618').style("stroke-dasharray", ("3, 3")).attr('stroke-width', 2).attr('fill', 'none');
        } else if (d.values["0"]["type"] === "interw") {
            vis.append('svg:path').attr('d', lineGen(d.values)).attr('stroke', '#ff0039').style("stroke-dasharray", ("7, 7")).attr('stroke-width', 2).attr('fill', 'none');
        }
     });
    vis.append('text').attr('x', viswidth / 2).attr('y', visheight - 5).style("font-weight", "bold").text('Coût (Milliers $)');
    vis.append('text').attr("transform", "rotate(-90)").attr('x', -visheight / 2).attr('y', 15).style("text-anchor", "middle").style("font-weight", "bold").text('Rendement espéré (%)');
}
function CheckForm() {
    var CheckedForm = true;
    for (var i = document.getElementsByClassName('textfield').length - 1; i >= 0; i--) {
        var id = document.getElementsByClassName('textfield')[i].id;
        $('#' + id).parent('div').removeClass('has-warning has-feedback');
        $('#' + id).parent('div').find('span[class="glyphicon glyphicon-warning-sign form-control-feedback"]').remove();
    }
    for (var i = document.getElementsByClassName('textfield').length - 1; i >= 0; i--) {
        if (document.getElementsByClassName('textfield')[i].value.length === 0) {
            var id = document.getElementsByClassName('textfield')[i].id;
            $('#' + id).parent('div').addClass('has-warning has-feedback');
            $('#' + id).parent('div').append('');
            var CheckedForm = false;
        }
    }
    return CheckedForm;
}
function UpdateGraph() {
    if (CheckForm() === true) {
        var NewData = MakeDataArray(DataForm());
        d3.select("svg").remove();
        $('#visualisationspace').append('<svg id="visualisation" width="100%" height="500"></svg>');
        MakeGraph(NewData);
    } else {
        $('#modal-label').text('Données');
        $('#modal-body').text('Check tes affaires! Il manque des infos!');
        $('#modal-button').text("J'ai compris!");
        $('#modalwindow').modal('show');
    }
}
function SaveGraph() {
    if (CheckForm() === true) {
        saveSvgAsPng(document.getElementById("visualisation"), "IOSChart.png");
    } else {
        $('#modal-label').text('Données');
        $('#modal-body').text('Check tes affaires! Il manque des infos!');
        $('#modal-button').text("J'ai compris!");
        $('#modalwindow').modal('show');
    }
}<|endoftext|>


<commit_before>/**
 * View code for expressions.
 *
 * @flow
 */
'use strict';

import React, {
    Image,
    Text,
    View,
    DeviceEventEmitter,
} from 'react-native';

import StatelessComponent from './StatelessComponent'
import {TrackedText, TrackedView} from './TrackedViews'

import type {
    DisplayExpression,
    DisplayLambda,
    DisplayFuncCall,
    DisplayVariable,
    DisplayReference,
    ViewKey,
} from './types'

import * as t from './types'

// This is the type returned by RelativeImageStub.
type AssetId = number;

type ExpressionPropTypes = {
    expr: DisplayExpression,
}
class Expression extends StatelessComponent<ExpressionPropTypes> {
    render() {
        console.log("called 2");
        const {expr} = this.props;
        return t.matchDisplayExpression(expr, {
            displayLambda: (expr) => <Lambda expr={expr} />,
            displayFuncCall: (expr) => <FuncCall expr={expr} />,
            displayVariable: (expr) => <Variable expr={expr} />,
            displayReference: (expr) => <Reference expr={expr} />,
        });
    }
}

type LambdaPropTypes = {
    expr: DisplayLambda,
}
class Lambda extends StatelessComponent<LambdaPropTypes> {
    render() {
        const {exprKey, varKey, emptyBodyKey, varName, body} = this.props.expr;
        var bodyElement;
        if (body != null) {
            bodyElement = <Expression expr={body} />;
        } else {
            bodyElement = <EmptyBody viewKey={emptyBodyKey} />;
        }
        return <ExprContainer viewKey={exprKey}>
            <ExprText>λ</ExprText>
            <ExprText viewKey={varKey}>{varName}</ExprText>
            <Bracket source={require('./img/left_bracket.png')}/>
            {bodyElement}
            <Bracket source={require('./img/right_bracket.png')}/>
        </ExprContainer>;
    }
}

type FuncCallPropTypes = {
    expr: DisplayFuncCall,
}
class FuncCall extends StatelessComponent<FuncCallPropTypes> {
    render() {
        const {exprKey, func, arg} = this.props.expr;
        return <ExprContainer viewKey={exprKey}>
            <Expression expr={func} />
            <Bracket source={require('./img/left_paren.png')}/>
            <Expression expr={arg} />
            <Bracket source={require('./img/right_paren.png')}/>
        </ExprContainer>;
    }
}

type VariablePropTypes = {
    expr: DisplayVariable,
}
class Variable extends StatelessComponent<VariablePropTypes> {
    render() {
        const {exprKey, varName} = this.props.expr;
        return <ExprContainer viewKey={exprKey}>
            <ExprText>{varName}</ExprText>
        </ExprContainer>;
    }
}

type ReferencePropTypes = {
    expr: DisplayReference,
}
class Reference extends StatelessComponent<ReferencePropTypes> {
    render() {
        const {exprKey, defName} = this.props.expr;
        return <ExprContainer viewKey={exprKey}>
            <ExprText>{defName}</ExprText>
        </ExprContainer>
    }
}

type ExprContainerPropTypes = {
    children: any,
    viewKey: ?ViewKey,
}
class ExprContainer extends StatelessComponent<ExprContainerPropTypes> {
    render() {
        const {children, viewKey} = this.props;
        return <TrackedView viewKey={viewKey} style={{
            flexDirection: 'row',
            backgroundColor: "white",
            elevation: 5,
            paddingTop: 1,
            alignItems: "center",
            paddingBottom: 1,
            paddingLeft: 2,
            paddingRight: 2,
            marginTop: 1,
            marginBottom: 1,
            marginLeft: 2,
            marginRight: 2,
        }}>
            {children}
        </TrackedView>
    }
}

type ExprTextPropTypes = {
    children: any,
    viewKey: ?ViewKey,
}
class ExprText extends StatelessComponent<ExprTextPropTypes> {
    render() {
        const {children, viewKey} = this.props;
        return <TrackedText viewKey={viewKey} style={{
                paddingLeft: 6,
                paddingRight: 6,
                fontSize: 28,
                color: "black",
                textAlign: "center",
                textAlignVertical: "center",
            }}>
            {children}
        </TrackedText>;
    }
}

type EmptyBodyPropTypes = {
    viewKey: ?ViewKey,
}
class EmptyBody extends StatelessComponent<EmptyBodyPropTypes> {
    render() {
        return <TrackedView viewKey={this.props.viewKey} style={{
            backgroundColor: "#FFBBBB",
            padding: 2,
            width: 20,
            height: 40,
            margin: 1,
            alignSelf: "center",
        }}>
        </TrackedView>;
    }
}

type BracketPropTypes = {
    source: AssetId,
}
class Bracket extends StatelessComponent<BracketPropTypes> {
    render() {
        // We want the width of the bracket to be fixed, but for the height to
        // match the available space. We can accomplish this by wrapping it in a
        // vertical flexbox and setting flex to 1, then setting the height of
        // the image itself to 0. This causes the flexbox to use the enclosing
        // height, and the image is stretched to 100%.
        const {source} = this.props;
        return <View style={{flexDirection: "column", alignSelf: "stretch"}}>
            <Image source={source} style={{
            width: 6,
            height: 0,
            resizeMode: "stretch",
            flex: 1,
            marginTop: 0.5,
            marginBottom: 0.5,
        }}/>
        </View>;
    }
}

export default Expression;<commit_msg>Remove accidental console.log<commit_after>/**
 * View code for expressions.
 *
 * @flow
 */
'use strict';

import React, {
    Image,
    Text,
    View,
    DeviceEventEmitter,
} from 'react-native';

import StatelessComponent from './StatelessComponent'
import {TrackedText, TrackedView} from './TrackedViews'

import type {
    DisplayExpression,
    DisplayLambda,
    DisplayFuncCall,
    DisplayVariable,
    DisplayReference,
    ViewKey,
} from './types'

import * as t from './types'

// This is the type returned by RelativeImageStub.
type AssetId = number;

type ExpressionPropTypes = {
    expr: DisplayExpression,
}
class Expression extends StatelessComponent<ExpressionPropTypes> {
    render() {
        const {expr} = this.props;
        return t.matchDisplayExpression(expr, {
            displayLambda: (expr) => <Lambda expr={expr} />,
            displayFuncCall: (expr) => <FuncCall expr={expr} />,
            displayVariable: (expr) => <Variable expr={expr} />,
            displayReference: (expr) => <Reference expr={expr} />,
        });
    }
}

type LambdaPropTypes = {
    expr: DisplayLambda,
}
class Lambda extends StatelessComponent<LambdaPropTypes> {
    render() {
        const {exprKey, varKey, emptyBodyKey, varName, body} = this.props.expr;
        var bodyElement;
        if (body != null) {
            bodyElement = <Expression expr={body} />;
        } else {
            bodyElement = <EmptyBody viewKey={emptyBodyKey} />;
        }
        return <ExprContainer viewKey={exprKey}>
            <ExprText>λ</ExprText>
            <ExprText viewKey={varKey}>{varName}</ExprText>
            <Bracket source={require('./img/left_bracket.png')}/>
            {bodyElement}
            <Bracket source={require('./img/right_bracket.png')}/>
        </ExprContainer>;
    }
}

type FuncCallPropTypes = {
    expr: DisplayFuncCall,
}
class FuncCall extends StatelessComponent<FuncCallPropTypes> {
    render() {
        const {exprKey, func, arg} = this.props.expr;
        return <ExprContainer viewKey={exprKey}>
            <Expression expr={func} />
            <Bracket source={require('./img/left_paren.png')}/>
            <Expression expr={arg} />
            <Bracket source={require('./img/right_paren.png')}/>
        </ExprContainer>;
    }
}

type VariablePropTypes = {
    expr: DisplayVariable,
}
class Variable extends StatelessComponent<VariablePropTypes> {
    render() {
        const {exprKey, varName} = this.props.expr;
        return <ExprContainer viewKey={exprKey}>
            <ExprText>{varName}</ExprText>
        </ExprContainer>;
    }
}

type ReferencePropTypes = {
    expr: DisplayReference,
}
class Reference extends StatelessComponent<ReferencePropTypes> {
    render() {
        const {exprKey, defName} = this.props.expr;
        return <ExprContainer viewKey={exprKey}>
            <ExprText>{defName}</ExprText>
        </ExprContainer>
    }
}

type ExprContainerPropTypes = {
    children: any,
    viewKey: ?ViewKey,
}
class ExprContainer extends StatelessComponent<ExprContainerPropTypes> {
    render() {
        const {children, viewKey} = this.props;
        return <TrackedView viewKey={viewKey} style={{
            flexDirection: 'row',
            backgroundColor: "white",
            elevation: 5,
            paddingTop: 1,
            alignItems: "center",
            paddingBottom: 1,
            paddingLeft: 2,
            paddingRight: 2,
            marginTop: 1,
            marginBottom: 1,
            marginLeft: 2,
            marginRight: 2,
        }}>
            {children}
        </TrackedView>
    }
}

type ExprTextPropTypes = {
    children: any,
    viewKey: ?ViewKey,
}
class ExprText extends StatelessComponent<ExprTextPropTypes> {
    render() {
        const {children, viewKey} = this.props;
        return <TrackedText viewKey={viewKey} style={{
                paddingLeft: 6,
                paddingRight: 6,
                fontSize: 28,
                color: "black",
                textAlign: "center",
                textAlignVertical: "center",
            }}>
            {children}
        </TrackedText>;
    }
}

type EmptyBodyPropTypes = {
    viewKey: ?ViewKey,
}
class EmptyBody extends StatelessComponent<EmptyBodyPropTypes> {
    render() {
        return <TrackedView viewKey={this.props.viewKey} style={{
            backgroundColor: "#FFBBBB",
            padding: 2,
            width: 20,
            height: 40,
            margin: 1,
            alignSelf: "center",
        }}>
        </TrackedView>;
    }
}

type BracketPropTypes = {
    source: AssetId,
}
class Bracket extends StatelessComponent<BracketPropTypes> {
    render() {
        // We want the width of the bracket to be fixed, but for the height to
        // match the available space. We can accomplish this by wrapping it in a
        // vertical flexbox and setting flex to 1, then setting the height of
        // the image itself to 0. This causes the flexbox to use the enclosing
        // height, and the image is stretched to 100%.
        const {source} = this.props;
        return <View style={{flexDirection: "column", alignSelf: "stretch"}}>
            <Image source={source} style={{
            width: 6,
            height: 0,
            resizeMode: "stretch",
            flex: 1,
            marginTop: 0.5,
            marginBottom: 0.5,
        }}/>
        </View>;
    }
}

export default Expression;<|endoftext|>


<commit_before>CanvasProvider = {
	canvases: [],
	getCanvas: function(width, height) {
		var canvas = this.canvases.length
			? this.canvases.pop()
			: document.createElement('canvas');
		canvas.width = width;
		canvas.height = height;
		return canvas;
	},

	returnCanvas: function(canvas) {
		this.canvases.push(canvas);
	}
};
<commit_msg>Allow CanvasProvider to receive sizes too.<commit_after>CanvasProvider = {
	canvases: [],
	getCanvas: function() {
		var size = Size.read(arguments);
		var canvas = this.canvases.length
			? this.canvases.pop()
			: document.createElement('canvas');
		canvas.width = size.width;
		canvas.height = size.height;
		return canvas;
	},

	returnCanvas: function(canvas) {
		// reset canvas:
		canvas.width = canvas.width;
		this.canvases.push(canvas);
	}
};
<|endoftext|>