<commit_before>var request = require('request');
var prompt = require('prompt');
var express = require('express');
var correl8 = require('correl8');
var nopt = require('nopt');
var noptUsage = require('nopt-usage');
var dates = require('moves-date');
var Moves = require('moves');
var moves;

var c8 = correl8('moves');
var defaultPort = 3000;
var defaultUrl = 'http://localhost:' + defaultPort + '/';
var MAX_DAYS = 50;
var summaryIndex = 'moves-summary';
var summaryType = 'moves-summary';
var moveIndex = 'moves-move';
var moveType = 'moves-move';
var placeIndex = 'moves-place';
var placeType = 'moves-place';

var placeFields = {
  type: 'string',
  startTime: 'date',
  endTime: 'date',
  place: {
    id: 'integer',
    type: 'string',
    location: {
      lat: 'float',
      lon: 'float',
      position: 'geo_point'
    }
  },
  'lastUpdate': 'date'
};
var moveFields = {
  type: 'string',
  startTime: 'date',
  endTime: 'date',
  activities: {
    activity: 'string',
    group: 'string',
    manual: 'boolean',
    startTime: 'date',
    endTime: 'date',
    duration: 'float',
    distance: 'float',
    steps: 'integer',
    calories: 'integer',
    trackPoints: {
      lat: 'float',
      lon: 'float',
      position: 'geo_point',
      time: 'date'
    }
  },
  'lastUpdate': 'date'
};
var summaryFields = {
  timestamp: 'date',
  summary: {
    activity: 'string',
    group: 'string',
    duration: 'float',
    distance: 'float',
    steps: 'integer',
    calories: 'integer'
  },
  caloriesIdle: 'integer',
  lastUpdate: 'date'
};

var knownOpts = {
  'authenticate': Boolean,
  'help': Boolean,
  'init': Boolean,
  'clear': Boolean,
  'start': Date,
  'end': Date
};
var shortHands = {
  'h': ['--help'],
  'i': ['--init'],
  'c': ['--clear'],
  'k': ['--key'],
  'from': ['--start'],
  's': ['--start'],
  'to': ['--end'],
  'e': ['--end']
};
var description = {
  'authenticate': ' Store your Moves API credentials and exit',
  'help': ' Display this usage text and exit',
  'init': ' Create the index and exit',
  'clear': ' Clear all data in the index',
  'start': ' Start date as YYYY-MM-DD',
  'end': ' End date as YYYY-MM-DD'
};
var options = nopt(knownOpts, shortHands, process.argv, 1);
var firstDate = options['start'] || null;
var lastDate = options['end'] || new Date();
var conf;

// console.log(options);
if (options['help']) {
  console.log('Usage: ');
  console.log(noptUsage(knownOpts, shortHands, description));
}
else if (options['authenticate']) {
  var app = express();
  app.all('/', function (req, res) {
    if (req.query && req.query.code) {
      c8.config().then(function(result) {
        if (result.hits && result.hits.hits && result.hits.hits[0] && result.hits.hits[0]._source['client_id']) {
          moves = new Moves(result.hits.hits[0]._source);
          moves.token(req.query.code, function(error, response, body) {
            if (error) {
              console.trace(error);
              res.json(error);
              return;
            }
            var rb = JSON.parse(response.body);
            if (rb) {
              if (rb.error) {
                console.trace(rb.error);
                res.json(rb.error);
                return;
              }
              c8.config(rb).then(function(){
                res.send('Access token saved.');
                console.log('Access token saved.');
                c8.release();
                process.exit;
              });
            }
          });
        }
      });
    }
    else {
      res.send('Waiting for code in query string...');
    }
  });
  var server = app.listen(defaultPort, function () {
    var host = server.address().address;
    var port = server.address().port;
    // console.log('Temporary Moves auth server listening at http://%s:%s', host, port);
  });
  var config = {};
  prompt.start();
  prompt.message = '';
  var promptProps = {
    properties: {
      client_id: {
        description: 'Enter your Moves client ID'.magenta
      },
      client_secret: {
        description: 'Enter your Moves client secret'.magenta
      },
      redirect_uri: {
        description: 'Enter your redirect URL (' + defaultUrl+ ')'.magenta
      },
    }
  }
  prompt.get(promptProps, function (err, result) {
    if (err) {
      console.trace(err);
    }
    else {
      config = result;
      console.log(config);
      c8.config(config).then(function(){
        console.log('Configuration stored.');
      }).catch(function(error) {
        console.trace(error);
      });
      moves = new Moves(config);
      var auth_url = moves.authorize({
        scope: ['activity', 'location']
      });
      console.log('Thanks! Now open ' + auth_url + ' in your browser!');
    }
  });
}
else if (options['clear']) {
  c8.type(summaryType).clear().then(function(res) {
    c8.type(placeType).clear().then(function(res) {
      c8.type(moveType).clear().then(function(res) {
        console.log('Index cleared.');
        c8.release();
      });
    });
  }).catch(function(error) {
    console.trace(error);
    c8.release();
  });
}
else if (options['init']) {
  c8.type(summaryType).init(summaryFields).then(function() {
    return c8.type(placeType).init(placeFields);
  }).then(function() {
    return c8.type(moveType).init(moveFields);
  }).then(function(res) {
    console.log('Index initialized.');
    // c8.release();
  }).catch(function(error) {
    console.trace(error);
    c8.release();
  });
}
else {
  c8.config().then(function(res) {
    if (res.hits && res.hits.hits && res.hits.hits[0] && res.hits.hits[0]._source['client_id']) {
      conf = res.hits.hits[0]._source;
      moves = new Moves({
        client_id: conf.client_id,
        client_secret: conf.client_secret,
        redirect_uri: conf.redirect_uri
      });
      c8.type(summaryType).search({
        fields: ['timestamp'],
        size: 1,
        sort: [{'timestamp': 'desc'}],
      }).then(function(response) {
        if (firstDate) {
          console.log('Setting first time to ' + firstDate);
          importData(firstDate);
        }
        else if (response && response.hits && response.hits.hits && response.hits.hits[0] && response.hits.hits[0].fields && response.hits.hits[0].fields.timestamp) {
          console.log('Setting first time to ' + response.hits.hits[0].fields.timestamp);
          firstDate = new Date(response.hits.hits[0].fields.timestamp);
          importData(firstDate);
        }
        else {
          moves.get('/user/profile', conf.access_token, function(error, response, body) {
            if (error) {
              console.trace(error);
              return;
            }
            else if (response.body === 'expired_access_token') {
              refreshToken(conf);
            }
            else {
              var rb = JSON.parse(response.body);
              if (!rb || rb.error) {
                console.trace(rb.error);
                refreshToken(conf);
                return;
              }
              else {
                var user = JSON.parse(body);
                // console.log(user);
                // console.log('Setting first time to Moves date ' + user.profile.firstDate);
                firstDate = dates.parseISODate(user.profile.firstDate);
                importData(firstDate);
              }
            }
          });
        }
      }).catch(function(error) {
        if (error.body && error.body.error && error.body.error.type &&
            error.body.error.type === 'index_not_found_exception') {
          console.log('Init first with --init');
          console.trace(error);
        }
        else {
          console.trace(error);
          var msg = 'Configure first. Go to https://dev.moves-app.com/apps\n' +
          'Create a new app for Correl8. Then run:\nnode ' + process.argv[1] + ' --authenticate';
          console.log(msg);
        }
        c8.release();
      });
    }
    else {
      var msg = 'Configure first. Go to https://dev.moves-app.com/apps\n' +
      'Create a new app for Correl8. Then run:\nnode ' + process.argv[1] + ' --authenticate';
      console.log(msg);
      c8.release();
    }
  });
}

function importData(firstDate) {
  if (!firstDate) {
    console.warn('No starting date...');
    return;
  }
  var startTime = firstDate;
  // startTime.setDate(startTime.getDate() + 1);
  var now = dates.day(new Date());
  var fromDate = dates.day(startTime);
  if (fromDate === now) {
    console.log('Todays data already exists! Try again tomorrow...');
  }
  var dayCount = 0;
  var doneCount = 0;
  while (fromDate < now) {
    toDate = fromDate;
    moves.get('/user/storyline/daily?from=' + fromDate + '&to=' + toDate + '&trackPoints=true', conf.access_token, function(error, response, body) {
      if (error) {
        console.warn(error);
        return;
      }
      else if (response.body === 'expired_access_token') {
        refreshToken();
        return;
      }
      else if (!response.body) {
        console.warn('No response body in history!');
        return;
      }
      else if (response.body.substr(0, 1) != '[') {
        console.warn('Invalid response body in history: ' + response.body)
        return;
      }
      else {
        var rb = JSON.parse(response.body);
        if (!rb || rb.error) {
          refreshToken(getHistory);
        }
        else {
          var document = JSON.parse(body)[0];
          console.log(document.date);
          var bulk = splitToBulk(prepareForElastic(document));
          c8.bulk(bulk).then(function(result) {
            console.log('Indexed ' + result.items.length + ' documents in ' + result.took + ' ms.');
          }).catch(function(error) {
            console.trace(error);
          });
        }
      }
      if (parseInt(response.headers['x-ratelimit-minuteremaining']) < 1) {
        console.warn('Minute limit exceeded!')
        dayCount = MAX_DAYS;
      }
    });
    if (dayCount++ >= MAX_DAYS) {
      return;
    }
    startTime.setDate(startTime.getDate() + 1);
    fromDate = dates.day(startTime);
  }
}

function refreshToken(next) {
  console.log('Refreshing token...');
  moves.refresh_token(refresh_token, function(error, response, body) {
    if (error) {
      console.warn('Refresh got error: ' + error);
      return;
    }
    // console.log(body); // should store!
    var rb = JSON.parse(response.body);
    // console.log(rb);
    if (!rb || rb.error) {
      if (rb.error === 'invalid_grant') {
        console.trace(rb.error);
        // getToken(next);
      }
      console.trace(rb.error);
      // reauthorize();
    }
    else {
      console.log('Token refreshed. Try again!')
      // next(); // possible infinite loop!
    }
  });
}

function prepareForElastic(document) {
  for (var prop in document) {
    // console.log(prop + ' is ' + typeof(document[prop]));
    if (typeof(document[prop]) === 'object') {
      // console.log('Object ' + prop);
      document[prop] = prepareForElastic(document[prop]);
    }
    else if (typeof(document[prop]) === 'array') {
      // console.log('Array ' + prop);
      for (var i=0; i<document[prop].length; i++) {
        document[prop][i] = prepareForElastic(document[prop][i]);
      }
    }
    else if ((prop === 'startTime') || (prop === 'endTime') ||
             (prop === 'date') || (prop === 'time')) {
      // console.log('Date ' + prop);
      document[prop] = dates.parseISODate(document[prop]);
    }
    else if (prop === 'lat') {
      // console.log('Position ' + prop);
      document['position'] = document.lat + ', ' + document.lon;
    }
  }
  return document;
}

function splitToBulk(document) {
  var d = document.date;
  var bulk = [];
  bulk.push({index: {_index: c8.type(summaryType)._index, _type: c8._type}});
  bulk.push({timestamp: d, summary: document.summary, caloriesIdle: document.caloriesIdle, lastUpdate: document.lastUpdate});
  if (document.segments && document.segments.length) {
    for (var i=0; i<document.segments.length; i++) {
      var seg = document.segments[i];
      seg.timestamp = seg.startTime;
      if (seg.type === 'place') {
        seg.position = seg.place.location.position;
      }
      c8.type(seg.type == 'place' ? placeType : moveType);
      bulk.push({index: {_index: c8._index, _type: c8._type}});
      bulk.push(seg);
    }
  }
  return bulk;
}
<commit_msg>add id values to bulk<commit_after>var request = require('request');
var prompt = require('prompt');
var express = require('express');
var correl8 = require('correl8');
var nopt = require('nopt');
var noptUsage = require('nopt-usage');
var dates = require('moves-date');
var Moves = require('moves');
var moves;

var c8 = correl8('moves');
var defaultPort = 3000;
var defaultUrl = 'http://localhost:' + defaultPort + '/';
var MAX_DAYS = 50;
var summaryIndex = 'moves-summary';
var summaryType = 'moves-summary';
var moveIndex = 'moves-move';
var moveType = 'moves-move';
var placeIndex = 'moves-place';
var placeType = 'moves-place';

var placeFields = {
  type: 'string',
  startTime: 'date',
  endTime: 'date',
  place: {
    id: 'integer',
    type: 'string',
    location: {
      lat: 'float',
      lon: 'float',
      position: 'geo_point'
    }
  },
  'lastUpdate': 'date'
};
var moveFields = {
  type: 'string',
  startTime: 'date',
  endTime: 'date',
  activities: {
    activity: 'string',
    group: 'string',
    manual: 'boolean',
    startTime: 'date',
    endTime: 'date',
    duration: 'float',
    distance: 'float',
    steps: 'integer',
    calories: 'integer',
    trackPoints: {
      lat: 'float',
      lon: 'float',
      position: 'geo_point',
      time: 'date'
    }
  },
  'lastUpdate': 'date'
};
var summaryFields = {
  timestamp: 'date',
  summary: {
    activity: 'string',
    group: 'string',
    duration: 'float',
    distance: 'float',
    steps: 'integer',
    calories: 'integer'
  },
  caloriesIdle: 'integer',
  lastUpdate: 'date'
};

var knownOpts = {
  'authenticate': Boolean,
  'help': Boolean,
  'init': Boolean,
  'clear': Boolean,
  'start': Date,
  'end': Date
};
var shortHands = {
  'h': ['--help'],
  'i': ['--init'],
  'c': ['--clear'],
  'k': ['--key'],
  'from': ['--start'],
  's': ['--start'],
  'to': ['--end'],
  'e': ['--end']
};
var description = {
  'authenticate': ' Store your Moves API credentials and exit',
  'help': ' Display this usage text and exit',
  'init': ' Create the index and exit',
  'clear': ' Clear all data in the index',
  'start': ' Start date as YYYY-MM-DD',
  'end': ' End date as YYYY-MM-DD'
};
var options = nopt(knownOpts, shortHands, process.argv, 1);
var firstDate = options['start'] || null;
var lastDate = options['end'] || new Date();
var conf;

// console.log(options);
if (options['help']) {
  console.log('Usage: ');
  console.log(noptUsage(knownOpts, shortHands, description));
}
else if (options['authenticate']) {
  var app = express();
  app.all('/', function (req, res) {
    if (req.query && req.query.code) {
      c8.config().then(function(result) {
        if (result.hits && result.hits.hits && result.hits.hits[0] && result.hits.hits[0]._source['client_id']) {
          moves = new Moves(result.hits.hits[0]._source);
          moves.token(req.query.code, function(error, response, body) {
            if (error) {
              console.trace(error);
              res.json(error);
              return;
            }
            var rb = JSON.parse(response.body);
            if (rb) {
              if (rb.error) {
                console.trace(rb.error);
                res.json(rb.error);
                return;
              }
              c8.config(rb).then(function(){
                res.send('Access token saved.');
                console.log('Access token saved.');
                c8.release();
                process.exit;
              });
            }
          });
        }
      });
    }
    else {
      res.send('Waiting for code in query string...');
    }
  });
  var server = app.listen(defaultPort, function () {
    var host = server.address().address;
    var port = server.address().port;
    // console.log('Temporary Moves auth server listening at http://%s:%s', host, port);
  });
  var config = {};
  prompt.start();
  prompt.message = '';
  var promptProps = {
    properties: {
      client_id: {
        description: 'Enter your Moves client ID'.magenta
      },
      client_secret: {
        description: 'Enter your Moves client secret'.magenta
      },
      redirect_uri: {
        description: 'Enter your redirect URL (' + defaultUrl+ ')'.magenta
      },
    }
  }
  prompt.get(promptProps, function (err, result) {
    if (err) {
      console.trace(err);
    }
    else {
      config = result;
      console.log(config);
      c8.config(config).then(function(){
        console.log('Configuration stored.');
      }).catch(function(error) {
        console.trace(error);
      });
      moves = new Moves(config);
      var auth_url = moves.authorize({
        scope: ['activity', 'location']
      });
      console.log('Thanks! Now open ' + auth_url + ' in your browser!');
    }
  });
}
else if (options['clear']) {
  c8.type(summaryType).clear().then(function(res) {
    c8.type(placeType).clear().then(function(res) {
      c8.type(moveType).clear().then(function(res) {
        console.log('Index cleared.');
        c8.release();
      });
    });
  }).catch(function(error) {
    console.trace(error);
    c8.release();
  });
}
else if (options['init']) {
  c8.type(summaryType).init(summaryFields).then(function() {
    return c8.type(placeType).init(placeFields);
  }).then(function() {
    return c8.type(moveType).init(moveFields);
  }).then(function(res) {
    console.log('Index initialized.');
    // c8.release();
  }).catch(function(error) {
    console.trace(error);
    c8.release();
  });
}
else {
  c8.config().then(function(res) {
    if (res.hits && res.hits.hits && res.hits.hits[0] && res.hits.hits[0]._source['client_id']) {
      conf = res.hits.hits[0]._source;
      moves = new Moves({
        client_id: conf.client_id,
        client_secret: conf.client_secret,
        redirect_uri: conf.redirect_uri
      });
      c8.type(summaryType).search({
        fields: ['timestamp'],
        size: 1,
        sort: [{'timestamp': 'desc'}],
      }).then(function(response) {
        if (firstDate) {
          console.log('Setting first time to ' + firstDate);
          importData(firstDate);
        }
        else if (response && response.hits && response.hits.hits && response.hits.hits[0] && response.hits.hits[0].fields && response.hits.hits[0].fields.timestamp) {
          console.log('Setting first time to ' + response.hits.hits[0].fields.timestamp);
          firstDate = new Date(response.hits.hits[0].fields.timestamp);
          importData(firstDate);
        }
        else {
          moves.get('/user/profile', conf.access_token, function(error, response, body) {
            if (error) {
              console.trace(error);
              return;
            }
            else if (response.body === 'expired_access_token') {
              refreshToken(conf);
            }
            else {
              var rb = JSON.parse(response.body);
              if (!rb || rb.error) {
                console.trace(rb.error);
                refreshToken(conf);
                return;
              }
              else {
                var user = JSON.parse(body);
                // console.log(user);
                // console.log('Setting first time to Moves date ' + user.profile.firstDate);
                firstDate = dates.parseISODate(user.profile.firstDate);
                importData(firstDate);
              }
            }
          });
        }
      }).catch(function(error) {
        if (error.body && error.body.error && error.body.error.type &&
            error.body.error.type === 'index_not_found_exception') {
          console.log('Init first with --init');
          console.trace(error);
        }
        else {
          console.trace(error);
          var msg = 'Configure first. Go to https://dev.moves-app.com/apps\n' +
          'Create a new app for Correl8. Then run:\nnode ' + process.argv[1] + ' --authenticate';
          console.log(msg);
        }
        c8.release();
      });
    }
    else {
      var msg = 'Configure first. Go to https://dev.moves-app.com/apps\n' +
      'Create a new app for Correl8. Then run:\nnode ' + process.argv[1] + ' --authenticate';
      console.log(msg);
      c8.release();
    }
  });
}

function importData(firstDate) {
  if (!firstDate) {
    console.warn('No starting date...');
    return;
  }
  var startTime = firstDate;
  // startTime.setDate(startTime.getDate() + 1);
  var now = dates.day(new Date());
  var fromDate = dates.day(startTime);
  if (fromDate === now) {
    console.log('Todays data already exists! Try again tomorrow...');
  }
  var dayCount = 0;
  var doneCount = 0;
  while (fromDate < now) {
    toDate = fromDate;
    moves.get('/user/storyline/daily?from=' + fromDate + '&to=' + toDate + '&trackPoints=true', conf.access_token, function(error, response, body) {
      if (error) {
        console.warn(error);
        return;
      }
      else if (response.body === 'expired_access_token') {
        refreshToken();
        return;
      }
      else if (!response.body) {
        console.warn('No response body in history!');
        return;
      }
      else if (response.body.substr(0, 1) != '[') {
        console.warn('Invalid response body in history: ' + response.body)
        return;
      }
      else {
        var rb = JSON.parse(response.body);
        if (!rb || rb.error) {
          refreshToken(getHistory);
        }
        else {
          var document = JSON.parse(body)[0];
          console.log(document.date);
          var bulk = splitToBulk(prepareForElastic(document));
          c8.bulk(bulk).then(function(result) {
            console.log('Indexed ' + result.items.length + ' documents in ' + result.took + ' ms.');
          }).catch(function(error) {
            console.trace(error);
          });
        }
      }
      if (parseInt(response.headers['x-ratelimit-minuteremaining']) < 1) {
        console.warn('Minute limit exceeded!')
        dayCount = MAX_DAYS;
      }
    });
    if (dayCount++ >= MAX_DAYS) {
      return;
    }
    startTime.setDate(startTime.getDate() + 1);
    fromDate = dates.day(startTime);
  }
}

function refreshToken(next) {
  console.log('Refreshing token...');
  moves.refresh_token(refresh_token, function(error, response, body) {
    if (error) {
      console.warn('Refresh got error: ' + error);
      return;
    }
    // console.log(body); // should store!
    var rb = JSON.parse(response.body);
    // console.log(rb);
    if (!rb || rb.error) {
      if (rb.error === 'invalid_grant') {
        console.trace(rb.error);
        // getToken(next);
      }
      console.trace(rb.error);
      // reauthorize();
    }
    else {
      console.log('Token refreshed. Try again!')
      // next(); // possible infinite loop!
    }
  });
}

function prepareForElastic(document) {
  for (var prop in document) {
    // console.log(prop + ' is ' + typeof(document[prop]));
    if (typeof(document[prop]) === 'object') {
      // console.log('Object ' + prop);
      document[prop] = prepareForElastic(document[prop]);
    }
    else if (typeof(document[prop]) === 'array') {
      // console.log('Array ' + prop);
      for (var i=0; i<document[prop].length; i++) {
        document[prop][i] = prepareForElastic(document[prop][i]);
      }
    }
    else if ((prop === 'startTime') || (prop === 'endTime') ||
             (prop === 'date') || (prop === 'time')) {
      // console.log('Date ' + prop);
      document[prop] = dates.parseISODate(document[prop]);
    }
    else if (prop === 'lat') {
      // console.log('Position ' + prop);
      document['position'] = document.lat + ', ' + document.lon;
    }
  }
  return document;
}

function splitToBulk(document) {
  var d = document.date;
  var bulk = [];
  bulk.push({index: {_index: c8.type(summaryType)._index, _type: c8._type}});
  bulk.push({timestamp: d, summary: document.summary, caloriesIdle: document.caloriesIdle, lastUpdate: document.lastUpdate});
  if (document.segments && document.segments.length) {
    for (var i=0; i<document.segments.length; i++) {
      var seg = document.segments[i];
      seg.timestamp = seg.startTime;
      if (seg.type === 'place') {
        seg.position = seg.place.location.position;
        seg.id = seg.timestamp + '-' + seg.place.id;
        c8.type(placeType);
      }
      else {
        c8.type(moveType);
        seg.id = seg.timestamp + '-' + seg.activity;
      }
      bulk.push({index: {_index: c8._index, _type: c8._type, _id: seg.id}});
      bulk.push(seg);
    }
  }
  return bulk;
}
<|endoftext|>


<commit_before>// ==UserScript==
// @name         mute-chat
// @namespace    https://github.com/EFox2413
// @version      0.1
// @author       EFox2413
// @match        https://www.playinitium.com/*
// @grant        none
// ==/UserScript==
/* jshint -W097 */
'use strict';

var $ = window.jQuery;

var banList = [];

// add a ban
function addBan( name ) {
    if (checkNameOnBanList( name )) {
        console.log( name + " is on ban list already.");
        return;
    }
    banList.push(name);
}

// remove a ban from banList
function unBan( name ) {
    var removed = false;
    banList.forEach( function( each, ind ) {
        if (name.localeCompare(each) == 0) {
            banList.splice(ind, 1);
            removed = true;
        }
    });

    if (removed === false) {
        console.log(name + " is not muted.");
    }
}

// mainly for debug, prints every item on banList
function getBanList() {
    banList.forEach( function( each ) {
        console.log(each + ";");
    });
}

// check if name is on ban list
function checkNameOnBanList( name ) {
    for (var i = 0; i < banList.length; i++) {
        if ( banList[i].localeCompare(name) == 0 ) {
            return true;
        }
    }
    return false;
}

// verify the sender of message is the one playing the game
function myMessage( id ) {
    var relStr = $( '.character-display-box' ).children( 'a' ).attr( 'rel' ).toString();
    var myId = relStr.substring(relStr.search( 'Id=') + 3);

    if ( id == myId ) {
        return true;
    }
    return false;
}

messager.onChatMessage = function(chatMessage) {
    // check if sender's name is on ban list
    console.log(chatMessage.nickname + ", banned: " + checkNameOnBanList(chatMessage.nickname));

    if (checkNameOnBanList(chatMessage.nickname) == true) {
        //        console.log("message surpressed, exit function");
        return;
    }

    // check if mute command is sent
    if (chatMessage.message.startsWith('/mute ')) {
        if ( myMessage(chatMessage.characterId )) {
            if ( chatMessage.nickname != chatMessage.message.substring(6) ) {
                addBan(chatMessage.message.substring(6));
            }
        }
    }

    // check if unmute command is sent
    if (chatMessage.message.startsWith('/unmute ')) {
        if( myMessage(chatMessage.characterId )) {
            unBan(chatMessage.message.substring(8));
        }
    }

    var html = "
";
    if (chatMessage.createdDate!=null)
    {
        var date = new Date(chatMessage.createdDate);
        var shortTime = date.toLocaleTimeString();
        var cutoff = shortTime.length;
        if (shortTime.indexOf(":")>0)
            cutoff = shortTime.lastIndexOf(":");
        else if (shortTime.indexOf(".")>0)
            cutoff = shortTime.lastIndexOf(".");

        shortTime = shortTime.substring(0, cutoff);
        var longDate = date.toLocaleDateString();

        html+="";
        html+="["+shortTime+"] ";
        html+="";
    }
    if (chatMessage.code=="PrivateChat")
    {
        html+=""+chatMessage.nickname+"";
        html+="";
        html+=" ";
        html+=chatMessage.message;
        html+="
";
    }
    else if (chatMessage.mode==null)
    {
        var meMode = chatMessage.message.startsWith("/me ");

        html+="";

        if (chatMessage.characterId!=null && chatMessage.message.startsWith('/me  ')) {
            html += "<a class='clue' style='color:" + '#'+(Math.random()*0xFFFFFF<<0).toString(16) + "' rel='viewcharactermini.jsp?characterId=" + chatMessage.characterId + "'>" + chatMessage.nickname + ":";
        } else if (chatMessage.characterId!=null && meMode==false) {
            html+=chatMessage.nicknameStyled;
        } else
            html+=chatMessage.nickname;
        html+="";
        html+="";

        if (meMode)
        {
            html+=" ";
            chatMessage.message = chatMessage.message.substring(4);
        }
        else
            html+=": ";
        html+=chatMessage.message;
        html+="
";
    }
    else if (chatMessage.mode=="admin")
    {
        html+="";
        html+=chatMessage.message;
        html+="
";
    }
    html+="
";
    $("#chat_messages_"+chatMessage.code).prepend(html);

    notifyNewMessage(chatMessage.code);
};
<commit_msg>Add an additional match line for http (mute-chat.js)<commit_after>// ==UserScript==
// @name         mute-chat
// @namespace    https://github.com/EFox2413
// @version      0.1
// @author       EFox2413
// @match        https://www.playinitium.com/*
// @match        http://www.playinitium.com/*
// @grant        none
// ==/UserScript==
/* jshint -W097 */
'use strict';

var $ = window.jQuery;

var banList = [];

// add a ban
function addBan( name ) {
    if (checkNameOnBanList( name )) {
        console.log( name + " is on ban list already.");
        return;
    }
    banList.push(name);
}

// remove a ban from banList
function unBan( name ) {
    var removed = false;
    banList.forEach( function( each, ind ) {
        if (name.localeCompare(each) == 0) {
            banList.splice(ind, 1);
            removed = true;
        }
    });

    if (removed === false) {
        console.log(name + " is not muted.");
    }
}

// mainly for debug, prints every item on banList
function getBanList() {
    banList.forEach( function( each ) {
        console.log(each + ";");
    });
}

// check if name is on ban list
function checkNameOnBanList( name ) {
    for (var i = 0; i < banList.length; i++) {
        if ( banList[i].localeCompare(name) == 0 ) {
            return true;
        }
    }
    return false;
}

// verify the sender of message is the one playing the game
function myMessage( id ) {
    var relStr = $( '.character-display-box' ).children( 'a' ).attr( 'rel' ).toString();
    var myId = relStr.substring(relStr.search( 'Id=') + 3);

    if ( id == myId ) {
        return true;
    }
    return false;
}

messager.onChatMessage = function(chatMessage) {
    // check if sender's name is on ban list
    console.log(chatMessage.nickname + ", banned: " + checkNameOnBanList(chatMessage.nickname));

    if (checkNameOnBanList(chatMessage.nickname) == true) {
        //        console.log("message surpressed, exit function");
        return;
    }

    // check if mute command is sent
    if (chatMessage.message.startsWith('/mute ')) {
        if ( myMessage(chatMessage.characterId )) {
            if ( chatMessage.nickname != chatMessage.message.substring(6) ) {
                addBan(chatMessage.message.substring(6));
            }
        }
    }

    // check if unmute command is sent
    if (chatMessage.message.startsWith('/unmute ')) {
        if( myMessage(chatMessage.characterId )) {
            unBan(chatMessage.message.substring(8));
        }
    }

    var html = "
";
    if (chatMessage.createdDate!=null)
    {
        var date = new Date(chatMessage.createdDate);
        var shortTime = date.toLocaleTimeString();
        var cutoff = shortTime.length;
        if (shortTime.indexOf(":")>0)
            cutoff = shortTime.lastIndexOf(":");
        else if (shortTime.indexOf(".")>0)
            cutoff = shortTime.lastIndexOf(".");

        shortTime = shortTime.substring(0, cutoff);
        var longDate = date.toLocaleDateString();

        html+="";
        html+="["+shortTime+"] ";
        html+="";
    }
    if (chatMessage.code=="PrivateChat")
    {
        html+=""+chatMessage.nickname+"";
        html+="";
        html+=" ";
        html+=chatMessage.message;
        html+="
";
    }
    else if (chatMessage.mode==null)
    {
        var meMode = chatMessage.message.startsWith("/me ");

        html+="";

        if (chatMessage.characterId!=null && chatMessage.message.startsWith('/me  ')) {
            html += "<a class='clue' style='color:" + '#'+(Math.random()*0xFFFFFF<<0).toString(16) + "' rel='viewcharactermini.jsp?characterId=" + chatMessage.characterId + "'>" + chatMessage.nickname + ":";
        } else if (chatMessage.characterId!=null && meMode==false) {
            html+=chatMessage.nicknameStyled;
        } else
            html+=chatMessage.nickname;
        html+="";
        html+="";

        if (meMode)
        {
            html+=" ";
            chatMessage.message = chatMessage.message.substring(4);
        }
        else
            html+=": ";
        html+=chatMessage.message;
        html+="
";
    }
    else if (chatMessage.mode=="admin")
    {
        html+="";
        html+=chatMessage.message;
        html+="
";
    }
    html+="
";
    $("#chat_messages_"+chatMessage.code).prepend(html);

    notifyNewMessage(chatMessage.code);
};
<|endoftext|>


<commit_before>var api_factory = require('./common').api_factory,
    out = require('./common').out,
    fs = require('fs');

module.exports = function(router, req, resp, next, opt) {
    /* 获取 API 详情 */
    var APIS = api_factory(opt);
    var matches = req['url'].match(router);
    var apiname = matches[1];
    if (APIS[apiname]) {
        var item = APIS[apiname];
        var result = {
            name: item['name'],
            title: item['title'],
            version: item['version'],
            desc: item['desc'],
            cost: item['cost'],
            icon: item['icon'],
            conf: item['endpoint']['app']['conf']
        };
        out(resp, 200, content, JSON.stringify({
            'err': null,
            'result': result
        }, null, 4));
    } else {
        out(resp, 404, JSON.stringify({ 'err': 'not found' }, null, 4));
    };
}
<commit_msg>upadted<commit_after>var api_factory = require('./common').api_factory,
    out = require('./common').out,
    fs = require('fs');

module.exports = function(router, req, resp, next, opt) {
    /* 获取 API 详情 */
    var APIS = api_factory(opt);
    var matches = req['url'].match(router);
    var apiname = matches[1];
    if (APIS[apiname]) {
        var item = APIS[apiname];
        var result = {
            name: item['name'],
            title: item['title'],
            version: item['version'],
            desc: item['desc'],
            cost: item['cost'],
            icon: item['icon'],
            conf: item['endpoint']['app']['conf']
        };
        out(resp, 200, JSON.stringify({
            'err': null,
            'result': result
        }, null, 4));
    } else {
        out(resp, 404, JSON.stringify({ 'err': 'not found' }, null, 4));
    };
}
<|endoftext|>


<commit_before>var $overlay = $('

');
var $image = $("");
var $caption = $("

");
/* variables */
$overlay.append($image);
$overlay.append($caption);
$("#portfolio").append($overlay);
$overlay.hide();

/* lightbox jquery */
$(".col-sm-6 a").click(function() {
    event.preventDefault();
    var href = $(this).attr("href");
    console.log(href);
    $image.attr("src", href);
    $overlay.show();

    var captionText = $(this).children("img").attr("alt");
    $caption.text(captionText);
});

$overlay.click(function() {
    $overlay.hide();
});

/* place holder response in lieu of back-end */
$(".sub").click(function () {
    event.preventDefault();
    $(".col-md-8").replaceWith("
Thank you for your submission!
")
});<commit_msg>logging button press<commit_after>var $overlay = $('

');
var $image = $("");
var $caption = $("

");
/* variables */
$overlay.append($image);
$overlay.append($caption);
$("#portfolio").append($overlay);
$overlay.hide();

/* lightbox jquery */
$(".col-sm-6 a").click(function() {
    event.preventDefault();
    var href = $(this).attr("href");
    console.log(href);
    $image.attr("src", href);
    $overlay.show();

    var captionText = $(this).children("img").attr("alt");
    $caption.text(captionText);
});

$overlay.click(function() {
    $overlay.hide();
});

/* place holder response in lieu of back-end */
$(".sub").click(function () {
    event.preventDefault();
    console.log(this);
    $(".col-md-8").replaceWith("
Thank you for your submission!
")
});<|endoftext|>


<commit_before>(function(window, document, undefined) {
    window.onload = init;
    function init() {
        //get the canvas
        var canvas = document.getElementById("mapcanvas");
        var c = canvas.getContext("2d");
        var cwidth = 960;
        var cheight = 540;
        var moves = {
            u: [0,-1],
            d: [0,1],
            l: [-1,0],
            r: [1,0]
        };
        document.getElementById("paintbtn").onclick = paint;

        function shuffle(array) {
          var currentIndex = array.length, temporaryValue, randomIndex ;

          // While there remain elements to shuffle...
          while (0 !== currentIndex) {

            // Pick a remaining element...
            randomIndex = Math.floor(Math.random() * currentIndex);
            currentIndex -= 1;

            // And swap it with the current element.
            temporaryValue = array[currentIndex];
            array[currentIndex] = array[randomIndex];
            array[randomIndex] = temporaryValue;
          }

          return array;
        }

        function reset(){
            c.clearRect ( 0 , 0 , canvas.width, canvas.height );
            c.beginPath();
        }

        function walk(start, stop, steps){
            var distX = stop.x - start.x;
            var distY = stop.y - start.y;

            var walkSteps = [];
            for(var i = 0; i< Math.abs(distX); i++){
                if(distX < 0){
                    walkSteps.push(moves.l);
                } else {
                    walkSteps.push(moves.r);
                }
            }
            for(var i = 0; i< Math.abs(distY); i++){
                if(distY < 0){
                    walkSteps.push(moves.u);
                } else {
                    walkSteps.push(moves.d);
                }
            }

            //add a number of random pairs based on how big our grid is
            for(var i = 0; i< steps; i++){
                var rand = Math.floor(Math.random() * 2);
                if(rand < 1){
                    walkSteps.push(moves.u);
                    walkSteps.push(moves.d);
                } else{
                    walkSteps.push(moves.l);
                    walkSteps.push(moves.r);
                }
            }

            return shuffle(walkSteps);
        }

        function createRoom(x, y, pw, ph){
            var randw = Math.floor((Math.random() * (pw/2) + 1) );
            var randh = Math.floor((Math.random() * (ph/2) + 1) );
            //alert(randw + ", " + randh);

            return [randw, randh];
        }

        function paint(){
            reset();

            var widthSelect = document.getElementById("width");
            var pathWidth = widthSelect.options[widthSelect.selectedIndex].value;

            var heightSelect = document.getElementById("height");
            var pathHeight = heightSelect.options[heightSelect.selectedIndex].value;
            //alert(pathWidth + ", " + pathHeight);

            //create a start and endpoint based on the grid size
            var startpoint = {
               x: -1,
               y: -1
            }
           var endpoint = {
               x: -1,
               y: -1
            }
            startpoint.x = 0;
            startpoint.y = pathHeight - 1;

            endpoint.x = pathWidth - 1;
            endpoint.y = 0;

            //paint the base grid
            for(var i = 0; i< pathWidth; i++){
                for(var j = 0; j< pathHeight; j++){

                    c.beginPath();
                    //c.lineWidth = 1;
                    c.fillStyle = "#000000";
                    c.fillRect(i*30, j*30, 30, 30);
                    c.stroke();
               }
           }

           var randsteps = 2* Math.floor((pathWidth/2) * (pathHeight/2));

           //create a random path that we will walk
           var walkArray = walk(startpoint, endpoint, randsteps);

           //create two moving points representing where we are and where we were
           var movingpoint = {
               x: -1,
               y: -1
           };
           var movingpointold = {
               x: -1,
               y: -1
           };
           movingpoint.x = startpoint.x;
           movingpoint.y = startpoint.y;
           movingpointold.x = startpoint.x;
           movingpointold.y = startpoint.y;

           //follow the path and paint along the way
           for (var i = 0; i< walkArray.length; i++){
               movingpoint.x = movingpoint.x + walkArray[i][0];
               movingpoint.y = movingpoint.y + walkArray[i][1];
               var oppcurrMoveX = -1 * walkArray[i][0];
               var oppcurrMoveY = -1 * walkArray[i][1];
               var index = -1;
               for(var j = i; j< walkArray.length; j++){
                   if(walkArray[j][0] == oppcurrMoveX && walkArray[j][1] == oppcurrMoveY){
                       index = j;
                       break;
                   }
               }
               if(movingpoint.x > pathWidth -1){
                   movingpoint.x = movingpoint.x - 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }

               }
               if(movingpoint.x < 0){
                   movingpoint.x = movingpoint.x + 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }

               }
               if(movingpoint.y > pathHeight -1){
                   movingpoint.y = movingpoint.y - 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }

               }
               if( movingpoint.y < 0){
                   movingpoint.y = movingpoint.y + 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }

               }

               var movedirX = movingpoint.x - movingpointold.x;
               var movedirY = movingpoint.y - movingpointold.y;

               for(var l = 0; l< 30; l++){
                   c.fillStyle = "#FFFFFF";
                   c.fillRect(movingpointold.x*30 + l*movedirX + 9, movingpointold.y*30 + l*movedirY + 9, 6, 6);
               }

               c.fillStyle = "#FFFFFF";
               c.fillRect(movingpoint.x*30, movingpoint.y*30, 24, 24);

               movingpointold.x = movingpoint.x;
               movingpointold.y = movingpoint.y;
           }

            for(var i = 0; i< Math.floor(pathWidth/2)+1; i++){
                for(var j = 0; j< Math.floor(pathHeight/2)+1; j++){
                    var randRoom = Math.floor((Math.random() * 9));
                    if(randRoom < 1){
                        roomDim = createRoom(i,j,pathWidth,pathHeight);
                        c.beginPath();
                        //c.lineWidth = 3;
                        c.fillStyle = "#FFFFFF";
                        c.fillRect(i*30 , j*30, roomDim[0]*30 - 6, roomDim[1]*30 - 6);
                        c.stroke();
                    }
                }
            }

            //paint the start and end points.
            c.fillStyle = "#33CC33";
            c.fillRect(startpoint.x*30, startpoint.y*30, 24, 24);
            c.fillStyle = "#CC0000";
            c.fillRect(endpoint.x*30, endpoint.y*30, 24 ,24);
        }
    }
})(window, document, undefined);
<commit_msg>Update script.js<commit_after>(function(window, document, undefined) {
    window.onload = init;
    function init() {
        //get the canvas
        var canvas = document.getElementById("mapcanvas");
        var c = canvas.getContext("2d");
        var cwidth = 960;
        var cheight = 540;
        var moves = {
            u: [0,-1],
            d: [0,1],
            l: [-1,0],
            r: [1,0]
        };
        document.getElementById("paintbtn").onclick = paint;

        function floodfill(node, targetcolor, replacementcolor){
            if(targetcolor == replacementcolor){
                return;
            }
            if(node.color != targetcolor){
                return;
            }
            node.color = replacementcolor;
            westnode = {
                x:0,
                y:0
            };
            westnode.x = node.x - 1;
            westnode.y = node.y;
            eastnode = {
                x:0,
                y:0
            };
            eastnode.x = node.x + 1;
            eastnode.x = node.x
            northnode = {
                x:0,
                y:0
            };
            northnode.x = node.x;
            northnode.y = node.y - 1;
            southnode = {
                x:0,
                y:0
            };
            southnode.x = node.x;
            southnode.y = node.y + 1;
            floodfill(westnode, targetcolor, replacementcolor);
            floodfill(eastnode, targetcolor, replacementcolor);
            floodfill(northnode, targetcolor, replacementcolor);
            floodfill(southnode, targetcolor, replacementcolor);
            return;

        }

        function shuffle(array) {
          var currentIndex = array.length, temporaryValue, randomIndex ;

          // While there remain elements to shuffle...
          while (0 !== currentIndex) {

            // Pick a remaining element...
            randomIndex = Math.floor(Math.random() * currentIndex);
            currentIndex -= 1;

            // And swap it with the current element.
            temporaryValue = array[currentIndex];
            array[currentIndex] = array[randomIndex];
            array[randomIndex] = temporaryValue;
          }

          return array;
        }

        function reset(){
            c.clearRect ( 0 , 0 , canvas.width, canvas.height );
            c.beginPath();
        }

        function walk(start, stop, steps){
            var distX = stop.x - start.x;
            var distY = stop.y - start.y;

            var walkSteps = [];
            for(var i = 0; i< Math.abs(distX); i++){
                if(distX < 0){
                    walkSteps.push(moves.l);
                } else {
                    walkSteps.push(moves.r);
                }
            }
            for(var i = 0; i< Math.abs(distY); i++){
                if(distY < 0){
                    walkSteps.push(moves.u);
                } else {
                    walkSteps.push(moves.d);
                }
            }

            //add a number of random pairs based on how big our grid is
            for(var i = 0; i< steps; i++){
                var rand = Math.floor(Math.random() * 2);
                if(rand < 1){
                    walkSteps.push(moves.u);
                    walkSteps.push(moves.d);
                } else{
                    walkSteps.push(moves.l);
                    walkSteps.push(moves.r);
                }
            }

            return shuffle(walkSteps);
        }

        function createRoom(x, y, pw, ph){
            var randw = Math.floor((Math.random() * (pw/2) + 1) );
            var randh = Math.floor((Math.random() * (ph/2) + 1) );
            //alert(randw + ", " + randh);

            return [randw, randh];
        }

        function paint(){
            reset();

            var widthSelect = document.getElementById("width");
            var pathWidth = widthSelect.options[widthSelect.selectedIndex].value;

            var heightSelect = document.getElementById("height");
            var pathHeight = heightSelect.options[heightSelect.selectedIndex].value;
            //alert(pathWidth + ", " + pathHeight);

            //create a start and endpoint based on the grid size
            var startpoint = {
               x: -1,
               y: -1
            }
           var endpoint = {
               x: -1,
               y: -1
            }
            startpoint.x = 0;
            startpoint.y = pathHeight - 1;

            endpoint.x = pathWidth - 1;
            endpoint.y = 0;

            //paint the base grid
            for(var i = 0; i< pathWidth; i++){
                for(var j = 0; j< pathHeight; j++){

                    c.beginPath();
                    //c.lineWidth = 1;
                    c.fillStyle = "#000000";
                    c.fillRect(i*30, j*30, 30, 30);
                    c.stroke();
               }
           }

           var randsteps = 2* Math.floor((pathWidth/2) * (pathHeight/2));

           //create a random path that we will walk
           var walkArray = walk(startpoint, endpoint, randsteps);

           //create two moving points representing where we are and where we were
           var movingpoint = {
               x: -1,
               y: -1
           };
           var movingpointold = {
               x: -1,
               y: -1
           };
           movingpoint.x = startpoint.x;
           movingpoint.y = startpoint.y;
           movingpointold.x = startpoint.x;
           movingpointold.y = startpoint.y;

           //follow the path and paint along the way
           for (var i = 0; i< walkArray.length; i++){
               movingpoint.x = movingpoint.x + walkArray[i][0];
               movingpoint.y = movingpoint.y + walkArray[i][1];
               var oppcurrMoveX = -1 * walkArray[i][0];
               var oppcurrMoveY = -1 * walkArray[i][1];
               var index = -1;
               for(var j = i; j< walkArray.length; j++){
                   if(walkArray[j][0] == oppcurrMoveX && walkArray[j][1] == oppcurrMoveY){
                       index = j;
                       break;
                   }
               }
               if(movingpoint.x > pathWidth -1){
                   movingpoint.x = movingpoint.x - 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }

               }
               if(movingpoint.x < 0){
                   movingpoint.x = movingpoint.x + 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }

               }
               if(movingpoint.y > pathHeight -1){
                   movingpoint.y = movingpoint.y - 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }

               }
               if( movingpoint.y < 0){
                   movingpoint.y = movingpoint.y + 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }

               }

               var movedirX = movingpoint.x - movingpointold.x;
               var movedirY = movingpoint.y - movingpointold.y;

               for(var l = 0; l< 30; l++){
                   c.fillStyle = "#FFFFFF";
                   c.fillRect(movingpointold.x*30 + l*movedirX + 9, movingpointold.y*30 + l*movedirY + 9, 6, 6);
               }

               c.fillStyle = "#FFFFFF";
               c.fillRect(movingpoint.x*30, movingpoint.y*30, 24, 24);

               movingpointold.x = movingpoint.x;
               movingpointold.y = movingpoint.y;
           }

            for(var i = 0; i< Math.floor(pathWidth/2)+1; i++){
                for(var j = 0; j< Math.floor(pathHeight/2)+1; j++){
                    var randRoom = Math.floor((Math.random() * 9));
                    if(randRoom < 1){
                        roomDim = createRoom(i,j,pathWidth,pathHeight);
                        c.beginPath();
                        //c.lineWidth = 3;
                        c.fillStyle = "#FFFFFF";
                        c.fillRect(i*30 , j*30, roomDim[0]*30 - 6, roomDim[1]*30 - 6);
                        c.stroke();
                    }
                }
            }

            //paint the start and end points.
            c.fillStyle = "#33CC33";
            c.fillRect(startpoint.x*30, startpoint.y*30, 24, 24);
            c.fillStyle = "#CC0000";
            c.fillRect(endpoint.x*30, endpoint.y*30, 24 ,24);

            var imgdata = c.getImageData(0,0,1,1).data;
        }
    }
})(window, document, undefined);
<|endoftext|>


<commit_before>(function() {

	// load the available notes and tags.
	loadNotes(0);
	loadTags();
	var showingComplete = false;
	var $noteList = $('#note-list');
	var $completedNoteButton = $('#complete-notes-button');
	var $showAllNotesButton = $('#show-all-notes-button');
	var $newNoteSection = $('#new-note-section');

	function loadNotes(complete) {

		$.ajax({
			url: 'includes/load-note.php',
			method: 'POST',
			data: {
				userId: userId,
				complete: complete
			}
		})
		.done(function(data, result) {
			if(result === 'success') {

				if(data !== 'none') {
					$noteList.append(data);
				} else {
					$noteList.append('It appears that you have not yet created any notes. Create your first one.');
				}

				if(complete !== 1) {
					$showAllNotesButton.show();
					$completedNoteButton.html('	Show Completed Notes');
				} else {
					// change the button text. Remove the show all notes.
					$showAllNotesButton.hide();
					$completedNoteButton.html('	Show Active Notes');
				}
			}
		})
		.fail(function(error) {
			console.log('It failed: ', error);
		});
	}

	function loadTags() {

		$.ajax({
			url: 'includes/load-tags.php',
			method: 'POST'
		})
		.done(function(data, result) {
			if(result == 'success') {
				$('#add-note-tags').append(data);
				toastr.info('Loading success');
			}
		})
		.fail(function(error) {
			console.log(error);
		});
	}

	function addTag(where, input, edit) {
		var newTag = $(input).val();

		if(newTag.trim() !== '') {
			if(edit) {
				$(where).append('
<input type="checkbox" checked name="edit-tag" data-tag="' + newTag + '" value="' + newTag + '">' + newTag + '
');
			} else {
				$(where).append('
<input type="checkbox" checked name="new-tag" data-tag="' + newTag + '" value="' + newTag + '">' + newTag + '
');
			}
			$(input).val('');
		}
	}

	toastr.options = {
		"timeOut": "2000",
		"preventDuplicates": false,
		"closeButton": true
	};

	// Hide the form to create new note until clicked
	$newNoteSection.hide();
	$('.note-text-validation, .edit-note-text-validation').hide();

	$('#new-note-button').on('click', function(){
		$newNoteSection.toggle();
	});

/* 	$('#show-new-tag-button').on('click', function() {
		$('#new-tag-section').toggle();
	}); */

	$showAllNotesButton.on('click', function() {
		$('.note').show();
	});

	$('#add-note-button').on('click', function() {

		var noteText = $('#add-note-text').val();
		var noteTitle = $('#add-note-title').val();
		var tagArray = [];

		if(noteText.trim() === '') {
			$('.note-text-validation').show();
			return;
		}

		$('input:checkbox[name=new-tag]:checked').each(function() {
			tagArray.push($(this).val());
		});

		$.ajax({
			url: 'includes/add-new-note.php',
			method: 'POST',
			data: {
				noteText: noteText,
				noteTags: tagArray,
				noteTitle: noteTitle,
				userId: userId
			}
		})
		.done(function(data, result) {
			var tags = '';
			$.each(tagArray, function(index, value) {
				tags += '' + value + '';
			});

			$noteList.append('
Note ID: ' + data + '
' + noteTitle + '

' + noteText + '
' + tags + '

');

			// Reset and confirmation.
			$('#add-note-title').val('');
			$('#add-note-text').val('');
			$('input:checkbox[name=new-tag]').removeAttr('checked');
			tagsToAdd = [];
			toastr.success('Note has been added successfully!');
			$newNoteSection.hide();
		})
		.fail(function(error) {
			console.log('There was a failure: ', error);
		});

	});

	$('#show-new-tag-button').on('click', function() {
		addTag('#add-note-tags', '#add-new-tag-text', false);
	});

	$('#edit-new-tag-button').on('click', function() {
		addTag('#edit-note-tags', '#edit-new-tag-text', true);
	});

	$noteList.on('click', '.note-tags', function() {

		var tag = $(this).data('tag');
		var notes = $('.note');
		var hide = [];
		$('.note').show();

		$.each(notes, function(index, value) {
			$value = $(value);

			var tags = $value.children('.note-tags');
			var tagData = [];

			$.each(tags, function(i, childTag) {
				$this = $(childTag);
				var data = $this.data('tag');
				tagData.push(data);
			});

			if(tagData.indexOf(tag) === -1) {
				hide.push(value);
			}
		});

		$.each(hide, function(index, value) {
			$(value).hide();
		});

		toastr.info('Now only showing notes with the tag "' + tag + '"');
	});

	$noteList.on('click', '.remove-note', function() {

		if(!confirm('Are you sure you wish to remove this note?')) {
			return;
		}

		$this = $(this);
		var deleteId = $this.closest('.note').data('id');

 		$.ajax({
			method: 'POST',
			url: 'includes/delete-note.php',
			data: {
				deleteNote: deleteId
			}
		})
		.done(function(data, result) {
			$this.closest('.note').remove();
			toastr.success('Note has been deleted!');
		})
		.fail(function(error) {
			console.log('An error has occurred: ', error);
		});

	});

	$noteList.on('click', '.edit-note', function() {
		// edit the note in the database.
		// also edit the note which is in the DOM
		// would probably be best to have this done in a modal.
		// TODO : above - skeleton code is below.
		$this = $(this);
		var noteId = $this.closest('.note').data('id');
		$('#save-note-button').data('id', noteId);
		var parent = $this.closest('.note');

		var $parent = $(parent);
		var title = $parent.find('.note-title')[0].textContent;
		var text = $parent.find('.note-text')[0].textContent;
		var tags = $parent.find('.note-tags');

		var tagArray = [];

		$.each(tags, function(index, value) {
			tagArray.push(value.textContent);
		});

		$('#note-edit-modal').modal('show');
		$('#edit-note-tags').empty();
		$('#edit-note-title').val(title);
		$('#edit-note-text').val(text);
		$.each(tagArray, function(index, value) {
			$('#edit-note-tags').append('
<input type="checkbox" checked name="edit-tag" data-tag="' + value + '" value="' + value + '">' + value + '
');
		});

		// TODO : when the modals okay button is clicked take the new data and update the database with it.
	});

	$noteList.on('click', '.note-done', function() {

		$this = $(this);
		var noteId = $this.closest('.note').data('id');

		$.ajax({
			method: 'POST',
			url: 'includes/note-done.php',
			data: {
				noteId: noteId,
				complete: 1
			}
		})
		.done(function(data, result) {
			console.log(data, result)
			$this.closest('.note').remove();
			toastr.success('Note marked as complete!');
		})
		.fail(function(error) {
			console.log('An error has occurred: ', error);
		});

	});

	$completedNoteButton.on('click', function() {
		if(showingComplete) {
			$noteList.empty();
			$completedNoteButton.html('	Show Completed Notes');
			showingComplete = false;
			loadNotes(0);
		} else {
			$noteList.empty();
			$completedNoteButton.html('	Show Active Notes');
			showingComplete = true;
			loadNotes(1);
		}
	});

	$noteList.on('click', '.mark-note-active', function() {

 		$this = $(this);
		var noteId = $this.closest('.note').data('id');
		console.log(noteId)
		$.ajax({
			method: 'POST',
			url: 'includes/note-done.php',
			data: {
				noteId: noteId,
				complete: 0
			}
		})
		.done(function(data, result) {
			console.log(data, result)
			$this.closest('.note').remove();
			toastr.success('Note marked as active!');
		})
		.fail(function(error) {
			console.log('An error has occurred: ', error);
		});

	});

	$('#save-note-button').on('click', function() {

 		var title = $('#edit-note-title').val();
		var text = $('#edit-note-text').val();
		var tagArray = [];
		var noteId = $('#save-note-button').data('id');

		$('input:checkbox[name=edit-tag]:checked').each(function() {
			tagArray.push($(this).val());
		});

 		$.ajax({
			method: 'POST',
			url: 'includes/edit-note.php',
			data: {
				noteText: text,
				noteId: noteId,
				noteTitle: title,
				noteTags: tagArray
			}
		})
		.done(function(data, result) {
			// update the DOM here.
			var note = $('[data-id="' + noteId + '"]');
			$(note).children('.note-title')[0].textContent = title;
			$(note).children('.note-text')[0].textContent = text;
			var newText = $(note).children('.note-text')[0];
			$(note).children('.note-tags').remove();
			var tags = '';

			$.each(tagArray, function(index, value) {
				tags += '' + value + '';
			});

			$(newText).after(tags);

			$('#note-edit-modal').modal('hide');

			toastr.success('Note successfully updated!');
		})
		.fail(function(error) {
			console.log('An error has occurred: ', error);
		});
	});

	$noteList.on('click', '#note-edit-modal', function() {
		$('#note-edit-modal').show();
	})

	$('#close-new-note').on('click', function() {
		$newNoteSection.hide();
	});

	$('#add-note-text').on('keyup', function() {
		$('.note-text-validation').hide();
	});

	$('#edit-note-text').on('keyup', function() {
		$('.edit-note-text-validation').hide();
	});

	$('#add-new-tag-text').on('keyup', function(event) {
		if(event.keyCode == 13) {
			addTag('#add-note-tags', '#add-new-tag-text', false);
		}
	});

	$('#edit-new-tag-text').on('keyup', function(event) {
		if(event.keyCode == 13) {
			addTag('#edit-note-tags', '#edit-new-tag-text', true);
		}
	});

	$('#refresh-button').on('click', function() {
		window.location.reload();
	});

})();<commit_msg>JS updated to handle the JSON which is returned. Refresh button no longer refreshes the whole page, but just the notes and tags.<commit_after>(function() {

	// load the available notes and tags.
	loadNotes(0);
	loadTags();
	var showingComplete = false;
	var $noteList = $('#note-list');
	var $completedNoteButton = $('#complete-notes-button');
	var $showAllNotesButton = $('#show-all-notes-button');
	var $newNoteSection = $('#new-note-section');

	function loadNotes(complete) {

		$.ajax({
			url: 'includes/load-note.php',
			method: 'POST',
			data: {
				userId: userId,
				complete: complete
			}
		})
		.done(function(data, result) {
			if(result === 'success') {

				if(data !== 'none') {
					$noteList.append(data);
				} else {
					$noteList.append('It appears that you have not yet created any notes. Create your first one.');
				}

				if(complete !== 1) {
					$showAllNotesButton.show();
					$completedNoteButton.html('	Show Completed Notes');
				} else {
					// change the button text. Remove the show all notes.
					$showAllNotesButton.hide();
					$completedNoteButton.html('	Show Active Notes');
				}
			}
		})
		.fail(function(error) {
			console.log('It failed: ', error);
		});
	}

	function loadTags() {

		$.ajax({
			url: 'includes/load-tags.php',
			method: 'POST'
		})
		.done(function(data, result) {
			if(result == 'success') {
				data = $.parseJSON(data);
				$.each(data[0], function(index, value) {
					$('#add-note-tags').append('
<input type="checkbox" name="new-tag" data-tag="' + value + '" value="' + value + '">' + value + '
');
				});

				// change this so that it creates an option box.
				$.each(data[1], function(index, value) {
					$('.new-note-group').after('
<input type="checkbox" name="new-tag" data-tag="' + value + '" value="' + value + '">' + value + '
');
				});
			}
		})
		.fail(function(error) {
			console.log(error);
		});
	}

	function addTag(where, input, edit) {
		var newTag = $(input).val();

		if(newTag.trim() !== '') {
			if(edit) {
				$(where).append('
<input type="checkbox" checked name="edit-tag" data-tag="' + newTag + '" value="' + newTag + '">' + newTag + '
');
			} else {
				$(where).append('
<input type="checkbox" checked name="new-tag" data-tag="' + newTag + '" value="' + newTag + '">' + newTag + '
');
			}
			$(input).val('');
		}
	}

	toastr.options = {
		"timeOut": "2000",
		"preventDuplicates": false,
		"closeButton": true
	};

	// Hide the form to create new note until clicked
	$newNoteSection.hide();
	$('.note-text-validation, .edit-note-text-validation').hide();

	$('#new-note-button').on('click', function(){
		$newNoteSection.toggle();
	});

/* 	$('#show-new-tag-button').on('click', function() {
		$('#new-tag-section').toggle();
	}); */

	$showAllNotesButton.on('click', function() {
		$('.note').show();
	});

	$('#add-note-button').on('click', function() {

		var noteText = $('#add-note-text').val();
		var noteTitle = $('#add-note-title').val();
		var tagArray = [];

		if(noteText.trim() === '') {
			$('.note-text-validation').show();
			return;
		}

		$('input:checkbox[name=new-tag]:checked').each(function() {
			tagArray.push($(this).val());
		});

		$.ajax({
			url: 'includes/add-new-note.php',
			method: 'POST',
			data: {
				noteText: noteText,
				noteTags: tagArray,
				noteTitle: noteTitle,
				userId: userId
			}
		})
		.done(function(data, result) {
			var tags = '';
			$.each(tagArray, function(index, value) {
				tags += '' + value + '';
			});

			$noteList.append('
Note ID: ' + data + '
' + noteTitle + '

' + noteText + '
' + tags + '

');

			// Reset and confirmation.
			$('#add-note-title').val('');
			$('#add-note-text').val('');
			$('input:checkbox[name=new-tag]').removeAttr('checked');
			tagsToAdd = [];
			toastr.success('Note has been added successfully!');
			$newNoteSection.hide();
		})
		.fail(function(error) {
			console.log('There was a failure: ', error);
		});

	});

	$('#show-new-tag-button').on('click', function() {
		addTag('#add-note-tags', '#add-new-tag-text', false);
	});

	$('#edit-new-tag-button').on('click', function() {
		addTag('#edit-note-tags', '#edit-new-tag-text', true);
	});

	$noteList.on('click', '.note-tags', function() {

		var tag = $(this).data('tag');
		var notes = $('.note');
		var hide = [];
		$('.note').show();

		$.each(notes, function(index, value) {
			$value = $(value);

			var tags = $value.children('.note-tags');
			var tagData = [];

			$.each(tags, function(i, childTag) {
				$this = $(childTag);
				var data = $this.data('tag');
				tagData.push(data);
			});

			if(tagData.indexOf(tag) === -1) {
				hide.push(value);
			}
		});

		$.each(hide, function(index, value) {
			$(value).hide();
		});

		toastr.info('Now only showing notes with the tag "' + tag + '"');
	});

	$noteList.on('click', '.remove-note', function() {

		if(!confirm('Are you sure you wish to remove this note?')) {
			return;
		}

		$this = $(this);
		var deleteId = $this.closest('.note').data('id');

 		$.ajax({
			method: 'POST',
			url: 'includes/delete-note.php',
			data: {
				deleteNote: deleteId
			}
		})
		.done(function(data, result) {
			$this.closest('.note').remove();
			toastr.success('Note has been deleted!');
		})
		.fail(function(error) {
			console.log('An error has occurred: ', error);
		});

	});

	$noteList.on('click', '.edit-note', function() {
		// edit the note in the database.
		// also edit the note which is in the DOM
		// would probably be best to have this done in a modal.
		// TODO : above - skeleton code is below.
		$this = $(this);
		var noteId = $this.closest('.note').data('id');
		$('#save-note-button').data('id', noteId);
		var parent = $this.closest('.note');

		var $parent = $(parent);
		var title = $parent.find('.note-title')[0].textContent;
		var text = $parent.find('.note-text')[0].textContent;
		var tags = $parent.find('.note-tags');

		var tagArray = [];

		$.each(tags, function(index, value) {
			tagArray.push(value.textContent);
		});

		$('#note-edit-modal').modal('show');
		$('#edit-note-tags').empty();
		$('#edit-note-title').val(title);
		$('#edit-note-text').val(text);
		$.each(tagArray, function(index, value) {
			$('#edit-note-tags').append('
<input type="checkbox" checked name="edit-tag" data-tag="' + value + '" value="' + value + '">' + value + '
');
		});

		// TODO : when the modals okay button is clicked take the new data and update the database with it.
	});

	$noteList.on('click', '.note-done', function() {

		$this = $(this);
		var noteId = $this.closest('.note').data('id');

		$.ajax({
			method: 'POST',
			url: 'includes/note-done.php',
			data: {
				noteId: noteId,
				complete: 1
			}
		})
		.done(function(data, result) {
			console.log(data, result)
			$this.closest('.note').remove();
			toastr.success('Note marked as complete!');
		})
		.fail(function(error) {
			console.log('An error has occurred: ', error);
		});

	});

	$completedNoteButton.on('click', function() {
		if(showingComplete) {
			$noteList.empty();
			$completedNoteButton.html('	Show Completed Notes');
			showingComplete = false;
			loadNotes(0);
		} else {
			$noteList.empty();
			$completedNoteButton.html('	Show Active Notes');
			showingComplete = true;
			loadNotes(1);
		}
	});

	$noteList.on('click', '.mark-note-active', function() {

 		$this = $(this);
		var noteId = $this.closest('.note').data('id');
		console.log(noteId)
		$.ajax({
			method: 'POST',
			url: 'includes/note-done.php',
			data: {
				noteId: noteId,
				complete: 0
			}
		})
		.done(function(data, result) {
			console.log(data, result)
			$this.closest('.note').remove();
			toastr.success('Note marked as active!');
		})
		.fail(function(error) {
			console.log('An error has occurred: ', error);
		});

	});

	$('#save-note-button').on('click', function() {

 		var title = $('#edit-note-title').val();
		var text = $('#edit-note-text').val();
		var tagArray = [];
		var noteId = $('#save-note-button').data('id');

		$('input:checkbox[name=edit-tag]:checked').each(function() {
			tagArray.push($(this).val());
		});

 		$.ajax({
			method: 'POST',
			url: 'includes/edit-note.php',
			data: {
				noteText: text,
				noteId: noteId,
				noteTitle: title,
				noteTags: tagArray
			}
		})
		.done(function(data, result) {
			// update the DOM here.
			var note = $('[data-id="' + noteId + '"]');
			$(note).children('.note-title')[0].textContent = title;
			$(note).children('.note-text')[0].textContent = text;
			var newText = $(note).children('.note-text')[0];
			$(note).children('.note-tags').remove();
			var tags = '';

			$.each(tagArray, function(index, value) {
				tags += '' + value + '';
			});

			$(newText).after(tags);

			$('#note-edit-modal').modal('hide');

			toastr.success('Note successfully updated!');
		})
		.fail(function(error) {
			console.log('An error has occurred: ', error);
		});
	});

	$noteList.on('click', '#note-edit-modal', function() {
		$('#note-edit-modal').show();
	})

	$('#close-new-note').on('click', function() {
		$newNoteSection.hide();
	});

	$('#add-note-text').on('keyup', function() {
		$('.note-text-validation').hide();
	});

	$('#edit-note-text').on('keyup', function() {
		$('.edit-note-text-validation').hide();
	});

	$('#add-new-tag-text').on('keyup', function(event) {
		if(event.keyCode == 13) {
			addTag('#add-note-tags', '#add-new-tag-text', false);
		}
	});

	$('#edit-new-tag-text').on('keyup', function(event) {
		if(event.keyCode == 13) {
			addTag('#edit-note-tags', '#edit-new-tag-text', true);
		}
	});

	$('#refresh-button').on('click', function() {
		$noteList.empty();
		$('.checkbox').remove();
		loadNotes(0);
		loadTags();
	});

})();<|endoftext|>


<commit_before>$(document).ready(function() {
    var $header = $("#mainSearch"),
        $clone = $header.before($header.clone().addClass("clone"));

    $(window).on("scroll", function() {
        var fromTop = $("html,body").scrollTop();
        $(window).toggleClass("down", (fromTop > 400));
    });
});<commit_msg>tweak<commit_after>$(document).ready(function() {
    var $header = $("#mainSearch"),
        $clone = $header.before($header.clone().addClass("clone"));

    $(window).on("scroll", function() {
        var fromTop = $("html,body").scrollTop();
        $clone.toggleClass("down", (fromTop > 400));
    });
});<|endoftext|>


<commit_before>$(function() {

    var img_urls = ["img/deer.png", "img/dolphin.png", "img/kangaroo.png", "img/leopard.png", "img/panther.png", "img/penguin.png", "img/rabbit.png", "img/sheep.png", "img/swan.png", "img/wolf.png", "img/zebra.png", "img/duck.png", "img/deer.png", "img/dolphin.png", "img/kangaroo.png", "img/leopard.png", "img/panther.png", "img/penguin.png", "img/rabbit.png", "img/sheep.png", "img/swan.png", "img/wolf.png", "img/zebra.png", "img/duck.png"];

    //Shuffle js array > http://stackoverflow.com/a/2450976/4991434
    function shuffle(array) {
        var currentIndex = array.length,
            temporaryValue, randomIndex;

        // While there remain elements to shuffle...
        while (0 !== currentIndex) {

            // Pick a remaining element...
            randomIndex = Math.floor(Math.random() * currentIndex);
            currentIndex -= 1;

            // And swap it with the current element.
            temporaryValue = array[currentIndex];
            array[currentIndex] = array[randomIndex];
            array[randomIndex] = temporaryValue;
        }

        return array;
    }

    var arr = img_urls;
    arr = shuffle(arr);
    //console.log(arr);

    for (i = 0; i < img_urls.length; i++) {
        $(".items").append(
            "

" + img_urls[i] + "

"
        );
    }

    var first;
    var second;

    var total_clicks = 0;
    var count = 0;

    function check_level() {
        if (total_clicks === 8) {

            $(".first-svg").removeClass("level");

        } else if (total_clicks === 14) {

            $(".second-svg").removeClass("level");

        } else if (total_clicks === 22) {

            $(".third-svg").removeClass("level");

        }
    }

    function check_if_game_over() {
        if ($(".matched").length === 48) {

            setTimeout(function() {
                alert("Game over");
            }, 1200);

            setTimeout(function() {
                location.reload();
            }, 1800);

        }
    }

    $(".front").click(function(e) {

        count++;

        //prevent fast click
        if ($(e.target).data('oneclicked') != 'yes') {
            $(e.target).css("pointer-events", "none")
            setTimeout(function() {
                $(e.target).css("pointer-events", "auto")
            }, 400);
        }

        if (count === 1) {

            $(this, ".front").addClass("showBack-front").addClass("clicked");
            $(this).next('.back').addClass("showBack-back").addClass("clicked");

            first = $(this, ".front").text();

        } else {

            $(this, ".front").addClass("showBack-front").addClass("clicked");;
            $(this).next('.back').addClass("showBack-back").addClass("clicked");;

            second = $(this, ".front").text();
            count = 0;

            $(".front").css("pointer-events", "none");

            setTimeout(function() {

                if (first === second) {

                    total_clicks = total_clicks - 1;

                    $('.clicked').addClass('animated tada matched');

                    //Check if game over
                    check_if_game_over();

                } else {

                    $(".front").removeClass("showBack-front");
                    $(".back").removeClass("showBack-back");

                    $('.clicked').addClass('animated shake');

                    setTimeout(function() {
                        $(".clicked").removeClass("clicked shake");
                    }, 500);

                }

                $(".front").css("pointer-events", "auto");

                total_clicks++;
                $(".total_clicks span").text(total_clicks);
                check_level();

            }, 600);

        }

        return false;
    });

});
<commit_msg>add pointer events:none for matched animals<commit_after>$(function() {

    var img_urls = ["img/deer.png", "img/dolphin.png", "img/kangaroo.png", "img/leopard.png", "img/panther.png", "img/penguin.png", "img/rabbit.png", "img/sheep.png", "img/swan.png", "img/wolf.png", "img/zebra.png", "img/duck.png", "img/deer.png", "img/dolphin.png", "img/kangaroo.png", "img/leopard.png", "img/panther.png", "img/penguin.png", "img/rabbit.png", "img/sheep.png", "img/swan.png", "img/wolf.png", "img/zebra.png", "img/duck.png"];

    //Shuffle js array > http://stackoverflow.com/a/2450976/4991434
    function shuffle(array) {
        var currentIndex = array.length,
            temporaryValue, randomIndex;

        // While there remain elements to shuffle...
        while (0 !== currentIndex) {

            // Pick a remaining element...
            randomIndex = Math.floor(Math.random() * currentIndex);
            currentIndex -= 1;

            // And swap it with the current element.
            temporaryValue = array[currentIndex];
            array[currentIndex] = array[randomIndex];
            array[randomIndex] = temporaryValue;
        }

        return array;
    }

    var arr = img_urls;
    arr = shuffle(arr);
    //console.log(arr);

    for (i = 0; i < img_urls.length; i++) {
        $(".items").append(
            "

" + img_urls[i] + "

"
        );
    }

    var first;
    var second;

    var total_clicks = 0;
    var count = 0;

    function check_level() {
        if (total_clicks === 8) {

            $(".first-svg").removeClass("level");

        } else if (total_clicks === 14) {

            $(".second-svg").removeClass("level");

        } else if (total_clicks === 22) {

            $(".third-svg").removeClass("level");

        }
    }

    function check_if_game_over() {
        if ($(".matched").length === 48) {

            setTimeout(function() {
                alert("Game over");
            }, 1200);

            setTimeout(function() {
                location.reload();
            }, 1800);

        }
    }

    $(".front").click(function(e) {

        count++;

        //prevent fast click
        if ($(e.target).data('oneclicked') != 'yes') {
            $(e.target).css("pointer-events", "none")
            setTimeout(function() {
                $(e.target).css("pointer-events", "auto")
            }, 400);
        }

        if (count === 1) {

            $(this, ".front").addClass("showBack-front").addClass("clicked");
            $(this).next('.back').addClass("showBack-back").addClass("clicked");

            first = $(this, ".front").text();

        } else {

            $(this, ".front").addClass("showBack-front").addClass("clicked");;
            $(this).next('.back').addClass("showBack-back").addClass("clicked");;

            second = $(this, ".front").text();
            count = 0;

            $(".front").css("pointer-events", "none");

            setTimeout(function() {

                if (first === second) {

                    total_clicks = total_clicks - 1;

                    $('.clicked').addClass('animated tada matched no-pointer-events');

                    //Check if game over
                    check_if_game_over();

                } else {

                    $(".front").removeClass("showBack-front");
                    $(".back").removeClass("showBack-back");

                    $('.clicked').addClass('animated shake');

                    setTimeout(function() {
                        $(".clicked").removeClass("clicked shake");
                    }, 500);

                }

                $(".front").css("pointer-events", "auto");

                total_clicks++;
                $(".total_clicks span").text(total_clicks);
                check_level();

            }, 600);

        }

        return false;
    });

});
<|endoftext|>


<commit_before>/*	Author:
		TMW - (Author Name Here)
*/

$(function() {
	// Any globals go here in CAPS (but avoid if possible)

	// follow a singleton pattern
	// (http://addyosmani.com/resources/essentialjsdesignpatterns/book/#singletonpatternjavascript)
	var SiteSetup = {
		variableX : '', // please don't keep me - only for example syntax!

		init : function () {

		}
	};

	SiteSetup.init();

});// End Doc Ready

<commit_msg>Create global TMW namespace & add jshint & jslint directives<commit_after>/*jslint sloppy: true, white: true, browser: true, devel: true */
/*jshint forin:true, noarg:true, noempty:true, eqeqeq:true, bitwise:true, strict:false, curly:true, browser:true, indent:4, maxerr:50, sloppy:true, white:false, smarttabs:false */

/*	Author:
		TMW - (Author Name Here)
*/

// ======================================
// === Declare global 'TMW' namespace ===
// ======================================
var TMW = window.TMW || {};

// Create a closure to maintain scope of the '$' and remain compatible with other frameworks
(function($) {

	$(function() {
		// Any globals go here in CAPS (but avoid if possible)

		// follow a singleton pattern
		// (http://addyosmani.com/resources/essentialjsdesignpatterns/book/#singletonpatternjavascript)

		TMW.SiteSetup = {
			variableX : '', // please don't keep me - only for example syntax!

			init : function () {

			}
		};

		TMW.SiteSetup.init();

	});// END DOC READY

	/* optional triggers

	// WINDOW.LOAD
	$(window).load(function() {

	});

	// WINDOW.RESIZE
	$(window).resize(function() {

	});

	*/

})(jQuery);

<|endoftext|>


<commit_before>$( document ).ready(function() {
	var appID = "7c3832ce234904f30881f09806b7a6d7";

   	$(".query_btn").click(function(){

    	var query_param = $(this).prev().val();

    	if ($(this).prev().attr("placeholder") == "City") {
    		var weather = "http://api.openweathermap.org/data/2.5/weather?q=" + query_param + "&APPID=" + appID;
    	} else if ($(this).prev().attr("placeholder") == "Zip Code") {
    		var weather = "http://api.openweathermap.org/data/2.5/weather?zip=" + query_param + "&APPID=" + appID;
    	} else if ($(this).prev().attr("placeholder") == "GeoLocation") {
    		// var weather = "api.openweathermap.org/data/2.5/weather?lat=" + lat + "&lon=" + lon + "&APPID=" + appID;
    	}

        $.getJSON(weather,function(json){
            $("#city").html(json.name);
            $("#main_weather").html(json.weather[0].main);
            $("#description_weather").html(json.weather[0].description);
            $("#weather_image").attr("src", "http://openweathermap.org/img/w/" + json.weather[0].icon + ".png");
            $("#temperature").html(json.main.temp);
            $("#pressure").html(json.main.pressure);;
            $("#humidity").html(json.main.humidity);;
        });
    })

});<commit_msg>updated javascript for OpenWeatherMap<commit_after>$( document ).ready(function() {
	var appID = "7c3832ce234904f30881f09806b7a6d7";

   	$(".query_btn").click(function(){

    	var query_param = $(this).prev().val();

    	if ($(this).prev().attr("placeholder") == "City") {
    		var weather = "http://api.openweathermap.org/data/2.5/weather?q=" + query_param + "&units=imperial&APPID=" + appID;
    	} else if ($(this).prev().attr("placeholder") == "Zip Code") {
    		var weather = "http://api.openweathermap.org/data/2.5/weather?zip=" + query_param + "&units=imperial&APPID=" + appID;
    	} else if ($(this).prev().attr("placeholder") == "GeoLocation") {
    		// var weather = "api.openweathermap.org/data/2.5/weather?lat=" + lat + "&lon=" + lon + "&units=imperial&APPID=" + appID;
    	}

        $.getJSON(weather,function(json){
            $("#city").html(json.name);
            $("#main_weather").html(json.weather[0].main);
            $("#description_weather").html(json.weather[0].description);
            $("#weather_image").attr("src", "http://openweathermap.org/img/w/" + json.weather[0].icon + ".png");
            $("#temperature").html(json.main.temp);
            $("#pressure").html(json.main.pressure);;
            $("#humidity").html(json.main.humidity);;
        });
    })

});<|endoftext|>


<commit_before>var map = L.map('map').setView([44.98044862724291, -93.26319694519043], 15);

		L.control.locate({
                      strings: {
                                 title: "Zoom to your current location"
                               }
               ,locateOptions: {
                                 maxZoom: 17
                               }
                     }).addTo(map);

//var baselayer = new L.StamenTileLayer("toner-lite");
var baselayer = new L.StamenTileLayer("terrain");
baselayer.addTo(map);

var confPin = L.MakiMarkers.icon({
    icon: "star",
    color: "#ff0000",
    size: "l"
});

var pendingPin = L.MakiMarkers.icon({
    icon: "beer",
    color: "#939393",
    size: "m"
});

var tapLayer = new L.GeoJSON.AJAX("js/places.geojson",{
		    pointToLayer: function (feature, latlng) {

				 var html = '';
               if (feature.properties.web) {
                      html += '
' + feature.properties.title + '
';
                                           }
               else {
                      html += '
' + feature.properties.title + '
';
                    }
               if (feature.properties.address) {
                      html += '
'+ feature.properties.address + '
';
                                               }
               if (feature.properties.scoop) {
                      html += '
'+ feature.properties.scoop + '
';
                                               }
      html += '

';
      var popup = new L.popup({closeButton:false}).setContent(html);

      var marker = new L.marker(latlng);
      if (feature.properties.poi_type === 'conf') {
          marker.setIcon(confPin);
         }
      else {
          marker.setIcon(pendingPin);
         }
      //marker.setIcon(beerPin);
		  marker.bindPopup(popup);

		  return marker;
		    }
		});

tapLayer.addTo(map);

<commit_msg>more place types and icons<commit_after>var map = L.map('map').setView([44.98044862724291, -93.26319694519043], 15);

		L.control.locate({
                      strings: {
                                 title: "Zoom to your current location"
                               }
               ,locateOptions: {
                                 maxZoom: 17
                               }
                     }).addTo(map);

//var baselayer = new L.StamenTileLayer("toner-lite");
var baselayer = new L.StamenTileLayer("terrain");
baselayer.addTo(map);

var confPin = L.MakiMarkers.icon({
    icon: "star",
    color: "#ff0000",
    size: "l"
});

var beerPin = L.MakiMarkers.icon({
    icon: "beer",
    color: "##23344c",
    size: "m"
});

var barPin = L.MakiMarkers.icon({
    icon: "bar",
    color: "##23344c",
    size: "m"
});

var restaurantPin = L.MakiMarkers.icon({
    icon: "restaurant",
    color: "##23344c",
    size: "m"
});

var coffeePin = L.MakiMarkers.icon({
    icon: "cafe",
    color: "##23344c",
    size: "m"
});

var tapLayer = new L.GeoJSON.AJAX("js/places.geojson",{
		    pointToLayer: function (feature, latlng) {

				 var html = '';
               if (feature.properties.web) {
                      html += '
' + feature.properties.title + '
';
                                           }
               else {
                      html += '
' + feature.properties.title + '
';
                    }
               if (feature.properties.address) {
                      html += '
'+ feature.properties.address + '
';
                                               }
               if (feature.properties.scoop) {
                      html += '
'+ feature.properties.scoop + '
';
                                               }
      html += '

';
      var popup = new L.popup({closeButton:false}).setContent(html);

      var marker = new L.marker(latlng);
      if (feature.properties.poi_type === 'conf') {
          marker.setIcon(confPin);
         }
      if (feature.properties.poi_type === 'beer') {
          marker.setIcon(confPin);
         }
      if (feature.properties.poi_type === 'bar') {
          marker.setIcon(confPin);
         }
      if (feature.properties.poi_type === 'restaurant') {
          marker.setIcon(confPin);
         }
      if (feature.properties.poi_type === 'cafe') {
          marker.setIcon(confPin);
         }

      //marker.setIcon(beerPin);
		  marker.bindPopup(popup);

		  return marker;
		    }
		});

tapLayer.addTo(map);

<|endoftext|>