<commit_before>(function($){
  $.fn.instagram = function(options) {
    var that = this,
        apiEndpoint = "https://api.instagram.com/v1",
        settings = {
            hash: null
          , userId: null
          , locationId: null
          , search: null
          , accessToken: null
          , clientId: null
          , show: null
          , onLoad: null
          , onComplete: null
          , maxId: null
          , minId: null
          , next_url: null
          , image_size: null
        };

    options && $.extend(settings, options);

    function createPhotoElement(photo) {
      var image_url = photo.images.thumbnail.url;

      if (settings.image_size == 'low_resolution') {
        image_url = photo.images.low_resolution.url;
      }
      else if (settings.image_size == 'thumbnail') {
        image_url = photo.images.thumbnail.url;
      }
      else if (settings.image_size == 'standard_resolution') {
        image_url = photo.images.standard_resolution.url;
      }

      return $('<div>')
        .addClass('instagram-placeholder')
        .attr('id', photo.id)
        .append(
          $('<a>')
            .attr('target', '_blank')
            .attr('href', photo.link)
            .append(
              $('<img>')
                .addClass('instagram-image')
                .attr('src', image_url)
            )
        );
    }

    function createEmptyElement() {
      return $('<div>')
        .addClass('instagram-placeholder')
        .attr('id', 'empty')
        .append($('<p>').html('No photos for this query'));
    }

    function composeRequestURL() {

      var url = apiEndpoint,
          params = {};

      if (settings.next_url != null) {
        return settings.next_url;
      }

      if(settings.hash != null) {
        url += "/tags/" + settings.hash + "/media/recent";
      }
      else if(settings.search != null) {
        url += "/media/search";
        params.lat = settings.search.lat;
        params.lng = settings.search.lng;
        settings.search.max_timestamp != null && (params.max_timestamp = settings.search.max_timestamp);
        settings.search.min_timestamp != null && (params.min_timestamp = settings.search.min_timestamp);
        settings.search.distance != null && (params.distance = settings.search.distance);
      }
      else if(settings.userId != null) {
        url += "/users/" + settings.userId + "/media/recent";
      }
      else if(settings.locationId != null) {
        url += "/locations/" + settings.locationId + "/media/recent";
      }
      else {
        url += "/media/popular";
      }

      settings.accessToken != null && (params.access_token = settings.accessToken);
      settings.clientId != null && (params.client_id = settings.clientId);
      settings.minId != null && (params.min_id = settings.minId);
      settings.maxId != null && (params.max_id = settings.maxId);

      url += "?" + $.param(params)

      return url;
    }

    settings.onLoad != null && typeof settings.onLoad == 'function' && settings.onLoad();

    $.ajax({
      type: "GET",
      dataType: "jsonp",
      cache: false,
      url: composeRequestURL(),
      success: function(res) {
        var length = typeof res.data != 'undefined' ? res.data.length : 0;
        var limit = settings.show != null && settings.show < length ? settings.show : length;

        if(limit > 0) {
          for(var i = 0; i < limit; i++) {
            that.append(createPhotoElement(res.data[i]));
          }
        }
        else {
          that.append(createEmptyElement());
        }

        settings.onComplete != null && typeof settings.onComplete == 'function' && settings.onComplete(res.data, res);
      }
    });

    return this;
  };
})(jQuery);
<commit_msg>Added count to parameter so that a larger result set is returned<commit_after>(function($){
  $.fn.instagram = function(options) {
    var that = this,
        apiEndpoint = "https://api.instagram.com/v1",
        settings = {
            hash: null
          , userId: null
          , locationId: null
          , search: null
          , accessToken: null
          , clientId: null
          , show: null
          , onLoad: null
          , onComplete: null
          , maxId: null
          , minId: null
          , next_url: null
          , image_size: null
        };

    options && $.extend(settings, options);

    function createPhotoElement(photo) {
      var image_url = photo.images.thumbnail.url;

      if (settings.image_size == 'low_resolution') {
        image_url = photo.images.low_resolution.url;
      }
      else if (settings.image_size == 'thumbnail') {
        image_url = photo.images.thumbnail.url;
      }
      else if (settings.image_size == 'standard_resolution') {
        image_url = photo.images.standard_resolution.url;
      }

      return $('<div>')
        .addClass('instagram-placeholder')
        .attr('id', photo.id)
        .append(
          $('<a>')
            .attr('target', '_blank')
            .attr('href', photo.link)
            .append(
              $('<img>')
                .addClass('instagram-image')
                .attr('src', image_url)
            )
        );
    }

    function createEmptyElement() {
      return $('<div>')
        .addClass('instagram-placeholder')
        .attr('id', 'empty')
        .append($('<p>').html('No photos for this query'));
    }

    function composeRequestURL() {

      var url = apiEndpoint,
          params = {};

      if (settings.next_url != null) {
        return settings.next_url;
      }

      if(settings.hash != null) {
        url += "/tags/" + settings.hash + "/media/recent";
      }
      else if(settings.search != null) {
        url += "/media/search";
        params.lat = settings.search.lat;
        params.lng = settings.search.lng;
        settings.search.max_timestamp != null && (params.max_timestamp = settings.search.max_timestamp);
        settings.search.min_timestamp != null && (params.min_timestamp = settings.search.min_timestamp);
        settings.search.distance != null && (params.distance = settings.search.distance);
      }
      else if(settings.userId != null) {
        url += "/users/" + settings.userId + "/media/recent";
      }
      else if(settings.locationId != null) {
        url += "/locations/" + settings.locationId + "/media/recent";
      }
      else {
        url += "/media/popular";
      }

      settings.accessToken != null && (params.access_token = settings.accessToken);
      settings.clientId != null && (params.client_id = settings.clientId);
      settings.minId != null && (params.min_id = settings.minId);
      settings.maxId != null && (params.max_id = settings.maxId);

      params.count = 100;

      url += "?" + $.param(params)

      return url;
    }

    settings.onLoad != null && typeof settings.onLoad == 'function' && settings.onLoad();

    $.ajax({
      type: "GET",
      dataType: "jsonp",
      cache: false,
      url: composeRequestURL(),
      success: function(res) {
        var length = typeof res.data != 'undefined' ? res.data.length : 0;
        var limit = settings.show != null && settings.show < length ? settings.show : length;

        if(limit > 0) {
          for(var i = 0; i < limit; i++) {
            that.append(createPhotoElement(res.data[i]));
          }
        }
        else {
          that.append(createEmptyElement());
        }

        settings.onComplete != null && typeof settings.onComplete == 'function' && settings.onComplete(res.data, res);
      }
    });

    return this;
  };
})(jQuery);
<|endoftext|>


<commit_before>$(document).on("turbolinks:load", function(){

  seatingChartContainer = $('.seating-chart_container');
  if (seatingChartContainer) {
    var seatingChart = new SeatingChart(seatingChartContainer);
  }

});

var SeatingChart = function(container) {
  this.seats;
  this.students;
  this.section;
  this.fetchSeats();

  this.seatSide;
  this.container = container;
  this.containerWidth = container.width();
};

SeatingChart.prototype.calculateSeatSide = function(numberOfColumns, containerWidth) {
  this.seatSide = (containerWidth / numberOfColumns)
};

SeatingChart.prototype.fetchSeats = function() {
  var action = window.location.pathname + '/seats';
  var that = this;
  $.ajax({
    url: action,
    method: 'GET',
    dataType: 'json'
  })
  .done(function(response){
    console.log(response)
    that.seats = response.seats;
    that.students = response.students;
    that.section = response.section;
    that.calculateSeatSide(that.section.number_of_columns,that.containerWidth);
    that.renderSeats();
  });
};

SeatingChart.prototype.renderSeats = function() {
  for (let i = 0; i < this.seats.length; i++) {
    seat = this.seats[i]
    // console.log(seat)
    studentName = this.students.filter(function(student){return student.id === seat.student_id})[0].first_name;
    // console.log(student)
    this.container.append(this.renderSeat(seat, studentName));
  };
};

SeatingChart.prototype.renderSeat = function(seat,student) {
  var xDistance = (seat.column_number * this.seatSide).toString() + 'px'
  var yDistance = (seat.row_number * this.seatSide).toString() + 'px'
  return(`

${studentName}

  `);
}
<commit_msg>Refactors seating chart render<commit_after>$(document).on("turbolinks:load", function(){

  var section = new Section($(".seating-chart_container"))

  $(window).resize(function(){
    section.renderSeats();
  });

});

class Section {

  constructor(container) {
    this.section, this.students, this.seats;
    this.dataCollected = false;
    this.fetchData();

    this.containerWidth, this.seatSide;
    this.container = container;
  }

  fetchData() {
    var action, that;
    action = window.location.pathname + '/seats';
    that = this;
    $.ajax({
      url: action,
      method: 'GET',
      dataType: 'json'
    })
    .done(function(response) {
      that.section = response.section;
      that.students = response.students;
      that.seats = response.seats;
      that.dataCollected = true;
      that.renderSeats();
    });
  }

  updateSizing() {
    let cW = this.container.width();
    let sS = cW / this.section.number_of_columns;
    this.containerWidth = cW;
    this.seatSide = sS;
    this.container.height(sS * this.section.number_of_rows);
  }

  renderSeats() {
    this.container.empty();
    this.updateSizing();
    for (let i = 0; i < this.seats.length; i++) {
      let seat = this.seats[i];
      let studentName = this.students.filter(function(student){ return student.id === seat.student_id })[0].first_name;
      this.container.append(this.renderSeat(seat, studentName));
    };
  }

  renderSeat(seat,studentName) {
    let x = (seat.column_number * this.seatSide).toString() + 'px';
    let y = (seat.row_number * this.seatSide).toString() + 'px';
    return(`

${studentName}

    `);
  }

}<|endoftext|>


<commit_before>'use strict';

var _ = require('underscore'),
    View = require('../views/Base');

module.exports = function() {

};
module.exports.prototype = {

  name: 'base',
  rightLevel: -1,

  extend: function(child) {
    return _.extend({}, this, child);
  },

  run: function(action) {
    this.action = action;
    this.view.setTemplate(this.area + '/' + this.name + '/' + action);
    var callFunc = action.replace(/(-[a-z])/g, function(v) { return v.replace(/-/,'').toUpperCase();});
    if (this[callFunc + 'Action']) {
      this[callFunc + 'Action']();
    }
    else {
      var e = new Error('Action "' + callFunc + 'Action" was not found in controller "' + this.name + '"');
      e.code = 'ACTION_NOT_FOUND';
      throw e;
    }
    // can not render view here, because most of the time the db requests are async
  },

  init: function(req, res, next) {

    if (this.rightLevel >= 0) {
      if (!req.session.user) {
        var querystring = require('querystring');
        var escaped = querystring.escape(req.originalUrl);
        res.redirect('/users/log/in?returnto=' + escaped);
        res.end();
      }
      else {
        if (req.session.user.rightLevel > this.rightLevel) {
          res.render('error-rights', {title: 'Keine erforderlichen Rechte'});
        }
      }
    }

    this.request = req;
    this.response = res;
    this.mongodb = req.mongodb;
    this.mongo = req.mongo;

    this.view = new View(this);
    this.view.setOnlyContent(req.param('_view') === 'only_content');
  }
};
<commit_msg>strange<commit_after>'use strict';

var _ = require('underscore'),
    View = require('../views/Base');

module.exports = function() {

};
module.exports.prototype = {

  name: 'base',
  rightLevel: -1,

  extend: function(child) {
    return _.extend({}, this, child);
  },

  run: function(action) {
    this.action = action;
    this.view.setTemplate(this.area + '/' + this.name + '/' + action);
    var callFunc = action.replace(/(-[a-z])/g, function(v) { return v.replace(/-/,'').toUpperCase();});
    if (this[callFunc + 'Action']) {
      this[callFunc + 'Action']();
    }
    else {
      var e = new Error('Action "' + callFunc + 'Action" was not found in controller "' + this.name + '"');
      e.code = 'ACTION_NOT_FOUND';
      throw e;
    }
    // can not render view here, because most of the time the db requests are async
  },

  init: function(req, res, next) {

    if (this.rightLevel >= 0) {
      if (!req.session.user) {
        var querystring = require('querystring');
        var escaped = querystring.escape(req.originalUrl);
        res.redirect('/users/log/in?returnto=' + escaped);
        res.end();
        return;
      }
      else {
        if (req.session.user.rightLevel > this.rightLevel) {
          res.render('error-rights', {title: 'Keine erforderlichen Rechte'});
        }
      }
    }

    this.request = req;
    this.response = res;
    this.mongodb = req.mongodb;
    this.mongo = req.mongo;

    this.view = new View(this);
    this.view.setOnlyContent(req.param('_view') === 'only_content');
  }
};
<|endoftext|>


<commit_before>import child_process from 'child_process';
import fs from 'fs';

export default class ADB {

  constructor() {
    this.device = [];
    this.selected_device;
  }

  version() {

    let child = child_process.spawnSync("adb", ["version"]);
    if(child.stderr && child.stderr.toString() !="") {
      throw new Error(" "+child.stderr);
      return;
    }
    return child.stdout.toString().trim().replace("/\n\r/ig", "");
  }

  devices() {

    let child = child_process.spawnSync("adb", ["devices"]);
    if(child.stderr && child.stderr.toString() !="") {
      throw new Error(" "+child.stderr);
      return;
    }

    let output = child.stdout.toString();
    let match_devices = output.match(/(emulator-)?[\w\d]+\s+device\n/ig);

    if(match_devices == null) return this.device;
    if(!match_devices.length) return this.device;

    for(let k in match_devices) {

      let match_device = match_devices[k].split(/\n/);
      for(let i in match_devices) {
        if(match_devices[i] == "") continue;
        if(!/device/ig.test(match_devices[i])) continue;
        let did = match_devices[i].replace(/\tdevice/ig, "");
            did = did.replace(/\n/ig, "");
        if(this.device.indexOf(did) != -1) continue;

        let device_info = this.deviceInfo(did);
        this.device.push(device_info);
      }
    }

    this.selected_device = this.selected_device || this.device[0];
    return this.device;
  }

  userProcessList(device) {

    if(!this.isDeviceAvailable(device)) {
      throw new Error("No device selected");
      return;
    }
    let child = child_process.spawnSync("adb", ["-s", device, "shell", "ps"]);
    if(child.stderr && child.stderr.toString() !="") {
      throw new Error(" "+child.stderr);
      return;
    }
    let output = child.stdout.toString().split("\r\n");
    let list = [];
    for(let i=0;i<output.length;i++) {
      try {
        let process = output[i];
        if(!/u\d_\w\d+/.test(process)) continue;
        process = process.split(/\s+/);
        process = {
          user : process[0],
          pid : process[1],
          pkg : process[8]
        }
        list.push(process);
      }catch(e){}
    }
    return list;
  }

  deviceInfo(device) {

    let info = {
      id: device
    };

    let child = child_process.spawnSync("adb", ["-s", device, "shell", "getprop", "ro.product.model"]);
    if(child.stderr && child.stderr.toString() !="") {
      throw new Error(" "+child.stderr);
      return;
    }
    info.model = child.stdout.toString().replace("\r\n","");

    child = child_process.spawnSync("adb", ["-s", device, "shell", "getprop", "ro.build.version.release"]);
    if(child.stderr && child.stderr.toString() !="") {
      throw new Error(" "+child.stderr);
      return;
    }
    info.version = child.stdout.toString().replace("\r\n","");
    return info;
  }

  selectDevice(device) {
    this.selected_device = device;
  }

  isPackageInstalled(_package_) {

    let packages = this.listPackages();
    for(let i in packages)
      if(packages[i] == _package_) return true;

    return false;
  }

  promptUninstall(_package_) {

    if(!this.selected_device) {
      throw new Error("No device selected");
      return;
    }
    let did = this.selected_device.id;
    if(!this.isDeviceAvailable(did)) {
      throw new Error("Device no longer available");
      return;
    }

    let params = ["shell", "am" ,"start", "-a", "android.intent.action.DELETE", "-d", "package:"+_package_];
    if(did) {
      params.unshift(did);
      params.unshift("-s");
    }

    let child = child_process.spawnSync("adb", params);
    if(child.stderr && child.stderr.toString() !="") {
      throw new Error(" "+child.stderr);
      return;
    }
    let output = child.stdout.toString().trim().replace("\r\n","");
    return output;
  }

  uninstall(_package_) {

    if(!this.selected_device) {
      throw new Error("No device selected");
      return;
    }
    let did = this.selected_device.id;
    if(!this.isDeviceAvailable(did)) {
      throw new Error("Device no longer available");
      return;
    }

    let params = ["shell", "pm", "uninstall", "-k", _package_];
    if(did) {
      params.unshift(did);
      params.unshift("-s");
    }
    let child = child_process.spawnSync("adb", params);
    return !this.isPackageInstalled(_package_);

  }

  install(apk_path, _package_) {

    if(!this.selected_device) {
      throw new Error("No device selected");
      return;
    }
    let did = this.selected_device.id;
    if(!this.isDeviceAvailable(did)) {
      throw new Error("Device no longer available");
      return;
    }

    if(!fs.existsSync(apk_path)) throw new Error("Apk file not found!");

    let params = ["install", apk_path];
    if(did) {
      params.unshift(did);
      params.unshift("-s");
    }
    let child = child_process.spawnSync("adb", params);
    return this.isPackageInstalled(_package_);
  }

  packageInfo(_package_) {

    if(!this.selected_device) {
      throw new Error("No device selected");
      return;
    }
    let did = this.selected_device.id;
    if(!this.isDeviceAvailable(did)) {
      throw new Error("Device no longer available");
      return;
    }

    let params = ["shell", "dumpsys", "package", _package_];
    if(did) {
      params.unshift(did);
      params.unshift("-s");
    }
    let child = child_process.spawnSync("adb", params);
    if(child.stderr && child.stderr.toString() !="") {
      throw new Error(" "+child.stderr);
    }

    let output = child.stdout.toString().trim().replace("/\r\n/ig");
    if(output == "")
      throw new Error("Package not found");

    let info = {
      id: _package_
    }
    info.versionCode = output.match(/versionCode=\d+/)[0].replace(/versionCode=/,"");
    info.versionName = output.match(/versionName=[\d\.\w]+/)[0].replace(/versionName=/,"");
    info.targetSdk = output.match(/targetSdk=\d+/)[0].replace(/targetSdk=/,"");
    return info;
  }

  isAppRunning(_package_) {

    if(!this.selected_device) {
      throw new Error("No device selected");
      return;
    }
    let did = this.selected_device.id;
    if(!this.isDeviceAvailable(did)) {
      throw new Error("Device no longer available");
      return;
    }

    let params = ["shell" ,"ps"];
    if(did) {
      params.unshift(did);
      params.unshift("-s");
    }

    let child = child_process.spawnSync("adb", params);
    if(child.stderr && child.stderr.toString() !="") {
      throw new Error(" "+child.stderr);
    }

    let output = child.stdout.toString();
    return output.indexOf(_package_) != -1 ? true : false;
  }

  closeApp(_package_) {

    if(!this.selected_device) {
      throw new Error("No device selected");
      return;
    }
    let did = this.selected_device.id;
    if(!this.isDeviceAvailable(did)) {
      throw new Error("Device no longer available");
      return;
    }

    let params = ["shell" ,"am", "force-stop", _package_];
    if(did) {
      params.unshift(did);
      params.unshift("-s");
    }

    let child = child_process.spawnSync("adb", params);
    if(child.stderr && child.stderr.toString() !="") {
      throw new Error(" "+child.stderr);
    }
  }

  listPackages() {

    if(!this.selected_device) {
      throw new Error("No device selected");
      return;
    }
    let did = this.selected_device.id;
    if(!this.isDeviceAvailable(did)) {
      throw new Error("Device no longer available");
      return;
    }

    let params = ["shell" ,"pm", "list", "packages"];
    if(did) {
      params.unshift(did);
      params.unshift("-s");
    }

    let child = child_process.spawnSync("adb", params);
    if(child.stderr && child.stderr.toString() !="") {
      throw new Error(" "+child.stderr);
      return;
    }

    let output = child.stdout.toString();
    let list = output.split(/\n/);

    let packages = [];
    if(!list.length) return packages;
    for(let i in list) {

      if(list[i] == "") continue;

      let pkg = list[i];
          pkg = pkg.replace("package:","");
          pkg = pkg.replace(/\r/,"");

      packages.push(pkg);
    }

    return packages;
  }

  isDeviceAvailable(device_id) {
    try {
      let devices = this.devices();
      for(let i in devices)
        if(devices[i].id == device_id)
          return true;

    }catch(e) {}
    return false;
  }

};
<commit_msg>debug adb version<commit_after>import child_process from 'child_process';
import fs from 'fs';

export default class ADB {

  constructor() {
    this.device = [];
    this.selected_device;
  }

  version() {

    let child = child_process.spawnSync("adb", ["version"]);
    if(child.stderr && child.stderr.toString() !="") {
      throw new Error(" "+child.stderr);
      return;
    }
    let output = child.stdout;
    console.log(" "+ output);
    return child.stdout.toString().trim().replace("/\n\r/ig", "");
  }

  devices() {

    let child = child_process.spawnSync("adb", ["devices"]);
    if(child.stderr && child.stderr.toString() !="") {
      throw new Error(" "+child.stderr);
      return;
    }

    let output = child.stdout.toString();
    let match_devices = output.match(/(emulator-)?[\w\d]+\s+device\n/ig);

    if(match_devices == null) return this.device;
    if(!match_devices.length) return this.device;

    for(let k in match_devices) {

      let match_device = match_devices[k].split(/\n/);
      for(let i in match_devices) {
        if(match_devices[i] == "") continue;
        if(!/device/ig.test(match_devices[i])) continue;
        let did = match_devices[i].replace(/\tdevice/ig, "");
            did = did.replace(/\n/ig, "");
        if(this.device.indexOf(did) != -1) continue;

        let device_info = this.deviceInfo(did);
        this.device.push(device_info);
      }
    }

    this.selected_device = this.selected_device || this.device[0];
    return this.device;
  }

  userProcessList(device) {

    if(!this.isDeviceAvailable(device)) {
      throw new Error("No device selected");
      return;
    }
    let child = child_process.spawnSync("adb", ["-s", device, "shell", "ps"]);
    if(child.stderr && child.stderr.toString() !="") {
      throw new Error(" "+child.stderr);
      return;
    }
    let output = child.stdout.toString().split("\r\n");
    let list = [];
    for(let i=0;i<output.length;i++) {
      try {
        let process = output[i];
        if(!/u\d_\w\d+/.test(process)) continue;
        process = process.split(/\s+/);
        process = {
          user : process[0],
          pid : process[1],
          pkg : process[8]
        }
        list.push(process);
      }catch(e){}
    }
    return list;
  }

  deviceInfo(device) {

    let info = {
      id: device
    };

    let child = child_process.spawnSync("adb", ["-s", device, "shell", "getprop", "ro.product.model"]);
    if(child.stderr && child.stderr.toString() !="") {
      throw new Error(" "+child.stderr);
      return;
    }
    info.model = child.stdout.toString().replace("\r\n","");

    child = child_process.spawnSync("adb", ["-s", device, "shell", "getprop", "ro.build.version.release"]);
    if(child.stderr && child.stderr.toString() !="") {
      throw new Error(" "+child.stderr);
      return;
    }
    info.version = child.stdout.toString().replace("\r\n","");
    return info;
  }

  selectDevice(device) {
    this.selected_device = device;
  }

  isPackageInstalled(_package_) {

    let packages = this.listPackages();
    for(let i in packages)
      if(packages[i] == _package_) return true;

    return false;
  }

  promptUninstall(_package_) {

    if(!this.selected_device) {
      throw new Error("No device selected");
      return;
    }
    let did = this.selected_device.id;
    if(!this.isDeviceAvailable(did)) {
      throw new Error("Device no longer available");
      return;
    }

    let params = ["shell", "am" ,"start", "-a", "android.intent.action.DELETE", "-d", "package:"+_package_];
    if(did) {
      params.unshift(did);
      params.unshift("-s");
    }

    let child = child_process.spawnSync("adb", params);
    if(child.stderr && child.stderr.toString() !="") {
      throw new Error(" "+child.stderr);
      return;
    }
    let output = child.stdout.toString().trim().replace("\r\n","");
    return output;
  }

  uninstall(_package_) {

    if(!this.selected_device) {
      throw new Error("No device selected");
      return;
    }
    let did = this.selected_device.id;
    if(!this.isDeviceAvailable(did)) {
      throw new Error("Device no longer available");
      return;
    }

    let params = ["shell", "pm", "uninstall", "-k", _package_];
    if(did) {
      params.unshift(did);
      params.unshift("-s");
    }
    let child = child_process.spawnSync("adb", params);
    return !this.isPackageInstalled(_package_);

  }

  install(apk_path, _package_) {

    if(!this.selected_device) {
      throw new Error("No device selected");
      return;
    }
    let did = this.selected_device.id;
    if(!this.isDeviceAvailable(did)) {
      throw new Error("Device no longer available");
      return;
    }

    if(!fs.existsSync(apk_path)) throw new Error("Apk file not found!");

    let params = ["install", apk_path];
    if(did) {
      params.unshift(did);
      params.unshift("-s");
    }
    let child = child_process.spawnSync("adb", params);
    return this.isPackageInstalled(_package_);
  }

  packageInfo(_package_) {

    if(!this.selected_device) {
      throw new Error("No device selected");
      return;
    }
    let did = this.selected_device.id;
    if(!this.isDeviceAvailable(did)) {
      throw new Error("Device no longer available");
      return;
    }

    let params = ["shell", "dumpsys", "package", _package_];
    if(did) {
      params.unshift(did);
      params.unshift("-s");
    }
    let child = child_process.spawnSync("adb", params);
    if(child.stderr && child.stderr.toString() !="") {
      throw new Error(" "+child.stderr);
    }

    let output = child.stdout.toString().trim().replace("/\r\n/ig");
    if(output == "")
      throw new Error("Package not found");

    let info = {
      id: _package_
    }
    info.versionCode = output.match(/versionCode=\d+/)[0].replace(/versionCode=/,"");
    info.versionName = output.match(/versionName=[\d\.\w]+/)[0].replace(/versionName=/,"");
    info.targetSdk = output.match(/targetSdk=\d+/)[0].replace(/targetSdk=/,"");
    return info;
  }

  isAppRunning(_package_) {

    if(!this.selected_device) {
      throw new Error("No device selected");
      return;
    }
    let did = this.selected_device.id;
    if(!this.isDeviceAvailable(did)) {
      throw new Error("Device no longer available");
      return;
    }

    let params = ["shell" ,"ps"];
    if(did) {
      params.unshift(did);
      params.unshift("-s");
    }

    let child = child_process.spawnSync("adb", params);
    if(child.stderr && child.stderr.toString() !="") {
      throw new Error(" "+child.stderr);
    }

    let output = child.stdout.toString();
    return output.indexOf(_package_) != -1 ? true : false;
  }

  closeApp(_package_) {

    if(!this.selected_device) {
      throw new Error("No device selected");
      return;
    }
    let did = this.selected_device.id;
    if(!this.isDeviceAvailable(did)) {
      throw new Error("Device no longer available");
      return;
    }

    let params = ["shell" ,"am", "force-stop", _package_];
    if(did) {
      params.unshift(did);
      params.unshift("-s");
    }

    let child = child_process.spawnSync("adb", params);
    if(child.stderr && child.stderr.toString() !="") {
      throw new Error(" "+child.stderr);
    }
  }

  listPackages() {

    if(!this.selected_device) {
      throw new Error("No device selected");
      return;
    }
    let did = this.selected_device.id;
    if(!this.isDeviceAvailable(did)) {
      throw new Error("Device no longer available");
      return;
    }

    let params = ["shell" ,"pm", "list", "packages"];
    if(did) {
      params.unshift(did);
      params.unshift("-s");
    }

    let child = child_process.spawnSync("adb", params);
    if(child.stderr && child.stderr.toString() !="") {
      throw new Error(" "+child.stderr);
      return;
    }

    let output = child.stdout.toString();
    let list = output.split(/\n/);

    let packages = [];
    if(!list.length) return packages;
    for(let i in list) {

      if(list[i] == "") continue;

      let pkg = list[i];
          pkg = pkg.replace("package:","");
          pkg = pkg.replace(/\r/,"");

      packages.push(pkg);
    }

    return packages;
  }

  isDeviceAvailable(device_id) {
    try {
      let devices = this.devices();
      for(let i in devices)
        if(devices[i].id == device_id)
          return true;

    }catch(e) {}
    return false;
  }

};
<|endoftext|>


<commit_before>Template.newReport.onCreated(trackPageView);
Template.newReport.onRendered(function() {
  const taginput = makeTagInput('#new-report-stop-view', {
    type: 'stop'
  });
  taginput.on('itemRemoved', function(evt) {
    Router.current().state.set('new-report-stops', []);
    Router.current().state.set('new-report-lines', []);
  });
  this.autorun(() => updateSelectedStopInput(taginput));

  TagSubs.subscribe('tagLabelsWithTypes');
});

Template.newReport.helpers({
  seenHint() {
    return Session.get('user has seen the new report hint');
  },
  isStopSelected() {
     return Router.current().state.get('new-report-stops').length;
  },
  getTagName: function(key) {
    return Tags.findOne({key}).name;
  },
  fav: function(key) {
    return isFav(key) ?
      'nj-tag--fav' : null;
  },
});

Template.newReport.events({
  'click .nj-new-report__understood': function(evt) {
    evt.preventDefault();
    Session.setPersistent('user has seen the new report hint', true);
  },
  'keyup [type="text"]': function(_, template) {
    checkValid(template.find('form'));
  },
  'click .nj-new-report__select-stop': function(evt) {
    Router.current().state.set('modal-stop-active', true);
  },
  'click .nj-new-report__select-lines': function(evt) {
    Router.current().state.set('modal-lines-active', true);
  },
  'click .nj-new-report__lines .nj-tag__remove': function(evt) {
    const dir = evt.currentTarget.parentNode.dataset.dir;
    const state = Router.current().state;
    const lines = state.get('new-report-lines');
    const pos = lines.indexOf(dir);
    Router.current().state.set('new-report-lines',
      [...lines.slice(0, pos), ...lines.slice(pos + 1)]);
  },
  'submit form': function(evt) {
    evt.preventDefault();
    const state = Router.current().state;
    Meteor.call(
      'createReport',
      evt.target['new-report-text'].value,
      [...state.get('new-report-stops'), ...state.get('new-report-lines')]
    );
    queuedToasts.push([pickRandom(toasts.created)]);
    Router.go('feed.all');
  },
});

/* Select stop modal */

Template.newReportStop.onRendered(function() {
  const taginput = makeTagInput('#new-report-stop-edit', {
    type: 'stop'
  });
  $('.nj-new-report-stop .tt-input').focus();
  taginput.on('itemAdded', function(evt) {
    Router.current().state.set('new-report-stops', [evt.item.key]);
    Router.current().state.set('modal-stop-active', false);
  });

  updateSelectedStopInput(taginput);
});

Template.newReportStop.events({
  'click .nj-new-report-stop__back': function(evt, template) {
    Router.current().state.set('modal-stop-active', false);
  },
});

/* Select lines modal */

Template.newReportLines.onCreated(function() {
  const [stopKey] = Router.current().state.get('new-report-stops');
  this.subscribe('stopData', stopKey);

  const state = Router.current().state;
  state.set('new-report-lines-selecting',
    state.get('new-report-lines'));
});

Template.newReportLines.helpers({
  stop() {
    const [key] = Router.current().state.get('new-report-stops');
    return Tags.findOne({key});
  },
  getDirName: function(key) {
    return Tags.findOne({key}).name;
  },
  selected: function(key) {
    const allSelected = Router.current().state
      .get('new-report-lines-selecting');
    return contains(allSelected, key) ?
      'nj-new-report-lines__dir--selected' : null;
  },
  fav: function(key) {
    return isFav(key) ?
      'nj-tag--fav' : null;
  }
});

Template.newReportLines.events({
  'click .nj-new-report-lines__back': function(evt, template) {
    const state = Router.current().state;
    state.set('new-report-lines-selecting', []);
    state.set('modal-lines-active', false);
  },
  'click .nj-new-report-lines__done': function(evt, template) {
    const state = Router.current().state;
    state.set('new-report-lines', state.get('new-report-lines-selecting'));
    state.set('new-report-lines-selecting', []);
    state.set('modal-lines-active', false);
  },
  'click .nj-new-report-lines__dir': function(evt) {
    const state = Router.current().state;
    const key = evt.currentTarget.dataset.dir;
    const prev = state.get('new-report-lines-selecting');
    if (contains(prev, key)) {
      const pos = prev.indexOf(key);
      state.set('new-report-lines-selecting',
        [...prev.slice(0, pos), ...prev.slice(pos + 1)]);
    } else {
      state.set('new-report-lines-selecting', [...prev, key]);
    }
  },
  ['click .mdl-collapse__trigger'](evt) {
    $(evt.currentTarget)
      .parents('.mdl-collapse')
      .toggleClass('mdl-collapse--opened');
  }
});
<commit_msg>seen-new-report-hint-1<commit_after>Template.newReport.onCreated(trackPageView);
Template.newReport.onRendered(function() {
  const taginput = makeTagInput('#new-report-stop-view', {
    type: 'stop'
  });
  taginput.on('itemRemoved', function(evt) {
    Router.current().state.set('new-report-stops', []);
    Router.current().state.set('new-report-lines', []);
  });
  this.autorun(() => updateSelectedStopInput(taginput));

  TagSubs.subscribe('tagLabelsWithTypes');
});

Template.newReport.helpers({
  seenHint() {
    return Meteor.user().profile['seen-new-report-hint-1'];
  },
  isStopSelected() {
     return Router.current().state.get('new-report-stops').length;
  },
  getTagName: function(key) {
    return Tags.findOne({key}).name;
  },
  fav: function(key) {
    return isFav(key) ?
      'nj-tag--fav' : null;
  },
});

Template.newReport.events({
  'click .nj-new-report__understood': function(evt) {
    evt.preventDefault();
    Meteor.users.update(Meteor.userId(), {
      $set: {
        'profile.seen-new-report-hint-1': true
      }
    });
  },
  'keyup [type="text"]': function(_, template) {
    checkValid(template.find('form'));
  },
  'click .nj-new-report__select-stop': function(evt) {
    Router.current().state.set('modal-stop-active', true);
  },
  'click .nj-new-report__select-lines': function(evt) {
    Router.current().state.set('modal-lines-active', true);
  },
  'click .nj-new-report__lines .nj-tag__remove': function(evt) {
    const dir = evt.currentTarget.parentNode.dataset.dir;
    const state = Router.current().state;
    const lines = state.get('new-report-lines');
    const pos = lines.indexOf(dir);
    Router.current().state.set('new-report-lines',
      [...lines.slice(0, pos), ...lines.slice(pos + 1)]);
  },
  'submit form': function(evt) {
    evt.preventDefault();
    const state = Router.current().state;
    Meteor.call(
      'createReport',
      evt.target['new-report-text'].value,
      [...state.get('new-report-stops'), ...state.get('new-report-lines')]
    );
    queuedToasts.push([pickRandom(toasts.created)]);
    Router.go('feed.all');
  },
});

/* Select stop modal */

Template.newReportStop.onRendered(function() {
  const taginput = makeTagInput('#new-report-stop-edit', {
    type: 'stop'
  });
  $('.nj-new-report-stop .tt-input').focus();
  taginput.on('itemAdded', function(evt) {
    Router.current().state.set('new-report-stops', [evt.item.key]);
    Router.current().state.set('modal-stop-active', false);
  });

  updateSelectedStopInput(taginput);
});

Template.newReportStop.events({
  'click .nj-new-report-stop__back': function(evt, template) {
    Router.current().state.set('modal-stop-active', false);
  },
});

/* Select lines modal */

Template.newReportLines.onCreated(function() {
  const [stopKey] = Router.current().state.get('new-report-stops');
  this.subscribe('stopData', stopKey);

  const state = Router.current().state;
  state.set('new-report-lines-selecting',
    state.get('new-report-lines'));
});

Template.newReportLines.helpers({
  stop() {
    const [key] = Router.current().state.get('new-report-stops');
    return Tags.findOne({key});
  },
  getDirName: function(key) {
    return Tags.findOne({key}).name;
  },
  selected: function(key) {
    const allSelected = Router.current().state
      .get('new-report-lines-selecting');
    return contains(allSelected, key) ?
      'nj-new-report-lines__dir--selected' : null;
  },
  fav: function(key) {
    return isFav(key) ?
      'nj-tag--fav' : null;
  }
});

Template.newReportLines.events({
  'click .nj-new-report-lines__back': function(evt, template) {
    const state = Router.current().state;
    state.set('new-report-lines-selecting', []);
    state.set('modal-lines-active', false);
  },
  'click .nj-new-report-lines__done': function(evt, template) {
    const state = Router.current().state;
    state.set('new-report-lines', state.get('new-report-lines-selecting'));
    state.set('new-report-lines-selecting', []);
    state.set('modal-lines-active', false);
  },
  'click .nj-new-report-lines__dir': function(evt) {
    const state = Router.current().state;
    const key = evt.currentTarget.dataset.dir;
    const prev = state.get('new-report-lines-selecting');
    if (contains(prev, key)) {
      const pos = prev.indexOf(key);
      state.set('new-report-lines-selecting',
        [...prev.slice(0, pos), ...prev.slice(pos + 1)]);
    } else {
      state.set('new-report-lines-selecting', [...prev, key]);
    }
  },
  ['click .mdl-collapse__trigger'](evt) {
    $(evt.currentTarget)
      .parents('.mdl-collapse')
      .toggleClass('mdl-collapse--opened');
  }
});
<|endoftext|>


<commit_before>/**
 * Lazy loading
 * Initialize and handle layloading of images
 *
 * Uses echo.js plugin
 */

var lazyload = {

	/**
	 * Init lazyloading of images via customized Echo.js method.
	 * Runs Resrc when image is in viewport and js-resrcIsLazy class is set.
	 * Runs 'normal' echo.js scripts when js-resrcIsLazy is not set.
	 * Add a is-loading and is-loaded class on loading and done.
	 *
	 * Make sure the modified echo.js plugin is included in your gruntfile.
	 */
	init: function() {

		lazyload.bindResrcToWindow();

		var lazyimages = document.querySelectorAll('img[data-src]');

		for (var i = 0; i < lazyimages.length; i++) {
			if(lazyimages[i].classList.contains('js-resrcNotLazy') === true) {
				lazyload.runResrcNonLazy(lazyimages[i]);
			}
			else {
				lazyload.elementLoading(lazyimages[i]);
			}
		}

		/* Use echo.js plugin */
		echo.init({
			offset: 88,
			throttle: 250, // Using a throttle will set a small timeout when the user scrolls and will keep throttling until the user stops. The default is 250 milliseconds.
			debounce: false, // By default the throttling function is actually a debounce function so that the checking function is only triggered after a user stops scrolling. To use traditional throttling where it will only check the images every throttle milliseconds, set debounce to false.
			unload: false,
			selector: 'data-src',
			callback: function(element){
				if(element.classList.contains('js-resrcIsLazy') === true && typeof(window.resrc.run) !== 'undefined') {
					window.resrc.run(element);
				}
				lazyload.elementLoaded(element);
			}
		});
	},

	/**
	 * Bind ReSrc variable to window, to use it everywhere
	 */
	bindResrcToWindow: function() {
		// var resrc; // this should be disabled, so resrc can be inherited!
		if(typeof resrc === 'undefined') {
			// Set resrc to false if it's not loaded (on local for example)
			resrc = false;
		}
		window.resrc = resrc;
	},

	/**
	 * Get Resrc url and replace the src with that url
	 * Will run Resrc for elements with the .resrc class, needs data-src attribute
	 * @param  {DOM node} element the image element
	 */
	runResrcNonLazy: function(element) {
		// Only run if resrc is set by bindResrcToWindow
		if(typeof window.resrc.run !== 'undefined') {
			// Use ReSRC to get the path
			path = window.resrc.getResrcImageObject(element).resrcImgPath;
			// Replace src
			element.setAttribute('src', path);
			// Remove data-src so lazyload (echo) will not load it again
			element.removeAttribute('data-src');
		}
	},

	elementLoading: function(element) {
		var parent = domparents.findAncestorByClass(element, 'FigureImage');
		parent.classList.add('is-loading');
	},

	elementLoaded: function(element) {
		var parent = domparents.findAncestorByClass(element, 'FigureImage');
		parent.classList.remove('is-loading');
		parent.classList.add('is-loaded');
	},

	/**
	 * Defer loading of videos's, loop all videos and fire deferVideo function
	 */
	initDeferVideos: function() {
		var deferredvideos = document.querySelectorAll('iframe[data-deferred-src]');
		// console.log(deferredvideos);
		for (var i = 0; i < deferredvideos.length; i++) {
			lazyload.deferVideo(deferredvideos[i]);
		}
	},

	/**
	 * Deferred loading of video, replace the src by the data attribute
	 * @param  {DOM node} element the video element
	 */
	deferVideo: function(element) {
		var src = element.getAttribute('data-deferred-src');
		element.setAttribute('src',src);
	}

};
<commit_msg>Set lazyload to debounce (instead of throttle) and increase offset.<commit_after>/**
 * Lazy loading
 * Initialize and handle layloading of images
 *
 * Uses echo.js plugin
 */

var lazyload = {

	/**
	 * Init lazyloading of images via customized Echo.js method.
	 * Runs Resrc when image is in viewport and js-resrcIsLazy class is set.
	 * Runs 'normal' echo.js scripts when js-resrcIsLazy is not set.
	 * Add a is-loading and is-loaded class on loading and done.
	 *
	 * Make sure the modified echo.js plugin is included in your gruntfile.
	 */
	init: function() {

		lazyload.bindResrcToWindow();

		var lazyimages = document.querySelectorAll('img[data-src]');

		for (var i = 0; i < lazyimages.length; i++) {
			if(lazyimages[i].classList.contains('js-resrcNotLazy') === true) {
				lazyload.runResrcNonLazy(lazyimages[i]);
			}
			else {
				lazyload.elementLoading(lazyimages[i]);
			}
		}

		/* Use echo.js plugin */
		echo.init({
			offset: 512,
			throttle: 250, // Using a throttle will set a small timeout when the user scrolls and will keep throttling until the user stops. The default is 250 milliseconds.
			debounce: true, // By default the throttling function is actually a debounce function so that the checking function is only triggered after a user stops scrolling. To use traditional throttling where it will only check the images every throttle milliseconds, set debounce to false.
			unload: false,
			selector: 'data-src',
			callback: function(element){
				if(element.classList.contains('js-resrcIsLazy') === true && typeof(window.resrc.run) !== 'undefined') {
					window.resrc.run(element);
				}
				lazyload.elementLoaded(element);
			}
		});
	},

	/**
	 * Bind ReSrc variable to window, to use it everywhere
	 */
	bindResrcToWindow: function() {
		// var resrc; // this should be disabled, so resrc can be inherited!
		if(typeof resrc === 'undefined') {
			// Set resrc to false if it's not loaded (on local for example)
			resrc = false;
		}
		window.resrc = resrc;
	},

	/**
	 * Get Resrc url and replace the src with that url
	 * Will run Resrc for elements with the .resrc class, needs data-src attribute
	 * @param  {DOM node} element the image element
	 */
	runResrcNonLazy: function(element) {
		// Only run if resrc is set by bindResrcToWindow
		if(typeof window.resrc.run !== 'undefined') {
			// Use ReSRC to get the path
			path = window.resrc.getResrcImageObject(element).resrcImgPath;
			// Replace src
			element.setAttribute('src', path);
			// Remove data-src so lazyload (echo) will not load it again
			element.removeAttribute('data-src');
		}
	},

	elementLoading: function(element) {
		var parent = domparents.findAncestorByClass(element, 'FigureImage');
		parent.classList.add('is-loading');
	},

	elementLoaded: function(element) {
		var parent = domparents.findAncestorByClass(element, 'FigureImage');
		parent.classList.remove('is-loading');
		parent.classList.add('is-loaded');
	},

	/**
	 * Defer loading of videos's, loop all videos and fire deferVideo function
	 */
	initDeferVideos: function() {
		var deferredvideos = document.querySelectorAll('iframe[data-deferred-src]');
		// console.log(deferredvideos);
		for (var i = 0; i < deferredvideos.length; i++) {
			lazyload.deferVideo(deferredvideos[i]);
		}
	},

	/**
	 * Deferred loading of video, replace the src by the data attribute
	 * @param  {DOM node} element the video element
	 */
	deferVideo: function(element) {
		var src = element.getAttribute('data-deferred-src');
		element.setAttribute('src',src);
	}

};
<|endoftext|>


<commit_before>var Base = require('../core/Base');
var AssertionHelper = require('./AssertionHelper');
var _ = require('lodash');
var zombie = require('zombie');
var Mocha = require('mocha');
var npath = require('path');
var child = require('child_process');
var Loader = require('../core/Loader');
var createUID = require('../../node_modules/wunderbits.core/public/lib/createUID');

function getRandomInt (min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

var _super = Base.prototype;
var mocha = new Mocha();

var port = getRandomInt(3000, 3999);
var server, started, _server;

function start () {
  _server = child.exec('PORT=' + port + ' LEGACY_RENDER=true node main.js');
  started = (new Date()).valueOf();
}

module.exports = Base.extend({

  // TODO: this has to be done better - we need to just wait until it's all rendered, the server must emit an event - probably gonna have to use child.spawn, and mute the logger instead of child.exec
  'serverDelay': process.env.TRAVIS ? 10000 : 5000,

  'initialize': function () {

    var self = this;
    _super.initialize.apply(self, arguments);

    self.options.tempPath = npath.join(process.cwd(), 'tests/temp');

    self.itShould = new AssertionHelper({
      'test': self
    });

    if (!server) {

      server = self.deferred();
      start();
      var lapsed = (new Date()).valueOf() - started;
      var delay = self.serverDelay - lapsed;
      setTimeout(function () {
        server.resolve();
      }, delay);
    }
  },

  'writeTempFile': function (path, content) {

    var self = this;

    if (!path || typeof path !== 'string') {
      throw new Error('Cannot write temporary file, invalid path @ ' + path);
    }

    if (!content) {
      throw new Error('Cannot write temporary file, no content provided @ ' + path);
    }

    var tempPath = self.options.tempPath;
    path = npath.join(tempPath, path);

    self.filesystem.forceExists(tempPath);
    return self.filesystem.writeFile(path, content);
  },

  'getTempFilename': function () {

    return createUID();
  },

  'removeTempFile': function (path, wait) {

    var self = this;

    if (wait !== false) {
      wait = true;
    }

    if (!path || typeof path !== 'string') {
      throw new Error('Cannot remove temporary file, invalid path @ ' + path);
    }

    var tempPath = self.options.tempPath;
    path = npath.join(tempPath, path);

    if (wait && !self.filesystem.pathExists(path)) {
      return setTimeout(function () {
        self.removeTempFile(path, wait);
      }, 100);
    }

    self.filesystem.forceExists(tempPath);
    return self.filesystem.recursiveDelete(path);
  },

  'before': function (callback) {

    return before(callback);
  },

  'beforeEach': function (callback) {

    return beforeEach(callback);
  },

  'after': function (callback) {

    return after(callback);
  },

  'afterEach': function (callback) {

    return afterEach(callback);
  },

  'when': function (name, callback) {

    var self = this;
    return describe('when ' + name, callback);
  },

  'spec': function (name, callback) {

    var self = this;

    if (!process.env.LEGACY_RENDER) {
      name = name.grey.inverse.bold;
    }

    return describe(name, callback);
  },

  'it': function (message, callback) {

    var self = this;

    if (!message || typeof message !== 'string') {
      throw new Error('Message is not a string');
    }

    if (message.indexOf('it') !== 0) {
      message = 'it ' + message;
    }

    return it.call(global, message, callback);
  },

  'integration': function (url, callback) {

    var self = this;

    if (!url || typeof url !== 'string') {
      throw new Error('Message is not a string');
    }

    if (!callback || typeof callback !== 'function') {
      return;
    }

    if (url.indexOf('http') < 0) {
      url = 'http://localhost:' + port + url;
    }

    var displayUrl = process.env.LEGACY_RENDER ? url : url.grey.inverse.bold;

    return describe(displayUrl, function () {

      this.timeout(self.serverDelay * 2);

      before(function (done) {

        var _self = this;

        server.done(function () {
          _self.browser = new zombie();
          _self.browser.visit(url, done);
        });
      });

      return (function () {

        return callback.apply(global, arguments);
      })();
    });
  }
});<commit_msg>force temp path<commit_after>var Base = require('../core/Base');
var AssertionHelper = require('./AssertionHelper');
var _ = require('lodash');
var zombie = require('zombie');
var Mocha = require('mocha');
var npath = require('path');
var child = require('child_process');
var Loader = require('../core/Loader');
var createUID = require('../../node_modules/wunderbits.core/public/lib/createUID');

function getRandomInt (min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

var _super = Base.prototype;
var mocha = new Mocha();

var port = getRandomInt(3000, 3999);
var server, started, _server;

function start () {
  _server = child.exec('PORT=' + port + ' LEGACY_RENDER=true node main.js');
  started = (new Date()).valueOf();
}

module.exports = Base.extend({

  // TODO: this has to be done better - we need to just wait until it's all rendered, the server must emit an event - probably gonna have to use child.spawn, and mute the logger instead of child.exec
  'serverDelay': process.env.TRAVIS ? 10000 : 5000,

  'initialize': function () {

    var self = this;
    _super.initialize.apply(self, arguments);

    var tempPath = self.options.tempPath = npath.join(process.cwd(), 'tests/temp');
    self.filesystem.forceExists(tempPath);

    self.itShould = new AssertionHelper({
      'test': self
    });

    if (!server) {

      server = self.deferred();
      start();
      var lapsed = (new Date()).valueOf() - started;
      var delay = self.serverDelay - lapsed;
      setTimeout(function () {
        server.resolve();
      }, delay);
    }
  },

  'writeTempFile': function (path, content) {

    var self = this;

    if (!path || typeof path !== 'string') {
      throw new Error('Cannot write temporary file, invalid path @ ' + path);
    }

    if (!content) {
      throw new Error('Cannot write temporary file, no content provided @ ' + path);
    }

    var tempPath = self.options.tempPath;
    path = npath.join(tempPath, path);

    return self.filesystem.writeFile(path, content);
  },

  'getTempFilename': function () {

    return createUID();
  },

  'removeTempFile': function (path, wait) {

    var self = this;

    if (wait !== false) {
      wait = true;
    }

    if (!path || typeof path !== 'string') {
      throw new Error('Cannot remove temporary file, invalid path @ ' + path);
    }

    var tempPath = self.options.tempPath;
    path = npath.join(tempPath, path);

    if (wait && !self.filesystem.pathExists(path)) {
      return setTimeout(function () {
        self.removeTempFile(path, wait);
      }, 100);
    }

    return self.filesystem.recursiveDelete(path);
  },

  'before': function (callback) {

    return before(callback);
  },

  'beforeEach': function (callback) {

    return beforeEach(callback);
  },

  'after': function (callback) {

    return after(callback);
  },

  'afterEach': function (callback) {

    return afterEach(callback);
  },

  'when': function (name, callback) {

    var self = this;
    return describe('when ' + name, callback);
  },

  'spec': function (name, callback) {

    var self = this;

    if (!process.env.LEGACY_RENDER) {
      name = name.grey.inverse.bold;
    }

    return describe(name, callback);
  },

  'it': function (message, callback) {

    var self = this;

    if (!message || typeof message !== 'string') {
      throw new Error('Message is not a string');
    }

    if (message.indexOf('it') !== 0) {
      message = 'it ' + message;
    }

    return it.call(global, message, callback);
  },

  'integration': function (url, callback) {

    var self = this;

    if (!url || typeof url !== 'string') {
      throw new Error('Message is not a string');
    }

    if (!callback || typeof callback !== 'function') {
      return;
    }

    if (url.indexOf('http') < 0) {
      url = 'http://localhost:' + port + url;
    }

    var displayUrl = process.env.LEGACY_RENDER ? url : url.grey.inverse.bold;

    return describe(displayUrl, function () {

      this.timeout(self.serverDelay * 2);

      before(function (done) {

        var _self = this;

        server.done(function () {
          _self.browser = new zombie();
          _self.browser.visit(url, done);
        });
      });

      return (function () {

        return callback.apply(global, arguments);
      })();
    });
  }
});<|endoftext|>


<commit_before>/*
 	scrollr standalone - v0.0.1 (doesn't use TweenMax or hammer.js)
 	jQuery plugin for scrolling or dragging through an array of images
	by Robert Bue (@robert_bue)

 	Dual licensed under MIT and GPL.
 */

;(function ( $, window, document, undefined ) {

    var pluginName = "scrollr",
        dataPlugin = "plugin_" + pluginName,

        // default options
        defaults = {
			offset : 0,
            fade : false,
            autoHandle: true,
            minHandleHeight: 35,
            maxHandleHeight: 9999999
		};

    var Plugin = function ( element, options ) {

        this.element = element;
        //console.log(element);
        this.settings = $.extend( {}, defaults, options );
        this._defaults = defaults;
        this._name = pluginName;
        this.build();
        this.events();
    };

    Plugin.prototype.build = function () {
        var self = this;

        self.settings = this.settings,
        self.target = $(self.element),
        self.targetWidth = self.target.width(),
        self.targetHeight = self.target.height(),
        self.ticker = 0,
        self.scrollTop = 0,
        self.scrolling = false,
        self.totalHeight = 0;
        self.timer = null;

        // Wheel events
        //self.wheelEvents = ( 'onwheel' in document || document.documentMode >= 9 ) ? ['wheel'] : ['mousewheel', 'DomMouseScroll', 'MozMousePixelScroll'];
        self.wheelEvents = ( 'onwheel' in document || document.documentMode >= 9 ) ? 'wheel' : 'mousewheel DOMMouseScroll MozMousePixelScroll';
        // webkitDirectionInvertedFromDevice

        // Key events
        //var hasKeyDown = 'onkeydown' in document;
        self.keyEvents = "keydown";
        //self.keyEvents = ( 'onkeydown' in document ) ? "onkeydown" : "keydown";

        // Mouse events
        //self.mouseEvents = "mousedown touchstart";
        self.mouseEvents = [
        'touchstart mousedown',
        'touchmove mousemove',
        'touchend touchcancel mouseup'];

        // Pointer events
        // var hasTouchWin = ( navigator.msMaxTouchPoints ) ? navigator.msMaxTouchPoints && navigator.msMaxTouchPoints > 1 : navigator.MaxTouchPoints && navigator.MaxTouchPoints > 1;
        // bodyTouchAction = document.body.style.msTouchAction;
        // document.body.style.msTouchAction = "none";

        //self.hasPointerEvents = window.navigator.pointerEnabled || window.navigator.msPointerEnabled;

        if ( window.PointerEvent ) {
            self.keyEvents = "pointerdown";
        } else if ( window.MSPointerEvent ) {
            self.keyEvents = "MSPointerDown";
        }

        // Touch events
        var hasTouch = 'ontouchstart' in window;
        self.mobileRegex = /mobile|tablet|ip(ad|hone|od)|android|silk/i;
        // check hammer.js - NO_MOUSEEVENTS
        if ( hasTouch && window.navigator.userAgent.match(self.mobileRegex) ) {
            return;
        }

        // Add a scrollr class
        self.target.addClass('scrollr');

        self.target.wrapInner('

').append('

');

        // this.scrollbar = $(document.createElement('div')).addClass('lazybar-' + this.options.axis);
        // this.scrubber = $(document.createElement('div')).addClass('scrubber').appendTo(this.scrollbar);

        // Optimze this - $innner = createelement(div);
        self.target.scrollrInner = self.target.find('.scrollr-inner');
        self.target.scrollrBar = self.target.find('.scrollr-scrollbar-y');
        self.target.scrollrHandle = self.target.find('.scrollr-handle');

        // Set tabindex to 0 to allow keydown event
        self.target.scrollrInner.attr("tabindex", 0);

        // Get scrollbar width and sets padding
        // FIX THIS: DONT DO THIS EVERYTIME
        var scrollBarWidth = getScrollbarWidth();

        if ( scrollBarWidth === 0 ) {
            //currentPadding = window.getComputedStyle(this.content, null).getPropertyValue('padding-right').replace(/\D+/g, '');
            currentPadding = 0;

            cssRule = {
                right: -14,
                paddingRight: +currentPadding + 14
            };
        }

        //else if (BROWSER_SCROLLBAR_WIDTH) {
        else {
            cssRule = {
                right: -scrollBarWidth
            };
        }

        if (cssRule != null) {
            //self.target.scrollrInner.css(cssRule);
        }

        // Find height of content
        // Add this as a public method for updating the height after DOM changes
        // var intElemScrollHeight = document.getElementById(id_attribute_value).scrollHeight;
        // self.target.scrollrInner.children().each(function(){
        //     self.totalHeight = self.totalHeight + $(this).outerHeight(true);
        // });
        self.totalHeight = self.target.scrollrInner[0].scrollHeight;

        if ( self.settings.fade ) {
            self.target.scrollrBar.hide();
            self.target.addClass('scrollr-fade');
        }

        // Checks if the browser support transform property
        // FIX THIS: IS EXECUTED EVERY TIME
        if ( !self.transformProperty ) {
            if ( $.support.transform && $.support.transform !== "transform" ) {
                // Checks if browser support translate3d
                // If so we'll use translate3d because its faster, right?
                if ( isTranslate3dSupported() ) {
                    self.transformProperty = "translate3d"
                } else {
                    self.transformProperty = "translate";
                }
            } else {
                self.transformProperty = "top";
            }
        }

        this.update();
        this.scrollbarPosition();
    }

    Plugin.prototype.events = function () {

        var self = this;

        // Mousewheel
        //self.target.on(self.wheelEvents + " " + self.keyEvents + " " + self.mouseEvents[0], function(event) {
        self.target.on(self.wheelEvents + " " + self.keyEvents, function(event) {
            self.eventTrigger();
        });

        var mouse = {},
            start = {},
            handle = {},
            area;

        // Drag handle
       self.target.scrollrBar.on(self.mouseEvents[0], function(event) {

            self.eventTrigger();

            self.scrollTop = (event.pageY / (self.scrollrInnerHeight + self.scrollrHandleHeight)) * (self.totalHeight);
            console.log(self.scrollTop);

            self.target.scrollrInner.scrollTop(self.scrollTop);

        });

        self.target.scrollrHandle.on(self.mouseEvents[0], function(event) {

            event.stopPropagation();

            self.dragging = true;

            self.eventTrigger();

            self.handleDragging = setInterval(function() {
                self.eventTrigger();
            }, 100);

            self.target.addClass('scrolling');

            if ( self.transformProperty == "top" ) {
                handle.y = parseInt(self.target.scrollrHandle.css('top'));
            } else {
                handle.y = self.target.scrollrHandle.css('transform');
                handle.y = handle.y.match(/(-?[0-9\.]+)/g);
                handle.y = parseInt(handle.y[5]);
            }

            start.y = event.pageY;
        });

        $(document).on(self.mouseEvents[1], function(event) {

            if ( self.dragging ) {
                event.preventDefault();

                mouse.moveX = event.pageX;
                mouse.moveY = event.pageY - start.y;

                self.scrollbarTop = handle.y + mouse.moveY;

                self.scrollTop = Math.round(self.scrollbarTop * (self.totalHeight - self.scrollrInnerHeight) / (self.scrollrInnerHeight - self.scrollrHandleHeight));

                self.target.scrollrInner.scrollTop(self.scrollTop);
            }
        });

        $(document).on(self.mouseEvents[2], function() {
            //if (self.target.hasClass('scrolling')) {
            self.dragging = false;
            clearInterval(self.handleDragging);
            self.target.removeClass('scrolling');
            //}
        });

        $(window).on("resize", function(event) {
            self.update();
            console.log('reisze');
        });
    }

    Plugin.prototype.update = function () {

        var self = this;

        self.scrollrInnerHeight = self.target.scrollrInner.height();
        self.scrollrHandleHeight = self.target.scrollrHandle.height();
        //console.log(self.totalHeight);
        //console.log(self.scrollrInnerHeight);

        // Set the height of the handle from the content height vs visible height ratio
        if ( self.settings.autoHandle ) {
            self.scrollrHandleHeight = Math.round((self.scrollrInnerHeight / self.totalHeight) * self.scrollrInnerHeight);

            self.scrollrHandleHeight = Math.min(self.scrollrHandleHeight, self.settings.maxHandleHeight);
            self.scrollrHandleHeight = Math.max(self.scrollrHandleHeight, self.settings.minHandleHeight);

            self.target.scrollrHandle.height(self.scrollrHandleHeight);
        }

        if ( self.totalHeight < self.scrollrInnerHeight ) {
            self.target.scrollrBar.hide();
        } else {
            self.target.scrollrBar.show();
        }
    }

    Plugin.prototype.scrollbarPosition = function () {
        var self = this;
        self.scrollLeft = self.target.scrollrInner.scrollLeft();
        self.scrollTop = self.target.scrollrInner.scrollTop();

        //console.log(self.scrollrInnerHeight);
        //console.log(self.scrollTop);

        self.scrollTop = Math.round((self.scrollTop / (self.totalHeight - self.scrollrInnerHeight)) * (self.scrollrInnerHeight - self.scrollrHandleHeight));

        self.scrollTop = Math.min(self.scrollTop, (self.scrollrInnerHeight - self.scrollrHandleHeight));
        self.scrollTop = Math.max(self.scrollTop, 0);

        //element.target.scrollrHandle.css({"top": self.scrollTop});
        //self.target.scrollrHandle.css({ transform: "translateY(" + self.scrollTop + "px)" });
        self.target.scrollrHandle.css(
            cssValues(0, self.scrollTop, self.transformProperty)
        );

    }

    Plugin.prototype.eventTrigger = function () {
        var self = this;

        // Add focus for keydown event
        // FIX THIS: JUMPS TO THIS WHEN ALREADY SCROLLED DOWN ON SITE
        // self.target.scrollrInner.focus();

        //console.log(event);

        clearTimeout(self.timer);

        if ( !self.scrolling ) {
            self.start(self);
        }

        self.scrolling = true;

        self.timer = setTimeout(function(){
            self.stop(self);
        }, 500);
    }

    Plugin.prototype.loop = function (self) {
        //console.log('loop')
        var self = this;
        this.scrollbarPosition();

        this.ticker = requestAnimationFrame(function(){
            self.loop()
        });

        // ES5
        //requestAnimationFrame(this.update.bind(this)});

    }

    Plugin.prototype.start = function () {
        this.loop();
        this.target.addClass('scrollr-active');
    }

    Plugin.prototype.stop = function () {
        if ( self.dragging ) {
            return; //is this needed?
        }

        cancelAnimationFrame(this.ticker);
        this.ticker = null;
        this.scrolling = false;
        this.target.removeClass('scrollr-active');
    }

    Plugin.prototype.destroy = function () {
        this.element.data( dataPlugin, null );
    }

    // Formats css values
    function cssValues(x, y, property) {

        if ( property == "translate" ) {
            cssValue = {
                transform: "translate(" + x + "px, " + y + "px)"
            };
        }

        else if ( property == "translate3d" ) {
            cssValue = {
                transform: "translate3d(" + x + "px, " + y + "px, 0)"
            };
        }

        else {
            cssValue = {
                left: x + "px",
                top: y + "px"
            };
        }

        return cssValue;
    }

    function getScrollbarWidth() {
        var div, divStyle, scrollbarWidth;
        div = document.createElement('div');
        divStyle = div.style;
        divStyle.position = 'absolute';
        divStyle.width = '100px';
        divStyle.height = '100px';
        divStyle.overflow = "scroll";
        divStyle.top = '-9999px';
        document.body.appendChild(div);
        scrollbarWidth = div.offsetWidth - div.clientWidth;
        document.body.removeChild(div);

        return scrollbarWidth;
    }

    // Testing for CSS 3D Transforms Support
    // optimize this - already got vendor prefixes from cssPropertyCheck
    function isTranslate3dSupported() {
        var el = document.createElement('div'),
        has3d,
        transforms = {
            'webkitTransform':'-webkit-transform',
            'OTransform':'-o-transform',
            'msTransform':'-ms-transform',
            'MozTransform':'-moz-transform',
            'transform':'transform'
        };

        // Add it to the body to get the computed style
        document.body.insertBefore(el, null);

        for(var t in transforms){
            if( el.style[t] !== undefined ){
                el.style[t] = 'translate3d(1px,1px,1px)';
                has3d = window.getComputedStyle(el).getPropertyValue(transforms[t]);
            }
        }

        document.body.removeChild(el);

        return (has3d !== undefined && has3d.length > 0 && has3d !== "none");
    }

    function cssPropertyCheck( prop ) {
        var vendorProp, supportedProp,
        capProp = prop.charAt( 0 ).toUpperCase() + prop.slice( 1 ),
        prefixes = [ "Moz", "Webkit", "O", "ms" ],
        div = document.createElement( "div" );

        if ( prop in div.style ) {
            supportedProp = prop;
        } else {
            for ( var i = 0; i < prefixes.length; i++ ) {
            vendorProp = prefixes[ i ] + capProp;
                if ( vendorProp in div.style ) {
                    supportedProp = vendorProp;
                    break;
                }
            }
        }

        div = null;
        $.support[ prop ] = supportedProp;
        return supportedProp;
    }

    var transform = cssPropertyCheck("transform");

    // requestAnimationFrame polyfill
    // https://gist.github.com/paulirish/1579671
    (function() {
        var lastTime = 0;
        var vendors = ['ms', 'moz', 'webkit', 'o'];
        for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
            window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
            window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame']
                                       || window[vendors[x]+'CancelRequestAnimationFrame'];
        }

        if (!window.requestAnimationFrame)
            window.requestAnimationFrame = function(callback, element) {
                var currTime = new Date().getTime();
                var timeToCall = Math.max(0, 16 - (currTime - lastTime));
                var id = window.setTimeout(function() { callback(currTime + timeToCall); },
                  timeToCall);
                lastTime = currTime + timeToCall;
                return id;
            };

        if (!window.cancelAnimationFrame)
            window.cancelAnimationFrame = function(id) {
                clearTimeout(id);
            };
    }());

    $.fn[ pluginName ] = function ( options ) {
        return this.each(function() {
            if ( !$.data( this, "plugin_" + pluginName ) ) {
                $.data( this, "plugin_" + pluginName, new Plugin( this, options ) );
            }
        });
    };

}(jQuery, window, document));<commit_msg>added preventDefault on mousemove<commit_after>/*
 	scrollr standalone - v0.0.1 (doesn't use TweenMax or hammer.js)
 	jQuery plugin for scrolling or dragging through an array of images
	by Robert Bue (@robert_bue)

 	Dual licensed under MIT and GPL.
 */

;(function ( $, window, document, undefined ) {

    var pluginName = "scrollr",
        dataPlugin = "plugin_" + pluginName,

        // default options
        defaults = {
			offset : 0,
            fade : false,
            autoHandle: true,
            minHandleHeight: 35,
            maxHandleHeight: 9999999
		};

    var Plugin = function ( element, options ) {

        this.element = element;
        //console.log(element);
        this.settings = $.extend( {}, defaults, options );
        this._defaults = defaults;
        this._name = pluginName;
        this.build();
        this.events();
    };

    Plugin.prototype.build = function () {
        var self = this;

        self.settings = this.settings,
        self.target = $(self.element),
        self.targetWidth = self.target.width(),
        self.targetHeight = self.target.height(),
        self.ticker = 0,
        self.scrollTop = 0,
        self.scrolling = false,
        self.totalHeight = 0;
        self.timer = null;

        // Wheel events
        //self.wheelEvents = ( 'onwheel' in document || document.documentMode >= 9 ) ? ['wheel'] : ['mousewheel', 'DomMouseScroll', 'MozMousePixelScroll'];
        self.wheelEvents = ( 'onwheel' in document || document.documentMode >= 9 ) ? 'wheel' : 'mousewheel DOMMouseScroll MozMousePixelScroll';
        // webkitDirectionInvertedFromDevice

        // Key events
        //var hasKeyDown = 'onkeydown' in document;
        self.keyEvents = "keydown";
        //self.keyEvents = ( 'onkeydown' in document ) ? "onkeydown" : "keydown";

        // Mouse events
        //self.mouseEvents = "mousedown touchstart";
        self.mouseEvents = [
        'touchstart mousedown',
        'touchmove mousemove',
        'touchend touchcancel mouseup'];

        // Pointer events
        // var hasTouchWin = ( navigator.msMaxTouchPoints ) ? navigator.msMaxTouchPoints && navigator.msMaxTouchPoints > 1 : navigator.MaxTouchPoints && navigator.MaxTouchPoints > 1;
        // bodyTouchAction = document.body.style.msTouchAction;
        // document.body.style.msTouchAction = "none";

        //self.hasPointerEvents = window.navigator.pointerEnabled || window.navigator.msPointerEnabled;

        if ( window.PointerEvent ) {
            self.keyEvents = "pointerdown";
        } else if ( window.MSPointerEvent ) {
            self.keyEvents = "MSPointerDown";
        }

        // Touch events
        var hasTouch = 'ontouchstart' in window;
        self.mobileRegex = /mobile|tablet|ip(ad|hone|od)|android|silk/i;
        // check hammer.js - NO_MOUSEEVENTS
        if ( hasTouch && window.navigator.userAgent.match(self.mobileRegex) ) {
            return;
        }

        // Add a scrollr class
        self.target.addClass('scrollr');

        self.target.wrapInner('

').append('

');

        // this.scrollbar = $(document.createElement('div')).addClass('lazybar-' + this.options.axis);
        // this.scrubber = $(document.createElement('div')).addClass('scrubber').appendTo(this.scrollbar);

        // Optimze this - $innner = createelement(div);
        self.target.scrollrInner = self.target.find('.scrollr-inner');
        self.target.scrollrBar = self.target.find('.scrollr-scrollbar-y');
        self.target.scrollrHandle = self.target.find('.scrollr-handle');

        // Set tabindex to 0 to allow keydown event
        self.target.scrollrInner.attr("tabindex", 0);

        // Get scrollbar width and sets padding
        // FIX THIS: DONT DO THIS EVERYTIME
        var scrollBarWidth = getScrollbarWidth();

        if ( scrollBarWidth === 0 ) {
            //currentPadding = window.getComputedStyle(this.content, null).getPropertyValue('padding-right').replace(/\D+/g, '');
            currentPadding = 0;

            cssRule = {
                right: -14,
                paddingRight: +currentPadding + 14
            };
        }

        //else if (BROWSER_SCROLLBAR_WIDTH) {
        else {
            cssRule = {
                right: -scrollBarWidth
            };
        }

        if (cssRule != null) {
            //self.target.scrollrInner.css(cssRule);
        }

        // Find height of content
        // Add this as a public method for updating the height after DOM changes
        // var intElemScrollHeight = document.getElementById(id_attribute_value).scrollHeight;
        // self.target.scrollrInner.children().each(function(){
        //     self.totalHeight = self.totalHeight + $(this).outerHeight(true);
        // });
        self.totalHeight = self.target.scrollrInner[0].scrollHeight;

        if ( self.settings.fade ) {
            self.target.scrollrBar.hide();
            self.target.addClass('scrollr-fade');
        }

        // Checks if the browser support transform property
        // FIX THIS: IS EXECUTED EVERY TIME
        if ( !self.transformProperty ) {
            if ( $.support.transform && $.support.transform !== "transform" ) {
                // Checks if browser support translate3d
                // If so we'll use translate3d because its faster, right?
                if ( isTranslate3dSupported() ) {
                    self.transformProperty = "translate3d"
                } else {
                    self.transformProperty = "translate";
                }
            } else {
                self.transformProperty = "top";
            }
        }

        this.update();
        this.scrollbarPosition();
    }

    Plugin.prototype.events = function () {

        var self = this;

        // Mousewheel
        //self.target.on(self.wheelEvents + " " + self.keyEvents + " " + self.mouseEvents[0], function(event) {
        self.target.on(self.wheelEvents + " " + self.keyEvents, function(event) {
            self.eventTrigger();
        });

        var mouse = {},
            start = {},
            handle = {},
            area;

        // Drag handle
       self.target.scrollrBar.on(self.mouseEvents[0], function(event) {

            self.eventTrigger();

            self.scrollTop = (event.pageY / (self.scrollrInnerHeight + self.scrollrHandleHeight)) * (self.totalHeight);
            console.log(self.scrollTop);

            self.target.scrollrInner.scrollTop(self.scrollTop);

        });

        self.target.scrollrHandle.on(self.mouseEvents[0], function(event) {

            event.preventDefault();
            event.stopPropagation();

            self.dragging = true;

            self.eventTrigger();

            self.handleDragging = setInterval(function() {
                self.eventTrigger();
            }, 100);

            self.target.addClass('scrolling');

            if ( self.transformProperty == "top" ) {
                handle.y = parseInt(self.target.scrollrHandle.css('top'));
            } else {
                handle.y = self.target.scrollrHandle.css('transform');
                handle.y = handle.y.match(/(-?[0-9\.]+)/g);
                handle.y = parseInt(handle.y[5]);
            }

            start.y = event.pageY;
        });

        $(document).on(self.mouseEvents[1], function(event) {

            if ( self.dragging ) {
                event.preventDefault();

                mouse.moveX = event.pageX;
                mouse.moveY = event.pageY - start.y;

                self.scrollbarTop = handle.y + mouse.moveY;

                self.scrollTop = Math.round(self.scrollbarTop * (self.totalHeight - self.scrollrInnerHeight) / (self.scrollrInnerHeight - self.scrollrHandleHeight));

                self.target.scrollrInner.scrollTop(self.scrollTop);
            }
        });

        $(document).on(self.mouseEvents[2], function() {
            //if (self.target.hasClass('scrolling')) {
            self.dragging = false;
            clearInterval(self.handleDragging);
            self.target.removeClass('scrolling');
            //}
        });

        $(window).on("resize", function(event) {
            self.update();
            console.log('reisze');
        });
    }

    Plugin.prototype.update = function () {

        var self = this;

        self.scrollrInnerHeight = self.target.scrollrInner.height();
        self.scrollrHandleHeight = self.target.scrollrHandle.height();
        //console.log(self.totalHeight);
        //console.log(self.scrollrInnerHeight);

        // Set the height of the handle from the content height vs visible height ratio
        if ( self.settings.autoHandle ) {
            self.scrollrHandleHeight = Math.round((self.scrollrInnerHeight / self.totalHeight) * self.scrollrInnerHeight);

            self.scrollrHandleHeight = Math.min(self.scrollrHandleHeight, self.settings.maxHandleHeight);
            self.scrollrHandleHeight = Math.max(self.scrollrHandleHeight, self.settings.minHandleHeight);

            self.target.scrollrHandle.height(self.scrollrHandleHeight);
        }

        if ( self.totalHeight < self.scrollrInnerHeight ) {
            self.target.scrollrBar.hide();
        } else {
            self.target.scrollrBar.show();
        }
    }

    Plugin.prototype.scrollbarPosition = function () {
        var self = this;
        self.scrollLeft = self.target.scrollrInner.scrollLeft();
        self.scrollTop = self.target.scrollrInner.scrollTop();

        //console.log(self.scrollrInnerHeight);
        //console.log(self.scrollTop);

        self.scrollTop = Math.round((self.scrollTop / (self.totalHeight - self.scrollrInnerHeight)) * (self.scrollrInnerHeight - self.scrollrHandleHeight));

        self.scrollTop = Math.min(self.scrollTop, (self.scrollrInnerHeight - self.scrollrHandleHeight));
        self.scrollTop = Math.max(self.scrollTop, 0);

        //element.target.scrollrHandle.css({"top": self.scrollTop});
        //self.target.scrollrHandle.css({ transform: "translateY(" + self.scrollTop + "px)" });
        self.target.scrollrHandle.css(
            cssValues(0, self.scrollTop, self.transformProperty)
        );

    }

    Plugin.prototype.eventTrigger = function () {
        var self = this;

        // Add focus for keydown event
        // FIX THIS: JUMPS TO THIS WHEN ALREADY SCROLLED DOWN ON SITE
        // self.target.scrollrInner.focus();

        //console.log(event);

        clearTimeout(self.timer);

        if ( !self.scrolling ) {
            self.start(self);
        }

        self.scrolling = true;

        self.timer = setTimeout(function(){
            self.stop(self);
        }, 500);
    }

    Plugin.prototype.loop = function (self) {
        //console.log('loop')
        var self = this;
        this.scrollbarPosition();

        this.ticker = requestAnimationFrame(function(){
            self.loop()
        });

        // ES5
        //requestAnimationFrame(this.update.bind(this)});

    }

    Plugin.prototype.start = function () {
        this.loop();
        this.target.addClass('scrollr-active');
    }

    Plugin.prototype.stop = function () {
        if ( self.dragging ) {
            return; //is this needed?
        }

        cancelAnimationFrame(this.ticker);
        this.ticker = null;
        this.scrolling = false;
        this.target.removeClass('scrollr-active');
    }

    Plugin.prototype.destroy = function () {
        this.element.data( dataPlugin, null );
    }

    // Formats css values
    function cssValues(x, y, property) {

        if ( property == "translate" ) {
            cssValue = {
                transform: "translate(" + x + "px, " + y + "px)"
            };
        }

        else if ( property == "translate3d" ) {
            cssValue = {
                transform: "translate3d(" + x + "px, " + y + "px, 0)"
            };
        }

        else {
            cssValue = {
                left: x + "px",
                top: y + "px"
            };
        }

        return cssValue;
    }

    function getScrollbarWidth() {
        var div, divStyle, scrollbarWidth;
        div = document.createElement('div');
        divStyle = div.style;
        divStyle.position = 'absolute';
        divStyle.width = '100px';
        divStyle.height = '100px';
        divStyle.overflow = "scroll";
        divStyle.top = '-9999px';
        document.body.appendChild(div);
        scrollbarWidth = div.offsetWidth - div.clientWidth;
        document.body.removeChild(div);

        return scrollbarWidth;
    }

    // Testing for CSS 3D Transforms Support
    // optimize this - already got vendor prefixes from cssPropertyCheck
    function isTranslate3dSupported() {
        var el = document.createElement('div'),
        has3d,
        transforms = {
            'webkitTransform':'-webkit-transform',
            'OTransform':'-o-transform',
            'msTransform':'-ms-transform',
            'MozTransform':'-moz-transform',
            'transform':'transform'
        };

        // Add it to the body to get the computed style
        document.body.insertBefore(el, null);

        for(var t in transforms){
            if( el.style[t] !== undefined ){
                el.style[t] = 'translate3d(1px,1px,1px)';
                has3d = window.getComputedStyle(el).getPropertyValue(transforms[t]);
            }
        }

        document.body.removeChild(el);

        return (has3d !== undefined && has3d.length > 0 && has3d !== "none");
    }

    function cssPropertyCheck( prop ) {
        var vendorProp, supportedProp,
        capProp = prop.charAt( 0 ).toUpperCase() + prop.slice( 1 ),
        prefixes = [ "Moz", "Webkit", "O", "ms" ],
        div = document.createElement( "div" );

        if ( prop in div.style ) {
            supportedProp = prop;
        } else {
            for ( var i = 0; i < prefixes.length; i++ ) {
            vendorProp = prefixes[ i ] + capProp;
                if ( vendorProp in div.style ) {
                    supportedProp = vendorProp;
                    break;
                }
            }
        }

        div = null;
        $.support[ prop ] = supportedProp;
        return supportedProp;
    }

    var transform = cssPropertyCheck("transform");

    // requestAnimationFrame polyfill
    // https://gist.github.com/paulirish/1579671
    (function() {
        var lastTime = 0;
        var vendors = ['ms', 'moz', 'webkit', 'o'];
        for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
            window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
            window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame']
                                       || window[vendors[x]+'CancelRequestAnimationFrame'];
        }

        if (!window.requestAnimationFrame)
            window.requestAnimationFrame = function(callback, element) {
                var currTime = new Date().getTime();
                var timeToCall = Math.max(0, 16 - (currTime - lastTime));
                var id = window.setTimeout(function() { callback(currTime + timeToCall); },
                  timeToCall);
                lastTime = currTime + timeToCall;
                return id;
            };

        if (!window.cancelAnimationFrame)
            window.cancelAnimationFrame = function(id) {
                clearTimeout(id);
            };
    }());

    $.fn[ pluginName ] = function ( options ) {
        return this.each(function() {
            if ( !$.data( this, "plugin_" + pluginName ) ) {
                $.data( this, "plugin_" + pluginName, new Plugin( this, options ) );
            }
        });
    };

}(jQuery, window, document));<|endoftext|>


<commit_before>(function(GOVUK, Modules) {
  "use strict";

  GOVUK.timeCache = {};
  GOVUK.resultCache = {};

  var dd = new diffDOM();

  let getter = function(resource, interval, render) {

    if (
      GOVUK.resultCache[resource] &&
      (Date.now() < GOVUK.timeCache[resource])
    ) {
      render(GOVUK.resultCache[resource]);
    } else {
      GOVUK.timeCache[resource] = Date.now() + interval;
      $.get(
        resource,
        response => render(GOVUK.resultCache[resource] = response)
      );
    }

  };

  let poller = (resource, key, $component, interval) => () => getter(
    resource, interval, response => dd.apply(
      $component.get(0),
      dd.diff($component.get(0), $(response[key]).get(0))
    )
  );

  Modules.UpdateContent = function() {

    this.start = function(component) {

      const $component = $(component);
      interval = ($(component).data("interval-seconds") * 1000) || 1500;

      setInterval(
        poller($component.data('resource'), $component.data('key'), $component, interval),
        interval / 5
      );

    };
  };

})(window.GOVUK, window.GOVUK.Modules);
<commit_msg>Stop AJAX updates queuing requests<commit_after>(function(Modules) {
  "use strict";

  var queues = {};
  var dd = new diffDOM();

  var getRenderer = $component => response => dd.apply(
    $component.get(0),
    dd.diff($component.get(0), $(response[$component.data('key')]).get(0))
  );

  var getQueue = resource => (
    queues[resource] = queues[resource] || []
  );

  var flushQueue = function(queue, response) {
    while(queue.length) queue.shift()(response);
  };

  var poll = function(renderer, resource, queue, interval) {

    if (queue.push(renderer) === 1) $.get(
      resource,
      response => flushQueue(queue, response)
    );

    setTimeout(
      () => poll(...arguments), interval
    );

  };

  Modules.UpdateContent = function() {

    this.start = component => poll(
      getRenderer($(component)),
      $(component).data('resource'),
      getQueue($(component).data('resource')),
      ($(component).data('interval-seconds') || 1.5) * 1000
    );

  };

})(window.GOVUK.Modules);
<|endoftext|>


<commit_before>Template[getTemplate('poll_form')].helpers ({
	binaryPoll: function () {
		return this.poll.type == "binary";
	},
	multiplePoll: function () {
		return this.poll.type == "multiple";
	},
	pollVoted: function () {
		var userId = Meteor.userId(),
			options = this.poll.options,
			optionsLength = options.length;
		if (optionsLength > 0) {
			for (var i=0; i < optionsLength; i++) {
				if (_.contains(options[i].voters, userId)) {
					return true;
				}
			}
		}
		return false;
	},
	multiplePollBarPercentage: function (options) {
		var pollOptions = options.hash.options,
			optionsLength = pollOptions.length,
			biggist = 0;
		for(var i=0; i< optionsLength; i++) {
			var optionVotes = pollOptions[i].votes;

			if (optionVotes > biggist) {
				biggist = optionVotes;
			} else {
				biggist = biggist;
			}
		}
		if (!_.isUndefined(options.hash.voteCount)) {
			var percentage = Math.round((options.hash.votes / biggist) * 100, -1);
			if (percentage > 100) {
				return 100;
			}
			return percentage;
		}
	},
	votePercentage: function (options) {
		if (!_.isUndefined(options.hash.voteCount)) {
			return Math.round(options.hash.votes / options.hash.voteCount * 100, -1);
		}
		return Math.round(this.poll.options[options.hash.order-1].votes / this.poll.voteCount * 100, -1);
	},
	hasVotes: function() {
		return this.votes > 0;
	}
});

Template[getTemplate('poll_form')].events({
  'click .poll-multiple-vote-btn': function(e, instance){
    e.preventDefault();
    var post = instance.data;

    if(!Meteor.user()){
      Router.go('atSignIn');
      flashMessage(i18n.t("please_log_in_first"), "info");
    }
    if(_.isUndefined(this.voteOrder)) {
    	console.log("this is undefined");
    }
    Meteor.call('pollVote', post, this, function(error, result){
      trackEvent("post poll-voted", {'_id': post._id});
    });
  },
  'click .poll-binary-vote-btn': function(e, instance){
    e.preventDefault();
    var order = e.currentTarget.id;
    var option = instance.data.poll.options[order-1];

    if(!Meteor.user()){
      Router.go('atSignIn');
      flashMessage(i18n.t("please_log_in_first"), "info");
    }

    Meteor.call('pollVote', this, option, function(error, result){
      trackEvent("post poll-voted", {'_id': post._id});
    });
  }
});

Template[getTemplate('poll_form')].rendered = function(){
	this.$('#vote-result-bar-1').progress();
	this.$('#vote-result-bar-2').progress();
	this.$('#vote-result-bar-3').progress();
	this.$('#vote-result-bar-4').progress();
	this.$('#vote-result-bar-5').progress();
}<commit_msg>fix post undefined when vote on binary poll<commit_after>Template[getTemplate('poll_form')].helpers ({
	binaryPoll: function () {
		return this.poll.type == "binary";
	},
	multiplePoll: function () {
		return this.poll.type == "multiple";
	},
	pollVoted: function () {
		var userId = Meteor.userId(),
			options = this.poll.options,
			optionsLength = options.length;
		if (optionsLength > 0) {
			for (var i=0; i < optionsLength; i++) {
				if (_.contains(options[i].voters, userId)) {
					return true;
				}
			}
		}
		return false;
	},
	multiplePollBarPercentage: function (options) {
		var pollOptions = options.hash.options,
			optionsLength = pollOptions.length,
			biggist = 0;
		for(var i=0; i< optionsLength; i++) {
			var optionVotes = pollOptions[i].votes;

			if (optionVotes > biggist) {
				biggist = optionVotes;
			} else {
				biggist = biggist;
			}
		}
		if (!_.isUndefined(options.hash.voteCount)) {
			var percentage = Math.round((options.hash.votes / biggist) * 100, -1);
			if (percentage > 100) {
				return 100;
			}
			return percentage;
		}
	},
	votePercentage: function (options) {
		if (!_.isUndefined(options.hash.voteCount)) {
			return Math.round(options.hash.votes / options.hash.voteCount * 100, -1);
		}
		return Math.round(this.poll.options[options.hash.order-1].votes / this.poll.voteCount * 100, -1);
	},
	hasVotes: function() {
		return this.votes > 0;
	}
});

Template[getTemplate('poll_form')].events({
  'click .poll-multiple-vote-btn': function(e, instance){
    e.preventDefault();
    var post = instance.data;

    if(!Meteor.user()){
      Router.go('atSignIn');
      flashMessage(i18n.t("please_log_in_first"), "info");
    }
    if(_.isUndefined(this.voteOrder)) {
    	console.log("this is undefined");
    }
    Meteor.call('pollVote', post, this, function(error, result){
      trackEvent("post poll-voted", {'_id': post._id});
    });
  },
  'click .poll-binary-vote-btn': function(e, instance){
    e.preventDefault();
    var order = e.currentTarget.id;
    var option = instance.data.poll.options[order-1];

    if(!Meteor.user()){
      Router.go('atSignIn');
      flashMessage(i18n.t("please_log_in_first"), "info");
    }

    Meteor.call('pollVote', this, option, function(error, result){
      trackEvent("post poll-voted", {'_id': this._id});
    });
  }
});

Template[getTemplate('poll_form')].rendered = function(){
	this.$('#vote-result-bar-1').progress();
	this.$('#vote-result-bar-2').progress();
	this.$('#vote-result-bar-3').progress();
	this.$('#vote-result-bar-4').progress();
	this.$('#vote-result-bar-5').progress();
}<|endoftext|>


<commit_before>// plugin for toggling
define([], function() {
  (function($) {
    $.fn.toggle = function(opts) {
      var defaults = {
        headingSelector: ".toggle-header",
        contentSelector: ".toggle-content"
      };
      var settings = $.extend({}, defaults, opts);
      return this.each(function() {
        var wrapper = $(this);
        var toggle = wrapper.find(settings.headingSelector).show();
        var content = wrapper.find(settings.contentSelector).hide();
        toggle.on("click", function(e) {
          console.log("clicked");
          console.log(content);
          e.preventDefault();
          content.toggle();
        });
      });
    }
  })(jQuery);
});
<commit_msg>update JS toggle<commit_after>// plugin for toggling
define([], function() {
  (function($) {
    $.fn.toggle = function(opts) {
      var defaults = {
        headingSelector: ".toggle-header",
        contentSelector: ".toggle-content"
      };
      var settings = $.extend({}, defaults, opts);
      return this.each(function() {
        var wrapper = $(this);
        var toggle = wrapper.find(settings.headingSelector).show();
        var content = wrapper.find(settings.contentSelector);
        content.hide();
        toggle.on("click", function(e) {
          content.slideToggle();
          e.preventDefault();
        });
      });
    }
  })(jQuery);
});
<|endoftext|>