<commit_before>/*jshint globalstrict:true*/
/*global angular:false*/
'use strict';

var isDefined = angular.isDefined,
    isFunction = angular.isFunction,
    isString = angular.isString,
    isObject = angular.isObject,
    isArray = angular.isArray,
    forEach = angular.forEach,
    extend = angular.extend,
    copy = angular.copy;

var abstractKey = 'abstract';

function inherit(parent, extra) {
  return extend(new (extend(function() {}, { prototype: parent }))(), extra);
}

function defaults(opts, defs) {
  return extend({}, defs, pick(opts || {}, objectKeys(defs)));
}

function merge(dst) {
  forEach(arguments, function(obj) {
    if (obj !== dst) {
      forEach(obj, function(value, key) {
        if (!dst.hasOwnProperty(key)) dst[key] = value;
      });
    }
  });
  return dst;
}

/**
 * Recursive function iterator
 */
function FunctionIterator(items) {

  var it = function(initial) {
    var noOp = function() {};
    var get  = (function() { return this.next() || noOp; }).bind(this);
    var next = function() { return get()(initial, next); };
    return next();
  };

  extend(this, {
    items: items,
    _current: -1
  });

  return it.bind(this);
}

FunctionIterator.prototype.current = function() {
  return this.items[this._current];
};

FunctionIterator.prototype.next = function() {
  this._current++;
  return this.current();
};

/**
 * Finds the common ancestor path between two states.
 *
 * @param {Object} first The first state.
 * @param {Object} second The second state.
 * @return {Array} Returns an array of state names in descending order, not including the root.
 */
function ancestors(first, second) {
  var path = [];

  for (var n in first.path) {
    if (first.path[n] !== second.path[n]) break;
    path.push(first.path[n]);
  }
  return path;
}

/**
 * IE8-safe wrapper for `Object.keys()`.
 *
 * @param {Object} object A JavaScript object.
 * @return {Array} Returns the keys of the object as an array.
 */
function objectKeys(object) {
  if (Object.keys) {
    return Object.keys(object);
  }
  var result = [];

  forEach(object, function(val, key) {
    result.push(key);
  });
  return result;
}

/**
 * IE8-safe wrapper for `Array.prototype.indexOf()`.
 *
 * @param {Array} array A JavaScript array.
 * @param {*} value A value to search the array for.
 * @return {Number} Returns the array index value of `value`, or `-1` if not present.
 */
var arraySearch = indexOf;
function indexOf(array, value) {
  if (Array.prototype.indexOf) {
    return array.indexOf(value, Number(arguments[2]) || 0);
  }
  var len = array.length >>> 0, from = Number(arguments[2]) || 0;
  from = (from < 0) ? Math.ceil(from) : Math.floor(from);

  if (from < 0) from += len;

  for (; from < len; from++) {
    if (from in array && array[from] === value) return from;
  }
  return -1;
}

/**
 * Merges a set of parameters with all parameters inherited between the common parents of the
 * current state and a given destination state.
 *
 * @param {Object} currentParams The value of the current state parameters ($stateParams).
 * @param {Object} newParams The set of parameters which will be composited with inherited params.
 * @param {Object} $current Internal definition of object representing the current state.
 * @param {Object} $to Internal definition of object representing state to transition to.
 */
function inheritParams(currentParams, newParams, $current, $to) {
  var parents = ancestors($current, $to), parentParams, inherited = {}, inheritList = [];

  for (var i in parents) {
    if (!parents[i].params) continue;
    parentParams = objectKeys(parents[i].params);
    if (!parentParams.length) continue;

    for (var j in parentParams) {
      if (indexOf(inheritList, parentParams[j]) >= 0) continue;
      inheritList.push(parentParams[j]);
      inherited[parentParams[j]] = currentParams[parentParams[j]];
    }
  }
  return extend({}, inherited, newParams);
}

/**
 * Performs a non-strict comparison of the subset of two objects, defined by a list of keys.
 *
 * @param {Object} a The first object.
 * @param {Object} b The second object.
 * @param {Array} keys The list of keys within each object to compare. If the list is empty or not specified,
 *                     it defaults to the list of keys in `a`.
 * @return {Boolean} Returns `true` if the keys match, otherwise `false`.
 */
function equalForKeys(a, b, keys) {
  if (!keys) {
    keys = [];
    for (var n in a) keys.push(n); // Used instead of Object.keys() for IE8 compatibility
  }

  for (var i=0; i<keys.length; i++) {
    var k = keys[i];
    if (a[k] != b[k]) return false; // Not '===', values aren't necessarily normalized
  }
  return true;
}

/**
 * Returns the subset of an object, based on a list of keys.
 *
 * @param {Array} keys
 * @param {Object} values
 * @return {Boolean} Returns a subset of `values`.
 */
function filterByKeys(keys, values) {
  var filtered = {};

  forEach(keys, function (name) {
    if (isDefined(values[name])) filtered[name] = values[name];
  });
  return filtered;
}

// like _.indexBy
// when you know that your index values will be unique, or you want last-one-in to win
function indexBy(array, propName) {
  var result = {};
  forEach(array, function(item) {
    result[item[propName]] = item;
  });
  return result;
}

// extracted from underscore.js
// Return a copy of the object only containing the whitelisted properties.
function pick(obj) {
  var copy = {};
  var keys = Array.prototype.concat.apply(Array.prototype, Array.prototype.slice.call(arguments, 1));
  for (var key in obj) {
    if (keys.indexOf(key) !== -1) copy[key] = obj[key];
  }
  return copy;
}

// extracted from underscore.js
// Return a copy of the object omitting the blacklisted properties.
function omit(obj) {
  var copy = {};
  var keys = Array.prototype.concat.apply(Array.prototype, Array.prototype.slice.call(arguments, 1));
  for (var key in obj) {
    if (keys.indexOf(key) === -1) copy[key] = obj[key];
  }
  return copy;
}

function pluck(collection, key) {
  return map(collection, prop(key));
}

function filter(collection, callback) {
  var arr = isArray(collection), result = arr ? [] : {};
  forEach(collection, function(val, i) {
    if (callback(val, i)) {
      if (arr) result.push(val);
      else result[i] = val;
    }
  });
  return result;
}

function _filter(callback) {
  return function (collection) { return filter(collection, callback); };
}

function find(collection, callback) {
  var result;

  forEach(collection, function(val, i) {
    if (result) return;
    if (callback(val, i)) result = val;
  });

  return result;
}

function tpl(string, vals) {
  return string.replace(/\{([\w.]+)\}/g, function(_, key) {
    return parse(key)(vals) || "";
  });
}

function map(collection, callback) {
  var result = isArray(collection) ? [] : {};

  forEach(collection, function(val, i) {
    result[i] = callback(val, i);
  });
  return result;
}

function _map(callback) {
  return function mapper(collection) { return map(collection, callback); };
}

function unnest(list) {
  var result = [];
  forEach(list, function(val) { result = result.concat(val); });
  return result;
}

function unroll(callback) {
  callback = callback || angular.identity;

  return function(object) {
    var result = [];
    forEach(object, function(val, key) {
      var tmp = {};
      tmp[key] = val;
      result.push(callback(tmp));
    });
    return result;
  };
}

function flattenPrototypeChain(obj) {
  var objs = [];
  do {
    objs.push(obj);
  } while ((obj = Object.getPrototypeOf(obj)));
  objs.reverse();

  var result = {};
  forEach(objs, function(obj) {
    extend(result, obj);
  });
  return result;
}

// Return a completely flattened version of an array.
function flatten (array) {
  function _flatten(input, output) {
    forEach(input, function(value) {
      if (angular.isArray(value)) {
        _flatten(value, output);
      } else {
        output.push(value);
      }
    });
    return output;
  }

  return _flatten(array, []);
}

// Checks if a value is injectable
function isInjectable(value) {
  return (isFunction(value) || (isArray(value) && isFunction(value[value.length - 1])));
}

function isNull(o) { return o === null; }

function compose() {
  var args = arguments;
  var start = args.length - 1;
  return function() {
    var i = start;
    var result = args[start].apply(this, arguments);
    while (i--) result = args[i].call(this, result);
    return result;
  };
}

function pipe() {
  return compose.apply(null, [].slice.call(arguments).reverse());
}

function prop(name) {
  return function(obj) { return obj && obj[name]; };
}

function parse(name) {
  return pipe.apply(null, name.split("\.").map(prop));
}

function not(fn) {
  return function() { return !fn.apply(null, [].slice.call(arguments)); };
}

function and(fn1, fn2) {
  return function() {
    return fn1.apply(null, [].slice.call(arguments)) && fn2.apply(null, [].slice.call(arguments));
  };
}

function or(fn1, fn2) {
  return function() {
    return fn1.apply(null, [].slice.call(arguments)) || fn2.apply(null, [].slice.call(arguments));
  };
}

function is(ctor) {
  return function(val) { return val != null && val.constructor === ctor || val instanceof ctor; };
}

function eq(comp) {
  return function(val) { return val === comp; };
}

function isEq(fn1, fn2) {
  return function() {
    var args = [].slice.call(arguments);
    return fn1.apply(null, args) === fn2.apply(null, args);
  };
}

function val(v) {
  return function() { return v; };
}

function invoke(method, args) {
  return function(obj) {
    return obj[method].apply(obj, args);
  };
}

function pattern(struct) {
  return function(val) {
    for (var i = 0; i < struct.length; i++) {
      if (struct[i][0](val)) return struct[i][1](val);
    }
  };
}

var isPromise = and(isObject, pipe(prop('then'), isFunction));

var GlobBuilder = (function() {

  function Glob(text) {

    var glob = text.split('.');

    // Returns true if glob matches current $state name.
    this.matches = function(name) {
      var segments = name.split('.');

      // match single stars
      for (var i = 0, l = glob.length; i < l; i++) {
        if (glob[i] === '*') segments[i] = '*';
      }

      // match greedy starts
      if (glob[0] === '**') {
         segments = segments.slice(segments.indexOf(glob[1]));
         segments.unshift('**');
      }
      // match greedy ends
      if (glob[glob.length - 1] === '**') {
         segments.splice(segments.indexOf(glob[glob.length - 2]) + 1, Number.MAX_VALUE);
         segments.push('**');
      }
      if (glob.length != segments.length) return false;

      return segments.join('') === glob.join('');
    };
  }

  return {
    // Checks text to see if it looks like a glob.
    is: function(text) {
      return text.indexOf('*') > -1;
    },

    // Factories a glob matcher from a string
    fromString: function(text) {
      if (!this.is(text)) return null;
      return new Glob(text);
    }
  };
})();

/**
 * @ngdoc overview
 * @name ui.router.util
 *
 * @description
 * # ui.router.util sub-module
 *
 * This module is a dependency of other sub-modules. Do not include this module as a dependency
 * in your angular app (use {@link ui.router} module instead).
 *
 */
angular.module('ui.router.util', ['ng']);

/**
 * @ngdoc overview
 * @name ui.router.router
 *
 * @requires ui.router.util
 *
 * @description
 * # ui.router.router sub-module
 *
 * This module is a dependency of other sub-modules. Do not include this module as a dependency
 * in your angular app (use {@link ui.router} module instead).
 */
angular.module('ui.router.router', ['ui.router.util']);

/**
 * @ngdoc overview
 * @name ui.router.state
 *
 * @requires ui.router.router
 * @requires ui.router.util
 *
 * @description
 * # ui.router.state sub-module
 *
 * This module is a dependency of the main ui.router module. Do not include this module as a dependency
 * in your angular app (use {@link ui.router} module instead).
 *
 */
angular.module('ui.router.state', ['ui.router.router', 'ui.router.util']);

/**
 * @ngdoc overview
 * @name ui.router
 *
 * @requires ui.router.state
 *
 * @description
 * # ui.router
 *
 * ## The main module for ui.router
 * There are several sub-modules included with the ui.router module, however only this module is needed
 * as a dependency within your angular app. The other modules are for organization purposes.
 *
 * The modules are:
 * * ui.router - the main "umbrella" module
 * * ui.router.router -
 *
 * *You'll need to include **only** this module as the dependency within your angular app.*
 *
 * <pre>
 * <!doctype html>
 * <html ng-app="myApp">
 * <head>
 *   <script src="js/angular.js"></script>
 *   <!-- Include the ui-router script -->
 *   <script src="js/angular-ui-router.min.js"></script>
 *   <script>
 *     // ...and add 'ui.router' as a dependency
 *     var myApp = angular.module('myApp', ['ui.router']);
 *   </script>
 * </head>
 * <body>
 * </body>
 * </html>
 * </pre>
 */
angular.module('ui.router', ['ui.router.state']);

angular.module('ui.router.compat', ['ui.router']);
<commit_msg>chore(common): removed flattenPrototypeChain<commit_after>/*jshint globalstrict:true*/
/*global angular:false*/
'use strict';

var isDefined = angular.isDefined,
    isFunction = angular.isFunction,
    isString = angular.isString,
    isObject = angular.isObject,
    isArray = angular.isArray,
    forEach = angular.forEach,
    extend = angular.extend,
    copy = angular.copy;

var abstractKey = 'abstract';

function inherit(parent, extra) {
  return extend(new (extend(function() {}, { prototype: parent }))(), extra);
}

function defaults(opts, defs) {
  return extend({}, defs, pick(opts || {}, objectKeys(defs)));
}

function merge(dst) {
  forEach(arguments, function(obj) {
    if (obj !== dst) {
      forEach(obj, function(value, key) {
        if (!dst.hasOwnProperty(key)) dst[key] = value;
      });
    }
  });
  return dst;
}

/**
 * Recursive function iterator
 */
function FunctionIterator(items) {

  var it = function(initial) {
    var noOp = function() {};
    var get  = (function() { return this.next() || noOp; }).bind(this);
    var next = function() { return get()(initial, next); };
    return next();
  };

  extend(this, {
    items: items,
    _current: -1
  });

  return it.bind(this);
}

FunctionIterator.prototype.current = function() {
  return this.items[this._current];
};

FunctionIterator.prototype.next = function() {
  this._current++;
  return this.current();
};

/**
 * Finds the common ancestor path between two states.
 *
 * @param {Object} first The first state.
 * @param {Object} second The second state.
 * @return {Array} Returns an array of state names in descending order, not including the root.
 */
function ancestors(first, second) {
  var path = [];

  for (var n in first.path) {
    if (first.path[n] !== second.path[n]) break;
    path.push(first.path[n]);
  }
  return path;
}

/**
 * IE8-safe wrapper for `Object.keys()`.
 *
 * @param {Object} object A JavaScript object.
 * @return {Array} Returns the keys of the object as an array.
 */
function objectKeys(object) {
  if (Object.keys) {
    return Object.keys(object);
  }
  var result = [];

  forEach(object, function(val, key) {
    result.push(key);
  });
  return result;
}

/**
 * IE8-safe wrapper for `Array.prototype.indexOf()`.
 *
 * @param {Array} array A JavaScript array.
 * @param {*} value A value to search the array for.
 * @return {Number} Returns the array index value of `value`, or `-1` if not present.
 */
var arraySearch = indexOf;
function indexOf(array, value) {
  if (Array.prototype.indexOf) {
    return array.indexOf(value, Number(arguments[2]) || 0);
  }
  var len = array.length >>> 0, from = Number(arguments[2]) || 0;
  from = (from < 0) ? Math.ceil(from) : Math.floor(from);

  if (from < 0) from += len;

  for (; from < len; from++) {
    if (from in array && array[from] === value) return from;
  }
  return -1;
}

/**
 * Merges a set of parameters with all parameters inherited between the common parents of the
 * current state and a given destination state.
 *
 * @param {Object} currentParams The value of the current state parameters ($stateParams).
 * @param {Object} newParams The set of parameters which will be composited with inherited params.
 * @param {Object} $current Internal definition of object representing the current state.
 * @param {Object} $to Internal definition of object representing state to transition to.
 */
function inheritParams(currentParams, newParams, $current, $to) {
  var parents = ancestors($current, $to), parentParams, inherited = {}, inheritList = [];

  for (var i in parents) {
    if (!parents[i].params) continue;
    parentParams = objectKeys(parents[i].params);
    if (!parentParams.length) continue;

    for (var j in parentParams) {
      if (indexOf(inheritList, parentParams[j]) >= 0) continue;
      inheritList.push(parentParams[j]);
      inherited[parentParams[j]] = currentParams[parentParams[j]];
    }
  }
  return extend({}, inherited, newParams);
}

/**
 * Performs a non-strict comparison of the subset of two objects, defined by a list of keys.
 *
 * @param {Object} a The first object.
 * @param {Object} b The second object.
 * @param {Array} keys The list of keys within each object to compare. If the list is empty or not specified,
 *                     it defaults to the list of keys in `a`.
 * @return {Boolean} Returns `true` if the keys match, otherwise `false`.
 */
function equalForKeys(a, b, keys) {
  if (!keys) {
    keys = [];
    for (var n in a) keys.push(n); // Used instead of Object.keys() for IE8 compatibility
  }

  for (var i=0; i<keys.length; i++) {
    var k = keys[i];
    if (a[k] != b[k]) return false; // Not '===', values aren't necessarily normalized
  }
  return true;
}

/**
 * Returns the subset of an object, based on a list of keys.
 *
 * @param {Array} keys
 * @param {Object} values
 * @return {Boolean} Returns a subset of `values`.
 */
function filterByKeys(keys, values) {
  var filtered = {};

  forEach(keys, function (name) {
    if (isDefined(values[name])) filtered[name] = values[name];
  });
  return filtered;
}

// like _.indexBy
// when you know that your index values will be unique, or you want last-one-in to win
function indexBy(array, propName) {
  var result = {};
  forEach(array, function(item) {
    result[item[propName]] = item;
  });
  return result;
}

// extracted from underscore.js
// Return a copy of the object only containing the whitelisted properties.
function pick(obj) {
  var copy = {};
  var keys = Array.prototype.concat.apply(Array.prototype, Array.prototype.slice.call(arguments, 1));
  for (var key in obj) {
    if (keys.indexOf(key) !== -1) copy[key] = obj[key];
  }
  return copy;
}

// extracted from underscore.js
// Return a copy of the object omitting the blacklisted properties.
function omit(obj) {
  var copy = {};
  var keys = Array.prototype.concat.apply(Array.prototype, Array.prototype.slice.call(arguments, 1));
  for (var key in obj) {
    if (keys.indexOf(key) === -1) copy[key] = obj[key];
  }
  return copy;
}

function pluck(collection, key) {
  return map(collection, prop(key));
}

function filter(collection, callback) {
  var arr = isArray(collection), result = arr ? [] : {};
  forEach(collection, function(val, i) {
    if (callback(val, i)) {
      if (arr) result.push(val);
      else result[i] = val;
    }
  });
  return result;
}

function _filter(callback) {
  return function (collection) { return filter(collection, callback); };
}

function find(collection, callback) {
  var result;

  forEach(collection, function(val, i) {
    if (result) return;
    if (callback(val, i)) result = val;
  });

  return result;
}

function tpl(string, vals) {
  return string.replace(/\{([\w.]+)\}/g, function(_, key) {
    return parse(key)(vals) || "";
  });
}

function map(collection, callback) {
  var result = isArray(collection) ? [] : {};

  forEach(collection, function(val, i) {
    result[i] = callback(val, i);
  });
  return result;
}

function _map(callback) {
  return function mapper(collection) { return map(collection, callback); };
}

function unnest(list) {
  var result = [];
  forEach(list, function(val) { result = result.concat(val); });
  return result;
}

function unroll(callback) {
  callback = callback || angular.identity;

  return function(object) {
    var result = [];
    forEach(object, function(val, key) {
      var tmp = {};
      tmp[key] = val;
      result.push(callback(tmp));
    });
    return result;
  };
}

// Return a completely flattened version of an array.
function flatten (array) {
  function _flatten(input, output) {
    forEach(input, function(value) {
      if (angular.isArray(value)) {
        _flatten(value, output);
      } else {
        output.push(value);
      }
    });
    return output;
  }

  return _flatten(array, []);
}

// Checks if a value is injectable
function isInjectable(value) {
  return (isFunction(value) || (isArray(value) && isFunction(value[value.length - 1])));
}

function isNull(o) { return o === null; }

function compose() {
  var args = arguments;
  var start = args.length - 1;
  return function() {
    var i = start;
    var result = args[start].apply(this, arguments);
    while (i--) result = args[i].call(this, result);
    return result;
  };
}

function pipe() {
  return compose.apply(null, [].slice.call(arguments).reverse());
}

function prop(name) {
  return function(obj) { return obj && obj[name]; };
}

function parse(name) {
  return pipe.apply(null, name.split("\.").map(prop));
}

function not(fn) {
  return function() { return !fn.apply(null, [].slice.call(arguments)); };
}

function and(fn1, fn2) {
  return function() {
    return fn1.apply(null, [].slice.call(arguments)) && fn2.apply(null, [].slice.call(arguments));
  };
}

function or(fn1, fn2) {
  return function() {
    return fn1.apply(null, [].slice.call(arguments)) || fn2.apply(null, [].slice.call(arguments));
  };
}

function is(ctor) {
  return function(val) { return val != null && val.constructor === ctor || val instanceof ctor; };
}

function eq(comp) {
  return function(val) { return val === comp; };
}

function isEq(fn1, fn2) {
  return function() {
    var args = [].slice.call(arguments);
    return fn1.apply(null, args) === fn2.apply(null, args);
  };
}

function val(v) {
  return function() { return v; };
}

function invoke(method, args) {
  return function(obj) {
    return obj[method].apply(obj, args);
  };
}

function pattern(struct) {
  return function(val) {
    for (var i = 0; i < struct.length; i++) {
      if (struct[i][0](val)) return struct[i][1](val);
    }
  };
}

var isPromise = and(isObject, pipe(prop('then'), isFunction));

var GlobBuilder = (function() {

  function Glob(text) {

    var glob = text.split('.');

    // Returns true if glob matches current $state name.
    this.matches = function(name) {
      var segments = name.split('.');

      // match single stars
      for (var i = 0, l = glob.length; i < l; i++) {
        if (glob[i] === '*') segments[i] = '*';
      }

      // match greedy starts
      if (glob[0] === '**') {
         segments = segments.slice(segments.indexOf(glob[1]));
         segments.unshift('**');
      }
      // match greedy ends
      if (glob[glob.length - 1] === '**') {
         segments.splice(segments.indexOf(glob[glob.length - 2]) + 1, Number.MAX_VALUE);
         segments.push('**');
      }
      if (glob.length != segments.length) return false;

      return segments.join('') === glob.join('');
    };
  }

  return {
    // Checks text to see if it looks like a glob.
    is: function(text) {
      return text.indexOf('*') > -1;
    },

    // Factories a glob matcher from a string
    fromString: function(text) {
      if (!this.is(text)) return null;
      return new Glob(text);
    }
  };
})();

/**
 * @ngdoc overview
 * @name ui.router.util
 *
 * @description
 * # ui.router.util sub-module
 *
 * This module is a dependency of other sub-modules. Do not include this module as a dependency
 * in your angular app (use {@link ui.router} module instead).
 *
 */
angular.module('ui.router.util', ['ng']);

/**
 * @ngdoc overview
 * @name ui.router.router
 *
 * @requires ui.router.util
 *
 * @description
 * # ui.router.router sub-module
 *
 * This module is a dependency of other sub-modules. Do not include this module as a dependency
 * in your angular app (use {@link ui.router} module instead).
 */
angular.module('ui.router.router', ['ui.router.util']);

/**
 * @ngdoc overview
 * @name ui.router.state
 *
 * @requires ui.router.router
 * @requires ui.router.util
 *
 * @description
 * # ui.router.state sub-module
 *
 * This module is a dependency of the main ui.router module. Do not include this module as a dependency
 * in your angular app (use {@link ui.router} module instead).
 *
 */
angular.module('ui.router.state', ['ui.router.router', 'ui.router.util']);

/**
 * @ngdoc overview
 * @name ui.router
 *
 * @requires ui.router.state
 *
 * @description
 * # ui.router
 *
 * ## The main module for ui.router
 * There are several sub-modules included with the ui.router module, however only this module is needed
 * as a dependency within your angular app. The other modules are for organization purposes.
 *
 * The modules are:
 * * ui.router - the main "umbrella" module
 * * ui.router.router -
 *
 * *You'll need to include **only** this module as the dependency within your angular app.*
 *
 * <pre>
 * <!doctype html>
 * <html ng-app="myApp">
 * <head>
 *   <script src="js/angular.js"></script>
 *   <!-- Include the ui-router script -->
 *   <script src="js/angular-ui-router.min.js"></script>
 *   <script>
 *     // ...and add 'ui.router' as a dependency
 *     var myApp = angular.module('myApp', ['ui.router']);
 *   </script>
 * </head>
 * <body>
 * </body>
 * </html>
 * </pre>
 */
angular.module('ui.router', ['ui.router.state']);

angular.module('ui.router.compat', ['ui.router']);
<|endoftext|>


<commit_before>var config = require('config');
var mapModule = require('map');
var plugins = require('./leaflet_plugins');
var polyUtil = require('./polyline_encoded.js');
var routeboxer = require('./leaflet_routeboxer.js');

var center = config.geocode().center.split(',').map(parseFloat)
if (config.map_provider && config.map_provider() !== 'AmigoCloud') {
  L.mapbox.accessToken = config.mapbox_access_token();
}

module.exports = function(el) {
  var map, realtime, southWest, northEast, blurLayer;

  if (config.map_provider && config.map_provider() === 'AmigoCloud') {
    southWest = L.latLng(35.946877085397,-123.480610897013);
    northEast = L.latLng(40.763279543715,-118.789317362500);
    map = (new L.amigo.map(el, {
      amigoLogo: 'right',
      loadAmigoLayers: false,
      inertia: false,
      zoomAnimation: $('.hide-map').css('display') !== 'none',
      maxBounds: L.latLngBounds(southWest, northEast),
      minZoom: 8
    })).setView([center[1], center[0]], config.geocode().zoom);

    L.amigo.auth.setToken(config.support_data_token());

    blurLayer = L.tileLayer(
    'https://www.amigocloud.com/api/v1/users/'+
	'23/projects/3019/datasets/23835/tiles/{z}/{x}/{y}.png?' +
	'token=' + config.support_data_token(),
      {
        name: 'Uncovered Area'
      }
    );

    map.addAuthLayer({
      id: config.mapbox_map_id(),
      accessToken: config.mapbox_access_token(),
      name: 'Gray',
      provider: 'mapbox'
    });
    map.addBaseLayer(L.amigo.AmigoGray);
    map.layersControl.addBaseLayer(
      L.bingLayer(
        config.bing_key(),
	{
	  type: 'Road',
	  attribution: 'Bing Maps'
	}
      ),
      'Bing Road'
    );
    map.layersControl.addOverlay(blurLayer);
    blurLayer.addTo(map);

    module.exports.activeMap = map;

    map.realtimeControl = L.control.toggleRealTime().addTo(map);

    realtime = mapModule.realtime();
    console.log("entre amigo", map)

  } else {
    console.log("entre mapaboxs");
    map = L.mapbox.map(el, config.mapbox_map_id(), {
      attributionControl: false,
      inertia: false,
      zoomAnimation: false
    }).setView([center[1], center[0]], config.geocode().zoom);
  }

  return map;
};

module.exports.getMap = function () {
  return this.activeMap;
};

module.exports.cleanRoute = function() {
    module.exports.activeRoute.removeLayer();
    module.exports.activeRoute = null;
};

module.exports.polyline_creadas = [];

module.exports.getpolyline_creadas = function () {
  return this.polyline_creadas;
};

module.exports.marker_map = function(from, to, map){
    console.log("mapa from ->", from);
    console.log("mapa to ->", to);
     var IconStart = L.icon({
        iconUrl: 'assets/images/graphics/start.svg',
        iconSize: [40, 55],
        iconAnchor: [20, 50],
        popupAnchor:  [0, -50]
    });
    var IconEnd = L.icon({
        iconUrl: 'assets/images/graphics/end.svg',
        iconSize: [40, 55],
        iconAnchor: [20, 50],
        popupAnchor:  [0, -50]
    });

    //L.marker([37.35337508231001,-121.93626880645752], {icon: IconStart}).bindPopup('From').addTo(map);
    //L.marker([37.44377324953697,-122.16601610183714], {icon: IconEnd}).bindPopup('to').addTo(map);
    var markerform = new L.marker([from[0],from[1]], {icon: IconStart}).bindPopup('From').addTo(map);
    var markerto = new L.marker([to[0],to[1]], {icon: IconEnd}).bindPopup('to').addTo(map);

    this.polyline_creadas.push(markerform);
    this.polyline_creadas.push(markerto);
};

module.exports.marker_map_point = function(to, map){

    console.log("mapa point to ->", to);
    var name = to[2];

        var circle =
            L.CircleMarker([to[0], to[1]], {
            radius: 5,
            fillColor: "#ff7800",
            color: "#000",
            weight: 1,
            opacity: 1,
            fillOpacity: 0.8,
        });
    //L.animatedMarker([to[0], to[1]], 20, {
    //    color: '#000',
    //    fillColor: '#ffffff',
    //    fillOpacity: 1
    //}).addTo(map);

    this.polyline_creadas.push(circle);
};

module.exports.drawRouteAmigo = function(route,mode) {
      var color = '#000';
      var weight = 5;
      var dasharray= '';
        console.log("imprime mode ->", mode);
        if (mode=="CAR") {
            color = '#9E9E9E';
            dasharray= '6';
            weight = 3;

        }else if(mode=="BICYCLE") {
            color = '#FF0000';
            dasharray= '6';
            weight = 3;

        }else if(mode=="SUBWAY" || mode=="RAIL") {
            color = '#FF0000';
             weight = 8;

        }
        else if(mode == "WALK") {
            color = '#0BC8F4';
            dasharray= '6';
             weight = 3;
        }
        else if(mode=="BUS") {
            color = '#FEF0B5';
             weight = 8;
        }

       var color_options = {
            color: color,
            opacity: 1,
            weight: weight,
            dashArray: dasharray
        };

      route = new L.Polyline(L.PolylineUtil.decode(route, 5), color_options);
      this.polyline_creadas.push(route);
        console.log("pintamos datos ->", this.polyline_creadas);
        //module.exports.polyline_creadas.push(route);
      var boxes = L.RouteBoxer.box(route, 5);
      var bounds = new L.LatLngBounds([]);
      var boxpolys = new Array(boxes.length);

      for (var i = 0; i < boxes.length; i++) {
        bounds.extend(boxes[i]);
      }
      route.addTo(this.activeMap);
      this.activeMap.fitBounds(bounds);
};

<commit_msg>change circle<commit_after>var config = require('config');
var mapModule = require('map');
var plugins = require('./leaflet_plugins');
var polyUtil = require('./polyline_encoded.js');
var routeboxer = require('./leaflet_routeboxer.js');

var center = config.geocode().center.split(',').map(parseFloat)
if (config.map_provider && config.map_provider() !== 'AmigoCloud') {
  L.mapbox.accessToken = config.mapbox_access_token();
}

module.exports = function(el) {
  var map, realtime, southWest, northEast, blurLayer;

  if (config.map_provider && config.map_provider() === 'AmigoCloud') {
    southWest = L.latLng(35.946877085397,-123.480610897013);
    northEast = L.latLng(40.763279543715,-118.789317362500);
    map = (new L.amigo.map(el, {
      amigoLogo: 'right',
      loadAmigoLayers: false,
      inertia: false,
      zoomAnimation: $('.hide-map').css('display') !== 'none',
      maxBounds: L.latLngBounds(southWest, northEast),
      minZoom: 8
    })).setView([center[1], center[0]], config.geocode().zoom);

    L.amigo.auth.setToken(config.support_data_token());

    blurLayer = L.tileLayer(
    'https://www.amigocloud.com/api/v1/users/'+
	'23/projects/3019/datasets/23835/tiles/{z}/{x}/{y}.png?' +
	'token=' + config.support_data_token(),
      {
        name: 'Uncovered Area'
      }
    );

    map.addAuthLayer({
      id: config.mapbox_map_id(),
      accessToken: config.mapbox_access_token(),
      name: 'Gray',
      provider: 'mapbox'
    });
    map.addBaseLayer(L.amigo.AmigoGray);
    map.layersControl.addBaseLayer(
      L.bingLayer(
        config.bing_key(),
	{
	  type: 'Road',
	  attribution: 'Bing Maps'
	}
      ),
      'Bing Road'
    );
    map.layersControl.addOverlay(blurLayer);
    blurLayer.addTo(map);

    module.exports.activeMap = map;

    map.realtimeControl = L.control.toggleRealTime().addTo(map);

    realtime = mapModule.realtime();
    console.log("entre amigo", map)

  } else {
    console.log("entre mapaboxs");
    map = L.mapbox.map(el, config.mapbox_map_id(), {
      attributionControl: false,
      inertia: false,
      zoomAnimation: false
    }).setView([center[1], center[0]], config.geocode().zoom);
  }

  return map;
};

module.exports.getMap = function () {
  return this.activeMap;
};

module.exports.cleanRoute = function() {
    module.exports.activeRoute.removeLayer();
    module.exports.activeRoute = null;
};

module.exports.polyline_creadas = [];

module.exports.getpolyline_creadas = function () {
  return this.polyline_creadas;
};

module.exports.marker_map = function(from, to, map){
    console.log("mapa from ->", from);
    console.log("mapa to ->", to);
     var IconStart = L.icon({
        iconUrl: 'assets/images/graphics/start.svg',
        iconSize: [40, 55],
        iconAnchor: [20, 50],
        popupAnchor:  [0, -50]
    });
    var IconEnd = L.icon({
        iconUrl: 'assets/images/graphics/end.svg',
        iconSize: [40, 55],
        iconAnchor: [20, 50],
        popupAnchor:  [0, -50]
    });

    //L.marker([37.35337508231001,-121.93626880645752], {icon: IconStart}).bindPopup('From').addTo(map);
    //L.marker([37.44377324953697,-122.16601610183714], {icon: IconEnd}).bindPopup('to').addTo(map);
    var markerform = new L.marker([from[0],from[1]], {icon: IconStart}).bindPopup('From').addTo(map);
    var markerto = new L.marker([to[0],to[1]], {icon: IconEnd}).bindPopup('to').addTo(map);

    this.polyline_creadas.push(markerform);
    this.polyline_creadas.push(markerto);
};

module.exports.marker_map_point = function(to, map){

    console.log("mapa point to ->", to);
    var name = to[2];

        var circle =
            L.CircleMarker([to[0], to[1]], {
            radius: 5,
            fillColor: "#ff7800",
            color: "#000",
            weight: 1,
            opacity: 1,
            fillOpacity: 0.8
        }).addTo(map);

    //L.animatedMarker([to[0], to[1]], 20, {
    //    color: '#000',
    //    fillColor: '#ffffff',
    //    fillOpacity: 1
    //}).addTo(map);

    this.polyline_creadas.push(circle);
};

module.exports.drawRouteAmigo = function(route,mode) {
      var color = '#000';
      var weight = 5;
      var dasharray= '';
        console.log("imprime mode ->", mode);
        if (mode=="CAR") {
            color = '#9E9E9E';
            dasharray= '6';
            weight = 3;

        }else if(mode=="BICYCLE") {
            color = '#FF0000';
            dasharray= '6';
            weight = 3;

        }else if(mode=="SUBWAY" || mode=="RAIL") {
            color = '#FF0000';
             weight = 8;

        }
        else if(mode == "WALK") {
            color = '#0BC8F4';
            dasharray= '6';
             weight = 3;
        }
        else if(mode=="BUS") {
            color = '#FEF0B5';
             weight = 8;
        }

       var color_options = {
            color: color,
            opacity: 1,
            weight: weight,
            dashArray: dasharray
        };

      route = new L.Polyline(L.PolylineUtil.decode(route, 5), color_options);
      this.polyline_creadas.push(route);
        console.log("pintamos datos ->", this.polyline_creadas);
        //module.exports.polyline_creadas.push(route);
      var boxes = L.RouteBoxer.box(route, 5);
      var bounds = new L.LatLngBounds([]);
      var boxpolys = new Array(boxes.length);

      for (var i = 0; i < boxes.length; i++) {
        bounds.extend(boxes[i]);
      }
      route.addTo(this.activeMap);
      this.activeMap.fitBounds(bounds);
};

<|endoftext|>


<commit_before>var geom = require('pex-geom');
var glu = require('pex-glu');
var materials = require('pex-materials');
var color = require('pex-color');

var Geometry = geom.Geometry;
var Vec3 = geom.Vec3;
var Mesh = glu.Mesh;
var SolidColor = materials.SolidColor;
var Color = color.Color;

function VertexNormalHelper(geometry, color) {
  color = color || Color.Orange;
  var length = 0.1;

  if (!geometry.normals) {
    geometry.computeSmoothNormals();
  }

  var g = new Geometry({ vertices: true, edges: false, faces: false });
  var vertices = geometry.vertices;
  var normals = geometry.normals;
  vertices.forEach(function(v, vi) {
    var normal = normals[vi];
    g.vertices.push(v, v.dup().add(normal.dup().scale(length)));
  })
  Mesh.call(this, g, new SolidColor({ color: color, pointSize: 10 }), { lines: true });
}

VertexNormalHelper.prototype = Object.create(Mesh.prototype);

module.exports = VertexNormalHelper;<commit_msg>Renamed computeSmoothNormals<commit_after>var geom = require('pex-geom');
var glu = require('pex-glu');
var materials = require('pex-materials');
var color = require('pex-color');

var Geometry = geom.Geometry;
var Vec3 = geom.Vec3;
var Mesh = glu.Mesh;
var SolidColor = materials.SolidColor;
var Color = color.Color;

function VertexNormalHelper(geometry, color) {
  color = color || Color.Orange;
  var length = 0.1;

  if (!geometry.normals) {
    geometry.computeNormals();
  }

  var g = new Geometry({ vertices: true, edges: false, faces: false });
  var vertices = geometry.vertices;
  var normals = geometry.normals;
  vertices.forEach(function(v, vi) {
    var normal = normals[vi];
    g.vertices.push(v, v.dup().add(normal.dup().scale(length)));
  })
  Mesh.call(this, g, new SolidColor({ color: color, pointSize: 10 }), { lines: true });
}

VertexNormalHelper.prototype = Object.create(Mesh.prototype);

module.exports = VertexNormalHelper;<|endoftext|>


<commit_before>var CoreView = require('backbone/core-view');
var TableViewModel = require('./table-view-model.js');
var TableHeadView = require('./head/table-head-view');
var TableBodyView = require('./body/table-body-view');
var addTableRow = require('./operations/table-add-row');
var addTableColumn = require('./operations/table-add-column');

/*
 *  Main table view
 */

module.exports = CoreView.extend({

  options: {
    readonly: false
  },

  className: 'Table',
  tagName: 'div',

  initialize: function (opts) {
    if (!opts.querySchemaModel) throw new Error('querySchemaModel is required');
    if (!opts.columnsCollection) throw new Error('columnsCollection is required');
    if (!opts.rowsCollection) throw new Error('rowsCollection is required');
    if (!opts.modals) throw new Error('modals is required');

    this._rowsCollection = opts.rowsCollection;
    this._modals = opts.modals;
    this._columnsCollection = opts.columnsCollection;
    this._querySchemaModel = opts.querySchemaModel;

    this._tableViewModel = new TableViewModel({
      readonly: opts.readonly,
      tableName: opts.tableName
    }, {
      querySchemaModel: this._querySchemaModel
    });

    this._initBinds();

    var querySchemaStatus = this._querySchemaModel.get('status');
    if (querySchemaStatus === 'unfetched') {
      this._querySchemaModel.fetch();
    } else if (querySchemaStatus === 'fetched') {
      this._fetchRowsData();
    }
  },

  render: function () {
    this.clearSubViews();
    this.$el.empty();
    this._initViews();
    return this;
  },

  _initBinds: function () {
    this._querySchemaModel.bind('change:query', this._onQueryChanged, this);
    this._querySchemaModel.bind('change:status', this._fetchRowsData, this);
    this._tableViewModel.bind('change:sort_order change:order_by', this._fetchRowsData, this);
    this.add_related_model(this._querySchemaModel);
  },

  _fetchRowsData: function () {
    if (this._querySchemaModel.get('status') === 'fetched') {
      this._rowsCollection.fetch({
        data: {
          page: this._tableViewModel.get('page'),
          order_by: this._tableViewModel.get('order_by'),
          sort_order: this._tableViewModel.get('sort_order'),
          exclude: !this._tableViewModel.isCustomQueryApplied() ? ['the_geom_webmercator'] : []
        }
      });
    }
  },

  _initViews: function () {
    var tableHeadView = new TableHeadView({
      modals: this._modals,
      querySchemaModel: this._querySchemaModel,
      columnsCollection: this._columnsCollection,
      tableViewModel: this._tableViewModel
    });

    this.addView(tableHeadView);
    this.$el.append(tableHeadView.render().el);

    var tableBodyView = new TableBodyView({
      modals: this._modals,
      columnsCollection: this._columnsCollection,
      rowsCollection: this._rowsCollection,
      querySchemaModel: this._querySchemaModel,
      tableViewModel: this._tableViewModel
    });

    this.addView(tableBodyView);
    this.$el.append(tableBodyView.render().el);
  },

  addRow: function () {
    addTableRow({
      tableViewModel: this._tableViewModel,
      rowsCollection: this._rowsCollection
    });
  },

  addColumn: function () {
    addTableColumn({
      tableViewModel: this._tableViewModel,
      columnsCollection: this._columnsCollection
    });
  },

  _onQueryChanged: function () {
    this._tableViewModel.resetFetchDefaults();
  }

});
<commit_msg>Removing paginator from the table view<commit_after>var CoreView = require('backbone/core-view');
var $ = require('jquery');
var TableViewModel = require('./table-view-model.js');
var TableHeadView = require('./head/table-head-view');
var TableBodyView = require('./body/table-body-view');
var addTableRow = require('./operations/table-add-row');
var addTableColumn = require('./operations/table-add-column');

/*
 *  Main table view
 */

module.exports = CoreView.extend({

  options: {
    readonly: false
  },

  className: 'Table',
  tagName: 'div',

  initialize: function (opts) {
    if (!opts.querySchemaModel) throw new Error('querySchemaModel is required');
    if (!opts.columnsCollection) throw new Error('columnsCollection is required');
    if (!opts.rowsCollection) throw new Error('rowsCollection is required');
    if (!opts.modals) throw new Error('modals is required');

    this._rowsCollection = opts.rowsCollection;
    this._modals = opts.modals;
    this._columnsCollection = opts.columnsCollection;
    this._querySchemaModel = opts.querySchemaModel;

    this._tableViewModel = new TableViewModel({
      readonly: opts.readonly,
      tableName: opts.tableName
    }, {
      querySchemaModel: this._querySchemaModel
    });

    this._initBinds();

    var querySchemaStatus = this._querySchemaModel.get('status');
    if (querySchemaStatus === 'unfetched') {
      this._querySchemaModel.fetch();
    } else if (querySchemaStatus === 'fetched') {
      this._fetchRowsData();
    }
  },

  render: function () {
    this.clearSubViews();
    this.$el.empty();
    this._initViews();
    return this;
  },

  _initBinds: function () {
    this._querySchemaModel.bind('change:query', this._onQueryChanged, this);
    this._querySchemaModel.bind('change:status', this._fetchRowsData, this);
    this._tableViewModel.bind('change:sort_order change:order_by', this._fetchRowsData, this);
    this.add_related_model(this._querySchemaModel);
  },

  _fetchRowsData: function () {
    if (this._querySchemaModel.get('status') === 'fetched') {
      this._rowsCollection.fetch({
        data: {
          page: this._tableViewModel.get('page'),
          order_by: this._tableViewModel.get('order_by'),
          sort_order: this._tableViewModel.get('sort_order'),
          exclude: !this._tableViewModel.isCustomQueryApplied() ? ['the_geom_webmercator'] : []
        }
      });
    }
  },

  _initViews: function () {
    var tableHeadView = new TableHeadView({
      modals: this._modals,
      querySchemaModel: this._querySchemaModel,
      columnsCollection: this._columnsCollection,
      tableViewModel: this._tableViewModel
    });

    this.addView(tableHeadView);
    this.$el.append(tableHeadView.render().el);

    var tableBodyView = new TableBodyView({
      modals: this._modals,
      columnsCollection: this._columnsCollection,
      rowsCollection: this._rowsCollection,
      querySchemaModel: this._querySchemaModel,
      tableViewModel: this._tableViewModel
    });

    this.addView(tableBodyView);
    this.$el.append(tableBodyView.render().el);
  },

  addRow: function () {
    addTableRow({
      tableViewModel: this._tableViewModel,
      rowsCollection: this._rowsCollection
    });
  },

  addColumn: function () {
    addTableColumn({
      tableViewModel: this._tableViewModel,
      columnsCollection: this._columnsCollection
    });
  },

  // Remove elements that are not applied in the view
  remove: function () {
    $('.Table-paginator').remove();
    CoreView.prototype.remove.apply(this);
  },

  _onQueryChanged: function () {
    this._tableViewModel.resetFetchDefaults();
  }

});
<|endoftext|>


<commit_before>// Based on BluefruitLE by Don Coleman (https://github.com/don/cordova-plugin-ble-central/tree/master/examples/bluefruitle)

/* global mainPage, deviceList, refreshButton, statusText */
/* global detailPage, resultDiv, messageInput, sendButton, disconnectButton */
/* global ble  */
/* jshint browser: true , devel: true*/
'use strict';

// ASCII only
function bytesToString(buffer) {
    return String.fromCharCode.apply(null, new Uint8Array(buffer));
}

// ASCII only
function stringToBytes(string) {
    var array = new Uint8Array(string.length);
    for (var i = 0, l = string.length; i < l; i++) {
        array[i] = string.charCodeAt(i);
    }
    return array.buffer;
}

// this is Nordic's UART service
var bluefruit = {
    serviceUUID: '6e400001-b5a3-f393-e0a9-e50e24dcca9e',
    txCharacteristic: '6e400002-b5a3-f393-e0a9-e50e24dcca9e', // transmit is from the phone's perspective
    rxCharacteristic: '6e400003-b5a3-f393-e0a9-e50e24dcca9e'  // receive is from the phone's perspective
};

var badges = ['D1:90:32:2F:F1:4B','E1:C1:21:A2:B2:E0'];
var badgesConnStat = {};

var ConnStateEnum = {
    DISCONNECTED :1,
    DISCONNECTING : 2,
    CONNECTING : 3,
    CONNECTED : 4,
};

var app = {
    initialize: function() {
        this.bindEvents();
        detailPage.hidden = true;
    },
    bindEvents: function() {
        document.addEventListener('deviceready', this.onDeviceReady, false);
        refreshButton.addEventListener('touchstart', this.refreshDeviceList, false);
        sendButton.addEventListener('click', this.sendData, false);
        connectButton.addEventListener('touchstart', this.connect, false);
        isConnectedButton.addEventListener('touchstart', this.isConnected, false);
        disconnectButton.addEventListener('touchstart', this.disconnect, false);
        deviceList.addEventListener('touchstart', this.connect, false); // assume not scrolling
    },
    onDeviceReady: function() {
        app.showStatusText("Ready");

        for (var i = 0; i < badges.length; ++i) {
            console.log("Adding: "+badges[i]);
            badgesConnStat[badges[i]]=ConnStateEnum.DISCONNECTED;
        }

        console.log(badgesConnStat);
    },

    refreshDeviceList: function() {
        app.showStatusText("Starting scan");
        deviceList.innerHTML = ''; // empties the list
        /*
        if (cordova.platformId === 'android') { // Android filtering is broken
            ble.scan([], 5, app.onDiscoverDevice, app.onError);
        } else {
            ble.scan([bluefruit.serviceUUID], 5, app.onDiscoverDevice, app.onError);
        }*/
        ble.startScan([], app.onDiscoverDevice, app.onError);
        console.log('Start scan call end');
    },

    onDiscoverDevice: function(device) {
        var listItem = document.createElement('li'),
            html = '' + device.name + '
' +
                'RSSI: ' + device.rssi + ' | ' +
                device.id;

        if (device.name == "BADGE") {
            app.showStatusText('Found: '+ device.id);
            //app.connectToDevice(device.id);

            listItem.dataset.deviceId = device.id;
            listItem.innerHTML = html;
            deviceList.appendChild(listItem);
        }
    },

    connectToDevice: function(deviceId) {
        console.log('Attempingt to connect '+ deviceId);
        var onConnect = function(peripheral) {
                console.log('Connected '+ deviceId);
                badgesConnStat[deviceId] = ConnStateEnum.CONNECTED;
                //app.determineWriteType(peripheral);

                // subscribe for incoming data
                //ble.startNotification(deviceId, bluefruit.serviceUUID, bluefruit.rxCharacteristic, app.onData, app.onError);
                //sendButton.dataset.deviceId = deviceId;
                //disconnectButton.dataset.deviceId = deviceId;
                //resultDiv.innerHTML = "";
                //app.showDetailPage();

                //app.disconnectFromDevice(deviceId);

            },
            onConnectError = function(reason) {
                console.log('Error Connecting '+ deviceId + " "+reason);
                badgesConnStat[deviceId] = ConnStateEnum.DISCONNECTED;
                //app.disconnectFromDevice(deviceId); // just in case
            };

        if (badgesConnStat[deviceId] == ConnStateEnum.DISCONNECTED) {
            console.log('Connecting '+ deviceId);
            badgesConnStat[deviceId] = ConnStateEnum.CONNECTING;
            ble.connect(deviceId, onConnect, onConnectError);
        } else {
            console.log('Will not try to connect. Already existing active connection '+ deviceId + ", Status: "+badgesConnStat[deviceId]);
        }
    },

    disconnectFromDevice: function(deviceId) {
        console.log('Attemping to disconnect '+ deviceId);
        var onDisconnectError = function(reason) {
                app.showStatusText('Error disconnecting '+ deviceId + " "+reason);
                //app.disconnectFromDevice(deviceId); // just in case
            },
            onDisconnect = function(e) {
                console.log('Disconnected from '+ deviceId +' '+ e);
                badgesConnStat[deviceId] = ConnStateEnum.DISCONNECTED;
            };

        if (badgesConnStat[deviceId] == ConnStateEnum.CONNECTED) {
            console.log('Disconnecting '+ deviceId);
            badgesConnStat[deviceId] = ConnStateEnum.DISCONNECTING;
            ble.disconnect(deviceId, onDisconnect, onDisconnectError);
        } else {
            console.log('Will not try to disconnect '+ deviceId + ", Status: "+badgesConnStat[deviceId]);
        }
    },

    determineWriteType: function(peripheral) {
        // Adafruit nRF8001 breakout uses WriteWithoutResponse for the TX characteristic
        // Newer Bluefruit devices use Write Request for the TX characteristic

        var characteristic = peripheral.characteristics.filter(function(element) {
            if (element.characteristic.toLowerCase() === bluefruit.txCharacteristic) {
                return element;
            }
        })[0];

        if (characteristic.properties.indexOf('WriteWithoutResponse') > -1) {
            app.writeWithoutResponse = true;
        } else {
            app.writeWithoutResponse = false;
        }

    },
    onData: function(data) { // data received from Arduino
        console.log(data);
        resultDiv.innerHTML = resultDiv.innerHTML + "Received: " + bytesToString(data) + "
";
        resultDiv.scrollTop = resultDiv.scrollHeight;
    },
    sendData: function(event) { // send data to Arduino

        var success = function() {
            console.log("success");
            resultDiv.innerHTML = resultDiv.innerHTML + "Sent: " + messageInput.value + "
";
            resultDiv.scrollTop = resultDiv.scrollHeight;
        };

        var failure = function() {
            alert("Failed writing data to the bluefruit le");
        };

        var data = stringToBytes(messageInput.value);
        var deviceId = event.target.dataset.deviceId;

        if (app.writeWithoutResponse) {
            ble.writeWithoutResponse(
                deviceId,
                bluefruit.serviceUUID,
                bluefruit.txCharacteristic,
                data, success, failure
            );
        } else {
            ble.write(
                deviceId,
                bluefruit.serviceUUID,
                bluefruit.txCharacteristic,
                data, success, failure
            );
        }

    },
    connect: function(event) {
        app.showStatusText('Connecting All');
        //var deviceId = event.target.dataset.deviceId;
        //ble.disconnect(deviceId, app.showMainPage, app.onError);
        app.connectToDevice('D1:90:32:2F:F1:4B');
        app.connectToDevice('E1:C1:21:A2:B2:E0');
        app.showStatusText('Connect call ended');
    },
    isConnected: function(event) {
        console.log('isConnected?');
        for (var i = 0; i < badges.length; ++i) {
            var badge = badges[i];
            console.log("Status for "+badge+": "+badgesConnStat[badge]);
            ble.isConnected(
                badge,
                function() {
                    console.log("Peripheral "+badge+" is connected");
                },
                function() {
                    console.log("Peripheral "+badge+" is *not* connected");
                }
            );
        }
        app.showStatusText('isConnected? call ended');
    },
    disconnect: function(event) {
        app.showStatusText('Disconnecting All');
        //var deviceId = event.target.dataset.deviceId;
        //ble.disconnect(deviceId, app.showMainPage, app.onError);
        app.disconnectFromDevice('D1:90:32:2F:F1:4B');
        app.disconnectFromDevice('E1:C1:21:A2:B2:E0');
        app.showStatusText('Disconnect call ended');
    },
    showMainPage: function() {
        mainPage.hidden = false;
        detailPage.hidden = true;
    },
    showDetailPage: function() {
        mainPage.hidden = true;
        detailPage.hidden = false;
    },
    /*
    onConnectError: function(reason) {
        console.log('Error connecting'+ reason);
        app.showStatusText('could not connect because'+ reason);
        //alert("ERROR Connecting: " + reason); // real apps should use notification.alert
    },
    */
    onError: function(reason) {
        console.log('Error '+ reason);
        //alert("ERROR: " + reason); // real apps should use notification.alert
    },

    showStatusText: function(info) {
        console.log(info);
        document.getElementById("statusText").innerHTML = info;
    }
};
<commit_msg>fixed colsures for isConnected<commit_after>// Based on BluefruitLE by Don Coleman (https://github.com/don/cordova-plugin-ble-central/tree/master/examples/bluefruitle)

/* global mainPage, deviceList, refreshButton, statusText */
/* global detailPage, resultDiv, messageInput, sendButton, disconnectButton */
/* global ble  */
/* jshint browser: true , devel: true*/
'use strict';

// ASCII only
function bytesToString(buffer) {
    return String.fromCharCode.apply(null, new Uint8Array(buffer));
}

// ASCII only
function stringToBytes(string) {
    var array = new Uint8Array(string.length);
    for (var i = 0, l = string.length; i < l; i++) {
        array[i] = string.charCodeAt(i);
    }
    return array.buffer;
}

// this is Nordic's UART service
var bluefruit = {
    serviceUUID: '6e400001-b5a3-f393-e0a9-e50e24dcca9e',
    txCharacteristic: '6e400002-b5a3-f393-e0a9-e50e24dcca9e', // transmit is from the phone's perspective
    rxCharacteristic: '6e400003-b5a3-f393-e0a9-e50e24dcca9e'  // receive is from the phone's perspective
};

var badges = ['D1:90:32:2F:F1:4B','E1:C1:21:A2:B2:E0'];
var badgesConnStat = {};

var ConnStateEnum = {
    DISCONNECTED :1,
    DISCONNECTING : 2,
    CONNECTING : 3,
    CONNECTED : 4,
};

var app = {
    initialize: function() {
        this.bindEvents();
        detailPage.hidden = true;
    },
    bindEvents: function() {
        document.addEventListener('deviceready', this.onDeviceReady, false);
        refreshButton.addEventListener('touchstart', this.refreshDeviceList, false);
        sendButton.addEventListener('click', this.sendData, false);
        connectButton.addEventListener('touchstart', this.connect, false);
        isConnectedButton.addEventListener('touchstart', this.isConnected, false);
        disconnectButton.addEventListener('touchstart', this.disconnect, false);
        deviceList.addEventListener('touchstart', this.connect, false); // assume not scrolling
    },
    onDeviceReady: function() {
        app.showStatusText("Ready");

        for (var i = 0; i < badges.length; ++i) {
            console.log("Adding: "+badges[i]);
            badgesConnStat[badges[i]]=ConnStateEnum.DISCONNECTED;
        }

        console.log(badgesConnStat);
    },

    refreshDeviceList: function() {
        app.showStatusText("Starting scan");
        deviceList.innerHTML = ''; // empties the list
        /*
        if (cordova.platformId === 'android') { // Android filtering is broken
            ble.scan([], 5, app.onDiscoverDevice, app.onError);
        } else {
            ble.scan([bluefruit.serviceUUID], 5, app.onDiscoverDevice, app.onError);
        }*/
        ble.startScan([], app.onDiscoverDevice, app.onError);
        console.log('Start scan call end');
    },

    onDiscoverDevice: function(device) {
        var listItem = document.createElement('li'),
            html = '' + device.name + '
' +
                'RSSI: ' + device.rssi + ' | ' +
                device.id;

        if (device.name == "BADGE") {
            app.showStatusText('Found: '+ device.id);
            //app.connectToDevice(device.id);

            listItem.dataset.deviceId = device.id;
            listItem.innerHTML = html;
            deviceList.appendChild(listItem);
        }
    },

    connectToDevice: function(deviceId) {
        console.log('Attempingt to connect '+ deviceId);
        var onConnect = function(peripheral) {
                console.log('Connected '+ deviceId);
                badgesConnStat[deviceId] = ConnStateEnum.CONNECTED;
                //app.determineWriteType(peripheral);

                // subscribe for incoming data
                //ble.startNotification(deviceId, bluefruit.serviceUUID, bluefruit.rxCharacteristic, app.onData, app.onError);
                //sendButton.dataset.deviceId = deviceId;
                //disconnectButton.dataset.deviceId = deviceId;
                //resultDiv.innerHTML = "";
                //app.showDetailPage();

                //app.disconnectFromDevice(deviceId);

            },
            onConnectError = function(reason) {
                console.log('Error Connecting '+ deviceId + " "+reason);
                badgesConnStat[deviceId] = ConnStateEnum.DISCONNECTED;
                //app.disconnectFromDevice(deviceId); // just in case
            };

        if (badgesConnStat[deviceId] == ConnStateEnum.DISCONNECTED) {
            console.log('Connecting '+ deviceId);
            badgesConnStat[deviceId] = ConnStateEnum.CONNECTING;
            ble.connect(deviceId, onConnect, onConnectError);
        } else {
            console.log('Will not try to connect. Already existing active connection '+ deviceId + ", Status: "+badgesConnStat[deviceId]);
        }
    },

    disconnectFromDevice: function(deviceId) {
        console.log('Attemping to disconnect '+ deviceId);
        var onDisconnectError = function(reason) {
                app.showStatusText('Error disconnecting '+ deviceId + " "+reason);
                //app.disconnectFromDevice(deviceId); // just in case
            },
            onDisconnect = function(e) {
                console.log('Disconnected from '+ deviceId +' '+ e);
                badgesConnStat[deviceId] = ConnStateEnum.DISCONNECTED;
            };

        if (badgesConnStat[deviceId] == ConnStateEnum.CONNECTED) {
            console.log('Disconnecting '+ deviceId);
            badgesConnStat[deviceId] = ConnStateEnum.DISCONNECTING;
            ble.disconnect(deviceId, onDisconnect, onDisconnectError);
        } else {
            console.log('Will not try to disconnect '+ deviceId + ", Status: "+badgesConnStat[deviceId]);
        }
    },

    determineWriteType: function(peripheral) {
        // Adafruit nRF8001 breakout uses WriteWithoutResponse for the TX characteristic
        // Newer Bluefruit devices use Write Request for the TX characteristic

        var characteristic = peripheral.characteristics.filter(function(element) {
            if (element.characteristic.toLowerCase() === bluefruit.txCharacteristic) {
                return element;
            }
        })[0];

        if (characteristic.properties.indexOf('WriteWithoutResponse') > -1) {
            app.writeWithoutResponse = true;
        } else {
            app.writeWithoutResponse = false;
        }

    },
    onData: function(data) { // data received from Arduino
        console.log(data);
        resultDiv.innerHTML = resultDiv.innerHTML + "Received: " + bytesToString(data) + "
";
        resultDiv.scrollTop = resultDiv.scrollHeight;
    },
    sendData: function(event) { // send data to Arduino

        var success = function() {
            console.log("success");
            resultDiv.innerHTML = resultDiv.innerHTML + "Sent: " + messageInput.value + "
";
            resultDiv.scrollTop = resultDiv.scrollHeight;
        };

        var failure = function() {
            alert("Failed writing data to the bluefruit le");
        };

        var data = stringToBytes(messageInput.value);
        var deviceId = event.target.dataset.deviceId;

        if (app.writeWithoutResponse) {
            ble.writeWithoutResponse(
                deviceId,
                bluefruit.serviceUUID,
                bluefruit.txCharacteristic,
                data, success, failure
            );
        } else {
            ble.write(
                deviceId,
                bluefruit.serviceUUID,
                bluefruit.txCharacteristic,
                data, success, failure
            );
        }

    },
    connect: function(event) {
        app.showStatusText('Connecting All');
        //var deviceId = event.target.dataset.deviceId;
        //ble.disconnect(deviceId, app.showMainPage, app.onError);
        app.connectToDevice('D1:90:32:2F:F1:4B');
        app.connectToDevice('E1:C1:21:A2:B2:E0');
        app.showStatusText('Connect call ended');
    },
    isConnected: function(event) {
        console.log('isConnected?');
        for (var i = 0; i < badges.length; ++i) {
            // careful with te
            var badge=badges[i];
            console.log("Status for "+badge+": "+badgesConnStat[badge]);
            ble.isConnected(
                badge,
                function(badge) { // careful - create a closure here
                    return function() {
                        console.log("Peripheral "+badge+" is connected");
                    }
                },
                function(badge) { // careful - create a closure here
                    return function() {
                        console.log("Peripheral "+badge+" is *not* connected");
                    }
                }
            );
        }
        app.showStatusText('isConnected? call ended');
    },
    disconnect: function(event) {
        app.showStatusText('Disconnecting All');
        //var deviceId = event.target.dataset.deviceId;
        //ble.disconnect(deviceId, app.showMainPage, app.onError);
        app.disconnectFromDevice('D1:90:32:2F:F1:4B');
        app.disconnectFromDevice('E1:C1:21:A2:B2:E0');
        app.showStatusText('Disconnect call ended');
    },
    showMainPage: function() {
        mainPage.hidden = false;
        detailPage.hidden = true;
    },
    showDetailPage: function() {
        mainPage.hidden = true;
        detailPage.hidden = false;
    },
    /*
    onConnectError: function(reason) {
        console.log('Error connecting'+ reason);
        app.showStatusText('could not connect because'+ reason);
        //alert("ERROR Connecting: " + reason); // real apps should use notification.alert
    },
    */
    onError: function(reason) {
        console.log('Error '+ reason);
        //alert("ERROR: " + reason); // real apps should use notification.alert
    },

    showStatusText: function(info) {
        console.log(info);
        document.getElementById("statusText").innerHTML = info;
    }
};
<|endoftext|>


<commit_before>/**
 * @author mrdoob / http://mrdoob.com/
 * @author alteredq / http://alteredqualia.com/
 */

THREE.JSONLoader = function ( manager ) {

	this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;

	this.withCredentials = false;

};

THREE.JSONLoader.prototype = {

	constructor: THREE.JSONLoader,

	load: function( url, onLoad, onProgress, onError ) {

		var scope = this;

		var texturePath = this.texturePath && ( typeof this.texturePath === "string" ) ? this.texturePath : THREE.Loader.prototype.extractUrlBase( url );

		var loader = new THREE.XHRLoader( this.manager );
		loader.setCrossOrigin( this.crossOrigin );
		loader.setWithCredentials( this.withCredentials );
		loader.load( url, function ( text ) {

			var json = JSON.parse( text );
			var metadata = json.metadata;

			if ( metadata !== undefined ) {

				if ( metadata.type === 'object' ) {

					console.error( 'THREE.JSONLoader: ' + url + ' should be loaded with THREE.ObjectLoader instead.' );
					return;

				}

				if ( metadata.type === 'scene' ) {

					console.error( 'THREE.JSONLoader: ' + url + ' should be loaded with THREE.SceneLoader instead.' );
					return;

				}

			}

			var object = scope.parse( json, texturePath );
			onLoad( object.geometry, object.materials );

		} );

	},

	setCrossOrigin: function ( value ) {

		this.crossOrigin = value;

	},

	setTexturePath: function ( value ) {

		this.texturePath = value;

	},

	parse: function ( json, texturePath ) {

		var geometry = new THREE.Geometry(),
		scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0;

		parseModel( scale );

		parseSkin();
		parseMorphing( scale );

		geometry.computeFaceNormals();
		geometry.computeBoundingSphere();

		function parseModel( scale ) {

			function isBitSet( value, position ) {

				return value & ( 1 << position );

			}

			var i, j, fi,

			offset, zLength,

		colorIndex, normalIndex, uvIndex, materialIndex,

			type,
			isQuad,
			hasMaterial,
			hasFaceVertexUv,
			hasFaceNormal, hasFaceVertexNormal,
			hasFaceColor, hasFaceVertexColor,

		vertex, face, faceA, faceB, hex, normal,

			uvLayer, uv, u, v,

			faces = json.faces,
			vertices = json.vertices,
			normals = json.normals,
			colors = json.colors,

			nUvLayers = 0;

			if ( json.uvs !== undefined ) {

				// disregard empty arrays

				for ( i = 0; i < json.uvs.length; i ++ ) {

					if ( json.uvs[ i ].length ) nUvLayers ++;

				}

				for ( i = 0; i < nUvLayers; i ++ ) {

					geometry.faceVertexUvs[ i ] = [];

				}

			}

			offset = 0;
			zLength = vertices.length;

			while ( offset < zLength ) {

				vertex = new THREE.Vector3();

				vertex.x = vertices[ offset ++ ] * scale;
				vertex.y = vertices[ offset ++ ] * scale;
				vertex.z = vertices[ offset ++ ] * scale;

				geometry.vertices.push( vertex );

			}

			offset = 0;
			zLength = faces.length;

			while ( offset < zLength ) {

				type = faces[ offset ++ ];

				isQuad              = isBitSet( type, 0 );
				hasMaterial         = isBitSet( type, 1 );
				hasFaceVertexUv     = isBitSet( type, 3 );
				hasFaceNormal       = isBitSet( type, 4 );
				hasFaceVertexNormal = isBitSet( type, 5 );
				hasFaceColor	     = isBitSet( type, 6 );
				hasFaceVertexColor  = isBitSet( type, 7 );

				// console.log("type", type, "bits", isQuad, hasMaterial, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);

				if ( isQuad ) {

					faceA = new THREE.Face3();
					faceA.a = faces[ offset ];
					faceA.b = faces[ offset + 1 ];
					faceA.c = faces[ offset + 3 ];

					faceB = new THREE.Face3();
					faceB.a = faces[ offset + 1 ];
					faceB.b = faces[ offset + 2 ];
					faceB.c = faces[ offset + 3 ];

					offset += 4;

					if ( hasMaterial ) {

						materialIndex = faces[ offset ++ ];
						faceA.materialIndex = materialIndex;
						faceB.materialIndex = materialIndex;

					}

					// to get face <=> uv index correspondence

					fi = geometry.faces.length;

					if ( hasFaceVertexUv ) {

						for ( i = 0; i < nUvLayers; i ++ ) {

							uvLayer = json.uvs[ i ];

							geometry.faceVertexUvs[ i ][ fi ] = [];
							geometry.faceVertexUvs[ i ][ fi + 1 ] = [];

							for ( j = 0; j < 4; j ++ ) {

								uvIndex = faces[ offset ++ ];

								u = uvLayer[ uvIndex * 2 ];
								v = uvLayer[ uvIndex * 2 + 1 ];

								uv = new THREE.Vector2( u, v );

								if ( j !== 2 ) geometry.faceVertexUvs[ i ][ fi ].push( uv );
								if ( j !== 0 ) geometry.faceVertexUvs[ i ][ fi + 1 ].push( uv );

							}

						}

					}

					if ( hasFaceNormal ) {

						normalIndex = faces[ offset ++ ] * 3;

						faceA.normal.set(
							normals[ normalIndex ++ ],
							normals[ normalIndex ++ ],
							normals[ normalIndex ]
						);

						faceB.normal.copy( faceA.normal );

					}

					if ( hasFaceVertexNormal ) {

						for ( i = 0; i < 4; i ++ ) {

							normalIndex = faces[ offset ++ ] * 3;

							normal = new THREE.Vector3(
								normals[ normalIndex ++ ],
								normals[ normalIndex ++ ],
								normals[ normalIndex ]
							);

							if ( i !== 2 ) faceA.vertexNormals.push( normal );
							if ( i !== 0 ) faceB.vertexNormals.push( normal );

						}

					}

					if ( hasFaceColor ) {

						colorIndex = faces[ offset ++ ];
						hex = colors[ colorIndex ];

						faceA.color.setHex( hex );
						faceB.color.setHex( hex );

					}

					if ( hasFaceVertexColor ) {

						for ( i = 0; i < 4; i ++ ) {

							colorIndex = faces[ offset ++ ];
							hex = colors[ colorIndex ];

							if ( i !== 2 ) faceA.vertexColors.push( new THREE.Color( hex ) );
							if ( i !== 0 ) faceB.vertexColors.push( new THREE.Color( hex ) );

						}

					}

					geometry.faces.push( faceA );
					geometry.faces.push( faceB );

				} else {

					face = new THREE.Face3();
					face.a = faces[ offset ++ ];
					face.b = faces[ offset ++ ];
					face.c = faces[ offset ++ ];

					if ( hasMaterial ) {

						materialIndex = faces[ offset ++ ];
						face.materialIndex = materialIndex;

					}

					// to get face <=> uv index correspondence

					fi = geometry.faces.length;

					if ( hasFaceVertexUv ) {

						for ( i = 0; i < nUvLayers; i ++ ) {

							uvLayer = json.uvs[ i ];

							geometry.faceVertexUvs[ i ][ fi ] = [];

							for ( j = 0; j < 3; j ++ ) {

								uvIndex = faces[ offset ++ ];

								u = uvLayer[ uvIndex * 2 ];
								v = uvLayer[ uvIndex * 2 + 1 ];

								uv = new THREE.Vector2( u, v );

								geometry.faceVertexUvs[ i ][ fi ].push( uv );

							}

						}

					}

					if ( hasFaceNormal ) {

						normalIndex = faces[ offset ++ ] * 3;

						face.normal.set(
							normals[ normalIndex ++ ],
							normals[ normalIndex ++ ],
							normals[ normalIndex ]
						);

					}

					if ( hasFaceVertexNormal ) {

						for ( i = 0; i < 3; i ++ ) {

							normalIndex = faces[ offset ++ ] * 3;

							normal = new THREE.Vector3(
								normals[ normalIndex ++ ],
								normals[ normalIndex ++ ],
								normals[ normalIndex ]
							);

							face.vertexNormals.push( normal );

						}

					}

					if ( hasFaceColor ) {

						colorIndex = faces[ offset ++ ];
						face.color.setHex( colors[ colorIndex ] );

					}

					if ( hasFaceVertexColor ) {

						for ( i = 0; i < 3; i ++ ) {

							colorIndex = faces[ offset ++ ];
							face.vertexColors.push( new THREE.Color( colors[ colorIndex ] ) );

						}

					}

					geometry.faces.push( face );

				}

			}

		};

		function parseSkin() {

			var influencesPerVertex = ( json.influencesPerVertex !== undefined ) ? json.influencesPerVertex : 2;

			if ( json.skinWeights ) {

				for ( var i = 0, l = json.skinWeights.length; i < l; i += influencesPerVertex ) {

					var x =                               json.skinWeights[ i ];
					var y = ( influencesPerVertex > 1 ) ? json.skinWeights[ i + 1 ] : 0;
					var z = ( influencesPerVertex > 2 ) ? json.skinWeights[ i + 2 ] : 0;
					var w = ( influencesPerVertex > 3 ) ? json.skinWeights[ i + 3 ] : 0;

					geometry.skinWeights.push( new THREE.Vector4( x, y, z, w ) );

				}

			}

			if ( json.skinIndices ) {

				for ( var i = 0, l = json.skinIndices.length; i < l; i += influencesPerVertex ) {

					var a =                               json.skinIndices[ i ];
					var b = ( influencesPerVertex > 1 ) ? json.skinIndices[ i + 1 ] : 0;
					var c = ( influencesPerVertex > 2 ) ? json.skinIndices[ i + 2 ] : 0;
					var d = ( influencesPerVertex > 3 ) ? json.skinIndices[ i + 3 ] : 0;

					geometry.skinIndices.push( new THREE.Vector4( a, b, c, d ) );

				}

			}

			geometry.bones = json.bones;

			if ( geometry.bones && geometry.bones.length > 0 && ( geometry.skinWeights.length !== geometry.skinIndices.length || geometry.skinIndices.length !== geometry.vertices.length ) ) {

				console.warn( 'When skinning, number of vertices (' + geometry.vertices.length + '), skinIndices (' +
					geometry.skinIndices.length + '), and skinWeights (' + geometry.skinWeights.length + ') should match.' );

			}

			// could change this to json.animations[0] or remove completely

			geometry.animation = json.animation;
			geometry.animations = json.animations;

		};

		function parseMorphing( scale ) {

			if ( json.morphTargets !== undefined ) {

				var i, l, v, vl, dstVertices, srcVertices;

				for ( i = 0, l = json.morphTargets.length; i < l; i ++ ) {

					geometry.morphTargets[ i ] = {};
					geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
					geometry.morphTargets[ i ].vertices = [];

					dstVertices = geometry.morphTargets[ i ].vertices;
					srcVertices = json.morphTargets[ i ].vertices;

					for ( v = 0, vl = srcVertices.length; v < vl; v += 3 ) {

						var vertex = new THREE.Vector3();
						vertex.x = srcVertices[ v ] * scale;
						vertex.y = srcVertices[ v + 1 ] * scale;
						vertex.z = srcVertices[ v + 2 ] * scale;

						dstVertices.push( vertex );

					}

				}

			}

			if ( json.morphColors !== undefined ) {

				var i, l, c, cl, dstColors, srcColors, color;

				for ( i = 0, l = json.morphColors.length; i < l; i ++ ) {

					geometry.morphColors[ i ] = {};
					geometry.morphColors[ i ].name = json.morphColors[ i ].name;
					geometry.morphColors[ i ].colors = [];

					dstColors = geometry.morphColors[ i ].colors;
					srcColors = json.morphColors[ i ].colors;

					for ( c = 0, cl = srcColors.length; c < cl; c += 3 ) {

						color = new THREE.Color( 0xffaa00 );
						color.setRGB( srcColors[ c ], srcColors[ c + 1 ], srcColors[ c + 2 ] );
						dstColors.push( color );

					}

				}

			}

		};

		if ( json.materials === undefined || json.materials.length === 0 ) {

			return { geometry: geometry };

		} else {

			var materials = THREE.Loader.prototype.initMaterials( json.materials, texturePath, this.crossOrigin );

			return { geometry: geometry, materials: materials };

		}

	}

};
<commit_msg>JSONLoader: backwards compatibility.<commit_after>/**
 * @author mrdoob / http://mrdoob.com/
 * @author alteredq / http://alteredqualia.com/
 */

THREE.JSONLoader = function ( manager ) {

	if ( typeof manager === 'boolean' ) {

		console.warn( 'THREE.JSONLoader: showStatus parameter has been removed from constructor.' );
		manager = undefined;

	}

	this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;

	this.withCredentials = false;

};

THREE.JSONLoader.prototype = {

	constructor: THREE.JSONLoader,

	get statusDomElement () {

		if ( this._statusDomElement === undefined ) {

			this._statusDomElement = document.createElement( 'div' );

		}

		console.warn( 'THREE.JSONLoader: .statusDomElement has been removed.' );
		return this._statusDomElement;

	},

	load: function( url, onLoad, onProgress, onError ) {

		var scope = this;

		var texturePath = this.texturePath && ( typeof this.texturePath === "string" ) ? this.texturePath : THREE.Loader.prototype.extractUrlBase( url );

		var loader = new THREE.XHRLoader( this.manager );
		loader.setCrossOrigin( this.crossOrigin );
		loader.setWithCredentials( this.withCredentials );
		loader.load( url, function ( text ) {

			var json = JSON.parse( text );
			var metadata = json.metadata;

			if ( metadata !== undefined ) {

				if ( metadata.type === 'object' ) {

					console.error( 'THREE.JSONLoader: ' + url + ' should be loaded with THREE.ObjectLoader instead.' );
					return;

				}

				if ( metadata.type === 'scene' ) {

					console.error( 'THREE.JSONLoader: ' + url + ' should be loaded with THREE.SceneLoader instead.' );
					return;

				}

			}

			var object = scope.parse( json, texturePath );
			onLoad( object.geometry, object.materials );

		} );

	},

	setCrossOrigin: function ( value ) {

		this.crossOrigin = value;

	},

	setTexturePath: function ( value ) {

		this.texturePath = value;

	},

	parse: function ( json, texturePath ) {

		var geometry = new THREE.Geometry(),
		scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0;

		parseModel( scale );

		parseSkin();
		parseMorphing( scale );

		geometry.computeFaceNormals();
		geometry.computeBoundingSphere();

		function parseModel( scale ) {

			function isBitSet( value, position ) {

				return value & ( 1 << position );

			}

			var i, j, fi,

			offset, zLength,

		colorIndex, normalIndex, uvIndex, materialIndex,

			type,
			isQuad,
			hasMaterial,
			hasFaceVertexUv,
			hasFaceNormal, hasFaceVertexNormal,
			hasFaceColor, hasFaceVertexColor,

		vertex, face, faceA, faceB, hex, normal,

			uvLayer, uv, u, v,

			faces = json.faces,
			vertices = json.vertices,
			normals = json.normals,
			colors = json.colors,

			nUvLayers = 0;

			if ( json.uvs !== undefined ) {

				// disregard empty arrays

				for ( i = 0; i < json.uvs.length; i ++ ) {

					if ( json.uvs[ i ].length ) nUvLayers ++;

				}

				for ( i = 0; i < nUvLayers; i ++ ) {

					geometry.faceVertexUvs[ i ] = [];

				}

			}

			offset = 0;
			zLength = vertices.length;

			while ( offset < zLength ) {

				vertex = new THREE.Vector3();

				vertex.x = vertices[ offset ++ ] * scale;
				vertex.y = vertices[ offset ++ ] * scale;
				vertex.z = vertices[ offset ++ ] * scale;

				geometry.vertices.push( vertex );

			}

			offset = 0;
			zLength = faces.length;

			while ( offset < zLength ) {

				type = faces[ offset ++ ];

				isQuad              = isBitSet( type, 0 );
				hasMaterial         = isBitSet( type, 1 );
				hasFaceVertexUv     = isBitSet( type, 3 );
				hasFaceNormal       = isBitSet( type, 4 );
				hasFaceVertexNormal = isBitSet( type, 5 );
				hasFaceColor	     = isBitSet( type, 6 );
				hasFaceVertexColor  = isBitSet( type, 7 );

				// console.log("type", type, "bits", isQuad, hasMaterial, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);

				if ( isQuad ) {

					faceA = new THREE.Face3();
					faceA.a = faces[ offset ];
					faceA.b = faces[ offset + 1 ];
					faceA.c = faces[ offset + 3 ];

					faceB = new THREE.Face3();
					faceB.a = faces[ offset + 1 ];
					faceB.b = faces[ offset + 2 ];
					faceB.c = faces[ offset + 3 ];

					offset += 4;

					if ( hasMaterial ) {

						materialIndex = faces[ offset ++ ];
						faceA.materialIndex = materialIndex;
						faceB.materialIndex = materialIndex;

					}

					// to get face <=> uv index correspondence

					fi = geometry.faces.length;

					if ( hasFaceVertexUv ) {

						for ( i = 0; i < nUvLayers; i ++ ) {

							uvLayer = json.uvs[ i ];

							geometry.faceVertexUvs[ i ][ fi ] = [];
							geometry.faceVertexUvs[ i ][ fi + 1 ] = [];

							for ( j = 0; j < 4; j ++ ) {

								uvIndex = faces[ offset ++ ];

								u = uvLayer[ uvIndex * 2 ];
								v = uvLayer[ uvIndex * 2 + 1 ];

								uv = new THREE.Vector2( u, v );

								if ( j !== 2 ) geometry.faceVertexUvs[ i ][ fi ].push( uv );
								if ( j !== 0 ) geometry.faceVertexUvs[ i ][ fi + 1 ].push( uv );

							}

						}

					}

					if ( hasFaceNormal ) {

						normalIndex = faces[ offset ++ ] * 3;

						faceA.normal.set(
							normals[ normalIndex ++ ],
							normals[ normalIndex ++ ],
							normals[ normalIndex ]
						);

						faceB.normal.copy( faceA.normal );

					}

					if ( hasFaceVertexNormal ) {

						for ( i = 0; i < 4; i ++ ) {

							normalIndex = faces[ offset ++ ] * 3;

							normal = new THREE.Vector3(
								normals[ normalIndex ++ ],
								normals[ normalIndex ++ ],
								normals[ normalIndex ]
							);

							if ( i !== 2 ) faceA.vertexNormals.push( normal );
							if ( i !== 0 ) faceB.vertexNormals.push( normal );

						}

					}

					if ( hasFaceColor ) {

						colorIndex = faces[ offset ++ ];
						hex = colors[ colorIndex ];

						faceA.color.setHex( hex );
						faceB.color.setHex( hex );

					}

					if ( hasFaceVertexColor ) {

						for ( i = 0; i < 4; i ++ ) {

							colorIndex = faces[ offset ++ ];
							hex = colors[ colorIndex ];

							if ( i !== 2 ) faceA.vertexColors.push( new THREE.Color( hex ) );
							if ( i !== 0 ) faceB.vertexColors.push( new THREE.Color( hex ) );

						}

					}

					geometry.faces.push( faceA );
					geometry.faces.push( faceB );

				} else {

					face = new THREE.Face3();
					face.a = faces[ offset ++ ];
					face.b = faces[ offset ++ ];
					face.c = faces[ offset ++ ];

					if ( hasMaterial ) {

						materialIndex = faces[ offset ++ ];
						face.materialIndex = materialIndex;

					}

					// to get face <=> uv index correspondence

					fi = geometry.faces.length;

					if ( hasFaceVertexUv ) {

						for ( i = 0; i < nUvLayers; i ++ ) {

							uvLayer = json.uvs[ i ];

							geometry.faceVertexUvs[ i ][ fi ] = [];

							for ( j = 0; j < 3; j ++ ) {

								uvIndex = faces[ offset ++ ];

								u = uvLayer[ uvIndex * 2 ];
								v = uvLayer[ uvIndex * 2 + 1 ];

								uv = new THREE.Vector2( u, v );

								geometry.faceVertexUvs[ i ][ fi ].push( uv );

							}

						}

					}

					if ( hasFaceNormal ) {

						normalIndex = faces[ offset ++ ] * 3;

						face.normal.set(
							normals[ normalIndex ++ ],
							normals[ normalIndex ++ ],
							normals[ normalIndex ]
						);

					}

					if ( hasFaceVertexNormal ) {

						for ( i = 0; i < 3; i ++ ) {

							normalIndex = faces[ offset ++ ] * 3;

							normal = new THREE.Vector3(
								normals[ normalIndex ++ ],
								normals[ normalIndex ++ ],
								normals[ normalIndex ]
							);

							face.vertexNormals.push( normal );

						}

					}

					if ( hasFaceColor ) {

						colorIndex = faces[ offset ++ ];
						face.color.setHex( colors[ colorIndex ] );

					}

					if ( hasFaceVertexColor ) {

						for ( i = 0; i < 3; i ++ ) {

							colorIndex = faces[ offset ++ ];
							face.vertexColors.push( new THREE.Color( colors[ colorIndex ] ) );

						}

					}

					geometry.faces.push( face );

				}

			}

		};

		function parseSkin() {

			var influencesPerVertex = ( json.influencesPerVertex !== undefined ) ? json.influencesPerVertex : 2;

			if ( json.skinWeights ) {

				for ( var i = 0, l = json.skinWeights.length; i < l; i += influencesPerVertex ) {

					var x =                               json.skinWeights[ i ];
					var y = ( influencesPerVertex > 1 ) ? json.skinWeights[ i + 1 ] : 0;
					var z = ( influencesPerVertex > 2 ) ? json.skinWeights[ i + 2 ] : 0;
					var w = ( influencesPerVertex > 3 ) ? json.skinWeights[ i + 3 ] : 0;

					geometry.skinWeights.push( new THREE.Vector4( x, y, z, w ) );

				}

			}

			if ( json.skinIndices ) {

				for ( var i = 0, l = json.skinIndices.length; i < l; i += influencesPerVertex ) {

					var a =                               json.skinIndices[ i ];
					var b = ( influencesPerVertex > 1 ) ? json.skinIndices[ i + 1 ] : 0;
					var c = ( influencesPerVertex > 2 ) ? json.skinIndices[ i + 2 ] : 0;
					var d = ( influencesPerVertex > 3 ) ? json.skinIndices[ i + 3 ] : 0;

					geometry.skinIndices.push( new THREE.Vector4( a, b, c, d ) );

				}

			}

			geometry.bones = json.bones;

			if ( geometry.bones && geometry.bones.length > 0 && ( geometry.skinWeights.length !== geometry.skinIndices.length || geometry.skinIndices.length !== geometry.vertices.length ) ) {

				console.warn( 'When skinning, number of vertices (' + geometry.vertices.length + '), skinIndices (' +
					geometry.skinIndices.length + '), and skinWeights (' + geometry.skinWeights.length + ') should match.' );

			}

			// could change this to json.animations[0] or remove completely

			geometry.animation = json.animation;
			geometry.animations = json.animations;

		};

		function parseMorphing( scale ) {

			if ( json.morphTargets !== undefined ) {

				var i, l, v, vl, dstVertices, srcVertices;

				for ( i = 0, l = json.morphTargets.length; i < l; i ++ ) {

					geometry.morphTargets[ i ] = {};
					geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
					geometry.morphTargets[ i ].vertices = [];

					dstVertices = geometry.morphTargets[ i ].vertices;
					srcVertices = json.morphTargets[ i ].vertices;

					for ( v = 0, vl = srcVertices.length; v < vl; v += 3 ) {

						var vertex = new THREE.Vector3();
						vertex.x = srcVertices[ v ] * scale;
						vertex.y = srcVertices[ v + 1 ] * scale;
						vertex.z = srcVertices[ v + 2 ] * scale;

						dstVertices.push( vertex );

					}

				}

			}

			if ( json.morphColors !== undefined ) {

				var i, l, c, cl, dstColors, srcColors, color;

				for ( i = 0, l = json.morphColors.length; i < l; i ++ ) {

					geometry.morphColors[ i ] = {};
					geometry.morphColors[ i ].name = json.morphColors[ i ].name;
					geometry.morphColors[ i ].colors = [];

					dstColors = geometry.morphColors[ i ].colors;
					srcColors = json.morphColors[ i ].colors;

					for ( c = 0, cl = srcColors.length; c < cl; c += 3 ) {

						color = new THREE.Color( 0xffaa00 );
						color.setRGB( srcColors[ c ], srcColors[ c + 1 ], srcColors[ c + 2 ] );
						dstColors.push( color );

					}

				}

			}

		};

		if ( json.materials === undefined || json.materials.length === 0 ) {

			return { geometry: geometry };

		} else {

			var materials = THREE.Loader.prototype.initMaterials( json.materials, texturePath, this.crossOrigin );

			return { geometry: geometry, materials: materials };

		}

	}

};
<|endoftext|>


<commit_before>
module.exports = vector_math;

var SIMD = require("simd");

function vector_math() {}

vector_math.EPSILON = typeof Number.EPSILON !== undefined ? Number.EPSILON : 1e-6;
vector_math.ENABLE_SIMD =  false;
vector_math.SIMD_AVAILABLE = typeof SIMD !== undefined;
vector_math.USE_SIMD = function() { return vector_math.ENABLE_SIMD && vector_math.SIMD_AVAILABLE };<commit_msg>(Common) : Random to global namespace<commit_after>
module.exports = vector_math;

var SIMD = require("simd");

function vector_math() {}

vector_math.EPSILON = typeof Number.EPSILON !== undefined ? Number.EPSILON : 1e-6;
vector_math.RANDOM = Math.random;
vector_math.ENABLE_SIMD =  false;
vector_math.SIMD_AVAILABLE = typeof SIMD !== undefined;
vector_math.USE_SIMD = function() { return vector_math.ENABLE_SIMD && vector_math.SIMD_AVAILABLE };<|endoftext|>


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

// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

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

// At this point, libs with most common functions are loaded
// Options are ready but not loaded

// Debug print function for the main, will be overwriten in modules
var dbg = function(str) {
	utils.dbg("main", str);
};

// Firefox hacks to simulate chrome APIs
if($.browser.mozilla) {
	var chrome = {
		extension: {
			getURL: function(str) {
				return self.options[str];
			}
		}
	};
}

dbg("[Init] Loading general funcs");
// Only DOM modifying functions are here

// Import a javascript file from the site if we need it elsewhere (jQ function doesn't seem to work as intended)
var appendNativeScript = function (jsFileName) {
	var script = document.createElement("script");
	script.type = "text/javascript";
	script.src = jsFileName;
	dbg("[NativeScript] Append " + jsFileName);
	document.body.appendChild(script);
};

// Insert script into DOM - Escape sandboxing
var insertScript = function (id, f, removeAfterUse) {
	var script = document.createElement("script");
	script.type = "text/javascript";
	script.id = id;
	script.textContent = "(" + f.toString() + ")(jQuery)";
	document.body.appendChild(script);
	if(removeAfterUse) {
		$("#" + id).remove();
	}
};

// Builds our specific frames from a frame object :
// { id, classes, title, header, data, relativeToId, relativeToObj, relativeToWindow, top, left, css, buttons = [ /* close is by default */ { b_id, b_text, b_callback} ], onCloseCallback, underButtonsText }
var appendFrame = function(o) {
	// Build custom buttons
	var additionnalButtons = '';
	if(o.buttons) {
		 $.each(o.buttons, function(i, button) {
			additionnalButtons += '<input type="button" id="gksi_' + o.id + '_' + button.b_id + '" class="fine" value=" ' + button.b_text + ' "> ';
		})
	}

	// Build entire frame
	var gksi_frame = '

' + o.title + '
' +
		'
' + (o.header ? '
' + o.header + '
' : '') + '
' + o.data + '
' +
		'
' + (additionnalButtons.length ? additionnalButtons : '' ) + '<input type="button" id="gksi_' + o.id + '_close" class="fine" value=" Fermer ">
' +
		(o.underButtonsText ? '
' + o.underButtonsText + '
': '') +
		'

';

	// Append
	$("#navigation").append(gksi_frame);

	var frame = $("#gksi_" + o.id);
	// Close button
	$("#gksi_" + o.id + "_close").click(function() {
		if(o.onCloseCallback) {
			o.onCloseCallback();
		}
		frame.remove();
		return false;
	});

	// Custom buttons management and callbacks
	if(additionnalButtons.length) {
		$.each(o.buttons, function(i, button) {
			if(button.b_callback) {
				$("#gksi_" + o.id + "_" + button.b_id).click(function() {
					button.b_callback($("#gksi_" + o.id + "_data"), "#gksi_" + o.id);
					return false;
				});
			}
		});
	}

	if(o.css) {
		$.each(o.css, function(key, value) {
			frame.css(key, value);
		});
		frame.css("overflow", "auto");
	}

	// Position correction on resize
	if(!opt.get("global", "allow_frame_css")) {
		if(o.relativeToId) {
			$(window).resize(function() {
				var toOffset = $("#" + o.relativeToId).offset();
				frame.offset({ top: toOffset.top + o.top, left: toOffset.left + o.left });
			});
			$(window).trigger("resize");
		}

		if(o.relativeToObj) {
			$(window).resize(function() {
				var toOffset = o.relativeToObj.offset();
				frame.offset({ top: toOffset.top + o.top, left: toOffset.left + o.left });
			});
			$(window).trigger("resize");
		}

		if(o.relativeToWindow) {
			$(window).resize(function() {
				var body = document[$.browser.mozilla ? "documentElement" : "body"];
				if(o.top === true) {
					o.top = $(window).height() / 2 - frame.height() / 2;
				}
				if(o.left === true) {
					o.left = $(window).width() / 2 - frame.width() / 2;
				}
				frame.offset({ top: body.scrollTop + o.top + ($("#entete").css("position") == "fixed" ? $("#entete").height() : 0), left: body.scrollLeft + o.left });
			});
			$(window).trigger("resize");
		}
	}

	// Background-color correction
	var transparentCss = "rgba(0, 0, 0, 0)", transparentCssFirefox = "transparent";
	if($(".gksi_frame_content").css("background-color") == transparentCss || $(".gksi_frame_data").css("background-color") == transparentCssFirefox) {
		dbg("[frame_builder] Can't find background-color");
		// Go up as much as needed to find some non-transparent color
		var cssTries = [ "#navigation", "#centre", "#navig_bloc_user", "#header" ];
		$.each(cssTries, function(i, cssId) {
			if($(cssId).css("background-color") != transparentCss && $(cssId).css("background-color") != transparentCssFirefox) {
				dbg("[frame_builder] Took " + cssId + " background-color");
				// Instead of creating style on frame, let's append to our custom CSS area
				appendCSS('.gksi_frame_content { background-color: ' + $(cssId).css("background-color") + '; } ');
				return false;
			}
		});
	}
};

// Default GKSi CSS
var insertCSS = function() {
	dbg("Inserting custom CSS");
	$("head").append("");
};

// Custom CSS insertion, mostly used by the frame builder
var appendCSS = function(css) {
	$("#gksi_css").append(css);
};

// Custom divs insertion & funcs
var ignoreScrolling = false, pauseEndlessScrolling = false, stopEndlessScrolling = false;
var insertDivs = function() {
	// The back to top button - We build it on init and show it when needed
	$("#global").append('');
	$("#backTopButton").click(function() {
		ignoreScrolling = true;
		$("html, body").animate({ scrollTop: 0 }, 800, "swing", function() {
			ignoreScrolling = false;
		});
		$(this).hide();
		$("#esPauseButton").hide();
		return false;
	});
	$("#esPauseButton").click(function() {
		if(pauseEndlessScrolling) {
			$("#esPauseButton").removeClass("esButtonPaused");
			$("#esPauseButton").addClass("esButtonActive");
			pauseEndlessScrolling = false;
		}
		else {
			$("#esPauseButton").removeClass("esButtonActive");
			$("#esPauseButton").addClass("esButtonPaused");
			pauseEndlessScrolling = true;
		}
		return false;
	});
};

dbg("[Init] Starting the engine");
// Parse our url string from the browser
var pageUrl = utils.parseUrl(window.location.href);
// Load all options
opt.load();
// Load global saved data
gData.load();
// Insert custom CSS and divs
insertCSS();
insertDivs();
// Each module will be inserted in the modules object for an easier inter-modules communication
var modules = {};
// Print some url debug to make sure the parser is not going nuts
dbg(pageUrl);
dbg(utils.craftUrl(pageUrl));
// Each .module.js from the manifest will now be read by the javascript engine
// then the loader will launch them if the url is matching
dbg("[Init] Ready");<commit_msg>Comply with Mozilla validation requests - close #78<commit_after>// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

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

// At this point, libs with most common functions are loaded
// Options are ready but not loaded

// Debug print function for the main, will be overwriten in modules
var dbg = function(str) {
	utils.dbg("main", str);
};

// Firefox hacks to simulate chrome APIs
if($.browser.mozilla) {
	var chrome = {
		extension: {
			getURL: function(str) {
				return self.options[str];
			}
		}
	};
}

dbg("[Init] Loading general funcs");
// Only DOM modifying functions are here

// Import a javascript file from the site if we need it elsewhere (jQ function doesn't seem to work as intended)
var appendNativeScript = function (jsFileName) {
	$("body").append($("