<commit_before>// ==========================================
// BOWER: Manager Object Definition
// ==========================================
// Copyright 2012 Twitter, Inc
// Licensed under The MIT License
// http://opensource.org/licenses/MIT
// ==========================================
// Events:
//  - install: fired when everything is installed
//  - package: fired for each installed packaged
//  - resolve: fired when deps resolved (with a true/false indicating success or error)
//  - error: fired on all errors
//  - data: fired when trying to output data
//  - end: fired when finished installing
// ==========================================

var events     = require('events');
var semver     = require('semver');
var async      = require('async');
var path       = require('path');
var glob       = require('glob');
var fs         = require('fs');
var _          = require('lodash');

var Package    = require('./package');
var UnitWork   = require('./unit_work');
var config     = require('./config');
var fileExists = require('../util/file-exists');
var template   = require('../util/template');
var prune      = require('../util/prune');

// read local dependencies (with versions)
// read json dependencies (resolving along the way into temp dir)
// merge local dependencies with json dependencies
// prune and move dependencies into local directory

var Manager = function (endpoints, opts) {
  this.dependencies    = {};
  this.cwd             = process.cwd();
  this.endpoints       = endpoints || [];
  this.unitWork        = new UnitWork;
  this.opts            = opts || {};
  this.errors          = [];
};

Manager.prototype = Object.create(events.EventEmitter.prototype);
Manager.prototype.constructor = Manager;

Manager.prototype.loadJSON = function () {
  var json = path.join(this.cwd, config.json);
  fileExists(json, function (exists) {
    if (!exists) {
      // If the json does not exist, assume one
      this.json = {
        name: path.basename(this.cwd),
        version: '0.0.0'
      },
      this.name = this.json.name;
      this.version = this.json.version;
      return this.emit('loadJSON');
    }

    fs.readFile(json, 'utf8', function (err, json) {
      if (err) return this.emit('error', err);
      try {
        this.json    = JSON.parse(json);
      } catch (e) {
        return this.emit('error', new Error('There was an error while reading the ' + config.json));
      }
      this.name    = this.json.name;
      this.version = this.json.version;
      this.emit('loadJSON', json.slice(-1) === '\n');
    }.bind(this));
  }.bind(this));

  return this;
};

Manager.prototype.resolve = function () {
  var resolved = function () {
    // If there is errors, report them
    if (this.errors.length) return this.reportErrors();
    // If there is an error while pruning (conflict) then abort installation
    if (!this.prune()) return this.emit('resolve', false);
    // Otherwise all is fine, so we install
    this.once('install', this.emit.bind(this, 'resolve', true)).install();
  }.bind(this);

  // Resolve locally first
  this.once('resolveLocal', function () {
    if (this.endpoints.length) {
      // TODO: When resolving specific endpoints we need to restore all the local
      //       packages and their hierarchy (all from the local folder)
      //       If something goes wrong, simply do resolveFromJSON before
      //       calling resolved() (slower)
      //       This will solve issue #200
      this.once('resolveEndpoints', resolved).resolveEndpoints();
    } else {
      this.once('resolveFromJson', resolved).resolveFromJson();
    }
  }).resolveLocal();

  return this;
};

Manager.prototype.resolveLocal = function () {
  glob('./' + config.directory + '/*', function (err, dirs) {
    if (err) return this.emit('error', err);
    dirs.forEach(function (dir) {
      var name = path.basename(dir);
      var pkg = new Package(name, dir, this);

      this.dependencies[name] = [];
      this.dependencies[name].push(pkg);

      this.gatherPackageErrors(pkg);
    }.bind(this));
    this.emit('resolveLocal');
  }.bind(this));

  return this;
};

Manager.prototype.resolveEndpoints = function () {
  var endpointNames = this.opts.endpointNames || {};

  async.forEach(this.endpoints, function (endpoint, next) {
    var name = endpointNames[endpoint];
    var pkg  = new Package(name, endpoint, this);

    pkg.root = true;
    this.dependencies[name] = this.dependencies[name] || [];
    this.dependencies[name].push(pkg);

    this.gatherPackageErrors(pkg);
    pkg.once('error', next);
    pkg.once('resolve', function () {
      pkg.removeListener('error', next);
      next();
    }).resolve();
  }.bind(this), this.emit.bind(this, 'resolveEndpoints'));

  return this;
};

Manager.prototype.resolveFromJson = function () {
  this.once('loadJSON', function () {
    var dependencies = this.json.dependencies || {};

    // add devDependencies
    if (!this.opts.production && this.json.devDependencies) {
      dependencies = _.extend({}, dependencies, this.json.devDependencies);
    }

    async.forEach(Object.keys(dependencies), function (name, next) {
      var endpoint = dependencies[name];
      var pkg      = new Package(name, endpoint, this);

      pkg.root = true;
      this.dependencies[name] = this.dependencies[name] || [];
      this.dependencies[name].push(pkg);

      this.gatherPackageErrors(pkg);
      pkg.once('error', next);
      pkg.once('resolve', function () {
        pkg.removeListener('error', next);
        next();
      }).resolve();
    }.bind(this), this.emit.bind(this, 'resolveFromJson'));
  }.bind(this)).loadJSON();

  return this;
};

// Private
Manager.prototype.getDeepDependencies = function () {
  var result = {};

  for (var name in this.dependencies) {
    this.dependencies[name].forEach(function (pkg) {
      result[pkg.name] = result[pkg.name] || [];
      result[pkg.name].push(pkg);
      pkg.getDeepDependencies().forEach(function (pkg) {
        result[pkg.name] = result[pkg.name] || [];
        result[pkg.name].push(pkg);
      });
    });
  }

  return result;
};

Manager.prototype.prune = function () {
  var result = prune(this.getDeepDependencies(), this.opts.forceLatest);
  var name;

  // If there is conflicted deps, print them and fail
  if (result.conflicted) {
    for (name in result.conflicted) {
      this.reportConflicts(name, result.conflicted[name]);
    }

    return false;
  }

  this.dependencies = {};

  // If there is conflicted deps but they where forcebly resolved
  // Print a warning about them
  if (result.forceblyResolved) {
    for (name in result.forceblyResolved) {
      this.reportForceblyResolved(name, result.forceblyResolved[name]);
      this.dependencies[name] = result.forceblyResolved[name];
      this.dependencies[name][0].root = true;
    }
  }

  _.extend(this.dependencies, result.resolved);

  return true;
};

Manager.prototype.gatherPackageErrors = function (pkg) {
  // Listen to all the errors
  // The first error will call the next callback and we continue to gather more until the end
  // This makes sense because a package forwards its deep dependencies errors
  pkg.on('error', function (err, origin) {
    pkg = origin || pkg;

    // If the error message starts with the package name, strip it
    if (!err.message.indexOf(pkg.name + ' ')) {
      err.message = err.message.substr(pkg.name.length + 1);
    }

    this.errors.push({ pkg: pkg, error: err });
  }.bind(this));
};

Manager.prototype.install = function () {
  async.forEach(Object.keys(this.dependencies), function (name, next) {
    var pkg = this.dependencies[name][0];
    pkg.once('install', function () {
      this.emit('package', pkg);
      next();
    }.bind(this)).install();
    pkg.once('error', next);
  }.bind(this), function () {
    if (this.errors.length) this.reportErrors();
    return this.emit('install');
  }.bind(this));
};

Manager.prototype.muteDependencies = function () {
  for (var name in this.dependencies) {
    this.dependencies[name].forEach(function (pkg) {
      pkg.removeAllListeners();
      pkg.on('error', function () {});
    });
  }
};

Manager.prototype.reportErrors = function () {
  this.muteDependencies();
  template('error-summary', { errors: this.errors }).on('data', function (data) {
    this.emit('data', data);
    this.emit('resolve', false);
  }.bind(this));
};

Manager.prototype.reportConflicts = function (name, packages) {
  var versions = [];
  var requirements = [];

  packages = packages.filter(function (pkg) { return !!pkg.version; });
  packages.forEach(function (pkg) {
    requirements.push({ pkg: pkg, tag: pkg.originalTag || '~' + pkg.version });
    versions.push((pkg.originalTag || '~' + pkg.version).white);
  });

  this.emit('error', new Error('No resolvable version for ' + name));
  this.emit('data', template('conflict', {
    name: name,
    requirements: requirements,
    json: config.json,
    versions: versions.slice(0, -1).join(', ') + ' or ' + versions[versions.length - 1]
  }, true));
};

Manager.prototype.reportForceblyResolved = function (name, packages) {
  var requirements = [];

  packages = packages.filter(function (pkg) { return !!pkg.version; });
  packages.forEach(function (pkg) {
    requirements.push({ pkg: pkg, tag: pkg.originalTag || '~' + pkg.version });
  });

  this.emit('data', template('resolved-conflict', {
    name: name,
    requirements: requirements,
    json: config.json,
    resolvedTo: packages[0].version,
    forceLatest: this.opts.forceLatest
  }, true));
};

// ----- list ----- //

// Used in list command
// TODO: not sure if this belongs here.. maybe move it to the list command?
Manager.prototype.list = function (options) {
  options = options || {};
   // If the user passed the paths or map options, we don't need to fetch versions
  this._isCheckingVersions = !options.offline && !options.paths && !options.map && options.argv;
  this.once('resolveLocal', this.getDependencyList.bind(this))
    .resolveLocal();
};

Manager.prototype.getDependencyList = function () {

  var packages = {};
  var values;
  var checkVersions = this._isCheckingVersions;

  if (checkVersions) {
    template('action', { name: 'discover', shizzle: 'Please wait while newer package versions are being discovered' })
      .on('data', this.emit.bind(this, 'data'));
  }

  Object.keys(this.dependencies).forEach(function (key) {
    packages[key] = this.dependencies[key][0];
  }.bind(this));

  values = _.values(packages);
  // Do not proceed if no values
  if (!values.length) {
    return packages;
  }
  // Load JSON and get version for each package
  async.forEach(values, function (pkg, next) {
    pkg.once('loadJSON', function () {
      // Only check versions if not offline and it's a repo
      var fetchVersions = checkVersions &&
                          pkg.json.repository &&
                          (pkg.json.repository.type === 'git' || pkg.json.repository.type === 'local-repo');

      if (fetchVersions) {
        pkg.once('versions', function (versions) {
          pkg.tags = versions.map(function (ver) {
            return semver.valid(ver) ? semver.clean(ver) : ver;
          });
          next();
        }).versions();
      } else {
        pkg.tags = [];
        next();
      }
    }).loadJSON();
  }.bind(this), this.emit.bind(this, 'list', packages));
};

module.exports = Manager;<commit_msg>Unnecessary comment.<commit_after>// ==========================================
// BOWER: Manager Object Definition
// ==========================================
// Copyright 2012 Twitter, Inc
// Licensed under The MIT License
// http://opensource.org/licenses/MIT
// ==========================================
// Events:
//  - install: fired when everything is installed
//  - package: fired for each installed packaged
//  - resolve: fired when deps resolved (with a true/false indicating success or error)
//  - error: fired on all errors
//  - data: fired when trying to output data
//  - end: fired when finished installing
// ==========================================

var events     = require('events');
var semver     = require('semver');
var async      = require('async');
var path       = require('path');
var glob       = require('glob');
var fs         = require('fs');
var _          = require('lodash');

var Package    = require('./package');
var UnitWork   = require('./unit_work');
var config     = require('./config');
var fileExists = require('../util/file-exists');
var template   = require('../util/template');
var prune      = require('../util/prune');

// read local dependencies (with versions)
// read json dependencies (resolving along the way into temp dir)
// merge local dependencies with json dependencies
// prune and move dependencies into local directory

var Manager = function (endpoints, opts) {
  this.dependencies    = {};
  this.cwd             = process.cwd();
  this.endpoints       = endpoints || [];
  this.unitWork        = new UnitWork;
  this.opts            = opts || {};
  this.errors          = [];
};

Manager.prototype = Object.create(events.EventEmitter.prototype);
Manager.prototype.constructor = Manager;

Manager.prototype.loadJSON = function () {
  var json = path.join(this.cwd, config.json);
  fileExists(json, function (exists) {
    if (!exists) {
      // If the json does not exist, assume one
      this.json = {
        name: path.basename(this.cwd),
        version: '0.0.0'
      },
      this.name = this.json.name;
      this.version = this.json.version;
      return this.emit('loadJSON');
    }

    fs.readFile(json, 'utf8', function (err, json) {
      if (err) return this.emit('error', err);
      try {
        this.json    = JSON.parse(json);
      } catch (e) {
        return this.emit('error', new Error('There was an error while reading the ' + config.json));
      }
      this.name    = this.json.name;
      this.version = this.json.version;
      this.emit('loadJSON', json.slice(-1) === '\n');
    }.bind(this));
  }.bind(this));

  return this;
};

Manager.prototype.resolve = function () {
  var resolved = function () {
    // If there is errors, report them
    if (this.errors.length) return this.reportErrors();
    // If there is an error while pruning (conflict) then abort installation
    if (!this.prune()) return this.emit('resolve', false);
    // Otherwise all is fine, so we install
    this.once('install', this.emit.bind(this, 'resolve', true)).install();
  }.bind(this);

  // Resolve locally first
  this.once('resolveLocal', function () {
    if (this.endpoints.length) {
      // TODO: When resolving specific endpoints we need to restore all the local
      //       packages and their hierarchy (all from the local folder)
      //       If something goes wrong, simply do resolveFromJSON before
      //       calling resolved() (slower)
      //       This will solve issue #200
      this.once('resolveEndpoints', resolved).resolveEndpoints();
    } else {
      this.once('resolveFromJson', resolved).resolveFromJson();
    }
  }).resolveLocal();

  return this;
};

Manager.prototype.resolveLocal = function () {
  glob('./' + config.directory + '/*', function (err, dirs) {
    if (err) return this.emit('error', err);
    dirs.forEach(function (dir) {
      var name = path.basename(dir);
      var pkg = new Package(name, dir, this);

      this.dependencies[name] = [];
      this.dependencies[name].push(pkg);

      this.gatherPackageErrors(pkg);
    }.bind(this));
    this.emit('resolveLocal');
  }.bind(this));

  return this;
};

Manager.prototype.resolveEndpoints = function () {
  var endpointNames = this.opts.endpointNames || {};

  async.forEach(this.endpoints, function (endpoint, next) {
    var name = endpointNames[endpoint];
    var pkg  = new Package(name, endpoint, this);

    pkg.root = true;
    this.dependencies[name] = this.dependencies[name] || [];
    this.dependencies[name].push(pkg);

    this.gatherPackageErrors(pkg);
    pkg.once('error', next);
    pkg.once('resolve', function () {
      pkg.removeListener('error', next);
      next();
    }).resolve();
  }.bind(this), this.emit.bind(this, 'resolveEndpoints'));

  return this;
};

Manager.prototype.resolveFromJson = function () {
  this.once('loadJSON', function () {
    var dependencies = this.json.dependencies || {};

    // add devDependencies
    if (!this.opts.production && this.json.devDependencies) {
      dependencies = _.extend({}, dependencies, this.json.devDependencies);
    }

    async.forEach(Object.keys(dependencies), function (name, next) {
      var endpoint = dependencies[name];
      var pkg      = new Package(name, endpoint, this);

      pkg.root = true;
      this.dependencies[name] = this.dependencies[name] || [];
      this.dependencies[name].push(pkg);

      this.gatherPackageErrors(pkg);
      pkg.once('error', next);
      pkg.once('resolve', function () {
        pkg.removeListener('error', next);
        next();
      }).resolve();
    }.bind(this), this.emit.bind(this, 'resolveFromJson'));
  }.bind(this)).loadJSON();

  return this;
};

// Private
Manager.prototype.getDeepDependencies = function () {
  var result = {};

  for (var name in this.dependencies) {
    this.dependencies[name].forEach(function (pkg) {
      result[pkg.name] = result[pkg.name] || [];
      result[pkg.name].push(pkg);
      pkg.getDeepDependencies().forEach(function (pkg) {
        result[pkg.name] = result[pkg.name] || [];
        result[pkg.name].push(pkg);
      });
    });
  }

  return result;
};

Manager.prototype.prune = function () {
  var result = prune(this.getDeepDependencies(), this.opts.forceLatest);
  var name;

  // If there is conflicted deps, print them and fail
  if (result.conflicted) {
    for (name in result.conflicted) {
      this.reportConflicts(name, result.conflicted[name]);
    }

    return false;
  }

  this.dependencies = {};

  // If there is conflicted deps but they where forcebly resolved
  // Print a warning about them
  if (result.forceblyResolved) {
    for (name in result.forceblyResolved) {
      this.reportForceblyResolved(name, result.forceblyResolved[name]);
      this.dependencies[name] = result.forceblyResolved[name];
      this.dependencies[name][0].root = true;
    }
  }

  _.extend(this.dependencies, result.resolved);

  return true;
};

Manager.prototype.gatherPackageErrors = function (pkg) {
  pkg.on('error', function (err, origin) {
    pkg = origin || pkg;

    // If the error message starts with the package name, strip it
    if (!err.message.indexOf(pkg.name + ' ')) {
      err.message = err.message.substr(pkg.name.length + 1);
    }

    this.errors.push({ pkg: pkg, error: err });
  }.bind(this));
};

Manager.prototype.install = function () {
  async.forEach(Object.keys(this.dependencies), function (name, next) {
    var pkg = this.dependencies[name][0];
    pkg.once('install', function () {
      this.emit('package', pkg);
      next();
    }.bind(this)).install();
    pkg.once('error', next);
  }.bind(this), function () {
    if (this.errors.length) this.reportErrors();
    return this.emit('install');
  }.bind(this));
};

Manager.prototype.muteDependencies = function () {
  for (var name in this.dependencies) {
    this.dependencies[name].forEach(function (pkg) {
      pkg.removeAllListeners();
      pkg.on('error', function () {});
    });
  }
};

Manager.prototype.reportErrors = function () {
  this.muteDependencies();
  template('error-summary', { errors: this.errors }).on('data', function (data) {
    this.emit('data', data);
    this.emit('resolve', false);
  }.bind(this));
};

Manager.prototype.reportConflicts = function (name, packages) {
  var versions = [];
  var requirements = [];

  packages = packages.filter(function (pkg) { return !!pkg.version; });
  packages.forEach(function (pkg) {
    requirements.push({ pkg: pkg, tag: pkg.originalTag || '~' + pkg.version });
    versions.push((pkg.originalTag || '~' + pkg.version).white);
  });

  this.emit('error', new Error('No resolvable version for ' + name));
  this.emit('data', template('conflict', {
    name: name,
    requirements: requirements,
    json: config.json,
    versions: versions.slice(0, -1).join(', ') + ' or ' + versions[versions.length - 1]
  }, true));
};

Manager.prototype.reportForceblyResolved = function (name, packages) {
  var requirements = [];

  packages = packages.filter(function (pkg) { return !!pkg.version; });
  packages.forEach(function (pkg) {
    requirements.push({ pkg: pkg, tag: pkg.originalTag || '~' + pkg.version });
  });

  this.emit('data', template('resolved-conflict', {
    name: name,
    requirements: requirements,
    json: config.json,
    resolvedTo: packages[0].version,
    forceLatest: this.opts.forceLatest
  }, true));
};

// ----- list ----- //

// Used in list command
// TODO: not sure if this belongs here.. maybe move it to the list command?
Manager.prototype.list = function (options) {
  options = options || {};
   // If the user passed the paths or map options, we don't need to fetch versions
  this._isCheckingVersions = !options.offline && !options.paths && !options.map && options.argv;
  this.once('resolveLocal', this.getDependencyList.bind(this))
    .resolveLocal();
};

Manager.prototype.getDependencyList = function () {

  var packages = {};
  var values;
  var checkVersions = this._isCheckingVersions;

  if (checkVersions) {
    template('action', { name: 'discover', shizzle: 'Please wait while newer package versions are being discovered' })
      .on('data', this.emit.bind(this, 'data'));
  }

  Object.keys(this.dependencies).forEach(function (key) {
    packages[key] = this.dependencies[key][0];
  }.bind(this));

  values = _.values(packages);
  // Do not proceed if no values
  if (!values.length) {
    return packages;
  }
  // Load JSON and get version for each package
  async.forEach(values, function (pkg, next) {
    pkg.once('loadJSON', function () {
      // Only check versions if not offline and it's a repo
      var fetchVersions = checkVersions &&
                          pkg.json.repository &&
                          (pkg.json.repository.type === 'git' || pkg.json.repository.type === 'local-repo');

      if (fetchVersions) {
        pkg.once('versions', function (versions) {
          pkg.tags = versions.map(function (ver) {
            return semver.valid(ver) ? semver.clean(ver) : ver;
          });
          next();
        }).versions();
      } else {
        pkg.tags = [];
        next();
      }
    }).loadJSON();
  }.bind(this), this.emit.bind(this, 'list', packages));
};

module.exports = Manager;<|endoftext|>


<commit_before>'use strict';

var express = require('express');
var compression = require('compression');
var path = require('path');
var bodyParser = require('body-parser');

// auth purpose
var session = require('express-session');
var passport = require('passport');
var mongoStore = require('connect-mongo')(session);
var mongoose = require('mongoose');

var config = require('./environment');

module.exports = function (app) {

  var env = config.env;

  app.set('view engine', 'html');
  app.use(bodyParser.urlencoded({ extended: false }));
  app.use(bodyParser.json());
  app.use(compression());
  app.use(function(req, res, next){
    var chalk = require('chalk');
    if(req.method !== 'GET') {
      console.info(''
        , chalk.yellow(req.method)
        , chalk.red(req.url)
      );
    }
    next();
  });
  app.use(passport.initialize());
  app.use(express.static(path.join(config.root, 'client')));
  app.set('appPath', 'client');

  app.use(session({
    secret: config.secrets.session,
    resave: true,
    saveUninitialized: true,
    store: new mongoStore({ mongooseConnection: mongoose.connection })
  }));

  if (env === 'development' || env === 'test') {
    app.use(require('errorhandler')());
  }

};
<commit_msg>fixing production<commit_after>'use strict';

var express = require('express');
var compression = require('compression');
var path = require('path');
var bodyParser = require('body-parser');

// auth purpose
var session = require('express-session');
var passport = require('passport');
var mongoStore = require('connect-mongo')(session);
var mongoose = require('mongoose');

var config = require('./environment');

module.exports = function (app) {

  var env = config.env;

  app.set('view engine', 'html');
  app.use(bodyParser.urlencoded({ extended: false }));
  app.use(bodyParser.json());
  app.use(compression());
  app.use(function(req, res, next){
    var chalk = require('chalk');
    console.info('[REQ]'
      , chalk.green(req.method)
      , chalk.grey(req.url)
    );
    next();
  });
  app.use(passport.initialize());
  app.use(express.static(path.join(config.root, 'client')));
  app.set('appPath', 'client');

  app.use(session({
    secret: config.secrets.session,
    resave: true,
    saveUninitialized: true,
    store: new mongoStore({ mongooseConnection: mongoose.connection })
  }));

  if (env === 'development' || env === 'test') {
    app.use(require('errorhandler')());
  }

};
<|endoftext|>


<commit_before>var API_KEY = process.env.SEND_GRID || require('./sendGrid-config.js');
var sendgrid = require('sendgrid')(API_KEY);

module.exports = {
  signupEmail: function(toEmail) {
    var emailBodyHtml = '
Join Reserver.space
' +
                        'Click here to sign up.';

    var email = new sendgrid.Email({
      to: toEmail,
      from: 'no-reply@reserver.space',
      subject: 'Join Reserver.space!',
      text: emailBodyHtml
    });

    sendgrid.send(email, function(err, json) {
      if(err){
        console.error(err);
      }
    });
  },

  reservationEmail: function(toEmail, reservationDetail) {
    var emailSubject = 'New Reservation at ' + reservationDetail.location + ' in ' +
                       reservationDetail.room;
    var emailBodyHtml = '
New reservation details:
' +
                        '
Location: ' + reservationDetail.location + '
' +
                        '
Room: ' + reservationDetail.room + '
' +
                        '
Title: ' + reservationDetail.reservationName + '
' +
                        '
Start: ' + reservationDetail.start + '
' +
                        '
End: ' + reservationDetail.end + '
' +
                        '
Reserved By: ' + reservationDetail.createdBy + '
';

    var email = new sendgrid.Email({
      to: toEmail,
      from: 'no-reply@reserver.space',
      subject: emailSubject,
      text: emailBodyHtml
    });

    sendgrid.send(email, function(err, json) {
      if(err){
        console.error(err);
      }
    });
  }
};
<commit_msg>[refact]: fixes html in email body<commit_after>var API_KEY = process.env.SEND_GRID || require('./sendGrid-config.js');
var sendgrid = require('sendgrid')(API_KEY);

module.exports = {
  signupEmail: function(toEmail) {
    var emailBodyHtml = '<title></title>' +
                        '
Join Reserver.space
' +
                        'Click here to sign up.';

    var email = new sendgrid.Email({
      to: toEmail,
      from: 'no-reply@reserver.space',
      subject: 'Join Reserver.space!',
      text: emailBodyHtml
    });

    sendgrid.send(email, function(err, json) {
      if(err){
        console.error(err);
      }
    });
  },

  reservationEmail: function(toEmail, reservationDetail) {
    var emailSubject = 'New Reservation at ' + reservationDetail.location + ' in ' +
                       reservationDetail.room;
    var emailBodyHtml = '<title></title>' +
                        '
New reservation details:
' +
                        '
Location: ' + reservationDetail.location + '
' +
                        '
Room: ' + reservationDetail.room + '
' +
                        '
Title: ' + reservationDetail.reservationName + '
' +
                        '
Start: ' + reservationDetail.start + '
' +
                        '
End: ' + reservationDetail.end + '
' +
                        '
Reserved By: ' + reservationDetail.createdBy + '
';

    var email = new sendgrid.Email({
      to: toEmail,
      from: 'no-reply@reserver.space',
      subject: emailSubject,
      text: emailBodyHtml
    });

    sendgrid.send(email, function(err, json) {
      if(err){
        console.error(err);
      }
    });
  }
};
<|endoftext|>


<commit_before>/*#ifndef(UMD)*/
"use strict";
/*global _gpfDefIntrf*/ // gpf.define for interfaces
/*global _gpfIgnore*/ // Helper to remove unused parameter warning
/*#endif*/

/**
 * Defines the possibility for the object to be saved as XML
 *
 * @class gpf.interfaces.IXmlSerializable
 * @extends gpf.interfaces.Interface
 */
_gpfDefIntrf("IXmlSerializable", {

    /**
     * Translate obj into an gpf.interfaces.IXmlContentHandler and serialize
     * itself into XML
     *
     * @param {gpf.interfaces.IXmlContentHandler} out XML Content handler
     * @param {gpf.events.Handler} eventsHandler
     *
     * @event ready
     */
    "[toXml]": [gpf.$ClassEventHandler()],
    toXml: function (out, eventsHandler) {
        _gpfIgnore(out, eventsHandler);
    }

});

/**
 * Defines the possibility for an object to receive XML serialization events
 *
 * @class gpf.interfaces.IXmlContentHandler
 * @extends gpf.interfaces.Interface
 *
 * Inspired from
 * http://www.saxproject.org/apidoc/org/xml/sax/ContentHandler.html
 */
_gpfDefIntrf("IXmlContentHandler", {

    /**
     * Receive notification of character data
     *
     * @param {String} buffer characters
     * @param {gpf.events.Handler} eventsHandler
     *
     * @event ready
     */
    "[characters]": [gpf.$ClassEventHandler()],
    characters: function (buffer, eventsHandler) {
        _gpfIgnore(buffer, eventsHandler);
    },

    /**
     * Receive notification of the end of a document
     *
     * @param {gpf.events.Handler} eventsHandler
     *
     * @event ready
     */
    "[endDocument]": [gpf.$ClassEventHandler()],
    endDocument: function (eventsHandler) {
        _gpfIgnore(eventsHandler);
    },

    /**
     * Signal the end of an element
     *
     * @param {gpf.events.Handler} eventsHandler
     *
     * @event ready
     */
    "[endElement]": [gpf.$ClassEventHandler()],
    endElement: function (eventsHandler) {
        _gpfIgnore(eventsHandler);
    },

    /**
     *  End the scope of a prefix-URI mapping
     *
     * @param {String} prefix
     *
     * @event ready
     */
    endPrefixMapping: function (prefix) {
        _gpfIgnore(prefix);
    },

    /**
     * Receive notification of ignorable whitespace in element content
     *
     * @param {String} buffer characters
     * @param {gpf.events.Handler} eventsHandler
     *
     * @event ready
     */
    "[ignorableWhitespace]": [gpf.$ClassEventHandler()],
    ignorableWhitespace: function (buffer, eventsHandler) {
        _gpfIgnore(buffer, eventsHandler);
    },

    /**
     * Receive notification of a processing instruction
     *
     * @param {String} target
     * @param {String} data
     * @param {gpf.events.Handler} eventsHandler
     *
     * @event ready
     */
    "[processingInstruction]": [gpf.$ClassEventHandler()],
    processingInstruction: function (target, data, eventsHandler) {
        _gpfIgnore(target, data, eventsHandler);
    },

    /**
     * Receive an object for locating the origin of SAX document events.
     *
     * @param {*} locator
     */
    setDocumentLocator: function (locator) {
        _gpfIgnore(locator);
    },

    /**
     * Receive notification of a skipped entity
     *
     * @param {String} name
     */
    skippedEntity: function (name) {
        _gpfIgnore(name);
    },

    /**
     * Receive notification of the beginning of a document
     *
     * @param {gpf.events.Handler} eventsHandler
     */
    "[startDocument]": [gpf.$ClassEventHandler()],
    startDocument: function (eventsHandler) {
        _gpfIgnore(eventsHandler);
    },

    /**
     * Receive notification of the beginning of an element
     *
     * @param {Object} name structure containing
     * - {String} uri [uri=""] namespace uri (if any)
     * - {String} localName
     * - {String} [qName=localName] qName qualified name
     * @param {Object} attributes attribute dictionary (string/string)
     * @param {gpf.events.Handler} eventsHandler
     */
    "[startElement]": [gpf.$ClassEventHandler()],
    startElement: function (name, attributes, eventsHandler) {
        _gpfIgnore(name, attributes, eventsHandler);
    },

    /**
     * Begin the scope of a prefix-URI Namespace mapping
     *
     * @param {String} prefix
     * @param {String} uri
     */
    startPrefixMapping: function (prefix, uri) {
        _gpfIgnore(prefix, uri);
    }

});

<commit_msg>documentation<commit_after>/**
 * @file IXmlSerializable, IXmlContentHandler
 */
/*#ifndef(UMD)*/
"use strict";
/*global _gpfDefIntrf*/ // gpf.define for interfaces
/*global _gpfIgnore*/ // Helper to remove unused parameter warning
/*#endif*/

/**
 * Defines the possibility for the object to be saved as XML
 *
 * @class gpf.interfaces.IXmlSerializable
 * @extends gpf.interfaces.Interface
 */
_gpfDefIntrf("IXmlSerializable", {

    /**
     * Translate obj into an gpf.interfaces.IXmlContentHandler and serialize
     * itself into XML
     *
     * @param {gpf.interfaces.IXmlContentHandler} out XML Content handler
     * @param {gpf.events.Handler} eventsHandler
     *
     * @event ready
     */
    "[toXml]": [gpf.$ClassEventHandler()],
    toXml: function (out, eventsHandler) {
        _gpfIgnore(out, eventsHandler);
    }

});

/**
 * Defines the possibility for an object to receive XML serialization events
 *
 * @class gpf.interfaces.IXmlContentHandler
 * @extends gpf.interfaces.Interface
 *
 * Inspired from
 * http://www.saxproject.org/apidoc/org/xml/sax/ContentHandler.html
 */
_gpfDefIntrf("IXmlContentHandler", {

    /**
     * Receive notification of character data
     *
     * @param {String} buffer characters
     * @param {gpf.events.Handler} eventsHandler
     *
     * @event ready
     */
    "[characters]": [gpf.$ClassEventHandler()],
    characters: function (buffer, eventsHandler) {
        _gpfIgnore(buffer, eventsHandler);
    },

    /**
     * Receive notification of the end of a document
     *
     * @param {gpf.events.Handler} eventsHandler
     *
     * @event ready
     */
    "[endDocument]": [gpf.$ClassEventHandler()],
    endDocument: function (eventsHandler) {
        _gpfIgnore(eventsHandler);
    },

    /**
     * Signal the end of an element
     *
     * @param {gpf.events.Handler} eventsHandler
     *
     * @event ready
     */
    "[endElement]": [gpf.$ClassEventHandler()],
    endElement: function (eventsHandler) {
        _gpfIgnore(eventsHandler);
    },

    /**
     *  End the scope of a prefix-URI mapping
     *
     * @param {String} prefix
     *
     * @event ready
     */
    endPrefixMapping: function (prefix) {
        _gpfIgnore(prefix);
    },

    /**
     * Receive notification of ignorable whitespace in element content
     *
     * @param {String} buffer characters
     * @param {gpf.events.Handler} eventsHandler
     *
     * @event ready
     */
    "[ignorableWhitespace]": [gpf.$ClassEventHandler()],
    ignorableWhitespace: function (buffer, eventsHandler) {
        _gpfIgnore(buffer, eventsHandler);
    },

    /**
     * Receive notification of a processing instruction
     *
     * @param {String} target
     * @param {String} data
     * @param {gpf.events.Handler} eventsHandler
     *
     * @event ready
     */
    "[processingInstruction]": [gpf.$ClassEventHandler()],
    processingInstruction: function (target, data, eventsHandler) {
        _gpfIgnore(target, data, eventsHandler);
    },

    /**
     * Receive an object for locating the origin of SAX document events.
     *
     * @param {*} locator
     */
    setDocumentLocator: function (locator) {
        _gpfIgnore(locator);
    },

    /**
     * Receive notification of a skipped entity
     *
     * @param {String} name
     */
    skippedEntity: function (name) {
        _gpfIgnore(name);
    },

    /**
     * Receive notification of the beginning of a document
     *
     * @param {gpf.events.Handler} eventsHandler
     */
    "[startDocument]": [gpf.$ClassEventHandler()],
    startDocument: function (eventsHandler) {
        _gpfIgnore(eventsHandler);
    },

    /**
     * Receive notification of the beginning of an element
     *
     * @param {Object} name structure containing
     * - {String} uri [uri=""] namespace uri (if any)
     * - {String} localName
     * - {String} [qName=localName] qName qualified name
     * @param {Object} attributes attribute dictionary (string/string)
     * @param {gpf.events.Handler} eventsHandler
     */
    "[startElement]": [gpf.$ClassEventHandler()],
    startElement: function (name, attributes, eventsHandler) {
        _gpfIgnore(name, attributes, eventsHandler);
    },

    /**
     * Begin the scope of a prefix-URI Namespace mapping
     *
     * @param {String} prefix
     * @param {String} uri
     */
    startPrefixMapping: function (prefix, uri) {
        _gpfIgnore(prefix, uri);
    }

});

<|endoftext|>


<commit_before>/**
 * @fileOverview
 * Widget module.

 * Represents widget class.
 * Implements common widget interface.
 * All render details must be implemented in classes ******Widget.js
 * and added to typesMap
 * @author Shmidt Ivan
 * @version 0.0.1
 * @module Widget
 * @requires FiltersList
 * @requires Utils
 * @requires MessageCenter
 */
define([
    'FiltersList',
    'Utils',
    'MessageCenter',
    'HighchartsWidget',
    'PivotWidget',
    'TextWidget'
], function (FiltersList, Utils, mc, HighchartsWidget, PivotWidget, TextWidget) {
    /**
     * Creates new Widget object
     * @alias module:Widget
     * @constructor Widget
     * @param config Configuration object
     * @listens module:MessageCenter#widget*_data_acquired
     * @return {module:Widget} new Widget object
     * @example
     *
Creating new widget

     * new Widget(config);
     */
    function Widget(opts) {

        this.def = opts.promise;
        opts = opts || {};
        /** @lends module:Widget#*/
        'use strict';
        this.active = false;
        /**
         * If defined, would be used for data convertion
         * @function module:Widget#convertor
         * @return ConvertedData
         */
        this.convertor = _.has(opts, 'convertor') ? opts.convertor : null;
        /**
         * @var {number} module:Widget#id ID of widget in dashboard
         */
        this.id = _.has(opts, 'id') ? opts.id : null;
        this.callback = opts.callback || undefined;
        /**
         * @var {string} module:Widget#name Name of widget (title)
         */
        this.name = _.has(opts, 'config') ? opts.config.title.text : "Widget" + this.id;
        /**
         * @var {module:Dashboard} module:Widget#dashboard Parent dashboard object
         */
        this.dashboard = _.has(opts, 'dashboard') ? opts.dashboard : null;
        /**
         * @var {Object} module:Widget#config Chart config object
         */
        this.config = _.has(opts, 'config') ? opts.config : {};
        /**
         * @var {Object} module:Widget#chart Amcharts object, created after rendering
         *@deprecated
         */
        this.chart = '';
        this.subs = [];

        /**
         * @var {string} module:Widget#cube Cube name used by widget
         */
        this.cube = null;
        var parts = opts.datasource.data.MDX.toUpperCase().split("FROM ");
        if (parts.length >= 2) {
            this.cube = parts[1].split(" ")[0].replace("[", "").replace("]", "");
        }

        /**
         * @var {object} module:Widget#datasource Object with getter and setter, represents Widget's data source
         */
        var _datasource = {};

        //Set up datasource without using setter
        _datasource = opts.datasource || {
            data: {}
        };
        Object.defineProperty(this, 'datasource', {
            get: function () {
                var retVal = _datasource.data.MDX;
                //if (this.type = 'pivot') retVal = _datasource.data.basemdx;
                if (this.filters.hasFilters()) {
                    var _filters = this.filters.getAll();
                    for (var i in _filters) {
                        if ($.isArray(_filters[i].value)) {
                            if (_filters[i].value.length == 1) {
                                if (_filters[i].value[0] != '') retVal += ' %FILTER ' + _filters[i].path + "." + _filters[i].value[0];
                            } else {
                                retVal += ' %FILTER {'
                                for (var k = 0; k < _filters[i].value.length; k++) {
                                    if (_filters[i].value[k] != "") retVal += _filters[i].path + "." + _filters[i].value[k] + ",";
                                }
                                if (retVal.substr(retVal.length - 1, 1) == ",") retVal= retVal.substr(0, retVal.length - 1);
                                retVal += "} ";
                            }
                        } else {
                            if (_filters[i].value != '') retVal += ' %FILTER ' + _filters[i].path + "." + _filters[i].value;
                        }
                    }
                }
                if (this.controls) {
                    for (var i = 0; i< this.controls.length; i++) {
                        if (this.controls[i].action == "applyFilter") {
                            retVal += ' %FILTER {' + this.controls[i].targetProperty +  "." + this.controls[i].value + "} ";
                        }

                    }
                }
                return {
                    data: {
                        MDX: retVal
                    }
                };
            },
            set: function (value) {
                _datasource = value;
                this.requestData();
            }

        });
        this.filters = "";

        var typesMap = {
            'highcharts': HighchartsWidget,
            'pivot': PivotWidget,
            'textMeter': TextWidget
        };
        //Extend with type-specified opts
        if (_.has(opts, 'type') && _.has(typesMap, opts.type)) {
            _.extend(this, new typesMap[opts.type](opts))
        };
        /**
         * Callback, fired when data acquired
         * @function module:Widget#onDataAcquired
         * @private
         * @todo Route which field data would be kept
         */
        this.onDataAcquired = function (d, isDrillDown) {
            //console.log(d);
             $("#widget" + this.id).parent().find(".error-msg").html('').hide();
            if(isDrillDown === undefined) isDrillDown = false;
            if (d===undefined || d.data === null) {
                $("#widget" + this.id).parent().find(".error-msg").html("
Dataset is empty, change filters or query
").show();
                return;
            }
            if (this.convertor) {
                // d =  || d;
                d = this.convertor(d);
            }
            if (this.callback) {
                //Added widget link to callback's call
                this.callback(d,this);
            }
            if (this.renderWidget) this.renderWidget(isDrillDown);
        };
        this.removeRefs = function () {
            var self = this;
            _.each(this.subs, function (sub, i) {
                mc.remove(sub);
                sub = null;
                self.subs.splice(i, 1);
            });
            this.subs = [];
            self = null;
        };
        //When created widget, must subscribe to widget[i] data acquired
        this.init(opts);
        return this;
    };

    Widget.prototype.toString = function () {
        return "Widget" + this.id;
    };
    Widget.prototype.init = function (opts) {
        this.subs.push(mc.subscribe("data_acquired:widget" + this.id, {
            subscriber: this,
            callback: this.onDataAcquired
        }));
        mc.subscribe("clear:widgets", {
            subscriber: this,
            callback: this.removeRefs,
            once: true
        });
        /**
         * @var {module:FiltersList} module:Widget#filters Selected filters list
         */
        this.filters = new FiltersList({
            filters: opts.filters || [],
            onSetFilter: this.requestData,
            container: "#widget" + this.id,
            w_obj: this
        });
        var self = this;
        this.createHolder().then(function(){self.requestData()});
        mc.publish('[Init]Finished: ' +this.name);
    };
    /**
     * Simply renders widget
     *@function module:Widget#render
     */
    Widget.prototype.createHolder = function () {
        var def = $.Deferred();

        var widget_holder = this.dashboard.config.holder + " .dashboard" || ".content .dashboard";
        var self = this;
        require(["text!../views/Widget.html"], function (html) {
            html = html./*replace("{{title}}", self.name).*/replace("{{id}}", self.id);
            if ($("#widget" + self.id)[0] == undefined) {
                $(widget_holder).append(html);
                def.resolve();
            }
            self = null;
        });

        return def.promise();

    };
    /**
     * Request data from module:MessageCenter
     * @function module:Widget#requestData
     * @fires module:MessageCenter#data_requested
     */
    Widget.prototype.requestData = function () {
        mc.publish("data_requested:widget" + this.id, {
            data: this.datasource.data
        });
    };

    /**
     * Called when widget activated(currently on screen)
     * @function module:Widget#onActivate
     */
    Widget.prototype.onActivate = function () {
        if (this.filters.hasFilters()) $("#btnMainFilter").addClass("tab-item-green"); else $("#btnMainFilter").removeClass("tab-item-green");
    }

    /**
     * Called when widget deactivated
     * @function module:Widget#onActivate
     */
    Widget.prototype.onDeactivate = function () {
        $("#btnMainFilter").removeClass("tab-item-green");
    }

    return Widget;
})<commit_msg>custom drilldown support<commit_after>/**
 * @fileOverview
 * Widget module.

 * Represents widget class.
 * Implements common widget interface.
 * All render details must be implemented in classes ******Widget.js
 * and added to typesMap
 * @author Shmidt Ivan
 * @version 0.0.1
 * @module Widget
 * @requires FiltersList
 * @requires Utils
 * @requires MessageCenter
 */
define([
    'FiltersList',
    'Utils',
    'MessageCenter',
    'HighchartsWidget',
    'PivotWidget',
    'TextWidget'
], function (FiltersList, Utils, mc, HighchartsWidget, PivotWidget, TextWidget) {
    /**
     * Creates new Widget object
     * @alias module:Widget
     * @constructor Widget
     * @param config Configuration object
     * @listens module:MessageCenter#widget*_data_acquired
     * @return {module:Widget} new Widget object
     * @example
     *
Creating new widget

     * new Widget(config);
     */
    function Widget(opts) {

        this.def = opts.promise;
        opts = opts || {};
        /** @lends module:Widget#*/
        'use strict';
        this.active = false;
        /**
         * If defined, would be used for data convertion
         * @function module:Widget#convertor
         * @return ConvertedData
         */
        this.convertor = _.has(opts, 'convertor') ? opts.convertor : null;
        /**
         * @var {number} module:Widget#id ID of widget in dashboard
         */
        this.id = _.has(opts, 'id') ? opts.id : null;
        this.callback = opts.callback || undefined;
        /**
         * @var {string} module:Widget#name Name of widget (title)
         */
        this.name = _.has(opts, 'config') ? opts.config.title.text : "Widget" + this.id;
        /**
         * @var {module:Dashboard} module:Widget#dashboard Parent dashboard object
         */
        this.dashboard = _.has(opts, 'dashboard') ? opts.dashboard : null;
        /**
         * @var {Object} module:Widget#config Chart config object
         */
        this.config = _.has(opts, 'config') ? opts.config : {};
        /**
         * @var {Object} module:Widget#chart Amcharts object, created after rendering
         *@deprecated
         */
        this.chart = '';
        this.subs = [];
        this.pivotName = null;
        this.pivotData = null;
        this.drillLevel = 0;
        this.drills = [];
        this.controls = [];
        /**
         * @var {string} module:Widget#cube Cube name used by widget
         */
        this.cube = null;
        var parts = opts.datasource.data.MDX.toUpperCase().split("FROM ");
        if (parts.length >= 2) {
            this.cube = parts[1].split(" ")[0].replace("[", "").replace("]", "");
        }

        /**
         * @var {object} module:Widget#datasource Object with getter and setter, represents Widget's data source
         */
        var _datasource = {};

        //Set up datasource without using setter
        _datasource = opts.datasource || {
            data: {}
        };
        Object.defineProperty(this, 'datasource', {
            get: function () {
                var retVal = _datasource.data.MDX;
                //if (this.type = 'pivot') retVal = _datasource.data.basemdx;
                if (this.filters.hasFilters()) {
                    var _filters = this.filters.getAll();
                    for (var i in _filters) {
                        if ($.isArray(_filters[i].value)) {
                            if (_filters[i].value.length == 1) {
                                if (_filters[i].value[0] != '') retVal += ' %FILTER ' + _filters[i].path + "." + _filters[i].value[0];
                            } else {
                                retVal += ' %FILTER {'
                                for (var k = 0; k < _filters[i].value.length; k++) {
                                    if (_filters[i].value[k] != "") retVal += _filters[i].path + "." + _filters[i].value[k] + ",";
                                }
                                if (retVal.substr(retVal.length - 1, 1) == ",") retVal= retVal.substr(0, retVal.length - 1);
                                retVal += "} ";
                            }
                        } else {
                            if (_filters[i].value != '') retVal += ' %FILTER ' + _filters[i].path + "." + _filters[i].value;
                        }
                    }
                }
                /*if (this.controls) {
                    for (var i = 0; i< this.controls.length; i++) {
                        if (this.controls[i].action == "applyFilter") {
                            retVal += ' %FILTER {' + this.controls[i].targetProperty +  "." + this.controls[i].value + "} ";
                        }

                    }
                }*/
                return {
                    data: {
                        MDX: retVal
                    }
                };
            },
            set: function (value) {
                _datasource = value;
                this.requestData();
            }

        });
        this.filters = "";

        var typesMap = {
            'highcharts': HighchartsWidget,
            'pivot': PivotWidget,
            'textMeter': TextWidget
        };
        //Extend with type-specified opts
        if (_.has(opts, 'type') && _.has(typesMap, opts.type)) {
            _.extend(this, new typesMap[opts.type](opts))
        };

        /**
         * Callback, fired when pivot data acquired
         * @function module:Widget#onPivotDataAcquired
         * @private
         *
         */
        this.onPivotDataAcquired = function (d) {
            var data = d.data;
            if (typeof data != "object") data = JSON.parse(d);
            this.pivotData = data;
        };

        /**
         * Callback, fired when data acquired
         * @function module:Widget#onDataAcquired
         * @private
         * @todo Route which field data would be kept
         */
        this.onDataAcquired = function (d, isDrillDown) {
            //console.log(d);
             $("#widget" + this.id).parent().find(".error-msg").html('').hide();
            if(isDrillDown === undefined) isDrillDown = false;
            if (d===undefined || d.data === null) {
                $("#widget" + this.id).parent().find(".error-msg").html("
Dataset is empty, change filters or query
").show();
                return;
            }
            if (this.convertor) {
                // d =  || d;
                d = this.convertor(d);
            }
            if (this.callback) {
                //Added widget link to callback's call
                this.callback(d,this);
            }
            if (this.renderWidget) this.renderWidget(isDrillDown);
        };
        this.removeRefs = function () {
            var self = this;
            _.each(this.subs, function (sub, i) {
                mc.remove(sub);
                sub = null;
                self.subs.splice(i, 1);
            });
            this.subs = [];
            self = null;
        };
        //When created widget, must subscribe to widget[i] data acquired
        this.init(opts);
        return this;
    };

    Widget.prototype.toString = function () {
        return "Widget" + this.id;
    };
    Widget.prototype.init = function (opts) {
        this.pivotName = opts.datasource.pivot;

        this.subs.push(mc.subscribe("data_acquired:widget" + this.id, {
            subscriber: this,
            callback: this.onDataAcquired
        }));

        this.subs.push(mc.subscribe("pivotdata_acquired:widget" + this.id, {
            subscriber: this,
            callback: this.onPivotDataAcquired
        }));

        mc.subscribe("clear:widgets", {
            subscriber: this,
            callback: this.removeRefs,
            once: true
        });
        /**
         * @var {module:FiltersList} module:Widget#filters Selected filters list
         */
        this.filters = new FiltersList({
            filters: opts.filters || [],
            onSetFilter: this.requestData,
            container: "#widget" + this.id,
            w_obj: this
        });
        var self = this;
        this.createHolder().then(function(){self.requestData()});
        mc.publish('[Init]Finished: ' +this.name);
    };
    /**
     * Simply renders widget
     *@function module:Widget#render
     */
    Widget.prototype.createHolder = function () {
        var def = $.Deferred();

        var widget_holder = this.dashboard.config.holder + " .dashboard" || ".content .dashboard";
        var self = this;
        require(["text!../views/Widget.html"], function (html) {
            html = html./*replace("{{title}}", self.name).*/replace("{{id}}", self.id);
            if ($("#widget" + self.id)[0] == undefined) {
                $(widget_holder).append(html);
                def.resolve();
            }
            self = null;
        });

        return def.promise();

    };
    /**
     * Request data from module:MessageCenter
     * @function module:Widget#requestData
     * @fires module:MessageCenter#data_requested
     */
    Widget.prototype.requestData = function () {
        this.drillLevel = 0;
        this.drills = [];
        mc.publish("data_requested:widget" + this.id, {
            data: this.datasource.data
        });
        if (this.pivotName) {
            mc.publish("pivotdata_requested:widget" + this.id, {
                data: this.pivotName
            });
        }
    };

    /**
     * Called when widget activated(currently on screen)
     * @function module:Widget#onActivate
     */
    Widget.prototype.onActivate = function () {
        if (this.filters.hasFilters()) $("#btnMainFilter").addClass("tab-item-green"); else $("#btnMainFilter").removeClass("tab-item-green");
    }

    /**
     * Called when widget deactivated
     * @function module:Widget#onActivate
     */
    Widget.prototype.onDeactivate = function () {
        $("#btnMainFilter").removeClass("tab-item-green");
    }

    return Widget;
})<|endoftext|>


<commit_before>angular.module("viradapp.config", [])
.factory('Conn', function(){
    CONN = "DEFAULT";

    // Connection Change Handler
    // This function just change the global connection type
    var connChangeHandler = function(conn){
        if(window.Connection) {
            if(Connection.NONE == conn.type){
                viradapp.value('CONN', Connection.NONE);
            } else if(Connection.ETHERNET == conn.type
                || Connection.WIFI == conn.type
                    || Connection.CELL_4G){
                        CONN = "FAST";
                    } else {
                        CONN = "SLOW";
                    }
        } else {
            CONN = "UNKNOWN";
        }
    }

    document.addEventListener("online", connChangeHandler, false);
    document.addEventListener("offline", connChangeHandler, false);

    return {
        type: function(){
            return CONN;
        }
    }
})
.factory('GlobalConfiguration', function(){
    return {
        BASE_URL : "http://viradacultural.prefeitura.sp.gov.br/2015/wp-content/themes/viradacultural-2015/app",
        TEMPLATE_URL : "http://viradacultural.prefeitura.sp.gov.br/2015/wp-content/themes/viradacultural-2015",
        SHARE_URL : "http://viradacultural.prefeitura.sp.gov.br/2015",
        APP_ID: '1379698002311750'
    }
});

<commit_msg>facebook: add app_id<commit_after>angular.module("viradapp.config", [])
.factory('Conn', function(){
    CONN = "DEFAULT";

    // Connection Change Handler
    // This function just change the global connection type
    var connChangeHandler = function(conn){
        if(window.Connection) {
            if(Connection.NONE == conn.type){
                viradapp.value('CONN', Connection.NONE);
            } else if(Connection.ETHERNET == conn.type
                || Connection.WIFI == conn.type
                    || Connection.CELL_4G){
                        CONN = "FAST";
                    } else {
                        CONN = "SLOW";
                    }
        } else {
            CONN = "UNKNOWN";
        }
    }

    document.addEventListener("online", connChangeHandler, false);
    document.addEventListener("offline", connChangeHandler, false);

    return {
        type: function(){
            return CONN;
        }
    }
})
.factory('GlobalConfiguration', function(){
    return {
        BASE_URL : "http://viradacultural.prefeitura.sp.gov.br/2015/wp-content/themes/viradacultural-2015/app",
        TEMPLATE_URL : "http://viradacultural.prefeitura.sp.gov.br/2015/wp-content/themes/viradacultural-2015",
        SHARE_URL : "http://viradacultural.prefeitura.sp.gov.br/2015",
        APP_ID: '1460336737533597'
    }
});

<|endoftext|>


<commit_before>function on_load() {
  mostrar_curso();
}

function toggle_modal_agregar() {
  e = document.getElementById('modal');
  e.style.visibility = e.style.visibility == 'visible' ? 'hidden' : 'visible';
}

function toggle_modal_clonar() {
  e = document.getElementById('modal');
  e.style.visibility = e.style.visibility == 'visible' ? 'hidden' : 'visible';

  document.getElementById('new_clave').value = document.getElementById('clave_materia').value;
  document.getElementById('new_materia').value = document.getElementById('materia').value;
  document.getElementById('new_academia').value = document.getElementById('academia').value;
  document.getElementById('new_nrc').value = document.getElementById('nrc').value;
  document.getElementById('new_seccion').value = document.getElementById('seccion').value;
}

function mostrar_curso() {
  ciclo = document.getElementById('ciclo_select').value;
  clave = document.getElementById('curso_select').value.split(" ")[0];

  if (ciclo == '') {
    document.getElementById('ciclo_select').disabled = true;
  }

  $.ajax({
    type: 'POST',
    data: {llenar_curso:'', ciclo:ciclo, clave:clave},
    dataType: 'json',
    success: function(info) {
      document.getElementById('clave_materia').value = info['clave_materia'];
      document.getElementById('materia').value = info['materia'];
      document.getElementById('academia').value = info['academia'];
      document.getElementById('nrc').value = info['nrc'];
      document.getElementById('seccion').value = info['seccion'];
      var horarios = info['dia'].length;
      console.log('horarios: '+horarios);
      for (var i = 0; i < horarios; i++) {
        console.log(info['dia'][i]+': '+info['horas_por_dia'][i]+', '+info['horario'][i]);
      }
    },
    error: function() {
      document.getElementById('curso_select').disabled = true;
      document.getElementById('clave_materia').disabled = true;
      document.getElementById('nrc').disabled = true;
      document.getElementById('seccion').disabled = true;
      document.getElementById('b_diaclase').disabled = true;
      document.getElementById('ver_evaluacion').disabled = true;
      document.getElementById('ver_asistencias').disabled = true;
      document.getElementById('clonar').disabled = true;
    }
  });
}

function mostrar_materia(clave_materia, materia, academia) {
  clave = document.getElementById(clave_materia).value;

  $.ajax({
    type: 'POST',
    data: {llenar_materia:'', clave:clave},
    dataType: 'json',
    success: function(info) {
      document.getElementById(materia).value = info['materia'];
      document.getElementById(academia).value = info['academia'];
    },
    error: function() {
      caja = document.getElementById(clave_materia);
      colorearCaja(false);
      caja.title="La clave de la materia es incorrecta";
      document.getElementById(materia).value = '';
      document.getElementById(academia).value = '';
    }
  });
}

function agregar_curso()
{
  ciclo = document.getElementById('new_ciclo').value;
  clave = document.getElementById('new_clave').value;
  nrc = document.getElementById('new_nrc').value;
  seccion = document.getElementById('new_seccion').value;
  var dia="";
  var hora="";
  var duracion="";
  for(i=1;i<=id_horario;i++)
  {
    if(document.getElementById('cClase_'+i))
    {
      dia_actual=document.getElementById('SelectDia_m_'+i).value.trim();
      hora_actual=document.getElementById('Hora_inicio_clasem_'+i).value.trim();
      duracion_actual=document.getElementById('duracion_'+i).value.trim();
      if(dia_festivo_actual.length!=0 || descripcion_actual.length!=0)
      {
        dia+=dia_actual+",";
        hora+=hora_actual+",";
        duracion+=duracion_actual+",";
      }
    }
  }
  $.ajax({
    type: 'POST',
    data: {guardar:'',ciclo:ciclo,clave:clave,nrc:nrc,seccion:seccion,dia:dia,hora:hora, duracion:duracion},
    success: function() {
      location.reload();
    }
  });
}
<commit_msg>Limpiar datos en agregar cursos<commit_after>function on_load() {
  mostrar_curso();
}

function toggle_modal_agregar() {
  e = document.getElementById('modal');
  e.style.visibility = e.style.visibility == 'visible' ? 'hidden' : 'visible';

  document.getElementById('new_clave').value = '';
  document.getElementById('new_materia').value = '';
  document.getElementById('new_academia').value = '';
  document.getElementById('new_nrc').value = '';
  document.getElementById('new_seccion').value = '';
}

function toggle_modal_clonar() {
  e = document.getElementById('modal');
  e.style.visibility = e.style.visibility == 'visible' ? 'hidden' : 'visible';

  document.getElementById('new_clave').value = document.getElementById('clave_materia').value;
  document.getElementById('new_materia').value = document.getElementById('materia').value;
  document.getElementById('new_academia').value = document.getElementById('academia').value;
  document.getElementById('new_nrc').value = document.getElementById('nrc').value;
  document.getElementById('new_seccion').value = document.getElementById('seccion').value;
}

function mostrar_curso() {
  ciclo = document.getElementById('ciclo_select').value;
  clave = document.getElementById('curso_select').value.split(" ")[0];

  if (ciclo == '') {
    document.getElementById('ciclo_select').disabled = true;
  }

  $.ajax({
    type: 'POST',
    data: {llenar_curso:'', ciclo:ciclo, clave:clave},
    dataType: 'json',
    success: function(info) {
      document.getElementById('clave_materia').value = info['clave_materia'];
      document.getElementById('materia').value = info['materia'];
      document.getElementById('academia').value = info['academia'];
      document.getElementById('nrc').value = info['nrc'];
      document.getElementById('seccion').value = info['seccion'];
      var horarios = info['dia'].length;
      console.log('horarios: '+horarios);
      for (var i = 0; i < horarios; i++) {
        console.log(info['dia'][i]+': '+info['horas_por_dia'][i]+', '+info['horario'][i]);
      }
    },
    error: function() {
      document.getElementById('curso_select').disabled = true;
      document.getElementById('clave_materia').disabled = true;
      document.getElementById('nrc').disabled = true;
      document.getElementById('seccion').disabled = true;
      document.getElementById('b_diaclase').disabled = true;
      document.getElementById('ver_evaluacion').disabled = true;
      document.getElementById('ver_asistencias').disabled = true;
      document.getElementById('clonar').disabled = true;
    }
  });
}

function mostrar_materia(clave_materia, materia, academia) {
  clave = document.getElementById(clave_materia).value;

  $.ajax({
    type: 'POST',
    data: {llenar_materia:'', clave:clave},
    dataType: 'json',
    success: function(info) {
      document.getElementById(materia).value = info['materia'];
      document.getElementById(academia).value = info['academia'];
    },
    error: function() {
      caja = document.getElementById(clave_materia);
      colorearCaja(false);
      caja.title="La clave de la materia es incorrecta";
      document.getElementById(materia).value = '';
      document.getElementById(academia).value = '';
    }
  });
}

function agregar_curso()
{
  ciclo = document.getElementById('new_ciclo').value;
  clave = document.getElementById('new_clave').value;
  nrc = document.getElementById('new_nrc').value;
  seccion = document.getElementById('new_seccion').value;
  var dia="";
  var hora="";
  var duracion="";
  for(i=1;i<=id_horario;i++)
  {
    if(document.getElementById('cClase_'+i))
    {
      dia_actual=document.getElementById('SelectDia_m_'+i).value.trim();
      hora_actual=document.getElementById('Hora_inicio_clasem_'+i).value.trim();
      duracion_actual=document.getElementById('duracion_'+i).value.trim();
      if(dia_festivo_actual.length!=0 || descripcion_actual.length!=0)
      {
        dia+=dia_actual+",";
        hora+=hora_actual+",";
        duracion+=duracion_actual+",";
      }
    }
  }
  $.ajax({
    type: 'POST',
    data: {guardar:'',ciclo:ciclo,clave:clave,nrc:nrc,seccion:seccion,dia:dia,hora:hora, duracion:duracion},
    success: function() {
      location.reload();
    }
  });
}
<|endoftext|>


<commit_before>Template7.registerHelper('placeholder', function(plchldrContent) {
    var ret = 'placeholder="' + plchldrContent + '"';
    return ret;
});

// Initialize app
var myApp = new Framework7({
    swipeBackPage: false,
    swipePanelOnlyClose: true,
    template7Pages: true
});

var $$ = Dom7;

var langIsSeleted = window.localStorage.getItem("langIsSelected");
var userLoggedIn = window.localStorage.getItem("isLogin");
var selectedLang;
var langData;

if (langIsSeleted) {
    selectedLang = window.localStorage.getItem("lang");
} else {
    selectedLang = "tr"; // Set turkish to default language
}

// Add view
var mainView = myApp.addView('.view-main', {

});

getLangJson();

changePanelLanguage();

setTimeout(function() {

    checkLangStatus();

}, 3000);

function checkLangStatus() {
    if (langIsSeleted) {
        checkLoginStatus();
    } else {
        mainView.router.loadPage({ url: 'language.html', ignoreCache: true });
    }
}

function changePanelLanguage() {

    myApp.alert(langData);
    var panelData = langData + '.' + selectedLang + '.panel';

    $$('#panelTitle').text(panelData.panelTitle);
    $$('#orderItem').text(panelData.orderItem);
    $$('#orderBoxItem').text(panelData.orderBoxItem);
    $$('#accountItem').text(panelData.accountItem);
    $$('#addressItem').text(panelData.addressItem);
    $$('#myOrdersItem').text(panelData.myOrdersItem);
    $$('#workItem').text(panelData.workItem);
    $$('#helpItem').text(panelData.helpItem);
    $$('#infoItem').text(panelData.infoItem);
    $$('#messageItem').text(panelData.messageItem);
    $$('#logoutItem').text(panelData.logoutItem);
}

function loadPageWithLang(pageName) {
    var cntxName = 'languages.' + selectedLang + '.' + pageName;
    var pgUrl = pageName + '.html';

    mainView.router.load({
        url: pgUrl,
        contextName: cntxName
    });
}

function checkLoginStatus() {

    try {
        if (userLoggedIn) {
            loadPageWithLang('main');

        } else {
            loadPageWithLang('login');
        }
    } catch (e) {
        myApp.alert(e);
    }

}

function getLangJson() {
    $$.getJSON('./languages/lang.json', function(data) {
        myApp.template7Data.languages = data.languages;
        langData = JSON.stringify(data.languages);
        myApp.alert(langData);
    });
}

// Handle Cordova Device Ready Event
$$(document).on('deviceready', function() {
    console.log("Device is ready!");
});

// Option 2. Using one 'pageInit' event handler for all pages:
$$(document).on('pageInit', function(e) {
    // Get page data from event data
    var page = e.detail.page;

    if (page.name === 'login') {
        // Following code will be executed for page with data-page attribute equal to "about"
        //myApp.alert('Here comes login page');
        $$('.btnLogin').on('click', function() {
            var email = $$('#txtEmail').val();
            var pass = $$('#txtPassword').val();
            var response = mobileLogin(email, pass);

            if (response != 'NOK') {
                loadPageWithLang('main');
                window.localStorage.setItem("isLogin", true);
            } else {
                window.localStorage.setItem("isLogin", false);

            }

        });

        $$('.btnForgetPassword').on('click', function() {
            myApp.alert('Unuttum bişeyleri');
        });

        $$('.btnRegister').on('click', function() {
            myApp.prompt('Lütfen E-mail Adresini Giriniz', 'Kayıt Ekranı', function(value) {

                var email = value;
                var response = mobileRegister(email);

                if (response != "NOK") {
                    loadPageWithLang('main');
                }

            });
        });
    }

    if (page.name === 'main') {

    }

    if (page.name === 'language') {

        $$('.btnLangTr').on('click', function() {

            window.localStorage.setItem("langIsSelected", true);
            window.localStorage.setItem("lang", "tr");
            selectedLang = "tr";
            checkLoginStatus();
        });

        $$('.btnLangGer').on('click', function() {
            window.localStorage.setItem("langIsSelected", true);
            window.localStorage.setItem("lang", "de");
            selectedLang = "de";
            checkLoginStatus();
        });

    }

});

var calendarBirthday = myApp.calendar({
    input: '#calendarBirthday',
});

var postCodeSearch = myApp.autocomplete({
    input: '#autocomplete-dropdown-ajax',
    openIn: 'dropdown',
    preloader: true, //enable preloader
    valueProperty: 'id', //object's "value" property name
    textProperty: 'name', //object's "text" property name
    limit: 8, //limit to 8 results
    dropdownPlaceholderText: '35394 Giessen"',
    expandInput: true, // expand input
    source: function(autocomplete, query, render) {
        var results = [];
        if (query.length === 0) {
            render(results);
            return;
        }
        // Show Preloader
        autocomplete.showPreloader();
        // Do Ajax request to Autocomplete data
        $$.ajax({
            url: 'autocomplete-languages.json',
            method: 'GET',
            dataType: 'json',
            //send "query" to server. Useful in case you generate response dynamically
            data: {
                query: query
            },
            success: function(data) {
                // Find matched items
                for (var i = 0; i < data.length; i++) {
                    if (data[i].name.toLowerCase().indexOf(query.toLowerCase()) >= 0) results.push(data[i]);
                }
                // Hide Preoloader
                autocomplete.hidePreloader();
                // Render items by passing array with result items
                render(results);
            }
        });
    }
});<commit_msg>dsdfsdf<commit_after>Template7.registerHelper('placeholder', function(plchldrContent) {
    var ret = 'placeholder="' + plchldrContent + '"';
    return ret;
});

// Initialize app
var myApp = new Framework7({
    swipeBackPage: false,
    swipePanelOnlyClose: true,
    template7Pages: true
});

var $$ = Dom7;

var langIsSeleted = window.localStorage.getItem("langIsSelected");
var userLoggedIn = window.localStorage.getItem("isLogin");
var selectedLang;
var langData;

if (langIsSeleted) {
    selectedLang = window.localStorage.getItem("lang");
} else {
    selectedLang = "tr"; // Set turkish to default language
}

// Add view
var mainView = myApp.addView('.view-main', {

});

getLangJson();

setTimeout(function() {

    checkLangStatus();

}, 3000);

function checkLangStatus() {
    if (langIsSeleted) {
        checkLoginStatus();
    } else {
        mainView.router.loadPage({ url: 'language.html', ignoreCache: true });
    }
}

function changePanelLanguage() {

    myApp.alert(langData);
    var panelData = langData + '.' + selectedLang + '.panel';

    $$('#panelTitle').text(panelData.panelTitle);
    $$('#orderItem').text(panelData.orderItem);
    $$('#orderBoxItem').text(panelData.orderBoxItem);
    $$('#accountItem').text(panelData.accountItem);
    $$('#addressItem').text(panelData.addressItem);
    $$('#myOrdersItem').text(panelData.myOrdersItem);
    $$('#workItem').text(panelData.workItem);
    $$('#helpItem').text(panelData.helpItem);
    $$('#infoItem').text(panelData.infoItem);
    $$('#messageItem').text(panelData.messageItem);
    $$('#logoutItem').text(panelData.logoutItem);
}

function loadPageWithLang(pageName) {
    var cntxName = 'languages.' + selectedLang + '.' + pageName;
    var pgUrl = pageName + '.html';

    mainView.router.load({
        url: pgUrl,
        contextName: cntxName
    });
}

function checkLoginStatus() {

    try {
        if (userLoggedIn) {
            loadPageWithLang('main');

        } else {
            loadPageWithLang('login');
        }
    } catch (e) {
        myApp.alert(e);
    }

}

function getLangJson() {
    $$.getJSON('./languages/lang.json', function(data) {
        myApp.template7Data.languages = data.languages;
        langData = JSON.stringify(data.languages);
        changePanelLanguage();
    });
}

// Handle Cordova Device Ready Event
$$(document).on('deviceready', function() {
    console.log("Device is ready!");
});

// Option 2. Using one 'pageInit' event handler for all pages:
$$(document).on('pageInit', function(e) {
    // Get page data from event data
    var page = e.detail.page;

    if (page.name === 'login') {
        // Following code will be executed for page with data-page attribute equal to "about"
        //myApp.alert('Here comes login page');
        $$('.btnLogin').on('click', function() {
            var email = $$('#txtEmail').val();
            var pass = $$('#txtPassword').val();
            var response = mobileLogin(email, pass);

            if (response != 'NOK') {
                loadPageWithLang('main');
                window.localStorage.setItem("isLogin", true);
            } else {
                window.localStorage.setItem("isLogin", false);

            }

        });

        $$('.btnForgetPassword').on('click', function() {
            myApp.alert('Unuttum bişeyleri');
        });

        $$('.btnRegister').on('click', function() {
            myApp.prompt('Lütfen E-mail Adresini Giriniz', 'Kayıt Ekranı', function(value) {

                var email = value;
                var response = mobileRegister(email);

                if (response != "NOK") {
                    loadPageWithLang('main');
                }

            });
        });
    }

    if (page.name === 'main') {

    }

    if (page.name === 'language') {

        $$('.btnLangTr').on('click', function() {

            window.localStorage.setItem("langIsSelected", true);
            window.localStorage.setItem("lang", "tr");
            selectedLang = "tr";
            checkLoginStatus();
        });

        $$('.btnLangGer').on('click', function() {
            window.localStorage.setItem("langIsSelected", true);
            window.localStorage.setItem("lang", "de");
            selectedLang = "de";
            checkLoginStatus();
        });

    }

});

var calendarBirthday = myApp.calendar({
    input: '#calendarBirthday',
});

var postCodeSearch = myApp.autocomplete({
    input: '#autocomplete-dropdown-ajax',
    openIn: 'dropdown',
    preloader: true, //enable preloader
    valueProperty: 'id', //object's "value" property name
    textProperty: 'name', //object's "text" property name
    limit: 8, //limit to 8 results
    dropdownPlaceholderText: '35394 Giessen"',
    expandInput: true, // expand input
    source: function(autocomplete, query, render) {
        var results = [];
        if (query.length === 0) {
            render(results);
            return;
        }
        // Show Preloader
        autocomplete.showPreloader();
        // Do Ajax request to Autocomplete data
        $$.ajax({
            url: 'autocomplete-languages.json',
            method: 'GET',
            dataType: 'json',
            //send "query" to server. Useful in case you generate response dynamically
            data: {
                query: query
            },
            success: function(data) {
                // Find matched items
                for (var i = 0; i < data.length; i++) {
                    if (data[i].name.toLowerCase().indexOf(query.toLowerCase()) >= 0) results.push(data[i]);
                }
                // Hide Preoloader
                autocomplete.hidePreloader();
                // Render items by passing array with result items
                render(results);
            }
        });
    }
});<|endoftext|>


<commit_before>//  Basketball Digital Board script.js file
//  A project by LIA - Advanced Interaction Laboratory
//  Authors:    Yago Arroyo Gonçalves
//              George Pagliuso

// Function:    init
// Objective:   Initialize SVG Canvas with court's div
// Parameters:  none
// Return:      none
function init() {
    svgCanvas = new SvgCanvas(document.getElementById("court"));

    //  The piece of code below will get touches to behave like
    //  mouse clicks.
    //  Code originally from:
    //  http://stackoverflow.com/questions/8058699/drag-drop-on-mobile-devices-using-some-code-that-translates-event-code-included

    $("#court").children().bind('touchstart touchmove touchend touchcancel', function(){
        var touches = event.changedTouches,    first = touches[0],    type = "";
        switch(event.type){
          case "touchstart": type = "mousedown";
        break;
          case "touchmove":  type="mousemove";
        break;
          case "touchend":   type="mouseup";
        break;
          default: return;
        }

        var simulatedEvent = document.createEvent("MouseEvent");
        simulatedEvent.initMouseEvent(type, true, true, window, 1,
                          first.screenX, first.screenY,
                          first.clientX, first.clientY, false,
                          false, false, false, 0/*left*/, null);
        first.target.dispatchEvent(simulatedEvent);
        event.preventDefault();
    });
}

// Function:    set_color
// Objective:   Change line type from solid to dashed
//              and vice-versa
// Parameters:  obj: object containing the selected color's button
// Return:      none

function set_color(obj) {
    // Reset classes to simple button
    if ($("#blue").hasClass("active"))
        $("#blue").removeClass("active");
    else if ($("#red").hasClass("active"))
        $("#red").removeClass("active");
    else if ($("#green").hasClass("active"))
        $("#green").removeClass("active");
    else if ($("#eraser").hasClass("active")) {
        $("#eraser").removeClass("active");
        ctx.lineWidth = 3;
        ctx.globalCompositeOperation = 'source-over';
    }

    // Make clicked active
    $("#"+obj.id).addClass("active");

    // Select line color
    if (obj.id == 'eraser') {
        ctx.globalCompositeOperation = 'destination-out';
        ctx.lineWidth = 30;
    } else
        ctx.strokeStyle = obj.id;
}

// Function:    line_type
// Objective:   Change line type from solid to dashed
//              and vice-versa
// Parameters:  obj: object containing the line type's button
// Return:      none

function line_type(obj) {
    // Reset classes to simple button
    if ($("#solid").hasClass("active"))
        $("#solid").removeClass("active");
    else if ($("#dashed").hasClass("active"))
        $("#dashed").removeClass("active");

    // Make clicked active
    $("#"+obj.id).addClass("active");

    // Select line type
    switch (obj.id) {
        case "solid":
            ctx.setLineDash([0]);
            break;
        case "dashed":
            ctx.setLineDash([25,15]);
            break;
    }
}

// Function:    clear
// Objective:   Clear current content from court
// Parameters:  none
// Return:      none

function erase() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
}

// Function:    save
// Objective:   save canvas to file (?)
// Parameters:  none
// Return:      none

function save() {
    svgCanvas.save();
}

// Function:    show_info
// Objective:   toggle info balloons on/off
// Parameters:  btn: object containing info button
// Return:      none

function show_info(btn) {
    // Toggle button on/off
    if ($("#"+btn.id).hasClass("active")) {
        $("#"+btn.id).attr("class", "button");
        $("#info-balloons").hide();
    } else {
        $("#"+btn.id).attr("class", "button active");
        $("#info-balloons").show();
    }
}<commit_msg>Removed SVG Canvas leftovers<commit_after>//  Basketball Digital Board script.js file
//  A project by LIA - Advanced Interaction Laboratory
//  Authors:    Yago Arroyo Gonçalves
//              George Pagliuso

// Function:    init
// Objective:   Initialize SVG Canvas with court's div
// Parameters:  none
// Return:      none
function init() {
    //  The piece of code below will get touches to behave like
    //  mouse clicks.
    //  Code originally from:
    //  http://stackoverflow.com/questions/8058699/drag-drop-on-mobile-devices-using-some-code-that-translates-event-code-included

    $("#court").children().bind('touchstart touchmove touchend touchcancel', function(){
        var touches = event.changedTouches,    first = touches[0],    type = "";
        switch(event.type){
          case "touchstart": type = "mousedown";
        break;
          case "touchmove":  type="mousemove";
        break;
          case "touchend":   type="mouseup";
        break;
          default: return;
        }

        var simulatedEvent = document.createEvent("MouseEvent");
        simulatedEvent.initMouseEvent(type, true, true, window, 1,
                          first.screenX, first.screenY,
                          first.clientX, first.clientY, false,
                          false, false, false, 0/*left*/, null);
        first.target.dispatchEvent(simulatedEvent);
        event.preventDefault();
    });
}

// Function:    set_color
// Objective:   Change line type from solid to dashed
//              and vice-versa
// Parameters:  obj: object containing the selected color's button
// Return:      none

function set_color(obj) {
    // Reset classes to simple button
    if ($("#blue").hasClass("active"))
        $("#blue").removeClass("active");
    else if ($("#red").hasClass("active"))
        $("#red").removeClass("active");
    else if ($("#green").hasClass("active"))
        $("#green").removeClass("active");
    else if ($("#eraser").hasClass("active")) {
        $("#eraser").removeClass("active");
        ctx.lineWidth = 3;
        ctx.globalCompositeOperation = 'source-over';
    }

    // Make clicked active
    $("#"+obj.id).addClass("active");

    // Select line color
    if (obj.id == 'eraser') {
        ctx.globalCompositeOperation = 'destination-out';
        ctx.lineWidth = 30;
    } else
        ctx.strokeStyle = obj.id;
}

// Function:    line_type
// Objective:   Change line type from solid to dashed
//              and vice-versa
// Parameters:  obj: object containing the line type's button
// Return:      none

function line_type(obj) {
    // Reset classes to simple button
    if ($("#solid").hasClass("active"))
        $("#solid").removeClass("active");
    else if ($("#dashed").hasClass("active"))
        $("#dashed").removeClass("active");

    // Make clicked active
    $("#"+obj.id).addClass("active");

    // Select line type
    switch (obj.id) {
        case "solid":
            ctx.setLineDash([0]);
            break;
        case "dashed":
            ctx.setLineDash([25,15]);
            break;
    }
}

// Function:    clear
// Objective:   Clear current content from court
// Parameters:  none
// Return:      none

function erase() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
}

// Function:    save
// Objective:   save canvas to file (?)
// Parameters:  none
// Return:      none

function save() {
    svgCanvas.save();
}

// Function:    show_info
// Objective:   toggle info balloons on/off
// Parameters:  btn: object containing info button
// Return:      none

function show_info(btn) {
    // Toggle button on/off
    if ($("#"+btn.id).hasClass("active")) {
        $("#"+btn.id).attr("class", "button");
        $("#info-balloons").hide();
    } else {
        $("#"+btn.id).attr("class", "button active");
        $("#info-balloons").show();
    }
}<|endoftext|>


<commit_before>define([
    '/json/api.js',
    '/common/crypto.js',
    '/common/cryptpad-common.js',
    //'/customize/pad.js'
], function (RtListMap, Crypto, Common) {
    var $ = window.jQuery;

    var secret = Common.getSecrets();

    var config = {
        channel: secret.channel,
        cryptKey: secret.key,
        data: {},
    };

    var module = window.APP = {};

    var $repl = $('[name="repl"]');

    var setEditable = module.setEditable = function (bool) {
        [$repl].forEach(function ($el) {
            $el.attr('disabled', !bool);
        });
    };

    var initializing = true;

    // TODO replace with `proxy.on('init'` ?
    // or just remove?
    var onInit = config.onInit = function (info) {
        console.log("initializing!");
        window.location.hash = info.channel + secret.key;
    };

    // TODO replace with `proxy.on('ready'` ?
    var onReady = config.onReady = function (info) {
        setEditable(true);
    };

    setEditable(false);

    // TODO replace with `proxy.on('disconnect'` ?
    var onAbort = config.onAbort = function (info) {
        setEditable(false);
        window.alert("Network connection lost");
    };

    var rt = module.rt = RtListMap.create(config);

    // set up user interface hooks
    $repl.on('keyup', function (e) {
        if (e.which === 13) {
            var value = $repl.val();

            if (!value.trim()) { return; }

            console.log("evaluating `%s`", value);
            var x = rt.proxy;

            console.log('> ', eval(value)); // jshint ignore:line
            console.log();
            $repl.val('');
        }
    });
});
<commit_msg>add sample listeners for debugging<commit_after>define([
    '/json/api.js',
    '/common/crypto.js',
    '/common/cryptpad-common.js',
    //'/customize/pad.js'
], function (RtListMap, Crypto, Common) {
    var $ = window.jQuery;

    var secret = Common.getSecrets();

    var config = {
        channel: secret.channel,
        cryptKey: secret.key,
        data: {},
    };

    var module = window.APP = {};

    var $repl = $('[name="repl"]');

    var setEditable = module.setEditable = function (bool) {
        [$repl].forEach(function ($el) {
            $el.attr('disabled', !bool);
        });
    };

    var initializing = true;

    // TODO replace with `proxy.on('init'` ?
    // or just remove?
    var onInit = config.onInit = function (info) {
        console.log("initializing!");
        window.location.hash = info.channel + secret.key;
    };

    // TODO replace with `proxy.on('ready'` ?
    var onReady = config.onReady = function (info) {
        setEditable(true);
    };

    setEditable(false);

    // TODO replace with `proxy.on('disconnect'` ?
    var onAbort = config.onAbort = function (info) {
        setEditable(false);
        window.alert("Network connection lost");
    };

    var rt = module.rt = RtListMap.create(config);

    // set up user interface hooks
    $repl.on('keyup', function (e) {
        if (e.which === 13) {
            var value = $repl.val();

            if (!value.trim()) { return; }

            console.log("evaluating `%s`", value);
            var x = rt.proxy;

            console.log('> ', eval(value)); // jshint ignore:line
            console.log();
            $repl.val('');
        }
    });

    // debugging TODO remove
    //rt.proxy.on('change', 'u', (o, n) => console.log("'u' changed!", o,n));
    //rt.proxy.on('change', ['u', 2], (o, n) => (console.log("'u[2]' changed!", o, n), true));
});
<|endoftext|>


<commit_before>$(document).ready(function() {

  BVB.init();

  $(document).on("click", "#menu a", function() {
    href = $(this).attr("href");
    window.location.hash = href;
  });

  $(document).on("click", ".fav-star", function() {
    var recipe_id = $(this).data("recipe-id");
    var fav_span = BVB.getFavSpan(recipe_id);
    $("span[data-recipe-id=" + recipe_id + "]").replaceWith(fav_span);
  });

  $(document).on("click", "#close_menu_cross", function(){
    var api = $("#menu").data( "mmenu" );
    api.close();
  });

  $(document).on("click", "#send_contact_form", function(e){
    var attributes_arr = _($("#contact_form").serializeArray())
    var value_arr = attributes_arr.pluck("value");
    if (_(value_arr).includes("")){
      alert("Por favor, rellena todos los campos.");
      return false;
    }
    e.preventDefault();

    $.ajaxSetup({
       beforeSend: function(xhr) {
           xhr.setRequestHeader('Access-Control-Allow-Headers', 'Access-Control-Allow-Origin');
           xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
       }
    });

    $.ajax({
       type: 'GET',
       url: 'endpoint',
       data: {
               name: _(attributes_arr).find({name: "name"}).value,
               from: _(attributes_arr).find({name: "email"}).value,
               comment: _(attributes_arr).find({name: "comment"}).value,
             },
    })
    .always(function(){
      $("input[type=text], textarea").val("");
      alert("¡Tu mensaje ha sido enviado, gracias!");
    });
  });

});
<commit_msg>Add password to send email call in ready.js<commit_after>$(document).ready(function() {

  BVB.init();

  $(document).on("click", "#menu a", function() {
    href = $(this).attr("href");
    window.location.hash = href;
  });

  $(document).on("click", ".fav-star", function() {
    var recipe_id = $(this).data("recipe-id");
    var fav_span = BVB.getFavSpan(recipe_id);
    $("span[data-recipe-id=" + recipe_id + "]").replaceWith(fav_span);
  });

  $(document).on("click", "#close_menu_cross", function(){
    var api = $("#menu").data( "mmenu" );
    api.close();
  });

  $(document).on("click", "#send_contact_form", function(e){
    var attributes_arr = _($("#contact_form").serializeArray())
    var value_arr = attributes_arr.pluck("value");
    if (_(value_arr).includes("")){
      alert("Por favor, rellena todos los campos.");
      return false;
    }
    e.preventDefault();

    $.ajaxSetup({
       beforeSend: function(xhr) {
           xhr.setRequestHeader('Access-Control-Allow-Headers', 'Access-Control-Allow-Origin');
           xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
       }
    });

    $.ajax({
       type: 'GET',
       url: Settings.send_email_endpoint,
       data: {
               bvb: btoa(Settings.send_email_password + _(attributes_arr).find({name: "email"}).value),
               name: _(attributes_arr).find({name: "name"}).value,
               from: _(attributes_arr).find({name: "email"}).value,
               comment: _(attributes_arr).find({name: "comment"}).value,
             },
    })
    .always(function(){
      $("input[type=text], textarea").val("");
      alert("¡Tu mensaje ha sido enviado, gracias!");
    });
  });

});
<|endoftext|>