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

	var L = require('leaflet'),
		Waypoint = L.Class.extend({
			initialize: function(latLng, name) {
				this.latLng = latLng;
				this.name = name;
			}
		});

	L.Routing = L.Routing || {};
	L.extend(L.Routing, require('./L.Routing.Autocomplete'));

	function selectInputText(input) {
		if (input.setSelectionRange) {
			// On iOS, select() doesn't work
			input.setSelectionRange(0, 9999);
		} else {
			// On at least IE8, setSeleectionRange doesn't exist
			input.select();
		}
	}

	L.Routing.Plan = L.Class.extend({
		includes: L.Mixin.Events,

		options: {
			dragStyles: [
				{color: 'black', opacity: 0.15, weight: 9},
				{color: 'white', opacity: 0.8, weight: 6},
				{color: 'red', opacity: 1, weight: 2, dashArray: '7,12'}
			],
			draggableWaypoints: true,
			addWaypoints: true,
			maxGeocoderTolerance: 200,
			autocompleteOptions: {},
			geocodersClassName: '',
			geocoderClassName: '',
			geocoderPlaceholder: function(i, numberWaypoints) {
				return i === 0 ?
					'Start' :
					(i < numberWaypoints - 1 ?
									'Via ' + i :
									'End');
			},
			geocoderClass: function() {
				return '';
			},
			createGeocoder: function() {
				var e = L.DomUtil.create('input', '');
				return {
					container: e,
					input: e
				};
			},
			waypointNameFallback: function(latLng) {
				var ns = latLng.lat < 0 ? 'S' : 'N',
				    ew = latLng.lng < 0 ? 'W' : 'E',
				    lat = (Math.round(Math.abs(latLng.lat) * 10000) / 10000).toString(),
				    lng = (Math.round(Math.abs(latLng.lng) * 10000) / 10000).toString();
				return ns + lat + ', ' + ew + lng;
			}
		},

		initialize: function(waypoints, options) {
			L.Util.setOptions(this, options);
			this._waypoints = [];
			this.setWaypoints(waypoints);
		},

		isReady: function() {
			var i;
			for (i = 0; i < this._waypoints.length; i++) {
				if (!this._waypoints[i].latLng) {
					return false;
				}
			}

			return true;
		},

		getWaypoints: function() {
			var i,
				wps = [];

			for (i = 0; i < this._waypoints.length; i++) {
				wps.push(this._waypoints[i]);
			}

			return wps;
		},

		setWaypoints: function(waypoints) {
			var args = [0, this._waypoints.length].concat(waypoints);
			this.spliceWaypoints.apply(this, args);
			return this;
		},

		spliceWaypoints: function() {
			var args = [arguments[0], arguments[1]],
			    i,
			    wp;

			for (i = 2; i < arguments.length; i++) {
				args.push(arguments[i] && arguments[i].hasOwnProperty('latLng') ? arguments[i] : new Waypoint(arguments[i]));
			}

			[].splice.apply(this._waypoints, args);

			while (this._waypoints.length < 2) {
				wp = new Waypoint();
				this._waypoints.push(wp);
				args.push(wp);
			}

			this._updateMarkers();
			this._fireChanged.apply(this, args);
		},

		onAdd: function(map) {
			this._map = map;
			this._updateMarkers();
		},

		onRemove: function() {
			var i;
			this._removeMarkers();

			if (this._newWp) {
				for (i = 0; i < this._newWp.lines.length; i++) {
					this._map.removeLayer(this._newWp.lines[i]);
				}
			}

			delete this._map;
		},

		createGeocoders: function() {
			var container = L.DomUtil.create('div', 'leaflet-routing-geocoders ' + this.options.geocodersClassName),
				waypoints = this._waypoints,
			    i,
			    geocoderElem,
			    addWpBtn;

			this._geocoderContainer = container;
			this._geocoderElems = [];

			for (i = 0; i < waypoints.length; i++) {
				geocoderElem = this._createGeocoder(i);
				container.appendChild(geocoderElem.container);
				this._geocoderElems.push(geocoderElem);
			}

			addWpBtn = L.DomUtil.create('button', '', container);
			addWpBtn.setAttribute('type', 'button');
			addWpBtn.innerHTML = '+';
			if (this.options.addWaypoints) {
				L.DomEvent.addListener(addWpBtn, 'click', function() {
					this.spliceWaypoints(waypoints.length, 0, null);
				}, this);
			} else {
				addWpBtn.style.display = 'none';
			}

			this.on('waypointsspliced', this._updateGeocoders);

			return container;
		},

		_createGeocoder: function(i) {
			var nWps = this._waypoints.length,
				g = this.options.createGeocoder(i, nWps),
				geocoderInput = g.input,
				wp = this._waypoints[i];
			geocoderInput.setAttribute('placeholder', this.options.geocoderPlaceholder(i, nWps));
			geocoderInput.className = this.options.geocoderClass(i, nWps);

			this._updateWaypointName(i, geocoderInput);
			// This has to be here, or geocoder's value will not be properly
			// initialized.
			// TODO: look into why and make _updateWaypointName fix this.
			geocoderInput.value = wp.name;

			L.DomEvent.addListener(geocoderInput, 'click', function() {
				selectInputText(this);
			}, geocoderInput);

			new L.Routing.Autocomplete(geocoderInput, function(r) {
					geocoderInput.value = r.name;
					wp.name = r.name;
					wp.latLng = r.center;
					this._updateMarkers();
					this._fireChanged();
					this._focusGeocoder(i + 1);
				}, this, L.extend({
					resultFn: this.options.geocoder.geocode,
					resultContext: this.options.geocoder,
					autocompleteFn: this.options.geocoder.suggest,
					autocompleteContext: this.options.geocoder
				}, this.options.autocompleteOptions));

			return g;
		},

		_updateGeocoders: function(e) {
			var newElems = [],
			    i,
			    geocoderElem,
			    beforeElem;

			// Determine where to insert geocoders for new waypoints
			if (e.index >= this._geocoderElems.length) {
				// lastChild is the "add new wp" button
				beforeElem = this._geocoderContainer.lastChild;
			} else {
				beforeElem = this._geocoderElems[e.index].container;
			}

			// Insert new geocoders for new waypoints
			for (i = 0; i < e.added.length; i++) {
				geocoderElem = this._createGeocoder(e.index + i);
				this._geocoderContainer.insertBefore(geocoderElem.container, beforeElem);
				newElems.push(geocoderElem);
			}
			//newElems.reverse();

			for (i = e.index; i < e.index + e.nRemoved; i++) {
				this._geocoderContainer.removeChild(this._geocoderElems[i].container);
			}

			newElems.splice(0, 0, e.index, e.nRemoved);
			[].splice.apply(this._geocoderElems, newElems);

			for (i = 0; i < this._geocoderElems.length; i++) {
				this._geocoderElems[i].input.placeholder = this.options.geocoderPlaceholder(i, this._waypoints.length);
				this._geocoderElems[i].input.className = this.options.geocoderClass(i, this._waypoints.length);
			}
		},

		_updateGeocoder: function(i, geocoderElem) {
			var wp = this._waypoints[i],
			    value = wp && wp.name ? wp.name : '';
			if (geocoderElem) {
				geocoderElem.value = value;
			}
		},

		_updateWaypointName: function(i, geocoderElem, force) {
			var wp = this._waypoints[i],
					wpCoords;

			wp.name = wp.name || '';

			if (wp.latLng && (force || !wp.name)) {
				wpCoords = this.options.waypointNameFallback(wp.latLng);
				if (this.options.geocoder && this.options.geocoder.reverse) {
					this.options.geocoder.reverse(wp.latLng, 67108864 /* zoom 18 */, function(rs) {
						if (rs.length > 0 && rs[0].center.distanceTo(wp.latLng) < this.options.maxGeocoderTolerance) {
							wp.name = rs[0].name;
						} else {
							wp.name = wpCoords;
						}
						this._updateGeocoder(i, geocoderElem);
					}, this);
				} else {
					wp.name = wpCoords;
				}

				this._updateGeocoder(i, geocoderElem);
			}

		},

		_removeMarkers: function() {
			var i;
			if (this._markers) {
				for (i = 0; i < this._markers.length; i++) {
					if (this._markers[i]) {
						this._map.removeLayer(this._markers[i]);
					}
				}
			}
			this._markers = [];
		},

		_updateMarkers: function() {
			var i,
			    icon,
			    m;

			if (!this._map) {
				return;
			}

			this._removeMarkers();

			for (i = 0; i < this._waypoints.length; i++) {
				if (this._waypoints[i].latLng) {
					icon = (typeof(this.options.waypointIcon) === 'function') ?
						this.options.waypointIcon(i, this._waypoints[i].name, this._waypoints.length) :
						this.options.waypointIcon;
					m = this._createMarker(icon, i);
					if (this.options.draggableWaypoints) {
						this._hookWaypointEvents(m, i);
					}
				} else {
					m = null;
				}
				this._markers.push(m);
			}
		},

		_createMarker: function(icon, i) {
			var options = {
				draggable: true
			};
			if (icon) {
				options.icon = icon;
			}

			return L.marker(this._waypoints[i].latLng, options).addTo(this._map);
		},

		_fireChanged: function() {
			this.fire('waypointschanged', {waypoints: this.getWaypoints()});

			if (arguments.length >= 2) {
				this.fire('waypointsspliced', {
					index: Array.prototype.shift.call(arguments),
					nRemoved: Array.prototype.shift.call(arguments),
					added: arguments
				});
			}
		},

		_hookWaypointEvents: function(m, i) {
			m.on('dragstart', function(e) {
				this.fire('waypointdragstart', this._createWaypointEvent(i, e));
			}, this);
			m.on('drag', function(e) {
				this._waypoints[i].latLng = e.target.getLatLng();
				this.fire('waypointdrag', this._createWaypointEvent(i, e));
			}, this);
			m.on('dragend', function(e) {
				this.fire('waypointdragend', this._createWaypointEvent(i, e));
				this._waypoints[i].latLng = e.target.getLatLng();
				this._waypoints[i].name = '';
				this._updateWaypointName(i, this._geocoderElems && this._geocoderElems[i].input, true);
				this._fireChanged();
			}, this);
		},

		_createWaypointEvent: function(i, e) {
			return {index: i, latlng: e.target.getLatLng()};
		},

		dragNewWaypoint: function(e) {
			var i;
			this._newWp = {
				afterIndex: e.afterIndex,
				marker: L.marker(e.latlng).addTo(this._map),
				lines: []
			};

			for (i = 0; i < this.options.dragStyles.length; i++) {
				this._newWp.lines.push(L.polyline([
					this._waypoints[e.afterIndex].latLng,
					e.latlng,
					this._waypoints[e.afterIndex + 1].latLng
				], this.options.dragStyles[i]).addTo(this._map));
			}

			this._markers.splice(e.afterIndex + 1, 0, this._newWp.marker);
			this._map.on('mousemove', this._onDragNewWp, this);
			this._map.on('mouseup', this._onWpRelease, this);
		},

		_onDragNewWp: function(e) {
			var i;
			this._newWp.marker.setLatLng(e.latlng);
			for (i = 0; i < this._newWp.lines.length; i++) {
				this._newWp.lines[i].spliceLatLngs(1, 1, e.latlng);
			}
		},

		_onWpRelease: function(e) {
			var i;
			this._map.off('mouseup', this._onWpRelease, this);
			this._map.off('mousemove', this._onDragNewWp, this);
			for (i = 0; i < this._newWp.lines.length; i++) {
				this._map.removeLayer(this._newWp.lines[i]);
			}
			this.spliceWaypoints(this._newWp.afterIndex + 1, 0, e.latlng);
			delete this._newWp;
		},

		_focusGeocoder: function(i) {
			var input;
			if (this._geocoderElems[i]) {
				input = this._geocoderElems[i].input;
				input.focus();
				selectInputText(input);
			} else {
				document.activeElement.blur();
			}
		}
	});

	L.Routing.plan = function(waypoints, options) {
		return new L.Routing.Plan(waypoints, options);
	};

	module.exports = L.Routing;
})();
<commit_msg>Add close button to geocoder<commit_after>(function() {
	'use strict';

	var L = require('leaflet'),
		Waypoint = L.Class.extend({
			initialize: function(latLng, name) {
				this.latLng = latLng;
				this.name = name;
			}
		});

	L.Routing = L.Routing || {};
	L.extend(L.Routing, require('./L.Routing.Autocomplete'));

	function selectInputText(input) {
		if (input.setSelectionRange) {
			// On iOS, select() doesn't work
			input.setSelectionRange(0, 9999);
		} else {
			// On at least IE8, setSeleectionRange doesn't exist
			input.select();
		}
	}

	L.Routing.Plan = L.Class.extend({
		includes: L.Mixin.Events,

		options: {
			dragStyles: [
				{color: 'black', opacity: 0.15, weight: 9},
				{color: 'white', opacity: 0.8, weight: 6},
				{color: 'red', opacity: 1, weight: 2, dashArray: '7,12'}
			],
			draggableWaypoints: true,
			addWaypoints: true,
			maxGeocoderTolerance: 200,
			autocompleteOptions: {},
			geocodersClassName: '',
			geocoderClassName: '',
			geocoderPlaceholder: function(i, numberWaypoints) {
				return i === 0 ?
					'Start' :
					(i < numberWaypoints - 1 ?
									'Via ' + i :
									'End');
			},
			geocoderClass: function() {
				return '';
			},
			createGeocoder: function() {
				var e = L.DomUtil.create('input', '');
				return {
					container: e,
					input: e
				};
			},
			waypointNameFallback: function(latLng) {
				var ns = latLng.lat < 0 ? 'S' : 'N',
				    ew = latLng.lng < 0 ? 'W' : 'E',
				    lat = (Math.round(Math.abs(latLng.lat) * 10000) / 10000).toString(),
				    lng = (Math.round(Math.abs(latLng.lng) * 10000) / 10000).toString();
				return ns + lat + ', ' + ew + lng;
			}
		},

		initialize: function(waypoints, options) {
			L.Util.setOptions(this, options);
			this._waypoints = [];
			this.setWaypoints(waypoints);
		},

		isReady: function() {
			var i;
			for (i = 0; i < this._waypoints.length; i++) {
				if (!this._waypoints[i].latLng) {
					return false;
				}
			}

			return true;
		},

		getWaypoints: function() {
			var i,
				wps = [];

			for (i = 0; i < this._waypoints.length; i++) {
				wps.push(this._waypoints[i]);
			}

			return wps;
		},

		setWaypoints: function(waypoints) {
			var args = [0, this._waypoints.length].concat(waypoints);
			this.spliceWaypoints.apply(this, args);
			return this;
		},

		spliceWaypoints: function() {
			var args = [arguments[0], arguments[1]],
			    i,
			    wp;

			for (i = 2; i < arguments.length; i++) {
				args.push(arguments[i] && arguments[i].hasOwnProperty('latLng') ? arguments[i] : new Waypoint(arguments[i]));
			}

			[].splice.apply(this._waypoints, args);

			while (this._waypoints.length < 2) {
				wp = new Waypoint();
				this._waypoints.push(wp);
				args.push(wp);
			}

			this._updateMarkers();
			this._fireChanged.apply(this, args);
		},

		onAdd: function(map) {
			this._map = map;
			this._updateMarkers();
		},

		onRemove: function() {
			var i;
			this._removeMarkers();

			if (this._newWp) {
				for (i = 0; i < this._newWp.lines.length; i++) {
					this._map.removeLayer(this._newWp.lines[i]);
				}
			}

			delete this._map;
		},

		createGeocoders: function() {
			var container = L.DomUtil.create('div', 'leaflet-routing-geocoders ' + this.options.geocodersClassName),
				waypoints = this._waypoints,
			    i,
			    geocoderElem,
			    addWpBtn;

			this._geocoderContainer = container;
			this._geocoderElems = [];

			for (i = 0; i < waypoints.length; i++) {
				geocoderElem = this._createGeocoder(i);
				container.appendChild(geocoderElem.container);
				this._geocoderElems.push(geocoderElem);
			}

			addWpBtn = L.DomUtil.create('button', '', container);
			addWpBtn.setAttribute('type', 'button');
			addWpBtn.innerHTML = '+';
			if (this.options.addWaypoints) {
				L.DomEvent.addListener(addWpBtn, 'click', function() {
					this.spliceWaypoints(waypoints.length, 0, null);
				}, this);
			} else {
				addWpBtn.style.display = 'none';
			}

			this.on('waypointsspliced', this._updateGeocoders);

			return container;
		},

		_createGeocoder: function(i) {
			var nWps = this._waypoints.length,
				g = this.options.createGeocoder(i, nWps),
				closeButton = g.closeButton,
				geocoderInput = g.input,
				wp = this._waypoints[i];
			geocoderInput.setAttribute('placeholder', this.options.geocoderPlaceholder(i, nWps));
			geocoderInput.className = this.options.geocoderClass(i, nWps);

			this._updateWaypointName(i, geocoderInput);
			// This has to be here, or geocoder's value will not be properly
			// initialized.
			// TODO: look into why and make _updateWaypointName fix this.
			geocoderInput.value = wp.name;

			L.DomEvent.addListener(geocoderInput, 'click', function() {
				selectInputText(this);
			}, geocoderInput);

			if (closeButton) {
				L.DomEvent.addListener(closeButton, 'click', function() {
					this.spliceWaypoints(i, 1);
				}, this);
			}

			new L.Routing.Autocomplete(geocoderInput, function(r) {
					geocoderInput.value = r.name;
					wp.name = r.name;
					wp.latLng = r.center;
					this._updateMarkers();
					this._fireChanged();
					this._focusGeocoder(i + 1);
				}, this, L.extend({
					resultFn: this.options.geocoder.geocode,
					resultContext: this.options.geocoder,
					autocompleteFn: this.options.geocoder.suggest,
					autocompleteContext: this.options.geocoder
				}, this.options.autocompleteOptions));

			return g;
		},

		_updateGeocoders: function(e) {
			var newElems = [],
			    i,
			    geocoderElem,
			    beforeElem;

			// Determine where to insert geocoders for new waypoints
			if (e.index >= this._geocoderElems.length) {
				// lastChild is the "add new wp" button
				beforeElem = this._geocoderContainer.lastChild;
			} else {
				beforeElem = this._geocoderElems[e.index].container;
			}

			// Insert new geocoders for new waypoints
			for (i = 0; i < e.added.length; i++) {
				geocoderElem = this._createGeocoder(e.index + i);
				this._geocoderContainer.insertBefore(geocoderElem.container, beforeElem);
				newElems.push(geocoderElem);
			}
			//newElems.reverse();

			for (i = e.index; i < e.index + e.nRemoved; i++) {
				this._geocoderContainer.removeChild(this._geocoderElems[i].container);
			}

			newElems.splice(0, 0, e.index, e.nRemoved);
			[].splice.apply(this._geocoderElems, newElems);

			for (i = 0; i < this._geocoderElems.length; i++) {
				this._geocoderElems[i].input.placeholder = this.options.geocoderPlaceholder(i, this._waypoints.length);
				this._geocoderElems[i].input.className = this.options.geocoderClass(i, this._waypoints.length);
			}
		},

		_updateGeocoder: function(i, geocoderElem) {
			var wp = this._waypoints[i],
			    value = wp && wp.name ? wp.name : '';
			if (geocoderElem) {
				geocoderElem.value = value;
			}
		},

		_updateWaypointName: function(i, geocoderElem, force) {
			var wp = this._waypoints[i],
					wpCoords;

			wp.name = wp.name || '';

			if (wp.latLng && (force || !wp.name)) {
				wpCoords = this.options.waypointNameFallback(wp.latLng);
				if (this.options.geocoder && this.options.geocoder.reverse) {
					this.options.geocoder.reverse(wp.latLng, 67108864 /* zoom 18 */, function(rs) {
						if (rs.length > 0 && rs[0].center.distanceTo(wp.latLng) < this.options.maxGeocoderTolerance) {
							wp.name = rs[0].name;
						} else {
							wp.name = wpCoords;
						}
						this._updateGeocoder(i, geocoderElem);
					}, this);
				} else {
					wp.name = wpCoords;
				}

				this._updateGeocoder(i, geocoderElem);
			}

		},

		_removeMarkers: function() {
			var i;
			if (this._markers) {
				for (i = 0; i < this._markers.length; i++) {
					if (this._markers[i]) {
						this._map.removeLayer(this._markers[i]);
					}
				}
			}
			this._markers = [];
		},

		_updateMarkers: function() {
			var i,
			    icon,
			    m;

			if (!this._map) {
				return;
			}

			this._removeMarkers();

			for (i = 0; i < this._waypoints.length; i++) {
				if (this._waypoints[i].latLng) {
					icon = (typeof(this.options.waypointIcon) === 'function') ?
						this.options.waypointIcon(i, this._waypoints[i].name, this._waypoints.length) :
						this.options.waypointIcon;
					m = this._createMarker(icon, i);
					if (this.options.draggableWaypoints) {
						this._hookWaypointEvents(m, i);
					}
				} else {
					m = null;
				}
				this._markers.push(m);
			}
		},

		_createMarker: function(icon, i) {
			var options = {
				draggable: true
			};
			if (icon) {
				options.icon = icon;
			}

			return L.marker(this._waypoints[i].latLng, options).addTo(this._map);
		},

		_fireChanged: function() {
			this.fire('waypointschanged', {waypoints: this.getWaypoints()});

			if (arguments.length >= 2) {
				this.fire('waypointsspliced', {
					index: Array.prototype.shift.call(arguments),
					nRemoved: Array.prototype.shift.call(arguments),
					added: arguments
				});
			}
		},

		_hookWaypointEvents: function(m, i) {
			m.on('dragstart', function(e) {
				this.fire('waypointdragstart', this._createWaypointEvent(i, e));
			}, this);
			m.on('drag', function(e) {
				this._waypoints[i].latLng = e.target.getLatLng();
				this.fire('waypointdrag', this._createWaypointEvent(i, e));
			}, this);
			m.on('dragend', function(e) {
				this.fire('waypointdragend', this._createWaypointEvent(i, e));
				this._waypoints[i].latLng = e.target.getLatLng();
				this._waypoints[i].name = '';
				this._updateWaypointName(i, this._geocoderElems && this._geocoderElems[i].input, true);
				this._fireChanged();
			}, this);
		},

		_createWaypointEvent: function(i, e) {
			return {index: i, latlng: e.target.getLatLng()};
		},

		dragNewWaypoint: function(e) {
			var i;
			this._newWp = {
				afterIndex: e.afterIndex,
				marker: L.marker(e.latlng).addTo(this._map),
				lines: []
			};

			for (i = 0; i < this.options.dragStyles.length; i++) {
				this._newWp.lines.push(L.polyline([
					this._waypoints[e.afterIndex].latLng,
					e.latlng,
					this._waypoints[e.afterIndex + 1].latLng
				], this.options.dragStyles[i]).addTo(this._map));
			}

			this._markers.splice(e.afterIndex + 1, 0, this._newWp.marker);
			this._map.on('mousemove', this._onDragNewWp, this);
			this._map.on('mouseup', this._onWpRelease, this);
		},

		_onDragNewWp: function(e) {
			var i;
			this._newWp.marker.setLatLng(e.latlng);
			for (i = 0; i < this._newWp.lines.length; i++) {
				this._newWp.lines[i].spliceLatLngs(1, 1, e.latlng);
			}
		},

		_onWpRelease: function(e) {
			var i;
			this._map.off('mouseup', this._onWpRelease, this);
			this._map.off('mousemove', this._onDragNewWp, this);
			for (i = 0; i < this._newWp.lines.length; i++) {
				this._map.removeLayer(this._newWp.lines[i]);
			}
			this.spliceWaypoints(this._newWp.afterIndex + 1, 0, e.latlng);
			delete this._newWp;
		},

		_focusGeocoder: function(i) {
			var input;
			if (this._geocoderElems[i]) {
				input = this._geocoderElems[i].input;
				input.focus();
				selectInputText(input);
			} else {
				document.activeElement.blur();
			}
		}
	});

	L.Routing.plan = function(waypoints, options) {
		return new L.Routing.Plan(waypoints, options);
	};

	module.exports = L.Routing;
})();
<|endoftext|>


<commit_before>function OAuthConsumer(options) {
    if (arguments.length > 0) {
        this.init(options);
    }

    this.oauth_version = '1.0';
    this.signature_method = 'PLAINTEXT';

    this.init = function(options) {
        // default to using cookies
        options.use_cookies = options.use_cookies || true;

        this.debug = options.debug == false ? false : true;
        this.key = options.key || '';
        this.secret = options.secret || '';
        this.callback_url = options.callback_url || 'oob';
        this.token = options.token || '';
        this.token_secret = options.token_secret || '';
        this.use_cookies = options.use_cookies;
        this.oauth_verifier = options.oauth_verifier || '';
        this.cookie;

        this.onauthorized = options.onauthorized;

        if (options.use_cookies) {
            this.cookie = new OAuthCookie('oauth_token');
            var values = this.cookie.getValue().split('|');
            if (values) {
                this.token = values[0];
                this.token_secret = values[1];
                this.oauth_verifier = values[2];
            }
        }
    };

    this.authorize = function(){
        if (!(sandbox_oauth.token && sandbox_oauth.token_secret)) {
            // need to get a access token
            this.getRequestToken();
        }

        if (this.token && this.token_secret && !this.oauth_verifier) {
            var url = this.authorizeToken();
            window.open(url);
            var verification = document.createElement('input');
            verification.setAttribute('type', 'text');
            verification.setAttribute('id', 'verification');
            document.body.appendChild(verification);

            var button = document.createElement('input');
            button.setAttribute('type', 'button');
            button.setAttribute('id', 'verify');
            button.setAttribute('value', 'Verify');
            document.body.appendChild(button);

            var self = this;
            button.onclick = function() {
                var verification = document.getElementById('verification');
                self.oauth_verifier = verification.value;
                self.getAccessToken();
            };
        }

        if(this.token && this.token_secret && this.oauth_verifier){
            this.onauthorized.call(this);
        }
    };

    this.getRequestToken = function(){
        if (this.debug) {
            netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead UniversalBrowserWrite");
        }

        var xhr = new XMLHttpRequest();
        xhr.open('POST', this.requestTokenUrl, false);
        xhr.setRequestHeader('Authorization', this.getHeaderString());
        xhr.send(this.getRequestString());
        if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 304)) {
            // oauth_token=hh5s93j4hdidpola&oauth_token_secret=hdhd0244k9j7ao03&
            var token_string_params = xhr.responseText.split('&');
            for (var i = 0; i < token_string_params.length; i++) {
                var param = token_string_params[i].split('=');
                if (param[0] == 'oauth_token') {
                    this.token = param[1];
                }
                if (param[0] == 'oauth_token_secret') {
                    this.token_secret = param[1];
                }
            }
        }

        return this;
    };

    this.authorizeToken = function(){
        if (this.debug) {
            netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead UniversalBrowserWrite");
        }

        return this.authorizationUrl + '?' + this.getRequestString();
    };

    this.getAccessToken = function(){
        if (this.debug) {
            netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead UniversalBrowserWrite");
        }

        var xhr = new XMLHttpRequest();
        xhr.open('POST', this.accessTokenUrl, false);
        xhr.setRequestHeader('Authorization', this.getHeaderString());
        xhr.send(this.getRequestString());
        if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 304)) {
            // oauth_token=hh5s93j4hdidpola&oauth_token_secret=hdhd0244k9j7ao03&
            var token_string_params = xhr.responseText.split('&');
            for (var i = 0; i < token_string_params.length; i++) {
                var param = token_string_params[i].split('=');
                if (param[0] == 'oauth_token') {
                    this.token = param[1];
                }
                if (param[0] == 'oauth_token_secret') {
                    this.token_secret = param[1];
                }
            }

            this.cookie.setValue(this.token + '|' + this.token_secret + '|' + this.oauth_verifier);
        }
        this.authorize();
        return this;
    };

    this.getHeaderString = function() {
        var header = [];
        var params = {
            'realm': this.realm,
            'oauth_callback': this.callback_url,
            'oauth_consumer_key': this.key,
            'oauth_token': this.token,
            'oauth_signature_method': this.signature_method,
            'oauth_timestamp': this.getTimestamp(),
            'oauth_nonce': this.getNonce(),
            'oauth_verifier': this.oauth_verifier,
            'oauth_signature': (
                new OAuthConsumer.signatureMethods[this.signature_method]
             ).sign(this.secret, this.token_secret),
            'oauth_version': this.oauth_version
        };

        var OU = OAuthUtilities;
        for (var i in params) {
            if (params.hasOwnProperty(i) && params[i]) {
                header.push(OU.urlEncode(i) + '="' + OU.urlEncode(params[i]) + '"');
            }
        }

        return 'OAuth ' + header.join(',');
    };

    this.getRequestString = function() {
        var request = [];
        var params = {
            'oauth_callback': this.callback_url,
            'oauth_consumer_key': this.key,
            'oauth_token': this.token,
            'oauth_signature_method': this.signature_method,
            'oauth_timestamp': this.getTimestamp(),
            'oauth_nonce': this.getNonce(),
            'oauth_verifier': this.oauth_verifier,
            'oauth_signature': (
                new OAuthConsumer.signatureMethods[this.signature_method]
             ).sign(this.secret, this.token_secret),
            'oauth_version': VERSION
        };

        var OU = OAuthUtilities;
        for (var i in params) {
            if (params.hasOwnProperty(i) && params[i]) {
                request.push(OU.urlEncode(i) + '=' + OU.urlEncode(params[i]));
            }
        }

        return request.join('&');
    };

    this.onauthorized = function(){};

    this.getTimestamp = function() {
        return parseInt((new Date).getTime() / 1000) + '';
    };

    this.getNonce = function(key_length){
        key_length = key_length || 64;

        var key_bytes = key_length / 8;
        var value = '';
        var key_iter = key_bytes / 4;
        var key_remainder = key_bytes % 4;
        var chars = ['20', '21', '22', '23', '24', '25', '26', '27', '28', '29',
                     '2A', '2B', '2C', '2D', '2E', '2F', '30', '31', '32', '33',
                     '34', '35', '36', '37', '38', '39', '3A', '3B', '3C', '3D',
                     '3E', '3F', '40', '41', '42', '43', '44', '45', '46', '47',
                     '48', '49', '4A', '4B', '4C', '4D', '4E', '4F', '50', '51',
                     '52', '53', '54', '55', '56', '57', '58', '59', '5A', '5B',
                     '5C', '5D', '5E', '5F', '60', '61', '62', '63', '64', '65',
                     '66', '67', '68', '69', '6A', '6B', '6C', '6D', '6E', '6F',
                     '70', '71', '72', '73', '74', '75', '76', '77', '78', '79',
                     '7A', '7B', '7C', '7D', '7E'];

        for (var i = 0; i < key_iter; i++) {
            value += chars[rand()] + chars[rand()] + chars[rand()]+ chars[rand()];
        }

        // handle remaing bytes
        for (var i = 0; i < key_remainder; i++) {
            value += chars[rand()];
        }

        return value;

        function rand() {
            return Math.floor(Math.random() * chars.length);
        }
    };
}

OAuthConsumer.signatureMethods = {};
<commit_msg>added a default signature method<commit_after>function OAuthConsumer(options) {
    if (arguments.length > 0) {
        this.init(options);
    }

    this.oauth_version = '1.0';
    this.signature_method = 'PLAINTEXT';

    this.init = function(options) {
        // default to using cookies
        options.use_cookies = options.use_cookies || true;

        this.debug = options.debug == false ? false : true;
        this.key = options.key || '';
        this.secret = options.secret || '';
        this.callback_url = options.callback_url || 'oob';
        this.token = options.token || '';
        this.token_secret = options.token_secret || '';
        this.use_cookies = options.use_cookies;
        this.oauth_verifier = options.oauth_verifier || '';
        this.cookie;

        this.onauthorized = options.onauthorized;

        if (options.use_cookies) {
            this.cookie = new OAuthCookie('oauth_token');
            var values = this.cookie.getValue().split('|');
            if (values) {
                this.token = values[0];
                this.token_secret = values[1];
                this.oauth_verifier = values[2];
            }
        }
    };

    this.authorize = function(){
        if (!(sandbox_oauth.token && sandbox_oauth.token_secret)) {
            // need to get a access token
            this.getRequestToken();
        }

        if (this.token && this.token_secret && !this.oauth_verifier) {
            var url = this.authorizeToken();
            window.open(url);
            var verification = document.createElement('input');
            verification.setAttribute('type', 'text');
            verification.setAttribute('id', 'verification');
            document.body.appendChild(verification);

            var button = document.createElement('input');
            button.setAttribute('type', 'button');
            button.setAttribute('id', 'verify');
            button.setAttribute('value', 'Verify');
            document.body.appendChild(button);

            var self = this;
            button.onclick = function() {
                var verification = document.getElementById('verification');
                self.oauth_verifier = verification.value;
                self.getAccessToken();
            };
        }

        if(this.token && this.token_secret && this.oauth_verifier){
            this.onauthorized.call(this);
        }
    };

    this.getRequestToken = function(){
        if (this.debug) {
            netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead UniversalBrowserWrite");
        }

        var xhr = new XMLHttpRequest();
        xhr.open('POST', this.requestTokenUrl, false);
        xhr.setRequestHeader('Authorization', this.getHeaderString());
        xhr.send(this.getRequestString());
        if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 304)) {
            // oauth_token=hh5s93j4hdidpola&oauth_token_secret=hdhd0244k9j7ao03&
            var token_string_params = xhr.responseText.split('&');
            for (var i = 0; i < token_string_params.length; i++) {
                var param = token_string_params[i].split('=');
                if (param[0] == 'oauth_token') {
                    this.token = param[1];
                }
                if (param[0] == 'oauth_token_secret') {
                    this.token_secret = param[1];
                }
            }
        }

        return this;
    };

    this.authorizeToken = function(){
        if (this.debug) {
            netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead UniversalBrowserWrite");
        }

        return this.authorizationUrl + '?' + this.getRequestString();
    };

    this.getAccessToken = function(){
        if (this.debug) {
            netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead UniversalBrowserWrite");
        }

        var xhr = new XMLHttpRequest();
        xhr.open('POST', this.accessTokenUrl, false);
        xhr.setRequestHeader('Authorization', this.getHeaderString());
        xhr.send(this.getRequestString());
        if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 304)) {
            // oauth_token=hh5s93j4hdidpola&oauth_token_secret=hdhd0244k9j7ao03&
            var token_string_params = xhr.responseText.split('&');
            for (var i = 0; i < token_string_params.length; i++) {
                var param = token_string_params[i].split('=');
                if (param[0] == 'oauth_token') {
                    this.token = param[1];
                }
                if (param[0] == 'oauth_token_secret') {
                    this.token_secret = param[1];
                }
            }

            this.cookie.setValue(this.token + '|' + this.token_secret + '|' + this.oauth_verifier);
        }
        this.authorize();
        return this;
    };

    this.getHeaderString = function() {
        var header = [];
        var params = {
            'realm': this.realm,
            'oauth_callback': this.callback_url,
            'oauth_consumer_key': this.key,
            'oauth_token': this.token,
            'oauth_signature_method': this.signature_method,
            'oauth_timestamp': this.getTimestamp(),
            'oauth_nonce': this.getNonce(),
            'oauth_verifier': this.oauth_verifier,
            'oauth_signature': (
                new OAuthConsumer.signatureMethods[this.signature_method]
             ).sign(this.secret, this.token_secret),
            'oauth_version': this.oauth_version
        };

        var OU = OAuthUtilities;
        for (var i in params) {
            if (params.hasOwnProperty(i) && params[i]) {
                header.push(OU.urlEncode(i) + '="' + OU.urlEncode(params[i]) + '"');
            }
        }

        return 'OAuth ' + header.join(',');
    };

    this.getRequestString = function() {
        var request = [];
        var params = {
            'oauth_callback': this.callback_url,
            'oauth_consumer_key': this.key,
            'oauth_token': this.token,
            'oauth_signature_method': this.signature_method,
            'oauth_timestamp': this.getTimestamp(),
            'oauth_nonce': this.getNonce(),
            'oauth_verifier': this.oauth_verifier,
            'oauth_signature': (
                new OAuthConsumer.signatureMethods[this.signature_method]
             ).sign(this.secret, this.token_secret),
            'oauth_version': this.oauth_version
        };

        var OU = OAuthUtilities;
        for (var i in params) {
            if (params.hasOwnProperty(i) && params[i]) {
                request.push(OU.urlEncode(i) + '=' + OU.urlEncode(params[i]));
            }
        }

        return request.join('&');
    };

    this.onauthorized = function(){};

    this.getTimestamp = function() {
        return parseInt((new Date).getTime() / 1000) + '';
    };

    this.getNonce = function(key_length){
        key_length = key_length || 64;

        var key_bytes = key_length / 8;
        var value = '';
        var key_iter = key_bytes / 4;
        var key_remainder = key_bytes % 4;
        var chars = ['20', '21', '22', '23', '24', '25', '26', '27', '28', '29',
                     '2A', '2B', '2C', '2D', '2E', '2F', '30', '31', '32', '33',
                     '34', '35', '36', '37', '38', '39', '3A', '3B', '3C', '3D',
                     '3E', '3F', '40', '41', '42', '43', '44', '45', '46', '47',
                     '48', '49', '4A', '4B', '4C', '4D', '4E', '4F', '50', '51',
                     '52', '53', '54', '55', '56', '57', '58', '59', '5A', '5B',
                     '5C', '5D', '5E', '5F', '60', '61', '62', '63', '64', '65',
                     '66', '67', '68', '69', '6A', '6B', '6C', '6D', '6E', '6F',
                     '70', '71', '72', '73', '74', '75', '76', '77', '78', '79',
                     '7A', '7B', '7C', '7D', '7E'];

        for (var i = 0; i < key_iter; i++) {
            value += chars[rand()] + chars[rand()] + chars[rand()]+ chars[rand()];
        }

        // handle remaing bytes
        for (var i = 0; i < key_remainder; i++) {
            value += chars[rand()];
        }

        return value;

        function rand() {
            return Math.floor(Math.random() * chars.length);
        }
    };
}

OAuthConsumer.signatureMethods = {};
<|endoftext|>


<commit_before>$(document).ready(function() {

	var $tabs = $('dl.tabs.entity-form');
	if ($tabs.length > 0) {
	    var $lastTab = $tabs.find('dd:last');
	    if ($lastTab.width() + $lastTab.position().left + 15 > $tabs.width()) {
            $tabs.mCustomScrollbar({
                theme: 'dark',
                autoHideScrollbar: true,
                horizontalScroll: true
            });
	    }
	}

	// When the delete button is clicked, we can change the desired action for the
	// form and submit it normally (not via AJAX).
	$('body').on('click', 'button.delete-button', function(event) {
	    var $form = BLCAdmin.getForm($(this));
		var currentAction = $form.attr('action');

		$form.attr('action', currentAction + '/delete');
		$form.submit();
	});

	$('body').on('click', 'button.submit-button', function(event) {
	    var $form = BLCAdmin.getForm($(this));
	    $form.submit();
		event.preventDefault();
	});

	$('body').on('submit', 'form.entity-form', function(event) {
        var submit = BLCAdmin.runSubmitHandlers($(this));
        return submit;
	});

    $('body').on('click', 'button.add-main-entity', function(event) {
    	BLCAdmin.showLinkAsModal($(this).data('url'));
    	return false;
    });

    $('body').on('click', 'a.add-main-entity-select-type', function(event) {
    	BLCAdmin.modalNavigateTo($(this).attr('href'));
    	return false;
    });

	$('body').on('submit', 'form.modal-add-entity-form', function(event) {
        var submit = BLCAdmin.runSubmitHandlers($(this));

        if (submit) {
    		BLC.ajax({
    			url: this.action,
    			type: "POST",
    			data: $(this).serialize()
    		}, function(data) {
    			$('.modal .modal-body .tabs-content').replaceWith($(data).find('.modal-body .tabs-content'));
    	    });
        }
		return false;
	});

});
<commit_msg>Resolves #310 by re-initialize the form after the submitting the AJAX add new entity<commit_after>$(document).ready(function() {

	var $tabs = $('dl.tabs.entity-form');
	if ($tabs.length > 0) {
	    var $lastTab = $tabs.find('dd:last');
	    if ($lastTab.width() + $lastTab.position().left + 15 > $tabs.width()) {
            $tabs.mCustomScrollbar({
                theme: 'dark',
                autoHideScrollbar: true,
                horizontalScroll: true
            });
	    }
	}

	// When the delete button is clicked, we can change the desired action for the
	// form and submit it normally (not via AJAX).
	$('body').on('click', 'button.delete-button', function(event) {
	    var $form = BLCAdmin.getForm($(this));
		var currentAction = $form.attr('action');

		$form.attr('action', currentAction + '/delete');
		$form.submit();
	});

	$('body').on('click', 'button.submit-button', function(event) {
	    var $form = BLCAdmin.getForm($(this));
	    $form.submit();
		event.preventDefault();
	});

	$('body').on('submit', 'form.entity-form', function(event) {
        var submit = BLCAdmin.runSubmitHandlers($(this));
        return submit;
	});

    $('body').on('click', 'button.add-main-entity', function(event) {
    	BLCAdmin.showLinkAsModal($(this).data('url'));
    	return false;
    });

    $('body').on('click', 'a.add-main-entity-select-type', function(event) {
    	BLCAdmin.modalNavigateTo($(this).attr('href'));
    	return false;
    });

	$('body').on('submit', 'form.modal-add-entity-form', function(event) {
        var submit = BLCAdmin.runSubmitHandlers($(this));

        if (submit) {
    		BLC.ajax({
    			url: this.action,
    			type: "POST",
    			data: $(this).serialize()
    		}, function(data) {
    			$('.modal .modal-body .tabs-content').replaceWith($(data).find('.modal-body .tabs-content'));
    			BLCAdmin.initializeFields($('.modal .modal-body .tabs-content'));
    	    });
        }
		return false;
	});

});
<|endoftext|>


<commit_before>/*========================================================================

   This file is part of the GOsa project -  http://gosa-project.org

   Copyright:
      (C) 2010-2017 GONICUS GmbH, Germany, http://www.gonicus.de

   License:
      LGPL-2.1: http://www.gnu.org/licenses/lgpl-2.1.html

   See the LICENSE file in the project's top-level directory for details.

======================================================================== */

/**
 *
 */
qx.Class.define("gosa.plugins.yql.Main", {
  extend : gosa.plugins.AbstractDashboardWidget,

  construct : function() {
    this.base(arguments);
  },

  /*
   *****************************************************************************
   PROPERTIES
   *****************************************************************************
   */
  properties : {
    appearance: {
      refine: true,
      init: "gosa-dashboard-widget-yql"
    },

    query: {
      check: "String",
      init: "",
      apply: "_applyQuery"
    },

    mapping: {
      check: "Object",
      init: {},
      transform: "string2json"
    },

    /**
     * refresh rate in seconds
     */
    refreshRate: {
      check: "Number",
      init: 360,
      event: "changeRefreshRate"
    }
  },

  /*
   *****************************************************************************
   MEMBERS
   *****************************************************************************
   */
  members : {
    __store: null,
    __timer: null,

    draw: function() {
      // add your code here
    },

    // overridden
    _createChildControlImpl: function(id) {
      var control;

      switch(id) {

        case "list":
          control = new qx.ui.list.List();
          control.setLabelPath("title");
          this.getChildControl("content").add(control);
          break;
      }

      return control || this.base(arguments, id);
    },

    string2json: function(value) {
      if (!value) {
        return {};
      }
      return qx.lang.Type.isString(value) ? qx.lang.Json.parse(value) : value;
    },

    // property apply
    _applyQuery: function(value) {
      if (value) {
        if (!this.__store) {
          this.__store = new qx.data.store.Yql(value, this.__getDelegate());
          this.__store.bind("model", this.getChildControl("list"), "model");
          this.__createTimer();
          this.__timer.addListener("interval", this.__store.reload, this);
        }
      }
    },

    __createTimer: function() {
      if (!this.__timer) {
        this.__timer = new qx.event.Timer(this.getRefreshRate());
        this.bind("refreshRate", this.__timer, "interval", {
          converter: function(value) {
            return value * 1000;
          }
        });
      }
    },

    __getDelegate: function() {
      return {
        manipulateData: function(data) {
          return data.query.results.item;
        }
      }
    }
  },

  defer: function () {
    gosa.data.DashboardController.registerWidget(gosa.plugins.yql.Main, {
      displayName: qx.locale.Manager.tr("YQL"),
      defaultColspan: 3,
      defaultRowspan: 5,
      theme: {
        appearance : gosa.plugins.yql.Appearance
      },
      settings: {
        mandatory: ["query"],
        properties: {
          query: {
            type: "String",
            title: qx.locale.Manager.tr("YQL query")
          },
          refreshRate: {
            type: "Number",
            title: qx.locale.Manager.tr("Refresh rate"),
            minValue: 0,
            maxValue: 86400 // one day (in seconds)
          }
        }
      }
    });
  }
});<commit_msg>add icon<commit_after>/*========================================================================

   This file is part of the GOsa project -  http://gosa-project.org

   Copyright:
      (C) 2010-2017 GONICUS GmbH, Germany, http://www.gonicus.de

   License:
      LGPL-2.1: http://www.gnu.org/licenses/lgpl-2.1.html

   See the LICENSE file in the project's top-level directory for details.

======================================================================== */

/**
 *
 */
qx.Class.define("gosa.plugins.yql.Main", {
  extend : gosa.plugins.AbstractDashboardWidget,

  construct : function() {
    this.base(arguments);
  },

  /*
   *****************************************************************************
   PROPERTIES
   *****************************************************************************
   */
  properties : {
    appearance: {
      refine: true,
      init: "gosa-dashboard-widget-yql"
    },

    query: {
      check: "String",
      init: "",
      apply: "_applyQuery"
    },

    mapping: {
      check: "Object",
      init: {},
      transform: "string2json"
    },

    /**
     * refresh rate in seconds
     */
    refreshRate: {
      check: "Number",
      init: 360,
      event: "changeRefreshRate"
    }
  },

  /*
   *****************************************************************************
   MEMBERS
   *****************************************************************************
   */
  members : {
    __store: null,
    __timer: null,

    draw: function() {
      // add your code here
    },

    // overridden
    _createChildControlImpl: function(id) {
      var control;

      switch(id) {

        case "list":
          control = new qx.ui.list.List();
          control.setLabelPath("title");
          this.getChildControl("content").add(control);
          break;
      }

      return control || this.base(arguments, id);
    },

    string2json: function(value) {
      if (!value) {
        return {};
      }
      return qx.lang.Type.isString(value) ? qx.lang.Json.parse(value) : value;
    },

    // property apply
    _applyQuery: function(value) {
      if (value) {
        if (!this.__store) {
          this.__store = new qx.data.store.Yql(value, this.__getDelegate());
          this.__store.bind("model", this.getChildControl("list"), "model");
          this.__createTimer();
          this.__timer.addListener("interval", this.__store.reload, this);
        }
      }
    },

    __createTimer: function() {
      if (!this.__timer) {
        this.__timer = new qx.event.Timer(this.getRefreshRate());
        this.bind("refreshRate", this.__timer, "interval", {
          converter: function(value) {
            return value * 1000;
          }
        });
      }
    },

    __getDelegate: function() {
      return {
        manipulateData: function(data) {
          return data.query.results.item;
        }
      }
    }
  },

  defer: function () {
    gosa.data.DashboardController.registerWidget(gosa.plugins.yql.Main, {
      displayName: qx.locale.Manager.tr("YQL"),
      icon: "@Ligature/yahoo",
      defaultColspan: 3,
      defaultRowspan: 5,
      theme: {
        appearance : gosa.plugins.yql.Appearance
      },
      settings: {
        mandatory: ["query"],
        properties: {
          query: {
            type: "String",
            title: qx.locale.Manager.tr("YQL query")
          },
          refreshRate: {
            type: "Number",
            title: qx.locale.Manager.tr("Refresh rate"),
            minValue: 0,
            maxValue: 86400 // one day (in seconds)
          }
        }
      }
    });
  }
});<|endoftext|>


<commit_before>const JestUtil = require("#SRC/js/utils/JestUtil");

JestUtil.unMockStores(["TaskDirectoryStore", "MesosLogStore"]);

const DirectoryItem = require("../../../structs/DirectoryItem");
const TaskDirectory = require("../../../structs/TaskDirectory");
/* eslint-disable no-unused-vars */
const React = require("react");
/* eslint-enable no-unused-vars */
const ReactDOM = require("react-dom");

const TaskDirectoryActions = require("../../../events/TaskDirectoryActions");
const TaskFileViewer = require("../TaskFileViewer");

describe("TaskFileViewer", function() {
  beforeEach(function() {
    this.container = global.document.createElement("div");
    this.instance = ReactDOM.render(
      <TaskFileViewer
        directory={
          new TaskDirectory({ items: [{ nlink: 1, path: "/stdout" }] })
        }
        params={{ filePath: "undefined" }}
        selectedLogFile={new DirectoryItem({ nlink: 1, path: "/stdout" })}
        task={{ slave_id: "foo" }}
      />,
      this.container
    );
  });

  afterEach(function() {
    ReactDOM.unmountComponentAtNode(this.container);
  });

  describe("#render", function() {
    it("sets button disabled when file is not found", function() {
      this.instance = ReactDOM.render(
        <TaskFileViewer
          directory={new TaskDirectory({ items: [{ nlink: 1, path: "" }] })}
          params={{ filePath: "undefined" }}
          task={{ slave_id: "foo" }}
        />,
        this.container
      );
      const btn = this.container.querySelector("a.button.button-primary-link");
      // If btn.props.disabled = true, then disabled attribute will return an object.
      // If btn.props.disabled = false, then disabled attribute will be undefined.
      // So here we just test to see if attribute exists
      expect(btn.attributes.disabled).toBeTruthy();
    });

    it("sets button not disabled when file is found", function() {
      const btn = this.container.querySelector("a.button.button-primary-link");
      // If btn.props.disabled = false, then disabled attribute will be undefined
      expect(btn.attributes.disabled).toEqual(undefined);
    });

    it("renders stdout on first render", function() {
      this.instance.state = { currentView: 0 };
      TaskDirectoryActions.getDownloadURL = jasmine.createSpy(
        "TaskDirectoryActions#getDownloadURL"
      );

      this.instance.render();

      expect(TaskDirectoryActions.getDownloadURL).toHaveBeenCalledWith(
        "foo",
        "/stdout"
      );
    });

    it("renders stderr when view is changed", function() {
      this.instance = ReactDOM.render(
        <TaskFileViewer
          directory={
            new TaskDirectory({
              items: [
                { nlink: 1, path: "/stdout" },
                { nlink: 1, path: "/stderr" }
              ]
            })
          }
          params={{ filePath: "/stderr" }}
          selectedLogFile={new DirectoryItem({ nlink: 1, path: "/stderr" })}
          task={{ slave_id: "foo" }}
        />,
        this.container
      );

      // Setup spy after state has been configured
      TaskDirectoryActions.getDownloadURL = jasmine.createSpy(
        "TaskDirectoryActions#getDownloadURL"
      );

      this.instance.render();

      expect(TaskDirectoryActions.getDownloadURL).toHaveBeenCalledWith(
        "foo",
        "/stderr"
      );
    });

    it("limits files to stdout and stderr when provided", function() {
      this.instance = ReactDOM.render(
        <TaskFileViewer
          directory={
            new TaskDirectory({
              items: [
                { nlink: 1, path: "/foo" },
                { nlink: 1, path: "/stdout" },
                { nlink: 1, path: "/stderr" }
              ]
            })
          }
          params={{}}
          limitLogFiles={["stdout", "stderr"]}
          task={{ slave_id: "foo" }}
        />,
        this.container
      );

      expect(this.instance.getLogFiles()).toEqual([
        new DirectoryItem({ nlink: 1, path: "/stdout" }),
        new DirectoryItem({ nlink: 1, path: "/stderr" })
      ]);
    });

    it("includes all files when limit is not provided", function() {
      this.instance = ReactDOM.render(
        <TaskFileViewer
          directory={
            new TaskDirectory({
              items: [
                { nlink: 1, path: "/foo" },
                { nlink: 1, path: "/stdout" },
                { nlink: 1, path: "/stderr" }
              ]
            })
          }
          params={{}}
          task={{ slave_id: "foo" }}
        />,
        this.container
      );

      expect(this.instance.getLogFiles()).toEqual([
        new DirectoryItem({ nlink: 1, path: "/foo" }),
        new DirectoryItem({ nlink: 1, path: "/stdout" }),
        new DirectoryItem({ nlink: 1, path: "/stderr" })
      ]);
    });
  });
});
<commit_msg>test(TaskFileViewer): add test for redirection logic<commit_after>const JestUtil = require("#SRC/js/utils/JestUtil");

JestUtil.unMockStores(["TaskDirectoryStore", "MesosLogStore"]);

const DirectoryItem = require("../../../structs/DirectoryItem");
const TaskDirectory = require("../../../structs/TaskDirectory");
/* eslint-disable no-unused-vars */
const React = require("react");
/* eslint-enable no-unused-vars */
const ReactDOM = require("react-dom");

const TaskDirectoryActions = require("../../../events/TaskDirectoryActions");
const TaskFileViewer = require("../TaskFileViewer");

describe("TaskFileViewer", function() {
  describe("#getNewRoute", function() {
    let getNewRoute;
    beforeEach(function() {
      getNewRoute = TaskFileViewer.prototype.getNewRoute;
    });

    it("does not augment the path if there is a :filePath placeholder", function() {
      const params = {
        filePath: "%2Fvar%2Flib%2Fbar",
        id: "/data-services/kafka",
        taskID: "kafka-0-broker__d79a8dae-f0c4-48bd-a6c7-269856337fc9"
      };
      expect(
        getNewRoute(
          "/services/detail/:id/tasks/:taskID/files/view(/:filePath(/:innerPath))",
          params,
          "/var/lib/foo"
        )
      ).toBe(
        "/services/detail/%2Fdata-services%2Fkafka/tasks/kafka-0-broker__d79a8dae-f0c4-48bd-a6c7-269856337fc9/files/view/%252Fvar%252Flib%252Ffoo/%252Fvar%252Flib%252Ffoo"
      );
    });

    it("does augment the path without a / if there is no placeholder", function() {
      const params = {
        filePath: "%2Fvar%2Flib%2Fbar",
        id: "/data-services/kafka",
        taskID: "kafka-0-broker__d79a8dae-f0c4-48bd-a6c7-269856337fc9"
      };
      expect(
        getNewRoute(
          "/services/detail/:id/tasks/:taskID/files/view",
          params,
          "/var/lib/foo"
        )
      ).toBe(
        "/services/detail/%2Fdata-services%2Fkafka/tasks/kafka-0-broker__d79a8dae-f0c4-48bd-a6c7-269856337fc9/files/view/%252Fvar%252Flib%252Ffoo"
      );
    });

    it("does augment the path with a / if there is no placeholder and no /", function() {
      it("does augment the path without a / if there is no placeholder", function() {
        const params = {
          filePath: "%2Fvar%2Flib%2Fbar",
          id: "/data-services/kafka",
          taskID: "kafka-0-broker__d79a8dae-f0c4-48bd-a6c7-269856337fc9"
        };
        expect(
          getNewRoute(
            "/services/detail/:id/tasks/:taskID/files/view/",
            params,
            "/var/lib/foo"
          )
        ).toBe(
          "/services/detail/%2Fdata-services%2Fkafka/tasks/kafka-0-broker__d79a8dae-f0c4-48bd-a6c7-269856337fc9/files/view/%252Fvar%252Flib%252Ffoo"
        );
      });
    });
  });

  describe("#render", function() {
    beforeEach(function() {
      this.container = global.document.createElement("div");
      this.instance = ReactDOM.render(
        <TaskFileViewer
          directory={
            new TaskDirectory({ items: [{ nlink: 1, path: "/stdout" }] })
          }
          params={{ filePath: "undefined" }}
          selectedLogFile={new DirectoryItem({ nlink: 1, path: "/stdout" })}
          task={{ slave_id: "foo" }}
        />,
        this.container
      );
    });

    afterEach(function() {
      ReactDOM.unmountComponentAtNode(this.container);
    });
    it("sets button disabled when file is not found", function() {
      this.instance = ReactDOM.render(
        <TaskFileViewer
          directory={new TaskDirectory({ items: [{ nlink: 1, path: "" }] })}
          params={{ filePath: "undefined" }}
          task={{ slave_id: "foo" }}
        />,
        this.container
      );
      const btn = this.container.querySelector("a.button.button-primary-link");
      // If btn.props.disabled = true, then disabled attribute will return an object.
      // If btn.props.disabled = false, then disabled attribute will be undefined.
      // So here we just test to see if attribute exists
      expect(btn.attributes.disabled).toBeTruthy();
    });

    it("sets button not disabled when file is found", function() {
      const btn = this.container.querySelector("a.button.button-primary-link");
      // If btn.props.disabled = false, then disabled attribute will be undefined
      expect(btn.attributes.disabled).toEqual(undefined);
    });

    it("renders stdout on first render", function() {
      this.instance.state = { currentView: 0 };
      TaskDirectoryActions.getDownloadURL = jasmine.createSpy(
        "TaskDirectoryActions#getDownloadURL"
      );

      this.instance.render();

      expect(TaskDirectoryActions.getDownloadURL).toHaveBeenCalledWith(
        "foo",
        "/stdout"
      );
    });

    it("renders stderr when view is changed", function() {
      this.instance = ReactDOM.render(
        <TaskFileViewer
          directory={
            new TaskDirectory({
              items: [
                { nlink: 1, path: "/stdout" },
                { nlink: 1, path: "/stderr" }
              ]
            })
          }
          params={{ filePath: "/stderr" }}
          selectedLogFile={new DirectoryItem({ nlink: 1, path: "/stderr" })}
          task={{ slave_id: "foo" }}
        />,
        this.container
      );

      // Setup spy after state has been configured
      TaskDirectoryActions.getDownloadURL = jasmine.createSpy(
        "TaskDirectoryActions#getDownloadURL"
      );

      this.instance.render();

      expect(TaskDirectoryActions.getDownloadURL).toHaveBeenCalledWith(
        "foo",
        "/stderr"
      );
    });

    it("limits files to stdout and stderr when provided", function() {
      this.instance = ReactDOM.render(
        <TaskFileViewer
          directory={
            new TaskDirectory({
              items: [
                { nlink: 1, path: "/foo" },
                { nlink: 1, path: "/stdout" },
                { nlink: 1, path: "/stderr" }
              ]
            })
          }
          params={{}}
          limitLogFiles={["stdout", "stderr"]}
          task={{ slave_id: "foo" }}
        />,
        this.container
      );

      expect(this.instance.getLogFiles()).toEqual([
        new DirectoryItem({ nlink: 1, path: "/stdout" }),
        new DirectoryItem({ nlink: 1, path: "/stderr" })
      ]);
    });

    it("includes all files when limit is not provided", function() {
      this.instance = ReactDOM.render(
        <TaskFileViewer
          directory={
            new TaskDirectory({
              items: [
                { nlink: 1, path: "/foo" },
                { nlink: 1, path: "/stdout" },
                { nlink: 1, path: "/stderr" }
              ]
            })
          }
          params={{}}
          task={{ slave_id: "foo" }}
        />,
        this.container
      );

      expect(this.instance.getLogFiles()).toEqual([
        new DirectoryItem({ nlink: 1, path: "/foo" }),
        new DirectoryItem({ nlink: 1, path: "/stdout" }),
        new DirectoryItem({ nlink: 1, path: "/stderr" })
      ]);
    });
  });
});
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2015 Memorial Sloan-Kettering Cancer Center.
 *
 * This library is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY, WITHOUT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS
 * FOR A PARTICULAR PURPOSE. The software and documentation provided hereunder
 * is on an "as is" basis, and Memorial Sloan-Kettering Cancer Center has no
 * obligations to provide maintenance, support, updates, enhancements or
 * modifications. In no event shall Memorial Sloan-Kettering Cancer Center be
 * liable to any party for direct, indirect, special, incidental or
 * consequential damages, including lost profits, arising out of the use of this
 * software and its documentation, even if Memorial Sloan-Kettering Cancer
 * Center has been advised of the possibility of such damage.
 */

/*
 * This file is part of cBioPortal.
 *
 * cBioPortal is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

var StudyViewInitTopComponents = (function() {
    function liClickCallBack(_id, _text) {
        StudyViewInitCharts.createNewChart(_id, _text);
    };

    function addEvents() {

        $('#study-view-header-left-2').unbind('click');
        $('#study-view-header-left-2').click(function (){
            // clear all breadcrumbs
            BreadCrumbs.clearAllBreadCrumbs();

            var i,
                _charts = StudyViewInitCharts.getCharts(),
                _chartsLength = _charts.length;

            StudyViewInitScatterPlot.setclearFlag(true);

            //Previous using dc.filterAll(), but this will redraw word cloud
            //several times based on the number of charts. Right now, only
            //redraw word cloud if the chart has filter
            for( i = 0; i < _chartsLength; i++){
                if(_charts[i] !== "" &&
                        _charts[i].getChart().filter() !== null){

                    _charts[i].getChart().filter(null);
                }
            }

            //If set the filter to null the update scatterplot in charts do
            //not work, so need to update scatter plot here
            //StudyViewInitCharts.redrawScatter();

            dc.redrawAll();
            StudyViewInitTables.clearAllSelected();
            StudyViewInitCharts.resetBars();
            StudyViewInitCharts.redrawSpecialPlots();
            setTimeout(function() {
                StudyViewInitScatterPlot.setclearFlag(false);
            }, StudyViewParams.summaryParams.transitionDuration);
            StudyViewInitCharts.changeHeader();
        });

        $("#study-view-case-select-custom-submit-btn").click(function() {
            var ids = $('#study-view-case-select-custom-input').val().trim().split(/\s+/);
            var convertedIds = convertIds(ids);
            $('#study-view-header-right-1').qtip('toggle');
            if(_.isArray(convertedIds) && convertedIds.length > 0) {
                StudyViewInitCharts.filterChartsByGivingIDs(convertedIds);
                BreadCrumbs.updateSelectCaseIDdBreadCrumb('study-view-select-case', 'Custom', 'User defined cases', ids);
            }
        });

        $("#study-view-tutorial").click(function() {
            StudyViewInitIntroJS.init();
        });

        $("#study-view-header-left-5").click(function() {
            var _url;
            var _selectedCaseIds = StudyViewInitCharts.getSelectedCasesID();
            var _selectedPatientIds = StudyViewProxy.getPatientIdsBySampleIds(_selectedCaseIds);

            _selectedPatientIds = _selectedPatientIds.sort();
            _url =  "case.do?cancer_study_id="+
                    StudyViewParams.params.studyId+
                    "&case_id="+_selectedPatientIds[0]+
                    "#nav_case_ids="+_selectedPatientIds.join(",");

            window.open(_url);
        });

        $("#study-view-header-left-6").click(function () {
            var content = '';
            var sampleIds = StudyViewInitCharts.getSelectedCasesID();
            var attr = StudyViewProxy.getAttrData();
            var arr = [];
            var attrL = 0, arrL = 0;
            var strA = [];

            if (sampleIds.length === StudyViewProxy.getSampleIds().length) {
                arr = StudyViewProxy.getArrData();
            } else {
                arr = StudyViewProxy.getArrDataBySampleIds(sampleIds);
            }

            attrL = attr.length;
            for (var i = 0; i < attrL; i++) {
                strA.push(attr[i].display_name || 'Unknown');
            }
            content = strA.join('\t');
            strA.length =0;

            arrL = arr.length;

            for (var i = 0; i < arrL; i++) {
                strA.length = 0;
                for (var j = 0; j < attrL; j++) {
                    strA.push(arr[i][attr[j].attr_id]);
                }
                content += '\r\n' + strA.join('\t');
            }

            var downloadOpts = {
                filename: StudyViewParams.params.studyId + "_clinical_data.txt",
                contentType: "text/plain;charset=utf-8",
                preProcess: false
            };

            cbio.download.initDownload(content, downloadOpts);
        });

        $("#study-view-form").click(function(event){
            // add the necessary fields to the form
            if(!QueryByGeneTextArea.isEmpty()) {
                event.preventDefault();
                QueryByGeneTextArea.validateGenes(decideSubmit, false);
            }
        });

        $("#study-view-header-left-1").hover(function () {
            $("#query-by-gene-textarea").css("outline", "-webkit-focus-ring-color auto 5px");
            $("#study-view-header-left-5").css("outline", "-webkit-focus-ring-color auto 5px");
        }, function() {
            $("#query-by-gene-textarea").css("outline", "");
            $("#study-view-header-left-5").css("outline", "");
        });

        $("#study-view-header-left-5").hover(function () {
            $("#study-view-header-left-5").css("outline", "-webkit-focus-ring-color auto 5px");
        }, function() {
            $("#study-view-header-left-5").css("outline", "");
        });

        $("#study-view-header-left-6").hover(function () {
            $("#study-view-header-left-5").css("outline", "-webkit-focus-ring-color auto 5px");
        }, function() {
            $("#study-view-header-left-5").css("outline", "");
        });

    }

    // decide whether to proceed with the submit of the form
    function decideSubmit(allValid){
        // if all genes are valid, submit, otherwise show a notification
        if(allValid){
            new QueryByGeneUtil().addStudyViewFields();
            $("#study-view-form").trigger("submit");
        }
        else {
            new Notification().createNotification("There were problems with the selected genes. Please fix.", {message_type: "danger"});
            $("#query-by-gene-textarea").focus();
        }
    }

    //The selected id should be sample based. Check patient list if unidentified id exists.
    function convertIds(ids) {
        var radioVal = $('input[name=study-view-case-select-custom-radio]:checked').val();
        var sampleIds = [];
        var unmapped = [];
        if (radioVal === 'patient') {
            _.each(ids, function (id) {
                var mappedId = StudyViewProxy.getSampleIdsByPatientIds([id]);
                if (_.isUndefined(mappedId) || _.isEmpty(mappedId)) {
                    unmapped.push(id);
                } else {
                    sampleIds = sampleIds.concat(mappedId);
                }
            });
        } else {
            _.each(ids, function (id) {
                if (StudyViewProxy.sampleIdExist(id)) {
                    sampleIds.push(id);
                } else {
                    unmapped.push(id);
                }
            });
        }

        if (unmapped.length > 0) {
            new Notification().createNotification(sampleIds.length +
                ' samples selected. The following ' + (radioVal === 'patient' ? 'patient' : 'sample') +
                ' ID' + (unmapped.length === 1 ? ' was' : 's were') + ' not found in this study: ' +
                unmapped.join(', '), {message_type: 'warning'});
        } else {
            new Notification().createNotification(sampleIds.length + ' samples selected.', {message_type: 'info'});
        }

        return sampleIds;
    }

    function changeHeader(_filteredResult, _numOfCases, _removedChart){
        var _caseID = [],
            _resultLength = _filteredResult.length,
            _charts = StudyViewInitCharts.getCharts(),

            //Check whether page has been scrolled or not, The position of
            //left-3 will be different
            windowScolled = false;

        for(var i=0; i<_filteredResult.length ; i++){
            _caseID.push(_filteredResult[i].CASE_ID);
        }

        $("#study-view-header-left-1").css('display','block');

        $("#study-view-header-left-3").css('display','block')
        $("#study-view-header-left-3").text("Samples selected: ");
        $("#study-view-header-left-5").css('display','block');
        $("#study-view-header-left-5").text(_resultLength);

        if(_resultLength !== _numOfCases){
            if(_resultLength === 0){
                $("#study-view-header-left-1").css('display','none');
                //$("#study-view-header-left-4").css('display','none');
            }
        }
        $("#study-view-header-left-case-ids").val(_caseID.join(" "));
    }

    function initAddCharts(target) {
        AddCharts.init(target);
        AddCharts.initAddChartsButton(StudyViewInitCharts.getShowedChartsInfo());
        AddCharts.liClickCallback(liClickCallBack);
    }

    function createDiv() {
        var _newElement = StudyViewBoilerplate.headerDiv(),
            _customDialogQtip = jQuery.extend(true, {}, StudyViewBoilerplate.headerCaseSelectCustomDialog);

        $("#study-view-header-function").append(_newElement);
        $("#study-view-header-function").append(StudyViewBoilerplate.customDialogDiv);
        $("#study-view-header-left-cancer_study-ids").val(StudyViewParams.params.studyId);
        $("#study-view-header-left-case-ids").val(StudyViewParams.params.sampleIds.join(" "));
        //$("#study-view-header-function").append(StudyViewBoilerplate.tutorialDiv);
        _customDialogQtip.position.target = $(window);
        _customDialogQtip.content.text = $('#study-view-case-select-custom-dialog');
        $('#study-view-header-right-1').qtip(_customDialogQtip);

        initAddCharts("#study-view-header-right");
        // ensure header has proper values
        StudyViewInitCharts.changeHeader();
    }

    return {
        init: function() {
            createDiv();
            addEvents();
            QueryByGeneTextArea.init('#query-by-gene-textarea', StudyViewInitTables.updateGeneHighlights);
        },

        changeHeader: changeHeader,
    };
})();<commit_msg>Add qTip for sample selected number<commit_after>/*
 * Copyright (c) 2015 Memorial Sloan-Kettering Cancer Center.
 *
 * This library is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY, WITHOUT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS
 * FOR A PARTICULAR PURPOSE. The software and documentation provided hereunder
 * is on an "as is" basis, and Memorial Sloan-Kettering Cancer Center has no
 * obligations to provide maintenance, support, updates, enhancements or
 * modifications. In no event shall Memorial Sloan-Kettering Cancer Center be
 * liable to any party for direct, indirect, special, incidental or
 * consequential damages, including lost profits, arising out of the use of this
 * software and its documentation, even if Memorial Sloan-Kettering Cancer
 * Center has been advised of the possibility of such damage.
 */

/*
 * This file is part of cBioPortal.
 *
 * cBioPortal is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

var StudyViewInitTopComponents = (function() {
    function liClickCallBack(_id, _text) {
        StudyViewInitCharts.createNewChart(_id, _text);
    };

    function addEvents() {

        $('#study-view-header-left-2').unbind('click');
        $('#study-view-header-left-2').click(function (){
            // clear all breadcrumbs
            BreadCrumbs.clearAllBreadCrumbs();

            var i,
                _charts = StudyViewInitCharts.getCharts(),
                _chartsLength = _charts.length;

            StudyViewInitScatterPlot.setclearFlag(true);

            //Previous using dc.filterAll(), but this will redraw word cloud
            //several times based on the number of charts. Right now, only
            //redraw word cloud if the chart has filter
            for( i = 0; i < _chartsLength; i++){
                if(_charts[i] !== "" &&
                        _charts[i].getChart().filter() !== null){

                    _charts[i].getChart().filter(null);
                }
            }

            //If set the filter to null the update scatterplot in charts do
            //not work, so need to update scatter plot here
            //StudyViewInitCharts.redrawScatter();

            dc.redrawAll();
            StudyViewInitTables.clearAllSelected();
            StudyViewInitCharts.resetBars();
            StudyViewInitCharts.redrawSpecialPlots();
            setTimeout(function() {
                StudyViewInitScatterPlot.setclearFlag(false);
            }, StudyViewParams.summaryParams.transitionDuration);
            StudyViewInitCharts.changeHeader();
        });

        $("#study-view-case-select-custom-submit-btn").click(function() {
            var ids = $('#study-view-case-select-custom-input').val().trim().split(/\s+/);
            var convertedIds = convertIds(ids);
            $('#study-view-header-right-1').qtip('toggle');
            if(_.isArray(convertedIds) && convertedIds.length > 0) {
                StudyViewInitCharts.filterChartsByGivingIDs(convertedIds);
                BreadCrumbs.updateSelectCaseIDdBreadCrumb('study-view-select-case', 'Custom', 'User defined cases', ids);
            }
        });

        $("#study-view-tutorial").click(function() {
            StudyViewInitIntroJS.init();
        });

        $("#study-view-header-left-5").click(function() {
            var _url;
            var _selectedCaseIds = StudyViewInitCharts.getSelectedCasesID();
            var _selectedPatientIds = StudyViewProxy.getPatientIdsBySampleIds(_selectedCaseIds);

            _selectedPatientIds = _selectedPatientIds.sort();
            _url =  "case.do?cancer_study_id="+
                    StudyViewParams.params.studyId+
                    "&case_id="+_selectedPatientIds[0]+
                    "#nav_case_ids="+_selectedPatientIds.join(",");

            window.open(_url);
        });

        $("#study-view-header-left-6").click(function () {
            var content = '';
            var sampleIds = StudyViewInitCharts.getSelectedCasesID();
            var attr = StudyViewProxy.getAttrData();
            var arr = [];
            var attrL = 0, arrL = 0;
            var strA = [];

            if (sampleIds.length === StudyViewProxy.getSampleIds().length) {
                arr = StudyViewProxy.getArrData();
            } else {
                arr = StudyViewProxy.getArrDataBySampleIds(sampleIds);
            }

            attrL = attr.length;
            for (var i = 0; i < attrL; i++) {
                strA.push(attr[i].display_name || 'Unknown');
            }
            content = strA.join('\t');
            strA.length =0;

            arrL = arr.length;

            for (var i = 0; i < arrL; i++) {
                strA.length = 0;
                for (var j = 0; j < attrL; j++) {
                    strA.push(arr[i][attr[j].attr_id]);
                }
                content += '\r\n' + strA.join('\t');
            }

            var downloadOpts = {
                filename: StudyViewParams.params.studyId + "_clinical_data.txt",
                contentType: "text/plain;charset=utf-8",
                preProcess: false
            };

            cbio.download.initDownload(content, downloadOpts);
        });

        $("#study-view-form").click(function(event){
            // add the necessary fields to the form
            if(!QueryByGeneTextArea.isEmpty()) {
                event.preventDefault();
                QueryByGeneTextArea.validateGenes(decideSubmit, false);
            }
        });

        $("#study-view-header-left-1").hover(function () {
            $("#query-by-gene-textarea").css("outline", "-webkit-focus-ring-color auto 5px");
            $("#study-view-header-left-5").css("outline", "-webkit-focus-ring-color auto 5px");
        }, function() {
            $("#query-by-gene-textarea").css("outline", "");
            $("#study-view-header-left-5").css("outline", "");
        });

        $("#study-view-header-left-5").hover(function () {
            $("#study-view-header-left-5").css("outline", "-webkit-focus-ring-color auto 5px");
        }, function() {
            $("#study-view-header-left-5").css("outline", "");
        });

        $("#study-view-header-left-6").hover(function () {
            $("#study-view-header-left-5").css("outline", "-webkit-focus-ring-color auto 5px");
        }, function() {
            $("#study-view-header-left-5").css("outline", "");
        });

        $('#study-view-header-left-5').qtip({
            content: {text: 'Click to view the selected cases' },
            style: { classes: 'qtip-light qtip-rounded qtip-shadow qtip-lightyellow' },
            show: {event: 'mouseover'},
            hide: {fixed:true, delay: 100, event: 'mouseout'},
            position: {my:'bottom center', at:'top center', viewport: $(window)}
        });
    }

    // decide whether to proceed with the submit of the form
    function decideSubmit(allValid){
        // if all genes are valid, submit, otherwise show a notification
        if(allValid){
            new QueryByGeneUtil().addStudyViewFields();
            $("#study-view-form").trigger("submit");
        }
        else {
            new Notification().createNotification("There were problems with the selected genes. Please fix.", {message_type: "danger"});
            $("#query-by-gene-textarea").focus();
        }
    }

    //The selected id should be sample based. Check patient list if unidentified id exists.
    function convertIds(ids) {
        var radioVal = $('input[name=study-view-case-select-custom-radio]:checked').val();
        var sampleIds = [];
        var unmapped = [];
        if (radioVal === 'patient') {
            _.each(ids, function (id) {
                var mappedId = StudyViewProxy.getSampleIdsByPatientIds([id]);
                if (_.isUndefined(mappedId) || _.isEmpty(mappedId)) {
                    unmapped.push(id);
                } else {
                    sampleIds = sampleIds.concat(mappedId);
                }
            });
        } else {
            _.each(ids, function (id) {
                if (StudyViewProxy.sampleIdExist(id)) {
                    sampleIds.push(id);
                } else {
                    unmapped.push(id);
                }
            });
        }

        if (unmapped.length > 0) {
            new Notification().createNotification(sampleIds.length +
                ' samples selected. The following ' + (radioVal === 'patient' ? 'patient' : 'sample') +
                ' ID' + (unmapped.length === 1 ? ' was' : 's were') + ' not found in this study: ' +
                unmapped.join(', '), {message_type: 'warning'});
        } else {
            new Notification().createNotification(sampleIds.length + ' samples selected.', {message_type: 'info'});
        }

        return sampleIds;
    }

    function changeHeader(_filteredResult, _numOfCases, _removedChart){
        var _caseID = [],
            _resultLength = _filteredResult.length,
            _charts = StudyViewInitCharts.getCharts(),

            //Check whether page has been scrolled or not, The position of
            //left-3 will be different
            windowScolled = false;

        for(var i=0; i<_filteredResult.length ; i++){
            _caseID.push(_filteredResult[i].CASE_ID);
        }

        $("#study-view-header-left-1").css('display','block');

        $("#study-view-header-left-3").css('display','block')
        $("#study-view-header-left-3").text("Samples selected: ");
        $("#study-view-header-left-5").css('display','block');
        $("#study-view-header-left-5").text(_resultLength);

        if(_resultLength !== _numOfCases){
            if(_resultLength === 0){
                $("#study-view-header-left-1").css('display','none');
                //$("#study-view-header-left-4").css('display','none');
            }
        }
        $("#study-view-header-left-case-ids").val(_caseID.join(" "));
    }

    function initAddCharts(target) {
        AddCharts.init(target);
        AddCharts.initAddChartsButton(StudyViewInitCharts.getShowedChartsInfo());
        AddCharts.liClickCallback(liClickCallBack);
    }

    function createDiv() {
        var _newElement = StudyViewBoilerplate.headerDiv(),
            _customDialogQtip = jQuery.extend(true, {}, StudyViewBoilerplate.headerCaseSelectCustomDialog);

        $("#study-view-header-function").append(_newElement);
        $("#study-view-header-function").append(StudyViewBoilerplate.customDialogDiv);
        $("#study-view-header-left-cancer_study-ids").val(StudyViewParams.params.studyId);
        $("#study-view-header-left-case-ids").val(StudyViewParams.params.sampleIds.join(" "));
        //$("#study-view-header-function").append(StudyViewBoilerplate.tutorialDiv);
        _customDialogQtip.position.target = $(window);
        _customDialogQtip.content.text = $('#study-view-case-select-custom-dialog');
        $('#study-view-header-right-1').qtip(_customDialogQtip);

        initAddCharts("#study-view-header-right");
        // ensure header has proper values
        StudyViewInitCharts.changeHeader();
    }

    return {
        init: function() {
            createDiv();
            addEvents();
            QueryByGeneTextArea.init('#query-by-gene-textarea', StudyViewInitTables.updateGeneHighlights);
        },

        changeHeader: changeHeader,
    };
})();<|endoftext|>