<commit_before>/*
 * @class Control.Layers
 * @aka L.Control.Layers
 * @inherits Control
 *
 * The layers control gives users the ability to switch between different base layers and switch overlays on/off (check out the [detailed example](http://leafletjs.com/examples/layers-control.html)). Extends `Control`.
 *
 * @example
 *
 * ```js
 * var baseLayers = {
 * 	"Mapbox": mapbox,
 * 	"OpenStreetMap": osm
 * };
 *
 * var overlays = {
 * 	"Marker": marker,
 * 	"Roads": roadsLayer
 * };
 *
 * L.control.layers(baseLayers, overlays).addTo(map);
 * ```
 *
 * The `baseLayers` and `overlays` parameters are object literals with layer names as keys and `Layer` objects as values:
 *
 * ```js
 * {
 *     "<someName1>": layer1,
 *     "<someName2>": layer2
 * }
 * ```
 *
 * The layer names can contain HTML, which allows you to add additional styling to the items:
 *
 * ```js
 * {"<img src='my-layer-icon' /> <span class='my-layer-item'>My Layer</span>": myLayer}
 * ```
 */

L.Control.Layers = L.Control.extend({
	// @section
	// @aka Control.Layers options
	options: {
		// @option collapsed: Boolean = true
		// If `true`, the control will be collapsed into an icon and expanded on mouse hover or touch.
		collapsed: true,
		position: 'topright',

		// @option autoZIndex: Boolean = true
		// If `true`, the control will assign zIndexes in increasing order to all of its layers so that the order is preserved when switching them on/off.
		autoZIndex: true,

		// @option hideSingleBase: Boolean = false
		// If `true`, the base layers in the control will be hidden when there is only one.
		hideSingleBase: false
	},

	initialize: function (baseLayers, overlays, options) {
		L.setOptions(this, options);

		this._layers = [];
		this._lastZIndex = 0;
		this._handlingClick = false;

		for (var i in baseLayers) {
			this._addLayer(baseLayers[i], i);
		}

		for (i in overlays) {
			this._addLayer(overlays[i], i, true);
		}
	},

	onAdd: function (map) {
		this._initLayout();
		this._update();

		this._map = map;
		map.on('zoomend', this._checkDisabledLayers, this);

		return this._container;
	},

	onRemove: function () {
		this._map.off('zoomend', this._checkDisabledLayers, this);

		for (var id in this._layers) {
			this._layers[id].layer.off('add remove', this._onLayerChange, this);
		}
	},

	// @method addBaseLayer(layer: Layer, name: String): this
	// Adds a base layer (radio button entry) with the given name to the control.
	addBaseLayer: function (layer, name) {
		this._addLayer(layer, name);
		return (this._map) ? this._update() : this;
	},

	// @method addOverlay(layer: Layer, name: String): this
	// Adds an overlay (checkbox entry) with the given name to the control.
	addOverlay: function (layer, name) {
		this._addLayer(layer, name, true);
		return (this._map) ? this._update() : this;
	},

	// @method removeLayer(layer: Layer): this
	// Remove the given layer from the control.
	removeLayer: function (layer) {
		layer.off('add remove', this._onLayerChange, this);

		var obj = this._getLayer(L.stamp(layer));
		if (obj) {
			this._layers.splice(this._layers.indexOf(obj), 1);
		}
		return (this._map) ? this._update() : this;
	},

	// @method expand(): this
	// Expand the control container if collapsed.
	expand: function () {
		L.DomUtil.addClass(this._container, 'leaflet-control-layers-expanded');
		this._form.style.height = null;
		var acceptableHeight = this._map.getSize().y - (this._container.offsetTop + 50);
		if (acceptableHeight < this._form.clientHeight) {
			L.DomUtil.addClass(this._form, 'leaflet-control-layers-scrollbar');
			this._form.style.height = acceptableHeight + 'px';
		} else {
			L.DomUtil.removeClass(this._form, 'leaflet-control-layers-scrollbar');
		}
		this._checkDisabledLayers();
		return this;
	},

	// @method collapse(): this
	// Collapse the control container if expanded.
	collapse: function () {
		L.DomUtil.removeClass(this._container, 'leaflet-control-layers-expanded');
		return this;
	},

	_initLayout: function () {
		var className = 'leaflet-control-layers',
		    container = this._container = L.DomUtil.create('div', className);

		// makes this work on IE touch devices by stopping it from firing a mouseout event when the touch is released
		container.setAttribute('aria-haspopup', true);

		L.DomEvent.disableClickPropagation(container);
		if (!L.Browser.touch) {
			L.DomEvent.disableScrollPropagation(container);
		}

		var form = this._form = L.DomUtil.create('form', className + '-list');

		if (this.options.collapsed) {
			if (!L.Browser.android) {
				L.DomEvent.on(container, {
					mouseenter: this.expand,
					mouseleave: this.collapse
				}, this);
			}

			var link = this._layersLink = L.DomUtil.create('a', className + '-toggle', container);
			link.href = '#';
			link.title = 'Layers';

			if (L.Browser.touch) {
				L.DomEvent
				    .on(link, 'click', L.DomEvent.stop)
				    .on(link, 'click', this.expand, this);
			} else {
				L.DomEvent.on(link, 'focus', this.expand, this);
			}

			// work around for Firefox Android issue https://github.com/Leaflet/Leaflet/issues/2033
			L.DomEvent.on(form, 'click', function () {
				setTimeout(L.bind(this._onInputClick, this), 0);
			}, this);

			this._map.on('click', this.collapse, this);
			// TODO keyboard accessibility
		} else {
			this.expand();
		}

		this._baseLayersList = L.DomUtil.create('div', className + '-base', form);
		this._separator = L.DomUtil.create('div', className + '-separator', form);
		this._overlaysList = L.DomUtil.create('div', className + '-overlays', form);

		container.appendChild(form);
	},

	_getLayer: function (id) {
		for (var i = 0; i <= this._layers.length; i++) {

			if (this._layers[i] && L.stamp(this._layers[i].layer) === id) {
				return this._layers[i];
			}
		}
	},

	_addLayer: function (layer, name, overlay) {
		layer.on('add remove', this._onLayerChange, this);

		this._layers.push({
			layer: layer,
			name: name,
			overlay: overlay
		});

		if (this.options.autoZIndex && layer.setZIndex) {
			this._lastZIndex++;
			layer.setZIndex(this._lastZIndex);
		}
	},

	_update: function () {
		if (!this._container) { return this; }

		L.DomUtil.empty(this._baseLayersList);
		L.DomUtil.empty(this._overlaysList);

		var baseLayersPresent, overlaysPresent, i, obj, baseLayersCount = 0;

		for (i in this._layers) {
			obj = this._layers[i];
			this._addItem(obj);
			overlaysPresent = overlaysPresent || obj.overlay;
			baseLayersPresent = baseLayersPresent || !obj.overlay;
			baseLayersCount += !obj.overlay ? 1 : 0;
		}

		// Hide base layers section if there's only one layer.
		if (this.options.hideSingleBase) {
			baseLayersPresent = baseLayersPresent && baseLayersCount > 1;
			this._baseLayersList.style.display = baseLayersPresent ? '' : 'none';
		}

		this._separator.style.display = overlaysPresent && baseLayersPresent ? '' : 'none';

		return this;
	},

	_onLayerChange: function (e) {
		if (!this._handlingClick) {
			this._update();
		}

		var obj = this._getLayer(L.stamp(e.target));

		// @namespace Map
		// @section Layer events
		// @event baselayerchange: LayersControlEvent
		// Fired when the base layer is changed through the [layer control](#control-layers).
		// @event overlayadd: LayersControlEvent
		// Fired when an overlay is selected through the [layer control](#control-layers).
		// @event overlayremove: LayersControlEvent
		// Fired when an overlay is deselected through the [layer control](#control-layers).
		// @namespace Control.Layers
		var type = obj.overlay ?
			(e.type === 'add' ? 'overlayadd' : 'overlayremove') :
			(e.type === 'add' ? 'baselayerchange' : null);

		if (type) {
			this._map.fire(type, obj);
		}
	},

	// IE7 bugs out if you create a radio dynamically, so you have to do it this hacky way (see http://bit.ly/PqYLBe)
	_createRadioElement: function (name, checked) {

		var radioHtml = '<input type="radio" class="leaflet-control-layers-selector" name="' +
				name + '"' + (checked ? ' checked="checked"' : '') + '/>';

		var radioFragment = document.createElement('div');
		radioFragment.innerHTML = radioHtml;

		return radioFragment.firstChild;
	},

	_addItem: function (obj) {
		var label = document.createElement('label'),
		    checked = this._map.hasLayer(obj.layer),
		    input;

		if (obj.overlay) {
			input = document.createElement('input');
			input.type = 'checkbox';
			input.className = 'leaflet-control-layers-selector';
			input.defaultChecked = checked;
		} else {
			input = this._createRadioElement('leaflet-base-layers', checked);
		}

		input.layerId = L.stamp(obj.layer);

		L.DomEvent.on(input, 'click', this._onInputClick, this);

		var name = document.createElement('span');
		name.innerHTML = ' ' + obj.name;

		// Helps from preventing layer control flicker when checkboxes are disabled
		// https://github.com/Leaflet/Leaflet/issues/2771
		var holder = document.createElement('div');

		label.appendChild(holder);
		holder.appendChild(input);
		holder.appendChild(name);

		var container = obj.overlay ? this._overlaysList : this._baseLayersList;
		container.appendChild(label);

		this._checkDisabledLayers();
		return label;
	},

	_onInputClick: function () {
		var inputs = this._form.getElementsByTagName('input'),
		    input, layer, hasLayer;
		var addedLayers = [],
		    removedLayers = [];

		this._handlingClick = true;

		for (var i = inputs.length - 1; i >= 0; i--) {
			input = inputs[i];
			layer = this._getLayer(input.layerId).layer;
			hasLayer = this._map.hasLayer(layer);

			if (input.checked && !hasLayer) {
				addedLayers.push(layer);

			} else if (!input.checked && hasLayer) {
				removedLayers.push(layer);
			}
		}

		// Bugfix issue 2318: Should remove all old layers before readding new ones
		for (i = 0; i < removedLayers.length; i++) {
			this._map.removeLayer(removedLayers[i]);
		}
		for (i = 0; i < addedLayers.length; i++) {
			this._map.addLayer(addedLayers[i]);
		}

		this._handlingClick = false;

		this._refocusOnMap();
	},

	_checkDisabledLayers: function () {
		var inputs = this._form.getElementsByTagName('input'),
		    input,
		    layer,
		    zoom = this._map.getZoom();

		for (var i = inputs.length - 1; i >= 0; i--) {
			input = inputs[i];
			layer = this._getLayer(input.layerId).layer;
			input.disabled = (layer.options.minZoom !== undefined && zoom < layer.options.minZoom) ||
			                 (layer.options.maxZoom !== undefined && zoom > layer.options.maxZoom);

		}
	},

	_expand: function () {
		// Backward compatibility, remove me in 1.1.
		return this.expand();
	},

	_collapse: function () {
		// Backward compatibility, remove me in 1.1.
		return this.collapse();
	}

});

// @factory L.control.layers(baselayers?: Object, overlays?: Object, options?: Control.Layers options)
// Creates an attribution control with the given layers. Base layers will be switched with radio buttons, while overlays will be switched with checkboxes. Note that all base layers should be passed in the base layers object, but only one should be added to the map during map instantiation.
L.control.layers = function (baseLayers, overlays, options) {
	return new L.Control.Layers(baseLayers, overlays, options);
};
<commit_msg>Replace for..in with standard for in L.Control.Layers, fixes #4508 (#4509)<commit_after>/*
 * @class Control.Layers
 * @aka L.Control.Layers
 * @inherits Control
 *
 * The layers control gives users the ability to switch between different base layers and switch overlays on/off (check out the [detailed example](http://leafletjs.com/examples/layers-control.html)). Extends `Control`.
 *
 * @example
 *
 * ```js
 * var baseLayers = {
 * 	"Mapbox": mapbox,
 * 	"OpenStreetMap": osm
 * };
 *
 * var overlays = {
 * 	"Marker": marker,
 * 	"Roads": roadsLayer
 * };
 *
 * L.control.layers(baseLayers, overlays).addTo(map);
 * ```
 *
 * The `baseLayers` and `overlays` parameters are object literals with layer names as keys and `Layer` objects as values:
 *
 * ```js
 * {
 *     "<someName1>": layer1,
 *     "<someName2>": layer2
 * }
 * ```
 *
 * The layer names can contain HTML, which allows you to add additional styling to the items:
 *
 * ```js
 * {"<img src='my-layer-icon' /> <span class='my-layer-item'>My Layer</span>": myLayer}
 * ```
 */

L.Control.Layers = L.Control.extend({
	// @section
	// @aka Control.Layers options
	options: {
		// @option collapsed: Boolean = true
		// If `true`, the control will be collapsed into an icon and expanded on mouse hover or touch.
		collapsed: true,
		position: 'topright',

		// @option autoZIndex: Boolean = true
		// If `true`, the control will assign zIndexes in increasing order to all of its layers so that the order is preserved when switching them on/off.
		autoZIndex: true,

		// @option hideSingleBase: Boolean = false
		// If `true`, the base layers in the control will be hidden when there is only one.
		hideSingleBase: false
	},

	initialize: function (baseLayers, overlays, options) {
		L.setOptions(this, options);

		this._layers = [];
		this._lastZIndex = 0;
		this._handlingClick = false;

		for (var i in baseLayers) {
			this._addLayer(baseLayers[i], i);
		}

		for (i in overlays) {
			this._addLayer(overlays[i], i, true);
		}
	},

	onAdd: function (map) {
		this._initLayout();
		this._update();

		this._map = map;
		map.on('zoomend', this._checkDisabledLayers, this);

		return this._container;
	},

	onRemove: function () {
		this._map.off('zoomend', this._checkDisabledLayers, this);

		for (var i = 0; i < this._layers.length; i++) {
			this._layers[i].layer.off('add remove', this._onLayerChange, this);
		}
	},

	// @method addBaseLayer(layer: Layer, name: String): this
	// Adds a base layer (radio button entry) with the given name to the control.
	addBaseLayer: function (layer, name) {
		this._addLayer(layer, name);
		return (this._map) ? this._update() : this;
	},

	// @method addOverlay(layer: Layer, name: String): this
	// Adds an overlay (checkbox entry) with the given name to the control.
	addOverlay: function (layer, name) {
		this._addLayer(layer, name, true);
		return (this._map) ? this._update() : this;
	},

	// @method removeLayer(layer: Layer): this
	// Remove the given layer from the control.
	removeLayer: function (layer) {
		layer.off('add remove', this._onLayerChange, this);

		var obj = this._getLayer(L.stamp(layer));
		if (obj) {
			this._layers.splice(this._layers.indexOf(obj), 1);
		}
		return (this._map) ? this._update() : this;
	},

	// @method expand(): this
	// Expand the control container if collapsed.
	expand: function () {
		L.DomUtil.addClass(this._container, 'leaflet-control-layers-expanded');
		this._form.style.height = null;
		var acceptableHeight = this._map.getSize().y - (this._container.offsetTop + 50);
		if (acceptableHeight < this._form.clientHeight) {
			L.DomUtil.addClass(this._form, 'leaflet-control-layers-scrollbar');
			this._form.style.height = acceptableHeight + 'px';
		} else {
			L.DomUtil.removeClass(this._form, 'leaflet-control-layers-scrollbar');
		}
		this._checkDisabledLayers();
		return this;
	},

	// @method collapse(): this
	// Collapse the control container if expanded.
	collapse: function () {
		L.DomUtil.removeClass(this._container, 'leaflet-control-layers-expanded');
		return this;
	},

	_initLayout: function () {
		var className = 'leaflet-control-layers',
		    container = this._container = L.DomUtil.create('div', className);

		// makes this work on IE touch devices by stopping it from firing a mouseout event when the touch is released
		container.setAttribute('aria-haspopup', true);

		L.DomEvent.disableClickPropagation(container);
		if (!L.Browser.touch) {
			L.DomEvent.disableScrollPropagation(container);
		}

		var form = this._form = L.DomUtil.create('form', className + '-list');

		if (this.options.collapsed) {
			if (!L.Browser.android) {
				L.DomEvent.on(container, {
					mouseenter: this.expand,
					mouseleave: this.collapse
				}, this);
			}

			var link = this._layersLink = L.DomUtil.create('a', className + '-toggle', container);
			link.href = '#';
			link.title = 'Layers';

			if (L.Browser.touch) {
				L.DomEvent
				    .on(link, 'click', L.DomEvent.stop)
				    .on(link, 'click', this.expand, this);
			} else {
				L.DomEvent.on(link, 'focus', this.expand, this);
			}

			// work around for Firefox Android issue https://github.com/Leaflet/Leaflet/issues/2033
			L.DomEvent.on(form, 'click', function () {
				setTimeout(L.bind(this._onInputClick, this), 0);
			}, this);

			this._map.on('click', this.collapse, this);
			// TODO keyboard accessibility
		} else {
			this.expand();
		}

		this._baseLayersList = L.DomUtil.create('div', className + '-base', form);
		this._separator = L.DomUtil.create('div', className + '-separator', form);
		this._overlaysList = L.DomUtil.create('div', className + '-overlays', form);

		container.appendChild(form);
	},

	_getLayer: function (id) {
		for (var i = 0; i <= this._layers.length; i++) {

			if (this._layers[i] && L.stamp(this._layers[i].layer) === id) {
				return this._layers[i];
			}
		}
	},

	_addLayer: function (layer, name, overlay) {
		layer.on('add remove', this._onLayerChange, this);

		this._layers.push({
			layer: layer,
			name: name,
			overlay: overlay
		});

		if (this.options.autoZIndex && layer.setZIndex) {
			this._lastZIndex++;
			layer.setZIndex(this._lastZIndex);
		}
	},

	_update: function () {
		if (!this._container) { return this; }

		L.DomUtil.empty(this._baseLayersList);
		L.DomUtil.empty(this._overlaysList);

		var baseLayersPresent, overlaysPresent, i, obj, baseLayersCount = 0;

		for (i = 0; i < this._layers.length; i++) {
			obj = this._layers[i];
			this._addItem(obj);
			overlaysPresent = overlaysPresent || obj.overlay;
			baseLayersPresent = baseLayersPresent || !obj.overlay;
			baseLayersCount += !obj.overlay ? 1 : 0;
		}

		// Hide base layers section if there's only one layer.
		if (this.options.hideSingleBase) {
			baseLayersPresent = baseLayersPresent && baseLayersCount > 1;
			this._baseLayersList.style.display = baseLayersPresent ? '' : 'none';
		}

		this._separator.style.display = overlaysPresent && baseLayersPresent ? '' : 'none';

		return this;
	},

	_onLayerChange: function (e) {
		if (!this._handlingClick) {
			this._update();
		}

		var obj = this._getLayer(L.stamp(e.target));

		// @namespace Map
		// @section Layer events
		// @event baselayerchange: LayersControlEvent
		// Fired when the base layer is changed through the [layer control](#control-layers).
		// @event overlayadd: LayersControlEvent
		// Fired when an overlay is selected through the [layer control](#control-layers).
		// @event overlayremove: LayersControlEvent
		// Fired when an overlay is deselected through the [layer control](#control-layers).
		// @namespace Control.Layers
		var type = obj.overlay ?
			(e.type === 'add' ? 'overlayadd' : 'overlayremove') :
			(e.type === 'add' ? 'baselayerchange' : null);

		if (type) {
			this._map.fire(type, obj);
		}
	},

	// IE7 bugs out if you create a radio dynamically, so you have to do it this hacky way (see http://bit.ly/PqYLBe)
	_createRadioElement: function (name, checked) {

		var radioHtml = '<input type="radio" class="leaflet-control-layers-selector" name="' +
				name + '"' + (checked ? ' checked="checked"' : '') + '/>';

		var radioFragment = document.createElement('div');
		radioFragment.innerHTML = radioHtml;

		return radioFragment.firstChild;
	},

	_addItem: function (obj) {
		var label = document.createElement('label'),
		    checked = this._map.hasLayer(obj.layer),
		    input;

		if (obj.overlay) {
			input = document.createElement('input');
			input.type = 'checkbox';
			input.className = 'leaflet-control-layers-selector';
			input.defaultChecked = checked;
		} else {
			input = this._createRadioElement('leaflet-base-layers', checked);
		}

		input.layerId = L.stamp(obj.layer);

		L.DomEvent.on(input, 'click', this._onInputClick, this);

		var name = document.createElement('span');
		name.innerHTML = ' ' + obj.name;

		// Helps from preventing layer control flicker when checkboxes are disabled
		// https://github.com/Leaflet/Leaflet/issues/2771
		var holder = document.createElement('div');

		label.appendChild(holder);
		holder.appendChild(input);
		holder.appendChild(name);

		var container = obj.overlay ? this._overlaysList : this._baseLayersList;
		container.appendChild(label);

		this._checkDisabledLayers();
		return label;
	},

	_onInputClick: function () {
		var inputs = this._form.getElementsByTagName('input'),
		    input, layer, hasLayer;
		var addedLayers = [],
		    removedLayers = [];

		this._handlingClick = true;

		for (var i = inputs.length - 1; i >= 0; i--) {
			input = inputs[i];
			layer = this._getLayer(input.layerId).layer;
			hasLayer = this._map.hasLayer(layer);

			if (input.checked && !hasLayer) {
				addedLayers.push(layer);

			} else if (!input.checked && hasLayer) {
				removedLayers.push(layer);
			}
		}

		// Bugfix issue 2318: Should remove all old layers before readding new ones
		for (i = 0; i < removedLayers.length; i++) {
			this._map.removeLayer(removedLayers[i]);
		}
		for (i = 0; i < addedLayers.length; i++) {
			this._map.addLayer(addedLayers[i]);
		}

		this._handlingClick = false;

		this._refocusOnMap();
	},

	_checkDisabledLayers: function () {
		var inputs = this._form.getElementsByTagName('input'),
		    input,
		    layer,
		    zoom = this._map.getZoom();

		for (var i = inputs.length - 1; i >= 0; i--) {
			input = inputs[i];
			layer = this._getLayer(input.layerId).layer;
			input.disabled = (layer.options.minZoom !== undefined && zoom < layer.options.minZoom) ||
			                 (layer.options.maxZoom !== undefined && zoom > layer.options.maxZoom);

		}
	},

	_expand: function () {
		// Backward compatibility, remove me in 1.1.
		return this.expand();
	},

	_collapse: function () {
		// Backward compatibility, remove me in 1.1.
		return this.collapse();
	}

});

// @factory L.control.layers(baselayers?: Object, overlays?: Object, options?: Control.Layers options)
// Creates an attribution control with the given layers. Base layers will be switched with radio buttons, while overlays will be switched with checkboxes. Note that all base layers should be passed in the base layers object, but only one should be added to the map during map instantiation.
L.control.layers = function (baseLayers, overlays, options) {
	return new L.Control.Layers(baseLayers, overlays, options);
};
<|endoftext|>


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

  angular.module('SmallBIApp')
    .controller('loginController', loginController);

  function loginController(AuthService) {
    var vm = this;
    vm.dadosLogin = {};

    angular.extend(vm, {
      login: login
    });

    function login() {
      AuthService.signin(vm.dadosLogin).then(
        function () {

      }, function () {

      });
    }

    function activate() {

    }

    activate();
  }
})();
<commit_msg>Update login.controller.js<commit_after>
(function () {
  'use strict';

  angular.module('SmallBIApp')
    .controller('loginController', loginController);

  function loginController(AuthService) {
    var vm = this;
    vm.dadosLogin = {};

    angular.extend(vm, {
      login: login
    });

    function login() {
      AuthService.signin(vm.dadosLogin).then(
        function (result) {
        console.log(result);
      }, function () {

      });
    }
  }
})();
<|endoftext|>


<commit_before>/**
 *  @license 3-clause BSD
 *  @link https://github.com/QuestionKey/QuestionKey-Core
 */

function QuestionKeyNormalTree(targetSelector, options, theme) {
  this.options = $.extend({
      // required
      'treeServer':null,
      'treeId':null,
      // optional
      'hasSSL':true,
      'forceSSL':false,
      'serverURLSSL':null,
      'serverURLNotSSL':null,
      'logUserActions':true,
      'showPreviousAnswers':true,
      'callBackAfterDrawNode':null,
  }, options || {});
  if (!this.options.treeServer) {
      this.options.treeServer = document.location.host;
  }
  if (!this.options.serverURLSSL) {
      this.options.serverURLSSL = 'https://' + this.options.treeServer;
  }
  if (!this.options.serverURLNotSSL) {
      this.options.serverURLNotSSL = 'http://' + this.options.treeServer;
  }
    this.theme = $.extend({
        'loadingHTML':function(data) { return '
Loading, Please Wait
'; },
        'bodyHTML':function(data) {
            return '
'+
                '

'+
                '

'+
                '<form class="optionsWrapper" onsubmit="var id=$(this).find(\'input.option:checked\').val(); if (id) {'+data.this+'.selectOption(id);} return false;">

<input type="submit" value="Next"></form>'+
                '
'+
                '
Restart
'+
                '

Previous Answers

';
        },
        'bodySelectorTitle':'.title',
        'bodySelectorBody':'.body',
        'bodySelectorOptionsWrapper':'.optionsWrapper',
        'bodySelectorOptionsList':'.optionsList',
        'bodyselectorPreviousAnswersWrapper':'.previousAnswersWrapper',
        'bodyselectorPreviousAnswersList':'.previousAnswersTable',
        'bodyselectorPreviousAnswerItem':'.previousAnswersTable tr.answer',
        'previousAnswerHTML':function(data) {
            return '
'+
                ''+$("
").text(data.node.title_previous_answers).html()+'	'+
                ''+$("
").text(data.nodeOption.title).html()+'	'+
                'Change This	'+
                '
'; // TODO escape!
        },
        'optionHTML':function(data) {
            return '
'+
                ''+
                '<input name="option" class="option" type="radio" value="'+data.option.id+'">'+
                ''+$("
").text(data.option.title).html()+''+
                ''+
                '
';
        }
    }, theme || {});
  if (this.options.hasSSL && this.options.forceSSL) {
      this.serverURL = this.options.serverURLSSL;
  } else if (this.options.hasSSL) {
      this.serverURL = ('https:' == document.location.protocol ? this.options.serverURLSSL : this.options.serverURLNotSSL);
  } else {
      this.serverURL = this.options.serverURLNotSSL;
  }
  this.targetSelector = targetSelector;
  this.treeData = null;
  this.globalVariableName = null;
  this.sessionId = null;
  this.sessionRanTreeVersionId = null;
  this.started = false;
  this.stack = [];
  this.start = function() {
    this.started = true;
    if (this.treeData) {
      this._start();
    } else {
      $(this.targetSelector).html(this.theme.loadingHTML({}));
    }
  };
  this._start = function() {
    $(this.targetSelector).html(this.theme.bodyHTML( {'resetJavaScript':'window.'+this.globalVariableName+'.restart()', 'this':'window.'+this.globalVariableName } ));
    this._showStartNode();
  }
  this.restart = function() {
    if (!this.started) {
      return;
    }
    // remove this, as we are starting a new instance of running this tree
    this.sessionRanTreeVersionId = null;
    this._showStartNode();
  }
  this._showStartNode = function() {
    if (this.options.showPreviousAnswers) {
        $(this.targetSelector).find(this.theme.bodyselectorPreviousAnswersWrapper).hide();
        $(this.targetSelector).find(this.theme.bodyselectorPreviousAnswerItem).remove();
    }
    this.stack = [ { 'nodeId': this.treeData.start_node.id, 'nodeOptionId':null, 'goneBackTo': false  } ];
    this._showNode();
  }
  this._showNode = function() {
    var node = this.treeData.nodes[this.stack[this.stack.length - 1].nodeId];
    $(this.targetSelector).find(this.theme.bodySelectorTitle).html(node.title);
    if (node.body_text) {
      $(this.targetSelector).find(this.theme.bodySelectorBody).text(node.body_text);
    } else if (node.body_html) {
        $(this.targetSelector).find(this.theme.bodySelectorBody).html(node.body_html);
    }
    var optionsHTML = '';
    for(i in node.options) {
      var option = node.options[i];
      optionsHTML += this.theme.optionHTML({
          'selectOptionJavaScript':  'window.'+this.globalVariableName+'.selectOption(\''+option.id+'\')' ,
          'option': option
      });
    }
    if (optionsHTML) {
        $(this.targetSelector).find(this.theme.bodySelectorOptionsWrapper).show();
        $(this.targetSelector).find(this.theme.bodySelectorOptionsList).html(optionsHTML);
    } else {
        $(this.targetSelector).find(this.theme.bodySelectorOptionsWrapper).hide();
    }
    if (this.options.callBackAfterDrawNode) {
        this.options.callBackAfterDrawNode({ 'node':node });
    }
    // Stats
    if (this.options.logUserActions) {
        var data = {
            'session_id': this.sessionId,
            'ran_tree_version_id': this.sessionRanTreeVersionId,
            'tree_id': this.options.treeId,
            'tree_version_id': this.treeData.version.public_id,
            'node_id': this.stack[this.stack.length - 1].nodeId,
            'node_option_id': this.stack[this.stack.length - 1].nodeOptionId,
            'gone_back_to': this.stack[this.stack.length - 1].goneBackTo,
        };
        $.ajax({
            context: this,
            dataType: "jsonp",
            url: this.serverURL + '/api/v1/visitorsession/action.jsonp?callback=?',
            data: data,
            method: 'GET',
            success: function(data) {
                this.sessionId = data.session.id;
                if (data.session_ran_tree_version) {
                    this.sessionRanTreeVersionId = data.session_ran_tree_version.id;
                }
            },
        });
    }
  };
  this.selectOption = function(optionId) {
    var node = this.treeData.nodes[this.stack[this.stack.length - 1].nodeId];
    if (!node.title_previous_answers) {
        node.title_previous_answers = node.title;
    }
    var option = node.options[optionId];
    if (this.options.showPreviousAnswers) {
        $(this.targetSelector).find(this.theme.bodyselectorPreviousAnswersWrapper).show();
        $(this.targetSelector).find(this.theme.bodyselectorPreviousAnswersList).append(this.theme.previousAnswerHTML({'node':node, 'nodeOption':option,'stackPos':this.stack.length, 'this':'window.'+this.globalVariableName}));
    }
    this.stack.push({ 'nodeId':option.destination_node.id, 'nodeOptionId':option.id, 'goneBackTo': false });
    this._showNode();
  };
  this.goBackTo = function(stackPos) {
      if (stackPos < 2) {
          this.restart();
      } else {
          while(this.stack.length > stackPos) {
              this.stack.pop();
              $(this.targetSelector).find(this.theme.bodyselectorPreviousAnswerItem).last().remove();
          }
          this.stack[this.stack.length - 1].goneBackTo = true;
          this._showNode();
      }
  };
  var globalRefNum = Math.floor(Math.random() * 999999999) + 1;
  while("QuestionKeyNormalTree"+globalRefNum in window) {
    globalRefNum = Math.floor(Math.random() * 999999999) + 1;
  }
  window["QuestionKeyNormalTree"+globalRefNum] = this;
  this.globalVariableName = "QuestionKeyNormalTree"+globalRefNum;
  $.ajax({
    context: this,
    dataType: "jsonp",
    url: this.serverURL + '/api/v1/tree/' + this.options.treeId + '/data.jsonp?callback=?',
    success: function(data) {
      this.treeData = data;
      if (this.started) {
        this._start();
      }
    },
  });

}
<commit_msg>Add ScrollIntoViewOnChange option<commit_after>/**
 *  @license 3-clause BSD
 *  @link https://github.com/QuestionKey/QuestionKey-Core
 */

function QuestionKeyNormalTree(targetSelector, options, theme) {
  this.options = $.extend({
      // required
      'treeServer':null,
      'treeId':null,
      // optional
      'hasSSL':true,
      'forceSSL':false,
      'serverURLSSL':null,
      'serverURLNotSSL':null,
      'logUserActions':true,
      'showPreviousAnswers':true,
      'callBackAfterDrawNode':null,
      'scrollIntoViewOnChange':false,
  }, options || {});
  if (!this.options.treeServer) {
      this.options.treeServer = document.location.host;
  }
  if (!this.options.serverURLSSL) {
      this.options.serverURLSSL = 'https://' + this.options.treeServer;
  }
  if (!this.options.serverURLNotSSL) {
      this.options.serverURLNotSSL = 'http://' + this.options.treeServer;
  }
    this.theme = $.extend({
        'loadingHTML':function(data) { return '
Loading, Please Wait
'; },
        'bodyHTML':function(data) {
            return '
'+
                '

'+
                '

'+
                '<form class="optionsWrapper" onsubmit="var id=$(this).find(\'input.option:checked\').val(); if (id) {'+data.this+'.selectOption(id);} return false;">

<input type="submit" value="Next"></form>'+
                '
'+
                '
Restart
'+
                '

Previous Answers

';
        },
        'bodySelectorTitle':'.title',
        'bodySelectorBody':'.body',
        'bodySelectorOptionsWrapper':'.optionsWrapper',
        'bodySelectorOptionsList':'.optionsList',
        'bodyselectorPreviousAnswersWrapper':'.previousAnswersWrapper',
        'bodyselectorPreviousAnswersList':'.previousAnswersTable',
        'bodyselectorPreviousAnswerItem':'.previousAnswersTable tr.answer',
        'previousAnswerHTML':function(data) {
            return '
'+
                ''+$("
").text(data.node.title_previous_answers).html()+'	'+
                ''+$("
").text(data.nodeOption.title).html()+'	'+
                'Change This	'+
                '
'; // TODO escape!
        },
        'optionHTML':function(data) {
            return '
'+
                ''+
                '<input name="option" class="option" type="radio" value="'+data.option.id+'">'+
                ''+$("
").text(data.option.title).html()+''+
                ''+
                '
';
        }
    }, theme || {});
  if (this.options.hasSSL && this.options.forceSSL) {
      this.serverURL = this.options.serverURLSSL;
  } else if (this.options.hasSSL) {
      this.serverURL = ('https:' == document.location.protocol ? this.options.serverURLSSL : this.options.serverURLNotSSL);
  } else {
      this.serverURL = this.options.serverURLNotSSL;
  }
  this.targetSelector = targetSelector;
  this.treeData = null;
  this.globalVariableName = null;
  this.sessionId = null;
  this.sessionRanTreeVersionId = null;
  this.started = false;
  this.stack = [];
  this.start = function() {
    this.started = true;
    if (this.treeData) {
      this._start();
    } else {
      $(this.targetSelector).html(this.theme.loadingHTML({}));
    }
  };
  this._start = function() {
    $(this.targetSelector).html(this.theme.bodyHTML( {'resetJavaScript':'window.'+this.globalVariableName+'.restart()', 'this':'window.'+this.globalVariableName } ));
    this._showStartNode();
  }
  this.restart = function() {
    if (!this.started) {
      return;
    }
    // remove this, as we are starting a new instance of running this tree
    this.sessionRanTreeVersionId = null;
    this._showStartNode();
  }
  this._showStartNode = function() {
    if (this.options.showPreviousAnswers) {
        $(this.targetSelector).find(this.theme.bodyselectorPreviousAnswersWrapper).hide();
        $(this.targetSelector).find(this.theme.bodyselectorPreviousAnswerItem).remove();
    }
    this.stack = [ { 'nodeId': this.treeData.start_node.id, 'nodeOptionId':null, 'goneBackTo': false  } ];
    this._showNode();
  }
  this._showNode = function() {
    var node = this.treeData.nodes[this.stack[this.stack.length - 1].nodeId];
    $(this.targetSelector).find(this.theme.bodySelectorTitle).html(node.title);
    if (node.body_text) {
      $(this.targetSelector).find(this.theme.bodySelectorBody).text(node.body_text);
    } else if (node.body_html) {
        $(this.targetSelector).find(this.theme.bodySelectorBody).html(node.body_html);
    }
    var optionsHTML = '';
    for(i in node.options) {
      var option = node.options[i];
      optionsHTML += this.theme.optionHTML({
          'selectOptionJavaScript':  'window.'+this.globalVariableName+'.selectOption(\''+option.id+'\')' ,
          'option': option
      });
    }
    if (optionsHTML) {
        $(this.targetSelector).find(this.theme.bodySelectorOptionsWrapper).show();
        $(this.targetSelector).find(this.theme.bodySelectorOptionsList).html(optionsHTML);
    } else {
        $(this.targetSelector).find(this.theme.bodySelectorOptionsWrapper).hide();
    }
    if (this.options.scrollIntoViewOnChange) {
        $(this.targetSelector).get(0).scrollIntoView();
    }
    if (this.options.callBackAfterDrawNode) {
        this.options.callBackAfterDrawNode({ 'node':node });
    }
    // Stats
    if (this.options.logUserActions) {
        var data = {
            'session_id': this.sessionId,
            'ran_tree_version_id': this.sessionRanTreeVersionId,
            'tree_id': this.options.treeId,
            'tree_version_id': this.treeData.version.public_id,
            'node_id': this.stack[this.stack.length - 1].nodeId,
            'node_option_id': this.stack[this.stack.length - 1].nodeOptionId,
            'gone_back_to': this.stack[this.stack.length - 1].goneBackTo,
        };
        $.ajax({
            context: this,
            dataType: "jsonp",
            url: this.serverURL + '/api/v1/visitorsession/action.jsonp?callback=?',
            data: data,
            method: 'GET',
            success: function(data) {
                this.sessionId = data.session.id;
                if (data.session_ran_tree_version) {
                    this.sessionRanTreeVersionId = data.session_ran_tree_version.id;
                }
            },
        });
    }
  };
  this.selectOption = function(optionId) {
    var node = this.treeData.nodes[this.stack[this.stack.length - 1].nodeId];
    if (!node.title_previous_answers) {
        node.title_previous_answers = node.title;
    }
    var option = node.options[optionId];
    if (this.options.showPreviousAnswers) {
        $(this.targetSelector).find(this.theme.bodyselectorPreviousAnswersWrapper).show();
        $(this.targetSelector).find(this.theme.bodyselectorPreviousAnswersList).append(this.theme.previousAnswerHTML({'node':node, 'nodeOption':option,'stackPos':this.stack.length, 'this':'window.'+this.globalVariableName}));
    }
    this.stack.push({ 'nodeId':option.destination_node.id, 'nodeOptionId':option.id, 'goneBackTo': false });
    this._showNode();
  };
  this.goBackTo = function(stackPos) {
      if (stackPos < 2) {
          this.restart();
      } else {
          while(this.stack.length > stackPos) {
              this.stack.pop();
              $(this.targetSelector).find(this.theme.bodyselectorPreviousAnswerItem).last().remove();
          }
          this.stack[this.stack.length - 1].goneBackTo = true;
          this._showNode();
      }
  };
  var globalRefNum = Math.floor(Math.random() * 999999999) + 1;
  while("QuestionKeyNormalTree"+globalRefNum in window) {
    globalRefNum = Math.floor(Math.random() * 999999999) + 1;
  }
  window["QuestionKeyNormalTree"+globalRefNum] = this;
  this.globalVariableName = "QuestionKeyNormalTree"+globalRefNum;
  $.ajax({
    context: this,
    dataType: "jsonp",
    url: this.serverURL + '/api/v1/tree/' + this.options.treeId + '/data.jsonp?callback=?',
    success: function(data) {
      this.treeData = data;
      if (this.started) {
        this._start();
      }
    },
  });

}
<|endoftext|>


<commit_before>jQuery.entwine("workflow", function($) {
	$(".workflow-field").entwine({
		Loading: null,
		Dialog:  null,
		onmatch: function() {
			var self = this;

			this.setLoading(this.find(".workflow-field-loading"));
			this.setDialog(this.find(".workflow-field-dialog"));

			this.getDialog().data("workflow-field", this).dialog({
				autoOpen: false,
				width:    800,
				height:   600,
				modal:    true
			});

			this.getDialog().on("click", "button", function() {
				$(this).addClass("loading ui-state-disabled");
			});

			this.getDialog().on("submit", "form", function() {
				$(this).ajaxSubmit(function(response) {
					if($(response).is(".workflow-field")) {
						self.getDialog().empty().dialog("close");
						self.replaceWith(response);
					} else {
						self.getDialog().html(response);
					}
				});

				return false;
			});
		},
		showDialog: function(url) {
			var dlg = this.getDialog();

			dlg.empty().dialog("open");
			dlg.parent().addClass("loading");

			$.get(url).done(function(body) {
				dlg.html(body).parent().removeClass("loading");
			});
		},
		loading: function(toggle) {
			this.getLoading().toggle(typeof(toggle) == "undefined" || toggle);
		}
	});

	function helper() {
		return $("
").addClass("ui-state-highlight").appendTo("body");
	}

	$(".workflow-field .workflow-field-actions").entwine({
		onmatch: function() {
			$(".workflow-field .workflow-field-action-disabled").on('click',function() {
				return false;
			});
			this.sortable({
				axis:        "y",
				containment: this,
				placeholder: "ui-state-highlight workflow-placeholder",
				handle:      ".workflow-field-action-drag",
				tolerance:   "pointer",
				update: function() {
					var actions = $(this).find(".workflow-field-action");
					var field   = $(this).closest(".workflow-field");
					var link    = field.data("sort-link");
					var ids     = actions.map(function() { return $(this).data("id"); });

					var data = {
						"id[]":  ids.get(),
						"class": "WorkflowAction",
						"SecurityID": field.data("securityid")
					};

					field.loading();
					$.post(link, data).done(function() { field.loading(false); });
				}
			});
		}
	});

	$(".workflow-field .workflow-field-action-transitions").entwine({
		onmatch: function() {
			this.sortable({
				axis:        "y",
				containment: this,
				handle:      ".workflow-field-action-drag",
				tolerance:   "pointer",
				update: function() {
					var trans = $(this).find("li");
					var field = $(this).closest(".workflow-field");
					var link  = field.data("sort-link");
					var ids   = trans.map(function() { return $(this).data("id"); });

					var data = {
						"id[]":   ids.get(),
						"class":  "WorkflowTransition",
						"parent": $(this).closest(".workflow-field-action").data("id"),
						"SecurityID": field.data("securityid")
					};

					field.loading();
					$.post(link, data).done(function() { field.loading(false); });
				}
			});
		}
	});

	$(".workflow-field .workflow-field-create-class").entwine({
		onmatch: function() {
			this.chosen().addClass("has-chnz");
		},
		onchange: function() {
			this.siblings(".workflow-field-do-create").toggleClass("ui-state-disabled", !this.val());
		}
	});

	$(".workflow-field .workflow-field-do-create").entwine({
		onclick: function() {
			var sel   = this.siblings(".workflow-field-create-class");
			var field = this.closest(".workflow-field");

			if(sel.val()) {
				field.showDialog(sel.val());
			}

			return false;
		}
	});

	$(".workflow-field .workflow-field-open-dialog").entwine({
		onclick: function() {
			this.closest(".workflow-field").showDialog(this.prop("href"));
			return false;
		}
	});

	$(".workflow-field .workflow-field-delete").entwine({
		onclick: function() {
			if(confirm(ss.i18n._t('Workflow.DeleteQuestion'))) {
				var data = {
					"SecurityID" : this.data("securityid")
				};
				$.post(this.prop('href'), data).done(function(body) {
					$(".workflow-field").replaceWith(body);
				});
			}

			return false;
		}
	});

	/*
	 * Simple implementation of the jQuery-UI timepicker widget
	 * @see: http://trentrichardson.com/examples/timepicker/ for more config options
	 *
	 * This will need some more work when it comes to implementing i18n functionality. Fortunately, the library handles these as option-settings quite well.
	 */
	$("#Root_PublishingSchedule").entwine({
		onclick: function() {
			if(typeof $.fn.timepicker() !== 'object' || !$('input.hasTimePicker').length >0) {
				return false;
			}
			var field = $('input.hasTimePicker');
			var defaultTime = function() {
				var date = new Date();
				return date.getHours()+':'+date.getMinutes();
			}
			var pickerOpts = {
				useLocalTimezone: true,
				defaultValue: defaultTime,
				controlType: 'select',
				timeFormat: 'HH:mm'
			};
			field.timepicker(pickerOpts);
			return false;
		},
		onmatch: function(){
			var self = this,
				publishDate = this.find('#PublishOnDate input.date'),
				publishTime = this.find('#PublishOnDate input.time'),
				parent = this.find('#PublishOnDate');

			if(!$('#Form_EditForm_action_publish').attr('disabled')){
				self.checkEmbargo($(publishDate).val(), $(publishTime).val(), parent);

				publishDate.change(function(){
					self.checkEmbargo($(publishDate).val(),$(publishTime).val(), parent);
				});

				publishTime.change(function(){
					self.checkEmbargo($(publishDate).val(), $(publishTime).val(), parent);
				});
			}

			this._super();
		},
		/*
		 * Helper function opens publishing schedule tab when link clicked
		 */
		linkScheduled: function(parent){
			$('#workflow-schedule').click(function(){
				var tabID = parent.closest('.ui-tabs-panel.tab').attr('id');
				$('#tab-'+tabID).trigger('click');
				return false;
			});
		},
		/*
		 * Checks whether an embargo is present.
		 * If an embargo is present, display an altered actions panel,
		 * with a message notifying the user
		 */
		checkEmbargo: function(publishDate, publishTime, parent){

			// Something has changed, remove any existing embargo message
			$('.Actions #embargo-message').remove();

			if(publishDate == '' && publishTime == '' ){
				//No Embargo, remove customizations
				$('#Form_EditForm_action_publish').removeClass('embargo');
				$('#Form_EditForm_action_publish').prev('button').removeClass('ui-corner-right');
			} else {

				var link,
					message;

				$('#Form_EditForm_action_publish').addClass('embargo');
				$('#Form_EditForm_action_publish').prev('button').addClass('ui-corner-right');

				if(publishDate === ''){
					//Has time, not date
					message = ss.i18n.sprintf(
						ss.i18n._t('Workflow.EMBARGOMESSAGETIME'),
						publishTime
					);

				}else if(publishTime === ''){
					//has date no time
					message = ss.i18n.sprintf(
						ss.i18n._t('Workflow.EMBARGOMESSAGEDATE'),
						publishDate
					);
				}else{
					//has date and time
					message = ss.i18n.sprintf(
						ss.i18n._t('Workflow.EMBARGOMESSAGEDATETIME'),
						publishDate,
						publishTime
					);
				}

				message = message.replace('','');

				//Append message with link
				$('.Actions #ActionMenus').after('
' + message + '
');

				//Active link
				this.linkScheduled(parent);
			}

			return false;
		}
	});
});

<commit_msg>Fixes #108. Incorrect auto publish text and link appears in CMS.<commit_after>jQuery.entwine("workflow", function($) {
	$(".workflow-field").entwine({
		Loading: null,
		Dialog:  null,
		onmatch: function() {
			var self = this;

			this.setLoading(this.find(".workflow-field-loading"));
			this.setDialog(this.find(".workflow-field-dialog"));

			this.getDialog().data("workflow-field", this).dialog({
				autoOpen: false,
				width:    800,
				height:   600,
				modal:    true
			});

			this.getDialog().on("click", "button", function() {
				$(this).addClass("loading ui-state-disabled");
			});

			this.getDialog().on("submit", "form", function() {
				$(this).ajaxSubmit(function(response) {
					if($(response).is(".workflow-field")) {
						self.getDialog().empty().dialog("close");
						self.replaceWith(response);
					} else {
						self.getDialog().html(response);
					}
				});

				return false;
			});
		},
		showDialog: function(url) {
			var dlg = this.getDialog();

			dlg.empty().dialog("open");
			dlg.parent().addClass("loading");

			$.get(url).done(function(body) {
				dlg.html(body).parent().removeClass("loading");
			});
		},
		loading: function(toggle) {
			this.getLoading().toggle(typeof(toggle) == "undefined" || toggle);
		}
	});

	function helper() {
		return $("
").addClass("ui-state-highlight").appendTo("body");
	}

	$(".workflow-field .workflow-field-actions").entwine({
		onmatch: function() {
			$(".workflow-field .workflow-field-action-disabled").on('click',function() {
				return false;
			});
			this.sortable({
				axis:        "y",
				containment: this,
				placeholder: "ui-state-highlight workflow-placeholder",
				handle:      ".workflow-field-action-drag",
				tolerance:   "pointer",
				update: function() {
					var actions = $(this).find(".workflow-field-action");
					var field   = $(this).closest(".workflow-field");
					var link    = field.data("sort-link");
					var ids     = actions.map(function() { return $(this).data("id"); });

					var data = {
						"id[]":  ids.get(),
						"class": "WorkflowAction",
						"SecurityID": field.data("securityid")
					};

					field.loading();
					$.post(link, data).done(function() { field.loading(false); });
				}
			});
		}
	});

	$(".workflow-field .workflow-field-action-transitions").entwine({
		onmatch: function() {
			this.sortable({
				axis:        "y",
				containment: this,
				handle:      ".workflow-field-action-drag",
				tolerance:   "pointer",
				update: function() {
					var trans = $(this).find("li");
					var field = $(this).closest(".workflow-field");
					var link  = field.data("sort-link");
					var ids   = trans.map(function() { return $(this).data("id"); });

					var data = {
						"id[]":   ids.get(),
						"class":  "WorkflowTransition",
						"parent": $(this).closest(".workflow-field-action").data("id"),
						"SecurityID": field.data("securityid")
					};

					field.loading();
					$.post(link, data).done(function() { field.loading(false); });
				}
			});
		}
	});

	$(".workflow-field .workflow-field-create-class").entwine({
		onmatch: function() {
			this.chosen().addClass("has-chnz");
		},
		onchange: function() {
			this.siblings(".workflow-field-do-create").toggleClass("ui-state-disabled", !this.val());
		}
	});

	$(".workflow-field .workflow-field-do-create").entwine({
		onclick: function() {
			var sel   = this.siblings(".workflow-field-create-class");
			var field = this.closest(".workflow-field");

			if(sel.val()) {
				field.showDialog(sel.val());
			}

			return false;
		}
	});

	$(".workflow-field .workflow-field-open-dialog").entwine({
		onclick: function() {
			this.closest(".workflow-field").showDialog(this.prop("href"));
			return false;
		}
	});

	$(".workflow-field .workflow-field-delete").entwine({
		onclick: function() {
			if(confirm(ss.i18n._t('Workflow.DeleteQuestion'))) {
				var data = {
					"SecurityID" : this.data("securityid")
				};
				$.post(this.prop('href'), data).done(function(body) {
					$(".workflow-field").replaceWith(body);
				});
			}

			return false;
		}
	});

	/*
	 * Simple implementation of the jQuery-UI timepicker widget
	 * @see: http://trentrichardson.com/examples/timepicker/ for more config options
	 *
	 * This will need some more work when it comes to implementing i18n functionality. Fortunately, the library handles these as option-settings quite well.
	 */
	$("#Root_PublishingSchedule").entwine({
		onclick: function() {
			if(typeof $.fn.timepicker() !== 'object' || !$('input.hasTimePicker').length >0) {
				return false;
			}
			var field = $('input.hasTimePicker');
			var defaultTime = function() {
				var date = new Date();
				return date.getHours()+':'+date.getMinutes();
			}
			var pickerOpts = {
				useLocalTimezone: true,
				defaultValue: defaultTime,
				controlType: 'select',
				timeFormat: 'HH:mm'
			};
			field.timepicker(pickerOpts);
			return false;
		},
		onmatch: function(){
			var self = this,
				publishDate = this.find('#PublishOnDate input.date'),
				publishTime = this.find('#PublishOnDate input.time'),
				parent = this.find('#PublishOnDate');

			if(!$('#Form_EditForm_action_publish').attr('disabled')){
				self.checkEmbargo($(publishDate).val(), $(publishTime).val(), parent);

				publishDate.change(function(){
					self.checkEmbargo($(publishDate).val(),$(publishTime).val(), parent);
				});

				publishTime.change(function(){
					self.checkEmbargo($(publishDate).val(), $(publishTime).val(), parent);
				});
			}

			this._super();
		},
		/*
		 * Helper function opens publishing schedule tab when link clicked
		 */
		linkScheduled: function(parent){
			$('#workflow-schedule').click(function(){
				var tabID = parent.closest('.ui-tabs-panel.tab').attr('id');
				$('#tab-'+tabID).trigger('click');
				return false;
			});
		},
		/*
		 * Checks whether an embargo is present.
		 * If an embargo is present, display an altered actions panel,
		 * with a message notifying the user
		 */
		checkEmbargo: function(publishDate, publishTime, parent){

			// Something has changed, remove any existing embargo message
			$('.Actions #embargo-message').remove();

			/*
			 * Fuzzy checking:
			 * There may not be $(#PublishOnXXX input.date) DOM objects = undefined.
			 * There may be $(#PublishOnXXX input.date) DOM objects = val() method may return zero-length.
			 */
			var noPublishDate = (publishDate === undefined || publishDate.length == 0);
			var noPublishTime = (publishTime === undefined || publishTime.length == 0);

			if(noPublishDate && noPublishTime){
				//No Embargo, remove customizations
				$('#Form_EditForm_action_publish').removeClass('embargo');
				$('#Form_EditForm_action_publish').prev('button').removeClass('ui-corner-right');
			} else {

				var link,
					message;

				$('#Form_EditForm_action_publish').addClass('embargo');
				$('#Form_EditForm_action_publish').prev('button').addClass('ui-corner-right');

				if(publishDate === ''){
					//Has time, not date
					message = ss.i18n.sprintf(
						ss.i18n._t('Workflow.EMBARGOMESSAGETIME'),
						publishTime
					);

				}else if(publishTime === ''){
					//has date no time
					message = ss.i18n.sprintf(
						ss.i18n._t('Workflow.EMBARGOMESSAGEDATE'),
						publishDate
					);
				}else{
					//has date and time
					message = ss.i18n.sprintf(
						ss.i18n._t('Workflow.EMBARGOMESSAGEDATETIME'),
						publishDate,
						publishTime
					);
				}

				message = message.replace('','');

				//Append message with link
				$('.Actions #ActionMenus').after('
' + message + '
');

				//Active link
				this.linkScheduled(parent);
			}

			return false;
		}
	});
});

<|endoftext|>


<commit_before>'use strict';

module.exports = (_, model, state) =>

_.div({class: 'resource-editor resource-editor--publication-editor'},
    _.include(require('./inc/header')),
    _.div({class: 'resource-editor__body', name: 'body'},
        state.name === 'error' ? [
            _.div({class: 'widget widget--message centered warn'},
                state.message
            )

        ] : state.tab === 'overview' ? [
            _.div({class: 'resource-editor__welcome'},
                _.h1('Publications'),
                _.p('Click any item in the panel to edit it.'),
                _.p('Use the context menu (right click or the ', _.span({class: 'fa fa-ellipsis-v'}), ' button) to perform other actions.'),
                _.div({class: 'widget-group'},
                    _.button({class: 'widget widget--button', onclick: _.onClickNew, title: 'Create a new publication'}, 'New publication'),
                    _.button({class: 'widget widget--button', onclick: _.onClickStartTour, title: 'Start a tour of the UI'}, 'Quick tour')
                )
            )

        ] : [
            _.field({label: 'Id'},
                _.text({disabled: model.isLocked, value: model.id, onchange: _.onChangeId})
            ),
            _.field({label: 'Name'},
                _.text({disabled: model.isLocked, value: model.name, onchange: _.onChangeName})
            ),
            _.field({label: 'GET URL', description: 'Where to query this publication from'},
                _.div({class: 'widget-group'},
                    _.label({class: 'widget widget--label'}, state.getUrl),
                    _.button({title: 'Copy URL', class: 'widget widget--button small fa fa-copy', onclick: _.onClickCopyGetUrl}),
                    _.button({title: 'Go to URL', class: 'widget widget--button small fa fa-external-link', onclick: _.onClickGoToGetUrl})
                )
            ),
            _.field({label: 'Processor', description: 'The format to expose content in', labelTag: 'h2'},
                state.processorEditor,
            ),
            _.field({label: 'Deployer', description: 'Where to deploy published content', labelTag: 'h2'},
                state.deployerEditor
            ),
            _.field({label: 'Root contents', description: 'Limit the exposed content'},
                _.popup({autocomplete: true, disabled: model.isLocked, multiple: true, clearable: true, value: model.rootContents, options: state.contentOptions, onchange: _.onChangeRootContents})
            ),
            model.rootContents && model.rootContents.length > 0 ? [
                _.field({label: 'Include root', description: 'Include the root items in this publication'},
                    _.checkbox({disabled: model.isLocked, value: model.includeRoot, onchange: _.onChangeIncludeRoot})
                )
            ] : null,
            _.field({label: 'Allowed schemas', description: 'Limit the the type of exposed content'},
                _.popup({autocomplete: true, disabled: model.isLocked, multiple: true, value: model.allowedSchemas, options: state.schemaOptions, onchange: _.onChangeAllowedSchemas})
            )
        ]
    ),
    _.include(require('./inc/footer'))
)
<commit_msg>Publication editor UI fix<commit_after>'use strict';

module.exports = (_, model, state) =>

_.div({class: 'resource-editor resource-editor--publication-editor'},
    _.include(require('./inc/header')),
    _.div({class: 'resource-editor__body', name: 'body'},
        state.name === 'error' ? [
            _.div({class: 'widget widget--message centered warn'},
                state.message
            )

        ] : state.tab === 'overview' ? [
            _.div({class: 'resource-editor__welcome'},
                _.h1('Publications'),
                _.p('Click any item in the panel to edit it.'),
                _.p('Use the context menu (right click or the ', _.span({class: 'fa fa-ellipsis-v'}), ' button) to perform other actions.'),
                _.div({class: 'widget-group'},
                    _.button({class: 'widget widget--button', onclick: _.onClickNew, title: 'Create a new publication'}, 'New publication'),
                    _.button({class: 'widget widget--button', onclick: _.onClickStartTour, title: 'Start a tour of the UI'}, 'Quick tour')
                )
            )

        ] : [
            _.field({label: 'Id'},
                _.text({disabled: model.isLocked, value: model.id, onchange: _.onChangeId})
            ),
            _.field({label: 'Name'},
                _.text({disabled: model.isLocked, value: model.name, onchange: _.onChangeName})
            ),
            _.field({label: 'GET URL', description: 'Where to query this publication from'},
                _.div({class: 'widget-group'},
                    _.label({class: 'widget widget--label'}, state.getUrl),
                    _.button({title: 'Copy URL', class: 'widget widget--button small fa fa-copy', onclick: _.onClickCopyGetUrl}),
                    _.button({title: 'Go to URL', class: 'widget widget--button small fa fa-external-link', onclick: _.onClickGoToGetUrl})
                )
            ),
            _.field({label: 'Processor', description: 'The format to expose content in', labelTag: 'h2'},
                state.processorEditor,
            ),
            _.field({label: 'Deployer', description: 'Where to deploy published content', labelTag: 'h2'},
                state.deployerEditor
            ),
            _.field({label: 'Limits', labelTag: 'h2'},
                _.field({label: 'Root contents', description: 'Limit the exposed content'},
                    _.popup({autocomplete: true, disabled: model.isLocked, multiple: true, clearable: true, value: model.rootContents, options: state.contentOptions, onchange: _.onChangeRootContents})
                ),
                model.rootContents && model.rootContents.length > 0 ? [
                    _.field({label: 'Include root', description: 'Include the root items in this publication'},
                        _.checkbox({disabled: model.isLocked, value: model.includeRoot, onchange: _.onChangeIncludeRoot})
                    )
                ] : null,
                _.field({label: 'Allowed schemas', description: 'Limit the the type of exposed content'},
                    _.popup({autocomplete: true, disabled: model.isLocked, multiple: true, value: model.allowedSchemas, options: state.schemaOptions, onchange: _.onChangeAllowedSchemas})
                )
            )
        ]
    ),
    _.include(require('./inc/footer'))
)
<|endoftext|>


<commit_before>/**
 * @license
 * Licensed Materials - Property of IBM
 * 5725-I43 (C) Copyright IBM Corp. 2006, 2013. All Rights Reserved.
 * US Government Users Restricted Rights - Use, duplication or
 * disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
 */

/*global process, module*/

// This module returns an "environment" object which encapsulates the request options needed to communicate with Analytics Repository.
function _setupBlueMixMode(emitter, settings, logger, utils, https, url) {

  'use strict';

  logger.logEnter('setupBlueMixMode');

  var runningInPublicEnv = utils.isRunningInPublicEnv ? utils.isRunningInPublicEnv(settings) : false;

  // Do some validation of the environment.
  if(runningInPublicEnv) {
    logger.log('SDK is running in user public environment.');

    if(!settings) {
      emitter.emit('error', 'SDK authorization settings are required when running in user org.');
      return null;
    } else if(typeof settings.AZFilterAppId !== 'string' || settings.AZFilterAppId.length < 1) {
      emitter.emit('error', 'Missing required setting: AZFilterAppId');
      return null;
    } else if(typeof settings.AZServerUrl !== 'string' || settings.AZServerUrl.length < 1) {
      emitter.emit('error', 'Missing required setting: AZServerUrl');
      return null;
    } else if(typeof settings.AZTokenProvider !== 'function') {
      emitter.emit('error', 'Missing required setting: AZTokenProvider');
      return null;
    }

    var azUrl = url.parse(settings.AZServerUrl);
    var azHostName = azUrl.hostname;

    if(!azHostName) {
      emitter.emit('error', 'AZServerUrl is not set to a valid URL: ' + settings.AZServerUrl);
      return null;
    }

    var domain,

    dotIndex = azHostName.indexOf('.');

    if (dotIndex > 0) {
      domain = azHostName.substring(dotIndex+1);
    }

    if(typeof domain !== 'string' || domain.length < 1) {
      emitter.emit('error', 'Unable to extract domain from AZServerUrl: ' + settings.AZServerUrl);
      return null;
    }

    // Host of Analytics Proxy using domain from AZ server.
    var proxyUrl = 'https://imfmobileanalytics.' + domain;

    if (process.env.ANALYTICS_PROXY_URL_OVERRIDE) {
      proxyUrl = process.env.ANALYTICS_PROXY_URL_OVERRIDE;
    }

    url = url.parse(proxyUrl);
    logger.log('Using analytics proxy hostname: ' + url.hostname);

    // Get an initial access token
    var proxyAccessToken;
    settings.AZTokenProvider().then(function(token) {
        proxyAccessToken = token;
        logger.log('Initial proxy access token: ' + proxyAccessToken);
	}, function(err) {
		logger.log(err);
		emitter.emit('error', 'Unable to get initial access token from AZTokenProvider');
                return null;
	});

  } else {
    logger.log('SDK is running in IMF organization.');

    if (!process.env.VCAP_SERVICES || process.env.VCAP_SERVICES === 'null') {
      emitter.emit('error', 'VCAP_SERVICES is not defined.');
      return null;
    }

    var esCredentials, // Used when SDK is running in elasticsearch mode.
    esIndexNamePathPrefix, // prefixed to all elasticsearch requests, b/c they must take place in the context of an index.
    esIndexName, // name of the elasticsearch index extracted from the credentials url.
    vcapServices = JSON.parse(process.env.VCAP_SERVICES);

    // Cycle through all bound services and look for elasticsearch.
    for (var key in vcapServices) {
      if (vcapServices.hasOwnProperty(key)) {

        var fullInfo;

        if (key.indexOf('AESearch') === 0) {

          // If we are bound to the analytics elasticsearch service,
          // the SDK will be running in elasticsearch mode.
          logger.log('Bound to Analytics Elasticsearch service.  SDK will use Elasticsearch.');

          fullInfo = vcapServices[key][0];

          if (fullInfo.credentials) {
            esCredentials = fullInfo.credentials;
          }
        }
      }
    }

    if (esCredentials) {

      url = url.parse(esCredentials.url);
      esIndexNamePathPrefix = url.path;
      esIndexName = url.path.substring(url.path.lastIndexOf('/') + 1);

    } else {
      // Not in elasticsearch mode, so we are required to have elasticsearch credentials.
      emitter.emit('error', 'No AESearch service credentials were found in VCAP_SERVICES: ' + process.env.VCAP_SERVICES);
      return null;
    }
  }

  logger.logExit('setupBlueMixMode');

  // Create the environment object.
  return {

    get: https.get,

    request: https.request,

    loadEventTypes: function loadEventTypes(callback, failureCallback) {

      // load event types directly from elasticsearch.
      var hostForEventTypesRequest = url.hostname;

      if (process.env.TESTONLY_ES_HOSTNAME_OVERRIDE) {
        // Only used by test code to simulate failures when loading the event types.
        hostForEventTypesRequest = process.env.TESTONLY_ES_HOSTNAME_OVERRIDE;
        logger.log('loadEventTypes overriding mappings url.  host override: ' + hostForEventTypesRequest);
      }

      var options;

      if(runningInPublicEnv) {
        options = {
            path: '/imfmobileanalytics/proxy/v1/eventtypes',
            hostname: hostForEventTypesRequest,
            port: url.port,
            headers: {
              'Authorization': proxyAccessToken
            }
          };
      } else {
        options = {
            path: esIndexNamePathPrefix + '/_mapping',
            hostname: hostForEventTypesRequest,
            port: url.port,
            auth: esCredentials.userid + ':' + esCredentials.password
          };
      }

      logger.log('loadEventTypes options: ' + JSON.stringify(options));

      var respCallback = function (json) {

        var eventTypes;

        try {
          eventTypes = JSON.parse(json);
        } catch (e) {
          emitter.emit('error', 'Error parsing GET event types response: ' + e);
          return;
        }

        if(!runningInPublicEnv) {
          // Extract mappings from ES respond that contains attributes for the <index_name>.mappings
          var mappingsForIndex = eventTypes[esIndexName];

          if (mappingsForIndex && mappingsForIndex.mappings) {
            eventTypes = mappingsForIndex.mappings;
          } else {
            emitter.emit('error', 'GET event types response does not contain mappings for index: ' + esIndexName);
            return;
          }
        } else {
          logger.log('loadEventTypes: Using eventTypes returned from proxy.');
        }

        callback(eventTypes);
      };

      var respConsumerCallback = utils.responseConsumer(logger, 'getting event types', 200, failureCallback ? failureCallback : emitter, respCallback);

      var request = https.get(options, respConsumerCallback);

      request.on('error', function (e) {
        emitter.emit('error', 'Error getting event types: ' + e);
        if (failureCallback) {
          failureCallback();
        }
      });
    },

    elasticsearchOptions: function elasticsearchOptions(method, path) {

      var options;

      if(runningInPublicEnv) {
        options = {
            method: method,
            path: path,
            hostname: url.hostname,
            port: url.port,
            headers: {
              'Authorization': proxyAccessToken
            }
          };
      } else {
        options = {
            method: method,
            path: esIndexNamePathPrefix + path,
            hostname: url.hostname,
            port: url.port,
            auth: esCredentials.userid + ':' + esCredentials.password
          };
      }

      logger.log('elasticsearchOptions: ' + JSON.stringify(options));

      return options;
    },

    // After invoking this function, one must invoke elasticsearchOptions again in order for new access token to be used.
    refreshProxyAccessToken: function refreshProxyAccessToken() {
        settings.AZTokenProvider().then(function(token) {
            proxyAccessToken = token;
            logger.log('Refreshed proxy access token: ' + proxyAccessToken);
        }, function(err) {
            logger.log(err);
            emitter.emit('error', 'Unable to refresh access token from AZTokenProvider');
            return null;
       });
    }
  };
}

module.exports = {
  setupBlueMixMode: _setupBlueMixMode,
};
<commit_msg>filtering out empty headers<commit_after>/**
 * @license
 * Licensed Materials - Property of IBM
 * 5725-I43 (C) Copyright IBM Corp. 2006, 2013. All Rights Reserved.
 * US Government Users Restricted Rights - Use, duplication or
 * disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
 */

/*global process, module*/

// This module returns an "environment" object which encapsulates the request options needed to communicate with Analytics Repository.
function _setupBlueMixMode(emitter, settings, logger, utils, https, url) {

  'use strict';

  logger.logEnter('setupBlueMixMode');

  var runningInPublicEnv = utils.isRunningInPublicEnv ? utils.isRunningInPublicEnv(settings) : false;

  // Do some validation of the environment.
  if(runningInPublicEnv) {
    logger.log('SDK is running in user public environment.');

    if(!settings) {
      emitter.emit('error', 'SDK authorization settings are required when running in user org.');
      return null;
    } else if(typeof settings.AZFilterAppId !== 'string' || settings.AZFilterAppId.length < 1) {
      emitter.emit('error', 'Missing required setting: AZFilterAppId');
      return null;
    } else if(typeof settings.AZServerUrl !== 'string' || settings.AZServerUrl.length < 1) {
      emitter.emit('error', 'Missing required setting: AZServerUrl');
      return null;
    } else if(typeof settings.AZTokenProvider !== 'function') {
      emitter.emit('error', 'Missing required setting: AZTokenProvider');
      return null;
    }

    var azUrl = url.parse(settings.AZServerUrl);
    var azHostName = azUrl.hostname;

    if(!azHostName) {
      emitter.emit('error', 'AZServerUrl is not set to a valid URL: ' + settings.AZServerUrl);
      return null;
    }

    var domain,

    dotIndex = azHostName.indexOf('.');

    if (dotIndex > 0) {
      domain = azHostName.substring(dotIndex+1);
    }

    if(typeof domain !== 'string' || domain.length < 1) {
      emitter.emit('error', 'Unable to extract domain from AZServerUrl: ' + settings.AZServerUrl);
      return null;
    }

    // Host of Analytics Proxy using domain from AZ server.
    var proxyUrl = 'https://imfmobileanalytics.' + domain;

    if (process.env.ANALYTICS_PROXY_URL_OVERRIDE) {
      proxyUrl = process.env.ANALYTICS_PROXY_URL_OVERRIDE;
    }

    url = url.parse(proxyUrl);
    logger.log('Using analytics proxy hostname: ' + url.hostname);

    // Get an initial access token
    var proxyAccessToken;
    settings.AZTokenProvider().then(function(token) {
        proxyAccessToken = token;
        logger.log('Initial proxy access token: ' + proxyAccessToken);
	}, function(err) {
		logger.log(err);
		emitter.emit('error', 'Unable to get initial access token from AZTokenProvider');
                return null;
	});

  } else {
    logger.log('SDK is running in IMF organization.');

    if (!process.env.VCAP_SERVICES || process.env.VCAP_SERVICES === 'null') {
      emitter.emit('error', 'VCAP_SERVICES is not defined.');
      return null;
    }

    var esCredentials, // Used when SDK is running in elasticsearch mode.
    esIndexNamePathPrefix, // prefixed to all elasticsearch requests, b/c they must take place in the context of an index.
    esIndexName, // name of the elasticsearch index extracted from the credentials url.
    vcapServices = JSON.parse(process.env.VCAP_SERVICES);

    // Cycle through all bound services and look for elasticsearch.
    for (var key in vcapServices) {
      if (vcapServices.hasOwnProperty(key)) {

        var fullInfo;

        if (key.indexOf('AESearch') === 0) {

          // If we are bound to the analytics elasticsearch service,
          // the SDK will be running in elasticsearch mode.
          logger.log('Bound to Analytics Elasticsearch service.  SDK will use Elasticsearch.');

          fullInfo = vcapServices[key][0];

          if (fullInfo.credentials) {
            esCredentials = fullInfo.credentials;
          }
        }
      }
    }

    if (esCredentials) {

      url = url.parse(esCredentials.url);
      esIndexNamePathPrefix = url.path;
      esIndexName = url.path.substring(url.path.lastIndexOf('/') + 1);

    } else {
      // Not in elasticsearch mode, so we are required to have elasticsearch credentials.
      emitter.emit('error', 'No AESearch service credentials were found in VCAP_SERVICES: ' + process.env.VCAP_SERVICES);
      return null;
    }
  }

  logger.logExit('setupBlueMixMode');

  // Create the environment object.
  return {

    get: https.get,

    request: https.request,

    loadEventTypes: function loadEventTypes(callback, failureCallback) {

      // load event types directly from elasticsearch.
      var hostForEventTypesRequest = url.hostname;

      if (process.env.TESTONLY_ES_HOSTNAME_OVERRIDE) {
        // Only used by test code to simulate failures when loading the event types.
        hostForEventTypesRequest = process.env.TESTONLY_ES_HOSTNAME_OVERRIDE;
        logger.log('loadEventTypes overriding mappings url.  host override: ' + hostForEventTypesRequest);
      }

      var options;

      if(runningInPublicEnv) {
        options = {
            path: '/imfmobileanalytics/proxy/v1/eventtypes',
            hostname: hostForEventTypesRequest,
            port: url.port,
            headers: {
              'Authorization': proxyAccessToken
            }
          };
      } else {
        options = {
            path: esIndexNamePathPrefix + '/_mapping',
            hostname: hostForEventTypesRequest,
            port: url.port,
            auth: esCredentials.userid + ':' + esCredentials.password
          };
      }

      logger.log('loadEventTypes options: ' + JSON.stringify(options));

      var respCallback = function (json) {

        var eventTypes;

        try {
          eventTypes = JSON.parse(json);
        } catch (e) {
          emitter.emit('error', 'Error parsing GET event types response: ' + e);
          return;
        }

        if(!runningInPublicEnv) {
          // Extract mappings from ES respond that contains attributes for the <index_name>.mappings
          var mappingsForIndex = eventTypes[esIndexName];

          if (mappingsForIndex && mappingsForIndex.mappings) {
            eventTypes = mappingsForIndex.mappings;
          } else {
            emitter.emit('error', 'GET event types response does not contain mappings for index: ' + esIndexName);
            return;
          }
        } else {
          logger.log('loadEventTypes: Using eventTypes returned from proxy.');
        }

        callback(eventTypes);
      };

      // Update undefined values in headers to empty strings
      for (var key in options.headers){
        if (!options.headers[key])
          //options.headers[key]="";
        delete options.headers[key];
      }

      var respConsumerCallback = utils.responseConsumer(logger, 'getting event types', 200, failureCallback ? failureCallback : emitter, respCallback);

      var request = https.get(options, respConsumerCallback);

      request.on('error', function (e) {
        emitter.emit('error', 'Error getting event types: ' + e);
        if (failureCallback) {
          failureCallback();
        }
      });
    },

    elasticsearchOptions: function elasticsearchOptions(method, path) {

      var options;

      if(runningInPublicEnv) {
        options = {
            method: method,
            path: path,
            hostname: url.hostname,
            port: url.port,
            headers: {
              'Authorization': proxyAccessToken
            }
          };
      } else {
        options = {
            method: method,
            path: esIndexNamePathPrefix + path,
            hostname: url.hostname,
            port: url.port,
            auth: esCredentials.userid + ':' + esCredentials.password
          };
      }

      logger.log('elasticsearchOptions: ' + JSON.stringify(options));

      return options;
    },

    // After invoking this function, one must invoke elasticsearchOptions again in order for new access token to be used.
    refreshProxyAccessToken: function refreshProxyAccessToken() {
        settings.AZTokenProvider().then(function(token) {
            proxyAccessToken = token;
            logger.log('Refreshed proxy access token: ' + proxyAccessToken);
        }, function(err) {
            logger.log(err);
            emitter.emit('error', 'Unable to refresh access token from AZTokenProvider');
            return null;
       });
    }
  };
}

module.exports = {
  setupBlueMixMode: _setupBlueMixMode,
};
<|endoftext|>


<commit_before><commit_msg>test stack methods<commit_after>// Stacks

/*
Stack is an ordered collection of itmes that follows LIFO (last in first out)
principle.  The addition of new items andthe removal of existing items
occurs at the same end.

The end of the stack is known as the top and the opposite is known as the base

Newest elements are near the top and the oldest elements are near the base

Stacks used by compilers in programming languages and by computer memory
to store variables and method calls
*/

/* IF we were to build a stack class in javascript, what properties and
methods would we need to include?

1) We would need an array to store the elements of the stack
2) Push to add new items to the top of the stack
3) pop to remove the top item from the stack (and to return removed element)
4) peek to return the top element from the stack (w/o modifying it)
5) isEmpty which will return true if stack is empty and false if not
6) clear which will remove all the elements in the stack
7) size which will return how many elements the stack contains
*/

function Stack(){

  var items = [];

  this.push = function(element){
    items.push(element);
  };

  this.pop = function(){
    return items.pop();
  };

  this.peek = function(){
    return items[items.length-1];
  };

  this.isEmpty = function(){
    return items.length === 0;
  };

  this.size = function(){
    return items.length;
  };

  this.clear = function(){
    items = [];
  };

  this.print = function(){
    console.log(items.toString());
  };
}

// using the stack class

var stack = new Stack();

console.log(stack.isEmpty());

stack.push(5);
stack.push(8);

console.log(stack.peek());
stack.print();

stack.push(11);

console.log(stack.size());
console.log(stack.isEmpty());

stack.push(15);

stack.pop();
stack.pop();

stack.print();
<|endoftext|>