<commit_before>import _ from 'lodash';
import React from 'react';
import { branch as BranchMixin } from 'baobab-react/mixins';
import BaobabPropTypes from 'baobab-prop-types';

/**
 * SchemaCursorMixin is designed for use with baobab-react mixin `branch`.
 * General purpose of mixin is tree autogeneration with schema.
 *
 * This mixin add cursors from component `schema` for `tree` component prop or root tree.
 *
 * Example of usage:
 *
 * Our tree (auto-generated from schema):
 * {
 *  globalVal: 'global value (predefined)',
 *  form: {
 *    name: '',
 *    externalId: ''
 *  }
 * }
 *
 * const EditForm = React.createClass({
 *  mixins: [SchemaBranchMixin],
 *  schema: {
 *    name: '',
 *    externalId: ''
 *  },
 *  cursors: {
 *    globalVal: ['globalVal']
 *  },
 *  render() {
 *    We have this.cursors.globalVal (via baobab-react branch mixin)
 *    And we have `this.cursors.name`, `this.cursors.externalId` via
 *    SchemaBranchMixin.
 *    `this.state.name` and others state params contains value from
 *    appropriate cursor via baobab-react branch mixin
 *
 *    If `tree` props is not received from child component, global tree will
 *    be used
 *  }
 * });
 *
 * const Page = React.createClass({
 *   mixins: [SchemaBranchMixin],
 *
 *   schema: {
 *     form: {}
 *   },
 *
 *   render() {
 *     return (<EditForm tree={this.cursors.form} />);
 *   }
 * });
 */

const SchemaBranchMixin = {
  propTypes: {
    tree: React.PropTypes.oneOfType([BaobabPropTypes.baobab, BaobabPropTypes.cursor]),
  },

  contextTypes: {
    tree: BaobabPropTypes.baobab,
  },

  getTreeCursor(props) {
    return props.tree || this.context.tree.select();
  },

  getInitialState() {
    if (_.isFunction(this.cursors)) {
      this.cursors = this.cursors(this.props, this.context);
    }

    this.cursors = this.cursors || {};
    this.schema = this.schema || {};

    const tree = this.getTreeCursor(this.props);

    // Add initial cursors to first-level schema
    // Baobab-react branch mixin will add watchers for this cursors
    _.each(this.schema, (value, key) => this.cursors[key] = tree.select(key));
  },

  componentWillMount() {
    const tree = this.getTreeCursor(this.props);

    this.updateStateFromTree(tree);
  },

  componentWillReceiveProps(nextProps) {
    const oldTree = this.getTreeCursor(this.props);
    const newTree = this.getTreeCursor(nextProps);

    if (oldTree !== newTree) {
      // Change cursor mapping for new tree via accessing to private `__cursorsMapping`
      // Baobab-react branch mixin will refresh watcher in this step
      _.each(this.schema, (value, key) => this.__cursorsMapping[key] = newTree.select(key));

      this.updateStateFromTree(newTree);
    }
  },

  /**
   * Create state from tree and update current state with created state
   *
   * @param tree
   */
  updateStateFromTree(tree) {
    this.setState(this.createState(tree));
  },

  /**
   * Create state in tree corresponding to schema at first-level
   * Returns object which represent state
   *
   * @param tree Baobab Tree
   * @returns {Object}
   */
  createState(tree) {
    function iterate(curTree, curSchema) {
      return _.mapValues(curSchema, (value, key) => {
        const cursor = curTree.select(key);

        if (!cursor.exists() || curSchema._override === true) {
          cursor.set(value);
        } else if (_.isPlainObject(value) && _.isPlainObject(cursor.get())) {
          iterate(cursor, value);
        }

        return cursor.get();
      });
    }

    const state = iterate(tree, this.schema);
    this.context.tree.commit();

    return state;
  },
};

export default {
  displayName: 'SchemaBranchMixin',

  mixins: [SchemaBranchMixin, BranchMixin],
};
<commit_msg>Fix #6<commit_after>import _ from 'lodash';
import React from 'react';
import { branch as BranchMixin } from 'baobab-react/mixins';
import BaobabPropTypes from 'baobab-prop-types';

/**
 * SchemaCursorMixin is designed for use with baobab-react mixin `branch`.
 * General purpose of mixin is tree autogeneration with schema.
 *
 * This mixin add cursors from component `schema` for `tree` component prop or root tree.
 *
 * Example of usage:
 *
 * Our tree (auto-generated from schema):
 * {
 *  globalVal: 'global value (predefined)',
 *  form: {
 *    name: '',
 *    externalId: ''
 *  }
 * }
 *
 * const EditForm = React.createClass({
 *  mixins: [SchemaBranchMixin],
 *  schema: {
 *    name: '',
 *    externalId: ''
 *  },
 *  cursors: {
 *    globalVal: ['globalVal']
 *  },
 *  render() {
 *    We have this.cursors.globalVal (via baobab-react branch mixin)
 *    And we have `this.cursors.name`, `this.cursors.externalId` via
 *    SchemaBranchMixin.
 *    `this.state.name` and others state params contains value from
 *    appropriate cursor via baobab-react branch mixin
 *
 *    If `tree` props is not received from child component, global tree will
 *    be used
 *  }
 * });
 *
 * const Page = React.createClass({
 *   mixins: [SchemaBranchMixin],
 *
 *   schema: {
 *     form: {}
 *   },
 *
 *   render() {
 *     return (<EditForm tree={this.cursors.form} />);
 *   }
 * });
 */

const SchemaBranchMixin = {
  propTypes: {
    tree: React.PropTypes.oneOfType([BaobabPropTypes.baobab, BaobabPropTypes.cursor]),
  },

  contextTypes: {
    tree: BaobabPropTypes.baobab,
  },

  getTreeCursor(props) {
    return props.tree || this.context.tree.select();
  },

  getInitialState() {
    if (_.isFunction(this.cursors)) {
      this.cursors = this.cursors(this.props, this.context);
    } else {
      this.cursors = _.cloneDeep(this.cursors) || {};
    }

    this.schema = _.cloneDeep(this.schema || {});

    const tree = this.getTreeCursor(this.props);

    // Add initial cursors to first-level schema
    // Baobab-react branch mixin will add watchers for this cursors
    _.each(this.schema, (value, key) => this.cursors[key] = tree.select(key));
  },

  componentWillMount() {
    const tree = this.getTreeCursor(this.props);

    this.updateStateFromTree(tree);
  },

  componentWillReceiveProps(nextProps) {
    const oldTree = this.getTreeCursor(this.props);
    const newTree = this.getTreeCursor(nextProps);

    if (oldTree !== newTree) {
      // Change cursor mapping for new tree via accessing to private `__cursorsMapping`
      // Baobab-react branch mixin will refresh watcher in this step
      _.each(this.schema, (value, key) => this.__cursorsMapping[key] = newTree.select(key));

      this.updateStateFromTree(newTree);
    }
  },

  /**
   * Create state from tree and update current state with created state
   *
   * @param tree
   */
  updateStateFromTree(tree) {
    this.setState(this.createState(tree));
  },

  /**
   * Create state in tree corresponding to schema at first-level
   * Returns object which represent state
   *
   * @param tree Baobab Tree
   * @returns {Object}
   */
  createState(tree) {
    function iterate(curTree, curSchema) {
      return _.mapValues(curSchema, (value, key) => {
        const cursor = curTree.select(key);

        if (!cursor.exists() || curSchema._override === true) {
          cursor.set(value);
        } else if (_.isPlainObject(value) && _.isPlainObject(cursor.get())) {
          iterate(cursor, value);
        }

        return cursor.get();
      });
    }

    const state = iterate(tree, this.schema);
    this.context.tree.commit();

    return state;
  },
};

export default {
  displayName: 'SchemaBranchMixin',

  mixins: [SchemaBranchMixin, BranchMixin],
};
<|endoftext|>


<commit_before>'use strict';

function draw(){
    if(settings['clear']){
        buffer.clearRect(
          0,
          0,
          width,
          height
        );
    }

    for(var object in objects){
        // Draw rectangles if not in lines mode.
        if(mode != 1){
            buffer.fillStyle = objects[object]['color'];
            buffer.fillRect(
              objects[object]['x'],
              objects[object]['y'],
              objects[object]['x'] - mouse_x,
              objects[object]['y'] - mouse_y
            );
        }

        // Draw lines if not in rectangles mode.
        if(mode != 2){
            buffer.beginPath();
            buffer.moveTo(
              objects[object]['x'],
              objects[object]['y']
            );

            var extra_x = 0;
            var extra_y = 0;
            var target_x = mouse_x - objects[object]['x'];
            var target_y = mouse_y - objects[object]['y'];

            if(settings['line-fixed-length'] !== 0){
                var length = Math.sqrt(
                  target_x * target_x + target_y * target_y
                );

                target_x /= length;
                target_x *= settings['line-fixed-length'];
                target_y /= length;
                target_y *= settings['line-fixed-length'];
            }

            if(settings['line-length-multiplier'] !== 1){
                target_x *= settings['line-length-multiplier'];
                target_y *= settings['line-length-multiplier'];
            }

            if(settings['line-extra-length'] !== 0){
                extra_x = mouse_x - objects[object]['x'];
                extra_y = mouse_y - objects[object]['y'];

                var length = Math.sqrt(
                  extra_x * extra_x + extra_y * extra_y
                );

                extra_x /= length;
                extra_x *= settings['line-extra-length'];
                extra_y /= length;
                extra_y *= settings['line-extra-length'];
            }

            buffer.lineTo(
              objects[object]['x'] + target_x + extra_x,
              objects[object]['y'] + target_y + extra_y
            );
            buffer.closePath();
            buffer.strokeStyle = objects[object]['color'];
            buffer.stroke();
        }
    }

    if(settings['clear']){
        canvas.clearRect(
          0,
          0,
          width,
          height
        );
    }
    canvas.drawImage(
      document.getElementById('buffer'),
      0,
      0
    );
}

function random_hex(){
    var choices = '0123456789abcdef';
    return '#'
      + choices.charAt(Math.floor(Math.random() * 16))
      + choices.charAt(Math.floor(Math.random() * 16))
      + choices.charAt(Math.floor(Math.random() * 16));
}

function randomize_objects(){
    objects.length = 0;

    var loop_counter = settings['number-of-objects'] - 1;
    do{
        // Create randomized object.
        objects.push({
          'color': random_hex(),
          'x': Math.floor(Math.random() * width),
          'y': Math.floor(Math.random() * height),
        });
    }while(loop_counter--);

    draw();
}

function reset(){
    if(!window.confirm('Reset settings?')){
        return;
    }

    var ids = {
      'clear': true,
      'mouse-lock': true,
    };
    for(var id in ids){
        document.getElementById(id).checked = ids[id];
    }

    ids = {
      'line-extra-length': 0,
      'line-fixed-length': 0,
      'line-length-multiplier': 1,
      'line-width': 1,
      'number-of-objects': 100,
      'randomize-key': 'R',
    };
    for(var id in ids){
        document.getElementById(id).value = ids[id];
    }

    save();
}

function resize(){
    if(mode <= 0){
        return;
    }

    height = window.innerHeight;
    document.getElementById('buffer').height = height;
    document.getElementById('canvas').height = height;
    y = height / 2;
    mouse_y = y;

    width = window.innerWidth;
    document.getElementById('buffer').width = width;
    document.getElementById('canvas').width = width;
    x = width / 2;
    mouse_x = x;

    buffer.lineWidth = settings['line-width'];
    mouse_drag = false;
    randomize_objects();
}

// Save settings into window.localStorage if they differ from default.
function save(){
    var ids = [
      'clear',
      'mouse-lock',
    ];
    for(var id in ids){
        var checked = document.getElementById(ids[id]).checked;
        settings[ids[id]] = checked;

        if(checked){
            window.localStorage.removeItem('Warped.htm-' + ids[id]);

        }else{
            window.localStorage.setItem(
              'Warped.htm-' + ids[id],
              1
            );
        }
    }

    ids = {
      'line-extra-length': 0,
      'line-fixed-length': 0,
      'line-length-multiplier': 1,
      'line-width': 1,
    };
    for(id in ids){
        settings[id] = parseFloat(document.getElementById(id).value);

        if(settings[id] === ids[id]
          || isNaN(settings[id])){
            window.localStorage.removeItem('Warped.htm-' + id);

        }else{
            window.localStorage.setItem(
              'Warped.htm-' + id,
              settings[id]
            );
        }
    }

    settings['randomize-key'] = document.getElementById('randomize-key').value;
    if(settings['randomize-key'] === 'R'){
        window.localStorage.removeItem('Warped.htm-randomize-key');

    }else{
        window.localStorage.setItem(
          'Warped.htm-randomize-key',
          settings['randomize-key']
        );
    }

    var number_of_objects = document.getElementById('number-of-objects').value;
    if(number_of_objects == 100
      || isNaN(number_of_objects)
      || number_of_objects < 1){
        window.localStorage.removeItem('Warped.htm-number-of-objects');
        settings['number-of-objects'] = 100;

    }else{
        settings['number-of-objects'] = parseInt(number_of_objects);
        window.localStorage.setItem(
          'Warped.htm-number-of-objects',
          settings['number-of-objects']
        );
    }
}

function setmode(newmode){
    mode = newmode;

    // Visualization mode.
    if(mode > 0){
        save();

        document.body.innerHTML =
          '<canvas id=canvas></canvas><canvas id=buffer></canvas>';

        var contextAttributes = {
          'alpha': false,
        };
        buffer = document.getElementById('buffer').getContext(
          '2d',
          contextAttributes
        );
        canvas = document.getElementById('canvas').getContext(
          '2d',
          contextAttributes
        );

        resize();

        return;
    }

    // Main menu mode.
    buffer = 0;
    canvas = 0;

    document.body.innerHTML = '

Both
Lines
Rectangles

<input disabled value=ESC>Main Menu
<input id=randomize-key maxlength=1 value='
      + settings['randomize-key'] + '>Randomize

<input '
      + (settings['clear'] ? 'checked ' : '') + 'id=clear type=checkbox>Clear
<input id=line-extra-length value='
      + settings['line-extra-length'] + '>Line Extra Length
<input id=line-fixed-length value='
      + settings['line-fixed-length'] + '>Line Fixed Length
<input id=line-length-multiplier value='
      + settings['line-length-multiplier'] + '>Line Length Multiplier
<input id=line-width value='
      + settings['line-width'] + '>Line Width
<input '
      + (settings['mouse-lock'] ? 'checked ' : '') + 'id=mouse-lock type=checkbox>Mouse Lock
<input id=number-of-objects value='
      + settings['number-of-objects'] + '>Objects
Reset Settings

';
}

var buffer = 0;
var canvas = 0;
var height = 0;
var objects = [];
var mode = 0;
var mouse_drag = false;
var mouse_x = 0;
var mouse_y = 0;
var settings = {
  'clear': window.localStorage.getItem('Warped.htm-clear') === null,
  'line-extra-length': parseInt(window.localStorage.getItem('Warped.htm-line-extra-length')) || 0,
  'line-fixed-length': parseInt(window.localStorage.getItem('Warped.htm-line-fixed-length')) || 0,
  'line-length-multiplier': parseInt(window.localStorage.getItem('Warped.htm-line-length-multiplier')) || 1,
  'line-width': parseInt(window.localStorage.getItem('Warped.htm-line-width')) || 1,
  'randomize-key': window.localStorage.getItem('Warped.htm-randomize-key') || 'R',
  'mouse-lock': window.localStorage.getItem('Warped.htm-mouse-lock') === null,
  'number-of-objects': parseInt(window.localStorage.getItem('Warped.htm-number-of-objects')) || 100,
};
var x = 0;
var width = 0;
var y = 0;

window.onkeydown = function(e){
    if(mode <= 0){
        return;
    }

    var key = e.keyCode || e.which;

    // settings['randomize-key']: randomize current objects.
    if(String.fromCharCode(key) === settings['randomize-key']){
        randomize_objects();

    // ESC: return to the main menu.
    }else if(key === 27){
        setmode(0);
    }
};

window.onload = function(e){
    resize();
    setmode(0);
};

window.onmousedown =
  window.ontouchstart = function(e){
    if(mode <= 0){
        return;
    }

    mouse_drag = true;
    mouse_x = e.pageX;
    mouse_y = e.pageY;

    draw();
};

window.onmousemove = function(e){
    if(mode <= 0
      || (!settings['mouse-lock'] && !mouse_drag)){
        return;
    }

    mouse_x = e.pageX;
    mouse_y = e.pageY;

    draw();
};

window.onmouseup = function(e){
    mouse_drag = false;
};

window.onresize = resize;
<commit_msg>improved formatting<commit_after>'use strict';

function draw(){
    if(settings['clear']){
        buffer.clearRect(
          0,
          0,
          width,
          height
        );
    }

    for(var object in objects){
        // Draw rectangles if not in lines mode.
        if(mode != 1){
            buffer.fillStyle = objects[object]['color'];
            buffer.fillRect(
              objects[object]['x'],
              objects[object]['y'],
              objects[object]['x'] - mouse_x,
              objects[object]['y'] - mouse_y
            );
        }

        // Draw lines if not in rectangles mode.
        if(mode != 2){
            buffer.beginPath();
            buffer.moveTo(
              objects[object]['x'],
              objects[object]['y']
            );

            var extra_x = 0;
            var extra_y = 0;
            var target_x = mouse_x - objects[object]['x'];
            var target_y = mouse_y - objects[object]['y'];

            if(settings['line-fixed-length'] !== 0){
                var length = Math.sqrt(
                  target_x * target_x + target_y * target_y
                );

                target_x /= length;
                target_x *= settings['line-fixed-length'];
                target_y /= length;
                target_y *= settings['line-fixed-length'];
            }

            if(settings['line-length-multiplier'] !== 1){
                target_x *= settings['line-length-multiplier'];
                target_y *= settings['line-length-multiplier'];
            }

            if(settings['line-extra-length'] !== 0){
                extra_x = mouse_x - objects[object]['x'];
                extra_y = mouse_y - objects[object]['y'];

                var length = Math.sqrt(
                  extra_x * extra_x + extra_y * extra_y
                );

                extra_x /= length;
                extra_x *= settings['line-extra-length'];
                extra_y /= length;
                extra_y *= settings['line-extra-length'];
            }

            buffer.lineTo(
              objects[object]['x'] + target_x + extra_x,
              objects[object]['y'] + target_y + extra_y
            );
            buffer.closePath();
            buffer.strokeStyle = objects[object]['color'];
            buffer.stroke();
        }
    }

    if(settings['clear']){
        canvas.clearRect(
          0,
          0,
          width,
          height
        );
    }
    canvas.drawImage(
      document.getElementById('buffer'),
      0,
      0
    );
}

function random_hex(){
    var choices = '0123456789abcdef';
    return '#'
      + choices.charAt(Math.floor(Math.random() * 16))
      + choices.charAt(Math.floor(Math.random() * 16))
      + choices.charAt(Math.floor(Math.random() * 16));
}

function randomize_objects(){
    objects.length = 0;

    var loop_counter = settings['number-of-objects'] - 1;
    do{
        // Create randomized object.
        objects.push({
          'color': random_hex(),
          'x': Math.floor(Math.random() * width),
          'y': Math.floor(Math.random() * height),
        });
    }while(loop_counter--);

    draw();
}

function reset(){
    if(!window.confirm('Reset settings?')){
        return;
    }

    var ids = {
      'clear': true,
      'mouse-lock': true,
    };
    for(var id in ids){
        document.getElementById(id).checked = ids[id];
    }

    ids = {
      'line-extra-length': 0,
      'line-fixed-length': 0,
      'line-length-multiplier': 1,
      'line-width': 1,
      'number-of-objects': 100,
      'randomize-key': 'R',
    };
    for(var id in ids){
        document.getElementById(id).value = ids[id];
    }

    save();
}

function resize(){
    if(mode <= 0){
        return;
    }

    height = window.innerHeight;
    document.getElementById('buffer').height = height;
    document.getElementById('canvas').height = height;
    y = height / 2;
    mouse_y = y;

    width = window.innerWidth;
    document.getElementById('buffer').width = width;
    document.getElementById('canvas').width = width;
    x = width / 2;
    mouse_x = x;

    buffer.lineWidth = settings['line-width'];
    mouse_drag = false;
    randomize_objects();
}

// Save settings into window.localStorage if they differ from default.
function save(){
    var ids = [
      'clear',
      'mouse-lock',
    ];
    for(var id in ids){
        var checked = document.getElementById(ids[id]).checked;
        settings[ids[id]] = checked;

        if(checked){
            window.localStorage.removeItem('Warped.htm-' + ids[id]);

        }else{
            window.localStorage.setItem(
              'Warped.htm-' + ids[id],
              1
            );
        }
    }

    ids = {
      'line-extra-length': 0,
      'line-fixed-length': 0,
      'line-length-multiplier': 1,
      'line-width': 1,
    };
    for(id in ids){
        settings[id] = parseFloat(document.getElementById(id).value);

        if(settings[id] === ids[id]
          || isNaN(settings[id])){
            window.localStorage.removeItem('Warped.htm-' + id);

        }else{
            window.localStorage.setItem(
              'Warped.htm-' + id,
              settings[id]
            );
        }
    }

    settings['randomize-key'] = document.getElementById('randomize-key').value;
    if(settings['randomize-key'] === 'R'){
        window.localStorage.removeItem('Warped.htm-randomize-key');

    }else{
        window.localStorage.setItem(
          'Warped.htm-randomize-key',
          settings['randomize-key']
        );
    }

    var number_of_objects = document.getElementById('number-of-objects').value;
    if(number_of_objects == 100
      || isNaN(number_of_objects)
      || number_of_objects < 1){
        window.localStorage.removeItem('Warped.htm-number-of-objects');
        settings['number-of-objects'] = 100;

    }else{
        settings['number-of-objects'] = parseInt(number_of_objects);
        window.localStorage.setItem(
          'Warped.htm-number-of-objects',
          settings['number-of-objects']
        );
    }
}

function setmode(newmode){
    mode = newmode;

    // Visualization mode.
    if(mode > 0){
        save();

        document.body.innerHTML =
          '<canvas id=canvas></canvas><canvas id=buffer></canvas>';

        var contextAttributes = {
          'alpha': false,
        };
        buffer = document.getElementById('buffer').getContext(
          '2d',
          contextAttributes
        );
        canvas = document.getElementById('canvas').getContext(
          '2d',
          contextAttributes
        );

        resize();

        return;
    }

    // Main menu mode.
    buffer = 0;
    canvas = 0;

    document.body.innerHTML = '

Both
Lines
Rectangles

<input disabled value=ESC>Main Menu
<input id=randomize-key maxlength=1 value='
      + settings['randomize-key'] + '>Randomize

<input '
      + (settings['clear'] ? 'checked ' : '') + 'id=clear type=checkbox>Clear
<input id=line-extra-length value='
      + settings['line-extra-length'] + '>Line Extra Length
<input id=line-fixed-length value='
      + settings['line-fixed-length'] + '>Line Fixed Length
<input id=line-length-multiplier value='
      + settings['line-length-multiplier'] + '>Line Length Multiplier
<input id=line-width value='
      + settings['line-width'] + '>Line Width
<input '
      + (settings['mouse-lock'] ? 'checked ' : '') + 'id=mouse-lock type=checkbox>Mouse Lock
<input id=number-of-objects value='
      + settings['number-of-objects'] + '>Objects
Reset Settings

';
}

var buffer = 0;
var canvas = 0;
var height = 0;
var objects = [];
var mode = 0;
var mouse_drag = false;
var mouse_x = 0;
var mouse_y = 0;
var settings = {
  'clear': window.localStorage.getItem('Warped.htm-clear') === null,
  'line-extra-length': parseInt(window.localStorage.getItem('Warped.htm-line-extra-length')) || 0,
  'line-fixed-length': parseInt(window.localStorage.getItem('Warped.htm-line-fixed-length')) || 0,
  'line-length-multiplier': parseInt(window.localStorage.getItem('Warped.htm-line-length-multiplier')) || 1,
  'line-width': parseInt(window.localStorage.getItem('Warped.htm-line-width')) || 1,
  'randomize-key': window.localStorage.getItem('Warped.htm-randomize-key') || 'R',
  'mouse-lock': window.localStorage.getItem('Warped.htm-mouse-lock') === null,
  'number-of-objects': parseInt(window.localStorage.getItem('Warped.htm-number-of-objects')) || 100,
};
var width = 0;
var x = 0;
var y = 0;

window.onkeydown = function(e){
    if(mode <= 0){
        return;
    }

    var key = e.keyCode || e.which;

    // settings['randomize-key']: randomize current objects.
    if(String.fromCharCode(key) === settings['randomize-key']){
        randomize_objects();

    // ESC: return to the main menu.
    }else if(key === 27){
        setmode(0);
    }
};

window.onload = function(e){
    resize();
    setmode(0);
};

window.onmousedown =
  window.ontouchstart = function(e){
    if(mode <= 0){
        return;
    }

    mouse_drag = true;
    mouse_x = e.pageX;
    mouse_y = e.pageY;

    draw();
};

window.onmousemove = function(e){
    if(mode <= 0
      || (!settings['mouse-lock'] && !mouse_drag)){
        return;
    }

    mouse_x = e.pageX;
    mouse_y = e.pageY;

    draw();
};

window.onmouseup = function(e){
    mouse_drag = false;
};

window.onresize = resize;
<|endoftext|>


<commit_before>/*
 * jq-plugin
 *
 * The MIT License (MIT)
 *
 * Copyright (c) 2014 Jesús Manuel Germade Castiñeiras <jesus@germade.es>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 */

(function (root) {

  if( !root.$ ) {
    return;
  }

  var jq = root.$,
      jDoc = jq(document)
      pluginCache = {},
      pluginsAre = {},
      pluginsFilterCache = {};

  function pluginSelectorFilter (pluginSelector) {
    if( !pluginsFilterCache[pluginSelector] ) {
      pluginsFilterCache[pluginSelector] = function (el) {

        if( el.__found__ ) {
          return false;
        }
        el.__found__ = true;

        el.$$plugins = el.$$plugins || {};
        if( !el.$$plugins[pluginSelector] ) {
          el.$$plugins[pluginSelector] = true;
          return true;
        }
      };
    }
    return pluginsFilterCache[pluginSelector];
  }

  function findElements (jBase, pluginSelector) {
    var matches = [], n = 0, i, j, len, len2, filtered,
        pluginFilter = pluginSelectorFilter(pluginSelector);

    for( i = 0, len = jBase.length ; i < len ; i++ ) {
      filtered = [].filter.call( jBase[i].querySelectorAll(pluginSelector), pluginFilter );
      for( j = 0, len2 = filtered.length ; j < len2 ; j++ ) {
        matches[n++] = filtered[j];
      }
    }

    for( i = 0 ; i < n ; i++ ) {
      delete matches[i].__found__;
    }

    return jq(matches);
  }

  function runPlugin (jBase, pluginSelector) {
    var handler = pluginCache[pluginSelector],
        elements = findElements(jBase, pluginSelector);

    if( handler && elements.length ) {
      if( handler._collection ) {
        handler( elements );
      } else {
        elements.each(handler);
      }
    }
  }

  function initPlugin () {
    pluginsAre.loading = true;
    jq(function () {
      for( var pluginSelector in pluginCache ) {
        runPlugin(jDoc, pluginSelector);
      }

      jq(document.body).on('DOMSubtreeModified', function (e) {
        var jTarget = jq(event.target);

        for( var pluginSelector in pluginCache ) {
          runPlugin(jTarget, pluginSelector);
        }
      });

      delete pluginsAre.loading;
      pluginsAre.running = true;
    });
  }

  jq.plugin = function (selector, handler, collection) {
    if( typeof selector !== 'string' || !(handler instanceof Function) ) {
      throw new Error('required selector (string) and handler (function)');
      return;
    }

    pluginCache[selector] = handler;
    pluginCache[selector]._collection = !!collection;

    if( pluginsAre.loading ) {
      return;
    }

    if( pluginsAre.running ) {
      runPlugin(jDoc, selector);
    } else {
      initPlugin();
    }
  };

  // widgets

  var widgets = {},
      widgetsAre = {};

  function missingWidget () {
    if( this.$$plugins && this.$$plugins['[data-widget]'] ) {
      delete this.$$plugins['[data-widget]'];
    }
  }

  function initWidget () {
    widgetsAre.loading = true;
    jq(function () {
      jq.plugin('[data-widget]', function () {
        ( widgets[this.getAttribute('data-widget')] || missingWidget ).call(this);
      });
      delete widgetsAre.loading;
      widgetsAre.running = true;
    });
  };

  jq.widget = function (widgetName, handler) {
    if( typeof widgetName === 'string' && handler instanceof Function ) {

      widgets[widgetName] = handler;

      if( widgetsAre.loading ) {
        return;
      }

      if( widgetsAre.running ) {
        jq('[data-widget="' + widgetName + '"]').each(handler);
      } else {
        initWidget();
      }
    }
  };

})(this);
<commit_msg>strange bug<commit_after>/*
 * jq-plugin
 *
 * The MIT License (MIT)
 *
 * Copyright (c) 2014 Jesús Manuel Germade Castiñeiras <jesus@germade.es>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 */

(function (root) {

  if( !root.$ ) {
    return;
  }

  var jq = root.$,
      jDoc = jq(document)
      pluginCache = {},
      pluginsAre = {},
      pluginsFilterCache = {};

  function pluginSelectorFilter (pluginSelector) {
    if( !pluginsFilterCache[pluginSelector] ) {
      pluginsFilterCache[pluginSelector] = function (el) {

        if( el.__found__ ) {
          return false;
        }
        el.__found__ = true;

        el.$$plugins = el.$$plugins || {};
        if( !el.$$plugins[pluginSelector] ) {
          el.$$plugins[pluginSelector] = true;
          return true;
        }
      };
    }
    return pluginsFilterCache[pluginSelector];
  }

  function findElements (jBase, pluginSelector) {
    var matches = [], n = 0, i, j, len, len2, filtered,
        pluginFilter = pluginSelectorFilter(pluginSelector);

    for( i = 0, len = jBase.length ; i < len ; i++ ) {
      filtered = [].filter.call( jBase[i].querySelectorAll(pluginSelector), pluginFilter );
      for( j = 0, len2 = filtered.length ; j < len2 ; j++ ) {
        matches[n++] = filtered[j];
      }
    }

    for( i = 0 ; i < n ; i++ ) {
      delete matches[i].__found__;
    }

    return jq(matches);
  }

  function runPlugin (jBase, pluginSelector) {
    var handler = pluginCache[pluginSelector],
        elements = findElements(jBase, pluginSelector);

    if( handler && elements.length ) {
      if( handler._collection ) {
        handler( elements );
      } else {
        elements.each(handler);
      }
    }
  }

  function initPlugin () {
    pluginsAre.loading = true;
    jq(function () {
      for( var pluginSelector in pluginCache ) {
        runPlugin(jDoc, pluginSelector);
      }

      jq(document.body).on('DOMSubtreeModified', function (event) {
        var jTarget = jq(event.target);

        for( var pluginSelector in pluginCache ) {
          runPlugin(jTarget, pluginSelector);
        }
      });

      delete pluginsAre.loading;
      pluginsAre.running = true;
    });
  }

  jq.plugin = function (selector, handler, collection) {
    if( typeof selector !== 'string' || !(handler instanceof Function) ) {
      throw new Error('required selector (string) and handler (function)');
      return;
    }

    pluginCache[selector] = handler;
    pluginCache[selector]._collection = !!collection;

    if( pluginsAre.loading ) {
      return;
    }

    if( pluginsAre.running ) {
      runPlugin(jDoc, selector);
    } else {
      initPlugin();
    }
  };

  // widgets

  var widgets = {},
      widgetsAre = {};

  function missingWidget () {
    if( this.$$plugins && this.$$plugins['[data-widget]'] ) {
      delete this.$$plugins['[data-widget]'];
    }
  }

  function initWidget () {
    widgetsAre.loading = true;
    jq(function () {
      jq.plugin('[data-widget]', function () {
        ( widgets[this.getAttribute('data-widget')] || missingWidget ).call(this);
      });
      delete widgetsAre.loading;
      widgetsAre.running = true;
    });
  };

  jq.widget = function (widgetName, handler) {
    if( typeof widgetName === 'string' && handler instanceof Function ) {

      widgets[widgetName] = handler;

      if( widgetsAre.loading ) {
        return;
      }

      if( widgetsAre.running ) {
        jq('[data-widget="' + widgetName + '"]').each(handler);
      } else {
        initWidget();
      }
    }
  };

})(this);
<|endoftext|>


<commit_before>#!/usr/bin/env node

(function() {
    'use strict';

    var express     = require('express'),
        bodyParser  = require('body-parser'),
        info        = require('../package'),
        app         = express(),

        DB          = process.env.USERITO_DB,
        userito     = require('..')({
            type: DB ? 'db' : 'file',
            db: DB
        }),

        PORT        = process.env.USERITO_PORT || 3000,

        server;

    app.use(bodyParser.urlencoded({
        extended: true
    }));

    app.get('/', function(req, res) {
        res.send({
            name: info.name,
            version: info.version,
            api: {
                'GET /users': 'get all users',
                'GET /user/:username': 'get user with :username',
                'PUT /user/:username': 'modify user with :username',
                'POST /user': 'create user',
                'DELETE /user': 'remove user'
            }
        });
    });

    app.get('/users', function (req, res) {
        userito.all(send(res));
    });

    app.get('/user/:username', function(req, res) {
        var username      = Number(req.params.username);

        userito.get(username, send(res));
    });

    app.put('/user/:username', function(req, res) {
        var username      = Number(req.params.username);

        userito.modify(username, req.body, send(res));
    });

    app.post('/user', function(req, res) {
        userito.create(req.body, send(res));
    });

    app.delete('/user/:username', function(req, res) {
        var username      = Number(req.params.username);

        userito.remove(username, send(res));
    });

    app.use('*', function(req, res) {
        res
            .status(500)
            .json({
                message: 'api not defined'
            });
    });

    function send(res) {
        return function(error, data, appError) {
            if (data)
                res.send(data);
            else if (error)
                res
                    .status(500)
                    .send(error);
            else
                res
                    .status(400)
                    .send(appError);
        };
    }

    server = app.listen(PORT, function () {
        var host = server.address().address;
        var port = server.address().port;

        console.log('%s v%s listening at http://%s:%s', info.name, info.version, host, port);
    });

})();
<commit_msg>fix(userito) Number(username) -> username<commit_after>#!/usr/bin/env node

(function() {
    'use strict';

    var express     = require('express'),
        bodyParser  = require('body-parser'),
        info        = require('../package'),
        app         = express(),

        DB          = process.env.USERITO_DB,
        userito     = require('..')({
            type: DB ? 'db' : 'file',
            db: DB
        }),

        PORT        = process.env.USERITO_PORT || 3000,

        server;

    app.use(bodyParser.urlencoded({
        extended: true
    }));

    app.get('/', function(req, res) {
        res.send({
            name: info.name,
            version: info.version,
            api: {
                'GET /users': 'get all users',
                'GET /user/:username': 'get user with :username',
                'PUT /user/:username': 'modify user with :username',
                'POST /user': 'create user',
                'DELETE /user': 'remove user'
            }
        });
    });

    app.get('/users', function (req, res) {
        userito.all(send(res));
    });

    app.get('/user/:username', function(req, res) {
        var username = req.params.username;
        userito.get(username, send(res));
    });

    app.put('/user/:username', function(req, res) {
        var username = req.params.username;
        userito.modify(username, req.body, send(res));
    });

    app.post('/user', function(req, res) {
        userito.create(req.body, send(res));
    });

    app.delete('/user/:username', function(req, res) {
        var username = req.params.username;
        userito.remove(username, send(res));
    });

    app.use('*', function(req, res) {
        res
            .status(500)
            .json({
                message: 'api not defined'
            });
    });

    function send(res) {
        return function(error, data, appError) {
            if (data)
                res.send(data);
            else if (error)
                res
                    .status(500)
                    .send(error);
            else
                res
                    .status(400)
                    .send(appError);
        };
    }

    server = app.listen(PORT, function () {
        var host = server.address().address;
        var port = server.address().port;

        console.log('%s v%s listening at http://%s:%s', info.name, info.version, host, port);
    });

})();
<|endoftext|>


<commit_before>var chips = {};

chips.attiny44 = require('./attiny/attiny44');
chips.attiny45 = require('./attiny/attiny45');
chips.attiny84 = require('./attiny/attiny84');

module.exports = chips;
<commit_msg>import new translations to exports<commit_after>var chips = {};

/* ATMEGA */
chips.atmega128 = require('atmega/atmega128');
chips.atmega1280 = require('atmega/atmega1280');
chips.atmega1281 = require('atmega/atmega1281');
chips.atmega1284 = require('atmega/atmega1284');
chips.atmega1284p = require('atmega/atmega1284p');
chips.atmega1284rfr2 = require('atmega/atmega1284rfr2');
chips.atmega128a = require('atmega/atmega128a');
chips.atmega128rfa1 = require('atmega/atmega128rfa1');
chips.atmega128rfr2 = require('atmega/atmega128rfr2');
chips.atmega16 = require('atmega/atmega16');
chips.atmega162 = require('atmega/atmega162');
chips.atmega164a = require('atmega/atmega164a');
chips.atmega164p = require('atmega/atmega164p');
chips.atmega164pa = require('atmega/atmega164pa');
chips.atmega165a = require('atmega/atmega165a');
chips.atmega165p = require('atmega/atmega165p');
chips.atmega165pa = require('atmega/atmega165pa');
chips.atmega168 = require('atmega/atmega168');
chips.atmega168a = require('atmega/atmega168a');
chips.atmega168p = require('atmega/atmega168p');
chips.atmega168pa = require('atmega/atmega168pa');
chips.atmega168pb = require('atmega/atmega168pb');
chips.atmega169a = require('atmega/atmega169a');
chips.atmega169p = require('atmega/atmega169p');
chips.atmega169pa = require('atmega/atmega169pa');
chips.atmega16a = require('atmega/atmega16a');
chips.atmega16hva = require('atmega/atmega16hva');
chips.atmega16hvb = require('atmega/atmega16hvb');
chips.atmega16hvbrevb = require('atmega/atmega16hvbrevb');
chips.atmega16m1 = require('atmega/atmega16m1');
chips.atmega16u2 = require('atmega/atmega16u2');
chips.atmega16u4 = require('atmega/atmega16u4');
chips.atmega2560 = require('atmega/atmega2560');
chips.atmega2561 = require('atmega/atmega2561');
chips.atmega2564rfr2 = require('atmega/atmega2564rfr2');
chips.atmega256rfr2 = require('atmega/atmega256rfr2');
chips.atmega32 = require('atmega/atmega32');
chips.atmega324a = require('atmega/atmega324a');
chips.atmega324p = require('atmega/atmega324p');
chips.atmega324pa = require('atmega/atmega324pa');
chips.atmega325 = require('atmega/atmega325');
chips.atmega3250 = require('atmega/atmega3250');
chips.atmega3250a = require('atmega/atmega3250a');
chips.atmega3250p = require('atmega/atmega3250p');
chips.atmega3250pa = require('atmega/atmega3250pa');
chips.atmega325a = require('atmega/atmega325a');
chips.atmega325p = require('atmega/atmega325p');
chips.atmega325pa = require('atmega/atmega325pa');
chips.atmega328 = require('atmega/atmega328');
chips.atmega328p = require('atmega/atmega328p');
chips.atmega329 = require('atmega/atmega329');
chips.atmega3290 = require('atmega/atmega3290');
chips.atmega3290a = require('atmega/atmega3290a');
chips.atmega3290p = require('atmega/atmega3290p');
chips.atmega3290pa = require('atmega/atmega3290pa');
chips.atmega329a = require('atmega/atmega329a');
chips.atmega329p = require('atmega/atmega329p');
chips.atmega329pa = require('atmega/atmega329pa');
chips.atmega32a = require('atmega/atmega32a');
chips.atmega32c1 = require('atmega/atmega32c1');
chips.atmega32hvb = require('atmega/atmega32hvb');
chips.atmega32hvbrevb = require('atmega/atmega32hvbrevb');
chips.atmega32m1 = require('atmega/atmega32m1');
chips.atmega32u2 = require('atmega/atmega32u2');
chips.atmega32u4 = require('atmega/atmega32u4');
chips.atmega48 = require('atmega/atmega48');
chips.atmega48a = require('atmega/atmega48a');
chips.atmega48p = require('atmega/atmega48p');
chips.atmega48pa = require('atmega/atmega48pa');
chips.atmega48pb = require('atmega/atmega48pb');
chips.atmega64 = require('atmega/atmega64');
chips.atmega640 = require('atmega/atmega640');
chips.atmega644 = require('atmega/atmega644');
chips.atmega644a = require('atmega/atmega644a');
chips.atmega644p = require('atmega/atmega644p');
chips.atmega644pa = require('atmega/atmega644pa');
chips.atmega644rfr2 = require('atmega/atmega644rfr2');
chips.atmega645 = require('atmega/atmega645');
chips.atmega6450 = require('atmega/atmega6450');
chips.atmega6450a = require('atmega/atmega6450a');
chips.atmega6450p = require('atmega/atmega6450p');
chips.atmega645a = require('atmega/atmega645a');
chips.atmega645p = require('atmega/atmega645p');
chips.atmega649 = require('atmega/atmega649');
chips.atmega6490 = require('atmega/atmega6490');
chips.atmega6490a = require('atmega/atmega6490a');
chips.atmega6490p = require('atmega/atmega6490p');
chips.atmega649a = require('atmega/atmega649a');
chips.atmega649p = require('atmega/atmega649p');
chips.atmega64a = require('atmega/atmega64a');
chips.atmega64c1 = require('atmega/atmega64c1');
chips.atmega64hve2 = require('atmega/atmega64hve2');
chips.atmega64m1 = require('atmega/atmega64m1');
chips.atmega64rfr2 = require('atmega/atmega64rfr2');
chips.atmega8 = require('atmega/atmega8');
chips.atmega8515 = require('atmega/atmega8515');
chips.atmega8535 = require('atmega/atmega8535');
chips.atmega88 = require('atmega/atmega88');
chips.atmega88a = require('atmega/atmega88a');
chips.atmega88p = require('atmega/atmega88p');
chips.atmega88pa = require('atmega/atmega88pa');
chips.atmega88pb = require('atmega/atmega88pb');
chips.atmega8a = require('atmega/atmega8a');
chips.atmega8hva = require('atmega/atmega8hva');
chips.atmega8u2 = require('atmega/atmega8u2');

/* ATTINY */
chips.attiny13 = require('attiny/attiny13');
chips.attiny13a = require('attiny/attiny13a');
chips.attiny1634 = require('attiny/attiny1634');
chips.attiny167 = require('attiny/attiny167');
chips.attiny2313 = require('attiny/attiny2313');
chips.attiny2313a = require('attiny/attiny2313a');
chips.attiny24 = require('attiny/attiny24');
chips.attiny24a = require('attiny/attiny24a');
chips.attiny25 = require('attiny/attiny25');
chips.attiny26 = require('attiny/attiny26');
chips.attiny261 = require('attiny/attiny261');
chips.attiny261a = require('attiny/attiny261a');
chips.attiny4313 = require('attiny/attiny4313');
chips.attiny43u = require('attiny/attiny43u');
chips.attiny44 = require('attiny/attiny44');
chips.attiny441 = require('attiny/attiny441');
chips.attiny44a = require('attiny/attiny44a');
chips.attiny45 = require('attiny/attiny45');
chips.attiny461 = require('attiny/attiny461');
chips.attiny461a = require('attiny/attiny461a');
chips.attiny48 = require('attiny/attiny48');
chips.attiny828 = require('attiny/attiny828');
chips.attiny84 = require('attiny/attiny84');
chips.attiny841 = require('attiny/attiny841');
chips.attiny84a = require('attiny/attiny84a');
chips.attiny85 = require('attiny/attiny85');
chips.attiny861 = require('attiny/attiny861');
chips.attiny861a = require('attiny/attiny861a');
chips.attiny87 = require('attiny/attiny87');
chips.attiny88 = require('attiny/attiny88');

module.exports = chips;
<|endoftext|>


<commit_before>const temperatureController = require('./temperatureController');
const express = require('express');
const http = require('http').Server(express);
const io = require('socket.io')(http);

const gatherData = function () {
    return {
        currentTemp: temperatureController.getActualTemperature(),
        targetTemp: temperatureController.getTargetTemperature(),
    };
};

const propagateData = function () {
    io.sockets.emit('dataupdate', gatherData());
};

const app = express();
app.set('view engine', 'ejs');
app.use(express.static(__dirname+'/../public'));
 app.get('/', function(req, res){
   res.render('index', gatherData());
 });

 app.listen(3000);

 //Socket.IO
 io.on('connection', function(socket) {
     socket.on('increment', function(){
         temperatureController.incrementTargetTemperature();
         propagateData();
     });
     socket.on('decrement', function() {
         temperatureController.decrementTargetTemperature();
         propagateData();
     })
 });
<commit_msg>Debugging<commit_after>const temperatureController = require('./temperatureController');
const express = require('express');
const http = require('http').Server(express);
const io = require('socket.io')(http);

const gatherData = function (){
    return {
        currentTemp: temperatureController.getActualTemperature(),
        targetTemp: temperatureController.getTargetTemperature(),
    };
};

const propagateData = function () {
    var results = gatherData();
    io.sockets.emit('dataupdate', results);
};

const app = express();
app.set('view engine', 'ejs');
app.use(express.static(__dirname+'/../public'));
 app.get('/', function(req, res){
   res.render('index', gatherData());
 });

 app.listen(3000);

 //Socket.IO
 io.on('connection', function(socket) {
     socket.on('increment', function(){
         temperatureController.incrementTargetTemperature();
         propagateData();
     });
     socket.on('decrement', function() {
         temperatureController.decrementTargetTemperature();
         propagateData();
     })
 });
<|endoftext|>


<commit_before>'use strict';

function draw_logic(){
    for(var object in objects){
        // Draw rectangles if not in lines mode.
        if(canvas_mode != 1){
            canvas_buffer.fillStyle = objects[object]['color'];
            canvas_buffer.fillRect(
              objects[object]['x'],
              objects[object]['y'],
              objects[object]['x'] - mouse_x,
              objects[object]['y'] - mouse_y
            );
        }

        // Draw lines if not in rectangles mode.
        if(canvas_mode != 2){
            canvas_buffer.beginPath();
            canvas_buffer.moveTo(
              objects[object]['x'],
              objects[object]['y']
            );

            var extra_x = 0;
            var extra_y = 0;
            var target_x = mouse_x - objects[object]['x'];
            var target_y = mouse_y - objects[object]['y'];

            if(settings_settings['line-fixed-length'] !== 0){
                var length = Math.sqrt(
                  target_x * target_x + target_y * target_y
                );

                target_x /= length;
                target_x *= settings_settings['line-fixed-length'];
                target_y /= length;
                target_y *= settings_settings['line-fixed-length'];
            }

            if(settings_settings['line-length-multiplier'] !== 1){
                target_x *= settings_settings['line-length-multiplier'];
                target_y *= settings_settings['line-length-multiplier'];
            }

            if(settings_settings['line-extra-length'] !== 0){
                extra_x = mouse_x - objects[object]['x'];
                extra_y = mouse_y - objects[object]['y'];

                var length = Math.sqrt(
                  extra_x * extra_x + extra_y * extra_y
                );

                extra_x /= length;
                extra_x *= settings_settings['line-extra-length'];
                extra_y /= length;
                extra_y *= settings_settings['line-extra-length'];
            }

            canvas_buffer.lineTo(
              objects[object]['x'] + target_x + extra_x,
              objects[object]['y'] + target_y + extra_y
            );
            canvas_buffer.closePath();
            canvas_buffer.strokeStyle = objects[object]['color'];
            canvas_buffer.stroke();
        }
    }
}

function randomize_objects(){
    objects.length = 0;

    var loop_counter = settings_settings['number-of-objects'] - 1;
    do{
        // Create randomized object.
        objects.push({
          'color': random_hex(),
          'x': random_integer(canvas_width),
          'y': random_integer(canvas_height),
        });
    }while(loop_counter--);

    canvas_draw();
}

function resize_logic(){
    mouse_y = canvas_y;
    mouse_x = canvas_x;

    canvas_buffer.lineWidth = settings_settings['line-width'];
    mouse_drag = false;
    randomize_objects();
}

function setmode_logic(){
    // Main menu mode.
    if(canvas_mode === 0){
        document.body.innerHTML = '

Both
'
          + 'Lines
Rectangles

'
          + '

<input disabled value=ESC>Main Menu
'
          + '<input id=randomize-key maxlength=1>Randomize

'
          + '
<input id=line-extra-length>Line Extra Length
'
          + '<input id=line-fixed-length>Line Fixed Length
'
          + '<input id=line-length-multiplier>Line Length Multiplier
'
          + '<input id=line-width>Line Width
'
          + '<input id=mouse-lock type=checkbox>Mouse Lock
'
          + '<input id=number-of-objects>Objects
'
          + 'Reset Settings

';
        settings_update();

    // Visualization mode.
    }else{
        settings_save();
    }
}

var mouse_drag = false;
var mouse_x = 0;
var mouse_y = 0;
var objects = [];

window.onkeydown = function(e){
    if(canvas_mode <= 0){
        return;
    }

    var key = e.keyCode || e.which;

    // settings_settings['randomize-key']: randomize current objects.
    if(String.fromCharCode(key) === settings_settings['randomize-key']){
        randomize_objects();

    // ESC: return to the main menu.
    }else if(key === 27){
        canvas_setmode(0);
    }
};

window.onload = function(){
    settings_init(
      'Warped.htm-',
      {
        'line-extra-length': 0,
        'line-fixed-length': 0,
        'line-length-multiplier': 1,
        'line-width': 1,
        'randomize-key': 'R',
        'mouse-lock': true,
        'number-of-objects': 100,
      }
    );
    canvas_init();
};

window.onmousedown =
  window.ontouchstart = function(e){
    if(canvas_mode <= 0){
        return;
    }

    mouse_drag = true;
    mouse_x = e.pageX;
    mouse_y = e.pageY;

    canvas_draw();
};

window.onmousemove = function(e){
    if(canvas_mode <= 0
      || (!settings_settings['mouse-lock'] && !mouse_drag)){
        return;
    }

    mouse_x = e.pageX;
    mouse_y = e.pageY;

    canvas_draw();
};

window.onmouseup = function(e){
    mouse_drag = false;
};
<commit_msg>improved formatting<commit_after>'use strict';

function draw_logic(){
    for(var object in objects){
        // Draw rectangles if not in lines mode.
        if(canvas_mode != 1){
            canvas_buffer.fillStyle = objects[object]['color'];
            canvas_buffer.fillRect(
              objects[object]['x'],
              objects[object]['y'],
              objects[object]['x'] - mouse_x,
              objects[object]['y'] - mouse_y
            );
        }

        // Draw lines if not in rectangles mode.
        if(canvas_mode != 2){
            canvas_buffer.beginPath();
            canvas_buffer.moveTo(
              objects[object]['x'],
              objects[object]['y']
            );

            var extra_x = 0;
            var extra_y = 0;
            var target_x = mouse_x - objects[object]['x'];
            var target_y = mouse_y - objects[object]['y'];

            if(settings_settings['line-fixed-length'] !== 0){
                var length = Math.sqrt(
                  target_x * target_x + target_y * target_y
                );

                target_x /= length;
                target_x *= settings_settings['line-fixed-length'];
                target_y /= length;
                target_y *= settings_settings['line-fixed-length'];
            }

            if(settings_settings['line-length-multiplier'] !== 1){
                target_x *= settings_settings['line-length-multiplier'];
                target_y *= settings_settings['line-length-multiplier'];
            }

            if(settings_settings['line-extra-length'] !== 0){
                extra_x = mouse_x - objects[object]['x'];
                extra_y = mouse_y - objects[object]['y'];

                var length = Math.sqrt(
                  extra_x * extra_x + extra_y * extra_y
                );

                extra_x /= length;
                extra_x *= settings_settings['line-extra-length'];
                extra_y /= length;
                extra_y *= settings_settings['line-extra-length'];
            }

            canvas_buffer.lineTo(
              objects[object]['x'] + target_x + extra_x,
              objects[object]['y'] + target_y + extra_y
            );
            canvas_buffer.closePath();
            canvas_buffer.strokeStyle = objects[object]['color'];
            canvas_buffer.stroke();
        }
    }
}

function randomize_objects(){
    objects.length = 0;

    var loop_counter = settings_settings['number-of-objects'] - 1;
    do{
        // Create randomized object.
        objects.push({
          'color': random_hex(),
          'x': random_integer(canvas_width),
          'y': random_integer(canvas_height),
        });
    }while(loop_counter--);

    canvas_draw();
}

function resize_logic(){
    mouse_y = canvas_y;
    mouse_x = canvas_x;

    canvas_buffer.lineWidth = settings_settings['line-width'];
    mouse_drag = false;
    randomize_objects();
}

function setmode_logic(){
    // Main menu mode.
    if(canvas_mode === 0){
        document.body.innerHTML = '

Both
'
          + 'Lines
Rectangles

'
          + '

<input disabled value=ESC>Main Menu
'
          + '<input id=randomize-key maxlength=1>Randomize

'
          + '
<input id=line-extra-length>Line Extra Length
'
          + '<input id=line-fixed-length>Line Fixed Length
'
          + '<input id=line-length-multiplier>Line Length Multiplier
'
          + '<input id=line-width>Line Width
'
          + '<input id=mouse-lock type=checkbox>Mouse Lock
'
          + '<input id=number-of-objects>Objects
'
          + 'Reset Settings

';
        settings_update();

    // Visualization mode.
    }else{
        settings_save();
    }
}

var mouse_drag = false;
var mouse_x = 0;
var mouse_y = 0;
var objects = [];

window.onkeydown = function(e){
    if(canvas_mode <= 0){
        return;
    }

    var key = e.keyCode || e.which;

    // settings_settings['randomize-key']: randomize current objects.
    if(String.fromCharCode(key) === settings_settings['randomize-key']){
        randomize_objects();

    // ESC: return to the main menu.
    }else if(key === 27){
        canvas_setmode(0);
    }
};

window.onload = function(){
    settings_init(
      'Warped.htm-',
      {
        'line-extra-length': 0,
        'line-fixed-length': 0,
        'line-length-multiplier': 1,
        'line-width': 1,
        'mouse-lock': true,
        'number-of-objects': 100,
        'randomize-key': 'R',
      }
    );
    canvas_init();
};

window.onmousedown =
  window.ontouchstart = function(e){
    if(canvas_mode <= 0){
        return;
    }

    mouse_drag = true;
    mouse_x = e.pageX;
    mouse_y = e.pageY;

    canvas_draw();
};

window.onmousemove = function(e){
    if(canvas_mode <= 0
      || (!settings_settings['mouse-lock'] && !mouse_drag)){
        return;
    }

    mouse_x = e.pageX;
    mouse_y = e.pageY;

    canvas_draw();
};

window.onmouseup = function(e){
    mouse_drag = false;
};
<|endoftext|>


<commit_before>var list_of_quicktests = [
  {name:"animate_area", categories:["area", "animate"]},
  {name:"animate_horizontalBar", categories:["horizontalbar", "animate"]},
  {name:"animate_scatter", categories:["scatter", "animate"]},
  {name:"animate_verticalBar", categories:["verticalbar", "animate"]},
  {name:"interaction_dragzoomx", categories:["area", "interaction"]},
  {name:"interaction_panzoom", categories:["scatter", "gridlines", "interaction"]},
  {name:"legend_basic", categories:["layout", "legend", "scatter", "line", "title"]},
  {name:"scale_interactive", categories:["scale", "interaction", "scatter", "gridlines"]},
  {name:"basic_area", categories:["area", "basic"]}
]

<commit_msg>Update list_of_quicktests.js<commit_after>var list_of_quicktests = [
  {name:"animate_area", categories:["area", "animate"]},
  {name:"animate_horizontalBar", categories:["horizontalbar", "animate"]},
  {name:"animate_scatter", categories:["scatter", "animate"]},
  {name:"animate_verticalBar", categories:["verticalbar", "animate"]},
  {name:"interaction_dragzoomx", categories:["area", "interaction"]},
  {name:"interaction_panzoom", categories:["scatter", "gridlines", "interaction"]},
  {name:"legend_basic", categories:["layout", "legend", "scatter", "line", "title"]},
  {name:"scale_interactive", categories:["scale", "interaction", "scatter", "gridlines"]},
  {name:"basic_area", categories:["area", "basic"]},
  {name:"cat-axis_verticalBar", categories:["verticalbar", "cat-axis", "animate"]}

]

<|endoftext|>


<commit_before>//@TODO Arreglar datepicker // Afegir style CSS Registrar(atenuat)
//@TODO Activar botó registrar al validar tots els camps. (return true/false)

window.onload = function () {

  associaDOMevents();

  //localStorage
  init();

};

//Inici funcions

function associaDOMevents() {
//Associar events de la Vista
//variables
document.getElementById("nom").addEventListener("blur", valNom, true);
document.getElementById("cognom").addEventListener("blur", valCognom, true);
document.getElementById("email").addEventListener("blur", valEmail, true);
document.getElementById("telf").addEventListener("blur", valTelf, true);
document.getElementById("banc").addEventListener("blur", valBanc, true);
document.getElementById("contrasenya").addEventListener("blur", valPass, true);
document.getElementById("contrasenya2").addEventListener("blur", valPass2, true);

document.getElementById("nom").onkeyup = lsNom
document.getElementById("cognom").onkeyup = lsCognom
document.getElementById("telf").onkeyup = lsTelf
document.getElementById("adress").onkeyup =  lsAdress
document.getElementById("poblacio").onkeyup = lsPoblacio
document.getElementById("cp").onkeyup = lsCp
document.getElementById("pais").onkeyup = lsPais
document.getElementById("datepicker").onkeyup = lsDatePicker
document.getElementById("email").onkeyup = lsEmail
document.getElementById("banc").onkeyup = lsBanc

}

//Definició de funcions de validació

function valNom(){
  var elemVal = document.getElementById("nom");
  var regex = /^[A-Za-z]{2,20}$/;
  var valor =  elemVal.value;

  var errPara = document.createElement("p");
  var errText = document.createTextNode("Mínim 2 caràcters i màxim 20 caràcters");
  errPara.appendChild(errText);

  if(!regex.test(valor)){
    elemVal.classList.add('noValid');
    var divErr = document.getElementById("errNom");
    if (divErr.hasChildNodes()) {
      divErr.removeChild(divErr.childNodes[0]);
    }
    divErr.appendChild(errPara);
    if (elemVal.classList.contains('valid') ) {
      elemVal.classList.remove('valid');
    };

  } else{
    elemVal.classList.add('valid');

    var divErr = document.getElementById("errNom");
    if (divErr.hasChildNodes()) {
      divErr.removeChild(divErr.childNodes[0]);
    }

    if (elemVal.classList.contains('noValid') ) {
      elemVal.classList.remove('noValid');
    };
  }
}

   //Comprova si el COGNOM es correcte
   function valCognom(){
    var elemVal = document.getElementById("cognom");
    var regex = /^[A-Z a-z]{3,20}$/;
    var valor =  elemVal.value;

    var errPara = document.createElement("p");
    var errText = document.createTextNode("Mínim 3 caràcters i màxim 30 caràcters");
    errPara.appendChild(errText);

    if(!regex.test(valor)){
      elemVal.classList.add('noValid');

      var divErr = document.getElementById("errCognom");
      if (divErr.hasChildNodes()) {
      divErr.removeChild(divErr.childNodes[0]);
    }
      divErr.appendChild(errPara);
      if (elemVal.classList.contains('valid') ) {
        elemVal.classList.remove('valid');
      };

    } else{
      elemVal.classList.add('valid');

      var divErr = document.getElementById("errCognom");
      if (divErr.hasChildNodes()) {
      divErr.removeChild(divErr.childNodes[0]);
    }

      if (elemVal.classList.contains('noValid') ) {
        elemVal.classList.remove('noValid');
      };
    }
  }

    //Comprova si l'EMAIL es valid
    function valEmail(){
      var elemVal = document.getElementById("email");
      var regex = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
      var valor =  elemVal.value;

      var errPara = document.createElement("p");
      var errText = document.createTextNode("Introdueix un correu vàlid 'exemple@exemple.com'");
      errPara.appendChild(errText);

      if(!regex.test(valor)){
        elemVal.classList.add('noValid');

        var divErr = document.getElementById("errMail");
        if (divErr.hasChildNodes()) {
      divErr.removeChild(divErr.childNodes[0]);
    }
        divErr.appendChild(errPara);
        if (elemVal.classList.contains('valid') ) {
          elemVal.classList.remove('valid');
        };

      } else{
        elemVal.classList.add('valid');

        var divErr = document.getElementById("errMail");
        if (divErr.hasChildNodes()) {
      divErr.removeChild(divErr.childNodes[0]);
    }

        if (elemVal.classList.contains('noValid') ) {
          elemVal.classList.remove('noValid');
        };
      }
    }

    function valTelf(){
      var elemVal = document.getElementById("telf");
      var regex = /(\+376[0-9]{6})$/i;
      var valor =  elemVal.value;

      var errPara = document.createElement("p");
      var errText = document.createTextNode("Introdueix un telèfon de 6 números.");
      errPara.appendChild(errText);

      if(!regex.test(valor)){
        elemVal.classList.add('noValid');

        var divErr = document.getElementById("errTelf");
        if (divErr.hasChildNodes()) {
      divErr.removeChild(divErr.childNodes[0]);
    }
        divErr.appendChild(errPara);
        if (elemVal.classList.contains('valid') ) {
          elemVal.classList.remove('valid');
        };

      } else{
        elemVal.classList.add('valid');

        var divErr = document.getElementById("errTelf");
        if (divErr.hasChildNodes()) {
      divErr.removeChild(divErr.childNodes[0]);
    }

        if (elemVal.classList.contains('noValid') ) {
          elemVal.classList.remove('noValid');
        };
      }
    }

    function valBanc(){
      var elemVal = document.getElementById("banc");
      var regex = /AD[0-9]{2}000(1|3)[0-9]{16}/i;
      var regAndBank = /AD[0-9]{2}0001[0-9]{16}/i;
      var regCredit = /AD[0-9]{2}0003[0-9]{16}/i;

      var bankPara = document.createElement("p");
      var andBank = document.createTextNode("AndBank");
      var credit = document.createTextNode("Crèdit Andorrà");
      var valor =  elemVal.value;

      var errPara = document.createElement("p");
      var errText = document.createTextNode("Introdueix un IBAN vàlid (ADCC BBBB SSSS ZZZZ ZZZZ ZZZZ).");
      errPara.appendChild(errText);

      if(!regex.test(valor)){
        elemVal.classList.add('noValid');
        var divErr = document.getElementById("errBanc");
        if (divErr.hasChildNodes()) {
      divErr.removeChild(divErr.childNodes[0]);
    }
        divErr.appendChild(errPara);
        if (elemVal.classList.contains('valid') ) {
          elemVal.classList.remove('valid');
        };
      } else{
        elemVal.classList.add('valid');

        var divErr = document.getElementById("errBanc");
        if (divErr.hasChildNodes()) {
      divErr.removeChild(divErr.childNodes[0]);
    }

        if(regAndBank.test(valor)){
          bankPara.appendChild(andBank);
          divErr.appendChild(bankPara);
        }
        if(regCredit.test(valor)){
          bankPara.appendChild(credit);
          divErr.appendChild(bankPara);
        }

        if (elemVal.classList.contains('noValid') ) {
          elemVal.classList.remove('noValid');
        };
      }
    }

    function valPass(){
      var elemVal = document.getElementById("contrasenya");
      var regex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d{2,})[^ ]{6,}$/;
      var valor =  elemVal.value;

      var errPara = document.createElement("p");
      var errText = document.createTextNode("Ha de contenir un mínim de 2 digits, una majúscula i una minúscula i 6 caràcters de llarg");
      errPara.appendChild(errText);

      if(!regex.test(valor)){
        elemVal.classList.add('noValid');
        var divErr = document.getElementById("errPass");
        if (divErr.hasChildNodes()) {
      divErr.removeChild(divErr.childNodes[0]);
    }
        divErr.appendChild(errPara);
        if (elemVal.classList.contains('valid') ) {
          elemVal.classList.remove('valid');
        };

      } else{
        elemVal.classList.add('valid');

        var divErr = document.getElementById("errPass");
        if (divErr.hasChildNodes()) {
      divErr.removeChild(divErr.childNodes[0]);
    }

        if (elemVal.classList.contains('noValid') ) {
          elemVal.classList.remove('noValid');
        };
      }
    }

    function valPass2(){
      var elemVal = document.getElementById("contrasenya2");
      var contra = document.getElementById("contrasenya").value;
      var valor =  elemVal.value;

      var errPara = document.createElement("p");
      var errText = document.createTextNode("Les contrasenyes han de coincidir");
      errPara.appendChild(errText);

      if(valor != contra){
        elemVal.classList.add('noValid');
        var divErr = document.getElementById("errPass2");
        if (divErr.hasChildNodes()) {
      divErr.removeChild(divErr.childNodes[0]);
    }
        divErr.appendChild(errPara);
        if (elemVal.classList.contains('valid') ) {
          elemVal.classList.remove('valid');
        };

      } else{
        elemVal.classList.add('valid');

        var divErr = document.getElementById("errPass2");
        if (divErr.hasChildNodes()) {
      divErr.removeChild(divErr.childNodes[0]);
    }

        if (elemVal.classList.contains('noValid') ) {
          elemVal.classList.remove('noValid');
        };
      }
    }

    //Funcions de guardar al localStorage

    function lsNom () {
      var elemLS = document.getElementById("nom").value;
      localStorage.setItem('nom', elemLS);
    }

    function lsCognom () {
      var elemLS = document.getElementById("cognom").value;
      localStorage.setItem('cognom', elemLS);
    }

    function lsTelf () {
      var elemLS = document.getElementById("telf").value;
      localStorage.setItem('telf', elemLS);
    }

    function lsAdress () {
      var elemLS = document.getElementById("adress").value;
      localStorage.setItem('adress', elemLS);
    }

    function lsPoblacio () {
      var elemLS = document.getElementById("poblacio").value;
      localStorage.setItem('poblacio', elemLS);
    }

    function lsCp () {
      var elemLS = document.getElementById("cp").value;
      localStorage.setItem('cp', elemLS);
    }
    function lsPais () {
      var elemLS = document.getElementById("pais").value;
      localStorage.setItem('pais', elemLS);
    }

    function lsDatePicker() {
      var elemLS = document.getElementById("datepicker").value;
      localStorage.setItem('datepicker', elemLS);
    }

    function lsEmail () {
      var elemLS = document.getElementById("email").value;
      localStorage.setItem('email', elemLS);
    }

    function lsBanc () {
      var elemLS = document.getElementById("banc").value;
      localStorage.setItem('banc', elemLS);
    }

//Recuperem valors de la localStorage al carregar la pagina (si existeixen)
    function init() {

      if (localStorage["nom"]) {
       document.getElementById("nom").value = localStorage.getItem('nom');
     }
     if (localStorage["cognom"]) {
       document.getElementById("cognom").value = localStorage.getItem('cognom');
     }
     if (localStorage["telf"]) {
       document.getElementById("telf").value = localStorage.getItem('telf');
     }
     if (localStorage["adress"]) {
       document.getElementById("adress").value = localStorage.getItem('adress');
     }
     if (localStorage["poblacio"]) {
       document.getElementById("poblacio").value = localStorage.getItem('poblacio');
     }
     if (localStorage["cp"]) {
       document.getElementById("cp").value = localStorage.getItem('cp');
     }
     if (localStorage["pais"]) {
       document.getElementById("pais").value = localStorage.getItem('pais');
     }
     if (localStorage["datepicker"]) {
       document.getElementById("datepicker").value = localStorage.getItem('datepicker');
     }
     if (localStorage["email"]) {
       document.getElementById("email").value = localStorage.getItem('email');
     }
     if (localStorage["banc"]) {
       document.getElementById("banc").value = localStorage.getItem('banc');
     }
   }

<commit_msg>Afegit validació de tot el formulari (validacioTot()) Afegida funció per desactivar i activar el botó de registrar. Fixed #2 i Fixed #3<commit_after>
window.onload = function () {

  associaDOMevents();

  //localStorage
  init();

};

//Inici funcions

function associaDOMevents() {
//Associar events de la Vista
//variables
document.getElementById("nom").addEventListener("blur", valNom , true);
document.getElementById("cognom").addEventListener("blur", valCognom , true);
document.getElementById("email").addEventListener("blur", valEmail , true);
document.getElementById("telf").addEventListener("blur", valTelf , true);
document.getElementById("banc").addEventListener("blur", valBanc , true);
document.getElementById("contrasenya").addEventListener("blur", valPass , true);
document.getElementById("contrasenya2").addEventListener("blur", valPass2 , true);

document.getElementById("condicions").onchange = validarTot;

document.getElementById("nom").onkeyup = lsNom;
document.getElementById("cognom").onkeyup = lsCognom;
document.getElementById("telf").onkeyup = lsTelf;
document.getElementById("adress").onkeyup =  lsAdress;
document.getElementById("poblacio").onkeyup = lsPoblacio;
document.getElementById("cp").onkeyup = lsCp;
document.getElementById("pais").onkeyup = lsPais;
document.getElementById("datepicker").onkeyup = lsDatePicker;
document.getElementById("email").onkeyup = lsEmail;
document.getElementById("banc").onkeyup = lsBanc;

  //Calendari de "naixement"
  $(function() {
    $( "#datepicker" ).datepicker();
  });

}

//Definició de funcions de validació

function valNom(){
  var elemVal = document.getElementById("nom");
  var regex = /^[A-Za-z]{2,20}$/;
  var valor =  elemVal.value;

  var errPara = document.createElement("p");
  var errText = document.createTextNode("Mínim 2 caràcters i màxim 20 caràcters");
  errPara.appendChild(errText);

  if(!regex.test(valor)){
    elemVal.classList.add('noValid');
    var divErr = document.getElementById("errNom");
    if (divErr.hasChildNodes()) {
      divErr.removeChild(divErr.childNodes[0]);
    }
    divErr.appendChild(errPara);
    if (elemVal.classList.contains('valid') ) {
      elemVal.classList.remove('valid');
    };
    return false;
  } else{
    elemVal.classList.add('valid');

    var divErr = document.getElementById("errNom");
    if (divErr.hasChildNodes()) {
      divErr.removeChild(divErr.childNodes[0]);
    }

    if (elemVal.classList.contains('noValid') ) {
      elemVal.classList.remove('noValid');
    };
    return true;
  }
}

   //Comprova si el COGNOM es correcte
   function valCognom(){
    var elemVal = document.getElementById("cognom");
    var regex = /^[A-Z a-z]{3,20}$/;
    var valor =  elemVal.value;

    var errPara = document.createElement("p");
    var errText = document.createTextNode("Mínim 3 caràcters i màxim 30 caràcters");
    errPara.appendChild(errText);

    if(!regex.test(valor)){
      elemVal.classList.add('noValid');

      var divErr = document.getElementById("errCognom");
      if (divErr.hasChildNodes()) {
        divErr.removeChild(divErr.childNodes[0]);
      }
      divErr.appendChild(errPara);
      if (elemVal.classList.contains('valid') ) {
        elemVal.classList.remove('valid');
      };
      return false
    } else{
      elemVal.classList.add('valid');

      var divErr = document.getElementById("errCognom");
      if (divErr.hasChildNodes()) {
        divErr.removeChild(divErr.childNodes[0]);
      }

      if (elemVal.classList.contains('noValid') ) {
        elemVal.classList.remove('noValid');
      };
      return true
    }
  }

    //Comprova si l'EMAIL es valid
    function valEmail(){
      var elemVal = document.getElementById("email");
      var regex = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
      var valor =  elemVal.value;

      var errPara = document.createElement("p");
      var errText = document.createTextNode("Introdueix un correu vàlid 'exemple@exemple.com'");
      errPara.appendChild(errText);

      if(!regex.test(valor)){
        elemVal.classList.add('noValid');

        var divErr = document.getElementById("errMail");
        if (divErr.hasChildNodes()) {
          divErr.removeChild(divErr.childNodes[0]);
        }
        divErr.appendChild(errPara);
        if (elemVal.classList.contains('valid') ) {
          elemVal.classList.remove('valid');
        };
        return false;
      } else{
        elemVal.classList.add('valid');

        var divErr = document.getElementById("errMail");
        if (divErr.hasChildNodes()) {
          divErr.removeChild(divErr.childNodes[0]);
        }

        if (elemVal.classList.contains('noValid') ) {
          elemVal.classList.remove('noValid');
        };
        return true;
      }
    }

    function valTelf(){
      var elemVal = document.getElementById("telf");
      var regex = /(\+376[0-9]{6})$/i;
      var valor =  elemVal.value;

      var errPara = document.createElement("p");
      var errText = document.createTextNode("Introdueix un telèfon de 6 números.");
      errPara.appendChild(errText);

      if(!regex.test(valor)){
        elemVal.classList.add('noValid');

        var divErr = document.getElementById("errTelf");
        if (divErr.hasChildNodes()) {
          divErr.removeChild(divErr.childNodes[0]);
        }
        divErr.appendChild(errPara);
        if (elemVal.classList.contains('valid') ) {
          elemVal.classList.remove('valid');
        };
        return false;
      } else{
        elemVal.classList.add('valid');

        var divErr = document.getElementById("errTelf");
        if (divErr.hasChildNodes()) {
          divErr.removeChild(divErr.childNodes[0]);
        }

        if (elemVal.classList.contains('noValid') ) {
          elemVal.classList.remove('noValid');
        };
        return true;
      }
    }

    function valBanc(){
      var elemVal = document.getElementById("banc");
      var regex = /AD[0-9]{2}000(1|3)[0-9]{16}/i;
      var regAndBank = /AD[0-9]{2}0001[0-9]{16}/i;
      var regCredit = /AD[0-9]{2}0003[0-9]{16}/i;

      var bankPara = document.createElement("p");
      var andBank = document.createTextNode("AndBank");
      var credit = document.createTextNode("Crèdit Andorrà");
      var valor =  elemVal.value;

      var errPara = document.createElement("p");
      var errText = document.createTextNode("Introdueix un IBAN vàlid (ADCC BBBB SSSS ZZZZ ZZZZ ZZZZ).");
      errPara.appendChild(errText);

      if(!regex.test(valor)){
        elemVal.classList.add('noValid');
        var divErr = document.getElementById("errBanc");
        if (divErr.hasChildNodes()) {
          divErr.removeChild(divErr.childNodes[0]);
        }
        divErr.appendChild(errPara);
        if (elemVal.classList.contains('valid') ) {
          elemVal.classList.remove('valid');
        };
        return false;
      } else{
        elemVal.classList.add('valid');

        var divErr = document.getElementById("errBanc");
        if (divErr.hasChildNodes()) {
          divErr.removeChild(divErr.childNodes[0]);
        }

        if(regAndBank.test(valor)){
          bankPara.appendChild(andBank);
          divErr.appendChild(bankPara);
        }
        if(regCredit.test(valor)){
          bankPara.appendChild(credit);
          divErr.appendChild(bankPara);
        }

        if (elemVal.classList.contains('noValid') ) {
          elemVal.classList.remove('noValid');
        };
        return true;
      }
    }

    function valPass(){
      var elemVal = document.getElementById("contrasenya");
      var regex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d{2,})[^ ]{6,}$/;
      var valor =  elemVal.value;

      var errPara = document.createElement("p");
      var errText = document.createTextNode("Ha de contenir un mínim de 2 digits, una majúscula i una minúscula i 6 caràcters de llarg");
      errPara.appendChild(errText);

      if(!regex.test(valor)){
        elemVal.classList.add('noValid');
        var divErr = document.getElementById("errPass");
        if (divErr.hasChildNodes()) {
          divErr.removeChild(divErr.childNodes[0]);
        }
        divErr.appendChild(errPara);
        if (elemVal.classList.contains('valid') ) {
          elemVal.classList.remove('valid');
        };
        return false;
      } else{
        elemVal.classList.add('valid');

        var divErr = document.getElementById("errPass");
        if (divErr.hasChildNodes()) {
          divErr.removeChild(divErr.childNodes[0]);
        }

        if (elemVal.classList.contains('noValid') ) {
          elemVal.classList.remove('noValid');
        };
        return true;
      }
    }

    function valPass2(){
      var elemVal = document.getElementById("contrasenya2");
      var contra = document.getElementById("contrasenya").value;
      var valor =  elemVal.value;

      var errPara = document.createElement("p");
      var errText = document.createTextNode("Les contrasenyes han de coincidir");
      errPara.appendChild(errText);

      if(valor != contra || valor===""){
        elemVal.classList.add('noValid');
        var divErr = document.getElementById("errPass2");
        if (divErr.hasChildNodes()) {
          divErr.removeChild(divErr.childNodes[0]);
        }
        divErr.appendChild(errPara);
        if (elemVal.classList.contains('valid') ) {
          elemVal.classList.remove('valid');
        };
        return false;
      } else{
        elemVal.classList.add('valid');

        var divErr = document.getElementById("errPass2");
        if (divErr.hasChildNodes()) {
          divErr.removeChild(divErr.childNodes[0]);
        }

        if (elemVal.classList.contains('noValid') ) {
          elemVal.classList.remove('noValid');
        };
        return true;
      }
    }

    //Validar tot formulari
    function validarTot (){
      valNom();
      valCognom();
      valEmail();
      valTelf();
      valBanc();
      valPass();
      valPass2();
      if (valNom() && valCognom() && valEmail() && valTelf() && valBanc() && valPass() && valPass2()) {
        var boto = document.getElementById("registrar");
        boto.classList.remove("des");
        boto.setAttribute("disabled", "false");
      } else {
        var boto = document.getElementById("registrar");
        boto.classList.add("des");
        boto.setAttribute("disabled", "true");
        document.getElementById("condicions").checked = false;
      }
    }

    //Funcions de guardar al localStorage

    function lsNom () {
      var elemLS = document.getElementById("nom").value;
      localStorage.setItem('nom', elemLS);
    }

    function lsCognom () {
      var elemLS = document.getElementById("cognom").value;
      localStorage.setItem('cognom', elemLS);
    }

    function lsTelf () {
      var elemLS = document.getElementById("telf").value;
      localStorage.setItem('telf', elemLS);
    }

    function lsAdress () {
      var elemLS = document.getElementById("adress").value;
      localStorage.setItem('adress', elemLS);
    }

    function lsPoblacio () {
      var elemLS = document.getElementById("poblacio").value;
      localStorage.setItem('poblacio', elemLS);
    }

    function lsCp () {
      var elemLS = document.getElementById("cp").value;
      localStorage.setItem('cp', elemLS);
    }
    function lsPais () {
      var elemLS = document.getElementById("pais").value;
      localStorage.setItem('pais', elemLS);
    }

    function lsDatePicker() {
      var elemLS = document.getElementById("datepicker").value;
      localStorage.setItem('datepicker', elemLS);
    }

    function lsEmail () {
      var elemLS = document.getElementById("email").value;
      localStorage.setItem('email', elemLS);
    }

    function lsBanc () {
      var elemLS = document.getElementById("banc").value;
      localStorage.setItem('banc', elemLS);
    }

//Recuperem valors de la localStorage al carregar la pagina (si existeixen)
function init() {

  if (localStorage["nom"]) {
   document.getElementById("nom").value = localStorage.getItem('nom');
 }
 if (localStorage["cognom"]) {
   document.getElementById("cognom").value = localStorage.getItem('cognom');
 }
 if (localStorage["telf"]) {
   document.getElementById("telf").value = localStorage.getItem('telf');
 }
 if (localStorage["adress"]) {
   document.getElementById("adress").value = localStorage.getItem('adress');
 }
 if (localStorage["poblacio"]) {
   document.getElementById("poblacio").value = localStorage.getItem('poblacio');
 }
 if (localStorage["cp"]) {
   document.getElementById("cp").value = localStorage.getItem('cp');
 }
 if (localStorage["pais"]) {
   document.getElementById("pais").value = localStorage.getItem('pais');
 }
 if (localStorage["datepicker"]) {
   document.getElementById("datepicker").value = localStorage.getItem('datepicker');
 }
 if (localStorage["email"]) {
   document.getElementById("email").value = localStorage.getItem('email');
 }
 if (localStorage["banc"]) {
   document.getElementById("banc").value = localStorage.getItem('banc');
 }
}

<|endoftext|>


<commit_before>(function() {

		alert('inside main.js');
		var adapter = new LocalStorageAdapter();

		if(window.addEventListener) {
			alert(window.addEventListener);
		} else {
			alert('no addEventListener');
		}

    /* --------------------------------- Event Registration -------------------------------- */
    window.addEventListener('hashchange', route);

    /* ---------------------------------- Local Functions ---------------------------------- */

				alert('calling route');
    route();

    function replaceChildren(parentElement, children) {
	parentElement.innerHTML = '';
	parentElement.appendChild(children);
    }

    function route() {
        var hash = window.location.hash;
	var content = $('#content');

		alert('inside route');
	var showHome = function(){
		replaceChildren(content, new HomeView(adapter).render());
	};

	var showSessions = function(){
		var sessionsToDisplay = adapter.getSessions();
		replaceChildren(content, new SessionsView(sessionsToDisplay, adapter).render());
	};

	var showSpeakers = function(){
		var speakersToDisplay = adapter.getSpeakers();
		replaceChildren(content, new SpeakersView(speakersToDisplay).render());

	};	if(!hash){
		alert('running showHome');
		showHome();
		return;
	}

	var showSessionsBySpeakers = function(){
		var speakers = getUrlVars().speakers;
		var sessionsToDisplay = adapter.getSessionsBySpeaker(speakers);
		replaceChildren(content, new SessionsView(sessionsToDisplay, adapter).render());

	};

	var showFamilySessions = function(){
		var category = 'Family';
		var sessionsToDisplay = adapter.getSessionsByCategory(category);
		replaceChildren(content, new SessionsView(sessionsToDisplay, adapter).render());

	};

	if(!hash){
		showHome();
		return;
	}

	var showSessionDetails = function() {
		var id = parseInt(getUrlVars().id, 10);
		var sessionToDisplay = adapter.getSessionById(id);
		replaceChildren(content, new SessionDetailsView(sessionToDisplay).render());
	};

	var showSessionsByTitle = function() {
		var title = getUrlVars().title;
		var sessionsToDisplay = adapter.getSessionsByTitle(title);
		replaceChildren(content, new SessionsView(sessionsToDisplay).render());
	};

	var showSessionsByDay = function() {
		var day = getUrlVars().day;
		var sessionsToDisplay = adapter.getSessionsByDay(day);
		replaceChildren(content, new SessionsView(sessionsToDisplay).render());
	};

	var showMySchedule = function() {
		var sessionsToDisplay = adapter.getSessionsInMySchedule();
		replaceChildren(content, new SessionsView(sessionsToDisplay, adapter).render());
	};

	var showSessionsByScheduled = function() {
		var scheduled = getUrlVars().scheduled;
		var sessionsToDisplay = adapter.getSessionsByScheduled(scheduled);
		replaceChildren(content, new SessionsView(sessionsToDisplay).render());
	};

	var showMap = function(){
		replaceChildren(content, new MapView().render());
	};

	var showPolicies = function(){
		replaceChildren(content, new PoliciesView().render());
	};

	var hashWithoutQueryString = hash;
	if(hash.lastIndexOf('?') !== -1) {
		hashWithoutQueryString = hash.substring(0, hash.lastIndexOf('?'))
	}

	var routeTable = {
	'#home': showHome,
	'#sessions': showSessions,
	'#speakers': showSpeakers,
	'#showsessionsbytitle': showSessionsByTitle,
	'#showsessionsbyday': showSessionsByDay,
	'#showsessionsbyscheduled': showSessionsByScheduled,
	'#showsessionsbyspeaker': showSessionsBySpeakers,
	'#familysessions': showFamilySessions,
	'#sessiondetails': showSessionDetails,
	'#myschedule': showMySchedule,
	'#map': showMap,
	'#policies': showPolicies,
	};

	routeTable[hashWithoutQueryString]();
    }

		alert('calling route');
    route();
})();
<commit_msg>Removed alerts<commit_after>(function() {

		var adapter = new LocalStorageAdapter();

    /* --------------------------------- Event Registration -------------------------------- */
    window.addEventListener('hashchange', route);

    /* ---------------------------------- Local Functions ---------------------------------- */

    function replaceChildren(parentElement, children) {
	parentElement.innerHTML = '';
	parentElement.appendChild(children);
    }

    function route() {
        var hash = window.location.hash;
	var content = $('#content');

	var showHome = function(){
		replaceChildren(content, new HomeView(adapter).render());
	};

	var showSessions = function(){
		var sessionsToDisplay = adapter.getSessions();
		replaceChildren(content, new SessionsView(sessionsToDisplay, adapter).render());
	};

	var showSpeakers = function(){
		var speakersToDisplay = adapter.getSpeakers();
		replaceChildren(content, new SpeakersView(speakersToDisplay).render());

	};	if(!hash){
		showHome();
		return;
	}

	var showSessionsBySpeakers = function(){
		var speakers = getUrlVars().speakers;
		var sessionsToDisplay = adapter.getSessionsBySpeaker(speakers);
		replaceChildren(content, new SessionsView(sessionsToDisplay, adapter).render());

	};

	var showFamilySessions = function(){
		var category = 'Family';
		var sessionsToDisplay = adapter.getSessionsByCategory(category);
		replaceChildren(content, new SessionsView(sessionsToDisplay, adapter).render());

	};

	if(!hash){
		showHome();
		return;
	}

	var showSessionDetails = function() {
		var id = parseInt(getUrlVars().id, 10);
		var sessionToDisplay = adapter.getSessionById(id);
		replaceChildren(content, new SessionDetailsView(sessionToDisplay).render());
	};

	var showSessionsByTitle = function() {
		var title = getUrlVars().title;
		var sessionsToDisplay = adapter.getSessionsByTitle(title);
		replaceChildren(content, new SessionsView(sessionsToDisplay).render());
	};

	var showSessionsByDay = function() {
		var day = getUrlVars().day;
		var sessionsToDisplay = adapter.getSessionsByDay(day);
		replaceChildren(content, new SessionsView(sessionsToDisplay).render());
	};

	var showMySchedule = function() {
		var sessionsToDisplay = adapter.getSessionsInMySchedule();
		replaceChildren(content, new SessionsView(sessionsToDisplay, adapter).render());
	};

	var showSessionsByScheduled = function() {
		var scheduled = getUrlVars().scheduled;
		var sessionsToDisplay = adapter.getSessionsByScheduled(scheduled);
		replaceChildren(content, new SessionsView(sessionsToDisplay).render());
	};

	var showMap = function(){
		replaceChildren(content, new MapView().render());
	};

	var showPolicies = function(){
		replaceChildren(content, new PoliciesView().render());
	};

	var hashWithoutQueryString = hash;
	if(hash.lastIndexOf('?') !== -1) {
		hashWithoutQueryString = hash.substring(0, hash.lastIndexOf('?'))
	}

	var routeTable = {
	'#home': showHome,
	'#sessions': showSessions,
	'#speakers': showSpeakers,
	'#showsessionsbytitle': showSessionsByTitle,
	'#showsessionsbyday': showSessionsByDay,
	'#showsessionsbyscheduled': showSessionsByScheduled,
	'#showsessionsbyspeaker': showSessionsBySpeakers,
	'#familysessions': showFamilySessions,
	'#sessiondetails': showSessionDetails,
	'#myschedule': showMySchedule,
	'#map': showMap,
	'#policies': showPolicies,
	};

	routeTable[hashWithoutQueryString]();
    }

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