<commit_before>'use strict';

var p5 = require('../core/core');
require('./p5.Geometry3D');

/**
 * draw a plane with given a width and height
 * @param  {Number} width             the width of the plane
 * @param  {Number} height            the height of the plane
 * @param  {Number} detailX(optional) number of vertices on horizontal surface
 * @param  {Number} detailY(optional) number of vertices on horizontal surface
 * example
 *

 *
 * function setup(){
 *   createCanvas(windowWidth, windowHeight, 'webgl');
 * }
 *
 * var theta = 0;
 *
 * function draw(){
 *   background(255, 255, 255, 255);
 *   translate(0, 0, -100);
 *   push();
 *   rotateZ(theta);
 *   rotateX(theta);
 *   rotateY(theta);
 *   plane(100, 100);
 *   pop();
 *   theta += 0.05;
 *
 *

 */
p5.prototype.plane = function(width, height, detailX, detailY){

  width = width || 1;
  height = height || 1;

  detailX = detailX || 1;
  detailY = detailY || 1;

  var gId = 'plane|'+width+'|'+height+'|'+detailX+'|'+detailY;

  if(!this._graphics.geometryInHash(gId)){

    var geometry3d = new p5.Geometry3D();

    var createPlane = function(u, v){
      var x = 2 * width * u - width;
      var y = 2 * height * v - height;
      var z = 0;
      return new p5.Vector(x, y, z);
    };

    geometry3d.parametricGeometry(createPlane, detailX, detailY);

    var obj = geometry3d.generateObj();

    this._graphics.initBuffer(gId, obj);

  }

  this._graphics.drawBuffer(gId);

};

/**
 * draw a sphere with given raduis
 * @param  {Number} radius            radius of the sphere
 * @param  {Number} detailX(optional) number of vertices on horizontal surface
 * @param  {Number} detailY(optional) number of vertices on vertical surface
 * example
 *

 *
 * function setup(){
 *   createCanvas(windowWidth, windowHeight, 'webgl');
 * }
 *
 * var theta = 0;
 *
 * function draw(){
 *   background(255, 255, 255, 255);
 *   translate(0, 0, -100);
 *   push();
 *   rotateZ(theta);
 *   rotateX(theta);
 *   rotateY(theta);
 *   sphere(100);
 *   pop();
 *   theta += 0.05;
 *
 *

 */
p5.prototype.sphere = function(radius, detailX, detailY){

  radius = radius || 50;

  detailX = detailX || 12;
  detailY = detailY || 8;

  var gId = 'sphere|'+radius+'|'+detailX+'|'+detailY;

  if(!this._graphics.geometryInHash(gId)){

    var geometry3d = new p5.Geometry3D();

    var createSphere = function(u, v){
      var theta = 2 * Math.PI * u;
      var phi = Math.PI * v - Math.PI / 2;
      var x = radius * Math.cos(phi) * Math.sin(theta);
      var y = radius * Math.sin(phi);
      var z = radius * Math.cos(phi) * Math.cos(theta);
      return new p5.Vector(x, y, z);
    };

    geometry3d.parametricGeometry(createSphere, detailX, detailY);

    var obj = geometry3d.generateObj();

    this._graphics.initBuffer(gId, obj);
  }

  this._graphics.drawBuffer(gId);

  return this;
};

/**
 * draw a cylinder with given radius and height
 * @param  {Number} radius            radius of the surface
 * @param  {Number} height            height of the cylinder
 * @param  {Number} detailX(optional) number of vertices on horizontal surface
 * @param  {Number} detailY(optional) number of vertices on vertical surface
 * example
 *

 *
 * function setup(){
 *   createCanvas(windowWidth, windowHeight, 'webgl');
 * }
 *
 * var theta = 0;
 *
 * function draw(){
 *   background(255, 255, 255, 255);
 *   translate(0, 0, -100);
 *   push();
 *   rotateZ(theta);
 *   rotateX(theta);
 *   rotateY(theta);
 *   cylinder(100, 200);
 *   pop();
 *   theta += 0.05;
 *
 *

 */
p5.prototype.cylinder = function(radius, height, detailX, detailY){

  radius = radius || 50;
  height = height || 50;

  detailX = detailX || 12;
  detailY = detailY || 8;

  var gId = 'cylinder|'+radius+'|'+height+'|'+detailX+'|'+detailY;

  if(!this._graphics.geometryInHash(gId)){

    var geometry3d = new p5.Geometry3D();

    var createCylinder = function(u, v){
      var theta = 2 * Math.PI * u;
      var x = radius * Math.sin(theta);
      var y = 2 * height * v - height;
      var z = radius * Math.cos(theta);
      return new p5.Vector(x, y, z);
    };

    geometry3d.parametricGeometry(createCylinder, detailX, detailY);
    geometry3d.mergeVertices();

    var createTop = function(u, v){
      var theta = 2 * Math.PI * u;
      var x = radius * Math.sin(-theta);
      var y = height;
      var z = radius * Math.cos(theta);
      if(v === 0){
        return new p5.Vector(0, height, 0);
      }
      else{
        return new p5.Vector(x, y, z);
      }
    };

    geometry3d.parametricGeometry(
      createTop, detailX, 1, geometry3d.vertices.length);

    var createBottom = function(u, v){
      var theta = 2 * Math.PI * u;
      var x = radius * Math.sin(theta);
      var y = -height;
      var z = radius * Math.cos(theta);
      if(v === 0){
        return new p5.Vector(0, -height, 0);
      }else{
        return new p5.Vector(x, y, z);
      }
    };

    geometry3d.parametricGeometry(
      createBottom, detailX, 1, geometry3d.vertices.length);

    var obj = geometry3d.generateObj(true);

    this._graphics.initBuffer(gId, obj);
  }

  this._graphics.drawBuffer(gId);

  return this;
};

/**
 * draw a cone with given radius and height
 * @param  {Number} radius            radius of the bottom surface
 * @param  {Number} height            height of the cone
 * @param  {Number} detailX(optional) number of vertices on horizontal surface
 * @param  {Number} detailY(optional) number of vertices on vertical surface
 * example
 *

 *
 * function setup(){
 *   createCanvas(windowWidth, windowHeight, 'webgl');
 * }
 *
 * var theta = 0;
 *
 * function draw(){
 *   background(255, 255, 255, 255);
 *   translate(0, 0, -100);
 *   push();
 *   rotateZ(theta);
 *   rotateX(theta);
 *   rotateY(theta);
 *   cone(100, 200);
 *   pop();
 *   theta += 0.05;
 *
 *

 */
p5.prototype.cone = function(radius, height, detailX, detailY){

  radius = radius || 50;
  height = height || 50;

  detailX = detailX || 12;
  detailY = detailY || 8;

  var gId = 'cone|'+radius+'|'+height+'|'+detailX+'|'+detailY;

  if(!this._graphics.geometryInHash(gId)){

    var geometry3d = new p5.Geometry3D();

    var createCone = function(u, v){
      var theta = 2 * Math.PI * u;
      var x = radius * (1 - v) * Math.sin(theta);
      var y = 2 * height * v - height;
      var z = radius * (1 - v) * Math.cos(theta);
      return new p5.Vector(x, y, z);
    };

    geometry3d.parametricGeometry(createCone, detailX, detailY);
    geometry3d.mergeVertices();

    var createBottom = function(u, v){
      var theta = 2 * Math.PI * u;
      var x = radius * (1 - v) * Math.sin(-theta);
      var y = -height;
      var z = radius * (1 - v) * Math.cos(theta);
      return new p5.Vector(x, y, z);
    };

    geometry3d.parametricGeometry(
      createBottom, detailX, 1, geometry3d.vertices.length);

    var obj = geometry3d.generateObj(true);

    this._graphics.initBuffer(gId, obj);
  }

  this._graphics.drawBuffer(gId);

  return this;
};

/**
 * draw a torus with given radius and tube radius
 * @param  {Number} radius            radius of the whole ring
 * @param  {Number} tubeRadius        radius of the tube
 * @param  {Number} detailX(optional) number of vertices on horizontal surface
 * @param  {Number} detailY(optional) number of vertices on vertical surface
 * example
 *

 *
 * function setup(){
 *   createCanvas(windowWidth, windowHeight, 'webgl');
 * }
 *
 * var theta = 0;
 *
 * function draw(){
 *   background(255, 255, 255, 255);
 *   translate(0, 0, -100);
 *   push();
 *   rotateZ(theta);
 *   rotateX(theta);
 *   rotateY(theta);
 *   torus(100, 20);
 *   pop();
 *   theta += 0.05;
 *
 *

 */
p5.prototype.torus = function(radius, tubeRadius, detailX, detailY){

  radius = radius || 50;
  tubeRadius = tubeRadius || 20;

  detailX = detailX || 12;
  detailY = detailY || 8;

  var gId = 'torus|'+radius+'|'+tubeRadius+'|'+detailX+'|'+detailY;

  if(!this._graphics.geometryInHash(gId)){

    var geometry3d = new p5.Geometry3D();

    var createTorus = function(u, v){
      var theta = 2 * Math.PI * u;
      var phi = 2 * Math.PI * v;
      var x = (radius + tubeRadius * Math.cos(phi)) * Math.cos(theta);
      var y = (radius + tubeRadius * Math.cos(phi)) * Math.sin(theta);
      var z = tubeRadius * Math.sin(phi);
      return new p5.Vector(x, y, z);
    };

    geometry3d.parametricGeometry(createTorus, detailX, detailY);

    var obj = geometry3d.generateObj();

    this._graphics.initBuffer(gId, obj);
  }

  this._graphics.drawBuffer(gId);

  return this;
};

/**
 * draw a box with given widht, height and depth
 * @param  {Number} width  width of the box
 * @param  {Number} height height of the box
 * @param  {Number} depth  depth of the box
 * example
 *

 *
 * function setup(){
 *   createCanvas(windowWidth, windowHeight, 'webgl');
 * }
 *
 * var theta = 0;
 *
 * function draw(){
 *   background(255, 255, 255, 255);
 *   translate(0, 0, -100);
 *   push();
 *   rotateZ(theta);
 *   rotateX(theta);
 *   rotateY(theta);
 *   box(100, 100, 100);
 *   pop();
 *   theta += 0.05;
 *
 *

 */
p5.prototype.box = function(width, height, depth){

  width = width || 10;
  height = height || width;
  depth = depth || width;

  //detail for box as optional
  var detailX = typeof arguments[3] === Number ? arguments[3] : 1;
  var detailY = typeof arguments[4] === Number ? arguments[4] : 1;

  var gId = 'cube|'+width+'|'+height+'|'+depth+'|'+detailX+'|'+detailY;

  if(!this._graphics.geometryInHash(gId)){

    var geometry3d = new p5.Geometry3D();

    var createPlane1 = function(u, v){
      var x = 2 * width * u - width;
      var y = 2 * height * v - height;
      var z = depth;
      return new p5.Vector(x, y, z);
    };
    var createPlane2 = function(u, v){
      var x = 2 * width * ( 1 - u ) - width;
      var y = 2 * height * v - height;
      var z = -depth;
      return new p5.Vector(x, y, z);
    };
    var createPlane3 = function(u, v){
      var x = 2 * width * ( 1 - u ) - width;
      var y = height;
      var z = 2 * depth * v - depth;
      return new p5.Vector(x, y, z);
    };
    var createPlane4 = function(u, v){
      var x = 2 * width * u - width;
      var y = -height;
      var z = 2 * depth * v - depth;
      return new p5.Vector(x, y, z);
    };
    var createPlane5 = function(u, v){
      var x = width;
      var y = 2 * height * u - height;
      var z = 2 * depth * v - depth;
      return new p5.Vector(x, y, z);
    };
    var createPlane6 = function(u, v){
      var x = -width;
      var y = 2 * height * ( 1 - u ) - height;
      var z = 2 * depth * v - depth;
      return new p5.Vector(x, y, z);
    };

    geometry3d.parametricGeometry(
      createPlane1, detailX, detailY, geometry3d.vertices.length);
    geometry3d.parametricGeometry(
      createPlane2, detailX, detailY, geometry3d.vertices.length);
    geometry3d.parametricGeometry(
      createPlane3, detailX, detailY, geometry3d.vertices.length);
    geometry3d.parametricGeometry(
      createPlane4, detailX, detailY, geometry3d.vertices.length);
    geometry3d.parametricGeometry(
      createPlane5, detailX, detailY, geometry3d.vertices.length);
    geometry3d.parametricGeometry(
      createPlane6, detailX, detailY, geometry3d.vertices.length);

    var obj = geometry3d.generateObj(true);

    this._graphics.initBuffer(gId, obj);
  }

  this._graphics.drawBuffer(gId);

  return this;

};

module.exports = p5;
<commit_msg>box and plane are as big as the other by default not<commit_after>'use strict';

var p5 = require('../core/core');
require('./p5.Geometry3D');

/**
 * draw a plane with given a width and height
 * @param  {Number} width             the width of the plane
 * @param  {Number} height            the height of the plane
 * @param  {Number} detailX(optional) number of vertices on horizontal surface
 * @param  {Number} detailY(optional) number of vertices on horizontal surface
 * example
 *

 *
 * function setup(){
 *   createCanvas(windowWidth, windowHeight, 'webgl');
 * }
 *
 * var theta = 0;
 *
 * function draw(){
 *   background(255, 255, 255, 255);
 *   translate(0, 0, -100);
 *   push();
 *   rotateZ(theta);
 *   rotateX(theta);
 *   rotateY(theta);
 *   plane(100, 100);
 *   pop();
 *   theta += 0.05;
 *
 *

 */
p5.prototype.plane = function(width, height, detailX, detailY){

  width = width || 50;
  height = height || 50;

  detailX = detailX || 1;
  detailY = detailY || 1;

  var gId = 'plane|'+width+'|'+height+'|'+detailX+'|'+detailY;

  if(!this._graphics.geometryInHash(gId)){

    var geometry3d = new p5.Geometry3D();

    var createPlane = function(u, v){
      var x = 2 * width * u - width;
      var y = 2 * height * v - height;
      var z = 0;
      return new p5.Vector(x, y, z);
    };

    geometry3d.parametricGeometry(createPlane, detailX, detailY);

    var obj = geometry3d.generateObj();

    this._graphics.initBuffer(gId, obj);

  }

  this._graphics.drawBuffer(gId);

};

/**
 * draw a sphere with given raduis
 * @param  {Number} radius            radius of the sphere
 * @param  {Number} detailX(optional) number of vertices on horizontal surface
 * @param  {Number} detailY(optional) number of vertices on vertical surface
 * example
 *

 *
 * function setup(){
 *   createCanvas(windowWidth, windowHeight, 'webgl');
 * }
 *
 * var theta = 0;
 *
 * function draw(){
 *   background(255, 255, 255, 255);
 *   translate(0, 0, -100);
 *   push();
 *   rotateZ(theta);
 *   rotateX(theta);
 *   rotateY(theta);
 *   sphere(100);
 *   pop();
 *   theta += 0.05;
 *
 *

 */
p5.prototype.sphere = function(radius, detailX, detailY){

  radius = radius || 50;

  detailX = detailX || 12;
  detailY = detailY || 8;

  var gId = 'sphere|'+radius+'|'+detailX+'|'+detailY;

  if(!this._graphics.geometryInHash(gId)){

    var geometry3d = new p5.Geometry3D();

    var createSphere = function(u, v){
      var theta = 2 * Math.PI * u;
      var phi = Math.PI * v - Math.PI / 2;
      var x = radius * Math.cos(phi) * Math.sin(theta);
      var y = radius * Math.sin(phi);
      var z = radius * Math.cos(phi) * Math.cos(theta);
      return new p5.Vector(x, y, z);
    };

    geometry3d.parametricGeometry(createSphere, detailX, detailY);

    var obj = geometry3d.generateObj();

    this._graphics.initBuffer(gId, obj);
  }

  this._graphics.drawBuffer(gId);

  return this;
};

/**
 * draw a cylinder with given radius and height
 * @param  {Number} radius            radius of the surface
 * @param  {Number} height            height of the cylinder
 * @param  {Number} detailX(optional) number of vertices on horizontal surface
 * @param  {Number} detailY(optional) number of vertices on vertical surface
 * example
 *

 *
 * function setup(){
 *   createCanvas(windowWidth, windowHeight, 'webgl');
 * }
 *
 * var theta = 0;
 *
 * function draw(){
 *   background(255, 255, 255, 255);
 *   translate(0, 0, -100);
 *   push();
 *   rotateZ(theta);
 *   rotateX(theta);
 *   rotateY(theta);
 *   cylinder(100, 200);
 *   pop();
 *   theta += 0.05;
 *
 *

 */
p5.prototype.cylinder = function(radius, height, detailX, detailY){

  radius = radius || 50;
  height = height || 50;

  detailX = detailX || 12;
  detailY = detailY || 8;

  var gId = 'cylinder|'+radius+'|'+height+'|'+detailX+'|'+detailY;

  if(!this._graphics.geometryInHash(gId)){

    var geometry3d = new p5.Geometry3D();

    var createCylinder = function(u, v){
      var theta = 2 * Math.PI * u;
      var x = radius * Math.sin(theta);
      var y = 2 * height * v - height;
      var z = radius * Math.cos(theta);
      return new p5.Vector(x, y, z);
    };

    geometry3d.parametricGeometry(createCylinder, detailX, detailY);
    geometry3d.mergeVertices();

    var createTop = function(u, v){
      var theta = 2 * Math.PI * u;
      var x = radius * Math.sin(-theta);
      var y = height;
      var z = radius * Math.cos(theta);
      if(v === 0){
        return new p5.Vector(0, height, 0);
      }
      else{
        return new p5.Vector(x, y, z);
      }
    };

    geometry3d.parametricGeometry(
      createTop, detailX, 1, geometry3d.vertices.length);

    var createBottom = function(u, v){
      var theta = 2 * Math.PI * u;
      var x = radius * Math.sin(theta);
      var y = -height;
      var z = radius * Math.cos(theta);
      if(v === 0){
        return new p5.Vector(0, -height, 0);
      }else{
        return new p5.Vector(x, y, z);
      }
    };

    geometry3d.parametricGeometry(
      createBottom, detailX, 1, geometry3d.vertices.length);

    var obj = geometry3d.generateObj(true);

    this._graphics.initBuffer(gId, obj);
  }

  this._graphics.drawBuffer(gId);

  return this;
};

/**
 * draw a cone with given radius and height
 * @param  {Number} radius            radius of the bottom surface
 * @param  {Number} height            height of the cone
 * @param  {Number} detailX(optional) number of vertices on horizontal surface
 * @param  {Number} detailY(optional) number of vertices on vertical surface
 * example
 *

 *
 * function setup(){
 *   createCanvas(windowWidth, windowHeight, 'webgl');
 * }
 *
 * var theta = 0;
 *
 * function draw(){
 *   background(255, 255, 255, 255);
 *   translate(0, 0, -100);
 *   push();
 *   rotateZ(theta);
 *   rotateX(theta);
 *   rotateY(theta);
 *   cone(100, 200);
 *   pop();
 *   theta += 0.05;
 *
 *

 */
p5.prototype.cone = function(radius, height, detailX, detailY){

  radius = radius || 50;
  height = height || 50;

  detailX = detailX || 12;
  detailY = detailY || 8;

  var gId = 'cone|'+radius+'|'+height+'|'+detailX+'|'+detailY;

  if(!this._graphics.geometryInHash(gId)){

    var geometry3d = new p5.Geometry3D();

    var createCone = function(u, v){
      var theta = 2 * Math.PI * u;
      var x = radius * (1 - v) * Math.sin(theta);
      var y = 2 * height * v - height;
      var z = radius * (1 - v) * Math.cos(theta);
      return new p5.Vector(x, y, z);
    };

    geometry3d.parametricGeometry(createCone, detailX, detailY);
    geometry3d.mergeVertices();

    var createBottom = function(u, v){
      var theta = 2 * Math.PI * u;
      var x = radius * (1 - v) * Math.sin(-theta);
      var y = -height;
      var z = radius * (1 - v) * Math.cos(theta);
      return new p5.Vector(x, y, z);
    };

    geometry3d.parametricGeometry(
      createBottom, detailX, 1, geometry3d.vertices.length);

    var obj = geometry3d.generateObj(true);

    this._graphics.initBuffer(gId, obj);
  }

  this._graphics.drawBuffer(gId);

  return this;
};

/**
 * draw a torus with given radius and tube radius
 * @param  {Number} radius            radius of the whole ring
 * @param  {Number} tubeRadius        radius of the tube
 * @param  {Number} detailX(optional) number of vertices on horizontal surface
 * @param  {Number} detailY(optional) number of vertices on vertical surface
 * example
 *

 *
 * function setup(){
 *   createCanvas(windowWidth, windowHeight, 'webgl');
 * }
 *
 * var theta = 0;
 *
 * function draw(){
 *   background(255, 255, 255, 255);
 *   translate(0, 0, -100);
 *   push();
 *   rotateZ(theta);
 *   rotateX(theta);
 *   rotateY(theta);
 *   torus(100, 20);
 *   pop();
 *   theta += 0.05;
 *
 *

 */
p5.prototype.torus = function(radius, tubeRadius, detailX, detailY){

  radius = radius || 50;
  tubeRadius = tubeRadius || 20;

  detailX = detailX || 12;
  detailY = detailY || 8;

  var gId = 'torus|'+radius+'|'+tubeRadius+'|'+detailX+'|'+detailY;

  if(!this._graphics.geometryInHash(gId)){

    var geometry3d = new p5.Geometry3D();

    var createTorus = function(u, v){
      var theta = 2 * Math.PI * u;
      var phi = 2 * Math.PI * v;
      var x = (radius + tubeRadius * Math.cos(phi)) * Math.cos(theta);
      var y = (radius + tubeRadius * Math.cos(phi)) * Math.sin(theta);
      var z = tubeRadius * Math.sin(phi);
      return new p5.Vector(x, y, z);
    };

    geometry3d.parametricGeometry(createTorus, detailX, detailY);

    var obj = geometry3d.generateObj();

    this._graphics.initBuffer(gId, obj);
  }

  this._graphics.drawBuffer(gId);

  return this;
};

/**
 * draw a box with given widht, height and depth
 * @param  {Number} width  width of the box
 * @param  {Number} height height of the box
 * @param  {Number} depth  depth of the box
 * example
 *

 *
 * function setup(){
 *   createCanvas(windowWidth, windowHeight, 'webgl');
 * }
 *
 * var theta = 0;
 *
 * function draw(){
 *   background(255, 255, 255, 255);
 *   translate(0, 0, -100);
 *   push();
 *   rotateZ(theta);
 *   rotateX(theta);
 *   rotateY(theta);
 *   box(100, 100, 100);
 *   pop();
 *   theta += 0.05;
 *
 *

 */
p5.prototype.box = function(width, height, depth){

  width = width || 50;
  height = height || width;
  depth = depth || width;

  //detail for box as optional
  var detailX = typeof arguments[3] === Number ? arguments[3] : 1;
  var detailY = typeof arguments[4] === Number ? arguments[4] : 1;

  var gId = 'cube|'+width+'|'+height+'|'+depth+'|'+detailX+'|'+detailY;

  if(!this._graphics.geometryInHash(gId)){

    var geometry3d = new p5.Geometry3D();

    var createPlane1 = function(u, v){
      var x = 2 * width * u - width;
      var y = 2 * height * v - height;
      var z = depth;
      return new p5.Vector(x, y, z);
    };
    var createPlane2 = function(u, v){
      var x = 2 * width * ( 1 - u ) - width;
      var y = 2 * height * v - height;
      var z = -depth;
      return new p5.Vector(x, y, z);
    };
    var createPlane3 = function(u, v){
      var x = 2 * width * ( 1 - u ) - width;
      var y = height;
      var z = 2 * depth * v - depth;
      return new p5.Vector(x, y, z);
    };
    var createPlane4 = function(u, v){
      var x = 2 * width * u - width;
      var y = -height;
      var z = 2 * depth * v - depth;
      return new p5.Vector(x, y, z);
    };
    var createPlane5 = function(u, v){
      var x = width;
      var y = 2 * height * u - height;
      var z = 2 * depth * v - depth;
      return new p5.Vector(x, y, z);
    };
    var createPlane6 = function(u, v){
      var x = -width;
      var y = 2 * height * ( 1 - u ) - height;
      var z = 2 * depth * v - depth;
      return new p5.Vector(x, y, z);
    };

    geometry3d.parametricGeometry(
      createPlane1, detailX, detailY, geometry3d.vertices.length);
    geometry3d.parametricGeometry(
      createPlane2, detailX, detailY, geometry3d.vertices.length);
    geometry3d.parametricGeometry(
      createPlane3, detailX, detailY, geometry3d.vertices.length);
    geometry3d.parametricGeometry(
      createPlane4, detailX, detailY, geometry3d.vertices.length);
    geometry3d.parametricGeometry(
      createPlane5, detailX, detailY, geometry3d.vertices.length);
    geometry3d.parametricGeometry(
      createPlane6, detailX, detailY, geometry3d.vertices.length);

    var obj = geometry3d.generateObj(true);

    this._graphics.initBuffer(gId, obj);
  }

  this._graphics.drawBuffer(gId);

  return this;

};

module.exports = p5;
<|endoftext|>


<commit_before>var iPhoneStyle = function(selector_or_elems, options) {
  options = Object.extend(Object.clone(iPhoneStyle.defaults), options || {});
  var elems;
  if (Object.isString(selector_or_elems)) {
    elems = $$(selector_or_elems);
  } else {
    elems = [selector_or_elems].flatten();
  }
  return(elems.each(function(elem) {

    if (!elem.match('input[type=checkbox]')) {
      return;
    }

    elem.setOpacity(0);
    elem.wrap('div', { 'class': options.containerClass});
    elem.insert({ 'after': '

' })
        .insert({ 'after': ''+ options.uncheckedLabel + '' })
        .insert({ 'after': '' + options.checkedLabel   + '' });

    var handle  = elem.up().down('.' + options.handleClass),
      offlabel  = elem.adjacent('.' + options.labelOffClass).first(),
      offspan   = offlabel.down('span'),
      onlabel   = elem.adjacent('.' + options.labelOnClass).first(),
      onspan    = onlabel.down('span'),
      container = elem.up('.' + options.containerClass);

    if (options.resizeHandle) {
      var min = (onlabel.getWidth() < offlabel.getWidth()) ? onlabel.getWidth() : offlabel.getWidth();
      handle.setStyle({width: min + 'px'});
    }
    if (options.resizeContainer) {
      var max = (onlabel.getWidth() > offlabel.getWidth()) ? onlabel.getWidth() : offlabel.getWidth();
      container.setStyle({width: max + handle.getWidth() + 12 + 'px'});
    }
    offlabel.setStyle({width: container.getWidth() - 5  + 'px'});

    var rightside = container.getWidth() - handle.getWidth() - 3;

    if (elem.checked) {
      handle.setStyle({ left: rightside + 'px' });
      onlabel.setStyle({ width: rightside + 4 + 'px' });
      offspan.setStyle({ 'marginRight': rightside + 'px' });
    } else {
      handle.setStyle({ left: 0 });
      onlabel.setStyle({ width: 0 });
      onspan.setStyle({ 'marginLeft': -rightside + 'px' });
    }

    elem.change = function() {
      var is_onstate = elem.checked;
      var p = handle.positionedOffset().first() / rightside;
      new Effect.Tween(null, p, Number(is_onstate), { duration: options.duration / 1000 }, function(p) {
        handle.setStyle({ left: p * rightside + 'px' });
        onlabel.setStyle({ width: p * rightside + 4 + 'px' });
        offspan.setStyle({ 'marginRight': -p * rightside + 'px' });
        onspan.setStyle({ 'marginLeft': -(1 - p) * rightside + 'px' });
      });
    };
    elem.observe('change', elem.change);

    var down = function(e) {
      e.stop();
      iPhoneStyle.clicking = handle;
      var x = Event.pointerX(e) || e.changedTouches[0].pageX;
      iPhoneStyle.dragStartPosition = x - (Number(handle.style.left.replace(/px$/, "")) || 0);
      Event.stop(e);
    };

    container.observe('mousedown', down);
    container.observe('touchstart', down);

    var move = function(e) {
      if (iPhoneStyle.clicking == handle) {
        e.stop();
        var x = Event.pointerX(e) || e.changedTouches[0].pageX;
        if (x != iPhoneStyle.dragStartPosition) {
          iPhoneStyle.dragging = true;
        }
        var p = (x - iPhoneStyle.dragStartPosition) / rightside;
        if (p < 0) { p = 0; }
        if (p > 1) { p = 1; }
        handle.setStyle({ left: p * rightside + 'px' });
        onlabel.setStyle({ width: p * rightside + 4 + 'px' });
        offspan.setStyle({ 'marginRight': -p * rightside + 'px' });
        onspan.setStyle({ 'marginLeft': -(1 - p) * rightside + 'px' });
      }
    };

    document.observe('mousemove', move);
    document.observe('touchmove', move);

    container.observe('mousedown', function(e) {
      e.stop();
      iPhoneStyle.clicking = handle;
      iPhoneStyle.dragStartPosition = Event.pointerX(e) - (Number(handle.style.left.replace(/px$/, "")) || 0);
      return false;
    });

    var up = function(e) {
      if (iPhoneStyle.clicking == handle) {
        e.stop();
        if (!iPhoneStyle.dragging) {
          var is_onstate = elem.checked;
          elem.writeAttribute('checked', !is_onstate);
        } else {
          var x = Event.pointerX(e) || e.changedTouches[0].pageX;
          var p = (x - iPhoneStyle.dragStartPosition) / rightside;
          elem.writeAttribute('checked', (p >= 0.5));
        }
        iPhoneStyle.clicking = null;
        iPhoneStyle.dragging = null;
        elem.change();
      }
    };
    document.observe('touchend', up);
    document.observe('mouseup', up);

    // Disable text selection
    [container, onlabel, offlabel, handle].invoke('observe', 'mousedown', function(e) { e.preventDefault(); return false; });
    if (Prototype.Browser.IE) {
      [container, onlabel, offlabel, handle].invoke('observe', 'startselect', function(e) { Event.stop(e); return false; });
    }
  }));
};

iPhoneStyle.defaults = {
  duration:          200,
  checkedLabel:      'ON',
  uncheckedLabel:    'OFF',
  resizeHandle:      true,
  resizeContainer:   true,
  background:        '#fff',
  containerClass:    'iPhoneCheckContainer',
  labelOnClass:      'iPhoneCheckLabelOn',
  labelOffClass:     'iPhoneCheckLabelOff',
  handleClass:       'iPhoneCheckHandle',
  handleCenterClass: 'iPhoneCheckHandleCenter',
  handleRightClass:  'iPhoneCheckHandleRight'
};
<commit_msg>Fixing an obscure IE8 issue, references #9.<commit_after>var iPhoneStyle = function(selector_or_elems, options) {
  options = Object.extend(Object.clone(iPhoneStyle.defaults), options || {});
  var elems;
  if (Object.isString(selector_or_elems)) {
    elems = $$(selector_or_elems);
  } else {
    elems = [selector_or_elems].flatten();
  }
  return(elems.each(function(elem) {

    if (!elem.match('input[type=checkbox]')) {
      return;
    }

    elem.setOpacity(0);
    elem.wrap('div', { 'class': options.containerClass});
    elem.insert({ 'after': '

' })
        .insert({ 'after': ''+ options.uncheckedLabel + '' })
        .insert({ 'after': '' + options.checkedLabel   + '' });

    var handle  = elem.up().down('.' + options.handleClass),
      offlabel  = elem.adjacent('.' + options.labelOffClass).first(),
      offspan   = offlabel.down('span'),
      onlabel   = elem.adjacent('.' + options.labelOnClass).first(),
      onspan    = onlabel.down('span'),
      container = elem.up();

    if (options.resizeHandle) {
      var min = (onlabel.getWidth() < offlabel.getWidth()) ? onlabel.getWidth() : offlabel.getWidth();
      handle.setStyle({width: min + 'px'});
    }
    if (options.resizeContainer) {
      var max = (onlabel.getWidth() > offlabel.getWidth()) ? onlabel.getWidth() : offlabel.getWidth();
      container.setStyle({width: max + handle.getWidth() + 12 + 'px'});
    }
    offlabel.setStyle({width: container.getWidth() - 5  + 'px'});

    var rightside = container.getWidth() - handle.getWidth() - 3;

    if (elem.checked) {
      handle.setStyle({ left: rightside + 'px' });
      onlabel.setStyle({ width: rightside + 4 + 'px' });
      offspan.setStyle({ 'marginRight': rightside + 'px' });
    } else {
      handle.setStyle({ left: 0 });
      onlabel.setStyle({ width: 0 });
      onspan.setStyle({ 'marginLeft': -rightside + 'px' });
    }

    elem.change = function() {
      var is_onstate = elem.checked;
      var p = handle.positionedOffset().first() / rightside;
      new Effect.Tween(null, p, Number(is_onstate), { duration: options.duration / 1000 }, function(p) {
        handle.setStyle({ left: p * rightside + 'px' });
        onlabel.setStyle({ width: p * rightside + 4 + 'px' });
        offspan.setStyle({ 'marginRight': -p * rightside + 'px' });
        onspan.setStyle({ 'marginLeft': -(1 - p) * rightside + 'px' });
      });
    };
    elem.observe('change', elem.change);

    var down = function(e) {
      e.stop();
      iPhoneStyle.clicking = handle;
      var x = Event.pointerX(e) || e.changedTouches[0].pageX;
      iPhoneStyle.dragStartPosition = x - (Number(handle.style.left.replace(/px$/, "")) || 0);
      Event.stop(e);
    };

    container.observe('mousedown', down);
    container.observe('touchstart', down);

    var move = function(e) {
      if (iPhoneStyle.clicking == handle) {
        e.stop();
        var x = Event.pointerX(e) || e.changedTouches[0].pageX;
        if (x != iPhoneStyle.dragStartPosition) {
          iPhoneStyle.dragging = true;
        }
        var p = (x - iPhoneStyle.dragStartPosition) / rightside;
        if (p < 0) { p = 0; }
        if (p > 1) { p = 1; }
        handle.setStyle({ left: p * rightside + 'px' });
        onlabel.setStyle({ width: p * rightside + 4 + 'px' });
        offspan.setStyle({ 'marginRight': -p * rightside + 'px' });
        onspan.setStyle({ 'marginLeft': -(1 - p) * rightside + 'px' });
      }
    };

    document.observe('mousemove', move);
    document.observe('touchmove', move);

    container.observe('mousedown', function(e) {
      e.stop();
      iPhoneStyle.clicking = handle;
      iPhoneStyle.dragStartPosition = Event.pointerX(e) - (Number(handle.style.left.replace(/px$/, "")) || 0);
      return false;
    });

    var up = function(e) {
      if (iPhoneStyle.clicking == handle) {
        e.stop();
        if (!iPhoneStyle.dragging) {
          var is_onstate = elem.checked;
          elem.writeAttribute('checked', !is_onstate);
        } else {
          var x = Event.pointerX(e) || e.changedTouches[0].pageX;
          var p = (x - iPhoneStyle.dragStartPosition) / rightside;
          elem.writeAttribute('checked', (p >= 0.5));
        }
        iPhoneStyle.clicking = null;
        iPhoneStyle.dragging = null;
        elem.change();
      }
    };
    document.observe('touchend', up);
    document.observe('mouseup', up);

    // Disable text selection
    [container, onlabel, offlabel, handle].invoke('observe', 'mousedown', function(e) { e.preventDefault(); return false; });
    if (Prototype.Browser.IE) {
      [container, onlabel, offlabel, handle].invoke('observe', 'startselect', function(e) { Event.stop(e); return false; });
    }
  }));
};

iPhoneStyle.defaults = {
  duration:          200,
  checkedLabel:      'ON',
  uncheckedLabel:    'OFF',
  resizeHandle:      true,
  resizeContainer:   true,
  background:        '#fff',
  containerClass:    'iPhoneCheckContainer',
  labelOnClass:      'iPhoneCheckLabelOn',
  labelOffClass:     'iPhoneCheckLabelOff',
  handleClass:       'iPhoneCheckHandle',
  handleCenterClass: 'iPhoneCheckHandleCenter',
  handleRightClass:  'iPhoneCheckHandleRight'
};
<|endoftext|>


<commit_before>var chart = function(csvpath, colormap, key_order, expand) {
colorrange = ["#F0AD4E", "#8c6699", "#a65959",];
strokecolor = '#000';

var format = d3.time.format("%Y-%m-%d %H:%M:%S %Z");
var date_format = d3.time.format("%Y-%m-%d");
var month_format = d3.time.format("%b");

var margin = {top: 20, right: 60, bottom: 30, left: 60};
var width = 600;
var height = 600 - margin.top - margin.bottom;

var tooltip = d3.select("#chart-container")
    .append("div")
    .attr("class", "remove")
    .style("visibility", "hidden")
    .style('margin-left', '60px')
    ;

var x = d3.time.scale()
    .range([0, width]);

var y = d3.scale.linear()
    .range([height-10, 0]);

var z = d3.scale.ordinal()
    .range(colorrange);

// X Axis scale with year ticks
var xAxis = d3.svg.axis()
    .scale(x)
    .orient("bottom")
    .ticks(d3.time.years)
    .tickSize(20)
    .outerTickSize(0);

// X Axis scale with month ticks
var xAxisMonths = d3.svg.axis()
    .scale(x)
    .orient("bottom")
    .ticks(d3.time.months)
    .tickSize(5)
    .outerTickSize(0);

// Y Axis scale on the left
var yAxis = d3.svg.axis()
    .scale(y);

// Y Axis scale on the right
var yAxisr = d3.svg.axis()
    .scale(y);

var stack = d3.layout.stack()
    .offset(expand ? 'expand' : 'zero')
    .values(function(d) { return d.values; })
    .x(function(d) { return d.date; })
    .y(function(d) { return d.num_packages; });

var nest = d3.nest()
    .key(function(d) { return d.status; })
    .sortKeys(function (a, b) {
            return key_order.indexOf(a) - key_order.indexOf(b);
        } );

var area = d3.svg.area()
    .interpolate("cardinal")
    .x(function(d) { return x(d.date); })
    .y0(function(d) { return y(d.y0); })
    .y1(function(d) { return y(d.y0 + d.y); });

var svg = d3.select(".chart")
        .style("position", "relative")
  .append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
  .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

var graph = d3.csv(csvpath, function(data) {
  data.forEach(function(d) {
    d.date = format.parse(d.date);//.substr(0, 19));
    d.num_packages = +d.num_packages;
  });
  data = data.filter( function (d) { return d.date >= new Date(2015, 9, 10); } );

  // If the data spans less than years, we'll want to show month names on the X axis
  var year_span = data[data.length-1].date.getFullYear() - data[0].date.getFullYear();
  var show_months = (year_span < 2);

  var layers = stack(nest.entries(data));

  x.domain(d3.extent(data, function(d) { return d.date; }));
  y.domain([0, d3.max(data, function(d) { return d.y0 + d.y; })]);

  svg.selectAll(".layer")
      .data(layers)
    .enter().append("path")
      .attr("class", "layer")
      .attr("d", function(d) { return area(d.values); })
      .style("fill", function(d, i) {
        return colormap[d.key];
      });

  svg.append("g")
      .attr("class", "x axis")
      .attr("transform", "translate(0," + height + ")")
      .call(xAxis)
  .selectAll("text")
    .attr("y", 6)
    .attr("x", 6)
    .style("text-anchor", "start")
    .text( function (d) { return d.getFullYear(); });

  svg.append("g")
      .attr("class", "x axis")
      .attr("transform", "translate(0," + height + ")")
      .call(xAxisMonths)
  .selectAll("text")
    .text( function (d) {
        // Only show month names if there's space (show_months),
        // and skip month name for January (d.getMonth() == 0)
        return show_months && d.getMonth() ? month_format(d) : "";
    });

  if (expand) {
    var y_format = function(d) { return d * 100 + '%'; };
  } else {
    var y_format = function(d) { return '' + d; };
  }

  svg.append("g")
      .attr("class", "y axis")
      .attr("transform", "translate(" + width + ", 0)")
      .call(yAxis.orient("right").tickFormat( y_format ));

  svg.append("g")
      .attr("class", "y axis")
      .call(yAxis.orient("left").tickFormat( y_format ));

  var make_minibadge = function (key) {
    return " ";
  }
  var reset_tooltip = function () {
    var lines = [" "]
    key_order.forEach(function (key) {
      var p = make_minibadge(key);
      var text = key;
        lines.splice(1, 0, p + text);
    });
    tooltip.html( "
" + lines.join('
') + "
" ).style("visibility", "visible");
  };

  svg.selectAll(".layer")
    .attr("opacity", 1)
    .on("mouseover", function(d, i) {
      svg.selectAll(".layer").transition()
      .duration(250)
      .attr("opacity", function(d, j) {
        return j != i ? 1 : 1;
    })})

    .on("mousemove", function(dd, i) {
      var m=this;
      var lines = [];
      layers.forEach(function (d, i) {
      mousex = d3.mouse(m);
      mousex = mousex[0];
      var invertedx = x.invert(mousex);
      var selected = (d.values);
      for (var k = 0; k < selected.length; k++) {
        if (selected[k].date > invertedx) break;
        entry = selected[k];
        datearray[k] = selected[k].date;
      }

      pro = entry.num_packages;

      if (lines.length == 0) lines.push(date_format(entry.date));
      var p = make_minibadge(d.key);
      var text = d.key + ': ' + pro + " packages";
      if (dd === d) {
        lines.splice(1, 0, p + "" + text + "");
      } else {
        lines.splice(1, 0, p + text);
      }
      });
      tooltip.html( "
" + lines.join('
') + "
" ).style("visibility", "visible");
    })
    .on("mouseout", function(d, i) {
      d3.select(this)
      .classed("hover", false)
       .attr("stroke-width", "0px");
      //reset_tooltip();
  })

  var vertical = d3.select(".chart")
        .append("div")
        .attr("class", "remove")
        .style("position", "absolute")
        .style("z-index", "19")
        .style("width", "1px")
        .style("height", "560px")
        .style("top", "10px")
        .style("bottom", "30px")
        .style("left", "0px")
        .style("opacity", "0.5")
        .style("background-color", "#fff");
//*
  d3.select(".chart")
      .on("mousemove", function(){
         mousex = d3.mouse(this);
         mousex = mousex[0] + 5;
         vertical.style("left", mousex + "px" )})
      .on("mouseover", function(){
         mousex = d3.mouse(this);
         mousex = mousex[0] + 5;
         vertical.style("left", mousex + "px")});
         //*/
  reset_tooltip();
});
}
<commit_msg>Adjust position & alignment of the X axis labels for history graphs.<commit_after>var chart = function(csvpath, colormap, key_order, expand) {
colorrange = ["#F0AD4E", "#8c6699", "#a65959",];
strokecolor = '#000';

var format = d3.time.format("%Y-%m-%d %H:%M:%S %Z");
var date_format = d3.time.format("%Y-%m-%d");
var month_format = d3.time.format("%b");

var margin = {top: 20, right: 60, bottom: 30, left: 60};
var width = 600;
var height = 600 - margin.top - margin.bottom;

var tooltip = d3.select("#chart-container")
    .append("div")
    .attr("class", "remove")
    .style("visibility", "hidden")
    .style('margin-left', '60px')
    ;

var x = d3.time.scale()
    .range([0, width]);

var y = d3.scale.linear()
    .range([height-10, 0]);

var z = d3.scale.ordinal()
    .range(colorrange);

// X Axis scale with year ticks
var xAxis = d3.svg.axis()
    .scale(x)
    .orient("bottom")
    .ticks(d3.time.years)
    .tickSize(20)
    .outerTickSize(0);

// X Axis scale with month ticks
var xAxisMonths = d3.svg.axis()
    .scale(x)
    .orient("bottom")
    .ticks(d3.time.months)
    .tickSize(5)
    .outerTickSize(0);

// Y Axis scale on the left
var yAxis = d3.svg.axis()
    .scale(y);

// Y Axis scale on the right
var yAxisr = d3.svg.axis()
    .scale(y);

var stack = d3.layout.stack()
    .offset(expand ? 'expand' : 'zero')
    .values(function(d) { return d.values; })
    .x(function(d) { return d.date; })
    .y(function(d) { return d.num_packages; });

var nest = d3.nest()
    .key(function(d) { return d.status; })
    .sortKeys(function (a, b) {
            return key_order.indexOf(a) - key_order.indexOf(b);
        } );

var area = d3.svg.area()
    .interpolate("cardinal")
    .x(function(d) { return x(d.date); })
    .y0(function(d) { return y(d.y0); })
    .y1(function(d) { return y(d.y0 + d.y); });

var svg = d3.select(".chart")
        .style("position", "relative")
  .append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
  .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

var graph = d3.csv(csvpath, function(data) {
  data.forEach(function(d) {
    d.date = format.parse(d.date);//.substr(0, 19));
    d.num_packages = +d.num_packages;
  });
  data = data.filter( function (d) { return d.date >= new Date(2015, 9, 10); } );

  // If the data spans less than years, we'll want to show month names on the X axis
  var year_span = data[data.length-1].date.getFullYear() - data[0].date.getFullYear();
  var show_months = (year_span < 2);

  var layers = stack(nest.entries(data));

  x.domain(d3.extent(data, function(d) { return d.date; }));
  y.domain([0, d3.max(data, function(d) { return d.y0 + d.y; })]);

  svg.selectAll(".layer")
      .data(layers)
    .enter().append("path")
      .attr("class", "layer")
      .attr("d", function(d) { return area(d.values); })
      .style("fill", function(d, i) {
        return colormap[d.key];
      });

  svg.append("g")
      .attr("class", "x axis")
      .attr("transform", "translate(0," + height + ")")
      .call(xAxis)
  .selectAll("text")
    .attr("y", 9)
    .attr("x", 3)
    .style("text-anchor", "start")
    .text( function (d) { return d.getFullYear(); });

  svg.append("g")
      .attr("class", "x axis")
      .attr("transform", "translate(0," + height + ")")
      .call(xAxisMonths)
  .selectAll("text")
    .attr("y", 9)
    .attr("x", 3)
    .style("text-anchor", "start")
    .text( function (d) {
        // Only show month names if there's space (show_months),
        // and skip month name for January (d.getMonth() == 0)
        return show_months && d.getMonth() ? month_format(d) : "";
    });

  if (expand) {
    var y_format = function(d) { return d * 100 + '%'; };
  } else {
    var y_format = function(d) { return '' + d; };
  }

  svg.append("g")
      .attr("class", "y axis")
      .attr("transform", "translate(" + width + ", 0)")
      .call(yAxis.orient("right").tickFormat( y_format ));

  svg.append("g")
      .attr("class", "y axis")
      .call(yAxis.orient("left").tickFormat( y_format ));

  var make_minibadge = function (key) {
    return " ";
  }
  var reset_tooltip = function () {
    var lines = [" "]
    key_order.forEach(function (key) {
      var p = make_minibadge(key);
      var text = key;
        lines.splice(1, 0, p + text);
    });
    tooltip.html( "
" + lines.join('
') + "
" ).style("visibility", "visible");
  };

  svg.selectAll(".layer")
    .attr("opacity", 1)
    .on("mouseover", function(d, i) {
      svg.selectAll(".layer").transition()
      .duration(250)
      .attr("opacity", function(d, j) {
        return j != i ? 1 : 1;
    })})

    .on("mousemove", function(dd, i) {
      var m=this;
      var lines = [];
      layers.forEach(function (d, i) {
      mousex = d3.mouse(m);
      mousex = mousex[0];
      var invertedx = x.invert(mousex);
      var selected = (d.values);
      for (var k = 0; k < selected.length; k++) {
        if (selected[k].date > invertedx) break;
        entry = selected[k];
        datearray[k] = selected[k].date;
      }

      pro = entry.num_packages;

      if (lines.length == 0) lines.push(date_format(entry.date));
      var p = make_minibadge(d.key);
      var text = d.key + ': ' + pro + " packages";
      if (dd === d) {
        lines.splice(1, 0, p + "" + text + "");
      } else {
        lines.splice(1, 0, p + text);
      }
      });
      tooltip.html( "
" + lines.join('
') + "
" ).style("visibility", "visible");
    })
    .on("mouseout", function(d, i) {
      d3.select(this)
      .classed("hover", false)
       .attr("stroke-width", "0px");
      //reset_tooltip();
  })

  var vertical = d3.select(".chart")
        .append("div")
        .attr("class", "remove")
        .style("position", "absolute")
        .style("z-index", "19")
        .style("width", "1px")
        .style("height", "560px")
        .style("top", "10px")
        .style("bottom", "30px")
        .style("left", "0px")
        .style("opacity", "0.5")
        .style("background-color", "#fff");
//*
  d3.select(".chart")
      .on("mousemove", function(){
         mousex = d3.mouse(this);
         mousex = mousex[0] + 5;
         vertical.style("left", mousex + "px" )})
      .on("mouseover", function(){
         mousex = d3.mouse(this);
         mousex = mousex[0] + 5;
         vertical.style("left", mousex + "px")});
         //*/
  reset_tooltip();
});
}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2010 Shoichi Sakane <sakane@tanu.org>, All rights reserved.
 * See the file LICENSE in the top level directory for more details.
 */

//==== DONT TOUCH BELOW ===
//==== INTERNAL USE ===
/*
 * tzOffset: (integer, internally)
 * firstRetrieve: (integer, internally)
 * totalPoints: (integer, internally)
 *     the number of total points in the canvas.
 *     288 points will be plotted if both xrange and updateInterval are default.
 * xtickFormat:
 * xtickSize:
 * flotXAxisBase:
 * flotSeriesBase:
 * flotLegendBase:
 * flotGridBase:
 * errorbarPointStyle:
 */

/*
 * initialization
 */
var _wrenDataSet = [];
var _wrenEvTimeout = null;

/*
 * XXX need to check the contents of wrenObj.
 */
function wren_init()
{
  if (typeof(wrenObj) == 'undefined') {
    alert('ERROR: wrenObj must be defined.');
  }

  // once it gets multiple data, it will get one data from next time.
  wrenObj.firstRetrieve = true;

  /* check whether type exists */
  if (typeof(wrenObj.type) == 'undefined') {
    alert('ERROR: wrenObj.type must be defined.');
  }

  /* check type and set query function */
  // XXX here, should call init function according to the type.
  if (wrenObj.type == 'kiwi') {
    kiwi_init(wrenObj);
  } else if (wrenObj.type == 'fiap') {
    fiap_init(wrenObj);
  } else if (wrenObj.type == 'kii') {
    kii_init(wrenObj);
  } else {
    alert('ERROR: wrenObj.type must be defined or be kiwi, fiap, or kii.');
  }

  /* check wrenObj.tz */
  if (typeof(wrenObj.tz) == 'undefined') {
    wrenObj.tz = 0;
  }
  wrenObj.tzOffset = (wrenObj.tz * 3600000); // wrenObj.tz * 60 * 60 * 1000

  /* check wrenObj.updateInterval and wrenObj.totalPoints */
  if (!wrenObj.hasOwnProperty('updateInterval')) {
    wrenObj.updateInterval = 600000;
  }
  if (!wrenObj.hasOwnProperty('xrange')) {
    wrenObj.xrange = 172800000;
  }
  wrenObj.totalPoints = wrenObj.xrange / wrenObj.updateInterval;

  /*
   * if xrange is more than 2.5 days, the xtick format will be YY/mm/dd,
   * otherwise HH:MM:DD.
   */
  if (wrenObj.xrange >= 889032704) {
    /* 2 months */
    //wrenObj.xtickFormat = "%Y/%m/%d";
    wrenObj.xtickFormat = "%m/%d";
    wrenObj.xtickSize = [ 15, "day" ];
  } else if (wrenObj.xrange >= 216000000) {
    /* 2.5 days */
    wrenObj.xtickFormat = "%H:%M";
    wrenObj.xtickSize = [ 12, "hour" ];
  } else if (wrenObj.xrange >= 86400000) {
    /* 1 day */
    wrenObj.xtickFormat = "%H:%M";
    wrenObj.xtickSize = [ 6, "hour" ];
  } else if (wrenObj.xrange >= 43200000) {
    /* 12 hours */
    wrenObj.xtickFormat = "%H:%M";
    wrenObj.xtickSize = [ 1, "hour" ];
  } else if (wrenObj.xrange >= 3600000) {
    /* 1 hour */
    wrenObj.xtickFormat = "%H:%M";
    wrenObj.xtickSize = [ 15, "minute" ];
  } else {
    wrenObj.xtickFormat = "%H:%M:%S";
    wrenObj.xtickSize = [ wrenObj.xrange / 1000 / 5, "second" ];
  }

  wrenObj.flotXAxisBase = {
    mode: "time",
    timezone: "browser",
    tickSize: wrenObj.xtickSize,
    timeformat: wrenObj.xtickFormat,
  //  tickFormatter: tick_x_format,
  //  minTickSize: [ 20, "second" ],
    axisLabel: "Time",
    axisLabelUseCanvas: true,
    axisLabelFontSizePixels: 10,
    axisLabelFontFamily: 'Verdana, Arial',
    axisLabelPadding: 10
  };

  wrenObj.flotSeriesBase = {
    lines: {
      lineWidth: 1.2
    },
    bars: {
      align: "center",
      fillColor: { colors: [{ opacity: 1 }, { opacity: 1}] },
      barWidth: 500,
      lineWidth: 1
    }
  };

  wrenObj.flotLegendBase = {
    noColumns: 0,
    position:"nw"
  };

  wrenObj.flotGridBase = {
    backgroundColor: { colors: ["#ffffff", "#EDF5FF"] }
  };

  wrenObj.errorbarPointStyle = {
    radius: 0,
    errorbars: "y",
    yerr: {
      show:true,
      asymmetric:true,
      upperCap:"-",
      lowerCap:"-",
      radius:5
    } };
}

function tick_x_format(v, axis) {
  var date = new Date(v);
  if (date.getSeconds() % xxx == 0) {
    var hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
    var minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
    var seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
    return hours + ":" + minutes + ":" + seconds;
  } else {
    return "";
  }
}

/*
 * @param member a list of indexes, e.g. [ 1, 2 ]
 */
function get_float_axes(member) {
  var v_yaxes = [];
  for (var i = 0; i < member.length; i++) {
    var idx = member[i];
    var d = {
      min: wrenObj.dataDef[idx].min,
      max: wrenObj.dataDef[idx].max,
      tickSize:wrenObj.dataDef[idx].ytick,
      axisLabel: wrenObj.dataDef[idx].unit,
      axisLabelUseCanvas: true,
      axisLabelFontSizePixels: 12,
      axisLabelFontFamily: 'Verdana, Arial',
      axisLabelPadding: 6
    };
    if (wrenObj.dataDef[idx].yaxis == 2)
      d["position"] = "right";
    v_yaxes.push(d);
  }
  return {
    series: wrenObj.flotSeriesBase,
    xaxis: wrenObj.flotXAxisBase,
    yaxes: v_yaxes,
    legend: wrenObj.flotLegendBase,
    grid: wrenObj.flotGridBase,
  };
}

/*
 * @param member a list of indexes, e.g. [ 1, 2 ]
 */
function update_flot_data(member) {
  var ret = [];
  for (var i = 0; i < member.length; i++) {
    var idx = member[i];
//console.log(_wrenDataSet[idx]);
    var dataset = {
      label: wrenObj.dataDef[idx].label + ": " + _wrenDataSet[idx][0][1] + " " + wrenObj.dataDef[idx].unit,
      data: _wrenDataSet[idx],
      lines: { show: true, fill: false, lineWidth: 1.2 },
      color: wrenObj.dataDef[idx].color,
      //clickable: "true",
      //hoverable: "true",
    };
    if (wrenObj.dataDef[idx].yaxis == 2)
      dataset['yaxis'] = 2;
    if (_wrenDataSet[idx][0].length == 4)
      dataset['points'] = wrenObj.errorbarPointStyle;
    ret.push(dataset);
  }
  return ret;
}

/*
 * flotDef: defines a combination of dataDefs.
 *   = [ {
 *         flot: <canvas id>,
 *         set: [ <# of list of dataDefs> ]
 *       }, {...} ]
 */
function update_canvas()
{
  for (var i = 0; i < wrenObj.flotDef.length; i++) {
    var canvas = wrenObj.flotDef[i].flot;
    var dataset = update_flot_data(wrenObj.flotDef[i].set);
    var opt = get_float_axes(wrenObj.flotDef[i].set);
    $.plot($(canvas), dataset, opt);
  }
}

/*
 * dataDef: defines a set of parameter for a single line or points.
 *   = [ {
 *         key: [ <list of keys> ],
 *         label: "<label>",
 *         unit: "<unit>",
 *         color: "<color>",
 *         min: <number>,
 *         max: <number>,
 *         ytick: <number>,
 *         yaxis: <option: 2>
 *     }, {...} ]
 */

/*
 * update the dataset, _wrenDataSet.
 * @param obj a list of points in json.
 * @param obj index of the target in dataDef.
 * XXX this function needs to be reviewd..
 */
function wren_update_dataset(res, i)
{
  var kvt = [];
  for (var j = 0; j < wrenObj.dataDef[i].key.length; j++) {
    kvt[j] = res[wrenObj.dataDef[i].key[j]];
//console.log('kvt', j, kvt[j]);
  }
  for (var k = 0; k < kvt[0].length; k++) {
    var d = kvt[0][k];
    if (wrenObj.dataDef[i].key.length > 1) {
      /*
       * assuming it's an errorbar chart.
       */
      var y = kvt[0][k][1];
      var found = false;
//console.log('#of res', wrenObj.dataDef[i].key.length);
      for (var j = 1; j < wrenObj.dataDef[i].key.length; j++) {
        for (var q = 0; q < kvt[j].length; q++) {
          if (kvt[j][q][0] == kvt[0][k][0]) {
            found = true;
            z = kvt[j][q][1];
            if (z > y)
              z -= y;
            else
              z = y - z;
            d.push(z);
            break;
          }
        }
        if (wrenObj.dataDef[i].key.length > 1 && found == false) {
          console.log('ERROR: no suitable value for', wrenObj.dataDef[i].key[0], kvt[0][k][0]);
        }
      }
    }
    _wrenDataSet[i].unshift(d);
  }
}

function fill_dataset(i)
{
//console.log('before filled: _wrenDataSet', i, _wrenDataSet[i]);
//console.log('  length', _wrenDataSet[i].length);
  var x = _wrenDataSet[i][_wrenDataSet[i].length - 1][0];
  var jmax = wrenObj.totalPoints - _wrenDataSet[i].length;
  for (var j = 0; j < jmax; j++) {
    var d = [x -= wrenObj.updateInterval];
    for (var k = 0; k < wrenObj.dataDef[i].key.length; k++) {
      d.push(0);
    }
    _wrenDataSet[i].push(d);
  }
//console.log('filled _wrenDataSet[i].length', _wrenDataSet[i].length);
}

/*
 * send a query.
 */
function send_query()
{
  var cb;
  if (wrenObj.firstRetrieve == true)
    cb = cb_server_response_at_once;
  else
    cb = cb_server_response;
  /* call the proper function for query. */
  wrenObj.query_function(wrenObj, cb, cb_error);
}

function set_timeout()
{
  _wrenEvTimeout = setTimeout(send_query, wrenObj.updateInterval);
}

function cb_error()
{
  clearTimeout(_wrenEvTimeout);
  /*
   * retry anyway.
   * XXX it should be done according to the error code from the server.
   */
  set_timeout();
}

/*
 * it deals with one record.
 * callback function to parse the response.
 * update the data set and canvas.
 */
function cb_server_response(res)
{
  clearTimeout(_wrenEvTimeout);
  res = wren_obj_serialize(res, wrenObj.tzOffset);
  for (var i = 0; i < wrenObj.dataDef.length; i++) {
    _wrenDataSet[i].pop();  // remove the oldest record.
    wren_update_dataset(res, i);
  }
  update_canvas();
  set_timeout();
}

/*
 * it deals with all records in the duratoin.
 * callback function to parse the response at once.
 * update the data set and canvas.
 */
function cb_server_response_at_once(res)
{
  clearTimeout(_wrenEvTimeout);
  if (wrenObj.firstRetrieve == true) {
    wrenObj.firstRetrieve = false;
  }
  res = wren_obj_serialize(res, wrenObj.tzOffset);
  for (var i = 0; i < wrenObj.dataDef.length; i++) {
    wren_update_dataset(res, i);
    fill_dataset(i);
  }
  update_canvas();
  set_timeout();
}

/********
 *
 * callback for events.
 */

function ev_click_start()
{
  clearTimeout(_wrenEvTimeout);
  send_query();
}

function ev_click_stop()
{
  clearTimeout(_wrenEvTimeout);
}

function ev_init()
{
  document.getElementById('btnStop').addEventListener('click', ev_click_stop, false);
  document.getElementById('btnStart').addEventListener('click', ev_click_start, false);
}

$(document).ready(function() {
  for (var i = 0; i < wrenObj.dataDef.length; i++) {
    _wrenDataSet[i] = [];
    /*
     * update the field of the keys in the document if these fields exist.
     */
  }
  wren_init();
  ev_init();
});
<commit_msg>attribute definitions should be placed after the attribute required check.<commit_after>/*
 * Copyright (C) 2010 Shoichi Sakane <sakane@tanu.org>, All rights reserved.
 * See the file LICENSE in the top level directory for more details.
 */

//==== DONT TOUCH BELOW ===
//==== INTERNAL USE ===
/*
 * tzOffset: (integer, internally)
 * firstRetrieve: (integer, internally)
 * totalPoints: (integer, internally)
 *     the number of total points in the canvas.
 *     288 points will be plotted if both xrange and updateInterval are default.
 * xtickFormat:
 * xtickSize:
 * flotXAxisBase:
 * flotSeriesBase:
 * flotLegendBase:
 * flotGridBase:
 * errorbarPointStyle:
 */

/*
 * initialization
 */
var _wrenDataSet = [];
var _wrenEvTimeout = null;

/*
 * XXX need to check the contents of wrenObj.
 */
function wren_init()
{
  if (typeof(wrenObj) == 'undefined') {
    alert('ERROR: wrenObj must be defined.');
  }

  /* check whether type exists */
  if (typeof(wrenObj.type) == 'undefined') {
    alert('ERROR: wrenObj.type must be defined.');
  }

  /* check type and set query function */
  // XXX here, should call init function according to the type.
  if (wrenObj.type == 'kiwi') {
    kiwi_init(wrenObj);
  } else if (wrenObj.type == 'fiap') {
    fiap_init(wrenObj);
  } else if (wrenObj.type == 'kii') {
    kii_init(wrenObj);
  } else {
    alert('ERROR: wrenObj.type must be defined or be kiwi, fiap, or kii.');
  }

  // once it gets multiple data, it will get one data from next time.
  wrenObj.firstRetrieve = true;

  /* check wrenObj.tz */
  if (typeof(wrenObj.tz) == 'undefined') {
    wrenObj.tz = 0;
  }
  wrenObj.tzOffset = (wrenObj.tz * 3600000); // wrenObj.tz * 60 * 60 * 1000

  /* check wrenObj.updateInterval and wrenObj.totalPoints */
  if (!wrenObj.hasOwnProperty('updateInterval')) {
    wrenObj.updateInterval = 600000;
  }
  if (!wrenObj.hasOwnProperty('xrange')) {
    wrenObj.xrange = 172800000;
  }
  wrenObj.totalPoints = wrenObj.xrange / wrenObj.updateInterval;

  /*
   * if xrange is more than 2.5 days, the xtick format will be YY/mm/dd,
   * otherwise HH:MM:DD.
   */
  if (wrenObj.xrange >= 889032704) {
    /* 2 months */
    //wrenObj.xtickFormat = "%Y/%m/%d";
    wrenObj.xtickFormat = "%m/%d";
    wrenObj.xtickSize = [ 15, "day" ];
  } else if (wrenObj.xrange >= 216000000) {
    /* 2.5 days */
    wrenObj.xtickFormat = "%H:%M";
    wrenObj.xtickSize = [ 12, "hour" ];
  } else if (wrenObj.xrange >= 86400000) {
    /* 1 day */
    wrenObj.xtickFormat = "%H:%M";
    wrenObj.xtickSize = [ 6, "hour" ];
  } else if (wrenObj.xrange >= 43200000) {
    /* 12 hours */
    wrenObj.xtickFormat = "%H:%M";
    wrenObj.xtickSize = [ 1, "hour" ];
  } else if (wrenObj.xrange >= 3600000) {
    /* 1 hour */
    wrenObj.xtickFormat = "%H:%M";
    wrenObj.xtickSize = [ 15, "minute" ];
  } else {
    wrenObj.xtickFormat = "%H:%M:%S";
    wrenObj.xtickSize = [ wrenObj.xrange / 1000 / 5, "second" ];
  }

  wrenObj.flotXAxisBase = {
    mode: "time",
    timezone: "browser",
    tickSize: wrenObj.xtickSize,
    timeformat: wrenObj.xtickFormat,
  //  tickFormatter: tick_x_format,
  //  minTickSize: [ 20, "second" ],
    axisLabel: "Time",
    axisLabelUseCanvas: true,
    axisLabelFontSizePixels: 10,
    axisLabelFontFamily: 'Verdana, Arial',
    axisLabelPadding: 10
  };

  wrenObj.flotSeriesBase = {
    lines: {
      lineWidth: 1.2
    },
    bars: {
      align: "center",
      fillColor: { colors: [{ opacity: 1 }, { opacity: 1}] },
      barWidth: 500,
      lineWidth: 1
    }
  };

  wrenObj.flotLegendBase = {
    noColumns: 0,
    position:"nw"
  };

  wrenObj.flotGridBase = {
    backgroundColor: { colors: ["#ffffff", "#EDF5FF"] }
  };

  wrenObj.errorbarPointStyle = {
    radius: 0,
    errorbars: "y",
    yerr: {
      show:true,
      asymmetric:true,
      upperCap:"-",
      lowerCap:"-",
      radius:5
    } };
}

function tick_x_format(v, axis) {
  var date = new Date(v);
  if (date.getSeconds() % xxx == 0) {
    var hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
    var minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
    var seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
    return hours + ":" + minutes + ":" + seconds;
  } else {
    return "";
  }
}

/*
 * @param member a list of indexes, e.g. [ 1, 2 ]
 */
function get_float_axes(member) {
  var v_yaxes = [];
  for (var i = 0; i < member.length; i++) {
    var idx = member[i];
    var d = {
      min: wrenObj.dataDef[idx].min,
      max: wrenObj.dataDef[idx].max,
      tickSize:wrenObj.dataDef[idx].ytick,
      axisLabel: wrenObj.dataDef[idx].unit,
      axisLabelUseCanvas: true,
      axisLabelFontSizePixels: 12,
      axisLabelFontFamily: 'Verdana, Arial',
      axisLabelPadding: 6
    };
    if (wrenObj.dataDef[idx].yaxis == 2)
      d["position"] = "right";
    v_yaxes.push(d);
  }
  return {
    series: wrenObj.flotSeriesBase,
    xaxis: wrenObj.flotXAxisBase,
    yaxes: v_yaxes,
    legend: wrenObj.flotLegendBase,
    grid: wrenObj.flotGridBase,
  };
}

/*
 * @param member a list of indexes, e.g. [ 1, 2 ]
 */
function update_flot_data(member) {
  var ret = [];
  for (var i = 0; i < member.length; i++) {
    var idx = member[i];
//console.log(_wrenDataSet[idx]);
    var dataset = {
      label: wrenObj.dataDef[idx].label + ": " + _wrenDataSet[idx][0][1] + " " + wrenObj.dataDef[idx].unit,
      data: _wrenDataSet[idx],
      lines: { show: true, fill: false, lineWidth: 1.2 },
      color: wrenObj.dataDef[idx].color,
      //clickable: "true",
      //hoverable: "true",
    };
    if (wrenObj.dataDef[idx].yaxis == 2)
      dataset['yaxis'] = 2;
    if (_wrenDataSet[idx][0].length == 4)
      dataset['points'] = wrenObj.errorbarPointStyle;
    ret.push(dataset);
  }
  return ret;
}

/*
 * flotDef: defines a combination of dataDefs.
 *   = [ {
 *         flot: <canvas id>,
 *         set: [ <# of list of dataDefs> ]
 *       }, {...} ]
 */
function update_canvas()
{
  for (var i = 0; i < wrenObj.flotDef.length; i++) {
    var canvas = wrenObj.flotDef[i].flot;
    var dataset = update_flot_data(wrenObj.flotDef[i].set);
    var opt = get_float_axes(wrenObj.flotDef[i].set);
    $.plot($(canvas), dataset, opt);
  }
}

/*
 * dataDef: defines a set of parameter for a single line or points.
 *   = [ {
 *         key: [ <list of keys> ],
 *         label: "<label>",
 *         unit: "<unit>",
 *         color: "<color>",
 *         min: <number>,
 *         max: <number>,
 *         ytick: <number>,
 *         yaxis: <option: 2>
 *     }, {...} ]
 */

/*
 * update the dataset, _wrenDataSet.
 * @param obj a list of points in json.
 * @param obj index of the target in dataDef.
 * XXX this function needs to be reviewd..
 */
function wren_update_dataset(res, i)
{
  var kvt = [];
  for (var j = 0; j < wrenObj.dataDef[i].key.length; j++) {
    kvt[j] = res[wrenObj.dataDef[i].key[j]];
//console.log('kvt', j, kvt[j]);
  }
  for (var k = 0; k < kvt[0].length; k++) {
    var d = kvt[0][k];
    if (wrenObj.dataDef[i].key.length > 1) {
      /*
       * assuming it's an errorbar chart.
       */
      var y = kvt[0][k][1];
      var found = false;
//console.log('#of res', wrenObj.dataDef[i].key.length);
      for (var j = 1; j < wrenObj.dataDef[i].key.length; j++) {
        for (var q = 0; q < kvt[j].length; q++) {
          if (kvt[j][q][0] == kvt[0][k][0]) {
            found = true;
            z = kvt[j][q][1];
            if (z > y)
              z -= y;
            else
              z = y - z;
            d.push(z);
            break;
          }
        }
        if (wrenObj.dataDef[i].key.length > 1 && found == false) {
          console.log('ERROR: no suitable value for', wrenObj.dataDef[i].key[0], kvt[0][k][0]);
        }
      }
    }
    _wrenDataSet[i].unshift(d);
  }
}

function fill_dataset(i)
{
//console.log('before filled: _wrenDataSet', i, _wrenDataSet[i]);
//console.log('  length', _wrenDataSet[i].length);
  var x = _wrenDataSet[i][_wrenDataSet[i].length - 1][0];
  var jmax = wrenObj.totalPoints - _wrenDataSet[i].length;
  for (var j = 0; j < jmax; j++) {
    var d = [x -= wrenObj.updateInterval];
    for (var k = 0; k < wrenObj.dataDef[i].key.length; k++) {
      d.push(0);
    }
    _wrenDataSet[i].push(d);
  }
//console.log('filled _wrenDataSet[i].length', _wrenDataSet[i].length);
}

/*
 * send a query.
 */
function send_query()
{
  var cb;
  if (wrenObj.firstRetrieve == true)
    cb = cb_server_response_at_once;
  else
    cb = cb_server_response;
  /* call the proper function for query. */
  wrenObj.query_function(wrenObj, cb, cb_error);
}

function set_timeout()
{
  _wrenEvTimeout = setTimeout(send_query, wrenObj.updateInterval);
}

function cb_error()
{
  clearTimeout(_wrenEvTimeout);
  /*
   * retry anyway.
   * XXX it should be done according to the error code from the server.
   */
  set_timeout();
}

/*
 * it deals with one record.
 * callback function to parse the response.
 * update the data set and canvas.
 */
function cb_server_response(res)
{
  clearTimeout(_wrenEvTimeout);
  res = wren_obj_serialize(res, wrenObj.tzOffset);
  for (var i = 0; i < wrenObj.dataDef.length; i++) {
    _wrenDataSet[i].pop();  // remove the oldest record.
    wren_update_dataset(res, i);
  }
  update_canvas();
  set_timeout();
}

/*
 * it deals with all records in the duratoin.
 * callback function to parse the response at once.
 * update the data set and canvas.
 */
function cb_server_response_at_once(res)
{
  clearTimeout(_wrenEvTimeout);
  if (wrenObj.firstRetrieve == true) {
    wrenObj.firstRetrieve = false;
  }
  res = wren_obj_serialize(res, wrenObj.tzOffset);
  for (var i = 0; i < wrenObj.dataDef.length; i++) {
    wren_update_dataset(res, i);
    fill_dataset(i);
  }
  update_canvas();
  set_timeout();
}

/********
 *
 * callback for events.
 */

function ev_click_start()
{
  clearTimeout(_wrenEvTimeout);
  send_query();
}

function ev_click_stop()
{
  clearTimeout(_wrenEvTimeout);
}

function ev_init()
{
  document.getElementById('btnStop').addEventListener('click', ev_click_stop, false);
  document.getElementById('btnStart').addEventListener('click', ev_click_start, false);
}

$(document).ready(function() {
  for (var i = 0; i < wrenObj.dataDef.length; i++) {
    _wrenDataSet[i] = [];
    /*
     * update the field of the keys in the document if these fields exist.
     */
  }
  wren_init();
  ev_init();
});
<|endoftext|>


<commit_before>// (C) Copyright 2014-2015 Hewlett-Packard Development Company, L.P.

var React = require('react');
var Article = require('grommet/components/Article');
var DocsHeader = require('./DocsHeader');
var Footer = require('grommet/components/Footer');
var Section = require('grommet/components/Section');
var Headline = require('grommet/components/Headline');
var Tiles = require('grommet/components/Tiles');
var Tile = require('grommet/components/Tile');
var Menu = require('grommet/components/Menu');
var Button = require('grommet/components/Button');
var Link = require('react-router').Link;
var GrommetLogo = require('grommet/components/icons/Grommet');

var HomeSection = React.createClass({
  render: function () {
    return (

        {this.props.children}

    );
  }
});

var Home = React.createClass({

  _onClick: function () {
    // no-op
  },

  render: function() {
    return (

        <DocsHeader float={true} />

        <HomeSection texture={'url(img/home_intro.png)'}>
          <GrommetLogo large={true} />
          <Headline large={true}>Grommet</Headline>
          <Headline small={true}>The most advanced open source UX framework for
            enterprise applications.</Headline>
        </HomeSection>

        <HomeSection colorIndex="neutral-1">
          <Headline>Create once and deliver everywhere.</Headline>
          <Headline small={true}>Application experiences that look great while solving problems.</Headline>
          <Menu direction="row" justify="center">
            <Link to="design">
              <Button label="See more examples" onClick={this._onClick} large={true} primary={true} />
            </Link>
            <Link to="develop_getstarted">
              <Button label="Test our demo app" onClick={this._onClick} large={true} />
            </Link>
          </Menu>

        </HomeSection>

        <HomeSection colorIndex="neutral-2" texture={'url(img/home_features.png)'}>
          <Headline>So little gets you sooooooo much!</Headline>
          <Headline small={true}>We’ve tried it all in enterprise and we think we’ve got a good foundation.</Headline>
          <Menu direction="row" justify="center">
            <Link to="develop_architecture">
              <Button label="Our architecture" onClick={this._onClick} large={true} primary={true} />
            </Link>
            <Link to="develop_getstarted">
              <Button label="How to use" onClick={this._onClick} large={true} />
            </Link>
          </Menu>
        </HomeSection>

        <HomeSection texture={'url(img/home_design.png)'}>
          <Headline>Ready for your Design Workflow.</Headline>
          <Headline small={true}>All the resources you could possibly need! Sticker sheets, Stencils,
            PSDs, and more.</Headline>
          <Menu direction="row" justify="center">
            <Link to="design">
              <Button label="Start designing" onClick={this._onClick} large={true} primary={true} />
            </Link>
            <Link to="design_resources">
              <Button label="All resources" onClick={this._onClick} large={true} />
            </Link>
          </Menu>

or, grab your favorite sticker sheet:

          <Tiles small={true} fill={true}>
            <Tile align="center">

              Adobe Illustrator
            </Tile>
            <Tile align="center">

              Adobe Photoshop
            </Tile>
            <Tile align="center">

              Sketch
            </Tile>
            <Tile align="center">

              Axure
            </Tile>
            <Tile align="center">

              Balsamiq
            </Tile>
          </Tiles>
        </HomeSection>

        <HomeSection colorIndex="neutral-3">
          <Headline>Develop your next project with Grommet.</Headline>
          <Headline small={true}>Let’s get an application on your local environment!</Headline>
          <Menu direction="row" justify="center">
            <Link to="develop_getstarted">
              <Button label="Start project" onClick={this._onClick} large={true} primary={true} />
            </Link>
            <Link to="develop_tutorial">
              <Button label="View tutorial" onClick={this._onClick} large={true} />
            </Link>
          </Menu>

or, just copy and paste into terminal:

Hello Grommet!

              The easiest way to learn a new framework is by writing a simple
              application on top of it. Grommet depends
              on Node and Gulp.

              {"$ npm install -g grommet\n$ grommet init sample-app"}

        </HomeSection>

        <HomeSection>
          <Headline>Built with the best stuff.</Headline>
          <Headline small={true}>The tools you know and love, all packaged together in one
            easy-to-use solution.</Headline>
          <Menu direction="row" justify="center">

              <Button label="View project on Github" onClick={this._onClick} large={true} primary={true} />

          </Menu>

or, check out their sites, they have some cool stuff too...

          <Tiles small={true} fill={true}>
            <Tile>

            </Tile>
            <Tile>

            </Tile>
            <Tile>

            </Tile>
            <Tile>

            </Tile>
            <Tile>

            </Tile>
            <Tile>

            </Tile>
            <Tile>

            </Tile>
            <Tile>

            </Tile>
          </Tiles>
        </HomeSection>

        <HomeSection colorIndex="neutral-2">
          <Headline>Let’s keep in touch!</Headline>
          <Headline small={true}>Follow us on the Grommet blog to get the latest updates.</Headline>
          <Menu direction="row" justify="center">
            <Link to="develop_getstarted">
              <Button label="Grommet blog" onClick={this._onClick} large={true} primary={true} />
            </Link>
          </Menu>

We also pop our heads out at these place as well...

          <Tiles fill={true}>
            <Tile>

@grommetux

            </Tile>
            <Tile>

grommet

            </Tile>
            <Tile>

grommetux

            </Tile>
            <Tile>

grommetux

            </Tile>
            <Tile>

grommetux

            </Tile>
          </Tiles>
        </HomeSection>

Build your ideas with Grommet!

            This work is licensed under the Creative Commons Attribution 4.0 International License.

          <Menu label="Theme">
            Grommet
            HPE
            HPInc
          </Menu>

    );
  }

});

module.exports = Home;
<commit_msg>Changed link to Slack to point to Slackin and made it first in list.<commit_after>// (C) Copyright 2014-2015 Hewlett-Packard Development Company, L.P.

var React = require('react');
var Article = require('grommet/components/Article');
var DocsHeader = require('./DocsHeader');
var Footer = require('grommet/components/Footer');
var Section = require('grommet/components/Section');
var Headline = require('grommet/components/Headline');
var Tiles = require('grommet/components/Tiles');
var Tile = require('grommet/components/Tile');
var Menu = require('grommet/components/Menu');
var Button = require('grommet/components/Button');
var Link = require('react-router').Link;
var GrommetLogo = require('grommet/components/icons/Grommet');

var HomeSection = React.createClass({
  render: function () {
    return (

        {this.props.children}

    );
  }
});

var Home = React.createClass({

  _onClick: function () {
    // no-op
  },

  render: function() {
    return (

        <DocsHeader float={true} />

        <HomeSection texture={'url(img/home_intro.png)'}>
          <GrommetLogo large={true} />
          <Headline large={true}>Grommet</Headline>
          <Headline small={true}>The most advanced open source UX framework for
            enterprise applications.</Headline>
        </HomeSection>

        <HomeSection colorIndex="neutral-1">
          <Headline>Create once and deliver everywhere.</Headline>
          <Headline small={true}>Application experiences that look great while solving problems.</Headline>
          <Menu direction="row" justify="center">
            <Link to="design">
              <Button label="See more examples" onClick={this._onClick} large={true} primary={true} />
            </Link>
            <Link to="develop_getstarted">
              <Button label="Test our demo app" onClick={this._onClick} large={true} />
            </Link>
          </Menu>

        </HomeSection>

        <HomeSection colorIndex="neutral-2" texture={'url(img/home_features.png)'}>
          <Headline>So little gets you sooooooo much!</Headline>
          <Headline small={true}>We’ve tried it all in enterprise and we think we’ve got a good foundation.</Headline>
          <Menu direction="row" justify="center">
            <Link to="develop_architecture">
              <Button label="Our architecture" onClick={this._onClick} large={true} primary={true} />
            </Link>
            <Link to="develop_getstarted">
              <Button label="How to use" onClick={this._onClick} large={true} />
            </Link>
          </Menu>
        </HomeSection>

        <HomeSection texture={'url(img/home_design.png)'}>
          <Headline>Ready for your Design Workflow.</Headline>
          <Headline small={true}>All the resources you could possibly need! Sticker sheets, Stencils,
            PSDs, and more.</Headline>
          <Menu direction="row" justify="center">
            <Link to="design">
              <Button label="Start designing" onClick={this._onClick} large={true} primary={true} />
            </Link>
            <Link to="design_resources">
              <Button label="All resources" onClick={this._onClick} large={true} />
            </Link>
          </Menu>

or, grab your favorite sticker sheet:

          <Tiles small={true} fill={true}>
            <Tile align="center">

              Adobe Illustrator
            </Tile>
            <Tile align="center">

              Adobe Photoshop
            </Tile>
            <Tile align="center">

              Sketch
            </Tile>
            <Tile align="center">

              Axure
            </Tile>
            <Tile align="center">

              Balsamiq
            </Tile>
          </Tiles>
        </HomeSection>

        <HomeSection colorIndex="neutral-3">
          <Headline>Develop your next project with Grommet.</Headline>
          <Headline small={true}>Let’s get an application on your local environment!</Headline>
          <Menu direction="row" justify="center">
            <Link to="develop_getstarted">
              <Button label="Start project" onClick={this._onClick} large={true} primary={true} />
            </Link>
            <Link to="develop_tutorial">
              <Button label="View tutorial" onClick={this._onClick} large={true} />
            </Link>
          </Menu>

or, just copy and paste into terminal:

Hello Grommet!

              The easiest way to learn a new framework is by writing a simple
              application on top of it. Grommet depends
              on Node and Gulp.

              {"$ npm install -g grommet\n$ grommet init sample-app"}

        </HomeSection>

        <HomeSection>
          <Headline>Built with the best stuff.</Headline>
          <Headline small={true}>The tools you know and love, all packaged together in one
            easy-to-use solution.</Headline>
          <Menu direction="row" justify="center">

              <Button label="View project on Github" onClick={this._onClick} large={true} primary={true} />

          </Menu>

or, check out their sites, they have some cool stuff too...

          <Tiles small={true} fill={true}>
            <Tile>

            </Tile>
            <Tile>

            </Tile>
            <Tile>

            </Tile>
            <Tile>

            </Tile>
            <Tile>

            </Tile>
            <Tile>

            </Tile>
            <Tile>

            </Tile>
            <Tile>

            </Tile>
          </Tiles>
        </HomeSection>

        <HomeSection colorIndex="neutral-2">
          <Headline>Let’s keep in touch!</Headline>
          <Headline small={true}>Follow us on the Grommet blog to get the latest updates.</Headline>
          <Menu direction="row" justify="center">
            <Link to="develop_getstarted">
              <Button label="Grommet blog" onClick={this._onClick} large={true} primary={true} />
            </Link>
          </Menu>

We also pop our heads out at these place as well...

          <Tiles fill={true}>
            <Tile>

grommet

            </Tile>
            <Tile>

@grommetux

            </Tile>
            <Tile>

grommetux

            </Tile>
            <Tile>

grommetux

            </Tile>
            <Tile>

grommetux

            </Tile>
          </Tiles>
        </HomeSection>

Build your ideas with Grommet!

            This work is licensed under the Creative Commons Attribution 4.0 International License.

          <Menu label="Theme">
            Grommet
            HPE
            HPInc
          </Menu>

    );
  }

});

module.exports = Home;
<|endoftext|>


<commit_before>fullscreen = function() {
	screenfull.toggle();
}

Polymer('character-card', {
	response: "",
	character: {
		"Might":"",
		"Speed":"",
		"Knowledge":"",
		"Sanity":"",
		"MightIndex":"",
		"SpeedIndex":"",
		"KnowledgeIndex":"",
		"SanityIndex":""
	},

	getStats: function() {
		stats = {
			"array":"",
			"index":"",
			"element":""
		}

		switch(attribute) {
			case "might":
				stats.array = this.character.Might;
				stats.index = this.character.MightIndex;
				stats.element = document.querySelector("character-card::shadow #might-score").innerHTML;
				break;
			case "speed":
				stats.array = this.character.Speed;
				stats.index = this.character.SpeedIndex;
				stats.element = document.querySelector("character-card::shadow #speed-score").innerHTML;
				break;
			case "knowledge":
				stats.array = this.character.Knowledge;
				stats.element = document.querySelector("character-card::shadow #knowledge-score").innerHTML;
				stats.index = this.character.KnowledgeIndex;
				break;
			case "sanity":
				stats.array = this.character.Sanity;
				stats.index = this.character.SanityIndex;
				stats.element = document.querySelector("character-card::shadow #sanity-score").innerHTML;
				break;
		}

		// alert(this.stats.index);
		return stats;
	},

	increaseScore: function(attribute) {
		console.log("increase");
		stats = this.getStats(attribute);
		console.log(stats.index);
		if(stats.index < 8) {
			stats.element = stats.array[++stats.index];
			console.log(stats.array[stats.index]);
		}
	},

	decreaseScore: function(attribute) {
		console.log("decrease");
		stats = this.getStats(attribute);

		if(--stats.index) {
			stats.element = stats.array[stats.index];
		}
		else {
			alert("You've died.");
		}
	},

	setHeader: function(character) {
		switch(character) {
			case "ox-bellows":
			case "darrin-flash-williams":
				color = "#F44336";
				break;
			case "father-rhinehardt":
			case "professor-longfellow":
				color = "#9E9E9E";
				break;
			case "vivian-lopez":
			case "madame-zostra":
				color = "#3F51B5";
				break;
			case "peter-akimoto":
			case "brandon-jaspers":
				color = "#8BC34A";
				break;
			case "missy-dobourde":
			case "zoe-ingstrom":
				color = "#FFC107";
				break;
			case "jenny-leclerc":
			case "heather-granville":
				color = "#9C27B0";
				break;
			default:
				color = "#000000";
		}

		document.querySelector("character-card::shadow #character-name").style.backgroundColor = color;
	},

	setCardValues: function(character) {
		characters = [
				"ox-bellows",
				"father-rhinehardt",
				"vivian-lopez",
				"peter-akimoto",
				"missy-dobourde",
				"jenny-leclerc",
				"darrin-flash-williams",
				"professor-longfellow",
				"madame-zostra",
				"brandon-jaspers",
				"zoe-ingstrom",
				"heather-granville"
		]

		selection = this.response.Characters[characters.indexOf(character)];

		document.querySelector("character-card::shadow #character-name").innerHTML = selection.Name;
		document.querySelector("character-card::shadow #age").innerHTML = selection.Age;
		document.querySelector("character-card::shadow #height").innerHTML = selection.Height;
		document.querySelector("character-card::shadow #weight").innerHTML = selection.Weight;
		document.querySelector("character-card::shadow #birthday").innerHTML = selection.Birthday;
		document.querySelector("character-card::shadow #hobbies").innerHTML = selection.Hobbies;
		document.querySelector("character-card::shadow #might-score").innerHTML = selection.Might[selection.BaseMightIndex];
		document.querySelector("character-card::shadow #speed-score").innerHTML = selection.Speed[selection.BaseSpeedIndex];
		document.querySelector("character-card::shadow #knowledge-score").innerHTML = selection.Knowledge[selection.BaseKnowledgeIndex];
		document.querySelector("character-card::shadow #sanity-score").innerHTML = selection.Sanity[selection.BaseSanityIndex];

		this.character.Might = selection.Might;
		this.character.Speed = selection.Speed;
		this.character.Knowledge = selection.Knowledge;
		this.character.Sanity = selection.Sanity;
		this.character.MightIndex = selection.BaseMightIndex
		this.character.SpeedIndex = selection.BaseSpeedIndex
		this.character.KnowledgeIndex = selection.BaseKnowledgeIndex
		this.character.SanityIndex = selection.BaseSanityIndex
	},

	getCharacter: function(character) {
		self = this;

		this.setHeader(character);

		request = new XMLHttpRequest();
		request.open("GET", "/polymer-character-card/elements/character-card/characters.json", true);

		response = "";
		request.onreadystatechange = function() {
			if(request.readyState === request.DONE) {
				status = request.status;

				if((status >= 200 && status < 300) || status === 304 || status === 0) {
					self.response = JSON.parse(request.responseText);
					self.setCardValues(character);
				}
			}
		};
		request.send();
	},

	attached: function() {
		self = this;

		document.querySelector("character-card::shadow .up").addEventListener("click", function(event) {
			attribute = event.target.attributes['name'].value;
			self.increaseScore(attribute);
		});

		document.querySelector("character-card::shadow .down").addEventListener("click", function(event) {
			attribute = event.target.attributes['name'].value;
			self.decreaseScore(attribute);
		});

		this.getCharacter("darrin-flash-williams");
	},
});<commit_msg>Fixed JSON functionality<commit_after>fullscreen = function() {
	screenfull.toggle();
}

Polymer('character-card', {
	response: "",
	character: {
		"Might":"",
		"Speed":"",
		"Knowledge":"",
		"Sanity":"",
		"MightIndex":"",
		"SpeedIndex":"",
		"KnowledgeIndex":"",
		"SanityIndex":""
	},

	getStats: function() {
		stats = {
			"array":"",
			"index":"",
			"element":""
		}

		switch(attribute) {
			case "might":
				stats.array = this.character.Might;
				stats.index = this.character.MightIndex;
				stats.element = document.querySelector("character-card::shadow #might-score").innerHTML;
				break;
			case "speed":
				stats.array = this.character.Speed;
				stats.index = this.character.SpeedIndex;
				stats.element = document.querySelector("character-card::shadow #speed-score").innerHTML;
				break;
			case "knowledge":
				stats.array = this.character.Knowledge;
				stats.element = document.querySelector("character-card::shadow #knowledge-score").innerHTML;
				stats.index = this.character.KnowledgeIndex;
				break;
			case "sanity":
				stats.array = this.character.Sanity;
				stats.index = this.character.SanityIndex;
				stats.element = document.querySelector("character-card::shadow #sanity-score").innerHTML;
				break;
		}

		// alert(this.stats.index);
		return stats;
	},

	increaseScore: function(attribute) {
		console.log("increase");
		stats = this.getStats(attribute);
		console.log(stats.index);
		if(stats.index < 8) {
			stats.element = stats.array[++stats.index];
			console.log(stats.array[stats.index]);
		}
	},

	decreaseScore: function(attribute) {
		console.log("decrease");
		stats = this.getStats(attribute);

		if(--stats.index) {
			stats.element = stats.array[stats.index];
		}
		else {
			alert("You've died.");
		}
	},

	setHeader: function(character) {
		switch(character) {
			case "ox-bellows":
			case "darrin-flash-williams":
				color = "#F44336";
				break;
			case "father-rhinehardt":
			case "professor-longfellow":
				color = "#9E9E9E";
				break;
			case "vivian-lopez":
			case "madame-zostra":
				color = "#3F51B5";
				break;
			case "peter-akimoto":
			case "brandon-jaspers":
				color = "#8BC34A";
				break;
			case "missy-dobourde":
			case "zoe-ingstrom":
				color = "#FFC107";
				break;
			case "jenny-leclerc":
			case "heather-granville":
				color = "#9C27B0";
				break;
			default:
				color = "#000000";
		}

		document.querySelector("character-card::shadow #character-name").style.backgroundColor = color;
	},

	setCardValues: function(character) {
		characters = [
				"ox-bellows",
				"father-rhinehardt",
				"vivian-lopez",
				"peter-akimoto",
				"missy-dobourde",
				"jenny-leclerc",
				"darrin-flash-williams",
				"professor-longfellow",
				"madame-zostra",
				"brandon-jaspers",
				"zoe-ingstrom",
				"heather-granville"
		]

		selection = this.response.Characters[characters.indexOf(character)];

		document.querySelector("character-card::shadow #character-name").innerHTML = selection.Name;
		document.querySelector("character-card::shadow #age").innerHTML = selection.Age;
		document.querySelector("character-card::shadow #height").innerHTML = selection.Height;
		document.querySelector("character-card::shadow #weight").innerHTML = selection.Weight;
		document.querySelector("character-card::shadow #birthday").innerHTML = selection.Birthday;
		document.querySelector("character-card::shadow #hobbies").innerHTML = selection.Hobbies;
		document.querySelector("character-card::shadow #might-score").innerHTML = selection.Might[selection.BaseMightIndex];
		document.querySelector("character-card::shadow #speed-score").innerHTML = selection.Speed[selection.BaseSpeedIndex];
		document.querySelector("character-card::shadow #knowledge-score").innerHTML = selection.Knowledge[selection.BaseKnowledgeIndex];
		document.querySelector("character-card::shadow #sanity-score").innerHTML = selection.Sanity[selection.BaseSanityIndex];

		this.character.Might = selection.Might;
		this.character.Speed = selection.Speed;
		this.character.Knowledge = selection.Knowledge;
		this.character.Sanity = selection.Sanity;
		this.character.MightIndex = selection.BaseMightIndex
		this.character.SpeedIndex = selection.BaseSpeedIndex
		this.character.KnowledgeIndex = selection.BaseKnowledgeIndex
		this.character.SanityIndex = selection.BaseSanityIndex
	},

	getCharacter: function(character) {
		self = this;

		this.setHeader(character);

		request = new XMLHttpRequest();
		request.open("GET", "/polymer-character-card/elements/character-card/characters.json", true);

		response = "";
		request.onreadystatechange = function() {
			if(request.readyState === request.DONE) {
				status = request.status;

				if((status >= 200 && status < 300) || status === 304 || status === 0) {
					self.response = JSON.parse(request.responseText);
					self.setCardValues(character);
				}
			}
		};
		request.send();
	},

	attached: function() {
		self = this;

		document.querySelector("character-card::shadow .up").addEventListener("click", function(event) {
			attribute = event.target.attributes['name'].value;
			self.increaseScore(attribute);
		});

		document.querySelector("character-card::shadow .down").addEventListener("click", function(event) {
			attribute = event.target.attributes['name'].value;
			self.decreaseScore(attribute);
		});

		this.getCharacter("darrin-flash-williams");
	},
});
<|endoftext|>


<commit_before>/* Extends the Utils class */
var Utils = Utils || {};

Utils.websiteUrl = "https://wwwdev.fieldlinguist.com:3182";
Utils.authUrl = "https://authdev.fieldlinguist.com:3183";
Utils.audioUrl = "https://audiodev.fieldlinguist.com:3184";
Utils.lexiconUrl = "https://lexicondev.fieldlinguist.com:3185";
Utils.corpusUrl = "https://corpusdev.fieldlinguist.com:3186";
Utils.activityUrl = "https://activitydev.fieldlinguist.com:3187";
Utils.widgetUrl = "https://widgetdev.fieldlinguist.com:3188";

/*
 * Use the current app's chrome url, assuming if its a dev, they will have their
 * own url that is not from the market, and if its a bleeding edge user, they
 * will have the market one. In both cases it is save to return the
 * window.location.href but this code is added to be clear that there is also a
 * bleeding edge url for users.
 */
Utils.chromeClientUrl = function(){
  if (window.location.origin != "chrome-extension://eeipnabdeimobhlkfaiohienhibfcfpa"){
    return window.location.origin;
  }else{
    return "chrome-extension://eeipnabdeimobhlkfaiohienhibfcfpa";
  }
};

Utils.defaultCouchConnection = function() {
  return {
    protocol : "https://",
    domain : "ifielddevs.iriscouch.com",
    port : "6984",
    pouchname : "default",
    path : ""
  };
};
<commit_msg>taking the port off the iriscouch, realized we were doing it server side<commit_after>/* Extends the Utils class */
var Utils = Utils || {};

Utils.websiteUrl = "https://wwwdev.fieldlinguist.com:3182";
Utils.authUrl = "https://authdev.fieldlinguist.com:3183";
Utils.audioUrl = "https://audiodev.fieldlinguist.com:3184";
Utils.lexiconUrl = "https://lexicondev.fieldlinguist.com:3185";
Utils.corpusUrl = "https://corpusdev.fieldlinguist.com:3186";
Utils.activityUrl = "https://activitydev.fieldlinguist.com:3187";
Utils.widgetUrl = "https://widgetdev.fieldlinguist.com:3188";

/*
 * Use the current app's chrome url, assuming if its a dev, they will have their
 * own url that is not from the market, and if its a bleeding edge user, they
 * will have the market one. In both cases it is save to return the
 * window.location.href but this code is added to be clear that there is also a
 * bleeding edge url for users.
 */
Utils.chromeClientUrl = function(){
  if (window.location.origin != "chrome-extension://eeipnabdeimobhlkfaiohienhibfcfpa"){
    return window.location.origin;
  }else{
    return "chrome-extension://eeipnabdeimobhlkfaiohienhibfcfpa";
  }
};

Utils.defaultCouchConnection = function() {
  return {
    protocol : "https://",
    domain : "ifielddevs.iriscouch.com",
    port : "443",
    pouchname : "default",
    path : ""
  };
};
<|endoftext|>


<commit_before>/* su-endless-scroll - v1.0.0 - 2015-08-20 */

var mod = angular.module('suEndlessScroll', []);

mod.directive('suEndlessScroll', ['$window',
  function($window) {
  	return {
      restrict: 'A',
      scope: {
        suEndlessScroll: '&',
        suEndlessScrollOffset: '@offset',
        suEndlessScrollAutoCheck: '@autoCheck'
      },
      link: function(scope, element, attrs) {
        var elementHeight, currentScrollHeight, triggerPoint;
        var _element = angular.element(element);
        var _window = angular.element($window);
        var currentScrollHeight = _element.scrollHeight;
        var eventFired = false;
        var defaultOffset = 30;
        var offset = (!scope.offset)? defaultOffset : scope.offset;
        var autoCheckInterval = 1000;
        var autoCheck = (!scope.autoCheck)? true : scope.autoCheck;

        function setHeightRelatedVariables() {
          elementHeight = element.outerHeight();
          triggerPoint = (parseInt(elementHeight) + parseInt(offset));
          currentScrollHeight = _element.scrollHeight;
        }

        function testConditions(eventElement) {
          var scrollPosition = (eventElement.scrollHeight - eventElement.scrollTop);

          if(currentScrollHeight !== eventElement.scrollHeight) {
            currentScrollHeight = eventElement.scrollHeight;
            eventFired = false;
          }

          if(scrollPosition <= triggerPoint && !eventFired) {
            scope.suEndlessScroll();
            eventFired = true;
          }
        }

        function initAutoCheck() {
          if(autoCheck) {
            setInterval(function() {
              console.log();
              testConditions(_element);
            }, autoCheckInterval);
          }
        }

        function init() {
          setHeightRelatedVariables();
          initAutoCheck();

          _element.bind('scroll', function() {
            testConditions(this);
          });

          _window.bind('resize', function() {
            setHeightRelatedVariables();
            testConditions(_element);
          });
        }

        init();
      }
  	};
  }
]);
<commit_msg>Integrating more functionality into the directive<commit_after>/* su-endless-scroll - v1.0.0 - 2015-08-20 */
var mod = angular.module('suEndlessScroll', []);

mod.directive('suEndlessScroll', ['$window',
  function($window) {
  	return {
      restrict: 'A',
      scope: {
        suEndlessScroll: '=',
        suEndlessScrollOutput: '=',
        suEndlessScrollOffset: '=',
        suEndlessScrollLimit: '=',
        suEndlessScrollAutoCheck: '='
      },
      link: function(scope, element, attrs) {
        var elementHeight, currentScrollHeight, triggerPoint;
        var currentScrollHeight = angular.element(element).scrollHeight;
        var eventFired = false;
        var offset = (scope.suEndlessScrollOffset === undefined)? 30 : parseInt(scope.suEndlessScrollOffset);
        var autoCheckInterval = 1000;
        var autoCheck = (!scope.suEndlessScrollAutoCheck)? true : scope.suEndlessScrollAutoCheck;
        var displayLimit = (scope.suEndlessScrollLimit === undefined || parseInt(scope.suEndlessScrollLimit) < 1)? 20 : parseInt(scope.suEndlessScrollLimit);

        function setHeightRelatedVariables() {
          elementHeight = element.outerHeight();
          triggerPoint = (parseInt(elementHeight) + parseInt(offset));
          currentScrollHeight = angular.element(element).scrollHeight;
        }

        function testConditions(eventElement) {
          var scrollPosition = (eventElement.scrollHeight - eventElement.scrollTop);

          if(currentScrollHeight !== eventElement.scrollHeight) {
            currentScrollHeight = eventElement.scrollHeight;
            eventFired = false;
          }

          if(scrollPosition <= triggerPoint && !eventFired) {
            processData();
            eventFired = true;
          }
        }

        function processData(clear) {
          if(clear) {
            scope.suEndlessScrollOutput = [];
            angular.element(element)[0].scrollTop = 0;
          }

          if(!scope.suEndlessScroll || !scope.suEndlessScroll[scope.suEndlessScrollOutput.length]) {
            return;
          }

          var _scrollItemsCount = scope.suEndlessScrollOutput.length;

          for(var x = 0; x < displayLimit; x++) {
            var nextIndex = ((_scrollItemsCount)+x);

            if(scope.suEndlessScroll[nextIndex]) {
              scope.suEndlessScrollOutput.push(scope.suEndlessScroll[nextIndex]);
            }
          }

          if(!scope.$parent.$$phase){
            scope.$parent.$digest();
          }
        }

        function initAutoCheck() {
          if(autoCheck) {
            setInterval(function() {
              testConditions(angular.element(element));
            }, autoCheckInterval);
          }
        }

        function init() {
          setHeightRelatedVariables();
          initAutoCheck();

          angular.element(element).bind('scroll', function() {
            testConditions(this);
          });

          angular.element($window).bind('resize', function() {
            setHeightRelatedVariables();
            testConditions(angular.element(element));
          });

          scope.$watch('suEndlessScroll', function(newData, oldData) {
            if(newData) {
              processData(true);
            }
          }, true);
        }

        init();
      }
  	};
  }
]);
<|endoftext|>