<commit_before>// Seeding database with lorem data

var mongoose = require('mongoose');
var User = mongoose.model('User');
var ctrlAuth = require('../controller/authentication');

User.find(function (err, users) {

  if (users.length > 0) {
    console.log('server: Database already seeded.');
  } else {

    // console.log("server: Seeding database..");
    // var userData = [{
    //   email: "johnbaker@mail.com",
    //   name: 'John Baker'
    // }, {
    //   email: "wixlxiw@mail.com",
    //   name: "Willie Xis"
    // }, {
    //   email: "dineshzy@mail.com",
    //   name: "Dinesh ZY"
    // }, {
    //   email: "shovel-paladin@mail.com",
    //   name: "Shovel Paladin"
    // }, {
    //   email: "cherylgck@mail.com",
    //   name: "Cheryl Goh"
    // }, {
    //   email: "lunagirl79@mail.com",
    //   name: "Kristy Hadfield"
    // }];

    // for (var i = 0; i < userData.length; i++) {
    //   var newUser = new User(userData[i]);

    //   User.create(userData[i], function(err, saved) {
    //     if (err) {
    //       console.log("mongodb: CREATE ROW ERROR");
    //       console.log("=============================================");
    //       console.log(err);
    //       console.log("=============================================");
    //     }
    //     console.log("mongodb: Create user success: " + saved.username);
    //   });
    // }

  }
});
<commit_msg>removed required authentication in seed<commit_after>// Seeding database with lorem data

var mongoose = require('mongoose');
var User = mongoose.model('User');
// var ctrlAuth = require('/controller/authentication');

User.find(function (err, users) {

  if (users.length > 0) {
    console.log('server: Database already seeded.');
  } else {

    // console.log("server: Seeding database..");
    // var userData = [{
    //   email: "johnbaker@mail.com",
    //   name: 'John Baker'
    // }, {
    //   email: "wixlxiw@mail.com",
    //   name: "Willie Xis"
    // }, {
    //   email: "dineshzy@mail.com",
    //   name: "Dinesh ZY"
    // }, {
    //   email: "shovel-paladin@mail.com",
    //   name: "Shovel Paladin"
    // }, {
    //   email: "cherylgck@mail.com",
    //   name: "Cheryl Goh"
    // }, {
    //   email: "lunagirl79@mail.com",
    //   name: "Kristy Hadfield"
    // }];

    // for (var i = 0; i < userData.length; i++) {
    //   var newUser = new User(userData[i]);

    //   User.create(userData[i], function(err, saved) {
    //     if (err) {
    //       console.log("mongodb: CREATE ROW ERROR");
    //       console.log("=============================================");
    //       console.log(err);
    //       console.log("=============================================");
    //     }
    //     console.log("mongodb: Create user success: " + saved.username);
    //   });
    // }

  }
});
<|endoftext|>


<commit_before>var extend = require('ampersand-class-extend');
var io = require ('socket.io-client');

var AmpersandIOConst = function(socket, options){
  options || (options = {});
  if(socket){
    if(typeof socket === 'string'){
      socket = io(socket);
    }
    this.socket = socket;
  }
  if(options.listeners){
    this.listeners = {};
    this.addListeners(options.listeners);
  }
  if(options.setListeners){
    this.setListeners();
  }
  if(options.events){
    this.events = options.events;
  }
};

AmpersandIOConst.extend = extend;

var AmpersandIO = AmpersandIOConst.extend({

  socket: io.connect(),

  // The name of the events to be used in each operation
  events: {
    myEvent: 'event-one',
    otherEvent: 'event-two'
  },

  listeners: {
    'event-three':{
      fn: function(data, cb){
        console.log('event three received');
        return cb();
      },
      active: false,
    },
    'event-four': {
      fn: function(data, cb){
        console.log('event four received');
        return cb();
      },
      active: false,
    }
  },

  addListeners: function(listeners){
    for(var listenerID in listeners){
      if(!listeners.hasOwnProperty(listenerID)){
        continue;
      }
      if(this.listeners[listenerID] && this.listeners[listenerID].active){
        continue;
      }
      var listener = listeners[listenerID];
      if(this.events[listenerID]){
        listenerID = this.events[listenerID];
      }
      if(typeof listenerID === 'string'){
        listenerID = [listenerID];
      }
      for(var i = 0; i < listenerID.length; i++){
        var id = listenerID[i];
        this.listeners[id] = {fn: listener.fn};
        if(listener.active){
          this.socket.on(id, this.listeners[id].fn);
          this.listeners[id].active = true;
        }
        else{
          this.listeners[id].active = false;
        }
      }
    }
  },

  setListeners: function (listeners){
    if(!listeners){
      listeners = Object.keys(this.listeners);
    }
    for(var i = 0; i < listeners.length; i++){
      var listenerID = listeners[i];
      var listener = this.listeners[listenerID];
      if(!listener.active){
        listener.active = true;
        if(this.events[listenerID]){
          listenerID = this.events[listenerID];
        }
        if(typeof listenerID === 'string'){
          listenerID = [listenerID];
        }
        for(var j = 0; j < listenerID.length; j++){
          this.socket.on(listenerID[j], listener.fn);
        }
      }
    }
  },

  removeListeners: function (listeners){
    if(!listeners){
      listeners = Object.keys(this.listeners);
    }
    for(var i = 0; i < listeners.length; i++){
      var listenerID = listeners[i];
      var listener = this.listeners[listenerID];
      if(listener.active){
        listener.active = false;
        if(this.events[listenerID]){
          listenerID = this.events[listenerID];
        }
        if(typeof listenerID === 'string'){
          listenerID = [listenerID];
        }
        for(var j = 0; j < listenerID.length; j++){
          this.socket.removeListener(listenerID[j], listener.fn);
        }
      }
    }
  },
  // Overridable function responsible for emitting the events
  emit: function (event, model, options){
    if(typeof event === 'string'){
      event = [event];
    }
    for(var i = 0; i < event.length; i++){
      if(options.room){
        io.to(options.room).emit(event[i], model, options.callback);
      }
      else{
        this.socket.emit(event[i], model, options.callback);
      }
    }
  }
});

module.exports = AmpersandIO;<commit_msg>bug on listeners init<commit_after>var extend = require('ampersand-class-extend');
var io = require ('socket.io-client');

var AmpersandIOConst = function(socket, options){
  options || (options = {});
  if(socket){
    if(typeof socket === 'string'){
      socket = io(socket);
    }
    this.socket = socket;
  }
  if(options.events){
    this.events = options.events;
  }
  if(options.listeners){
    this.listeners = {};
    this.addListeners(options.listeners);
  }
  if(options.setListeners){
    this.setListeners();
  }
};

AmpersandIOConst.extend = extend;

var AmpersandIO = AmpersandIOConst.extend({

  socket: io.connect(),

  // The name of the events to be used in each operation
  events: {
    myEvent: 'event-one',
    otherEvent: 'event-two'
  },

  listeners: {
    'event-three':{
      fn: function(data, cb){
        console.log('event three received');
        return cb();
      },
      active: false,
    },
    'event-four': {
      fn: function(data, cb){
        console.log('event four received');
        return cb();
      },
      active: false,
    }
  },

  addListeners: function(listeners){
    for(var listenerID in listeners){
      if(!listeners.hasOwnProperty(listenerID)){
        continue;
      }
      if(this.listeners[listenerID] && this.listeners[listenerID].active){
        continue;
      }
      var listener = listeners[listenerID];
      if(this.events[listenerID]){
        listenerID = this.events[listenerID];
      }
      if(typeof listenerID === 'string'){
        listenerID = [listenerID];
      }
      for(var i = 0; i < listenerID.length; i++){
        var id = listenerID[i];
        this.listeners[id] = {fn: listener.fn};
        if(listener.active){
          this.socket.on(id, this.listeners[id].fn);
          this.listeners[id].active = true;
        }
        else{
          this.listeners[id].active = false;
        }
      }
    }
  },

  setListeners: function (listeners){
    if(!listeners){
      listeners = Object.keys(this.listeners);
    }
    for(var i = 0; i < listeners.length; i++){
      var listenerID = listeners[i];
      var listener = this.listeners[listenerID];
      if(!listener.active){
        listener.active = true;
        if(this.events[listenerID]){
          listenerID = this.events[listenerID];
        }
        if(typeof listenerID === 'string'){
          listenerID = [listenerID];
        }
        for(var j = 0; j < listenerID.length; j++){
          this.socket.on(listenerID[j], listener.fn);
        }
      }
    }
  },

  removeListeners: function (listeners){
    if(!listeners){
      listeners = Object.keys(this.listeners);
    }
    for(var i = 0; i < listeners.length; i++){
      var listenerID = listeners[i];
      var listener = this.listeners[listenerID];
      if(listener.active){
        listener.active = false;
        if(this.events[listenerID]){
          listenerID = this.events[listenerID];
        }
        if(typeof listenerID === 'string'){
          listenerID = [listenerID];
        }
        for(var j = 0; j < listenerID.length; j++){
          this.socket.removeListener(listenerID[j], listener.fn);
        }
      }
    }
  },
  // Overridable function responsible for emitting the events
  emit: function (event, model, options){
    if(typeof event === 'string'){
      event = [event];
    }
    for(var i = 0; i < event.length; i++){
      if(options.room){
        io.to(options.room).emit(event[i], model, options.callback);
      }
      else{
        this.socket.emit(event[i], model, options.callback);
      }
    }
  }
});

module.exports = AmpersandIO;<|endoftext|>


<commit_before>'use strict';
/**
 * Github FileBrowser configuration module.
 */

var m = require('mithril');
var $ = require('jquery');
var URI = require('URIjs');
var Fangorn = require('js/fangorn');
var waterbutler = require('js/waterbutler');
var $osf = require('js/osfHelpers');

// Cross browser key codes for the Command key
var commandKeys = [224, 17, 91, 93];

function _uploadUrl(item, file) {
    return waterbutler.buildTreeBeardUpload(item, file, {branch: item.data.branch});
}

// TODO: Refactor, repeating from core function too much
function _removeEvent (event, items) {
    var tb = this;
    function cancelDelete() {
        tb.modal.dismiss();
    }

    function runDelete (item) {
        tb.select('.tb-modal-footer .text-danger').html(' Deleting...').css('color', 'grey');
        // delete from server, if successful delete from view
        $.ajax({
            url: waterbutler.buildTreeBeardDelete(item, {branch: item.data.branch, sha: item.data.extra.fileSha}),
            type : 'DELETE',
            beforeSend: $osf.setXHRAuthorization
        }).done(function (data) {
                // delete view
                tb.deleteNode(item.parentID, item.id);
                Fangorn.Utils.dismissToolbar.call(tb);
                tb.modal.dismiss();
                tb.clearMultiselect();

        }).fail(function (data) {
                tb.modal.dismiss();
                Fangorn.Utils.dismissToolbar.call(tb);
                item.notify.update('Delete failed.', 'danger', undefined, 3000);
                tb.clearMultiselect();
        });
    }

    function runDeleteMultiple(items){
        items.forEach(function(item){
            runDelete(item);
        });
    }
    // If there is only one item being deleted, don't complicate the issue:
    if(items.length === 1) {
        var parent = items[0].parent();
        var mithrilContentSingle = m('div', [
            m('h3.break-word', 'Delete "' + items[0].data.name + '"'),
            m('p', 'This action is irreversible.'),
            parent.children.length < 2 ? m('p', 'If a folder in Github has no children it will automatically be removed.') : ''
        ]);
        var mithrilButtonsSingle = m('div', [
            m('span.tb-modal-btn', { 'class' : 'text-default', onclick : function() { cancelDelete(); } }, 'Cancel'),
            m('span.tb-modal-btn', { 'class' : 'text-danger', onclick : function() { runDelete(items[0]); }  }, 'Delete')
        ]);
        // This is already being checked before this step but will keep this edit permission check
        if(items[0].data.permissions.edit){
            tb.modal.update(mithrilContentSingle, mithrilButtonsSingle);
        }
    } else {
        // Check if all items can be deleted
        var canDelete = true;
        var deleteList = [];
        var noDeleteList = [];
        var mithrilContentMultiple;
        var mithrilButtonsMultiple;
        items.forEach(function(item, index, arr){
            if(!item.data.permissions.edit){
                canDelete = false;
                noDeleteList.push(item);
            } else {
                deleteList.push(item);
            }
        });
        // If all items can be deleted
        if(canDelete){
            mithrilContentMultiple = m('div', [
                    m('h3.break-word', 'Delete multiple files?'),
                    m('p', 'This action is irreversible.'),
                    deleteList.map(function(item){
                        return m('.fangorn-canDelete.text-success', item.data.name);
                    })
                ]);
            mithrilButtonsMultiple =  m('div', [
                    m('span.tb-modal-btn', { 'class' : 'text-default', onclick : function() { cancelDelete(); } }, 'Cancel'),
                    m('span.tb-modal-btn', { 'class' : 'text-danger', onclick : function() { runDeleteMultiple.call(tb, deleteList); }  }, 'Delete All')
                ]);
        } else {
            mithrilContentMultiple = m('div', [
                    m('h3.break-word', 'Delete multiple files?'),
                    m('p', 'Some of these files can\'t be deleted but you can delete the ones highlighted with green. This action is irreversible.'),
                    deleteList.map(function(n){
                        return m('.fangorn-canDelete.text-success', n.data.name);
                    }),
                    noDeleteList.map(function(n){
                        return m('.fangorn-noDelete.text-warning', n.data.name);
                    })
                ]);
            mithrilButtonsMultiple =  m('div', [
                    m('span.tb-modal-btn', { 'class' : 'text-default', onclick : function() { cancelDelete(); } }, 'Cancel'),
                    m('span.tb-modal-btn', { 'class' : 'text-danger', onclick : function() { runDeleteMultiple.call(tb, deleteList); }  }, 'Delete Some')
                ]);
        }
        tb.modal.update(mithrilContentMultiple, mithrilButtonsMultiple);
    }

    return true; // Let fangorn know this config option was used.
}

// Define Fangorn Button Actions
var _githubItemButtons = {
    view: function (ctrl, args, children) {
        var tb = args.treebeard;
        var item = args.item;
        var buttons = [];
        function _downloadEvent(event, item, col) {
            event.stopPropagation();
            window.location = waterbutler.buildTreeBeardDownload(item, {fileSha: item.data.extra.fileSha});
        }
        // Download Zip File
        if (item.kind === 'folder') {
            var branchArray = [];
            if (item.data.branches) {
                item.data.branch = item.data.branch || item.data.defaultBranch;
                for (var i = 0; i < item.data.branches.length; i++) {
                    var selected = item.data.branches[i] === item.data.branch ? 'selected' : '';
                    branchArray.push(m('option', {
                        selected: selected,
                        value: item.data.branches[i]
                    }, item.data.branches[i]));
                }
            }
            if (item.data.addonFullname) {
                buttons.push(
                    m.component(Fangorn.Components.dropdown, {
                        'label': 'Branch: ',
                        onchange: function (event) {
                            changeBranch.call(tb, item, event.target.value);
                        },
                        icon: 'fa fa-external-link',
                        className: 'text-info'
                    }, branchArray)
                );
            }
            if (tb.options.placement !== 'fileview') {
                // If File and FileRead are not defined dropzone is not supported and neither is uploads
                if (window.File && window.FileReader && item.data.permissions && item.data.permissions.edit) {
                    buttons.push(
                        m.component(Fangorn.Components.button, {
                            onclick: function (event) {
                                Fangorn.ButtonEvents._uploadEvent.call(tb, event, item);
                            },
                            icon: 'fa fa-upload',
                            className: 'text-success'
                        }, 'Upload'),
                        m.component(Fangorn.Components.button, {
                            onclick: function (event) {
                                tb.toolbarMode(Fangorn.Components.toolbarModes.ADDFOLDER);
                            },
                            icon: 'fa fa-plus',
                            className: 'text-success'
                        }, 'Create Folder'),
                        m.component(Fangorn.Components.button, {
                            onclick: function (event) {
                                _removeEvent.call(tb, event, [item]);
                            },
                            icon: 'fa fa-trash',
                            className: 'text-danger'
                        }, 'Delete')
                    );
                }
                if (item.data.addonFullname) {
                    buttons.push(
                        m.component(Fangorn.Components.button, {
                            onclick: function (event) {
                                window.location = item.data.urls.zip;
                            },
                            icon: 'fa fa-download',
                            className: 'text-primary'
                        }, 'Download'),
                        m.component(Fangorn.Components.button, {
                            onclick: function (event) {
                                window.open(item.data.urls.repo, '_blank');
                            },
                            icon: 'fa fa-external-link',
                            className: 'text-info'
                        }, 'Open')
                    );
                }
            }
        } else if (item.kind === 'file' && tb.options.placement !== 'fileview') {
            buttons.push(
                m.component(Fangorn.Components.button, {
                    onclick: function (event) {
                        _downloadEvent.call(tb, event, item);
                    },
                    icon: 'fa fa-download',
                    className: 'text-primary'
                }, 'Download')
            );
            if (item.data.permissions && item.data.permissions.view) {
                buttons.push(
                    m.component(Fangorn.Components.button, {
                        onclick: function(event) {
                            gotoFile.call(tb, item);
                        },
                        icon: 'fa fa-file-o',
                        className : 'text-info'
                    }, 'View'));
            }
            if (item.data.permissions && item.data.permissions.edit) {
                buttons.push(
                    m.component(Fangorn.Components.button, {
                        onclick: function (event) {
                            _removeEvent.call(tb, event, [item]);
                        },
                        icon: 'fa fa-trash',
                        className: 'text-danger'
                    }, 'Delete')
                );
            }
            if (item.data.permissions && item.data.permissions.view && !item.data.permissions.private) {
                buttons.push(
                    m('a.text-info.fangorn-toolbar-icon', {href: item.data.extra.webView}, [
                        m('i.fa.fa-external-link'),
                        m('span', 'View on GitHub')
                    ])
                );
            }
        }

        if(item.data.provider && !item.data.isAddonRoot && item.data.permissions && item.data.permissions.edit && tb.options.placement !== 'fileview') {
            buttons.push(
                m.component(Fangorn.Components.button, {
                    onclick: function() {
                        tb.toolbarMode(Fangorn.Components.toolbarModes.RENAME);
                    },
                    tooltip: 'Change the name of the item',
                    icon: 'fa fa-font',
                    className : 'text-info'
                }, 'Rename')
            );
        }

        return m('span', buttons); // Tell fangorn this function is used.
    }
};

function changeBranch(item, ref){
    item.data.branch = ref;
    this.updateFolder(null, item);
}

function _resolveLazyLoad(item) {
    return waterbutler.buildTreeBeardMetadata(item, {ref: item.data.branch});
}

function _fangornLazyLoadOnLoad (tree, event) {
    var tb = this;
    tree.children.forEach(function(item) {
        Fangorn.Utils.inheritFromParent(item, tree, ['branch']);
    });
    Fangorn.Utils.setCurrentFileID.call(tb, tree, window.contextVars.node.id, window.contextVars.file);
    if(!event && tb.isMultiselected(tb.currentFileID)){
        Fangorn.Utils.scrollToFile.call(tb, tb.currentFileID);
    }
}

function gotoFile (item) {
    var tb = this;
    var fileurl = new URI(item.data.nodeUrl)
        .segment('files')
        .segment(item.data.provider)
        .segment(item.data.path.substring(1))
        .search({branch: item.data.branch})
        .toString();
    if(commandKeys.indexOf(tb.pressedKey) !== -1) {
        window.open(fileurl, '_blank');
    } else {
        window.open(fileurl, '_self');
    }
}

function _fangornGithubTitle(item, col)  {
    var tb = this;
    if (item.data.isAddonRoot && item.connected === false) { // as opposed to undefined, avoids unnecessary setting of this value
        return Fangorn.Utils.connectCheckTemplate.call(this, item);
    }

    if (item.data.addonFullname) {
        var urlParams = $osf.urlParams();

        if (!item.data.branch) {
            if (urlParams.branch && urlParams.branch != item.data.branch) {
                item.data.branch = urlParams.branch;
            }
        }
        var branch = item.data.branch || item.data.defaultBranch;

        return m('span',[
            m('github-name', item.data.name + ' (' + branch + ')')
        ]);
    } else {
        if (item.kind === 'file' && item.data.permissions.view) {
            return m('span',[
                m('github-name.fg-file-links', {
                    onclick: function() {
                        gotoFile.call(tb, item);
                    }
                }, item.data.name)]);
        } else {
            return m('span', item.data.name);
        }
    }
}

function _fangornColumns (item) {
    var tb = this;
    var selectClass = '';
    var node = item.parent().parent();
    var columns = [];
    columns.push({
        data : 'name',
        folderIcons : true,
        filter: true,
        custom : _fangornGithubTitle
    });

    if(tb.options.placement === 'project-files') {
        columns.push(
        {
            data  : 'downloads',
            filter : false,
            css : ''
        });
    }
    return columns;
}

function _fangornFolderIcons(item){
    if(item.data.iconUrl){
        return m('img',{src:item.data.iconUrl, style:{width:'16px', height:'auto'}}, ' ');
    }
    return undefined;
}

function _fangornUploadComplete(item){
    var index = this.returnIndex(item.id);
}

function _fangornUploadSuccess(file, item, response) {
    if (response) {
        response.branch = item.parent().data.branch;
    }
}

// Register configuration
Fangorn.config.github = {
    // Handle changing the branch select
    uploadUrl: _uploadUrl,
    lazyload: _resolveLazyLoad,
    resolveRows: _fangornColumns,
    folderIcon: _fangornFolderIcons,
    onUploadComplete: _fangornUploadComplete,
    lazyLoadOnLoad: _fangornLazyLoadOnLoad,
    uploadSuccess: _fangornUploadSuccess,
    itemButtons: _githubItemButtons,
    removeEvent : _removeEvent
};
<commit_msg>Revert "Add delete button for GitHub folders in file view"<commit_after>'use strict';
/**
 * Github FileBrowser configuration module.
 */

var m = require('mithril');
var $ = require('jquery');
var URI = require('URIjs');
var Fangorn = require('js/fangorn');
var waterbutler = require('js/waterbutler');
var $osf = require('js/osfHelpers');

// Cross browser key codes for the Command key
var commandKeys = [224, 17, 91, 93];

function _uploadUrl(item, file) {
    return waterbutler.buildTreeBeardUpload(item, file, {branch: item.data.branch});
}

// TODO: Refactor, repeating from core function too much
function _removeEvent (event, items) {
    var tb = this;
    function cancelDelete() {
        tb.modal.dismiss();
    }

    function runDelete (item) {
        tb.select('.tb-modal-footer .text-danger').html(' Deleting...').css('color', 'grey');
        // delete from server, if successful delete from view
        $.ajax({
            url: waterbutler.buildTreeBeardDelete(item, {branch: item.data.branch, sha: item.data.extra.fileSha}),
            type : 'DELETE',
            beforeSend: $osf.setXHRAuthorization
        }).done(function (data) {
                // delete view
                tb.deleteNode(item.parentID, item.id);
                Fangorn.Utils.dismissToolbar.call(tb);
                tb.modal.dismiss();
                tb.clearMultiselect();

        }).fail(function (data) {
                tb.modal.dismiss();
                Fangorn.Utils.dismissToolbar.call(tb);
                item.notify.update('Delete failed.', 'danger', undefined, 3000);
                tb.clearMultiselect();
        });
    }

    function runDeleteMultiple(items){
        items.forEach(function(item){
            runDelete(item);
        });
    }
    // If there is only one item being deleted, don't complicate the issue:
    if(items.length === 1) {
        var parent = items[0].parent();
        var mithrilContentSingle = m('div', [
            m('h3.break-word', 'Delete "' + items[0].data.name + '"'),
            m('p', 'This action is irreversible.'),
            parent.children.length < 2 ? m('p', 'If a folder in Github has no children it will automatically be removed.') : ''
        ]);
        var mithrilButtonsSingle = m('div', [
            m('span.tb-modal-btn', { 'class' : 'text-default', onclick : function() { cancelDelete(); } }, 'Cancel'),
            m('span.tb-modal-btn', { 'class' : 'text-danger', onclick : function() { runDelete(items[0]); }  }, 'Delete')
        ]);
        // This is already being checked before this step but will keep this edit permission check
        if(items[0].data.permissions.edit){
            tb.modal.update(mithrilContentSingle, mithrilButtonsSingle);
        }
    } else {
        // Check if all items can be deleted
        var canDelete = true;
        var deleteList = [];
        var noDeleteList = [];
        var mithrilContentMultiple;
        var mithrilButtonsMultiple;
        items.forEach(function(item, index, arr){
            if(!item.data.permissions.edit){
                canDelete = false;
                noDeleteList.push(item);
            } else {
                deleteList.push(item);
            }
        });
        // If all items can be deleted
        if(canDelete){
            mithrilContentMultiple = m('div', [
                    m('h3.break-word', 'Delete multiple files?'),
                    m('p', 'This action is irreversible.'),
                    deleteList.map(function(item){
                        return m('.fangorn-canDelete.text-success', item.data.name);
                    })
                ]);
            mithrilButtonsMultiple =  m('div', [
                    m('span.tb-modal-btn', { 'class' : 'text-default', onclick : function() { cancelDelete(); } }, 'Cancel'),
                    m('span.tb-modal-btn', { 'class' : 'text-danger', onclick : function() { runDeleteMultiple.call(tb, deleteList); }  }, 'Delete All')
                ]);
        } else {
            mithrilContentMultiple = m('div', [
                    m('h3.break-word', 'Delete multiple files?'),
                    m('p', 'Some of these files can\'t be deleted but you can delete the ones highlighted with green. This action is irreversible.'),
                    deleteList.map(function(n){
                        return m('.fangorn-canDelete.text-success', n.data.name);
                    }),
                    noDeleteList.map(function(n){
                        return m('.fangorn-noDelete.text-warning', n.data.name);
                    })
                ]);
            mithrilButtonsMultiple =  m('div', [
                    m('span.tb-modal-btn', { 'class' : 'text-default', onclick : function() { cancelDelete(); } }, 'Cancel'),
                    m('span.tb-modal-btn', { 'class' : 'text-danger', onclick : function() { runDeleteMultiple.call(tb, deleteList); }  }, 'Delete Some')
                ]);
        }
        tb.modal.update(mithrilContentMultiple, mithrilButtonsMultiple);
    }

    return true; // Let fangorn know this config option was used.
}

// Define Fangorn Button Actions
var _githubItemButtons = {
    view: function (ctrl, args, children) {
        var tb = args.treebeard;
        var item = args.item;
        var buttons = [];
        function _downloadEvent(event, item, col) {
            event.stopPropagation();
            window.location = waterbutler.buildTreeBeardDownload(item, {fileSha: item.data.extra.fileSha});
        }
        // Download Zip File
        if (item.kind === 'folder') {
            var branchArray = [];
            if (item.data.branches) {
                item.data.branch = item.data.branch || item.data.defaultBranch;
                for (var i = 0; i < item.data.branches.length; i++) {
                    var selected = item.data.branches[i] === item.data.branch ? 'selected' : '';
                    branchArray.push(m('option', {
                        selected: selected,
                        value: item.data.branches[i]
                    }, item.data.branches[i]));
                }
            }
            if (item.data.addonFullname) {
                buttons.push(
                    m.component(Fangorn.Components.dropdown, {
                        'label': 'Branch: ',
                        onchange: function (event) {
                            changeBranch.call(tb, item, event.target.value);
                        },
                        icon: 'fa fa-external-link',
                        className: 'text-info'
                    }, branchArray)
                );
            }
            if (tb.options.placement !== 'fileview') {
                // If File and FileRead are not defined dropzone is not supported and neither is uploads
                if (window.File && window.FileReader && item.data.permissions && item.data.permissions.edit) {
                    buttons.push(
                        m.component(Fangorn.Components.button, {
                            onclick: function (event) {
                                Fangorn.ButtonEvents._uploadEvent.call(tb, event, item);
                            },
                            icon: 'fa fa-upload',
                            className: 'text-success'
                        }, 'Upload'),
                        m.component(Fangorn.Components.button, {
                            onclick: function (event) {
                                tb.toolbarMode(Fangorn.Components.toolbarModes.ADDFOLDER);
                            },
                            icon: 'fa fa-plus',
                            className: 'text-success'
                        }, 'Create Folder')
                    );
                }
                if (item.data.addonFullname) {
                    buttons.push(
                        m.component(Fangorn.Components.button, {
                            onclick: function (event) {
                                window.location = item.data.urls.zip;
                            },
                            icon: 'fa fa-download',
                            className: 'text-primary'
                        }, 'Download'),
                        m.component(Fangorn.Components.button, {
                            onclick: function (event) {
                                window.open(item.data.urls.repo, '_blank');
                            },
                            icon: 'fa fa-external-link',
                            className: 'text-info'
                        }, 'Open')
                    );
                }
            }
        } else if (item.kind === 'file' && tb.options.placement !== 'fileview') {
            buttons.push(
                m.component(Fangorn.Components.button, {
                    onclick: function (event) {
                        _downloadEvent.call(tb, event, item);
                    },
                    icon: 'fa fa-download',
                    className: 'text-primary'
                }, 'Download')
            );
            if (item.data.permissions && item.data.permissions.view) {
                buttons.push(
                    m.component(Fangorn.Components.button, {
                        onclick: function(event) {
                            gotoFile.call(tb, item);
                        },
                        icon: 'fa fa-file-o',
                        className : 'text-info'
                    }, 'View'));
            }
            if (item.data.permissions && item.data.permissions.edit) {
                buttons.push(
                    m.component(Fangorn.Components.button, {
                        onclick: function (event) {
                            _removeEvent.call(tb, event, [item]);
                        },
                        icon: 'fa fa-trash',
                        className: 'text-danger'
                    }, 'Delete')
                );
            }
            if (item.data.permissions && item.data.permissions.view && !item.data.permissions.private) {
                buttons.push(
                    m('a.text-info.fangorn-toolbar-icon', {href: item.data.extra.webView}, [
                        m('i.fa.fa-external-link'),
                        m('span', 'View on GitHub')
                    ])
                );
            }
        }

        if(item.data.provider && !item.data.isAddonRoot && item.data.permissions && item.data.permissions.edit && tb.options.placement !== 'fileview') {
            buttons.push(
                m.component(Fangorn.Components.button, {
                    onclick: function() {
                        tb.toolbarMode(Fangorn.Components.toolbarModes.RENAME);
                    },
                    tooltip: 'Change the name of the item',
                    icon: 'fa fa-font',
                    className : 'text-info'
                }, 'Rename')
            );
        }

        return m('span', buttons); // Tell fangorn this function is used.
    }
};

function changeBranch(item, ref){
    item.data.branch = ref;
    this.updateFolder(null, item);
}

function _resolveLazyLoad(item) {
    return waterbutler.buildTreeBeardMetadata(item, {ref: item.data.branch});
}

function _fangornLazyLoadOnLoad (tree, event) {
    var tb = this;
    tree.children.forEach(function(item) {
        Fangorn.Utils.inheritFromParent(item, tree, ['branch']);
    });
    Fangorn.Utils.setCurrentFileID.call(tb, tree, window.contextVars.node.id, window.contextVars.file);
    if(!event && tb.isMultiselected(tb.currentFileID)){
        Fangorn.Utils.scrollToFile.call(tb, tb.currentFileID);
    }
}

function gotoFile (item) {
    var tb = this;
    var fileurl = new URI(item.data.nodeUrl)
        .segment('files')
        .segment(item.data.provider)
        .segment(item.data.path.substring(1))
        .search({branch: item.data.branch})
        .toString();
    if(commandKeys.indexOf(tb.pressedKey) !== -1) {
        window.open(fileurl, '_blank');
    } else {
        window.open(fileurl, '_self');
    }
}

function _fangornGithubTitle(item, col)  {
    var tb = this;
    if (item.data.isAddonRoot && item.connected === false) { // as opposed to undefined, avoids unnecessary setting of this value
        return Fangorn.Utils.connectCheckTemplate.call(this, item);
    }

    if (item.data.addonFullname) {
        var urlParams = $osf.urlParams();

        if (!item.data.branch) {
            if (urlParams.branch && urlParams.branch != item.data.branch) {
                item.data.branch = urlParams.branch;
            }
        }
        var branch = item.data.branch || item.data.defaultBranch;

        return m('span',[
            m('github-name', item.data.name + ' (' + branch + ')')
        ]);
    } else {
        if (item.kind === 'file' && item.data.permissions.view) {
            return m('span',[
                m('github-name.fg-file-links', {
                    onclick: function() {
                        gotoFile.call(tb, item);
                    }
                }, item.data.name)]);
        } else {
            return m('span', item.data.name);
        }
    }
}

function _fangornColumns (item) {
    var tb = this;
    var selectClass = '';
    var node = item.parent().parent();
    var columns = [];
    columns.push({
        data : 'name',
        folderIcons : true,
        filter: true,
        custom : _fangornGithubTitle
    });

    if(tb.options.placement === 'project-files') {
        columns.push(
        {
            data  : 'downloads',
            filter : false,
            css : ''
        });
    }
    return columns;
}

function _fangornFolderIcons(item){
    if(item.data.iconUrl){
        return m('img',{src:item.data.iconUrl, style:{width:'16px', height:'auto'}}, ' ');
    }
    return undefined;
}

function _fangornUploadComplete(item){
    var index = this.returnIndex(item.id);
}

function _fangornUploadSuccess(file, item, response) {
    if (response) {
        response.branch = item.parent().data.branch;
    }
}

// Register configuration
Fangorn.config.github = {
    // Handle changing the branch select
    uploadUrl: _uploadUrl,
    lazyload: _resolveLazyLoad,
    resolveRows: _fangornColumns,
    folderIcon: _fangornFolderIcons,
    onUploadComplete: _fangornUploadComplete,
    lazyLoadOnLoad: _fangornLazyLoadOnLoad,
    uploadSuccess: _fangornUploadSuccess,
    itemButtons: _githubItemButtons,
    removeEvent : _removeEvent
};
<|endoftext|>


<commit_before>define(function(require) {

	'use strict';

	var $        = require('jquery');
	var _        = require('underscore');
	var Backbone = require('backbone');
	var PIXI     = require('pixi');
	var html     = require('text!templates/heatmap.html');

	var OscillatorView       = require('views/oscillator');
	var BarrierView          = require('views/barrier');
	var SegmentPotentialView = require('views/segment-potential');

	/*
	 * "Local" variables for functions to share and recycle
	 */
	var lat,
		width,
		height,
	    i,
	    j,
	    particles,
	    brightness;

	/**
	 * HeatmapView is the main focus of the app.  It shows the values of the 2D lattice
	 *   on a graph with two axes (default x and y but dependent on the WaveSimulation).
	 *   Includes the containing panel, the (colored) heatmap itself, axis labels and
	 *   measurements, and interactive components including the barriers, cross-section
	 *   slider, and (for now) oscillator controls.
	 *
	 */
	var HeatmapView = Backbone.View.extend({

		template: _.template(html),

		tagName: 'figure',
		className: 'heatmap-container',

		events: {
			'slide .cross-section-slider' : 'moveCrossSection',
			'set   .cross-section-slider' : 'stopCrossSection'
		},

		initialize: function(options) {

			// Default values
			options = _.extend({
				title: 'Top View',
				x: {
					start: 0,
					end: 100,
					step: 10,
					label: 'x (cm)'
				},
				y: {
					start: 0,
					end: 100,
					step: 10,
					label: 'y (cm)'
				},
				brightness: 0.5,
				color: '#0D6A7C'
			}, options);

			// Save options
			if (options.waveSimulation)
				this.waveSimulation = options.waveSimulation;
			else
				throw 'HeatmapView requires a WaveSimulation model to render.';

			// Save graph information for rendering
			this.graphInfo = {
				title: options.title,
				x: options.x,
				y: options.y
			};

			// The alpha modifer for particles
			this.brightness = options.brightness;

			// Background color for canvas
			this.color = options.color;

			// To keep track of history so we can interpolate values
			this.previousLattice = this.waveSimulation.lattice.clone();

			// Lists of views for updating
			this.segmentPotentialViews = [];
			this.oscillatorViews = [];

			// Bind events
			$(window).bind('resize', $.proxy(this.windowResized, this));

			// Cached calculations of lattice-canvas ratios
			this.xSpacing = 1;
			this.ySpacing = 1;

			// Listeners
			this.listenTo(this.waveSimulation, 'segment-potential-added', this.renderSegmentPotentialView);
			this.listenTo(this.waveSimulation, 'change:oscillatorCount', this.changeOscillatorCount);

			this.on('change:color', this.changeColor);
		},

		/**
		 * Renders content and canvas for heatmap
		 */
		render: function() {
			this.$el.empty();

			this.renderContainer();
			this.initRenderer();
			this.initGraphics();
			this.changeColor();

			return this;
		},

		/**
		 * Renders html container
		 */
		renderContainer: function() {
			this.$el.html(this.template(this.graphInfo));

			this.$('.cross-section-slider').noUiSlider({
				start: (this.graphInfo.y.end - this.graphInfo.y.start) / 2,
				direction: 'rtl',
				orientation: 'vertical',
				behaviour: 'none',
				range: {
					min: this.graphInfo.y.start,
					max: this.graphInfo.y.end
				}
			}).find('.noUi-handle')
				.append('
')
				.append('
');
		},

		/**
		 * Initializes a renderer using the .heatmap-canvas canvas element
		 */
		initRenderer: function() {
			this.$canvas = this.$('.heatmap-canvas');

			this.renderer = PIXI.autoDetectRenderer(
				this.$canvas.width(),  // Width
				this.$canvas.height(), // Height
				this.$canvas[0],       // Canvas element
				true,                  // Transparent background
				true                   // Antialiasing
			);
		},

		initGraphics: function() {
			// Create a stage to hold everything
			this.stage = new PIXI.Stage(0x000000);

			// Create a specialized container for rendering lots of particles
			this.spriteBatch = new PIXI.SpriteBatch();
			this.stage.addChild(this.spriteBatch);

			this.initParticles();
			this.initComponents();
		},

		initComponents: function() {
			this.barrierView = new BarrierView({
				heatmapView: this,
				barrier: this.waveSimulation.barrier
			});
			this.barrierView.render();
			this.$('.potential-views').append(this.barrierView.el);

			for (var i = 0; i < this.waveSimulation.oscillators.length; i++) {
				this.renderOscillatorView(this.waveSimulation.oscillators[i]);
			}
			this.changeOscillatorCount();
		},

		initParticles: function() {
			this.particles = [];

			width  = this.waveSimulation.lattice.width;
			height = this.waveSimulation.lattice.height;

			var texture = this.generateParticleTexture(0);
			var particle;
			var row;

			for (i = 0; i < width; i++) {
				row = [];
				for (j = 0; j < height; j++) {
					// Create a particle representing this cell
					particle = new PIXI.Sprite(texture);
					particle.anchor.x = particle.anchor.y = 0.5;

					row.push(particle);
					this.spriteBatch.addChild(particle);
				}
				this.particles.push(row);
			}

			// Just try it...it actually works on FireFox
			this.positionParticles();
		},

		positionParticles: function() {
			width  = this.waveSimulation.lattice.width;
			height = this.waveSimulation.lattice.height;

			var xSpacing = this.$canvas.width()  / (width - 1);
			var ySpacing = this.$canvas.height() / (height - 1);

			particles = this.particles;

			var texture = this.generateParticleTexture(Math.max(xSpacing, ySpacing) * 2);
			var particle;

			for (i = 0; i < width; i++) {
				for (j = 0; j < height; j++) {
					particle = particles[i][j];
					particle.setTexture(texture);
					particle.position.x = xSpacing * i;
					particle.position.y = ySpacing * (height - j - 1); // Reverse bottom to top with offset
				}
			}

			this.xSpacing = xSpacing;
			this.ySpacing = ySpacing;
		},

		generateParticleTexture: function(radius) {
			// Draw on a canvas and then use it as a texture for our particles
			var canvas = document.createElement('canvas');
			canvas.width  = radius * 2 || 1;
			canvas.height = radius * 2 || 1;

			var ctx = canvas.getContext('2d');

			var gradient = ctx.createRadialGradient(radius, radius, 0, radius, radius, radius);
			gradient.addColorStop(0, 'rgba(255,255,255,1)');
			gradient.addColorStop(1, 'rgba(255,255,255,0)');

			ctx.fillStyle = gradient;
			ctx.fillRect(0, 0, radius * 2, radius * 2);

			return new PIXI.Texture.fromCanvas(canvas);
		},

		updateParticles: function(interpolationFactor) {
			lat    = this.waveSimulation.lattice.data;
			width  = this.waveSimulation.lattice.width;
			height = this.waveSimulation.lattice.height;

			//prevLat = this.previousLattice.data;

			brightness = this.brightness;

			particles = this.particles;

			for (i = 0; i < width; i++) {
				for (j = 0; j < height; j++) {
					//interpolatedValue = prevLat[i][j] * (1 - interpolationFactor) + lat[i][j] * interpolationFactor;
					particles[i][j].alpha = this.alphaFromCellValue(lat[i][j]/*interpolationFactor*/) * brightness;
				}
			}

			//this.previousLattice.copy(this.waveSimulation.lattice);
		},

		alphaFromCellValue: function(value) {
			value = (value + 1.0) / 2.0;
			if (value > 1)
				return 1;
			if (value < 0)
				return 0;
			return value;
		},

		/**
		 * Called on a window resize to resize the canvas
		 */
		windowResized: function(event) {
			this.resizeOnNextUpdate = true;
		},

		resize: function(event) {
			var width  = this.$canvas.width();
			var height = this.$canvas.height();
			if (width != this.renderer.width || height != this.renderer.height) {
				this.width  = width;
				this.height = height;
				this.renderer.resize(width, height);
				this.positionParticles();
				this.trigger('resized');
			}
			this.resizeOnNextUpdate = false;
		},

		update: function(time, delta) {
			if (this.resizeOnNextUpdate)
				this.resize();

			// Update particles to match new lattice
			if (this.particles)
				this.updateParticles();

			this.barrierView.update(time, delta);

			for (i = 0; i < this.segmentPotentialViews.length; i++)
				this.segmentPotentialViews[i].update(time, delta);

			for (i = 0; i < this.oscillatorViews.length; i++)
				this.oscillatorViews[i].update(time, delta);

			// Render everything
			this.renderer.render(this.stage);
		},

		moveCrossSection: function(event) {
			this.waveSimulation.set('crossSectionY', $(event.target).val());

			if (!this.crossSectionMoving) {
				this.crossSectionMoving = true;
				this.trigger('cross-section-slide-start');
			}
		},

		stopCrossSection: function(event) {
			this.crossSectionMoving = false;
			this.trigger('cross-section-slide-stop');
		},

		changeColor: function() {
			this.$canvas.css('background-color', this.color);
		},

		renderSegmentPotentialView: function(segmentPotential) {
			// Create a new view and render it
			var segmentPotentialView = new SegmentPotentialView({
				heatmapView: this,
				segment: segmentPotential
			});
			segmentPotentialView.render();

			// Append the rendered element
			this.$('.potential-views').append(segmentPotentialView.el);

			// Add it to our list for updating
			this.segmentPotentialViews.push(segmentPotentialView);

			// Remove it from the list if it gets removed
			this.listenTo(segmentPotentialView, 'remove', function() {
				this.segmentPotentialViews = _.filter(this.segmentPotentialViews, function(view) {
					return view.segment !== segmentPotential;
				});
			});

			// Make sure it renders the first time because it's set to render only when there are changes.
			segmentPotentialView.updateOnNextFrame = true;
		},

		renderOscillatorView: function(oscillator) {
			// Create a new view and render it
			var oscillatorView = new OscillatorView({
				heatmapView: this,
				oscillator: oscillator
			});
			oscillatorView.render();

			// Append the rendered element
			this.$('.oscillator-views').append(oscillatorView.el);

			// Add it to our list for updating
			this.oscillatorViews.push(oscillatorView);

			// Remove it from the list if it gets removed
			this.listenTo(oscillatorView, 'remove', function() {
				this.oscillatorViews = _.filter(this.oscillatorViews, function(view) {
					return view.oscillator !== oscillator;
				});
			});

			// Make sure it renders the first time because it's set to render only when there are changes.
			oscillatorView.updateOnNextFrame = true;
		},

		changeOscillatorCount: function() {
			var count = this.waveSimulation.get('oscillatorCount');

			for (i = 0; i < this.oscillatorViews.length; i++)
				this.oscillatorViews[i].hide();

			for (i = 0; i < count; i++)
				this.oscillatorViews[i].show();
		},

		isVisiblePoint: function(x, y) {
			return (x < this.waveSimulation.lattice.width - 1 && x >= 0 && y < this.waveSimulation.lattice.height - 1 && y >= 0);
		}

	});

	return HeatmapView;
});
<commit_msg>Fixed a Firefox bug<commit_after>define(function(require) {

	'use strict';

	var $        = require('jquery');
	var _        = require('underscore');
	var Backbone = require('backbone');
	var PIXI     = require('pixi');
	var html     = require('text!templates/heatmap.html');

	var OscillatorView       = require('views/oscillator');
	var BarrierView          = require('views/barrier');
	var SegmentPotentialView = require('views/segment-potential');

	/*
	 * "Local" variables for functions to share and recycle
	 */
	var lat,
		width,
		height,
	    i,
	    j,
	    particles,
	    brightness;

	/**
	 * HeatmapView is the main focus of the app.  It shows the values of the 2D lattice
	 *   on a graph with two axes (default x and y but dependent on the WaveSimulation).
	 *   Includes the containing panel, the (colored) heatmap itself, axis labels and
	 *   measurements, and interactive components including the barriers, cross-section
	 *   slider, and (for now) oscillator controls.
	 *
	 */
	var HeatmapView = Backbone.View.extend({

		template: _.template(html),

		tagName: 'figure',
		className: 'heatmap-container',

		events: {
			'slide .cross-section-slider' : 'moveCrossSection',
			'set   .cross-section-slider' : 'stopCrossSection'
		},

		initialize: function(options) {

			// Default values
			options = _.extend({
				title: 'Top View',
				x: {
					start: 0,
					end: 100,
					step: 10,
					label: 'x (cm)'
				},
				y: {
					start: 0,
					end: 100,
					step: 10,
					label: 'y (cm)'
				},
				brightness: 0.5,
				color: '#0D6A7C'
			}, options);

			// Save options
			if (options.waveSimulation)
				this.waveSimulation = options.waveSimulation;
			else
				throw 'HeatmapView requires a WaveSimulation model to render.';

			// Save graph information for rendering
			this.graphInfo = {
				title: options.title,
				x: options.x,
				y: options.y
			};

			// The alpha modifer for particles
			this.brightness = options.brightness;

			// Background color for canvas
			this.color = options.color;

			// To keep track of history so we can interpolate values
			this.previousLattice = this.waveSimulation.lattice.clone();

			// Lists of views for updating
			this.segmentPotentialViews = [];
			this.oscillatorViews = [];

			// Bind events
			$(window).bind('resize', $.proxy(this.windowResized, this));

			// Cached calculations of lattice-canvas ratios
			this.xSpacing = 1;
			this.ySpacing = 1;

			// Listeners
			this.listenTo(this.waveSimulation, 'segment-potential-added', this.renderSegmentPotentialView);
			this.listenTo(this.waveSimulation, 'change:oscillatorCount', this.changeOscillatorCount);

			this.on('change:color', this.changeColor);
		},

		/**
		 * Renders content and canvas for heatmap
		 */
		render: function() {
			this.$el.empty();

			this.renderContainer();
			this.initRenderer();
			this.initGraphics();
			this.changeColor();

			return this;
		},

		/**
		 * Renders html container
		 */
		renderContainer: function() {
			this.$el.html(this.template(this.graphInfo));

			this.$('.cross-section-slider').noUiSlider({
				start: (this.graphInfo.y.end - this.graphInfo.y.start) / 2,
				direction: 'rtl',
				orientation: 'vertical',
				behaviour: 'none',
				range: {
					min: this.graphInfo.y.start,
					max: this.graphInfo.y.end
				}
			}).find('.noUi-handle')
				.append('
')
				.append('
');
		},

		/**
		 * Initializes a renderer using the .heatmap-canvas canvas element
		 */
		initRenderer: function() {
			this.$canvas = this.$('.heatmap-canvas');

			this.renderer = PIXI.autoDetectRenderer(
				this.$canvas.width(),  // Width
				this.$canvas.height(), // Height
				this.$canvas[0],       // Canvas element
				true,                  // Transparent background
				true                   // Antialiasing
			);

			this.width  = this.$canvas.width();
			this.height = this.$canvas.height();
		},

		initGraphics: function() {
			// Create a stage to hold everything
			this.stage = new PIXI.Stage(0x000000);

			// Create a specialized container for rendering lots of particles
			this.spriteBatch = new PIXI.SpriteBatch();
			this.stage.addChild(this.spriteBatch);

			this.initParticles();
			this.initComponents();
		},

		initComponents: function() {
			this.barrierView = new BarrierView({
				heatmapView: this,
				barrier: this.waveSimulation.barrier
			});
			this.barrierView.render();
			this.$('.potential-views').append(this.barrierView.el);

			for (var i = 0; i < this.waveSimulation.oscillators.length; i++) {
				this.renderOscillatorView(this.waveSimulation.oscillators[i]);
			}
			this.changeOscillatorCount();
		},

		initParticles: function() {
			this.particles = [];

			width  = this.waveSimulation.lattice.width;
			height = this.waveSimulation.lattice.height;

			var texture = this.generateParticleTexture(0);
			var particle;
			var row;

			for (i = 0; i < width; i++) {
				row = [];
				for (j = 0; j < height; j++) {
					// Create a particle representing this cell
					particle = new PIXI.Sprite(texture);
					particle.anchor.x = particle.anchor.y = 0.5;

					row.push(particle);
					this.spriteBatch.addChild(particle);
				}
				this.particles.push(row);
			}

			// Just try it...it actually works on FireFox
			this.positionParticles();
		},

		positionParticles: function() {
			width  = this.waveSimulation.lattice.width;
			height = this.waveSimulation.lattice.height;

			var xSpacing = this.$canvas.width()  / (width - 1);
			var ySpacing = this.$canvas.height() / (height - 1);

			particles = this.particles;

			var texture = this.generateParticleTexture(Math.max(xSpacing, ySpacing) * 2);
			var particle;

			for (i = 0; i < width; i++) {
				for (j = 0; j < height; j++) {
					particle = particles[i][j];
					particle.setTexture(texture);
					particle.position.x = xSpacing * i;
					particle.position.y = ySpacing * (height - j - 1); // Reverse bottom to top with offset
				}
			}

			this.xSpacing = xSpacing;
			this.ySpacing = ySpacing;
		},

		generateParticleTexture: function(radius) {
			// Draw on a canvas and then use it as a texture for our particles
			var canvas = document.createElement('canvas');
			canvas.width  = radius * 2 || 1;
			canvas.height = radius * 2 || 1;

			var ctx = canvas.getContext('2d');

			var gradient = ctx.createRadialGradient(radius, radius, 0, radius, radius, radius);
			gradient.addColorStop(0, 'rgba(255,255,255,1)');
			gradient.addColorStop(1, 'rgba(255,255,255,0)');

			ctx.fillStyle = gradient;
			ctx.fillRect(0, 0, radius * 2, radius * 2);

			return new PIXI.Texture.fromCanvas(canvas);
		},

		updateParticles: function(interpolationFactor) {
			lat    = this.waveSimulation.lattice.data;
			width  = this.waveSimulation.lattice.width;
			height = this.waveSimulation.lattice.height;

			//prevLat = this.previousLattice.data;

			brightness = this.brightness;

			particles = this.particles;

			for (i = 0; i < width; i++) {
				for (j = 0; j < height; j++) {
					//interpolatedValue = prevLat[i][j] * (1 - interpolationFactor) + lat[i][j] * interpolationFactor;
					particles[i][j].alpha = this.alphaFromCellValue(lat[i][j]/*interpolationFactor*/) * brightness;
				}
			}

			//this.previousLattice.copy(this.waveSimulation.lattice);
		},

		alphaFromCellValue: function(value) {
			value = (value + 1.0) / 2.0;
			if (value > 1)
				return 1;
			if (value < 0)
				return 0;
			return value;
		},

		/**
		 * Called on a window resize to resize the canvas
		 */
		windowResized: function(event) {
			this.resizeOnNextUpdate = true;
		},

		resize: function(event) {
			var width  = this.$canvas.width();
			var height = this.$canvas.height();
			this.width  = width;
			this.height = height;
			if (width != this.renderer.width || height != this.renderer.height) {
				this.renderer.resize(width, height);
				this.positionParticles();
				this.trigger('resized');
			}
			this.resizeOnNextUpdate = false;
		},

		update: function(time, delta) {
			if (this.resizeOnNextUpdate)
				this.resize();

			// Update particles to match new lattice
			if (this.particles)
				this.updateParticles();

			this.barrierView.update(time, delta);

			for (i = 0; i < this.segmentPotentialViews.length; i++)
				this.segmentPotentialViews[i].update(time, delta);

			for (i = 0; i < this.oscillatorViews.length; i++)
				this.oscillatorViews[i].update(time, delta);

			// Render everything
			this.renderer.render(this.stage);
		},

		moveCrossSection: function(event) {
			this.waveSimulation.set('crossSectionY', $(event.target).val());

			if (!this.crossSectionMoving) {
				this.crossSectionMoving = true;
				this.trigger('cross-section-slide-start');
			}
		},

		stopCrossSection: function(event) {
			this.crossSectionMoving = false;
			this.trigger('cross-section-slide-stop');
		},

		changeColor: function() {
			this.$canvas.css('background-color', this.color);
		},

		renderSegmentPotentialView: function(segmentPotential) {
			// Create a new view and render it
			var segmentPotentialView = new SegmentPotentialView({
				heatmapView: this,
				segment: segmentPotential
			});
			segmentPotentialView.render();

			// Append the rendered element
			this.$('.potential-views').append(segmentPotentialView.el);

			// Add it to our list for updating
			this.segmentPotentialViews.push(segmentPotentialView);

			// Remove it from the list if it gets removed
			this.listenTo(segmentPotentialView, 'remove', function() {
				this.segmentPotentialViews = _.filter(this.segmentPotentialViews, function(view) {
					return view.segment !== segmentPotential;
				});
			});

			// Make sure it renders the first time because it's set to render only when there are changes.
			segmentPotentialView.updateOnNextFrame = true;
		},

		renderOscillatorView: function(oscillator) {
			// Create a new view and render it
			var oscillatorView = new OscillatorView({
				heatmapView: this,
				oscillator: oscillator
			});
			oscillatorView.render();

			// Append the rendered element
			this.$('.oscillator-views').append(oscillatorView.el);

			// Add it to our list for updating
			this.oscillatorViews.push(oscillatorView);

			// Remove it from the list if it gets removed
			this.listenTo(oscillatorView, 'remove', function() {
				this.oscillatorViews = _.filter(this.oscillatorViews, function(view) {
					return view.oscillator !== oscillator;
				});
			});

			// Make sure it renders the first time because it's set to render only when there are changes.
			oscillatorView.updateOnNextFrame = true;
		},

		changeOscillatorCount: function() {
			var count = this.waveSimulation.get('oscillatorCount');

			for (i = 0; i < this.oscillatorViews.length; i++)
				this.oscillatorViews[i].hide();

			for (i = 0; i < count; i++)
				this.oscillatorViews[i].show();
		},

		isVisiblePoint: function(x, y) {
			return (x < this.waveSimulation.lattice.width - 1 && x >= 0 && y < this.waveSimulation.lattice.height - 1 && y >= 0);
		}

	});

	return HeatmapView;
});
<|endoftext|>


<commit_before>var transactions = []
/*cash: [
  {
    date: '3/7/2014',
    amount: -213.39,
    payee: 'Kroger',
    category: 'Groceries',
    memo: 'this is a memo'
  },
  {
    date: '3/6/2014',
    amount: -8.16,
    payee: 'Starbucks',
    category: 'Dining Out:Coffee'
  }
]
}; */

var payees = {
  Hofer: ["HOFER DANKT", "Alltag: Lebensmittel"],
  Merkur: ["MERKUR DANKT", "Alltag: Lebensmittel"],
  Fressnapf: ["FRESSNAPF", "Tiere: Futter"],
  A1: ["A1 RECHNUNG", "Monatliche Fixkosten: Telefon & Internet"],
  Bankgebühren: ["KARTENGEBUEHR", "Projekte: Steuern & Gebühren"],
  Bauhaus: ["BAUHAUS", "Projekte: Wohnen, Möbel, Garten"],
  "Bob Rechnung": ["BOB RECHNUNG", "Monatliche Fixkosten: Telefon & Internet"],
  DM: [ "DM-FIL.", "Alltag: Medizin & Gesundheit"],
  Bankgebühren: ["Einbehaltene KESt", "Projekte: Steuern & Gebühren"]

}

var qif = require('qif');

var fs = require('fs')
var sys = require('sys')

var csv = require('csv-parser')

/*
Maybe more synchronous with this snippet in the future?

function parseCsvFile(fileName, callback){
  var stream = fs.createReadStream(fileName)
*/

fs.createReadStream('my-secret-sample.csv', {encoding: 'ascii'})
  .pipe(csv({
    raw: false,    // do not decode to utf-8 strings
    headers: ["KtoNr", "memo", "Valuta", "date", "amount", "Balance", "Currency"],
    separator: ';' // specify optional cell separator
    }))
  .on('data', function(data) {
    var payee = "", category = ""
    // replace , with . in amount (US format)
    data["amount"] = data["amount"].replace(".","").replace(",",".")
    var info = data["memo"].split(/(AT|BG|FE|IG|MC|OG|VB|VD)\/(\d\d\d\d\d\d\d\d\d)\s/)
    //remove leading 0 in transaction/checknumber
    info[2] = info[2].replace(/^0*/,'')

    for(key in payees){
     if( (info[0] + info[3]).match(payees[key][0]) )
       {
         //console.log(key, payees[key][1])
         payee = key
         category = payees[key][1]
       }
    }
    if(info[0].match(/Bezahlung Maestro/))
     { info[0] = info[0].replace(/Bezahlung Maestro\s*(\d*\.\d\d\s*|\s*)/,"" ) }
    if(info[0].match(/Gutschrift .berweisung/))
     { info[0] = info[0].replace(/Gutschrift .berweisung\s*/,"" ) }
    if(info[0].match(/Abbuchung Einzugserm.chtigung/))
     { info[0] = info[0].replace(/Abbuchung Einzugserm.chtigung\s*(\d*|\s*).*BKAUATWWXXX AT\d*/,"" ) }
    if(info[0].match(/Auszahlung Maestro/))
     // this one doesnt work:
     { info[0] = info[0].replace(/Auszahlung Maestro(\s|\.|\d)*AUTOMAT/,"Bankomat" ) }
    if(info[0].match(/Abbuchung Einzugserm.chtigung/))
     { info[0] = info[0].replace(/Abbuchung Einzugserm.chtigung\s*/,"" ) }
    if(info[0].match(/Gutschrift EU-Standardzahlung/))
     { info[0] = info[0].replace(/Gutschrift EU-Standardzahlung\s*(\d*|\s*)/,"" ) }
    if(info[0].match(/Abbuchung Onlinebanking/))
     { info[0] = info[0].replace(/Abbuchung Onlinebanking\s*(\d*|\s*)/,"" ) }
    if(info[0].match(/Abbuchung Dauerauftrag/))
     { info[0] = info[0].replace(/Abbuchung Dauerauftrag\s*(\d*|\s*)/,"" ) }

    console.log("memo", info[0] + ' '+ info[3])
    transaction = {"amount": data["amount"],
                   "payee": payee,
                   "memo": info[0] + ' '+ info[3],
                   "checknumber": info[2],
                   "category": category,
                   "date": data["date"] }

    //console.log("Transaction:", transaction)
    transactions.push( transaction )
}).on('end', function() {
  console.log("Read", transactions.length, "Transactions from CSV")
  qif.writeToFile({cash: transactions}, './out.qif', function (err, qifData) {
    if(err)
      {
        console.log("Err: ", err, "qif ", qifData)
      }

  });

});
<commit_msg>csv2qif now uses cmd line options<commit_after>var transactions = []
/*cash: [
  {
    date: '3/7/2014',
    amount: -213.39,
    payee: 'Kroger',
    category: 'Groceries',
    memo: 'this is a memo'
  },
  {
    date: '3/6/2014',
    amount: -8.16,
    payee: 'Starbucks',
    category: 'Dining Out:Coffee'
  }
]
}; */

var payees = {
  Hofer: ["HOFER DANKT", "Alltag: Lebensmittel"],
  Merkur: ["MERKUR DANKT", "Alltag: Lebensmittel"],
  Fressnapf: ["FRESSNAPF", "Tiere: Futter"],
  A1: ["A1 RECHNUNG", "Monatliche Fixkosten: Telefon & Internet"],
  Bankgebühren: ["KARTENGEBUEHR", "Projekte: Steuern & Gebühren"],
  Bauhaus: ["BAUHAUS", "Projekte: Wohnen, Möbel, Garten"],
  "Bob Rechnung": ["BOB RECHNUNG", "Monatliche Fixkosten: Telefon & Internet"],
  DM: [ "DM-FIL.", "Alltag: Medizin & Gesundheit"],
  Bankgebühren: ["Einbehaltene KESt", "Projekte: Steuern & Gebühren"]

}

var qif = require('qif');

var fs = require('fs')
var sys = require('sys')

var csv = require('csv-parser')

var cmdline = require('commander');

cmdline
  .version('0.0.2')
  .option('-i, --input [filename]', 'Input file name including .csv ending. Default input.csv', "input.csv")
  .option('-o, --output [filename]', 'Output file name including .qif ending. Default output.qif', "output.qif")
  .parse(process.argv);

/*
Maybe more synchronous with this snippet in the future?

function parseCsvFile(fileName, callback){
  var stream = fs.createReadStream(fileName)
*/
// console.log("input: ", cmdline.input)
// console.log("output: ", cmdline.output)
// process.exit(0);

fs.createReadStream(cmdline.input, {encoding: 'ascii'})
  .pipe(csv({
    raw: false,    // do not decode to utf-8 strings
    headers: ["KtoNr", "memo", "Valuta", "date", "amount", "Balance", "Currency"],
    separator: ';' // specify optional cell separator
    }))
  .on('data', function(data) {
    var payee = "", category = ""
    // replace , with . in amount (US format)
    data["amount"] = data["amount"].replace(".","").replace(",",".")
    var info = data["memo"].split(/(AT|BG|FE|IG|MC|OG|VB|VD)\/(\d\d\d\d\d\d\d\d\d)\s/)
    //remove leading 0 in transaction/checknumber
    info[2] = info[2].replace(/^0*/,'')

    for(key in payees){
     if( (info[0] + info[3]).match(payees[key][0]) )
       {
         //console.log(key, payees[key][1])
         payee = key
         category = payees[key][1]
       }
    }
    if(info[0].match(/Bezahlung Maestro/))
     { info[0] = info[0].replace(/Bezahlung Maestro\s*(\d*\.\d\d\s*|\s*)/,"" ) }
    if(info[0].match(/Gutschrift .berweisung/))
     { info[0] = info[0].replace(/Gutschrift .berweisung\s*/,"" ) }
    if(info[0].match(/Abbuchung Einzugserm.chtigung/))
     { info[0] = info[0].replace(/Abbuchung Einzugserm.chtigung\s*(\d*|\s*).*BKAUATWWXXX AT\d*/,"" ) }
    if(info[0].match(/Auszahlung Maestro/))
     // this one doesnt work:
     { info[0] = info[0].replace(/Auszahlung Maestro(\s|\.|\d)*AUTOMAT/,"Bankomat" ) }
    if(info[0].match(/Abbuchung Einzugserm.chtigung/))
     { info[0] = info[0].replace(/Abbuchung Einzugserm.chtigung\s*/,"" ) }
    if(info[0].match(/Gutschrift EU-Standardzahlung/))
     { info[0] = info[0].replace(/Gutschrift EU-Standardzahlung\s*(\d*|\s*)/,"" ) }
    if(info[0].match(/Abbuchung Onlinebanking/))
     { info[0] = info[0].replace(/Abbuchung Onlinebanking\s*(\d*|\s*)/,"" ) }
    if(info[0].match(/Abbuchung Dauerauftrag/))
     { info[0] = info[0].replace(/Abbuchung Dauerauftrag\s*(\d*|\s*)/,"" ) }

    console.log("memo", info[0] + ' '+ info[3])
    transaction = {"amount": data["amount"],
                   "payee": payee,
                   "memo": info[0] + ' '+ info[3],
                   "checknumber": info[2],
                   "category": category,
                   "date": data["date"] }

    //console.log("Transaction:", transaction)
    transactions.push( transaction )
}).on('end', function() {
  console.log("Read", transactions.length, "Transactions from CSV")
  qif.writeToFile({cash: transactions}, cmdline.output, function (err, qifData) {
    if(err)
      {
        console.log("Err: ", err, "qif ", qifData)
      }

  });

});
<|endoftext|>


<commit_before>var http = require("http"),
    path = require("path"),
    url = require("url"),
    fs = require("fs"),
    port = process.argv[2] || 8888;
    basePath = process.argv[3] || "./browser";

/*
  Our own quick mime lookup because nexe fails to
  include the npm package mime's list of mime types
*/
var mimeLookup = function(filename) {
  var tokens = filename.split('.');

  if(tokens.length == 0) // default to html
    return "text/html";

  var extension = tokens[tokens.length - 1];

  if(extension == "html")
    return "text/html";
  if(extension == "png")
    return "image/png";
  if(extension == "svg")
    return "image/svg+xml";
  if(extension == "jpg")
    return "image/jpeg";
  if(extension == "css")
    return "text/css";

  return "text/html";
}

http.createServer(function(request, response) {

  var uri = url.parse(request.url).pathname
    , filename = path.join(basePath, uri);

  fs.exists(filename, function(exists) {

    /* Always load the single page app index.html
    unless another file exists or this is a directory */
    if(!exists || fs.statSync(filename).isDirectory()) {
      filename = basePath + "/index.html"
    }

    fs.readFile(filename, "binary", function(err, file) {
      if(err) {
        response.writeHead(500, {"Content-Type": "text/plain"});
        response.write(err + "\n");
        response.end();
        return;
      }

      response.writeHead(200, {"Content-Type": mimeLookup(filename)});
      response.write(file, "binary");
      response.end();
    });
  });
}).listen(parseInt(port, 10));

console.log("Blockstack Browser proxy server running at: http://localhost:" + port);
console.log("Browser path: " + basePath);
console.log("Press Control + C to shutdown");
<commit_msg>add usage instructions<commit_after>/*
 Quick and dirty server for serving single page apps on localhost.

 Usage:
 node blockstackProxy.js <port> <basePath>
*/

var http = require("http"),
    path = require("path"),
    url = require("url"),
    fs = require("fs"),
    port = process.argv[2] || 8888;
    basePath = process.argv[3] || "./browser";

/*
  Our own quick mime lookup because nexe fails to
  include the npm package mime's list of mime types
*/
var mimeLookup = function(filename) {
  var tokens = filename.split('.');

  if(tokens.length == 0) // default to html
    return "text/html";

  var extension = tokens[tokens.length - 1];

  if(extension == "html")
    return "text/html";
  if(extension == "png")
    return "image/png";
  if(extension == "svg")
    return "image/svg+xml";
  if(extension == "jpg")
    return "image/jpeg";
  if(extension == "css")
    return "text/css";

  return "text/html";
}

http.createServer(function(request, response) {

  var uri = url.parse(request.url).pathname
    , filename = path.join(basePath, uri);

  fs.exists(filename, function(exists) {

    /* Always load the single page app index.html
    unless another file exists or this is a directory */
    if(!exists || fs.statSync(filename).isDirectory()) {
      filename = basePath + "/index.html"
    }

    fs.readFile(filename, "binary", function(err, file) {
      if(err) {
        response.writeHead(500, {"Content-Type": "text/plain"});
        response.write(err + "\n");
        response.end();
        return;
      }

      response.writeHead(200, {"Content-Type": mimeLookup(filename)});
      response.write(file, "binary");
      response.end();
    });
  });
}).listen(parseInt(port, 10));

console.log("Blockstack Browser proxy server running at: http://localhost:" + port);
console.log("Browser path: " + basePath);
console.log("Press Control + C to shutdown");
<|endoftext|>


<commit_before>// ver 10.1
var home = {};

home.init = function(){
    if($("header").hasClass('home-header')){
        home.toggleSections();
    }
    if($("section").hasClass('home-content')){
        if(isLoggedIn){
            home.filterSection.activityFeed();
            home.loadSection.activityFeed();
        } else {
            home.filterSection.enjoy();
            home.loadSection.enjoy();
        }
        home.toggleTabs();
    }
};

home.toggleSections = function(){
    $(".home-header ul.sections li").on('click', function(){
        var category = $(this).attr('data-category-id');
        var activeCategory = $(".home-header ul.sections li.active").attr('data-category-id');

        $(".home-header .category-container div[data-category-id='" + activeCategory + "']").fadeOut('500', function(){
            $(".home-header .category-container div[data-category-id='" + category + "']").hide().removeClass('hidden').fadeIn('500');
        });

        $(".home-header ul.sections li").removeClass('active');
        $(this).addClass('active');
    });
};

home.toggleTabs = function(){

    if(isLoggedIn){
        $("section.home-content .content-container:not('[data-type-tab='activityFeed']')").hide();
    }else{
        $("section.home-content .legend:not('.active')").hide();
        $("section.home-content .content-container:not('[data-type-tab='enjoy']')").hide();
    }

    $(".home-header ul.tabs li").on('click', function(){
        var typeTab = $(this).attr('data-type-tab');
        console.log("tab clicked: " + typeTab)
        $(".home-header ul.tabs li").removeClass('active');
        $(this).addClass('active');

        $("section.home-content .legend").hide();
        $("section.home-content .content-container").hide();

        if(typeTab != 'enjoy'){
            if(!window['home']['loadedSection'][typeTab]){
                console.log("about to load section: " + typeTab)
                window['home']['loadSection'][typeTab]();
            }
        }

        $('section.home-content .legend[data-type-tab="' + typeTab + '"]').show();
        $("section.home-content .content-container[data-type-tab='" + typeTab + "']").show();

        var $contentContainer = $("section.home-content .content-container[data-type-tab='" + typeTab + "']");
        var $container = $contentContainer.find('#elements');
        $container.attr('data-feed-source', 'home_ajaxactivityfeed');
        if($contentContainer.hasClass('isIso')) {
            $container.data('fwGalerizer').resize()
        }
    });
};

home.filterSection = {};
home.filterSection.activityFeed = function(){
    $("section.content-container[data-type-tab='activityFeed'] .tags span.label").on('click', function(){
        if($(this).not('.active')){
            $(this).parent().find('.active').removeClass('active');
            $(this).addClass('active');
            $("section.elements").html('');
            home.loadSection.activityFeed({
                'filters': $(this).attr('data-feed-filter')
            });
        }
    });
};

// TAG filters for enjoy (user not logged in)
// In homeController.php ajaxEnjoyAction() takes two parameters:
// @param: filter (can be 0 sort by weight or 1 sort only highlight (media owned by fw) )
// @param: tag (show videos associated with a tagid)
home.filterSection.enjoy = function(){
    var $contentContainer = $('section.home-content .content-container[data-type-tab="enjoy"]');
    var $container = $contentContainer.find('#elements');
    // Remove all listeners
    $("section.content-container[data-type-tab='enjoy'] .tags span.label").off();
    // Bind listeners
    var $filters = $("section.content-container[data-type-tab='enjoy'] .tags span.label").on('click', function(){
        if($(this).not('.active')){
            $(this).parent().find('.active').removeClass('active');
            $(this).addClass('active');
            $contentContainer.removeClass('isIso');
            $container.data('fwGalerizer').destroy();
            var tagId = parseInt($(this).attr('data-tag-id'));
            // Filter by weight or highlight
            if(isNaN(tagId)) {
                $('section.home-content .content-container[data-type-tab="enjoy"] .tags .pull-left').find('[data-tag-id]').remove();
                home.loadSection.enjoy({
                    'filters': $(this).attr('data-feed-filter')
                });
            } else {
                home.loadSection.enjoy({
                    'tag': tagId
                });
            }
        }
    });
};

home.loadSection = {};

home.loadedSection = {
    'enjoy': true,
    'follow': false,
    'connect': false,
    'participate': false,

    'activityFeed': false,
    'popularFeed': false
};

home.loadSection.enjoy = function(params){

    if(typeof(params) == 'undefined'){
        params = {};
    }
    var $toAppendTrending = $('section.home-content .content-container[data-type-tab="enjoy"] .tags .pull-left');
    var $contentContainer = $('section.home-content .content-container[data-type-tab="enjoy"]');
    var $container = $contentContainer.find('#elements');

    $container.attr('data-feed-source', 'home_ajaxenjoy');
    if(!$contentContainer.hasClass('isIso')) {
        $container.fwGalerizer({
            endless: false,
            normalize: false,
            feedfilter: params || {},
            onDataReady: function(jsonData) {
                var i, outp = [];
                var normalize = function(video) {
                    var href = Routing.generate(appLocale + '_video_show', {
                        'id': video.id,
                        'slug': video.slug
                    });
                    var authorUrl = Routing.generate(appLocale + '_user_land', {
                        'username': video.author.username
                    });
                    var hrefModal = Routing.generate(appLocale + '_modal_media', {
                        'id': video.id,
                        'type': 'video'
                    });
                    return {
                            'type': 'video',
                            'date': video.createdAt,
                            'href': href,
                            'hrefModal': hrefModal,
                            'image': video.image,
                            'slug': video.slug,
                            'title': video.title,
                            'author': video.author.username,
                            'authorHref': video.author.url,
                            'authorImage': video.author.image
                    };
                };
                for(i in jsonData.trending){
                    var tag = jsonData.trending[i];

                    var elementToAppend = $('');

                    elementToAppend.html(tag.title)
                    .attr('data-tag-id', tag.id)
                    .attr('data-tag-slug', tag.slug);

                    var ids = [];
                    $('section.home-content .content-container[data-type-tab="enjoy"] .tags .pull-left')
                    .find('[data-tag-id]')
                    .each(function(el) {
                        //console.log($(this).attr('data-tag-id'))
                        ids.push($(this).attr('data-tag-id'));
                    });
                    // Prevent duplicates
                    if($.inArray(tag.id,ids) < 0) {
                        //$toAppendTrending.append(elementToAppend);
                        $(elementToAppend).hide().appendTo($toAppendTrending).fadeIn('slow');
                    }

                    // Bind listeners
                    home.filterSection.enjoy();
                }
                for(i in jsonData.videos) {
                    if (jsonData.videos.hasOwnProperty(i)) {
                        outp.push(normalize(jsonData.videos[i]));
                    }
                }
                return outp;
            },
            onGallery: function() {
                $contentContainer.removeClass('loading');
            }
        });
        home.loadedSection.enjoy = true;
        $contentContainer.addClass('isIso');
    };
    return;
}

home.loadSection.connect = function(){
    var toAppendElements = $('section.home-content .content-container[data-type-tab="connect"] .fans-list');

    toAppendElements.parent().addClass('loading');
    ajax.genericAction('home_ajaxconnect', {}, function(r){
        for(var i in r.fans){
            var fan = r.fans[i];

            var loop = parseInt(i);
            loop++;
            if(r.fans.length == loop)  {
                var callback = function(){
                    toAppendElements.removeClass('loading');
                    home.loadedSection.connect = true;
                };
            }else{
                var callback = function(){};
            }
            templateHelper.renderTemplate('fans-element', fan, toAppendElements.selector, false, callback);
            toAppendElements.parent().removeClass('loading');
        }
    }, function(e){
        error(e);
    });
};

home.loadSection.participate = function(){
    var toAppendElements = $('section.home-content .content-container[data-type-tab="participate"] .events-grid');

    toAppendElements.parent().addClass('loading');

    ajax.genericAction('home_ajaxparticipate', {}, function(r){
        for(var i in r.events){
            var event = r.events[i];
            var callback = function(){};

            templateHelper.renderTemplate('event-grid_element', event, toAppendElements.selector, false, callback);
        }
        toAppendElements.parent().removeClass('loading');
        home.loadedSection.participate = true;
    }, function(e){
        error(e)
    });
};

home.loadSection.activityFeed = function(params){

    if(typeof(params) == 'undefined'){
        params = {};
    }
    var $contentContainer = $('section.home-content .content-container[data-type-tab="activityFeed"]');
    var $container = $contentContainer.find('#elements');
    $container.attr('data-feed-source', 'home_ajaxpopularfeed');
    if(!$contentContainer.hasClass('isIso')) {
        $contentContainer.addClass('loading');
        $container.fwGalerizer({
            onEndless: function(plugin) {
                $contentContainer.addClass('loading');
                var lastDate = $('section.home-content .content-container[data-type-tab="activityFeed"] #elements .post').last().attr('data-element-date');
                plugin.options.feedfilter = {
                    'date': lastDate
                };
                console.log("new filter")
                console.log(plugin.options.feedfilter)
                return plugin.options.feedfilter;
            },
            onGallery: function() {
                $contentContainer.removeClass('loading');
            }
        })
        home.loadedSection.activityFeed = true;
        $contentContainer.addClass('isIso');
    };
    return;
}

home.loadSection.popularFeed = function(params){

    if(typeof(params) == 'undefined'){
        params = {};
    }
    var $contentContainer = $('section.home-content .content-container[data-type-tab="popularFeed"]');
    var $container = $contentContainer.find('#elements');
    $container.attr('data-feed-source', 'home_ajaxpopularfeed');
    if(!$contentContainer.hasClass('isIso')) {
        $contentContainer.addClass('loading');
        $container.fwGalerizer({
            onEndless: function(plugin) {
                $contentContainer.addClass('loading');
                var lastDate = $('section.home-content .content-container[data-type-tab="popularFeed"] #elements .post').last().attr('data-element-date');
                plugin.options.feedfilter = {
                    'date': lastDate
                };
                console.log("new filter")
                console.log(plugin.options.feedfilter)
                return plugin.options.feedfilter;
            },
            onGallery: function() {
                $contentContainer.removeClass('loading');
            }
        });
        home.loadedSection.popularFeed = true;
        $contentContainer.addClass('isIso');
    };
    return;
}

;$(document).ready(function(){
    home.init();
});<commit_msg>fix problemas de filtros en tab de actividades<commit_after>// ver 10.1
var home = {};

home.init = function(){
    if($("header").hasClass('home-header')){
        home.toggleSections();
    }
    if($("section").hasClass('home-content')){
        if(isLoggedIn){
            home.filterSection.activityFeed();
            home.loadSection.activityFeed();
        } else {
            home.filterSection.enjoy();
            home.loadSection.enjoy();
        }
        home.toggleTabs();
    }
};

home.toggleSections = function(){
    $(".home-header ul.sections li").on('click', function(){
        var category = $(this).attr('data-category-id');
        var activeCategory = $(".home-header ul.sections li.active").attr('data-category-id');

        $(".home-header .category-container div[data-category-id='" + activeCategory + "']").fadeOut('500', function(){
            $(".home-header .category-container div[data-category-id='" + category + "']").hide().removeClass('hidden').fadeIn('500');
        });

        $(".home-header ul.sections li").removeClass('active');
        $(this).addClass('active');
    });
};

home.toggleTabs = function(){

    if(isLoggedIn){
        $("section.home-content .content-container:not('[data-type-tab='activityFeed']')").hide();
    }else{
        $("section.home-content .legend:not('.active')").hide();
        $("section.home-content .content-container:not('[data-type-tab='enjoy']')").hide();
    }

    $(".home-header ul.tabs li").on('click', function(){
        var typeTab = $(this).attr('data-type-tab');
        console.log("tab clicked: " + typeTab)
        $(".home-header ul.tabs li").removeClass('active');
        $(this).addClass('active');

        $("section.home-content .legend").hide();
        $("section.home-content .content-container").hide();

        if(typeTab != 'enjoy'){
            if(!window['home']['loadedSection'][typeTab]){
                console.log("about to load section: " + typeTab)
                window['home']['loadSection'][typeTab]();
            }
        }

        $('section.home-content .legend[data-type-tab="' + typeTab + '"]').show();
        $("section.home-content .content-container[data-type-tab='" + typeTab + "']").show();

        var $contentContainer = $("section.home-content .content-container[data-type-tab='" + typeTab + "']");
        var $container = $contentContainer.find('#elements');
        $container.attr('data-feed-source', 'home_ajaxactivityfeed');
        if($contentContainer.hasClass('isIso')) {
            $container.data('fwGalerizer').resize()
        }
    });
};

home.filterSection = {};
home.filterSection.activityFeed = function(){

    var $contentContainer = $('section.home-content .content-container[data-type-tab="activityFeed"]');
    var $container = $contentContainer.find('#elements');

    $("section.content-container[data-type-tab='activityFeed'] .tags span.label").on('click', function(){
        if($(this).not('.active')){
            $(this).parent().find('.active').removeClass('active');
            $(this).addClass('active');

            $contentContainer.removeClass('isIso');
            $container.data('fwGalerizer').destroy();
            //var filterId = parseInt($(this).attr('data-feed-filter'));
            home.loadSection.activityFeed({
                'filters': $(this).attr('data-feed-filter')
            });
        }
    });
};

// TAG filters for enjoy (user not logged in)
// In homeController.php ajaxEnjoyAction() takes two parameters:
// @param: filter (can be 0 sort by weight or 1 sort only highlight (media owned by fw) )
// @param: tag (show videos associated with a tagid)
home.filterSection.enjoy = function(){
    var $contentContainer = $('section.home-content .content-container[data-type-tab="enjoy"]');
    var $container = $contentContainer.find('#elements');
    // Remove all listeners
    $("section.content-container[data-type-tab='enjoy'] .tags span.label").off();
    // Bind listeners
    var $filters = $("section.content-container[data-type-tab='enjoy'] .tags span.label").on('click', function(){
        if($(this).not('.active')){
            $(this).parent().find('.active').removeClass('active');
            $(this).addClass('active');
            $contentContainer.removeClass('isIso');
            $container.data('fwGalerizer').destroy();
            var tagId = parseInt($(this).attr('data-tag-id'));
            // Filter by weight or highlight
            if(isNaN(tagId)) {
                $('section.home-content .content-container[data-type-tab="enjoy"] .tags .pull-left').find('[data-tag-id]').remove();
                home.loadSection.enjoy({
                    'filters': $(this).attr('data-feed-filter')
                });
            } else {
                home.loadSection.enjoy({
                    'tag': tagId
                });
            }
        }
    });
};

home.loadSection = {};

home.loadedSection = {
    'enjoy': true,
    'follow': false,
    'connect': false,
    'participate': false,

    'activityFeed': false,
    'popularFeed': false
};

home.loadSection.enjoy = function(params){

    if(typeof(params) == 'undefined'){
        params = {};
    }
    var $toAppendTrending = $('section.home-content .content-container[data-type-tab="enjoy"] .tags .pull-left');
    var $contentContainer = $('section.home-content .content-container[data-type-tab="enjoy"]');
    var $container = $contentContainer.find('#elements');

    $container.attr('data-feed-source', 'home_ajaxenjoy');
    if(!$contentContainer.hasClass('isIso')) {
        $container.fwGalerizer({
            endless: false,
            normalize: false,
            feedfilter: params,
            onDataReady: function(jsonData) {
                var i, outp = [];
                var normalize = function(video) {
                    var href = Routing.generate(appLocale + '_video_show', {
                        'id': video.id,
                        'slug': video.slug
                    });
                    var authorUrl = Routing.generate(appLocale + '_user_land', {
                        'username': video.author.username
                    });
                    var hrefModal = Routing.generate(appLocale + '_modal_media', {
                        'id': video.id,
                        'type': 'video'
                    });
                    return {
                            'type': 'video',
                            'date': video.createdAt,
                            'href': href,
                            'hrefModal': hrefModal,
                            'image': video.image,
                            'slug': video.slug,
                            'title': video.title,
                            'author': video.author.username,
                            'authorHref': video.author.url,
                            'authorImage': video.author.image
                    };
                };
                for(i in jsonData.trending){
                    var tag = jsonData.trending[i];

                    var elementToAppend = $('');

                    elementToAppend.html(tag.title)
                    .attr('data-tag-id', tag.id)
                    .attr('data-tag-slug', tag.slug);

                    var ids = [];
                    $('section.home-content .content-container[data-type-tab="enjoy"] .tags .pull-left')
                    .find('[data-tag-id]')
                    .each(function(el) {
                        //console.log($(this).attr('data-tag-id'))
                        ids.push($(this).attr('data-tag-id'));
                    });
                    // Prevent duplicates
                    if($.inArray(tag.id,ids) < 0) {
                        //$toAppendTrending.append(elementToAppend);
                        $(elementToAppend).hide().appendTo($toAppendTrending).fadeIn('slow');
                    }

                    // Bind listeners
                    home.filterSection.enjoy();
                }
                for(i in jsonData.videos) {
                    if (jsonData.videos.hasOwnProperty(i)) {
                        outp.push(normalize(jsonData.videos[i]));
                    }
                }
                return outp;
            },
            onGallery: function() {
                $contentContainer.removeClass('loading');
            }
        });
        home.loadedSection.enjoy = true;
        $contentContainer.addClass('isIso');
    };
    return;
}

home.loadSection.connect = function(){
    var toAppendElements = $('section.home-content .content-container[data-type-tab="connect"] .fans-list');

    toAppendElements.parent().addClass('loading');
    ajax.genericAction('home_ajaxconnect', {}, function(r){
        for(var i in r.fans){
            var fan = r.fans[i];

            var loop = parseInt(i);
            loop++;
            if(r.fans.length == loop)  {
                var callback = function(){
                    toAppendElements.removeClass('loading');
                    home.loadedSection.connect = true;
                };
            }else{
                var callback = function(){};
            }
            templateHelper.renderTemplate('fans-element', fan, toAppendElements.selector, false, callback);
            toAppendElements.parent().removeClass('loading');
        }
    }, function(e){
        error(e);
    });
};

home.loadSection.participate = function(){
    var toAppendElements = $('section.home-content .content-container[data-type-tab="participate"] .events-grid');

    toAppendElements.parent().addClass('loading');

    ajax.genericAction('home_ajaxparticipate', {}, function(r){
        for(var i in r.events){
            var event = r.events[i];
            var callback = function(){};

            templateHelper.renderTemplate('event-grid_element', event, toAppendElements.selector, false, callback);
        }
        toAppendElements.parent().removeClass('loading');
        home.loadedSection.participate = true;
    }, function(e){
        error(e)
    });
};

home.loadSection.activityFeed = function(params){

    if(typeof(params) == 'undefined'){
        params = {};
    }
    console.log("params")
    console.log(params)
    var $contentContainer = $('section.home-content .content-container[data-type-tab="activityFeed"]');
    var $container = $contentContainer.find('#elements');
    $container.attr('data-feed-source', 'home_ajaxactivityfeed');
    if(!$contentContainer.hasClass('isIso')) {
        $contentContainer.addClass('loading');
        $container.fwGalerizer({
            feedfilter: params,
            onEndless: function(plugin) {
                $contentContainer.addClass('loading');
                var lastDate = $('section.home-content .content-container[data-type-tab="activityFeed"] #elements .post').last().attr('data-element-date');
                plugin.options.feedfilter = {
                    'date': lastDate
                };
                console.log("new filter")
                console.log(plugin.options.feedfilter)
                return plugin.options.feedfilter;
            },
            onGallery: function() {
                $contentContainer.removeClass('loading');
            }
        })
        home.loadedSection.activityFeed = true;
        $contentContainer.addClass('isIso');
    };
    return;
}

home.loadSection.popularFeed = function(params){

    if(typeof(params) == 'undefined'){
        params = {};
    }
    var $contentContainer = $('section.home-content .content-container[data-type-tab="popularFeed"]');
    var $container = $contentContainer.find('#elements');
    $container.attr('data-feed-source', 'home_ajaxpopularfeed');
    if(!$contentContainer.hasClass('isIso')) {
        $contentContainer.addClass('loading');
        $container.fwGalerizer({
            onEndless: function(plugin) {
                $contentContainer.addClass('loading');
                var lastDate = $('section.home-content .content-container[data-type-tab="popularFeed"] #elements .post').last().attr('data-element-date');
                plugin.options.feedfilter = {
                    'date': lastDate
                };
                console.log("new filter")
                console.log(plugin.options.feedfilter)
                return plugin.options.feedfilter;
            },
            onGallery: function() {
                $contentContainer.removeClass('loading');
            }
        });
        home.loadedSection.popularFeed = true;
        $contentContainer.addClass('isIso');
    };
    return;
}

;$(document).ready(function(){
    home.init();
});<|endoftext|>