<commit_before>"use strict";
/* jshint undef: true, unused: true */
/* global Applet, describe, it, expect, beforeEach */

$(function () {
});

describe('Applet:', function () {

  beforeEach(function () {
    $('#THE_STAGE').empty();
  });

  describe('id:', function () {

    it('adds ID attr to element', function () {
      var stage = $('#THE_STAGE');
      stage.html('
id
');
      var id = Applet.id($('#THE_STAGE div:first'));
      expect(
        $('#' + id).html()
      ).toEqual('id');
    }); // === it adds ID attr to element

    it('does not override original ID', function () {
      var stage = $('#THE_STAGE');
      stage.html('
override id
');
      var id = Applet.id($('#THE_STAGE div:first'));
      expect(id).toEqual('non_override_1');
    }); // === it does not override original ID

  }); // === describe id =================

  describe('attrs:', function () {

    it('returns attrs of node', function () {
      var result = Applet.attrs($('

')[0]);
      expect(result).toEqual({id: "000", img: ".png"});
    }); // === it returns attrs of node

  }); // === describe attrs =================

  describe('is_true:', function () {

    it('returns true if key is "truthy"', function () {
      expect(
        Applet.is_true({time: 'morning'}, 'time')
      ).toEqual(true);
    }); // === it returns true if key is "truthy"

    it('returns true if: !key , key is !truthy', function () {
      expect(
        Applet.is_true({time: false}, '!time')
      ).toEqual(true);
    }); // === it returns true if: !key , key is !truthy

    it('handles nested keys', function () {
      expect(
        Applet.is_true({first: {second: { third: true}}}, '!first.second.third')
      ).toEqual(true);
    }); // === it handles nested keys

    it('handles multiple exclamation marks', function () {
      expect(
        Applet.is_true({first: false}, '!!!first')
      ).toEqual(true);
    }); // === it handles multiple exclamation marks

    it('returns undefined if one non-nested key is specified, but not found', function () {
      expect(
        Applet.is_true({}, 'first')
      ).toEqual(undefined);
    }); // === it returns undefined if one non-nested key is specified, but not found

  }); // === describe is_true =================

  describe('node_array:', function () {

    it('returns an Array when passed a String', function () {
      var arr = Applet.node_array('

');

      expect(arr).toEqual([
        {
        tag:   'DIV',
        attrs:  {id: '111', show_if: 'happy?'},
        custom: {},
        childs: [
          {tag: 'SPAN', attrs: {}, custom: {}, childs: []}
        ]
      }
      ]);
    }); // === it returns an Array when passed a String

    it('returns raw text nodes', function () {
      var arr = Applet.node_array('
ab
');

      expect(
        _.pluck(arr[0].childs[0].childs, 'nodeValue')
      ).toEqual(
      ['a', undefined, 'b']
      );
    }); // === it returns raw text nodes

  }); // === describe node_array =================

  describe('compiling scripts:', function () {

    it('does not re-evaluate scripts', function () {
      $('#THE_STAGE').html('');
      Applet.run(Applet.insert_before);
      Applet.run(Applet.insert_before);
      Applet.run(Applet.insert_before);
      expect($('#THE_STAGE').html()).toEqual('
OK
');
    }); // === it does not re-evaluate scripts

    it('keeps evaulating nested scripts until done', function () {
      $('#THE_STAGE').html(
        '' +
        '</script>' +
        '</script>'
      );

      Applet.run(Applet.insert_before);
      expect(
        $('#THE_STAGE').html()
      ).toEqual('
OK
');
    }); // === it keeps evaulating nested scripts until done
  }); // === describe compiling scripts =================

}); // === describe Applet =================
<commit_msg>Dev. checkpoint.<commit_after>"use strict";
/* jshint undef: true, unused: true */
/* global Applet, describe, it, expect, beforeEach */

describe('Applet:', function () {

  beforeEach(function () {
    $('#THE_STAGE').empty();
  });

  describe('id:', function () {

    it('adds ID attr to element', function () {
      var stage = $('#THE_STAGE');
      stage.html('
id
');
      var id = Applet.id($('#THE_STAGE div:first'));
      expect(
        $('#' + id).html()
      ).toEqual('id');
    }); // === it adds ID attr to element

    it('does not override original ID', function () {
      var stage = $('#THE_STAGE');
      stage.html('
override id
');
      var id = Applet.id($('#THE_STAGE div:first'));
      expect(id).toEqual('non_override_1');
    }); // === it does not override original ID

  }); // === describe id =================

  describe('attrs:', function () {

    it('returns attrs of node', function () {
      var result = Applet.attrs($('

')[0]);
      expect(result).toEqual({id: "000", img: ".png"});
    }); // === it returns attrs of node

  }); // === describe attrs =================

  describe('is_true:', function () {

    it('returns true if key is "truthy"', function () {
      expect(
        Applet.is_true({time: 'morning'}, 'time')
      ).toEqual(true);
    }); // === it returns true if key is "truthy"

    it('returns true if: !key , key is !truthy', function () {
      expect(
        Applet.is_true({time: false}, '!time')
      ).toEqual(true);
    }); // === it returns true if: !key , key is !truthy

    it('handles nested keys', function () {
      expect(
        Applet.is_true({first: {second: { third: true}}}, '!first.second.third')
      ).toEqual(true);
    }); // === it handles nested keys

    it('handles multiple exclamation marks', function () {
      expect(
        Applet.is_true({first: false}, '!!!first')
      ).toEqual(true);
    }); // === it handles multiple exclamation marks

    it('returns undefined if one non-nested key is specified, but not found', function () {
      expect(
        Applet.is_true({}, 'first')
      ).toEqual(undefined);
    }); // === it returns undefined if one non-nested key is specified, but not found

  }); // === describe is_true =================

  describe('node_array:', function () {

    it('returns an Array when passed a String', function () {
      var arr = Applet.node_array('

');

      expect(arr).toEqual([
        {
        tag:   'DIV',
        attrs:  {id: '111', show_if: 'happy?'},
        custom: {},
        childs: [
          {tag: 'SPAN', attrs: {}, custom: {}, childs: []}
        ]
      }
      ]);
    }); // === it returns an Array when passed a String

    it('returns raw text nodes', function () {
      var arr = Applet.node_array('
ab
');

      expect(
        _.pluck(arr[0].childs[0].childs, 'nodeValue')
      ).toEqual(
      ['a', undefined, 'b']
      );
    }); // === it returns raw text nodes

  }); // === describe node_array =================

  describe('compiling scripts:', function () {

    it('does not re-evaluate scripts', function () {
      $('#THE_STAGE').html('');
      Applet.run(Applet.insert_before);
      Applet.run(Applet.insert_before);
      Applet.run(Applet.insert_before);
      expect($('#THE_STAGE').html()).toEqual('
OK
');
    }); // === it does not re-evaluate scripts

    it('keeps evaulating nested scripts until done', function () {
      $('#THE_STAGE').html(
        '' +
        '</script>' +
        '</script>'
      );

      Applet.run(Applet.insert_before);
      expect(
        $('#THE_STAGE').html()
      ).toEqual('
OK
');
    }); // === it keeps evaulating nested scripts until done
  }); // === describe compiling scripts =================

}); // === describe Applet =================
<|endoftext|>


<commit_before>(function(){

  var Spine;
  if (typeof exports !== "undefined") {
    Spine = exports;
  } else {
    Spine = this.Spine = {};
  }

  Spine.version = "0.0.4";

  var $ = Spine.$ = this.jQuery || this.Zepto || function(){ return arguments[0]; };

  var makeArray = Spine.makeArray = function(args){
    return Array.prototype.slice.call(args, 0);
  };

  // Shim Array, as these functions aren't in IE
  if (typeof Array.prototype.indexOf === "undefined")
    Array.prototype.indexOf = function(value){
      for ( var i = 0; i < this.length; i++ )
    		if ( this[ i ] === value )
    			return i;
    	return -1;
    };

  var Events = Spine.Events = {
    bind: function(ev, callback) {
      var evs   = ev.split(" ");
      var calls = this._callbacks || (this._callbacks = {});

      for (var i=0; i < evs.length; i++)
        (this._callbacks[evs[i]] || (this._callbacks[evs[i]] = [])).push(callback);

      return this;
    },

    trigger: function() {
      var args = makeArray(arguments);
      var ev   = args.shift();

      var list, calls, i, l;
      if (!(calls = this._callbacks)) return false;
      if (!(list  = this._callbacks[ev])) return false;

      for (i = 0, l = list.length; i < l; i++)
        if (list[i].apply(this, args) === false)
          break;

      return true;
    },

    unbind: function(ev, callback){
      if ( !ev ) {
        this._callbacks = {};
        return this;
      }

      var list, calls, i, l;
      if (!(calls = this._callbacks)) return this;
      if (!(list  = this._callbacks[ev])) return this;

      if ( !callback ) {
        delete this._callbacks[ev];
        return this;
      }

      for (i = 0, l = list.length; i < l; i++)
        if (callback === list[i]) {
          list.splice(i, 1);
          break;
        }

      return this;
    }
  };

  var Log = Spine.Log = {
    trace: true,

    logPrefix: "(App)",

    log: function(){
      if ( !this.trace ) return;
      if (typeof console == "undefined") return;
      var args = makeArray(arguments);
      if (this.logPrefix) args.unshift(this.logPrefix);
      console.log.apply(console, args);
      return this;
    }
  };

  // Classes (or prototypial inheritors)

  if (typeof Object.create !== "function")
      Object.create = function(o) {
        function F() {}
        F.prototype = o;
        return new F();
      };

  var moduleKeywords = ["included", "extended"];

  var Class = Spine.Class = {
    inherited: function(){},
    created: function(){},

    prototype: {
      initialize: function(){},
      init: function(){}
    },

    create: function(include, extend){
      var object = Object.create(this);
      object.parent    = this;
      object.prototype = object.fn = Object.create(this.prototype);

      if (include) object.include(include);
      if (extend)  object.extend(extend);

      object.created();
      this.inherited(object);
      return object;
    },

    init: function(){
      var instance = Object.create(this.prototype);
      instance.parent = this;

      instance.initialize.apply(instance, arguments);
      instance.init.apply(instance, arguments);
      return instance;
    },

    proxy: function(func){
      var thisObject = this;
      return(function(){
        return func.apply(thisObject, arguments);
      });
    },

    proxyAll: function(){
      var functions = makeArray(arguments);
      for (var i=0; i < functions.length; i++)
        this[functions[i]] = this.proxy(this[functions[i]]);
    },

    include: function(obj){
      for(var key in obj)
        if (moduleKeywords.indexOf(key) == -1)
          this.fn[key] = obj[key];

      var included = obj.included;
      if (included) included.apply(this);
      return this;
    },

    extend: function(obj){
      for(var key in obj)
        if (moduleKeywords.indexOf(key) == -1)
          this[key] = obj[key];

      var extended = obj.extended;
      if (extended) extended.apply(this);
      return this;
    }
  };

  Class.prototype.proxy    = Class.proxy;
  Class.prototype.proxyAll = Class.proxyAll;
  Class.inst               = Class.init;
  Class.sub                = Class.create;

  // Models

  Spine.guid = function(){
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
      var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
      return v.toString(16);
    }).toUpperCase();
  };

  var Model = Spine.Model = Class.create();

  Model.extend(Events);

  Model.extend({
    setup: function(name, atts){
      var model = Model.sub();
      if (name) model.name = name;
      if (atts) model.attributes = atts;
      return model;
    },

    created: function(sub){
      this.records = {};
      this.attributes = this.attributes ?
        makeArray(this.attributes) : [];
    },

    find: function(id){
      var record = this.records[id];
      if ( !record ) throw("Unknown record");
      return record.clone();
    },

    exists: function(id){
      try {
        return this.find(id);
      } catch (e) {
        return false;
      }
    },

    refresh: function(values){
      if(Model.ajaxPrefix && this.prefix) {
        values = values[this.prefix];
      }
      values = this.fromJSON(values);
      this.records = {};

      for (var i=0, il = values.length; i < il; i++) {
        var record = values[i];
        record.newRecord = false;
        this.records[record.id] = record;
      }

      this.trigger("refresh");
      return this;
    },

    select: function(callback){
      var result = [];

      for (var key in this.records)
        if (callback(this.records[key]))
          result.push(this.records[key]);

      return this.cloneArray(result);
    },

    findByAttribute: function(name, value){
      for (var key in this.records)
        if (this.records[key][name] == value)
          return this.records[key].clone();
    },

    findAllByAttribute: function(name, value){
      return(this.select(function(item){
        return(item[name] == value);
      }));
    },

    each: function(callback){
      for (var key in this.records)
        callback(this.records[key]);
    },

    all: function(){
      return this.cloneArray(this.recordsValues());
    },

    first: function(){
      var record = this.recordsValues()[0];
      return(record && record.clone());
    },

    last: function(){
      var values = this.recordsValues()
      var record = values[values.length - 1];
      return(record && record.clone());
    },

    count: function(){
      return this.recordsValues().length;
    },

    deleteAll: function(){
      for (var key in this.records)
        delete this.records[key];
    },

    destroyAll: function(){
      for (var key in this.records)
        this.records[key].destroy();
    },

    update: function(id, atts){
      this.find(id).updateAttributes(atts);
    },

    create: function(atts){
      var record = this.init(atts);
      return record.save();
    },

    destroy: function(id){
      this.find(id).destroy();
    },

    sync: function(callback){
      this.bind("change", callback);
    },

    fetch: function(callbackOrParams){
      typeof(callbackOrParams) == 'function' ? this.bind("fetch", callbackOrParams) : this.trigger("fetch", callbackOrParams);
    },

    toJSON: function(){
      return this.recordsValues();
    },

    fromJSON: function(objects){
      if ( !objects ) return;
      if (typeof objects == "string")
        objects = JSON.parse(objects)
      if (typeof objects.length == "number") {
        var results = [];
        for (var i=0; i < objects.length; i++)
          results.push(this.init(objects[i]));
        return results;
      } else {
        return this.init(objects);
      }
    },

    // Private

    recordsValues: function(){
      var result = [];
      for (var key in this.records)
        result.push(this.records[key]);
      return result;
    },

    cloneArray: function(array){
      var result = [];
      for (var i=0; i < array.length; i++)
        result.push(array[i].clone());
      return result;
    }
  });

  Model.include({
    model: true,
    newRecord: true,

    init: function(atts){
      if (atts) this.load(atts);
      this.trigger("init", this);
    },

    isNew: function(){
      return this.newRecord;
    },

    isValid: function(){
      return(!this.validate());
    },

    validate: function(){ },

    load: function(atts){
      for(var name in atts)
        this[name] = atts[name];
    },

    attributes: function(){
      var result = {};
      for (var i=0; i < this.parent.attributes.length; i++) {
        var attr = this.parent.attributes[i];
        result[attr] = this[attr];
      }
      result.id = this.id;
      return result;
    },

    eql: function(rec){
      return(rec && rec.id === this.id &&
             rec.parent === this.parent);
    },

    save: function(){
      var error = this.validate();
      if ( error ) {
        this.trigger("error", this, error)
        return false;
      }

      this.trigger("beforeSave", this);
      this.newRecord ? this.create() : this.update();
      this.trigger("save", this);
      return this;
    },

    updateAttribute: function(name, value){
      this[name] = value;
      return this.save();
    },

    updateAttributes: function(atts){
      this.load(atts);
      return this.save();
    },

    destroy: function(){
      this.trigger("beforeDestroy", this);
      delete this.parent.records[this.id];
      this.destroyed = true;
      this.trigger("destroy", this);
      this.trigger("change", this, "destroy");
    },

    dup: function(){
      var result = this.parent.init(this.attributes());
      result.newRecord = this.newRecord;
      return result;
    },

    clone: function(){
      return Object.create(this);
    },

    reload: function(){
      if ( this.newRecord ) return this;
      var original = this.parent.find(this.id);
      this.load(original.attributes());
      return original;
    },

    toJSON: function(){
      return(this.attributes());
    },

    exists: function(){
      return(this.id && this.id in this.parent.records);
    },

    // Private

    update: function(){
      this.trigger("beforeUpdate", this);
      var records = this.parent.records;
      records[this.id].load(this.attributes());
      var clone = records[this.id].clone();
      this.trigger("update", clone);
      this.trigger("change", clone, "update");
    },

    create: function(){
      this.trigger("beforeCreate", this);
      if ( !this.id ) this.id = Spine.guid();
      this.newRecord   = false;
      var records      = this.parent.records;
      records[this.id] = this.dup();
      var clone        = records[this.id].clone();
      this.trigger("create", clone);
      this.trigger("change", clone, "create");
    },

    bind: function(events, callback){
      return this.parent.bind(events, this.proxy(function(record){
        if ( record && this.eql(record) )
          callback.apply(this, arguments);
      }));
    },

    trigger: function(){
      return this.parent.trigger.apply(this.parent, arguments);
    }
  });

  // Controllers

  var eventSplitter = /^(\w+)\s*(.*)$/;

  var Controller = Spine.Controller = Class.create({
    tag: "div",

    initialize: function(options){
      this.options = options;

      for (var key in this.options)
        this[key] = this.options[key];

      if (!this.el) this.el = document.createElement(this.tag);
      this.el = $(this.el);

      if ( !this.events ) this.events = this.parent.events;
      if ( !this.elements ) this.elements = this.parent.elements;

      if (this.events) this.delegateEvents();
      if (this.elements) this.refreshElements();
      if (this.proxied) this.proxyAll.apply(this, this.proxied);
    },

    $: function(selector){
      return $(selector, this.el);
    },

    delegateEvents: function(){
      for (var key in this.events) {
        var methodName = this.events[key];
        var method     = this.proxy(this[methodName]);

        var match      = key.match(eventSplitter);
        var eventName  = match[1], selector = match[2];

        if (selector === '') {
          this.el.bind(eventName, method);
        } else {
          this.el.delegate(selector, eventName, method);
        }
      }
    },

    refreshElements: function(){
      for (var key in this.elements) {
        this[this.elements[key]] = this.$(key);
      }
    },

    delay: function(func, timeout){
      setTimeout(this.proxy(func), timeout || 0);
    }
  });

  Controller.include(Events);
  Controller.include(Log);

  Spine.App = Class.create();
  Spine.App.extend(Events)
  Controller.fn.App = Spine.App;
})();<commit_msg>Moved the prefix code from refresh to fromJSON as per suggestion from maccman<commit_after>(function(){

  var Spine;
  if (typeof exports !== "undefined") {
    Spine = exports;
  } else {
    Spine = this.Spine = {};
  }

  Spine.version = "0.0.4";

  var $ = Spine.$ = this.jQuery || this.Zepto || function(){ return arguments[0]; };

  var makeArray = Spine.makeArray = function(args){
    return Array.prototype.slice.call(args, 0);
  };

  // Shim Array, as these functions aren't in IE
  if (typeof Array.prototype.indexOf === "undefined")
    Array.prototype.indexOf = function(value){
      for ( var i = 0; i < this.length; i++ )
    		if ( this[ i ] === value )
    			return i;
    	return -1;
    };

  var Events = Spine.Events = {
    bind: function(ev, callback) {
      var evs   = ev.split(" ");
      var calls = this._callbacks || (this._callbacks = {});

      for (var i=0; i < evs.length; i++)
        (this._callbacks[evs[i]] || (this._callbacks[evs[i]] = [])).push(callback);

      return this;
    },

    trigger: function() {
      var args = makeArray(arguments);
      var ev   = args.shift();

      var list, calls, i, l;
      if (!(calls = this._callbacks)) return false;
      if (!(list  = this._callbacks[ev])) return false;

      for (i = 0, l = list.length; i < l; i++)
        if (list[i].apply(this, args) === false)
          break;

      return true;
    },

    unbind: function(ev, callback){
      if ( !ev ) {
        this._callbacks = {};
        return this;
      }

      var list, calls, i, l;
      if (!(calls = this._callbacks)) return this;
      if (!(list  = this._callbacks[ev])) return this;

      if ( !callback ) {
        delete this._callbacks[ev];
        return this;
      }

      for (i = 0, l = list.length; i < l; i++)
        if (callback === list[i]) {
          list.splice(i, 1);
          break;
        }

      return this;
    }
  };

  var Log = Spine.Log = {
    trace: true,

    logPrefix: "(App)",

    log: function(){
      if ( !this.trace ) return;
      if (typeof console == "undefined") return;
      var args = makeArray(arguments);
      if (this.logPrefix) args.unshift(this.logPrefix);
      console.log.apply(console, args);
      return this;
    }
  };

  // Classes (or prototypial inheritors)

  if (typeof Object.create !== "function")
      Object.create = function(o) {
        function F() {}
        F.prototype = o;
        return new F();
      };

  var moduleKeywords = ["included", "extended"];

  var Class = Spine.Class = {
    inherited: function(){},
    created: function(){},

    prototype: {
      initialize: function(){},
      init: function(){}
    },

    create: function(include, extend){
      var object = Object.create(this);
      object.parent    = this;
      object.prototype = object.fn = Object.create(this.prototype);

      if (include) object.include(include);
      if (extend)  object.extend(extend);

      object.created();
      this.inherited(object);
      return object;
    },

    init: function(){
      var instance = Object.create(this.prototype);
      instance.parent = this;

      instance.initialize.apply(instance, arguments);
      instance.init.apply(instance, arguments);
      return instance;
    },

    proxy: function(func){
      var thisObject = this;
      return(function(){
        return func.apply(thisObject, arguments);
      });
    },

    proxyAll: function(){
      var functions = makeArray(arguments);
      for (var i=0; i < functions.length; i++)
        this[functions[i]] = this.proxy(this[functions[i]]);
    },

    include: function(obj){
      for(var key in obj)
        if (moduleKeywords.indexOf(key) == -1)
          this.fn[key] = obj[key];

      var included = obj.included;
      if (included) included.apply(this);
      return this;
    },

    extend: function(obj){
      for(var key in obj)
        if (moduleKeywords.indexOf(key) == -1)
          this[key] = obj[key];

      var extended = obj.extended;
      if (extended) extended.apply(this);
      return this;
    }
  };

  Class.prototype.proxy    = Class.proxy;
  Class.prototype.proxyAll = Class.proxyAll;
  Class.inst               = Class.init;
  Class.sub                = Class.create;

  // Models

  Spine.guid = function(){
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
      var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
      return v.toString(16);
    }).toUpperCase();
  };

  var Model = Spine.Model = Class.create();

  Model.extend(Events);

  Model.extend({
    setup: function(name, atts){
      var model = Model.sub();
      if (name) model.name = name;
      if (atts) model.attributes = atts;
      return model;
    },

    created: function(sub){
      this.records = {};
      this.attributes = this.attributes ?
        makeArray(this.attributes) : [];
    },

    find: function(id){
      var record = this.records[id];
      if ( !record ) throw("Unknown record");
      return record.clone();
    },

    exists: function(id){
      try {
        return this.find(id);
      } catch (e) {
        return false;
      }
    },

    refresh: function(values){
      values = this.fromJSON(values);
      this.records = {};

      for (var i=0, il = values.length; i < il; i++) {
        var record = values[i];
        record.newRecord = false;
        this.records[record.id] = record;
      }

      this.trigger("refresh");
      return this;
    },

    select: function(callback){
      var result = [];

      for (var key in this.records)
        if (callback(this.records[key]))
          result.push(this.records[key]);

      return this.cloneArray(result);
    },

    findByAttribute: function(name, value){
      for (var key in this.records)
        if (this.records[key][name] == value)
          return this.records[key].clone();
    },

    findAllByAttribute: function(name, value){
      return(this.select(function(item){
        return(item[name] == value);
      }));
    },

    each: function(callback){
      for (var key in this.records)
        callback(this.records[key]);
    },

    all: function(){
      return this.cloneArray(this.recordsValues());
    },

    first: function(){
      var record = this.recordsValues()[0];
      return(record && record.clone());
    },

    last: function(){
      var values = this.recordsValues()
      var record = values[values.length - 1];
      return(record && record.clone());
    },

    count: function(){
      return this.recordsValues().length;
    },

    deleteAll: function(){
      for (var key in this.records)
        delete this.records[key];
    },

    destroyAll: function(){
      for (var key in this.records)
        this.records[key].destroy();
    },

    update: function(id, atts){
      this.find(id).updateAttributes(atts);
    },

    create: function(atts){
      var record = this.init(atts);
      return record.save();
    },

    destroy: function(id){
      this.find(id).destroy();
    },

    sync: function(callback){
      this.bind("change", callback);
    },

    fetch: function(callbackOrParams){
      typeof(callbackOrParams) == 'function' ? this.bind("fetch", callbackOrParams) : this.trigger("fetch", callbackOrParams);
    },

    toJSON: function(){
      return this.recordsValues();
    },

    fromJSON: function(objects){
      if ( !objects ) return;
      if (typeof objects == "string")
        objects = JSON.parse(objects)
      if(Model.ajaxPrefix && this.prefix) {
        objects = objects[this.prefix];
      }
      if (typeof objects.length == "number") {
        var results = [];
        for (var i=0; i < objects.length; i++)
          results.push(this.init(objects[i]));
        return results;
      } else {
        return this.init(objects);
      }
    },

    // Private

    recordsValues: function(){
      var result = [];
      for (var key in this.records)
        result.push(this.records[key]);
      return result;
    },

    cloneArray: function(array){
      var result = [];
      for (var i=0; i < array.length; i++)
        result.push(array[i].clone());
      return result;
    }
  });

  Model.include({
    model: true,
    newRecord: true,

    init: function(atts){
      if (atts) this.load(atts);
      this.trigger("init", this);
    },

    isNew: function(){
      return this.newRecord;
    },

    isValid: function(){
      return(!this.validate());
    },

    validate: function(){ },

    load: function(atts){
      for(var name in atts)
        this[name] = atts[name];
    },

    attributes: function(){
      var result = {};
      for (var i=0; i < this.parent.attributes.length; i++) {
        var attr = this.parent.attributes[i];
        result[attr] = this[attr];
      }
      result.id = this.id;
      return result;
    },

    eql: function(rec){
      return(rec && rec.id === this.id &&
             rec.parent === this.parent);
    },

    save: function(){
      var error = this.validate();
      if ( error ) {
        this.trigger("error", this, error)
        return false;
      }

      this.trigger("beforeSave", this);
      this.newRecord ? this.create() : this.update();
      this.trigger("save", this);
      return this;
    },

    updateAttribute: function(name, value){
      this[name] = value;
      return this.save();
    },

    updateAttributes: function(atts){
      this.load(atts);
      return this.save();
    },

    destroy: function(){
      this.trigger("beforeDestroy", this);
      delete this.parent.records[this.id];
      this.destroyed = true;
      this.trigger("destroy", this);
      this.trigger("change", this, "destroy");
    },

    dup: function(){
      var result = this.parent.init(this.attributes());
      result.newRecord = this.newRecord;
      return result;
    },

    clone: function(){
      return Object.create(this);
    },

    reload: function(){
      if ( this.newRecord ) return this;
      var original = this.parent.find(this.id);
      this.load(original.attributes());
      return original;
    },

    toJSON: function(){
      return(this.attributes());
    },

    exists: function(){
      return(this.id && this.id in this.parent.records);
    },

    // Private

    update: function(){
      this.trigger("beforeUpdate", this);
      var records = this.parent.records;
      records[this.id].load(this.attributes());
      var clone = records[this.id].clone();
      this.trigger("update", clone);
      this.trigger("change", clone, "update");
    },

    create: function(){
      this.trigger("beforeCreate", this);
      if ( !this.id ) this.id = Spine.guid();
      this.newRecord   = false;
      var records      = this.parent.records;
      records[this.id] = this.dup();
      var clone        = records[this.id].clone();
      this.trigger("create", clone);
      this.trigger("change", clone, "create");
    },

    bind: function(events, callback){
      return this.parent.bind(events, this.proxy(function(record){
        if ( record && this.eql(record) )
          callback.apply(this, arguments);
      }));
    },

    trigger: function(){
      return this.parent.trigger.apply(this.parent, arguments);
    }
  });

  // Controllers

  var eventSplitter = /^(\w+)\s*(.*)$/;

  var Controller = Spine.Controller = Class.create({
    tag: "div",

    initialize: function(options){
      this.options = options;

      for (var key in this.options)
        this[key] = this.options[key];

      if (!this.el) this.el = document.createElement(this.tag);
      this.el = $(this.el);

      if ( !this.events ) this.events = this.parent.events;
      if ( !this.elements ) this.elements = this.parent.elements;

      if (this.events) this.delegateEvents();
      if (this.elements) this.refreshElements();
      if (this.proxied) this.proxyAll.apply(this, this.proxied);
    },

    $: function(selector){
      return $(selector, this.el);
    },

    delegateEvents: function(){
      for (var key in this.events) {
        var methodName = this.events[key];
        var method     = this.proxy(this[methodName]);

        var match      = key.match(eventSplitter);
        var eventName  = match[1], selector = match[2];

        if (selector === '') {
          this.el.bind(eventName, method);
        } else {
          this.el.delegate(selector, eventName, method);
        }
      }
    },

    refreshElements: function(){
      for (var key in this.elements) {
        this[this.elements[key]] = this.$(key);
      }
    },

    delay: function(func, timeout){
      setTimeout(this.proxy(func), timeout || 0);
    }
  });

  Controller.include(Events);
  Controller.include(Log);

  Spine.App = Class.create();
  Spine.App.extend(Events)
  Controller.fn.App = Spine.App;
})();<|endoftext|>


<commit_before>// Configure overload to throw type errors
Overload.prototype.err = function() {
    throw new TypeError();
};
Overload.defineType('D', function(val) {
    return val instanceof D;
});

var _ = require('_');

require('_.string');

var parser = require('./D/parser'),
    utils = require('./utils'),
    array = require('./modules/array'),
    onready = require('./modules/onready'),
    selectors = require('./modules/selectors'),
    transversal = require('./modules/transversal'),
    dimensions = require('./modules/dimensions'),
    manip = require('./modules/manip'),
    css = require('./modules/css'),
    attr = require('./modules/attr'),
    prop = require('./modules/prop'),
    val = require('./modules/val'),
    position = require('./modules/position'),
    classes = require('./modules/classes');

// Store previous reference
var _prevD = window.D;

var DOM = function(arg) {
    // Wasn't created with "new"
    if (!(this instanceof DOM)) { return new DOM(arg); }

    // Nothin
    if (!arg) { return; }

    // Element
    if (arg.nodeType || arg === window || arg === document) {
        this.push(arg);
        return;
    }

    // String
    if (_.isString(arg)) {

        // HTML string
        if (utils.isHtml(arg)) {
            utils.merge(this, parser.parseHtml(arg));
            return;
        }

        // Selector: perform a find without creating a new DOM
        utils.merge(this, selectors.find(arg, true));
        return;
    }

    // Array of Elements or NodeList
    if (_.isArray(arg) || _.isNodeList(arg)) {
        utils.merge(this, arg);
        return;
    }

    // Document a ready
    if (_.isFunction(arg)) {
        onready(arg);
    }
};

var _hasMoreConflict = false,
    _prevjQuery,
    _prev$;

_.extend(DOM, parser.D, {
    each:    array.each,
    map:     _.map,
    extend:  _.extend,
    forEach: _.each,

    noConflict: function() {
        if (_hasMoreConflict) {
            window.jQuery = _prevjQuery;
            window.$ = _prev$;

            _hasMoreConflict = false;
        }

        window.D = _prevD;
        return DOM;
    },

    moreConflict: function() {
        _hasMoreConflict = true;
        _prevjQuery = window.jQuery;
        _prev$ = window.$;
        window.jQuery = window.Zepto = window.$ = DOM;
    }
});

var arrayProto = (function() {

    var keys = [
            'length',
            'toString',
            'toLocaleString',
            'join',
            'pop',
            'push',
            'concat',
            'reverse',
            'shift',
            'unshift',
            'slice',
            'splice',
            'sort',
            'some',
            'every',
            'indexOf',
            'lastIndexOf',
            'reduce',
            'reduceRight'
        ],
        idx = keys.length,
        obj = {};

    while (idx--) {
        obj[keys[idx]] = Array.prototype[keys[idx]];
    }

    return obj;

}());

_.extend(
    DOM.prototype,
    arrayProto,
    array.fn,
    selectors.fn,
    transversal.fn,
    manip.fn,
    dimensions.fn,
    css.fn,
    attr.fn,
    prop.fn,
    val.fn,
    classes.fn,
    position.fn,
    { constructor: DOM }
);

// Expose the prototype so that
// it can be hooked into for plugins
DOM.fn = DOM.prototype;

module.exports = window.D = DOM;

if (typeof define === 'function' && define.amd) {
    define('D', [], function() {
        return DOM;
    });
}

/*
        _bind = function(elem, eventName, callback) {
            if (elem.addEventListener) {
                return elem.addEventListener(eventName, callback);
            }

            elem.attachEvent('on' + eventName, function() {
                callback.call(elem);
            });
        },

        _unbind = function(elem, eventName, callback) {
            if (elem.removeEventListener) {
                return elem.removeEventListener(eventName, callback);
            }

            elem.detachEvent('on' + eventName, callback);
        },

        html: function(str) {
            if (_exists(str)) {
                this.elem.innerHTML = ('' + str);
                return this;
            }

            return this.elem.innerHTML;
        },

        offset: function() {
            return this.elem.getBoundingClientRect();
        },

        on: function(eventName, callback) {
            _bind(this.elem, eventName, callback);
            return this;
        },

        off: function(eventName, callback) {
            _unbind(this.elem, eventName, callback);
            return this;
        }
    };
*/
<commit_msg>Minor/Ignore<commit_after>// Configure overload to throw type errors
Overload.prototype.err = function() {
    throw new TypeError();
};
Overload.defineType('D', function(val) {
    return val instanceof D;
});

var _ = require('_');

require('_.string');

var parser = require('./D/parser'),
    utils = require('./utils'),
    array = require('./modules/array'),
    onready = require('./modules/onready'),
    selectors = require('./modules/selectors'),
    transversal = require('./modules/transversal'),
    dimensions = require('./modules/dimensions'),
    manip = require('./modules/manip'),
    css = require('./modules/css'),
    attr = require('./modules/attr'),
    prop = require('./modules/prop'),
    val = require('./modules/val'),
    position = require('./modules/position'),
    classes = require('./modules/classes');

// Store previous reference
var _prevD = window.D;

var DOM = function(arg) {
    // Wasn't created with "new"
    if (!(this instanceof DOM)) { return new DOM(arg); }

    // Nothin
    if (!arg) { return; }

    // Element
    if (arg.nodeType || arg === window || arg === document) {
        this.push(arg);
        return;
    }

    // String
    if (_.isString(arg)) {

        // HTML string
        if (utils.isHtml(arg)) {
            utils.merge(this, parser.parseHtml(arg));
            return;
        }

        // Selector: perform a find without creating a new DOM
        utils.merge(this, selectors.find(arg, true));
        return;
    }

    // Array of Elements or NodeList
    if (_.isArray(arg) || _.isNodeList(arg)) {
        utils.merge(this, arg);
        return;
    }

    // Document a ready
    if (_.isFunction(arg)) {
        onready(arg);
    }
};

var _hasMoreConflict = false,
    _prevjQuery,
    _prev$;

_.extend(DOM, parser.D, {
    each:    array.each,
    map:     _.map,
    extend:  _.extend,
    forEach: _.each,

    noConflict: function() {
        if (_hasMoreConflict) {
            window.jQuery = _prevjQuery;
            window.$ = _prev$;

            _hasMoreConflict = false;
        }

        window.D = _prevD;
        return DOM;
    },

    moreConflict: function() {
        _hasMoreConflict = true;
        _prevjQuery = window.jQuery;
        _prev$ = window.$;
        window.jQuery = window.Zepto = window.$ = DOM;
    }
});

var arrayProto = (function() {

    var keys = [
            'length',
            'toString',
            'toLocaleString',
            'join',
            'pop',
            'push',
            'concat',
            'reverse',
            'shift',
            'unshift',
            'slice',
            'splice',
            'sort',
            'some',
            'every',
            'indexOf',
            'lastIndexOf',
            'reduce',
            'reduceRight'
        ],
        idx = keys.length,
        obj = {};

    while (idx--) {
        obj[keys[idx]] = Array.prototype[keys[idx]];
    }

    return obj;

}());

_.extend(
    DOM.prototype,
    arrayProto,
    array.fn,
    selectors.fn,
    transversal.fn,
    manip.fn,
    dimensions.fn,
    css.fn,
    attr.fn,
    prop.fn,
    val.fn,
    classes.fn,
    position.fn,
    { constructor: DOM }
);

// Expose the prototype so that
// it can be hooked into for plugins
DOM.fn = DOM.prototype;

module.exports = window.D = DOM;

if (typeof define === 'function' && define.amd) {
    define('D', [], function() {
        return DOM;
    });
}

/*
        _bind = function(elem, eventName, callback) {
            if (elem.addEventListener) {
                return elem.addEventListener(eventName, callback);
            }

            elem.attachEvent('on' + eventName, function() {
                callback.call(elem);
            });
        },

        _unbind = function(elem, eventName, callback) {
            if (elem.removeEventListener) {
                return elem.removeEventListener(eventName, callback);
            }

            elem.detachEvent('on' + eventName, callback);
        },

        html: function(str) {
            if (_exists(str)) {
                this.elem.innerHTML = ('' + str);
                return this;
            }

            return this.elem.innerHTML;
        },

        offset: function() {
            return this.elem.getBoundingClientRect();
        },

        on: function(eventName, callback) {
            _bind(this.elem, eventName, callback);
            return this;
        },

        off: function(eventName, callback) {
            _unbind(this.elem, eventName, callback);
            return this;
        }
    };
*/
<|endoftext|>


<commit_before>/*!
 * F - a JavaScript framework for modular and scalable SPAs
 */

/* global define */
/* global global */
/* global jQuery, _ */

var F = (function(){
    "use strict";

    // Initial Setup
    // -------------

    // Save the previous value of the `F` variable, so that it can be
    // restored later on, if `noConflict` is used.
    var F = {};
    var previousF = F;

    // Current version of the library. Keep in sync with `package.json` and `bower.json`.
    F.VERSION = '0.0.2';

    // Set framework to debug mode. Disabled by default
    F.DEBUG = false;

    // Runs F.js in *noConflict* mode, returning the `F` variable
    // to its previous owner. Returns a reference to this F object.
    F.noConflict = function() {
        F = previousF;
        return this;
    };

    // Extensions Plugging
    // -------------------
    /*
    F.Core = Core;
    F.Core.dispatcher = Dispatcher; // don't expose the dispatcher. Only core has it
    F.Core.http = Http;
    F.Core.log = F.log = new Log();
    F.Sandbox = Sandbox;
    F.Store = Store;
    F.util = Util;
    F.http = Http;
    F.$ = DOM;
    F.Storage = Storage;
    F.Module = Mod;

    F.router = Router;
    // We can use backbone views or riot components
    // F.BackboneView = View;

    // Shortcuts
    // ---------
    F.ready = Util.ready;
    F.extend = Util.extend;
    */
    return F;
}());<commit_msg>remove unused globals<commit_after>/*!
 * F - a JavaScript framework for modular and scalable SPAs
 */

/* global jQuery, _ */

var F = (function(){
    "use strict";

    // Initial Setup
    // -------------

    // Save the previous value of the `F` variable, so that it can be
    // restored later on, if `noConflict` is used.
    var F = {};
    var previousF = F;

    // Current version of the library. Keep in sync with `package.json` and `bower.json`.
    F.VERSION = '0.0.2';

    // Set framework to debug mode. Disabled by default
    F.DEBUG = false;

    // Runs F.js in *noConflict* mode, returning the `F` variable
    // to its previous owner. Returns a reference to this F object.
    F.noConflict = function() {
        F = previousF;
        return this;
    };

    // Extensions Plugging
    // -------------------
    /*
    F.Core = Core;
    F.Core.dispatcher = Dispatcher; // don't expose the dispatcher. Only core has it
    F.Core.http = Http;
    F.Core.log = F.log = new Log();
    F.Sandbox = Sandbox;
    F.Store = Store;
    F.util = Util;
    F.http = Http;
    F.$ = DOM;
    F.Storage = Storage;
    F.Module = Mod;

    F.router = Router;
    // We can use backbone views or riot components
    // F.BackboneView = View;

    // Shortcuts
    // ---------
    F.ready = Util.ready;
    F.extend = Util.extend;
    */
    return F;
}());<|endoftext|>


<commit_before>window.c.h = (function(m, moment){
  //Date Helpers
  var momentify = function(date, format){
    format = format || 'DD/MM/YYYY';
    return date ? moment(date).format(format) : 'no date';
  },

  momentFromString = function(date, format){
    var european = moment(date, format || 'DD/MM/YYYY');
    return european.isValid() ? european : moment(date);
  },

  //Object manipulation helpers
  generateRemaingTime = function(project) {
    var remainingTextObj = m.prop({}),
        translatedTime = {
          days: 'dias',
          minutes: 'minutos',
          hours: 'horas',
          seconds: 'segundos'
        };

    remainingTextObj({
      unit: translatedTime[project.remaining_time.unit || 'seconds'],
      total: project.remaining_time.total
    });

    return remainingTextObj;
  },

  //Number formatting helpers
  generateFormatNumber = function(s, c){
    return function(number, n, x) {
      if (number === null || number === undefined) {
        return null;
      }

      var re = '\\d(?=(\\d{' + (x || 3) + '})+' + (n > 0 ? '\\D' : '$') + ')',
          num = number.toFixed(Math.max(0, ~~n));
      return (c ? num.replace('.', c) : num).replace(new RegExp(re, 'g'), '$&' + (s || ','));
    };
  },
  formatNumber = generateFormatNumber('.', ','),

  //Object manipulation helpers
  toggleProp = function(defaultState, alternateState){
    var p = m.prop(defaultState);
    p.toggle = function(){
      p(((p() === alternateState) ? defaultState : alternateState));
    };

    return p;
  },

  idVM = m.postgrest.filtersVM({id: 'eq'}),

  //Templates
  loader = function(){
    return m('.u-text-center.u-margintop-30[style="margin-bottom:-110px;"]', [
      m('img[alt="Loader"][src="https://s3.amazonaws.com/catarse.files/loader.gif"]')
    ]);
  },

  fbParse = function() {
    var tryParse = function() {
      try {
        window.FB.XFBML.parse();
      } catch (e) {
        console.log(e);
      }
    };

    return window.setTimeout(tryParse, 500); //use timeout to wait async of facebook
  },

  pluralize = function(count, s, p) {
    return (count > 1 ? count + p : count + s);
  },

  simpleFormat = function(str) {
    str = str.replace(/\r\n?/, "\n");
    if (str.length > 0) {
      str = str.replace(/\n\n+/g, '

');
      str = str.replace(/\n/g, '
');
      str = '
' + str + '
';
    }
    return str;
  };

  return {
    momentify: momentify,
    momentFromString: momentFromString,
    formatNumber: formatNumber,
    idVM: idVM,
    toggleProp: toggleProp,
    loader: loader,
    fbParse: fbParse,
    pluralize: pluralize,
    simpleFormat: simpleFormat,
    generateRemaingTime: generateRemaingTime
  };
}(window.m, window.moment));
<commit_msg>added rewardSouldOut helper<commit_after>window.c.h = (function(m, moment){
  //Date Helpers
  var momentify = function(date, format){
    format = format || 'DD/MM/YYYY';
    return date ? moment(date).format(format) : 'no date';
  },

  momentFromString = function(date, format){
    var european = moment(date, format || 'DD/MM/YYYY');
    return european.isValid() ? european : moment(date);
  },

  //Object manipulation helpers
  generateRemaingTime = function(project) {
    var remainingTextObj = m.prop({}),
        translatedTime = {
          days: 'dias',
          minutes: 'minutos',
          hours: 'horas',
          seconds: 'segundos'
        };

    remainingTextObj({
      unit: translatedTime[project.remaining_time.unit || 'seconds'],
      total: project.remaining_time.total
    });

    return remainingTextObj;
  },

  //Number formatting helpers
  generateFormatNumber = function(s, c){
    return function(number, n, x) {
      if (number === null || number === undefined) {
        return null;
      }

      var re = '\\d(?=(\\d{' + (x || 3) + '})+' + (n > 0 ? '\\D' : '$') + ')',
          num = number.toFixed(Math.max(0, ~~n));
      return (c ? num.replace('.', c) : num).replace(new RegExp(re, 'g'), '$&' + (s || ','));
    };
  },
  formatNumber = generateFormatNumber('.', ','),

  //Object manipulation helpers
  toggleProp = function(defaultState, alternateState){
    var p = m.prop(defaultState);
    p.toggle = function(){
      p(((p() === alternateState) ? defaultState : alternateState));
    };

    return p;
  },

  idVM = m.postgrest.filtersVM({id: 'eq'}),

  //Templates
  loader = function(){
    return m('.u-text-center.u-margintop-30[style="margin-bottom:-110px;"]', [
      m('img[alt="Loader"][src="https://s3.amazonaws.com/catarse.files/loader.gif"]')
    ]);
  },

  fbParse = function() {
    var tryParse = function() {
      try {
        window.FB.XFBML.parse();
      } catch (e) {
        console.log(e);
      }
    };

    return window.setTimeout(tryParse, 500); //use timeout to wait async of facebook
  },

  pluralize = function(count, s, p) {
    return (count > 1 ? count + p : count + s);
  },

  simpleFormat = function(str) {
    str = str.replace(/\r\n?/, '\n');
    if (str.length > 0) {
      str = str.replace(/\n\n+/g, '

');
      str = str.replace(/\n/g, '
');
      str = '
' + str + '
';
    }
    return str;
  },

  rewardSouldOut = function(reward) {
    return (reward.maximum_contributions > 0 ?
        (reward.paid_count + reward.waiting_payment_count >= reward.maximum_contributions) : false);
  },

  };

  return {
    momentify: momentify,
    momentFromString: momentFromString,
    formatNumber: formatNumber,
    idVM: idVM,
    toggleProp: toggleProp,
    loader: loader,
    fbParse: fbParse,
    pluralize: pluralize,
    simpleFormat: simpleFormat,
    generateRemaingTime: generateRemaingTime,
    rewardSouldOut: rewardSouldOut,
  };
}(window.m, window.moment));
<|endoftext|>


<commit_before>// Return the first value that is not `null` nor `undefined`.
const coalesce = require('extant')
const ascension = require('ascension')

const Strata = require('b-tree')

function create (destructible, options) {
    const leaf = coalesce(options.leaf, 4096)
    const branch = coalesce(options.leaf, 4096)
    const strata = new Strata(destructible, {
        directory: options.directory,
        serializer: options.serializer,
        comparator: ascension([ options.comparator, BigInt ], function (object) {
            return [ object.value, object.version ]
        }),
        branch: { split: branch, merge: branch - 1 },
        leaf: { split: leaf, merge: leaf - 1 },
        cache: options.cache
    })
    return strata
}

exports.create = create
<commit_msg>Remove dead code.<commit_after><|endoftext|>


<commit_before>// -----------------------------------------------------------------------------
// CONSTANTS
// -----------------------------------------------------------------------------

// Default modifier keys for binds
const MODIFIERS = ['ctrl', 'shift'];

// Default modifier keys for resizing windows binds
const RESIZE_MODIFIERS = ['shift', 'alt'];

// Default modifier keys for positioning windows binds.
const POSITION_MODIFIERS = ['ctrl', 'shift'];

// Grid width and height for centering windows with different sizes
const GRID_WIDTH = 12;
const GRID_HEIGHT = 10;

// Margin to have around each window edge
const MARGIN = 10;

// Size for resizing/positioning increments/decrements.
const RESIZE_POSITION_AMOUNT = 40;

// -----------------------------------------------------------------------------
// FUNCTIONS
// -----------------------------------------------------------------------------

Bind.on("s", MODIFIERS, () => {
  Stark.run("/usr/bin/open", ["/System/Library/CoreServices/ScreenSaverEngine.app"]);
});

// -----------------------------------------------------------------------------
// WINDOW MOVEMENT
// -----------------------------------------------------------------------------

Bind.on("up", POSITION_MODIFIERS, () => {
  const win = Window.focused();

  if (!win) {
    return;
  }

  const x = win.topLeft.x;
  const y = win.topLeft.y - RESIZE_POSITION_AMOUNT;

  win.setTopLeft({ x, y });
});

Bind.on("down", POSITION_MODIFIERS, () => {
  const win = Window.focused();

  if (!win) {
    return;
  }

  const x = win.topLeft.x;
  const y = win.topLeft.y + RESIZE_POSITION_AMOUNT;

  win.setTopLeft({ x, y });
});

Bind.on("left", POSITION_MODIFIERS, () => {
  const win = Window.focused();

  if (!win) {
    return;
  }

  const x = win.topLeft.x - RESIZE_POSITION_AMOUNT;
  const y = win.topLeft.y;

  win.setTopLeft({ x, y });
});

Bind.on("right", POSITION_MODIFIERS, () => {
  const win = Window.focused();

  if (!win) {
    return;
  }

  const x = win.topLeft.x + RESIZE_POSITION_AMOUNT;
  const y = win.topLeft.y;

  win.setTopLeft({ x, y });
});

// -----------------------------------------------------------------------------
// WINDOW RESIZING
// -----------------------------------------------------------------------------

Bind.on("up", RESIZE_MODIFIERS, () => {
  const win = Window.focused();

  if (!win) {
    return;
  }

  const width = win.size.width;
  const height = win.size.height - RESIZE_POSITION_AMOUNT;

  win.setSize({ width, height });
});

Bind.on("down", RESIZE_MODIFIERS, () => {
  const win = Window.focused();

  if (!win) {
    return;
  }

  const width = win.size.width;
  const height = win.size.height + RESIZE_POSITION_AMOUNT;

  win.setSize({ width, height });
});

Bind.on("left", RESIZE_MODIFIERS, () => {
  const win = Window.focused();

  if (!win) {
    return;
  }

  const width = win.size.width - RESIZE_POSITION_AMOUNT;
  const height = win.size.height;

  win.setSize({ width, height });
});

Bind.on("right", RESIZE_MODIFIERS, () => {
  const win = Window.focused();

  if (!win) {
    return;
  }

  const width = win.size.width + RESIZE_POSITION_AMOUNT;
  const height = win.size.height;

  win.setSize({ width, height });
});

// -----------------------------------------------------------------------------
// WINDOW CENTERING
// -----------------------------------------------------------------------------

Bind.on("z", MODIFIERS, () => {
  const win = Window.focused();

  if (!win) {
    return;
  }

  const r = win.screen.frameWithoutDockOrMenu;

  const x = (r.width / GRID_WIDTH) * 2;
  const y = r.y + (r.height / GRID_HEIGHT) * 2;

  const width = (r.width / GRID_WIDTH) * 8;
  const height = (r.height / GRID_HEIGHT) * 6;

  win.setFrame({ x, y, width, height });
});

Bind.on("x", MODIFIERS, () => {
  const win = Window.focused();

  if (!win) {
    return;
  }

  const r = win.screen.frameWithoutDockOrMenu;

  const x = r.width / GRID_WIDTH;
  const y = r.y + (r.height / GRID_HEIGHT);

  const width = (r.width / GRID_WIDTH) * 10;
  const height = (r.height / GRID_HEIGHT) * 8;

  win.setFrame({ x, y, width, height });
});

Bind.on("c", MODIFIERS, () => {
  const win = Window.focused();

  if (!win) {
    return;
  }

  const r = win.screen.frameWithoutDockOrMenu;

  const x = r.x + MARGIN;
  const y = r.y + MARGIN;

  const width = r.width - (MARGIN * 2);
  const height = r.height - (MARGIN * 2);

  win.setFrame({ x, y, width, height });
});

// -----------------------------------------------------------------------------
// WINDOW POSITIONING
// -----------------------------------------------------------------------------

Bind.on("h", MODIFIERS, () => {
  const win = Window.focused();

  if (!win) {
    return;
  }

  const r = win.screen.frameWithoutDockOrMenu;

  const x = r.x + MARGIN;
  const y = r.y + MARGIN;

  const width = r.width / 2 - (MARGIN + (MARGIN / 2));
  const height = r.height - (MARGIN * 2);

  win.setFrame({ x, y, width, height });
});

Bind.on("l", MODIFIERS, () => {
  const win = Window.focused();

  if (!win) {
    return;
  }

  const r = win.screen.frameWithoutDockOrMenu;

  const x = (r.x + (r.width / 2)) + (MARGIN / 2);
  const y = r.y + MARGIN;

  const width = r.width / 2 - (MARGIN + (MARGIN / 2));
  const height = r.height - (MARGIN * 2);

  win.setFrame({ x, y, width, height });
});

Bind.on("j", MODIFIERS, () => {
  const win = Window.focused();

  if (!win) {
    return;
  }

  const r = win.screen.frameWithoutDockOrMenu;

  const x = r.x + MARGIN;
  const y = r.y + MARGIN;

  const width = r.width / 2 - (MARGIN + (MARGIN / 2));
  const height = r.height / 2 - (MARGIN + (MARGIN / 2));

  win.setFrame({ x, y, width, height });
});

Bind.on("k", MODIFIERS, () => {
  const win = Window.focused();

  if (!win) {
    return;
  }

  const r = win.screen.frameWithoutDockOrMenu;

  const x = (r.x + (r.width / 2)) + (MARGIN / 2);
  const y = r.y + MARGIN;

  const width = r.width / 2 - (MARGIN + (MARGIN / 2));
  const height = r.height / 2 - (MARGIN + (MARGIN / 2));

  win.setFrame({ x, y, width, height });
});

// -----------------------------------------------------------------------------
// APP POSITIONING
// -----------------------------------------------------------------------------

Bind.on("t", MODIFIERS, () => {
  const app = App.find("Tweetbot");

  if (!app) {
    return;
  }

  _.each(app.windows(), (win) => {
    const r = win.screen.frameWithoutDockOrMenu;

    const x = r.x + MARGIN;
    const y = r.y + MARGIN;

    const width = r.width / 4 - (MARGIN + (MARGIN / 2));
    const height = r.height - (MARGIN * 2);

    win.setFrame({ x, y, width, height });
  });
});

// -----------------------------------------------------------------------------
// EVENTS
// -----------------------------------------------------------------------------

Event.on("applicationDidLaunch", (app) => {
  if (app.name === 'iTerm2') {
    _.each(app.windows({ visible: true }), (win) => {
      const r = win.screen.frameWithoutDockOrMenu;

      const x = r.x + MARGIN;
      const y = r.y + MARGIN;

      const width = r.width / 2 - (MARGIN + (MARGIN / 2));
      const height = r.height - (MARGIN * 2);

      win.setFrame({ x, y, width, height });
    });

    return;
  }
});

Event.on("windowDidOpen", (win) => {
  if (win.app.name === 'MacVim') {
    const r = win.screen.frameWithoutDockOrMenu;

    const x = (r.x + (r.width / 2)) + (MARGIN / 2);
    const y = r.y + MARGIN;

    const width = r.width / 2 - (MARGIN + (MARGIN / 2));
    const height = r.height - (MARGIN * 2);

    win.setFrame({ x, y, width, height });

    return;
  }
});
<commit_msg>Update stark.js<commit_after>// -----------------------------------------------------------------------------
// CONSTANTS
// -----------------------------------------------------------------------------

// Default modifier keys for binds
const MODIFIERS = ['ctrl', 'shift'];

// Default modifier keys for resizing windows binds
const RESIZE_MODIFIERS = ['shift', 'alt'];

// Default modifier keys for positioning windows binds.
const POSITION_MODIFIERS = ['ctrl', 'shift'];

// Grid width and height for centering windows with different sizes
const GRID_WIDTH = 12;
const GRID_HEIGHT = 10;

// Margin to have around each window edge
const MARGIN = 10;

// Size for resizing/positioning increments/decrements.
const RESIZE_POSITION_AMOUNT = 40;

// -----------------------------------------------------------------------------
// FUNCTIONS
// -----------------------------------------------------------------------------

Bind.on("s", MODIFIERS, () => {
  Stark.run("/usr/bin/open", ["/System/Library/CoreServices/ScreenSaverEngine.app"]);
});

// -----------------------------------------------------------------------------
// WINDOW MOVEMENT
// -----------------------------------------------------------------------------

Bind.on("up", POSITION_MODIFIERS, () => {
  const win = Window.focused();

  if (!win) {
    return;
  }

  const x = win.topLeft.x;
  const y = win.topLeft.y - RESIZE_POSITION_AMOUNT;

  win.setTopLeft({ x, y });
});

Bind.on("down", POSITION_MODIFIERS, () => {
  const win = Window.focused();

  if (!win) {
    return;
  }

  const x = win.topLeft.x;
  const y = win.topLeft.y + RESIZE_POSITION_AMOUNT;

  win.setTopLeft({ x, y });
});

Bind.on("left", POSITION_MODIFIERS, () => {
  const win = Window.focused();

  if (!win) {
    return;
  }

  const x = win.topLeft.x - RESIZE_POSITION_AMOUNT;
  const y = win.topLeft.y;

  win.setTopLeft({ x, y });
});

Bind.on("right", POSITION_MODIFIERS, () => {
  const win = Window.focused();

  if (!win) {
    return;
  }

  const x = win.topLeft.x + RESIZE_POSITION_AMOUNT;
  const y = win.topLeft.y;

  win.setTopLeft({ x, y });
});

// -----------------------------------------------------------------------------
// WINDOW RESIZING
// -----------------------------------------------------------------------------

Bind.on("up", RESIZE_MODIFIERS, () => {
  const win = Window.focused();

  if (!win) {
    return;
  }

  const width = win.size.width;
  const height = win.size.height - RESIZE_POSITION_AMOUNT;

  win.setSize({ width, height });
});

Bind.on("down", RESIZE_MODIFIERS, () => {
  const win = Window.focused();

  if (!win) {
    return;
  }

  const width = win.size.width;
  const height = win.size.height + RESIZE_POSITION_AMOUNT;

  win.setSize({ width, height });
});

Bind.on("left", RESIZE_MODIFIERS, () => {
  const win = Window.focused();

  if (!win) {
    return;
  }

  const width = win.size.width - RESIZE_POSITION_AMOUNT;
  const height = win.size.height;

  win.setSize({ width, height });
});

Bind.on("right", RESIZE_MODIFIERS, () => {
  const win = Window.focused();

  if (!win) {
    return;
  }

  const width = win.size.width + RESIZE_POSITION_AMOUNT;
  const height = win.size.height;

  win.setSize({ width, height });
});

// -----------------------------------------------------------------------------
// WINDOW CENTERING
// -----------------------------------------------------------------------------

Bind.on("z", MODIFIERS, () => {
  const win = Window.focused();

  if (!win) {
    return;
  }

  const r = win.screen.frameWithoutDockOrMenu;

  const x = (r.width / GRID_WIDTH) * 2;
  const y = r.y + (r.height / GRID_HEIGHT) * 2;

  const width = (r.width / GRID_WIDTH) * 8;
  const height = (r.height / GRID_HEIGHT) * 6;

  win.setFrame({ x, y, width, height });
});

Bind.on("x", MODIFIERS, () => {
  const win = Window.focused();

  if (!win) {
    return;
  }

  const r = win.screen.frameWithoutDockOrMenu;

  const x = r.width / GRID_WIDTH;
  const y = r.y + (r.height / GRID_HEIGHT);

  const width = (r.width / GRID_WIDTH) * 10;
  const height = (r.height / GRID_HEIGHT) * 8;

  win.setFrame({ x, y, width, height });
});

Bind.on("c", MODIFIERS, () => {
  const win = Window.focused();

  if (!win) {
    return;
  }

  const r = win.screen.frameWithoutDockOrMenu;

  const x = r.x + MARGIN;
  const y = r.y + MARGIN;

  const width = r.width - (MARGIN * 2);
  const height = r.height - (MARGIN * 2);

  win.setFrame({ x, y, width, height });
});

// -----------------------------------------------------------------------------
// WINDOW POSITIONING
// -----------------------------------------------------------------------------

Bind.on("h", MODIFIERS, () => {
  const win = Window.focused();

  if (!win) {
    return;
  }

  const r = win.screen.frameWithoutDockOrMenu;

  const x = r.x + MARGIN;
  const y = r.y + MARGIN;

  const width = r.width / 2 - (MARGIN + (MARGIN / 2));
  const height = r.height - (MARGIN * 2);

  win.setFrame({ x, y, width, height });
});

Bind.on("l", MODIFIERS, () => {
  const win = Window.focused();

  if (!win) {
    return;
  }

  const r = win.screen.frameWithoutDockOrMenu;

  const x = (r.x + (r.width / 2)) + (MARGIN / 2);
  const y = r.y + MARGIN;

  const width = r.width / 2 - (MARGIN + (MARGIN / 2));
  const height = r.height - (MARGIN * 2);

  win.setFrame({ x, y, width, height });
});

Bind.on("j", MODIFIERS, () => {
  const win = Window.focused();

  if (!win) {
    return;
  }

  const r = win.screen.frameWithoutDockOrMenu;

  const x = r.x + MARGIN;
  const y = r.y + MARGIN;

  const width = r.width / 2 - (MARGIN + (MARGIN / 2));
  const height = r.height / 2 - (MARGIN + (MARGIN / 2));

  win.setFrame({ x, y, width, height });
});

Bind.on("k", MODIFIERS, () => {
  const win = Window.focused();

  if (!win) {
    return;
  }

  const r = win.screen.frameWithoutDockOrMenu;

  const x = (r.x + (r.width / 2)) + (MARGIN / 2);
  const y = r.y + MARGIN;

  const width = r.width / 2 - (MARGIN + (MARGIN / 2));
  const height = r.height / 2 - (MARGIN + (MARGIN / 2));

  win.setFrame({ x, y, width, height });
});

// -----------------------------------------------------------------------------
// APP POSITIONING
// -----------------------------------------------------------------------------

Bind.on("t", MODIFIERS, () => {
  const app = App.find("Tweetbot");

  if (!app) {
    return;
  }

  _.each(app.windows(), (win) => {
    const r = win.screen.frameWithoutDockOrMenu;

    const x = r.x + MARGIN;
    const y = r.y + MARGIN;

    const width = r.width / 4 - (MARGIN + (MARGIN / 2));
    const height = r.height - (MARGIN * 2);

    win.setFrame({ x, y, width, height });
  });
});

// -----------------------------------------------------------------------------
// EVENTS
// -----------------------------------------------------------------------------

Event.on("applicationDidLaunch", (app) => {
  if (app.name === 'iTerm2' && !app.isTerminated) {
    _.each(app.windows({ visible: true }), (win) => {
      const r = win.screen.frameWithoutDockOrMenu;

      const x = r.x + MARGIN;
      const y = r.y + MARGIN;

      const width = r.width / 2 - (MARGIN + (MARGIN / 2));
      const height = r.height - (MARGIN * 2);

      win.setFrame({ x, y, width, height });
    });

    return;
  }
});
<|endoftext|>


<commit_before>var u = require('./util')
var isMessage = u.isMessage
var isNote = u.isNote

//okay just pretending to be purely functional
//(but if you have good functional disipline, you can mutate)
function clone (state) { return state }

//actually, want to be able to initialize this in receive mode or not.
exports.init = function (local, seq) {
  return {
    local: local,
    sending: seq > 0,
    receiving: false,
    sent: Math.abs(seq), received: Math.abs(seq),
    ready: null,
    effect: []
  }
}

//this is not a reduce, and it has side effects.
exports.read = function (state) {
  if(!state.ready) return [null, state]
  var _ready = state.ready
  state.ready =  null
  if(isMessage(_ready))
    state.sent = _ready.sequence
  return [_ready, state]
}

exports.receiveMessage = function (state, msg) {
  var _state = clone(state)
  _state.received = Math.max(state.received || 0, msg.sequence)

  var seq = state.local[msg.author]
  if(msg.sequence <= seq) {
    //we already know this, please shut up!
    if(state.receiving) {
      _state.receiving = false
      _state.ready = {id: msg.author, seq: - seq}
    }
  }
  else if(msg.sequence == seq + 1) {
    //they said what we where going to
    if(state.ready) _state.ready = null
    _state.effect = {action: 'append', value: msg}
  }
  else
    _state.error = true

  return _state
}

exports.receiveNote = function (state, note) {
  var _state = clone(state)
  var seq = state.local[note.id]
  var requested = note.seq > 0
  var _seq = Math.abs(note.seq)

  _state.received = _seq

  if(!requested)
    _state.sending = false
  else
    _state.sending = true
  if(isMessage(state.ready) && _seq > state.ready.sequence)
      state.ready = null
  if(seq < _seq && !state.receiving) {
    _state.receiving = true
    _state.ready = {id: note.id, seq: seq}
  }
  if(seq > _seq && requested) {
    _state.effect = {action: 'get', value: {id: note.id, seq: _seq + 1}}
  }

  return _state
}

//we have either written a new message ourselves,
//or received a message (and validated it) from another peer.
exports.appendMessage = function (state, msg) {
  //if this is the msg they need next, make
  var _state = clone(state)
  if(state.sending && state.sent + 1 === msg.sequence)
    _state.ready = msg
  else if(!state.sending)
    //how about some way to delay sending notes, for bandwidth?
    //and to slow down upwards replication if you are datacapped.
    _state.ready = {id: msg.author, seq: msg.sequence * -1}
}

//have retrived an requested message
exports.retriveMessage = function (state, msg) {
  var _state = clone(state)
  if(state.sending && state.received + 1 == msg.sequence)
    _state.ready = msg
  //if we are not in sending state, just stop.
  //otherwise, the next retrival will be triggered by READ
  return _state
}

<commit_msg>logic for appendMessage<commit_after>var u = require('./util')
var isMessage = u.isMessage
var isNote = u.isNote

//okay just pretending to be purely functional
//(but if you have good functional disipline, you can mutate)
function clone (state) { return state }

//actually, want to be able to initialize this in receive mode or not.
exports.init = function (local, seq) {
  return {
    local: local,
    sending: seq > 0,
    receiving: false,
    sent: Math.abs(seq), received: Math.abs(seq),
    ready: null,
    effect: []
  }
}

//this is not a reduce, and it has side effects.
exports.read = function (state) {
  if(!state.ready) return [null, state]
  var _ready = state.ready
  state.ready =  null
  if(isMessage(_ready))
    state.sent = _ready.sequence
  return [_ready, state]
}

exports.receiveMessage = function (state, msg) {
  var _state = clone(state)
  _state.received = Math.max(state.received || 0, msg.sequence)

  var seq = state.local[msg.author]
  if(msg.sequence <= seq) {
    //we already know this, please shut up!
    if(state.receiving) {
      _state.receiving = false
      _state.ready = {id: msg.author, seq: - seq}
    }
  }
  else if(msg.sequence == seq + 1) {
    //they said what we where going to
    if(state.ready) _state.ready = null
    _state.effect = {action: 'append', value: msg}
  }
  else
    _state.error = true

  return _state
}

exports.receiveNote = function (state, note) {
  var _state = clone(state)
  var seq = state.local[note.id]
  var requested = note.seq > 0
  var _seq = Math.abs(note.seq)

  _state.received = _seq

  if(!requested)
    _state.sending = false
  else
    _state.sending = true
  if(isMessage(state.ready) && _seq > state.ready.sequence)
      state.ready = null
  if(seq < _seq && !state.receiving) {
    _state.receiving = true
    _state.ready = {id: note.id, seq: seq}
  }
  if(seq > _seq && requested) {
    _state.effect = {action: 'get', value: {id: note.id, seq: _seq + 1}}
  }

  return _state
}

//we have either written a new message ourselves,
//or received a message (and validated it) from another peer.
exports.appendMessage = function (state, msg) {
  //if this is the msg they need next, make
  var _state = clone(state)
  if(state.sending) {
    if(state.sent + 1 === msg.sequence && state.received < msg.sequence)
      _state.ready = msg
    else if(isNote(state.ready)) //this should only happen when it is the initial request
      _state.ready = {id: msg.author, seq: msg.sequence}
    else if(!isMessage(_state.ready))
      _state.ready = null
  }
  else if(!state.sending) {
    //unless we know they are up to this, send a note
    if(msg.sequence > state.received)
      _state.ready = {id: msg.author, seq: -msg.sequence}
    else if(isNote(state.ready) && state.ready.seq > 0)
      state.ready.seq = message.sequence
    else
      state.ready = null
  }
  return state
}

//have retrived an requested message
exports.retriveMessage = function (state, msg) {
  var _state = clone(state)
  if(state.sending && state.received + 1 == msg.sequence)
    _state.ready = msg
  //if we are not in sending state, just stop.
  //otherwise, the next retrival will be triggered by READ
  return _state
}

<|endoftext|>


<commit_before>function empresaANombre(Appple)

<commit_msg>Init utilis<commit_after>const request = require('request');

export default [
    mapStock,
    priceStock
]

function mapStock(stockName) {

}

function priceStock(Stockacronym) {

}

<|endoftext|>


<commit_before>/**
 * This script contains elements for the common look and feel aspects
 * of the example.
 */

$(document).ready(function(){
  $('#header').html('

' +
                    '
Free Trade Agreement Portal

' +
                    '

');

  var example = 'https://github.com/AusFTAs/' + window.location.toString().match(/[/](example-api-.*)[/]/)[1];

  $('#header').append('
Clone me on GitHub
');
  $('#header').append('
Clone me on GitHub
');

  $('#footer').html('

' +
  '
' +
    '
' +
      '
Clone example on Github |
' +
      '
API |
' +
      '
DFAT FTA Portal |
' +
      '
DFAT Free Trade Agreements |
' +
      '
NICTA
' +
    '
' +
  '
' +
  '
');
});
<commit_msg>Change relative URLs to absolute URLs<commit_after>/**
 * This script contains elements for the common look and feel aspects
 * of the example.
 */

$(document).ready(function(){
  $('#header').html('

' +
                    '
Free Trade Agreement Portal

' +
                    '

');

  var example = 'https://github.com/AusFTAs/' + window.location.toString().match(/[/](example-api-.*)[/]/)[1];

  $('#header').append('
Clone me on GitHub
');
  $('#header').append('
Clone me on GitHub
');

  $('#footer').html('

' +
  '
' +
    '
' +
      '
Clone example on Github |
' +
      '
API |
' +
      '
DFAT FTA Portal |
' +
      '
DFAT Free Trade Agreements |
' +
      '
NICTA
' +
    '
' +
  '
' +
  '
');
});
<|endoftext|>


<commit_before>/*
 * Swipe 2.0
 *
 * Brad Birdsall
 * Copyright 2013, MIT License
 *
*/

function Swipe(container, options) {

  "use strict";

  // utilities
  var noop = function() {}; // simple no operation function
  var offloadFn = function(fn) { setTimeout(fn || noop, 0) }; // offload a functions execution

  // check browser capabilities
  var browser = {
    addEventListener: !!window.addEventListener,
    touch: ('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch,
    transitions: (function(temp) {
      var props = ['transitionProperty', 'WebkitTransition', 'MozTransition', 'OTransition', 'msTransition'];
      for ( var i in props ) if (temp.style[ props[i] ] !== undefined) return true;
      return false;
    })(document.createElement('swipe'))
  };

  // quit if no root element
  if (!container) return;
  var element = container.children[0];
  var slides, slidePos, width, length;
  options = options || {};
  var index = parseInt(options.startSlide, 10) || 0;
  var speed = options.speed || 300;
  var debug = false;

  function setup() {

    // cache slides
    slides = element.children;
    length = slides.length;
    width = $(element).children('.row').outerWidth();

    // create an array to store current positions of each slide
    slidePos = new Array(slides.length);

    //if there's an option on the left, offset other elements by its width
    var offsetLeft = 0;

    // Determine width of each slide
    var slideWrapWidth = 0;

    $(slides).each(function(i) {
      if(i === 0 && $(this).hasClass('options'))
        offsetLeft = $(this).outerWidth();

      slidePos[i] = slideWrapWidth - offsetLeft;
      slideWrapWidth += $(this).outerWidth();
    });

    // Set total swipe element container width
    element.style.width = slideWrapWidth + 'px';

    // stack elements
    var pos = slides.length;
    while(pos--) {

      var slide = slides[pos];
      slide.style.width = slide.clientWidth + 'px';
      slide.setAttribute('data-index', pos);
      move(pos, -offsetLeft, 0);
    }

    container.style.visibility = 'visible';

  }

  function move(index, dist, speed) {
    // index = item we're viewing, dist = initiated translation distance (used for resets)
    translate(index, dist, speed);
    slidePos[index] = dist; //sets the new position for the item with # index
  }

  function translateAll(dist, speed) {
    translate(index-1, dist + slidePos[index], speed);
    translate(index, dist + slidePos[index], speed);
    translate(index+1, dist + slidePos[index], speed);
  }

  function translate(index, dist, speed) {
    var slide = slides[index];
    var style = slide && slide.style;
    if (!style) return;

    style.webkitTransitionDuration =
    style.MozTransitionDuration =
    style.msTransitionDuration =
    style.OTransitionDuration =
    style.transitionDuration = speed + 'ms';

    style.webkitTransform = 'translate(' + dist + 'px,0)' + 'translateZ(0)';
    style.msTransform =
    style.MozTransform =
    style.OTransform = 'translateX(' + dist + 'px)';

  }

  function translateContent(row, delta, optionswidth) {

    /* Swiping left

    //Allow row content to slowly stop sliding beyond this point
      translateContent(activeRow, Math.abs(delta.x + activeOptions.rightWidth), false);

    */

    /* Swiping right

    //Allow row content to slowly stop sliding beyond this point
      translateContent(activeRow, (delta.x - activeOptions.leftWidth), true);

    */

    if(delta !== 0) {
      var directionalMultiplier = delta / Math.abs(delta); // Returns 1 or -1 depending on direction of delta (1 => Left to right swipe)
      var actualTranslateDistance = (delta*directionalMultiplier) - optionswidth;

      actualTranslateDistance = actualTranslateDistance * ((width - actualTranslateDistance) / (3*width) * directionalMultiplier);
    } else
      actualTranslateDistance = 0;

    // Make sure that the content transitions back slowly on release, else follow swipe movement without delay
    if(delta === 0)
      $(row).children().css('-webkit-transition', '-webkit-transform 0.2s');
    else
      $(row).children().css('-webkit-transition', '-webkit-transform 0s');

    // Do the actual translation of the content
    $(row).children().css('-webkit-transform', 'translate(' +(actualTranslateDistance) +'px, 0) translateZ(0)');
  }

  // setup initial vars
  var start = {};
  var delta = {};
  var isScrolling;

  // setup event capturing
  var events = {

    handleEvent: function(event) {

      switch (event.type) {
        case 'touchstart': this.start(event); break;
        case 'touchmove': this.move(event); break;
        case 'touchend': offloadFn(this.end(event)); break;
        case 'resize': offloadFn(setup); break;
      }

      if (options.stopPropagation) event.stopPropagation();

    },
    start: function(event) {
      if(debug)  $("h2").html('touch');

      var touches = event.touches[0];
      // measure start values
      start = {

        // get initial touch coords
        x: touches.pageX,
        y: touches.pageY,

        // store time to determine touch duration
        time: +new Date

      };

      // used for testing first move event
      isScrolling = undefined;

      // reset delta and end measurements
      delta = {};

      // attach touchmove and touchend listeners
      if(!$(event.target).hasClass('options')) {
        element.addEventListener('touchmove', this, false);
        element.addEventListener('touchend', this, false);
      }

    },
    move: function(event) {
      if(debug) $("h2").html('move');

      // ensure swiping with one touch and not pinching
      if ( event.touches.length > 1 || event.scale && event.scale !== 1) return
      if (options.disableScroll) event.preventDefault();

      var touches = event.touches[0];

      // measure change in x and y
      delta = {
        x: touches.pageX - start.x,
        y: touches.pageY - start.y
      }

      // determine if scrolling test has run - one time test
      if (typeof isScrolling == 'undefined')
        isScrolling = !!(isScrolling || Math.abs(delta.x) < Math.abs(delta.y));

      /*  #   #   #   #   #   #   #   #   #   #

      This is where the magic happens.

      #   #   #   #   #   #   #   #   #   #   # */

      var activeRow = ($(event.target).hasClass('row')) ? event.target : event.target.parentElement;
      var activeOptions, revealedOptions;

      if (!isScrolling) {
        event.preventDefault();

        /*  # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

            WHEN SWIPING TO CLOSE REVEALED OPTIONS

            # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # */

        // Used to check if we have any revealed options
        revealedOptions = $(".fn-reveal.st-revealed");

        if(revealedOptions.length === 1) {

          if(revealedOptions.hasClass('left') && delta.x < 0 && delta.x > -(revealedOptions.outerWidth() + 3))
            translateAll(revealedOptions.outerWidth() + delta.x, 0);

          else if(revealedOptions.hasClass('right') && delta.x > 0 && delta.x < (revealedOptions.outerWidth() + 3))
            translateAll(-revealedOptions.outerWidth() + delta.x, 0);

        }

        /*  # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

            HANDLES ALL THE MOVING OF THE ROW AND TRIGGERING OF OPTIONS

            # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # */

        else {
          activeOptions = (delta.x < 0) ? activeRow.nextElementSibling : activeRow.previousElementSibling;
        }

        // If the swipe hasnt gone past the width of the options container, keep things moving
        if(Math.abs(delta.x) < activeOptions.clientWidth)
          translateAll(delta.x, 0);
        else {
          if($(activeOptions).hasClass('st-triggered'))
            translateContent(activeRow, delta.x, activeOptions.clientWidth); // Allow row content to slowly stop sliding beyond this point

          // This is the triggering swipe, options have not been triggered
          else {

            // Translate elements to make sure options are fully revealed
            translateAll(delta.x / Math.abs(delta.x) * activeOptions.clientWidth, 0);

            // Update status to triggered
            $(activeOptions).addClass('st-triggered');

            if($(activeOptions).hasClass('fn-toggle'))
              $(activeOptions).trigger('toggle'); // Trigger a 'swipe-toggle' event for the user to customize what should happen when activated
          }

        }
      }

    },
    end: function(event) {
      if(debug) $("h2").html("end");

      var triggeredOptions = $(".options.st-triggered");
      var activeRow = triggeredOptions.siblings('.row');
      var touchpoint = event.target;

       /*
          # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

          Trigger this if the right option has been triggered.

          # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
        */

      if(triggeredOptions.hasClass('fn-toggle')) {

        translateAll(0, speed); // Resets position of elements
        translateContent(activeRow, 0, false); // Resets position of content to initial position

        // Reset triggered status on triggered options pane
        triggeredOptions.removeClass('st-triggered');

        // Trigger event 'toggleend'
        triggeredOptions.trigger('toggleend');

      } else if(triggeredOptions.hasClass('fn-reveal')) {

        if(triggeredOptions.hasClass('st-revealed') && !$(touchpoint).hasClass('option')) {

          // Reset all elements to their initial position
          translateAll(0, speed);

          // Update status to not revealed
          triggeredOptions.removeClass('st-revealed');

          // Reset triggered status on triggered options pane
          triggeredOptions.removeClass('st-triggered');

        } else
          triggeredOptions.addClass('st-revealed');
      }

      // Resets content in row to initial position
      translateContent(activeRow, 0, false);

      if(triggeredOptions.length === 0) {
        // Resets elements
        translateAll(0, speed);
      }

      // measure duration
      var duration = +new Date - start.time;

      // determine if slide attempt triggers next/prev slide
      var isValidSlide =
            Number(duration) < 250               // if slide duration is less than 250ms
            && Math.abs(delta.x) > 20            // and if slide amt is greater than 20px
            || Math.abs(delta.x) > 79;           // or if slide amt is greater than half the width

      // determine if slide attempt is past start and end
      var isPastBounds =
            !index && delta.x > 0                            // if first slide and slide amt is greater than 0
            || index == slides.length - 1 && delta.x < 0;    // or if last slide and slide amt is less than 0

      if (options.continuous) isPastBounds = false;

      // determine direction of swipe (true:right, false:left)
      var fromRightToLeft = delta.x < 0;

      // kill touchmove and touchend event listeners until touchstart called again
      element.removeEventListener('touchmove', events, false)
      element.removeEventListener('touchend', events, false)

    },

  }

  // trigger setup
  setup();

  // add event listeners
  if (browser.addEventListener) {

    // set touchstart event on element
    if (browser.touch) element.addEventListener('touchstart', events, false);

    // set resize event on window
    window.addEventListener('resize', events, false);

  } else {
    window.onresize = function () { setup() }; // to play nice with old IE
  }

}

if ( window.jQuery || window.Zepto ) {
  (function($) {
    $.fn.Swipe = function(params) {
      return this.each(function() {
        $(this).data('Swipe', new Swipe($(this)[0], params));
      });
    }
  })( window.jQuery || window.Zepto )
}
<commit_msg>Delete swipe.js<commit_after><|endoftext|>