<commit_before>"use strict";

var AnimationTimer = function(terrain) {
  var FRAMES_PER_SECONDS = 60;
  var MILLISECONDS_PER_TICK = 1000.0 / FRAMES_PER_SECONDS;

  var masterStartTime;
  var previousTickStartTime;
  var totalTicks = 0;

  var animator = new Animator(terrain);

  var tick = function(timestamp) {
    var tickStartTime = performance.now();

    if (!masterStartTime) {
      masterStartTime = tickStartTime;
    }

    var ticksToProcess = 1;
    var expectedFramesSoFar = Math.floor((tickStartTime - masterStartTime) / MILLISECONDS_PER_TICK);
    if (expectedFramesSoFar > totalTicks) {
      ticksToProcess += (expectedFramesSoFar - totalTicks);
    }

    for (var i = 0; i < ticksToProcess; i++) {
      animator.tick();
      totalTicks += 1;
    }

    renderer.render(scene, camera);

    previousTickStartTime = tickStartTime;

    requestAnimFrame(tick);
  };

  var animationTimer = {};

  animationTimer.start = function() {
    requestAnimFrame(tick);
  };

  return animationTimer;
};

var Animator = function(terrain) {
  var animator = {};

  var xPositionGenerator = new MotionGenerator();
  var zPositionGenerator = new LinearMotionGenerator(2, CityConfig.HALF_SCENE_DEPTH);

  animator.tick = function() {
    camera.position.x += xPositionGenerator.nextValue();
    camera.position.z += -zPositionGenerator.nextValue();

    var mapX = Coordinates.sceneXToMapX(camera.position.x);
    var mapZ = Coordinates.sceneZToMapZ(camera.position.z);

    var y = terrain.heightAtCoordinates(mapX, mapZ);
    camera.position.y = y + 0.5;
  };

  return animator;
};

var MotionGenerator = function() {
  var motionGenerator = {};

  motionGenerator.nextValue = function() {
    return 0.0;
  };

  motionGenerator.isComplete = function() {
    return false;
  };

  motionGenerator.onComplete = function() { };

  return motionGenerator;
};

var LinearMotionGenerator = function(delta, target) {
  var accumulator = 0.0;
  var isComplete = false;

  var linearMotionGenerator = new MotionGenerator();

  linearMotionGenerator.nextValue = function() {
    if (isComplete) {
      return 0.0;
    }

    accumulator += delta;

    if (accumulator <= target) {
      return delta;
    }
    else {
      isComplete = true;
      return (delta - (accumulator - target));
    }
  };

  linearMotionGenerator.isComplete = function() {
    return isComplete;
  };

  linearMotionGenerator.onComplete = function() { };

  return linearMotionGenerator;
};

var AnimationManager = function() {
  var TARGET_FRAME_WINDOW = 1000 / 60;   // 60 frames per second
  var FOWARD_MOTION_DELTA = 0.2;

  var animationManager = {};
  var animators = [];
  var previousFrameTimestamp;

  var deltaX;
  var deltaZ;
  var targetX;
  var targetGridX;
  var targetZ;
  var targetGridZ;
  var targetAngle = 0;
  var deltaAngle;

  var init = function() {
    var START_X = 0;
    var START_Y = 40;
    var START_Z = CityConfig.HALF_SCENE_DEPTH;

    camera.position.x = START_X;
    camera.position.y = START_Y;
    camera.position.z = START_Z;

    targetX = 0;
    targetZ = 0;
    deltaX = 0.0;
    deltaZ = -FOWARD_MOTION_DELTA;

    var distanceToCityEdge = Math.abs(START_Z - ((CityConfig.BLOCK_ROWS * CityConfig.BLOCK_AND_STREET_DEPTH) / 2));
    var framesUntilCityEdge = Math.abs(distanceToCityEdge / deltaZ);
    var terrainHeightAtTouchdown = terrain.heightAtCoordinates(0.0, CityConfig.HALF_BLOCK_ROWS) + 0.5;
    var swoopDescentDelta = (START_Y - terrainHeightAtTouchdown) / framesUntilCityEdge;

    var ramp = new rampAnimation(framesUntilCityEdge, -swoopDescentDelta, terrainHeightAtTouchdown + 0.5, 1000000);
    var forward = new forwardAnimation(targetX, deltaX, targetZ, deltaZ);
    animators = [ramp, forward];
  };

  var determineNextTargetPoint = function() {
    if (targetGridX == undefined || targetGridZ == undefined) {
      targetGridX = 0;
      targetGridZ = -1;
    }
    else {
      var oldTargetGridX = targetGridX;
      var oldTargetGridZ = targetGridZ;

      while (oldTargetGridX == targetGridX && oldTargetGridZ == targetGridZ) {
        if (deltaX == 0) {
          targetGridX = Math.floor(Math.random() * CityConfig.BLOCK_ROWS) - CityConfig.HALF_BLOCK_ROWS;
        }
        else if (deltaZ == 0) {
          targetGridZ = Math.floor(Math.random() * CityConfig.BLOCK_COLUMNS) - CityConfig.HALF_BLOCK_COLUMNS;
        }
      }
    }

    targetX = Coordinates.mapXToSceneX(targetGridX);
    targetZ = Coordinates.mapZToSceneZ(targetGridZ);

    deltaX = (camera.position.x == targetX) ? 0 : FOWARD_MOTION_DELTA;
    deltaZ = (camera.position.z == targetZ) ? 0 : FOWARD_MOTION_DELTA;
    deltaX *= (camera.position.x > targetX) ? -1 : 1;
    deltaZ *= (camera.position.z > targetZ) ? -1 : 1;
  };

  var determineRotationAngle = function() {
    var RIGHT_ANGLE = Math.PI / 2;
    var ROTATION_DELTA = 0.03;

    var oldTargetAngle = targetAngle;
    if (deltaX != 0 && oldTargetAngle == 0) {  // NORTH
      targetAngle = (deltaX < 0) ? targetAngle + RIGHT_ANGLE : targetAngle - RIGHT_ANGLE;
    }
    else if (deltaZ != 0 && (oldTargetAngle == RIGHT_ANGLE || oldTargetAngle == ((-3 * Math.PI) / 2))) {  // EAST
      targetAngle = (deltaZ < 0) ? targetAngle - RIGHT_ANGLE : targetAngle + RIGHT_ANGLE;
    }
    else if (deltaX != 0 && (oldTargetAngle == Math.PI || oldTargetAngle == Math.PI * -1)) {  // SOUTH
      targetAngle = (deltaX < 0) ? targetAngle - RIGHT_ANGLE : targetAngle + RIGHT_ANGLE;
    }
    else if (deltaZ != 0 && (oldTargetAngle == Math.PI / -2 || oldTargetAngle == (Math.PI * 3) / 2)) {  // WEST
      targetAngle = (deltaZ < 0) ? targetAngle + RIGHT_ANGLE : targetAngle - RIGHT_ANGLE;
    }

    deltaAngle = ROTATION_DELTA;
    deltaAngle *= (targetAngle > oldTargetAngle) ? 1 : -1;
  };

  animationManager.animate = function() {
    var currentTimestamp = new Date().getTime();
    var frameCount;

    if (animators.length === 0) {
      init();
    }

    if (previousFrameTimestamp === undefined) {
      frameCount = 1;
    }
    else {
      frameCount = Math.floor((currentTimestamp - previousFrameTimestamp) / TARGET_FRAME_WINDOW);
      if (frameCount < 1) {
        frameCount = 1;
      }
    }
    previousFrameTimestamp = currentTimestamp;

    var newAnimators = [];
    animators.forEach(function (animator) {
      animator.animate(frameCount);

      if (animator.finished === true) {
        if (animator instanceof rampAnimation) {
          newAnimators.push(new hoverAnimation());
        }
        else if (animator instanceof forwardAnimation) {
          determineNextTargetPoint();
          determineRotationAngle();
          newAnimators.push(new rotationAnimation(targetAngle, deltaAngle));
        }
        else if (animator instanceof rotationAnimation) {
          newAnimators.push(new forwardAnimation(targetX, deltaX, targetZ, deltaZ));
        }
        else if (animator instanceof hoverAnimation) {
          newAnimators.push(new hoverAnimation());
        }
      }
      else {
        newAnimators.push(animator);
      }
    });
    animators = newAnimators;

    var mapX = Coordinates.sceneXToMapX(camera.position.x);
    var mapZ = Coordinates.sceneZToMapZ(camera.position.z);

    var y = terrain.heightAtCoordinates(mapX, mapZ);
    camera.position.y = Math.max(camera.position.y, y + 0.5);

    renderer.render(scene, camera);
    requestAnimFrame(animationManager.animate);
  };

  return animationManager;
};

function forwardAnimation(targetX, deltaX, targetZ, deltaZ) {
  this.targetX = targetX;
  this.deltaX = deltaX;
  this.targetZ = targetZ;
  this.deltaZ = deltaZ;
  this.finished = false;
}

forwardAnimation.prototype.animate = function(frameCount) {
  camera.position.x += this.deltaX * frameCount;
  camera.position.z += this.deltaZ * frameCount;

  if ((this.deltaX < 0 && camera.position.x < this.targetX) || (this.deltaX > 0 && camera.position.x > this.targetX) ||
      (this.deltaZ < 0 && camera.position.z < this.targetZ) || (this.deltaZ > 0 && camera.position.z > this.targetZ)) {
    camera.position.x = this.targetX;
    camera.position.z = this.targetZ;

    this.finished = true;
  }
}

function rotationAnimation(targetAngle, deltaAngle) {
  this.targetAngle = targetAngle;
  this.deltaAngle = deltaAngle;
  this.finished = false;
}

rotationAnimation.prototype.animate = function(frameCount) {
  camera.rotation.y += this.deltaAngle * frameCount;

  if ((this.deltaAngle < 0 && camera.rotation.y <= this.targetAngle) || (this.deltaAngle > 0 && camera.rotation.y >= this.targetAngle)) {
    if (this.targetAngle >= Math.PI * 2 || this.targetAngle <= Math.PI * -2) {
      this.targetAngle = 0;
    }

    camera.rotation.y = this.targetAngle;
    this.finished = true;
  }
}

function rampAnimation(frameDistance, deltaY, minHeight, maxHeight) {
  this.ticks = 0;
  this.frameDistance = frameDistance;
  this.deltaY = deltaY;
  this.minHeight = minHeight;
  this.maxHeight = maxHeight;
  this.finished = false;
}

rampAnimation.prototype.animate = function(frameCount) {
  if (camera.position.y >= this.minHeight && camera.position.y <= this.maxHeight) {
    camera.position.y += this.deltaY * frameCount;
  }
  if (camera.position.y < this.minHeight) {
    camera.position.y = this.minHeight;
  }
  if (camera.position.y > this.maxHeight) {
    camera.position.y = this.maxHeight;
  }

  this.ticks += frameCount;
  if (this.ticks > this.frameDistance) {
    this.finished = true;
  }
}

function hoverAnimation() {
  var frameDistance = (Math.random() * 300) + 300;
  var deltaY = (camera.position.y > 0.5) ? -0.05 : 0.05;

  this.rampAnimation = new rampAnimation(frameDistance, deltaY, 0.5, 15);
  this.finished = false;
}

hoverAnimation.prototype.animate = function(frameCount) {
  this.rampAnimation.animate(frameCount);
  this.finished = this.rampAnimation.finished;
}
<commit_msg>Using consistent terminology<commit_after>"use strict";

var AnimationTimer = function(terrain) {
  var FRAMES_PER_SECONDS = 60;
  var MILLISECONDS_PER_TICK = 1000.0 / FRAMES_PER_SECONDS;

  var masterStartTime;
  var previousTickStartTime;
  var totalTicks = 0;

  var animator = new Animator(terrain);

  var tick = function(timestamp) {
    var tickStartTime = performance.now();

    if (!masterStartTime) {
      masterStartTime = tickStartTime;
    }

    var ticksToProcess = 1;
    var expectedFramesSoFar = Math.floor((tickStartTime - masterStartTime) / MILLISECONDS_PER_TICK);
    if (expectedFramesSoFar > totalTicks) {
      ticksToProcess += (expectedFramesSoFar - totalTicks);
    }

    for (var i = 0; i < ticksToProcess; i++) {
      animator.tick();
      totalTicks += 1;
    }

    renderer.render(scene, camera);

    previousTickStartTime = tickStartTime;

    requestAnimFrame(tick);
  };

  var animationTimer = {};

  animationTimer.start = function() {
    requestAnimFrame(tick);
  };

  return animationTimer;
};

var Animator = function(terrain) {
  var animator = {};

  var xPositionGenerator = new MotionGenerator();
  var zPositionGenerator = new LinearMotionGenerator(2, CityConfig.HALF_SCENE_DEPTH);

  animator.tick = function() {
    camera.position.x += xPositionGenerator.nextValue();
    camera.position.z += -zPositionGenerator.nextValue();

    var mapX = Coordinates.sceneXToMapX(camera.position.x);
    var mapZ = Coordinates.sceneZToMapZ(camera.position.z);

    var y = terrain.heightAtCoordinates(mapX, mapZ);
    camera.position.y = y + 0.5;
  };

  return animator;
};

var MotionGenerator = function() {
  var motionGenerator = {};

  motionGenerator.nextValue = function() {
    return 0.0;
  };

  motionGenerator.isComplete = function() {
    return false;
  };

  motionGenerator.onComplete = function() { };

  return motionGenerator;
};

var LinearMotionGenerator = function(delta, target) {
  var accumulator = 0.0;
  var isComplete = false;

  var linearMotionGenerator = new MotionGenerator();

  linearMotionGenerator.nextValue = function() {
    if (isComplete) {
      return 0.0;
    }

    accumulator += delta;

    if (accumulator <= target) {
      return delta;
    }
    else {
      isComplete = true;
      return (delta - (accumulator - target));
    }
  };

  linearMotionGenerator.isComplete = function() {
    return isComplete;
  };

  linearMotionGenerator.onComplete = function() { };

  return linearMotionGenerator;
};

var AnimationManager = function() {
  var TARGET_FRAME_WINDOW = 1000 / 60;   // 60 frames per second
  var FOWARD_MOTION_DELTA = 0.2;

  var animationManager = {};
  var animators = [];
  var previousFrameTimestamp;

  var deltaX;
  var deltaZ;
  var targetX;
  var targetMapX;
  var targetZ;
  var targetMapZ;
  var targetAngle = 0;
  var deltaAngle;

  var init = function() {
    var START_X = 0;
    var START_Y = 40;
    var START_Z = CityConfig.HALF_SCENE_DEPTH;

    camera.position.x = START_X;
    camera.position.y = START_Y;
    camera.position.z = START_Z;

    targetX = 0;
    targetZ = 0;
    deltaX = 0.0;
    deltaZ = -FOWARD_MOTION_DELTA;

    var distanceToCityEdge = Math.abs(START_Z - ((CityConfig.BLOCK_ROWS * CityConfig.BLOCK_AND_STREET_DEPTH) / 2));
    var framesUntilCityEdge = Math.abs(distanceToCityEdge / deltaZ);
    var terrainHeightAtTouchdown = terrain.heightAtCoordinates(0.0, CityConfig.HALF_BLOCK_ROWS) + 0.5;
    var swoopDescentDelta = (START_Y - terrainHeightAtTouchdown) / framesUntilCityEdge;

    var ramp = new rampAnimation(framesUntilCityEdge, -swoopDescentDelta, terrainHeightAtTouchdown + 0.5, 1000000);
    var forward = new forwardAnimation(targetX, deltaX, targetZ, deltaZ);
    animators = [ramp, forward];
  };

  var determineNextTargetPoint = function() {
    if (targetMapX == undefined || targetMapZ == undefined) {
      targetMapX = 0;
      targetMapZ = -1;
    }
    else {
      var oldTargetMapX = targetMapX;
      var oldTargetMapZ = targetMapZ;

      while (oldTargetMapX == targetMapX && oldTargetMapZ == targetMapZ) {
        if (deltaX == 0) {
          targetMapX = Math.floor(Math.random() * CityConfig.BLOCK_ROWS) - CityConfig.HALF_BLOCK_ROWS;
        }
        else if (deltaZ == 0) {
          targetMapZ = Math.floor(Math.random() * CityConfig.BLOCK_COLUMNS) - CityConfig.HALF_BLOCK_COLUMNS;
        }
      }
    }

    targetX = Coordinates.mapXToSceneX(targetMapX);
    targetZ = Coordinates.mapZToSceneZ(targetMapZ);

    deltaX = (camera.position.x == targetX) ? 0 : FOWARD_MOTION_DELTA;
    deltaZ = (camera.position.z == targetZ) ? 0 : FOWARD_MOTION_DELTA;
    deltaX *= (camera.position.x > targetX) ? -1 : 1;
    deltaZ *= (camera.position.z > targetZ) ? -1 : 1;
  };

  var determineRotationAngle = function() {
    var RIGHT_ANGLE = Math.PI / 2;
    var ROTATION_DELTA = 0.03;

    var oldTargetAngle = targetAngle;
    if (deltaX != 0 && oldTargetAngle == 0) {  // NORTH
      targetAngle = (deltaX < 0) ? targetAngle + RIGHT_ANGLE : targetAngle - RIGHT_ANGLE;
    }
    else if (deltaZ != 0 && (oldTargetAngle == RIGHT_ANGLE || oldTargetAngle == ((-3 * Math.PI) / 2))) {  // EAST
      targetAngle = (deltaZ < 0) ? targetAngle - RIGHT_ANGLE : targetAngle + RIGHT_ANGLE;
    }
    else if (deltaX != 0 && (oldTargetAngle == Math.PI || oldTargetAngle == Math.PI * -1)) {  // SOUTH
      targetAngle = (deltaX < 0) ? targetAngle - RIGHT_ANGLE : targetAngle + RIGHT_ANGLE;
    }
    else if (deltaZ != 0 && (oldTargetAngle == Math.PI / -2 || oldTargetAngle == (Math.PI * 3) / 2)) {  // WEST
      targetAngle = (deltaZ < 0) ? targetAngle + RIGHT_ANGLE : targetAngle - RIGHT_ANGLE;
    }

    deltaAngle = ROTATION_DELTA;
    deltaAngle *= (targetAngle > oldTargetAngle) ? 1 : -1;
  };

  animationManager.animate = function() {
    var currentTimestamp = new Date().getTime();
    var frameCount;

    if (animators.length === 0) {
      init();
    }

    if (previousFrameTimestamp === undefined) {
      frameCount = 1;
    }
    else {
      frameCount = Math.floor((currentTimestamp - previousFrameTimestamp) / TARGET_FRAME_WINDOW);
      if (frameCount < 1) {
        frameCount = 1;
      }
    }
    previousFrameTimestamp = currentTimestamp;

    var newAnimators = [];
    animators.forEach(function (animator) {
      animator.animate(frameCount);

      if (animator.finished === true) {
        if (animator instanceof rampAnimation) {
          newAnimators.push(new hoverAnimation());
        }
        else if (animator instanceof forwardAnimation) {
          determineNextTargetPoint();
          determineRotationAngle();
          newAnimators.push(new rotationAnimation(targetAngle, deltaAngle));
        }
        else if (animator instanceof rotationAnimation) {
          newAnimators.push(new forwardAnimation(targetX, deltaX, targetZ, deltaZ));
        }
        else if (animator instanceof hoverAnimation) {
          newAnimators.push(new hoverAnimation());
        }
      }
      else {
        newAnimators.push(animator);
      }
    });
    animators = newAnimators;

    var mapX = Coordinates.sceneXToMapX(camera.position.x);
    var mapZ = Coordinates.sceneZToMapZ(camera.position.z);

    var y = terrain.heightAtCoordinates(mapX, mapZ);
    camera.position.y = Math.max(camera.position.y, y + 0.5);

    renderer.render(scene, camera);
    requestAnimFrame(animationManager.animate);
  };

  return animationManager;
};

function forwardAnimation(targetX, deltaX, targetZ, deltaZ) {
  this.targetX = targetX;
  this.deltaX = deltaX;
  this.targetZ = targetZ;
  this.deltaZ = deltaZ;
  this.finished = false;
}

forwardAnimation.prototype.animate = function(frameCount) {
  camera.position.x += this.deltaX * frameCount;
  camera.position.z += this.deltaZ * frameCount;

  if ((this.deltaX < 0 && camera.position.x < this.targetX) || (this.deltaX > 0 && camera.position.x > this.targetX) ||
      (this.deltaZ < 0 && camera.position.z < this.targetZ) || (this.deltaZ > 0 && camera.position.z > this.targetZ)) {
    camera.position.x = this.targetX;
    camera.position.z = this.targetZ;

    this.finished = true;
  }
}

function rotationAnimation(targetAngle, deltaAngle) {
  this.targetAngle = targetAngle;
  this.deltaAngle = deltaAngle;
  this.finished = false;
}

rotationAnimation.prototype.animate = function(frameCount) {
  camera.rotation.y += this.deltaAngle * frameCount;

  if ((this.deltaAngle < 0 && camera.rotation.y <= this.targetAngle) || (this.deltaAngle > 0 && camera.rotation.y >= this.targetAngle)) {
    if (this.targetAngle >= Math.PI * 2 || this.targetAngle <= Math.PI * -2) {
      this.targetAngle = 0;
    }

    camera.rotation.y = this.targetAngle;
    this.finished = true;
  }
}

function rampAnimation(frameDistance, deltaY, minHeight, maxHeight) {
  this.ticks = 0;
  this.frameDistance = frameDistance;
  this.deltaY = deltaY;
  this.minHeight = minHeight;
  this.maxHeight = maxHeight;
  this.finished = false;
}

rampAnimation.prototype.animate = function(frameCount) {
  if (camera.position.y >= this.minHeight && camera.position.y <= this.maxHeight) {
    camera.position.y += this.deltaY * frameCount;
  }
  if (camera.position.y < this.minHeight) {
    camera.position.y = this.minHeight;
  }
  if (camera.position.y > this.maxHeight) {
    camera.position.y = this.maxHeight;
  }

  this.ticks += frameCount;
  if (this.ticks > this.frameDistance) {
    this.finished = true;
  }
}

function hoverAnimation() {
  var frameDistance = (Math.random() * 300) + 300;
  var deltaY = (camera.position.y > 0.5) ? -0.05 : 0.05;

  this.rampAnimation = new rampAnimation(frameDistance, deltaY, 0.5, 15);
  this.finished = false;
}

hoverAnimation.prototype.animate = function(frameCount) {
  this.rampAnimation.animate(frameCount);
  this.finished = this.rampAnimation.finished;
}
<|endoftext|>


<commit_before>/**
 * app.js
 *
 * This is the entry file for the application, only setup and boilerplate
 * code.
 */

// Needed for redux-saga es6 generator support
import 'babel-polyfill';

/* import injectTapEventPlugin from 'react-tap-event-plugin'; */
/* injectTapEventPlugin(); */

// Import all the third party stuff
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { applyRouterMiddleware, Router, browserHistory } from 'react-router';
import { syncHistoryWithStore } from 'react-router-redux';
import FontFaceObserver from 'fontfaceobserver';
import { useScroll } from 'react-router-scroll';
import 'sanitize.css/sanitize.css';

import { MuiThemeProvider } from 'material-ui/styles';

// Import root app
import App from 'containers/App';

// Import App Theme
import { theme } from 'utils/theme';

// Import selector for `syncHistoryWithStore`
import { makeSelectLocationState } from 'containers/App/selectors';

// Import Language Provider
import LanguageProvider from 'containers/LanguageProvider';

// Google Analytics
import ReactGA from 'react-ga';
import { gaTrackingId } from 'utils/constants';

// Load the favicon, the manifest.json file and the .htaccess file
/* eslint-disable import/no-webpack-loader-syntax */
import '!file-loader?name=[name].[ext]!./favicon.ico';
import '!file-loader?name=[name].[ext]!./manifest.json';
import 'file-loader?name=[name].[ext]!./.htaccess'; // eslint-disable-line import/extensions
/* eslint-enable import/no-webpack-loader-syntax */

import configureStore from './store';

// Import i18n messages
import { translationMessages } from './i18n';

// Import CSS reset and Global Styles
import './global-styles';

// Import routes
import createRoutes from './routes';

ReactGA.initialize(gaTrackingId);

function logPageView() {
  ReactGA.set({ page: window.location.pathname + window.location.search });
  ReactGA.pageview(window.location.pathname + window.location.search);
}

// Observe loading of Open Sans (to remove open sans, remove the <link> tag in
// the index.html file and this observer)
const openSansObserver = new FontFaceObserver('Open Sans', {});

// When Open Sans is loaded, add a font-family using Open Sans to the body
openSansObserver.load().then(() => {
  document.body.classList.add('fontLoaded');
}, () => {
  document.body.classList.remove('fontLoaded');
});

// Create redux store with history
// this uses the singleton browserHistory provided by react-router
// Optionally, this could be changed to leverage a created history
// e.g. `const browserHistory = useRouterHistory(createBrowserHistory)();`
const initialState = {};
const store = configureStore(initialState, browserHistory);

// Sync history and store, as the react-router-redux reducer
// is under the non-default key ("routing"), selectLocationState
// must be provided for resolving how to retrieve the "route" in the state
const history = syncHistoryWithStore(browserHistory, store, {
  selectLocationState: makeSelectLocationState(),
});

// Set up the router, wrapping all Routes in the App component
const rootRoute = {
  component: App,
  childRoutes: createRoutes(store),
};

// Initialize Google Analytics

const render = (messages) => {
  ReactDOM.render(
    <MuiThemeProvider theme={theme}>
      <Provider store={store}>
        <LanguageProvider messages={messages}>
          <Router
            history={history}
            routes={rootRoute}
            render={
              // Scroll to top when going to a new page, imitating default browser
              // behaviour
              applyRouterMiddleware(useScroll())
            }
            onUpdate={logPageView} // Google Analytics
          />
        </LanguageProvider>
      </Provider>
    </MuiThemeProvider>,
    document.getElementById('app')
  );
};

// Hot reloadable translation json files
if (module.hot) {
  // modules.hot.accept does not accept dynamic dependencies,
  // have to be constants at compile-time
  module.hot.accept('./i18n', () => {
    render(translationMessages);
  });
}

// Chunked polyfill for browsers without Intl support
if (!window.Intl) {
  (new Promise((resolve) => {
    resolve(import('intl'));
  }))
    .then(() => Promise.all([
      import('intl/locale-data/jsonp/en.js'),
      import('intl/locale-data/jsonp/de.js'),
    ]))
    .then(() => render(translationMessages))
    .catch((err) => {
      throw err;
    });
} else {
  render(translationMessages);
}

// Install ServiceWorker and AppCache in the end since
// it's not most important operation and if main code fails,
// we do not want it installed
if (process.env.NODE_ENV === 'production') {
  require('offline-plugin/runtime').install(); // eslint-disable-line global-require
}
<commit_msg>Dummy checkin<commit_after>/**
 * app.js
 *
 * This is the entry file for the application, only setup and boilerplate
 * code.
 */

// Needed for redux-saga es6 generator support
import 'babel-polyfill';

/* import injectTapEventPlugin from 'react-tap-event-plugin'; */
/* injectTapEventPlugin(); */
// Import all the third party stuff
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { applyRouterMiddleware, Router, browserHistory } from 'react-router';
import { syncHistoryWithStore } from 'react-router-redux';
import FontFaceObserver from 'fontfaceobserver';
import { useScroll } from 'react-router-scroll';
import 'sanitize.css/sanitize.css';

import { MuiThemeProvider } from 'material-ui/styles';

// Import root app
import App from 'containers/App';

// Import App Theme
import { theme } from 'utils/theme';

// Import selector for `syncHistoryWithStore`
import { makeSelectLocationState } from 'containers/App/selectors';

// Import Language Provider
import LanguageProvider from 'containers/LanguageProvider';

// Google Analytics
import ReactGA from 'react-ga';
import { gaTrackingId } from 'utils/constants';

// Load the favicon, the manifest.json file and the .htaccess file
/* eslint-disable import/no-webpack-loader-syntax */
import '!file-loader?name=[name].[ext]!./favicon.ico';
import '!file-loader?name=[name].[ext]!./manifest.json';
import 'file-loader?name=[name].[ext]!./.htaccess'; // eslint-disable-line import/extensions
/* eslint-enable import/no-webpack-loader-syntax */

import configureStore from './store';

// Import i18n messages
import { translationMessages } from './i18n';

// Import CSS reset and Global Styles
import './global-styles';

// Import routes
import createRoutes from './routes';

ReactGA.initialize(gaTrackingId);

function logPageView() {
  ReactGA.set({ page: window.location.pathname + window.location.search });
  ReactGA.pageview(window.location.pathname + window.location.search);
}

// Observe loading of Open Sans (to remove open sans, remove the <link> tag in
// the index.html file and this observer)
const openSansObserver = new FontFaceObserver('Open Sans', {});

// When Open Sans is loaded, add a font-family using Open Sans to the body
openSansObserver.load().then(() => {
  document.body.classList.add('fontLoaded');
}, () => {
  document.body.classList.remove('fontLoaded');
});

// Create redux store with history
// this uses the singleton browserHistory provided by react-router
// Optionally, this could be changed to leverage a created history
// e.g. `const browserHistory = useRouterHistory(createBrowserHistory)();`
const initialState = {};
const store = configureStore(initialState, browserHistory);

// Sync history and store, as the react-router-redux reducer
// is under the non-default key ("routing"), selectLocationState
// must be provided for resolving how to retrieve the "route" in the state
const history = syncHistoryWithStore(browserHistory, store, {
  selectLocationState: makeSelectLocationState(),
});

// Set up the router, wrapping all Routes in the App component
const rootRoute = {
  component: App,
  childRoutes: createRoutes(store),
};

// Initialize Google Analytics

const render = (messages) => {
  ReactDOM.render(
    <MuiThemeProvider theme={theme}>
      <Provider store={store}>
        <LanguageProvider messages={messages}>
          <Router
            history={history}
            routes={rootRoute}
            render={
              // Scroll to top when going to a new page, imitating default browser
              // behaviour
              applyRouterMiddleware(useScroll())
            }
            onUpdate={logPageView} // Google Analytics
          />
        </LanguageProvider>
      </Provider>
    </MuiThemeProvider>,
    document.getElementById('app')
  );
};

// Hot reloadable translation json files
if (module.hot) {
  // modules.hot.accept does not accept dynamic dependencies,
  // have to be constants at compile-time
  module.hot.accept('./i18n', () => {
    render(translationMessages);
  });
}

// Chunked polyfill for browsers without Intl support
if (!window.Intl) {
  (new Promise((resolve) => {
    resolve(import('intl'));
  }))
    .then(() => Promise.all([
      import('intl/locale-data/jsonp/en.js'),
      import('intl/locale-data/jsonp/de.js'),
    ]))
    .then(() => render(translationMessages))
    .catch((err) => {
      throw err;
    });
} else {
  render(translationMessages);
}

// Install ServiceWorker and AppCache in the end since
// it's not most important operation and if main code fails,
// we do not want it installed
if (process.env.NODE_ENV === 'production') {
  require('offline-plugin/runtime').install(); // eslint-disable-line global-require
}
<|endoftext|>


<commit_before>'use strict';

angular.module('h_autocomplete', [
  'Autocomplete'
]);
<commit_msg>Remove app.js<commit_after><|endoftext|>


<commit_before>var f,g;

var BIBO  = $rdf.Namespace("http://purl.org/ontology/bibo/#");
var CHAT  = $rdf.Namespace("https://ns.rww.io/chat#");
var CURR  = $rdf.Namespace("https://w3id.org/cc#");
var DCT   = $rdf.Namespace("http://purl.org/dc/terms/");
var FACE  = $rdf.Namespace("https://graph.facebook.com/schema/~/");
var FOAF  = $rdf.Namespace("http://xmlns.com/foaf/0.1/");
var LIKE  = $rdf.Namespace("http://ontologi.es/like#");
var LINK  = $rdf.Namespace("http://www.w3.org/2007/ont/link#");
var LDP   = $rdf.Namespace("http://www.w3.org/ns/ldp#");
var MBLOG = $rdf.Namespace("http://www.w3.org/ns/mblog#");
var OWL   = $rdf.Namespace("http://www.w3.org/2002/07/owl#");
var PIM   = $rdf.Namespace("http://www.w3.org/ns/pim/space#");
var RDF   = $rdf.Namespace("http://www.w3.org/1999/02/22-rdf-syntax-ns#");
var RDFS  = $rdf.Namespace("http://www.w3.org/2000/01/rdf-schema#");
var SIOC  = $rdf.Namespace("http://rdfs.org/sioc/ns#");
var SOLID = $rdf.Namespace("http://www.w3.org/ns/solid/app#");
var URN   = $rdf.Namespace("urn:");
var XHV   = $rdf.Namespace("http://www.w3.org/1999/xhtml/vocab#");

var AUTHENDPOINT = "https://databox.me/";
var PROXY = "https://rww.io/proxy.php?uri={uri}";
var TIMEOUT = 2000;
var DEBUG = true;

var scope = {};

$rdf.Fetcher.crossSiteProxyTemplate=PROXY;

var App = angular.module('myApp', [
  'lumx',
  'ngAudio'
]);

App.config(function($locationProvider) {
  $locationProvider
    .html5Mode({ enabled: true, requireBase: false });
});

App.controller('Main', function($scope, $http, $location, $timeout, $sce, LxNotificationService, LxProgressService, LxDialogService, ngAudio) {

  // save app configuration if it's the first time the app runs
  $scope.initApp = function() {
    $scope.init();
  };

  $scope.TLSlogin = function() {
    $scope.loginTLSButtonText = 'Logging in...';
    console.log('logging in');
    $http({
      method: 'HEAD',
      url: AUTHENDPOINT,
      withCredentials: true
    }).success(function(data, status, headers) {
      // add dir to local list
      var user = headers('User');
      if (user && user.length > 0 && user.slice(0,4) == 'http') {
        //LxNotificationService.success('Login Successful!');
        $scope.loggedIn = true;
        $scope.user = user;
        console.log('success logged in a ' + user);
      } else {
        //LxNotificationService.error('WebID-TLS authentication failed.');
        console.log('WebID-TLS authentication failed.');
      }
      $scope.loginTLSButtonText = 'Login';
    }).error(function(data, status, headers) {
      LxNotificationService.error('Could not connect to auth server: HTTP '+status);
      console.log('Could not connect to auth server: HTTP '+status);
      $scope.loginTLSButtonText = 'Login';
    });
  };

  $scope.openDialog = function(elem, reset) {
      if (reset) {
          $scope.resetContact();
      }
      LxDialogService.open(elem);
      $(document).keyup(function(e) {
        if (e.keyCode===27) {
          LxDialogService.close(elem);
        }
      });
  };

  $scope.getLines = function(artes) {
    ret = 0;

    if (!artes) artes = $scope.artes;
    var count = artes.split("\n").length;
    ret += count;

    return ret;
  };

  $scope.logout = function() {
    $scope.init();
    LxNotificationService.success('Logout Successful!');
  };

  $scope.getNextChapter = function() {
    var n = g.statementsMatching($rdf.sym($scope.contentURI), XHV('next'));
    if (n.length > 0) {
      return n[0].object.value;
    }

    var chapter = parseInt($scope.contentURI.substr(-2));
    chapter += 1;
    var stem = $scope.contentURI.substr(0, $scope.contentURI.length - 2);

    if ($scope.chapter < 10) {
      stem += '0';
    }

    return stem + chapter;

  };

  $scope.next = function() {
    if ($scope.verse < $scope.verses.length-1) {
      $scope.verse++;
      $scope.line += $scope.getLines($scope.artes);
      $scope.render();
    } else {
      console.log('load next chapter');
      var next = $scope.getNextChapter();

      f.nowOrWhenFetched(next, undefined, function(ok, body) {
        var error = g.statementsMatching($rdf.sym(next), LINK('error'));

        if (error.length>0) {
          // process 402 or 403
          var c = confirm('HTTP 402, payment required!\nFirst two chapters are free.\nNext chapter costs 1 bit.\nWould you like to buy access?');
          if (c) {
            $scope.TLSlogin();
            setTimeout(pay, 1000);
          }
          return;
        }

        $scope.verse = 0;
        $scope.line = 1;
        $scope.chapter++;
        $scope.contentURI = next;

        $scope.render();
      });

    }
  };

  function pay() {
    if (!$scope.user) alert('Please log in first.');
    alert('paying ' + $scope.user);

    var bot = 'https://inartes.databox.me/profile/card#me';

    var wc = '<#this>  a <https://w3id.org/cc#Credit> ;\n';
    wc += '  <https://w3id.org/cc#source> \n    <' + $scope.user + '> ;\n';
    wc += '  <https://w3id.org/cc#destination> \n    <' + bot + '> ;\n';
    wc += '  <https://w3id.org/cc#amount> "' + 1 + '" ;\n';
    wc += '  <https://w3id.org/cc#currency> \n    <https://w3id.org/cc#bit> .\n';

    var hash = CryptoJS.SHA256($scope.user).toString();

    function postFile(file, data) {
      xhr = new XMLHttpRequest();
      xhr.open('POST', file, false);
      xhr.setRequestHeader('Content-Type', 'text/turtle; charset=UTF-8');
      xhr.send(data);
    }

    postFile('https://gitpay.databox.me/Public/.wallet/github.com/melvincarvalho/inartes.com/inbox/' + hash + '/', wc);
    console.log(wc);
  }

  $scope.render = function() {
    $scope.verses = g.statementsMatching(undefined, BIBO('content'), undefined, $rdf.sym($scope.contentURI) );
    if ($scope.verses.length > $scope.verse) {
      $scope.artes = $scope.verses[$scope.verse].object.value;
      $location.search('contentURI', $scope.verses[$scope.verse].subject.value);
    }
    console.log($scope.artes);
    $scope.$apply();
  };

  // set init variables
  $scope.init = function() {

    $scope.verse = 0;
    $scope.artes = 'loading...';
    $scope.chapter = 1;
    $scope.line = 1;

    $scope.defaultSound = 'audio/button-3.mp3';
    $scope.audio = ngAudio.load($scope.defaultSound);

    // start in memory DB
    g = $rdf.graph();
    f = $rdf.fetcher(g);
    // add CORS proxy
    var PROXY      = "https://data.fm/proxy?uri={uri}";
    var AUTH_PROXY = "https://rww.io/auth-proxy?uri=";
    //$rdf.Fetcher.crossSiteProxyTemplate=PROXY;
    var kb         = $rdf.graph();
    var fetcher    = $rdf.fetcher(kb);

    $scope.initialized = true;
    $scope.loggedIn = false;
    $scope.loginTLSButtonText = "Login";
    // display elements object

    var contentURI = 'https://inartes.databox.me/Public/dante/inferno-01';
    if ($location.search().contentURI) {
      contentURI = $location.search().contentURI.split('#')[0];
      if ($location.search().contentURI.split('#').length > 0) {
        var line = $location.search().contentURI.split('#')[1];
        if (parseInt(line)) {
          $scope.chapter = parseInt(contentURI.substr(-2));
          $scope.line = parseInt(line);
          $scope.verse = (parseInt(line)-1)/3;
        }
      }
    }
    $scope.contentURI = contentURI;

    f.nowOrWhenFetched(contentURI, undefined, function(ok, body) {
      $scope.render();
    });

  };

  $scope.initApp();

});
<commit_msg>cleanup unused function<commit_after>var f,g;

var BIBO  = $rdf.Namespace("http://purl.org/ontology/bibo/#");
var CHAT  = $rdf.Namespace("https://ns.rww.io/chat#");
var CURR  = $rdf.Namespace("https://w3id.org/cc#");
var DCT   = $rdf.Namespace("http://purl.org/dc/terms/");
var FACE  = $rdf.Namespace("https://graph.facebook.com/schema/~/");
var FOAF  = $rdf.Namespace("http://xmlns.com/foaf/0.1/");
var LIKE  = $rdf.Namespace("http://ontologi.es/like#");
var LINK  = $rdf.Namespace("http://www.w3.org/2007/ont/link#");
var LDP   = $rdf.Namespace("http://www.w3.org/ns/ldp#");
var MBLOG = $rdf.Namespace("http://www.w3.org/ns/mblog#");
var OWL   = $rdf.Namespace("http://www.w3.org/2002/07/owl#");
var PIM   = $rdf.Namespace("http://www.w3.org/ns/pim/space#");
var RDF   = $rdf.Namespace("http://www.w3.org/1999/02/22-rdf-syntax-ns#");
var RDFS  = $rdf.Namespace("http://www.w3.org/2000/01/rdf-schema#");
var SIOC  = $rdf.Namespace("http://rdfs.org/sioc/ns#");
var SOLID = $rdf.Namespace("http://www.w3.org/ns/solid/app#");
var URN   = $rdf.Namespace("urn:");
var XHV   = $rdf.Namespace("http://www.w3.org/1999/xhtml/vocab#");

var AUTHENDPOINT = "https://databox.me/";
var PROXY = "https://rww.io/proxy.php?uri={uri}";
var TIMEOUT = 2000;
var DEBUG = true;

var scope = {};

$rdf.Fetcher.crossSiteProxyTemplate=PROXY;

var App = angular.module('myApp', [
  'lumx',
  'ngAudio'
]);

App.config(function($locationProvider) {
  $locationProvider
    .html5Mode({ enabled: true, requireBase: false });
});

App.controller('Main', function($scope, $http, $location, $timeout, $sce, LxNotificationService, LxProgressService, LxDialogService, ngAudio) {

  // save app configuration if it's the first time the app runs
  $scope.initApp = function() {
    $scope.init();
  };

  $scope.TLSlogin = function() {
    $scope.loginTLSButtonText = 'Logging in...';
    console.log('logging in');
    $http({
      method: 'HEAD',
      url: AUTHENDPOINT,
      withCredentials: true
    }).success(function(data, status, headers) {
      // add dir to local list
      var user = headers('User');
      if (user && user.length > 0 && user.slice(0,4) == 'http') {
        //LxNotificationService.success('Login Successful!');
        $scope.loggedIn = true;
        $scope.user = user;
        console.log('success logged in a ' + user);
      } else {
        //LxNotificationService.error('WebID-TLS authentication failed.');
        console.log('WebID-TLS authentication failed.');
      }
      $scope.loginTLSButtonText = 'Login';
    }).error(function(data, status, headers) {
      LxNotificationService.error('Could not connect to auth server: HTTP '+status);
      console.log('Could not connect to auth server: HTTP '+status);
      $scope.loginTLSButtonText = 'Login';
    });
  };

  $scope.getLines = function(artes) {
    ret = 0;

    if (!artes) artes = $scope.artes;
    var count = artes.split("\n").length;
    ret += count;

    return ret;
  };

  $scope.logout = function() {
    $scope.init();
    LxNotificationService.success('Logout Successful!');
  };

  $scope.getNextChapter = function() {
    var n = g.statementsMatching($rdf.sym($scope.contentURI), XHV('next'));
    if (n.length > 0) {
      return n[0].object.value;
    }

    var chapter = parseInt($scope.contentURI.substr(-2));
    chapter += 1;
    var stem = $scope.contentURI.substr(0, $scope.contentURI.length - 2);

    if ($scope.chapter < 10) {
      stem += '0';
    }

    return stem + chapter;

  };

  $scope.next = function() {
    if ($scope.verse < $scope.verses.length-1) {
      $scope.verse++;
      $scope.line += $scope.getLines($scope.artes);
      $scope.render();
    } else {
      console.log('load next chapter');
      var next = $scope.getNextChapter();

      f.nowOrWhenFetched(next, undefined, function(ok, body) {
        var error = g.statementsMatching($rdf.sym(next), LINK('error'));

        if (error.length>0) {
          // process 402 or 403
          var c = confirm('HTTP 402, payment required!\nFirst two chapters are free.\nNext chapter costs 1 bit.\nWould you like to buy access?');
          if (c) {
            $scope.TLSlogin();
            setTimeout(pay, 1000);
          }
          return;
        }

        $scope.verse = 0;
        $scope.line = 1;
        $scope.chapter++;
        $scope.contentURI = next;

        $scope.render();
      });

    }
  };

  function pay() {
    if (!$scope.user) alert('Please log in first.');
    alert('paying ' + $scope.user);

    var bot = 'https://inartes.databox.me/profile/card#me';

    var wc = '<#this>  a <https://w3id.org/cc#Credit> ;\n';
    wc += '  <https://w3id.org/cc#source> \n    <' + $scope.user + '> ;\n';
    wc += '  <https://w3id.org/cc#destination> \n    <' + bot + '> ;\n';
    wc += '  <https://w3id.org/cc#amount> "' + 1 + '" ;\n';
    wc += '  <https://w3id.org/cc#currency> \n    <https://w3id.org/cc#bit> .\n';

    var hash = CryptoJS.SHA256($scope.user).toString();

    function postFile(file, data) {
      xhr = new XMLHttpRequest();
      xhr.open('POST', file, false);
      xhr.setRequestHeader('Content-Type', 'text/turtle; charset=UTF-8');
      xhr.send(data);
    }

    postFile('https://gitpay.databox.me/Public/.wallet/github.com/melvincarvalho/inartes.com/inbox/' + hash + '/', wc);
    console.log(wc);
  }

  $scope.render = function() {
    $scope.verses = g.statementsMatching(undefined, BIBO('content'), undefined, $rdf.sym($scope.contentURI) );
    if ($scope.verses.length > $scope.verse) {
      $scope.artes = $scope.verses[$scope.verse].object.value;
      $location.search('contentURI', $scope.verses[$scope.verse].subject.value);
    }
    console.log($scope.artes);
    $scope.$apply();
  };

  // set init variables
  $scope.init = function() {

    $scope.verse = 0;
    $scope.artes = 'loading...';
    $scope.chapter = 1;
    $scope.line = 1;

    $scope.defaultSound = 'audio/button-3.mp3';
    $scope.audio = ngAudio.load($scope.defaultSound);

    // start in memory DB
    g = $rdf.graph();
    f = $rdf.fetcher(g);
    // add CORS proxy
    var PROXY      = "https://data.fm/proxy?uri={uri}";
    var AUTH_PROXY = "https://rww.io/auth-proxy?uri=";
    //$rdf.Fetcher.crossSiteProxyTemplate=PROXY;
    var kb         = $rdf.graph();
    var fetcher    = $rdf.fetcher(kb);

    $scope.initialized = true;
    $scope.loggedIn = false;
    $scope.loginTLSButtonText = "Login";
    // display elements object

    var contentURI = 'https://inartes.databox.me/Public/dante/inferno-01';
    if ($location.search().contentURI) {
      contentURI = $location.search().contentURI.split('#')[0];
      if ($location.search().contentURI.split('#').length > 0) {
        var line = $location.search().contentURI.split('#')[1];
        if (parseInt(line)) {
          $scope.chapter = parseInt(contentURI.substr(-2));
          $scope.line = parseInt(line);
          $scope.verse = (parseInt(line)-1)/3;
        }
      }
    }
    $scope.contentURI = contentURI;

    f.nowOrWhenFetched(contentURI, undefined, function(ok, body) {
      $scope.render();
    });

  };

  $scope.initApp();

});
<|endoftext|>


<commit_before>/**
 * Initializes all need modules
 *
 */
var pcAppDependencies = [
    'ngRoute',
    'ui.bootstrap',
    'pcApp.metrics',
    'pcApp.visualization',
    'pcApp.events',
    'pcApp.common',
    'pcApp.fcm',
    'pcApp.developer',
    'pcApp.search',
    'pcApp.ratings',
    'pcApp.indicators',
    'pcApp.datasets',
    'pcApp.feedbacks',
    'pcApp.ags',
    'pcApp.references.directives.resolve',
    'dialogs.main',
    'dialogs.default-translations',
    'ngSpectrum',
    'skrollrDirectives',
    'ngProgress',
    'isteven-multi-select',
    'rzModule',
    'checklist-model',
    'duScroll',
    'angulartics',
    'angulartics.piwik'
];

if (policyCompassConfig.ENABLE_ADHOCRACY) {
    pcAppDependencies.push.apply(pcAppDependencies, [
        'pcApp.adhocracyEmbedder',
        'pcApp.auth',
        'pcApp.deliberation'
    ]);
}

var pcApp = angular.module('pcApp', pcAppDependencies)

    .run(function ($rootScope, $location) {
        $rootScope.location = $location;
    })

/**
 * Very simple central error handling
 */
    .factory('$exceptionHandler', [
        '$injector', '$log', function ($injector, $log) {
            return function (exception, cause) {
                // Use the dialogs module to display error messages
                var dialogs = $injector.get("dialogs");
                dialogs.notify("Error", String(exception.message));
                $log.error(cause);
                $log.error(exception);
            };
        }
    ])

    .config([
        '$locationProvider', function ($locationProvider) {
            $locationProvider.html5Mode(false).hashPrefix('!');
        }
    ])

    .config([
        '$windowProvider', function($windowProvider) {
            var tracker_url = policyCompassConfig.PIWIK_TRACKER_URL;
            var _paq = [];
            _paq.push(['setDomains', policyCompassConfig.PIWIK_DOMAINS ]);
            _paq.push(['enableLinkTracking']);
            _paq.push(['disableCookies']);
            _paq.push(['setTrackerUrl', tracker_url + 'piwik.php']);
            _paq.push(['setSiteId', 1]);
            var $window = $windowProvider.$get();
            $window._paq = _paq;
            $.ajax({
                 url: tracker_url + "piwik.js",
                 dataType: "script"
            });
        }
    ]);
<commit_msg>Add option to disable piwik<commit_after>/**
 * Initializes all need modules
 *
 */
var pcAppDependencies = [
    'ngRoute',
    'ui.bootstrap',
    'pcApp.metrics',
    'pcApp.visualization',
    'pcApp.events',
    'pcApp.common',
    'pcApp.fcm',
    'pcApp.developer',
    'pcApp.search',
    'pcApp.ratings',
    'pcApp.indicators',
    'pcApp.datasets',
    'pcApp.feedbacks',
    'pcApp.ags',
    'pcApp.references.directives.resolve',
    'dialogs.main',
    'dialogs.default-translations',
    'ngSpectrum',
    'skrollrDirectives',
    'ngProgress',
    'isteven-multi-select',
    'rzModule',
    'checklist-model',
    'duScroll',
    'angulartics',
    'angulartics.piwik'
];

if (policyCompassConfig.ENABLE_ADHOCRACY) {
    pcAppDependencies.push.apply(pcAppDependencies, [
        'pcApp.adhocracyEmbedder',
        'pcApp.auth',
        'pcApp.deliberation'
    ]);
}

var pcApp = angular.module('pcApp', pcAppDependencies)

    .run(function ($rootScope, $location) {
        $rootScope.location = $location;
    })

/**
 * Very simple central error handling
 */
    .factory('$exceptionHandler', [
        '$injector', '$log', function ($injector, $log) {
            return function (exception, cause) {
                // Use the dialogs module to display error messages
                var dialogs = $injector.get("dialogs");
                dialogs.notify("Error", String(exception.message));
                $log.error(cause);
                $log.error(exception);
            };
        }
    ])

    .config([
        '$locationProvider', function ($locationProvider) {
            $locationProvider.html5Mode(false).hashPrefix('!');
        }
    ])

    .config([
        '$windowProvider', function($windowProvider) {
            if (! policyCompassConfig.PIWIK_TRACKER_URL) {
                $log.info("No piwik tracker enabled")
                return
            }

            var tracker_url = policyCompassConfig.PIWIK_TRACKER_URL;
            var _paq = [];
            _paq.push(['setDomains', policyCompassConfig.PIWIK_DOMAINS || [] ]);
            _paq.push(['enableLinkTracking']);
            _paq.push(['disableCookies']);
            _paq.push(['setTrackerUrl', tracker_url + 'piwik.php']);
            _paq.push(['setSiteId', 1]);
            var $window = $windowProvider.$get();
            $window._paq = _paq;
            $.ajax({
                 url: tracker_url + "piwik.js",
                 dataType: "script"
            });
        }
    ]);
<|endoftext|>


<commit_before>var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mailin = require('mailin');
var fs = require('fs');

var routes = require('./routes/index');
var users = require('./routes/users');

var accessKey = fs.readFileSync('/home/ubuntu/accessKey.txt').toString().trim();
var secretKey = fs.readFileSync('/home/ubuntu/secretKey.txt').toString().trim();

console.log(accessKey);
console.log(secretKey);

var nodemailer = require('nodemailer');
var ses = require('nodemailer-ses-transport');

// create reusable transporter object using SMTP transport
var transporter = nodemailer.createTransport(ses({
        accessKeyId: accessKey,
        secretAccessKey: secretKey,
        region: 'us-west-2'
    })
);

// NB! No need to recreate the transporter object. You can use
// the same transporter object for all e-mails

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

mailin.start({
  port: 25,
  disableWebhook: true // Disable the webhook posting.
});

/* Access simplesmtp server instance. */
mailin.on('authorizeUser', function(connection, username, password, done) {
  if (username == "johnsmith" && password == "mysecret") {
    done(null, true);
  } else {
    done(new Error("Unauthorized!"), false);
  }
});

/* Event emitted when a connection with the Mailin smtp server is initiated. */
mailin.on('startMessage', function (connection) {
  /* connection = {
      from: 'sender@somedomain.com',
      to: 'someaddress@yourdomain.com',
      id: 't84h5ugf',
      authentication: { username: null, authenticated: false, status: 'NORMAL' }
  }
  }; */
  console.log(connection);
});

/* Event emitted after a message was received and parsed. */
mailin.on('message', function (connection, data, content) {
  console.log(data);
  console.log(data.text.length);
  console.log(data.from[0].address);
  console.log(data.text);

  var mailOptions = {
    from: 'postmaster@gocha.io',
    to: 'success@simulator.amazonses.com',
    subject: data.subject,
    text: data.text
  };

  // send mail with defined transport object
  transporter.sendMail(mailOptions, function(error, info){
      if(error){
          console.log(error);
      }else{
          console.log('Message sent: ' + info.response);
      }
  });

  /* Do something useful with the parsed message here.
   * Use parsed message `data` directly or use raw message `content`. */
});

app.use('/', routes);
app.use('/users', users);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});

module.exports = app;

app.listen(80);<commit_msg>Bouncing now<commit_after>var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mailin = require('mailin');
var fs = require('fs');

var routes = require('./routes/index');
var users = require('./routes/users');

var accessKey = fs.readFileSync('/home/ubuntu/accessKey.txt').toString().trim();
var secretKey = fs.readFileSync('/home/ubuntu/secretKey.txt').toString().trim();

console.log(accessKey);
console.log(secretKey);

var nodemailer = require('nodemailer');
var ses = require('nodemailer-ses-transport');

// create reusable transporter object using SMTP transport
var transporter = nodemailer.createTransport(ses({
        accessKeyId: accessKey,
        secretAccessKey: secretKey,
        region: 'us-west-2'
    })
);

// NB! No need to recreate the transporter object. You can use
// the same transporter object for all e-mails

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

mailin.start({
  port: 25,
  disableWebhook: true // Disable the webhook posting.
});

/* Access simplesmtp server instance. */
mailin.on('authorizeUser', function(connection, username, password, done) {
  if (username == "johnsmith" && password == "mysecret") {
    done(null, true);
  } else {
    done(new Error("Unauthorized!"), false);
  }
});

/* Event emitted when a connection with the Mailin smtp server is initiated. */
mailin.on('startMessage', function (connection) {
  /* connection = {
      from: 'sender@somedomain.com',
      to: 'someaddress@yourdomain.com',
      id: 't84h5ugf',
      authentication: { username: null, authenticated: false, status: 'NORMAL' }
  }
  }; */
  console.log(connection);
});

/* Event emitted after a message was received and parsed. */
mailin.on('message', function (connection, data, content) {
  console.log(data);
  console.log(data.text.length);
  console.log(data.from[0].address);
  console.log(data.text);

  var mailOptions = {
    from: 'postmaster@gocha.io',
    to: data.from[0].address,
    subject: data.subject,
    text: data.text
  };

  // send mail with defined transport object
  transporter.sendMail(mailOptions, function(error, info){
      if(error){
          console.log(error);
      }else{
          console.log('Message sent: ' + info.response);
      }
  });

  /* Do something useful with the parsed message here.
   * Use parsed message `data` directly or use raw message `content`. */
});

app.use('/', routes);
app.use('/users', users);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});

module.exports = app;

app.listen(80);<|endoftext|>


<commit_before>//  This file containts opportunities bussines logic
//  function definitions section
lx.contact.renderContactDuplicates = function (duplicates) {
    console.warn("duplicados devueltos:", duplicates);
    $(".contact_duplicates ul li").remove();
    if (duplicates.data.length) {
        duplicates.data.forEach(function (element) {
            primary_address = {};
            element.emails.forEach(function (element) {
                if (element.primary_address === "1") {
                    primary_address.id = element.id;
                    primary_address.email_address = element.email_address;
                }
            });
            duplicate_detail = '<li id="' + element.id;
            duplicate_detail += '" data-account_id="' + element.accounts[0].id;
            duplicate_detail += '" data-cedula_c="' + element.cedula_c;
            duplicate_detail += '" data-first_name="' + element.first_name;
            duplicate_detail += '" data-last_name="' + element.last_name;
            duplicate_detail += '" data-lastname2_c="' + element.lastname2_c;
            duplicate_detail += '" data-phone_mobile="' + element.phone_mobile;
            duplicate_detail += '" data-phone_work="' + element.phone_work;
            duplicate_detail += '" data-title="' + element.title;
            duplicate_detail +=
                '" data-primary_email_address_id="' + primary_address.id;
            duplicate_detail +=
                '" data-primary_email_address="' +
                primary_address.email_address;
            duplicate_detail += '">';
            duplicate_detail +=
                element.first_name +
                " " +
                element.last_name +
                " " +
                element.lastname2_c +
                " " +
                element.cedula_c +
                " ";
            element.emails.forEach(function (element) {
                duplicate_detail += element.email_address + " ";
            });
            duplicate_detail += element.phone_mobile + " ";
            duplicate_detail += element.phone_work;
            // Client specific only fields
            // duplicate_detail += ' - ' + element.{fieldname};
            // Client specific only fields
            duplicate_detail += "
";
            $(".contact_duplicates ul").append(duplicate_detail);
        });
        newh = duplicates.data.length * 20 + 18; // last 18px bit is for duplicates title
        $(
            "#contact_duplicates_" + duplicates.fieldname + " .yui-ac-content"
        ).css("height", newh + "px");
        $(
            "#contact_duplicates_" + duplicates.fieldname + " .yui-ac-content"
        ).show(500);
        $(".contact_duplicates li").off("mouseover.contact_duplicates_list");
        $(".contact_duplicates li").on(
            "mouseover.contact_duplicates_list",
            function () {
                $(this).toggleClass("yui-ac-highlight");
                $(this).siblings("li").removeClass("yui-ac-highlight");
            }
        );
        $(".contact_duplicates li").off("click.contact_duplicates_list");
        $(".contact_duplicates li").on(
            "click.contact_duplicates_list",
            function () {
                $(".contact_duplicates .yui-ac-content").hide(500);
                console.warn(
                    "Redirecting to contacts Editview: - " +
                        window.location.origin +
                        window.location.pathname +
                        "?module=Contacts&return_module=Contacts&action=EditView&record=" +
                        this.id
                );
                toastr["info"](
                    "Redireccionando a " + $(this).data("first_name") + "...",
                    "Posibles duplicados encontrados",
                    {
                        positionClass: "toast-bottom-center",
                        showDuration: "0",
                        hideDuration: "0",
                        timeOut: "4000",
                        extendedTimeOut: "0",
                        progressBar: true,
                    }
                );
                window.location.href =
                    window.location.origin +
                    window.location.pathname +
                    "?module=Contacts&return_module=Contacts&action=EditView&record=" +
                    this.id;
            }
        );
    }
};

lx.contact.resultsSearchTSECRHandler = async function (forceCheck) {
    try {
        if (forceCheck) {
            lx.lionixCRM.config.modules = undefined;
            $("#cedula_c_lxajaxed").remove();
        }
        if ($("#cedula_c_lxajaxed").length == 0) {
            keyup_status = "disabled";
            $("#cedula_c").off("keyup.results_search_tsecr");
            if (lx.lionixCRM.config.modules.contacts.results_search_tsecr) {
                keyup_status = "enabled";
                $("#cedula_c").on(
                    "keyup.results_search_tsecr",
                    async function () {
                        if (lx.lionixCRM.config.debuglx) {
                            console.warn(
                                "key up ->",
                                String.fromCharCode(event.which)
                            );
                        }
                        if ($(this).val().length != 9) {
                            $("#first_name").val("");
                            $("#last_name").val("");
                            $("#lastname2_c").val("");
                        } else {
                            typed_cedula = $(this).val();
                            tsecrlist = await lx.lionixCRM.getTSECRData({
                                // Infoticos must be on same database server this SuiteCRM instance.
                                focusfieldname: this.id,
                                cedula_c: typed_cedula,
                            });
                            console.warn(
                                "After query to lx.lionixCRM.getTSECRData:",
                                tsecrlist
                            );
                            $("#cedula_c").val(tsecrlist.data[0].cedula_c);
                            $("#first_name").val(tsecrlist.data[0].first_name);
                            $("#last_name").val(tsecrlist.data[0].last_name);
                            $("#lastname2_c").val(
                                tsecrlist.data[0].lastname2_c
                            );
                            $("#first_name").focus();
                            $("#first_name").trigger("keypress");
                        }
                    }
                );
            }
            $("#cedula_c").append(
                '
'
            );
            console.warn(
                "keyup.results_search_tsecr on #cedula_c " + keyup_status
            );
        } else {
            if (lx.lionixCRM.config.debuglx) {
                console.warn(
                    `cedula_c_lxajaxed div indicator already exists and it's [${$(
                        "#cedula_c_lxajaxed"
                    ).data("results_search_tsecr")}].`
                );
            }
        }
    } catch (error) {
        console.error("Modules[contacts] properties are not present!");
        console.error("Retrieving modules[contacts] properties...");
        data = await lx.lionixCRM.getConfigOption("modules");
        console.error("Modules[contacts] successfully retrieved", data);
        lx.contact.resultsSearchTSECRHandler(false);
    }
};

lx.contact.resultsListDuplicatesHandler = function (forceCheck) {
    try {
        if (forceCheck) {
            lx.lionixCRM.config.modules = undefined;
            $("#full_name_lxajaxed").remove();
        }
        if ($("#full_name_lxajaxed").length == 0) {
            keyup_status = "disabled";
            $("#first_name, #last_name, #lastname2_c").off(
                "focusout.results_list_duplicates"
            );
            if (lx.lionixCRM.config.modules.contacts.results_list_duplicates) {
                keyup_status = "enabled";
                $("#first_name, #last_name, #lastname2_c").on(
                    "keypress.results_list_duplicates",
                    function () {
                        ffn = $("#first_name");
                        fln = $("#last_name");
                        fln2 = $("#lastname2_c");
                        // femail = $('#Contacts0emailAddress0');
                        // fced = $('#cedula_c');
                        if (
                            $(ffn).val().length > 2 &&
                            ($(fln).val().length > 2 ||
                                $(fln2).val().length > 2)
                        ) {
                            if (
                                $("#contact_duplicates_" + this.id).length == 0
                            ) {
                                // width: 750px can be changed in each Client
                                width = lx.lionixCRM.config.modules.contacts
                                    .results_list_duplicates_width
                                    ? lx.lionixCRM.config.modules.contacts
                                          .results_list_duplicates_width
                                    : 750;
                                $(this).before(
                                    '

Posibles duplicados encontrados

'
                                );
                            }
                            $("#first_name, #last_name, #lastname2_c").off(
                                "focusout.results_list_duplicates"
                            );
                            $("#first_name, #last_name, #lastname2_c").on(
                                "focusout.results_list_duplicates",
                                function () {
                                    $(
                                        ".contact_duplicates .yui-ac-content"
                                    ).hide(500);
                                }
                            );
                            lx.lionixCRM
                                .getContactDuplicates({
                                    fieldname: this.id,
                                    first_name: $(ffn).val(),
                                    last_name: $(fln).val(),
                                    lastname2_c: $(fln2).val(),
                                    // "cedula_c": $(fced).val(),
                                    // "email_address": $(femail).val()
                                })
                                .then(function (duplicates) {
                                    lx.contact.renderContactDuplicates(
                                        duplicates
                                    );
                                });
                        }
                    }
                );
            }
            $("#cedula_c").append(
                '
'
            );
            console.warn(
                "keypress.results_list_duplicates on #first_name, #last_name and #lastname2_c " +
                    keyup_status
            );
        } else {
            if (lx.lionixCRM.config.debuglx) {
                console.warn(
                    "full_name_lxajaxed div indicator already exists and it's [" +
                        $("#full_name_lxajaxed").data(
                            "results_list_duplicates"
                        ) +
                        "]."
                );
            }
        }
    } catch (error) {
        console.warn("Modules[contacts] properties are not present!");
        console.warn("Retrieving modules[contacts] properties...");
        lx.lionixCRM.getConfigOption("modules").then(function (data) {
            console.warn("Modules[contacts] successfully retrieved", data);
            lx.contact.resultsListDuplicatesHandler(false);
        });
    }
};

//Self-Invoking Anonymous Function Notation
// !function(){}();  easy to read, the result is unimportant.
// (function(){})();  like above but more parens.
// (function(){}());  Douglas Crockford's style when you need function results.
// Further reading: http://javascript.crockford.com/code.html then search for invoked immediately
!(function () {
    // create an observer instance
    // https://developer.mozilla.org/en/docs/Web/API/MutationObserver
    var observer = new MutationObserver(function (mutations) {
        if (mutations) {
            var crmEditView = document.forms["EditView"];
            if (crmEditView && !!crmEditView.module) {
                if (crmEditView.module.value == "Contacts") {
                    if (lx.lionixCRM.config.debuglx) {
                        console.warn(
                            "Bussines logic observer '%s' '%s' '%s' '%s'",
                            "contacts",
                            "lx-cedula-c.js",
                            "!function()",
                            "initial"
                        );
                    }
                    lx.contact.resultsSearchTSECRHandler(false);
                    lx.contact.resultsListDuplicatesHandler(false);
                }
            }
            // if needed only once, you can stop observing with observer.disconnect();
            // observer.disconnect();
        }
    });
    // Observer target
    var target = document.querySelector("#content");
    if (target) {
        // configuration of the observer:
        // NOTE: At the very least, childList, attributes, or characterData must be set to true. Otherwise, "An invalid or illegal string was specified" error is thrown.
        var config = {
            attributes: true,
            childList: true,
            // characterData: true,
            subtree: true,
        };
        // pass in the target node, as well as the observer options
        observer.observe(target, config);
    }
    // end observer
})();
//eof
<commit_msg>refactor: await for duplicates [ch225]<commit_after>//  This file containts opportunities bussines logic
//  function definitions section
lx.contact.renderContactDuplicates = function (duplicates) {
    console.warn("duplicados devueltos:", duplicates);
    $(".contact_duplicates ul li").remove();
    if (duplicates.data.length) {
        duplicates.data.forEach(function (element) {
            primary_address = {};
            element.emails.forEach(function (element) {
                if (element.primary_address === "1") {
                    primary_address.id = element.id;
                    primary_address.email_address = element.email_address;
                }
            });
            duplicate_detail = '<li id="' + element.id;
            duplicate_detail += '" data-account_id="' + element.accounts[0].id;
            duplicate_detail += '" data-cedula_c="' + element.cedula_c;
            duplicate_detail += '" data-first_name="' + element.first_name;
            duplicate_detail += '" data-last_name="' + element.last_name;
            duplicate_detail += '" data-lastname2_c="' + element.lastname2_c;
            duplicate_detail += '" data-phone_mobile="' + element.phone_mobile;
            duplicate_detail += '" data-phone_work="' + element.phone_work;
            duplicate_detail += '" data-title="' + element.title;
            duplicate_detail +=
                '" data-primary_email_address_id="' + primary_address.id;
            duplicate_detail +=
                '" data-primary_email_address="' +
                primary_address.email_address;
            duplicate_detail += '">';
            duplicate_detail +=
                element.first_name +
                " " +
                element.last_name +
                " " +
                element.lastname2_c +
                " " +
                element.cedula_c +
                " ";
            element.emails.forEach(function (element) {
                duplicate_detail += element.email_address + " ";
            });
            duplicate_detail += element.phone_mobile + " ";
            duplicate_detail += element.phone_work;
            // Client specific only fields
            // duplicate_detail += ' - ' + element.{fieldname};
            // Client specific only fields
            duplicate_detail += "
";
            $(".contact_duplicates ul").append(duplicate_detail);
        });
        newh = duplicates.data.length * 20 + 18; // last 18px bit is for duplicates title
        $(
            "#contact_duplicates_" + duplicates.fieldname + " .yui-ac-content"
        ).css("height", newh + "px");
        $(
            "#contact_duplicates_" + duplicates.fieldname + " .yui-ac-content"
        ).show(500);
        $(".contact_duplicates li").off("mouseover.contact_duplicates_list");
        $(".contact_duplicates li").on(
            "mouseover.contact_duplicates_list",
            function () {
                $(this).toggleClass("yui-ac-highlight");
                $(this).siblings("li").removeClass("yui-ac-highlight");
            }
        );
        $(".contact_duplicates li").off("click.contact_duplicates_list");
        $(".contact_duplicates li").on(
            "click.contact_duplicates_list",
            function () {
                $(".contact_duplicates .yui-ac-content").hide(500);
                console.warn(
                    "Redirecting to contacts Editview: - " +
                        window.location.origin +
                        window.location.pathname +
                        "?module=Contacts&return_module=Contacts&action=EditView&record=" +
                        this.id
                );
                toastr["info"](
                    "Redireccionando a " + $(this).data("first_name") + "...",
                    "Posibles duplicados encontrados",
                    {
                        positionClass: "toast-bottom-center",
                        showDuration: "0",
                        hideDuration: "0",
                        timeOut: "4000",
                        extendedTimeOut: "0",
                        progressBar: true,
                    }
                );
                window.location.href =
                    window.location.origin +
                    window.location.pathname +
                    "?module=Contacts&return_module=Contacts&action=EditView&record=" +
                    this.id;
            }
        );
    }
};

lx.contact.resultsSearchTSECRHandler = async function (forceCheck) {
    try {
        if (forceCheck) {
            lx.lionixCRM.config.modules = undefined;
            $("#cedula_c_lxajaxed").remove();
        }
        if ($("#cedula_c_lxajaxed").length == 0) {
            keyup_status = "disabled";
            $("#cedula_c").off("keyup.results_search_tsecr");
            if (lx.lionixCRM.config.modules.contacts.results_search_tsecr) {
                keyup_status = "enabled";
                $("#cedula_c").on(
                    "keyup.results_search_tsecr",
                    async function () {
                        if (lx.lionixCRM.config.debuglx) {
                            console.warn(
                                "key up ->",
                                String.fromCharCode(event.which)
                            );
                        }
                        if ($(this).val().length != 9) {
                            $("#first_name").val("");
                            $("#last_name").val("");
                            $("#lastname2_c").val("");
                        } else {
                            typed_cedula = $(this).val();
                            tsecrlist = await lx.lionixCRM.getTSECRData({
                                // Infoticos must be on same database server this SuiteCRM instance.
                                focusfieldname: this.id,
                                cedula_c: typed_cedula,
                            });
                            console.warn(
                                "After query to lx.lionixCRM.getTSECRData:",
                                tsecrlist
                            );
                            $("#cedula_c").val(tsecrlist.data[0].cedula_c);
                            $("#first_name").val(tsecrlist.data[0].first_name);
                            $("#last_name").val(tsecrlist.data[0].last_name);
                            $("#lastname2_c").val(
                                tsecrlist.data[0].lastname2_c
                            );
                            $("#first_name").focus();
                            $("#first_name").trigger("keypress");
                        }
                    }
                );
            }
            $("#cedula_c").append(
                '
'
            );
            console.warn(
                "keyup.results_search_tsecr on #cedula_c " + keyup_status
            );
        } else {
            if (lx.lionixCRM.config.debuglx) {
                console.warn(
                    `cedula_c_lxajaxed div indicator already exists and it's [${$(
                        "#cedula_c_lxajaxed"
                    ).data("results_search_tsecr")}].`
                );
            }
        }
    } catch (error) {
        console.error("Modules[contacts] properties are not present!");
        console.error("Retrieving modules[contacts] properties...");
        data = await lx.lionixCRM.getConfigOption("modules");
        console.error("Modules[contacts] successfully retrieved", data);
        lx.contact.resultsSearchTSECRHandler(false);
    }
};

lx.contact.resultsListDuplicatesHandler = function (forceCheck) {
    try {
        if (forceCheck) {
            lx.lionixCRM.config.modules = undefined;
            $("#full_name_lxajaxed").remove();
        }
        if ($("#full_name_lxajaxed").length == 0) {
            keyup_status = "disabled";
            $("#first_name, #last_name, #lastname2_c").off(
                "focusout.results_list_duplicates"
            );
            if (lx.lionixCRM.config.modules.contacts.results_list_duplicates) {
                keyup_status = "enabled";
                $("#first_name, #last_name, #lastname2_c").on(
                    "keypress.results_list_duplicates",
                    async function () {
                        ffn = $("#first_name");
                        fln = $("#last_name");
                        fln2 = $("#lastname2_c");
                        // femail = $('#Contacts0emailAddress0');
                        // fced = $('#cedula_c');
                        if (
                            $(ffn).val().length > 2 &&
                            ($(fln).val().length > 2 ||
                                $(fln2).val().length > 2)
                        ) {
                            if (
                                $("#contact_duplicates_" + this.id).length == 0
                            ) {
                                // width: 750px can be changed in each Client
                                width = lx.lionixCRM.config.modules.contacts
                                    .results_list_duplicates_width
                                    ? lx.lionixCRM.config.modules.contacts
                                          .results_list_duplicates_width
                                    : 750;
                                $(this).before(
                                    '

Posibles duplicados encontrados

'
                                );
                            }
                            $("#first_name, #last_name, #lastname2_c").off(
                                "focusout.results_list_duplicates"
                            );
                            $("#first_name, #last_name, #lastname2_c").on(
                                "focusout.results_list_duplicates",
                                function () {
                                    $(
                                        ".contact_duplicates .yui-ac-content"
                                    ).hide(500);
                                }
                            );
                            duplicates = await lx.lionixCRM.getContactDuplicates(
                                {
                                    fieldname: this.id,
                                    first_name: $(ffn).val(),
                                    last_name: $(fln).val(),
                                    lastname2_c: $(fln2).val(),
                                    // "cedula_c": $(fced).val(),
                                    // "email_address": $(femail).val()
                                }
                            );
                            lx.contact.renderContactDuplicates(duplicates);
                        }
                    }
                );
            }
            $("#cedula_c").append(
                '
'
            );
            console.warn(
                "keypress.results_list_duplicates on #first_name, #last_name and #lastname2_c " +
                    keyup_status
            );
        } else {
            if (lx.lionixCRM.config.debuglx) {
                console.warn(
                    "full_name_lxajaxed div indicator already exists and it's [" +
                        $("#full_name_lxajaxed").data(
                            "results_list_duplicates"
                        ) +
                        "]."
                );
            }
        }
    } catch (error) {
        console.warn("Modules[contacts] properties are not present!");
        console.warn("Retrieving modules[contacts] properties...");
        lx.lionixCRM.getConfigOption("modules").then(function (data) {
            console.warn("Modules[contacts] successfully retrieved", data);
            lx.contact.resultsListDuplicatesHandler(false);
        });
    }
};

//Self-Invoking Anonymous Function Notation
// !function(){}();  easy to read, the result is unimportant.
// (function(){})();  like above but more parens.
// (function(){}());  Douglas Crockford's style when you need function results.
// Further reading: http://javascript.crockford.com/code.html then search for invoked immediately
!(function () {
    // create an observer instance
    // https://developer.mozilla.org/en/docs/Web/API/MutationObserver
    var observer = new MutationObserver(function (mutations) {
        if (mutations) {
            var crmEditView = document.forms["EditView"];
            if (crmEditView && !!crmEditView.module) {
                if (crmEditView.module.value == "Contacts") {
                    if (lx.lionixCRM.config.debuglx) {
                        console.warn(
                            "Bussines logic observer '%s' '%s' '%s' '%s'",
                            "contacts",
                            "lx-cedula-c.js",
                            "!function()",
                            "initial"
                        );
                    }
                    lx.contact.resultsSearchTSECRHandler(false);
                    lx.contact.resultsListDuplicatesHandler(false);
                }
            }
            // if needed only once, you can stop observing with observer.disconnect();
            // observer.disconnect();
        }
    });
    // Observer target
    var target = document.querySelector("#content");
    if (target) {
        // configuration of the observer:
        // NOTE: At the very least, childList, attributes, or characterData must be set to true. Otherwise, "An invalid or illegal string was specified" error is thrown.
        var config = {
            attributes: true,
            childList: true,
            // characterData: true,
            subtree: true,
        };
        // pass in the target node, as well as the observer options
        observer.observe(target, config);
    }
    // end observer
})();
//eof
<|endoftext|>


<commit_before>K2.Knob = function(args) {
    if (arguments.length) {
        this.getready(args);
    }
};

K2.extend(K2.Knob, K2.UIElement);

K2.Knob.prototype.getready = function(args) {

    if (args === undefined) {
        throw new Error('Error: specArgs is undefined!');
    }

    // Call the constructor from the superclass.
    K2.Knob.superclass.getready.call(this, args);

    //now that all required properties have been inherited
    //from the parent class, define extra ones from this class

    //Default value is 0
    this.values = {'knobvalue' : 0};
    this.defaultSlot = 'knobvalue';

    this.sensitivity = args.sensitivity || 2000;
    this.imagesArray = args.imagesArray || null;

    // Can be 'atan' or 'updown'
    this.knobMethod = args.knobMethod || 'atan';

    var width = 0,
        height = 0;

    if (this.imagesArray.length < 1) {
        throw new Error('Invalid images array length, ' + this.imagesArray.length);
    }

    if (this.imagesArray.length == 1) {
        width = args.tileWidth;
        height = args.tileHeight;
        this.imageNum = args.imageNum;
    }

    else {
        this.imageNum = this.imagesArray.length;
        // Calculate maximum width and height.
        for (var i = 0, len = this.imagesArray.length; i < len; i += 1) {
            if (this.imagesArray[i].width > width) {
                width = this.imagesArray[i].width;
            }
            if (this.imagesArray[i].height > height) {
                height = this.imagesArray[i].height;
            }
        }
    }

    // Set them.
    this.setWidth(width);
    this.setHeight(height);

};

// This method returns an image index given the knob value.
K2.Knob.prototype.getImageNum = function() {
    if ((this.values.knobvalue < 0) || (this.values.knobvalue > 1)) {
        // Do nothing
        return undefined;
    }
    var ret = Math.round(this.values.knobvalue * (this.imageNum - 1));
    return ret;
};

K2.Knob.prototype.getImage = function() {

    var ret = this.getImageNum();
    return this.imagesArray[ret];
};

K2.Knob.prototype.calculateAngle = function (x,y) {

	var centerX = this.xOrigin + this.width / 2;
	var centerY = this.yOrigin + this.height / 2;

	console.log ("Point is: ", x, y, "Center is: ", centerX, centerY);

	var radtan = Math.atan2 (x - centerX, y - centerY);
	console.log('radiant atan ', radtan);

	var degreetan = radtan * (180 / Math.PI);
	degreetan = 180 - degreetan;
	console.log('degree atan ', degreetan);

	var range_val = K2.MathUtils.linearRange(0, 360, 0, 1, Math.floor(degreetan));
	return range_val;

};

// This method returns true if the point given belongs to this knob.
K2.Knob.prototype.isInROI = function(x, y) {
    if ((x > this.ROILeft) && (y > this.ROITop)) {
        if ((x < (this.ROILeft + this.ROIWidth)) && (y < (this.ROITop + this.ROIHeight))) {
            return true;
        }
    }
    return false;
};

K2.Knob.prototype.dragstart = K2.Knob.prototype.mousedown = K2.Knob.prototype.touchstart = function(x, y) {

    var inROI = this.isInROI(x, y);
    // Save the starting point if event happened in our ROI.
    if (inROI) {
        this.start_x = x;
        this.start_y = y;

        if (this.knobMethod === 'atan') {
            var range_val = this.calculateAngle (x,y);
            var ret = {'slot' : 'knobvalue', 'value' : range_val};
            return ret;
        }
    }

    // No value has been changed.
    return undefined;
};

K2.Knob.prototype.dragend = K2.Knob.prototype.mouseup = function(x, y) {

    // Reset the starting point.
    this.start_x = undefined;
    this.start_y = undefined;

    // No value has been changed
    return undefined;

};

K2.Knob.prototype.drag = K2.Knob.prototype.mousemove = function(curr_x, curr_y) {

	var ret;

	if (this.knobMethod === 'updown') {
		// TODO null or typeof
	    if ((this.start_x !== undefined) && (this.start_y !== undefined)) {

	        // This means that the mouse is currently down.
	        var deltaY = 0,
	            temp_value,
	            to_set;

	        deltaY = curr_y - this.start_y;

	        temp_value = this.values.knobvalue;

	        // Todo set sensitivity.
	        to_set = temp_value - deltaY / this.sensitivity;

	        if (to_set > 1) {
	            to_set = 1;
	        }
	        if (to_set < 0) {
	            to_set = 0;
	        }

	        ret = {'slot' : 'knobvalue', 'value' : to_set};

	        return ret;
	    }
	}

	else if (this.knobMethod === 'atan') {
		if ((this.start_x !== undefined) && (this.start_y !== undefined)) {
			var range_val = this.calculateAngle (curr_x, curr_y);
			ret = {'slot' : 'knobvalue', 'value' : range_val};
			return ret;
		}
	}

    // The mouse is currently up; ignore the event notify.
    return undefined;

};

// Setters
K2.Knob.prototype.setValue = function(slot, value) {
    var temp_value = value;

    if ((temp_value < 0) || (temp_value > 1)) {
        // Out of range; do not set
        return;
    }

    // Call the superclass
    K2.Knob.superclass.setValue.call(this, slot, value);

};

K2.Knob.prototype.refresh_CANVAS2D = function(engine) {

    // Draw if visible.
    if (this.isVisible === true) {
        if (this.imagesArray.length > 1) {
            // Get the image to draw
            var imageNum = this.getImageNum();
            // Draw the image on the canvas
            engine.context.drawImage(this.imagesArray[imageNum], this.xOrigin, this.yOrigin);
        }
        else if (this.imagesArray.length == 1) {
            var sx = 0;
            var sy = tileHeight * this.getImageNum();
            engine.context.drawImage(this.imagesArray[0], sx, sy, this.width, this.height, this.xOrigin, this.yOrigin, this.width, this.height);
        }
    }

};<commit_msg>Fixed a bug in Knob<commit_after>K2.Knob = function(args) {
    if (arguments.length) {
        this.getready(args);
    }
};

K2.extend(K2.Knob, K2.UIElement);

K2.Knob.prototype.getready = function(args) {

    if (args === undefined) {
        throw new Error('Error: specArgs is undefined!');
    }

    // Call the constructor from the superclass.
    K2.Knob.superclass.getready.call(this, args);

    //now that all required properties have been inherited
    //from the parent class, define extra ones from this class

    //Default value is 0
    this.values = {'knobvalue' : 0};
    this.defaultSlot = 'knobvalue';

    this.sensitivity = args.sensitivity || 2000;
    this.imagesArray = args.imagesArray || null;

    // Can be 'atan' or 'updown'
    this.knobMethod = args.knobMethod || 'atan';

    var width = 0,
        height = 0;

    if (this.imagesArray.length < 1) {
        throw new Error('Invalid images array length, ' + this.imagesArray.length);
    }

    if (this.imagesArray.length == 1) {
        width = args.tileWidth;
        height = args.tileHeight;
        this.imageNum = args.imageNum;
    }

    else {
        this.imageNum = this.imagesArray.length;
        // Calculate maximum width and height.
        for (var i = 0, len = this.imagesArray.length; i < len; i += 1) {
            if (this.imagesArray[i].width > width) {
                width = this.imagesArray[i].width;
            }
            if (this.imagesArray[i].height > height) {
                height = this.imagesArray[i].height;
            }
        }
    }

    // Set them.
    this.setWidth(width);
    this.setHeight(height);

};

// This method returns an image index given the knob value.
K2.Knob.prototype.getImageNum = function() {
    if ((this.values.knobvalue < 0) || (this.values.knobvalue > 1)) {
        // Do nothing
        return undefined;
    }
    var ret = Math.round(this.values.knobvalue * (this.imageNum - 1));
    return ret;
};

K2.Knob.prototype.getImage = function() {

    var ret = this.getImageNum();
    return this.imagesArray[ret];
};

K2.Knob.prototype.calculateAngle = function (x,y) {

	var centerX = this.xOrigin + this.width / 2;
	var centerY = this.yOrigin + this.height / 2;

	console.log ("Point is: ", x, y, "Center is: ", centerX, centerY);

	var radtan = Math.atan2 (x - centerX, y - centerY);
	console.log('radiant atan ', radtan);

	var degreetan = radtan * (180 / Math.PI);
	degreetan = 180 - degreetan;
	console.log('degree atan ', degreetan);

	var range_val = K2.MathUtils.linearRange(0, 360, 0, 1, Math.floor(degreetan));
	return range_val;

};

// This method returns true if the point given belongs to this knob.
K2.Knob.prototype.isInROI = function(x, y) {
    if ((x > this.ROILeft) && (y > this.ROITop)) {
        if ((x < (this.ROILeft + this.ROIWidth)) && (y < (this.ROITop + this.ROIHeight))) {
            return true;
        }
    }
    return false;
};

K2.Knob.prototype.dragstart = K2.Knob.prototype.mousedown = K2.Knob.prototype.touchstart = function(x, y) {

    var inROI = this.isInROI(x, y);
    // Save the starting point if event happened in our ROI.
    if (inROI) {
        this.start_x = x;
        this.start_y = y;

        if (this.knobMethod === 'atan') {
            var range_val = this.calculateAngle (x,y);
            var ret = {'slot' : 'knobvalue', 'value' : range_val};
            return ret;
        }
    }

    // No value has been changed.
    return undefined;
};

K2.Knob.prototype.dragend = K2.Knob.prototype.mouseup = function(x, y) {

    // Reset the starting point.
    this.start_x = undefined;
    this.start_y = undefined;

    // No value has been changed
    return undefined;

};

K2.Knob.prototype.drag = K2.Knob.prototype.mousemove = function(curr_x, curr_y) {

	var ret;

	if (this.knobMethod === 'updown') {
		// TODO null or typeof
	    if ((this.start_x !== undefined) && (this.start_y !== undefined)) {

	        // This means that the mouse is currently down.
	        var deltaY = 0,
	            temp_value,
	            to_set;

	        deltaY = curr_y - this.start_y;

	        temp_value = this.values.knobvalue;

	        // Todo set sensitivity.
	        to_set = temp_value - deltaY / this.sensitivity;

	        if (to_set > 1) {
	            to_set = 1;
	        }
	        if (to_set < 0) {
	            to_set = 0;
	        }

	        ret = {'slot' : 'knobvalue', 'value' : to_set};

	        return ret;
	    }
	}

	else if (this.knobMethod === 'atan') {
		if ((this.start_x !== undefined) && (this.start_y !== undefined)) {
			var range_val = this.calculateAngle (curr_x, curr_y);
			ret = {'slot' : 'knobvalue', 'value' : range_val};
			return ret;
		}
	}

    // The mouse is currently up; ignore the event notify.
    return undefined;

};

// Setters
K2.Knob.prototype.setValue = function(slot, value) {
    var temp_value = value;

    if ((temp_value < 0) || (temp_value > 1)) {
        // Out of range; do not set
        return;
    }

    // Call the superclass
    K2.Knob.superclass.setValue.call(this, slot, value);

};

K2.Knob.prototype.refresh_CANVAS2D = function(engine) {

    // Draw if visible.
    if (this.isVisible === true) {
        if (this.imagesArray.length > 1) {
            // Get the image to draw
            var imageNum = this.getImageNum();
            // Draw the image on the canvas
            engine.context.drawImage(this.imagesArray[imageNum], this.xOrigin, this.yOrigin);
        }
        else if (this.imagesArray.length == 1) {
            var sx = 0;
            var sy = this.height * this.getImageNum();
            engine.context.drawImage(this.imagesArray[0], sx, sy, this.width, this.height, this.xOrigin, this.yOrigin, this.width, this.height);
        }
    }

};<|endoftext|>