<commit_before>/*
Copyright (c) 2015 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
*/

(function(document) {
  'use strict';

  // Grab a reference to our auto-binding template
  // and give it some initial binding values
  // Learn more about auto-binding templates at http://goo.gl/Dx1u2g
  var app = document.querySelector('#app');

  app.displayInstalledToast = function() {
    // Check to make sure caching is actually enabled—it won't be in the dev environment.
    if (!document.querySelector('platinum-sw-cache').disabled) {
      document.querySelector('#caching-complete').show();
    }
  };

  // Listen for template bound event to know when bindings
  // have resolved and content has been stamped to the page
  app.addEventListener('dom-change', function() {
    console.log('Our app is ready to rock!');
  });

  // Startup the Notification Push Listener after login
  window.addEventListener('onAfterLogin', function(){
    console.log('onAfterLogin callback: configuring notifications');
    setupNotificationListener();
  });

  function setupNotificationListener(){
    bridgeit.xio.push.attach('http://dev.bridgeit.io/pushio/demos/realms/starbucks', bridgeit.io.auth.getLastKnownUsername());
    bridgeit.xio.push.addListener(function (payload) {
        console.log('Notification: ', payload);

        //normalize payload TODO!!
        if( payload.message && typeof payload.message === 'object' && payload.message.message){
          payload.message = payload.message.message;
        }

        //ignore first batch of notifications for admin as they are irrelevant
        var usernameFromGroup = payload.group.split('/').pop();
        if( payload.message === 'joined' && payload.username !== usernameFromGroup ){
          console.log('suppressing notification display');
          return;
        }

        var messageToDisplay;
        if( payload.message === 'joined' ){
          messageToDisplay = payload.username + ' joined group ' + payload.group;
        }
        else{
          messageToDisplay = payload.message;
        }

        var demoView = app.$.demoView;
        demoView.$$('demo-data').push('notifications', payload);

        demoView.message = messageToDisplay;
        demoView.querySelector('#toast').show();

        var demoData = demoView.$$('#demoData');
        if( demoData ){
          if( !demoData.notificationsByUser ){
            demoData.notificationsByUser = {};
          }
          var userNotificationList = demoData.notificationsByUser[payload.username];
          if( !userNotificationList ){
            userNotificationList = demoData.notificationsByUser[payload.username] = [];
          }
          userNotificationList.push(payload);
          demoData.lastNotificationTimestamp = payload.time;
        }
        else{
          console.warn('could not locate demoData element to store user notification');
        }
    });
    window.initializePushGroups(); //delegates to index.html for admins or client.html for regular users
  }

  if( bridgeit.io.auth.isLoggedIn()){
    setTimeout(setupNotificationListener, 3000);
  }

  // See https://github.com/Polymer/polymer/issues/1381
  window.addEventListener('WebComponentsReady', function() {
    // imports are loaded and elements have been registered
  });

  window.addEventListener('bridgeit-access-token-refreshed', function(e){
    console.log('demo app received event bridgeit-access-token-refreshed', e);
    bridgeit.xio.push.refreshConnection();
  });

  window.addEventListener('bridgeit-session-expired', function(e){
    console.log('demo app received event bridgeit-session-expired', e);
    bridgeit.xio.push.disconnect();
  });

  // Main area's paper-scroll-header-panel custom condensing transformation of
  // the appName in the middle-container and the bottom title in the bottom-container.
  // The appName is moved to top and shrunk on condensing. The bottom sub title
  // is shrunk to nothing on condensing.
  addEventListener('paper-header-transform', function(e) {
    var appName = document.querySelector('#mainToolbar .app-name');
    var middleContainer = document.querySelector('#mainToolbar .middle-container');
    var bottomContainer = document.querySelector('#mainToolbar .bottom-container');
    var detail = e.detail;
    var heightDiff = detail.height - detail.condensedHeight;
    var yRatio = Math.min(1, detail.y / heightDiff);
    var maxMiddleScale = 0.50;  // appName max size when condensed. The smaller the number the smaller the condensed size.
    var scaleMiddle = Math.max(maxMiddleScale, (heightDiff - detail.y) / (heightDiff / (1-maxMiddleScale))  + maxMiddleScale);
    var scaleBottom = 1 - yRatio;

    // Move/translate middleContainer
    Polymer.Base.transform('translate3d(0,' + yRatio * 100 + '%,0)', middleContainer);

    // Scale bottomContainer and bottom sub title to nothing and back
    Polymer.Base.transform('scale(' + scaleBottom + ') translateZ(0)', bottomContainer);

    // Scale middleContainer appName
    Polymer.Base.transform('scale(' + scaleMiddle + ') translateZ(0)', appName);
  });

  // Close drawer after menu item is selected if drawerPanel is narrow
  app.onDataRouteClick = function() {
    var drawerPanel = document.querySelector('#paperDrawerPanel');
    if (drawerPanel.narrow) {
      drawerPanel.closeDrawer();
    }
  };

  // Scroll page to top and expand header
  app.scrollPageToTop = function() {
    document.getElementById('mainContainer').scrollTop = 0;
  };

})(document);
<commit_msg>display username from group rather than actual notification.username who is the recipient<commit_after>/*
Copyright (c) 2015 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
*/

(function(document) {
  'use strict';

  // Grab a reference to our auto-binding template
  // and give it some initial binding values
  // Learn more about auto-binding templates at http://goo.gl/Dx1u2g
  var app = document.querySelector('#app');

  app.displayInstalledToast = function() {
    // Check to make sure caching is actually enabled—it won't be in the dev environment.
    if (!document.querySelector('platinum-sw-cache').disabled) {
      document.querySelector('#caching-complete').show();
    }
  };

  // Listen for template bound event to know when bindings
  // have resolved and content has been stamped to the page
  app.addEventListener('dom-change', function() {
    console.log('Our app is ready to rock!');
  });

  // Startup the Notification Push Listener after login
  window.addEventListener('onAfterLogin', function(){
    console.log('onAfterLogin callback: configuring notifications');
    setupNotificationListener();
  });

  function setupNotificationListener(){
    bridgeit.xio.push.attach('http://dev.bridgeit.io/pushio/demos/realms/starbucks', bridgeit.io.auth.getLastKnownUsername());
    bridgeit.xio.push.addListener(function (payload) {
        console.log('Notification: ', payload);

        //normalize payload TODO!!
        if( payload.message && typeof payload.message === 'object' && payload.message.message){
          payload.message = payload.message.message;
        }

        //ignore first batch of notifications for admin as they are irrelevant
        payload.usernameFromGroup = payload.group.split('/').pop();
        if( payload.message === 'joined' && payload.username !== payload.usernameFromGroup ){
          console.log('suppressing notification display');
          return;
        }

        var messageToDisplay;
        if( payload.message === 'joined' ){
          messageToDisplay = payload.usernameFromGroup + ' joined';
        }
        else{
          messageToDisplay = payload.message;
        }

        var demoView = app.$.demoView;
        demoView.$$('demo-data').push('notifications', payload);

        demoView.message = messageToDisplay;
        demoView.querySelector('#toast').show();

        var demoData = demoView.$$('#demoData');
        if( demoData ){
          if( !demoData.notificationsByUser ){
            demoData.notificationsByUser = {};
          }
          var userNotificationList = demoData.notificationsByUser[payload.usernameFromGroup];
          if( !userNotificationList ){
            userNotificationList = demoData.notificationsByUser[payload.usernameFromGroup] = [];
          }
          userNotificationList.push(payload);
          demoData.lastNotificationTimestamp = payload.time;
        }
        else{
          console.warn('could not locate demoData element to store user notification');
        }
    });
    window.initializePushGroups(); //delegates to index.html for admins or client.html for regular users
  }

  if( bridgeit.io.auth.isLoggedIn()){
    setTimeout(function(){
      setupNotificationListener();
      //initialize lastNotificationTimestamp so user list displays
      var demoData = app.$.demoView.$$('#demoData');
      if( demoData ){
         demoData.lastNotificationTimestamp = new Date().getTime();
      }
    }, 3000);
  }

  // See https://github.com/Polymer/polymer/issues/1381
  window.addEventListener('WebComponentsReady', function() {
    // imports are loaded and elements have been registered
  });

  window.addEventListener('bridgeit-access-token-refreshed', function(e){
    console.log('demo app received event bridgeit-access-token-refreshed', e);
    bridgeit.xio.push.refreshConnection();
  });

  window.addEventListener('bridgeit-session-expired', function(e){
    console.log('demo app received event bridgeit-session-expired', e);
    bridgeit.xio.push.disconnect();
  });

  // Main area's paper-scroll-header-panel custom condensing transformation of
  // the appName in the middle-container and the bottom title in the bottom-container.
  // The appName is moved to top and shrunk on condensing. The bottom sub title
  // is shrunk to nothing on condensing.
  addEventListener('paper-header-transform', function(e) {
    var appName = document.querySelector('#mainToolbar .app-name');
    var middleContainer = document.querySelector('#mainToolbar .middle-container');
    var bottomContainer = document.querySelector('#mainToolbar .bottom-container');
    var detail = e.detail;
    var heightDiff = detail.height - detail.condensedHeight;
    var yRatio = Math.min(1, detail.y / heightDiff);
    var maxMiddleScale = 0.50;  // appName max size when condensed. The smaller the number the smaller the condensed size.
    var scaleMiddle = Math.max(maxMiddleScale, (heightDiff - detail.y) / (heightDiff / (1-maxMiddleScale))  + maxMiddleScale);
    var scaleBottom = 1 - yRatio;

    // Move/translate middleContainer
    Polymer.Base.transform('translate3d(0,' + yRatio * 100 + '%,0)', middleContainer);

    // Scale bottomContainer and bottom sub title to nothing and back
    Polymer.Base.transform('scale(' + scaleBottom + ') translateZ(0)', bottomContainer);

    // Scale middleContainer appName
    Polymer.Base.transform('scale(' + scaleMiddle + ') translateZ(0)', appName);
  });

  // Close drawer after menu item is selected if drawerPanel is narrow
  app.onDataRouteClick = function() {
    var drawerPanel = document.querySelector('#paperDrawerPanel');
    if (drawerPanel.narrow) {
      drawerPanel.closeDrawer();
    }
  };

  // Scroll page to top and expand header
  app.scrollPageToTop = function() {
    document.getElementById('mainContainer').scrollTop = 0;
  };

})(document);
<|endoftext|>


<commit_before>'use strict';

var Backbone = require('backbone');
var Marionette = require('backbone.marionette');
var NUSMods = require('./nusmods');
var NavigationCollection = require('./common/collections/NavigationCollection');
var NavigationView = require('./common/views/NavigationView');
var Promise = require('bluebird'); // jshint ignore:line
var SelectedModulesController = require('./common/controllers/SelectedModulesController');
var TimetableModuleCollection = require('./common/collections/TimetableModuleCollection');
var _ = require('underscore');
var config = require('./common/config');
var localforage = require('localforage');
require('qTip2');

// Set Backbone.History.initialRoute to allow route handlers to find out if they
// were called from the initial route.
var loadUrl = Backbone.History.prototype.loadUrl;
Backbone.History.prototype.loadUrl = function() {
  if (!Backbone.History.initialRoute) {
    Backbone.History.initialRoute = true;
  } else {
    Backbone.History.initialRoute = false;
    // No longer initial route, restore original loadUrl.
    Backbone.History.prototype.loadUrl = loadUrl;
  }
  return loadUrl.apply(this, arguments);
};

var App = new Marionette.Application();

App.addRegions({
  mainRegion: '.content',
  navigationRegion: '#nav',
  selectRegion: '.navbar-form',
  bookmarksRegion: '.nm-bookmarks'
});

var navigationCollection = new NavigationCollection();
var navigationView = new NavigationView({collection: navigationCollection});
App.navigationRegion.show(navigationView);

App.reqres.setHandler('addNavigationItem', function (navigationItem) {
  return navigationCollection.add(navigationItem);
});

NUSMods.setConfig(config);

var selectedModulesControllers = [];

for (var i = 0; i < 5; i++) {
  selectedModulesControllers[i] = new SelectedModulesController({
    semester: i + 1
  });
}

App.reqres.setHandler('selectedModules', function (sem) {
  return selectedModulesControllers[sem - 1].selectedModules;
});
App.reqres.setHandler('addModule', function (sem, id, options) {
  return selectedModulesControllers[sem - 1].selectedModules.add({
    ModuleCode: id,
    Semester: sem
  }, options);
});
App.reqres.setHandler('removeModule', function (sem, id) {
  var selectedModules = selectedModulesControllers[sem - 1].selectedModules;
  return selectedModules.remove(selectedModules.get(id));
});
App.reqres.setHandler('isModuleSelected', function (sem, id) {
  return !!selectedModulesControllers[sem - 1].selectedModules.get(id);
});
App.reqres.setHandler('displayLessons', function (sem, id, display) {
  _.each(selectedModulesControllers[sem - 1].timetable.where({
    ModuleCode: id
  }), function (lesson) {
    lesson.set('display', display);
  });
});

var bookmarkedModulesNamespace = config.namespaces.bookmarkedModules + ':';

App.reqres.setHandler('getBookmarks', function (callback) {
  if (!callback) {
    return;
  }
  localforage.getItem(bookmarkedModulesNamespace, function (modules) {
    callback(modules);
  });
});
App.reqres.setHandler('addBookmark', function (id) {
  localforage.getItem(bookmarkedModulesNamespace, function (modules) {
    if (!_.contains(modules, id)) {
      modules.push(id);
    }
    localforage.setItem(bookmarkedModulesNamespace, modules);
  });
});
App.reqres.setHandler('deleteBookmark', function (id) {
  localforage.getItem(bookmarkedModulesNamespace, function (modules) {
    var index = modules.indexOf(id);
    if (index > -1) {
      modules.splice(index, 1);
      localforage.setItem(bookmarkedModulesNamespace, modules);
    }
  });
});

App.on('start', function () {
  var AppView = require('./common/views/AppView');

  new Marionette.AppRouter({
    routes: {
      '*default': function () {
        Backbone.history.navigate('timetable', {trigger: true, replace: true});
      }
    }
  });

  // header modules
  require('./timetable');
  require('./modules');
  // require('ivle');
  require('./barenus');
  require('./friends');
  require('./venues');
  require('./preferences');
  require('./blog');

  // footer modules
  require('./about');
  require('./contribute');
  require('./help');
  require('./support');

  Promise.all(_.map(_.range(1, 5), function(semester) {
    var semTimetableFragment = config.semTimetableFragment(semester);
    return localforage.getItem(semTimetableFragment + ':queryString')
      .then(function (savedQueryString) {
      if ('/' + semTimetableFragment === window.location.pathname) {
        var queryString = window.location.search.slice(1);
        if (queryString) {
          if (savedQueryString !== queryString) {
            // If initial query string does not match saved query string,
            // timetable is shared.
            App.request('selectedModules', semester).shared = true;
          }
          // If there is a query string for timetable, return so that it will
          // be used instead of saved query string.
          return;
        }
      }
      var selectedModules = TimetableModuleCollection.fromQueryStringToJSON(savedQueryString);
      return Promise.all(_.map(selectedModules, function (module) {
        return App.request('addModule', semester, module.ModuleCode, module);
      }));
    });
  }).concat([NUSMods.generateModuleCodes()])).then(function () {
    new AppView();

    Backbone.history.start({pushState: true});
  });

  localforage.getItem(bookmarkedModulesNamespace, function (modules) {
    if (!modules) {
      localforage.setItem(bookmarkedModulesNamespace, []);
    }
  });
});

module.exports = App;
<commit_msg>Rearrange nusessities order<commit_after>'use strict';

var Backbone = require('backbone');
var Marionette = require('backbone.marionette');
var NUSMods = require('./nusmods');
var NavigationCollection = require('./common/collections/NavigationCollection');
var NavigationView = require('./common/views/NavigationView');
var Promise = require('bluebird'); // jshint ignore:line
var SelectedModulesController = require('./common/controllers/SelectedModulesController');
var TimetableModuleCollection = require('./common/collections/TimetableModuleCollection');
var _ = require('underscore');
var config = require('./common/config');
var localforage = require('localforage');
require('qTip2');

// Set Backbone.History.initialRoute to allow route handlers to find out if they
// were called from the initial route.
var loadUrl = Backbone.History.prototype.loadUrl;
Backbone.History.prototype.loadUrl = function() {
  if (!Backbone.History.initialRoute) {
    Backbone.History.initialRoute = true;
  } else {
    Backbone.History.initialRoute = false;
    // No longer initial route, restore original loadUrl.
    Backbone.History.prototype.loadUrl = loadUrl;
  }
  return loadUrl.apply(this, arguments);
};

var App = new Marionette.Application();

App.addRegions({
  mainRegion: '.content',
  navigationRegion: '#nav',
  selectRegion: '.navbar-form',
  bookmarksRegion: '.nm-bookmarks'
});

var navigationCollection = new NavigationCollection();
var navigationView = new NavigationView({collection: navigationCollection});
App.navigationRegion.show(navigationView);

App.reqres.setHandler('addNavigationItem', function (navigationItem) {
  return navigationCollection.add(navigationItem);
});

NUSMods.setConfig(config);

var selectedModulesControllers = [];

for (var i = 0; i < 5; i++) {
  selectedModulesControllers[i] = new SelectedModulesController({
    semester: i + 1
  });
}

App.reqres.setHandler('selectedModules', function (sem) {
  return selectedModulesControllers[sem - 1].selectedModules;
});
App.reqres.setHandler('addModule', function (sem, id, options) {
  return selectedModulesControllers[sem - 1].selectedModules.add({
    ModuleCode: id,
    Semester: sem
  }, options);
});
App.reqres.setHandler('removeModule', function (sem, id) {
  var selectedModules = selectedModulesControllers[sem - 1].selectedModules;
  return selectedModules.remove(selectedModules.get(id));
});
App.reqres.setHandler('isModuleSelected', function (sem, id) {
  return !!selectedModulesControllers[sem - 1].selectedModules.get(id);
});
App.reqres.setHandler('displayLessons', function (sem, id, display) {
  _.each(selectedModulesControllers[sem - 1].timetable.where({
    ModuleCode: id
  }), function (lesson) {
    lesson.set('display', display);
  });
});

var bookmarkedModulesNamespace = config.namespaces.bookmarkedModules + ':';

App.reqres.setHandler('getBookmarks', function (callback) {
  if (!callback) {
    return;
  }
  localforage.getItem(bookmarkedModulesNamespace, function (modules) {
    callback(modules);
  });
});
App.reqres.setHandler('addBookmark', function (id) {
  localforage.getItem(bookmarkedModulesNamespace, function (modules) {
    if (!_.contains(modules, id)) {
      modules.push(id);
    }
    localforage.setItem(bookmarkedModulesNamespace, modules);
  });
});
App.reqres.setHandler('deleteBookmark', function (id) {
  localforage.getItem(bookmarkedModulesNamespace, function (modules) {
    var index = modules.indexOf(id);
    if (index > -1) {
      modules.splice(index, 1);
      localforage.setItem(bookmarkedModulesNamespace, modules);
    }
  });
});

App.on('start', function () {
  var AppView = require('./common/views/AppView');

  new Marionette.AppRouter({
    routes: {
      '*default': function () {
        Backbone.history.navigate('timetable', {trigger: true, replace: true});
      }
    }
  });

  // header modules
  require('./timetable');
  require('./modules');
  // require('ivle');
  require('./barenus');
  require('./friends');
  require('./venues');
  require('./nusessities');
  require('./preferences');
  require('./blog');

  // footer modules
  require('./about');
  require('./contribute');
  require('./help');
  require('./support');

  Promise.all(_.map(_.range(1, 5), function(semester) {
    var semTimetableFragment = config.semTimetableFragment(semester);
    return localforage.getItem(semTimetableFragment + ':queryString')
      .then(function (savedQueryString) {
      if ('/' + semTimetableFragment === window.location.pathname) {
        var queryString = window.location.search.slice(1);
        if (queryString) {
          if (savedQueryString !== queryString) {
            // If initial query string does not match saved query string,
            // timetable is shared.
            App.request('selectedModules', semester).shared = true;
          }
          // If there is a query string for timetable, return so that it will
          // be used instead of saved query string.
          return;
        }
      }
      var selectedModules = TimetableModuleCollection.fromQueryStringToJSON(savedQueryString);
      return Promise.all(_.map(selectedModules, function (module) {
        return App.request('addModule', semester, module.ModuleCode, module);
      }));
    });
  }).concat([NUSMods.generateModuleCodes()])).then(function () {
    new AppView();

    Backbone.history.start({pushState: true});
  });

  localforage.getItem(bookmarkedModulesNamespace, function (modules) {
    if (!modules) {
      localforage.setItem(bookmarkedModulesNamespace, []);
    }
  });
});

module.exports = App;
<|endoftext|>


<commit_before>// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

function showTooltip(trigger, target) {
    new Tooltip(trigger, target)
}

function trimSpaces(str) {
    while ((str.length > 0) && (str.charAt(0) == ' '))
        str = str.substring(1);
    while ((str.length > 0) && (str.charAt(str.length - 1) == ' '))
        str = str.substring(0, str.length - 1);
    return str;
}

function addToolListTag(tag_id) {
    tools_autocompleter=autocompleters['tools_autocompleter']
    var index=tools_autocompleter.itemIDsToJsonArrayIDs([tag_id])[0];
    var item = new Element('a', {
        'value': index
    });
    tools_autocompleter.addContactToList(item);
}

function addExpertiseListTag(tag_id) {
    expertise_autocompleter=autocompleters['expertise_autocompleter']
    var index=expertise_autocompleter.itemIDsToJsonArrayIDs([tag_id])[0];
    var item = new Element('a', {
        'value': index
    });
    expertise_autocompleter.addContactToList(item);
}

function addOrganismListTag(tag_id) {

    organism_autocompleter=autocompleters['organism_autocompleter']
    var index=organism_autocompleter.itemIDsToJsonArrayIDs([tag_id])[0];
    var item = new Element('a', {
        'value': index
    });
    organism_autocompleter.addContactToList(item);
}

function checkNotInList(id,list) {
    rtn = true;

    for(var i = 0; i < list.length; i++)
        if(list[i][1] == id) {
            rtn = false;
            break;
        }

    return(rtn);
}

function clearList(name) {
    select=$(name)
    while(select.length>0) {
        select.remove(select.options[0])
    }
}

function removeChildren(name) {
	$(name).childElements().each(function(e) {
	        e.remove();
	    });
}

function subset() {
  p1 = $F('group_name')
  p2 = $F('group_info')
  // p3 = $F('people_hidden')
  p3 = $F('people_hidden')
  return $H({ x: p1, y: p2, z: p3 });
}

// document.observe('dom:loaded', function() {
//      $('new-group-link').observe('click', function(event) {
//         event.stop();
//          Modalbox.show(this.href,
//              {title: 'Create new group',
//              width: 500}
//          );
//      });
//  })

// Ajax.Responders.register({
//   onCreate: function(){
//     $('spinner').show();
//   },
//   onComplete: function() {
//     if(Ajax.activeRequestCount == 0)
//       $('spinner').hide();
//   }
// });

//Ajax.Base.prototype.initialize = Ajax.Base.prototype.initialize.wrap(
//   function(p, options){
//     p(options);
//     this.options.parameters = this.options.parameters || {};
//     this.options.parameters.authenticity_token = window._token || '';
//   }
//);
<commit_msg>show/hide login box<commit_after>// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

function showTooltip(trigger, target) {
    new Tooltip(trigger, target)
}

function trimSpaces(str) {
    while ((str.length > 0) && (str.charAt(0) == ' '))
        str = str.substring(1);
    while ((str.length > 0) && (str.charAt(str.length - 1) == ' '))
        str = str.substring(0, str.length - 1);
    return str;
}

function addToolListTag(tag_id) {
    tools_autocompleter=autocompleters['tools_autocompleter']
    var index=tools_autocompleter.itemIDsToJsonArrayIDs([tag_id])[0];
    var item = new Element('a', {
        'value': index
    });
    tools_autocompleter.addContactToList(item);
}

function addExpertiseListTag(tag_id) {
    expertise_autocompleter=autocompleters['expertise_autocompleter']
    var index=expertise_autocompleter.itemIDsToJsonArrayIDs([tag_id])[0];
    var item = new Element('a', {
        'value': index
    });
    expertise_autocompleter.addContactToList(item);
}

function addOrganismListTag(tag_id) {

    organism_autocompleter=autocompleters['organism_autocompleter']
    var index=organism_autocompleter.itemIDsToJsonArrayIDs([tag_id])[0];
    var item = new Element('a', {
        'value': index
    });
    organism_autocompleter.addContactToList(item);
}

function checkNotInList(id,list) {
    rtn = true;

    for(var i = 0; i < list.length; i++)
        if(list[i][1] == id) {
            rtn = false;
            break;
        }

    return(rtn);
}

function clearList(name) {
    select=$(name)
    while(select.length>0) {
        select.remove(select.options[0])
    }
}

function removeChildren(name) {
	$(name).childElements().each(function(e) {
	        e.remove();
	    });
}

function subset() {
  p1 = $F('group_name')
  p2 = $F('group_info')
  // p3 = $F('people_hidden')
  p3 = $F('people_hidden')
  return $H({ x: p1, y: p2, z: p3 });
}

function showLoginBox(boxID) {
        var box = document.getElementById(boxID);
        if (box) {

                $(boxID).blindDown({ duration: 0.6 });
        }
}

function closeLoginBox(boxID) {
        var box = document.getElementById(boxID);
        if (box) {
                $(boxID).blindUp({ duration: 0.6 });
        }
}

// document.observe('dom:loaded', function() {
//      $('new-group-link').observe('click', function(event) {
//         event.stop();
//          Modalbox.show(this.href,
//              {title: 'Create new group',
//              width: 500}
//          );
//      });
//  })

// Ajax.Responders.register({
//   onCreate: function(){
//     $('spinner').show();
//   },
//   onComplete: function() {
//     if(Ajax.activeRequestCount == 0)
//       $('spinner').hide();
//   }
// });

//Ajax.Base.prototype.initialize = Ajax.Base.prototype.initialize.wrap(
//   function(p, options){
//     p(options);
//     this.options.parameters = this.options.parameters || {};
//     this.options.parameters.authenticity_token = window._token || '';
//   }
//);
<|endoftext|>


<commit_before>import React, { useEffect } from 'react';
import { useIntl } from 'react-intl';
import {
  SettingsPageTitle,
  useFocusWhenNavigate,
  useNotification,
  NoPermissions,
  useRBAC,
  NoContent,
  DynamicTable,
} from '@strapi/helper-plugin';
import { HeaderLayout, ContentLayout } from '@strapi/parts/Layout';
import { Main } from '@strapi/parts/Main';
import { Button } from '@strapi/parts/Button';
import { LinkButton } from '@strapi/parts/LinkButton';
import AddIcon from '@strapi/icons/AddIcon';
import { useQuery, useMutation, useQueryClient } from 'react-query';
import { useHistory } from 'react-router-dom';
import qs from 'qs';
import { axiosInstance } from '../../../../../core/utils';
import adminPermissions from '../../../../../permissions';
import tableHeaders from './utils/tableHeaders';
import TableRows from './DynamicTable';

const ApiTokenListView = () => {
  useFocusWhenNavigate();
  const queryClient = useQueryClient();
  const { formatMessage } = useIntl();
  const toggleNotification = useNotification();
  const {
    allowedActions: { canCreate, canDelete, canUpdate, canRead },
  } = useRBAC(adminPermissions.settings['api-tokens']);
  const { push } = useHistory();

  useEffect(() => {
    push({ search: qs.stringify({ sort: 'name:ASC' }, { encode: false }) });
  }, [push]);

  const { data: apiTokens, status, isFetching } = useQuery(
    ['api-tokens'],
    async () => {
      const {
        data: { data },
      } = await axiosInstance.get(`/admin/api-tokens`);

      return data;
    },
    {
      enabled: canRead,
      onError: () => {
        toggleNotification({
          type: 'warning',
          message: { id: 'notification.error', defaultMessage: 'An error occured' },
        });
      },
    }
  );

  const isLoading =
    canRead &&
    ((status !== 'success' && status !== 'error') || (status === 'success' && isFetching));

  const deleteMutation = useMutation(
    async id => {
      await axiosInstance.delete(`/admin/api-tokens/${id}`);
    },
    {
      onSuccess: async () => {
        await queryClient.invalidateQueries(['api-tokens']);
      },
      onError: err => {
        if (err?.response?.data?.data) {
          toggleNotification({ type: 'warning', message: err.response.data.data });
        } else {
          toggleNotification({
            type: 'warning',
            message: { id: 'notification.error', defaultMessage: 'An error occured' },
          });
        }
      },
    }
  );

  const shouldDisplayDynamicTable = canRead && apiTokens;
  const shouldDisplayNoContent = canRead && !apiTokens && !canCreate;
  const shouldDisplayNoContentWithCreationButton = canRead && !apiTokens && canCreate;

  return (
    <Main aria-busy={isLoading}>
      <SettingsPageTitle name="API Tokens" />
      <HeaderLayout
        title={formatMessage({ id: 'Settings.apiTokens.title', defaultMessage: 'API Tokens' })}
        subtitle={formatMessage({
          id: 'Settings.apiTokens.description',
          defaultMessage: 'List of generated tokens to consume the API',
        })}
        primaryAction={
          canCreate ? (
            <LinkButton
              data-testid="create-api-token-button"
              startIcon={<AddIcon />}
              size="L"
              to="/settings/api-tokens/create"
            >
              {formatMessage({
                id: 'Settings.apiTokens.create',
                defaultMessage: 'Add Entry',
              })}
            </LinkButton>
          ) : (
            undefined
          )
        }
      />
      <ContentLayout>
        {!canRead && <NoPermissions />}
        {shouldDisplayDynamicTable && (
          <DynamicTable
            headers={tableHeaders}
            contentType="api-tokens"
            rows={apiTokens}
            withBulkActions={canDelete || canUpdate}
            isLoading={isLoading}
            onConfirmDelete={id => deleteMutation.mutateAsync(id)}
          >
            <TableRows
              canDelete={canDelete}
              canUpdate={canUpdate}
              rows={apiTokens}
              withBulkActions={canDelete || canUpdate}
            />
          </DynamicTable>
        )}
        {shouldDisplayNoContentWithCreationButton && (
          <NoContent
            content={{
              id: 'Settings.apiTokens.addFirstToken',
              defaultMessage: 'Add your first API Token',
            }}
            action={
              <Button variant="secondary" startIcon={<AddIcon />}>
                {formatMessage({
                  id: 'Settings.apiTokens.addNewToken',
                  defaultMessage: 'Add new API Token',
                })}
              </Button>
            }
          />
        )}
        {shouldDisplayNoContent && (
          <NoContent
            content={{
              id: 'Settings.apiTokens.emptyStateLayout',
              defaultMessage: 'You don’t have any content yet...',
            }}
          />
        )}
      </ContentLayout>
    </Main>
  );
};

export default ApiTokenListView;
<commit_msg>implement the deletion of tokens<commit_after>import React, { useEffect } from 'react';
import { useIntl } from 'react-intl';
import {
  SettingsPageTitle,
  useFocusWhenNavigate,
  useNotification,
  NoPermissions,
  useRBAC,
  NoContent,
  DynamicTable,
} from '@strapi/helper-plugin';
import { HeaderLayout, ContentLayout } from '@strapi/parts/Layout';
import { Main } from '@strapi/parts/Main';
import { Button } from '@strapi/parts/Button';
import { LinkButton } from '@strapi/parts/LinkButton';
import AddIcon from '@strapi/icons/AddIcon';
import { useQuery, useMutation, useQueryClient } from 'react-query';
import { useHistory } from 'react-router-dom';
import qs from 'qs';
import { axiosInstance } from '../../../../../core/utils';
import adminPermissions from '../../../../../permissions';
import tableHeaders from './utils/tableHeaders';
import TableRows from './DynamicTable';

const ApiTokenListView = () => {
  useFocusWhenNavigate();
  const queryClient = useQueryClient();
  const { formatMessage } = useIntl();
  const toggleNotification = useNotification();
  const {
    allowedActions: { canCreate, canDelete, canUpdate, canRead },
  } = useRBAC(adminPermissions.settings['api-tokens']);
  const { push } = useHistory();

  useEffect(() => {
    push({ search: qs.stringify({ sort: 'name:ASC' }, { encode: false }) });
  }, [push]);

  const { data: apiTokens, status, isFetching } = useQuery(
    ['api-tokens'],
    async () => {
      const {
        data: { data },
      } = await axiosInstance.get(`/admin/api-tokens`);

      return data;
    },
    {
      enabled: canRead,
      onError: () => {
        toggleNotification({
          type: 'warning',
          message: { id: 'notification.error', defaultMessage: 'An error occured' },
        });
      },
    }
  );

  const isLoading =
    canRead &&
    ((status !== 'success' && status !== 'error') || (status === 'success' && isFetching));

  const deleteMutation = useMutation(
    async id => {
      await axiosInstance.delete(`/admin/api-tokens/${id}`);
    },
    {
      onSuccess: async () => {
        await queryClient.invalidateQueries(['api-tokens']);
      },
      onError: err => {
        if (err?.response?.data?.data) {
          toggleNotification({ type: 'warning', message: err.response.data.data });
        } else {
          toggleNotification({
            type: 'warning',
            message: { id: 'notification.error', defaultMessage: 'An error occured' },
          });
        }
      },
    }
  );

  const deleteMutation = useMutation(
    async id => {
      await axiosInstance.delete(`/admin/api-tokens/${id}`);
    },
    {
      onSuccess: async () => {
        await queryClient.invalidateQueries(['api-tokens']);
      },
      onError: err => {
        if (err?.response?.data?.data) {
          toggleNotification({ type: 'warning', message: err.response.data.data });
        } else {
          toggleNotification({
            type: 'warning',
            message: { id: 'notification.error', defaultMessage: 'An error occured' },
          });
        }
      },
    }
  );

  const shouldDisplayDynamicTable = canRead && apiTokens;
  const shouldDisplayNoContent = canRead && !apiTokens && !canCreate;
  const shouldDisplayNoContentWithCreationButton = canRead && !apiTokens && canCreate;

  return (
    <Main aria-busy={isLoading}>
      <SettingsPageTitle name="API Tokens" />
      <HeaderLayout
        title={formatMessage({ id: 'Settings.apiTokens.title', defaultMessage: 'API Tokens' })}
        subtitle={formatMessage({
          id: 'Settings.apiTokens.description',
          defaultMessage: 'List of generated tokens to consume the API',
        })}
        primaryAction={
          canCreate ? (
            <LinkButton
              data-testid="create-api-token-button"
              startIcon={<AddIcon />}
              size="L"
              to="/settings/api-tokens/create"
            >
              {formatMessage({
                id: 'Settings.apiTokens.create',
                defaultMessage: 'Add Entry',
              })}
            </LinkButton>
          ) : (
            undefined
          )
        }
      />
      <ContentLayout>
        {!canRead && <NoPermissions />}
        {shouldDisplayDynamicTable && (
          <DynamicTable
            headers={tableHeaders}
            contentType="api-tokens"
            rows={apiTokens}
            withBulkActions={canDelete || canUpdate}
            isLoading={isLoading}
            onConfirmDelete={id => deleteMutation.mutateAsync(id)}
          >
            <TableRows
              canDelete={canDelete}
              canUpdate={canUpdate}
              rows={apiTokens}
              withBulkActions={canDelete || canUpdate}
            />
          </DynamicTable>
        )}
        {shouldDisplayNoContentWithCreationButton && (
          <NoContent
            content={{
              id: 'Settings.apiTokens.addFirstToken',
              defaultMessage: 'Add your first API Token',
            }}
            action={
              <Button variant="secondary" startIcon={<AddIcon />}>
                {formatMessage({
                  id: 'Settings.apiTokens.addNewToken',
                  defaultMessage: 'Add new API Token',
                })}
              </Button>
            }
          />
        )}
        {shouldDisplayNoContent && (
          <NoContent
            content={{
              id: 'Settings.apiTokens.emptyStateLayout',
              defaultMessage: 'You don’t have any content yet...',
            }}
          />
        )}
      </ContentLayout>
    </Main>
  );
};

export default ApiTokenListView;
<|endoftext|>


<commit_before>goog.module('measurementLibrary.eventProcessor.testing.GoogleAnalyticsEventProcessor.persistTime');
goog.setTestOnly();

const GoogleAnalyticsEventProcessor = goog.require('measurementLibrary.eventProcessor.GoogleAnalyticsEventProcessor');

describe('The `persistTime` method ' +
    'of GoogleAnalyticsEventProcessor', () => {
  /**
   * Builds expectation object for the `persistTime` function by passing
   * in a key to make function call with. Also accepts a client ID
   * expiration override.
   * @param {string} key
   * @param {(number|undefined)=} clientIdExpires
   * @return {!Expectation}
   */
  function expectPersistTime(key, clientIdExpires = undefined) {
    const eventProcessor = new GoogleAnalyticsEventProcessor({
      'client_id_expires': clientIdExpires,
    });

    return expect(eventProcessor.persistTime(key, ''));
  }

  it('returns default when key is not clientId', () => {
    expectPersistTime('test').toBe(-1);
  });

  describe('When key is clientId', () => {
    it('returns two years when client_id_expires is not set', () => {
      expectPersistTime('client_id').toBe(2 * 365 * 24 * 60 * 60);
    });

    it('returns overridden number when client_id_expires is set', () => {
      expectPersistTime('client_id', /* clientIdExpires */ 0).toBe(0);
    });
  });
});
<commit_msg>Update persistTime_test.js<commit_after>goog.module('measurementLibrary.eventProcessor.testing.GoogleAnalyticsEventProcessor.persistTime');
goog.setTestOnly();

const GoogleAnalyticsEventProcessor = goog.require('measurementLibrary.eventProcessor.GoogleAnalyticsEventProcessor');

describe('The `persistTime` method ' +
    'of GoogleAnalyticsEventProcessor', () => {
  /**
   * Builds expectation object for the `persistTime` function by passing
   * in a key to make function call with. Also accepts a client ID
   * expiration override.
   * @param {string} key
   * @param {(number|undefined)=} clientIdExpires
   * @return {!Expectation}
   */
  function expectPersistTime(key, clientIdExpires = undefined) {
    const eventProcessor = new GoogleAnalyticsEventProcessor({
      'client_id_expires': clientIdExpires,
    });

    return expect(eventProcessor.persistTime(key, ''));
  }

  it('returns default when key is not client_id', () => {
    expectPersistTime('test').toBe(-1);
  });

  describe('When key is client_id', () => {
    it('returns two years when client_id_expires is not set', () => {
      expectPersistTime('client_id').toBe(2 * 365 * 24 * 60 * 60);
    });

    it('returns overridden number when client_id_expires is set', () => {
      expectPersistTime('client_id', /* clientIdExpires */ 0).toBe(0);
    });
  });
});
<|endoftext|>


<commit_before>import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';

moduleForComponent( 'sl-drop-option-divider', 'Integration | Component | sl drop option divider', {
    integration: true
});

test( 'Default rendered state', function( assert ) {
    this.render( hbs`
        {{sl-drop-option-divider}}
    ` );

    assert.ok(
        this.$( '>:first-child' ).hasClass( 'divider' ),
        'Rendered component initially has class "divider"'
    );

    assert.strictEqual(
        this.$( '>:first-child' ).attr( 'role' ),
        'separator',
        'ARIA role is properly set to "menuitem"'
    );
});
<commit_msg>updated description in sl-drop-option-divider test<commit_after>import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';

moduleForComponent( 'sl-drop-option-divider', 'Integration | Component | sl drop option divider', {
    integration: true
});

test( 'Default rendered state', function( assert ) {
    this.render( hbs`
        {{sl-drop-option-divider}}
    ` );

    assert.ok(
        this.$( '>:first-child' ).hasClass( 'divider' ),
        'Rendered component initially has class "divider"'
    );

    assert.strictEqual(
        this.$( '>:first-child' ).attr( 'role' ),
        'separator',
        'ARIA role is properly set to "separator"'
    );
});
<|endoftext|>


<commit_before>import { permissionToRemoveContributor } from 'preprint-service/helpers/permission-to-remove-contributor';
import { module, test } from 'qunit';
import Ember from 'ember';

module('Unit | Helper | permission to remove contributor');

test('cannot remove self as a contributor', function(assert) {
    var contrib = Ember.Object.create({
        'userId': '12345',
        'permission': 'admin',
        'unregisteredContributor': null,
        'bibliographic': true

    });
    var currentUser = Ember.Object.create({
        id: '12345',
        currentUserId: '12345'
    });
    var isAdmin = false;
    var node = Ember.Object.create({
        'registration': false
    });

    let result = permissionToRemoveContributor([contrib, currentUser, isAdmin, node]);
    assert.equal(result, false);
});

test('cannot remove contributor if you are not admin', function(assert) {
    var contrib = Ember.Object.create({
        'userId': 'abcde',
        'permission': 'admin',
        'unregisteredContributor': null,
        'bibliographic': true

    });
    var currentUser = Ember.Object.create({
        id: '12345',
        currentUserId: '12345'
    });
    var isAdmin = false;
    var node = Ember.Object.create({
        'registration': false
    });

    let result = permissionToRemoveContributor([contrib, currentUser, isAdmin, node]);
    assert.equal(result, false);
});

test('can remove another contributor if you are admin', function(assert) {
    var contrib = Ember.Object.create({
        'userId': 'abcde',
        'permission': 'admin',
        'unregisteredContributor': null,
        'bibliographic': true

    });
    var currentUser = Ember.Object.create({
        id: '12345',
        currentUserId: '12345'
    });
    var isAdmin = true;
    var node = Ember.Object.create({
        'registration': false
    });

    let result = permissionToRemoveContributor([contrib, currentUser, isAdmin, node]);
    assert.equal(result, true);
});
<commit_msg>Add test to permission-to-remove-contributor.<commit_after>import { permissionToRemoveContributor } from 'preprint-service/helpers/permission-to-remove-contributor';
import { module, test } from 'qunit';
import Ember from 'ember';

module('Unit | Helper | permission to remove contributor');

test('cannot remove self as a contributor', function(assert) {
    var contrib = Ember.Object.create({
        'userId': '12345',
        'permission': 'admin',
        'unregisteredContributor': null,
        'bibliographic': true

    });
    var currentUser = Ember.Object.create({
        id: '12345',
        currentUserId: '12345'
    });
    var isAdmin = false;
    var node = Ember.Object.create({
        'registration': false
    });

    let result = permissionToRemoveContributor([contrib, currentUser, isAdmin, node]);
    assert.equal(result, false);
});

test('cannot remove contributor if you are not admin', function(assert) {
    var contrib = Ember.Object.create({
        'userId': 'abcde',
        'permission': 'admin',
        'unregisteredContributor': null,
        'bibliographic': true

    });
    var currentUser = Ember.Object.create({
        id: '12345',
        currentUserId: '12345'
    });
    var isAdmin = false;
    var node = Ember.Object.create({
        'registration': false
    });

    let result = permissionToRemoveContributor([contrib, currentUser, isAdmin, node]);
    assert.equal(result, false);
});

test('can remove another contributor if you are admin', function(assert) {
    var contrib = Ember.Object.create({
        'userId': 'abcde',
        'permission': 'admin',
        'unregisteredContributor': null,
        'bibliographic': true

    });
    var currentUser = Ember.Object.create({
        id: '12345',
        currentUserId: '12345'
    });
    var isAdmin = true;
    var node = Ember.Object.create({
        'registration': false
    });

    let result = permissionToRemoveContributor([contrib, currentUser, isAdmin, node]);
    assert.equal(result, true);
});

test('cannot remove contributor from registration', function(assert) {
    // This scenario should never be happening.
    var contrib = Ember.Object.create({
        'userId': 'abcde',
        'permission': 'admin',
        'unregisteredContributor': null,
        'bibliographic': true

    });
    var currentUser = Ember.Object.create({
        id: '12345',
        currentUserId: '12345'
    });
    var isAdmin = true;
    var node = Ember.Object.create({
        'registration': true
    });

    let result = permissionToRemoveContributor([contrib, currentUser, isAdmin, node]);
    assert.equal(result, false);
});
<|endoftext|>


<commit_before>/**
 * Created by Lenovo on 2016/6/18.
 */
/********************************************************************************************************
 * Name: UML to YANG Mapping Tool
 * Copyright 2015 CAICT (China Academy of Information and Communication Technology (former China Academy of Telecommunication Research)). All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License").
 *
 * This tool is developed according to the mapping rules defined in onf2015.261_Mapping_Gdls_UML-YANG.08 by OpenNetworkFoundation(ONF) IMP group.
 *
 * file: \model\yang\leaf.js
 *
 * The above copyright information should be included in all distribution, reproduction or derivative works of this software.
 *
 ****************************************************************************************************/
var Util = require('./util.js');

function Package(name, id, path, comment, fileName) {
    this.name = name;
    this.id = id;
    this.path = path;
    this.description = comment;
    this.fileName = fileName;
    this.children = [];
    this.uses = [];
}
Package.prototype.writeNode = function (layer) {
    if(this.children.length == 0){
        return "";
    }
    var PRE = '';
    var k = layer;
    while (k-- > 0) {
        PRE += '\t';
    }

    //var name = "container " + this.name;
    var name = "/***********************\r\n* package " + this.name + "\r\n**********************/";
    name = name.replace(/\r\n/g, '\r\n' + PRE);
    if(!this.description){
        this.description = "none";
    }
    if (typeof this.description == 'string') {
        this.description = this.description.replace(/\r+\n\s*/g, '\r\n' + PRE + '\t\t');
        this.description = this.description.replace(/\"/g,"\'");
    }
    // var descript = this.description ? PRE + "\tdescription \"" + this.description + "\";\r\n" : "";
    var children = "";
    var sub;
    if (this.children) {
        for (var i = 0; i < this.children.length; i++) {
            if(sub != undefined){
                this.children[i - 1] = this.children[i];
            }
            if(this.children[i].name == "Interfaces"){
                sub = this.children[i];
            }
        }
        if(sub != undefined){
            this.children[this.children.length - 1] = sub;

        }
        for (var i = 0; i < this.children.length; i++) {
            children += this.children[i].writeNode(layer + 1);
        }
    }
    var uses = "";
    for(var i = 0; i < this.uses.length; i++){
        uses += PRE + "\tuses " + this.uses[i].name + ";\r\n";
    }
    var s = PRE + Util.yangifyName(name) + " \r\n" +
        children +
        Util.yangifyName(uses) +
        //descript +
        "\r\n";
    return s;
    /*var s = PRE + name + " {\r\n" +
        children +
        uses +
        descript +
        PRE + "}\r\n";
    return s;*/
};
module.exports = Package;
<commit_msg>housekeeping<commit_after>/**
 * Created by Lenovo on 2016/6/18.
 */
/********************************************************************************************************
 * Name: UML to YANG Mapping Tool
 * Copyright 2015 CAICT (China Academy of Information and Communication Technology (former China Academy of Telecommunication Research)). All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License").
 *
 * This tool is developed according to the mapping rules defined in onf2015.261_Mapping_Gdls_UML-YANG.08 by OpenNetworkFoundation(ONF) IMP group.
 *
 * file: \model\yang\package.js
 *
 * The above copyright information should be included in all distribution, reproduction or derivative works of this software.
 *
 ****************************************************************************************************/
var Util = require('./util.js');

function Package(name, id, path, comment, fileName) {
    this.name = name;
    this.id = id;
    this.path = path;
    this.description = comment;
    this.fileName = fileName;
    this.children = [];
    this.uses = [];
}
Package.prototype.writeNode = function (layer) {
    if(this.children.length == 0){
        return "";
    }
    var PRE = '';
    var k = layer;
    while (k-- > 0) {
        PRE += '\t';
    }

    //var name = "container " + this.name;
    var name = "/***********************\r\n* package " + this.name + "\r\n**********************/";
    name = name.replace(/\r\n/g, '\r\n' + PRE);
    if(!this.description){
        this.description = "none";
    }
    if (typeof this.description == 'string') {
        this.description = this.description.replace(/\r+\n\s*/g, '\r\n' + PRE + '\t\t');
        this.description = this.description.replace(/\"/g,"\'");
    }
    // var descript = this.description ? PRE + "\tdescription \"" + this.description + "\";\r\n" : "";
    var children = "";
    var sub;
    if (this.children) {
        for (var i = 0; i < this.children.length; i++) {
            if(sub != undefined){
                this.children[i - 1] = this.children[i];
            }
            if(this.children[i].name == "Interfaces"){
                sub = this.children[i];
            }
        }
        if(sub != undefined){
            this.children[this.children.length - 1] = sub;

        }
        for (var i = 0; i < this.children.length; i++) {
            children += this.children[i].writeNode(layer + 1);
        }
    }
    var uses = "";
    for(var i = 0; i < this.uses.length; i++){
        uses += PRE + "\tuses " + this.uses[i].name + ";\r\n";
    }
    var s = PRE + Util.yangifyName(name) + " \r\n" +
        children +
        Util.yangifyName(uses) +
        //descript +
        "\r\n";
    return s;
    /*var s = PRE + name + " {\r\n" +
        children +
        uses +
        descript +
        PRE + "}\r\n";
    return s;*/
};
module.exports = Package;
<|endoftext|>


<commit_before>define([
    'dojo/_base/window',
    'dojo/_base/declare',
    'dojo/parser',
    'sqleditor/widgets/TabPage',
    'sqleditor/widgets/_LayoutMixin',
    'sqleditor/widgets/_TabPageApi',
    'dojo/ready',
    'sqleditor/widgets/MessageQueue'
], function(win, declare, parser, TabPage, _LayoutMixin, _TabPageApi, ready, MessageQueue) {

    ready(function () {
        parser.parse();
    });

    return declare('sqleditor.tests.ui.tabpage', [_LayoutMixin, _TabPageApi], {

        buttonLogoutClick: function () {
        },

        comboboxSystemsOnChange: function () {
        },

        buttonNewClick: function () {
            var page = new TabPage();
            page.set('title', 'hello');
            this.tabContainer.addChild(page);
            page.startup();
            this.tabContainer.selectChild(page);
        }
    });
});
<commit_msg>Update tabpage.js<commit_after>define([
    'dojo/_base/window',
    'dojo/_base/declare',
    'dojo/parser',
    'sqleditor/widgets/TabPage',
    'sqleditor/widgets/_LayoutMixin',
    'sqleditor/widgets/_TabPageApi',
    'dojo/ready',
    'sqleditor/widgets/MessageQueue'
], function(win, declare, parser, TabPage, _LayoutMixin, _TabPageApi, ready, MessageQueue) {

    ready(function () {
        parser.parse();
    });

    return declare('sqleditor.tests.ui.tabpage', [_LayoutMixin, _TabPageApi], {

        buttonNewClick: function () {
            var page = new TabPage();
            page.set('title', 'hello');
            this.tabContainer.addChild(page);
            page.startup();
            this.tabContainer.selectChild(page);
        }
    });
});
<|endoftext|>


<commit_before>/*
 * Copyright 2012 - present by OpenGamma Inc. and the OpenGamma group of companies
 * Please see distribution for license.
 */
$.register_module({
    name: 'og.analytics.CellMenu',
    dependencies: ['og.common.gadgets.mapping'],
    obj: function () {
        var module = this,
            icons = '.og-num, .og-icon-new-window-2',
            open_icon = '.og-small',
            open_inplace = '.og-icon-down-chevron',
            expand_class = 'og-expanded',
            panels = ['south', 'dock-north', 'dock-center', 'dock-south'],
            width = 34,
            mapping = og.common.gadgets.mapping,
            $selector;
            type_map = mapping.data_type_map,
            onlydepgraphs = Object.keys(type_map) // a list of datatypes that only support depgraph gadgets
                .filter(function (key) {return type_map[key].length === 1 && type_map[key][0] === 0;});
        var constructor = function (grid) {
            var cellmenu = this, timer, depgraph = !!grid.config.source.depgraph, parent = grid.elements.parent,
                inplace_config; cellmenu.frozen = false; cellmenu.grid = grid;
            if (og.analytics.containers.initialize) throw new Error(module.name + ': there are no panels');
            og.api.text({module: 'og.analytics.cell_options'}).pipe(function (template) {
                (cellmenu.menu = $(template)).hide()
                .on('mouseleave', function () {
                    clearTimeout(timer), cellmenu.menu.removeClass(expand_class), cellmenu.hide();
                })
                .on('mouseenter', open_icon, function () {
                    clearTimeout(timer), timer = setTimeout(function () {cellmenu.menu.addClass(expand_class);}, 500);
                })
                .on('mouseenter', function () {
                    $.data(cellmenu, 'hover', true);
                })
                .on('click', open_icon, function () {
                    cellmenu.destroy_frozen();
                    cellmenu.menu.addClass(expand_class);
                })
                .on('mouseenter', icons, function () {
                    var panel = panels[$(this).text() - 1];
                    panels.forEach(function (val) {og.analytics.containers[val].highlight(true, val === panel);});
                })
                .on('mouseleave', icons, function () {
                    panels.forEach(function (val) {og.analytics.containers[val].highlight(false);});
                })
                .on('click', icons, function () {
                    var panel = panels[+$(this).text() - 1], cell = cellmenu.current,
                        options = mapping.options(cell, grid, panel);
                    cellmenu.destroy_frozen();
                    cellmenu.hide();
                    if (!panel) og.analytics.url.launch(options); else og.analytics.url.add(panel, options);
                });
                grid.on('cellhoverin', function (cell) {
                    if(cellmenu.frozen) return;
                    cellmenu.menu.removeClass(expand_class);
                    clearTimeout(timer);
                    var type = cell.type, hide = !(cellmenu.current = cell).value
                        || (cell.col < (depgraph ? 1 : 2)) || (cell.right > parent.width())
                        || (depgraph && $.inArray(type, onlydepgraphs) > -1);
                    if (hide) cellmenu.hide(); else cellmenu.show();
                }).on('cellhoverout', function () {
                    clearTimeout(timer);
                    setTimeout(function () {if (!cellmenu.menu.is(':hover')) {cellmenu.hide();}});
                });
                og.api.text({module: 'og.analytics.inplace_tash'}).pipe(function (tmpl_inplace) {
                    var unique = cellmenu.grid.id.slice(1);
                    inplace_config = ({$cntr: $('.og-inplace', cellmenu.menu), tmpl: tmpl_inplace, data:{name:unique}});
                    cellmenu.inplace = new og.common.util.ui.DropMenu(inplace_config);
                    cellmenu.container = new og.common.gadgets.GadgetsContainer('.OG-analytics-inplace-', unique);
                    cellmenu.inplace.$dom.toggle.on('click', function() {
                        if(cellmenu.inplace.toggle_handler()){
                            cellmenu.create_inplace();
                            cellmenu.inplace.$dom.menu.blurkill(cellmenu.destroy_frozen.bind(cellmenu));
                        }
                        else cellmenu.destroy_frozen();
                    });
                });
            });
        };
        constructor.prototype.destroy_frozen = function () {
            $('.OG-cell-options.og-frozen').remove();
        };
        constructor.prototype.create_inplace = function () {
            var cellmenu = this, panel = 'inplace', options, cell = cellmenu.current,
                offset = cellmenu.inplace.$dom.cntr.offset(), inner = cellmenu.inplace.$dom.menu;
            cellmenu.destroy_frozen();
            cellmenu.frozen = true;
            cellmenu.menu.addClass('og-frozen');
            options = mapping.options(cell, cellmenu.grid, panel);
            cellmenu.container.add([options]);
            if((offset.top + inner.height())> $(window).height())
                inner.css({marginTop: -inner.height()});
            if((offset.left + inner.width())> $(window).width())
                inner.css({marginLeft: -inner.width() + width} );
            cellmenu.grid.new_menu(cellmenu);

        };
        constructor.prototype.hide = function () {
           /*var cellmenu = this;
            if (cellmenu.menu && cellmenu.menu.length && !cellmenu.frozen) {
                cellmenu.menu.hide();
            }*/
        };
        constructor.prototype.show = function () {
            var cellmenu = this, current = this.current;
            if (cellmenu.menu && cellmenu.menu.length){
                (cellmenu.menu).appendTo($('body')).css(
                    {top: current.top, left: current.right - width + cellmenu.grid.offset.left}).show();
            }
        };
        return constructor;
    }
});<commit_msg>forgot to uncomment something<commit_after>/*
 * Copyright 2012 - present by OpenGamma Inc. and the OpenGamma group of companies
 * Please see distribution for license.
 */
$.register_module({
    name: 'og.analytics.CellMenu',
    dependencies: ['og.common.gadgets.mapping'],
    obj: function () {
        var module = this,
            icons = '.og-num, .og-icon-new-window-2',
            open_icon = '.og-small',
            open_inplace = '.og-icon-down-chevron',
            expand_class = 'og-expanded',
            panels = ['south', 'dock-north', 'dock-center', 'dock-south'],
            width = 34,
            mapping = og.common.gadgets.mapping,
            $selector;
            type_map = mapping.data_type_map,
            onlydepgraphs = Object.keys(type_map) // a list of datatypes that only support depgraph gadgets
                .filter(function (key) {return type_map[key].length === 1 && type_map[key][0] === 0;});
        var constructor = function (grid) {
            var cellmenu = this, timer, depgraph = !!grid.config.source.depgraph, parent = grid.elements.parent,
                inplace_config; cellmenu.frozen = false; cellmenu.grid = grid;
            if (og.analytics.containers.initialize) throw new Error(module.name + ': there are no panels');
            og.api.text({module: 'og.analytics.cell_options'}).pipe(function (template) {
                (cellmenu.menu = $(template)).hide()
                .on('mouseleave', function () {
                    clearTimeout(timer), cellmenu.menu.removeClass(expand_class), cellmenu.hide();
                })
                .on('mouseenter', open_icon, function () {
                    clearTimeout(timer), timer = setTimeout(function () {cellmenu.menu.addClass(expand_class);}, 500);
                })
                .on('mouseenter', function () {
                    $.data(cellmenu, 'hover', true);
                })
                .on('click', open_icon, function () {
                    cellmenu.destroy_frozen();
                    cellmenu.menu.addClass(expand_class);
                })
                .on('mouseenter', icons, function () {
                    var panel = panels[$(this).text() - 1];
                    panels.forEach(function (val) {og.analytics.containers[val].highlight(true, val === panel);});
                })
                .on('mouseleave', icons, function () {
                    panels.forEach(function (val) {og.analytics.containers[val].highlight(false);});
                })
                .on('click', icons, function () {
                    var panel = panels[+$(this).text() - 1], cell = cellmenu.current,
                        options = mapping.options(cell, grid, panel);
                    cellmenu.destroy_frozen();
                    cellmenu.hide();
                    if (!panel) og.analytics.url.launch(options); else og.analytics.url.add(panel, options);
                });
                grid.on('cellhoverin', function (cell) {
                    if(cellmenu.frozen) return;
                    cellmenu.menu.removeClass(expand_class);
                    clearTimeout(timer);
                    var type = cell.type, hide = !(cellmenu.current = cell).value
                        || (cell.col < (depgraph ? 1 : 2)) || (cell.right > parent.width())
                        || (depgraph && $.inArray(type, onlydepgraphs) > -1);
                    if (hide) cellmenu.hide(); else cellmenu.show();
                }).on('cellhoverout', function () {
                    clearTimeout(timer);
                    setTimeout(function () {if (!cellmenu.menu.is(':hover')) {cellmenu.hide();}});
                });
                og.api.text({module: 'og.analytics.inplace_tash'}).pipe(function (tmpl_inplace) {
                    var unique = cellmenu.grid.id.slice(1);
                    inplace_config = ({$cntr: $('.og-inplace', cellmenu.menu), tmpl: tmpl_inplace, data:{name:unique}});
                    cellmenu.inplace = new og.common.util.ui.DropMenu(inplace_config);
                    cellmenu.container = new og.common.gadgets.GadgetsContainer('.OG-analytics-inplace-', unique);
                    cellmenu.inplace.$dom.toggle.on('click', function() {
                        if(cellmenu.inplace.toggle_handler()){
                            cellmenu.create_inplace();
                            cellmenu.inplace.$dom.menu.blurkill(cellmenu.destroy_frozen.bind(cellmenu));
                        }
                        else cellmenu.destroy_frozen();
                    });
                });
            });
        };
        constructor.prototype.destroy_frozen = function () {
            $('.OG-cell-options.og-frozen').remove();
        };
        constructor.prototype.create_inplace = function () {
            var cellmenu = this, panel = 'inplace', options, cell = cellmenu.current,
                offset = cellmenu.inplace.$dom.cntr.offset(), inner = cellmenu.inplace.$dom.menu;
            cellmenu.destroy_frozen();
            cellmenu.frozen = true;
            cellmenu.menu.addClass('og-frozen');
            options = mapping.options(cell, cellmenu.grid, panel);
            cellmenu.container.add([options]);
            if((offset.top + inner.height())> $(window).height())
                inner.css({marginTop: -inner.height()});
            if((offset.left + inner.width())> $(window).width())
                inner.css({marginLeft: -inner.width() + width} );
            cellmenu.grid.new_menu(cellmenu);

        };
        constructor.prototype.hide = function () {
           var cellmenu = this;
            if (cellmenu.menu && cellmenu.menu.length && !cellmenu.frozen) {
                cellmenu.menu.hide();
            }
        };
        constructor.prototype.show = function () {
            var cellmenu = this, current = this.current;
            if (cellmenu.menu && cellmenu.menu.length){
                (cellmenu.menu).appendTo($('body')).css(
                    {top: current.top, left: current.right - width + cellmenu.grid.offset.left}).show();
            }
        };
        return constructor;
    }
});<|endoftext|>


<commit_before>/*
 * Radio Paradise player
 * Copyright (c) 2014 Alexey Michurin <a.michurin@gmail.com>
 * MIT License [http://www.opensource.org/licenses/mit-license.php]
 */

/*global window */
/*global streams, storage, toggle_playing_state, on_storage_change, image_info_init */

'use strict';

(function () {

  function init_stream_selectors(hidden_streams) {

    var si = window.document.getElementById('stream-info');
    var ss = window.document.getElementById('stream-selectors');
    var pe = window.document.getElementById('stream-point');

    function select_stream(sid) {
      return function () {
        storage.set({stream_id: sid});
      };
    }

    streams.list.forEach(function (v) {
      if (hidden_streams[v[0]]) {
        return;
      }
      var d = window.document.createElement('div');
      var s = window.document.createElement('span');
      s.innerText = v[1].title;
      d.appendChild(s);
      si.appendChild(d);
      var e = pe.cloneNode(true);
      e.onmouseover = function () {
        d.style.opacity = 0.85;
      };
      e.onmouseout = function () {
        d.style.opacity = 0;
      };
      e.onclick = select_stream(v[0]);
      e.id = v[0];
      ss.appendChild(e);
      ss.appendChild(window.document.createTextNode(' '));
    });

  }

  var volume_element = window.document.getElementById('volume-control');
  var volume_element_is_active = false;

  volume_element.onmousedown = function (e) {
    volume_element_is_active = true;
    window.document.body.onmousemove(e);
  };

  window.document.body.onmouseup = window.document.body.onmouseleave = function () {
    volume_element_is_active = false;
  };

  window.document.body.onmousemove = function (e) {
    if (volume_element_is_active) {
      var p = volume_element.getBoundingClientRect();
      var v = e.clientX - p.left - 6;
      v = (v < 0 ? 0 : v > 138 ? 138 : v) / 138;
      storage.set({volume: v});
    }
  };

  var play_pause_element = window.document.getElementById('play-pause-button');

  play_pause_element.onclick = function (event) {
    event.preventDefault();
    toggle_playing_state();
  };

  function update_play_pause_element(state) {
    // className do not works in chrome 35-36
    play_pause_element.setAttribute('class', 'container-' + (state ? 'on' : 'off'));
  }

  function update_selectors(sid) {
    Array.prototype.slice.call(
      window.document.querySelectorAll('#stream-selectors svg')
    ).forEach(function (e) {
      e.setAttribute('class', 'container-' + (e.id === sid ? 'on' : 'off'));
    });
  }

  function update_volume_element(volume) {
    volume_element.getElementsByTagName('circle')[0].setAttribute('cx', volume * 1380 + 60);
  }

  on_storage_change(function (ch) {
    if (ch.playing) {
      // can be changed by
      // - @here
      // - watchdog in background page
      update_play_pause_element(ch.playing.newValue);
    }
    if (ch.stream_id) {
      update_selectors(ch.stream_id.newValue);
    }
    if (ch.volume) {
      update_volume_element(ch.volume.newValue);
    }
  });

  storage.get({
    playing: false,
    volume: 0.75,
    stream_id: streams.def.stream,
    animation: true,
    hidden_streams: null // we must NOT use object as default because chrome merge default and actual objects
  }, function (x) {
    update_play_pause_element(x.playing);
    update_volume_element(x.volume);
    init_stream_selectors(x.hidden_streams || streams.hidden_by_default);
    update_selectors(x.stream_id);
    var not_animate = !x.animation;
    window.dom_keeper.get_all(function (cache) {
      image_info_init(cache, not_animate);
    });
  });

}());
<commit_msg>cosmetics<commit_after>/*
 * Radio Paradise player
 * Copyright (c) 2014 Alexey Michurin <a.michurin@gmail.com>
 * MIT License [http://www.opensource.org/licenses/mit-license.php]
 */

/*global window */
/*global streams, storage, toggle_playing_state, on_storage_change, image_info_init */

'use strict';

(function () {

  function init_stream_selectors(hidden_streams) {

    var si = window.document.getElementById('stream-info');
    var ss = window.document.getElementById('stream-selectors');
    var pe = window.document.getElementById('stream-point');

    function select_stream(sid) {
      return function () {
        storage.set({stream_id: sid});
      };
    }

    streams.list.forEach(function (v) {
      if (hidden_streams[v[0]]) {
        return;
      }
      var d = window.document.createElement('div');
      var s = window.document.createElement('span');
      s.innerText = v[1].title;
      d.appendChild(s);
      si.appendChild(d);
      var e = pe.cloneNode(true);
      e.onmouseover = function () {
        d.style.opacity = 0.85;
      };
      e.onmouseout = function () {
        d.style.opacity = 0;
      };
      e.onclick = select_stream(v[0]);
      e.id = v[0];
      ss.appendChild(e);
      ss.appendChild(window.document.createTextNode(' '));
    });

  }

  var volume_element = window.document.getElementById('volume-control');
  var volume_element_is_active = false;

  volume_element.onmousedown = function (e) {
    volume_element_is_active = true;
    window.document.body.onmousemove(e);
  };

  window.document.body.onmouseup = window.document.body.onmouseleave = function () {
    volume_element_is_active = false;
  };

  window.document.body.onmousemove = function (e) {
    if (volume_element_is_active) {
      var p = volume_element.getBoundingClientRect();
      var v = e.clientX - p.left - 6;
      v = (v < 0 ? 0 : v > 138 ? 138 : v) / 138;
      storage.set({volume: v});
    }
  };

  var play_pause_element = window.document.getElementById('play-pause-button');

  play_pause_element.onclick = function (event) {
    event.preventDefault();
    toggle_playing_state();
  };

  function update_play_pause_element(state) {
    // className do not works in chrome 35-36
    play_pause_element.setAttribute('class', 'container-' + (state ? 'on' : 'off'));
  }

  function update_selectors(sid) {
    Array.prototype.slice.call(
      window.document.querySelectorAll('#stream-selectors svg'),
      0
    ).forEach(function (e) {
      e.setAttribute('class', 'container-' + (e.id === sid ? 'on' : 'off'));
    });
  }

  function update_volume_element(volume) {
    volume_element.getElementsByTagName('circle')[0].setAttribute('cx', volume * 1380 + 60);
  }

  on_storage_change(function (ch) {
    if (ch.playing) {
      // can be changed by
      // - @here
      // - watchdog in background page
      update_play_pause_element(ch.playing.newValue);
    }
    if (ch.stream_id) {
      update_selectors(ch.stream_id.newValue);
    }
    if (ch.volume) {
      update_volume_element(ch.volume.newValue);
    }
  });

  storage.get({
    playing: false,
    volume: 0.75,
    stream_id: streams.def.stream,
    animation: true,
    hidden_streams: null // we must NOT use object as default because chrome merge default and actual objects
  }, function (x) {
    update_play_pause_element(x.playing);
    update_volume_element(x.volume);
    init_stream_selectors(x.hidden_streams || streams.hidden_by_default);
    update_selectors(x.stream_id);
    var not_animate = !x.animation;
    window.dom_keeper.get_all(function (cache) {
      image_info_init(cache, not_animate);
    });
  });

}());
<|endoftext|>


<commit_before>/*
 * @copyright 2012 - present by OpenGamma Inc
 * @license See distribution for license
 */
$.register_module({
    name: 'og.analytics.Selector',
    dependencies: ['og.analytics.Grid'],
    obj: function () {
        var module = this;
        return function (grid) {
            var selector = this, $ = grid.$, grid_offset, grid_width, grid_height;
            var auto_scroll = function (event, scroll_top, scroll_left, start) {
                var x = event.pageX - grid_offset.left, y = event.pageY - grid_offset.top,
                    fixed_width = grid.meta.columns.width.fixed, increment = 35, interval = 100,
                    scroll_body = grid.elements.scroll_body, over_fixed = x < fixed_width;
                clearTimeout(auto_scroll.timeout);
                if (x > grid_width) scroll_body.scrollLeft(scroll_left + increment);
                else if (over_fixed && start.x > fixed_width) scroll_body.scrollLeft(scroll_left - increment);
                else
                    if (over_fixed && (auto_scroll.scroll = auto_scroll.scroll || scroll_body.find('.OG-g-sel').length))
                        scroll_body.scrollLeft(scroll_left - increment);
                if (y < grid.meta.header_height) scroll_body.scrollTop(scroll_top - increment);
                else if (y > grid_height) scroll_body.scrollTop(scroll_top + increment);
                auto_scroll.timeout = setTimeout(function () {
                    auto_scroll(event, scroll_body.scrollTop(), scroll_body.scrollLeft(), start);
                }, interval);
            };
            auto_scroll.timeout = null;
            auto_scroll.scroll = false;
            var cleanup = function () {
                $(document).off('mousemove', mousemove_observer).off('mouseup', mouseup_observer);
                clearTimeout(auto_scroll.timeout);
                auto_scroll.scroll = false;
                grid.set_viewport();
            };
            var deselect = function () {
                $(grid.id + ' .OG-g-sel').remove();
                selector.render.memo = null;
            };
            var mousedown_observer = function (event) {
                var $cell, $target, start, fixed, right_click = event.which === 3 || event.button === 2,
                    scroll_left = grid.elements.scroll_body.scrollLeft(),
                    scroll_top = grid.elements.scroll_body.scrollTop();
                if (right_click) return; else cleanup();
                $cell = ($target = $(event.target)).is('.OG-g-cell') ? $target : $target.parents('.OG-g-cell:first');
                if (!$cell.length) return;
                grid_offset = grid.elements.parent.offset();
                grid_width = grid.elements.parent.width();
                grid_height = grid.elements.parent.height();
                fixed = +$cell.attr('class').match(/\sc(\d+)\s?/)[1] < grid.meta.columns.fixed.length;
                start = {
                    x: event.pageX - grid_offset.left + (fixed ? 0 : scroll_left),
                    y: event.pageY - grid_offset.top + scroll_top - grid.meta.header_height,
                };
                (mousemove_observer = function (event) {mousemove(start, event);})(event);
                $(document).on('mousemove', mousemove_observer).on('mouseup', mouseup_observer);
            };
            var mousemove = function (start, event) {
                event.preventDefault();
                var scroll_left = grid.elements.scroll_body.scrollLeft(),
                    scroll_top = grid.elements.scroll_body.scrollTop(),
                    fixed_width = grid.meta.columns.width.fixed, scroll_width = grid.meta.columns.width.scroll,
                    x = event.pageX - grid_offset.left + (event.pageX > fixed_width ? scroll_left : 0),
                    y = event.pageY - grid_offset.top + scroll_top - grid.meta.header_height,
                    areas = [], rectangle = {};
                auto_scroll(event, scroll_top, scroll_left, start);
                rectangle.top_left = nearest_cell(Math.min(start.x, x), Math.min(start.y, y));
                rectangle.bottom_right = nearest_cell(Math.max(start.x, x), Math.max(start.y, y));
                rectangle.width = rectangle.bottom_right.right - rectangle.top_left.left;
                rectangle.height = rectangle.bottom_right.bottom - rectangle.top_left.top;
                if (rectangle.top_left.left < fixed_width) areas.push({ // fixed overlay
                    position: {top: rectangle.top_left.top, left: rectangle.top_left.left},
                    dimensions: {
                        height: rectangle.height,
                        width: rectangle.width + rectangle.top_left.left > fixed_width ?
                            fixed_width - rectangle.top_left.left : rectangle.width
                    },
                    fixed: true
                });
                if (rectangle.bottom_right.right > fixed_width) areas.push({ // scroll overlay
                    position: {top: rectangle.top_left.top, left: areas[0] ? 0 : rectangle.top_left.left - fixed_width},
                    dimensions: {
                        height: rectangle.height,
                        width: areas[0] ? rectangle.width - areas[0].dimensions.width : rectangle.width
                    },
                    fixed: false
                });
                areas.rectangle = rectangle;
                selector.render(areas);
            };
            var mousemove_observer = $.noop;
            var mouseup_observer = cleanup;
            var nearest_cell = function (x, y) {
                var top, bottom, lcv, scan = grid.meta.columns.scan.all, len = scan.length;
                for (lcv = 0; lcv < len; lcv += 1) if (scan[lcv] > x) break;
                bottom = (Math.floor(y / grid.meta.row_height) + 1) * grid.meta.row_height;
                top = bottom - grid.meta.row_height;
                return {top: top, bottom: bottom, left: scan[lcv - 1] || 0, right: scan[lcv]};
            };
            var scroll_observer = function (timeout) {
                return function () { // sync scroll instantaneously and set viewport after scroll stops
                    grid.dataman.busy(true);
                    grid.elements.scroll_head.scrollLeft(grid.elements.scroll_body.scrollLeft());
                    grid.elements.fixed_body.scrollTop(grid.elements.scroll_body.scrollTop());
                    timeout = clearTimeout(timeout) ||
                        setTimeout(function () {grid.set_viewport(function () {grid.dataman.busy(false);})}, 200);
                }
            };
            selector.render = function (rectangles) {
                if (!selector.render.memo && !rectangles) return;
                if (rectangles) selector.render.memo = rectangles;
                $(grid.id + ' .OG-g-sel').remove();
                selector.render.memo.forEach(function (rectangle) {
                    $('
').click(deselect).css(rectangle.position).css(rectangle.dimensions)
                        .appendTo(grid.elements[rectangle.fixed ? 'fixed_body' : 'scroll_body']);
                });
            };
            selector.render.memo = null;
            selector.selection = function () {
                if (!selector.render.memo) return null;
                var bottom_right = selector.render.memo.rectangle.bottom_right,
                    top_left = selector.render.memo.rectangle.top_left,
                    row_start = Math.floor(top_left.top / grid.meta.row_height),
                    row_end = Math.floor(bottom_right.bottom / grid.meta.row_height),
                    lcv, scan = grid.meta.columns.scan.all, rows = [], cols = [];
                for (lcv = 0; lcv < scan.length; lcv += 1)
                    if (scan[lcv] <= bottom_right.right && scan[lcv] > top_left.left) cols.push(lcv);
                    else if (scan[lcv] > bottom_right.right) break;
                for (lcv = row_start; lcv < row_end; lcv += 1) rows.push(lcv);
                return {rows: rows, cols: cols};
            };
            // initialize
            grid.elements.parent[0].onselectstart = function () {return false;};
            grid.elements.parent.on('mousedown', mousedown_observer);
            grid.elements.scroll_body.on('scroll', scroll_observer(null));
        };
    }
});<commit_msg>tweaking selection to work more like excel: when you click, regardless of where you are clicking, a new selection starts at that point<commit_after>/*
 * @copyright 2012 - present by OpenGamma Inc
 * @license See distribution for license
 */
$.register_module({
    name: 'og.analytics.Selector',
    dependencies: ['og.analytics.Grid'],
    obj: function () {
        var module = this;
        return function (grid) {
            var selector = this, $ = grid.$, grid_offset, grid_width, grid_height;
            var auto_scroll = function (event, scroll_top, scroll_left, start) {
                var x = event.pageX - grid_offset.left, y = event.pageY - grid_offset.top,
                    fixed_width = grid.meta.columns.width.fixed, increment = 35, interval = 100,
                    scroll_body = grid.elements.scroll_body, over_fixed = x < fixed_width;
                clearTimeout(auto_scroll.timeout);
                if (x > grid_width) scroll_body.scrollLeft(scroll_left + increment);
                else if (over_fixed && start.x > fixed_width) scroll_body.scrollLeft(scroll_left - increment);
                else
                    if (over_fixed && (auto_scroll.scroll = auto_scroll.scroll || scroll_body.find('.OG-g-sel').length))
                        scroll_body.scrollLeft(scroll_left - increment);
                if (y < grid.meta.header_height) scroll_body.scrollTop(scroll_top - increment);
                else if (y > grid_height) scroll_body.scrollTop(scroll_top + increment);
                auto_scroll.timeout = setTimeout(function () {
                    auto_scroll(event, scroll_body.scrollTop(), scroll_body.scrollLeft(), start);
                }, interval);
            };
            auto_scroll.timeout = null;
            auto_scroll.scroll = false;
            var cleanup = function () {
                $(document).off('mousemove', mousemove_observer).off('mouseup', mouseup_observer);
                clearTimeout(auto_scroll.timeout);
                auto_scroll.scroll = false;
                grid.set_viewport();
            };
            var initialize = function () {
                grid_offset = grid.elements.parent.offset();
                grid_width = grid.elements.parent.width();
                grid_height = grid.elements.parent.height();
            };
            var mousedown_observer = function (event) {
                initialize();
                var $cell, $target, right_click = event.which === 3 || event.button === 2,
                    scroll_left = grid.elements.scroll_body.scrollLeft(),
                    scroll_top = grid.elements.scroll_body.scrollTop(),
                    fixed_width = grid.meta.columns.width.fixed,
                    x = event.pageX - grid_offset.left + (event.pageX > fixed_width ? scroll_left : 0),
                    y = event.pageY - grid_offset.top + scroll_top - grid.meta.header_height;
                if (right_click) return; else cleanup();
                $cell = ($target = $(event.target)).is('.OG-g-cell') ? $target : $target.parents('.OG-g-cell:first');
                if (!$cell.length && !$target.is('.OG-g-sel')) return;
                (mousemove_observer = function (event) {mousemove({x: x, y: y}, event);})(event);
                $(document).on('mousemove', mousemove_observer).on('mouseup', mouseup_observer);
            };
            var mousemove = function (start, event) {
                event.preventDefault();
                var scroll_left = grid.elements.scroll_body.scrollLeft(),
                    scroll_top = grid.elements.scroll_body.scrollTop(),
                    fixed_width = grid.meta.columns.width.fixed,
                    x = event.pageX - grid_offset.left + (event.pageX > fixed_width ? scroll_left : 0),
                    y = event.pageY - grid_offset.top + scroll_top - grid.meta.header_height,
                    areas = [], rectangle = {};
                auto_scroll(event, scroll_top, scroll_left, start);
                rectangle.top_left = nearest_cell(Math.min(start.x, x), Math.min(start.y, y));
                rectangle.bottom_right = nearest_cell(Math.max(start.x, x), Math.max(start.y, y));
                rectangle.width = rectangle.bottom_right.right - rectangle.top_left.left;
                rectangle.height = rectangle.bottom_right.bottom - rectangle.top_left.top;
                if (rectangle.top_left.left < fixed_width) areas.push({ // fixed overlay
                    position: {top: rectangle.top_left.top, left: rectangle.top_left.left},
                    dimensions: {
                        height: rectangle.height,
                        width: rectangle.width + rectangle.top_left.left > fixed_width ?
                            fixed_width - rectangle.top_left.left : rectangle.width
                    },
                    fixed: true
                });
                if (rectangle.bottom_right.right > fixed_width) areas.push({ // scroll overlay
                    position: {top: rectangle.top_left.top, left: areas[0] ? 0 : rectangle.top_left.left - fixed_width},
                    dimensions: {
                        height: rectangle.height,
                        width: areas[0] ? rectangle.width - areas[0].dimensions.width : rectangle.width
                    },
                    fixed: false
                });
                areas.rectangle = rectangle;
                selector.render(areas);
            };
            var mousemove_observer = $.noop;
            var mouseup_observer = cleanup;
            var nearest_cell = function (x, y) {
                var top, bottom, lcv, scan = grid.meta.columns.scan.all, len = scan.length;
                for (lcv = 0; lcv < len; lcv += 1) if (scan[lcv] > x) break;
                bottom = (Math.floor(y / grid.meta.row_height) + 1) * grid.meta.row_height;
                top = bottom - grid.meta.row_height;
                return {top: top, bottom: bottom, left: scan[lcv - 1] || 0, right: scan[lcv]};
            };
            var scroll_observer = function (timeout) {
                return function () { // sync scroll instantaneously and set viewport after scroll stops
                    grid.dataman.busy(true);
                    grid.elements.scroll_head.scrollLeft(grid.elements.scroll_body.scrollLeft());
                    grid.elements.fixed_body.scrollTop(grid.elements.scroll_body.scrollTop());
                    timeout = clearTimeout(timeout) ||
                        setTimeout(function () {grid.set_viewport(function () {grid.dataman.busy(false);})}, 200);
                }
            };
            selector.render = function (rectangles) {
                if (!selector.render.memo && !rectangles) return;
                if (rectangles) selector.render.memo = rectangles;
                $(grid.id + ' .OG-g-sel').remove();
                selector.render.memo.forEach(function (rectangle) {
                    $('
').css(rectangle.position).css(rectangle.dimensions)
                        .appendTo(grid.elements[rectangle.fixed ? 'fixed_body' : 'scroll_body']);
                });
            };
            selector.render.memo = null;
            selector.selection = function () {
                if (!selector.render.memo) return null;
                var bottom_right = selector.render.memo.rectangle.bottom_right,
                    top_left = selector.render.memo.rectangle.top_left,
                    row_start = Math.floor(top_left.top / grid.meta.row_height),
                    row_end = Math.floor(bottom_right.bottom / grid.meta.row_height),
                    lcv, scan = grid.meta.columns.scan.all, rows = [], cols = [];
                for (lcv = 0; lcv < scan.length; lcv += 1)
                    if (scan[lcv] <= bottom_right.right && scan[lcv] > top_left.left) cols.push(lcv);
                    else if (scan[lcv] > bottom_right.right) break;
                for (lcv = row_start; lcv < row_end; lcv += 1) rows.push(lcv);
                return {rows: rows, cols: cols};
            };
            // initialize
            grid.elements.parent[0].onselectstart = function () {return false;};
            grid.elements.parent.on('mousedown', mousedown_observer);
            grid.elements.scroll_body.on('scroll', scroll_observer(null));
        };
    }
});<|endoftext|>