<commit_before>iD.ui.preset.cycleway = function(field) {
    var event = d3.dispatch('change'),
        items;

    function cycleway(selection) {
        var wrap = selection.selectAll('.preset-input-wrap')
            .data([0]);

        wrap.enter().append('div')
            .attr('class', 'cf preset-input-wrap')
            .append('ul');

        items = wrap.select('ul').selectAll('li')
            .data(field.keys);

        // Enter

        var enter = items.enter().append('li')
            .attr('class', function(d) { return 'cf preset-cycleway-' + d; });

        enter.append('span')
            .attr('class', 'col6 label preset-label-cycleway')
            .attr('for', function(d) { return 'preset-input-cycleway-' + d; })
            .text(function(d) { return field.t('types.' + d); });

        enter.append('div')
            .attr('class', 'col6 preset-input-cycleway-wrap')
            .append('input')
            .attr('type', 'text')
            .attr('class', 'preset-input-cycleway')
            .attr('id', function(d) { return 'preset-input-cycleway-' + d; })
            .each(function(d) {
                d3.select(this)
                    .call(d3.combobox()
                        .data(cycleway.options(d)));
            });

        // Update

        wrap.selectAll('.preset-input-cycleway')
            .on('change', change)
            .on('blur', change);
    }

    function change(d) {
        var tag = {};
        tag[d] = d3.select(this).value() || undefined;
        if (tag[d] === 'none') {
            tag[d] = undefined;
        }
        event.change(tag);
    }

    cycleway.options = function() {
        var options = ['none', 'lane', 'shared_lane', 'track', 'share_busway', 'opposite_lane', 'opposite'];

        return options.map(function(option) {
            return {
                title: field.t('options.' + option + '.description'),
                value: option
            };
        });
    };

    cycleway.tags = function(tags) {
        items.selectAll('.preset-input-cycleway')
            .value(function(d) { return tags[d] || ''; })
            .attr('placeholder', function() {
                return tags.cycleway ? tags.cycleway : field.placeholder();
            });
    };

    cycleway.focus = function() {
        items.selectAll('.preset-input-cycleway')
            .node().focus();
    };

    return d3.rebind(cycleway, event, 'on');
};
<commit_msg>Decide when to use cycleway itself or cycleway:*<commit_after>iD.ui.preset.cycleway = function(field) {
    var event = d3.dispatch('change'),
        items;

    function cycleway(selection) {
        var wrap = selection.selectAll('.preset-input-wrap')
            .data([0]);

        wrap.enter().append('div')
            .attr('class', 'cf preset-input-wrap')
            .append('ul');

        items = wrap.select('ul').selectAll('li')
            .data(field.keys);

        // Enter

        var enter = items.enter().append('li')
            .attr('class', function(d) { return 'cf preset-cycleway-' + d; });

        enter.append('span')
            .attr('class', 'col6 label preset-label-cycleway')
            .attr('for', function(d) { return 'preset-input-cycleway-' + d; })
            .text(function(d) { return field.t('types.' + d); });

        enter.append('div')
            .attr('class', 'col6 preset-input-cycleway-wrap')
            .append('input')
            .attr('type', 'text')
            .attr('class', 'preset-input-cycleway')
            .attr('id', function(d) { return 'preset-input-cycleway-' + d; })
            .each(function(d) {
                d3.select(this)
                    .call(d3.combobox()
                        .data(cycleway.options(d)));
            });

        // Update

        wrap.selectAll('.preset-input-cycleway')
            .on('change', change)
            .on('blur', change);
    }

    function change() {
        var inputs = d3.selectAll('.preset-input-cycleway')[0],
            left = d3.select(inputs[0]).value(),
            right = d3.select(inputs[1]).value(),
            tag = {};
        if (left === 'none' || left === '') { left = undefined; }
        if (right === 'none' || right === '') { right = undefined; }

        // Always set both left and right as changing one can affect the other
        tag = {
            cycleway: undefined,
            'cycleway:left': left,
            'cycleway:right': right
        };

        // If the left and right tags match, use the cycleway tag to tag both
        // sides the same way
        if (left === right) {
            tag = {
                cycleway: left,
                'cycleway:left': undefined,
                'cycleway:right': undefined
            };
        }

        event.change(tag);
    }

    cycleway.options = function() {
        var options = ['none', 'lane', 'shared_lane', 'track', 'share_busway', 'opposite_lane', 'opposite'];

        return options.map(function(option) {
            return {
                title: field.t('options.' + option + '.description'),
                value: option
            };
        });
    };

    cycleway.tags = function(tags) {
        items.selectAll('.preset-input-cycleway')
            .value(function(d) {
                // If cycleway is set, always return that
                if (tags.cycleway) {
                    return tags.cycleway;
                }
                return tags[d] || '';
            })
            .attr('placeholder', field.placeholder());
    };

    cycleway.focus = function() {
        items.selectAll('.preset-input-cycleway')
            .node().focus();
    };

    return d3.rebind(cycleway, event, 'on');
};
<|endoftext|>


<commit_before>"use strict";

function timestamp() {

	return Math.floor(Date.now() / 1000);

}

function doSomethingSmart() {

  var ts = timestamp();
  // var timestamp = "something";

  return true;

}
<commit_msg>Update is-not-a-function.fix.js<commit_after>"use strict";

function timestamp() {

	return Math.floor(Date.now() / 1000);

}

function doSomethingSmart() {

  var ts = timestamp();
  // var timestamp = "something";
  var timestampVar = "something";

  return true;

}
<|endoftext|>


<commit_before>/*
Possible additions:
	scollTop
	CSS Matrix
*/

// test whether a CSS media type or query applies
$.media = (function() {
	// TODO: use window.matchMedia once at least one UA implements it
	var cache = {},
		$html = $( "html" ),
		testDiv = $( "
" ),
		fakeBody = $( "" ).append( testDiv );

	return function( query ) {
		if ( !( query in cache ) ) {
			var styleBlock = $( "" );
			$html.prepend( fakeBody ).prepend( styleBlock );
			cache[ query ] = testDiv.css( "position" ) === "absolute";
			fakeBody.add( styleBlock ).remove();
		}
		return cache[ query ];
	};
})();

var fakeBody = $( "" ).prependTo( "html" ),
	fbCSS = fakeBody[0].style,
	vendors = ['webkit','moz','o'],
	webos = window.palmGetResource || window.PalmServiceBridge, //only used to rule out scrollTop
	bb = window.blackberry; //only used to rule out box shadow, as it's filled opaque on BB

//thx Modernizr
function propExists( prop ){
	var uc_prop = prop.charAt(0).toUpperCase() + prop.substr(1),
		props   = (prop + ' ' + vendors.join(uc_prop + ' ') + uc_prop).split(' ');
	for(var v in props){
		if( fbCSS[ v ] !== undefined ){
			return true;
		}
	}
};

//test for dynamic-updating base tag support (allows us to avoid href,src attr rewriting)
function baseTagTest(){
	var fauxBase = location.protocol + '//' + location.host + location.pathname + "ui-dir/",
		base = $("<base>", {"href": fauxBase}).appendTo("head"),
		link = $( "" ).prependTo( fakeBody );
	$.support.dynamicBaseTag = !!link[0].href.match(fauxBase);
	base.remove();
};

baseTagTest();

$.extend( $.support, {
	orientation: "orientation" in window,
	touch: "ontouchend" in document,
	WebKitAnimationEvent: typeof WebKitTransitionEvent === "object",
	pushState: !!history.pushState,
	mediaquery: $.media('only all'),
	cssPseudoElement: !!propExists('content'),
	boxShadow: !!propExists('boxShadow') && !bb,
	scrollTop: ("pageXOffset" in window || "scrollTop" in document.documentElement || "scrollTop" in fakeBody[0]) && !webos
});

fakeBody.remove();

//for ruling out shadows via css
if( !$.support.boxShadow ){ $('html').addClass('ui-mobile-nosupport-boxshadow'); }<commit_msg>used indexOf instead of match.<commit_after>/*
Possible additions:
	scollTop
	CSS Matrix
*/

// test whether a CSS media type or query applies
$.media = (function() {
	// TODO: use window.matchMedia once at least one UA implements it
	var cache = {},
		$html = $( "html" ),
		testDiv = $( "
" ),
		fakeBody = $( "" ).append( testDiv );

	return function( query ) {
		if ( !( query in cache ) ) {
			var styleBlock = $( "" );
			$html.prepend( fakeBody ).prepend( styleBlock );
			cache[ query ] = testDiv.css( "position" ) === "absolute";
			fakeBody.add( styleBlock ).remove();
		}
		return cache[ query ];
	};
})();

var fakeBody = $( "" ).prependTo( "html" ),
	fbCSS = fakeBody[0].style,
	vendors = ['webkit','moz','o'],
	webos = window.palmGetResource || window.PalmServiceBridge, //only used to rule out scrollTop
	bb = window.blackberry; //only used to rule out box shadow, as it's filled opaque on BB

//thx Modernizr
function propExists( prop ){
	var uc_prop = prop.charAt(0).toUpperCase() + prop.substr(1),
		props   = (prop + ' ' + vendors.join(uc_prop + ' ') + uc_prop).split(' ');
	for(var v in props){
		if( fbCSS[ v ] !== undefined ){
			return true;
		}
	}
};

//test for dynamic-updating base tag support (allows us to avoid href,src attr rewriting)
function baseTagTest(){
	var fauxBase = location.protocol + '//' + location.host + location.pathname + "ui-dir/",
		base = $("<base>", {"href": fauxBase}).appendTo("head"),
		link = $( "" ).prependTo( fakeBody );
	$.support.dynamicBaseTag = link[0].href.indexOf(fauxBase) === 0;
	base.remove();
};

baseTagTest();

$.extend( $.support, {
	orientation: "orientation" in window,
	touch: "ontouchend" in document,
	WebKitAnimationEvent: typeof WebKitTransitionEvent === "object",
	pushState: !!history.pushState,
	mediaquery: $.media('only all'),
	cssPseudoElement: !!propExists('content'),
	boxShadow: !!propExists('boxShadow') && !bb,
	scrollTop: ("pageXOffset" in window || "scrollTop" in document.documentElement || "scrollTop" in fakeBody[0]) && !webos
});

fakeBody.remove();

//for ruling out shadows via css
if( !$.support.boxShadow ){ $('html').addClass('ui-mobile-nosupport-boxshadow'); }<|endoftext|>


<commit_before>import React, { PropTypes } from 'react'
import { AutoSizer } from 'react-virtualized'
import ProviderPlayers from './provider'
import screenfull from 'screenfull'

class PlayerView extends React.Component {
  static propTypes = {
    // queue
    curId: PropTypes.number,
    item: PropTypes.object,
    isPlaying: PropTypes.bool.isRequired,
    isFinished: PropTypes.bool.isRequired,
    // actions
    requestPlayNext: PropTypes.func.isRequired,
    emitStatus: PropTypes.func.isRequired,
    getMedia: PropTypes.func.isRequired,
    getMediaSuccess: PropTypes.func.isRequired,
    mediaError: PropTypes.func.isRequired,
    // player misc
    isFetching: PropTypes.bool.isRequired,
    libraryHasLoaded: PropTypes.bool.isRequired,
  }

  toggleFullscreen = this.toggleFullscreen.bind(this)

  componentDidMount() {
    // emit initial state
    this.props.emitStatus({
      curId: this.props.curId,
      curPos: 0,
      isPlaying: false,
    })
  }

  componentDidUpdate(prevProps) {
    if (this.props.item) {
      let { queueId, provider } = this.props.item

      if (prevProps.item && this.props.item && prevProps.item.queueId !== queueId && !ProviderPlayers[provider]) {
        // missing/invalid provider; trigger next track
        this.props.mediaError(id, 'No player provided for "'+provider+'"')
      }
    }

    // playing for the first time or after queue ended
    if (this.props.isPlaying && !prevProps.isPlaying && (this.props.curId === null || this.props.isFinished)) {
      // start at beginning of queue
      this.props.requestPlayNext()
    }
  }

  render () {
    let ActiveComp = 'div'
    let customProps = {}

    if (this.props.isFinished) {
      // show 'add more songs' placeholder
    } else if (!this.props.item) {
      // show 'press play to begin' placeholder
    } else if (!ProviderPlayers[this.props.item.provider]) {
      // show 'provider error' placeholder
    } else {
      ActiveComp = ProviderPlayers[this.props.item.provider]
      customProps = {
          item: this.props.item,
          isPlaying: this.props.isPlaying,
          getMedia: this.props.getMedia,
          getMediaSuccess: this.props.getMediaSuccess,
          onStatus: this.props.emitStatus,
          onMediaError: this.props.mediaError,
          onMediaEnd: this.props.requestPlayNext
      }
    }

    return (

 {this.ref = ref}}
        onClick={this.toggleFullscreen}
      >
        <AutoSizer>
          {({width, height}) => (
            <ActiveComp width={width} height={height} {...customProps}/>
          )}
        </AutoSizer>

    )
  }

  toggleFullscreen() {
    screenfull.toggle(this.ref)
  }
}

export default PlayerView
<commit_msg>Double click (instead of single) toggles player fullscreen<commit_after>import React, { PropTypes } from 'react'
import { AutoSizer } from 'react-virtualized'
import ProviderPlayers from './provider'
import screenfull from 'screenfull'

class PlayerView extends React.Component {
  static propTypes = {
    // queue
    curId: PropTypes.number,
    item: PropTypes.object,
    isPlaying: PropTypes.bool.isRequired,
    isFinished: PropTypes.bool.isRequired,
    // actions
    requestPlayNext: PropTypes.func.isRequired,
    emitStatus: PropTypes.func.isRequired,
    getMedia: PropTypes.func.isRequired,
    getMediaSuccess: PropTypes.func.isRequired,
    mediaError: PropTypes.func.isRequired,
    // player misc
    isFetching: PropTypes.bool.isRequired,
    libraryHasLoaded: PropTypes.bool.isRequired,
  }

  toggleFullscreen = this.toggleFullscreen.bind(this)

  componentDidMount() {
    // emit initial state
    this.props.emitStatus({
      curId: this.props.curId,
      curPos: 0,
      isPlaying: false,
    })
  }

  componentDidUpdate(prevProps) {
    if (this.props.item) {
      let { queueId, provider } = this.props.item

      if (prevProps.item && this.props.item && prevProps.item.queueId !== queueId && !ProviderPlayers[provider]) {
        // missing/invalid provider; trigger next track
        this.props.mediaError(id, 'No player provided for "'+provider+'"')
      }
    }

    // playing for the first time or after queue ended
    if (this.props.isPlaying && !prevProps.isPlaying && (this.props.curId === null || this.props.isFinished)) {
      // start at beginning of queue
      this.props.requestPlayNext()
    }
  }

  render () {
    let ActiveComp = 'div'
    let customProps = {}

    if (this.props.isFinished) {
      // show 'add more songs' placeholder
    } else if (!this.props.item) {
      // show 'press play to begin' placeholder
    } else if (!ProviderPlayers[this.props.item.provider]) {
      // show 'provider error' placeholder
    } else {
      ActiveComp = ProviderPlayers[this.props.item.provider]
      customProps = {
          item: this.props.item,
          isPlaying: this.props.isPlaying,
          getMedia: this.props.getMedia,
          getMediaSuccess: this.props.getMediaSuccess,
          onStatus: this.props.emitStatus,
          onMediaError: this.props.mediaError,
          onMediaEnd: this.props.requestPlayNext
      }
    }

    return (

 {this.ref = ref}}
        onDoubleClick={this.toggleFullscreen}
      >
        <AutoSizer>
          {({width, height}) => (
            <ActiveComp width={width} height={height} {...customProps}/>
          )}
        </AutoSizer>

    )
  }

  toggleFullscreen() {
    screenfull.toggle(this.ref)
  }
}

export default PlayerView
<|endoftext|>


<commit_before>class pubsub {
	constructor(options) {
		this.options = {
			/*
				Enables strict mode (shows more warnings)
			 */
			strict: false,

			/*
				Accepts a custom logger
			 */
			log: false,

			...options
		};
		this._pubsubEvents = {};
		this._pubsubHappened = {};
	}

	/*
		Publish an event.

		* **pub(event, [arg1, [arg2 ...]])**
		 * *event* the event to trigger;
		 * *arg1 ... argN* (optional) any number of additional params to pass to the event subscribers.
	*/
	pub(eventString) {
		if (!eventString) {
			throw new Error('pubsub.pub() received empty event string');
		}

		if (this.options.strict && arguments.length > 2) {
			console.warn(
				`[Deprecated] pub(): Publishing an event with many arguments is deprecated; use a single argument for the payload. Re: ${eventString}`
			);
		}

		var eventComponents = this.eventNamespace(eventString);
		var eventArray, i, ilen, j, jlen, args, subscriber, ret, event;
		for (i = 0, ilen = eventComponents.length; i < ilen; i++) {
			eventArray = this._pubsubEvents[(event = eventComponents[i])] || [];
			args = [];
			for (j = 1; j < arguments.length; j++) {
				args.push(arguments[j]);
			}

			if (this.options.log) {
				this.options.log('pub', event, args);
			}

			for (j = 0, jlen = eventArray.length; j < jlen; j++) {
				subscriber = eventArray[j];
				ret = subscriber[0].apply(subscriber[1] || this, args);
				if (subscriber[2] && ret !== false) {
					this.unsub(event, subscriber[0]);
				}
			}
			this._pubsubHappened[event] = args;
		}
		return this;
	}

	/*
		Subscribe a function to one or more events.

		 * **sub(eventString, method, [thisArg, [flags]])**
		   * *eventString* one or more space-separated events;
		   * *method* the function to subscribe to the events;
		   * *thisArg* (optional) context for the method;
		   * *flags* (optional) boleans to configure the subscribers's behavior:
		     * *once* if true, the subscriber will self-unsubscribe after the first successful execution. Use *pubsub.once()* for clarity;
		     * *recoup* if true, the subscriber will execute immediately if the event it subscribes to already happened. Use *pubsub.recoup()* for clarity.

		*Note:* When subscribing to multiple events, make sure these events are published with the same (or similar) list of arguments.
	*/
	sub(eventStr, method, thisArg, flags) {
		if (!eventStr) {
			throw new Error('sub(): received empty event string');
		}

		if (!method) {
			throw new Error('sub(): listener is undefined');
		}

		if (this.options.strict && thisArg) {
			console.warn(
				`[Deprecated] sub(): thisArg is deprecated; bind method manually instead. Re: ${eventStr}`
			);
		}

		if (this.options.log) {
			this.options.log('sub', eventStr, method, flags);
		}

		var events;

		if (Array.isArray(eventStr)) {
			events = eventStr;
		} else {
			events = eventStr.split(/\s+/);
			if (this.options.strict && events.length > 1) {
				console.warn(
					`[Deprecated] sub(): Subscribing to space-separated events is deprecated; use Array instead. Re: ${eventStr}`
				);
			}
		}

		var event, eventArray, i, len, oldArgs;

		flags = flags || { once: false, recoup: false };
		for (i = 0, len = events.length; i < len; i++) {
			eventArray = this._pubsubEvents[(event = events[i])];
			if (eventArray) {
				eventArray.push([method, thisArg, flags.once]);
			} else {
				this._pubsubEvents[event] = [[method, thisArg, flags.once]];
			}

			if (this.options.strict && this._pubsubHappened[event]) {
				console.warn(
					`[Warn] Subscribing to an event that already happened. Re: ${eventStr}`
				);
			}

			if (flags.recoup) {
				if (this.options.strict) {
					console.warn(
						`[Deprecated] recoup(): this method is deprecated; please consider an alternative pattern. Re: ${eventStr}`
					);
				}

				oldArgs = this._pubsubHappened[event];
				if (oldArgs) {
					method.apply(thisArg || this, oldArgs);
				}
			}
		}
		return this;
	}

	/*
		Unsubscribe a function from one or more events.

		 * **unsub(eventString, method)**
		   * *eventString* one or more space-separated events;
		   * *method* (optional) the function to unsubscribe

		If no *method* is provided, all attached methods will be unsubscribed from the event(s).
	*/
	unsub(eventStr, method) {
		if (!eventStr) {
			throw new Error('pubsub.unsub() received empty event string');
		}

		if (this.options.strict && !method) {
			console.warn(`[Deprecated] unsub(): called without a listener. Re: ${eventStr}`);
		}

		if (this.options.log) {
			this.options.log('unsub', eventStr, method, flags);
		}

		var events = eventStr.split(/\s+/),
			event,
			eventArray,
			newEventArray,
			i,
			j;
		for (i = 0; i < events.length; i++) {
			eventArray = this._pubsubEvents[(event = events[i])] || [];
			newEventArray = [];
			for (j = 0; method && j < eventArray.length; j++) {
				if (eventArray[j][0] !== method) {
					newEventArray.push(eventArray[j]);
				}
			}
			this._pubsubEvents[event] = newEventArray;
		}
		return this;
	}

	/*
		### pubsub.once
		Subscribe to an event once.

		The function will be unsubscribed upon successful exectution.
		To mark the function execution as unsuccessful
		(and thus keep it subscribed), make it return `false`.

		 * **once(eventString, method, thisArg)** identical to *pubsub.sub()*.
	*/
	once(eventStr, method, thisArg) {
		return this.sub(eventStr, method, thisArg, { once: true });
	}

	/*
		### pubsub.recoup
		Subscribe to an event, and execute immediately if that event was ever published before.

		If executed immediately, the subscriber will get as parameters the last values sent with the event.

		 * **recoup(eventString, method, thisArg)** identical to *pubsub.sub()*.
	*/
	recoup(eventStr, method, thisArg) {
		return this.sub(eventStr, method, thisArg, { recoup: true });
	}

	/*
		### pubsub.eventNamespace
		Parses the namespaced event string and returns an array of events to publish.
		The original implementation does: `"path:to:event" => ["path", "path:to", "path:to:event"]`.
		Overwrite the implementation to create your custom namespacing rules.
	*/
	eventNamespace(eventString) {
		var events = [],
			str = '',
			ch,
			i;
		for (i = 0; i < eventString.length; i++) {
			if ((ch = eventString.charAt(i)) === ':') {
				events.push(str);
			}
			str += ch;
		}
		events.push(str);
		return events;
	}
}

export default pubsub;
<commit_msg>Fixes typo<commit_after>class pubsub {
	constructor(options) {
		this.options = {
			/*
				Enables strict mode (shows more warnings)
			 */
			strict: false,

			/*
				Accepts a custom logger
			 */
			log: false,

			...options
		};
		this._pubsubEvents = {};
		this._pubsubHappened = {};
	}

	/*
		Publish an event.

		* **pub(event, [arg1, [arg2 ...]])**
		 * *event* the event to trigger;
		 * *arg1 ... argN* (optional) any number of additional params to pass to the event subscribers.
	*/
	pub(eventString) {
		if (!eventString) {
			throw new Error('pubsub.pub() received empty event string');
		}

		if (this.options.strict && arguments.length > 2) {
			console.warn(
				`[Deprecated] pub(): Publishing an event with many arguments is deprecated; use a single argument for the payload. Re: ${eventString}`
			);
		}

		var eventComponents = this.eventNamespace(eventString);
		var eventArray, i, ilen, j, jlen, args, subscriber, ret, event;
		for (i = 0, ilen = eventComponents.length; i < ilen; i++) {
			eventArray = this._pubsubEvents[(event = eventComponents[i])] || [];
			args = [];
			for (j = 1; j < arguments.length; j++) {
				args.push(arguments[j]);
			}

			if (this.options.log) {
				this.options.log('pub', event, args);
			}

			for (j = 0, jlen = eventArray.length; j < jlen; j++) {
				subscriber = eventArray[j];
				ret = subscriber[0].apply(subscriber[1] || this, args);
				if (subscriber[2] && ret !== false) {
					this.unsub(event, subscriber[0]);
				}
			}
			this._pubsubHappened[event] = args;
		}
		return this;
	}

	/*
		Subscribe a function to one or more events.

		 * **sub(eventString, method, [thisArg, [flags]])**
		   * *eventString* one or more space-separated events;
		   * *method* the function to subscribe to the events;
		   * *thisArg* (optional) context for the method;
		   * *flags* (optional) boleans to configure the subscribers's behavior:
		     * *once* if true, the subscriber will self-unsubscribe after the first successful execution. Use *pubsub.once()* for clarity;
		     * *recoup* if true, the subscriber will execute immediately if the event it subscribes to already happened. Use *pubsub.recoup()* for clarity.

		*Note:* When subscribing to multiple events, make sure these events are published with the same (or similar) list of arguments.
	*/
	sub(eventStr, method, thisArg, flags) {
		if (!eventStr) {
			throw new Error('sub(): received empty event string');
		}

		if (!method) {
			throw new Error('sub(): listener is undefined');
		}

		if (this.options.strict && thisArg) {
			console.warn(
				`[Deprecated] sub(): thisArg is deprecated; bind method manually instead. Re: ${eventStr}`
			);
		}

		if (this.options.log) {
			this.options.log('sub', eventStr, method, flags);
		}

		var events;

		if (Array.isArray(eventStr)) {
			events = eventStr;
		} else {
			events = eventStr.split(/\s+/);
			if (this.options.strict && events.length > 1) {
				console.warn(
					`[Deprecated] sub(): Subscribing to space-separated events is deprecated; use Array instead. Re: ${eventStr}`
				);
			}
		}

		var event, eventArray, i, len, oldArgs;

		flags = flags || { once: false, recoup: false };
		for (i = 0, len = events.length; i < len; i++) {
			eventArray = this._pubsubEvents[(event = events[i])];
			if (eventArray) {
				eventArray.push([method, thisArg, flags.once]);
			} else {
				this._pubsubEvents[event] = [[method, thisArg, flags.once]];
			}

			if (this.options.strict && this._pubsubHappened[event]) {
				console.warn(
					`[Warn] Subscribing to an event that already happened. Re: ${eventStr}`
				);
			}

			if (flags.recoup) {
				if (this.options.strict) {
					console.warn(
						`[Deprecated] recoup(): this method is deprecated; please consider an alternative pattern. Re: ${eventStr}`
					);
				}

				oldArgs = this._pubsubHappened[event];
				if (oldArgs) {
					method.apply(thisArg || this, oldArgs);
				}
			}
		}
		return this;
	}

	/*
		Unsubscribe a function from one or more events.

		 * **unsub(eventString, method)**
		   * *eventString* one or more space-separated events;
		   * *method* (optional) the function to unsubscribe

		If no *method* is provided, all attached methods will be unsubscribed from the event(s).
	*/
	unsub(eventStr, method) {
		if (!eventStr) {
			throw new Error('pubsub.unsub() received empty event string');
		}

		if (this.options.strict && !method) {
			console.warn(`[Deprecated] unsub(): called without a listener. Re: ${eventStr}`);
		}

		if (this.options.log) {
			this.options.log('unsub', eventStr, method);
		}

		var events = eventStr.split(/\s+/),
			event,
			eventArray,
			newEventArray,
			i,
			j;
		for (i = 0; i < events.length; i++) {
			eventArray = this._pubsubEvents[(event = events[i])] || [];
			newEventArray = [];
			for (j = 0; method && j < eventArray.length; j++) {
				if (eventArray[j][0] !== method) {
					newEventArray.push(eventArray[j]);
				}
			}
			this._pubsubEvents[event] = newEventArray;
		}
		return this;
	}

	/*
		### pubsub.once
		Subscribe to an event once.

		The function will be unsubscribed upon successful exectution.
		To mark the function execution as unsuccessful
		(and thus keep it subscribed), make it return `false`.

		 * **once(eventString, method, thisArg)** identical to *pubsub.sub()*.
	*/
	once(eventStr, method, thisArg) {
		return this.sub(eventStr, method, thisArg, { once: true });
	}

	/*
		### pubsub.recoup
		Subscribe to an event, and execute immediately if that event was ever published before.

		If executed immediately, the subscriber will get as parameters the last values sent with the event.

		 * **recoup(eventString, method, thisArg)** identical to *pubsub.sub()*.
	*/
	recoup(eventStr, method, thisArg) {
		return this.sub(eventStr, method, thisArg, { recoup: true });
	}

	/*
		### pubsub.eventNamespace
		Parses the namespaced event string and returns an array of events to publish.
		The original implementation does: `"path:to:event" => ["path", "path:to", "path:to:event"]`.
		Overwrite the implementation to create your custom namespacing rules.
	*/
	eventNamespace(eventString) {
		var events = [],
			str = '',
			ch,
			i;
		for (i = 0; i < eventString.length; i++) {
			if ((ch = eventString.charAt(i)) === ':') {
				events.push(str);
			}
			str += ch;
		}
		events.push(str);
		return events;
	}
}

export default pubsub;
<|endoftext|>


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

import {LitElement, html} from "lit";
import UtilsNew from "../../core/utilsNew.js";
import {RestResponse} from "../../core/clients/rest-response.js";
import LitUtils from "../commons/utils/lit-utils.js";

export default class OpencgaLogin extends LitElement {

    constructor() {
        super();
        this._init();
    }

    createRenderRoot() {
        return this;
    }

    static get properties() {
        return {
            opencgaSession: {
                type: Object
            },
            buttonText: {
                type: String
            },
            userName: {
                type: String
            },
            password: {
                type: String
            },
            notifyEventMessage: {
                type: String
            }
        };
    }

    _init() {
        this.userName = "";
        this.password = "";
        this.buttonText = "Sign in";
        this.signingIn = false;
    }

    firstUpdated(changedProperties) {
        $("#formLogin").validator("update");
        $("#formLogin").validator().on("submit", e => this.submitLogin(e));
        this.route();
    }

    updated(changedProperties) {
        if (changedProperties.has("opencgaSession")) {
            this.route();
        }
    }

    route() {
        if (this.opencgaSession?.study) {
            // window.location.hash = "#home";
            this.dispatchEvent(new CustomEvent("route", {
                detail: {
                    hash: "#home"
                }
            }));
        }
    }

    submitLogin(e) {
        // console.log("e", e);
        if (e.isDefaultPrevented()) {
            console.error("submitLogin() Error", e);
            // handle the invalid form...
            // this._clearHtmlDom(true);
        } else {
            // everything looks good!
            e.preventDefault();
            // this.dispatchEvent(new CustomEvent("signingIn"));

            const user = this.querySelector("#opencgaUser").value;
            const pass = this.querySelector("#opencgaPassword").value;

            try {
                // in case a previous error has prevented the creation of opencgaSession object (in opencgaClient.createSession()), this would be undefined
                if (this.opencgaSession) {
                    this.opencgaSession.opencgaClient.login(user, pass)
                        .then(restResponse => {

                            if (restResponse instanceof RestResponse) {
                                if (restResponse.getEvents?.("ERROR")?.length) {
                                    this.errorState = restResponse.getEvents("ERROR");
                                    UtilsNew.notifyError(restResponse);
                                } else if (restResponse) {
                                    this.querySelector("#opencgaUser").value = "";
                                    this.querySelector("#opencgaPassword").value = "";
                                    const token = restResponse.getResult(0).token;
                                    const decoded = jwt_decode(token);
                                    const dateExpired = new Date(decoded.exp * 1000);
                                    const validTimeSessionId = moment(dateExpired, "YYYYMMDDHHmmss").format("D MMM YY HH:mm:ss");
                                    this.dispatchEvent(new CustomEvent("login", {
                                        detail: {
                                            userId: user,
                                            token: token
                                        },
                                        bubbles: true,
                                        composed: true
                                    }));
                                    // new NotificationQueue().push("Welcome, " + user, "Your session is valid until " + validTimeSessionId, UtilsNew.MESSAGE_SUCCESS);
                                    const message = `Welcome back, <b>${user}</b>. Your session is valid until ${validTimeSessionId}`;
                                    LitUtils.dispatchEventCustom(this, "notificationSuccess", message);

                                }
                            } else {
                                this.errorState = [{name: "Generic Server Error", message: "Unexpected response format. Please check your host is up and running."}];
                                // new NotificationQueue().push(this.errorState[0].name, this.errorState[0].message, "error");
                                LitUtils.dispatchEventCustom(this, "notificationError", this.errorState[0].message);
                            }
                        })
                        .catch(response => {
                            // response isn't necessarily a restResponse instance
                            UtilsNew.notifyError(response);
                        }).finally(() => this.requestUpdate());
                } else {
                    // new NotificationQueue().push("Error retrieving OpencgaSession", null, "ERROR");
                    LitUtils.dispatchEventCustom(this, "notificationError", "Error retrieving OpencgaSession");
                }
            } catch (e) {
                this.errorState = [{name: "Generic Error", message: "Please contact your administrator."}];

            }

        }

    }

    checkEnterKey(e) {
        if (e.keyCode === 13) {
            // this.login();
        }
    }

    render() {
        return html`

                    <form id="formLogin" data-toggle="validator" class="form-horizontal" role="form">

                            User ID

                                <input id="opencgaUser" value="${this.userName}" type="text" pattern="^[_\\-A-z0-9@\\.]+$" class="form-control input-login"
                                       placeholder="User ID (case sensitive)" aria-label="Recipient's username" aria-describedby="username" required data-required-error="This field is required">

                            Password

                                <input id="opencgaPassword" value="${this.password}" type="password" maxlength="256" class="form-control input-login"
                                       placeholder="Password" aria-describedby="password" required>

                            <button type="submit" class="btn btn-lg btn-primary btn-block ripple">${this.buttonText}</button>

                    </form>

        ${this.errorState?.length ? html`

                ${this.errorState.map(error => html`<p><strong>${error.name}</strong></p><p>${error.message}</p>`)}

        ` : null}
        `;
    }

}

customElements.define("opencga-login", OpencgaLogin);

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

import {LitElement, html} from "lit";
import {RestResponse} from "../../core/clients/rest-response.js";
import LitUtils from "../commons/utils/lit-utils.js";

export default class OpencgaLogin extends LitElement {

    constructor() {
        super();
        this._init();
    }

    createRenderRoot() {
        return this;
    }

    static get properties() {
        return {
            opencgaSession: {
                type: Object
            },
            buttonText: {
                type: String
            },
            userName: {
                type: String
            },
            password: {
                type: String
            },
            notifyEventMessage: {
                type: String
            }
        };
    }

    _init() {
        this.userName = "";
        this.password = "";
        this.buttonText = "Sign in";
        this.signingIn = false;
    }

    firstUpdated(changedProperties) {
        $("#formLogin").validator("update");
        $("#formLogin").validator().on("submit", e => this.submitLogin(e));
        this.route();
    }

    updated(changedProperties) {
        if (changedProperties.has("opencgaSession")) {
            this.route();
        }
    }

    route() {
        if (this.opencgaSession?.study) {
            // window.location.hash = "#home";
            this.dispatchEvent(new CustomEvent("route", {
                detail: {
                    hash: "#home"
                }
            }));
        }
    }

    submitLogin(e) {
        // console.log("e", e);
        if (e.isDefaultPrevented()) {
            console.error("submitLogin() Error", e);
            // handle the invalid form...
            // this._clearHtmlDom(true);
        } else {
            // everything looks good!
            e.preventDefault();
            // this.dispatchEvent(new CustomEvent("signingIn"));

            const user = this.querySelector("#opencgaUser").value;
            const pass = this.querySelector("#opencgaPassword").value;

            // in case a previous error has prevented the creation of opencgaSession object (in opencgaClient.createSession()), this would be undefined
            if (this.opencgaSession) {
                this.opencgaSession.opencgaClient.login(user, pass)
                    .then(response => {
                        if (response instanceof RestResponse) {
                            if (response.getEvents?.("ERROR")?.length) {
                                this.errorState = response.getEvents("ERROR");
                                // UtilsNew.notifyError(response);
                                LitUtils.dispatchEventCustom(this, "responseError", response);
                            } else if (response) {
                                this.querySelector("#opencgaUser").value = "";
                                this.querySelector("#opencgaPassword").value = "";
                                const token = response.getResult(0).token;
                                const decoded = jwt_decode(token);
                                const dateExpired = new Date(decoded.exp * 1000);
                                const validTimeSessionId = moment(dateExpired, "YYYYMMDDHHmmss").format("D MMM YY HH:mm:ss");
                                LitUtils.dispatchEventCustom(this, "login", null, null, {
                                    userId: user,
                                    token: token
                                });
                                LitUtils.dispatchEventCustom(this, "notificationSuccess", null, null, {
                                    message: `Welcome back, <b>${user}</b>. Your session is valid until ${validTimeSessionId}`,
                                });
                            }
                        } else {
                            this.errorState = [
                                {
                                    name: "Generic Server Error",
                                    message: "Unexpected response format. Please check your host is up and running.",
                                },
                            ];
                            // new NotificationQueue().push(this.errorState[0].name, this.errorState[0].message, "error");
                            LitUtils.dispatchEventCustom(this, "notificationError", null, null, {
                                title: this.errorState[0].name,
                                message: this.errorState[0].message
                            });
                        }
                    })
                    .catch(response => {
                        // response isn't necessarily a restResponse instance
                        // UtilsNew.notifyError(response);
                        return LitUtils.dispatchEventCustom(this, "responseError", response);
                    });
            } else {
                // new NotificationQueue().push("Error retrieving OpencgaSession", null, "ERROR");
                LitUtils.dispatchEventCustom(this, "notificationError", null, null, {
                    title: "Error retrieving OpencgaSession",
                    message: `
                        There was an error retrieving the OpencgaSession.
                        Please try again later or contact the administrator if the problem persists.
                    `,
                });
            }
        }
    }

    checkEnterKey(e) {
        if (e.keyCode === 13) {
            // this.login();
        }
    }

    render() {
        return html`

                    <form id="formLogin" data-toggle="validator" class="form-horizontal" role="form">

                            User ID

                                <input id="opencgaUser" value="${this.userName}" type="text" pattern="^[_\\-A-z0-9@\\.]+$" class="form-control input-login"
                                       placeholder="User ID (case sensitive)" aria-label="Recipient's username" aria-describedby="username" required data-required-error="This field is required">

                            Password

                                <input id="opencgaPassword" value="${this.password}" type="password" maxlength="256" class="form-control input-login"
                                       placeholder="Password" aria-describedby="password" required>

                            <button type="submit" class="btn btn-lg btn-primary btn-block ripple">${this.buttonText}</button>

                    </form>

        ${this.errorState?.length ? html`

                ${this.errorState.map(error => html`<p><strong>${error.name}</strong></p><p>${error.message}</p>`)}

        ` : null}
        `;
    }

}

customElements.define("opencga-login", OpencgaLogin);

<|endoftext|>


<commit_before>(function(define) {'use strict';
define(function(require) {

return function(Variable) {

   // values will be an array
   function FactorVar(values, options) {
      this.levels(values.slice().sort());
      // the values of a factor "are" the corresponding codes
      this.values = new Variable.Vector(this.getCodes(values));
   }

   FactorVar.prototype = Object.create(Variable.prototype);

   // When called with no argument, returns an array of the levels.
   // When called with an array `arr` as the argument, uses `arr`
   // to set the levels.
   // Duplicates in `arr` are ignored.
   FactorVar.prototype.levels = function levels(arr) {
      var i;
      if (arguments.length === 0) { return this.c2v.slice(1); }
      // build this.v2c and this.c2v from arr
      this.c2v = [null];     // codes for levels begin from 1, not 0.
      this.v2c = {};
      for (i = 0; i < arr.length; i += 1) {
         if (arr[i] != null && !this.v2c.hasOwnProperty(arr[i])) {
            this.v2c[arr[i]] = this.c2v.length;
            this.c2v.push(arr[i].toString());
         }
      }
      return this;
   };

   // Given an array of string values, `values`, returns the
   // corresponding array of numerical codes.
   FactorVar.prototype.getCodes = function getCodes(values) {
      var v2c = this.v2c;
      return values.map(function(val) { return v2c[val]; });
   };

   FactorVar.prototype.get = function get(i) {
      var c2v = this.c2v;
      if (typeof i !== 'number') {
         return this.values.get(i).map(function(code) { return c2v[code]; });
      }
      return c2v[ this.values.get(i) ];
   };

   return FactorVar;
};

});

}(typeof define === 'function' && define.amd ? define : function(factory) {
   'use strict';
   module.exports = factory(require);
}));
<commit_msg>Shorter returns first<commit_after>(function(define) {'use strict';
define(function(require) {

return function(Variable) {

   // values will be an array
   function FactorVar(values, options) {
      this.levels(values.slice().sort());
      // the values of a factor "are" the corresponding codes
      this.values = new Variable.Vector(this.getCodes(values));
   }

   FactorVar.prototype = Object.create(Variable.prototype);

   // When called with no argument, returns an array of the levels.
   // When called with an array `arr` as the argument, uses `arr`
   // to set the levels.
   // Duplicates in `arr` are ignored.
   FactorVar.prototype.levels = function levels(arr) {
      var i;
      if (arguments.length === 0) { return this.c2v.slice(1); }
      // build this.v2c and this.c2v from arr
      this.c2v = [null];     // codes for levels begin from 1, not 0.
      this.v2c = {};
      for (i = 0; i < arr.length; i += 1) {
         if (arr[i] != null && !this.v2c.hasOwnProperty(arr[i])) {
            this.v2c[arr[i]] = this.c2v.length;
            this.c2v.push(arr[i].toString());
         }
      }
      return this;
   };

   // Given an array of string values, `values`, returns the
   // corresponding array of numerical codes.
   FactorVar.prototype.getCodes = function getCodes(values) {
      var v2c = this.v2c;
      return values.map(function(val) { return v2c[val]; });
   };

   FactorVar.prototype.get = function get(i) {
      var c2v = this.c2v;
      if (typeof i === 'number') { return c2v[ this.values.get(i) ]; }
      return this.values.get(i).map(function(code) { return c2v[code]; });
   };

   return FactorVar;
};

});

}(typeof define === 'function' && define.amd ? define : function(factory) {
   'use strict';
   module.exports = factory(require);
}));
<|endoftext|>


<commit_before>/**
* jquery.toxicbox ver.1.0.6
* ToxicBox - © 2015-2016 Berestov Andrey
* http://my-gallery.name
*/

var toxicbox_options={};

$( document ).ready(function() {(function () {

var l='en',
  rl={
    im : 'Фото',
    o : 'из'
  },
  el={
    im : 'Image',
    o : 'of'
  },
  basic_width = 960,
  auto_width = 'on',
  iu="images/toxic/",
  ps = 5,
  sp =1,
  alert_width = 300,
  start_box_size = 150,
  isMobile = {
    Android: function() {
      return navigator.userAgent.match(/Android/i);
    },
    BlackBerry: function() {
      return navigator.userAgent.match(/BlackBerry/i);
    },
    iOS: function() {
      return navigator.userAgent.match(/iPhone|iPad|iPod/i);
    },
    Opera: function() {
      return navigator.userAgent.match(/Opera Mini/i);
    },
    Windows: function() {
      return navigator.userAgent.match(/IEMobile/i);
    },
    any: function() {
      return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows());
    }
  },
  width = $(window).width(),
  height = $(window).height(),
  ci=$('a[data-toxic="group"]').length,
  ai = $('a[data-toxic="group"]'),
  ch=0,
  cw=0,
  back_src,
  next_src,
  cd,
  current_databox,
  is_single,
  zoom,
  cl;

//initialization settings

if (Object.keys(toxicbox_options).length) {
  if(toxicbox_options.language) l=toxicbox_options.language;
  if(toxicbox_options.padding) ps=toxicbox_options.padding;
  if(toxicbox_options.images_url) iu=toxicbox_options.images_url;
  if(toxicbox_options.alert_width) alert_width=toxicbox_options.alert_width;
  if(toxicbox_options.basic_width) basic_width=toxicbox_options.basic_width;
  if(toxicbox_options.auto_width) auto_width=toxicbox_options.auto_width;
  if(toxicbox_options.speed) sp=toxicbox_options.speed;
  if(toxicbox_options.start_box_size) start_box_size=toxicbox_options.start_box_size;
}

var old_width=start_box_size-ps*2,
  old_height=old_width;

$("a[data-toxic='single'], a[data-toxic='group']")
  .addClass('toxic_zoom');

$(new Image())
  .attr('src', iu+'loader.gif');

if (l=='ru') {
  cl=rl;
  } else {
  cl=el;
}

//correction for Mobile

function FixWidthForMobile() {
  if((navigator.userAgent.indexOf("Presto") + 1)||(navigator.userAgent.indexOf("iPhone") + 1)||(navigator.userAgent.indexOf("iPad") + 1)||(navigator.userAgent.indexOf("Android") + 1)) {
    width = window.innerWidth ;
  }
}

FixWidthForMobile();

function get_zoom(){
  zoom = Math.round(((window.outerWidth) / window.innerWidth)*100) / 100;
  return zoom;
}

document.body.addEventListener('touchend', function(e){
  zoom = get_zoom();
  width =(screen.width)/zoom;height = window.innerHeight;
  FixWidthForMobile();
}, false);

$( window ).resize(function() {
  if (!isMobile.any()){
    var ts=$("#toxic_showbox");
    zoom = get_zoom();
    width =$(window).width();height = $(window).height();
    if(ts){
      ts.css({'margin-left':0+'px','margin-top':0+'px','left':((width/2)-((cw)/2+ps)+$(window).scrollLeft())+'px','top':((height/2+$(window).scrollTop())-((ch)/2+ps))+'px'});
      if (parseInt(ts.css('top'))<0){ts.css('top','0');}
          }
                      }
});

//Processing loader

function image_start_load (){
  $('body')
    .prepend('');
}

function image_start_load_fix (){
  $('#toxic_loading')
    .fadeIn(100);
}

//Display of images

function chk_arrow(){
  if (!back_src) $('#toxic_showbox .toxic_larrow a').remove();
  if (!next_src) $('#toxic_showbox .toxic_rarrow a').remove();
}
function check_images(ct){
  var ts=$("#toxic_showbox"),
    tl=$('#toxic_loading'),
    cin,
    i;
  function fix_img_height(correct){
    $(correct)
      .css({'max-height':''+(height-ttx.height()-ps*2)+'px','width':'auto'});
    cw=$(correct).width();
    $(correct).css('width',cw+'px');
    ch = $(correct).height();
    }
    ts
      .prepend('

');
    var ttx=$('#toxic_textarea');
    for(i=0;i<ci;i++){
      if(cd==ai[i]) {
        cin=i+1;
        back_src=ai[i-1];
        next_src=ai[i+1];
        $(new Image())
          .attr('src', $(back_src).attr('href'));
        $(new Image())
          .attr('src', $(next_src).attr('href'));
        break;
      }
    }
    $(".toxic_current")
      .load(function() {
        ch = $(this).height();
        cw = $(this).width();
        fix_img_height(this);
        if(ct){
          if (is_single==2 ) {
              ttx
                .css('width',(cw-ps*2-40))
                .html('

'+cl.im+' '+cin+' '+cl.o+' '+ci+'

'+ct+'
');
                chk_arrow();
          }
          if (is_single==1 ) {
              ttx
                .html('
'+ct+'
');
          }
        }else{
          if (is_single==2 ) {
              ttx
                .html('
'+cl.im+' '+cin+' '+cl.o+' '+ci+'
')
                .prepend('

');
                chk_arrow();
		  }
          if (is_single==1 ){
              ttx
                .css('height',20+'px')
                .css('min-height',0);
		  }
        }

        fix_img_height(this);

        // TODO: Recall fix_img_height makes the calculation more precise

        $('#toxic_showbox .toxic_rarrow, #toxic_showbox .toxic_larrow')
          .css('width',''+((cw+20)/2-10)+'px');
        ch=ttx.height()+ch;
        ts
          .prepend('');
        $('#toxic_close')
          .css({'margin-left':(cw-20)+'px','margin-top':(ch-20)+'px'});
        ts
          .animate( {
            width:cw,
            height:ch,
            marginLeft:-(cw/2-(old_width)/2),
            marginTop:(-height/2+(height-ch)/2+old_height/2)
          },
		  500/sp,
		  function() {
		    tl
		      .fadeOut(100);
		    ttx
		      .css('width',(cw-40));
		      $('#toxic_showbox .toxic_current, #toxic_showbox #toxic_textarea, #toxic_showbox #toxic_close').fadeIn(200/sp);
		      }
		  );
      });
}

function st_set_after_cl_img() {
  var ct=$(cd).attr('title');
    $('body')
      .append('

');
    image_start_load();
    $(new Image())
      .attr('src', ''+$(cd).attr('href')+'')
      .load(check_images(ct));
    }

//Display of containers

function standart_setting_after_click_databox () {
    current_databox = $('#'+$(cd).attr('data-toxic-databox'));
    $('body')
      .append('

');
    var ts=$("#toxic_showbox");
    image_start_load();
    var tl=$('#toxic_loading');
    cw=current_databox.width()+(parseInt(current_databox.css('border-left-width')))+(parseInt(current_databox.css('border-right-width')))+(parseInt(current_databox.css('paddingLeft')))+(parseInt(current_databox.css('paddingLeft')));
    if (cw==width) {
      if (auto_width=='on') {
        cw=basic_width;
        $(current_databox)
          .css('width',cw+'px');
      }else {
        cw=width-ps*2;
      }
    }
    if (cw>width) {
      cw=width-(parseInt(current_databox.css('border-left-width')))-(parseInt(current_databox.css('border-right-width')))-(parseInt(current_databox.css('paddingLeft')))-(parseInt(current_databox.css('paddingLeft')))-ps*2;
      current_databox
        .css({'width':cw+'px','height':'auto'})
        .find('iframe')
        .attr('width',cw);
    }
    if ($(cd).attr('title')) {
      ts
        .prepend('
'+$(cd).attr('title')+'
');
      ch = $(current_databox).height()+parseInt($('#toxic_h2').css( 'height'))+20+(parseInt(current_databox.css('border-top-width')))+(parseInt(current_databox.css('border-bottom-width')))+(parseInt(current_databox.css('padding-top')))+(parseInt(current_databox.css('padding-bottom')));
    }else {
      ch = $(current_databox).height()+20+(parseInt(current_databox.css('border-top-width')))+(parseInt(current_databox.css('border-bottom-width')))+(parseInt(current_databox.css('padding-top')))+(parseInt(current_databox.css('padding-bottom')));
    }
    ts
      .animate( {
        width:cw,
        height:ch,
        marginLeft:-(cw/2-old_width/2),
        marginTop:(-height/2+(height-ch)/2+old_height/2)
	  },
      500/sp,
      function() {
        ts
          .append(current_databox)
          .append('')
          .css({'min-height':ch+'px','height':'auto'});
        current_databox.fadeIn(200/sp);
        $('#toxic_close.div_close')
          .css('margin-left',''+cw-20+'px')
          .fadeIn(200/sp);
        $('#toxic_h2').fadeIn(200/sp);
        tl
          .fadeOut(100, function(){
	        $(this).remove();
          });
        if ((parseInt(ts.css('top')))+(parseInt(ts.css('margin-top'))-$(window).scrollTop())<0) {
          ts
            .css('margin-top','0')
            .css('top',$(window).scrollTop());
        }
      });
}

//Display of notifications

function standart_setting_after_click_alert () {
  current_databox = $(cd)
    .attr('data-toxic-alert');
  $('body')
    .append('

');
  var ts=$("#toxic_showbox");
  ts
    .html('
'+current_databox+'
')
    .prepend('');
  image_start_load();
  var tl=$('#toxic_loading'),
    tsp=$("#toxic_showbox p");
  cw=tsp.width();
  ch=tsp.height()+20;
  if (cw>=width) {
    cw=width-ps*2;
    $("#toxic_showbox p.alert")
      .css('max-width',cw+'px');
    ch=tsp.height()+20;
  }
  ts
    .animate( {
      width:cw,
      height:ch,
      marginLeft:-(cw/2-old_width/2),
      marginTop:(-height/2+(height-ch)/2+old_height/2)
    },
    500/sp,
    function() {
      tsp.fadeIn(200/sp);
      $('#toxic_close.images_close')
        .css({'margin-left':''+cw-20+'px','margin-top':''+(ch-21)+'px'})
        .fadeIn(200/sp);
      tl
        .fadeOut(100, function(){
          $(this).remove();
        });
    });
}

//press the left - right

function get_new_img (correct, ct){
  cd = correct;
  ct=$(cd).attr('title');
  image_start_load_fix();
  $(new Image())
    .attr('src',$(cd).attr('href'))
    .load(function(){
      $('#toxic_showbox .toxic_current,#toxic_showbox #toxic_textarea, #toxic_showbox #toxic_close, #toxic_showbox #toxic_arrow_carrier').remove();
      check_images(ct);
    });
}

$( document )
  .on( "click", ".toxic_larrow a", function() {
    get_new_img(back_src);
    return false;
  })
  .on( "click", ".toxic_rarrow a", function() {
    get_new_img(next_src);
    return false;
  })
  .on( "click", 'a[data-toxic="group"]', function() {
    is_single=2;
    cd=this;
    st_set_after_cl_img();
    return false;
  })
  .on( "click", 'a[data-toxic="single"]', function() {
    is_single=1;
    cd=this;
    st_set_after_cl_img();
    return false;
  })
  .on( "click", '[data-toxic-databox]', function() {
    is_single=3;
    cd=this;
    standart_setting_after_click_databox();
    return false;
  })
  .on( "click", '[data-toxic-alert]', function() {
    is_single=3;
    cd=this;
    standart_setting_after_click_alert();
    return false;
  })
  .on( "click", "#toxic_dark, #toxic_close", function() {
    close_all();
    return false;
  })
  .keyup(function(e) {
    if (e.keyCode == 27) close_all();
  });

function close_all() {
  old_width=$('#toxic_showbox').width();
  old_height=$('#toxic_showbox').height();
  $('#toxic_dark, #toxic_showbox, #toxic_loading')
    .fadeOut(200/sp, function(){
      if($('#toxic_showbox').find('.div_close').length){
        $('body')
          .append(current_databox);
        current_databox
          .css('display','none');
      }
      if (is_single!=3){
        $('#toxic_loading')
          .remove();
      }
      $('#toxic_dark, #toxic_showbox')
        .remove();
    });
  return false;
}

})();});
<commit_msg>Delete jquery.toxicbox-1.0.6.js<commit_after><|endoftext|>


<commit_before>/**
 * Shows gene domains.
 */
(function( $, undefined ) {
    $.KBWidget({
        name: "KBaseGeneDomains",
        parent: "kbaseWidget",
        version: "1.0.0",

        options: {
            featureID: null,
            embedInCard: false,
            auth: null,
            loadingImage: "assets/img/loading.gif",
            genomeID: null,
            workspaceID: null,
            kbCache: null
        },

        init: function(options) {
            this._super(options);
            this.wsClient = this.options.kbCache.ws;

            this.render();

            return this;
        },

        render: function() {
            var self = this;

            self.$elem.append($('
').css("overflow","auto"));
            var $maindiv = self.$elem.find('#mainview');
            $maindiv.append('
');

            // Launch the first step in processing the data for the table
            this.processDomainAnnotationObjects();

        },

        processDomainAnnotationObjects: function(){
            var self = this;

            // Get DomainAnnotation objects referenced by a given genome
            var genomeIdentityObj = self.buildObjectIdentity(self.options.workspaceID, self.options.genomeID);
            self.wsClient.list_referencing_objects([genomeIdentityObj], function(data){

                var domainAnnotationObjectRefs = {};

                var objectRefs = data[0];
                for(var i = 0; i < objectRefs.length; i++){

                    var objectType = objectRefs[i][2];

                    if( /.DomainAnnotation-/.exec(objectType) ){
                        var wsId = objectRefs[i][6];
                        var objId = objectRefs[i][0];
                        var objVer = objectRefs[i][4];

                        var objRef = wsId + "/" + objId;
                        domainAnnotationObjectRefs[objRef] = objectRefs[i];
                    }
                }

                // if there are domain annotation objects then proceed to the next step
                // which is collecting ContigIndexElements
                if( ! $.isEmptyObject(domainAnnotationObjectRefs)){
                    self.processContigIndexElements(domainAnnotationObjectRefs);
                }
            });
        },

        processContigIndexElements: function(domainAnnotationObjectRefs){
            var self = this;

            // Build subObjectIdentities that will be later used as parameters to get contig ids and gene indexes
            // in DomainAnnotation objects
            var subObjectIdentities = [];
            var domainModelSetRefs = {};
            for(var objRef in domainAnnotationObjectRefs){
                subObjectIdentities.push({
                    'ref':objRef,
                    'included':['/feature_to_contig_and_index/' + self.options.featureID, '/used_dms_ref']
                });
            }

            // Get contigAndIndexElements that will be later used to get actual domain annotations
            var contigAndIndexElements = [];
            self.wsClient.get_object_subset(subObjectIdentities, function(data){

                for(var i = 0 ; i < data.length; i++){
                    var feature_to_contig_and_index = data[i].data.feature_to_contig_and_index;
                    var wsId = data[i].info[6];
                    var objId = data[i].info[0];
                    var objVer = data[i].info[4];

                    var dmsRef = data[i].data.used_dms_ref;
                    if( dmsRef != undefined){
                        domainModelSetRefs[dmsRef] = dmsRef;
                    }

                    for(var fci in feature_to_contig_and_index){

                        contigAndIndexElements.push({
                            'annObjectRef' : wsId + "/" + objId,
                            'contigId' : feature_to_contig_and_index[fci][0],
                            'geneIndex' : feature_to_contig_and_index[fci][1]
                        });
                    }
                }

                // if there domain annotation objects then proceed to the next step
                // which is collecting ContigIndexElements
                if( contigAndIndexElements.length > 0){
                    self.processDomainAnnotations(contigAndIndexElements, domainModelSetRefs);
                }
            });
        },

        processDomainAnnotations: function(contigAndIndexElements, domainModelSetRefs){
          var self = this;

            // Build subObjectIdentities that will be later used as parameters to get contig ids and gene indexes
            // in DomainAnnotation objects
            var subObjectIdentities = [];
            for(var i = 0; i < contigAndIndexElements.length; i++){
                var cgiElement = contigAndIndexElements[i];
                subObjectIdentities.push({
                    'ref':cgiElement['annObjectRef'],
                    'included':['/data' + '/' + cgiElement['contigId'] + '/' + cgiElement['geneIndex'] ]
                });
            }

            // Get domain annotations
            var uniqueDomains = {};
            var annotatedDomainsArray = [];
            self.wsClient.get_object_subset(subObjectIdentities, function(data){

                for(var i = 0 ; i < data.length; i++){
                    var wsId = data[i].info[6];
                    var objId = data[i].info[0];
                    var objVer = data[i].info[4];

                    for(var contigId in data[i].data.data){
                        var genesArray = data[i].data.data[contigId];
                        for(var j = 0 ; j < genesArray.length; j++){
                            var geneId = genesArray[j][0];
                            var geneStart = genesArray[j][1];
                            var geneEnd = genesArray[j][2];
                            var domainsInfo = genesArray[j][4];
                            for(var domainId in domainsInfo){
                                var domainsArray = domainsInfo[domainId];
                                for(var k = 0 ; k < domainsArray.length; k++){
                                    var domainStart = domainsArray[k][0];
                                    var domainEnd = domainsArray[k][1];
                                    var eValue = domainsArray[k][2];

                                    var domainSignature = domainId + "_" + domainStart + "_" + domainEnd;
                                    if(uniqueDomains[domainSignature] == undefined){
                                        uniqueDomains[domainSignature] = "";
                                    } else {
                                        // Because we mingh have several SAME domain annotations that came from
                                        // different DomainAnnotation objects linked to a given genome
                                        continue;
                                    }

                                    var domainImgWidth = (domainEnd - domainStart)*100/(geneEnd - geneStart);
                                    var  domainImgleftShift = (domainStart)*100/(geneEnd - geneStart);

                                    annotatedDomainsArray.push({
                                        'wsId': wsId,
                                        'objId': objId,
                                        'objVer' : objVer,
                                        'objRef': wsId + '/' + objId + "/" + objVer,
                                        'contigId' : contigId,
                                        'geneId' : geneId,
                                        'geneStart' : geneStart,
                                        'geneEnd' : geneEnd,
                                        'domainId' : domainId,
                                        'domainDescription' : '',
                                        'domainStart': domainStart,
                                        'domainEnd' : domainEnd,
                                        'eValue' : eValue,
                                        'image' : '
'
                                                + '

'
                                    });
                                }
                            }
                        }
                    }
                }

                // if there domain annotation objects then proceed to the next step: collect domain descriptions
                if( annotatedDomainsArray.length > 0){
                    self.processDomainDescirptions(annotatedDomainsArray, domainModelSetRefs);
                }

            });
        },

        processDomainDescirptions: function(annotatedDomainsArray, domainModelSetRefs){
            var self = this;

            var domainIds = {};
            for(var i = 0; i < annotatedDomainsArray.length; i++){
                domainIds[annotatedDomainsArray[i].domainId] = "";
            }

            // Build subObjectIdentities that will be later used as parameters to get contig ids and gene indexes
            // in DomainAnnotation objects
            var subObjectIdentities = [];
            for(var dms in domainModelSetRefs){
                var domainRefs = [];
                for(var domainId in domainIds){
                    domainRefs.push('/domain_accession_to_description/' + domainId);
                }
                subObjectIdentities.push({
                    'ref':dms,
                    'included': domainRefs
                });
            }

            var domainDescriptions = {};
            // Get domain annotations
            self.wsClient.get_object_subset(subObjectIdentities, function(data){

                //Get a hash of domain description
                for(var i = 0 ; i < data.length; i++){

                    var _domainDescriptions = data[i].data.domain_accession_to_description;
                    if(_domainDescriptions == undefined) continue;
                    for(var domainId in _domainDescriptions){
                        domainDescriptions[domainId] = _domainDescriptions[domainId];
                    }
                }

                // Update descriptions of domains in annotatedDomainsArray
                for(var i = 0; i < annotatedDomainsArray.length; i++){
                    var domainDescription = domainDescriptions[annotatedDomainsArray[i].domainId];
                    if(domainDescription != undefined){
                        annotatedDomainsArray[i].domainDescription = domainDescription;
                    }
                }

                // if there domain annotation objects then proceed to the next step: collect domain descriptions
                if( annotatedDomainsArray.length > 0){
                    self.bindDomainData(annotatedDomainsArray);
                }

            });
        },

        bindDomainData: function(annotatedDomainsArray){
            var self = this;

            var sDom = 't<fip>'
            if (annotatedDomainsArray.length<=10) {
                sDom = 'tfi';
            }

            var tblSettings = {
                //"sPaginationType": "full_numbers",
                "iDisplayLength": 10,
                "sDom": sDom,
                "aoColumns": [
                    {sTitle: "Domain", mData: "domainId"},
                    {sTitle: "Description", mData: "domainDescription", sWidth:"30%"},
                    {sTitle: "Location", mData: "image"},
                    {sTitle: "Start", mData: "domainStart"},
                    {sTitle: "End", mData: "domainEnd"},
                    {sTitle: "eValue", mData: "eValue"},
                    {sTitle: "DomainAnnotation object", mData: "objRef"}
                ],
                "aaData": annotatedDomainsArray
            };
            self.$elem.find('#ref-table').dataTable(tblSettings);

        },

        buildObjectIdentity: function(workspaceID, objectID) {
            var obj = {};
            if (/^\d+$/.exec(workspaceID))
                obj['wsid'] = workspaceID;
            else
                obj['workspace'] = workspaceID;

            // same for the id
            if (/^\d+$/.exec(objectID))
                obj['objid'] = objectID;
            else
                obj['name'] = objectID;
            return obj;
        },

        getData: function() {
            return {
                type: "Feature",
                id: this.options.featureID,
                workspace: this.options.workspaceID,
                title: "Gene Domains"
            };
        },

        showMessage: function(message) {
            var span = $("").append(message);

            this.$messagePane.empty()
                             .append(span)
                             .removeClass("kbwidget-hide-message");
        },

        hideMessage: function() {
            this.$messagePane.addClass("kbwidget-hide-message");
        },

        renderError: function(error) {
            errString = "Sorry, an unknown error occurred";
            if (typeof error === "string")
                errString = error;
            else if (error.error && error.error.message)
                errString = error.error.message;

            var $errorDiv = $("
")
                            .addClass("alert alert-danger")
                            .append("Error:")
                            .append("
" + errString);
            this.$elem.empty();
            this.$elem.append($errorDiv);
        },
    })
})( jQuery );<commit_msg>Updated kbaseGeneDomains card to toggle on click between short and ridiculously long domain descriptions<commit_after>/**
 * Shows gene domains.
 */
(function( $, undefined ) {
    $.KBWidget({
        name: "KBaseGeneDomains",
        parent: "kbaseWidget",
        version: "1.0.1",

        options: {
            featureID: null,
            embedInCard: false,
            auth: null,
            loadingImage: "assets/img/loading.gif",
            genomeID: null,
            workspaceID: null,
            kbCache: null,
	    maxDescriptionLength: 100
        },

        init: function(options) {
            this._super(options);
            this.wsClient = this.options.kbCache.ws;

            this.render();

            return this;
        },

        render: function() {
            var self = this;

            self.$elem.append($('
').css("overflow","auto"));
            var $maindiv = self.$elem.find('#mainview');
            $maindiv.append('
');

            // Launch the first step in processing the data for the table
            this.processDomainAnnotationObjects();
        },

        processDomainAnnotationObjects: function(){
            var self = this;

            // Get DomainAnnotation objects referenced by a given genome
            var genomeIdentityObj = self.buildObjectIdentity(self.options.workspaceID, self.options.genomeID);
            self.wsClient.list_referencing_objects([genomeIdentityObj], function(data){

                var domainAnnotationObjectRefs = {};

                var objectRefs = data[0];
                for(var i = 0; i < objectRefs.length; i++){

                    var objectType = objectRefs[i][2];

                    if( /.DomainAnnotation-/.exec(objectType) ){
                        var wsId = objectRefs[i][6];
                        var objId = objectRefs[i][0];
                        var objVer = objectRefs[i][4];

                        var objRef = wsId + "/" + objId;
                        domainAnnotationObjectRefs[objRef] = objectRefs[i];
                    }
                }

                // if there are domain annotation objects then proceed to the next step
                // which is collecting ContigIndexElements
                if( ! $.isEmptyObject(domainAnnotationObjectRefs)){
                    self.processContigIndexElements(domainAnnotationObjectRefs);
                }
            });
        },

        processContigIndexElements: function(domainAnnotationObjectRefs){
            var self = this;

            // Build subObjectIdentities that will be later used as parameters to get contig ids and gene indexes
            // in DomainAnnotation objects
            var subObjectIdentities = [];
            var domainModelSetRefs = {};
            for(var objRef in domainAnnotationObjectRefs){
                subObjectIdentities.push({
                    'ref':objRef,
                    'included':['/feature_to_contig_and_index/' + self.options.featureID, '/used_dms_ref']
                });
            }

            // Get contigAndIndexElements that will be later used to get actual domain annotations
            var contigAndIndexElements = [];
            self.wsClient.get_object_subset(subObjectIdentities, function(data){

                for(var i = 0 ; i < data.length; i++){
                    var feature_to_contig_and_index = data[i].data.feature_to_contig_and_index;
                    var wsId = data[i].info[6];
                    var objId = data[i].info[0];
                    var objVer = data[i].info[4];

                    var dmsRef = data[i].data.used_dms_ref;
                    if( dmsRef != undefined){
                        domainModelSetRefs[dmsRef] = dmsRef;
                    }

                    for(var fci in feature_to_contig_and_index){

                        contigAndIndexElements.push({
                            'annObjectRef' : wsId + "/" + objId,
                            'contigId' : feature_to_contig_and_index[fci][0],
                            'geneIndex' : feature_to_contig_and_index[fci][1]
                        });
                    }
                }

                // if there domain annotation objects then proceed to the next step
                // which is collecting ContigIndexElements
                if( contigAndIndexElements.length > 0){
                    self.processDomainAnnotations(contigAndIndexElements, domainModelSetRefs);
                }
            });
        },

        processDomainAnnotations: function(contigAndIndexElements, domainModelSetRefs){
          var self = this;

            // Build subObjectIdentities that will be later used as parameters to get contig ids and gene indexes
            // in DomainAnnotation objects
            var subObjectIdentities = [];
            for(var i = 0; i < contigAndIndexElements.length; i++){
                var cgiElement = contigAndIndexElements[i];
                subObjectIdentities.push({
                    'ref':cgiElement['annObjectRef'],
                    'included':['/data' + '/' + cgiElement['contigId'] + '/' + cgiElement['geneIndex'] ]
                });
            }

            // Get domain annotations
            var uniqueDomains = {};
            var annotatedDomainsArray = [];
            self.wsClient.get_object_subset(subObjectIdentities, function(data){

                for(var i = 0 ; i < data.length; i++){
                    var wsId = data[i].info[6];
                    var objId = data[i].info[0];
                    var objVer = data[i].info[4];

                    for(var contigId in data[i].data.data){
                        var genesArray = data[i].data.data[contigId];
                        for(var j = 0 ; j < genesArray.length; j++){
                            var geneId = genesArray[j][0];
                            var geneStart = genesArray[j][1];
                            var geneEnd = genesArray[j][2];
                            var domainsInfo = genesArray[j][4];
                            for(var domainId in domainsInfo){
                                var domainsArray = domainsInfo[domainId];
                                for(var k = 0 ; k < domainsArray.length; k++){
                                    var domainStart = domainsArray[k][0];
                                    var domainEnd = domainsArray[k][1];
                                    var eValue = domainsArray[k][2];

                                    var domainSignature = domainId + "_" + domainStart + "_" + domainEnd;
                                    if(uniqueDomains[domainSignature] == undefined){
                                        uniqueDomains[domainSignature] = "";
                                    } else {
                                        // Because we might have several SAME domain annotations that came from
                                        // different DomainAnnotation objects linked to a given genome
                                        continue;
                                    }

                                    var domainImgWidth = (domainEnd - domainStart)*100/(geneEnd - geneStart);
                                    var  domainImgleftShift = (domainStart)*100/(geneEnd - geneStart);

                                    annotatedDomainsArray.push({
                                        'wsId': wsId,
                                        'objId': objId,
                                        'objVer' : objVer,
                                        'objRef': wsId + '/' + objId + "/" + objVer,
                                        'contigId' : contigId,
                                        'geneId' : geneId,
                                        'geneStart' : geneStart,
                                        'geneEnd' : geneEnd,
                                        'domainId' : domainId,
                                        'domainDescription' : '',
                                        'domainStart': domainStart,
                                        'domainEnd' : domainEnd,
                                        'eValue' : eValue,
                                        'image' : '
'
                                                + '

'
                                    });
                                }
                            }
                        }
                    }
                }

                // if there domain annotation objects then proceed to the next step: collect domain descriptions
                if( annotatedDomainsArray.length > 0){
                    self.processDomainDescirptions(annotatedDomainsArray, domainModelSetRefs);
                }

            });
        },

        processDomainDescirptions: function(annotatedDomainsArray, domainModelSetRefs){
            var self = this;

            var domainIds = {};
            for(var i = 0; i < annotatedDomainsArray.length; i++){
                domainIds[annotatedDomainsArray[i].domainId] = "";
            }

            // Build subObjectIdentities that will be later used as parameters to get contig ids and gene indexes
            // in DomainAnnotation objects
            var subObjectIdentities = [];
            for(var dms in domainModelSetRefs){
                var domainRefs = [];
                for(var domainId in domainIds){
                    domainRefs.push('/domain_accession_to_description/' + domainId);
                }
                subObjectIdentities.push({
                    'ref':dms,
                    'included': domainRefs
                });
            }

            var domainDescriptions = {};
            var shortDomainDescriptions = {};
            // Get domain annotations
            self.wsClient.get_object_subset(subObjectIdentities, function(data){

                //Get a hash of domain description
                for(var i = 0 ; i < data.length; i++){
                    var _domainDescriptions = data[i].data.domain_accession_to_description;
                    if(_domainDescriptions == undefined) continue;
                    for(var domainId in _domainDescriptions){
                        domainDescriptions[domainId] = _domainDescriptions[domainId];
                        shortDomainDescriptions[domainId] = _domainDescriptions[domainId];
			if (shortDomainDescriptions[domainId].length > self.options.maxDescriptionLength) {
			    shortDomainDescriptions[domainId] = shortDomainDescriptions[domainId].substring(0,self.options.maxDescriptionLength) + "…";
			}
                    }
                }

                // Update descriptions of domains in annotatedDomainsArray
		for(var i = 0; i < annotatedDomainsArray.length; i++){
                    var domainDescription = shortDomainDescriptions[annotatedDomainsArray[i].domainId];
                    if(domainDescription != undefined){
                        annotatedDomainsArray[i].domainDescription = domainDescription;
                        annotatedDomainsArray[i].shortDomainDescription = domainDescription;
                        annotatedDomainsArray[i].longDomainDescription = domainDescriptions[annotatedDomainsArray[i].domainId];
                    }
                }

                // if there domain annotation objects then proceed to the next step: collect domain descriptions
                if( annotatedDomainsArray.length > 0){
                    self.bindDomainData(annotatedDomainsArray);
                }
            });
        },

        bindDomainData: function(annotatedDomainsArray){
            var self = this;

            var sDom = 't<fip>'
            if (annotatedDomainsArray.length<=10) {
                sDom = 'tfi';
            }

            var tblSettings = {
                //"sPaginationType": "full_numbers",
                "iDisplayLength": 10,
                "sDom": sDom,
                "aoColumns": [
                    {sTitle: "Domain", mData: "domainId"},
                    {sTitle: "Description", mData: "domainDescription", sWidth:"30%"},
                    {sTitle: "Location", mData: "image"},
                    {sTitle: "Start", mData: "domainStart"},
                    {sTitle: "End", mData: "domainEnd"},
                    {sTitle: "eValue", mData: "eValue"},
                    {sTitle: "DomainAnnotation object", mData: "objRef"}
                ],
                "aaData": annotatedDomainsArray
            };
            var domainTable = self.$elem.find('#ref-table').dataTable(tblSettings);
	    var showLong = [];
	    $('#ref-table tbody td').click(function(event) {
		var rowID = domainTable.fnGetPosition(event.target)[0];
		if (showLong[rowID] == undefined)
		    showLong[rowID] = 0;
		showLong[rowID] = 1-showLong[rowID];
		if (showLong[rowID]==1) {
		    domainTable.fnUpdate(annotatedDomainsArray[rowID].longDomainDescription,rowID,1);
		}
		else {
		    domainTable.fnUpdate(annotatedDomainsArray[rowID].shortDomainDescription,rowID,1);
		}
	    });
        },

        buildObjectIdentity: function(workspaceID, objectID) {
            var obj = {};
            if (/^\d+$/.exec(workspaceID))
                obj['wsid'] = workspaceID;
            else
                obj['workspace'] = workspaceID;

            // same for the id
            if (/^\d+$/.exec(objectID))
                obj['objid'] = objectID;
            else
                obj['name'] = objectID;
            return obj;
        },

        getData: function() {
            return {
                type: "Feature",
                id: this.options.featureID,
                workspace: this.options.workspaceID,
                title: "Gene Domains"
            };
        },

        showMessage: function(message) {
            var span = $("").append(message);

            this.$messagePane.empty()
                             .append(span)
                             .removeClass("kbwidget-hide-message");
        },

        hideMessage: function() {
            this.$messagePane.addClass("kbwidget-hide-message");
        },

        renderError: function(error) {
            errString = "Sorry, an unknown error occurred";
            if (typeof error === "string")
                errString = error;
            else if (error.error && error.error.message)
                errString = error.error.message;

            var $errorDiv = $("
")
                            .addClass("alert alert-danger")
                            .append("Error:")
                            .append("
" + errString);
            this.$elem.empty();
            this.$elem.append($errorDiv);
        },
    })
})( jQuery );<|endoftext|>


<commit_before>window.fakeStorage = {
  _data: {},

  setItem: function (id, val) {
    return this._data[id] = String(val);
  },

  getItem: function (id) {
    return this._data.hasOwnProperty(id) ? this._data[id] : undefined;
  },

  removeItem: function (id) {
    return delete this._data[id];
  },

  clear: function () {
    return this._data = {};
  }
};

function LocalStorageManager() {
  this.bestScoreKey     = "bestScore";
  this.gameStateKey     = "gameState";

  var supported = this.localStorageSupported();
  this.storage = supported ? window.localStorage : window.fakeStorage;
}

LocalStorageManager.prototype.localStorageSupported = function () {
  var testKey = "test";
  var storage = window.localStorage;

  try {
    storage.setItem(testKey, "1");
    storage.removeItem(testKey);
    return true;
  } catch (error) {
    return false;
  }
};

// Best score getters/setters
LocalStorageManager.prototype.getBestScore = function () {
  return this.storage.getItem(this.bestScoreKey) || 0;
};

LocalStorageManager.prototype.setBestScore = function (score) {
  this.storage.setItem(this.bestScoreKey, score);
};

// Game state getters/setters and clearing
LocalStorageManager.prototype.getGameState = function () {
  var stateJSON = this.storage.getItem(this.gameStateKey);
  return stateJSON ? JSON.parse(stateJSON) : null;
};

LocalStorageManager.prototype.setGameState = function (gameState) {
  this.storage.setItem(this.gameStateKey, JSON.stringify(gameState));
};

LocalStorageManager.prototype.clearGameState = function () {
  this.storage.removeItem(this.gameStateKey);
};
<commit_msg>Update local_storage_manager.js<commit_after>window.fakeStorage = {
  _data: {},

  setItem: function (id, val) {
    return this._data[id] = String(val);
  },

  getItem: function (id) {
    return this._data.hasOwnProperty(id) ? this._data[id] : undefined;
  },

  removeItem: function (id) {
    return delete this._data[id];
  },

  clear: function () {
    return this._data = {};
  }
};

function LocalStorageManager() {
  this.bestScoreKey     = "bestScoreStarwars";
  this.gameStateKey     = "gameStateStarwars";

  var supported = this.localStorageSupported();
  this.storage = supported ? window.localStorage : window.fakeStorage;
}

LocalStorageManager.prototype.localStorageSupported = function () {
  var testKey = "test";
  var storage = window.localStorage;

  try {
    storage.setItem(testKey, "1");
    storage.removeItem(testKey);
    return true;
  } catch (error) {
    return false;
  }
};

// Best score getters/setters
LocalStorageManager.prototype.getBestScore = function () {
  return this.storage.getItem(this.bestScoreKey) || 0;
};

LocalStorageManager.prototype.setBestScore = function (score) {
  this.storage.setItem(this.bestScoreKey, score);
};

// Game state getters/setters and clearing
LocalStorageManager.prototype.getGameState = function () {
  var stateJSON = this.storage.getItem(this.gameStateKey);
  return stateJSON ? JSON.parse(stateJSON) : null;
};

LocalStorageManager.prototype.setGameState = function (gameState) {
  this.storage.setItem(this.gameStateKey, JSON.stringify(gameState));
};

LocalStorageManager.prototype.clearGameState = function () {
  this.storage.removeItem(this.gameStateKey);
};
<|endoftext|>