<commit_before>//////////////////////////////////
//JQLite
//////////////////////////////////

var jqCache = {},
    jqName = 'ng-' + new Date().getTime(),
    jqId = 1,
    addEventListener = (window.document.attachEvent ?
      function(element, type, fn) {element.attachEvent('on' + type, fn);} :
      function(element, type, fn) {element.addEventListener(type, fn, false);}),
    removeEventListener = (window.document.detachEvent ?
      function(element, type, fn) {element.detachEvent('on' + type, fn); } :
      function(element, type, fn) { element.removeEventListener(type, fn, false); });

function jqNextId() { return (jqId++); }

function jqClearData(element) {
  var cacheId = element[jqName],
      cache = jqCache[cacheId];
  if (cache) {
    foreach(cache.bind || {}, function(fn, type){
      removeEventListener(element, type, fn);
    });
    delete jqCache[cacheId];
    if (msie)
      element[jqName] = ''; // ie does not allow deletion of attributes on elements.
    else
      delete element[jqName];
  }
}

function getStyle(element) {
  var current = {}, style = element[0].style, value, name, i;
  if (typeof style.length == 'number') {
    for(i = 0; i < style.length; i++) {
      name = style[i];
      current[name] = style[name];
    }
  } else {
    for (name in style) {
      value = style[name];
      if (1*name != name && name != 'cssText' && value && typeof value == 'string' && value !='false')
        current[name] = value;
    }
  }
  return current;
}

function JQLite(element) {
  if (isElement(element)) {
    this[0] = element;
    this.length = 1;
  } else if (isDefined(element.length) && element.item) {
    for(var i=0; i < element.length; i++) {
      this[i] = element[i];
    }
    this.length = element.length;
  }
}

JQLite.prototype = {
  data: function(key, value) {
    var element = this[0],
        cacheId = element[jqName],
        cache = jqCache[cacheId || -1];
    if (isDefined(value)) {
      if (!cache) {
        element[jqName] = cacheId = jqNextId();
        cache = jqCache[cacheId] = {};
      }
      cache[key] = value;
    } else {
      return cache ? cache[key] : _null;
    }
  },

  removeData: function(){
    jqClearData(this[0]);
  },

  dealoc: function(){
    (function dealoc(element){
      jqClearData(element);
      for ( var i = 0, children = element.childNodes; i < children.length; i++) {
        dealoc(children[i]);
      }
    })(this[0]);
  },

  bind: function(type, fn){
    var self = this,
        element = self[0],
        bind = self.data('bind'),
        eventHandler;
    if (!bind) this.data('bind', bind = {});
    foreach(type.split(' '), function(type){
      eventHandler = bind[type];
      if (!eventHandler) {
        bind[type] = eventHandler = function(event) {
          if (!event.preventDefault) {
            event.preventDefault = function(){
              event.returnValue = false;
            };
          }
          foreach(eventHandler.fns, function(fn){
            fn.call(self, event);
          });
        };
        eventHandler.fns = [];
        addEventListener(element, type, eventHandler);
      }
      eventHandler.fns.push(fn);
    });
  },

  trigger: function(type) {
    var evnt = document.createEvent('MouseEvent');
    evnt.initMouseEvent(type, true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, _null);
    this[0].dispatchEvent(evnt);
  },

  replaceWith: function(replaceNode) {
    this[0].parentNode.replaceChild(jqLite(replaceNode)[0], this[0]);
  },

  children: function() {
    return new JQLite(this[0].childNodes);
  },

  append: function(node) {
    var self = this[0];
    node = jqLite(node);
    foreach(node, function(child){
      self.appendChild(child);
    });
  },

  remove: function() {
    this.dealoc();
    var parentNode = this[0].parentNode;
    if (parentNode) parentNode.removeChild(this[0]);
  },

  removeAttr: function(name) {
    this[0].removeAttribute(name);
  },

  after: function(element) {
    this[0].parentNode.insertBefore(jqLite(element)[0], this[0].nextSibling);
  },

  hasClass: function(selector) {
    var className = " " + selector + " ";
    if ( (" " + this[0].className + " ").replace(/[\n\t]/g, " ").indexOf( className ) > -1 ) {
      return true;
    }
    return false;
  },

  removeClass: function(selector) {
    this[0].className = trim((" " + this[0].className + " ").replace(/[\n\t]/g, " ").replace(" " + selector + " ", ""));
  },

  toggleClass: function(selector, condition) {
   var self = this;
   (condition ? self.addClass : self.removeClass).call(self, selector);
  },

  addClass: function( selector ) {
    if (!this.hasClass(selector)) {
      this[0].className = trim(this[0].className + ' ' + selector);
    }
  },

  css: function(name, value) {
    var style = this[0].style;
    if (isString(name)) {
      if (isDefined(value)) {
        style[name] = value;
      } else {
        return style[name];
      }
    } else {
      extend(style, name);
    }
  },

  attr: function(name, value){
    var e = this[0];
    if (isObject(name)) {
      foreach(name, function(value, name){
        e.setAttribute(name, value);
      });
    } else if (isDefined(value)) {
      e.setAttribute(name, value);
    } else {
      var attributes = e.attributes,
          item = attributes ? attributes.getNamedItem(name) : _undefined;
      return item && item.specified ? item.value : _undefined;
    }
  },

  text: function(value) {
    if (isDefined(value)) {
      this[0].textContent = value;
    }
    return this[0].textContent;
  },

  val: function(value) {
    if (isDefined(value)) {
      this[0].value = value;
    }
    return this[0].value;
  },

  html: function(value) {
    if (isDefined(value)) {
      var i = 0, childNodes = this[0].childNodes;
      for ( ; i < childNodes.length; i++) {
        jqLite(childNodes[i]).dealoc();
      }
      this[0].innerHTML = value;
    }
    return this[0].innerHTML;
  },

  parent: function() {
    return jqLite(this[0].parentNode);
  },

  clone: function() { return jqLite(this[0].cloneNode(true)); }
};

if (msie) {
  extend(JQLite.prototype, {
    text: function(value) {
      var e = this[0];
      // NodeType == 3 is text node
      if (e.nodeType == 3) {
        if (isDefined(value)) e.nodeValue = value;
        return e.nodeValue;
      } else {
        if (isDefined(value)) e.innerText = value;
        return e.innerText;
      }
    },

    trigger: function(type) {
      this[0].fireEvent('on' + type);
    }
  });
}
<commit_msg>properly handle event's stopPropagation() and preventDefault() method in IE<commit_after>//////////////////////////////////
//JQLite
//////////////////////////////////

var jqCache = {},
    jqName = 'ng-' + new Date().getTime(),
    jqId = 1,
    addEventListener = (window.document.attachEvent ?
      function(element, type, fn) {element.attachEvent('on' + type, fn);} :
      function(element, type, fn) {element.addEventListener(type, fn, false);}),
    removeEventListener = (window.document.detachEvent ?
      function(element, type, fn) {element.detachEvent('on' + type, fn); } :
      function(element, type, fn) { element.removeEventListener(type, fn, false); });

function jqNextId() { return (jqId++); }

function jqClearData(element) {
  var cacheId = element[jqName],
      cache = jqCache[cacheId];
  if (cache) {
    foreach(cache.bind || {}, function(fn, type){
      removeEventListener(element, type, fn);
    });
    delete jqCache[cacheId];
    if (msie)
      element[jqName] = ''; // ie does not allow deletion of attributes on elements.
    else
      delete element[jqName];
  }
}

function getStyle(element) {
  var current = {}, style = element[0].style, value, name, i;
  if (typeof style.length == 'number') {
    for(i = 0; i < style.length; i++) {
      name = style[i];
      current[name] = style[name];
    }
  } else {
    for (name in style) {
      value = style[name];
      if (1*name != name && name != 'cssText' && value && typeof value == 'string' && value !='false')
        current[name] = value;
    }
  }
  return current;
}

function JQLite(element) {
  if (isElement(element)) {
    this[0] = element;
    this.length = 1;
  } else if (isDefined(element.length) && element.item) {
    for(var i=0; i < element.length; i++) {
      this[i] = element[i];
    }
    this.length = element.length;
  }
}

JQLite.prototype = {
  data: function(key, value) {
    var element = this[0],
        cacheId = element[jqName],
        cache = jqCache[cacheId || -1];
    if (isDefined(value)) {
      if (!cache) {
        element[jqName] = cacheId = jqNextId();
        cache = jqCache[cacheId] = {};
      }
      cache[key] = value;
    } else {
      return cache ? cache[key] : _null;
    }
  },

  removeData: function(){
    jqClearData(this[0]);
  },

  dealoc: function(){
    (function dealoc(element){
      jqClearData(element);
      for ( var i = 0, children = element.childNodes; i < children.length; i++) {
        dealoc(children[i]);
      }
    })(this[0]);
  },

  bind: function(type, fn){
    var self = this,
        element = self[0],
        bind = self.data('bind'),
        eventHandler;
    if (!bind) this.data('bind', bind = {});
    foreach(type.split(' '), function(type){
      eventHandler = bind[type];
      if (!eventHandler) {
        bind[type] = eventHandler = function(event) {
          if (!event.preventDefault) {
            event.preventDefault = function(){
              event.returnValue = false; //ie
            };
          }
          if (!event.stopPropagation) {
            event.stopPropagation = function() {
              event.cancelBubble = true; //ie
            }
          }
          foreach(eventHandler.fns, function(fn){
            fn.call(self, event);
          });
        };
        eventHandler.fns = [];
        addEventListener(element, type, eventHandler);
      }
      eventHandler.fns.push(fn);
    });
  },

  trigger: function(type) {
    var evnt = document.createEvent('MouseEvent');
    evnt.initMouseEvent(type, true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, _null);
    this[0].dispatchEvent(evnt);
  },

  replaceWith: function(replaceNode) {
    this[0].parentNode.replaceChild(jqLite(replaceNode)[0], this[0]);
  },

  children: function() {
    return new JQLite(this[0].childNodes);
  },

  append: function(node) {
    var self = this[0];
    node = jqLite(node);
    foreach(node, function(child){
      self.appendChild(child);
    });
  },

  remove: function() {
    this.dealoc();
    var parentNode = this[0].parentNode;
    if (parentNode) parentNode.removeChild(this[0]);
  },

  removeAttr: function(name) {
    this[0].removeAttribute(name);
  },

  after: function(element) {
    this[0].parentNode.insertBefore(jqLite(element)[0], this[0].nextSibling);
  },

  hasClass: function(selector) {
    var className = " " + selector + " ";
    if ( (" " + this[0].className + " ").replace(/[\n\t]/g, " ").indexOf( className ) > -1 ) {
      return true;
    }
    return false;
  },

  removeClass: function(selector) {
    this[0].className = trim((" " + this[0].className + " ").replace(/[\n\t]/g, " ").replace(" " + selector + " ", ""));
  },

  toggleClass: function(selector, condition) {
   var self = this;
   (condition ? self.addClass : self.removeClass).call(self, selector);
  },

  addClass: function( selector ) {
    if (!this.hasClass(selector)) {
      this[0].className = trim(this[0].className + ' ' + selector);
    }
  },

  css: function(name, value) {
    var style = this[0].style;
    if (isString(name)) {
      if (isDefined(value)) {
        style[name] = value;
      } else {
        return style[name];
      }
    } else {
      extend(style, name);
    }
  },

  attr: function(name, value){
    var e = this[0];
    if (isObject(name)) {
      foreach(name, function(value, name){
        e.setAttribute(name, value);
      });
    } else if (isDefined(value)) {
      e.setAttribute(name, value);
    } else {
      // the extra argument is to get the right thing for a.href in IE, see jQuery code
      return e.getAttribute(name, 2);
    }
  },

  text: function(value) {
    if (isDefined(value)) {
      this[0].textContent = value;
    }
    return this[0].textContent;
  },

  val: function(value) {
    if (isDefined(value)) {
      this[0].value = value;
    }
    return this[0].value;
  },

  html: function(value) {
    if (isDefined(value)) {
      var i = 0, childNodes = this[0].childNodes;
      for ( ; i < childNodes.length; i++) {
        jqLite(childNodes[i]).dealoc();
      }
      this[0].innerHTML = value;
    }
    return this[0].innerHTML;
  },

  parent: function() {
    return jqLite(this[0].parentNode);
  },

  clone: function() { return jqLite(this[0].cloneNode(true)); }
};

if (msie) {
  extend(JQLite.prototype, {
    text: function(value) {
      var e = this[0];
      // NodeType == 3 is text node
      if (e.nodeType == 3) {
        if (isDefined(value)) e.nodeValue = value;
        return e.nodeValue;
      } else {
        if (isDefined(value)) e.innerText = value;
        return e.innerText;
      }
    },

    trigger: function(type) {
      this[0].fireEvent('on' + type);
    }
  });
}
<|endoftext|>


<commit_before>/**
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 **/

"use strict";
var Tinkerforge = require('tinkerforge');
var devices = require('../lib/devices');

module.exports = function(RED) {

	function tinkerForgeRemoteSwitch(n) {
        RED.nodes.createNode(this,n);
        this.device = n.device;
        this.sensor = n.sensor;
        this.name = n.name;
        this.mode = n.mode;
	    this.addr1 = n.addr1;
	    this.addr2 = n.addr2;
        this.topic = n.topic;
        var node = this;

        node.ipcon = new Tinkerforge.IPConnection(); //devices[this.device].ipcon;
        node.ipcon.setAutoReconnect(true);
        var devs = devices.getDevices();
        node.ipcon.connect(devs[node.device].host, devs[node.device].port,function(error){
            if(error) {
                node.warn("couldn't connect");
            }
        });

        node.ipcon.on(Tinkerforge.IPConnection.CALLBACK_CONNECTED,
        function(connectReason) {
            node.md = new Tinkerforge.BrickletRemoteSwitch(node.sensor, node.ipcon);
        });

	node.on('input', function(msg){
	    if(node.md) {
	      if (typeof msg.payload === 'number') {
	        if (msg.payload == 1) {
                      var switchto = Tinkerforge.BrickletRemoteSwitch.SWITCH_TO_ON;
		    }
		    else {
                      var switchto = Tinkerforge.BrickletRemoteSwitch.SWITCH_TO_OFF;
 		    }
                switch (node.mode) {
                case 'A':node.md.switchSocketA(node.addr1, node.addr2, switchto);break;
                case 'B':node.md.switchSocketB(node.addr1, node.addr2, dwitchto);break;
                }
	      }
	    }
    });

        node.on('close',function() {
            node.ipcon.disconnect();
        });
    }

    RED.nodes.registerType('Tinkerforge RemoteSwitch', tinkerForgeRemoteSwitch);
}<commit_msg>Update RemoteSwitch.js<commit_after>/**
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 **/

"use strict";
var Tinkerforge = require('tinkerforge');
var devices = require('../lib/devices');

module.exports = function(RED) {

	function tinkerForgeRemoteSwitch(n) {
        RED.nodes.createNode(this,n);
        this.device = n.device;
        this.sensor = n.sensor;
        this.name = n.name;
        this.mode = n.mode;
	    this.addr1 = n.addr1;
	    this.addr2 = n.addr2;
        this.topic = n.topic;
        var node = this;

        node.ipcon = new Tinkerforge.IPConnection(); //devices[this.device].ipcon;
        node.ipcon.setAutoReconnect(true);
        var devs = devices.getDevices();
        node.ipcon.connect(devs[node.device].host, devs[node.device].port,function(error){
            if(error) {
                node.warn("couldn't connect");
            }
        });

        node.ipcon.on(Tinkerforge.IPConnection.CALLBACK_CONNECTED,
        function(connectReason) {
            node.md = new Tinkerforge.BrickletRemoteSwitch(node.sensor, node.ipcon);
        });

	node.on('input', function(msg){
	    if(node.md) {
	      if (typeof msg.payload === 'number') {
	        if (msg.payload == 1) {
                      var switchto = Tinkerforge.BrickletRemoteSwitch.SWITCH_TO_ON;
		    }
		    else {
                      var switchto = Tinkerforge.BrickletRemoteSwitch.SWITCH_TO_OFF;
 		    }
                switch (node.mode) {
                case 'A':node.md.switchSocketA(node.addr1, node.addr2, switchto);break;
                case 'B':node.md.switchSocketB(node.addr1, node.addr2, switchto);break;
                }
	      }
	    }
    });

        node.on('close',function() {
            node.ipcon.disconnect();
        });
    }

    RED.nodes.registerType('Tinkerforge RemoteSwitch', tinkerForgeRemoteSwitch);
}<|endoftext|>


<commit_before>'use strict';

setTimeout(function () {
	var hoge = arguments.length <= 0 || arguments[0] === undefined ? "ほげ" : arguments[0];

	console.log(hoge);
}, 500);<commit_msg>Update initial code<commit_after>$(document).ready(() => {

});
<|endoftext|>


<commit_before>HandsomeTrello.api = {
  request: function (type, url, data, callback) {
    var self = this;

    var xhttp = new XMLHttpRequest();

    if (typeof data !== 'object') {
      data = {};
    }

    if (type.toLowerCase() !== 'get') {
      data.token = self.base.getCookie('token');
    } else if (Object.keys(data).length) {
      url += '?' + self.base.generateParamsStringFromObject(data);

      data = {};
    }

    xhttp.open(type.toUpperCase(), url, true);
    xhttp.setRequestHeader('Content-Type', 'application/json');
    xhttp.setRequestHeader('X-Requested-With', 'XMLHttpRequest');

    xhttp.onreadystatechange = function () {
      if (xhttp.readyState === 4 && xhttp.status === 200 && typeof callback === 'function' && self.base.isJSONString(xhttp.responseText)) {
        callback(JSON.parse(xhttp.responseText));
      }
    };

    xhttp.send(JSON.stringify(data));
  },
  board: {
    get: function (boardId, callback) {
      var self = this.base;

      self.request('get', 'https://trello.com/1/boards/' + boardId, {
        lists: 'open',
        cards: 'all',
        card_checklists: 'all',
        members: 'all'
      }, callback);
    }
  },
  card: {
    get: function (cardId, callback) {
      var self = this.base;

      self.request('get', 'https://trello.com/1/cards/' + cardId, {
        checklists: 'all'
      }, callback);
    },
    create: function (title, columnId, pos, callback) {
      var self = this.base;

      var data = {
        name: title,
        pos: pos,
        dateLastActivity: Date.now(),
        closed: false,
        idLabels: [],
        idMembers: [],
        idBoard: self.base.data.boardId,
        idList: columnId
      };

      self.request('post', '/1/cards', data, callback);
    }
  },
  checklist: {
    getByCardId: function (cardId, callback) {
      var self = this.base;

      self.request('get', '/1/cards/' + cardId + '/checklists', {}, callback);
    },
    get: function (checklistId, callback) {
      var self = this.base;

      self.request('get', '/1/checklists/' + checklistId, {}, callback);
    },
    create: function (cardId, name, pos, callback) {
      var self = this.base;

      var data = {
        idCard: cardId,
        name: name,
        pos: pos
      };

      self.request('post', '/1/checklists', data, callback);
    },
    remove: function (checklistId, callback) {
      var self = this.base;

      self.request('delete', '/1/checklists/' + checklistId, {}, callback);
    },
    addItem: function (checklistId, name, pos, callback) {
      var self = this.base;

      var data = {
        name: name,
        pos: pos
      };

      self.request('post', '/1/checklists/' + checklistId + '/checkItems', data, callback);
    },
    deleteItem: function (checklistId, checkItemId, callback) {
      var self = this.base;

      var data = {
        idCheckItem: checkItemId
      };

      self.request('delete', '/1/checklists/' + checklistId + '/checkItems/' + checkItemId, data, callback);
    },
    nameItem: function (cardId, checklistId, checkItemId, name, callback) {
      var self = this.base;

      var data = {
        idChecklist: checklistId,
        idCheckItem: checkItemId,
        value: name
      };

      self.request('put', '/1/cards/' + cardId + '/checklist/' + checklistId + '/checkItem/' + checkItemId + '/name', data, callback);
    },
    posItem: function (cardId, checklistId, checkItemId, pos, callback) {
      var self = this.base;

      var data = {
        idChecklist: checklistId,
        idCheckItem: checkItemId,
        value: pos
      };

      self.request('put', '/1/cards/' + cardId + '/checklist/' + checklistId + '/checkItem/' + checkItemId + '/pos', data, callback);
    }
  },
  member: {
    get: function (username, data, callback) {
      var self = this.base;

      self.request('get', '/1/members/' + username, data, callback);
    }
  }
};
<commit_msg>Add queue to api request method<commit_after>HandsomeTrello.api = {
  queue: [],

  running: false,

  request: function () {
    var self = this;

    if (!self.queue.length) {
      self.running = false;

      return false;
    }

    if (self.running) {
      return false;
    }

    self.running = true;

    var requestData = self.queue[0],
        xhttp = new XMLHttpRequest();

    if (typeof requestData.data !== 'object') {
      requestData.data = {};
    }

    if (requestData.type.toLowerCase() !== 'get') {
      requestData.data.token = self.base.getCookie('token');
    } else if (Object.keys(requestData.data).length) {
      requestData.url += '?' + self.base.generateParamsStringFromObject(requestData.data);

      requestData.data = {};
    }

    xhttp.open(requestData.type.toUpperCase(), requestData.url, true);
    xhttp.setRequestHeader('Content-Type', 'application/json');
    xhttp.setRequestHeader('X-Requested-With', 'XMLHttpRequest');

    xhttp.onreadystatechange = function () {
      if (xhttp.readyState === 4) {
        if (xhttp.status === 200 && typeof requestData.callback === 'function' && self.base.isJSONString(xhttp.responseText)) {
          requestData.callback(JSON.parse(xhttp.responseText));
        }

        self.queue.splice(0, 1);

        self.running = false;

        self.request();
      }
    };

    xhttp.send(JSON.stringify(requestData.data));
  },

  addToQueue: function (type, url, data, callback) {
    var self = this;

    self.queue.push({
      type: type,
      url: url,
      data: data,
      callback: callback
    });

    self.request();
  },

  board: {
    get: function (boardId, callback) {
      var self = this.base;

      self.addToQueue('get', 'https://trello.com/1/boards/' + boardId, {
        lists: 'open',
        cards: 'all',
        card_checklists: 'all',
        members: 'all'
      }, callback);
    }
  },

  card: {
    get: function (cardId, callback) {
      var self = this.base;

      self.addToQueue('get', 'https://trello.com/1/cards/' + cardId, {
        checklists: 'all'
      }, callback);
    },
    create: function (title, columnId, pos, callback) {
      var self = this.base;

      var data = {
        name: title,
        pos: pos,
        dateLastActivity: Date.now(),
        closed: false,
        idLabels: [],
        idMembers: [],
        idBoard: self.base.data.boardId,
        idList: columnId
      };

      self.addToQueue('post', '/1/cards', data, callback);
    }
  },

  checklist: {
    getByCardId: function (cardId, callback) {
      var self = this.base;

      self.addToQueue('get', '/1/cards/' + cardId + '/checklists', {}, callback);
    },
    get: function (checklistId, callback) {
      var self = this.base;

      self.addToQueue('get', '/1/checklists/' + checklistId, {}, callback);
    },
    create: function (cardId, name, pos, callback) {
      var self = this.base;

      var data = {
        idCard: cardId,
        name: name,
        pos: pos
      };

      self.addToQueue('post', '/1/checklists', data, callback);
    },
    remove: function (checklistId, callback) {
      var self = this.base;

      self.addToQueue('delete', '/1/checklists/' + checklistId, {}, callback);
    },
    addItem: function (checklistId, name, pos, callback) {
      var self = this.base;

      var data = {
        name: name,
        pos: pos
      };

      self.addToQueue('post', '/1/checklists/' + checklistId + '/checkItems', data, callback);
    },
    deleteItem: function (checklistId, checkItemId, callback) {
      var self = this.base;

      var data = {
        idCheckItem: checkItemId
      };

      self.addToQueue('delete', '/1/checklists/' + checklistId + '/checkItems/' + checkItemId, data, callback);
    },
    nameItem: function (cardId, checklistId, checkItemId, name, callback) {
      var self = this.base;

      var data = {
        idChecklist: checklistId,
        idCheckItem: checkItemId,
        value: name
      };

      self.addToQueue('put', '/1/cards/' + cardId + '/checklist/' + checklistId + '/checkItem/' + checkItemId + '/name', data, callback);
    },
    posItem: function (cardId, checklistId, checkItemId, pos, callback) {
      var self = this.base;

      var data = {
        idChecklist: checklistId,
        idCheckItem: checkItemId,
        value: pos
      };

      self.addToQueue('put', '/1/cards/' + cardId + '/checklist/' + checklistId + '/checkItem/' + checkItemId + '/pos', data, callback);
    }
  },

  member: {
    get: function (username, data, callback) {
      var self = this.base;

      self.addToQueue('get', '/1/members/' + username, data, callback);
    }
  }
};
<|endoftext|>


<commit_before>var tpl = {

    // Hash of preloaded templates for the app
    templates:{},

    // Recursively pre-load all the templates for the app.
    // This implementation should be changed in a production environment. All the template files should be
    // concatenated in a single file.
    loadTemplates:function (names, callback) {

        var that = this;

        var loadTemplate = function (index) {
            var name = names[index];
            console.log('Loading template: ' + name + ', index: ' + index);
            $.get('templates/' + CONFIG.LANGUAGE + '/' + name + '.html', function (data) {
                that.templates[name] = data;
                index++;
                if (index < names.length) {
                    loadTemplate(index);
                } else {
                    callback();
                }
            });
        };

        loadTemplate(0);
    },

    // Get template by name from hash of preloaded templates
    get:function (name) {
        return this.templates[name];
    }

};

(function (FMS, Backbone, _, $) {
    _.extend(FMS, {
        templates: [
            'home', 'help', 'around', 'offline', 'save_offline', 'reports', 'login', 'address_search', 'existing', 'photo', 'details', 'details_extra', 'submit', 'submit_email', 'submit_name', 'submit_set_password', 'submit_password', 'submit_confirm', 'sent'
        ],

        usedBefore: 0,
        isLoggedIn: 0,
        isOffline: 0,
        initialized: 0,
        users: new FMS.Users(),
        currentUser: null,
        currentPosition: null,
        isAndroid: false,
        iPhoneModel: 0,
        uploadTimeout: CONFIG.UPLOAD_TIMEOUT || 120000,

        currentDraft: new FMS.Draft(),
        allDrafts: new FMS.Drafts(),

        reportToView: null,

        online: function() {
            FMS.isOffline = 0;
        },

        offline: function() {
            FMS.isOffline = 1;
        },

        checkOnlineStatus: function() {
            if ( navigator && navigator.connection && ( navigator.connection.type == Connection.NONE ||
                    navigator.connection.type == Connection.UNKNOWN ) ) {
                FMS.offline();
            } else {
                FMS.online();
            }
        },

        checkLoggedInStatus: function() {
            if ( FMS.isOffline ) {
            } else {
                $.ajax( {
                    url: CONFIG.FMS_URL + '/auth/ajax/check_auth',
                    type: 'GET',
                    dataType: 'json',
                    timeout: 30000,
                    success: function( data, status ) {
                        FMS.isLoggedIn = 1;
                    },
                    error: function() {
                        FMS.isLoggedIn = 0;
                    }
                } );
            }
        },

        saveCurrentDraft: function(force) {
            FMS.router.pause();
            if ( force || FMS.currentDraft.isPartial() ) {
                FMS.allDrafts.add( FMS.currentDraft );
                FMS.currentDraft.save();
                localStorage.currentDraftID = FMS.currentDraft.id;
            }
        },

        loadCurrentDraft: function() {
            if ( localStorage.currentDraftID && localStorage.currentDraftID != 'null' ) {
                var r = FMS.allDrafts.get( localStorage.currentDraftID );
                if ( r ) {
                    FMS.currentDraft = r;
                }
            }
            localStorage.currentDraftID = null;
        },

        removeDraft: function(draftID, removePhoto) {
            var draft = FMS.allDrafts.get(draftID);
            var uri = draft.get('file');
            FMS.allDrafts.remove(draft);
            draft.destroy();

            if ( removePhoto && uri ) {
                return FMS.files.deleteURI( uri );
            }
            var p = $.Deferred();
            p.resolve();
            return p;
        },

        setCurrentDraft: function(draft) {
            FMS.currentDraft = draft;
            localStorage.currentDraftID = draft.id;
        },

        clearCurrentDraft: function() {
            FMS.currentDraft = new FMS.Draft();
            localStorage.currentDraftID = null;
        },

        openExternal: function(e) {
            e.preventDefault();
            var el = $(e.srcElement);
            window.open(el.attr('href'), '_system');
            return false;
        },

        setupHelp: function() {
            var help = $('#help'),
            helpContent = $('#helpContent'),
            viewWidth = $(window).width(),
            viewHeight = $(window).height(),
            helpHeight = viewHeight;

            var template = _.template( tpl.get('help') );
            helpContent.html(template());

            if ( !help.hasClass('android2') ) {
                helpContent.height(helpHeight - 60);
            }
            help.css('left', viewWidth);
            help.show();
        },

        helpShow: function(e) {
            if (e) {
                e.preventDefault();
            }
            var help = $('#help');
            $('#display-help').hide();
            var onShow = function() {
                $('#help').show();
                $('#dismiss').show();
            };
            help.animate({left: 0}, onShow );
        },

        helpHide: function(e) {
            if (e) {
                e.preventDefault();
            }
            var help = $('#help'),
            viewWidth = $(window).width();

            $('#dismiss').hide();
            if ( help.hasClass('android2') ) {
                $('body').scrollTop(0);
            }
            var onHide = function() {
                $('#display-help').show();
                $('#helpContent').scrollTop(0);
            };
            help.animate({left: viewWidth}, 400, 'swing', onHide );
        },

        helpViewed: function() {
            FMS.usedBefore = 1;
            localStorage.usedBefore = 1;
        },

        initialize: function () {
            if ( this.initialized == 1 ) {
                return this;
            }
            $('#load-screen').height( $(window).height() );
            FMS.initialized = 1;
            if ( navigator && navigator.splashscreen ) {
                navigator.splashscreen.hide();
            }
            tpl.loadTemplates( FMS.templates, function() {

                if ( typeof device !== 'undefined' && device.platform === 'Android' ) {
                    $.mobile.defaultPageTransition = 'none';
                    FMS.isAndroid = true;
                    if ( parseInt(device.version) < 3 ) {
                        $('#help').addClass('android2');
                    }
                }

                if ( typeof device !== 'undefined' && device.platform === 'iOS' ) {
                    var model = parseInt(device.model.replace('iPhone',''), 10);
                    FMS.iPhoneModel = model;
                }

                _.extend(FMS, {
                    router: new FMS.appRouter(),
                    locator: new FMS.Locate()
                });
                _.extend( FMS.locator, Backbone.Events );

                // we only ever have the details of one user
                FMS.users.fetch();
                if ( FMS.users.length > 0 ) {
                    FMS.currentUser = FMS.users.get(1);
                }
                if ( FMS.currentUser === null ) {
                    FMS.currentUser = new FMS.User({id: 1});
                }

                if ( localStorage.usedBefore ) {
                    FMS.usedBefore = 1;
                }

                document.addEventListener('pause', function() { FMS.locator.stopTracking(); FMS.saveCurrentDraft(); }, false);
                document.addEventListener('resume', onResume, false);
                document.addEventListener('backbutton', function(e) { FMS.router.back(e); }, true);
                document.addEventListener('offline', function() { FMS.offline(); }, true);
                document.addEventListener('online', function() { FMS.online(); }, true);

                $(document).on('ajaxStart', function() { $.mobile.loading('show'); } );
                $(document).on('ajaxStop', function() { $.mobile.loading('hide'); } );

                $('#display-help').on('vclick', function(e) { FMS.helpShow(e); } );
                $('#dismiss').on('vclick', function(e) { FMS.helpHide(e); } );

                FMS.allDrafts.comparator = function(a,b) { var a_date = a.get('created'), b_date = b.get('created'); return a_date === b_date ? 0 : a_date < b_date ? 1 : -1; };
                FMS.allDrafts.fetch();
                FMS.checkOnlineStatus();
                FMS.loadCurrentDraft();
                FMS.checkLoggedInStatus();
                FMS.setupHelp();

                Backbone.history.start();
                navigator.splashscreen.hide();
                $('#display-help').show();
            });
        }
    });

    function onResume() {
        FMS.checkOnlineStatus();
        FMS.loadCurrentDraft();
        if ( ( FMS.router.currentView.id == 'front-page' || FMS.router.currentView.id == 'around-page' ) && FMS.currentPosition !== null ) {
            FMS.locator.trackPosition();
        }
    }
})(FMS, Backbone, _, $);

var androidStartUp = function() {
    // deviceready does not fire on some android versions very reliably so
    // we do this instead

    if (FMS.initialized === 1) {
        return;
    }

    if ( typeof device != 'undefined' ) {
        if ( device.platform == 'Android' ) {
            FMS.initialize();
        }
    } else {
        window.setTimeout( androidStartUp, 1000 );
    }
};

function onload() {
    document.addEventListener('deviceready', FMS.initialize, false);
    window.setTimeout( androidStartUp, 2000 );
}
<commit_msg>Fix android 2 scrolling caused by help<commit_after>var tpl = {

    // Hash of preloaded templates for the app
    templates:{},

    // Recursively pre-load all the templates for the app.
    // This implementation should be changed in a production environment. All the template files should be
    // concatenated in a single file.
    loadTemplates:function (names, callback) {

        var that = this;

        var loadTemplate = function (index) {
            var name = names[index];
            console.log('Loading template: ' + name + ', index: ' + index);
            $.get('templates/' + CONFIG.LANGUAGE + '/' + name + '.html', function (data) {
                that.templates[name] = data;
                index++;
                if (index < names.length) {
                    loadTemplate(index);
                } else {
                    callback();
                }
            });
        };

        loadTemplate(0);
    },

    // Get template by name from hash of preloaded templates
    get:function (name) {
        return this.templates[name];
    }

};

(function (FMS, Backbone, _, $) {
    _.extend(FMS, {
        templates: [
            'home', 'help', 'around', 'offline', 'save_offline', 'reports', 'login', 'address_search', 'existing', 'photo', 'details', 'details_extra', 'submit', 'submit_email', 'submit_name', 'submit_set_password', 'submit_password', 'submit_confirm', 'sent'
        ],

        usedBefore: 0,
        isLoggedIn: 0,
        isOffline: 0,
        initialized: 0,
        users: new FMS.Users(),
        currentUser: null,
        currentPosition: null,
        isAndroid: false,
        iPhoneModel: 0,
        uploadTimeout: CONFIG.UPLOAD_TIMEOUT || 120000,

        currentDraft: new FMS.Draft(),
        allDrafts: new FMS.Drafts(),

        reportToView: null,

        online: function() {
            FMS.isOffline = 0;
        },

        offline: function() {
            FMS.isOffline = 1;
        },

        checkOnlineStatus: function() {
            if ( navigator && navigator.connection && ( navigator.connection.type == Connection.NONE ||
                    navigator.connection.type == Connection.UNKNOWN ) ) {
                FMS.offline();
            } else {
                FMS.online();
            }
        },

        checkLoggedInStatus: function() {
            if ( FMS.isOffline ) {
            } else {
                $.ajax( {
                    url: CONFIG.FMS_URL + '/auth/ajax/check_auth',
                    type: 'GET',
                    dataType: 'json',
                    timeout: 30000,
                    success: function( data, status ) {
                        FMS.isLoggedIn = 1;
                    },
                    error: function() {
                        FMS.isLoggedIn = 0;
                    }
                } );
            }
        },

        saveCurrentDraft: function(force) {
            FMS.router.pause();
            if ( force || FMS.currentDraft.isPartial() ) {
                FMS.allDrafts.add( FMS.currentDraft );
                FMS.currentDraft.save();
                localStorage.currentDraftID = FMS.currentDraft.id;
            }
        },

        loadCurrentDraft: function() {
            if ( localStorage.currentDraftID && localStorage.currentDraftID != 'null' ) {
                var r = FMS.allDrafts.get( localStorage.currentDraftID );
                if ( r ) {
                    FMS.currentDraft = r;
                }
            }
            localStorage.currentDraftID = null;
        },

        removeDraft: function(draftID, removePhoto) {
            var draft = FMS.allDrafts.get(draftID);
            var uri = draft.get('file');
            FMS.allDrafts.remove(draft);
            draft.destroy();

            if ( removePhoto && uri ) {
                return FMS.files.deleteURI( uri );
            }
            var p = $.Deferred();
            p.resolve();
            return p;
        },

        setCurrentDraft: function(draft) {
            FMS.currentDraft = draft;
            localStorage.currentDraftID = draft.id;
        },

        clearCurrentDraft: function() {
            FMS.currentDraft = new FMS.Draft();
            localStorage.currentDraftID = null;
        },

        openExternal: function(e) {
            e.preventDefault();
            var el = $(e.srcElement);
            window.open(el.attr('href'), '_system');
            return false;
        },

        setupHelp: function() {
            var help = $('#help'),
            helpContent = $('#helpContent'),
            viewWidth = $(window).width(),
            viewHeight = $(window).height(),
            helpHeight = viewHeight;

            var template = _.template( tpl.get('help') );
            helpContent.html(template());

            if ( !help.hasClass('android2') ) {
                helpContent.height(helpHeight - 60);
                help.show();
            }
            help.css('left', viewWidth);
        },

        helpShow: function(e) {
            if (e) {
                e.preventDefault();
            }
            var help = $('#help');
            $('#display-help').hide();
            var onShow = function() {
                $('#help').show();
                $('#dismiss').show();
            };
            help.animate({left: 0}, onShow );
        },

        helpHide: function(e) {
            if (e) {
                e.preventDefault();
            }
            var help = $('#help'),
            viewWidth = $(window).width();

            $('#dismiss').hide();
            if ( help.hasClass('android2') ) {
                $('body').scrollTop(0);
            }
            var onHide = function() {
                $('#display-help').show();
                $('#helpContent').scrollTop(0);
                if ( $('#help').hasClass('android2') ) {
                    $('#help').hide();
                }
            };
            help.animate({left: viewWidth}, 400, 'swing', onHide );
        },

        helpViewed: function() {
            FMS.usedBefore = 1;
            localStorage.usedBefore = 1;
        },

        initialize: function () {
            if ( this.initialized == 1 ) {
                return this;
            }
            $('#load-screen').height( $(window).height() );
            FMS.initialized = 1;
            if ( navigator && navigator.splashscreen ) {
                navigator.splashscreen.hide();
            }
            tpl.loadTemplates( FMS.templates, function() {

                if ( typeof device !== 'undefined' && device.platform === 'Android' ) {
                    $.mobile.defaultPageTransition = 'none';
                    FMS.isAndroid = true;
                    if ( parseInt(device.version) < 3 ) {
                        $('#help').addClass('android2');
                    }
                }

                if ( typeof device !== 'undefined' && device.platform === 'iOS' ) {
                    var model = parseInt(device.model.replace('iPhone',''), 10);
                    FMS.iPhoneModel = model;
                }

                _.extend(FMS, {
                    router: new FMS.appRouter(),
                    locator: new FMS.Locate()
                });
                _.extend( FMS.locator, Backbone.Events );

                // we only ever have the details of one user
                FMS.users.fetch();
                if ( FMS.users.length > 0 ) {
                    FMS.currentUser = FMS.users.get(1);
                }
                if ( FMS.currentUser === null ) {
                    FMS.currentUser = new FMS.User({id: 1});
                }

                if ( localStorage.usedBefore ) {
                    FMS.usedBefore = 1;
                }

                document.addEventListener('pause', function() { FMS.locator.stopTracking(); FMS.saveCurrentDraft(); }, false);
                document.addEventListener('resume', onResume, false);
                document.addEventListener('backbutton', function(e) { FMS.router.back(e); }, true);
                document.addEventListener('offline', function() { FMS.offline(); }, true);
                document.addEventListener('online', function() { FMS.online(); }, true);

                $(document).on('ajaxStart', function() { $.mobile.loading('show'); } );
                $(document).on('ajaxStop', function() { $.mobile.loading('hide'); } );

                $('#display-help').on('vclick', function(e) { FMS.helpShow(e); } );
                $('#dismiss').on('vclick', function(e) { FMS.helpHide(e); } );

                FMS.allDrafts.comparator = function(a,b) { var a_date = a.get('created'), b_date = b.get('created'); return a_date === b_date ? 0 : a_date < b_date ? 1 : -1; };
                FMS.allDrafts.fetch();
                FMS.checkOnlineStatus();
                FMS.loadCurrentDraft();
                FMS.checkLoggedInStatus();
                FMS.setupHelp();

                Backbone.history.start();
                navigator.splashscreen.hide();
                $('#display-help').show();
            });
        }
    });

    function onResume() {
        FMS.checkOnlineStatus();
        FMS.loadCurrentDraft();
        if ( ( FMS.router.currentView.id == 'front-page' || FMS.router.currentView.id == 'around-page' ) && FMS.currentPosition !== null ) {
            FMS.locator.trackPosition();
        }
    }
})(FMS, Backbone, _, $);

var androidStartUp = function() {
    // deviceready does not fire on some android versions very reliably so
    // we do this instead

    if (FMS.initialized === 1) {
        return;
    }

    if ( typeof device != 'undefined' ) {
        if ( device.platform == 'Android' ) {
            FMS.initialize();
        }
    } else {
        window.setTimeout( androidStartUp, 1000 );
    }
};

function onload() {
    document.addEventListener('deviceready', FMS.initialize, false);
    window.setTimeout( androidStartUp, 2000 );
}
<|endoftext|>


<commit_before>var UI    = require('ui');
var Ajax  = require('ajax');
var Vibe  = require('ui/vibe');
var Accel = require('ui/accel');

var debug = 1;
var counter = 0; // parseInt(localStorage.getItem('counter')) || 0; // If the variable counter exists, pull it from the "localStorage" else initialize to zero.
var subredditcounter = 1;
var items = [];

var start_time = new Date().valueOf(), new_time, time_diff;
var start_force = 12, new_force, force_diff;

var pass = 0;
var start = false;
var URL;
var initialized = false;

//Listeners
Pebble.addEventListener("ready", function() {
  console.log("ready called!");
  initialized = true;
});

Pebble.addEventListener("showConfiguration",
  function(e) {
    Pebble.openURL("http://readdit.s3-website-us-east-1.amazonaws.com/"); // our dyanmic configuration page
  }
);
var options;
Pebble.addEventListener("webviewclosed",
  function(e) {
  if(e.response!= "CANCELED")
    {
  options = JSON.parse(decodeURIComponent(e.response));
  console.log("Options = " + JSON.stringify(options));
  localStorage.setItem('subreddit1',options.subreddit1.toLowerCase());
  localStorage.setItem('sortby1', options.sortby1.toLowerCase());
  URL = "http://reddit.com/r/" + options.subreddit1.toLowerCase() + "/" + options.sortby.toLowerCase() + "/.json";
  localStorage.setItem('subreddit2',options.subreddit2.toLowerCase());
  localStorage.setItem('sortby2',options.sortby2.toLowerCase());
    }
  }
);

// Vibration for installation
if (debug == 1) Vibe.vibrate('short');

// Initial UI
var main = new UI.Card({
  title: items.childern[0].data.score+" upvotes",
  subtitle: '',
  body: items.childern[0].data.title

});

main.show();
URL = "http://reddit.com/r/" + localStorage.getItem('subreddit1') + "/" + localStorage.getItem('sortby1') +  "/.json";

// Get datalove from reddit
Ajax({ url: URL, type: 'json' }, function(resp) {
  items = resp.data;
});

// Accelerometer
Accel.init();
/*
Accel.config({
  rate: 25,
  samples: 1,
  subscribe: true
});*/

// Scroll the list up or down
// This function is called on button click and accelerometer thing
function scroll_list(way) {
  if(way === 'down' && counter < 24)
     ++counter;
  else if(way === 'down' && counter === 24 )
    counter = 0;
  else if(way === 'up' && counter > 0)
    --counter;
  else if(way === 'up' && counter === 0)
    counter = 24;

  main.title(items.children[counter].data.score + " upvotes");
  main.subtitle("");
  //main.subtitle(items.children[counter].data.domain);
  main.body(items.children[counter].data.title);

  if (debug == 1) console.log("Counter: " + counter + "\n");

  localStorage.setItem('counter', counter);
}
function scroll_subreddit(way)
{
  if(way === 'down' && subredditcounter < 5)
    ++subredditcounter;
  else if(way === 'up' && subredditcounter > 0)
    --subredditcounter;
  URL = "http://reddit.com/r/" + localStorage.getItem('subreddit'+String(subredditcounter)) + "/" + localStorage.getItem('sortby' + String(subredditcounter)) + "/.json"
  counter = 0;
  main.title(items.children[counter].data.score + " upvotes");
  main.subtitle("");
  main.body(items.childern[counter].data.title);

}

// Monitor button clicks and call appropriate function
main.on('click', function(e) {
  switch (e.button) {
    case 'up' :
      scroll_list('up');
      start = true;
      console.log(URL);
      break;
    case 'down' :
      scroll_list('down');
      start = true;
      console.log(URL);
      break;

    // Link (page and comments) opening
    case 'select' :
      if(counter > 0)
        Pebble.openURL("http://reddit.com/" + items.children[counter-1].data.permalink + ".compact");
      break;

    default :
      if (debug == 1) console.log('lolwut');
      break;
  }
});
main.on('longClick', 'down', function(e){
    console.log("DOWN CLICK");
    scroll_subreddit('down');

});

main.on('accelTap', function(e) {
  /* if (pass > 0) {
    pass--;
    return;
  } */
  scroll_list(e.direction > 0 ? 'up' : 'down');
  // pass += 1;
});
<commit_msg>added multiple subreddit scrolling<commit_after>var UI    = require('ui');
var Ajax  = require('ajax');
var Vibe  = require('ui/vibe');
var Accel = require('ui/accel');

var debug = 1;
var counter = 0; // parseInt(localStorage.getItem('counter')) || 0; // If the variable counter exists, pull it from the "localStorage" else initialize to zero.
var items = [];
var subredditcounter = 1;
var start_time = new Date().valueOf(), new_time, time_diff;
var start_force = 12, new_force, force_diff;

var pass = 0;
var start = false;
var URL;
var initialized = false;

//Listeners
Pebble.addEventListener("ready", function() {
  console.log("ready called!");
  initialized = true;
});

Pebble.addEventListener("showConfiguration",
  function(e) {
    Pebble.openURL("http://readdit.s3-website-us-east-1.amazonaws.com/"); // our dyanmic configuration page
  }
);
var options;
Pebble.addEventListener("webviewclosed",
  function(e) {
  if(e.response!= "CANCELED")
    {
  options = JSON.parse(decodeURIComponent(e.response));
  console.log("Options = " + JSON.stringify(options));
  console.log(options.sortby1.toLowerCase());
  console.log("\n http://reddit.com/r/" + localStorage.getItem('subreddit1') + "/" + localStorage.getItem('sortby1') +  "/.json");
  localStorage.setItem('subreddit1',options.subreddit1.toLowerCase());
  localStorage.setItem('sortby1', options.sortby1.toLowerCase());
  localStorage.setItem('subreddit2',options.subreddit2.toLowerCase());
  localStorage.setItem('sortby2',options.sortby2.toLowerCase());
  //console.log(localStorage.getItem('subreddit1'));
  //console.log(localStorage.getItem('sortby1'));

      }
  }
);

// Vibration for installation
if (debug == 1) Vibe.vibrate('short');

URL = "http://reddit.com/r/" + localStorage.getItem('subreddit1') + "/" + localStorage.getItem('sortby1') +  "/.json";

// Get datalove from reddit

Ajax({ url: URL, type: 'json' }, function(resp) {
  items = resp.data;
  console.log("\n ajax sucessful \n");
});

var main = new UI.Card({
  title: 'Readdit',
  subtitle: 'Daily provider of nonsense since 1852',
  body: ''

});

main.show();

// Accelerometer
Accel.init();
/*
Accel.config({
  rate: 25,
  samples: 1,
  subscribe: true
});*/

// Scroll the list up or down
// This function is called on button click and accelerometer thing
function scroll_list(way) {
  main.title(items.children[counter].data.score + " upvotes");
  main.subtitle("");
  //main.subtitle(items.children[counter].data.domain);
  main.body(items.children[counter].data.title);

  if (debug == 1) console.log("Counter: " + counter + "\n");

  if(way === 'down' && counter < 24)
     ++counter;
  else if(way === 'down' && counter === 24 )
    counter = 0;
  else if(way === 'up' && counter > 0)
    --counter;
  else if(way === 'up' && counter === 0)
    counter = 24;

  localStorage.setItem('counter', counter);
}

// Monitor button clicks and call appropriate function
main.on('click', function(e) {
  switch (e.button) {
    case 'up' :
      scroll_list('up');
      start = true;
      console.log(URL);
      break;
    case 'down' :
      scroll_list('down');
      start = true;
      console.log(URL);
      break;

    // Link (page and comments) opening
    case 'select' :
      if(counter > 0)
        Pebble.openURL("http://reddit.com/" + items.children[counter-1].data.permalink + ".compact");
      break;

    default :
      if (debug == 1) console.log('lolwut');
      break;
  }
});

main.on('longClick', 'down', function(e){
    console.log("DOWN CLICK");
    scroll_subreddit('down');

});

main.on('longClick', 'up', function(e)
{
  console.log("UP CLICK");
  scroll_subreddit('up');
});

function scroll_subreddit(way)
{
  //console.log("Second subreddit " + localStorage.getItem('subreddit2'));
  if(way === 'down' && subredditcounter < 5)
    ++subredditcounter;
  else if(way === 'up' && subredditcounter > 0)
    --subredditcounter;
  //console.log(localStorage.getItem('subreddit'+String(subredditcounter)));
  URL = "http://reddit.com/r/" + localStorage.getItem('subreddit'+String(subredditcounter)) + "/" + localStorage.getItem('sortby' + String(subredditcounter)) + "/.json";
  //console.log(URL);
  Ajax({ url: URL, type: 'json' },
   function(resp) {
    console.log(URL);
    items = resp.data;
    console.log("\n "+ items.childern[counter].data.title + "\n");
    console.log("\n ajax finished \n");
  });
  counter = 0;
  main.title(items.children[counter].data.score + " upvotes");
  main.subtitle("");
  main.body(items.childern[counter].data.title);

}

main.on('accelTap', function(e) {
  /* if (pass > 0) {
    pass--;
    return;
  } */
  scroll_list(e.direction > 0 ? 'up' : 'down');
  // pass += 1;
});
<|endoftext|>


<commit_before>// JS Goes here - ES6 supported
// import Parallax from "parallax-js";
// const scene = document.getElementById('scene');
// const parallax = new Parallax(scene, {
//   scalarX: 4,
//   scalarY: 4
// });

import Barba from "barba.js";
const dom = Barba.Pjax.Dom;
dom.wrapperId = "js-wrapper";
dom.containerClass = "js-container";

document.addEventListener("DOMContentLoaded", () => {
    Barba.Pjax.init();
    Barba.Prefetch.init();

    // Scroll to the wrapper
    Barba.Dispatcher.on('transitionCompleted', () => {
        window.scrollTo(0, 0);
        initPhotoSwipeFromDOM(gallerySelector);
    });

    // Add transition to barba
    Barba.Pjax.getTransition = () => Transition;

    Barba.transitionLength = 250;
});
<commit_msg>fix barba js<commit_after>// JS Goes here - ES6 supported
// import Parallax from "parallax-js";
// const scene = document.getElementById('scene');
// const parallax = new Parallax(scene, {
//   scalarX: 4,
//   scalarY: 4
// });

import Barba from "barba.js";
const dom = Barba.Pjax.Dom;
dom.wrapperId = "js-wrapper";
dom.containerClass = "js-container";

Barba.Pjax.start();

// document.addEventListener("DOMContentLoaded", () => {
//     Barba.Pjax.init();
//     Barba.Prefetch.init();
//
//     // Scroll to the wrapper
//     Barba.Dispatcher.on('transitionCompleted', () => {
//         window.scrollTo(0, 0);
//     });
//
//     // Add transition to barba
//     Barba.Pjax.getTransition = () => Transition;
//
//     Barba.transitionLength = 250;
// });
<|endoftext|>


<commit_before>/*jslint nomen: true */
/*globals define: true */

/*
 * Basic app functionality for the mobile survey.
 */

define(function (require) {
  'use strict';

  var $ = require('jquery');
  var api = require('api');
  var FormView = require('form');
  var MapView = require('map');
  var appCacheManager = require('app-cache-manager');

  // Listen for status-change events and adjust the UI accordingly.
  function setupEventHandlers() {
    var $netStatusOffline = $('#net-status-offline');
    var $netStatusBackOnline = $('#net-status-back');

    $.subscribe('online', function () {
      $netStatusOffline.hide();
      $netStatusBackOnline.hide();
    });
    $.subscribe('offline', function () {
      $netStatusOffline.show();
      $netStatusBackOnline.hide();
    });
    $.subscribe('syncingResponses', function () {
      $netStatusOffline.hide();
      $netStatusBackOnline.show();
    });
    $.subscribe('syncedResponses', function () {
      $netStatusOffline.hide();
      $netStatusBackOnline.hide();
    });
  }

  var app = {
    /*
     * Show the survey & hide the front page after the sign-in form has been
     * submitted
     */
    init: function () {
      console.log("Initialize NSB");

      appCacheManager.init(function () {
        // Get the survey, slug, etv.
        var surveyPromise = api.getSurveyFromSlug();

        $('#loading-container').remove();
        $('#home-container').show();
        var $collectorName = $('#collector_name');
        var $collectorNameSubmit = $('#collector-name-submit');

        // Set the collector name, if we already know it.
        if ($.cookie('collectorName') !== null){
          $collectorName.val($.cookie('collectorName'));
        }

        $collectorNameSubmit.click(function(event) {
          $('#startpoint h2').html('Loading your survey');

          // Set a cookie with the collector's name
          console.log("Setting collector name");
          app.collectorName = $collectorName.val();
          $.cookie('collectorName', app.collectorName, { path: '/' });

          // Hide the homepage, show the survey
          $('#home-container').hide();
          $('#survey-container').show();

          // TODO: think this is deprecated / no longer necessary.
          $('body').attr('id', 'survey');

          // Wait until we have the survey data
          surveyPromise
          .done(function (survey) {
            api.init(function (error) {
              if (error) {
                $('#startpoint h2').html('Sorry, something went wrong. Please reload the page.');
                return;
              }

              setupEventHandlers();

              if (survey.type === 'point') {
                $('#startpoint h2').html('Welcome, ' + app.collectorName + '
Pan and add a point to begin');
              } else if (survey.type === 'address-point') {
                $('#startpoint h2').html('Welcome, ' + app.collectorName + '
Enter an address to begin');
              } else {
                $('#startpoint h2').html('Welcome, ' + app.collectorName + '
Tap a parcel to begin');
              }

              app.map = new MapView(app, 'map-div');
              app.f = new FormView(app, '#form');

              if (survey.type === 'address-point') {
                $.publish('readyForAddressForm');
              }
            });
          })
          .fail(function (jqXHR) {
            if (jqXHR.status === 404) {
              // Survey was not found
              $('#startpoint h2').html('Sorry, we couldn\'t find the survey. Please check the URL or contact the survey organizer.');
            } else {
              // Unknown error
              $('#startpoint h2').html('Sorry, something has gone wrong. Please try again in a bit or contact the survey organizer.');
            }
          });
        });
      });
    },

    // We'll use this to keep track of the object currently selected in the app
    selectedObject: {}
  };

  return app;
});
<commit_msg>Use 'select a location' language<commit_after>/*jslint nomen: true */
/*globals define: true */

/*
 * Basic app functionality for the mobile survey.
 */

define(function (require) {
  'use strict';

  var $ = require('jquery');
  var api = require('api');
  var FormView = require('form');
  var MapView = require('map');
  var appCacheManager = require('app-cache-manager');

  // Listen for status-change events and adjust the UI accordingly.
  function setupEventHandlers() {
    var $netStatusOffline = $('#net-status-offline');
    var $netStatusBackOnline = $('#net-status-back');

    $.subscribe('online', function () {
      $netStatusOffline.hide();
      $netStatusBackOnline.hide();
    });
    $.subscribe('offline', function () {
      $netStatusOffline.show();
      $netStatusBackOnline.hide();
    });
    $.subscribe('syncingResponses', function () {
      $netStatusOffline.hide();
      $netStatusBackOnline.show();
    });
    $.subscribe('syncedResponses', function () {
      $netStatusOffline.hide();
      $netStatusBackOnline.hide();
    });
  }

  var app = {
    /*
     * Show the survey & hide the front page after the sign-in form has been
     * submitted
     */
    init: function () {
      console.log("Initialize NSB");

      appCacheManager.init(function () {
        // Get the survey, slug, etv.
        var surveyPromise = api.getSurveyFromSlug();

        $('#loading-container').remove();
        $('#home-container').show();
        var $collectorName = $('#collector_name');
        var $collectorNameSubmit = $('#collector-name-submit');

        // Set the collector name, if we already know it.
        if ($.cookie('collectorName') !== null){
          $collectorName.val($.cookie('collectorName'));
        }

        $collectorNameSubmit.click(function(event) {
          $('#startpoint h2').html('Loading your survey');

          // Set a cookie with the collector's name
          console.log("Setting collector name");
          app.collectorName = $collectorName.val();
          $.cookie('collectorName', app.collectorName, { path: '/' });

          // Hide the homepage, show the survey
          $('#home-container').hide();
          $('#survey-container').show();

          // TODO: think this is deprecated / no longer necessary.
          $('body').attr('id', 'survey');

          // Wait until we have the survey data
          surveyPromise
          .done(function (survey) {
            api.init(function (error) {
              if (error) {
                $('#startpoint h2').html('Sorry, something went wrong. Please reload the page.');
                return;
              }

              setupEventHandlers();

              if (survey.type === 'point') {
                $('#startpoint h2').html('Welcome, ' + app.collectorName + '
Pan and add a point to begin');
              } else if (survey.type === 'address-point') {
                $('#startpoint h2').html('Welcome, ' + app.collectorName + '
Enter an address to begin');
              } else {
                $('#startpoint h2').html('Welcome, ' + app.collectorName + '
Select a location to begin');
              }

              app.map = new MapView(app, 'map-div');
              app.f = new FormView(app, '#form');

              if (survey.type === 'address-point') {
                $.publish('readyForAddressForm');
              }
            });
          })
          .fail(function (jqXHR) {
            if (jqXHR.status === 404) {
              // Survey was not found
              $('#startpoint h2').html('Sorry, we couldn\'t find the survey. Please check the URL or contact the survey organizer.');
            } else {
              // Unknown error
              $('#startpoint h2').html('Sorry, something has gone wrong. Please try again in a bit or contact the survey organizer.');
            }
          });
        });
      });
    },

    // We'll use this to keep track of the object currently selected in the app
    selectedObject: {}
  };

  return app;
});
<|endoftext|>


<commit_before>/**
 * Welcome to Pebble.js!
 *
 * This is where you write your app.
 */

var UI = require('ui');
var Vector2 = require('vector2');
var ajax = require('ajax');

function parseStepData(data){
    var steps = [];
    var i = 0;

    while(i < Object.keys(data[1].steps).length){
        var step = {
            title: 'Step ' + (i+1) + ' - ' + data[1].steps[i.toString()]
        }

        steps.push(step);

        i++;

    };

    return steps;
}

function getStep(data, step){
    return data[1].steps[step.toString()]
}

var main = new UI.Card({
    title: 'BBC Food',
    subtitle: 'v0.1',
    body: 'Hit any button to grab a random recipe!'
});

main.show();

main.on('click', 'up', function(e) {
    console.warn('Initialising application, grabbing data...');

    ajax({
        url: 'http://blog.jacob.uk.com:9111',
        type: 'json'
    },
    function(data) {
        var menu = new UI.Menu({
            sections: [{
                title: data[0].summary.title,
                items: [
                    {
                        title: 'About this dish',
                    }, {
                        title: 'Preperation',
                    }
                ]
            }]
        });

        menu.on('select', function(e) {
            if(e.itemIndex == 0){
                var card = new UI.Card();
                card.title('About this dish');
                card.body(data[0].summary.title);
                card.scrollable(true);
                card.style('large');
                card.show();
            }else if(e.itemIndex == 1){
                 var prep = new UI.Menu({
                    sections: [{
                        title: data[0].summary.title,
                        items: parseStepData(data)
                    }]
                });

                prep.on('select', function(e) {
                    console.log('selecting!')
                    var card = new UI.Card();
                    card.title('Step ' + (e.itemIndex + 1));
                    card.body(getStep(data, e.itemIndex));
                    card.scrollable(true);
                    card.style('large')
                    card.show();
                });

                prep.show();
            }
        });

        menu.show();
    },
    function(error) {
        var card = new UI.Card();
        card.title('Oops...');
        card.body('There was an issue, restart the app.');
        card.show();
    });
});

<commit_msg>Cleaning up code<commit_after>var UI = require('ui'),
    ajax = require('ajax');

function parseStepData(data){
    var steps = [];
    var i = 0;

    while(i < Object.keys(data[1].steps).length){
        var step = {
            title: 'Step ' + (i+1) + ' - ' + data[1].steps[i.toString()]
        };

        steps.push(step);
        i++;
    }

    return steps;
}

function getStep(data, step){
    return data[1].steps[step.toString()];
}

var main = new UI.Card({
    title: 'BBC Food',
    subtitle: 'v0.1',
    body: 'Hit any button to grab a random recipe!'
});

main.show();

main.on('click', 'up', function(e) {
    console.warn('Initialising application, grabbing data...');

    ajax({
        url: 'http://blog.jacob.uk.com:9111',
        type: 'json'
    },
    function(data) {
        var menu = new UI.Menu({
            sections: [{
                title: data[0].summary.title,
                items: [
                    {
                        title: 'About this dish',
                    }, {
                        title: 'Preperation',
                    }
                ]
            }]
        });

        menu.on('select', function(e) {
            if(e.itemIndex === 0){
                var card = new UI.Card({
                  title: 'About this dish',
                  body: data[0].summary.title,
                  scrollable: true,
                  style: 'large'
                });

                card.show();
            }else if(e.itemIndex == 1){
                 var prep = new UI.Menu({
                    sections: [{
                        title: data[0].summary.title,
                        items: parseStepData(data)
                    }]
                });

                prep.on('select', function(e) {
                    var card = new UI.Card();
                    card.title('Step ' + (e.itemIndex + 1));
                    card.body(getStep(data, e.itemIndex));
                    card.scrollable(true);
                    card.style('large');
                    card.show();
                });

                prep.show();
            }
        });

        menu.show();
    },
    function(error) {
        var card = new UI.Card({
          title: 'Oops...',
          body: 'Couldn\'t get recipe, check your internet connection'
        });

        card.show();
    });
});
<|endoftext|>


<commit_before>// Get Hash on hashchange
$(window).bind('hashchange', function () {
  getHash()
})

// Get Hash on loading page
$(document).ready(function () {
  initHolder()
  initInfo()
  getHash()
})

TRACKERS = [
  'ws://torrent.lunik.xyz:8000',
  'udp://torrent.lunik.xyz:8000',
  'http://torrent.lunik.xyz:8000/announce',
  'wss://tracker.webtorrent.io',
  'udp://tracker.internetwarriors.net:1337',
  'udp://tracker.leechers-paradise.org:6969',
  'udp://tracker.coppersurfer.tk:6969',
  'udp://exodus.desync.com:6969',
  'wss://tracker.btorrent.xyz',
  'wss://tracker.openwebtorrent.com',
  'wss://tracker.fastcast.nz'
]

// Get the hash and start torrent if there is an hash
function getHash () {
  var hash = window.location.hash.substring(1)
  hash = cleanHash(hash)
  if (hash.length > 0) {
    console.log('New Hash: ' + hash)
    var $holder = $('.holder')
    $holder.css('background', 'no-repeat center url("src/css/dashinfinity.gif")')
    var $instructions = $('.instructions')
    $instructions.text('Fetching metadata')
    download(hash)
  }
}

// turn magnet into hash
function cleanHash (hash) {
  var r = new RegExp('.*:')
  var r2 = new RegExp('&.*')
  return hash.replace(r, '').replace(r2, '')
}

// Initialise seed torrent
function initHolder () {
  var $holder = $('.holder')
  var $upload = $('.holder .upload .button')
  var $uploadBut = $('.holder .upload-but')
  var $state = $('.status')

  if (typeof window.FileReader === 'undefined') {
    $state.attr('id', 'fail')
    $state.text('Instant Share indisponible')
  } else {
    $state.attr('id', 'success')
    $state.text('Instant Share disponible')
  }

  $holder.on('dragover', function (event) {
    event.preventDefault()
    event.stopPropagation()
    this.id = 'hover'
    return false
  })

  $holder.on('dragleave', function (event) {
    event.preventDefault()
    event.stopPropagation()
    this.id = ''
    return false
  })

  $holder.on('drop', function (event) {
    this.id = ''
    event.preventDefault()
    event.stopPropagation()
    var file = event.originalEvent.dataTransfer.files[0]
    updateFileName(file.name)
    seed(file)
  })

  $upload.click(function () {
    $uploadBut.trigger('click')
  })

  $uploadBut.on('change', function () {
    updateFileName(this.files[0].name)
    seed(this.files[0])
  })
}

// Seed a file
function seed (file) {
  console.log(file)
  var client = new WebTorrent()
  var torrent = client.seed(file, {
    announce: TRACKERS
  }, onTorrentSeed)
  initTorrent(torrent)
}

// Initialise event on torrent
function initTorrent (torrent) {
  var $holder = $('.holder')
  var $instructions = $('.instructions')

  torrent.on('metadata', function () {
    updateFileName(torrent.name)
  })

  torrent.on('ready', function () {
    appendHolder(torrent)
  })

  torrent.on('download', function (chunkSize) {
    updateData(torrent.uploaded, torrent.downloaded, torrent.uploadSpeed, torrent.downloadSpeed)
    updatePeer(torrent.numPeers)
    updateProgress(Math.round(torrent.progress * 100))
    $instructions.text('Downloading')
  })

  torrent.on('wire', function (wire) {
    console.log('new peer: ' + wire.remoteAddress + ':' + wire.remotePort)
    updatePeer(torrent.numPeers)
  })

  torrent.on('done', function () {
    console.log('torrent finished downloading')
    updatePeer(torrent.numPeers)
    updateData(torrent.uploaded, torrent.downloaded, torrent.uploadSpeed, torrent.downloadSpeed)
    $holder.css('background', '')
  })

  torrent.on('upload', function (data) {
    updateData(torrent.uploaded, torrent.downloaded, torrent.uploadSpeed, torrent.downloadSpeed)
    updatePeer(torrent.numPeers)
    $instructions.text('Uploading')
  })

  torrent.on('noPeers', function () {
    console.log('no peers')
    updateData(torrent.uploaded, torrent.downloaded, torrent.uploadSpeed, torrent.downloadSpeed)
    updatePeer(torrent.numPeers)
    updateProgress(Math.round(torrent.progress * 100))
    $instructions.text('Seeding')
  })
}

// Download a torrent
function download (hash) {
  cleanBody()
  var client = new WebTorrent()
  var torrent = client.add({
    infoHash: hash,
    announce: TRACKERS
  }, onTorrentDownload)
  initTorrent(torrent)
}

// Callback on torrent finish
function onTorrentDownload (torrent) {
  console.log('Downloading ' + torrent.name)
  destroy(torrent)
}

// Clean holder body
function cleanBody () {
  $('.holder').html('')
}

// Callback function when torrent is seeding
function onTorrentSeed (torrent) {
  console.log('Seeding ' + torrent.name)
  console.log('Hash: ' + torrent.infoHash)
  updatePeer(torrent.numPeers)
  appendHolder(torrent)
  var link = document.location.hostname + document.location.pathname + '/#' + torrent.infoHash
  link = link.replace(/\/+/g, '/')
  prompt('Partager le lien:', link)
  destroy(torrent)
}

// Attempt to shutdown gracefully
function destroy (torrent) {
  window.addEventListener('beforeunload', function (e) {
    torrent.destroy(console.log('torrent destroyed'))
  })
}

// Show the input with the current url
function showInputUrl (url) {
  $('.url-input').val(url)
  $('.share-link').show()
}

// Show the download button for downloading the file
function showDownloadButton (fileName, url) {
  var $but = $('.download-url')
  $but.text('Télécharger ' + fileName)
  $but.attr('href', url)
  $but.attr('download', fileName)
}

// append a torrent to the holder
function appendHolder (torrent) {
  torrent.files.forEach(function (file) {
    file.appendTo('.holder', function (err) {
      if (err) {
        appendFileIcon(file.name.split('.')[file.name.split('.').length - 1])
      } else {
        $('.holder p').remove()
      }
    })
    file.getBlobURL(function (err, url) {
      if (err) {
        console.log(err)
      }
      showDownloadButton(file.name, url)
      var link = document.location.hostname + document.location.pathname + '/#' + torrent.infoHash
      link = link.replace(/\/+/g, '/')
      showInputUrl(link)
    })
  })
}

function appendFileIcon (extention) {
  if ($('.file-icon').length <= 0) {
    var $icon = $('<i>').addClass('file-icon fa fa-5x')
    switch (extention) {
      case 'zip':
      case 'rar':
      case 'tar':
      case 'gz':
        $icon.addClass('fa-file-archive-o')
        break

      case 'avi':
      case 'mkv':
      case 'mov':
        $icon.addClass('fa-file-video-o')
        break

      default:
        $icon.addClass('fa-file-o')
    }
    $icon.appendTo('.holder')
  }
}

// initialize values for torrent info
function initInfo () {
  updateProgress(0)
  updateData(0, 0, 0, 0)
  updatePeer(0)
}

// bytes to formated data
function formatData (bytes) {
  var sizes = ['B', 'kB', 'MB', 'GB', 'TB']
  if (bytes === 0) return '0 B'
  var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)), 10)
  return Math.round(bytes / Math.pow(1024, i), 2) + ' ' + sizes[i]
}

// bits to formated speed
function formatSpeed (bits) {
  var sizes = ['b/s', 'kb/s', 'Mb/s', 'Gb/s', 'Tb/s']
  if (bits === 0) return '0 b/s'
  var i = parseInt(Math.floor(Math.log(bits) / Math.log(1024)), 10)
  return Math.round(bits / Math.pow(1024, i), 2) + ' ' + sizes[i]
}

function updateFileName (name) {
  var $holder = $('.holder')
  $holder.html($('<p>').text(name))
}
// Update progress percentage
function updateProgress (percent) {
  var $progress = $('.torrent-infos .progress p')
  $progress.text(percent + '%')
}

// Update value of peer
function updatePeer (peerNum) {
  var $peer = $('.torrent-infos .peer p')
  $peer.text(peerNum)
}

// update the value of downloaded bytes
function updateData (upBytes, downBytes, upSpeed, downSpeed) {
  var $upData = $('.torrent-infos .uploaded-data p')
  $upData.text(formatData(upBytes) + ' @' + formatSpeed(upSpeed))
  var $downData = $('.torrent-infos .downloaded-data p')
  $downData.text(formatData(downBytes) + ' @' + formatSpeed(downSpeed))
}
<commit_msg>change order<commit_after>// Get Hash on hashchange
$(window).bind('hashchange', function () {
  getHash()
})

// Get Hash on loading page
$(document).ready(function () {
  initHolder()
  initInfo()
  getHash()
})

TRACKERS = [
  'ws://torrent.lunik.xyz:8000',
  'udp://torrent.lunik.xyz:8000',
  'http://torrent.lunik.xyz:8000/announce',
  'wss://tracker.webtorrent.io',
  'udp://tracker.internetwarriors.net:1337',
  'udp://tracker.leechers-paradise.org:6969',
  'udp://tracker.coppersurfer.tk:6969',
  'udp://exodus.desync.com:6969',
  'wss://tracker.btorrent.xyz',
  'wss://tracker.openwebtorrent.com',
  'wss://tracker.fastcast.nz'
]

// Get the hash and start torrent if there is an hash
function getHash () {
  var hash = window.location.hash.substring(1)
  hash = cleanHash(hash)
  if (hash.length > 0) {
    console.log('New Hash: ' + hash)
    var $holder = $('.holder')
    $holder.css('background', 'no-repeat center url("src/css/dashinfinity.gif")')
    var $instructions = $('.instructions')
    $instructions.text('Fetching metadata')
    download(hash)
  }
}

// turn magnet into hash
function cleanHash (hash) {
  var r = new RegExp('.*:')
  var r2 = new RegExp('&.*')
  return hash.replace(r, '').replace(r2, '')
}

// Initialise seed torrent
function initHolder () {
  var $holder = $('.holder')
  var $upload = $('.holder .upload .button')
  var $uploadBut = $('.holder .upload-but')
  var $state = $('.status')

  if (typeof window.FileReader === 'undefined') {
    $state.attr('id', 'fail')
    $state.text('Instant Share indisponible')
  } else {
    $state.attr('id', 'success')
    $state.text('Instant Share disponible')
  }

  $holder.on('dragover', function (event) {
    event.preventDefault()
    event.stopPropagation()
    this.id = 'hover'
    return false
  })

  $holder.on('dragleave', function (event) {
    event.preventDefault()
    event.stopPropagation()
    this.id = ''
    return false
  })

  $holder.on('drop', function (event) {
    this.id = ''
    event.preventDefault()
    event.stopPropagation()
    var file = event.originalEvent.dataTransfer.files[0]
    updateFileName(file.name)
    seed(file)
  })

  $upload.click(function () {
    $uploadBut.trigger('click')
  })

  $uploadBut.on('change', function () {
    updateFileName(this.files[0].name)
    seed(this.files[0])
  })
}

// Initialise event on torrent
function initTorrent (torrent) {
  var $holder = $('.holder')
  var $instructions = $('.instructions')

  torrent.on('metadata', function () {
    updateFileName(torrent.name)
  })

  torrent.on('ready', function () {
    appendHolder(torrent)
  })

  torrent.on('download', function (chunkSize) {
    updateData(torrent.uploaded, torrent.downloaded, torrent.uploadSpeed, torrent.downloadSpeed)
    updatePeer(torrent.numPeers)
    updateProgress(Math.round(torrent.progress * 100))
    $instructions.text('Downloading')
  })

  torrent.on('wire', function (wire) {
    console.log('new peer: ' + wire.remoteAddress + ':' + wire.remotePort)
    updatePeer(torrent.numPeers)
  })

  torrent.on('done', function () {
    console.log('torrent finished downloading')
    updatePeer(torrent.numPeers)
    updateData(torrent.uploaded, torrent.downloaded, torrent.uploadSpeed, torrent.downloadSpeed)
    $holder.css('background', '')
  })

  torrent.on('upload', function (data) {
    updateData(torrent.uploaded, torrent.downloaded, torrent.uploadSpeed, torrent.downloadSpeed)
    updatePeer(torrent.numPeers)
    $instructions.text('Uploading')
  })

  torrent.on('noPeers', function () {
    console.log('no peers')
    updateData(torrent.uploaded, torrent.downloaded, torrent.uploadSpeed, torrent.downloadSpeed)
    updatePeer(torrent.numPeers)
    updateProgress(Math.round(torrent.progress * 100))
    $instructions.text('Seeding')
  })
}

// Download a torrent
function download (hash) {
  cleanBody()
  var client = new WebTorrent()
  var torrent = client.add({
    infoHash: hash,
    announce: TRACKERS
  }, onTorrentDownload)
  initTorrent(torrent)
}

// Callback on torrent finish
function onTorrentDownload (torrent) {
  console.log('Downloading ' + torrent.name)
  destroy(torrent)
}

// Clean holder body
function cleanBody () {
  $('.holder').html('')
}

// Seed a file
function seed (file) {
  console.log(file)
  var client = new WebTorrent()
  var torrent = client.seed(file, {
    announce: TRACKERS
  }, onTorrentSeed)
  initTorrent(torrent)
}

// Callback function when torrent is seeding
function onTorrentSeed (torrent) {
  console.log('Seeding ' + torrent.name)
  console.log('Hash: ' + torrent.infoHash)
  updatePeer(torrent.numPeers)
  appendHolder(torrent)
  var link = document.location.hostname + document.location.pathname + '/#' + torrent.infoHash
  link = link.replace(/\/+/g, '/')
  prompt('Partager le lien:', link)
  destroy(torrent)
}

// Attempt to shutdown gracefully
function destroy (torrent) {
  window.addEventListener('beforeunload', function (e) {
    torrent.destroy(console.log('torrent destroyed'))
  })
}

// Show the input with the current url
function showInputUrl (url) {
  $('.url-input').val(url)
  $('.share-link').show()
}

// Show the download button for downloading the file
function showDownloadButton (fileName, url) {
  var $but = $('.download-url')
  $but.text('Télécharger ' + fileName)
  $but.attr('href', url)
  $but.attr('download', fileName)
}

// append a torrent to the holder
function appendHolder (torrent) {
  torrent.files.forEach(function (file) {
    file.appendTo('.holder', function (err) {
      if (err) {
        appendFileIcon(file.name.split('.')[file.name.split('.').length - 1])
      } else {
        $('.holder p').remove()
      }
    })
    file.getBlobURL(function (err, url) {
      if (err) {
        console.log(err)
      }
      showDownloadButton(file.name, url)
      var link = document.location.hostname + document.location.pathname + '/#' + torrent.infoHash
      link = link.replace(/\/+/g, '/')
      showInputUrl(link)
    })
  })
}

function appendFileIcon (extention) {
  if ($('.file-icon').length <= 0) {
    var $icon = $('<i>').addClass('file-icon fa fa-5x')
    switch (extention) {
      case 'zip':
      case 'rar':
      case 'tar':
      case 'gz':
        $icon.addClass('fa-file-archive-o')
        break

      case 'avi':
      case 'mkv':
      case 'mov':
        $icon.addClass('fa-file-video-o')
        break

      default:
        $icon.addClass('fa-file-o')
    }
    $icon.appendTo('.holder')
  }
}

// initialize values for torrent info
function initInfo () {
  updateProgress(0)
  updateData(0, 0, 0, 0)
  updatePeer(0)
}

// bytes to formated data
function formatData (bytes) {
  var sizes = ['B', 'kB', 'MB', 'GB', 'TB']
  if (bytes === 0) return '0 B'
  var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)), 10)
  return Math.round(bytes / Math.pow(1024, i), 2) + ' ' + sizes[i]
}

// bits to formated speed
function formatSpeed (bits) {
  var sizes = ['b/s', 'kb/s', 'Mb/s', 'Gb/s', 'Tb/s']
  if (bits === 0) return '0 b/s'
  var i = parseInt(Math.floor(Math.log(bits) / Math.log(1024)), 10)
  return Math.round(bits / Math.pow(1024, i), 2) + ' ' + sizes[i]
}

function updateFileName (name) {
  var $holder = $('.holder')
  $holder.html($('<p>').text(name))
}
// Update progress percentage
function updateProgress (percent) {
  var $progress = $('.torrent-infos .progress p')
  $progress.text(percent + '%')
}

// Update value of peer
function updatePeer (peerNum) {
  var $peer = $('.torrent-infos .peer p')
  $peer.text(peerNum)
}

// update the value of downloaded bytes
function updateData (upBytes, downBytes, upSpeed, downSpeed) {
  var $upData = $('.torrent-infos .uploaded-data p')
  $upData.text(formatData(upBytes) + ' @' + formatSpeed(upSpeed))
  var $downData = $('.torrent-infos .downloaded-data p')
  $downData.text(formatData(downBytes) + ' @' + formatSpeed(downSpeed))
}
<|endoftext|>