<commit_before>var debug = require('./debug'),
    appLogger = debug('App'),
    ProxyServer = require('./proxy-server'),
    PeerDiscovery = require('./peer-discovery'),
    Channel = require('./channel'),
    Peer = require('./peer'),
    networkUtils = require('./network-utils'),
    Promise = require('es6-promise').Promise,
    _ = require('lodash');

var App = function () {
  this.initialized = false;
};

App.prototype.init = function () {
  appLogger.info('init');

  if (this.initialized) {
    appLogger.warn('Already initialized');
    return;
  }

  networkUtils
    .findv4Ip(chrome.system.network.getNetworkInterfaces)
    .then(this.startWithPublicIp.bind(this), appLogger.error);
}

App.prototype.startWithPublicIp = function (publicIp) {
  appLogger.info('starting with public IP', publicIp);

  this.initialized = true;

  this.publicIp   = publicIp;
  this.publicPort = 0;

  this.localIp   = '127.0.0.1';
  this.localPort = 9009;

  // Channels that this proxy is participating in.
  // If a peer exists in either list, a channel
  // should be in here
  this.channels    = [];

  // All connected sockets on this machine
  this.localPeers  = [];

  // All remote peers that concern this proxy.
  // If no local peers exists for a channel then
  // any remote peers in that channel will be removed also.
  this.remotePeers = [];

  // A cache of adverts about peers on the network
  this.discoveryAdverts = [];

  // WebSocket connections to other proxies
  this.proxies = [];

  this.createLocalProxy();
  this.createExternalProxy()
    .then(function () {
      appLogger.log('External proxy ready with', this.publicPort);
      this.createPeerDiscovery();
    }.bind(this));
};

App.prototype.createLocalProxy = function () {
  /*
    Proxy server listens on well-known port 9009.
    Handles incoming websockets from the same device and routes
    them to where they needs to go.
  */
  var proxyLogger = debug('LocalProxy');
  this.proxyServer = new ProxyServer(this.localIp, this.localPort);
  this.proxyServer.on('connection', function (channelName, socket) {
    var channel = Channel.find(channelName, this.channels),
        peer;

    if (!channel) {
      channel = { name: channelName };
      this.channels.push(channel);
    }

    peer = Peer.create(channel, socket);

    proxyLogger.log('New local peer', peer);

    proxyLogger.log('before localPeers', this.localPeers.length);

    // FIX / TODO: this should be a subset of the peers that are in the channel
    Channel.connectPeers(peer, this.localPeers);
    this.localPeers.push(peer);

    // Broadcast local peer externally
    this.peerDiscovery.advertisePeer(peer);

    proxyLogger.log('after localPeers', this.localPeers.length);

    socket.addEventListener('message', function (evt) {
      proxyLogger.log('socket.message: ', evt);

      var locals = Channel.peers(channel, this.localPeers),
          remotes = Channel.peers(channel, this.remotePeers);

      proxyLogger.log('local peers', locals);
      proxyLogger.log('remote peers', remotes);

      var payload = {}, target;
      try {
        payload = JSON.parse(evt.data);
      } catch (err) {
        console.error('Error parsing message', err, evt);
      }

      if (payload.action === 'broadcast') {
        proxyLogger.log('Broadcast action: ', payload);
        // Send to local peers
        Channel.broadcastMessage(peer, locals, payload.data);
        // Send broadcast message to remote peers
        Channel.remoteBroadcastMessage(peer, remotes, payload.data);
      }
      else if (payload.action === 'message') {
        proxyLogger.log('Direct message action: ', payload);
        target = Peer.find(payload.target, this.localPeers);
        if (target) {
          proxyLogger.log('Sending to local peer: ', payload);
          Channel.directMessage(peer, target, payload.data);
          return;
        }

        target = Peer.find(payload.target, this.remotePeers);
        if (target) {
          proxyLogger.log('Sending to remote peer: ', payload);
          // Send message to remote peer
          Channel.directMessage(peer, target, payload.data);
          return;
        }

        proxyLogger.warn('Message for peer that cannot be found: ', payload);

        // FIXME: channel shouldn't be instance, should be data
        targetPeer = channel.getPeerById(payload.target);
        if (targetPeer) {
          targetPeer.send( protocol.message(peer, targetPeer, payload.data) );
        }
      }

    }.bind(this));

    socket.addEventListener('close', function (evt) {
      proxyLogger.log('socket.close: before remove', peer, this.localPeers.length, this.localPeers);

      // Remove this peer
      Peer.remove(peer, this.localPeers);

      proxyLogger.log('after remove', peer, this.localPeers.length, this.localPeers);

      // Disconnect localPeers in channel
      Channel.disconnectPeers(peer, Channel.peers(channel, this.localPeers));

      proxyLogger.log('Removed local peer', peer);

      // TODO: remove channel if no local peers left
      // TODO: close connection if no one using it

    }.bind(this));
  }.bind(this));
}

App.prototype.createExternalProxy = function () {
  return new Promise(function (resolve, reject) {
    /*
      External Proxy server listens on any available port and on
      the external interface.
      Handles incoming websockets from the other proxies and removes
      disconnections
    */
    var externalLogger = debug('ExternalProxy');
    this.externalServer = new ProxyServer(this.publicIp, this.publicPort);
    this.externalServer.on('ready', function (info) {
      externalLogger.log('has received public port', info);
      this.publicPort = info.localPort;
      resolve();
    }.bind(this));
    this.externalServer.on('connection', function (url, socket, request) {

      externalLogger.log('New external request', socket, url, request);

      var ip = request.headers.Host,
          proxy = _.find(this.proxies, { ip: ip, socket: socket });

      if (proxy) {
        throw Error('Proxy from ip ' + proxy.ip + ' already exists');
        return;
      }

      externalLogger.log('New connection from ip:', ip);
      proxy = { ip: ip, socket: socket };
      this.proxies.push(proxy);

      this.addHandlersForRemoteProxy(socket, externalLogger);

    }.bind(this));
  }.bind(this));
};

App.prototype.createPeerDiscovery = function () {
  var discoLogger = debug('Discovery');
  this.peerDiscovery = new PeerDiscovery(Peer.id());
  discoLogger.log('Starting with ', this.publicIp, this.publicPort);
  this.peerDiscovery.init(this.publicIp, this.publicPort);
  this.peerDiscovery.on('discover', function (record) {
    discoLogger.log('discover', record);
    // This channel will exist if a local peer is
    // bound to it
    var channel = Channel.find(record.channelName, this.channels),
        peer = Peer.find(record.peerId, this.remotePeers),
        proxy = _.find(this.proxies, { ip: record.ip }),
        socket;

    if (!channel) {
      discoLogger.log('no local peer bound to channel: ', record.channelName);
      this.discoveryAdverts.push(record);
      return;
    }

    if (peer) {
      discoLogger.log('remote peer already exists ', peer);
      return;
    }

    if (!proxy) {
      // Create proxy connection to this proxy
      socket = new WebSocket('ws://' + record.ip + ':' + record.port + '/remote');
      discoLogger.log('creating proxy connection to: ', record.ip + ':' + record.port);

      socket.addEventListener('open', function () {
        discoLogger.log('proxy connection open');
        proxy = { ip: record.ip, socket: socket };
        this.proxies.push(proxy);

        createRemotePeer.bind(this)();

        this.addHandlersForRemoteProxy(socket, discoLogger);
      }.bind(this));
    } else {
      createRemotePeer.bind(this)();
    }

    function createRemotePeer() {
      var peer = Peer.create(channel, socket, record.ip, record.peerId);
      this.remotePeers.push(peer);
      discoLogger.log('created remote peer', peer);
      // Connect remote peer to local peers and vice versa
      // FIXME: Find in channel
      Channel.connectPeers(peer, this.localPeers);
    };

  }.bind(this));
  this.peerDiscovery.on('query', function (reply) {
    discoLogger.log('query');
    // TODO: call reply to records
  }.bind(this));
};

App.prototype.addHandlersForRemoteProxy = function (socket, logger) {
  socket.addEventListener('message', function (evt) {
    logger.log('socket.message: ', evt);
    var payload = {}, target;
    try {
      payload = JSON.parse(evt.data);
    } catch (err) {
      console.error('Error parsing message', err, evt);
    }

    if (payload.action === 'broadcast') {
      logger.log('Broadcast action: ', payload);
      // find source peer in remotePeers
      var source = Peer.find(payload.source, this.remotePeers);

      if (!source) {
        logger.warn('Broadcast message from peer that is not in remote peers list', payload);
        return;
      }

      var channel = Channel.find(payload.channelName, this.channels),
          peers = Channel.peers(channel, this.localPeers);

      if (!channel) {
        logger.warn('Cannot find channel', payload.channelName, this.channels);
        return;
      }

      if (!peers || peers.length == 0) {
        logger.warn('No local peers for broadcast message', payload, peers);
        return;
      }

      // Send to all local peers in channel
      Channel.broadcastMessage(source, peers, payload.data);
    }
    else if (payload.action === 'message') {
      logger.log('Direct message action: ', payload, this.remotePeers);
      var source = Peer.find(payload.source, this.remotePeers);
      target = Peer.find(payload.target, this.localPeers);
      if (!source) {
         logger.log('Cannot find remote peer: ', source);
         return;
      }
      if (target) {
        logger.log('Sending to local peer: ', payload);
        Channel.directMessage(source, target, payload.data);
        return;
      }

      logger.warn('Message for peer that cannot be found: ', payload);
    }
    else if (payload.action === 'connect') {
      logger.log('Connect message action: ', payload);

      var channel = Channel.find(payload.channel, this.channels);

      if (!channel) {
        logger.warn('No local channel found', payload.channel);
      }

      var peer = Peer.find(payload.source, this.remotePeers);
      if (peer) {
        logger.warn('Connect message for existing remote peer', peer);
        return;
      }

      peer = Peer.create(channel, socket, payload.target);
      var target = Peer.find(payload.source, this.localPeers);
      if (!target) {
        logger.warn('Connect message target not found in local peers: ', payload, this.localPeers);
      } else {
        logger.log('Local target peer: ', target);
      }
      Channel.connectPeers(peer, [target]);
      this.remotePeers.push(peer);
      logger.log('Added remote peer: ', peer);
    }
  }.bind(this));

  socket.addEventListener('close', function (evt) {
    logger.log('socket.close, removing proxy connection');
    _.remove(this.proxies, { ip: ip });
    // TODO: Remove remote peers using this connection?
    // TODO: Notify local peers

  }.bind(this));
}

App.prototype.destroy = function () {
  appLogger.info('destroy');
};

module.exports = App;<commit_msg>Channel name<commit_after>var debug = require('./debug'),
    appLogger = debug('App'),
    ProxyServer = require('./proxy-server'),
    PeerDiscovery = require('./peer-discovery'),
    Channel = require('./channel'),
    Peer = require('./peer'),
    networkUtils = require('./network-utils'),
    Promise = require('es6-promise').Promise,
    _ = require('lodash');

var App = function () {
  this.initialized = false;
};

App.prototype.init = function () {
  appLogger.info('init');

  if (this.initialized) {
    appLogger.warn('Already initialized');
    return;
  }

  networkUtils
    .findv4Ip(chrome.system.network.getNetworkInterfaces)
    .then(this.startWithPublicIp.bind(this), appLogger.error);
}

App.prototype.startWithPublicIp = function (publicIp) {
  appLogger.info('starting with public IP', publicIp);

  this.initialized = true;

  this.publicIp   = publicIp;
  this.publicPort = 0;

  this.localIp   = '127.0.0.1';
  this.localPort = 9009;

  // Channels that this proxy is participating in.
  // If a peer exists in either list, a channel
  // should be in here
  this.channels    = [];

  // All connected sockets on this machine
  this.localPeers  = [];

  // All remote peers that concern this proxy.
  // If no local peers exists for a channel then
  // any remote peers in that channel will be removed also.
  this.remotePeers = [];

  // A cache of adverts about peers on the network
  this.discoveryAdverts = [];

  // WebSocket connections to other proxies
  this.proxies = [];

  this.createLocalProxy();
  this.createExternalProxy()
    .then(function () {
      appLogger.log('External proxy ready with', this.publicPort);
      this.createPeerDiscovery();
    }.bind(this));
};

App.prototype.createLocalProxy = function () {
  /*
    Proxy server listens on well-known port 9009.
    Handles incoming websockets from the same device and routes
    them to where they needs to go.
  */
  var proxyLogger = debug('LocalProxy');
  this.proxyServer = new ProxyServer(this.localIp, this.localPort);
  this.proxyServer.on('connection', function (channelName, socket) {
    var channel = Channel.find(channelName, this.channels),
        peer;

    if (!channel) {
      channel = { name: channelName };
      this.channels.push(channel);
    }

    peer = Peer.create(channel, socket);

    proxyLogger.log('New local peer', peer);

    proxyLogger.log('before localPeers', this.localPeers.length);

    // FIX / TODO: this should be a subset of the peers that are in the channel
    Channel.connectPeers(peer, this.localPeers);
    this.localPeers.push(peer);

    // Broadcast local peer externally
    this.peerDiscovery.advertisePeer(peer);

    proxyLogger.log('after localPeers', this.localPeers.length);

    socket.addEventListener('message', function (evt) {
      proxyLogger.log('socket.message: ', evt);

      var locals = Channel.peers(channel, this.localPeers),
          remotes = Channel.peers(channel, this.remotePeers);

      proxyLogger.log('local peers', locals);
      proxyLogger.log('remote peers', remotes);

      var payload = {}, target;
      try {
        payload = JSON.parse(evt.data);
      } catch (err) {
        console.error('Error parsing message', err, evt);
      }

      if (payload.action === 'broadcast') {
        proxyLogger.log('Broadcast action: ', payload);
        // Send to local peers
        Channel.broadcastMessage(peer, locals, payload.data);
        // Send broadcast message to remote peers
        Channel.remoteBroadcastMessage(peer, remotes, payload.data);
      }
      else if (payload.action === 'message') {
        proxyLogger.log('Direct message action: ', payload);
        target = Peer.find(payload.target, this.localPeers);
        if (target) {
          proxyLogger.log('Sending to local peer: ', payload);
          Channel.directMessage(peer, target, payload.data);
          return;
        }

        target = Peer.find(payload.target, this.remotePeers);
        if (target) {
          proxyLogger.log('Sending to remote peer: ', payload);
          // Send message to remote peer
          Channel.directMessage(peer, target, payload.data);
          return;
        }

        proxyLogger.warn('Message for peer that cannot be found: ', payload);

        // FIXME: channel shouldn't be instance, should be data
        targetPeer = channel.getPeerById(payload.target);
        if (targetPeer) {
          targetPeer.send( protocol.message(peer, targetPeer, payload.data) );
        }
      }

    }.bind(this));

    socket.addEventListener('close', function (evt) {
      proxyLogger.log('socket.close: before remove', peer, this.localPeers.length, this.localPeers);

      // Remove this peer
      Peer.remove(peer, this.localPeers);

      proxyLogger.log('after remove', peer, this.localPeers.length, this.localPeers);

      // Disconnect localPeers in channel
      Channel.disconnectPeers(peer, Channel.peers(channel, this.localPeers));

      proxyLogger.log('Removed local peer', peer);

      // TODO: remove channel if no local peers left
      // TODO: close connection if no one using it

    }.bind(this));
  }.bind(this));
}

App.prototype.createExternalProxy = function () {
  return new Promise(function (resolve, reject) {
    /*
      External Proxy server listens on any available port and on
      the external interface.
      Handles incoming websockets from the other proxies and removes
      disconnections
    */
    var externalLogger = debug('ExternalProxy');
    this.externalServer = new ProxyServer(this.publicIp, this.publicPort);
    this.externalServer.on('ready', function (info) {
      externalLogger.log('has received public port', info);
      this.publicPort = info.localPort;
      resolve();
    }.bind(this));
    this.externalServer.on('connection', function (url, socket, request) {

      externalLogger.log('New external request', socket, url, request);

      var ip = request.headers.Host,
          proxy = _.find(this.proxies, { ip: ip, socket: socket });

      if (proxy) {
        throw Error('Proxy from ip ' + proxy.ip + ' already exists');
        return;
      }

      externalLogger.log('New connection from ip:', ip);
      proxy = { ip: ip, socket: socket };
      this.proxies.push(proxy);

      this.addHandlersForRemoteProxy(socket, externalLogger);

    }.bind(this));
  }.bind(this));
};

App.prototype.createPeerDiscovery = function () {
  var discoLogger = debug('Discovery');
  this.peerDiscovery = new PeerDiscovery(Peer.id());
  discoLogger.log('Starting with ', this.publicIp, this.publicPort);
  this.peerDiscovery.init(this.publicIp, this.publicPort);
  this.peerDiscovery.on('discover', function (record) {
    discoLogger.log('discover', record);
    // This channel will exist if a local peer is
    // bound to it
    var channel = Channel.find(record.channelName, this.channels),
        peer = Peer.find(record.peerId, this.remotePeers),
        proxy = _.find(this.proxies, { ip: record.ip }),
        socket;

    if (!channel) {
      discoLogger.log('no local peer bound to channel: ', record.channelName);
      this.discoveryAdverts.push(record);
      return;
    }

    if (peer) {
      discoLogger.log('remote peer already exists ', peer);
      return;
    }

    if (!proxy) {
      // Create proxy connection to this proxy
      socket = new WebSocket('ws://' + record.ip + ':' + record.port + '/remote');
      discoLogger.log('creating proxy connection to: ', record.ip + ':' + record.port);

      socket.addEventListener('open', function () {
        discoLogger.log('proxy connection open');
        proxy = { ip: record.ip, socket: socket };
        this.proxies.push(proxy);

        createRemotePeer.bind(this)();

        this.addHandlersForRemoteProxy(socket, discoLogger);
      }.bind(this));
    } else {
      createRemotePeer.bind(this)();
    }

    function createRemotePeer() {
      var peer = Peer.create(channel, socket, record.ip, record.peerId);
      this.remotePeers.push(peer);
      discoLogger.log('created remote peer', peer);
      // Connect remote peer to local peers and vice versa
      // FIXME: Find in channel
      Channel.connectPeers(peer, this.localPeers);
    };

  }.bind(this));
  this.peerDiscovery.on('query', function (reply) {
    discoLogger.log('query');
    // TODO: call reply to records
  }.bind(this));
};

App.prototype.addHandlersForRemoteProxy = function (socket, logger) {
  socket.addEventListener('message', function (evt) {
    logger.log('socket.message: ', evt);
    var payload = {}, target;
    try {
      payload = JSON.parse(evt.data);
    } catch (err) {
      console.error('Error parsing message', err, evt);
    }

    if (payload.action === 'broadcast') {
      logger.log('Broadcast action: ', payload);
      // find source peer in remotePeers
      var source = Peer.find(payload.source, this.remotePeers);

      if (!source) {
        logger.warn('Broadcast message from peer that is not in remote peers list', payload);
        return;
      }

      var channel = Channel.find(payload.channel, this.channels),
          peers = Channel.peers(channel, this.localPeers);

      if (!channel) {
        logger.warn('Cannot find channel', payload.channel, this.channels);
        return;
      }

      if (!peers || peers.length == 0) {
        logger.warn('No local peers for broadcast message', payload, peers);
        return;
      }

      // Send to all local peers in channel
      Channel.broadcastMessage(source, peers, payload.data);
    }
    else if (payload.action === 'message') {
      logger.log('Direct message action: ', payload, this.remotePeers);
      var source = Peer.find(payload.source, this.remotePeers);
      target = Peer.find(payload.target, this.localPeers);
      if (!source) {
         logger.log('Cannot find remote peer: ', source);
         return;
      }
      if (target) {
        logger.log('Sending to local peer: ', payload);
        Channel.directMessage(source, target, payload.data);
        return;
      }

      logger.warn('Message for peer that cannot be found: ', payload);
    }
    else if (payload.action === 'connect') {
      logger.log('Connect message action: ', payload);

      var channel = Channel.find(payload.channel, this.channels);

      if (!channel) {
        logger.warn('No local channel found', payload.channel);
      }

      var peer = Peer.find(payload.source, this.remotePeers);
      if (peer) {
        logger.warn('Connect message for existing remote peer', peer);
        return;
      }

      peer = Peer.create(channel, socket, payload.target);
      var target = Peer.find(payload.source, this.localPeers);
      if (!target) {
        logger.warn('Connect message target not found in local peers: ', payload, this.localPeers);
      } else {
        logger.log('Local target peer: ', target);
      }
      Channel.connectPeers(peer, [target]);
      this.remotePeers.push(peer);
      logger.log('Added remote peer: ', peer);
    }
  }.bind(this));

  socket.addEventListener('close', function (evt) {
    logger.log('socket.close, removing proxy connection');
    _.remove(this.proxies, { ip: ip });
    // TODO: Remove remote peers using this connection?
    // TODO: Notify local peers

  }.bind(this));
}

App.prototype.destroy = function () {
  appLogger.info('destroy');
};

module.exports = App;<|endoftext|>


<commit_before>module.exports = function(load) {
    var categories = []

    // setup vars
    var class_id

    // if set to load only out of combat
    if (load.hasOwnProperty('use_combat') && !load.use_combat)
        categories.push('gen6')

    // check load requirements by class/spec
    // if any specs are selected without a class, or with multiple classes, we're just going to ignore them

    // if single class is selected
    if (load['class'] && load['class'].single) {
        class_id = getClassCategory(load['class'].single)
        if (class_id) {
            categories.push(class_id)
            if (load.use_spec && load['spec'] && load['spec'].single)
                categories.push(class_id+'-'+load['spec'].single)
            else if (load.use_spec && load['spec'] && load['spec'].multi.length>0) {
                for (var i=0; i<load['spec'].multi.length; i++) {
                    if (load['spec'].multi[i])
                        categories.push(class_id+'-'+i)
                }
            }
        }
    }

    // if multi-select class is used
    else if (load.use_class && load['class'] && load['class'].multi) {
        var list = []
        for (var classKey in load['class'].multi) {
            if (!load['class'].multi.hasOwnProperty(classKey)) continue
            if (load['class'].multi[classKey]) {
                class_id = getClassCategory(load['class'].single)
                if (class_id) {
                    categories.push(class_id)
                    list.push(class_id)
                }
            }
        }
        // if only one class is selected we can still check for specs
        if (list.length==1) {
            if (load.use_spec && load['spec'] && load['spec'].single)
                categories.push(class_id+'-'+load['spec'].single)
            else if (load.use_spec && load['spec'] && load['spec'].multi.length>0) {
                for (var i=0; i<load['spec'].multi.length; i++) {
                    if (load['spec'].multi[i])
                        categories.push(class_id+'-'+i)
                }
            }
        }
    }

    // check load-on-encounter ID
    if (load.use_encounterid && load.encounterid>0) {
        var raid = getEncounterCategory(id)
        if (raid.indexOf('raiden')==0)
            categories.push('raiden')
        else if (raid.indexOf('raidnh')==0)
            categories.push('raidnh')

        categories.push(raid)
    }

    return categories
}

function getClassCategory(str) {
    switch(str) {
        case 'DEATHKNIGHT':
            return 'cl6'
        case 'DEMONHUNTER':
            return 'cl12'
        case 'DRUID':
            return 'cl11'
        case 'HUNTER':
            return 'cl3'
        case 'MAGE':
            return 'cl8'
        case 'MONK':
            return 'cl10'
        case 'PALADIN':
            return 'cl2'
        case 'PRIEST':
            return 'cl5'
        case 'ROGUE':
            return 'cl4'
        case 'SHAMAN':
            return 'cl7'
        case 'WARLOCK':
            return 'cl9'
        case 'WARRIOR':
            return 'cl1'
    }
    return false
}

function getEncounterCategory(id) {
    switch (id) {
        case 1853:
            return 'raiden1'
        case 1876:
            return 'raiden4'
        case 1873:
            return 'raiden2'
        case 1841:
            return 'raiden5'
        case 1854:
            return 'raiden6'
        case 1877:
            return 'raiden7'
        case 1864:
            return 'raiden8'
        case 1849:
            return 'raidnh1'
        case 1865:
            return 'raidnh2'
        case 1867:
            return 'raidnh3'
        case 1871:
            return 'raidnh4'
        case 1862:
            return 'raidnh5'
        case 1842:
            return 'raidnh6'
        case 1886:
            return 'raidnh7'
        case 1863:
            return 'raidnh8'
        case 1872:
            return 'raidnh9'
        case 1866:
            return 'raidnh10'
    }
}
<commit_msg>Real fix<commit_after>module.exports = function(load) {
    var categories = []

    // setup vars
    var class_id

    // if set to load only out of combat
    if (load.hasOwnProperty('use_combat') && !load.use_combat)
        categories.push('gen6')

    // check load requirements by class/spec
    // if any specs are selected without a class, or with multiple classes, we're just going to ignore them

    // if single class is selected
    if (load['class'] && load['class'].single) {
        class_id = getClassCategory(load['class'].single)
        if (class_id) {
            categories.push(class_id)
            if (load.use_spec && load['spec'] && load['spec'].single)
                categories.push(class_id+'-'+load['spec'].single)
            else if (load.use_spec && load['spec'] && load['spec'].multi.length>0) {
                for (var i=0; i<load['spec'].multi.length; i++) {
                    if (load['spec'].multi[i])
                        categories.push(class_id+'-'+i)
                }
            }
        }
    }

    // if multi-select class is used
    else if (load.use_class && load['class'] && load['class'].multi) {
        var list = []
        console.error('aa')
        for (var classKey in load['class'].multi) {
        console.error('key', classKey)
            if (!load['class'].multi.hasOwnProperty(classKey)) continue

        console.error('has class',classKey)
            if (load['class'].multi[classKey]) {
                class_id = getClassCategory(classKey)
                if (class_id) {
                    categories.push(class_id)
                    list.push(class_id)
                }
            }
        }
        // if only one class is selected we can still check for specs
        if (list.length==1) {
            if (load.use_spec && load['spec'] && load['spec'].single)
                categories.push(class_id+'-'+load['spec'].single)
            else if (load.use_spec && load['spec'] && load['spec'].multi.length>0) {
                for (var i=0; i<load['spec'].multi.length; i++) {
                    if (load['spec'].multi[i])
                        categories.push(class_id+'-'+i)
                }
            }
        }
    }

    // check load-on-encounter ID
    if (load.use_encounterid && load.encounterid>0) {
        var raid = getEncounterCategory(id)
        if (raid.indexOf('raiden')==0)
            categories.push('raiden')
        else if (raid.indexOf('raidnh')==0)
            categories.push('raidnh')

        categories.push(raid)
    }

    return categories
}

function getClassCategory(str) {
    switch(str) {
        case 'DEATHKNIGHT':
            return 'cl6'
        case 'DEMONHUNTER':
            return 'cl12'
        case 'DRUID':
            return 'cl11'
        case 'HUNTER':
            return 'cl3'
        case 'MAGE':
            return 'cl8'
        case 'MONK':
            return 'cl10'
        case 'PALADIN':
            return 'cl2'
        case 'PRIEST':
            return 'cl5'
        case 'ROGUE':
            return 'cl4'
        case 'SHAMAN':
            return 'cl7'
        case 'WARLOCK':
            return 'cl9'
        case 'WARRIOR':
            return 'cl1'
    }
    return false
}

function getEncounterCategory(id) {
    switch (id) {
        case 1853:
            return 'raiden1'
        case 1876:
            return 'raiden4'
        case 1873:
            return 'raiden2'
        case 1841:
            return 'raiden5'
        case 1854:
            return 'raiden6'
        case 1877:
            return 'raiden7'
        case 1864:
            return 'raiden8'
        case 1849:
            return 'raidnh1'
        case 1865:
            return 'raidnh2'
        case 1867:
            return 'raidnh3'
        case 1871:
            return 'raidnh4'
        case 1862:
            return 'raidnh5'
        case 1842:
            return 'raidnh6'
        case 1886:
            return 'raidnh7'
        case 1863:
            return 'raidnh8'
        case 1872:
            return 'raidnh9'
        case 1866:
            return 'raidnh10'
    }
}
<|endoftext|>


<commit_before>Notifier = {

  did_add_new_event: function(ev) {
    Event.improve(ev);
    // we only notify on items that are latched to us.  TODO: turn back on
    // if (!ev.re || ev.re.resource().architect != This.user.vtag) return;

    if (ev.atype == 'error')        Notifier.error( ev.msg );

    // don't report if we're watching the thing
    if (ev.re == This.item) return;
    var go = ev.item_tag;

    if (ev.atype == 'signup')       Notifier.growl( go, ev.actor_title + " signed up!" );
    if (ev.atype == 'reported')     Notifier.growl( go, ev.actor_title + " reports: “"+ ev.msg   +"”" );
    if (ev.atype == 'answered')     Notifier.growl( go, ev.actor_title + " responded: “"+ ev.msg +"”" );
    if (ev.atype == 'answered_yes') Notifier.growl( go, ev.actor_title + " answered yes" );
    if (ev.atype == 'answered_no')  Notifier.growl( go, ev.actor_title + " answered no" );
    if (ev.atype == 'accepted')     Notifier.growl( go, ev.actor_title + " has accepted your assignment" );
    if (ev.atype == 'declined')     Notifier.growl( go, ev.actor_title + " has declined your assignment" );
    if (ev.atype == 'completed')    Notifier.growl( go, ev.actor_title + " has completed your assignment" );
    if (ev.atype == 'appreciated')  Notifier.growl( go, ev.actor_title + " has appreciated you" );
    if (ev.atype == 'blocked')      Notifier.growl( go, ev.actor_title + " has blocked you" );
  },

  success: function(msg, header) {
    if (!header) header = 'Sent';
    Notifier.growl(null, msg, {
      header: header,
      life: 10*1000,
      glue: 'before',
      theme: 'success'
    });
  },

  error: function(msg) {
    Notifier.growl(null, msg, {
      header: 'Error',
      life: 20*1000,
      glue: 'before',
      theme: 'error'
    });
  },

  growl_defaults: {
    life: 15*1000,
    open: function(e,m,o){ $(e).app_paint(); }
  },

  growl: function(go, msg, options){
    options = $.extend({}, this.growl_defaults, options);
    if (go) msg = ""+msg+"";
    $.jGrowl(msg, options);
  }

};
<commit_msg>add actor names to error growls<commit_after>Notifier = {

  did_add_new_event: function(ev) {
    Event.improve(ev);
    var go = ev.item_tag;
    // we only notify on items that are latched to us.  TODO: turn back on
    // if (!ev.re || ev.re.resource().architect != This.user.vtag) return;

    if (ev.atype == 'error')        Notifier.error( go, ev.msg, ev.actor_title );

    // don't report if we're watching the thing
    if (ev.re == This.item) return;

    if (ev.atype == 'signup')       Notifier.growl( go, ev.actor_title + " signed up!" );
    if (ev.atype == 'reported')     Notifier.growl( go, ev.actor_title + " reports: “"+ ev.msg   +"”" );
    if (ev.atype == 'answered')     Notifier.growl( go, ev.actor_title + " responded: “"+ ev.msg +"”" );
    if (ev.atype == 'answered_yes') Notifier.growl( go, ev.actor_title + " answered yes" );
    if (ev.atype == 'answered_no')  Notifier.growl( go, ev.actor_title + " answered no" );
    if (ev.atype == 'accepted')     Notifier.growl( go, ev.actor_title + " has accepted your assignment" );
    if (ev.atype == 'declined')     Notifier.growl( go, ev.actor_title + " has declined your assignment" );
    if (ev.atype == 'completed')    Notifier.growl( go, ev.actor_title + " has completed your assignment" );
    if (ev.atype == 'appreciated')  Notifier.growl( go, ev.actor_title + " has appreciated you" );
    if (ev.atype == 'blocked')      Notifier.growl( go, ev.actor_title + " has blocked you" );
  },

  success: function(msg, header) {
    if (!header) header = 'Sent';
    Notifier.growl(null, msg, {
      header: header,
      life: 10*1000,
      glue: 'before',
      theme: 'success'
    });
  },

  error: function(go, msg, actor) {
    header = actor ? 'Error for ' + actor : 'Error';
    Notifier.growl(go, msg, {
      header: header,
      life: 25*1000,
      glue: 'before',
      theme: 'error'
    });
  },

  growl_defaults: {
    life: 15*1000,
    open: function(e,m,o){ $(e).app_paint(); }
  },

  growl: function(go, msg, options){
    options = $.extend({}, this.growl_defaults, options);
    if (go) msg = ""+msg+"";
    $.jGrowl(msg, options);
  }

};
<|endoftext|>


<commit_before>export const weapons = require('./items/weapons.json');

const map = {
  location: {row:5,col:0},
  // "http://bit.ly/2d4jS28"  http://bit.ly/2dcQUM4
  //http://wallpapercave.com/sci-fi-background
  //http://bit.ly/2d4jS28
  //http://bit.ly/2dcQUM4
//https://s-media-cache-ak0.pinimg.com/originals/e8/15/87/e81587a6b72b12019e3f65450070a6c4.jpg

  // images:[[ "photos/artHere.png", "http://i.imgur.com/gOqnUMH.png", "https://wallpaperscraft.com/image/canyon_desert_horseback_rider_wild_west_cowboy_45538_2048x2048.jpg"],

  images:[[ 'office', "code1", "wildWest"],
  ["code2", "http://wallpapercave.com/wp/565sgAQ.jpg", "http://bit.ly/2cGiroJ"],
  ["fantasy", "code3", "http://cdn.wallpapersafari.com/16/58/qDXKtC.jpg"],
  ["https://hikemtshasta.files.wordpress.com/2013/04/cascades-plutos-cave-feb2013-047-copy-custom.jpg"],

  [],
  ['start', "artHere", "findArtOnline"]
  ],

  items: [[{name: "god-tier Sword", type: "meele", dmg: 12, stat: "str", equip: "rightHand"},{},{},{},{},{},{},{},{}],
  [],
  [],
  [],
  [],
  ['']],
  descriptions: [["description1", "description2", "description3", "description4", "description5", "description6", "description7", "description8", "description9"],
  [],
  [],
  [],
  [],
  []],
  enemyIds: [["3", "2", "1"],
  ["0","2"],
  ["1"],
  [],
  [],
  ["0","",""]],

  features: [["", "spells", ""],
  [],
  ["", "inventory", ""],
  [],
  [],
  ["","health","actions"]],

  easterEggs:[[[{className:"clippy", image:"https://media.giphy.com/media/XbPoIsyy9xqjS/200.gif"}] ,"",[{image:"http://i.imgur.com/f2rt3Zy.png", sound:"https://a.clyp.it/mq5rd1d1.mp3", className:"bang"}]],

  [[],[{image:"http://i.imgur.com/5kyJyll.png", sound:"https://a.clyp.it/cn4un2pr.mp3", className:"pew"},{image:'http://bestanimations.com/Sci-Fi/UFOs/ufo-flying-saucer-animated-gif-14.gif', className: 'spaceship'},{image: 'http://bestanimations.com/Sci-Fi/UFOs/UFO-12-june.gif', className: 'spaceship2'},{image: 'http://bestanimations.com/Sci-Fi/UFOs/UFO-08-june.gif',className: 'spaceship3'}]],
  [[{image: "http://bestanimations.com/Fantasy/Dragons/dragon-animated-gif-40.gif",className: 'dragon', mapSend:[3,0]},{image: 'http://bestanimations.com/Fantasy/bow-warrior-medieval-animation.gif', className: 'archer'},{image:'http://bestanimations.com/Fantasy/knights-fighting-medieval-animation.gif',className: 'knights'}],[],[{className:"flappy",image:"http://bestanimations.com/Animals/Reptiles/Dinosaurs/Dinosaur-10-june.gif"},{sound:"https://a.clyp.it/o2x1rwjo.mp3", className:"thriller", image:"http://bestanimations.com/Animals/Reptiles/Dinosaurs/dinosaur-animated-gif-8.gif"},{image:'http://bestanimations.com/Animals/Reptiles/Dinosaurs/Dinosaur-01-june.gif',className: 'rawr',sound:"https://a.clyp.it/sspvhmed.mp3"},{className:"trice",image:"http://bestanimations.com/Animals/Reptiles/Dinosaurs/dinosaur-animated-gif-1.gif", sound:"https://a.clyp.it/hblpp0cn.mp3"}]],

  [[{image:'http://bestanimations.com/Fantasy/knight-fighting-diablo-deamon-animation.gif',className:'caveFight'}]],
  [],
  [[],[{image:"http://i.imgur.com/A2DDh3m.png"},{image:"http://i.imgur.com/xrOJYnr.png"}],[{image:"http://i.imgur.com/PBaKOvT.png"}]]
  ],

  messages:[["The year is 3058 according to a select few record keepers. New age hipsters and Talking Mimes have taken over the world and declared time as relative, banning the recording of time and erasing history as we know it. Use your time travel ability to click around our map to different era's and prove that history did happen!",
  "[Selim]: What if we tried an old western theme instead? [Alex]: That makes no sense with magic in the game [Selim]: Oh, and steampunk does?? [Alex]: But steampunk is so coooooool!!!",
"Woah! Cowboy steampunk? Will will smith smith a giant robot spider? Yes, I think Will smith will smith a giant robot spider[giant robot spider item] "],

["[Alex]:Oooo ya Know what would be cooler than fantasy? STEAMPUNK!!! [Harp]: What?! That doesn't make any sense with magic in the game! [Alex]: Fine then, you just don't have to visit steampunk-theme then ",
"[Alex]Hmm, so we made progress on our maps, but our game features aren't done.. Quick, we need a storyline to cover this up! [Harp] I got it!...The year is 3058 according to a select few record keepers. New age hipsters and Talking Mimes have taken over the world and declared time as relative, banning the recording of time and erasing history as we know it. Use your time travel ability to click around our map to different era's to prove history happened, and collect items to battle the Talking Mime and his henchmen.",
"Howdy pardner, them high-fulutin software developers don't know how to decide on a theme! Why don't you click on that gun over there?"],

["[Talking Mime] My army of Talking Mime's has set upon your castle! We all watched a Charlie Chaplin flick to drive us into a rage!! We are the voice for the voiceless!! I dare you to stop my attack. [Instruction] Find the best way to escape the attack on your castle and battle the talking mime!",
"[Alex]:Fantasy sucks so much man, might as well make a game that has DINOSAURS in it.  [Harp]: Please tell me your not making this game have dinosaurs in it... ",
""
],

["This is a cave!!!!"],
[],
["Hello! We've updated our map recently, I hope you like it. Ufortunately, we forgot to finish the battle page, maybe you could find the missing pieces in here?","Harp: Great news! I convinced the development team to make this a fantasy themed game. I was outnumbered, but like any hobbit knows, size doesn't matter!", "Alex: PFT! Fantasy? Get a grip on reality man! As 'Lead Engineer' I declare this a Sci Fi game. Welcome to the future! "]],

  riddles:[[],
  ["",{question:" Solve this riddle and get that fancy space gun: the last man on the earth is locked in a room, he hears a knock on the door, who could it be?", answer:"woman", reward:weapons["LAZER_GUN"], className:"sciRiddle", solved:false}],
  [],
  [],
  [],
  []
  ]
}

export default map;<commit_msg>naming<commit_after>export const weapons = require('./items/weapons.json');

const map = {
  location: {row:5,col:0},
  // "http://bit.ly/2d4jS28"  http://bit.ly/2dcQUM4
  //http://wallpapercave.com/sci-fi-background
  //http://bit.ly/2d4jS28
  //http://bit.ly/2dcQUM4
//https://s-media-cache-ak0.pinimg.com/originals/e8/15/87/e81587a6b72b12019e3f65450070a6c4.jpg

  // images:[[ "photos/artHere.png", "http://i.imgur.com/gOqnUMH.png", "https://wallpaperscraft.com/image/canyon_desert_horseback_rider_wild_west_cowboy_45538_2048x2048.jpg"],

  images:[[ 'office', "code1", "wildWest"],
  ["code2", "sciFi", "http://bit.ly/2cGiroJ"],
  ["fantasy", "code3", "dinosaurs"],
  ["cave"],

  [],
  ['start', "artHere", "findArtOnline"]
  ],

  items: [[{name: "god-tier Sword", type: "meele", dmg: 12, stat: "str", equip: "rightHand"},{},{},{},{},{},{},{},{}],
  [],
  [],
  [],
  [],
  ['']],
  descriptions: [["description1", "description2", "description3", "description4", "description5", "description6", "description7", "description8", "description9"],
  [],
  [],
  [],
  [],
  []],
  enemyIds: [["3", "2", "1"],
  ["0","2"],
  ["1"],
  [],
  [],
  ["0","",""]],

  features: [["", "spells", ""],
  [],
  ["", "inventory", ""],
  [],
  [],
  ["","health","actions"]],

  easterEggs:[[[{className:"clippy", image:"https://media.giphy.com/media/XbPoIsyy9xqjS/200.gif"}] ,"",[{image:"http://i.imgur.com/f2rt3Zy.png", sound:"https://a.clyp.it/mq5rd1d1.mp3", className:"bang"}]],

  [[],[{image:"http://i.imgur.com/5kyJyll.png", sound:"https://a.clyp.it/cn4un2pr.mp3", className:"pew"},{image:'http://bestanimations.com/Sci-Fi/UFOs/ufo-flying-saucer-animated-gif-14.gif', className: 'spaceship'},{image: 'http://bestanimations.com/Sci-Fi/UFOs/UFO-12-june.gif', className: 'spaceship2'},{image: 'http://bestanimations.com/Sci-Fi/UFOs/UFO-08-june.gif',className: 'spaceship3'}]],
  [[{image: "http://bestanimations.com/Fantasy/Dragons/dragon-animated-gif-40.gif",className: 'dragon', mapSend:[3,0]},{image: 'http://bestanimations.com/Fantasy/bow-warrior-medieval-animation.gif', className: 'archer'},{image:'http://bestanimations.com/Fantasy/knights-fighting-medieval-animation.gif',className: 'knights'}],[],[{className:"flappy",image:"http://bestanimations.com/Animals/Reptiles/Dinosaurs/Dinosaur-10-june.gif"},{sound:"https://a.clyp.it/o2x1rwjo.mp3", className:"thriller", image:"http://bestanimations.com/Animals/Reptiles/Dinosaurs/dinosaur-animated-gif-8.gif"},{image:'http://bestanimations.com/Animals/Reptiles/Dinosaurs/Dinosaur-01-june.gif',className: 'rawr',sound:"https://a.clyp.it/sspvhmed.mp3"},{className:"trice",image:"http://bestanimations.com/Animals/Reptiles/Dinosaurs/dinosaur-animated-gif-1.gif", sound:"https://a.clyp.it/hblpp0cn.mp3"}]],

  [[{image:'http://bestanimations.com/Fantasy/knight-fighting-diablo-deamon-animation.gif',className:'caveFight'}]],
  [],
  [[],[{image:"http://i.imgur.com/A2DDh3m.png"},{image:"http://i.imgur.com/xrOJYnr.png"}],[{image:"http://i.imgur.com/PBaKOvT.png"}]]
  ],

  messages:[["The year is 3058 according to a select few record keepers. New age hipsters and Talking Mimes have taken over the world and declared time as relative, banning the recording of time and erasing history as we know it. Use your time travel ability to click around our map to different era's and prove that history did happen!",
  "[Selim]: What if we tried an old western theme instead? [Alex]: That makes no sense with magic in the game [Selim]: Oh, and steampunk does?? [Alex]: But steampunk is so coooooool!!!",
"Woah! Cowboy steampunk? Will will smith smith a giant robot spider? Yes, I think Will smith will smith a giant robot spider[giant robot spider item] "],

["[Alex]:Oooo ya Know what would be cooler than fantasy? STEAMPUNK!!! [Harp]: What?! That doesn't make any sense with magic in the game! [Alex]: Fine then, you just don't have to visit steampunk-theme then ",
"[Alex]Hmm, so we made progress on our maps, but our game features aren't done.. Quick, we need a storyline to cover this up! [Harp] I got it!...The year is 3058 according to a select few record keepers. New age hipsters and Talking Mimes have taken over the world and declared time as relative, banning the recording of time and erasing history as we know it. Use your time travel ability to click around our map to different era's to prove history happened, and collect items to battle the Talking Mime and his henchmen.",
"Howdy pardner, them high-fulutin software developers don't know how to decide on a theme! Why don't you click on that gun over there?"],

["[Talking Mime] My army of Talking Mime's has set upon your castle! We all watched a Charlie Chaplin flick to drive us into a rage!! We are the voice for the voiceless!! I dare you to stop my attack. [Instruction] Find the best way to escape the attack on your castle and battle the talking mime!",
"[Alex]:Fantasy sucks so much man, might as well make a game that has DINOSAURS in it.  [Harp]: Please tell me your not making this game have dinosaurs in it... ",
""
],

["This is a cave!!!!"],
[],
["Hello! We've updated our map recently, I hope you like it. Ufortunately, we forgot to finish the battle page, maybe you could find the missing pieces in here?","Harp: Great news! I convinced the development team to make this a fantasy themed game. I was outnumbered, but like any hobbit knows, size doesn't matter!", "Alex: PFT! Fantasy? Get a grip on reality man! As 'Lead Engineer' I declare this a Sci Fi game. Welcome to the future! "]],

  riddles:[[],
  ["",{question:" Solve this riddle and get that fancy space gun: the last man on the earth is locked in a room, he hears a knock on the door, who could it be?", answer:"woman", reward:weapons["LAZER_GUN"], className:"sciRiddle", solved:false}],
  [],
  [],
  [],
  []
  ]
}

export default map;<|endoftext|>


<commit_before>var innerInitialize = function() {
    console.log("It's the editor, man");
}<commit_msg>Create the canvas on editor start<commit_after>$(document).ready(function() {
    innerInitialize();
});

var innerInitialize = function() {
    // Create the canvas and context
    initCanvas($(window).width(), $(window).height());
    // initialize the camera
    camera = new Camera();
}<|endoftext|>


<commit_before>$(window).scroll(function() {
    if ($('.navbar').offset().top > 50) {
        $('.navbar-fixed-top').addClass('top-nav-collapse');
    } else {
        $('.navbar-fixed-top').removeClass('top-nav-collapse');
    }
});

$(function() {
    if(navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function(position) {
            var jqxhr = $.get('/school/find', {
                latitude: position.coords.latitude,
                longitude: position.coords.longitude
            });

            jqxhr.done(function(response) {
                console.log('success');
                loadMap(position, response);
                // update header with closest school and information about it.
            });

            jqxhr.fail(function(response) {
                console.log(response.responseText);
            });
        }, function() {
            console.log('Geolocation service failed.');
        });
    } else {
        console.log('Browser does not support Geolocation');
    }
});

function loadMap(position, school) {
    var mapOptions = {
        zoom: 13,
        center: new google.maps.LatLng(position.coords.latitude, position.coords.longitude),
        disableDefaultUI: true,
        scrollwheel: false,
        draggable: true,
        //styles: [{"featureType":"water","elementType":"geometry","stylers":[{"color":"#a2daf2"}]},{"featureType":"landscape.man_made","elementType":"geometry","stylers":[{"color":"#f7f1df"}]},{"featureType":"landscape.natural","elementType":"geometry","stylers":[{"color":"#d0e3b4"}]},{"featureType":"landscape.natural.terrain","elementType":"geometry","stylers":[{"visibility":"off"}]},{"featureType":"poi.park","elementType":"geometry","stylers":[{"color":"#bde6ab"}]},{"featureType":"poi","elementType":"labels","stylers":[{"visibility":"off"}]},{"featureType":"poi.medical","elementType":"geometry","stylers":[{"color":"#fbd3da"}]},{"featureType":"poi.business","stylers":[{"visibility":"off"}]},{"featureType":"road","elementType":"geometry.stroke","stylers":[{"visibility":"off"}]},{"featureType":"road","elementType":"labels","stylers":[{"visibility":"off"}]},{"featureType":"road.highway","elementType":"geometry.fill","stylers":[{"color":"#ffe15f"}]},{"featureType":"road.highway","elementType":"geometry.stroke","stylers":[{"color":"#efd151"}]},{"featureType":"road.arterial","elementType":"geometry.fill","stylers":[{"color":"#ffffff"}]},{"featureType":"road.local","elementType":"geometry.fill","stylers":[{"color":"black"}]},{"featureType":"transit.station.airport","elementType":"geometry.fill","stylers":[{"color":"#cfb2db"}]}]
    };

    var mapElement = document.getElementById('map');
    var map = new google.maps.Map(mapElement, mapOptions);
    var origin = position.coords.latitude + ',' + position.coords.longitude;
    var destination = school.latitude + ',' + school.longitude;
    var service = new google.maps.DirectionsService();

    var request = {
        origin: origin,
        destination: destination,
        travelMode: google.maps.DirectionsTravelMode.DRIVING
    };

    service.route(request, function(response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
            new google.maps.DirectionsRenderer({
                map: map,
                directions: response,
                suppressMarkers: true
            });

            var route = response.routes[0].legs[0];
            var startMarker = new google.maps.Marker({
                position: route.start_location,
                map: map,
                animation: google.maps.Animation.DROP,
                title: 'sadfasdf'
            });
            var startInfowindow = new google.maps.InfoWindow({
                content: 'Start'
            });
            startInfowindow.open(map, startInfowindow);

            // var endMarker = new google.maps.Marker({
            //     position: route.end_location,
            //     map: map,
            //     animation: google.maps.Animation.DROP,
            //     title: 'fasfdasd'
            // });
            // var endInfowindow = new google.maps.InfoWindow({
            //     content: 'End'
            // });
            // endInfowindow.open(map, endMarker);
        } else {
            console.log("Unable to retrieve your route");
        }
    });
}<commit_msg>Gettin' there<commit_after>$(window).scroll(function() {
    if ($('.navbar').offset().top > 50) {
        $('.navbar-fixed-top').addClass('top-nav-collapse');
    } else {
        $('.navbar-fixed-top').removeClass('top-nav-collapse');
    }
});

$(function() {
    if(navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function(position) {
            var jqxhr = $.get('/school/find', {
                latitude: position.coords.latitude,
                longitude: position.coords.longitude
            });

            jqxhr.done(function(response) {
                console.log('success');
                loadMap(position, response);
                // update header with closest school and information about it.
            });

            jqxhr.fail(function(response) {
                console.log(response.responseText);
            });
        }, function() {
            console.log('Geolocation service failed.');
        });
    } else {
        console.log('Browser does not support Geolocation');
    }
});

function loadMap(position, school) {
    var mapOptions = {
        zoom: 13,
        center: new google.maps.LatLng(position.coords.latitude, position.coords.longitude),
        disableDefaultUI: true,
        scrollwheel: false,
        draggable: true,
        //styles: [{"featureType":"water","elementType":"geometry","stylers":[{"color":"#a2daf2"}]},{"featureType":"landscape.man_made","elementType":"geometry","stylers":[{"color":"#f7f1df"}]},{"featureType":"landscape.natural","elementType":"geometry","stylers":[{"color":"#d0e3b4"}]},{"featureType":"landscape.natural.terrain","elementType":"geometry","stylers":[{"visibility":"off"}]},{"featureType":"poi.park","elementType":"geometry","stylers":[{"color":"#bde6ab"}]},{"featureType":"poi","elementType":"labels","stylers":[{"visibility":"off"}]},{"featureType":"poi.medical","elementType":"geometry","stylers":[{"color":"#fbd3da"}]},{"featureType":"poi.business","stylers":[{"visibility":"off"}]},{"featureType":"road","elementType":"geometry.stroke","stylers":[{"visibility":"off"}]},{"featureType":"road","elementType":"labels","stylers":[{"visibility":"off"}]},{"featureType":"road.highway","elementType":"geometry.fill","stylers":[{"color":"#ffe15f"}]},{"featureType":"road.highway","elementType":"geometry.stroke","stylers":[{"color":"#efd151"}]},{"featureType":"road.arterial","elementType":"geometry.fill","stylers":[{"color":"#ffffff"}]},{"featureType":"road.local","elementType":"geometry.fill","stylers":[{"color":"black"}]},{"featureType":"transit.station.airport","elementType":"geometry.fill","stylers":[{"color":"#cfb2db"}]}]
    };

    var mapElement = document.getElementById('map');
    var map = new google.maps.Map(mapElement, mapOptions);
    var origin = position.coords.latitude + ',' + position.coords.longitude;
    var destination = school.latitude + ',' + school.longitude;
    var service = new google.maps.DirectionsService();

    var request = {
        origin: origin,
        destination: destination,
        travelMode: google.maps.DirectionsTravelMode.DRIVING
    };

    service.route(request, function(response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
            new google.maps.DirectionsRenderer({
                map: map,
                directions: response,
                suppressMarkers: true
            });

            var startInfowindow = new google.maps.InfoWindow({
            });

            var route = response.routes[0].legs[0];
            var startMarker = new google.maps.Marker({
                position: route.start_location,
                map: map,
                animation: google.maps.Animation.DROP
            });
            startInfowindow.setContent('lsakdfalks');
            startInfowindow.open(map, startMarker);

            var endMarker = new google.maps.Marker({
                position: route.end_location,
                map: map,
                animation: google.maps.Animation.DROP
            });
             var endInfowindow = new google.maps.InfoWindow({
            });
            endInfowindow.setContent('lsakdfalks');
            endInfowindow.open(map, endMarker);
        } else {
            console.log("Unable to retrieve your route");
        }
    });
}<|endoftext|>


<commit_before>// @flow
import React, { Component, PropTypes } from 'react'
import MediaItem from './MediaItem'
import EditMenu from './edit-menu'
require('../styles/edit.scss')

class Edit extends Component {
  constructor() {
    super()
    this.onFilterChange = this.onFilterChange.bind(this)
  }

  onFilterChange(event) {
    event.preventDefault()
    const value = event.target.value
    this.props.updateFilter(value)
  }

  filteredMediaItems() {
    const { combineSubtitles, filter, media, toggleCheckbox, updateText, removeMedia } = this.props
    return Object.keys(media).map(key => media[key]).filter(item => item.text.toLowerCase().includes(filter.toLowerCase()))
      .map(item => <MediaItem
        combineSubtitles={combineSubtitles}
        key={item.index}
        mediaItem={item}
        updateMedia={this.props.updateMedia}
        toggleCheckbox={toggleCheckbox}
        updateText={updateText}
        removeMedia={removeMedia}
      />)
  }

  render() {
    const { bulkEditMedia, bulkDeleteMedia, canRedo, canUndo, createApkg, filter, media, onRedo, onUndo, selectMedia } = this.props

    return (

App Name Placeholder

Each item below will be a flashcard in Anki. Preview and edit them below. Click "Create Anki Deck" to export the deck.

        <EditMenu media={media} bulkEditMedia={bulkEditMedia} onFilterChange={this.onFilterChange} filter={filter} selectMedia={selectMedia} canRedo={canRedo} canUndo={canUndo} onRedo={onRedo} onUndo={onUndo} createApkg={createApkg} bulkDeleteMedia={bulkDeleteMedia} />

          {this.filteredMediaItems()}

    )
  }
}

Edit.propTypes = {
  bulkEditMedia: PropTypes.func.isRequired,
  bulkDeleteMedia: PropTypes.func.isRequired,
  canRedo: PropTypes.bool.isRequired,
  canUndo: PropTypes.bool.isRequired,
  combineSubtitles: PropTypes.func.isRequired,
  createApkg: PropTypes.func.isRequired,
  filter: PropTypes.string,
  media: PropTypes.object.isRequired,
  onRedo: PropTypes.func.isRequired,
  onUndo: PropTypes.func.isRequired,
  removeMedia: PropTypes.func.isRequired,
  selectMedia: PropTypes.func.isRequired,
  toggleCheckbox: PropTypes.func.isRequired,
  updateFilter: PropTypes.func.isRequired,
  updateMedia: PropTypes.func.isRequired,
  updateText: PropTypes.func.isRequired
}

export default Edit
<commit_msg>Prevent subtitle items from sticking out past window width<commit_after>// @flow
import React, { Component, PropTypes } from 'react'
import MediaItem from './MediaItem'
import EditMenu from './edit-menu'
require('../styles/edit.scss')

class Edit extends Component {
  constructor() {
    super()
    this.onFilterChange = this.onFilterChange.bind(this)
  }

  onFilterChange(event) {
    event.preventDefault()
    const value = event.target.value
    this.props.updateFilter(value)
  }

  filteredMediaItems() {
    const { combineSubtitles, filter, media, toggleCheckbox, updateText, removeMedia } = this.props
    return Object.keys(media).map(key => media[key]).filter(item => item.text.toLowerCase().includes(filter.toLowerCase()))
      .map(item => <MediaItem
        combineSubtitles={combineSubtitles}
        key={item.index}
        mediaItem={item}
        updateMedia={this.props.updateMedia}
        toggleCheckbox={toggleCheckbox}
        updateText={updateText}
        removeMedia={removeMedia}
      />)
  }

  render() {
    const { bulkEditMedia, bulkDeleteMedia, canRedo, canUndo, createApkg, filter, media, onRedo, onUndo, selectMedia } = this.props

    return (

App Name Placeholder

Each item below will be a flashcard in Anki. Preview and edit them below. Click "Create Anki Deck" to export the deck.

        <EditMenu media={media} bulkEditMedia={bulkEditMedia} onFilterChange={this.onFilterChange} filter={filter} selectMedia={selectMedia} canRedo={canRedo} canUndo={canUndo} onRedo={onRedo} onUndo={onUndo} createApkg={createApkg} bulkDeleteMedia={bulkDeleteMedia} />

            {this.filteredMediaItems()}

    )
  }
}

Edit.propTypes = {
  bulkEditMedia: PropTypes.func.isRequired,
  bulkDeleteMedia: PropTypes.func.isRequired,
  canRedo: PropTypes.bool.isRequired,
  canUndo: PropTypes.bool.isRequired,
  combineSubtitles: PropTypes.func.isRequired,
  createApkg: PropTypes.func.isRequired,
  filter: PropTypes.string,
  media: PropTypes.object.isRequired,
  onRedo: PropTypes.func.isRequired,
  onUndo: PropTypes.func.isRequired,
  removeMedia: PropTypes.func.isRequired,
  selectMedia: PropTypes.func.isRequired,
  toggleCheckbox: PropTypes.func.isRequired,
  updateFilter: PropTypes.func.isRequired,
  updateMedia: PropTypes.func.isRequired,
  updateText: PropTypes.func.isRequired
}

export default Edit
<|endoftext|>


<commit_before>/**
 * Created by Magicmen on 19.06.2017.
 */

$(document).ready(function () {
    var opacityControl = $('.jm-layer');

    $(window).scroll(function(){
        var top = $(window).scrollTop(),
            opacity = top > 500 ? 1 : top * 2 / 950;

        opacityControl.css('opacity', opacity);
        if (top > 3 ) {
            $('.jm-layer').css('z-index', '6');
        } else {
            $('.jm-layer').css('z-index', '');
        }

        if (window.scrollY == 0) {
            $('.jm-warp.warp-button-to-top').css({'z-index':'-1', 'opacity':'0'});
        } else if (top > window.screen.availHeight) {
            $('.jm-warp.warp-button-to-top').css({'z-index':'1', 'opacity':'1'});
        }
    });

    $('.warp-button-to-content').on('click', 'a', function () {
        if ($(this).data('href') == '@content') {
            $('body').scrollTop((window.screen.availHeight - 90) - 48);
        }
    });

    $('a[data-href="@content"]').hover(function () {
        $(this).tooltip('toggle');
    })
});<commit_msg>Изменение функционала странички<commit_after>/**
 * Created by Magicmen on 19.06.2017.
 */

$(document).ready(function () {
    var opacityControl = $('.jm-layer');

    $(window).scroll(function(){
        var top = $(window).scrollTop(),
            opacity = top > 500 ? 1 : top * 2 / 950;

        opacityControl.css('opacity', opacity);
        if (top > 3 ) {
            $('.jm-layer').css('z-index', '6');
        } else {
            $('.jm-layer').css('z-index', '');
        }

        if (window.scrollY == 0) {
            $('.jm-warp.warp-button-to-top').css({'z-index':'-1', 'opacity':'0'});
        } else if (top > (window.screen.availHeight - 90) - 48) {
            $('.jm-warp.warp-button-to-top').css({'z-index':'1', 'opacity':'1'});
        }
    });

    $('.warp-button-to-content').on('click', 'a', function () {
        if ($(this).data('href') == '@content') {
            $('body').scrollTop((window.screen.availHeight - 90) - 48);
        }
    });

    $('a[data-href="@content"]').hover(function () {
        $(this).tooltip('toggle');
    })
});<|endoftext|>


<commit_before>import React from 'react';
import {Card, CardActions, CardHeader, CardMedia, CardTitle, CardText, RaisedButton} from 'material-ui';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import lightBaseTheme from 'material-ui/styles/baseThemes/lightBaseTheme';
import injectTapEventPlugin from 'react-tap-event-plugin';
injectTapEventPlugin();

const Home = () => (
  <MuiThemeProvider muiTheme={getMuiTheme(lightBaseTheme)}>

          <Card>
            <CardMedia
              overlay={<CardTitle title="Featured Story" subtitle="James Comey's Conspicuous Independence" />}
            >

            </CardMedia>
          </Card>

          <Card>
            <CardMedia>
            </CardMedia>
            <CardText style={{'font-size': 25}}>entwine allows content creators to quickly embed interactive maps, information about key characters, and data visualizations into their stories.</CardText>

              <RaisedButton label="Create a Story Now" fullWidth={true} labelStyle={{'font-size': 22}}/>

          </Card>

          <Card>
            <CardMedia
              overlay={<CardTitle title="Featured Story" />}
            >

            </CardMedia>
          </Card>

          <Card>
            <CardMedia
              overlay={<CardTitle title="Featured Story" />}
            >

            </CardMedia>
          </Card>

          <Card>
            <CardMedia
              overlay={<CardTitle title="Featured Story" />}
            >

            </CardMedia>
          </Card>

          <Card>
            <CardMedia
              overlay={<CardTitle title="Featured Story" />}
            >

            </CardMedia>
          </Card>

  </MuiThemeProvider>
);

export default Home;
<commit_msg>add link<commit_after>import React from 'react';
import {Link} from 'react-router'
import {Card, CardActions, CardHeader, CardMedia, CardTitle, CardText, RaisedButton} from 'material-ui';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import lightBaseTheme from 'material-ui/styles/baseThemes/lightBaseTheme';
import injectTapEventPlugin from 'react-tap-event-plugin';
injectTapEventPlugin();

const Home = () => (
  <MuiThemeProvider muiTheme={getMuiTheme(lightBaseTheme)}>

          <Card>
            <CardMedia
              overlay={<CardTitle title="Featured Story" subtitle="James Comey's Conspicuous Independence" />}
            >

            </CardMedia>
          </Card>

          <Card>
            <CardMedia>
            </CardMedia>
            <CardText style={{'font-size': 25}}>entwine allows content creators to quickly embed interactive maps, information about key characters, and data visualizations into their stories.</CardText>

              <RaisedButton label="Create a Story Now" fullWidth={true} labelStyle={{'font-size': 22}} containerElement={<Link to="/editor"/>} />

          </Card>

          <Card>
            <CardMedia
              overlay={<CardTitle title="Featured Story" />}
            >

            </CardMedia>
          </Card>

          <Card>
            <CardMedia
              overlay={<CardTitle title="Featured Story" />}
            >

            </CardMedia>
          </Card>

          <Card>
            <CardMedia
              overlay={<CardTitle title="Featured Story" />}
            >

            </CardMedia>
          </Card>

          <Card>
            <CardMedia
              overlay={<CardTitle title="Featured Story" />}
            >

            </CardMedia>
          </Card>

  </MuiThemeProvider>
);

export default Home;
<|endoftext|>


<commit_before>/* eslint-disable no-unused-vars */
var utils = {
    strWrap: function (str) {
        if (str.includes('\n') || (str.includes('"') && str.includes("'"))) return '`';
        return str.includes('"') ? "'" : '"';
    },

    escapeRegExp: function (str, q) {
        return str.replace(new RegExp('[\\n*+?^${}()|[\\]\\\\' + q + ']', 'g'), '\\$&');
    },

    strMerge: function (str) {
        return str.replace(/'\s*\+\s*'|"\s*\+\s*"/g, '');
    },

    methodChain: function (str) {
        return str.replace(/(\[("|')((?!\d)[a-z_\d$]*)("|')\])/gi, '.$3 ');
    }
};
<commit_msg>Update strWrap<commit_after>/* eslint-disable no-unused-vars */
var utils = {
    strWrap: function (str) {
        if (str.includes('\n') || (str.includes('"') && str.includes("'"))) return '`';
        return !str.includes("'") ? "'" : '"';
    },

    escapeRegExp: function (str, q) {
        return str.replace(new RegExp('[\\n*+?^${}()|[\\]\\\\' + q + ']', 'g'), '\\$&');
    },

    strMerge: function (str) {
        return str.replace(/'\s*\+\s*'|"\s*\+\s*"/g, '');
    },

    methodChain: function (str) {
        return str.replace(/(\[("|')((?!\d)[a-z_\d$]*)("|')\])/gi, '.$3 ');
    }
};
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import styles from './Home.css';
import axios from 'axios';
import jarvis from 'file!../jarvis-bkrd.png';
import RaisedButton from 'material-ui/lib/raised-button';
import ActionRecordVoiceOver from 'material-ui/lib/svg-icons/action/record-voice-over';
import Modal from 'react-modal';
import VisitorModal from './VisitorModal';
import Motion from '../sensors/motion';
import * as Camera from '../sensors/camera';
import fs from 'fs';
import io from 'socket.io-client';
let socket = io(`http://jarviscsg.herokuapp.com:80`);

export default class Home extends Component {

  constructor(props) {
    super(props);

    this.state = {
      visitors: [],
      modalIsOpen: false
    }
  }

  closeModal = () => {
        this.setState({ modalIsOpen: false});
    }

  checkIn = () => {
    let self = this;
    axios.get('http://jarviscsg-api.herokuapp.com/api/schedules/now').then(function(response) {
      if (response.data.length > 0) {
        self.setState({
          visitors: response.data,
          modalIsOpen: true
        });
      } else {

        // need to create proper data object for office manager // jeff
        let data = {
          firstName: "someone",
          userName: "erichardson"
        };
        self.notifyEmployee(data);
      }
    });
  }

  notifyEmployee = (data) => {
    responsiveVoice.speak("Thank you. I will let " + data.firstName + "know you are here.", "UK English Male", {rate: 0.8});
    Camera.takePicture(data);
    this.closeModal();
  }

  render() {

    return (

          <RaisedButton
            backgroundColor="#218EC1"
            className={styles.button}
            style={style}
            label="Check In"
            labelColor="#FFF"
            onClick={this.checkIn}
            icon={<ActionRecordVoiceOver />}
          />

          <VisitorModal
            open={this.state.modalIsOpen}
            close = {this.closeModal}
            visitors = {this.state.visitors}
            notifyEmployee = {this.notifyEmployee} />

    );
  }
}

const style = {
  position: 'fixed',
  bottom: '20px',
  left: '200px',
  height: '60px',
  width: '400px'
}
<commit_msg>add notify manager call on home.js<commit_after>import React, { Component } from 'react';
import styles from './Home.css';
import axios from 'axios';
import jarvis from 'file!../jarvis-bkrd.png';
import RaisedButton from 'material-ui/lib/raised-button';
import ActionRecordVoiceOver from 'material-ui/lib/svg-icons/action/record-voice-over';
import Modal from 'react-modal';
import VisitorModal from './VisitorModal';
import Motion from '../sensors/motion';
import * as Camera from '../sensors/camera';
import fs from 'fs';
import io from 'socket.io-client';
let socket = io(`http://jarviscsg.herokuapp.com:80`);

export default class Home extends Component {

  constructor(props) {
    super(props);

    this.state = {
      visitors: [],
      modalIsOpen: false
    }
  }

  closeModal = () => {
        this.setState({ modalIsOpen: false});
    }

  checkIn = () => {
    let self = this;
    axios.get('http://jarviscsg-api.herokuapp.com/api/schedules/now').then(function(response) {
      if (response.data.length > 0) {
        self.setState({
          visitors: response.data,
          modalIsOpen: true
        });
      } else {
        console.log("notifying mangaer")
        self.notifyManager();
      }
    });
  }

  notifyManager = () => {

    responsiveVoice.speak("Thank you. I will let someone know you are here.", "UK English Male", {rate: 0.8});

    // need to create proper data object for office manager // jeff
    let data = {
      firstName: "someone",
      userName: "erichardson"
    };

    Camera.takePicture(data);
    this.closeModal();
  }

  notifyEmployee = (data) => {
    responsiveVoice.speak("Thank you. I will let " + data.firstName + "know you are here.", "UK English Male", {rate: 0.8});
    Camera.takePicture(data);
    this.closeModal();
  }

  render() {

    return (

          <RaisedButton
            backgroundColor="#218EC1"
            className={styles.button}
            style={style}
            label="Check In"
            labelColor="#FFF"
            onClick={this.checkIn}
            icon={<ActionRecordVoiceOver />}
          />

          <VisitorModal
            open={this.state.modalIsOpen}
            close = {this.closeModal}
            visitors = {this.state.visitors}
            notifyEmployee = {this.notifyEmployee} />

    );
  }
}

const style = {
  position: 'fixed',
  bottom: '20px',
  left: '200px',
  height: '60px',
  width: '400px'
}
<|endoftext|>


<commit_before>var test = false,originspp = 0;
numberWithCommas = function(x) {
    var parts = x.toString().split(".");
    parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    return parts.join(".");
}
removeCommas = function(myVar){
    myVar = myVar.replace(/[ ,]/g, "");
    return myVar;
}
validate = function(){
    if(!$("#psb").val()){
        $("#psb").val("0");
    }
    if(!$("#book").val()){
        $("#book").val("0");
    }
    if(!$("#bimbel").val()){
        $("#bimbel").val("0");
    }
    if(!$("#cashpay").val()){
        $("#cashpay").val("0");
    }
}
filltotal = function(){
    validate();
    var total = parseInt(removeCommas($("#spp_").val()))
        +parseInt(removeCommas($("#psb").val()))
        +parseInt(removeCommas($("#book").val()))
        +parseInt(removeCommas($("#bimbel").val()));
    $("#total").val(numberWithCommas(total));
}
fillreturnmoney = function(){
    validate();
    $("#returnmoney").val(numberWithCommas(parseInt(removeCommas($("#cashpay").val()))
        -parseInt(removeCommas($("#total").val()))));
}
togglespp = function(){
    if($("#sppcheckbox").prop("checked")){
        $("#sppmonthdiv").show();
        $("#spp_").val($("#orispp").val());
    }else{
        $("#sppmonthdiv").hide();
        $("#spp_").val(0);
    }
    filltotal();
    fillreturnmoney();
}
togglebimbel = function(){
    if($("#bimbelcheckbox").prop("checked")){
        $("#bimbelmonthdiv").show();
        $("#bimbel").val($("#oribimbel").val());
    }else{
        $("#bimbelmonthdiv").hide();
        $("#bimbel").val(0);
    }
    filltotal();
    fillreturnmoney();
}
$.fn.adjustval = function(options){
    $(this).change(function(){
        var settings = $.extend({
            firstmonth:$("#sppfrstmonth"),
            firstyear:$("#sppfrstyear"),
            nextmonth:$("#sppnextmonth"),
            nextyear:$("#sppnextyear"),
            hiddenval : $("#spp_"),
            shownval: $("#bimbel"),
            orival:$("#orival")
        },options);
        console.log("time changed");
        monthcount = 0;
        if(settings.nextyear.val()===settings.firstyear.val()){
            if(settings.nextmonth.val()===settings.firstmonth.val()){
                monthcount = 1;
            }else
            if(settings.nextmonth.val()>settings.firstmonth.val()){
                monthcount = settings.nextmonth.val() - settings.firstmonth.val() + 1;

            }else{
                settings.nextmonth.val(settings.firstmonth.val());
            }
        }else
        if(settings.nextyear.val()>settings.firstyear.val()){
            frsmonths = 12 - settings.firstmonth.val();
            months = 12*(settings.nextyear.val()-settings.firstyear.val() - 1);
            nextmonths = settings.nextmonth.val();
            monthcount = parseInt(frsmonths)+parseInt(months)+parseInt(nextmonths) + 1;
        }else{
            settings.nextyear.val(settings.firstyear.val());
        }
        _total = parseInt(settings.orival.val())*monthcount;
        settings.shownval.val(numberWithCommas(_total));
        settings.hiddenval.val(_total);
        filltotal();
        fillreturnmoney();
        if(test===true){
            alert(monthcount);
        };
    });
};
$.ajax({
    url:'/students/getjson',
    dataType:'json'
})
.done(function(res){
    $("#sname").focus(function(){
        $(this).select();
    });
    $('#sname').autocomplete({
        lookup: res.out,
        onSelect: function(suggestion) {
            console.log('suggestion-data',suggestion.data);
            console.log('suggestion',suggestion);
            console.log('cek status');
            $("#nis").val(suggestion.nis);
            $("#studentname").val(suggestion.name);
            $("#grade").val(suggestion.grade);
                $.ajax({
                    url:'/students/getproperties/'+suggestion.nis,
                    type:'get',
                    dataType:'Json'
                })
                .done(function(res){
                    originspp = res.spp;
                    $("#spp_").val(numberWithCommas(res.spp));
                    $("#spp").val(res.spp);
                    $("#orispp").val(res.spp);
                    $("#bimbel_").val(numberWithCommas(res.bimbel));
                    $("#bimbel").val(res.bimbel);
                    $("#oribimbel").val(res.bimbel);
                    $("#psb_").val(numberWithCommas(res.dupsbremain));
                    $("#psb").val(numberWithCommas(res.dupsbremain));
                    $("#book_").val(numberWithCommas(res.bookremain));
                    $("#book").val(numberWithCommas(res.bookremain));
                    $("#sppfrstmonth").val(res.sppmaxmonth);
                    $("#sppfrstyear").val(res.sppmaxyear);
                    $("#sppnextmonth").val(res.sppmaxmonth);
                    $("#sppnextyear").val(res.sppmaxyear);
                    $("#bimbelfrstmonth").val(res.bimbelmaxmonth);
                    $("#bimbelfrstyear").val(res.bimbelmaxyear);
                    $("#bimbelnextmonth").val(res.bimbelmaxmonth);
                    $("#bimbelnexttyear").val(res.bimbelmaxyear);
                    filltotal();
                    fillreturnmoney();
                    $(".sppperiod").change();
                    $(".bimbelperiod").change();
                    console.log("SPPMAXMONTH",res.sppmaxmonth);
                    console.log("SPPMAXYEAR",res.sppmaxyear);
                });
        },
        onHint: function (hint) {
            console.log('hint',hint);
        },
        onInvalidateSelection: function() {
        }
    });
})
.fail(function(err){
    console.log("Error fetch json",err);
});
$("#cashpay").keyup(function(){
    fillreturnmoney()
});
$("#cashpay").focus(function(){
    $(this).select();
})
$("#cashpay").blur(function(){
    $(this).val(numberWithCommas($(this).val()));
})
$(".affect-total").focus(function(){
    $(this).val(removeCommas($(this).val().toString()));
    $(this).select();
})
$(".formatted").blur(function(){
    $(this).val(numberWithCommas($(this).val().toString()));
})
togglespp();
$("#sppcheckbox").change(function(){
    togglespp();
})
togglebimbel();
$("#bimbelcheckbox").change(function(){
    togglebimbel();
});
$(".affect-total").keyup(function(){
    filltotal();
    fillreturnmoney();
});
$(".affect-total").change(function(){
    filltotal();
    fillreturnmoney();
});
$(".bimbelperiod").adjustval({
    firstmonth:$("#bimbelfrstmonth"),
    firstyear:$("#bimbelfrstyear"),
    nextmonth:$("#bimbelnextmonth"),
    nextyear:$("#bimbelnextyear"),
    hiddenval : $("#bimbel"),
    shownval: $("#bimbel_"),
    orival: $("#oribimbel")
});
$(".sppperiod").adjustval({
    firstmonth:$("#sppfrstmonth"),
    firstyear:$("#sppfrstyear"),
    nextmonth:$("#sppnextmonth"),
    nextyear:$("#sppnextyear"),
    hiddenval : $("#spp"),
    shownval: $("#spp_"),
    orival: $("#orispp")
});<commit_msg>fix bimbel next year on spp<commit_after>var test = false,originspp = 0;
numberWithCommas = function(x) {
    var parts = x.toString().split(".");
    parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    return parts.join(".");
}
removeCommas = function(myVar){
    myVar = myVar.replace(/[ ,]/g, "");
    return myVar;
}
validate = function(){
    if(!$("#psb").val()){
        $("#psb").val("0");
    }
    if(!$("#book").val()){
        $("#book").val("0");
    }
    if(!$("#bimbel").val()){
        $("#bimbel").val("0");
    }
    if(!$("#cashpay").val()){
        $("#cashpay").val("0");
    }
}
filltotal = function(){
    validate();
    var total = parseInt(removeCommas($("#spp_").val()))
        +parseInt(removeCommas($("#psb").val()))
        +parseInt(removeCommas($("#book").val()))
        +parseInt(removeCommas($("#bimbel").val()));
    $("#total").val(numberWithCommas(total));
}
fillreturnmoney = function(){
    validate();
    $("#returnmoney").val(numberWithCommas(parseInt(removeCommas($("#cashpay").val()))
        -parseInt(removeCommas($("#total").val()))));
}
togglespp = function(){
    if($("#sppcheckbox").prop("checked")){
        $("#sppmonthdiv").show();
        $("#spp_").val($("#orispp").val());
    }else{
        $("#sppmonthdiv").hide();
        $("#spp_").val(0);
    }
    filltotal();
    fillreturnmoney();
}
togglebimbel = function(){
    if($("#bimbelcheckbox").prop("checked")){
        $("#bimbelmonthdiv").show();
        $("#bimbel").val($("#oribimbel").val());
    }else{
        $("#bimbelmonthdiv").hide();
        $("#bimbel").val(0);
    }
    filltotal();
    fillreturnmoney();
}
$.fn.adjustval = function(options){
    $(this).change(function(){
        var settings = $.extend({
            firstmonth:$("#sppfrstmonth"),
            firstyear:$("#sppfrstyear"),
            nextmonth:$("#sppnextmonth"),
            nextyear:$("#sppnextyear"),
            hiddenval : $("#spp_"),
            shownval: $("#bimbel"),
            orival:$("#orival")
        },options);
        console.log("time changed");
        monthcount = 0;
        if(settings.nextyear.val()===settings.firstyear.val()){
            if(settings.nextmonth.val()===settings.firstmonth.val()){
                monthcount = 1;
            }else
            if(settings.nextmonth.val()>settings.firstmonth.val()){
                monthcount = settings.nextmonth.val() - settings.firstmonth.val() + 1;

            }else{
                settings.nextmonth.val(settings.firstmonth.val());
            }
        }else
        if(settings.nextyear.val()>settings.firstyear.val()){
            frsmonths = 12 - settings.firstmonth.val();
            months = 12*(settings.nextyear.val()-settings.firstyear.val() - 1);
            nextmonths = settings.nextmonth.val();
            monthcount = parseInt(frsmonths)+parseInt(months)+parseInt(nextmonths) + 1;
        }else{
            settings.nextyear.val(settings.firstyear.val());
        }
        _total = parseInt(settings.orival.val())*monthcount;
        settings.shownval.val(numberWithCommas(_total));
        settings.hiddenval.val(_total);
        filltotal();
        fillreturnmoney();
        if(test===true){
            alert(monthcount);
        };
    });
};
$.ajax({
    url:'/students/getjson',
    dataType:'json'
})
.done(function(res){
    $("#sname").focus(function(){
        $(this).select();
    });
    $('#sname').autocomplete({
        lookup: res.out,
        onSelect: function(suggestion) {
            console.log('suggestion-data',suggestion.data);
            console.log('suggestion',suggestion);
            console.log('cek status');
            $("#nis").val(suggestion.nis);
            $("#studentname").val(suggestion.name);
            $("#grade").val(suggestion.grade);
                $.ajax({
                    url:'/students/getproperties/'+suggestion.nis,
                    type:'get',
                    dataType:'Json'
                })
                .done(function(res){
                    originspp = res.spp;
                    $("#spp_").val(numberWithCommas(res.spp));
                    $("#spp").val(res.spp);
                    $("#orispp").val(res.spp);
                    $("#bimbel_").val(numberWithCommas(res.bimbel));
                    $("#bimbel").val(res.bimbel);
                    $("#oribimbel").val(res.bimbel);
                    $("#psb_").val(numberWithCommas(res.dupsbremain));
                    $("#psb").val(numberWithCommas(res.dupsbremain));
                    $("#book_").val(numberWithCommas(res.bookremain));
                    $("#book").val(numberWithCommas(res.bookremain));
                    $("#sppfrstmonth").val(res.sppmaxmonth);
                    $("#sppfrstyear").val(res.sppmaxyear);
                    $("#sppnextmonth").val(res.sppmaxmonth);
                    $("#sppnextyear").val(res.sppmaxyear);
                    $("#bimbelfrstmonth").val(res.bimbelmaxmonth);
                    $("#bimbelfrstyear").val(res.bimbelmaxyear);
                    $("#bimbelnextmonth").val(res.bimbelmaxmonth);
                    $("#bimbelnextyear").val(res.bimbelmaxyear);
                    filltotal();
                    fillreturnmoney();
                    $(".sppperiod").change();
                    $(".bimbelperiod").change();
                    console.log("SPPMAXMONTH",res.sppmaxmonth);
                    console.log("SPPMAXYEAR",res.sppmaxyear);
                });
        },
        onHint: function (hint) {
            console.log('hint',hint);
        },
        onInvalidateSelection: function() {
        }
    });
})
.fail(function(err){
    console.log("Error fetch json",err);
});
$("#cashpay").keyup(function(){
    fillreturnmoney()
});
$("#cashpay").focus(function(){
    $(this).select();
})
$("#cashpay").blur(function(){
    $(this).val(numberWithCommas($(this).val()));
})
$(".affect-total").focus(function(){
    $(this).val(removeCommas($(this).val().toString()));
    $(this).select();
})
$(".formatted").blur(function(){
    $(this).val(numberWithCommas($(this).val().toString()));
})
togglespp();
$("#sppcheckbox").change(function(){
    togglespp();
})
togglebimbel();
$("#bimbelcheckbox").change(function(){
    togglebimbel();
});
$(".affect-total").keyup(function(){
    filltotal();
    fillreturnmoney();
});
$(".affect-total").change(function(){
    filltotal();
    fillreturnmoney();
});
$(".bimbelperiod").adjustval({
    firstmonth:$("#bimbelfrstmonth"),
    firstyear:$("#bimbelfrstyear"),
    nextmonth:$("#bimbelnextmonth"),
    nextyear:$("#bimbelnextyear"),
    hiddenval : $("#bimbel"),
    shownval: $("#bimbel_"),
    orival: $("#oribimbel")
});
$(".sppperiod").adjustval({
    firstmonth:$("#sppfrstmonth"),
    firstyear:$("#sppfrstyear"),
    nextmonth:$("#sppnextmonth"),
    nextyear:$("#sppnextyear"),
    hiddenval : $("#spp"),
    shownval: $("#spp_"),
    orival: $("#orispp")
});<|endoftext|>


<commit_before>import React, { Component } from 'react';
import styles from './Home.css';
import axios from 'axios';
import jarvis from 'file!../jarvis-bkrd.png';
import RaisedButton from 'material-ui/lib/raised-button';
import ActionRecordVoiceOver from 'material-ui/lib/svg-icons/action/record-voice-over';
import Modal from 'react-modal';
import VisitorModal from './VisitorModal';
// import Motion from '../sensors/motion';
// import * as Camera from '../sensors/camera';

export default class Home extends Component {

  constructor(props) {
    super(props);

    this.state = {
      visitors: [],
      modalIsOpen: false
    }
  }

  closeModal = () => {
        this.setState({ modalIsOpen: false});
    }

  sendMessage = () => {
    responsiveVoice.speak("Thank you. I will let someone know you are here.", "UK English Male", {rate: 0.8});
    Camera.takePicture();
  }

  checkIn = () => {
    let self = this;
    axios.get('http://jarviscsg-api.herokuapp.com/api/schedules').then(function(response) {
      if (response.data.length > 0) {
        self.setState({
          visitors: response.data,
          modalIsOpen: true
        });
      } else {
        self.sendMessage();
      }
    });
  }

  notifyEmployee = (data) => {
    responsiveVoice.speak("Thank you. I will get " + data.firstName + "right now.", "UK English Male", {rate: 0.8});
    Camera.takePicture();
    this.closeModal();
  }

  render() {

    return (

          <RaisedButton
            backgroundColor="#218EC1"
            className={styles.button}
            style={style}
            label="Check In"
            labelColor="#FFF"
            onClick={this.checkIn}
            icon={<ActionRecordVoiceOver />}
          />

          <VisitorModal
            open={this.state.modalIsOpen}
            close = {this.closeModal}
            visitors = {this.state.visitors}
            notifyEmployee = {this.notifyEmployee} />

    );
  }
}

const style = {
  position: 'fixed',
  bottom: '20px',
  left: '240px',
  height: '60px',
  width: '400px'
}
<commit_msg>uncommented sensors<commit_after>import React, { Component } from 'react';
import styles from './Home.css';
import axios from 'axios';
import jarvis from 'file!../jarvis-bkrd.png';
import RaisedButton from 'material-ui/lib/raised-button';
import ActionRecordVoiceOver from 'material-ui/lib/svg-icons/action/record-voice-over';
import Modal from 'react-modal';
import VisitorModal from './VisitorModal';
import Motion from '../sensors/motion';
import * as Camera from '../sensors/camera';

export default class Home extends Component {

  constructor(props) {
    super(props);

    this.state = {
      visitors: [],
      modalIsOpen: false
    }
  }

  closeModal = () => {
        this.setState({ modalIsOpen: false});
    }

  sendMessage = () => {
    responsiveVoice.speak("Thank you. I will let someone know you are here.", "UK English Male", {rate: 0.8});
    Camera.takePicture();
  }

  checkIn = () => {
    let self = this;
    axios.get('http://jarviscsg-api.herokuapp.com/api/schedules').then(function(response) {
      if (response.data.length > 0) {
        self.setState({
          visitors: response.data,
          modalIsOpen: true
        });
      } else {
        self.sendMessage();
      }
    });
  }

  notifyEmployee = (data) => {
    responsiveVoice.speak("Thank you. I will get " + data.firstName + "right now.", "UK English Male", {rate: 0.8});
    Camera.takePicture();
    this.closeModal();
  }

  render() {

    return (

          <RaisedButton
            backgroundColor="#218EC1"
            className={styles.button}
            style={style}
            label="Check In"
            labelColor="#FFF"
            onClick={this.checkIn}
            icon={<ActionRecordVoiceOver />}
          />

          <VisitorModal
            open={this.state.modalIsOpen}
            close = {this.closeModal}
            visitors = {this.state.visitors}
            notifyEmployee = {this.notifyEmployee} />

    );
  }
}

const style = {
  position: 'fixed',
  bottom: '20px',
  left: '240px',
  height: '60px',
  width: '400px'
}
<|endoftext|>


<commit_before>var async = require('async');
var Promise = require('bluebird');
var levenshtein = require('./levenshtein');
var isEqual = require('./equal');

function transition(from, to, cb) {
	if(isEqual(from, to)) return cb();

	if(from.children.length === 0 && to.children.length === 0) {
		if(from.innerHTML !== to.innerHTML) {
			replace(from, to, cb);
		} else {
			equaliseAttributes(from, to);
			cb();
		}
	} else {
		var childrenFrom = Array.prototype.slice.call(from.children);
		var childrenTo = Array.prototype.slice.call(to.children);
		var matrix = levenshtein.matrix(childrenFrom, childrenTo, isSame);

		if(!worthy(from, to, matrix)) {
			replace(from, to, cb);
		} else {
			equaliseAttributes(from, to);
			diffChildren(childrenFrom, childrenTo, matrix, from, cb);
		}
	}
}

function worthy(from, to, matrix) {
	return levenshtein.distance(matrix) < from.children.length/2;
}

function equaliseAttributes(from, to) {
	var src = Array.prototype.slice.call(from.attributes);
	var dest = Array.prototype.slice.call(to.attributes);

	for(var x = 0; x < src.length; x++) {
		if(!to.hasAttribute(src[x].name)) {
			from.removeAttribute(src[x].name);
		}
	}

	for(var y = 0; y < dest.length; y++) {
		if(dest[y].value !== from.getAttribute(dest[y].name)) {
			from.setAttribute(dest[y].name, dest[y].value);
		}
	}
}

function diffChildren(childrenFrom, childrenTo, matrix, parent, cb) {
	var differences = levenshtein.diff(matrix, childrenTo);

	async.map(differences, function(difference, cb) {
		var from = childrenFrom[difference.position];
		var to = difference.value;

		if(difference.type === ':') {
			replace(from, to, cb);
		} else if(difference.type === '+') {
			insert(to, parent, difference.position);
		} else if(difference.type === '-') {
			remove(from, cb);
		} else if(difference.type === '=') {
			transition(from, to, cb);
		}
	}, cb);
}

function isSame(a, b) {
	return a.nodeName === b.nodeName &&
			a.id === b.id &&
			a.getAttribute('diff-id') === b.getAttribute('diff-id');
}

function replace(from, to, cb) {
	var position = siblingCount(from);
	var parent = from.parentNode;

	remove(from, function() {
		insert(to, parent, position, cb);
	});
}

function insert(el, parent, position, cb) {
	el.classList.add('out');
	parent.insertBefore(el, parent.children[position]);

	setTimeout(function() {
		el.classList.add('in');
		el.classList.remove('out');

		function listener() {
			el.removeEventListener('transitionend', listener);
			el.classList.remove('in');
			if(cb) cb();
		}

		if(hasTransition(el)) {
			el.addEventListener('transitionend', listener);
		} else {
			el.classList.remove('in');
			if(cb) cb();
		}
	}, 0);
}

function remove(el, cb) {
	el.classList.add('out');

	function listener() {
		el.removeEventListener('transitionend', listener);
		el.parentNode.removeChild(el);
		cb();
	}

	if(hasTransition(el)) {
		el.addEventListener('transitionend', listener);
	} else {
		el.parentNode.removeChild(el);
		cb();
	}
}

function hasTransition(el) {
	var style = getComputedStyle(el);
	return typeof style.transition === 'string' && style.transitionProperty !== 'none';
}

function siblingCount(el) {
	var i = 0;
	while((el = el.previousSibling)	!== null) i++;
	return i;
}

module.exports = Promise.promisify(transition);<commit_msg>Ignore text-nodes<commit_after>var async = require('async');
var Promise = require('bluebird');
var levenshtein = require('./levenshtein');
var isEqual = require('./equal');

function transition(from, to, cb) {
	if(isEqual(from, to)) return cb();

	if(from.children.length === 0 && to.children.length === 0) {
		if(from.innerHTML !== to.innerHTML) {
			replace(from, to, cb);
		} else {
			equaliseAttributes(from, to);
			cb();
		}
	} else {
		var childrenFrom = Array.prototype.slice.call(from.children);
		var childrenTo = Array.prototype.slice.call(to.children);
		var matrix = levenshtein.matrix(childrenFrom, childrenTo, isSame);

		if(!worthy(from, to, matrix)) {
			replace(from, to, cb);
		} else {
			equaliseAttributes(from, to);
			diffChildren(childrenFrom, childrenTo, matrix, from, cb);
		}
	}
}

function worthy(from, to, matrix) {
	return levenshtein.distance(matrix) < from.children.length/2;
}

function equaliseAttributes(from, to) {
	var src = Array.prototype.slice.call(from.attributes);
	var dest = Array.prototype.slice.call(to.attributes);

	for(var x = 0; x < src.length; x++) {
		if(!to.hasAttribute(src[x].name)) {
			from.removeAttribute(src[x].name);
		}
	}

	for(var y = 0; y < dest.length; y++) {
		if(dest[y].value !== from.getAttribute(dest[y].name)) {
			from.setAttribute(dest[y].name, dest[y].value);
		}
	}
}

function diffChildren(childrenFrom, childrenTo, matrix, parent, cb) {
	var differences = levenshtein.diff(matrix, childrenTo);

	async.map(differences, function(difference, cb) {
		var from = childrenFrom[difference.position];
		var to = difference.value;

		if(difference.type === ':') {
			replace(from, to, cb);
		} else if(difference.type === '+') {
			insert(to, parent, difference.position);
		} else if(difference.type === '-') {
			remove(from, cb);
		} else if(difference.type === '=') {
			transition(from, to, cb);
		}
	}, cb);
}

function isSame(a, b) {
	return a.nodeName === b.nodeName &&
			a.id === b.id &&
			a.getAttribute('diff-id') === b.getAttribute('diff-id');
}

function replace(from, to, cb) {
	var position = siblingCount(from);
	var parent = from.parentNode;

	remove(from, function() {
		insert(to, parent, position, cb);
	});
}

function insert(el, parent, position, cb) {
	el.classList.add('out');
	parent.insertBefore(el, parent.children[position]);

	setTimeout(function() {
		el.classList.add('in');
		el.classList.remove('out');

		function listener() {
			el.removeEventListener('transitionend', listener);
			el.classList.remove('in');
			if(cb) cb();
		}

		if(hasTransition(el)) {
			el.addEventListener('transitionend', listener);
		} else {
			el.classList.remove('in');
			if(cb) cb();
		}
	}, 0);
}

function remove(el, cb) {
	el.classList.add('out');

	function listener() {
		el.removeEventListener('transitionend', listener);
		el.parentNode.removeChild(el);
		cb();
	}

	if(hasTransition(el)) {
		el.addEventListener('transitionend', listener);
	} else {
		el.parentNode.removeChild(el);
		cb();
	}
}

function hasTransition(el) {
	var style = getComputedStyle(el);
	return typeof style.transition === 'string' && style.transitionProperty !== 'none';
}

function siblingCount(el) {
	var i = 0;
	while((el = el.previousSibling)	!== null) if(el.nodeType === 1) i++;
	return i;
}

module.exports = Promise.promisify(transition);<|endoftext|>


<commit_before>import React from 'react';
import {Link} from 'react-router';
import HomeStore from '../stores/HomeStore'
import HomeActions from '../actions/HomeActions';
import {first, without, findWhere} from 'underscore';

class Home extends React.Component {
  constructor(props) {
    super(props);
    this.state = HomeStore.getState();
    this.onChange = this.onChange.bind(this);
  }

  componentDidMount() {
    HomeStore.listen(this.onChange);
  }

  componentWillUnmount() {
    HomeStore.unlisten(this.onChange);
  }

  onChange(state) {
    this.setState(state);
  }

   handleClick() {
      HomeActions.getLoansOfAllBank();
      console.log("Click Here");

  }

  render() {

    // var characterNodes = this.state.characters.map((character, index) => {
    //   return (
    //

    //

    //
    //

    //

    //
Race: {character.race}

    //
Bloodline: {character.bloodline}

    //

    //

    //             <Link to={'/characters/' + character.characterId}>{character.name}</Link>
    //

    //

    //

    //

    //   );
    // });
    var loanNodes = this.state.loans.map((loanItem, index) => {
        return

{loanItem.loanName}

{loanItem.loanAmount}

{loanItem.loanTimeUnit}

{loanItem.loanSysId}

    });

    return (

          {loanNodes}

    );
  }
}

export default Home;<commit_msg>http request demo<commit_after>import React from 'react';
import {Link} from 'react-router';
import HomeStore from '../stores/HomeStore'
import HomeActions from '../actions/HomeActions';
import {first, without, findWhere} from 'underscore';

class Home extends React.Component {
  constructor(props) {
    super(props);
    this.state = HomeStore.getState();
    this.onChange = this.onChange.bind(this);
  }

  componentDidMount() {
    HomeStore.listen(this.onChange);
  }

  componentWillUnmount() {
    HomeStore.unlisten(this.onChange);
  }

  onChange(state) {
    this.setState(state);
  }

   handleClick() {
      HomeActions.getLoansOfAllBank();
      console.log("Click Here");

  }

  render() {
    var loanNodes = this.state.loans.map((loanItem, index) => {
        return

{loanItem.loanName}

{loanItem.loanAmount}

{loanItem.loanTimeUnit}

{loanItem.loanSysId}

    });

    return (

          {loanNodes}

    );
  }
}

export default Home;<|endoftext|>