<commit_before>var system;

function setup(){
  createCanvas(windowWidth, windowHeight);

  system = new SolarSystem();
}

function draw(){
  background(25);
  system.draw();
  system.tick();
}

class Physics {

  // G: 6.67408 × 10-11 m3 kg-1 s-2
  static get G_CONTSTANT(){ return 6.67408e-11; }

  // points from Obj1 => Obj2
  static forceDueToG(obj1, obj2){
    let r = p5.Vector.sub(obj2.pos, obj1.pos);
    let rSquared = r.magSq();
    let forceMag = Physics.G_CONTSTANT * obj1.mass * obj2.mass / rSquared;
    let force = r.setMag(forceMag);
    return force;
  }

  static orbitalV(ofObject, aroundObj){
    let r = p5.Vector.sub(aroundObj.pos, ofObject.pos);
    let speed = pow(Physics.G_CONTSTANT * aroundObj.mass / r.mag() , 0.5);
    let v = r.copy();
    v.rotate(HALF_PI);
    v.setMag(speed);
    return v;
  }
}

class SolarSystem {
  constructor() {
    this.objects = [];
    this.init();
  }

  static get scale_space(){ return 4.5e9 / width; }
  static get scale_time(){ return 1; }

  init(){
    let numObjects = 10;
    for(var i=0; i<numObjects; i++){

      if(i == 0){
        this.objects.push(this.generateStar());
      }else{
        this.objects.push(this.generatePlanet());
      }
    }
    this.setInitialOrbitalVelocities();
  }

  generateStar(idx){
    return new MassiveObject(0, 0, 1.9885e30, color(200,190,40));
  }

  generatePlanet(idx){
    // our solar system is 4.5e9 km along major axis;
    // mecury, perihelion: 46,001,200 km
    let randLoc = createVector(random(40, 2500) * 1e6, random(40, 2500) * 1e6);
    let randTheta = random(0, TWO_PI);
    randLoc.rotate(randTheta);

    // jupiter: 1.8982×1027 or 18,982x1023
    // mercury   3.3011×1023
    let mass = random(3, 10000) * 1e23;

    let surfaceColor = color(random(50, 200),random(50, 200),random(50, 200));
    return new MassiveObject(randLoc.x, randLoc.y, mass, surfaceColor);
  }

  setInitialOrbitalVelocities(){
    let star = this.objects[0];
    for(var i=1; i < this.objects.length; i++){
      let obj = this.objects[i];
      obj.velocity = Physics.orbitalV(obj, star);
    }
  }

  tick(){
    // for now, for simplicity
    //  ... keep the star fixed (don't apply any forces to it)
    let star = this.objects[0];
    for(var i=1; i < this.objects.length; i++){
      let obj = this.objects[i];
      let force = Physics.forceDueToG(obj, star);
      obj.accel = force.copy().div(obj.mass);
    }

    for(var i=1; i < this.objects.length; i++){
      this.objects[i].tick();
    }
  }

  draw(){
    push();
    translate(width/2, height/2);
    noStroke();
    for(var i=0; i < this.objects.length; i++){
      this.objects[i].draw();
    }
    pop();
  }
}

class MassiveObject {
  constructor(x, y, mass, color) {
    this.pos = createVector(x, y);
    this.accel = createVector(0, 0);
    this.velocity = createVector(0, 0);
    this.mass = mass; // kg
    this.c = color;

    this.scaledRadius = Math.log10(this.mass);
  }

  get x(){ return this.pos.x; }
  get y(){ return this.pos.y; }

  tick(){
    this.pos.add(this.velocity.mult(SolarSystem.scale_time));
    this.velocity.add(this.accel.mult(SolarSystem.scale_time));
  }

  draw(){
    fill(this.c);
    ellipse(this.x / SolarSystem.scale_space, this.y / SolarSystem.scale_space,
                this.scaledRadius, this.scaledRadius);
  }
}<commit_msg>p5js/solar-system - Fix time scale<commit_after>var system;

function setup(){
  createCanvas(windowWidth, windowHeight);

  system = new SolarSystem();
}

function draw(){
  background(25);
  system.draw();
  system.tick();
}

class Physics {

  // G: 6.67408 × 10-11 m3 kg-1 s-2
  static get G_CONTSTANT(){ return 6.67408e-11; }
  static get G_ADJUSTED(){ return SolarSystem.scale_time * Physics.G_CONTSTANT; }

  // points from Obj1 => Obj2
  static forceDueToG(obj1, obj2){
    let r = p5.Vector.sub(obj2.pos, obj1.pos);
    let rSquared = r.magSq();
    let forceMag = Physics.G_ADJUSTED * obj1.mass * obj2.mass / rSquared;
    let force = r.setMag(forceMag);
    return force;
  }

  static orbitalV(ofObject, aroundObj){
    let r = p5.Vector.sub(aroundObj.pos, ofObject.pos);
    let speed = pow(Physics.G_ADJUSTED * aroundObj.mass / r.mag() , 0.5);
    let v = r.copy();
    v.rotate(HALF_PI);
    v.setMag(speed);
    return v;
  }
}

class SolarSystem {
  constructor() {
    this.objects = [];
    this.init();
  }

  static get scale_space(){ return 4.5e9 / width; }
  static get scale_time(){ return 50.0; }

  init(){
    let numObjects = 10;
    for(var i=0; i<numObjects; i++){

      if(i == 0){
        this.objects.push(this.generateStar());
      }else{
        this.objects.push(this.generatePlanet());
      }
    }
    this.setInitialOrbitalVelocities();
  }

  generateStar(idx){
    return new MassiveObject(0, 0, 1.9885e30, color(200,190,40));
  }

  generatePlanet(idx){
    // our solar system is 4.5e9 km along major axis;
    // mecury, perihelion: 46,001,200 km
    let randLoc = createVector(random(40, 2500) * 1e6, random(40, 2500) * 1e6);
    let randTheta = random(0, TWO_PI);
    randLoc.rotate(randTheta);

    // jupiter: 1.8982×1027 or 18,982x1023
    // mercury   3.3011×1023
    let mass = random(3, 10000) * 1e23;

    let surfaceColor = color(random(50, 200),random(50, 200),random(50, 200));
    return new MassiveObject(randLoc.x, randLoc.y, mass, surfaceColor);
  }

  setInitialOrbitalVelocities(){
    let star = this.objects[0];
    for(var i=1; i < this.objects.length; i++){
      let obj = this.objects[i];
      obj.velocity = Physics.orbitalV(obj, star);
    }
  }

  tick(){
    // for now, for simplicity
    //  ... keep the star fixed (don't apply any forces to it)
    let star = this.objects[0];
    for(var i=1; i < this.objects.length; i++){
      let obj = this.objects[i];
      let force = Physics.forceDueToG(obj, star);
      obj.accel = force.copy().div(obj.mass);
    }

    for(var i=1; i < this.objects.length; i++){
      this.objects[i].tick();
    }
  }

  draw(){
    push();
    translate(width/2, height/2);
    noStroke();
    for(var i=0; i < this.objects.length; i++){
      this.objects[i].draw();
    }
    pop();
  }
}

class MassiveObject {
  constructor(x, y, mass, color) {
    this.pos = createVector(x, y);
    this.accel = createVector(0, 0);
    this.velocity = createVector(0, 0);
    this.mass = mass; // kg
    this.c = color;

    this.scaledRadius = Math.log10(this.mass);
  }

  get x(){ return this.pos.x; }
  get y(){ return this.pos.y; }

  tick(){
    this.pos.add(this.velocity);
    this.velocity.add(this.accel);
  }

  draw(){
    fill(this.c);
    ellipse(this.x / SolarSystem.scale_space, this.y / SolarSystem.scale_space,
                this.scaledRadius, this.scaledRadius);
  }
}<|endoftext|>


<commit_before>const moment = require('moment-timezone')
const twitchAPI = require('./twitchAPI')
const Archive = require('./mongo').ArchivedVideoLengths
const _ = require('lodash')

async function update() {
  const { body } = await twitchAPI.getArchivesKraken()
  const { videos } = body
  const operations = []
  videos.forEach((video) => {
    operations.push({
      updateOne: {
        filter: { videoId: video.broadcast_id },
        update: {
          videoId: video.broadcast_id,
          createdAt: video.created_at,
          length: video.length,
        },
        upsert: true,
      },
    })
  })
  await Archive.bulkWrite(operations)
}

async function getHoursThisQuarter() {
  const startOfQuarter = moment.tz('America/Los_Angeles').startOf('quarter')
  const endOfQuarter = moment.tz('America/Los_Angeles').endOf('quarter')
  const videosThisQuarter = await Archive.find({
    createdAt: { $gte: startOfQuarter, $lte: endOfQuarter },
  })
  const sum = videosThisQuarter.reduce((prev, next) => {
    return prev + next.length
  }, 0)
  const duration = moment.duration(sum, 'seconds')
  return Math.round(duration.asHours())
}

module.exports = () => {
  // Process videos every 20 minutes
  update().catch()
  setInterval(update, 1000 * 60 * 20)
  return {
    getHoursThisQuarter,
  }
}
<commit_msg>don't do bulk write with no operations<commit_after>const moment = require('moment-timezone')
const twitchAPI = require('./twitchAPI')
const Archive = require('./mongo').ArchivedVideoLengths
const _ = require('lodash')

async function update() {
  const { body } = await twitchAPI.getArchivesKraken()
  const { videos } = body
  const operations = []
  videos.forEach((video) => {
    operations.push({
      updateOne: {
        filter: { videoId: video.broadcast_id },
        update: {
          videoId: video.broadcast_id,
          createdAt: video.created_at,
          length: video.length,
        },
        upsert: true,
      },
    })
  })
  if (operations.length === 0) return
  await Archive.bulkWrite(operations)
}

async function getHoursThisQuarter() {
  const startOfQuarter = moment.tz('America/Los_Angeles').startOf('quarter')
  const endOfQuarter = moment.tz('America/Los_Angeles').endOf('quarter')
  const videosThisQuarter = await Archive.find({
    createdAt: { $gte: startOfQuarter, $lte: endOfQuarter },
  })
  const sum = videosThisQuarter.reduce((prev, next) => {
    return prev + next.length
  }, 0)
  const duration = moment.duration(sum, 'seconds')
  return Math.round(duration.asHours())
}

module.exports = () => {
  // Process videos every 20 minutes
  update().catch()
  setInterval(update, 1000 * 60 * 20)
  return {
    getHoursThisQuarter,
  }
}
<|endoftext|>


<commit_before>#!/usr/bin/env node

'use strict';

var program, path, fs, mkdirp, pkg, chalk;

program = require('commander');
fs      = require('fs');
mkdirp  = require('mkdirp');
path    = require('path');
chalk   = require('chalk');
pkg     = require('../package.json');

/**
File/Directory helper functions
*/
function write(path, str, mode) {
  fs.writeFile(path, str, { mode: mode || '0666' });
  console.log('    ' + chalk.green('create') + ': ' + path);
}

function copy(from, to) {
  write(to, fs.readFileSync(from, 'utf-8'));
}

function mkdir(path, fn) {
  mkdirp(path, '0755', function(err){
    if (err) {
      throw err;
    }
    console.log('    ' + chalk.green('create') + ' : ' + path);
    if (typeof fn === 'function'){
      fn();
    }
  });
}

function emptyDirectory(path, fn) {
  fs.readdir(path, function(err, files){
    if (err && 'ENOENT' !== err.code) {
      throw err;
    }
    fn(!files || !files.length);
  });
}

function createApplicationAt(dir){
  var appName, newPkg;

  // Determine the app name from the directory
  appName = path.basename(path.resolve(dir));

  console.log('\n' + chalk.cyan('Creating new ') + chalk.cyan.bold('image-resizer') + chalk.cyan(' app!'));
  console.log();

  process.on('exit', function(){
    console.log();
    console.log(chalk.green('   now install your dependencies') + ':');
    console.log('     $ npm install');
    console.log();
    console.log(chalk.green('   then run the app') + ':');
    console.log('     $ gulp watch');
    console.log();
  });

  // create a new package.json
  newPkg = {
    name: appName,
    version: '0.0.1',
    main: 'index.js',
    engines: {
      'node': pkg.engines.node
    },
    dependencies: {
      'image-resizer': '~' + pkg.version,
      'express': pkg.dependencies.express,
      'lodash': pkg.dependencies.lodash
    },
    devDependencies: pkg.devDependencies
  };

  write(dir + '/package.json', JSON.stringify(newPkg, null, 2));

  // create index.js
  copy(__dirname + '/./templates/index.js.tmpl', dir + '/index.js');

  // create the gulpfile
  copy(__dirname + '/./templates/gulpfile.js.tmpl', dir + '/gulpfile.js');

  // create .env
  copy(__dirname + '/./templates/.env.tmpl', dir + '/.env');

  // create .gitignore
  copy(__dirname + '/./templates/.gitignore.tmpl', dir + '/.gitignore');

  // create .jshintrc
  copy(__dirname + '/../.jshintrc', dir + '/.jshintrc');

  // create Heroku files
  //  - Procfile
  //  - .buildpacks
  write (dir + '/Procfile', 'web: node index.js');
  copy(__dirname + '/../.buildpacks', dir + '/.buildpacks');

  // create plugin folders
  //  - sources
  //  - filters
  mkdir(dir + '/plugins/sources');
  mkdir(dir + '/plugins/filters');
}

/**
Create the program and list the possible commands
*/
program.version(pkg.version);
program.option('-f, --force', 'force app build in an non-empty directory');
program.command('new')
  .description('Create new clean image-resizer app')
  .action(function(){
    var path = '.';
    emptyDirectory(path, function(empty){
      if (empty || program.force){
        createApplicationAt(path);
      } else {
        console.log(
          chalk.red('\n    The current directory is not empty, please use the force (-f) option to proceed.\n')
        );
      }
    });
  });
program.command('filter <name>')
  .description('Create new filter stream')
  .action(function(filterName){
    copy(__dirname + '/./templates/filter.js.tmpl', './plugins/filters/' + filterName + '.js');
  });
program.parse(process.argv);
<commit_msg>Moved Procfile and buildpacks to bin<commit_after>#!/usr/bin/env node

'use strict';

var program, path, fs, mkdirp, pkg, chalk;

program = require('commander');
fs      = require('fs');
mkdirp  = require('mkdirp');
path    = require('path');
chalk   = require('chalk');
pkg     = require('../package.json');

/**
File/Directory helper functions
*/
function write(path, str, mode) {
  fs.writeFile(path, str, { mode: mode || '0666' });
  console.log('    ' + chalk.green('create') + ': ' + path);
}

function copy(from, to) {
  write(to, fs.readFileSync(from, 'utf-8'));
}

function mkdir(path, fn) {
  mkdirp(path, '0755', function(err){
    if (err) {
      throw err;
    }
    console.log('    ' + chalk.green('create') + ' : ' + path);
    if (typeof fn === 'function'){
      fn();
    }
  });
}

function emptyDirectory(path, fn) {
  fs.readdir(path, function(err, files){
    if (err && 'ENOENT' !== err.code) {
      throw err;
    }
    fn(!files || !files.length);
  });
}

function createApplicationAt(dir){
  var appName, newPkg;

  // Determine the app name from the directory
  appName = path.basename(path.resolve(dir));

  console.log('\n' + chalk.cyan('Creating new ') + chalk.cyan.bold('image-resizer') + chalk.cyan(' app!'));
  console.log();

  process.on('exit', function(){
    console.log();
    console.log(chalk.green('   now install your dependencies') + ':');
    console.log('     $ npm install');
    console.log();
    console.log(chalk.green('   then run the app') + ':');
    console.log('     $ gulp watch');
    console.log();
  });

  // create a new package.json
  newPkg = {
    name: appName,
    version: '0.0.1',
    main: 'index.js',
    engines: {
      'node': pkg.engines.node
    },
    dependencies: {
      'image-resizer': '~' + pkg.version,
      'express': pkg.dependencies.express,
      'lodash': pkg.dependencies.lodash
    },
    devDependencies: pkg.devDependencies
  };

  write(dir + '/package.json', JSON.stringify(newPkg, null, 2));

  // create index.js
  copy(__dirname + '/./templates/index.js.tmpl', dir + '/index.js');

  // create the gulpfile
  copy(__dirname + '/./templates/gulpfile.js.tmpl', dir + '/gulpfile.js');

  // create .env
  copy(__dirname + '/./templates/.env.tmpl', dir + '/.env');

  // create .gitignore
  copy(__dirname + '/./templates/.gitignore.tmpl', dir + '/.gitignore');

  // create .jshintrc
  copy(__dirname + '/../.jshintrc', dir + '/.jshintrc');

  // create Heroku files
  copy(__dirname + '/./templates/.buildpacks.tmpl', dir + '/.buildpacks');
  copy(__dirname + '/./templates/Procfile.tmpl', dir + '/Procfile');

  // create plugin folders
  //  - sources
  //  - filters
  mkdir(dir + '/plugins/sources');
  mkdir(dir + '/plugins/filters');
}

/**
Create the program and list the possible commands
*/
program.version(pkg.version);
program.option('-f, --force', 'force app build in an non-empty directory');
program.command('new')
  .description('Create new clean image-resizer app')
  .action(function(){
    var path = '.';
    emptyDirectory(path, function(empty){
      if (empty || program.force){
        createApplicationAt(path);
      } else {
        console.log(
          chalk.red('\n    The current directory is not empty, please use the force (-f) option to proceed.\n')
        );
      }
    });
  });
program.command('filter <name>')
  .description('Create new filter stream')
  .action(function(filterName){
    copy(__dirname + '/./templates/filter.js.tmpl', './plugins/filters/' + filterName + '.js');
  });
program.parse(process.argv);
<|endoftext|>


<commit_before>;(function(win,doc,head,body){

  if(!('addEventListener' in win)) return;

  var wdth = (win.innerWidth || doc.documentElement.clientWidth || doc.body.clientWidth);
  var hght = (win.innerHeight || doc.documentElement.clientHeight || doc.body.clientHeight);
  var head = (doc.head || doc.getElementsByTagName('head')[0]);
  var prev_st = (win.scrollY || win.pageYOffset);
  var animating = false;
  var bg_inners = doc.querySelectorAll('.bg-inner');
  var nav_links = doc.querySelectorAll('nav>a');
  var i = nav_links.length;
  var j = 0;

  if('devicePixelRatio' in win && win.devicePixelRatio > 1 && wdth < 992){
    for(var x = 0; x < bg_inners.length; ++x){
      bg_inners[x].style.height = hght + 'px';
    }
  }

  loadStylesheets(['https://amdouglas.com/assets/css/fonts.css']);

  for(;j<i;++j) nav_links[j].addEventListener('click',handleNav,false);
  win.addEventListener('load',handleLoad,false);
  win.addEventListener('scroll',rebouncedScrollHandler,false);
  win.addEventListener('keydown',keyNav,false);

  function loadStylesheets(urls){
    for(var i = 0;i<urls.length;++i){
      var css = doc.createElement('link');
      css.rel = 'stylesheet';
      css.href = urls[i];
      head.appendChild(css);
    }
  }

  function handleLoad(){
    win.removeEventListener('load',handleLoad,false);
    updateNavigation('#home');
    appendJSONLD();
    var a=doc.querySelectorAll('input,textarea');
    for(var j=0;j<a.length;++j){
      a[j].removeAttribute('disabled');
      a[j].addEventListener('blur',function(e){(e.target || this).className='_blur';});
    }
    doc.querySelector('.sms').href='\u0073\u006D\u0073\u003a\u002b\u0034\u0034\u0037\u0039\u0033\u0031\u0035\u0036\u0035\u0038\u0034\u0036';
    if('devicePixelRatio' in win && win.devicePixelRatio > 1 && wdth < 992){
      appendTouchIcons();
    }
    if('serviceWorker' in navigator){
      navigator.serviceWorker.register('https://amdouglas.com/sw.js', {
        scope: '/'
      }).then(function(registration){
        console.info("SW registered [" + registration.scope + "]");
      }).catch(function(err){
        console.warn("SW failed to register [" + err + "]");
      });
    }
    win.GoogleAnalyticsObject = win.ga;
    win.ga = win.ga || function(){
      for(var p = 0; p < arguments.length; ++p){
        (win.ga.q = win.ga.q || []).push(arguments[p]);
      }
    };
    win.ga.l = 1 * new Date();
    var uas = doc.createElement('script');
    uas.async=!0;
    uas.src='https://www.google-analytics.com/analytics.js';
    body.appendChild(uas);
    win.ga('create','UA-70873652-1','auto');
    win.ga('send','pageview');
  }

  function appendTouchIcons(){
    var xhr = new XMLHttpRequest();
    xhr.open('GET', 'https://amdouglas.com/manifest.json', true);
    xhr.onreadystatechange = function(){
      if(xhr.readyState === 4){
        if(xhr.status >= 200 && xhr.status < 300){
          var data = JSON.parse(xhr.responseText);
          for(var j=0;j<data.icons.length;++j){
            if(data.icons[j].src.indexOf('apple') > -1){
              var icon = doc.createElement('link');
              icon.rel = 'apple-touch-icon-precomposed';
              icon.href = data.icons[j].src;
              icon.setAttribute('sizes', data.icons[j].sizes);
              head.appendChild(icon);
            }
          }
        }
      }
    };
    xhr.send();
  }

  function appendJSONLD(){
    var s_data = doc.createElement('script');
    s_data.type = 'application/ld+json';
    var xhr = new XMLHttpRequest();
    xhr.open('GET', 'https://amdouglas.com/data.jsonld', true);
    xhr.onreadystatechange = function(){
      if(xhr.readyState === 4){
        if(xhr.status >= 200 && xhr.status < 300){
          s_data.textContent = xhr.responseText;
          body.appendChild(s_data);
        }
      }
    };
    xhr.send();
  }

  function rebounce(f){
    var scheduled, context, args, len, i;
    return function(){
      context = this; args = [];
      len = args.length = arguments.length; i = 0;
      for(;i < len; ++i) args[i] = arguments[i];
      win.cancelAnimationFrame(scheduled);
      scheduled = win.requestAnimationFrame(function(){
        f.apply(context,args); scheduled = null;
      });
    }
  }

  function scrollHandler(){
    var sections = doc.getElementsByTagName('section');
    var s = 5, t = 0;
    var cur_st = (win.scrollY || win.pageYOffset);
    var scroll_dir = cur_st < prev_st ? 'u' : 'd';
    prev_st = cur_st;
    for(; s > t; ++t){
      var this_section = sections[t];
      var this_hash = '#' + this_section.id;
      var this_rect = this_section.getBoundingClientRect();
      switch(scroll_dir){
        case 'u':
          if(this_rect.bottom<(hght/2)&&this_rect.bottom>=0) updateNavigation(this_hash,scroll_dir);
          break;
        case 'd':
          if(this_rect.top<(hght/3)&&this_rect.top>=0) updateNavigation(this_hash,scroll_dir);
          break;
      }
    }
  }

  function updateNavigation(this_hash,scroll_dir){
    if(!animating){
      if(win.location.hash!==this_hash&&'history'in win&&'replaceState'in win.history){
        win.history.replaceState(null,null,this_hash);
      }
      addActiveClass();
    }
  }

  function addActiveClass(){
    var a=doc.getElementsByTagName('a');
    for(var i=0;i<a.length;++i){
      var c=a[i].hash;
      win.location.hash===c?a[i].classList.add('active'):a[i].classList.remove('active');
    }
  }

  function rebouncedScrollHandler(){
    return rebounce(scrollHandler());
  }

  function getPos(_t,_st,_f,_sf){
    if(_sf>_t) return _f;
    var d=(_sf/_t);
    return _st + (_f - _st) * (d<.5?4*d*d*d:(d-1)*(2*d-2)*(2*d-2)+1);
  }

  function getTime(){
    return ('performance'in win)?win.performance.now():new Date().getTime();
  }

  function smoothScroll(el){
    var _t = 400,
        _st = win.scrollY||win.pageYOffset,
        _f = (el.tagName.toLowerCase()!=='html')?el.getBoundingClientRect().top+_st:-_st,
        _ct = getTime(),
        step = function(){
          var _sf = getTime()-_ct;
          win.scroll(0,getPos(_t,_st,_f,_sf));
          if(_sf>_t){
            if(win.location.hash!==('#'+el.id)){
              win.location.replace('#'+el.id);
            }
          win.requestAnimationFrame(function(){
            animating = false;
            addActiveClass();
          });
          }else{
            win.requestAnimationFrame(step);
          }
        }
    animating = true;
    step();
  }

  function keyNav(e){
    if(!!animating || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey || e.defaultPrevented) return;
    var el = doc.getElementById(win.location.hash.substr(1));
    if(e.key){
      switch(e.key){
        case "ArrowDown":
          typeof e !== 'undefined' && e.preventDefault();
          if(el.nextElementSibling.tagName.toLowerCase()==='section')
            smoothScroll(el.nextElementSibling);
          break;
        case "ArrowUp":
          typeof e !== 'undefined' && e.preventDefault();
          if(el.previousElementSibling.tagName.toLowerCase()==='section')
            smoothScroll(el.previousElementSibling);
          break;
        default:
          return;
      }
    } else if(e.which){
      switch(e.which){
        case 40:
          typeof e !== 'undefined' && e.preventDefault();
          if(el.nextElementSibling.tagName.toLowerCase()==='section')
            smoothScroll(el.nextElementSibling);
          break;
        case 38:
          typeof e !== 'undefined' && e.preventDefault();
          if(el.previousElementSibling.tagName.toLowerCase()==='section')
            smoothScroll(el.previousElementSibling);
          break;
        default:
          return;
      }
    }
  }

  function handleNav(e){
    typeof e !== 'undefined' && e.preventDefault();
    var evt = (e.target || this),
        node = doc.getElementById(evt.hash.substring(1));
    if(!node) return;
    smoothScroll(node);
  }

})(window,window.document,window.document.head,window.document.body);
<commit_msg>Update app.js<commit_after>;(function(win,doc,head,body){

  if(!('addEventListener' in win)) return;

  var wdth = (win.innerWidth || doc.documentElement.clientWidth || doc.body.clientWidth);
  var hght = (win.innerHeight || doc.documentElement.clientHeight || doc.body.clientHeight);
  var head = (doc.head || doc.getElementsByTagName('head')[0]);
  var prev_st = (win.scrollY || win.pageYOffset);
  var animating = false;
  var nav_links = doc.querySelectorAll('nav>a');
  var i = nav_links.length;
  var j = 0;

  loadStylesheets(['https://amdouglas.com/assets/css/fonts.css']);

  for(;j<i;++j) nav_links[j].addEventListener('click',handleNav,false);
  win.addEventListener('load',handleLoad,false);
  win.addEventListener('scroll',rebouncedScrollHandler,false);
  win.addEventListener('keydown',keyNav,false);

  function loadStylesheets(urls){
    for(var i = 0;i<urls.length;++i){
      var css = doc.createElement('link');
      css.rel = 'stylesheet';
      css.href = urls[i];
      head.appendChild(css);
    }
  }

  function handleLoad(){
    win.removeEventListener('load',handleLoad,false);
    updateNavigation('#home');
    appendJSONLD();
    var a=doc.querySelectorAll('input,textarea');
    for(var j=0;j<a.length;++j){
      a[j].removeAttribute('disabled');
      a[j].addEventListener('blur',function(e){(e.target || this).className='_blur';});
    }
    doc.querySelector('.sms').href='\u0073\u006D\u0073\u003a\u002b\u0034\u0034\u0037\u0039\u0033\u0031\u0035\u0036\u0035\u0038\u0034\u0036';
    if('devicePixelRatio' in win && win.devicePixelRatio > 1 && wdth < 992){
      appendTouchIcons();
    }
    if('serviceWorker' in navigator){
      navigator.serviceWorker.register('https://amdouglas.com/sw.js', {
        scope: '/'
      }).then(function(registration){
        console.info("SW registered [" + registration.scope + "]");
      }).catch(function(err){
        console.warn("SW failed to register [" + err + "]");
      });
    }
    win.GoogleAnalyticsObject = win.ga;
    win.ga = win.ga || function(){
      for(var p = 0; p < arguments.length; ++p){
        (win.ga.q = win.ga.q || []).push(arguments[p]);
      }
    };
    win.ga.l = 1 * new Date();
    var uas = doc.createElement('script');
    uas.async=!0;
    uas.src='https://www.google-analytics.com/analytics.js';
    body.appendChild(uas);
    win.ga('create','UA-70873652-1','auto');
    win.ga('send','pageview');
  }

  function appendTouchIcons(){
    var xhr = new XMLHttpRequest();
    xhr.open('GET', 'https://amdouglas.com/manifest.json', true);
    xhr.onreadystatechange = function(){
      if(xhr.readyState === 4){
        if(xhr.status >= 200 && xhr.status < 300){
          var data = JSON.parse(xhr.responseText);
          for(var j=0;j<data.icons.length;++j){
            if(data.icons[j].src.indexOf('apple') > -1){
              var icon = doc.createElement('link');
              icon.rel = 'apple-touch-icon-precomposed';
              icon.href = data.icons[j].src;
              icon.setAttribute('sizes', data.icons[j].sizes);
              head.appendChild(icon);
            }
          }
        }
      }
    };
    xhr.send();
  }

  function appendJSONLD(){
    var s_data = doc.createElement('script');
    s_data.type = 'application/ld+json';
    var xhr = new XMLHttpRequest();
    xhr.open('GET', 'https://amdouglas.com/data.jsonld', true);
    xhr.onreadystatechange = function(){
      if(xhr.readyState === 4){
        if(xhr.status >= 200 && xhr.status < 300){
          s_data.textContent = xhr.responseText;
          body.appendChild(s_data);
        }
      }
    };
    xhr.send();
  }

  function rebounce(f){
    var scheduled, context, args, len, i;
    return function(){
      context = this; args = [];
      len = args.length = arguments.length; i = 0;
      for(;i < len; ++i) args[i] = arguments[i];
      win.cancelAnimationFrame(scheduled);
      scheduled = win.requestAnimationFrame(function(){
        f.apply(context,args); scheduled = null;
      });
    }
  }

  function scrollHandler(){
    var sections = doc.getElementsByTagName('section');
    var s = 5, t = 0;
    var cur_st = (win.scrollY || win.pageYOffset);
    var scroll_dir = cur_st < prev_st ? 'u' : 'd';
    prev_st = cur_st;
    for(; s > t; ++t){
      var this_section = sections[t];
      var this_hash = '#' + this_section.id;
      var this_rect = this_section.getBoundingClientRect();
      switch(scroll_dir){
        case 'u':
          if(this_rect.bottom<(hght/2)&&this_rect.bottom>=0) updateNavigation(this_hash,scroll_dir);
          break;
        case 'd':
          if(this_rect.top<(hght/3)&&this_rect.top>=0) updateNavigation(this_hash,scroll_dir);
          break;
      }
    }
  }

  function updateNavigation(this_hash,scroll_dir){
    if(!animating){
      if(win.location.hash!==this_hash&&'history'in win&&'replaceState'in win.history){
        win.history.replaceState(null,null,this_hash);
      }
      addActiveClass();
    }
  }

  function addActiveClass(){
    var a=doc.getElementsByTagName('a');
    for(var i=0;i<a.length;++i){
      var c=a[i].hash;
      win.location.hash===c?a[i].classList.add('active'):a[i].classList.remove('active');
    }
  }

  function rebouncedScrollHandler(){
    return rebounce(scrollHandler());
  }

  function getPos(_t,_st,_f,_sf){
    if(_sf>_t) return _f;
    var d=(_sf/_t);
    return _st + (_f - _st) * (d<.5?4*d*d*d:(d-1)*(2*d-2)*(2*d-2)+1);
  }

  function getTime(){
    return ('performance'in win)?win.performance.now():new Date().getTime();
  }

  function smoothScroll(el){
    var _t = 400,
        _st = win.scrollY||win.pageYOffset,
        _f = (el.tagName.toLowerCase()!=='html')?el.getBoundingClientRect().top+_st:-_st,
        _ct = getTime(),
        step = function(){
          var _sf = getTime()-_ct;
          win.scroll(0,getPos(_t,_st,_f,_sf));
          if(_sf>_t){
            if(win.location.hash!==('#'+el.id)){
              win.location.replace('#'+el.id);
            }
          win.requestAnimationFrame(function(){
            animating = false;
            addActiveClass();
          });
          }else{
            win.requestAnimationFrame(step);
          }
        }
    animating = true;
    step();
  }

  function keyNav(e){
    if(!!animating || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey || e.defaultPrevented) return;
    var el = doc.getElementById(win.location.hash.substr(1));
    if(e.key){
      switch(e.key){
        case "ArrowDown":
          typeof e !== 'undefined' && e.preventDefault();
          if(el.nextElementSibling.tagName.toLowerCase()==='section')
            smoothScroll(el.nextElementSibling);
          break;
        case "ArrowUp":
          typeof e !== 'undefined' && e.preventDefault();
          if(el.previousElementSibling.tagName.toLowerCase()==='section')
            smoothScroll(el.previousElementSibling);
          break;
        default:
          return;
      }
    } else if(e.which){
      switch(e.which){
        case 40:
          typeof e !== 'undefined' && e.preventDefault();
          if(el.nextElementSibling.tagName.toLowerCase()==='section')
            smoothScroll(el.nextElementSibling);
          break;
        case 38:
          typeof e !== 'undefined' && e.preventDefault();
          if(el.previousElementSibling.tagName.toLowerCase()==='section')
            smoothScroll(el.previousElementSibling);
          break;
        default:
          return;
      }
    }
  }

  function handleNav(e){
    typeof e !== 'undefined' && e.preventDefault();
    var evt = (e.target || this),
        node = doc.getElementById(evt.hash.substring(1));
    if(!node) return;
    smoothScroll(node);
  }

})(window,window.document,window.document.head,window.document.body);
<|endoftext|>


<commit_before>import 'font-awesome/css/font-awesome.css';
import '../scss/app.scss';
import './vendors';
import './overrides';
import './collections';
import 'lazysizes';

class App {
    init(selecteur) {
        const self = this;
        $(document).ready(function() {
            self.initComponents(selecteur);
            self.initPopups();
            self.initScrollTo();
            self.initMenuOnScrollListener();
            self.initHeaderSearch();
            self.initBreadcrumb();
        });
    }

    initBreadcrumb() {
        var bread = $('#bread .breadcrumb');
        var btnCollapse = $('#bread .btn');

        btnCollapse.click(function() {
            bread.toggleClass('collapsed');
            $(this)
                .find('.fa')
                .toggleClass('fa-chevron-down')
                .toggleClass('fa-chevron-right');
        });
    }

    initHeaderSearch() {
        var searchForm = $('.navbar .search-form');
        var searchBackdrop = $('#search-menu-backdrop');
        searchForm
            .find('input')
            .focus(function() {
                searchForm.addClass('focus');
                searchBackdrop.addClass('open');
            })
            .blur(function() {
                searchForm.removeClass('focus');
                searchBackdrop.removeClass('open');
            });
    }

    initPopups() {
        $('a.popup').click(function() {
            var width = 520,
                height = 350,
                leftPosition = window.screen.width / 2 - (width / 2 + 10),
                topPosition = window.screen.height / 2 - (height / 2 + 50),
                windowFeatures =
                    'status=no,height=' +
                    height +
                    ',width=' +
                    width +
                    ',left=' +
                    leftPosition +
                    ',top=' +
                    topPosition +
                    ',screenX=' +
                    leftPosition +
                    ',screenY=' +
                    topPosition +
                    ',toolbar=0,status=0';

            window.open($(this).attr('href'), 'sharer', windowFeatures);
            return false;
        });
    }

    initComponents(selecteur) {
        const self = this;
        $(selecteur || 'body')
            .data('bmd.bootstrapMaterialDesign', null)
            .bootstrapMaterialDesign();
        self.initAutofocus(selecteur);
        self.initConnexion(selecteur);
        self.initRegister(selecteur);
        self.initTooltips(selecteur);
        self.initLike(selecteur);
        self.initMore(selecteur);
        self.initSelectpicker(selecteur);
        self.initGallery(selecteur);
        self.initShortcutDates(selecteur);
        self.initFormErrors(selecteur);
    }

    initFormErrors(container) {
        $('label.bmd-label-static', container || document).each(function() {
            $(this).toggleClass('position-static', $(this).find('.invalid-feedback').length > 0);
        });
    }
    initShortcutDates(container) {
        $('input.shorcuts_date', container || document).each(function() {
            $(this).removeAttr('name');
            var input = this;
            var fromInput = $('#' + $(this).data('from'));
            var toInput = $('#' + $(this).data('to'));

            var moment = require('moment');

            var ranges = {};
            $.each($(input).data('ranges'), function(label, values) {
                ranges[label] = [moment(values[0]), values[1] === null ? null : moment(values[1])];
            });

            $(input).daterangepicker(
                {
                    startDate: fromInput.val() ? moment(fromInput.val()) : moment(),
                    endDate: toInput.val() ? moment(toInput.val()) : null,
                    autoUpdateInput: false,
                    ranges: ranges,
                    alwaysShowCalendars: Object.keys(ranges).length === 0,
                    showCustomRangeLabel: Object.keys(ranges).length > 0,
                    locale: {
                        applyLabel: 'OK',
                        cancelLabel: 'Annuler',
                        fromLabel: 'Du',
                        toLabel: 'Au',
                        customRangeLabel: 'Personnalisé',
                    },
                },
                cb
            );

            function cb(start, end, label) {
                var datas = $(input).data('daterangepicker');
                if (typeof datas.ranges[label] !== 'undefined') {
                    $(input).val(label);
                } else {
                    if (!end.isValid()) {
                        $(input).val('A partir du ' + start.format('ll'));
                    } else if (start.format('YYYY-MM-DD') === end.format('YYYY-MM-DD')) {
                        $(input).val('Le ' + start.format('ll'));
                    } else {
                        $(input).val('Du ' + start.format('ll') + ' au ' + end.format('ll'));
                    }
                }

                fromInput.val(start.isValid() ? start.format('YYYY-MM-DD') : '');
                toInput.val(end.isValid() ? end.format('YYYY-MM-DD') : '');
            }
        });
    }

    initGallery(container) {
        $('.image-gallery', container || document).each(function() {
            $(this)
                .fancybox({
                    helpers: {
                        title: {
                            type: 'inside',
                            position: 'top',
                        },
                        overlay: {
                            locked: false,
                        },
                    },
                })
                .click(function() {
                    return false;
                });
        });
    }

    //Deps: []
    initMore(container) {
        const self = this;
        $('.more', container || document).click(function(e) {
            e.preventDefault();

            $(this)
                .attr('disabled', true)
                .prepend(' ');

            var btn = $(this);
            var container = btn.parent().prev();
            $.get($(btn).attr('href'), function(html) {
                var currentContainer = $('
').html(html);
                btn.parent().remove();
                currentContainer.insertAfter(container);
                self.initComponents(currentContainer);
            });
        });
    }

    loadingButtons(selecteur) {
        $('.btn-submit', selecteur || document)
            .attr('disabled', true)
            .prepend(' ');
    }

    resetButtons(selecteur) {
        $('.btn-submit', selecteur || document)
            .attr('disabled', false)
            .find('.spinner-border')
            .remove();
    }

    /**
     * Deps: ['select-i18n']
     * @param {jQuery|document} selecteur le selecteur pour le filtrage
     * @returns {void}
     */
    initSelectpicker(selecteur) {
        $('select', selecteur || document).each(function() {
            $(this).selectpicker({
                style: $(this).data('style') || 'btn-primary',
            });
        });
    }

    //Deps: []
    initAutofocus(selecteur) {
        $('[autofocus]', selecteur || document).focus();
    }

    //Deps: []
    initMenuOnScrollListener() {
        var navbar = $('.navbar');
        var toggler = navbar.find('.navbar-toggler');
        var href = $(toggler).data('target');
        var elem = $(href);

        $(window).scrolled(200, function() {
            if (!toggler.hasClass('collapsed')) {
                $(elem).collapse('hide');
            }
        });

        $(window).scroll(function() {
            if ($(window).scrollTop() > 0) {
                $(navbar).addClass('navbar-shadow');
            } else {
                $(navbar).removeClass('navbar-shadow');
            }
        });
    }

    //Deps: ['bootstrap']
    initLike(selecteur) {
        var options = {
            css_selecteur_like: '.btn-like-event',
            css_active_class: 'btn-primary',
        };

        $(options.css_selecteur_like, selecteur || document).click(function() {
            var btn = $(this);

            if (btn.hasClass('connexion')) {
                return false;
            }

            btn.attr('disabled', true);
            $.post(btn.data('href'), { like: !btn.hasClass(options.css_active_class) }).done(function(msg) {
                btn.attr('disabled', !msg.success);
                if (msg.success) {
                    btn.toggleClass(options.css_active_class, msg.like);
                }
            });
        });
    }

    //Deps: ['bootstrap']
    initTooltips(selecteur) {
        $('[data-toggle="tooltip"]', selecteur || document).tooltip();
    }

    //Deps: ['scrollTo']
    initScrollTo() {
        var settings = {
            min: 200,
            inDelay: 300,
            outDelay: 200,
            containerID: 'toTop',
            scrollSpeed: 400,
            easingType: 'linear',
        };

        var toTopHidden = true;
        var toTop = $('#' + settings.containerID);

        if (!toTop.length) {
            return;
        }

        toTop.click(function(e) {
            e.preventDefault();
            $('html, body').animate({ scrollTop: 0 }, settings.scrollSpeed, settings.easingType);
        });

        $(window).scrolled(200, function() {
            var sd = $(this).scrollTop();
            if (sd > settings.min && toTopHidden) {
                toTop.fadeIn(settings.inDelay);
                toTopHidden = false;
            } else if (sd <= settings.min && !toTopHidden) {
                toTop.fadeOut(settings.outDelay);
                toTopHidden = true;
            }
        });
    }

    //Deps: []
    popup(href, parent, width, height, left, top) {
        window.parent_elem = parent;

        (width = width || 800),
            (height = height || 500),
            (left = left || $(window).width() / 2 - width / 2),
            (top = top || $(window).height() / 2 - height / 2);

        window.open(
            href,
            null,
            'width=' +
                width +
                ',height=' +
                height +
                ',toolbar=0,menubar=0,location=0,status=0,scrollbars=1,resizable=1,left=' +
                left +
                ',top=' +
                top +
                ',toolbar=0'
        );
    }

    //Deps: ['modals']
    initRegister(selecteur) {
        const self = this;
        $('.register', selecteur || document)
            .unbind('click')
            .click(function() {
                var $dialog = $('#dialog_details');
                $dialog
                    .modal('show')
                    .modal('loading')
                    .load($(this).attr('href'), function() {
                        self.handleRegister($dialog);
                    });

                return false;
            });
    }

    //Deps: ['modals', 'bootstrap']
    handleRegister($dialog) {
        const self = this;
        self.initComponents($dialog);
        $dialog
            .find('form')
            .unbind('submit')
            .submit(function() {
                var href = $(this).attr('action');
                var datas = $(this).serialize();
                var submit_button = $('#_register');
                submit_button.button('loading');
                $.post(href, datas).done(function(data) {
                    submit_button.button('reset');

                    if (typeof data.success === 'boolean' && data.success) {
                        $dialog.modal('hide');
                        location.reload();
                    } else {
                        $dialog.html(data);
                        self.handleRegister($dialog); //ne rien mettre après
                    }
                });
                return false;
            });
    }

    //Deps: ['modals']
    initConnexion(selecteur) {
        const self = this;
        $('.connexion', selecteur || document)
            .unbind('click')
            .click(function(e) {
                var $dialog = $('#dialog_details');
                $dialog
                    .modal('show')
                    .modal('loading')
                    .load($(this).attr('href'), function() {
                        self.handleLogin($dialog);
                    });
                return false;
            });
    }

    //Deps: ['modals', 'bootstrap']
    handleLogin($dialog) {
        const self = this;
        self.initComponents($dialog);
        $dialog
            .find('form')
            .unbind('submit')
            .submit(function() {
                var href = $(this).attr('action');
                var datas = $(this).serialize();
                var submit_button = $('#_submit');
                submit_button.button('loading');
                $.post(href, datas).done(function(data) {
                    submit_button.button('reset');
                    if (!data.success) {
                        $dialog.modal('setLittleErreur', data.message);
                    } else {
                        $dialog.modal('hide');
                        location.reload();
                    }
                });
                return false;
            });
    }
}

global.App = window.App = new App();
<commit_msg>Removed autofocus<commit_after>import 'font-awesome/css/font-awesome.css';
import '../scss/app.scss';
import './vendors';
import './overrides';
import './collections';
import 'lazysizes';

class App {
    init(selecteur) {
        const self = this;
        $(document).ready(function() {
            self.initComponents(selecteur);
            self.initPopups();
            self.initScrollTo();
            self.initMenuOnScrollListener();
            self.initHeaderSearch();
            self.initBreadcrumb();
        });
    }

    initBreadcrumb() {
        var bread = $('#bread .breadcrumb');
        var btnCollapse = $('#bread .btn');

        btnCollapse.click(function() {
            bread.toggleClass('collapsed');
            $(this)
                .find('.fa')
                .toggleClass('fa-chevron-down')
                .toggleClass('fa-chevron-right');
        });
    }

    initHeaderSearch() {
        var searchForm = $('.navbar .search-form');
        var searchBackdrop = $('#search-menu-backdrop');
        searchForm
            .find('input')
            .focus(function() {
                searchForm.addClass('focus');
                searchBackdrop.addClass('open');
            })
            .blur(function() {
                searchForm.removeClass('focus');
                searchBackdrop.removeClass('open');
            });
    }

    initPopups() {
        $('a.popup').click(function() {
            var width = 520,
                height = 350,
                leftPosition = window.screen.width / 2 - (width / 2 + 10),
                topPosition = window.screen.height / 2 - (height / 2 + 50),
                windowFeatures =
                    'status=no,height=' +
                    height +
                    ',width=' +
                    width +
                    ',left=' +
                    leftPosition +
                    ',top=' +
                    topPosition +
                    ',screenX=' +
                    leftPosition +
                    ',screenY=' +
                    topPosition +
                    ',toolbar=0,status=0';

            window.open($(this).attr('href'), 'sharer', windowFeatures);
            return false;
        });
    }

    initComponents(selecteur) {
        const self = this;
        $(selecteur || 'body')
            .data('bmd.bootstrapMaterialDesign', null)
            .bootstrapMaterialDesign();
        self.initConnexion(selecteur);
        self.initRegister(selecteur);
        self.initTooltips(selecteur);
        self.initLike(selecteur);
        self.initMore(selecteur);
        self.initSelectpicker(selecteur);
        self.initGallery(selecteur);
        self.initShortcutDates(selecteur);
        self.initFormErrors(selecteur);
    }

    initFormErrors(container) {
        $('label.bmd-label-static', container || document).each(function() {
            $(this).toggleClass('position-static', $(this).find('.invalid-feedback').length > 0);
        });
    }
    initShortcutDates(container) {
        $('input.shorcuts_date', container || document).each(function() {
            $(this).removeAttr('name');
            var input = this;
            var fromInput = $('#' + $(this).data('from'));
            var toInput = $('#' + $(this).data('to'));

            var moment = require('moment');

            var ranges = {};
            $.each($(input).data('ranges'), function(label, values) {
                ranges[label] = [moment(values[0]), values[1] === null ? null : moment(values[1])];
            });

            $(input).daterangepicker(
                {
                    startDate: fromInput.val() ? moment(fromInput.val()) : moment(),
                    endDate: toInput.val() ? moment(toInput.val()) : null,
                    autoUpdateInput: false,
                    ranges: ranges,
                    alwaysShowCalendars: Object.keys(ranges).length === 0,
                    showCustomRangeLabel: Object.keys(ranges).length > 0,
                    locale: {
                        applyLabel: 'OK',
                        cancelLabel: 'Annuler',
                        fromLabel: 'Du',
                        toLabel: 'Au',
                        customRangeLabel: 'Personnalisé',
                    },
                },
                cb
            );

            function cb(start, end, label) {
                var datas = $(input).data('daterangepicker');
                if (typeof datas.ranges[label] !== 'undefined') {
                    $(input).val(label);
                } else {
                    if (!end.isValid()) {
                        $(input).val('A partir du ' + start.format('ll'));
                    } else if (start.format('YYYY-MM-DD') === end.format('YYYY-MM-DD')) {
                        $(input).val('Le ' + start.format('ll'));
                    } else {
                        $(input).val('Du ' + start.format('ll') + ' au ' + end.format('ll'));
                    }
                }

                fromInput.val(start.isValid() ? start.format('YYYY-MM-DD') : '');
                toInput.val(end.isValid() ? end.format('YYYY-MM-DD') : '');
            }
        });
    }

    initGallery(container) {
        $('.image-gallery', container || document).each(function() {
            $(this)
                .fancybox({
                    helpers: {
                        title: {
                            type: 'inside',
                            position: 'top',
                        },
                        overlay: {
                            locked: false,
                        },
                    },
                })
                .click(function() {
                    return false;
                });
        });
    }

    //Deps: []
    initMore(container) {
        const self = this;
        $('.more', container || document).click(function(e) {
            e.preventDefault();

            $(this)
                .attr('disabled', true)
                .prepend(' ');

            var btn = $(this);
            var container = btn.parent().prev();
            $.get($(btn).attr('href'), function(html) {
                var currentContainer = $('
').html(html);
                btn.parent().remove();
                currentContainer.insertAfter(container);
                self.initComponents(currentContainer);
            });
        });
    }

    loadingButtons(selecteur) {
        $('.btn-submit', selecteur || document)
            .attr('disabled', true)
            .prepend(' ');
    }

    resetButtons(selecteur) {
        $('.btn-submit', selecteur || document)
            .attr('disabled', false)
            .find('.spinner-border')
            .remove();
    }

    /**
     * Deps: ['select-i18n']
     * @param {jQuery|document} selecteur le selecteur pour le filtrage
     * @returns {void}
     */
    initSelectpicker(selecteur) {
        $('select', selecteur || document).each(function() {
            $(this).selectpicker({
                style: $(this).data('style') || 'btn-primary',
            });
        });
    }

    //Deps: []
    initMenuOnScrollListener() {
        var navbar = $('.navbar');
        var toggler = navbar.find('.navbar-toggler');
        var href = $(toggler).data('target');
        var elem = $(href);

        $(window).scrolled(200, function() {
            if (!toggler.hasClass('collapsed')) {
                $(elem).collapse('hide');
            }
        });

        $(window).scroll(function() {
            if ($(window).scrollTop() > 0) {
                $(navbar).addClass('navbar-shadow');
            } else {
                $(navbar).removeClass('navbar-shadow');
            }
        });
    }

    //Deps: ['bootstrap']
    initLike(selecteur) {
        var options = {
            css_selecteur_like: '.btn-like-event',
            css_active_class: 'btn-primary',
        };

        $(options.css_selecteur_like, selecteur || document).click(function() {
            var btn = $(this);

            if (btn.hasClass('connexion')) {
                return false;
            }

            btn.attr('disabled', true);
            $.post(btn.data('href'), { like: !btn.hasClass(options.css_active_class) }).done(function(msg) {
                btn.attr('disabled', !msg.success);
                if (msg.success) {
                    btn.toggleClass(options.css_active_class, msg.like);
                }
            });
        });
    }

    //Deps: ['bootstrap']
    initTooltips(selecteur) {
        $('[data-toggle="tooltip"]', selecteur || document).tooltip();
    }

    //Deps: ['scrollTo']
    initScrollTo() {
        var settings = {
            min: 200,
            inDelay: 300,
            outDelay: 200,
            containerID: 'toTop',
            scrollSpeed: 400,
            easingType: 'linear',
        };

        var toTopHidden = true;
        var toTop = $('#' + settings.containerID);

        if (!toTop.length) {
            return;
        }

        toTop.click(function(e) {
            e.preventDefault();
            $('html, body').animate({ scrollTop: 0 }, settings.scrollSpeed, settings.easingType);
        });

        $(window).scrolled(200, function() {
            var sd = $(this).scrollTop();
            if (sd > settings.min && toTopHidden) {
                toTop.fadeIn(settings.inDelay);
                toTopHidden = false;
            } else if (sd <= settings.min && !toTopHidden) {
                toTop.fadeOut(settings.outDelay);
                toTopHidden = true;
            }
        });
    }

    //Deps: []
    popup(href, parent, width, height, left, top) {
        window.parent_elem = parent;

        (width = width || 800),
            (height = height || 500),
            (left = left || $(window).width() / 2 - width / 2),
            (top = top || $(window).height() / 2 - height / 2);

        window.open(
            href,
            null,
            'width=' +
                width +
                ',height=' +
                height +
                ',toolbar=0,menubar=0,location=0,status=0,scrollbars=1,resizable=1,left=' +
                left +
                ',top=' +
                top +
                ',toolbar=0'
        );
    }

    //Deps: ['modals']
    initRegister(selecteur) {
        const self = this;
        $('.register', selecteur || document)
            .unbind('click')
            .click(function() {
                var $dialog = $('#dialog_details');
                $dialog
                    .modal('show')
                    .modal('loading')
                    .load($(this).attr('href'), function() {
                        self.handleRegister($dialog);
                    });

                return false;
            });
    }

    //Deps: ['modals', 'bootstrap']
    handleRegister($dialog) {
        const self = this;
        self.initComponents($dialog);
        $dialog
            .find('form')
            .unbind('submit')
            .submit(function() {
                var href = $(this).attr('action');
                var datas = $(this).serialize();
                var submit_button = $('#_register');
                submit_button.button('loading');
                $.post(href, datas).done(function(data) {
                    submit_button.button('reset');

                    if (typeof data.success === 'boolean' && data.success) {
                        $dialog.modal('hide');
                        location.reload();
                    } else {
                        $dialog.html(data);
                        self.handleRegister($dialog); //ne rien mettre après
                    }
                });
                return false;
            });
    }

    //Deps: ['modals']
    initConnexion(selecteur) {
        const self = this;
        $('.connexion', selecteur || document)
            .unbind('click')
            .click(function(e) {
                var $dialog = $('#dialog_details');
                $dialog
                    .modal('show')
                    .modal('loading')
                    .load($(this).attr('href'), function() {
                        self.handleLogin($dialog);
                    });
                return false;
            });
    }

    //Deps: ['modals', 'bootstrap']
    handleLogin($dialog) {
        const self = this;
        self.initComponents($dialog);
        $dialog
            .find('form')
            .unbind('submit')
            .submit(function() {
                var href = $(this).attr('action');
                var datas = $(this).serialize();
                var submit_button = $('#_submit');
                submit_button.button('loading');
                $.post(href, datas).done(function(data) {
                    submit_button.button('reset');
                    if (!data.success) {
                        $dialog.modal('setLittleErreur', data.message);
                    } else {
                        $dialog.modal('hide');
                        location.reload();
                    }
                });
                return false;
            });
    }
}

global.App = window.App = new App();
<|endoftext|>


<commit_before>const html = document.getElementsByTagName('html')[0],
    body = document.getElementsByTagName('body')[0],
    jsoToUrle = obj => {
        var res = '', i;
        for(i in obj) res += `${encodeURIComponent(i)}=${encodeURIComponent(obj[i])}&`;
        return res.slice(0, -1)
    }
    http = new (class HTTP{
        /**
         * Gets contents from url
         * @param {String} url
         * @return {Promise<String>}
         */
        get(url){
            var xhr = new XMLHttpRequest();
            return new Promise((resolve, reject) => {
                xhr.open('GET', url, true);
                xhr.onreadystatechange = () => {
                    if (xhr.readyState != 4) return;
                    if (xhr.status != 200) reject(new Error(`Cannot get requested url. Error ${xhr.status}: ${xhr.statusText}`)); else resolve(xhr.responseText);
                };
                xhr.send()
            })
        }
        /**
         * Sends POST to url
         * @param {String} url
         * @param {Object} data
         * @return {Promise<String>}
         */
        post(url, data){
            var xhr = new XMLHttpRequest();
            return new Promise((resolve, reject) => {
                xhr.open('POST', url, true);
                xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
                xhr.onreadystatechange = () => {
                    if (xhr.readyState != 4) return;
                    if (xhr.status != 200) reject(new Error(`Cannot post to requested url. Error ${xhr.status}: ${xhr.statusText}`)); else resolve(xhr.responseText);
                };
                xhr.send(jsoToUrle(data));
            })
        }
    })();
/**
 * Checks if html or body matches selector
 * @param {String} selector Selector to check
 * @return {Boolean}
 */
function is(selector){
    function match(el){
        el.matches = (el.matches || el.matchesSelector || (() => {return false}))
    return selector => {return el.matches(selector)}
    }
    try {
        return match(body)(selector) || match(html)(selector)
    } catch(e){
        return false;
    }
}
/**
 * Checks if html or body matches all the selectors
 * @param {Array<String>} selectors Array of selectors to check
 * @return {Boolean}
 */
function isAll(selectors){
    var res = true;
    selectors.forEach(sel => {res = res && is(sel)});
    return res;
}
module.exports = {
    html,
    body,
    is,
    isAll,
    /**
     * jQ-like selecting i-face
     * @param {String} selector
     * @return {NodeListOf<HTMLElement>}
     */
    $: selector => {
        return document.querySelectorAll(selector)
    }, Cookies: new (class Cookies{
        /**
         * @typedef {Object} Options
         * @property {Number|Date} expires Interpreted differently, depending on the type: The number is the number of seconds before the expiration. For example, expires: 3600 - cookie for an hour. An object of type Date is the expiration date. If expires in the past, the cookie will be deleted. If expires is absent or 0, the cookie will be set as session and will disappear when the browser is closed.
         * @property {String} path Cookie path
         * @property {String} domain Cookie domain
         * @property {Boolean} secure Whether to forward only over a secure connection
         */
        constructor(){
            /**
             * Gets selected cookie
             * @param {String} name
             * @return {void}
             */
            this.get = name => {
                var matches = document.cookie.match(new RegExp(
                    "(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"
                ));
                return matches ? decodeURIComponent(matches[1]) : undefined;
            }
            /**
             * Sets selected cookie
             * @param {String} name
             * @param {String} value
             * @param {Options} options
             * @return {void}
             */
            this.set = (name, value, options) => {
                options = options || {};
                var expires = options.expires;
                if (typeof expires == "number" && expires) {
                    var d = new Date();
                    d.setTime(d.getTime() + expires * 1000);
                    expires = options.expires = d;
                }
                if (expires && expires.toUTCString) {
                    options.expires = expires.toUTCString();
                }
                value = encodeURIComponent(value);
                var updatedCookie = name + "=" + value;
                for (var propName in options){
                    updatedCookie += "; " + propName;
                    var propValue = options[propName];
                    if (propValue !== true) {
                        updatedCookie += "=" + propValue;
                    }
                }
                document.cookie = updatedCookie;
            }
            /**
             * Delete selected cookie
             * @param {String} name
             * @return {void}
             */
            this.del = name => {
                this.set(name, "", {
                    expires: -1
                })
            }
        }
    })(),
    http,
    apiv4pjs: new Proxy({}, {
        get(name){
            return data => {
                return http.get(`${location.origin}/addons/apiv4pjs?act=${encodeURIComponent(name)}&${jsoToUrle(data)}`);
            }
        },
        set(){
            return true
        }
    }),
}
<commit_msg>Fixed unresolved url<commit_after>const html = document.getElementsByTagName('html')[0],
    body = document.getElementsByTagName('body')[0],
    jsoToUrle = obj => {
        var res = '', i;
        for(i in obj) res += `${encodeURIComponent(i)}=${encodeURIComponent(obj[i])}&`;
        return res.slice(0, -1)
    }
    http = new (class HTTP{
        /**
         * Gets contents from url
         * @param {String} url
         * @return {Promise<String>}
         */
        get(url){
            var xhr = new XMLHttpRequest();
            return new Promise((resolve, reject) => {
                xhr.open('GET', url, true);
                xhr.onreadystatechange = () => {
                    if (xhr.readyState != 4) return;
                    if (xhr.status != 200) reject(new Error(`Cannot get requested url. Error ${xhr.status}: ${xhr.statusText}`)); else resolve(xhr.responseText);
                };
                xhr.send()
            })
        }
        /**
         * Sends POST to url
         * @param {String} url
         * @param {Object} data
         * @return {Promise<String>}
         */
        post(url, data){
            var xhr = new XMLHttpRequest();
            return new Promise((resolve, reject) => {
                xhr.open('POST', url, true);
                xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
                xhr.onreadystatechange = () => {
                    if (xhr.readyState != 4) return;
                    if (xhr.status != 200) reject(new Error(`Cannot post to requested url. Error ${xhr.status}: ${xhr.statusText}`)); else resolve(xhr.responseText);
                };
                xhr.send(jsoToUrle(data));
            })
        }
    })();
/**
 * Checks if html or body matches selector
 * @param {String} selector Selector to check
 * @return {Boolean}
 */
function is(selector){
    function match(el){
        el.matches = (el.matches || el.matchesSelector || (() => {return false}))
    return selector => {return el.matches(selector)}
    }
    try {
        return match(body)(selector) || match(html)(selector)
    } catch(e){
        return false;
    }
}
/**
 * Checks if html or body matches all the selectors
 * @param {Array<String>} selectors Array of selectors to check
 * @return {Boolean}
 */
function isAll(selectors){
    var res = true;
    selectors.forEach(sel => {res = res && is(sel)});
    return res;
}
module.exports = {
    html,
    body,
    is,
    isAll,
    /**
     * jQ-like selecting i-face
     * @param {String} selector
     * @return {NodeListOf<HTMLElement>}
     */
    $: selector => {
        return document.querySelectorAll(selector)
    }, Cookies: new (class Cookies{
        /**
         * @typedef {Object} Options
         * @property {Number|Date} expires Interpreted differently, depending on the type: The number is the number of seconds before the expiration. For example, expires: 3600 - cookie for an hour. An object of type Date is the expiration date. If expires in the past, the cookie will be deleted. If expires is absent or 0, the cookie will be set as session and will disappear when the browser is closed.
         * @property {String} path Cookie path
         * @property {String} domain Cookie domain
         * @property {Boolean} secure Whether to forward only over a secure connection
         */
        constructor(){
            /**
             * Gets selected cookie
             * @param {String} name
             * @return {void}
             */
            this.get = name => {
                var matches = document.cookie.match(new RegExp(
                    "(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"
                ));
                return matches ? decodeURIComponent(matches[1]) : undefined;
            }
            /**
             * Sets selected cookie
             * @param {String} name
             * @param {String} value
             * @param {Options} options
             * @return {void}
             */
            this.set = (name, value, options) => {
                options = options || {};
                var expires = options.expires;
                if (typeof expires == "number" && expires) {
                    var d = new Date();
                    d.setTime(d.getTime() + expires * 1000);
                    expires = options.expires = d;
                }
                if (expires && expires.toUTCString) {
                    options.expires = expires.toUTCString();
                }
                value = encodeURIComponent(value);
                var updatedCookie = name + "=" + value;
                for (var propName in options){
                    updatedCookie += "; " + propName;
                    var propValue = options[propName];
                    if (propValue !== true) {
                        updatedCookie += "=" + propValue;
                    }
                }
                document.cookie = updatedCookie;
            }
            /**
             * Delete selected cookie
             * @param {String} name
             * @return {void}
             */
            this.del = name => {
                this.set(name, "", {
                    expires: -1
                })
            }
        }
    })(),
    http,
    apiv4pjs: new Proxy({}, {
        get(target, act){
            return data => {
                return new Promise((resolve, reject) => {
                    http.get(`${location.origin}/addons/apiv4pjs?act=${encodeURIComponent(act)}&${jsoToUrle(data)}`).then(result => {
                        resolve(JSON.parse(result))
                    }).catch(reject)
                })
            }
        },
        set(){
            return true
        }
    }),
}
<|endoftext|>


<commit_before>var su = ''; //http://ec2-54-200-40-68.us-west-2.compute.amazonaws.com:8080';

var _user_details = '/user/details';

var _user_details = 'http://web.mit.edu/ambhave/www/suitup/user_details.json';

function init_user_details() {
    console.log('init_user_details()');

    $.getJSON(_user_details, function (data) {
        $('.user_username').text(data['username']);
    }).error(function (jqXhr, textStatus, error) {
        alert("ERROR: " + textStatus + ", " + error);
    });
}

$(document).ready(function () {
  //  login();
    //  init_user_details();

});

function chat_join(s) {
    $.ajax({
        type: "GET",
        url: su + '/chatroom/join',
        success: function (data) {
            chatroomid = JSON.parse(data).crid;
            $('#firepad').html('');
            var firepadRef = new Firebase('//hackmitsuitup.firebaseIO.com/firepads/' + chatroomid);
            var codeMirror = CodeMirror(document.getElementById('firepad'), {
                lineNumbers: true,
                mode: 'python'
            });
            var firepad = Firepad.fromCodeMirror(firepadRef, codeMirror);

            setTimeout(join_room, 2000);
            setTimeout(chat_check, 1000);
        }
    });
}

function join_room() {
    // webrtc.createRoom(chatroomid);
    webrtc.joinRoom(String(chatroomid));
}

function chat_leave() {
    $.ajax({
        type: "GET",
        url: su + '/chatroom/leave',
        success: function (data) {
            $('#firepad').html('');
        }
    });
    chatroomid = null;
    webrtc.leaveRoom(webrtc.roomName);
}

function chat_send(chat, convo) {
    $.ajax({
        type: "GET",
        url: su + '/message/send',
        data: { 's': $('#' + chat).val() }
    });
    $('#' + convo).val($('#' + convo).val() + '\nMe: ' + $('#' + chat).val());
    $('#' + chat).val('');
}

function chat_check() {
    $.ajax({
        type: "GET",
        url: su + '/message/check',
        success: function (data) {
            if (data != '') {
                console.log(data);
                $('#convo').val($('#convo').val() + '\nOther: ' + data);
            }
            setTimeout(chat_check, 1000);
        }
    });
}

// Load the SDK asynchronously
(function (d) {
    var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
    if (d.getElementById(id)) { return; }
    js = d.createElement('script'); js.id = id; js.async = true;
    js.src = "//connect.facebook.net/en_US/all.js";
    ref.parentNode.insertBefore(js, ref);
}(document));

var access_token = null;
var user_city = null;
var fb_user = null;

function login() {
    _login_wait();

    FB.login(function (response) {
        //_check_login();
    });
}
function logout() {
    _login_wait();

    FB.logout(function (response) {
        //_login_bad();
    });
}

// Additional JS functions here
window.fbAsyncInit = function () {
    FB.init({
        appId: '615988445111525', // App ID
        channelUrl: '//localhost:8000/channel.html', // Channel File
        status: true, // check login status
        cookie: true, // enable cookies to allow the server to access the session
        xfbml: true  // parse XFBML
    });

    // Additional init code here
    //_check_login();
    _login_wait();
    FB.getLoginStatus(function (response) {
        if (response.status !== 'connected') {
            _login_bad();
        }
    });

    FB.Event.subscribe('auth.statusChange', function (response) {
        _check_login();
        console.log(response);
    });
};

/* Helper Functions */
function _hide_all_login() {
    $('.pLoginBad').hide();
    $('.pLoginDone').hide();
    $('.pLoginWait').hide();
}
function _check_login() {
    _login_wait();
    FB.getLoginStatus(function (response) {
        if (response.status === 'connected') {
            _login_done(response);
        }
        else {
            _login_bad();
        }
    });
}
function _login_wait() {
    _hide_all_login();
    $('.pLoginWait').show();
}
function _login_bad() {
    _hide_all_login();
    $('.pLoginBad').show();
}
function _login_done(response) {

    if (response != null)
        access_token = response.authResponse.accessToken;

    FB.api('/me?fields=picture,name', function (response) {
        fb_user = response;
        console.log(response);
        $('.user_username').text(response.name);
        $('.user_photourl').attr('src', response.picture.data.url);

        _hide_all_login();
        $('.pLoginDone').show();
    });

    // TODO: UNCOMMENT THIS!!!!!!!!!!!!!!!!!!!!!!!!!!!
    $.ajax({ url: su + '/login?access_token=' + access_token }).success(function (data) { chat_join(); });

    //$.ajax({url:"demo_test.txt",success:function(result){    $("#div1").html(result);  }});

    /*

    FB.api('/me/home', function(response) {
       console.log(response);
       $('#news_feed').empty();
       for (var i = 0; i < response['data'].length; i++) {
           var item = response['data'][i];
           var txt = '
 \
                    \
                        \
                    \

  \

' + item['from']['name'] + '
            \

 \

';
           $('#news_feed').append(txt);
       }
    });*/
}
function _fatal_error(message) {
    $('body').html('Fatal Error! Please refresh the page

Message: ' + message);
}

<commit_msg>suitup chat join<commit_after>var su = ''; //http://ec2-54-200-40-68.us-west-2.compute.amazonaws.com:8080';

var _user_details = '/user/details';

var _user_details = 'http://web.mit.edu/ambhave/www/suitup/user_details.json';

function init_user_details() {
    console.log('init_user_details()');

    $.getJSON(_user_details, function (data) {
        $('.user_username').text(data['username']);
    }).error(function (jqXhr, textStatus, error) {
        alert("ERROR: " + textStatus + ", " + error);
    });
}

$(document).ready(function () {
  //  login();
    //  init_user_details();

});

function chat_join(s) {
    $.ajax({
        type: "GET",
        url: su + '/chatroom/join',
        success: function (data) {
            chatroomid = JSON.parse(data).crid;
            $('#firepad').html('');
            var firepadRef = new Firebase('//hackmitsuitup.firebaseIO.com/firepads/' + chatroomid);
            var codeMirror = CodeMirror(document.getElementById('firepad'), {
                lineNumbers: true,
                mode: 'python'
            });
            var firepad = Firepad.fromCodeMirror(firepadRef, codeMirror);

            setTimeout(join_room, 2000);
            setTimeout(chat_check, 1000);
        }
    });
}

function join_room() {
    // webrtc.createRoom(chatroomid);
    webrtc.joinRoom(String(chatroomid));
}

function chat_leave() {
    $.ajax({
        type: "GET",
        url: su + '/chatroom/leave',
        success: function (data) {
            sts = JSON.parse(data).status;
            console.log("sts: " + sts);
            if (sts == "failure") {
                chat_join()
            }
            else {
                $('#firepad').html('');
            }
        }
    });
    chatroomid = null;
    webrtc.leaveRoom(webrtc.roomName);
}

function chat_send(chat, convo) {
    $.ajax({
        type: "GET",
        url: su + '/message/send',
        data: { 's': $('#' + chat).val() }
    });
    $('#' + convo).val($('#' + convo).val() + '\nMe: ' + $('#' + chat).val());
    $('#' + chat).val('');
}

function chat_check() {
    $.ajax({
        type: "GET",
        url: su + '/message/check',
        success: function (data) {
            if (data != '') {
                console.log(data);
                $('#convo').val($('#convo').val() + '\nOther: ' + data);
            }
            setTimeout(chat_check, 1000);
        }
    });
}

// Load the SDK asynchronously
(function (d) {
    var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
    if (d.getElementById(id)) { return; }
    js = d.createElement('script'); js.id = id; js.async = true;
    js.src = "//connect.facebook.net/en_US/all.js";
    ref.parentNode.insertBefore(js, ref);
}(document));

var access_token = null;
var user_city = null;
var fb_user = null;

function login() {
    _login_wait();

    FB.login(function (response) {
        //_check_login();
    });
}
function logout() {
    _login_wait();

    FB.logout(function (response) {
        //_login_bad();
    });
}

// Additional JS functions here
window.fbAsyncInit = function () {
    FB.init({
        appId: '615988445111525', // App ID
        channelUrl: '//localhost:8000/channel.html', // Channel File
        status: true, // check login status
        cookie: true, // enable cookies to allow the server to access the session
        xfbml: true  // parse XFBML
    });

    // Additional init code here
    //_check_login();
    _login_wait();
    FB.getLoginStatus(function (response) {
        if (response.status !== 'connected') {
            _login_bad();
        }
    });

    FB.Event.subscribe('auth.statusChange', function (response) {
        _check_login();
        console.log(response);
    });
};

/* Helper Functions */
function _hide_all_login() {
    $('.pLoginBad').hide();
    $('.pLoginDone').hide();
    $('.pLoginWait').hide();
}
function _check_login() {
    _login_wait();
    FB.getLoginStatus(function (response) {
        if (response.status === 'connected') {
            _login_done(response);
        }
        else {
            _login_bad();
        }
    });
}
function _login_wait() {
    _hide_all_login();
    $('.pLoginWait').show();
}
function _login_bad() {
    _hide_all_login();
    $('.pLoginBad').show();
}
function _login_done(response) {

    if (response != null)
        access_token = response.authResponse.accessToken;

    FB.api('/me?fields=picture,name', function (response) {
        fb_user = response;
        console.log(response);
        $('.user_username').text(response.name);
        $('.user_photourl').attr('src', response.picture.data.url);

        _hide_all_login();
        $('.pLoginDone').show();
    });

    // TODO: UNCOMMENT THIS!!!!!!!!!!!!!!!!!!!!!!!!!!!
    $.ajax({ url: su + '/login?access_token=' + access_token }).success(function (data) { chat_join(); });

    //$.ajax({url:"demo_test.txt",success:function(result){    $("#div1").html(result);  }});

    /*

    FB.api('/me/home', function(response) {
       console.log(response);
       $('#news_feed').empty();
       for (var i = 0; i < response['data'].length; i++) {
           var item = response['data'][i];
           var txt = '
 \
                    \
                        \
                    \

  \

' + item['from']['name'] + '
            \

 \

';
           $('#news_feed').append(txt);
       }
    });*/
}
function _fatal_error(message) {
    $('body').html('Fatal Error! Please refresh the page

Message: ' + message);
}

<|endoftext|>


<commit_before>/*!
 * Accessibility Sniffer
 * Version: 0.1
 *
 * Copyright 2011, George Walters II
 * Licensed under MIT Version 2
 *
 * Date: Fri Aug 19 2011 8:58 AM -0500
 *
 * Usage:
 *	assistiveTech.init({
 *		flashLocale: "flash/assistiveTech.swf",
 *		callBack: "variable",
 *		cookieName: "assistiveTech",
 *		debug: "false",
 *		flashVersion: "9",
 *		replacementDiv: "assistiveTech",
 *		writeAnalytics: function (enabledFlag) { alert("Some Analytic data goes here"); }
 *	});
 */
var assistiveTech = (function () {
	var defaults = {
		version = 0.1,
		callBack,
		cookieName = "assistiveTech",
		debug = false,
		divId,
		flashLocale = "/flash/assistiveTech.swf",
		flashVersion = "9",
		success,
		techAssist = false,
		writeAnalytics
	},
		self = this,

//Public Methods
	getVersion = function () {
		return version;
	},

	getCookieName = function () {
		return cookieName;
	},

	getCookieValue = function () {
		var cookieInformation = self.getCookie();
		return cookieInformation[1];
	},

	init = function (options) {
		if (self.typeOf(options) === 'object') {
			for (var key in (options || {})) {
				self.defaults[key] = options[key];
			}
		}

		// Test to see if SWFObject is loaded and if not, load it dynamically from Google APIs
		//ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js

		if (!self.cookieExists() && !(typeof swfobject.embedSWF === "function") {
			self.loadSwfObject();
		} else if (!self.cookieExists()) {
			self.generateFlash();
		}
	},

	flashSuccess = function (accessibilityFlag) {
		self.defaults.techAssist = (self.defaults.debug) ? true
				: accessibilityFlag);
		self.setCookie();
		if (self.typeOf(self.defaults.writeAnalytics) === "function") {
			self.defaults.writeAnalytics((self.defaults.techAssist ? 'Yes' : 'No'));
		}
	},

// Private Methods
	loadSwfObject = function () {
		var that = this,
			body = document.getElementsByTagName("body")[0],
			script = document.createElement("script");

		script.type = "text/javascript";
		script.src = "//ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js";
		// Mozilla, Safari, Opera, etc
		script.onload = that.generateFlash;
		// IE
		script.onreadystatechange = function () {
			if (this.readyState === "complete") {
				self.generateFlash();
			}
		};

		body.appendChild(script);
	},

	generateFlash = function () {
		var that = this;
		that.flashVars = {callback:self.defaults.callBack + ".flashSuccess"};
		that.flashParams = {quality:"low",allowScriptAccess:"all"};

		// Write out the SWFObject
		swfobject.embedSWF(self.defaults.flashLocale, self.defaults.divID, 1, 1, self.defaults.flashVersion, false, that.flashVars, that.flashParams, false, assistiveTech.checkFlashInclusion);
	},

	checkFlashInclusion = function (flag) {
		if (document.getElementById(self.defaults.divID).type.indexOf("application/x-shockwave-flash") !== -1) {
			document.getElementById(self.defaults.divID).focus();
			self.flashSuccess(flag);
		}
		else {
			self.flashFailure();
		}
	},

	/**
	 * Embedding the Flash application failed.
	 * Display the version message in the assistiveTech div only
	 * if we've been asked to do so.
	 */
	flashFailure = function () {
		var that = this,
			flashVersion = swfobject.getFlashPlayerVersion();
		if (self.defaults.debug === "true") {
			if (flashVersion && (document.getElementById && (flashVersion.major > 0))) {
				document.getElementById(self.defaults.replacementDiv).innerHTML = "
This sample requires Flash Player version " +
					self.defaults.flashVersion + ". You have Flash player " +
					flashVersion.major + "." + flashVersion.minor + "." + flashVersion.rev +
					" installed. " +
					" Download the latest Flash Player to run the sample.
";
			}
		}
	},

	typeOf = function (value) {
		var s = 'null';
		if (value) {
			if (typeof value === 'object' && typeof value.length === 'number' &&
				!(value.propertyIsEnumerable('length')) &&
				typeof value.splice === 'function') {
				s = 'array';
			}
		}
		return s;
	},

	getCookie = function () {
		var cookies = document.cookie.split(';'),
			i = 0,
			cookieData,
			cookieName;
		for ( ; i < cookies.length; i = i + 1) {
			cookieData = cookieName = null;
			cookieData = cookies[i].split('=');
			cookieName = cookieData[0].replace(/^\s+|\s+$/g, '');
			if (cookieName === self.defaults.cookieName) {
				return cookieData;
			}
		}
		return false;
	},

	/**
	 *
	 * return true/false if cookie exists
	 */
	cookieExists = function () {
		var cookieInformation = self.getCookie(),
			existsFlag = false;
		if (self.defaults.debug === "true") {
			existsFlag = false;
		} else if (cookieInformation && cookieInformation.length > 1) {
			existsFlag = true;
		}
		return existsFlag;
	},

	setCookie = function () {
		var nextMonth = expiresDate = new Date();
		nextMonth.setSeconds(0);
		nextMonth.setMinutes(0);
		nextMonth.setHours(0);
		nextMonth.setMonth(nextMonth.getMonth() + 1);
		nextMonth.setDate(1);
		expiresDate = new Date(nextMonth);
		document.cookie = self.defaults.cookieName + "=" +
				escape(self.defaults.techAssist) + "; expires=" +
				expiresDate.toGMTString() + "; path=/";
	};

	return {
		init: init,
		flashSuccess: flashSuccess,
		getCookieName: getCookieName,
		getCookieValue: getCookieValue,
		getVersion: getVersion;
	}

}());<commit_msg>Code Cleanup<commit_after>/*!
 * Accessibility Sniffer
 * Version: 0.1
 *
 * Copyright 2011, George Walters II
 * Licensed under MIT Version 2
 *
 * Date: Fri Aug 19 2011 8:58 AM -0500
 *
 * Usage:
 *	assistiveTech.init({
 *		flashLocale: "flash/assistiveTech.swf",
 *		callBack: "variable",
 *		cookieName: "assistiveTech",
 *		debug: "false",
 *		flashVersion: "9",
 *		replacementDiv: "assistiveTech",
 *		writeAnalytics: function (enabledFlag) { alert("Some Analytic data goes here"); }
 *	});
 */
var assistiveTech = (function () {
	var defaults = {
		version = 0.1,
		callBack,
		cookieName = "assistiveTech",
		debug = false,
		divId,
		flashLocale = "/flash/assistiveTech.swf",
		flashVersion = "9",
		success,
		techAssist = false,
		writeAnalytics
	},
		self = this,

//Public Methods
	getVersion = function () {
		return version;
	},

	getCookieName = function () {
		return cookieName;
	},

	getCookieValue = function () {
		var cookieInformation = self.getCookie();
		return cookieInformation[1];
	},

	init = function (options) {
		if (self.typeOf(options) === 'object') {
			for (var key in (options || {})) {
				self.defaults[key] = options[key];
			}
		}

		// Test to see if SWFObject is loaded and if not, load it dynamically from Google APIs
		//ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js

		if (!self.cookieExists() && !(typeof swfobject.embedSWF === "function") {
			self.loadSwfObject();
		} else if (!self.cookieExists()) {
			self.generateFlash();
		}
	},

	flashSuccess = function (accessibilityFlag) {
		self.defaults.techAssist = (self.defaults.debug) ? true
				: accessibilityFlag);
		self.setCookie();
		if (self.typeOf(self.defaults.writeAnalytics) === "function") {
			self.defaults.writeAnalytics((self.defaults.techAssist ? 'Yes' : 'No'));
		}
	},

// Private Methods
	loadSwfObject = function () {
		var that = this,
			body = document.getElementsByTagName("body")[0],
			script = document.createElement("script");

		script.type = "text/javascript";
		script.src = "//ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js";
		// Mozilla, Safari, Opera, etc
		script.onload = that.generateFlash;
		// IE
		script.onreadystatechange = function () {
			if (this.readyState === "complete") {
				self.generateFlash();
			}
		};

		body.appendChild(script);
	},

	generateFlash = function () {
		var that = this;
		that.flashVars = {callback:self.defaults.callBack + ".flashSuccess"};
		that.flashParams = {quality:"low",allowScriptAccess:"all"};

		// Write out the SWFObject
		swfobject.embedSWF(self.defaults.flashLocale, self.defaults.divID, 1, 1, self.defaults.flashVersion, false, that.flashVars, that.flashParams, false, assistiveTech.checkFlashInclusion);
	},

	checkFlashInclusion = function (flag) {
		if (document.getElementById(self.defaults.divID).type.indexOf("application/x-shockwave-flash") !== -1) {
			document.getElementById(self.defaults.divID).focus();
			self.flashSuccess(flag);
		}
		else {
			self.flashFailure();
		}
	},

	/**
	 * Embedding the Flash application failed.
	 * Display the version message in the assistiveTech div only
	 * if we've been asked to do so.
	 */
	flashFailure = function () {
		var that = this,
			flashVersion = swfobject.getFlashPlayerVersion();
		if (self.defaults.debug === "true") {
			if (flashVersion && (document.getElementById && (flashVersion.major > 0))) {
				document.getElementById(self.defaults.replacementDiv).innerHTML = "
This sample requires Flash Player version " +
					self.defaults.flashVersion + ". You have Flash player " +
					flashVersion.major + "." + flashVersion.minor + "." + flashVersion.rev +
					" installed. " +
					" Download the latest Flash Player to run the sample.
";
			}
		}
	},

	typeOf = function (value) {
		var s = 'null';
		if (value) {
			if (typeof value === 'object' && typeof value.length === 'number' &&
				!(value.propertyIsEnumerable('length')) &&
				typeof value.splice === 'function') {
				s = 'array';
			}
		}
		return s;
	},

	getCookie = function () {
		var cookies = document.cookie.split(';'),
			i = 0,
			cookieData,
			cookieName;
		for ( ; i < cookies.length; i = i + 1) {
			cookieData = cookieName = null;
			cookieData = cookies[i].split('=');
			cookieName = cookieData[0].replace(/^\s+|\s+$/g, '');
			if (cookieName === self.defaults.cookieName) {
				return cookieData;
			}
		}
		return false;
	},

	/**
	 *
	 * return true/false if cookie exists
	 */
	cookieExists = function () {
		var cookieInformation = self.getCookie(),
			existsFlag = false;
		if (self.defaults.debug === "true") {
			existsFlag = false;
		} else if (cookieInformation && cookieInformation.length > 1) {
			existsFlag = true;
		}
		return existsFlag;
	},

	setCookie = function () {
		var nextMonth = new Date(), expiresDate;
		nextMonth.setSeconds(0);
		nextMonth.setMinutes(0);
		nextMonth.setHours(0);
		nextMonth.setMonth(nextMonth.getMonth() + 1);
		nextMonth.setDate(1);
		expiresDate = new Date(nextMonth);
		document.cookie = self.defaults.cookieName + "=" +
				escape(self.defaults.techAssist) + "; expires=" +
				expiresDate.toGMTString() + "; path=/";
	};

	return {
		init: init,
		flashSuccess: flashSuccess,
		getCookieName: getCookieName,
		getCookieValue: getCookieValue,
		getVersion: getVersion;
	}

}());<|endoftext|>