<commit_before>(function() {

  function stateSetter(widget, state) {
    return function() {
      console.log('widget:',widget);
      widget.view.setState(state);
    };
  }

  RemoteStorage.Widget = function(remoteStorage) {
    this.rs = remoteStorage;
    this.view = new View;

    this.rs.on('ready', stateSetter(this, 'connected'));
    this.rs.on('disconnected', stateSetter(this, 'disconnected'));
    this.view.on('connect',
                 function(a){
                   console.log(this);
                   this.rs.connect(a);
                }.bind(this)
  )
  };

  RemoteStorage.Widget.prototype = {
    display: function() {
      this.view.display.apply(this.view, arguments);
      return this;
    }
  };

  RemoteStorage.prototype.displayWidget = function() {
    if(typeof(this.widget) === 'undefined')
      (this.widget = new RemoteStorage.Widget(this)).display();
    else
      this.widget.display();
  };

  RemoteStorage.Widget._rs_init = function(remoteStorage){
    window.addEventListener('load', function() {
      remoteStorage.displayWidget();
    });
  }

    function cEl(t){
    return document.createElement(t);
  }
  function gCl(parent, className){
    return parent.getElementsByClassName(className)[0];
  }
  function gTl(parent, className){
    return parent.getElementsByTagName(className)[0];
  }

  function toggle_bubble(widget){
    var el = gCl(widget,'bubble-expandable');
    if(el.style.display === 'none'){
      show(el);
    }else{
      hide(el);
    }
  }
  function show(el, display){
    if(typeof(display) === 'undefined'){
      display = 'block';
    }
    el.style.display = display
    return el;
  }
  function hide(el){
    show(el,'none');
    return el;
  }

  // MAYBE do those two in a el.className.split(' ') way more safe
  function removeClass(el, className){
    el.className = el.className.replace(' '+className+' ', ' ');
  }
  function addClass(el, className){
    el.className += ' '+className;
  }

  function View(){
    if(typeof(document) === 'undefined') {
      throw "Widget not supported";
    }
    RemoteStorage.eventHandling(this,
                                'connect',
                                'disconnect',
                                'sync',
                                'reconnect',
                                'display')

    this.display = function() {

        if( ! (typeof(this.widget) === 'undefined') )
          return this.widget;

        var element = cEl('div')
        var style = cEl('style');
        style.innerHTML = RemoteStorage.Assets.widgetCss;

        element.id="remotestorage-widget"

        element.innerHTML = RemoteStorage.Assets.widget;

        element.appendChild(style)
        document.body.appendChild(element);

      var el;
        //connect button
      cb = gCl(element,'connect')
      gTl(cb, 'img').src=RemoteStorage.Assets.connectIcon;
      console.log(this);
      cb.addEventListener('click', this.events.connect.bind(this));

        // input
      el = gTl(element, 'form').userAddress;
      el.addEventListener('keyup', function(event){

        if(event.target.value) cb.removeAttribute('disabled');
        else cb.setAttribute('disabled','disabled');

      })

        //the cube
      el = gCl(element, 'cube');
      el.src = RemoteStorage.Assets.remoteStorageIcon
      el.addEventListener('click',
                          function(){
                            toggle_bubble(this.widget)
                          }.bind(this)
                         )

      this.widget = element;

      this.states.initial.bind(this)()
      return this.widget;
    }

    this.setState = function(state){
      var s;
      if(typeof(this.states[state]) === 'undefined'){
  	throw "Bad State assigned to view"
      }
      this.states[state].call(this);

    }

    this.setUserAdress = function(addr){
      widget.userAdress = addr;
    }
  };

  View.prototype = {
     // States:
     //  initial      - not connected
     //  authing      - in auth flow
     //  connected    - connected to remote storage, not syncing at the moment
     //  busy         - connected, syncing at the moment
     //  offline      - connected, but no network connectivity
     //  error        - connected, but sync error happened
     //  unauthorized - connected, but request returned 401
    currentState : 'initial',
    states :  {
      initial : function(){
        this.widget.className = "remotestorage-state-initial"
      },
      authing : function(){
      },
      connected : function(){
        this.widget.className = "remotestorage-state-connected"
      },
      busy : function(){},
      offline : function(){},
      error : function(){},
      unauthorized : function(){}
    },
    events : {
      connect : function() {
        event.preventDefault();
        console.log('connect button clicked')
        this._emit('connect', gTl(this.widget, 'form').userAddress.value);
      }
    }
  }

  // // the view.
  // var view = defaultView;
  // // options passed to displayWidget
  // var widgetOptions = {};
  // // passed to display() to avoid circular deps
  // var remoteStorage;

  // var reconnectInterval = 1000;

  // var offlineTimer = null;

  // var viewState;

  // function calcReconnectInterval() {
  //   var i = reconnectInterval;
  //   if(reconnectInterval < 10000) {
  //     reconnectInterval *= 2;
  //   }
  //   return i;
  // }

  // var stateActions = {
  //   offline: function() {
  //     if(! offlineTimer) {
  //       offlineTimer = setTimeout(function() {
  //         offlineTimer = null;
  //         sync.fullSync().
  //           then(function() {
  //             schedule.enable();
  //           });
  //       }, calcReconnectInterval());
  //     }
  //   },
  //   connected: function() {
  //     if(offlineTimer) {
  //       clearTimeout(offlineTimer);
  //       offlineTimer = null;
  //     }
  //   }
  // };

  // function setState(state) {
  //   if(state === viewState) {
  //     return;
  //   }
  //   viewState = state;
  //   var action = stateActions[state];
  //   if(action) {
  //     action.apply(null, arguments);
  //   }
  //   view.setState.apply(view, arguments);
  //   events.emit('state', state);
  // }

  // function requestToken(authEndpoint) {
  //   logger.info('requestToken', authEndpoint);
  //   var redirectUri = (widgetOptions.redirectUri || view.getLocation());
  //   var state;
  //   var md = redirectUri.match(/^(.+)#(.*)$/);
  //   if(md) {
  //     redirectUri = md[1];
  //     state = md[2];
  //   }
  //   var clientId = util.hostNameFromUri(redirectUri);
  //   authEndpoint += authEndpoint.indexOf('?') > 0 ? '&' : '?';
  //   var params = [
  //     ['redirect_uri', redirectUri],
  //     ['client_id', clientId],
  //     ['scope', remoteStorage.access.scopeParameter],
  //     ['response_type', 'token']
  //   ];
  //   if(typeof(state) === 'string' && state.length > 0) {
  //     params.push(['state', state]);
  //   }
  //   authEndpoint += params.map(function(kv) {
  //     return kv[0] + '=' + encodeURIComponent(kv[1]);
  //   }).join('&');
  //   console.log('redirecting to', authEndpoint);
  //   return view.redirectTo(authEndpoint);
  // }

  // function connectStorage(userAddress) {
  //   settings.set('userAddress', userAddress);
  //   setState('authing');
  //   return webfinger.getStorageInfo(userAddress).
  //     then(remoteStorage.setStorageInfo, function(error) {
  //       if(error === 'timeout') {
  //         adjustTimeout();
  //       }
  //       setState((typeof(error) === 'string') ? 'typing' : 'error', error);
  //     }).
  //     then(function(storageInfo) {
  //       if(storageInfo) {
  //         requestToken(storageInfo.properties['auth-endpoint']);
  //         schedule.enable();
  //       }
  //     }, util.curry(setState, 'error'));
  // }

  // function reconnectStorage() {
  //   connectStorage(settings.get('userAddress'));
  // }

  // function disconnectStorage() {
  //   schedule.disable();
  //   remoteStorage.flushLocal();
  //   events.emit('state', 'disconnected');
  //   events.emit('disconnect');
  // }

  // // destructively parse query string from URI fragment
  // function parseParams() {
  //   var md = view.getLocation().match(/^(.*?)#(.*)$/);
  //   var result = {};
  //   if(md) {
  //     var hash = md[2];
  //     hash.split('&').forEach(function(param) {
  //       var kv = param.split('=');
  //       if(kv[1]) {
  //         result[kv[0]] = decodeURIComponent(kv[1]);
  //       }
  //     });
  //     if(Object.keys(result).length > 0) {
  //       view.setLocation(md[1] + '#');
  //     }
  //   }
  //   return result;
  // }

  // function processParams() {
  //   var params = parseParams();

  //   // Query parameter: access_token
  //   if(params.access_token) {
  //     wireClient.setBearerToken(params.access_token);
  //   }
  //   // Query parameter: remotestorage
  //   if(params.remotestorage) {
  //     view.setUserAddress(params.remotestorage);
  //     setTimeout(function() {
  //       if(wireClient.getState() !== 'connected') {
  //         connectStorage(params.remotestorage);
  //       }
  //     }, 0);
  //   } else {
  //     var userAddress = settings.get('userAddress');
  //     if(userAddress) {
  //       view.setUserAddress(userAddress);
  //     }
  //   }
  //   // Query parameter: state
  //   if(params.state) {
  //     view.setLocation(view.getLocation().split('#')[0] + '#' + params.state);
  //   }
  // }

  // function handleSyncError(error) {
  //   if(error.message === 'unauthorized') {
  //     setState('unauthorized');
  //   } else if(error.message === 'network error') {
  //     setState('offline', error);
  //   } else {
  //     setState('error', error);
  //   }
  // }

  // function adjustTimeout() {
  //   var t = getputdelete.getTimeout();
  //   if(t < maxTimeout) {
  //     t *= timeoutAdjustmentFactor;
  //     webfinger.setTimeout(t);
  //     getputdelete.setTimeout(t);
  //   }
  // }

  // function handleSyncTimeout() {
  //   adjustTimeout();
  //   schedule.disable();
  //   setState('offline');
  // }

  // function initialSync() {
  //   if(settings.get('initialSyncDone')) {
  //     schedule.enable();
  //     store.fireInitialEvents().then(util.curry(events.emit, 'ready'));
  //   } else {
  //     setState('busy', true);
  //     sync.fullSync().then(function() {
  //       schedule.enable();
  //       settings.set('initialSyncDone', true);
  //       setState('connected');
  //       events.emit('ready');
  //     }, handleSyncError);
  //   }
  // }

  // function display(_remoteStorage, element, options) {
  //   remoteStorage = _remoteStorage;
  //   widgetOptions = options;
  //   if(! options) {
  //     options = {};
  //   }

  //   options.getLastSyncAt = function() {
  //     return (sync.lastSyncAt || new Date()).getTime();
  //   };

  //   schedule.watch('/', 30000);

  //   view.display(element, options);

  //   view.on('sync', sync.forceSync);
  //   view.on('connect', connectStorage);
  //   view.on('disconnect', disconnectStorage);
  //   view.on('reconnect', reconnectStorage);

  //   wireClient.on('busy', util.curry(setState, 'busy'));
  //   wireClient.on('unbusy', util.curry(setState, 'connected'));
  //   wireClient.on('connected', function() {
  //     setState('connected');
  //     initialSync();
  //   });
  //   wireClient.on('disconnected', util.curry(setState, 'initial'));

  //   BaseClient.on('error', util.curry(setState, 'error'));
  //   sync.on('error', handleSyncError);
  //   sync.on('timeout', handleSyncTimeout);

  //   processParams();

  //   wireClient.calcState();
  // }

  // RemoteStorage.widget = util.extend({
  //   display : display,

  //   clearSettings: settings.clear,

  //   setView: function(_view) {
  //     view = _view;
  //   }
  // }, events);

})();
<commit_msg>widget: added missing 'event' parameter<commit_after>(function() {

  function stateSetter(widget, state) {
    return function() {
      console.log('widget:',widget);
      widget.view.setState(state);
    };
  }

  RemoteStorage.Widget = function(remoteStorage) {
    this.rs = remoteStorage;
    this.view = new View;

    this.rs.on('ready', stateSetter(this, 'connected'));
    this.rs.on('disconnected', stateSetter(this, 'disconnected'));
    this.view.on('connect',
                 function(a){
                   console.log(this);
                   this.rs.connect(a);
                }.bind(this)
  )
  };

  RemoteStorage.Widget.prototype = {
    display: function() {
      this.view.display.apply(this.view, arguments);
      return this;
    }
  };

  RemoteStorage.prototype.displayWidget = function() {
    if(typeof(this.widget) === 'undefined')
      (this.widget = new RemoteStorage.Widget(this)).display();
    else
      this.widget.display();
  };

  RemoteStorage.Widget._rs_init = function(remoteStorage){
    window.addEventListener('load', function() {
      remoteStorage.displayWidget();
    });
  }

    function cEl(t){
    return document.createElement(t);
  }
  function gCl(parent, className){
    return parent.getElementsByClassName(className)[0];
  }
  function gTl(parent, className){
    return parent.getElementsByTagName(className)[0];
  }

  function toggle_bubble(widget){
    var el = gCl(widget,'bubble-expandable');
    if(el.style.display === 'none'){
      show(el);
    }else{
      hide(el);
    }
  }
  function show(el, display){
    if(typeof(display) === 'undefined'){
      display = 'block';
    }
    el.style.display = display
    return el;
  }
  function hide(el){
    show(el,'none');
    return el;
  }

  // MAYBE do those two in a el.className.split(' ') way more safe
  function removeClass(el, className){
    el.className = el.className.replace(' '+className+' ', ' ');
  }
  function addClass(el, className){
    el.className += ' '+className;
  }

  function View(){
    if(typeof(document) === 'undefined') {
      throw "Widget not supported";
    }
    RemoteStorage.eventHandling(this,
                                'connect',
                                'disconnect',
                                'sync',
                                'reconnect',
                                'display')

    this.display = function() {

        if( ! (typeof(this.widget) === 'undefined') )
          return this.widget;

        var element = cEl('div')
        var style = cEl('style');
        style.innerHTML = RemoteStorage.Assets.widgetCss;

        element.id="remotestorage-widget"

        element.innerHTML = RemoteStorage.Assets.widget;

        element.appendChild(style)
        document.body.appendChild(element);

      var el;
        //connect button
      cb = gCl(element,'connect')
      gTl(cb, 'img').src=RemoteStorage.Assets.connectIcon;
      console.log(this);
      cb.addEventListener('click', this.events.connect.bind(this));

        // input
      el = gTl(element, 'form').userAddress;
      el.addEventListener('keyup', function(event){

        if(event.target.value) cb.removeAttribute('disabled');
        else cb.setAttribute('disabled','disabled');

      })

        //the cube
      el = gCl(element, 'cube');
      el.src = RemoteStorage.Assets.remoteStorageIcon
      el.addEventListener('click',
                          function(){
                            toggle_bubble(this.widget)
                          }.bind(this)
                         )

      this.widget = element;

      this.states.initial.bind(this)()
      return this.widget;
    }

    this.setState = function(state){
      var s;
      if(typeof(this.states[state]) === 'undefined'){
  	throw "Bad State assigned to view"
      }
      this.states[state].call(this);

    }

    this.setUserAdress = function(addr){
      widget.userAdress = addr;
    }
  };

  View.prototype = {
     // States:
     //  initial      - not connected
     //  authing      - in auth flow
     //  connected    - connected to remote storage, not syncing at the moment
     //  busy         - connected, syncing at the moment
     //  offline      - connected, but no network connectivity
     //  error        - connected, but sync error happened
     //  unauthorized - connected, but request returned 401
    currentState : 'initial',
    states :  {
      initial : function(){
        this.widget.className = "remotestorage-state-initial"
      },
      authing : function(){
      },
      connected : function(){
        this.widget.className = "remotestorage-state-connected"
      },
      busy : function(){},
      offline : function(){},
      error : function(){},
      unauthorized : function(){}
    },
    events : {
      connect : function(event) {
        event.preventDefault();
        console.log('connect button clicked')
        this._emit('connect', gTl(this.widget, 'form').userAddress.value);
      }
    }
  }

  // // the view.
  // var view = defaultView;
  // // options passed to displayWidget
  // var widgetOptions = {};
  // // passed to display() to avoid circular deps
  // var remoteStorage;

  // var reconnectInterval = 1000;

  // var offlineTimer = null;

  // var viewState;

  // function calcReconnectInterval() {
  //   var i = reconnectInterval;
  //   if(reconnectInterval < 10000) {
  //     reconnectInterval *= 2;
  //   }
  //   return i;
  // }

  // var stateActions = {
  //   offline: function() {
  //     if(! offlineTimer) {
  //       offlineTimer = setTimeout(function() {
  //         offlineTimer = null;
  //         sync.fullSync().
  //           then(function() {
  //             schedule.enable();
  //           });
  //       }, calcReconnectInterval());
  //     }
  //   },
  //   connected: function() {
  //     if(offlineTimer) {
  //       clearTimeout(offlineTimer);
  //       offlineTimer = null;
  //     }
  //   }
  // };

  // function setState(state) {
  //   if(state === viewState) {
  //     return;
  //   }
  //   viewState = state;
  //   var action = stateActions[state];
  //   if(action) {
  //     action.apply(null, arguments);
  //   }
  //   view.setState.apply(view, arguments);
  //   events.emit('state', state);
  // }

  // function requestToken(authEndpoint) {
  //   logger.info('requestToken', authEndpoint);
  //   var redirectUri = (widgetOptions.redirectUri || view.getLocation());
  //   var state;
  //   var md = redirectUri.match(/^(.+)#(.*)$/);
  //   if(md) {
  //     redirectUri = md[1];
  //     state = md[2];
  //   }
  //   var clientId = util.hostNameFromUri(redirectUri);
  //   authEndpoint += authEndpoint.indexOf('?') > 0 ? '&' : '?';
  //   var params = [
  //     ['redirect_uri', redirectUri],
  //     ['client_id', clientId],
  //     ['scope', remoteStorage.access.scopeParameter],
  //     ['response_type', 'token']
  //   ];
  //   if(typeof(state) === 'string' && state.length > 0) {
  //     params.push(['state', state]);
  //   }
  //   authEndpoint += params.map(function(kv) {
  //     return kv[0] + '=' + encodeURIComponent(kv[1]);
  //   }).join('&');
  //   console.log('redirecting to', authEndpoint);
  //   return view.redirectTo(authEndpoint);
  // }

  // function connectStorage(userAddress) {
  //   settings.set('userAddress', userAddress);
  //   setState('authing');
  //   return webfinger.getStorageInfo(userAddress).
  //     then(remoteStorage.setStorageInfo, function(error) {
  //       if(error === 'timeout') {
  //         adjustTimeout();
  //       }
  //       setState((typeof(error) === 'string') ? 'typing' : 'error', error);
  //     }).
  //     then(function(storageInfo) {
  //       if(storageInfo) {
  //         requestToken(storageInfo.properties['auth-endpoint']);
  //         schedule.enable();
  //       }
  //     }, util.curry(setState, 'error'));
  // }

  // function reconnectStorage() {
  //   connectStorage(settings.get('userAddress'));
  // }

  // function disconnectStorage() {
  //   schedule.disable();
  //   remoteStorage.flushLocal();
  //   events.emit('state', 'disconnected');
  //   events.emit('disconnect');
  // }

  // // destructively parse query string from URI fragment
  // function parseParams() {
  //   var md = view.getLocation().match(/^(.*?)#(.*)$/);
  //   var result = {};
  //   if(md) {
  //     var hash = md[2];
  //     hash.split('&').forEach(function(param) {
  //       var kv = param.split('=');
  //       if(kv[1]) {
  //         result[kv[0]] = decodeURIComponent(kv[1]);
  //       }
  //     });
  //     if(Object.keys(result).length > 0) {
  //       view.setLocation(md[1] + '#');
  //     }
  //   }
  //   return result;
  // }

  // function processParams() {
  //   var params = parseParams();

  //   // Query parameter: access_token
  //   if(params.access_token) {
  //     wireClient.setBearerToken(params.access_token);
  //   }
  //   // Query parameter: remotestorage
  //   if(params.remotestorage) {
  //     view.setUserAddress(params.remotestorage);
  //     setTimeout(function() {
  //       if(wireClient.getState() !== 'connected') {
  //         connectStorage(params.remotestorage);
  //       }
  //     }, 0);
  //   } else {
  //     var userAddress = settings.get('userAddress');
  //     if(userAddress) {
  //       view.setUserAddress(userAddress);
  //     }
  //   }
  //   // Query parameter: state
  //   if(params.state) {
  //     view.setLocation(view.getLocation().split('#')[0] + '#' + params.state);
  //   }
  // }

  // function handleSyncError(error) {
  //   if(error.message === 'unauthorized') {
  //     setState('unauthorized');
  //   } else if(error.message === 'network error') {
  //     setState('offline', error);
  //   } else {
  //     setState('error', error);
  //   }
  // }

  // function adjustTimeout() {
  //   var t = getputdelete.getTimeout();
  //   if(t < maxTimeout) {
  //     t *= timeoutAdjustmentFactor;
  //     webfinger.setTimeout(t);
  //     getputdelete.setTimeout(t);
  //   }
  // }

  // function handleSyncTimeout() {
  //   adjustTimeout();
  //   schedule.disable();
  //   setState('offline');
  // }

  // function initialSync() {
  //   if(settings.get('initialSyncDone')) {
  //     schedule.enable();
  //     store.fireInitialEvents().then(util.curry(events.emit, 'ready'));
  //   } else {
  //     setState('busy', true);
  //     sync.fullSync().then(function() {
  //       schedule.enable();
  //       settings.set('initialSyncDone', true);
  //       setState('connected');
  //       events.emit('ready');
  //     }, handleSyncError);
  //   }
  // }

  // function display(_remoteStorage, element, options) {
  //   remoteStorage = _remoteStorage;
  //   widgetOptions = options;
  //   if(! options) {
  //     options = {};
  //   }

  //   options.getLastSyncAt = function() {
  //     return (sync.lastSyncAt || new Date()).getTime();
  //   };

  //   schedule.watch('/', 30000);

  //   view.display(element, options);

  //   view.on('sync', sync.forceSync);
  //   view.on('connect', connectStorage);
  //   view.on('disconnect', disconnectStorage);
  //   view.on('reconnect', reconnectStorage);

  //   wireClient.on('busy', util.curry(setState, 'busy'));
  //   wireClient.on('unbusy', util.curry(setState, 'connected'));
  //   wireClient.on('connected', function() {
  //     setState('connected');
  //     initialSync();
  //   });
  //   wireClient.on('disconnected', util.curry(setState, 'initial'));

  //   BaseClient.on('error', util.curry(setState, 'error'));
  //   sync.on('error', handleSyncError);
  //   sync.on('timeout', handleSyncTimeout);

  //   processParams();

  //   wireClient.calcState();
  // }

  // RemoteStorage.widget = util.extend({
  //   display : display,

  //   clearSettings: settings.clear,

  //   setView: function(_view) {
  //     view = _view;
  //   }
  // }, events);

})();
<|endoftext|>


<commit_before>/*!
loadCSS: load a CSS file asynchronously.
[c]2014 @scottjehl, Filament Group, Inc.
Licensed MIT
*/

/* exported loadCSS */
function loadCSS( href, before, media, callback ){
	"use strict";
	// Arguments explained:
	// `href` is the URL for your CSS file.
	// `before` optionally defines the element we'll use as a reference for injecting our <link>
	// By default, `before` uses the first <script> element in the page.
	// However, since the order in which stylesheets are referenced matters, you might need a more specific location in your document.
	// If so, pass a different reference element to the `before` argument and it'll insert before that instead
	// note: `insertBefore` is used instead of `appendChild`, for safety re: http://www.paulirish.com/2011/surefire-dom-element-insertion/
	var ss = window.document.createElement( "link" );
	var ref = before || window.document.getElementsByTagName( "script" )[ 0 ];
	var sheets = window.document.styleSheets;
	ss.rel = "stylesheet";
	ss.href = href;
	// temporarily, set media to something non-matching to ensure it'll fetch without blocking render
	ss.media = "only x";
	// DEPRECATED
	if( callback ) {
		ss.onload = callback;
	}

	// inject link
	ref.parentNode.insertBefore( ss, ref );
	// This function sets the link's media back to `all` so that the stylesheet applies once it loads
	// It is designed to poll until document.styleSheets includes the new sheet.
	ss.onloadcssdefined = function( cb ){
		var defined;
		var i = sheets.length;
		while( i-- ){
			if( sheets[ i ].href && sheets[ i ].href === ss.href ){
				defined = true;
				break;
			}
		}
		if( defined ){
			cb();
		} else {
			setTimeout(function() {
				ss.onloadcssdefined( cb );
			});
		}
	};
	ss.onloadcssdefined(function() {
		ss.media = media || "all";
	});
	return ss;
}
<commit_msg>optimise: Simplify by returning early from the loop<commit_after>/*!
loadCSS: load a CSS file asynchronously.
[c]2014 @scottjehl, Filament Group, Inc.
Licensed MIT
*/

/* exported loadCSS */
function loadCSS( href, before, media, callback ){
	"use strict";
	// Arguments explained:
	// `href` is the URL for your CSS file.
	// `before` optionally defines the element we'll use as a reference for injecting our <link>
	// By default, `before` uses the first <script> element in the page.
	// However, since the order in which stylesheets are referenced matters, you might need a more specific location in your document.
	// If so, pass a different reference element to the `before` argument and it'll insert before that instead
	// note: `insertBefore` is used instead of `appendChild`, for safety re: http://www.paulirish.com/2011/surefire-dom-element-insertion/
	var ss = window.document.createElement( "link" );
	var ref = before || window.document.getElementsByTagName( "script" )[ 0 ];
	var sheets = window.document.styleSheets;
	ss.rel = "stylesheet";
	ss.href = href;
	// temporarily, set media to something non-matching to ensure it'll fetch without blocking render
	ss.media = "only x";
	// DEPRECATED
	if( callback ) {
		ss.onload = callback;
	}

	// inject link
	ref.parentNode.insertBefore( ss, ref );
	// This function sets the link's media back to `all` so that the stylesheet applies once it loads
	// It is designed to poll until document.styleSheets includes the new sheet.
	ss.onloadcssdefined = function( cb ){
		var i = sheets.length;
		while( i-- ){
			if( sheets[ i ].href && sheets[ i ].href === ss.href ){
				cb();
				return;
			}
		}
		// Try again later
		setTimeout(function() {
			ss.onloadcssdefined( cb );
		});
	};
	ss.onloadcssdefined(function() {
		ss.media = media || "all";
	});
	return ss;
}
<|endoftext|>


<commit_before>/*!
loadCSS: load a CSS file asynchronously.
[c]2015 @scottjehl, Filament Group, Inc.
Licensed MIT
*/

/* exported loadCSS */
function loadCSS( href, before, media ){
	"use strict";
	// Arguments explained:
	// `href` [REQUIRED] is the URL for your CSS file.
	// `before` [OPTIONAL] is the element the script should use as a reference for injecting our stylesheet <link> before
		// By default, loadCSS attempts to inject the link after the last stylesheet or script in the DOM. However, you might desire a more specific location in your document.
	// `media` [OPTIONAL] is the media type or query of the stylesheet. By default it will be 'all'
	var ss = window.document.createElement( "link" );
	var ref;
	if( before ){
		ref = before;
	}
	else if( window.document.querySelectorAll ){
		var refs = window.document.querySelectorAll(  "style,link[rel=stylesheet],script" );
		// No need to check length. This script has a parent element, at least
		ref = refs[ refs.length - 1];
	}
	else {
		ref = window.document.getElementsByTagName( "script" )[ 0 ];
	}

	var sheets = window.document.styleSheets;
	ss.rel = "stylesheet";
	ss.href = href;
	// temporarily set media to something inapplicable to ensure it'll fetch without blocking render
	ss.media = "only x";

	// Inject link
		// Note: the ternary preserves the existing behavior of "before" argument, but we could choose to change the argument to "after" in a later release and standardize on ref.nextSibling for all refs
		// Note: `insertBefore` is used instead of `appendChild`, for safety re: http://www.paulirish.com/2011/surefire-dom-element-insertion/
	ref.parentNode.insertBefore( ss, ( before ? ref : ref.nextSibling ) );
	// A method (exposed on return object for external use) that mimics onload by polling until window.document.styleSheets until it includes the new sheet.
	ss.onloadcssdefined = function( cb ){
		var defined;
		for( var i = 0; i < sheets.length; i++ ){
			if( sheets[ i ].href && sheets[ i ].href === ss.href ){
				defined = true;
			}
		}
		if( defined ){
			cb();
		} else {
			setTimeout(function() {
				ss.onloadcssdefined( cb );
			});
		}
	};

	// once loaded, set link's media back to `all` so that the stylesheet applies once it loads
	ss.onloadcssdefined(function() {
		ss.media = media || "all";
	});
	return ss;
}
<commit_msg>iffe and w reference. fixes #91<commit_after>/*!
loadCSS: load a CSS file asynchronously.
[c]2015 @scottjehl, Filament Group, Inc.
Licensed MIT
*/
(function(w){
	"use strict";
	/* exported loadCSS */
	w.loadCSS = function( href, before, media ){
		// Arguments explained:
		// `href` [REQUIRED] is the URL for your CSS file.
		// `before` [OPTIONAL] is the element the script should use as a reference for injecting our stylesheet <link> before
			// By default, loadCSS attempts to inject the link after the last stylesheet or script in the DOM. However, you might desire a more specific location in your document.
		// `media` [OPTIONAL] is the media type or query of the stylesheet. By default it will be 'all'
		var ss = w.document.createElement( "link" );
		var ref;
		if( before ){
			ref = before;
		}
		else if( w.document.querySelectorAll ){
			var refs = w.document.querySelectorAll(  "style,link[rel=stylesheet],script" );
			// No need to check length. This script has a parent element, at least
			ref = refs[ refs.length - 1];
		}
		else {
			ref = w.document.getElementsByTagName( "script" )[ 0 ];
		}

		var sheets = w.document.styleSheets;
		ss.rel = "stylesheet";
		ss.href = href;
		// temporarily set media to something inapplicable to ensure it'll fetch without blocking render
		ss.media = "only x";

		// Inject link
			// Note: the ternary preserves the existing behavior of "before" argument, but we could choose to change the argument to "after" in a later release and standardize on ref.nextSibling for all refs
			// Note: `insertBefore` is used instead of `appendChild`, for safety re: http://www.paulirish.com/2011/surefire-dom-element-insertion/
		ref.parentNode.insertBefore( ss, ( before ? ref : ref.nextSibling ) );
		// A method (exposed on return object for external use) that mimics onload by polling until document.styleSheets until it includes the new sheet.
		ss.onloadcssdefined = function( cb ){
			var defined;
			for( var i = 0; i < sheets.length; i++ ){
				if( sheets[ i ].href && sheets[ i ].href === ss.href ){
					defined = true;
				}
			}
			if( defined ){
				cb();
			} else {
				setTimeout(function() {
					ss.onloadcssdefined( cb );
				});
			}
		};

		// once loaded, set link's media back to `all` so that the stylesheet applies once it loads
		ss.onloadcssdefined(function() {
			ss.media = media || "all";
		});
		return ss;
	};
}(this));
<|endoftext|>


<commit_before>// please ignore any magic, magic can be resolved at xia.umd@gmail.com

var nodemailer = require('nodemailer');
var Q = require('q');
var config = require('./config.js');
var knex = require('knex')({
  dialect: 'mysql',
  connection: config.mysql,
  debug: false
});

GetYesterdayMentions().then(function(mentions){

    var output = '
';
    for(var i in mentions) {
        output +=   '
' +
                    '' + mentions[i].framework + '	' +
                    ''+ mentions[i].count + '	' +
                    '
'
    }
    output += '
'

    var mailOptions = config.mailman;

    // send mail with defined transport object
    transporter.sendMail(mailOptions, function(error, info){
        if(error){
            console.log(error);
        }else{
            console.log('Message sent: ' + info.response);
            process.exit(1);
        }
    });
});

// create reusable transporter object using SMTP transport
var transporter = nodemailer.createTransport({
    service: 'Gmail',
    auth: config.gmailAuth
});

function GetYesterdayMentions() {
    var today = new Date();
    var start = new Date(1900 + today.getYear(), today.getMonth(), today.getDate()-1, 1).getTime() * 0.001;
    var end = new Date(1900 + today.getYear(), today.getMonth(), today.getDate(), 1).getTime() * 0.001;
    return knex('tweets')
    .distinct('flag').select()
    .then(function(targets){
        var promises = [];
        for (var index in targets){
            promises.push(_countMentions(targets[index].flag, start, end));
        }
        return Q.all(promises);
    });
}

function _yesterdayDate(){
    var today = new Date();
    //javascript has date values 0 indexed lol.
    return (today.getMonth()+1) + "/" + (today.getDate()-1);
}

function _countMentions(framework, start, end) {
    return knex('tweets').count('*')
    .where('created_at', '>', start)
    .where('created_at', '<', end)
    .where('flag', '=', framework)
    .then(function(row){
        return {
            count: row[0]['count(*)'],
            framework: framework
        }
    });
}
<commit_msg>moved date to mailman script woops<commit_after>// please ignore any magic, magic can be resolved at xia.umd@gmail.com

var nodemailer = require('nodemailer');
var Q = require('q');
var config = require('./config.js');
var knex = require('knex')({
  dialect: 'mysql',
  connection: config.mysql,
  debug: false
});

GetYesterdayMentions().then(function(mentions){

    var output = '
';
    for(var i in mentions) {
        output +=   '
' +
                    '' + mentions[i].framework + '	' +
                    ''+ mentions[i].count + '	' +
                    '
'
    }
    output += '
'

    var mailOptions = config.mailman;
    mailOptions.subject = 'Twitter Mentions ' + _yesterdayDate(),

    // send mail with defined transport object
    transporter.sendMail(mailOptions, function(error, info){
        if(error){
            console.log(error);
        }else{
            console.log('Message sent: ' + info.response);
            process.exit(1);
        }
    });
});

// create reusable transporter object using SMTP transport
var transporter = nodemailer.createTransport({
    service: 'Gmail',
    auth: config.gmailAuth
});

function GetYesterdayMentions() {
    var today = new Date();
    var start = new Date(1900 + today.getYear(), today.getMonth(), today.getDate()-1, 1).getTime() * 0.001;
    var end = new Date(1900 + today.getYear(), today.getMonth(), today.getDate(), 1).getTime() * 0.001;
    return knex('tweets')
    .distinct('flag').select()
    .then(function(targets){
        var promises = [];
        for (var index in targets){
            promises.push(_countMentions(targets[index].flag, start, end));
        }
        return Q.all(promises);
    });
}

function _yesterdayDate(){
    var today = new Date();
    //javascript has date values 0 indexed lol.
    return (today.getMonth()+1) + "/" + (today.getDate()-1);
}

function _countMentions(framework, start, end) {
    return knex('tweets').count('*')
    .where('created_at', '>', start)
    .where('created_at', '<', end)
    .where('flag', '=', framework)
    .then(function(row){
        return {
            count: row[0]['count(*)'],
            framework: framework
        }
    });
}
<|endoftext|>


<commit_before>var rfam = {
    bindings: {
        upi: '<',
        rna: '<',
        rfamHits: '<',
        toggleGoModal: '&'
    },

    controller: ['$http', '$interpolate', 'routes', function($http, $interpolate, routes) {
        var ctrl = this;

        ctrl.$onInit = function() {
            ctrl.help = "https://rnacentral.org/help/rfam-annotations";

            // group hits with same rfam_model_id
            ctrl.groupedHits = [];
            ctrl.rfamHits.forEach(function(hit) {
                var existingHit = ctrl.groupedHits.find(function(existingHit) {
                    return existingHit.rfam_model_id === hit.rfam_model_id;
                });
                if (existingHit) {
                    existingHit.raw.push(hit);
                    existingHit.ranges.push([hit.sequence_start, hit.sequence_stop, hit.sequence_completeness]);
                } else {
                    ctrl.groupedHits.push({
                        raw: [hit],
                        ranges: [[hit.sequence_start, hit.sequence_stop, hit.sequence_completeness]],
                        rfam_model: hit.rfam_model,
                        rfam_model_id: hit.rfam_model.rfam_model_id
                    });
                }

            });
        };

    }],

    templateUrl: '/static/js/components/sequence/rfam/rfam.html'
};

angular.module("rnaSequence").component("rfam", rfam);<commit_msg>Make Rfam help url relative<commit_after>var rfam = {
    bindings: {
        upi: '<',
        rna: '<',
        rfamHits: '<',
        toggleGoModal: '&'
    },

    controller: ['$http', '$interpolate', 'routes', function($http, $interpolate, routes) {
        var ctrl = this;

        ctrl.$onInit = function() {
            ctrl.help = "/help/rfam-annotations";

            // group hits with same rfam_model_id
            ctrl.groupedHits = [];
            ctrl.rfamHits.forEach(function(hit) {
                var existingHit = ctrl.groupedHits.find(function(existingHit) {
                    return existingHit.rfam_model_id === hit.rfam_model_id;
                });
                if (existingHit) {
                    existingHit.raw.push(hit);
                    existingHit.ranges.push([hit.sequence_start, hit.sequence_stop, hit.sequence_completeness]);
                } else {
                    ctrl.groupedHits.push({
                        raw: [hit],
                        ranges: [[hit.sequence_start, hit.sequence_stop, hit.sequence_completeness]],
                        rfam_model: hit.rfam_model,
                        rfam_model_id: hit.rfam_model.rfam_model_id
                    });
                }

            });
        };

    }],

    templateUrl: '/static/js/components/sequence/rfam/rfam.html'
};

angular.module("rnaSequence").component("rfam", rfam);
<|endoftext|>


<commit_before>'use strict';

var toNatural            = require('es5-ext/number/to-pos-integer')
  , object               = require('es5-ext/object/valid-object')
  , value                = require('es5-ext/object/valid-value')
  , memoize              = require('memoizee/plain')
  , ObservableValue      = require('observable-value')
  , ObservableSet        = require('observable-set')
  , ReactiveTable        = require('reactive-table')
  , ReactiveList         = require('reactive-table/list')
  , location             = require('mano/lib/client/location')
  , db                   = require('mano').db
  , fixLocationQuery     = require('../../utils/fix-location-query')
  , serializeSnapshotKey = require('../../utils/serialize-to-snapshot-key')
  , getFilter            = require('../../utils/get-users-filter')
  , Pagination            = require('./pagination')

  , ceil = Math.ceil, create = Object.create, keys = Object.keys;

var resolveUsers = function (value) {
	if (!value) return [];
	return value.split(',').map(function (id) {
		return db.objects.unserialize(id, db.User);
	});
};
var getUsersSnapshot = memoize(function (observable) {
	var set = new ObservableSet(resolveUsers(observable.value));
	observable.on('change', function (event) {
		set._postponed_ += 1;
		set.clear();
		resolveUsers(event.newValue).forEach(set.add, set);
		set._postponed_ -= 1;
	});
	return set;
}, { normalize: function (args) { return args[0].dbId; } });

module.exports = function (snapshots, options) {
	var list, table, pagination, i18n, columns
	  , statusQuery, searchQuery, pathname, pageLimit, statusMap
	  , active, update, appName, pageQuery, inSync, isPartial
	  , allUsers;

	var getPageCount = function (value) {
		if (!value) return 1;
		return ceil(value / pageLimit);
	};
	object(options);
	columns = object(options.columns);
	i18n = options.i18n ? object(options.i18n) : create(null);
	appName = value(options.appName);
	pathname = value(options.pathname);
	value(options.cacheLimits);
	pageLimit = options.cacheLimits.usersPerPage;
	statusMap = object(options.users);
	inSync = new ObservableValue(true);
	allUsers = statusMap[i18n.all || 'all'] || statusMap[''];
	isPartial = allUsers._size.map(function (value) {
		return value > options.cacheLimits.listedUsers;
	});

	update = function () {
		var status, search, normalizedSearch, page, snapshot, usersSnapshot
		  , snapshotTokens, snapshotKey, maxPage, users;
		if (!active) return;
		snapshotTokens = [appName];

		// Resolve status
		if (statusQuery) {
			if (statusQuery.value && !statusMap[statusQuery.value]) {
				fixLocationQuery(i18n.status || 'status');
			} else {
				status = statusQuery.value || '';
			}
			users = statusMap[status];
			if (status) snapshotTokens.push(status);
		} else {
			users = statusMap[''];
		}

		// Resolve search
		if (searchQuery) {
			search = searchQuery.value;
			if (search != null) {
				normalizedSearch = search.trim().toLowerCase();
				if (search !== normalizedSearch) {
					search = normalizedSearch;
					fixLocationQuery(i18n.search || 'search', search || null);
				}
			}
			if (search) {
				users = users.filter(getFilter(search));
				snapshotTokens.push(search);
			}
		}
		snapshot = db.User.dataSnapshots.get(serializeSnapshotKey(snapshotTokens));

		pagination.count.value = isPartial.value
			? snapshot._totalSize.map(getPageCount) : users._size.map(getPageCount);
		maxPage = pagination.count.value;

		// Resolve page
		if (pageQuery.value != null) {
			page = toNatural(pageQuery.value) || null;
			if (page === 1) page = null;
			if (page) {
				if (maxPage < page) page = (maxPage > 1) ? maxPage : null;
			}
			if (page) page = String(page);
			if (page !== pageQuery.value) fixLocationQuery(i18n.page || 'page', page);
			if (page) page = Number(page);
		}
		pagination.current.value = page || 1;

		// Update table
		if (isPartial.value) {
			// We rely on snapshots functionality
			snapshotTokens.unshift(page);
			// Inform remote
			snapshotKey = serializeSnapshotKey(snapshotTokens);
			if (snapshots.last !== snapshotKey) snapshots.add(snapshotKey);
			if (page) {
				// Rely on remote prepared snapshot
				usersSnapshot = getUsersSnapshot(snapshot._get(page));
				inSync.value = usersSnapshot._size.gt(0);
				list.set = usersSnapshot;
				list.page = 1;
				return;
			}
			inSync.value = snapshot._totalSize.map(function (value) {
				if (value == null) return false;
				return users._size.gtOrEq(value > pageLimit ? pageLimit : value);
			});
		}
		list.set = users;
		list.page = page || 1;
		inSync.value = true;
	};

	// Setup
	// Status filter
	if (keys(statusMap).length > 1) {
		statusQuery = location.query.get(i18n.status || 'status');
		statusQuery.on('change', update);
	}

	// Search filter
	if (options.searchFilter) {
		searchQuery = location.query.get(i18n.search || 'search');
		searchQuery.on('change', update);
	}

	// Pagination
	pageQuery = location.query.get(i18n.page || 'page');
	pageQuery.on('change', update);

	// Table configuration
	list = new ReactiveList(statusMap[''], options.compare);
	list.limit = pageLimit;
	table = new ReactiveTable(document, list, columns);
	table.pagination = pagination = new Pagination(pathname);

	table.inSync = inSync;
	inSync.on('change', function (event) {
		table.table.classList[event.newValue ? 'remove' : 'add']('not-in-sync');
	});

	if (options.id) table.table.id = options.id;
	if (options.class) table.table.className = options.class;

	location.on('change', function () {
		active = (this.pathname === pathname);
		update();
	});
	active = location.pathname === pathname;

	isPartial.on('change', update);
	window.addEventListener('focus', update, false);

	update();
	return table;
};
<commit_msg>Fix isPartial resolution<commit_after>'use strict';

var toNatural            = require('es5-ext/number/to-pos-integer')
  , object               = require('es5-ext/object/valid-object')
  , value                = require('es5-ext/object/valid-value')
  , memoize              = require('memoizee/plain')
  , ObservableValue      = require('observable-value')
  , ObservableSet        = require('observable-set')
  , ReactiveTable        = require('reactive-table')
  , ReactiveList         = require('reactive-table/list')
  , location             = require('mano/lib/client/location')
  , db                   = require('mano').db
  , fixLocationQuery     = require('../../utils/fix-location-query')
  , serializeSnapshotKey = require('../../utils/serialize-to-snapshot-key')
  , getFilter            = require('../../utils/get-users-filter')
  , Pagination            = require('./pagination')

  , ceil = Math.ceil, create = Object.create, keys = Object.keys;

var resolveUsers = function (value) {
	if (!value) return [];
	return value.split(',').map(function (id) {
		return db.objects.unserialize(id, db.User);
	});
};
var getUsersSnapshot = memoize(function (observable) {
	var set = new ObservableSet(resolveUsers(observable.value));
	observable.on('change', function (event) {
		set._postponed_ += 1;
		set.clear();
		resolveUsers(event.newValue).forEach(set.add, set);
		set._postponed_ -= 1;
	});
	return set;
}, { normalize: function (args) { return args[0].dbId; } });

module.exports = function (snapshots, options) {
	var list, table, pagination, i18n, columns
	  , statusQuery, searchQuery, pathname, pageLimit, statusMap
	  , active, update, appName, pageQuery, inSync, isPartial;

	var getPageCount = function (value) {
		if (!value) return 1;
		return ceil(value / pageLimit);
	};
	object(options);
	columns = object(options.columns);
	i18n = options.i18n ? object(options.i18n) : create(null);
	appName = value(options.appName);
	pathname = value(options.pathname);
	value(options.cacheLimits);
	pageLimit = options.cacheLimits.usersPerPage;
	statusMap = object(options.users);
	inSync = new ObservableValue(true);
	isPartial = (function () {
		var snapshotTokens = [appName];
		if (statusMap[i18n.all || 'all']) snapshotTokens.push(i18n.all || 'all');
		return db.User.dataSnapshots.get(serializeSnapshotKey(snapshotTokens))
			._totalSize.map(function (value) { return value > options.cacheLimits.listedUsers; });
	}());

	update = function () {
		var status, search, normalizedSearch, page, snapshot, usersSnapshot
		  , snapshotTokens, snapshotKey, maxPage, users;
		if (!active) return;
		snapshotTokens = [appName];

		// Resolve status
		if (statusQuery) {
			if (statusQuery.value && !statusMap[statusQuery.value]) {
				fixLocationQuery(i18n.status || 'status');
			} else {
				status = statusQuery.value || '';
			}
			users = statusMap[status];
			if (status) snapshotTokens.push(status);
		} else {
			users = statusMap[''];
		}

		// Resolve search
		if (searchQuery) {
			search = searchQuery.value;
			if (search != null) {
				normalizedSearch = search.trim().toLowerCase();
				if (search !== normalizedSearch) {
					search = normalizedSearch;
					fixLocationQuery(i18n.search || 'search', search || null);
				}
			}
			if (search) {
				users = users.filter(getFilter(search));
				snapshotTokens.push(search);
			}
		}
		snapshot = db.User.dataSnapshots.get(serializeSnapshotKey(snapshotTokens));

		pagination.count.value = isPartial.value
			? snapshot._totalSize.map(getPageCount) : users._size.map(getPageCount);
		maxPage = pagination.count.value;

		// Resolve page
		if (pageQuery.value != null) {
			page = toNatural(pageQuery.value) || null;
			if (page === 1) page = null;
			if (page) {
				if (maxPage < page) page = (maxPage > 1) ? maxPage : null;
			}
			if (page) page = String(page);
			if (page !== pageQuery.value) fixLocationQuery(i18n.page || 'page', page);
			if (page) page = Number(page);
		}
		pagination.current.value = page || 1;

		// Update table
		if (isPartial.value) {
			// We rely on snapshots functionality
			snapshotTokens.unshift(page);
			// Inform remote
			snapshotKey = serializeSnapshotKey(snapshotTokens);
			if (snapshots.last !== snapshotKey) snapshots.add(snapshotKey);
			if (page) {
				// Rely on remote prepared snapshot
				usersSnapshot = getUsersSnapshot(snapshot._get(page));
				inSync.value = usersSnapshot._size.gt(0);
				list.set = usersSnapshot;
				list.page = 1;
				return;
			}
			inSync.value = snapshot._totalSize.map(function (value) {
				if (value == null) return false;
				return users._size.gtOrEq(value > pageLimit ? pageLimit : value);
			});
		}
		list.set = users;
		list.page = page || 1;
		inSync.value = true;
	};

	// Setup
	// Status filter
	if (keys(statusMap).length > 1) {
		statusQuery = location.query.get(i18n.status || 'status');
		statusQuery.on('change', update);
	}

	// Search filter
	if (options.searchFilter) {
		searchQuery = location.query.get(i18n.search || 'search');
		searchQuery.on('change', update);
	}

	// Pagination
	pageQuery = location.query.get(i18n.page || 'page');
	pageQuery.on('change', update);

	// Table configuration
	list = new ReactiveList(statusMap[''], options.compare);
	list.limit = pageLimit;
	table = new ReactiveTable(document, list, columns);
	table.pagination = pagination = new Pagination(pathname);

	table.inSync = inSync;
	inSync.on('change', function (event) {
		table.table.classList[event.newValue ? 'remove' : 'add']('not-in-sync');
	});

	if (options.id) table.table.id = options.id;
	if (options.class) table.table.className = options.class;

	location.on('change', function () {
		active = (this.pathname === pathname);
		update();
	});
	active = location.pathname === pathname;

	isPartial.on('change', update);
	window.addEventListener('focus', update, false);

	update();
	return table;
};
<|endoftext|>


<commit_before>// Base view for user registration (Part A)

'use strict';

var location = require('mano/lib/client/location');

exports._parent = require('./user-base');

exports._match = 'businessProcess';

exports['sub-main'] = function () {

	var mobileCheckbox;

	div({ class: 'user-steps-menu-fixed-top-placeholder' },
		nav({ id: 'user-steps-menu', class: 'user-steps-menu', fixed: true },
			div({ class: 'content user-steps-menu-wrapper' },
				label({ class: 'user-steps-menu-show', for: 'show-steps-control' }, "Steps"),
				mobileCheckbox = input({ id: 'show-steps-control', type: 'checkbox', role: 'button' }
					), ul({ class: 'user-steps-menu-list' }, exports._stepsMenu(this)))));
	div({ class: 'content user-forms', id: 'step' });

	location.on('change', function () {
		mobileCheckbox.checked = false;
	});

};

exports._stepsMenu = Function.prototype;
<commit_msg>Added default registration menu. #702<commit_after>// Base view for user registration (Part A)

'use strict';

var location = require('mano/lib/client/location'),
_  = require('mano').i18n.bind('Registration'),
setProgressWidth = require('eregistrations/view/utils/set-progress-width');

exports._parent = require('./user-base');

exports._match = 'businessProcess';

exports['sub-main'] = function () {

	var mobileCheckbox;

	div({ class: 'user-steps-menu-fixed-top-placeholder' },
		nav({ id: 'user-steps-menu', class: 'user-steps-menu', fixed: true },
			div({ class: 'content user-steps-menu-wrapper' },
				label({ class: 'user-steps-menu-show', for: 'show-steps-control' }, "Steps"),
				mobileCheckbox = input({ id: 'show-steps-control', type: 'checkbox', role: 'button' }
					), ul({ class: 'user-steps-menu-list' }, exports._stepsMenu(this)))));
	div({ class: 'content user-forms', id: 'step' });

	location.on('change', function () {
		mobileCheckbox.checked = false;
	});

};

exports._stepsMenu = function () {
	return [
		li(
			{ class: 'user-steps-menu-start-step' },
			a({ href: '/guide/', id: 'step-guide' },
				_("1. Guide")),
			div({ class: 'user-steps-menu-item-progress',
				style: mmap(this.businessProcess._guideProgress, setProgressWidth) })
		),
		li(
			a({ href: '/forms/', id: 'step-form' },
				_("2. Fill the form")
				),
			div({ class: 'user-steps-menu-item-progress',
				style: mmap(this.businessProcess._dataForms.progress, setProgressWidth) })
		),
		li(
			a({ href: '/documents/', id: 'step-documents' },
				_("3. Upload docs")
				),
			div({ class: 'user-steps-menu-item-progress',
				style: mmap(this.businessProcess._requirementUploads.progress, setProgressWidth) })
		),
		li(
			a(_("4. Pay")
				),
			div({ class: 'user-steps-menu-item-progress',
				style: mmap(this.businessProcess._costs.onlinePaymentProgress, setProgressWidth) })
		),
		li(
			a({ href: '/submission/', id: 'step-submission' },
				_("5. Send file")
				),
			div({ class: 'user-steps-menu-item-progress',
				style: mmap(this.businessProcess._submissionForms.progress, setProgressWidth) })
		)];
};
<|endoftext|>


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

const MAPSKEY = config.MAPS_KEY
let neighborhood = [null , null];
let currentCategory = "all";

/* Calls addUIClickHandlers and getUserNeighborhood once page has loaded */
if (document.readyState === 'loading') {
    // adds on load event listeners if document hasn't yet loaded
    document.addEventListener('DOMContentLoaded', addUIClickHandlers)
    document.addEventListener('DOMContentLoaded', getUserNeighborhood);
} else {
    // if DOMContentLoaded has already fired, it simply calls the functions
    addUIClickHandlers();
    getUserNeighborhood();
}

/* Function adds all the necessary UI 'click' event listeners*/
function addUIClickHandlers() {
    // adds showModal and closeModal click events for the add task button
    if (document.body.contains(document.getElementById("addtaskbutton"))) {
        document.getElementById("addtaskbutton").addEventListener("click", showModal);
    	document.getElementById("close-button").addEventListener("click", closeModal);
    }

	// adds filterTasksBy click event listener to category buttons
	const categoryButtons = document.getElementsByClassName("categories");
    for (let i = 0; i < categoryButtons.length; i++) {
        categoryButtons[i].addEventListener("click", function(e) {
            filterTasksBy(e.target.id);
        });
    }
}

/* Function filters tasks by categories and styles selected categories */
function filterTasksBy(category) {
    currentCategory = category;

    // only fetches tasks if user's neighborhood has been retrieved
    if (JSON.stringify(neighborhood) != JSON.stringify([null, null])) {
        fetchTasks(category)
            .then(response => displayTasks(response));
    }
	// Unhighlights and resets styling for all category buttons
    const categoryButtons = document.getElementsByClassName("categories");
    for (let i = 0; i < categoryButtons.length; i++){
        let button = categoryButtons[i];
        if (document.getElementById(category) != button) {
            button.style.backgroundColor = "transparent";
    		button.style.color = "#222";
        	button.style.fontWeight = "normal";
        	button.addEventListener("mouseover", function() {
                button.style.backgroundColor = "lightgray";
            });
            button.addEventListener("mouseout", function() {
                button.style.backgroundColor = "transparent"
            });
        } else {
            button.style.backgroundColor = "#222";
        	button.style.color = "white";
        	button.style.fontWeight = "bold";
            button.addEventListener("mouseover", function() {
                button.style.backgroundColor = "#222";
            });
            button.addEventListener("mouseout", function() {
                button.style.backgroundColor = "#222"
            });
        }
    }
}

/* Function that display the help out overlay */
function helpOut(element) {
    const task = element.closest(".task");
    const overlay = task.getElementsByClassName("help-overlay");
    overlay[0].style.display = "block";
}

/* Function that hides the task after user confirms they want to help out */
function confirmHelp(element) {
    const url = "tasks/edit?key=" + element.dataset.key;
    const request = new Request(url, {method: "POST"});
    fetch(request).then(() => {
        if (JSON.stringify(neighborhood) != JSON.stringify([null, null])) {
            fetchTasks(currentCategory).then(response => displayTasks(response));
        }
    });
}

/* Function that hides the help out overlay */
function exitHelp(element) {
	element.closest(".help-overlay").style.display = "none";
}

/* Leonard's implementation of the Add Task modal */
function showModal() {
    var modal = document.getElementById("createTaskModalWrapper");
    modal.style.display = "block";
}
function closeModal() {
    var modal = document.getElementById("createTaskModalWrapper");
    modal.style.display = "none";
}
// If the user clicks outside of the modal, closes the modal directly
window.onclick = function(event) {
    var modal = document.getElementById("createTaskModalWrapper");
    if (event.target == modal) {
        modal.style.display = "none";
    }
}

/* Function dynamically adds Maps API and
begins the processes of retrieving the user's neighborhood*/
function getUserNeighborhood() {
    const script = document.createElement("script");
    script.type = "text/javascript";
    script.src =  "https://maps.googleapis.com/maps/api/js?key=" + MAPSKEY + "&callback=initialize";
    script.defer = true;
    script.async = true;
    document.head.appendChild(script);

    // Once the Maps API script has dynamically loaded it gets the user location,
    // waits until it gets an answer and then calls toNeighborhood passing the location
    // as an argument, updates the global neighborhood variable and then calls
    // fetchTasks and displayTasks
	window.initialize = function () {
        getUserLocation().then(location => toNeighborhood(location))
        	.then(() => fetchTasks())
            .then((response) => displayTasks(response))
            .catch(() => {
                console.error("User location and/or neighborhood could not be retrieved");
                document.getElementById("location-missing-message").style.display = "block";
            });
	}
}

/* Function that returns a promise to get and return the user's location */
 function getUserLocation() {
    return new Promise((resolve, reject) => {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(function(position) {
                var location = {lat: position.coords.latitude, lng: position.coords.longitude};
                resolve(location);
            }, function() {
                reject("User location failed");
            });
        } else {
            reject("User location is not supported by this browser");
        }
    });
}

/* Function that returns a promise to return a neighborhood
array that includes the postal code and country */
function toNeighborhood(latlng) {
	return new Promise((resolve, reject) => {
        const geocoder = new google.maps.Geocoder;
        geocoder.geocode({"location": latlng}, function(results, status) {
            if (status == "OK") {
                if (results[0]) {
                    const result = results[0]
                    let zipCode = "";
                    let country ="";
                    for (let i = result.address_components.length - 1; i >= 0; i--) {
                        let component = result.address_components[i];
                        if ((zipCode == "") && (component.types.indexOf("postal_code") >= 0 )) {
                            zipCode = component.long_name;
                        }
                        if ((country == "") && (component.types.indexOf("country") >= 0 )) {
                            country = component.long_name;
                        }
                        if (zipCode != "" && country != "") break;
                    }
                    neighborhood = [zipCode, country];
                    resolve([zipCode, country]);
                } else reject("Couldn't get neighborhood");
            } else reject("Couldn't get neighborhood");
        });
    });
}

/* Fetches tasks from servlet by neighborhood and category */
function fetchTasks(category) {
    let url = "/tasks?zipcode=" + neighborhood[0]+ "&country=" + neighborhood[1];
    if (category !== undefined && category != "all") {
        url += "&category=" + category;
    }
    return fetch(url);
}

/* Displays the tasks received from the server response */
function displayTasks(response) {
    response.json().then(html => {
        if (html){
            document.getElementById("no-tasks-message").style.display = "none";
            document.getElementById("tasks-message").style.display = "block";
            document.getElementById("tasks-list").innerHTML = html;
            document.getElementById("tasks-list").style.display = "block";
            addTasksClickHandlers();
        } else {
            document.getElementById("no-tasks-message").style.display = "block";
            document.getElementById("tasks-message").style.display = "none";
            document.getElementById("tasks-list").style.display = "none";
        }
    });
}

/* Function adds all the necessary tasks 'click' event listeners*/
function addTasksClickHandlers() {

    // adds confirmHelp click event listener to confirm help buttons
    const confirmHelpButtons = document.getElementsByClassName("confirm-help");
    for (let i = 0; i < confirmHelpButtons.length; i++){
        confirmHelpButtons[i].addEventListener("click", function(e) {
            confirmHelp(e.target);
        });

    }
    // adds exitHelp click event listener to exit help buttons
    const exitHelpButtons = document.getElementsByClassName("exit-help");
    for (let i = 0; i < exitConfirmButtons.length; i++) {
        exitHelpButtons[i].addEventListener("click", function(e) {
            exitHelp(e.target);
        });
    }
    // adds helpOut click event listener to help out buttons
    const helpOutButtons = document.getElementsByClassName("help-out");
        for (let i = 0; i < helpOutButtons.length; i++) {
            if (!helpOutButtons[i].classList.contains("disable-help")) {
                helpOutButtons[i].addEventListener("click", function(e) {
                    helpOut(e.target);
                });
            }
        }
}
<commit_msg>update comment for confirmHelp function<commit_after>// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

const MAPSKEY = config.MAPS_KEY
let neighborhood = [null , null];
let currentCategory = "all";

/* Calls addUIClickHandlers and getUserNeighborhood once page has loaded */
if (document.readyState === 'loading') {
    // adds on load event listeners if document hasn't yet loaded
    document.addEventListener('DOMContentLoaded', addUIClickHandlers)
    document.addEventListener('DOMContentLoaded', getUserNeighborhood);
} else {
    // if DOMContentLoaded has already fired, it simply calls the functions
    addUIClickHandlers();
    getUserNeighborhood();
}

/* Function adds all the necessary UI 'click' event listeners*/
function addUIClickHandlers() {
    // adds showModal and closeModal click events for the add task button
    if (document.body.contains(document.getElementById("addtaskbutton"))) {
        document.getElementById("addtaskbutton").addEventListener("click", showModal);
    	document.getElementById("close-button").addEventListener("click", closeModal);
    }

	// adds filterTasksBy click event listener to category buttons
	const categoryButtons = document.getElementsByClassName("categories");
    for (let i = 0; i < categoryButtons.length; i++) {
        categoryButtons[i].addEventListener("click", function(e) {
            filterTasksBy(e.target.id);
        });
    }
}

/* Function filters tasks by categories and styles selected categories */
function filterTasksBy(category) {
    currentCategory = category;

    // only fetches tasks if user's neighborhood has been retrieved
    if (JSON.stringify(neighborhood) != JSON.stringify([null, null])) {
        fetchTasks(category)
            .then(response => displayTasks(response));
    }
	// Unhighlights and resets styling for all category buttons
    const categoryButtons = document.getElementsByClassName("categories");
    for (let i = 0; i < categoryButtons.length; i++){
        let button = categoryButtons[i];
        if (document.getElementById(category) != button) {
            button.style.backgroundColor = "transparent";
    		button.style.color = "#222";
        	button.style.fontWeight = "normal";
        	button.addEventListener("mouseover", function() {
                button.style.backgroundColor = "lightgray";
            });
            button.addEventListener("mouseout", function() {
                button.style.backgroundColor = "transparent"
            });
        } else {
            button.style.backgroundColor = "#222";
        	button.style.color = "white";
        	button.style.fontWeight = "bold";
            button.addEventListener("mouseover", function() {
                button.style.backgroundColor = "#222";
            });
            button.addEventListener("mouseout", function() {
                button.style.backgroundColor = "#222"
            });
        }
    }
}

/* Function that display the help out overlay */
function helpOut(element) {
    const task = element.closest(".task");
    const overlay = task.getElementsByClassName("help-overlay");
    overlay[0].style.display = "block";
}

/* Function sends a fetch request to the edit task servlet when the user
offers to help out, edits the task's status and helper properties and
then reloads the task list */
function confirmHelp(element) {
    const url = "tasks/edit?key=" + element.dataset.key;
    const request = new Request(url, {method: "POST"});
    fetch(request).then(() => {
        if (JSON.stringify(neighborhood) != JSON.stringify([null, null])) {
            fetchTasks(currentCategory).then(response => displayTasks(response));
        }
    });
}

/* Function that hides the help out overlay */
function exitHelp(element) {
	element.closest(".help-overlay").style.display = "none";
}

/* Leonard's implementation of the Add Task modal */
function showModal() {
    var modal = document.getElementById("createTaskModalWrapper");
    modal.style.display = "block";
}
function closeModal() {
    var modal = document.getElementById("createTaskModalWrapper");
    modal.style.display = "none";
}
// If the user clicks outside of the modal, closes the modal directly
window.onclick = function(event) {
    var modal = document.getElementById("createTaskModalWrapper");
    if (event.target == modal) {
        modal.style.display = "none";
    }
}

/* Function dynamically adds Maps API and
begins the processes of retrieving the user's neighborhood*/
function getUserNeighborhood() {
    const script = document.createElement("script");
    script.type = "text/javascript";
    script.src =  "https://maps.googleapis.com/maps/api/js?key=" + MAPSKEY + "&callback=initialize";
    script.defer = true;
    script.async = true;
    document.head.appendChild(script);

    // Once the Maps API script has dynamically loaded it gets the user location,
    // waits until it gets an answer and then calls toNeighborhood passing the location
    // as an argument, updates the global neighborhood variable and then calls
    // fetchTasks and displayTasks
	window.initialize = function () {
        getUserLocation().then(location => toNeighborhood(location))
        	.then(() => fetchTasks())
            .then((response) => displayTasks(response))
            .catch(() => {
                console.error("User location and/or neighborhood could not be retrieved");
                document.getElementById("location-missing-message").style.display = "block";
            });
	}
}

/* Function that returns a promise to get and return the user's location */
 function getUserLocation() {
    return new Promise((resolve, reject) => {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(function(position) {
                var location = {lat: position.coords.latitude, lng: position.coords.longitude};
                resolve(location);
            }, function() {
                reject("User location failed");
            });
        } else {
            reject("User location is not supported by this browser");
        }
    });
}

/* Function that returns a promise to return a neighborhood
array that includes the postal code and country */
function toNeighborhood(latlng) {
	return new Promise((resolve, reject) => {
        const geocoder = new google.maps.Geocoder;
        geocoder.geocode({"location": latlng}, function(results, status) {
            if (status == "OK") {
                if (results[0]) {
                    const result = results[0]
                    let zipCode = "";
                    let country ="";
                    for (let i = result.address_components.length - 1; i >= 0; i--) {
                        let component = result.address_components[i];
                        if ((zipCode == "") && (component.types.indexOf("postal_code") >= 0 )) {
                            zipCode = component.long_name;
                        }
                        if ((country == "") && (component.types.indexOf("country") >= 0 )) {
                            country = component.long_name;
                        }
                        if (zipCode != "" && country != "") break;
                    }
                    neighborhood = [zipCode, country];
                    resolve([zipCode, country]);
                } else reject("Couldn't get neighborhood");
            } else reject("Couldn't get neighborhood");
        });
    });
}

/* Fetches tasks from servlet by neighborhood and category */
function fetchTasks(category) {
    let url = "/tasks?zipcode=" + neighborhood[0]+ "&country=" + neighborhood[1];
    if (category !== undefined && category != "all") {
        url += "&category=" + category;
    }
    return fetch(url);
}

/* Displays the tasks received from the server response */
function displayTasks(response) {
    response.json().then(html => {
        if (html){
            document.getElementById("no-tasks-message").style.display = "none";
            document.getElementById("tasks-message").style.display = "block";
            document.getElementById("tasks-list").innerHTML = html;
            document.getElementById("tasks-list").style.display = "block";
            addTasksClickHandlers();
        } else {
            document.getElementById("no-tasks-message").style.display = "block";
            document.getElementById("tasks-message").style.display = "none";
            document.getElementById("tasks-list").style.display = "none";
        }
    });
}

/* Function adds all the necessary tasks 'click' event listeners*/
function addTasksClickHandlers() {

    // adds confirmHelp click event listener to confirm help buttons
    const confirmHelpButtons = document.getElementsByClassName("confirm-help");
    for (let i = 0; i < confirmHelpButtons.length; i++){
        confirmHelpButtons[i].addEventListener("click", function(e) {
            confirmHelp(e.target);
        });

    }
    // adds exitHelp click event listener to exit help buttons
    const exitHelpButtons = document.getElementsByClassName("exit-help");
    for (let i = 0; i < exitConfirmButtons.length; i++) {
        exitHelpButtons[i].addEventListener("click", function(e) {
            exitHelp(e.target);
        });
    }
    // adds helpOut click event listener to help out buttons
    const helpOutButtons = document.getElementsByClassName("help-out");
        for (let i = 0; i < helpOutButtons.length; i++) {
            if (!helpOutButtons[i].classList.contains("disable-help")) {
                helpOutButtons[i].addEventListener("click", function(e) {
                    helpOut(e.target);
                });
            }
        }
}
<|endoftext|>