<commit_before>/*
 * jQuery UI Spinner @VERSION
 *
 * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Spinner
 *
 * Depends:
 *  jquery.ui.core.js
 *  jquery.ui.widget.js
 */
(function($) {

$.widget('ui.spinner', {
	defaultElement: "<input>",
	options: {
		incremental: true,
		max: null,
		min: null,
		numberformat: null,
		page: 10,
		step: null,
		value: null
	},

	_create: function() {
		this._draw();
		this._markupOptions();
		this._mousewheel();
		this._aria();
	},

	_markupOptions: function() {
		var _this = this;
		$.each({
			min: -Number.MAX_VALUE,
			max: Number.MAX_VALUE,
			step: 1
		}, function(attr, defaultValue) {
			if (_this.options[attr] === null) {
				var value = _this.element.attr(attr);
				_this.options[attr] = typeof value == "string" && value.length > 0 ? _this._parse(value) : defaultValue;
			}
		});
		this.value(this.options.value !== null ? this.options.value : this.element.val() || 0);
	},

	_draw: function() {
		var self = this,
			options = self.options;

		var uiSpinner = this.uiSpinner = self.element
			.addClass('ui-spinner-input')
			.attr('autocomplete', 'off')
			.wrap(self._uiSpinnerHtml())
			.parent()
				// add buttons
				.append(self._buttonHtml())
				// add behaviours
				.hover(function() {
					if (!options.disabled) {
						$(this).addClass('ui-state-hover');
					}
					self.hovered = true;
				}, function() {
					$(this).removeClass('ui-state-hover');
					self.hovered = false;
				});

		this.element
			.attr( "role", "spinbutton" )
			.bind('keydown.spinner', function(event) {
				if (self.options.disabled) {
					return;
				}
				if (self._start(event)) {
					return self._keydown(event);
				}
				return true;
			})
			.bind('keyup.spinner', function(event) {
				if (self.options.disabled) {
					return;
				}
				if (self.spinning) {
					self._stop(event);
					self._change(event);
				}
			})
			.bind('focus.spinner', function() {
				uiSpinner.addClass('ui-state-active');
				self.focused = true;
			})
			.bind('blur.spinner', function(event) {
				self.value(self.element.val());
				if (!self.hovered) {
					uiSpinner.removeClass('ui-state-active');
				}
				self.focused = false;
			});

		// button bindings
		this.buttons = uiSpinner.find('.ui-spinner-button')
			.attr("tabIndex", -1)
			.button()
			.removeClass("ui-corner-all")
			.bind('mousedown', function(event) {
				if (self.options.disabled) {
					return;
				}
				if (self._start(event) === false) {
					return false;
				}
				self._repeat(null, $(this).hasClass('ui-spinner-up') ? 1 : -1, event);
			})
			.bind('mouseup', function(event) {
				if (self.options.disabled) {
					return;
				}
				if (self.spinning) {
					self._stop(event);
					self._change(event);
				}
			})
			.bind("mouseenter", function() {
				if (self.options.disabled) {
					return;
				}
				// button will add ui-state-active if mouse was down while mouseleave and kept down
				if ($(this).hasClass("ui-state-active")) {
					if (self._start(event) === false) {
						return false;
					}
					self._repeat(null, $(this).hasClass('ui-spinner-up') ? 1 : -1, event);
				}
			})
			.bind("mouseleave", function() {
				if (self.spinning) {
					self._stop(event);
					self._change(event);
				}
			});

		// disable spinner if element was already disabled
		if (options.disabled) {
			this.disable();
		}
	},

	_keydown: function(event) {
		var o = this.options,
			KEYS = $.ui.keyCode;

		switch (event.keyCode) {
		case KEYS.UP:
			this._repeat(null, 1, event);
			return false;
		case KEYS.DOWN:
			this._repeat(null, -1, event);
			return false;
		case KEYS.PAGE_UP:
			this._repeat(null, this.options.page, event);
			return false;
		case KEYS.PAGE_DOWN:
			this._repeat(null, -this.options.page, event);
			return false;

		case KEYS.ENTER:
			this.value(this.element.val());
		}

		return true;
	},

	_mousewheel: function() {
		// need the delta normalization that mousewheel plugin provides
		if (!$.fn.mousewheel) {
			return;
		}
		var self = this;
		this.element.bind("mousewheel.spinner", function(event, delta) {
			if (self.options.disabled) {
				return;
			}
			if (!self.spinning && !self._start(event)) {
				return false;
			}
			self._spin((delta > 0 ? 1 : -1) * self.options.step, event);
			clearTimeout(self.timeout);
			self.timeout = setTimeout(function() {
				if (self.spinning) {
					self._stop(event);
					self._change(event);
				}
			}, 100);
			event.preventDefault();
		});
	},

	_uiSpinnerHtml: function() {
		return '';
	},

	_buttonHtml: function() {
		return '▲' +
				'▼';
	},

	_start: function(event) {
		if (!this.spinning && this._trigger('start', event) !== false) {
			if (!this.counter) {
				this.counter = 1;
			}
			this.spinning = true;
			return true;
		}
		return false;
	},

	_repeat: function(i, steps, event) {
		var self = this;
		i = i || 500;

		clearTimeout(this.timer);
		this.timer = setTimeout(function() {
			self._repeat(40, steps, event);
		}, i);

		self._spin(steps * self.options.step, event);
	},

	_spin: function(step, event) {
		if (!this.counter) {
			this.counter = 1;
		}

		// TODO refactor, maybe figure out some non-linear math
		var newVal = this.value() + step * (this.options.incremental &&
			this.counter > 20
				? this.counter > 100
					? this.counter > 200
						? 100
						: 10
					: 2
				: 1);

		if (this._trigger('spin', event, { value: newVal }) !== false) {
			this.value(newVal);
			this.counter++;
		}
	},

	_stop: function(event) {
		this.counter = 0;
		if (this.timer) {
			window.clearTimeout(this.timer);
		}
		this.element[0].focus();
		this.spinning = false;
		this._trigger('stop', event);
	},

	_change: function(event) {
		this._trigger('change', event);
	},

	_setOption: function(key, value) {
		if (key == 'value') {
			value = this._parse(value);
			if (value < this.options.min) {
				value = this.options.min;
			}
			if (value > this.options.max) {
				value = this.options.max;
			}
		}
		if (key == 'disabled') {
			if (value) {
				this.element.attr("disabled", true);
				this.buttons.button("disable");
			} else {
				this.element.removeAttr("disabled");
				this.buttons.button("enable");
			}
		}
		this._super( "_setOption", key, value );
	},

	_setOptions: function( options ) {
		this._super( "_setOptions", options );
		if ( "value" in options ) {
			this._format( this.options.value );
		}
		this._aria();
	},

	_aria: function() {
		this.element
			.attr('aria-valuemin', this.options.min)
			.attr('aria-valuemax', this.options.max)
			.attr('aria-valuenow', this.options.value);
	},

	_parse: function(val) {
		var input = val;
		if (typeof val == 'string') {
			val = $.global && this.options.numberformat ? $.global.parseFloat(val) : +val;
		}
		return isNaN(val) ? null : val;
	},

	_format: function(num) {
		this.element.val( $.global && this.options.numberformat ? $.global.format(num, this.options.numberformat) : num );
	},

	destroy: function() {
		this.element
			.removeClass('ui-spinner-input')
			.removeAttr('disabled')
			.removeAttr('autocomplete')
			.removeAttr('role')
			.removeAttr('aria-valuemin')
			.removeAttr('aria-valuemax')
			.removeAttr('aria-valuenow');
		this._super( "destroy" );
		this.uiSpinner.replaceWith(this.element);
	},

	stepUp: function(steps) {
		this._spin((steps || 1) * this.options.step);
	},

	stepDown: function(steps) {
		this._spin((steps || 1) * -this.options.step);
	},

	pageUp: function(pages) {
		this.stepUp((pages || 1) * this.options.page);
	},

	pageDown: function(pages) {
		this.stepDown((pages || 1) * this.options.page);
	},

	value: function(newVal) {
		if (!arguments.length) {
			return this._parse(this.element.val());
		}
		this.option('value', newVal);
	},

	widget: function() {
		return this.uiSpinner;
	}
});

$.ui.spinner.version = "@VERSION";

})(jQuery);
<commit_msg>Spinner: Use jQuery's focus() method instead of DOM method to set focus to input. Fixes testsuite in IE6.<commit_after>/*
 * jQuery UI Spinner @VERSION
 *
 * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Spinner
 *
 * Depends:
 *  jquery.ui.core.js
 *  jquery.ui.widget.js
 */
(function($) {

$.widget('ui.spinner', {
	defaultElement: "<input>",
	options: {
		incremental: true,
		max: null,
		min: null,
		numberformat: null,
		page: 10,
		step: null,
		value: null
	},

	_create: function() {
		this._draw();
		this._markupOptions();
		this._mousewheel();
		this._aria();
	},

	_markupOptions: function() {
		var _this = this;
		$.each({
			min: -Number.MAX_VALUE,
			max: Number.MAX_VALUE,
			step: 1
		}, function(attr, defaultValue) {
			if (_this.options[attr] === null) {
				var value = _this.element.attr(attr);
				_this.options[attr] = typeof value == "string" && value.length > 0 ? _this._parse(value) : defaultValue;
			}
		});
		this.value(this.options.value !== null ? this.options.value : this.element.val() || 0);
	},

	_draw: function() {
		var self = this,
			options = self.options;

		var uiSpinner = this.uiSpinner = self.element
			.addClass('ui-spinner-input')
			.attr('autocomplete', 'off')
			.wrap(self._uiSpinnerHtml())
			.parent()
				// add buttons
				.append(self._buttonHtml())
				// add behaviours
				.hover(function() {
					if (!options.disabled) {
						$(this).addClass('ui-state-hover');
					}
					self.hovered = true;
				}, function() {
					$(this).removeClass('ui-state-hover');
					self.hovered = false;
				});

		this.element
			.attr( "role", "spinbutton" )
			.bind('keydown.spinner', function(event) {
				if (self.options.disabled) {
					return;
				}
				if (self._start(event)) {
					return self._keydown(event);
				}
				return true;
			})
			.bind('keyup.spinner', function(event) {
				if (self.options.disabled) {
					return;
				}
				if (self.spinning) {
					self._stop(event);
					self._change(event);
				}
			})
			.bind('focus.spinner', function() {
				uiSpinner.addClass('ui-state-active');
				self.focused = true;
			})
			.bind('blur.spinner', function(event) {
				self.value(self.element.val());
				if (!self.hovered) {
					uiSpinner.removeClass('ui-state-active');
				}
				self.focused = false;
			});

		// button bindings
		this.buttons = uiSpinner.find('.ui-spinner-button')
			.attr("tabIndex", -1)
			.button()
			.removeClass("ui-corner-all")
			.bind('mousedown', function(event) {
				if (self.options.disabled) {
					return;
				}
				if (self._start(event) === false) {
					return false;
				}
				self._repeat(null, $(this).hasClass('ui-spinner-up') ? 1 : -1, event);
			})
			.bind('mouseup', function(event) {
				if (self.options.disabled) {
					return;
				}
				if (self.spinning) {
					self._stop(event);
					self._change(event);
				}
			})
			.bind("mouseenter", function() {
				if (self.options.disabled) {
					return;
				}
				// button will add ui-state-active if mouse was down while mouseleave and kept down
				if ($(this).hasClass("ui-state-active")) {
					if (self._start(event) === false) {
						return false;
					}
					self._repeat(null, $(this).hasClass('ui-spinner-up') ? 1 : -1, event);
				}
			})
			.bind("mouseleave", function() {
				if (self.spinning) {
					self._stop(event);
					self._change(event);
				}
			});

		// disable spinner if element was already disabled
		if (options.disabled) {
			this.disable();
		}
	},

	_keydown: function(event) {
		var o = this.options,
			KEYS = $.ui.keyCode;

		switch (event.keyCode) {
		case KEYS.UP:
			this._repeat(null, 1, event);
			return false;
		case KEYS.DOWN:
			this._repeat(null, -1, event);
			return false;
		case KEYS.PAGE_UP:
			this._repeat(null, this.options.page, event);
			return false;
		case KEYS.PAGE_DOWN:
			this._repeat(null, -this.options.page, event);
			return false;

		case KEYS.ENTER:
			this.value(this.element.val());
		}

		return true;
	},

	_mousewheel: function() {
		// need the delta normalization that mousewheel plugin provides
		if (!$.fn.mousewheel) {
			return;
		}
		var self = this;
		this.element.bind("mousewheel.spinner", function(event, delta) {
			if (self.options.disabled) {
				return;
			}
			if (!self.spinning && !self._start(event)) {
				return false;
			}
			self._spin((delta > 0 ? 1 : -1) * self.options.step, event);
			clearTimeout(self.timeout);
			self.timeout = setTimeout(function() {
				if (self.spinning) {
					self._stop(event);
					self._change(event);
				}
			}, 100);
			event.preventDefault();
		});
	},

	_uiSpinnerHtml: function() {
		return '';
	},

	_buttonHtml: function() {
		return '▲' +
				'▼';
	},

	_start: function(event) {
		if (!this.spinning && this._trigger('start', event) !== false) {
			if (!this.counter) {
				this.counter = 1;
			}
			this.spinning = true;
			return true;
		}
		return false;
	},

	_repeat: function(i, steps, event) {
		var self = this;
		i = i || 500;

		clearTimeout(this.timer);
		this.timer = setTimeout(function() {
			self._repeat(40, steps, event);
		}, i);

		self._spin(steps * self.options.step, event);
	},

	_spin: function(step, event) {
		if (!this.counter) {
			this.counter = 1;
		}

		// TODO refactor, maybe figure out some non-linear math
		var newVal = this.value() + step * (this.options.incremental &&
			this.counter > 20
				? this.counter > 100
					? this.counter > 200
						? 100
						: 10
					: 2
				: 1);

		if (this._trigger('spin', event, { value: newVal }) !== false) {
			this.value(newVal);
			this.counter++;
		}
	},

	_stop: function(event) {
		this.counter = 0;
		if (this.timer) {
			window.clearTimeout(this.timer);
		}
		this.element.focus();
		this.spinning = false;
		this._trigger('stop', event);
	},

	_change: function(event) {
		this._trigger('change', event);
	},

	_setOption: function(key, value) {
		if (key == 'value') {
			value = this._parse(value);
			if (value < this.options.min) {
				value = this.options.min;
			}
			if (value > this.options.max) {
				value = this.options.max;
			}
		}
		if (key == 'disabled') {
			if (value) {
				this.element.attr("disabled", true);
				this.buttons.button("disable");
			} else {
				this.element.removeAttr("disabled");
				this.buttons.button("enable");
			}
		}
		this._super( "_setOption", key, value );
	},

	_setOptions: function( options ) {
		this._super( "_setOptions", options );
		if ( "value" in options ) {
			this._format( this.options.value );
		}
		this._aria();
	},

	_aria: function() {
		this.element
			.attr('aria-valuemin', this.options.min)
			.attr('aria-valuemax', this.options.max)
			.attr('aria-valuenow', this.options.value);
	},

	_parse: function(val) {
		var input = val;
		if (typeof val == 'string') {
			val = $.global && this.options.numberformat ? $.global.parseFloat(val) : +val;
		}
		return isNaN(val) ? null : val;
	},

	_format: function(num) {
		this.element.val( $.global && this.options.numberformat ? $.global.format(num, this.options.numberformat) : num );
	},

	destroy: function() {
		this.element
			.removeClass('ui-spinner-input')
			.removeAttr('disabled')
			.removeAttr('autocomplete')
			.removeAttr('role')
			.removeAttr('aria-valuemin')
			.removeAttr('aria-valuemax')
			.removeAttr('aria-valuenow');
		this._super( "destroy" );
		this.uiSpinner.replaceWith(this.element);
	},

	stepUp: function(steps) {
		this._spin((steps || 1) * this.options.step);
	},

	stepDown: function(steps) {
		this._spin((steps || 1) * -this.options.step);
	},

	pageUp: function(pages) {
		this.stepUp((pages || 1) * this.options.page);
	},

	pageDown: function(pages) {
		this.stepDown((pages || 1) * this.options.page);
	},

	value: function(newVal) {
		if (!arguments.length) {
			return this._parse(this.element.val());
		}
		this.option('value', newVal);
	},

	widget: function() {
		return this.uiSpinner;
	}
});

$.ui.spinner.version = "@VERSION";

})(jQuery);
<|endoftext|>


<commit_before>goog.provide('ol.TilePriorityFunction');
goog.provide('ol.TileQueue');

goog.require('goog.events');
goog.require('goog.events.EventType');
goog.require('ol.Coordinate');
goog.require('ol.TileState');
goog.require('ol.structs.PriorityQueue');

/**
 * @typedef {function(ol.Tile, string, ol.Coordinate, number): number}
 */
ol.TilePriorityFunction;

/**
 * @constructor
 * @extends {ol.structs.PriorityQueue.<Array>}
 * @param {ol.TilePriorityFunction} tilePriorityFunction
 *     Tile priority function.
 * @param {function(): ?} tileChangeCallback
 *     Function called on each tile change event.
 * @struct
 */
ol.TileQueue = function(tilePriorityFunction, tileChangeCallback) {

  goog.base(
      this,
      /**
       * @param {Array} element Element.
       * @return {number} Priority.
       */
      function(element) {
        return tilePriorityFunction.apply(null, element);
      },
      /**
       * @param {Array} element Element.
       * @return {string} Key.
       */
      function(element) {
        return /** @type {ol.Tile} */ (element[0]).getKey();
      });

  /**
   * @private
   * @type {function(): ?}
   */
  this.tileChangeCallback_ = tileChangeCallback;

  /**
   * @private
   * @type {number}
   */
  this.tilesLoading_ = 0;

};
goog.inherits(ol.TileQueue, ol.structs.PriorityQueue);

/**
 * @return {number} Number of tiles loading.
 */
ol.TileQueue.prototype.getTilesLoading = function() {
  return this.tilesLoading_;
};

/**
 * @param {goog.events.Event} event Event.
 * @protected
 */
ol.TileQueue.prototype.handleTileChange = function(event) {
  var tile = /** @type {ol.Tile} */ (event.target);
  var state = tile.getState();
  if (state === ol.TileState.LOADED || state === ol.TileState.ERROR ||
      state === ol.TileState.EMPTY) {
    --this.tilesLoading_;
    this.tileChangeCallback_();
  }
};

/**
 * @param {number} maxTotalLoading Maximum number tiles to load simultaneously.
 * @param {number} maxNewLoads Maximum number of new tiles to load.
 */
ol.TileQueue.prototype.loadMoreTiles = function(maxTotalLoading, maxNewLoads) {
  var newLoads = Math.min(
      maxTotalLoading - this.getTilesLoading(), maxNewLoads, this.getCount());
  var i, tile;
  for (i = 0; i < newLoads; ++i) {
    tile = /** @type {ol.Tile} */ (this.dequeue()[0]);
    goog.events.listen(tile, goog.events.EventType.CHANGE,
        this.handleTileChange, false, this);
    tile.load();
  }
  this.tilesLoading_ += newLoads;
};
<commit_msg>Unregister tile change listeners<commit_after>goog.provide('ol.TilePriorityFunction');
goog.provide('ol.TileQueue');

goog.require('goog.events');
goog.require('goog.events.EventType');
goog.require('ol.Coordinate');
goog.require('ol.TileState');
goog.require('ol.structs.PriorityQueue');

/**
 * @typedef {function(ol.Tile, string, ol.Coordinate, number): number}
 */
ol.TilePriorityFunction;

/**
 * @constructor
 * @extends {ol.structs.PriorityQueue.<Array>}
 * @param {ol.TilePriorityFunction} tilePriorityFunction
 *     Tile priority function.
 * @param {function(): ?} tileChangeCallback
 *     Function called on each tile change event.
 * @struct
 */
ol.TileQueue = function(tilePriorityFunction, tileChangeCallback) {

  goog.base(
      this,
      /**
       * @param {Array} element Element.
       * @return {number} Priority.
       */
      function(element) {
        return tilePriorityFunction.apply(null, element);
      },
      /**
       * @param {Array} element Element.
       * @return {string} Key.
       */
      function(element) {
        return /** @type {ol.Tile} */ (element[0]).getKey();
      });

  /**
   * @private
   * @type {function(): ?}
   */
  this.tileChangeCallback_ = tileChangeCallback;

  /**
   * @private
   * @type {number}
   */
  this.tilesLoading_ = 0;

};
goog.inherits(ol.TileQueue, ol.structs.PriorityQueue);

/**
 * @return {number} Number of tiles loading.
 */
ol.TileQueue.prototype.getTilesLoading = function() {
  return this.tilesLoading_;
};

/**
 * @param {goog.events.Event} event Event.
 * @protected
 */
ol.TileQueue.prototype.handleTileChange = function(event) {
  var tile = /** @type {ol.Tile} */ (event.target);
  var state = tile.getState();
  if (state === ol.TileState.LOADED || state === ol.TileState.ERROR ||
      state === ol.TileState.EMPTY) {
    goog.events.unlisten(tile, goog.events.EventType.CHANGE,
        this.handleTileChange, false, this);
    --this.tilesLoading_;
    this.tileChangeCallback_();
  }
};

/**
 * @param {number} maxTotalLoading Maximum number tiles to load simultaneously.
 * @param {number} maxNewLoads Maximum number of new tiles to load.
 */
ol.TileQueue.prototype.loadMoreTiles = function(maxTotalLoading, maxNewLoads) {
  var newLoads = Math.min(
      maxTotalLoading - this.getTilesLoading(), maxNewLoads, this.getCount());
  var i, tile;
  for (i = 0; i < newLoads; ++i) {
    tile = /** @type {ol.Tile} */ (this.dequeue()[0]);
    goog.events.listen(tile, goog.events.EventType.CHANGE,
        this.handleTileChange, false, this);
    tile.load();
  }
  this.tilesLoading_ += newLoads;
};
<|endoftext|>


<commit_before>// JavaScript Document

function LoadFSList_FSList()
{
		$.post("/api/listfilesystems/").success(function(data, textStatus, jqXHR)
        {
            if(data.success)
            {
                var response = data.response;
				var fsName;
				var i=1;
				var action = " Stop FS | Config param | Remove";
				$.each(response, function(resKey, resValue)
                {
	                fsName = "" +  resValue.fsname + "";
					i++;
					$('#example').dataTable().fnAddData ([
					fsName,
					resValue.mgsname,
					resValue.mdsname,
					resValue.noofoss,
					resValue.noofost,
					resValue.kbytesused,
					resValue.kbytesfree,
					action
					]);
                });
            }
        })
        .error(function(event)
        {
             // Display of appropriate error message
        })
		.complete(function(event) {
		});
	/* table = table + "
"; */
}

function LoadMGT_EditFS()
{
		var fsname = $('#fs').val();
		$.post("/api/getvolumesdetails/",{filesystem:fsname}).success(function(data, textStatus, jqXHR)
        {
            if(data.success)
            {
                var response = data.response;
				$.each(response, function(resKey, resValue)
                {
					if(resValue.targetkind == "MGS")
					{
						if(resValue.targetstatus == "STARTED")
						{
							$('#example').dataTable().fnAddData ([
							resValue.targetmount,
							resValue.targetname,
							resValue.hostname,
							resValue.failover,
							"Stop"
							]);
						}
						else
						{
							$('#example').dataTable().fnAddData ([
							resValue.targetmount,
							resValue.targetname,
							resValue.hostname,
							resValue.failover,
							"Start"
							]);
						}
					}
                });
            }
        })
        .error(function(event)
        {
             // Display of appropriate error message
        })
		.complete(function(event) {
		});
}

function LoadMDT_EditFS()
{
	var fsname = $('#fs').val();
	$.post("/api/getvolumesdetails/",{filesystem:fsname}).success(function(data, textStatus, jqXHR)
        {
            if(data.success)
            {
                var response = data.response;
				$.each(response, function(resKey, resValue)
                {
					if(resValue.targetkind == "MDT")
					{
						if(resValue.targetstatus == "STARTED")
						{
							$('#mdt').dataTable().fnAddData ([
								resValue.targetdevice,
								resValue.targetname,
								resValue.hostname,
								resValue.failover,
								"Stop"
							]);
						}
						else
						{
							$('#mdt').dataTable().fnAddData ([
								resValue.targetdevice,
								resValue.targetname,
								resValue.hostname,
								resValue.failover,
								"Stop"
							]);
						}
					}
                });
            }
        })
        .error(function(event)
        {
             // Display of appropriate error message
        })
		.complete(function(event) {
		});
}

function LoadOST_EditFS()
{
	var fsname = $('#fs').val();
		$.post("/api/getvolumesdetails/",{filesystem:fsname}).success(function(data, textStatus, jqXHR)
        {
            if(data.success)
            {
                var response = data.response;
				$.each(response, function(resKey, resValue)
                {
					if(resValue.targetkind == "OST")
					{
						if(resValue.targetstatus == "STARTED")
						{
							$('#ost').dataTable().fnAddData ([
							resValue.targetmount,
							resValue.targetname,
							resValue.hostname,
							resValue.failover,
							"Stop"
							]);
						}
						else
						{
							$('#ost').dataTable().fnAddData ([
							resValue.targetmount,
							resValue.targetname,
							resValue.hostname,
							resValue.failover,
							"Start"
							]);
						}
					}
                });
            }
        })
        .error(function(event)
        {
             // Display of appropriate error message
        })
		.complete(function(event) {
		});

}

function LoadExistingMGT_EditFS()
{
	$('#popup-existing-mgt').dataTable().fnClearTable();
		$.post("/api/getvolumesdetails/",{filesystem:""}).success(function(data, textStatus, jqXHR)
        {
            if(data.success)
            {
                var response = data.response;
				var updatedTargetMnt="";
				$.each(response, function(resKey, resValue)
                {
						if(resValue.targetkind == "MGS")
						{
							if(updatedTargetMnt != resValue.targetmount)
							{
								if(resValue.targetstatus == "STARTED")
								{
									$('#popup-existing-mgt').dataTable().fnAddData ([
									resValue.targetmount,
									resValue.targetname,
									resValue.hostname,
									resValue.failover
									]);
								}
								else
								{
									$('#popup-existing-mgt').dataTable().fnAddData ([
									resValue.targetmount,
									resValue.targetname,
									resValue.hostname,
									resValue.failover
									]);
								}
						}
						updatedTargetMnt = resValue.targetmount;
					}
                });
            }
        })
        .error(function(event)
        {
             // Display of appropriate error message
        })
		.complete(function(event) {
		});
}

function CreateNewMGT_EditFS()
{
		$('#popup-new-mgt').dataTable().fnClearTable();
    	loadUsableVolumeList($('#popup-new-mgt'), function(vol_info) {return "<input type='radio' name='mgt'/>"});
}
function CreateNewMDT_EditFS()
{
	$('#popup-new-mdt').dataTable().fnClearTable();
  loadUsableVolumeList($('#popup-new-mdt'), function(vol_info) {return "<input type='radio' name='mdt'/>"});
}
function CreateOST_EditFS()
{
	$('#popup-new-ost').dataTable().fnClearTable();
  loadUsableVolumeList($('#popup-new-ost'), function(vol_info) {return "<input type='checkbox' name='" + vol_info.id + "'/>"});
}
function LoadMGTConfiguration_MGTConf()
{
	$('#popup-new-mgt').dataTable().fnClearTable();
	loadUsableVolumeList($('#popup-new-mgt'), function(vol_info) {return "<input type='checkbox' name='" + vol_info.id + "'/>"});
/*		$.post("/api/getdevices/",{"hostid": ""}).success(function(data, textStatus, jqXHR)
        {
            if(data.success)
            {
                var response = data.response;
				var failoverSelect;
				$.each(response, function(resKey, resValue)
                {
					if(resKey == 0)
					{
						failoverSelect = "<select>";
						$.each(resValue.failover, function(resFailoverKey, resFailoverValue)
						{
							if(resFailoverValue.failoverhost == undefined)
							{
								failoverSelect = failoverSelect + "<option value='volvo'>  Nonne  </option>";
							}
							else
							{
								failoverSelect = failoverSelect + "<option value='volvo'>" + resFailoverValue.failoverhost + "</option>";
							}
						});
						failoverSelect = failoverSelect + "</select>";
					}
					$('#popup-new-mgt').dataTable().fnAddData ([
						"<input type='radio' name='mgt'/>",
						resValue.devicepath,
						"<select><option value='volvo'>" + resValue.host + "</option></select>",
						failoverSelect,
						resValue.devicecapacity,
						resValue.isprimary,
						resValue.lun,
						resValue.lunname
					]);
				});
            }
        })
        .error(function(event)
        {
             // Display of appropriate error message
        })
		.complete(function(event) {
		});
		*/
}

function loadUsableVolumeList(datatable_container, select_widget_fn)
{
  $.get("/api/get_luns/", {'category': 'usable'}).success(function(data, textStatus, jqXHR)
  {
    if(data.success)
    {
      $.each(data.response, function(resKey, volume_info)
      {
        var primaryHostname = "---"
        var failoverHostname = "---"
        $.each(volume_info.available_hosts, function(host_id, host_info) {
          if (host_info.primary) {
            primaryHostname = host_info.label
          } else if (host_info.use) {
            failoverHostname = host_info.label
          }
        });

        datatable_container.dataTable().fnAddData ([
          select_widget_fn(volume_info),
          volume_info.name,
          volume_info.size,
          volume_info.kind,
          volume_info.status,
          primaryHostname,
          failoverHostname,
        ]);
      });
    }
  })
  .error(function(event)
  {
       // Display of appropriate error message
  })
}

function loadUnusedVolumeList()
{
  $.get("/api/get_luns/", {'category': 'unused'}).success(function(data, textStatus, jqXHR)
  {
    if(data.success)
    {
      $.each(data.response, function(resKey, resValue)
      {
        var blank_option = "<option value='-1'>---</option>";
        var blank_select = "<select disabled='disabled'>" + blank_option + "</select>"
        var primarySelect;
        var failoverSelect;

        var host_count = 0
        $.each(resValue.available_hosts, function(host_id, host_info) {
          host_count += 1;
        });
        if (host_count == 0) {
          primarySelect = blank_select
          failoverSelect = blank_select
        } else if (host_count == 1) {
          $.each(resValue.available_hosts, function(host_id, host_info) {
            primarySelect = "<select disabled='disabled'><option value='" + host_id + "'>" + host_info.label + "</option></select>";
          });
          failoverSelect = blank_select
        } else {
          primarySelect = "<select>";
          failoverSelect = "<select>";
          primarySelect += blank_option
          failoverSelect += blank_option
          $.each(resValue.available_hosts, function(host_id, host_info)
          {
            if (host_info.primary) {
              primarySelect += "<option value='" + host_id + "' selected='selected'>" + host_info.label + "</option>";
              failoverSelect += "<option value='" + host_id + "'>" + host_info.label + "</option>";
            } else if (host_info.use) {
              primarySelect += "<option value='" + host_id + "'>" + host_info.label + "</option>";
              failoverSelect += "<option value='" + host_id + "' selected='selected'>" + host_info.label + "</option>";
            } else {
              primarySelect += "<option value='" + host_id + "'>" + host_info.label + "</option>";
              failoverSelect += "<option value='" + host_id + "' selected='selected'>" + host_info.label + "</option>";
            }
          });
          failoverSelect += "</select>";
          primarySelect += "</select>";
        }

        $('#volume_configuration').dataTable().fnAddData ([
          resValue.name,
          primarySelect,
		  failoverSelect,
		  resValue.size,
          resValue.status
        ]);
      });
    }
  })
  .error(function(event) {
       // Display of appropriate error message
  })
	.complete(function(event) {
	});
}

function CreateMGT_MGTConf()
{
	var i=1;
	var checkboxCount = 0;
		$('#popup-new-ost').dataTable().fnClearTable();
 $.get("/api/get_luns/", {'category': 'unused'}).success(function(data, textStatus, jqXHR)
  {
    if(data.success)
    {
      $.each(data.response, function(resKey, resValue)
      {
        var blank_option = "<option value='-1'>---</option>";
        var blank_select = "<select disabled='disabled'>" + blank_option + "</select>"
        var primarySelect;
        var failoverSelect;

        var host_count = 0
        $.each(resValue.available_hosts, function(host_id, host_info) {
          host_count += 1;
        });
        if (host_count == 0) {
          primarySelect = blank_select
          failoverSelect = blank_select
        } else if (host_count == 1) {
          $.each(resValue.available_hosts, function(host_id, host_info) {
            primarySelect = "<select disabled='disabled'><option value='" + host_id + "'>" + host_info.label + "</option></select>";
          });
          failoverSelect = blank_select
        } else {
          primarySelect = "<select>";
          failoverSelect = "<select>";
          primarySelect += blank_option
          failoverSelect += blank_option
          $.each(resValue.available_hosts, function(host_id, host_info)
          {
            if (host_info.primary) {
              primarySelect += "<option value='" + host_id + "' selected='selected'>" + host_info.label + "</option>";
              failoverSelect += "<option value='" + host_id + "'>" + host_info.label + "</option>";
            } else if (host_info.use) {
              primarySelect += "<option value='" + host_id + "'>" + host_info.label + "</option>";
              failoverSelect += "<option value='" + host_id + "' selected='selected'>" + host_info.label + "</option>";
            } else {
              primarySelect += "<option value='" + host_id + "'>" + host_info.label + "</option>";
              failoverSelect += "<option value='" + host_id + "' selected='selected'>" + host_info.label + "</option>";
            }
          });
          failoverSelect += "</select>";
          primarySelect += "</select>";
        }

        $('#popup-new-ost').dataTable().fnAddData ([
          "<input type='checkbox' id='" + i+ "'/>",
		  resValue.name,
		  primarySelect,
		  failoverSelect,
		  resValue.size,
		  resValue.status
        ]);
		$('#'+i).live('click', function() {
						if($(this).attr('checked'))
						{
							checkboxCount++;
							$('#mgtConfig_btnNewMGT').removeAttr('disabled');
						}
						else
						{
							checkboxCount--;
						}
						if(checkboxCount==0)
						{
							$('#mgtConfig_btnNewMGT').attr('disabled', 'disabled');
						}
					});
					i++;

      });
    }
  })
  .error(function(event) {
       // Display of appropriate error message
  })
	.complete(function(event) {
	});

/*
		$.post("/api/getdevices/",{"hostid": ""}).success(function(data, textStatus, jqXHR)
        {
            if(data.success)
            {
                var response = data.response;
				var failoverSelect;
				var i=1;
				var checkboxCount = 0;
				$.each(response, function(resKey, resValue)
                {
					if(resKey == 0)
					{
						failoverSelect = "<select>";
						$.each(resValue.failover, function(resFailoverKey, resFailoverValue)
						{
							if(resFailoverValue.failoverhost==undefined)
							{
								failoverSelect = failoverSelect + "<option value='volvo'>  None  </option>";
							}
							else
							{
								failoverSelect = failoverSelect + "<option value='volvo'>" + resFailoverValue.failoverhost + "</option>";
							}
						});
						failoverSelect = failoverSelect + "</select>";
					}
					$('#popup-new-ost').dataTable().fnAddData ([
						"<input type='checkbox' id='" + i+ "'/>",
						resValue.devicepath,
						resValue.host,
						failoverSelect,
						resValue.devicecapacity,
						resValue.lun,
						resValue.lunname
					]);

					$('#'+i).live('click', function() {
						if($(this).attr('checked'))
						{
							checkboxCount++;
							$('#mgtConfig_btnNewMGT').removeAttr('disabled');
						}
						else
						{
							checkboxCount--;
						}
						if(checkboxCount==0)
						{
							$('#mgtConfig_btnNewMGT').attr('disabled', 'disabled');
						}
					});
					i++;
				});
            }
        })
        .error(function(event)
        {
             // Display of appropriate error message
        })
		.complete(function(event) {
		});
*/
}

function LoadMGTConfiguration_MGTConf()
{
		$.post("/api/getvolumesdetails/",{filesystem:""}).success(function(data, textStatus, jqXHR)
        {
            if(data.success)
            {
                var response = data.response;
				var targetpath="";
				var fsname="";
				var val_targetstatus;
				var val_targetmount;
				var val_hostname;
				var val_failover;
				var updated=0;

				if(data.response!="")
				{
					$.each(response, function(resKey, resValue)
					{
						if(resValue.targetkind == "MGS")
						{
							if(targetpath!=resValue.targetmount && targetpath!="")
							{
								//fsname = resValue.fsname;
								if(resValue.targetstatus == "STARTED")
								{
									$('#mgt_configuration').dataTable().fnAddData ([
									fsname,
									resValue.targetmount,
									resValue.hostname,
									resValue.failover,
									"Stop"
									]);
								}
								else
								{
									$('#mgt_configuration').dataTable().fnAddData ([
									fsname,
									resValue.targetmount,
									resValue.hostname,
									resValue.failover,
									"Start"
									]);
								}
								fsname="";
								updated=1;
							}
							else
							{
								if (fsname!="")
								{
									fsname = fsname +  "," + resValue.fsname;
								}
								else
								{
									fsname = resValue.fsname;
								}
								val_targetstatus=resValue.targetstatus;
								val_targetmount=resValue.targetmount;
								val_hostname=resValue.hostname;
								val_failover=resValue.failover;
								updated=0;
							}
							targetpath = resValue.targetmount;
						}

					});
					if(updated==0)
					{
						if(val_targetstatus == "STARTED")
						{
							$('#mgt_configuration').dataTable().fnAddData ([
							fsname,
							val_targetmount,
							val_hostname,
							val_failover,
							"Stop"
							]);
						}
						else
						{
							$('#mgt_configuration').dataTable().fnAddData ([
							fsname,
							val_targetmount,
							val_hostname,
							val_failover,
							"Start"
							]);
						}
					}
				}
            }
        })
        .error(function(event)
        {
             // Display of appropriate error message
        })
		.complete(function(event) {
		});
}

function LoadVolumeConf_VolumeConfig()
{
		$.post("/api/get_luns/",{"category": "usable"}).success(function(data, textStatus, jqXHR)
        {
            if(data.success)
            {
                var response = data.response;
				var primaryServer;
				$.each(response, function(resKey, resValue)
                {
						primaryServer = "<select>";
						$.each(resValue.available_hosts, function(resFailoverKey, resFailoverValue)
						{
								if(resFailoverValue.label==undefined)
								{
									primaryServer = primaryServer + "<option value='volvo'>  None  </option>";
								}
								else
								{
									primaryServer = primaryServer + "<option value='volvo'>" + resFailoverValue.label + "</option>";
								}
								primaryServer = primaryServer + "</select>";
						});
					$('#volume_configuration').dataTable().fnAddData ([
						resValue.name,
						primaryServer,
						"",
						resValue.status,
						resValue.size
				]);
				});
            }
        })
        .error(function(event)
        {
             // Display of appropriate error message
        })
		.complete(function(event) {
		});
	}

function LoadServerConf_ServerConfig()
{
	$.post("/api/listservers/",{"hostid": ""}).success(function(data, textStatus, jqXHR)
        {
            if(data.success)
            {
                var response = data.response;
				var lnet_status_mesg;
				$.each(response, function(resKey, resValue)
                {
					if(resValue.lnet_status == "OK")
					{
						lnet_status_mesg = "Stop Lnet | Remove | Unload Lnet | Configuration";
					}
					else
					{
						lnet_status_mesg = "Start Lnet | Remove | Unload Lnet | Configuration";
					}
					$('#server_configuration').dataTable().fnAddData ([
						resValue.host_address,
						resValue.failnode,
						resValue.lnet_status,
						lnet_status_mesg
					]);
				});
            }
        })
        .error(function(event)
        {
             // Display of appropriate error message
        })
		.complete(function(event) {
		});
}

function LoadFSData_EditFS()
{
	var fsname = $('#fs').val();
	$('#fsname').attr('value',fsname);
	if(fsname!="none")
	{
		$.post("/api/getfilesystem/",{"filesystem":fsname}).success(function(data, textStatus, jqXHR)
		{
				if(data.success)
				{
					var response = data.response;
					var lnet_status_mesg;
					$.each(response, function(resKey, resValue)
					{
						$('#total_capacity').html(resValue.kbytesused + resValue.kbytesfree);
						$('#mdt_file').html(resValue.kbytesused + resValue.mdtfileused);
						$('#inodes').html(resValue.kbytesused + resValue.kbytesfree);
						$('#total_oss').html(resValue.noofoss);
						$('#total_ost').html(resValue.noofost);
					});
				}
			})
			.error(function(event)
			{
				 // Display of appropriate error message
			})
			.complete(function(event) {
			});
	}
}<commit_msg>Remove rogue js file in templates dir<commit_after><|endoftext|>


<commit_before>'use strict';

var CustomError    = require('es5-ext/lib/Error/custom')
  , isFunction     = require('es5-ext/lib/Function/is-function')
  , invoke         = require('es5-ext/lib/Function/invoke')
  , noop           = require('es5-ext/lib/Function/noop')
  , d              = require('es5-ext/lib/Object/descriptor')
  , extend         = require('es5-ext/lib/Object/extend')
  , oForEach       = require('es5-ext/lib/Object/for-each')
  , callable       = require('es5-ext/lib/Object/valid-callable')
  , memoize        = require('memoizee/lib/regular')
  , ee             = require('event-emitter/lib/core')
  , isNode         = require('dom-ext/lib/Node/is-node')
  , validDocument  = require('dom-ext/lib/Document/valid-document')
  , makeElement    = require('dom-ext/lib/Document/prototype/make-element')
  , replaceContent = require('dom-ext/lib/Element/prototype/replace-content')
  , validSet       = require('set-collection/lib/valid-set')
  , stringify      = require('querystring-x/encode')
  , Db             = require('dbjs')

  , isArray = Array.isArray, map = Array.prototype.map
  , forEach = Array.prototype.forEach
  , defineProperty = Object.defineProperty
  , Base = Db.Base
  , cellName = { td: true, th: true }
  , Table;

require('memoizee/lib/ext/method');

module.exports = Table = function (document, set/*, options*/) {
	var options = Object(arguments[2]), getList, classes;
	this.document = validDocument(document);
	this.el = makeElement.bind(this.document);
	this.set = this.obj = validSet(set);
	this.sortMethods = {};
	this.filterMethods = {};
	this.current = {};

	this.render(options);
	if (options.class != null) {
		classes = String(options.class);
		if (classes) {
			classes.split(' ').forEach(function (name) {
				this.add(name);
			}, this.dom.classList);
		}
	}

	// Columns
	if (options.columns != null) {

		// Sort methods
		forEach.call(options.columns, function (options, index) {
			var method, name;
			if (!options.sort) return;
			name = options.default ? '' : String(options.name || index);
			method = this.setSortMethod(name, options.sort, options.reverse);
			options.sortName = name;
		}, this);

		// Head
		if (this.head) {
			map.call(options.columns, function (options, index) {
				if (options.head) return this.headCellRender(options.head, options);
				return this.head.appendChild(document.createElement('th'));
			}, this).forEach(this.head.appendChild, this.head);
		}

		// Cells
		this.cellRenderers = map.call(options.columns, function (options, index) {
			var name;
			if ((set._type_ === 'namespace') && (typeof options === 'string')) {
				name = options;
				if (this.head) {
					this.head.appendChild(
						this.headCellRender(set.prototype.get(name)._label)
					);
				}
				return function (item) { return item.get(name); };
			}
			if (options.render != null) {
				return callable(options.render);
			} else if (options.name != null) {
				name = String(options.name);
				return function (item) { return item.get(name); };
			} else {
				return noop;
			}
		}, this);
	} else if (set._type_ === 'namespace') {
		this.cellRenderers = set.prototype.getPropertyNames(options.tag)
			.listByOrder().map(function (name) {
				if (this.head) {
					this.head.appendChild(
						this.headCellRenderer(this.get(name)._label.toDOM(this.document))
					);
				}
				return function (item) { return item.get(name); };
			});
	} else {
		throw new CustomError("Columns layout not provided", 'MISSING_COLUMNS');
	}

	// Rows
	if (!this.sortMethods['']) {
		if (options.sort) {
			this.setSortMethod('', options.sort, options.reverse);
		} else {
			if (set._type_ === 'namespace') getList = invoke('listByCreatedAt');
			else if (set.listByOrder) getList = invoke('listByOrder');
			else getList = invoke('list');
			this.sortMethods[''] = {
				getList: getList,
				reverse: false
			};
		}
	}

	this.reset();
};

ee(Object.defineProperties(Table.prototype, extend({
	reverse: d(false),
	render: d(function (options) {
		var el = makeElement.bind(this.document);
		this.dom = el('table', { class: 'dbjs' },
			options.head ? el('thead', this.head = el('tr')) : null,
			this.body = el('tbody'));
	}),
	headCellRender: d(function (dom, options) {
		var sortName;
		if (isNode(dom) && (dom.nodeName.toLowerCase() === 'th')) return dom;
		if (options.sortName != null) {
			sortName = options.sortName;
			this.on('change', function () {
				var data = {};
				if (sortName) data.sort = sortName;
				if ((this.current.sort === sortName) && !this.current.reverse) {
					data.reverse = true;
				}
				data = stringify(data);
				dom.setAttribute('href',  data ? '?' + data : '.');
			});
			dom = this.el('a', dom);
		}
		return this.el('th', dom);
	}),
	cellRender: d(function (render, item) {
		var dom = render(item);
		if (isNode(dom) && cellName.hasOwnProperty(dom.nodeName.toLowerCase())) {
			return dom;
		}
		return makeElement.call(this.document, 'td', dom);
	}),
	setSortMethod: d(function (name, data, reverse) {
		var getList;
		if (typeof data === 'string') {
			if (!this.obj.listByProperty) {
				throw new CustomError("Property sort not supported",
					'NO_SET_NAME_SORT_SUPPORT');
			}
			getList = function (set) { return set.listByProperty(data); };
		} else if (isFunction(data)) {
			if (data.length === 1) {
				getList = memoize(data);
			} else {
				getList = memoize(function (set) { return set.list(data); });
			}
		}
		return (this.sortMethods[name] = {
			getList: getList,
			reverse: Boolean(reverse)
		});
	}),
	setFilterMethod: d(function (name, cb) {
		this.filterMethods[name] = cb;
	}),
	reset: d(function (data) {
		var set;
		data = Object(data);
		oForEach(this.filterMethods, function (fn, name) {
			var filtered;
			if (!data[name]) return;
			filtered = fn(data[name]);
			if (!filtered) return;
			if (set) set = set.intersection(filtered);
			else set = filtered;
		});
		if (set) this.set = set;
		else this.set = this.obj;
		this.sortBy(data.sort || '', data.reverse);
	}),
	sortBy: d(function (name, reverse) {
		var method;
		method = this.sortMethods[name] || this.sortMethods[''];
		reverse = Boolean(reverse);
		this.current.sort = name;
		this.current.reverse = reverse;
		if (method.reverse) reverse = !reverse;
		this.sort(method.getList(this.set), reverse);
	}),
	sort: d(function (list, reverse) {
		if (!isArray(list)) {
			throw new CustomError("List must be an array", "ARRAY_EXPECTED");
		}
		if (list.obj !== this.set) {
			throw new CustomError("List doesn't match set", 'LIST_MISMATCH');
		}
		reverse = Boolean(reverse);
		if ((this.list === list) && (this.reverse === reverse)) return;
		this.emit('change');
		if (this.list !== list) {
			if (this.list) this.list.off('change', this.reload);
			list.on('change', this.reload);
		}
		this.list = list;
		this.reverse = reverse;
		this.reload();
	}),
	emptyRow: d.gs(function () {
		defineProperty(this, 'emptyRow', d(this.el('tr', this.el('td',
			{ colspan: this.cellRenderers.length, class: 'empty' }, "No data"))));
		return this.emptyRow;
	}),
	toDOM: d(function () { return this.dom; })
}, memoize(function (item) {
	return makeElement.call(this.document, 'tr',
		this.cellRenderers.map(function (render) {
			return this.cellRender(render, item);
		}, this));
}, { method: 'rowRender' }), d.binder({
	reload: d(function () {
		var list;
		if (this.list.length) {
			list = this.list.map(this.rowRender);
			if (this.reverse) list.reverse();
		} else {
			list = [this.emptyRow];
		}
		replaceContent.call(this.body, list);
	})
}))));

Object.defineProperty(Base, 'DOMTable', d(Table));

Object.defineProperty(Db, 'toDOMTable', d(function (document/*, options*/) {
	return new this.DOMTable(document, this, arguments[1]);
}));
<commit_msg>More logical filter handling<commit_after>'use strict';

var CustomError    = require('es5-ext/lib/Error/custom')
  , isFunction     = require('es5-ext/lib/Function/is-function')
  , invoke         = require('es5-ext/lib/Function/invoke')
  , noop           = require('es5-ext/lib/Function/noop')
  , d              = require('es5-ext/lib/Object/descriptor')
  , extend         = require('es5-ext/lib/Object/extend')
  , oForEach       = require('es5-ext/lib/Object/for-each')
  , callable       = require('es5-ext/lib/Object/valid-callable')
  , memoize        = require('memoizee/lib/regular')
  , ee             = require('event-emitter/lib/core')
  , isNode         = require('dom-ext/lib/Node/is-node')
  , validDocument  = require('dom-ext/lib/Document/valid-document')
  , makeElement    = require('dom-ext/lib/Document/prototype/make-element')
  , replaceContent = require('dom-ext/lib/Element/prototype/replace-content')
  , validSet       = require('set-collection/lib/valid-set')
  , stringify      = require('querystring-x/encode')
  , Db             = require('dbjs')

  , isArray = Array.isArray, map = Array.prototype.map
  , forEach = Array.prototype.forEach
  , defineProperty = Object.defineProperty
  , Base = Db.Base
  , cellName = { td: true, th: true }
  , Table;

require('memoizee/lib/ext/method');

module.exports = Table = function (document, set/*, options*/) {
	var options = Object(arguments[2]), getList, classes;
	this.document = validDocument(document);
	this.el = makeElement.bind(this.document);
	this.set = this.obj = validSet(set);
	this.sortMethods = {};
	this.filterMethods = {};
	this.current = {};

	this.render(options);
	if (options.class != null) {
		classes = String(options.class);
		if (classes) {
			classes.split(' ').forEach(function (name) {
				this.add(name);
			}, this.dom.classList);
		}
	}

	// Columns
	if (options.columns != null) {

		// Sort methods
		forEach.call(options.columns, function (options, index) {
			var method, name;
			if (!options.sort) return;
			name = options.default ? '' : String(options.name || index);
			method = this.setSortMethod(name, options.sort, options.reverse);
			options.sortName = name;
		}, this);

		// Head
		if (this.head) {
			map.call(options.columns, function (options, index) {
				if (options.head) return this.headCellRender(options.head, options);
				return this.head.appendChild(document.createElement('th'));
			}, this).forEach(this.head.appendChild, this.head);
		}

		// Cells
		this.cellRenderers = map.call(options.columns, function (options, index) {
			var name;
			if ((set._type_ === 'namespace') && (typeof options === 'string')) {
				name = options;
				if (this.head) {
					this.head.appendChild(
						this.headCellRender(set.prototype.get(name)._label)
					);
				}
				return function (item) { return item.get(name); };
			}
			if (options.render != null) {
				return callable(options.render);
			} else if (options.name != null) {
				name = String(options.name);
				return function (item) { return item.get(name); };
			} else {
				return noop;
			}
		}, this);
	} else if (set._type_ === 'namespace') {
		this.cellRenderers = set.prototype.getPropertyNames(options.tag)
			.listByOrder().map(function (name) {
				if (this.head) {
					this.head.appendChild(
						this.headCellRenderer(this.get(name)._label.toDOM(this.document))
					);
				}
				return function (item) { return item.get(name); };
			});
	} else {
		throw new CustomError("Columns layout not provided", 'MISSING_COLUMNS');
	}

	// Rows
	if (!this.sortMethods['']) {
		if (options.sort) {
			this.setSortMethod('', options.sort, options.reverse);
		} else {
			if (set._type_ === 'namespace') getList = invoke('listByCreatedAt');
			else if (set.listByOrder) getList = invoke('listByOrder');
			else getList = invoke('list');
			this.sortMethods[''] = {
				getList: getList,
				reverse: false
			};
		}
	}

	this.reset();
};

ee(Object.defineProperties(Table.prototype, extend({
	reverse: d(false),
	render: d(function (options) {
		var el = makeElement.bind(this.document);
		this.dom = el('table', { class: 'dbjs' },
			options.head ? el('thead', this.head = el('tr')) : null,
			this.body = el('tbody'));
	}),
	headCellRender: d(function (dom, options) {
		var sortName;
		if (isNode(dom) && (dom.nodeName.toLowerCase() === 'th')) return dom;
		if (options.sortName != null) {
			sortName = options.sortName;
			this.on('change', function () {
				var data = {};
				if (sortName) data.sort = sortName;
				if ((this.current.sort === sortName) && !this.current.reverse) {
					data.reverse = true;
				}
				data = stringify(data);
				dom.setAttribute('href',  data ? '?' + data : '.');
			});
			dom = this.el('a', dom);
		}
		return this.el('th', dom);
	}),
	cellRender: d(function (render, item) {
		var dom = render(item);
		if (isNode(dom) && cellName.hasOwnProperty(dom.nodeName.toLowerCase())) {
			return dom;
		}
		return makeElement.call(this.document, 'td', dom);
	}),
	setSortMethod: d(function (name, data, reverse) {
		var getList;
		if (typeof data === 'string') {
			if (!this.obj.listByProperty) {
				throw new CustomError("Property sort not supported",
					'NO_SET_NAME_SORT_SUPPORT');
			}
			getList = function (set) { return set.listByProperty(data); };
		} else if (isFunction(data)) {
			if (data.length === 1) {
				getList = memoize(data);
			} else {
				getList = memoize(function (set) { return set.list(data); });
			}
		}
		return (this.sortMethods[name] = {
			getList: getList,
			reverse: Boolean(reverse)
		});
	}),
	setFilterMethod: d(function (name, cb) {
		this.filterMethods[name] = cb;
	}),
	reset: d(function (data) {
		var set;
		data = Object(data);
		oForEach(this.filterMethods, function (fn, name) {
			var filtered;
			if (data[name] == null) return;
			filtered = fn(data[name]);
			if (!filtered) return;
			if (set) set = set.intersection(filtered);
			else set = filtered;
		});
		if (set) this.set = set;
		else this.set = this.obj;
		this.sortBy(data.sort || '', data.reverse);
	}),
	sortBy: d(function (name, reverse) {
		var method;
		method = this.sortMethods[name] || this.sortMethods[''];
		reverse = Boolean(reverse);
		this.current.sort = name;
		this.current.reverse = reverse;
		if (method.reverse) reverse = !reverse;
		this.sort(method.getList(this.set), reverse);
	}),
	sort: d(function (list, reverse) {
		if (!isArray(list)) {
			throw new CustomError("List must be an array", "ARRAY_EXPECTED");
		}
		if (list.obj !== this.set) {
			throw new CustomError("List doesn't match set", 'LIST_MISMATCH');
		}
		reverse = Boolean(reverse);
		if ((this.list === list) && (this.reverse === reverse)) return;
		this.emit('change');
		if (this.list !== list) {
			if (this.list) this.list.off('change', this.reload);
			list.on('change', this.reload);
		}
		this.list = list;
		this.reverse = reverse;
		this.reload();
	}),
	emptyRow: d.gs(function () {
		defineProperty(this, 'emptyRow', d(this.el('tr', this.el('td',
			{ colspan: this.cellRenderers.length, class: 'empty' }, "No data"))));
		return this.emptyRow;
	}),
	toDOM: d(function () { return this.dom; })
}, memoize(function (item) {
	return makeElement.call(this.document, 'tr',
		this.cellRenderers.map(function (render) {
			return this.cellRender(render, item);
		}, this));
}, { method: 'rowRender' }), d.binder({
	reload: d(function () {
		var list;
		if (this.list.length) {
			list = this.list.map(this.rowRender);
			if (this.reverse) list.reverse();
		} else {
			list = [this.emptyRow];
		}
		replaceContent.call(this.body, list);
	})
}))));

Object.defineProperty(Base, 'DOMTable', d(Table));

Object.defineProperty(Db, 'toDOMTable', d(function (document/*, options*/) {
	return new this.DOMTable(document, this, arguments[1]);
}));
<|endoftext|>


<commit_before>/* @flow */

import type { Command, Option, OptionEntry } from '../types'

const OPTION_SHORT_MULTI = /^-([a-z0-9]{2,})$/i
const OPTION_COMPRESSED = /^(--[a-z0-9]+)=(.+)$|^(-[a-z0-9]+)=(.+)$/i

function getOptionByAlias(options: Array<Option>, alias: string): Option {
  const foundOption = options.find(option => option.aliases.indexOf(alias) !== -1)
  if (foundOption) {
    return foundOption
  }
  throw new Error(`Option ${alias} is not recognized`)
}

// TODO: --a !== -a
export default function parse(given: Array<string>, commands: Array<Command>, options: Array<Option>): {
  options: Array<OptionEntry>,
  command: null,
  parameters: Array<string>,
} {
  let command
  let parsedParameters = []
  const parsedOptions = []

  let lastOption: ?OptionEntry = null
  const argv = given.slice(2)
  for (let i = 0, length = argv.length; i < length; i++) {
    const chunk = argv[i]
    if (chunk === '--') {
      parsedParameters = parsedParameters.concat(argv.slice(i + 1))
      break
    }
    if (chunk.startsWith('-')) {
      if (lastOption) {
        if (lastOption.option.parameter && !lastOption.value) {
          throw new Error(`Option ${chunk} expects a value`)
        }
        parsedOptions.push(lastOption)
        lastOption = null
      }
      if (OPTION_SHORT_MULTI.test(chunk)) {
        // Expand -asd to -a -s -d in argv
        const matched = OPTION_SHORT_MULTI.exec(chunk)
        argv.splice(i, 1, ...matched[1].split('').map(e => `-${e}`))
        i--
        continue
      }
      if (OPTION_COMPRESSED.test(chunk)) {
        // Expand --bee=sea / -a=b to [--bee, sea]
        const matched = OPTION_COMPRESSED.exec(chunk)
        argv.splice(i, 1, matched[1] || matched[3], matched[2] || matched[4])
        i--
        continue
      }
      lastOption = {
        name: chunk,
        value: null,
        option: getOptionByAlias(options, chunk),
      }
    } else {
      if (!lastOption) {
        parsedParameters.push(chunk)
        continue
      }
      if (lastOption.option.parameter && !lastOption.value) {
        lastOption.value = chunk
        parsedOptions.push(lastOption)
        lastOption = null
      } else {
        parsedParameters.push(chunk)
      }
    }
  }
  if (lastOption) {
    if (lastOption.option.parameter && !lastOption.value) {
      throw new Error(`Option ${lastOption.name} expects a value`)
    }
    parsedOptions.push(lastOption)
  }

  // Process the bool options
  for (let i = 0, length = parsedOptions.length; i < length; i++) {
    const entry = parsedOptions[i]
    if (!entry.option.parameter) {
      entry.value = true
    }
  }

  // TODO: Find out the command and see if the parameters are valid

  return {
    options: parsedOptions,
    command: null,
    // TODO: Replace with real command
    parameters: parsedParameters,
  }
}
<commit_msg>:new: Add command and command parameter support to argv parser<commit_after>/* @flow */

import type { Command, Option, OptionEntry } from '../types'

const OPTION_SHORT_MULTI = /^-([a-z0-9]{2,})$/i
const OPTION_COMPRESSED = /^(--[a-z0-9]+)=(.+)$|^(-[a-z0-9]+)=(.+)$/i

function getOptionByAlias(options: Array<Option>, alias: string): Option {
  const foundOption = options.find(option => option.aliases.indexOf(alias) !== -1)
  if (foundOption) {
    return foundOption
  }
  throw new Error(`Option ${alias} is not recognized`)
}

export default function parse(given: Array<string>, commands: Array<Command>, options: Array<Option>): {
  options: Array<OptionEntry>,
  command: ?Command,
  parameters: Array<string>,
} {
  let parsedParameters = []
  const rawParameters = []
  const parsedOptions = []

  let lastOption: ?OptionEntry = null
  const argv = given.slice(2)
  for (let i = 0, length = argv.length; i < length; i++) {
    const chunk = argv[i]
    if (chunk === '--') {
      parsedParameters = parsedParameters.concat(argv.slice(i + 1))
      break
    }
    if (chunk.startsWith('-')) {
      if (lastOption) {
        if (lastOption.option.parameter && !lastOption.value) {
          throw new Error(`Option ${chunk} expects a value`)
        }
        parsedOptions.push(lastOption)
        lastOption = null
      }
      if (OPTION_SHORT_MULTI.test(chunk)) {
        // Expand -asd to -a -s -d in argv
        const matched = OPTION_SHORT_MULTI.exec(chunk)
        argv.splice(i, 1, ...matched[1].split('').map(e => `-${e}`))
        i--
        continue
      }
      if (OPTION_COMPRESSED.test(chunk)) {
        // Expand --bee=sea / -a=b to [--bee, sea]
        const matched = OPTION_COMPRESSED.exec(chunk)
        argv.splice(i, 1, matched[1] || matched[3], matched[2] || matched[4])
        i--
        continue
      }
      lastOption = {
        name: chunk,
        value: null,
        option: getOptionByAlias(options, chunk),
      }
    } else {
      if (!lastOption) {
        rawParameters.push(chunk)
        continue
      }
      if (lastOption.option.parameter && !lastOption.value) {
        lastOption.value = chunk
        parsedOptions.push(lastOption)
        lastOption = null
      } else {
        rawParameters.push(chunk)
      }
    }
  }
  if (lastOption) {
    if (lastOption.option.parameter && !lastOption.value) {
      throw new Error(`Option ${lastOption.name} expects a value`)
    }
    parsedOptions.push(lastOption)
  }

  // Process the bool options
  for (let i = 0, length = parsedOptions.length; i < length; i++) {
    const entry = parsedOptions[i]
    if (!entry.option.parameter) {
      entry.value = true
    }
  }

  let command = null
  for (let i = rawParameters.length; i--;) {
    const currentName = rawParameters.slice(0, i + 1).join('.')
    command = commands.find(entry => entry.name === currentName)
    if (command) {
      parsedParameters.unshift(...rawParameters.slice(i + 1))
      break
    }
  }

  if (command) {
    let notEnough = false
    let parameterIndex = 0
    for (let i = 0, length = command.parameters.length; i < length; i++) {
      const parameter = command.parameters[i]
      const value = parsedParameters[parameterIndex]
      if (!value && parameter.type.startsWith('required')) {
        notEnough = true
        break
      } else if (parameter.type.endsWith('variadic')) {
        parameterIndex = parsedParameters.length
        break
      } else if (value) {
        parameterIndex++
      }
    }
    if (notEnough) {
      throw new Error(`Not enough parameters for command: ${command.name.split('.').join(' ')}`)
    } else if (parameterIndex < parsedParameters.length) {
      throw new Error(`Too many parameters for command: ${command.name.split('.').join(' ')}`)
    }
    // TODO: Validation and filling
  }
  // TODO: fill default option values

  return {
    options: parsedOptions,
    command,
    parameters: parsedParameters,
  }
}
<|endoftext|>


<commit_before>/**
 * Created by timtian on 2016/8/26.
 */
var gutil = require('gulp-util');
var revver = require('../revver');

var parser = {};

parser.parse = function (text, filepath, options) {
    try {

        var resText = [];
        var textList = [];
        var mList = [];
        if (options.ignorePattern) {
            var tmptextList = text.split(options.ignorePattern);

            var m;
            var mindex = 0;
            textList.push({raw: tmptextList[mindex], ignore: false});
            while ((m = options.ignorePattern.exec(text)) !== null) {
                textList.push({raw: m[0], ignore: options.ignoreFilter(m)});
                mindex++;
                textList.push({raw: tmptextList[mindex], ignore: false});
            }
        } else {
            textList.push({raw:text, ignore:false});
        }

        for (var j = 0; j < textList.length; j++) {
            var revObj = textList[j];
            if (!revObj.ignore) {
                var revText = revObj.raw;
                for (var i = 0; i < options.fileTypes.length; i++) {
                    var fileType = options.fileTypes[i];
                    var pattern = options.patterns[fileType];
                    revText = revText.replace(pattern.regex, function (match, p1, p2, p3, offset, string) {

                        var q = p2.substring(0, 1);
                        var src = p2.substring(1, p2.length - 1);
                        var revv = revver.rev(src, filepath, options);
                        var newsrc = p2;

                        if (revv !== '') {
                            newsrc = options.transformPath(src, revv);
                            gutil.log(src + ' --> ', gutil.colors.green(newsrc));
                        } else {
                            gutil.log(gutil.colors.blue('ignore:rev is empty'), src);
                        }

                        return p1 + q + newsrc + q + p3;
                    })
                }
                resText.push(revText);
            }else{
                resText.push(revObj.raw);
            }

            if (mList.length > 0)
                resText.push(mList.shift());
        }

        return resText.join('');
    } catch (err) {
        gutil.log(gutil.colors.red(err.message));
        gutil.log(gutil.colors.red(err.stack));
    }
};

module.exports = parser;<commit_msg>Update plain.js<commit_after>/**
 * Created by timtian on 2016/8/26.
 */
var gutil = require('gulp-util');
var revver = require('../revver');

var parser = {};

parser.parse = function (text, filepath, options) {
    try {

        var resText = [];
        var textList = [];
        var mList = [];
        if (options.ignorePattern) {
            var tmptextList = text.split(options.ignorePattern);

            var m;
            var mindex = 0;
            textList.push({raw: tmptextList[mindex], ignore: false});
            while ((m = options.ignorePattern.exec(text)) !== null) {
                textList.push({raw: m[0], ignore: options.ignoreFilter(m)});
                mindex++;
                textList.push({raw: tmptextList[mindex], ignore: false});
            }
        } else {
            textList.push({raw:text, ignore:false});
        }

        for (var j = 0; j < textList.length; j++) {
            var revObj = textList[j];
            if (!revObj.ignore) {
                var revText = revObj.raw;
                for (var i = 0; i < options.fileTypes.length; i++) {
                    var fileType = options.fileTypes[i];
                    var pattern = options.patterns[fileType];
                    revText = revText.replace(pattern.regex, function (match, p1, p2, p3, offset, string) {

                        var q = p2.substring(0, 1);
                        var src = p2.substring(1, p2.length - 1);
                        var revv = revver.rev(src, filepath, options);
                        var newsrc = p2;

                        if (revv !== '') {
                            newsrc = options.transformPath(src, revv);
                            gutil.log(src + ' --> ', gutil.colors.green(newsrc));
                            return p1 + q + newsrc + q + p3;
                        } else {
                            gutil.log(gutil.colors.blue('ignore:rev is empty'), src);
                            return match;
                        }

                    })
                }
                resText.push(revText);
            }else{
                resText.push(revObj.raw);
            }

            if (mList.length > 0)
                resText.push(mList.shift());
        }

        return resText.join('');
    } catch (err) {
        gutil.log(gutil.colors.red(err.message));
        gutil.log(gutil.colors.red(err.stack));
    }
};

module.exports = parser;
<|endoftext|>


<commit_before>/*
 * Paper.js
 *
 * This file is part of Paper.js, a JavaScript Vector Graphics Library,
 * based on Scriptographer.org and designed to be largely API compatible.
 * http://paperjs.org/
 * http://scriptographer.org/
 *
 * Distributed under the MIT license. See LICENSE file for details.
 *
 * Copyright (c) 2011, Juerg Lehni & Jonathan Puckey
 * http://lehni.org/ & http://jonathanpuckey.com/
 *
 * All rights reserved.
 */

var Segment = this.Segment = Base.extend({
	beans: true,

	initialize: function(arg0, arg1, arg2, arg3, arg4, arg5) {
		if (arguments.length == 0) {
			this._point = SegmentPoint.create(this, 0, 0);
		} else if (arguments.length == 1) {
			// TODO: If beans are not activated, this won't copy from
			// an existing segment. OK?
			if (arg0.point) {
				this._point = SegmentPoint.create(this, arg0.point);
				this._handleIn = SegmentPoint.create(this, arg0.handleIn);
				this._handleOut = SegmentPoint.create(this, arg0.handleOut);
			} else {
				this._point = SegmentPoint.create(this, arg0);
			}
		} else if (arguments.length < 6) {
			if (arguments.length == 2 && !arg1.x) {
				this._point = SegmentPoint.create(this, arg0, arg1);
			} else {
				this._point = SegmentPoint.create(this, arg0);
				// Doesn't matter if these arguments exist, it creates 0, 0
				// points otherwise
				this._handleIn = SegmentPoint.create(this, arg1);
				this._handleOut = SegmentPoint.create(this, arg2);
			}
		} else if (arguments.length == 6) {
			this._point = SegmentPoint.create(this, arg0, arg1);
			this._handleIn = SegmentPoint.create(this, arg2, arg3);
			this._handleOut = SegmentPoint.create(this, arg4, arg5);
		}
		if (!this._handleIn)
			this._handleIn = SegmentPoint.create(this, 0, 0);
		if (!this._handleOut)
			this._handleOut = SegmentPoint.create(this, 0, 0);
	},

	getPoint: function() {
		return this._point;
	},

	setPoint: function(point) {
		point = Point.read(arguments);
		// Do not replace the internal object but update it instead, so
		// references to it are kept alive.
		this._point.set(point.x, point.y);
	},

	getHandleIn: function() {
		return this._handleIn;
	},

	setHandleIn: function(point) {
		point = Point.read(arguments);
		// See #setPoint:
		this._handleIn.set(point.x, point.y);
		// Update corner accordingly
		// this.corner = !this._handleIn.isParallel(this._handleOut);
	},

	getHandleInIfSet: function() {
		return this._handleIn._x == 0 && this._handleIn._y == 0
			? null : this._handleIn;
	},

	getHandleOut: function() {
		return this._handleOut;
	},

	setHandleOut: function(point) {
		point = Point.read(arguments);
		// See #setPoint:
		this._handleOut.set(point.x, point.y);
		// Update corner accordingly
		// this.corner = !this._handleIn.isParallel(this._handleOut);
	},

	getHandleOutIfSet: function() {
		return this._handleOut._x == 0 && this._handleOut._y == 0
			? null : this._handleOut;
	},

	getIndex: function() {
		// TODO: Cache and update indices instead of searching?
		return this._path ? this._path._segments.indexOf(this) : -1;
	},

	getPath: function() {
		return this._path;
	},

	getCurve: function() {
		if (this._path != null) {
			var index = this.getIndex();
			// The last segment of an open path belongs to the last curve
			// TODO: Port back to Scriptographer
			if (!this._path.closed && index == this._path._segments.length - 1)
				index--;
			return this._path.getCurves()[index];
		}
		return null;
	},

	getNext: function() {
		return this._path && this._path._segments[this.getIndex() + 1] || null;
	},

	getPrevious: function() {
		return this._path && this._path._segments[this.getIndex() - 1] || null;
	},

	isSelected: function(/* point */) {
		var point = arguments.length ? arguments[0] : this.point;
		var state = this._selectionState;
		if (point == this.point) {
			return state == SelectionState.POINT;
		} else if (point == this.handleIn) {
			return (state & SelectionState.HANDLE_IN)
					== SelectionState.HANDLE_IN;
		} else if (point == this.handleOut) {
			return (state & SelectionState.HANDLE_OUT)
					== SelectionState.HANDLE_OUT;
		}
		return false;
	},

	setSelected: function(/* pt, selected */) {
		var pt, selected;
		if (arguments.length == 2) {
			// setSelected(pt, selected)
			pt = arguments[0];
			selected = arguments[1];
		} else {
			// setSelected(selected)
			pt = this._point;
			selected = arguments[0];
		}
		if (!this._path)
			return;
		var wasSelected = !!this._selectionState;
		var state = this._selectionState,
			pointSelected = state == SelectionState.POINT,
			handleInSelected = (state & SelectionState.HANDLE_IN)
					== SelectionState.HANDLE_IN,
			handleOutSelected = (state & SelectionState.HANDLE_OUT)
					== SelectionState.HANDLE_OUT,
			previous = this.getPrevious(),
			next = this.getNext(),
			closed = this._path.closed,
			segments = this._path._segments,
			length = segments.length;
		if (length > 1 && closed) {
			if (previous == null)
				previous = segments[length - 1];
			if (next == null)
				next = segments[0];
		}
		if (pt == this._point) {
			if (pointSelected != selected) {
				if (selected) {
					handleInSelected = handleOutSelected = false;
				} else {
					// When deselecting a point, the handles get selected
					// instead depending on the selection state of their
					// neighbors.
					handleInSelected = previous != null
							&& (previous._point.isSelected()
							|| previous._handleOut.isSelected());
					handleOutSelected = next != null
						&& (next._point.isSelected()
						|| next._handleOut.isSelected());
				}
				pointSelected = selected;
			}
		} else if (pt == this._handleIn) {
			if (handleInSelected != selected) {
				// When selecting handles, the point get deselected.
				if (selected)
					pointSelected = false;
				handleInSelected = selected;
			}
		} else if (pt == this._handleOut) {
			if (handleOutSelected != selected) {
				// When selecting handles, the point get deselected.
				if (selected)
					pointSelected = false;
				handleOutSelected = selected;
			}
		}
		this._selectionState = pointSelected
			? SelectionState.POINT
			: handleInSelected
				? handleOutSelected
					? SelectionState.HANDLE_BOTH
					: SelectionState.HANDLE_IN
				: handleOutSelected
					? SelectionState.HANDLE_OUT
					: null;
		// If the selection state of the segment has changed, we need to let
		// it's path know and possibly add or remove it from
		// document._selectedItems
		if (wasSelected == !this._selectionState) {
			var path = this._path,
				selectedItems = path._document._selectedItems;
			if (!this._selectionState) {
				path._selectedSegmentCount--;
				if (path._selectedSegmentCount == 0) {
					var index = selectedItems.indexOf(this);
					selectedItems.slice(index, 1);
				}
			} else {
				path._selectedSegmentCount++;
				if (path._selectedSegmentCount == 1) {
					selectedItems.push(path);
				}
			}
		}
	},

	reverse: function() {
		return new Segment(this._point, this._handleOut, this._handleIn);
	},

	clone: function() {
		return new Segment(this);
	},

	remove: function() {
		if (this._path) {
			this._path._segments.splice(this.getIndex(), 1);
			if (this.isSelected())
				this._path._selectedSegmentCount--;
			return true;
		}
		return false;
	},

	toString: function() {
		return '{ point: ' + this._point
				+ (!this._handleIn.isZero()
					? ', handleIn: ' + this._handleIn : '')
				+ (this._handleOut.isZero()
					? ', handleOut: ' + this._handleOut : '')
				+ ' }';
	},

	_transformCoordinates: function(matrix, coords, change) {
		// Use matrix.transform version() that takes arrays of multiple
		// points for largely improved performance, as no calls to
		// Point.read() and Point constructors are necessary.
		var point = this._point,
			// If a matrix is defined, only transform handles if they are set.
			// This saves some computation time. If no matrix is set, always
			// use the real handles, as we just want to receive a filled
			// coords array for getBounds().
			handleIn =  matrix && this.getHandleInIfSet() || this._handleIn,
			handleOut = matrix && this.getHandleOutIfSet() || this._handleOut,
			x = point._x,
			y = point._y;
		coords[0] = x;
		coords[1] = y;
		var index = 2;
		// We need to convert handles to absolute coordinates in order
		// to transform them.
		if (handleIn) {
			coords[index++] = handleIn._x + x;
			coords[index++] = handleIn._y + y;
		}
		if (handleOut) {
			coords[index++] = handleOut._x + x;
			coords[index++] = handleOut._y + y;
		}
		if (matrix) {
			matrix.transform(coords, 0, coords, 0, index / 2);
			x = coords[0];
			y = coords[1];
			if (change) {
				// If change is true, we need to set the new values back
				point._x = x;
				point._y = y;
				index  = 2;
				if (handleIn) {
					handleIn._x = coords[index++] - x;
					handleIn._y = coords[index++] - y;
				}
				if (handleOut) {
					handleOut._x = coords[index++] - x;
					handleOut._y = coords[index++] - y;
				}
			} else {
				// We want to receive the results in coords, so make sure
				// handleIn and out are defined too, even if they're 0
				if (!handleIn) {
					coords[index++] = x;
					coords[index++] = y;
				}
				if (!handleOut) {
					coords[index++] = x;
					coords[index++] = y;
				}
			}
		}
	}
});
<commit_msg>Segment: add todo.<commit_after>/*
 * Paper.js
 *
 * This file is part of Paper.js, a JavaScript Vector Graphics Library,
 * based on Scriptographer.org and designed to be largely API compatible.
 * http://paperjs.org/
 * http://scriptographer.org/
 *
 * Distributed under the MIT license. See LICENSE file for details.
 *
 * Copyright (c) 2011, Juerg Lehni & Jonathan Puckey
 * http://lehni.org/ & http://jonathanpuckey.com/
 *
 * All rights reserved.
 */

var Segment = this.Segment = Base.extend({
	beans: true,

	initialize: function(arg0, arg1, arg2, arg3, arg4, arg5) {
		if (arguments.length == 0) {
			this._point = SegmentPoint.create(this, 0, 0);
		} else if (arguments.length == 1) {
			// TODO: If beans are not activated, this won't copy from
			// an existing segment. OK?
			if (arg0.point) {
				this._point = SegmentPoint.create(this, arg0.point);
				this._handleIn = SegmentPoint.create(this, arg0.handleIn);
				this._handleOut = SegmentPoint.create(this, arg0.handleOut);
			} else {
				this._point = SegmentPoint.create(this, arg0);
			}
		} else if (arguments.length < 6) {
			if (arguments.length == 2 && !arg1.x) {
				this._point = SegmentPoint.create(this, arg0, arg1);
			} else {
				this._point = SegmentPoint.create(this, arg0);
				// Doesn't matter if these arguments exist, it creates 0, 0
				// points otherwise
				this._handleIn = SegmentPoint.create(this, arg1);
				this._handleOut = SegmentPoint.create(this, arg2);
			}
		} else if (arguments.length == 6) {
			this._point = SegmentPoint.create(this, arg0, arg1);
			this._handleIn = SegmentPoint.create(this, arg2, arg3);
			this._handleOut = SegmentPoint.create(this, arg4, arg5);
		}
		if (!this._handleIn)
			this._handleIn = SegmentPoint.create(this, 0, 0);
		if (!this._handleOut)
			this._handleOut = SegmentPoint.create(this, 0, 0);
	},

	getPoint: function() {
		return this._point;
	},

	setPoint: function(point) {
		point = Point.read(arguments);
		// Do not replace the internal object but update it instead, so
		// references to it are kept alive.
		this._point.set(point.x, point.y);
	},

	getHandleIn: function() {
		return this._handleIn;
	},

	setHandleIn: function(point) {
		point = Point.read(arguments);
		// See #setPoint:
		this._handleIn.set(point.x, point.y);
		// Update corner accordingly
		// this.corner = !this._handleIn.isParallel(this._handleOut);
	},

	getHandleInIfSet: function() {
		return this._handleIn._x == 0 && this._handleIn._y == 0
			? null : this._handleIn;
	},

	getHandleOut: function() {
		return this._handleOut;
	},

	setHandleOut: function(point) {
		point = Point.read(arguments);
		// See #setPoint:
		this._handleOut.set(point.x, point.y);
		// Update corner accordingly
		// this.corner = !this._handleIn.isParallel(this._handleOut);
	},

	getHandleOutIfSet: function() {
		return this._handleOut._x == 0 && this._handleOut._y == 0
			? null : this._handleOut;
	},

	getIndex: function() {
		// TODO: Cache and update indices instead of searching?
		return this._path ? this._path._segments.indexOf(this) : -1;
	},

	getPath: function() {
		return this._path;
	},

	getCurve: function() {
		if (this._path != null) {
			var index = this.getIndex();
			// The last segment of an open path belongs to the last curve
			// TODO: Port back to Scriptographer
			if (!this._path.closed && index == this._path._segments.length - 1)
				index--;
			return this._path.getCurves()[index];
		}
		return null;
	},

	getNext: function() {
		return this._path && this._path._segments[this.getIndex() + 1] || null;
	},

	getPrevious: function() {
		return this._path && this._path._segments[this.getIndex() - 1] || null;
	},

	isSelected: function(/* point */) {
		var point = arguments.length ? arguments[0] : this.point;
		var state = this._selectionState;
		if (point == this.point) {
			return state == SelectionState.POINT;
		} else if (point == this.handleIn) {
			return (state & SelectionState.HANDLE_IN)
					== SelectionState.HANDLE_IN;
		} else if (point == this.handleOut) {
			return (state & SelectionState.HANDLE_OUT)
					== SelectionState.HANDLE_OUT;
		}
		return false;
	},

	// Todo: port setSelected(selected) back to Scriptographer
	setSelected: function(/* pt, selected */) {
		var pt, selected;
		if (arguments.length == 2) {
			// setSelected(pt, selected)
			pt = arguments[0];
			selected = arguments[1];
		} else {
			// setSelected(selected)
			pt = this._point;
			selected = arguments[0];
		}
		if (!this._path)
			return;
		var wasSelected = !!this._selectionState;
		var state = this._selectionState,
			pointSelected = state == SelectionState.POINT,
			handleInSelected = (state & SelectionState.HANDLE_IN)
					== SelectionState.HANDLE_IN,
			handleOutSelected = (state & SelectionState.HANDLE_OUT)
					== SelectionState.HANDLE_OUT,
			previous = this.getPrevious(),
			next = this.getNext(),
			closed = this._path.closed,
			segments = this._path._segments,
			length = segments.length;
		if (length > 1 && closed) {
			if (previous == null)
				previous = segments[length - 1];
			if (next == null)
				next = segments[0];
		}
		if (pt == this._point) {
			if (pointSelected != selected) {
				if (selected) {
					handleInSelected = handleOutSelected = false;
				} else {
					// When deselecting a point, the handles get selected
					// instead depending on the selection state of their
					// neighbors.
					handleInSelected = previous != null
							&& (previous._point.isSelected()
							|| previous._handleOut.isSelected());
					handleOutSelected = next != null
						&& (next._point.isSelected()
						|| next._handleOut.isSelected());
				}
				pointSelected = selected;
			}
		} else if (pt == this._handleIn) {
			if (handleInSelected != selected) {
				// When selecting handles, the point get deselected.
				if (selected)
					pointSelected = false;
				handleInSelected = selected;
			}
		} else if (pt == this._handleOut) {
			if (handleOutSelected != selected) {
				// When selecting handles, the point get deselected.
				if (selected)
					pointSelected = false;
				handleOutSelected = selected;
			}
		}
		this._selectionState = pointSelected
			? SelectionState.POINT
			: handleInSelected
				? handleOutSelected
					? SelectionState.HANDLE_BOTH
					: SelectionState.HANDLE_IN
				: handleOutSelected
					? SelectionState.HANDLE_OUT
					: null;
		// If the selection state of the segment has changed, we need to let
		// it's path know and possibly add or remove it from
		// document._selectedItems
		if (wasSelected == !this._selectionState) {
			var path = this._path,
				selectedItems = path._document._selectedItems;
			if (!this._selectionState) {
				path._selectedSegmentCount--;
				if (path._selectedSegmentCount == 0) {
					var index = selectedItems.indexOf(this);
					selectedItems.slice(index, 1);
				}
			} else {
				path._selectedSegmentCount++;
				if (path._selectedSegmentCount == 1) {
					selectedItems.push(path);
				}
			}
		}
	},

	reverse: function() {
		return new Segment(this._point, this._handleOut, this._handleIn);
	},

	clone: function() {
		return new Segment(this);
	},

	remove: function() {
		if (this._path) {
			this._path._segments.splice(this.getIndex(), 1);
			if (this.isSelected())
				this._path._selectedSegmentCount--;
			return true;
		}
		return false;
	},

	toString: function() {
		return '{ point: ' + this._point
				+ (!this._handleIn.isZero()
					? ', handleIn: ' + this._handleIn : '')
				+ (this._handleOut.isZero()
					? ', handleOut: ' + this._handleOut : '')
				+ ' }';
	},

	_transformCoordinates: function(matrix, coords, change) {
		// Use matrix.transform version() that takes arrays of multiple
		// points for largely improved performance, as no calls to
		// Point.read() and Point constructors are necessary.
		var point = this._point,
			// If a matrix is defined, only transform handles if they are set.
			// This saves some computation time. If no matrix is set, always
			// use the real handles, as we just want to receive a filled
			// coords array for getBounds().
			handleIn =  matrix && this.getHandleInIfSet() || this._handleIn,
			handleOut = matrix && this.getHandleOutIfSet() || this._handleOut,
			x = point._x,
			y = point._y;
		coords[0] = x;
		coords[1] = y;
		var index = 2;
		// We need to convert handles to absolute coordinates in order
		// to transform them.
		if (handleIn) {
			coords[index++] = handleIn._x + x;
			coords[index++] = handleIn._y + y;
		}
		if (handleOut) {
			coords[index++] = handleOut._x + x;
			coords[index++] = handleOut._y + y;
		}
		if (matrix) {
			matrix.transform(coords, 0, coords, 0, index / 2);
			x = coords[0];
			y = coords[1];
			if (change) {
				// If change is true, we need to set the new values back
				point._x = x;
				point._y = y;
				index  = 2;
				if (handleIn) {
					handleIn._x = coords[index++] - x;
					handleIn._y = coords[index++] - y;
				}
				if (handleOut) {
					handleOut._x = coords[index++] - x;
					handleOut._y = coords[index++] - y;
				}
			} else {
				// We want to receive the results in coords, so make sure
				// handleIn and out are defined too, even if they're 0
				if (!handleIn) {
					coords[index++] = x;
					coords[index++] = y;
				}
				if (!handleOut) {
					coords[index++] = x;
					coords[index++] = y;
				}
			}
		}
	}
});
<|endoftext|>