<commit_before>// Document
// HTMLDocument is an extension of Document.  If the browser has HTMLDocument but not Document, the former will suffice as an alias for the latter.
if (!this.Document){this.Document = this.HTMLDocument; }

// Element
if (!window.HTMLElement) { window.HTMLElement = window.Element; }

// Date.now
if(!Date.now){ Date.now = function now() { return new Date().getTime(); }; }

// performance.now
(function(){
	if ("performance" in window == false) {
		window.performance = {};
	}

	if ("now" in window.performance == false){
		var nowOffset = Date.now();

		window.performance.now = function now(){
			return Date.now() - nowOffset;
		}
	}
})();

// Array.prototype.indexOf
if (!Array.prototype.indexOf) {
	Array.prototype.indexOf = function indexOf(searchElement) {
		if (this === undefined || this === null) {
			throw new TypeError(this + 'is not an object');
		}

		var	arraylike = this instanceof String ? this.split('') : this,
			length = Math.max(Math.min(arraylike.length, 9007199254740991), 0) || 0,
			index = Number(arguments[1]) || 0;

		index = (index < 0 ? Math.max(length + index, 0) : index) - 1;

		while (++index < length) {
			if (index in arraylike && arraylike[index] === searchElement) {
				return index;
			}
		}

		return -1;
	};
}

// getComputedStyle
if (!('getComputedStyle' in window)) {
	(function(){
		function getComputedStylePixel(element, property, fontSize) {

			// Internet Explorer sometimes struggles to read currentStyle until the element's document is accessed.
			var value = element.document && element.currentStyle[property].match(/([\d\.]+)(%|cm|em|in|mm|pc|pt|)/) || [0, 0, ''],
				size = value[1],
				suffix = value[2],
				rootSize;

			fontSize = !fontSize ? fontSize : /%|em/.test(suffix) && element.parentElement ? getComputedStylePixel(element.parentElement, 'fontSize', null) : 16;
			rootSize = property == 'fontSize' ? fontSize : /width/i.test(property) ? element.clientWidth : element.clientHeight;

			return suffix == '%' ? size / 100 * rootSize :
				suffix == 'cm' ? size * 0.3937 * 96 :
				suffix == 'em' ? size * fontSize :
				suffix == 'in' ? size * 96 :
				suffix == 'mm' ? size * 0.3937 * 96 / 10 :
				suffix == 'pc' ? size * 12 * 96 / 72 :
				suffix == 'pt' ? size * 96 / 72 :
				size;
		}

		function setShortStyleProperty(style, property) {
			var	borderSuffix = property == 'border' ? 'Width' : '',
				t = property + 'Top' + borderSuffix,
				r = property + 'Right' + borderSuffix,
				b = property + 'Bottom' + borderSuffix,
				l = property + 'Left' + borderSuffix;

			style[property] = (style[t] == style[r] && style[t] == style[b] && style[t] == style[l] ? [ style[t] ] :
							style[t] == style[b] && style[l] == style[r] ? [ style[t], style[r] ] :
							style[l] == style[r] ? [ style[t], style[r], style[b] ] :
							[ style[t], style[r], style[b], style[l] ]).join(' ');
		}

		// <CSSStyleDeclaration>
		function CSSStyleDeclaration(element) {
			var style = this,
			currentStyle = element.currentStyle,
			fontSize = getComputedStylePixel(element, 'fontSize'),
			unCamelCase = function (match) {
				return '-' + match.toLowerCase();
			},
			property;

			for (property in currentStyle) {
				Array.prototype.push.call(style, property == 'styleFloat' ? 'float' : property.replace(/[A-Z]/, unCamelCase));

				if (property == 'width') {
					style[property] = element.offsetWidth + 'px';
				} else if (property == 'height') {
					style[property] = element.offsetHeight + 'px';
				} else if (property == 'styleFloat') {
					style.float = currentStyle[property];
				} else if (/margin.|padding.|border.+W/.test(property) && style[property] != 'auto') {
					style[property] = Math.round(getComputedStylePixel(element, property, fontSize)) + 'px';
				} else if (/^outline/.test(property)) {
					// errors on checking outline
					try {
						style[property] = currentStyle[property];
					} catch (error) {
						style.outlineColor = currentStyle.color;
						style.outlineStyle = style.outlineStyle || 'none';
						style.outlineWidth = style.outlineWidth || '0px';
						style.outline = [style.outlineColor, style.outlineWidth, style.outlineStyle].join(' ');
					}
				} else {
					style[property] = currentStyle[property];
				}
			}

			setShortStyleProperty(style, 'margin');
			setShortStyleProperty(style, 'padding');
			setShortStyleProperty(style, 'border');

			style.fontSize = Math.round(fontSize) + 'px';
		}

		CSSStyleDeclaration.prototype = {
			constructor: CSSStyleDeclaration,
			// <CSSStyleDeclaration>.getPropertyPriority
			getPropertyPriority: function () {
				throw new Error('NotSupportedError: DOM Exception 9');
			},
			// <CSSStyleDeclaration>.getPropertyValue
			getPropertyValue: function (property) {
				return this[property.replace(/-\w/g, function (match) {
					return match[1].toUpperCase();
				})];
			},
			// <CSSStyleDeclaration>.item
			item: function (index) {
				return this[index];
			},
			// <CSSStyleDeclaration>.removeProperty
			removeProperty: function () {
				throw new Error('NoModificationAllowedError: DOM Exception 7');
			},
			// <CSSStyleDeclaration>.setProperty
			setProperty: function () {
				throw new Error('NoModificationAllowedError: DOM Exception 7');
			},
			// <CSSStyleDeclaration>.getPropertyCSSValue
			getPropertyCSSValue: function () {
				throw new Error('NotSupportedError: DOM Exception 9');
			}
		};

		// <Global>.getComputedStyle
		window.getComputedStyle = function getComputedStyle(element) {
			return new CSSStyleDeclaration(element);
		};
	})();
}

// requestAnimationFrame
if (!window.requestAnimationFrame) {

	var	lastTime = Date.now();
	window.requestAnimationFrame = function (callback) {
		'use strict';
		if (typeof callback !== 'function') {
			throw new TypeError(callback + 'is not a function');
		}

		var
		currentTime = Date.now(),
		delay = 16 + lastTime - currentTime;

		if (delay < 0) {
			delay = 0;
		}

		lastTime = currentTime;

		return setTimeout(function () {
			lastTime = Date.now();

			callback(performance.now());
		}, delay);
	};

	window.cancelAnimationFrame = function (id) {
		clearTimeout(id);
	};
}

// Event
if (!window.addEventListener||!Window.prototype.addEventListener) {

	window.Event = Window.prototype.Event = function Event(type, eventInitDict) {
		if (!type) {
			throw new Error('Not enough arguments');
		}

		var event = document.createEventObject();

		event.type = type;
		event.bubbles = eventInitDict && eventInitDict.bubbles !== undefined ? eventInitDict.bubbles : false;
		event.cancelable = eventInitDict && eventInitDict.cancelable !== undefined ? eventInitDict.cancelable : false;

		return event;
	};

	window.addEventListener = Window.prototype.addEventListener = Document.prototype.addEventListener = Element.prototype.addEventListener = function addEventListener() {
		var	element = this,
		type = arguments[0],
		listener = arguments[1];

		if (!element._events) {
			element._events = {};
		}

		if (!element._events[type]) {
			element._events[type] = function (event) {
				var
				list = element._events[event.type].list,
				events = list.slice(),
				index = -1,
				length = events.length,
				eventElement;

				event.preventDefault = function preventDefault() {
					if (event.cancelable !== false) {
						event.returnValue = false;
					}
				};

				event.stopPropagation = function stopPropagation() {
					event.cancelBubble = true;
				};

				event.stopImmediatePropagation = function stopImmediatePropagation() {
					event.cancelBubble = true;
					event.cancelImmediate = true;
				};

				event.currentTarget = element;
				event.relatedTarget = event.fromElement || null;
				event.target = event.target || event.srcElement || element;
				event.timeStamp = new Date().getTime();

				if (event.clientX) {
					event.pageX = event.clientX + document.documentElement.scrollLeft;
					event.pageY = event.clientY + document.documentElement.scrollTop;
				}

				while (++index < length && !event.cancelImmediate) {
					if (index in events) {
						eventElement = events[index];

						if (list.indexOf(eventElement) !== -1 && typeof eventElement === 'function') {
							eventElement.call(element, event);
						}
					}
				}
			};

			element._events[type].list = [];

			if (element.attachEvent) {
				element.attachEvent('on' + type, element._events[type]);
			}
		}

		element._events[type].list.push(listener);
	};

	window.removeEventListener = Window.prototype.removeEventListener = Document.prototype.removeEventListener = Element.prototype.removeEventListener = function removeEventListener() {
		var
		element = this,
		type = arguments[0],
		listener = arguments[1],
		index;

		if (element._events && element._events[type] && element._events[type].list) {
			index = element._events[type].list.indexOf(listener);

			if (index !== -1) {
				element._events[type].list.splice(index, 1);

				if (!element._events[type].list.length) {
					if (element.detachEvent) {
						element.detachEvent('on' + type, element._events[type]);
					}
					delete element._events[type];
				}
			}
		}
	};

	window.dispatchEvent = Window.prototype.dispatchEvent = Document.prototype.dispatchEvent = Element.prototype.dispatchEvent = function dispatchEvent(event) {
		if (!arguments.length) {
			throw new Error('Not enough arguments');
		}

		if (!event || typeof event.type !== 'string') {
			throw new Error('DOM Events Exception 0');
		}

		var element = this, type = event.type;

		try {
			if (!event.bubbles) {
				event.cancelBubble = true;

				var cancelBubbleEvent = function (event) {
					event.cancelBubble = true;

					(element || window).detachEvent('on' + type, cancelBubbleEvent);
				};

				this.attachEvent('on' + type, cancelBubbleEvent);
			}

			this.fireEvent('on' + type, event);
		} catch (error) {
			event.target = element;

			do {
				event.currentTarget = element;

				if ('_events' in element && typeof element._events[type] === 'function') {
					element._events[type].call(element, event);
				}

				if (typeof element['on' + type] === 'function') {
					element['on' + type].call(element, event);
				}

				element = element.nodeType === 9 ? element.parentWindow : element.parentNode;
			} while (element && !event.cancelBubble);
		}

		return true;
	};
}

// CustomEvent
if (!window.CustomEvent) {
	window.CustomEvent = function CustomEvent(type, eventInitDict) {
		var event = new Event(type, eventInitDict);
		event.detail = eventInitDict && eventInitDict.detail || null;
		return event;
	};
}
<commit_msg>Update minifill.js<commit_after>// Document
// HTMLDocument is an extension of Document.  If the browser has HTMLDocument but not Document, the former will suffice as an alias for the latter.
if (!this.Document){this.Document = this.HTMLDocument; }

// Element
if (!window.HTMLElement) { window.HTMLElement = window.Element; }

// Date.now
if(!Date.now){ Date.now = function now() { return new Date().getTime(); }; }

// performance.now
(function(){
	if ("performance" in window == false) {
		window.performance = {};
	}

	if ("now" in window.performance == false){
		var nowOffset = Date.now();

		window.performance.now = function now(){
			return Date.now() - nowOffset;
		}
	}
})();

// Array.prototype.indexOf
if (!Array.prototype.indexOf) {
	Array.prototype.indexOf = function indexOf(searchElement) {
		if (this === undefined || this === null) {
			throw new TypeError(this + 'is not an object');
		}

		var	arraylike = this instanceof String ? this.split('') : this,
			length = Math.max(Math.min(arraylike.length, 9007199254740991), 0) || 0,
			index = Number(arguments[1]) || 0;

		index = (index < 0 ? Math.max(length + index, 0) : index) - 1;

		while (++index < length) {
			if (index in arraylike && arraylike[index] === searchElement) {
				return index;
			}
		}

		return -1;
	};
}

// getComputedStyle
if (!('getComputedStyle' in window)) {
	(function(){
		function getComputedStylePixel(element, property, fontSize) {

			// Internet Explorer sometimes struggles to read currentStyle until the element's document is accessed.
			var value = element.document && element.currentStyle[property].match(/([\d\.]+)(%|cm|em|in|mm|pc|pt|)/) || [0, 0, ''],
				size = value[1],
				suffix = value[2],
				rootSize;

			fontSize = !fontSize ? fontSize : /%|em/.test(suffix) && element.parentElement ? getComputedStylePixel(element.parentElement, 'fontSize', null) : 16;
			rootSize = property == 'fontSize' ? fontSize : /width/i.test(property) ? element.clientWidth : element.clientHeight;

			return suffix == '%' ? size / 100 * rootSize :
				suffix == 'cm' ? size * 0.3937 * 96 :
				suffix == 'em' ? size * fontSize :
				suffix == 'in' ? size * 96 :
				suffix == 'mm' ? size * 0.3937 * 96 / 10 :
				suffix == 'pc' ? size * 12 * 96 / 72 :
				suffix == 'pt' ? size * 96 / 72 :
				size;
		}

		function setShortStyleProperty(style, property) {
			var	borderSuffix = property == 'border' ? 'Width' : '',
				t = property + 'Top' + borderSuffix,
				r = property + 'Right' + borderSuffix,
				b = property + 'Bottom' + borderSuffix,
				l = property + 'Left' + borderSuffix;

			style[property] = (style[t] == style[r] && style[t] == style[b] && style[t] == style[l] ? [ style[t] ] :
							style[t] == style[b] && style[l] == style[r] ? [ style[t], style[r] ] :
							style[l] == style[r] ? [ style[t], style[r], style[b] ] :
							[ style[t], style[r], style[b], style[l] ]).join(' ');
		}

		// <CSSStyleDeclaration>
		function CSSStyleDeclaration(element) {
			var style = this,
			currentStyle = element.currentStyle,
			fontSize = getComputedStylePixel(element, 'fontSize'),
			unCamelCase = function (match) {
				return '-' + match.toLowerCase();
			},
			property;

			for (property in currentStyle) {
				Array.prototype.push.call(style, property == 'styleFloat' ? 'float' : property.replace(/[A-Z]/, unCamelCase));

				if (property == 'width') {
					style[property] = element.offsetWidth + 'px';
				} else if (property == 'height') {
					style[property] = element.offsetHeight + 'px';
				} else if (property == 'styleFloat') {
					style.float = currentStyle[property];
				} else if (/margin.|padding.|border.+W/.test(property) && style[property] != 'auto') {
					style[property] = Math.round(getComputedStylePixel(element, property, fontSize)) + 'px';
				} else if (/^outline/.test(property)) {
					// errors on checking outline
					try {
						style[property] = currentStyle[property];
					} catch (error) {
						style.outlineColor = currentStyle.color;
						style.outlineStyle = style.outlineStyle || 'none';
						style.outlineWidth = style.outlineWidth || '0px';
						style.outline = [style.outlineColor, style.outlineWidth, style.outlineStyle].join(' ');
					}
				} else {
					style[property] = currentStyle[property];
				}
			}

			setShortStyleProperty(style, 'margin');
			setShortStyleProperty(style, 'padding');
			setShortStyleProperty(style, 'border');

			style.fontSize = Math.round(fontSize) + 'px';
		}

		CSSStyleDeclaration.prototype = {
			constructor: CSSStyleDeclaration,
			// <CSSStyleDeclaration>.getPropertyPriority
			getPropertyPriority: function () {
				throw new Error('NotSupportedError: DOM Exception 9');
			},
			// <CSSStyleDeclaration>.getPropertyValue
			getPropertyValue: function (property) {
				return this[property.replace(/-\w/g, function (match) {
					return match[1].toUpperCase();
				})];
			},
			// <CSSStyleDeclaration>.item
			item: function (index) {
				return this[index];
			},
			// <CSSStyleDeclaration>.removeProperty
			removeProperty: function () {
				throw new Error('NoModificationAllowedError: DOM Exception 7');
			},
			// <CSSStyleDeclaration>.setProperty
			setProperty: function () {
				throw new Error('NoModificationAllowedError: DOM Exception 7');
			},
			// <CSSStyleDeclaration>.getPropertyCSSValue
			getPropertyCSSValue: function () {
				throw new Error('NotSupportedError: DOM Exception 9');
			}
		};

		// <Global>.getComputedStyle
		window.getComputedStyle = function getComputedStyle(element) {
			return new CSSStyleDeclaration(element);
		};
	})();
}

// requestAnimationFrame
if (!window.requestAnimationFrame) {

	var	lastTime = Date.now();
	window.requestAnimationFrame = function (callback) {
		'use strict';
		if (typeof callback !== 'function') {
			throw new TypeError(callback + 'is not a function');
		}

		var
		currentTime = Date.now(),
		delay = 16 + lastTime - currentTime;

		if (delay < 0) {
			delay = 0;
		}

		lastTime = currentTime;

		return setTimeout(function () {
			lastTime = Date.now();

			callback(performance.now());
		}, delay);
	};

	window.cancelAnimationFrame = function (id) {
		clearTimeout(id);
	};
}

// Event
if (!window.Event||!Window.prototype.Event) {
	(function (){

		window.Event = Window.prototype.Event = function Event(type, eventInitDict) {
			if (!type) {
				throw new Error('Not enough arguments');
			}

			var event = document.createEventObject();

			event.type = type;
			event.bubbles = eventInitDict && eventInitDict.bubbles !== undefined ? eventInitDict.bubbles : false;
			event.cancelable = eventInitDict && eventInitDict.cancelable !== undefined ? eventInitDict.cancelable : false;

			return event;
		};

		// addEventListener
		window.addEventListener = Window.prototype.addEventListener = Document.prototype.addEventListener = Element.prototype.addEventListener = function addEventListener() {
			var	element = this,
			type = arguments[0],
			listener = arguments[1];

			if (!element._events) {
				element._events = {};
			}

			if (!element._events[type]) {
				element._events[type] = function (event) {
					var
					list = element._events[event.type].list,
					events = list.slice(),
					index = -1,
					length = events.length,
					eventElement;

					event.preventDefault = function preventDefault() {
						if (event.cancelable !== false) {
							event.returnValue = false;
						}
					};

					event.stopPropagation = function stopPropagation() {
						event.cancelBubble = true;
					};

					event.stopImmediatePropagation = function stopImmediatePropagation() {
						event.cancelBubble = true;
						event.cancelImmediate = true;
					};

					event.currentTarget = element;
					event.relatedTarget = event.fromElement || null;
					event.target = event.target || event.srcElement || element;
					event.timeStamp = new Date().getTime();

					if (event.clientX) {
						event.pageX = event.clientX + document.documentElement.scrollLeft;
						event.pageY = event.clientY + document.documentElement.scrollTop;
					}

					while (++index < length && !event.cancelImmediate) {
						if (index in events) {
							eventElement = events[index];

							if (list.indexOf(eventElement) !== -1 && typeof eventElement === 'function') {
								eventElement.call(element, event);
							}
						}
					}
				};

				element._events[type].list = [];

				if (element.attachEvent) {
					element.attachEvent('on' + type, element._events[type]);
				}
			}

			element._events[type].list.push(listener);
		};

		window.removeEventListener = Window.prototype.removeEventListener = Document.prototype.removeEventListener = Element.prototype.removeEventListener = function removeEventListener() {
			var
			element = this,
			type = arguments[0],
			listener = arguments[1],
			index;

			if (element._events && element._events[type] && element._events[type].list) {
				index = element._events[type].list.indexOf(listener);

				if (index !== -1) {
					element._events[type].list.splice(index, 1);

					if (!element._events[type].list.length) {
						if (element.detachEvent) {
							element.detachEvent('on' + type, element._events[type]);
						}
						delete element._events[type];
					}
				}
			}
		};

		window.dispatchEvent = Window.prototype.dispatchEvent = Document.prototype.dispatchEvent = Element.prototype.dispatchEvent = function dispatchEvent(event) {
			if (!arguments.length) {
				throw new Error('Not enough arguments');
			}

			if (!event || typeof event.type !== 'string') {
				throw new Error('DOM Events Exception 0');
			}

			var element = this, type = event.type;

			try {
				if (!event.bubbles) {
					event.cancelBubble = true;

					var cancelBubbleEvent = function (event) {
						event.cancelBubble = true;

						(element || window).detachEvent('on' + type, cancelBubbleEvent);
					};

					this.attachEvent('on' + type, cancelBubbleEvent);
				}

				this.fireEvent('on' + type, event);
			} catch (error) {
				event.target = element;

				do {
					event.currentTarget = element;

					if ('_events' in element && typeof element._events[type] === 'function') {
						element._events[type].call(element, event);
					}

					if (typeof element['on' + type] === 'function') {
						element['on' + type].call(element, event);
					}

					element = element.nodeType === 9 ? element.parentWindow : element.parentNode;
				} while (element && !event.cancelBubble);
			}

			return true;
		};

		// CustomEvent
		window.CustomEvent = function CustomEvent(type, eventInitDict) {
			var event = new Event(type, eventInitDict);
			event.detail = eventInitDict && eventInitDict.detail || null;
			return event;
		};

	})()
}
<|endoftext|>


<commit_before>// Copyright (c) 2015 Intel Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

var DepthPhoto = function(object_id) {
  common.BindingObject.call(this, object_id ? object_id : common.getUniqueId());

  if (object_id == undefined)
    internal.postMessage('depthPhotoConstructor', [this._id]);

  function wrapRGB32ImageArgs(args) {
    if (args[0].format != 'RGB32')
      return null;
    var length = 2 * 4 + args[0].width * args[0].height * 4;
    var arrayBuffer = new ArrayBuffer(length);
    var view = new Int32Array(arrayBuffer, 0, 2);
    view[0] = args[0].width;
    view[1] = args[0].height;
    var view = new Uint8Array(arrayBuffer, 2 * 4);
    for (var i = 0; i < args[0].data.length; i++) {
      view[i] = args[0].data[i];
    }
    return arrayBuffer;
  };

  function wrapDepthImageArgs(args) {
    if (args[0].format != 'DEPTH')
      return null;
    var length = 2 * 4 + args[0].width * args[0].height * 2;
    var arrayBuffer = new ArrayBuffer(length);
    var view = new Int32Array(arrayBuffer, 0, 2);
    view[0] = args[0].width;
    view[1] = args[0].height;
    var view = new Uint16Array(arrayBuffer, 2 * 4);
    for (var i = 0; i < args[0].data.length; i++) {
      view[i] = args[0].data[i];
    }
    return arrayBuffer;
  };

  function wrapColorImageReturns(data) {
    var int32_array = new Int32Array(data);
    // int32_array[0] is the callback id.
    var width = int32_array[1];
    var height = int32_array[2];
    // 3 int32 (4 bytes) values.
    var header_byte_offset = 3 * 4;
    var buffer = new Uint8Array(data, header_byte_offset, width * height * 4);
    return { format: 'RGB32', width: width, height: height, data: buffer };
  };

  function wrapDepthImageReturns(data) {
    var int32_array = new Int32Array(data);
    // int32_array[0] is the callback id.
    var width = int32_array[1];
    var height = int32_array[2];
    // 3 int32 (4 bytes) values.
    var header_byte_offset = 3 * 4;
    var buffer = new Uint16Array(data, header_byte_offset, width * height);
    return { format: 'DEPTH', width: width, height: height, data: buffer };
  };

  function wrapPhotoReturns(data) {
    return new DepthPhoto(data.objectId);
  };

  function wrapBlobArg(data) {
    return new Promise(function(resolve, reject) {
      var reader = new FileReader();
      reader.onload = function(e) {
        var buffer = e.target.result;
        resolve(buffer);
      };
      reader.readAsArrayBuffer(data[0]);
    });
  }

  function wrapRawDataReturns(data) {
    // 1 int32 (4 bytes) value (callback id).
    var dataBuffer = data.slice(4);
    var blob = new Blob([dataBuffer], { type: 'image/jpeg' });
    return blob;
  };

  this._addBinaryMethodWithPromise2('loadXDM', wrapBlobArg);
  this._addMethodWithPromise('saveXDM', null, wrapRawDataReturns);
  this._addMethodWithPromise('queryReferenceImage', null, wrapColorImageReturns);
  this._addMethodWithPromise('queryOriginalImage', null, wrapColorImageReturns);
  this._addMethodWithPromise('queryDepthImage', null, wrapDepthImageReturns);
  this._addMethodWithPromise('queryRawDepthImage', null, wrapDepthImageReturns);
  this._addBinaryMethodWithPromise('setReferenceImage', wrapRGB32ImageArgs);
  this._addBinaryMethodWithPromise('setOriginalImage', wrapRGB32ImageArgs);
  this._addBinaryMethodWithPromise('setDepthImage', wrapDepthImageArgs);
  this._addBinaryMethodWithPromise('setRawDepthImage', wrapDepthImageArgs);
  this._addMethodWithPromise('clone', null, wrapPhotoReturns);

  Object.defineProperties(this, {
    'photoId': {
      value: object_id ? object_id : this._id,
      enumerable: true,
    },
  });
};

DepthPhoto.prototype = new common.EventTargetPrototype();
DepthPhoto.prototype.constructor = DepthPhoto;
exports.DepthPhoto = DepthPhoto;

var EnhancedPhotography = function(object_id) {
  common.BindingObject.call(this, common.getUniqueId());
  common.EventTarget.call(this);

  if (object_id == undefined)
    internal.postMessage('enhancedPhotographyConstructor', [this._id]);

  function wrapArgs(data) {
    data[0] = { objectId: data[0].photoId };
    return data;
  };

  function wrapImageArgs(args) {
    args[0] = { objectId: args[0].photoId };
    if ((args[1].data instanceof Uint8Array) ||
        (args[1].data instanceof Uint8ClampedArray)) {
      var uint8_array = args[1].data;
      var buffer = Array.prototype.slice.call(uint8_array);
      args[1].data = buffer;
    }
    return args;
  };

  function wrapDepthBlendArgsToArrayBuffer(args) {
    var photoId = args[0].photoId;
    var image = args[1];
    var point = args[2];
    var depth = args[3];
    var rotation = args[4];
    var scale = args[5];
    var alignedPhotoIdLen = photoId.length + 4 - photoId.length % 4;

    if (image.format != 'RGB32')
      return null;

    const bytesPerInt = 4;
    const bytesPerFloat = 4;
    // photoIdLen(int), photoId(string), image[imageWidth(int) imageHeight(int) imageData],
    // point[pointX PointY], depth, rotation[pitch yaw roll], scale
    var length = bytesPerInt + alignedPhotoIdLen + bytesPerInt * 2 + image.data.length +
        bytesPerInt * 2 + bytesPerInt + bytesPerInt * 3 + bytesPerFloat;
    var arrayBuffer = new ArrayBuffer(length);
    var offset = 0;
    var view = new Int32Array(arrayBuffer, offset, 1);
    view[0] = photoId.length;
    offset += bytesPerInt;

    view = new Uint8Array(arrayBuffer, offset, photoId.length);
    for (var i = 0; i < photoId.length; i++) {
      view[i] = photoId.charCodeAt(i);
    }
    offset += alignedPhotoIdLen;

    view = new Int32Array(arrayBuffer, offset, 2);
    view[0] = image.width;
    view[1] = image.height;
    offset += bytesPerInt * 2;

    view = new Uint8Array(arrayBuffer, offset, image.data.length);
    for (var i = 0; i < image.data.length; i++) {
      view[i] = image.data[i];
    }
    offset += image.data.length;

    view = new Int32Array(arrayBuffer, offset, 6);
    view[0] = point.x;
    view[1] = point.y;
    view[2] = depth;
    view[3] = rotation.pitch;
    view[4] = rotation.yaw;
    view[5] = rotation.roll;
    offset += bytesPerInt * 6;

    view = new Float32Array(arrayBuffer, offset, 1);
    view[0] = scale;

    return arrayBuffer;
  };

  function wrapReturns(data) {
    return new DepthPhoto(data.objectId);
  };

  function wrapRGB32ImageReturns(data) {
    var int32_array = new Int32Array(data);
    // int32_array[0] is the callback id.
    var width = int32_array[1];
    var height = int32_array[2];
    // 3 int32 (4 bytes) values.
    var header_byte_offset = 3 * 4;
    var buffer = new Uint8Array(data, header_byte_offset, width * height * 4);
    return { format: 'RGB32', width: width, height: height, data: buffer };
  };

  function wrapF32ImageReturns(data) {
    // 3 int32 (4 bytes) values.
    var header_byte_offset = 3 * 4;
    var int32_array = new Int32Array(data, 0, header_byte_offset);
    // int32_array[0] is the callback id.
    var width = int32_array[1];
    var height = int32_array[2];
    var buffer = new Float32Array(data, header_byte_offset, width * height);
    return { format: 'DEPTH_F32', width: width, height: height, data: buffer };
  };

  function wrapY8ImageReturns(data) {
    // 3 int32 (4 bytes) values.
    var header_byte_offset = 3 * 4;
    var int32_array = new Int32Array(data, 0, header_byte_offset);
    // int32_array[0] is the callback id.
    var width = int32_array[1];
    var height = int32_array[2];
    var buffer = new Uint8Array(data, header_byte_offset, width * height);
    return { format: 'Y8', width: width, height: height, data: buffer };
  };

  this._addMethodWithPromise('startPreview');
  this._addMethodWithPromise('stopPreview');
  this._addMethodWithPromise('getPreviewImage', null, wrapRGB32ImageReturns);
  this._addMethodWithPromise('takePhoto', null, wrapReturns);

  this._addMethodWithPromise('measureDistance', wrapArgs);
  this._addMethodWithPromise('depthRefocus', wrapArgs, wrapReturns);
  this._addMethodWithPromise('depthResize', wrapArgs, wrapReturns);
  this._addMethodWithPromise('enhanceDepth', wrapArgs, wrapReturns);
  this._addMethodWithPromise('pasteOnPlane', wrapImageArgs, wrapReturns);
  this._addMethodWithPromise('computeMaskFromCoordinate', wrapArgs, wrapF32ImageReturns);
  this._addMethodWithPromise('computeMaskFromThreshold', wrapArgs, wrapF32ImageReturns);
  this._addBinaryMethodWithPromise('depthBlend', wrapDepthBlendArgsToArrayBuffer, wrapReturns);
  this._addMethodWithPromise('objectSegment', wrapArgs, wrapY8ImageReturns);
  this._addMethodWithPromise('refineMask', null, wrapY8ImageReturns);
  this._addMethodWithPromise('initMotionEffect', wrapArgs);
  this._addMethodWithPromise('applyMotionEffect', null, wrapRGB32ImageReturns);

  this._addEvent('error');
  this._addEvent('preview');
};

EnhancedPhotography.prototype = new common.EventTargetPrototype();
EnhancedPhotography.prototype.constructor = EnhancedPhotography;

exports.EnhancedPhoto = new EnhancedPhotography();
<commit_msg>[EP] Enhance js code<commit_after>// Copyright (c) 2015 Intel Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

const bytesPerInt32 = 4;
const bytesPerRGB32Pixel = 4;
const bytesPerDEPTHPixel = 2;

function wrapRGB32ImageReturns(data) {
  var int32_array = new Int32Array(data, 0, 3);
  // int32_array[0] is the callback id.
  var width = int32_array[1];
  var height = int32_array[2];
  // 3 int32 (4 bytes) values.
  var header_byte_offset = 3 * bytesPerInt32;
  var buffer = new Uint8Array(data, header_byte_offset, width * height * bytesPerRGB32Pixel);
  return { format: 'RGB32', width: width, height: height, data: buffer };
}

var DepthPhoto = function(object_id) {
  common.BindingObject.call(this, object_id ? object_id : common.getUniqueId());

  if (object_id == undefined)
    internal.postMessage('depthPhotoConstructor', [this._id]);

  function wrapRGB32ImageArgs(args) {
    if (args[0].format != 'RGB32')
      return null;
    var length = 2 * bytesPerInt32 + args[0].width * args[0].height * bytesPerRGB32Pixel;
    var arrayBuffer = new ArrayBuffer(length);
    var view = new Int32Array(arrayBuffer, 0, 2);
    view[0] = args[0].width;
    view[1] = args[0].height;
    var view = new Uint8Array(arrayBuffer, 2 * bytesPerInt32);
    for (var i = 0; i < args[0].data.length; i++) {
      view[i] = args[0].data[i];
    }
    return arrayBuffer;
  };

  function wrapDepthImageArgs(args) {
    if (args[0].format != 'DEPTH')
      return null;
    var length = 2 * bytesPerInt32 + args[0].width * args[0].height * bytesPerDEPTHPixel;
    var arrayBuffer = new ArrayBuffer(length);
    var view = new Int32Array(arrayBuffer, 0, 2);
    view[0] = args[0].width;
    view[1] = args[0].height;
    var view = new Uint16Array(arrayBuffer, 2 * bytesPerInt32);
    for (var i = 0; i < args[0].data.length; i++) {
      view[i] = args[0].data[i];
    }
    return arrayBuffer;
  };

  function wrapDepthImageReturns(data) {
    var int32_array = new Int32Array(data, 0, 3);
    // int32_array[0] is the callback id.
    var width = int32_array[1];
    var height = int32_array[2];
    // 3 int32 (4 bytes) values.
    var header_byte_offset = 3 * bytesPerInt32;
    var buffer = new Uint16Array(data, header_byte_offset, width * height);
    return { format: 'DEPTH', width: width, height: height, data: buffer };
  };

  function wrapPhotoReturns(data) {
    return new DepthPhoto(data.objectId);
  };

  function wrapBlobArg(data) {
    return new Promise(function(resolve, reject) {
      var reader = new FileReader();
      reader.onload = function(e) {
        var buffer = e.target.result;
        resolve(buffer);
      };
      reader.readAsArrayBuffer(data[0]);
    });
  }

  function wrapRawDataReturns(data) {
    // 1 int32 (4 bytes) value (callback id).
    var dataBuffer = data.slice(4);
    var blob = new Blob([dataBuffer], { type: 'image/jpeg' });
    return blob;
  };

  this._addBinaryMethodWithPromise2('loadXDM', wrapBlobArg);
  this._addMethodWithPromise('saveXDM', null, wrapRawDataReturns);
  this._addMethodWithPromise('queryReferenceImage', null, wrapRGB32ImageReturns);
  this._addMethodWithPromise('queryOriginalImage', null, wrapRGB32ImageReturns);
  this._addMethodWithPromise('queryDepthImage', null, wrapDepthImageReturns);
  this._addMethodWithPromise('queryRawDepthImage', null, wrapDepthImageReturns);
  this._addBinaryMethodWithPromise('setReferenceImage', wrapRGB32ImageArgs);
  this._addBinaryMethodWithPromise('setOriginalImage', wrapRGB32ImageArgs);
  this._addBinaryMethodWithPromise('setDepthImage', wrapDepthImageArgs);
  this._addBinaryMethodWithPromise('setRawDepthImage', wrapDepthImageArgs);
  this._addMethodWithPromise('clone', null, wrapPhotoReturns);

  Object.defineProperties(this, {
    'photoId': {
      value: object_id ? object_id : this._id,
      enumerable: true,
    },
  });
};

DepthPhoto.prototype = new common.EventTargetPrototype();
DepthPhoto.prototype.constructor = DepthPhoto;
exports.DepthPhoto = DepthPhoto;

var EnhancedPhotography = function(object_id) {
  common.BindingObject.call(this, common.getUniqueId());
  common.EventTarget.call(this);

  if (object_id == undefined)
    internal.postMessage('enhancedPhotographyConstructor', [this._id]);

  function wrapArgs(data) {
    data[0] = { objectId: data[0].photoId };
    return data;
  };

  function wrapImageArgs(args) {
    args[0] = { objectId: args[0].photoId };
    if ((args[1].data instanceof Uint8Array) ||
        (args[1].data instanceof Uint8ClampedArray)) {
      var uint8_array = args[1].data;
      var buffer = Array.prototype.slice.call(uint8_array);
      args[1].data = buffer;
    }
    return args;
  };

  function wrapDepthBlendArgsToArrayBuffer(args) {
    var photoId = args[0].photoId;
    var image = args[1];
    var point = args[2];
    var depth = args[3];
    var rotation = args[4];
    var scale = args[5];
    var alignedPhotoIdLen = photoId.length + 4 - photoId.length % 4;

    if (image.format != 'RGB32')
      return null;

    const bytesPerFloat = 4;
    // photoIdLen(int), photoId(string), image[imageWidth(int) imageHeight(int) imageData],
    // point[pointX PointY], depth, rotation[pitch yaw roll], scale
    var length = bytesPerInt32 + alignedPhotoIdLen + bytesPerInt32 * 2 + image.data.length +
        bytesPerInt32 * 2 + bytesPerInt32 + bytesPerInt32 * 3 + bytesPerFloat;
    var arrayBuffer = new ArrayBuffer(length);
    var offset = 0;
    var view = new Int32Array(arrayBuffer, offset, 1);
    view[0] = photoId.length;
    offset += bytesPerInt32;

    view = new Uint8Array(arrayBuffer, offset, photoId.length);
    for (var i = 0; i < photoId.length; i++) {
      view[i] = photoId.charCodeAt(i);
    }
    offset += alignedPhotoIdLen;

    view = new Int32Array(arrayBuffer, offset, 2);
    view[0] = image.width;
    view[1] = image.height;
    offset += bytesPerInt32 * 2;

    view = new Uint8Array(arrayBuffer, offset, image.data.length);
    for (var i = 0; i < image.data.length; i++) {
      view[i] = image.data[i];
    }
    offset += image.data.length;

    view = new Int32Array(arrayBuffer, offset, 6);
    view[0] = point.x;
    view[1] = point.y;
    view[2] = depth;
    view[3] = rotation.pitch;
    view[4] = rotation.yaw;
    view[5] = rotation.roll;
    offset += bytesPerInt32 * 6;

    view = new Float32Array(arrayBuffer, offset, 1);
    view[0] = scale;

    return arrayBuffer;
  };

  function wrapReturns(data) {
    return new DepthPhoto(data.objectId);
  };

  function wrapF32ImageReturns(data) {
    // 3 int32 (4 bytes) values.
    var header_byte_offset = 3 * bytesPerInt32;
    var int32_array = new Int32Array(data, 0, 3);
    // int32_array[0] is the callback id.
    var width = int32_array[1];
    var height = int32_array[2];
    var buffer = new Float32Array(data, header_byte_offset, width * height);
    return { format: 'DEPTH_F32', width: width, height: height, data: buffer };
  };

  function wrapY8ImageReturns(data) {
    // 3 int32 (4 bytes) values.
    var header_byte_offset = 3 * bytesPerInt32;
    var int32_array = new Int32Array(data, 0, 3);
    // int32_array[0] is the callback id.
    var width = int32_array[1];
    var height = int32_array[2];
    var buffer = new Uint8Array(data, header_byte_offset, width * height);
    return { format: 'Y8', width: width, height: height, data: buffer };
  };

  this._addMethodWithPromise('startPreview');
  this._addMethodWithPromise('stopPreview');
  this._addMethodWithPromise('getPreviewImage', null, wrapRGB32ImageReturns);
  this._addMethodWithPromise('takePhoto', null, wrapReturns);

  this._addMethodWithPromise('measureDistance', wrapArgs);
  this._addMethodWithPromise('depthRefocus', wrapArgs, wrapReturns);
  this._addMethodWithPromise('depthResize', wrapArgs, wrapReturns);
  this._addMethodWithPromise('enhanceDepth', wrapArgs, wrapReturns);
  this._addMethodWithPromise('pasteOnPlane', wrapImageArgs, wrapReturns);
  this._addMethodWithPromise('computeMaskFromCoordinate', wrapArgs, wrapF32ImageReturns);
  this._addMethodWithPromise('computeMaskFromThreshold', wrapArgs, wrapF32ImageReturns);
  this._addBinaryMethodWithPromise('depthBlend', wrapDepthBlendArgsToArrayBuffer, wrapReturns);
  this._addMethodWithPromise('objectSegment', wrapArgs, wrapY8ImageReturns);
  this._addMethodWithPromise('refineMask', null, wrapY8ImageReturns);
  this._addMethodWithPromise('initMotionEffect', wrapArgs);
  this._addMethodWithPromise('applyMotionEffect', null, wrapRGB32ImageReturns);

  this._addEvent('error');
  this._addEvent('preview');
};

EnhancedPhotography.prototype = new common.EventTargetPrototype();
EnhancedPhotography.prototype.constructor = EnhancedPhotography;

exports.EnhancedPhoto = new EnhancedPhotography();
<|endoftext|>


<commit_before>'use strict';

angular.module('core').controller('MasterController', ['$scope', 'TrialData', 'hotkeys',
  function($scope, TrialData, hotkeys) {
    $scope.trialDataJson = function() {
      return TrialData.toJson();
    };

    // Global debug mode flag
    $scope.debugMode = false;

    // Setup hotkeys
    hotkeys.add({
      combo: 'd d',
      description: 'Toggle debug mode',
      callback: function() {
        $scope.debugMode = !$scope.debugMode;

        var alertMessage = 'Debug mode has been ';
        if ($scope.debugMode) {
          alertMessage += 'enabled.';
        } else {
          alertMessage += 'disabled.';
        }

        $scope.addAlert({type: 'info', msg: alertMessage});
      }
    });

    // Store/show alerts
    $scope.alerts = [];

    $scope.addAlert = function(alert) {

      var errorExists = false;
      for (var i = 0; i < $scope.alerts.length; i++) {
        if ($scope.alerts[i].msg === alert.msg && $scope.alerts[i].type === alert.type) {
          errorExists = true;
          break;
        }
      }

      if (!errorExists) {
        $scope.alerts.push(alert);
      }
    };

    $scope.closeAlert = function(index) {
      $scope.alerts.splice(index, 1);
    };

    $scope.addGenericErrorAlert = function() {
      $scope.addAlert({type: 'danger', msg: 'There seems to be a problem. Please contact a mediator for assistance.'});
    };

    $scope.blackoutClass = false;
    $scope.hideBody = function() {
      $scope.blackoutClass = true;
    };
    $scope.showBody = function() {
      $scope.blackoutClass = false;
    };
    $scope.toggleBodyVisibility = function() {
      $scope.blackoutClass = !$scope.blackoutClass;
    };
  }
]);<commit_msg>Use $scope.$apply when blacking out<commit_after>'use strict';

angular.module('core').controller('MasterController', ['$scope', 'TrialData', 'hotkeys',
  function($scope, TrialData, hotkeys) {
    $scope.trialDataJson = function() {
      return TrialData.toJson();
    };

    // Global debug mode flag
    $scope.debugMode = false;

    // Setup hotkeys
    hotkeys.add({
      combo: 'd d',
      description: 'Toggle debug mode',
      callback: function() {
        $scope.debugMode = !$scope.debugMode;

        var alertMessage = 'Debug mode has been ';
        if ($scope.debugMode) {
          alertMessage += 'enabled.';
        } else {
          alertMessage += 'disabled.';
        }

        $scope.addAlert({type: 'info', msg: alertMessage});
      }
    });

    // Store/show alerts
    $scope.alerts = [];

    $scope.addAlert = function(alert) {

      var errorExists = false;
      for (var i = 0; i < $scope.alerts.length; i++) {
        if ($scope.alerts[i].msg === alert.msg && $scope.alerts[i].type === alert.type) {
          errorExists = true;
          break;
        }
      }

      if (!errorExists) {
        $scope.alerts.push(alert);
      }
    };

    $scope.closeAlert = function(index) {
      $scope.alerts.splice(index, 1);
    };

    $scope.addGenericErrorAlert = function() {
      $scope.addAlert({type: 'danger', msg: 'There seems to be a problem. Please contact a mediator for assistance.'});
    };

    $scope.blackoutClass = false;
    $scope.hideBody = function() {
      $scope.$apply(function() {
        $scope.blackoutClass = true;
      });
    };
    $scope.showBody = function() {
      $scope.$apply(function() {
        $scope.blackoutClass = false;
      });
    };
    $scope.toggleBodyVisibility = function() {
      $scope.$apply(function() {
        $scope.blackoutClass = !$scope.blackoutClass;
      });
    };
  }
]);<|endoftext|>


<commit_before>'use strict';
angular.module('stats').directive('adopterMap', function(Contacts, googleService) {
    var addresses = [];
    var latlong = [];
    var adopterWithAddress = [];
    var streets = [];
    var citiesStatesZipCodes = [];
    // directive link function
    var link = function(scope, element, attrs) {
        googleService.google().then(function(google) {
            console.log(google);
            var geocoder = new google.maps.Geocoder();
            var map, infoWindow;
            var markers = [];

            // map config
            var mapOptions = {
                center: new google.maps.LatLng(30, -78),
                zoom: 4,
                mapTypeId: google.maps.MapTypeId.ROADMAP,
                scrollwheel: false
            };

            // init the map
            function initMap() {
                var adopters = Contacts.getAllAdopters(function() {
                    var i;
                    for(i = 0; i < adopters.length; i++) {
                        adopterWithAddress.push(adopters[i].firstName + ' ' + adopters[i].surname);
                        streets.push(adopters[i].address);
                        citiesStatesZipCodes.push(adopters[i].city + ', ' + adopters[i].state + ' ' + adopters[i].zipCode);
                        addresses.push(adopters[i]. address + ', ' + adopters[i].city + ', ' + adopters[i].state + ' ' + adopters[i].zipCode);
                    }
                    i = 0;
                    for(var j = 0; j < addresses.length; j++) {
                        console.log('5');
                        codeAddress(addresses[j], i);
                        i = i + 1;
                    }

                });

                if (map === void 0) {
                    map = new google.maps.Map(element[0], mapOptions);
                }
            }

            // place a marker
            function setMarker(map, position, title, content) {
                googleService.google().then(function(google) {
                    var marker;
                    var markerOptions = {
                        position: position,
                        map: map,
                        title: title,
                        icon: 'https://maps.google.com/mapfiles/ms/icons/blue-dot.png'
                    };

                    marker = new google.maps.Marker(markerOptions);
                    markers.push(marker); // add marker to array

                    google.maps.event.addListener(marker, 'click', function () {
                        // close window if not undefined
                        if (infoWindow !== void 0) {
                            infoWindow.close();
                        }
                        // create new window
                        var infoWindowOptions = {
                            content: content
                        };
                        infoWindow = new google.maps.InfoWindow(infoWindowOptions);
                        infoWindow.open(map, marker);
                    });
                });
            }
            function codeAddress(address, i) {
                geocoder.geocode( { 'address': address}, function(results, status) {
                    if (status === google.maps.GeocoderStatus.OK) {
                        var p = results[0].geometry.location;
                        setMarker(map, p, '', adopterWithAddress[i] + '
' + streets[i] + '
' + citiesStatesZipCodes[i]);
                    } else {
                        alert('Geocode was not successful for the following reason: ' + status);
                    }
                });
            }

            // show the map and place some markers
            initMap();
        });
    };

    return {
        restrict: 'A',
        template: '

',
        replace: true,
        link: link
    };
});

angular.module('stats').directive('originsMap', function(Cats, googleService) {
    var addresses = [];
    var latlong = [];
    var catWithAddress = [];
    // directive link function
    var link = function(scope, element, attrs) {
        var map, infoWindow;
        var markers = [];

        googleService.then(function(google) {

            // map config
            var mapOptions = {
                center: new google.maps.LatLng(30, -78),
                zoom: 4,
                mapTypeId: google.maps.MapTypeId.ROADMAP,
                scrollwheel: false
            };

            // init the map
            function initMap() {
                var cats = Cats.query(function() {
                    var i = 0;
                    for (i = 0; i < cats.length; i++) {
                        catWithAddress.push(cats[i].name);
                        addresses.push(cats[i].origin.address);
                    }
                    i = 0;
                    for (var j = 0; j < addresses.length; j++) {
                        console.log('5');
                        codeAddress(addresses[j], i);
                        i = i + 1;
                    }

                });
                console.log('ADDRESSES: ' + addresses.length + addresses[0]);
                if (map === void 0) {
                    map = new google.maps.Map(element[0], mapOptions);
                }
            }

            // place a marker
            function setMarker(map, position, title, content) {

                var marker;
                var markerOptions = {
                    position: position,
                    map: map,
                    title: title,
                    icon: 'https://maps.google.com/mapfiles/ms/icons/blue-dot.png'
                };

                marker = new google.maps.Marker(markerOptions);
                markers.push(marker); // add marker to array

                google.maps.event.addListener(marker, 'click', function () {
                    // close window if not undefined
                    if (infoWindow !== void 0) {
                        infoWindow.close();
                    }
                    // create new window
                    var infoWindowOptions = {
                        content: content
                    };
                    infoWindow = new google.maps.InfoWindow(infoWindowOptions);
                    infoWindow.open(map, marker);
                });
            }
            function codeAddress(address, i) {
                geocoder.geocode( { 'address': address}, function(results, status) {
                    if (status === google.maps.GeocoderStatus.OK) {
                        var p = results[0].geometry.location;
                        setMarker(map, p, '', catWithAddress[i] + '
' + addresses[i]);
                    } else {
                        alert('Geocode was not successful for the following reason: ' + status);
                    }
                });
            }

            // show the map and place some markers
            initMap();
        });
    };

    return {
        restrict: 'A',
        template: '

',
        replace: true,
        link: link
    };
});
<commit_msg>Fixed bug where Cat Origins Map wouldn't load.<commit_after>'use strict';
angular.module('stats').directive('adopterMap', function(Contacts, googleService) {
    var addresses = [];
    var latlong = [];
    var adopterWithAddress = [];
    var streets = [];
    var citiesStatesZipCodes = [];
    // directive link function
    var link = function(scope, element, attrs) {
        googleService.google().then(function(google) {
            console.log(google);
            var geocoder = new google.maps.Geocoder();
            var map, infoWindow;
            var markers = [];

            // map config
            var mapOptions = {
                center: new google.maps.LatLng(30, -78),
                zoom: 4,
                mapTypeId: google.maps.MapTypeId.ROADMAP,
                scrollwheel: false
            };

            // init the map
            function initMap() {
                var adopters = Contacts.getAllAdopters(function() {
                    var i;
                    for(i = 0; i < adopters.length; i++) {
                        adopterWithAddress.push(adopters[i].firstName + ' ' + adopters[i].surname);
                        streets.push(adopters[i].address);
                        citiesStatesZipCodes.push(adopters[i].city + ', ' + adopters[i].state + ' ' + adopters[i].zipCode);
                        addresses.push(adopters[i]. address + ', ' + adopters[i].city + ', ' + adopters[i].state + ' ' + adopters[i].zipCode);
                    }
                    i = 0;
                    for(var j = 0; j < addresses.length; j++) {
                        console.log('5');
                        codeAddress(addresses[j], i);
                        i = i + 1;
                    }

                });

                if (map === void 0) {
                    map = new google.maps.Map(element[0], mapOptions);
                }
            }

            // place a marker
            function setMarker(map, position, title, content) {
                googleService.google().then(function(google) {
                    var marker;
                    var markerOptions = {
                        position: position,
                        map: map,
                        title: title,
                        icon: 'https://maps.google.com/mapfiles/ms/icons/blue-dot.png'
                    };

                    marker = new google.maps.Marker(markerOptions);
                    markers.push(marker); // add marker to array

                    google.maps.event.addListener(marker, 'click', function () {
                        // close window if not undefined
                        if (infoWindow !== void 0) {
                            infoWindow.close();
                        }
                        // create new window
                        var infoWindowOptions = {
                            content: content
                        };
                        infoWindow = new google.maps.InfoWindow(infoWindowOptions);
                        infoWindow.open(map, marker);
                    });
                });
            }
            function codeAddress(address, i) {
                geocoder.geocode( { 'address': address}, function(results, status) {
                    if (status === google.maps.GeocoderStatus.OK) {
                        var p = results[0].geometry.location;
                        setMarker(map, p, '', adopterWithAddress[i] + '
' + streets[i] + '
' + citiesStatesZipCodes[i]);
                    } else {
                        alert('Geocode was not successful for the following reason: ' + status);
                    }
                });
            }

            // show the map and place some markers
            initMap();
        });
    };

    return {
        restrict: 'A',
        template: '

',
        replace: true,
        link: link
    };
});

angular.module('stats').directive('originsMap', function(Cats, googleService) {
    var addresses = [];
    var latlong = [];
    var catWithAddress = [];
    // directive link function
    var link = function(scope, element, attrs) {
        var map, infoWindow;
        var markers = [];

        googleService.google().then(function(google) {
        var geocoder = new google.maps.Geocoder();
            // map config
            var mapOptions = {
                center: new google.maps.LatLng(30, -78),
                zoom: 4,
                mapTypeId: google.maps.MapTypeId.ROADMAP,
                scrollwheel: false
            };

            // init the map
            function initMap() {
                var cats = Cats.query(function() {
                    var i = 0;
                    for (i = 0; i < cats.length; i++) {
                        catWithAddress.push(cats[i].name);
                        addresses.push(cats[i].origin.address);
                    }
                    i = 0;
                    for (var j = 0; j < addresses.length; j++) {
                        console.log('5');
                        codeAddress(addresses[j], i);
                        i = i + 1;
                    }

                });
                console.log('ADDRESSES: ' + addresses.length + addresses[0]);
                if (map === void 0) {
                    map = new google.maps.Map(element[0], mapOptions);
                }
            }

            // place a marker
            function setMarker(map, position, title, content) {

                var marker;
                var markerOptions = {
                    position: position,
                    map: map,
                    title: title,
                    icon: 'https://maps.google.com/mapfiles/ms/icons/blue-dot.png'
                };

                marker = new google.maps.Marker(markerOptions);
                markers.push(marker); // add marker to array

                google.maps.event.addListener(marker, 'click', function () {
                    // close window if not undefined
                    if (infoWindow !== void 0) {
                        infoWindow.close();
                    }
                    // create new window
                    var infoWindowOptions = {
                        content: content
                    };
                    infoWindow = new google.maps.InfoWindow(infoWindowOptions);
                    infoWindow.open(map, marker);
                });
            }
            function codeAddress(address, i) {
                geocoder.geocode( { 'address': address}, function(results, status) {
                    if (status === google.maps.GeocoderStatus.OK) {
                        var p = results[0].geometry.location;
                        setMarker(map, p, '', catWithAddress[i] + '
' + addresses[i]);
                    } else {
                        alert('Geocode was not successful for the following reason: ' + status);
                    }
                });
            }

            // show the map and place some markers
            initMap();
        });
    };

    return {
        restrict: 'A',
        template: '

',
        replace: true,
        link: link
    };
});
<|endoftext|>


<commit_before>'use strict';

// Trips controller
angular.module('trips').controller('TripsController', ['$scope', '$stateParams', '$location', 'Authentication', 'Trips', 'GoogleMapApi'.ns(),
	function($scope, $stateParams, $location, Authentication, Trips, GoogleMapApi) {
		$scope.authentication = Authentication;

		// Create new Trip
		$scope.create = function() {
			// Create new Trip object
			var trip = new Trips ({
				name: this.name
			});

			// Redirect after save
			trip.$save(function(response) {
				$location.path('trips/' + response._id);

				// Clear form fields
				$scope.name = '';
			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});
		};

		// Remove existing Trip
		$scope.remove = function( trip ) {
			if ( trip ) { trip.$remove();

				for (var i in $scope.trips ) {
					if ($scope.trips [i] === trip ) {
						$scope.trips.splice(i, 1);
					}
				}
			} else {
				$scope.trip.$remove(function() {
					$location.path('trips');
				});
			}
		};

		// Update existing Trip
		$scope.update = function() {
			var trip = $scope.trip ;

			trip.$update(function() {
				$location.path('trips/' + trip._id);
			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});
		};

		// Find a list of Trips
		$scope.find = function() {
			$scope.trips = Trips.query();
		};

		// Find existing Trip
		$scope.findOne = function() {
			$scope.trip = Trips.get({
				tripId: $stateParams.tripId
			},function(data) { //this runs after trip is loaded
				$scope.init();
			});
		};

		$scope.map = {
			//TODO: Center map on trip markers
			center: {
				latitude: 20,
				longitude: 0
			},
			zoom: 2,
			events: {
				/*click: function(maps, eventName, args){
					console.log('CLICKED ON:', args[0].latLng);
				},
				center_changed: function(maps, eventName, args){
					console.log('ALOOO');
				}*/
			},
			object: {}
		};

		$scope.searchbox = {
			template:'searchbox.tpl.html',
			position:'top-left',
			events: {}
		};

		$scope.togglePrivacy = function() {
			$scope.trip.privacy = $scope.trip.privacy?0:1;
			//TODO: optimize this, only pass field
			$scope.updateTrip();
		};

		GoogleMapApi.then(function(maps) {

			$scope.searchbox.events.places_changed = function(box, eventName, args){
				var map = $scope.map.object.getGMap();
				var place = box.getPlaces()[0];
				var marker = {
					place_name: place.name,
					place_id: place.place_id,
					location: {
						latitude: place.geometry.location.lat(),
						longitude: place.geometry.location.lng()
					}
				};
				//TODO: save in different collection
				//TODO: dont allow duplicates
				var exists = false;
				$scope.trip.markers.forEach(function(marker) {
					if(marker.place_id === place.place_id)
						exists = true;
				});
				if(!exists) {
					if(place.geometry.viewport)
					{
						marker.viewport = place.geometry.viewport;
						$scope.bounds.union(place.geometry.viewport);
					}
					else
						$scope.bounds.extend(place.geometry.location);
					$scope.lineCoords.push(place.geometry.location);
					$scope.path.setPath($scope.lineCoords);
					var index = $scope.trip.markers.push(marker)-1; //returns lenght
					$scope.centerMap(index);
					$scope.updateTrip();
				}
			};

			$scope.centerMap = function(index) {
				var map = $scope.map.object.getGMap();
				var marker = $scope.trip.markers[index];
				if(marker.viewport)
				{
					map.fitBounds(makeViewport(marker.viewport));
				}
				else {
					map.setCenter(
						{
							lat:marker.location.latitude,
							lng:marker.location.longitude
						});
					map.setZoom(17);
				}
			};

			$scope.deleteMarker = function(index) {
				$scope.trip.markers.splice(index, 1);
				$scope.init(); //need to re-init (bounds cant be "un-extended")
				//TODO: optimizar (lento a mandar)
				$scope.updateTrip();
			};

			$scope.updateTrip = function() {
				$scope.isLoading = true;
				$scope.sortableOptions.disabled = true;
				$scope.trip.$update().then(function (response) {
					$scope.isLoading = false;
					$scope.sortableOptions.disabled = false;
				});
			};

			$scope.sortableOptions = {
				start: function(e, ui) {
					ui.item.i = ui.item.index();
				},
				stop: function(e, ui) {
					$scope.lineCoords.splice(ui.item.index(), 0, $scope.lineCoords.splice(ui.item.i, 1)[0]);
					$scope.path.setPath($scope.lineCoords);
					$scope.updateTrip();
				}
			};

			$scope.path = new maps.Polyline({
				geodesic: true,
				strokeColor: 'blue',
				strokeWeight: 5,
				strokeOpacity: 0.5
			});

			function makeViewport(obj) {
				return new maps.LatLngBounds(
					new maps.LatLng(
						obj.Ea.k,
						obj.va.j
					),
					new maps.LatLng(
						obj.Ea.j,
						obj.va.k
					));
			}

			$scope.init = function() {
				var map = $scope.map.object.getGMap();
				$scope.bounds = new maps.LatLngBounds();
				$scope.lineCoords = [];
				for (var i=0; i<$scope.trip.markers.length; i++) {
					var marker = $scope.trip.markers[i];
					var latlng = new maps.LatLng(
						marker.location.latitude,
						marker.location.longitude
					);
					$scope.lineCoords.push(latlng);
					if(marker.viewport)
						$scope.bounds.union(makeViewport(marker.viewport));
					else
						$scope.bounds.extend(latlng);
				}
				$scope.path.setPath($scope.lineCoords);
				$scope.path.setMap(map);
				map.fitBounds($scope.bounds);
			};

			$scope.resetMap = function() {
				var map = $scope.map.object.getGMap();
				map.fitBounds($scope.bounds);
			};
		});
	}
]);
<commit_msg>Only update trip when order has been changed<commit_after>'use strict';

// Trips controller
angular.module('trips').controller('TripsController', ['$scope', '$stateParams', '$location', 'Authentication', 'Trips', 'GoogleMapApi'.ns(),
	function($scope, $stateParams, $location, Authentication, Trips, GoogleMapApi) {
		$scope.authentication = Authentication;

		// Create new Trip
		$scope.create = function() {
			// Create new Trip object
			var trip = new Trips ({
				name: this.name
			});

			// Redirect after save
			trip.$save(function(response) {
				$location.path('trips/' + response._id);

				// Clear form fields
				$scope.name = '';
			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});
		};

		// Remove existing Trip
		$scope.remove = function( trip ) {
			if ( trip ) { trip.$remove();

				for (var i in $scope.trips ) {
					if ($scope.trips [i] === trip ) {
						$scope.trips.splice(i, 1);
					}
				}
			} else {
				$scope.trip.$remove(function() {
					$location.path('trips');
				});
			}
		};

		// Update existing Trip
		$scope.update = function() {
			var trip = $scope.trip ;

			trip.$update(function() {
				$location.path('trips/' + trip._id);
			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});
		};

		// Find a list of Trips
		$scope.find = function() {
			$scope.trips = Trips.query();
		};

		// Find existing Trip
		$scope.findOne = function() {
			$scope.trip = Trips.get({
				tripId: $stateParams.tripId
			},function(data) { //this runs after trip is loaded
				$scope.init();
			});
		};

		$scope.map = {
			//TODO: Center map on trip markers
			center: {
				latitude: 20,
				longitude: 0
			},
			zoom: 2,
			events: {
				/*click: function(maps, eventName, args){
					console.log('CLICKED ON:', args[0].latLng);
				},
				center_changed: function(maps, eventName, args){
					console.log('ALOOO');
				}*/
			},
			object: {}
		};

		$scope.searchbox = {
			template:'searchbox.tpl.html',
			position:'top-left',
			events: {}
		};

		$scope.togglePrivacy = function() {
			$scope.trip.privacy = $scope.trip.privacy?0:1;
			//TODO: optimize this, only pass field
			$scope.updateTrip();
		};

		GoogleMapApi.then(function(maps) {

			$scope.searchbox.events.places_changed = function(box, eventName, args){
				var map = $scope.map.object.getGMap();
				var place = box.getPlaces()[0];
				var marker = {
					place_name: place.name,
					place_id: place.place_id,
					location: {
						latitude: place.geometry.location.lat(),
						longitude: place.geometry.location.lng()
					}
				};
				//TODO: save in different collection
				//TODO: dont allow duplicates
				var exists = false;
				$scope.trip.markers.forEach(function(marker) {
					if(marker.place_id === place.place_id)
						exists = true;
				});
				if(!exists) {
					if(place.geometry.viewport)
					{
						marker.viewport = place.geometry.viewport;
						$scope.bounds.union(place.geometry.viewport);
					}
					else
						$scope.bounds.extend(place.geometry.location);
					$scope.lineCoords.push(place.geometry.location);
					$scope.path.setPath($scope.lineCoords);
					var index = $scope.trip.markers.push(marker)-1; //returns lenght
					$scope.centerMap(index);
					$scope.updateTrip();
				}
			};

			$scope.centerMap = function(index) {
				var map = $scope.map.object.getGMap();
				var marker = $scope.trip.markers[index];
				if(marker.viewport)
				{
					map.fitBounds(makeViewport(marker.viewport));
				}
				else {
					map.setCenter(
						{
							lat:marker.location.latitude,
							lng:marker.location.longitude
						});
					map.setZoom(17);
				}
			};

			$scope.deleteMarker = function(index) {
				$scope.trip.markers.splice(index, 1);
				$scope.init(); //need to re-init (bounds cant be "un-extended")
				//TODO: optimizar (lento a mandar)
				$scope.updateTrip();
			};

			$scope.updateTrip = function() {
				$scope.isLoading = true;
				$scope.sortableOptions.disabled = true;
				$scope.trip.$update().then(function (response) {
					$scope.isLoading = false;
					$scope.sortableOptions.disabled = false;
				});
			};

			$scope.sortableOptions = {
				start: function(e, ui) {
					ui.item.i = ui.item.index();
				},
				stop: function(e, ui) {
					//update positions in lineCoords array
					if(ui.item.index()!==ui.item.i) {
						$scope.lineCoords.splice(ui.item.index(), 0, $scope.lineCoords.splice(ui.item.i, 1)[0]);
						$scope.path.setPath($scope.lineCoords);
						$scope.updateTrip();
					}
				}
			};

			$scope.path = new maps.Polyline({
				geodesic: true,
				strokeColor: 'blue',
				strokeWeight: 5,
				strokeOpacity: 0.5
			});

			function makeViewport(obj) {
				return new maps.LatLngBounds(
					new maps.LatLng(
						obj.Ea.k,
						obj.va.j
					),
					new maps.LatLng(
						obj.Ea.j,
						obj.va.k
					));
			}

			$scope.init = function() {
				var map = $scope.map.object.getGMap();
				$scope.bounds = new maps.LatLngBounds();
				$scope.lineCoords = [];
				for (var i=0; i<$scope.trip.markers.length; i++) {
					var marker = $scope.trip.markers[i];
					var latlng = new maps.LatLng(
						marker.location.latitude,
						marker.location.longitude
					);
					$scope.lineCoords.push(latlng);
					if(marker.viewport)
						$scope.bounds.union(makeViewport(marker.viewport));
					else
						$scope.bounds.extend(latlng);
				}
				$scope.path.setPath($scope.lineCoords);
				$scope.path.setMap(map);
				map.fitBounds($scope.bounds);
			};

			$scope.resetMap = function() {
				var map = $scope.map.object.getGMap();
				map.fitBounds($scope.bounds);
			};
		});
	}
]);
<|endoftext|>


<commit_before>/**
 * codemirror-spell-checker v1.0.6
 * Copyright Next Step Webs, Inc.
 * @link https://github.com/NextStepWebs/codemirror-spell-checker
 * @license MIT
 */
"use strict";var Typo=function(e,t,r,n){if(n=n||{},this.platform=n.platform||"chrome",this.dictionary=null,this.rules={},this.dictionaryTable={},this.compoundRules=[],this.compoundRuleCodes={},this.replacementTable=[],this.flags=n.flags||{},e){if(this.dictionary=e,"chrome"==this.platform)t||(t=this._readFile(chrome.extension.getURL("lib/typo/dictionaries/"+e+"/"+e+".aff"))),r||(r=this._readFile(chrome.extension.getURL("lib/typo/dictionaries/"+e+"/"+e+".dic")));else{var i=n.dictionaryPath||"";t||(t=this._readFile(i+"/"+e+"/"+e+".aff")),r||(r=this._readFile(i+"/"+e+"/"+e+".dic"))}this.rules=this._parseAFF(t),this.compoundRuleCodes={};for(var a=0,s=this.compoundRules.length;s>a;a++)for(var o=this.compoundRules[a],l=0,u=o.length;u>l;l++)this.compoundRuleCodes[o[l]]=[];"ONLYINCOMPOUND"in this.flags&&(this.compoundRuleCodes[this.flags.ONLYINCOMPOUND]=[]),this.dictionaryTable=this._parseDIC(r);for(var a in this.compoundRuleCodes)0==this.compoundRuleCodes[a].length&&delete this.compoundRuleCodes[a];for(var a=0,s=this.compoundRules.length;s>a;a++){for(var h=this.compoundRules[a],c="",l=0,u=h.length;u>l;l++){var p=h[l];c+=p in this.compoundRuleCodes?"("+this.compoundRuleCodes[p].join("|")+")":p}this.compoundRules[a]=RegExp(c,"i")}}return this};Typo.prototype={load:function(e){for(var t in e)this[t]=e[t];return this},_readFile:function(e,t){t||(t="ISO8859-1");var r=new XMLHttpRequest;return r.open("GET",e,!1),r.overrideMimeType&&r.overrideMimeType("text/plain; charset="+t),r.send(null),r.responseText},_parseAFF:function(e){var t={};e=this._removeAffixComments(e);for(var r=e.split("\n"),n=0,i=r.length;i>n;n++){var a=r[n],s=a.split(/\s+/),o=s[0];if("PFX"==o||"SFX"==o){for(var l=s[1],u=s[2],h=parseInt(s[3],10),c=[],p=n+1,f=n+1+h;f>p;p++){var a=r[p],d=a.split(/\s+/),v=d[2],g=d[3].split("/"),m=g[0];"0"===m&&(m="");var y=this.parseRuleCodes(g[1]),_=d[4],C={};C.add=m,y.length>0&&(C.continuationClasses=y),"."!==_&&(C.match=RegExp("SFX"===o?_+"$":"^"+_)),"0"!=v&&(C.remove="SFX"===o?RegExp(v+"$"):v),c.push(C)}t[l]={type:o,combineable:"Y"==u,entries:c},n+=h}else if("COMPOUNDRULE"===o){for(var h=parseInt(s[1],10),p=n+1,f=n+1+h;f>p;p++){var a=r[p],d=a.split(/\s+/);this.compoundRules.push(d[1])}n+=h}else if("REP"===o){var d=a.split(/\s+/);3===d.length&&this.replacementTable.push([d[1],d[2]])}else this.flags[o]=s[1]}return t},_removeAffixComments:function(e){return e=e.replace(/#.*$/gm,""),e=e.replace(/^\s\s*/m,"").replace(/\s\s*$/m,""),e=e.replace(/\n{2,}/g,"\n"),e=e.replace(/^\s\s*/,"").replace(/\s\s*$/,"")},_parseDIC:function(e){function t(e,t){e in n&&"object"==typeof n[e]||(n[e]=[]),n[e].push(t)}e=this._removeDicComments(e);for(var r=e.split("\n"),n={},i=1,a=r.length;a>i;i++){var s=r[i],o=s.split("/",2),l=o[0];if(o.length>1){var u=this.parseRuleCodes(o[1]);"NEEDAFFIX"in this.flags&&-1!=u.indexOf(this.flags.NEEDAFFIX)||t(l,u);for(var h=0,c=u.length;c>h;h++){var p=u[h],f=this.rules[p];if(f)for(var d=this._applyRule(l,f),v=0,g=d.length;g>v;v++){var m=d[v];if(t(m,[]),f.combineable)for(var y=h+1;c>y;y++){var _=u[y],C=this.rules[_];if(C&&C.combineable&&f.type!=C.type)for(var R=this._applyRule(m,C),b=0,F=R.length;F>b;b++){var x=R[b];t(x,[])}}}p in this.compoundRuleCodes&&this.compoundRuleCodes[p].push(l)}}else t(l.trim(),[])}return n},_removeDicComments:function(e){return e=e.replace(/^\t.*$/gm,"")},parseRuleCodes:function(e){if(!e)return[];if(!("FLAG"in this.flags))return e.split("");if("long"===this.flags.FLAG){for(var t=[],r=0,n=e.length;n>r;r+=2)t.push(e.substr(r,2));return t}return"num"===this.flags.FLAG?textCode.split(","):void 0},_applyRule:function(e,t){for(var r=t.entries,n=[],i=0,a=r.length;a>i;i++){var s=r[i];if(!s.match||e.match(s.match)){var o=e;if(s.remove&&(o=o.replace(s.remove,"")),"SFX"===t.type?o+=s.add:o=s.add+o,n.push(o),"continuationClasses"in s)for(var l=0,u=s.continuationClasses.length;u>l;l++){var h=this.rules[s.continuationClasses[l]];h&&(n=n.concat(this._applyRule(o,h)))}}}return n},check:function(e){var t=e.replace(/^\s\s*/,"").replace(/\s\s*$/,"");if(this.checkExact(t))return!0;if(t.toUpperCase()===t){var r=t[0]+t.substring(1).toLowerCase();if(this.hasFlag(r,"KEEPCASE"))return!1;if(this.checkExact(r))return!0}var n=t.toLowerCase();if(n!==t){if(this.hasFlag(n,"KEEPCASE"))return!1;if(this.checkExact(n))return!0}return!1},checkExact:function(e){var t=this.dictionaryTable[e];if(void 0===t){if("COMPOUNDMIN"in this.flags&&e.length>=this.flags.COMPOUNDMIN)for(var r=0,n=this.compoundRules.length;n>r;r++)if(e.match(this.compoundRules[r]))return!0;return!1}for(var r=0,n=t.length;n>r;r++)if(!this.hasFlag(e,"ONLYINCOMPOUND",t[r]))return!0;return!1},hasFlag:function(e,t,r){if(t in this.flags){if(void 0===r)var r=Array.prototype.concat.apply([],this.dictionaryTable[e]);if(r&&-1!==r.indexOf(this.flags[t]))return!0}return!1},alphabet:"",suggest:function(e,t){function r(e){for(var t=[],r=0,n=e.length;n>r;r++){for(var i=e[r],a=[],s=0,o=i.length+1;o>s;s++)a.push([i.substring(0,s),i.substring(s,i.length)]);for(var l=[],s=0,o=a.length;o>s;s++){var h=a[s];h[1]&&l.push(h[0]+h[1].substring(1))}for(var c=[],s=0,o=a.length;o>s;s++){var h=a[s];h[1].length>1&&c.push(h[0]+h[1][1]+h[1][0]+h[1].substring(2))}for(var p=[],s=0,o=a.length;o>s;s++){var h=a[s];if(h[1])for(var f=0,d=u.alphabet.length;d>f;f++)p.push(h[0]+u.alphabet[f]+h[1].substring(1))}for(var v=[],s=0,o=a.length;o>s;s++){var h=a[s];if(h[1])for(var f=0,d=u.alphabet.length;d>f;f++)p.push(h[0]+u.alphabet[f]+h[1])}t=t.concat(l),t=t.concat(c),t=t.concat(p),t=t.concat(v)}return t}function n(e){for(var t=[],r=0;r<e.length;r++)u.check(e[r])&&t.push(e[r]);return t}function i(e){function i(e,t){return e[1]<t[1]?-1:1}for(var a=r([e]),s=r(a),o=n(a).concat(n(s)),l={},h=0,c=o.length;c>h;h++)o[h]in l?l[o[h]]+=1:l[o[h]]=1;var p=[];for(var h in l)p.push([h,l[h]]);p.sort(i).reverse();for(var f=[],h=0,c=Math.min(t,p.length);c>h;h++)u.hasFlag(p[h][0],"NOSUGGEST")||f.push(p[h][0]);return f}if(t||(t=5),this.check(e))return[];for(var a=0,s=this.replacementTable.length;s>a;a++){var o=this.replacementTable[a];if(-1!==e.indexOf(o[0])){var l=e.replace(o[0],o[1]);if(this.check(l))return[l]}}var u=this;return u.alphabet="abcdefghijklmnopqrstuvwxyz",i(e)}};window.num_loaded=0;var aff_loading=!1,dic_loading=!1,aff_data="",dic_data="",typo;CodeMirror.defineMode("spell-checker",function(e){if(!aff_loading){aff_loading=!0;var t=new XMLHttpRequest;t.open("GET",serverurl+"/vendor/codemirror-spell-checker/en_US.aff",!0),t.onload=function(){4===t.readyState&&200===t.status&&(aff_data=t.responseText,num_loaded++,2==num_loaded&&(typo=new Typo("en_US",aff_data,dic_data,{platform:"any"})))},t.send(null)}if(!dic_loading){dic_loading=!0;var r=new XMLHttpRequest;r.open("GET",serverurl+"/vendor/codemirror-spell-checker/en_US.dic",!0),r.onload=function(){4===r.readyState&&200===r.status&&(dic_data=r.responseText,num_loaded++,2==num_loaded&&(typo=new Typo("en_US",aff_data,dic_data,{platform:"any"})))},r.send(null)}var n="!\"'#$%&()*+,-./:;<=>?@[\\]^_`{|}~ ",i=/^[A-Za-z][A-Za-z0-9]+$/,a={token:function(e){var t=e.peek(),r="";if(n.includes(t))return e.next(),null;for(;null!=(t=e.peek())&&!n.includes(t);)r+=t,e.next();return i.test(r)&&typo&&!typo.check(r)?"spell-error":null}},s=CodeMirror.getMode(e,e.backdrop||"text/plain");return CodeMirror.overlayMode(s,a,!0)}),String.prototype.includes||(String.prototype.includes=function(){return-1!==String.prototype.indexOf.apply(this,arguments)});
<commit_msg>Fix codemirror spell checker not considering abbreviation which contain apostrophe in word<commit_after>/**
 * codemirror-spell-checker v1.0.6
 * Copyright Next Step Webs, Inc.
 * @link https://github.com/NextStepWebs/codemirror-spell-checker
 * @license MIT
 */
"use strict";var Typo=function(e,t,r,n){if(n=n||{},this.platform=n.platform||"chrome",this.dictionary=null,this.rules={},this.dictionaryTable={},this.compoundRules=[],this.compoundRuleCodes={},this.replacementTable=[],this.flags=n.flags||{},e){if(this.dictionary=e,"chrome"==this.platform)t||(t=this._readFile(chrome.extension.getURL("lib/typo/dictionaries/"+e+"/"+e+".aff"))),r||(r=this._readFile(chrome.extension.getURL("lib/typo/dictionaries/"+e+"/"+e+".dic")));else{var i=n.dictionaryPath||"";t||(t=this._readFile(i+"/"+e+"/"+e+".aff")),r||(r=this._readFile(i+"/"+e+"/"+e+".dic"))}this.rules=this._parseAFF(t),this.compoundRuleCodes={};for(var a=0,s=this.compoundRules.length;s>a;a++)for(var o=this.compoundRules[a],l=0,u=o.length;u>l;l++)this.compoundRuleCodes[o[l]]=[];"ONLYINCOMPOUND"in this.flags&&(this.compoundRuleCodes[this.flags.ONLYINCOMPOUND]=[]),this.dictionaryTable=this._parseDIC(r);for(var a in this.compoundRuleCodes)0==this.compoundRuleCodes[a].length&&delete this.compoundRuleCodes[a];for(var a=0,s=this.compoundRules.length;s>a;a++){for(var h=this.compoundRules[a],c="",l=0,u=h.length;u>l;l++){var p=h[l];c+=p in this.compoundRuleCodes?"("+this.compoundRuleCodes[p].join("|")+")":p}this.compoundRules[a]=RegExp(c,"i")}}return this};Typo.prototype={load:function(e){for(var t in e)this[t]=e[t];return this},_readFile:function(e,t){t||(t="ISO8859-1");var r=new XMLHttpRequest;return r.open("GET",e,!1),r.overrideMimeType&&r.overrideMimeType("text/plain; charset="+t),r.send(null),r.responseText},_parseAFF:function(e){var t={};e=this._removeAffixComments(e);for(var r=e.split("\n"),n=0,i=r.length;i>n;n++){var a=r[n],s=a.split(/\s+/),o=s[0];if("PFX"==o||"SFX"==o){for(var l=s[1],u=s[2],h=parseInt(s[3],10),c=[],p=n+1,f=n+1+h;f>p;p++){var a=r[p],d=a.split(/\s+/),v=d[2],g=d[3].split("/"),m=g[0];"0"===m&&(m="");var y=this.parseRuleCodes(g[1]),_=d[4],C={};C.add=m,y.length>0&&(C.continuationClasses=y),"."!==_&&(C.match=RegExp("SFX"===o?_+"$":"^"+_)),"0"!=v&&(C.remove="SFX"===o?RegExp(v+"$"):v),c.push(C)}t[l]={type:o,combineable:"Y"==u,entries:c},n+=h}else if("COMPOUNDRULE"===o){for(var h=parseInt(s[1],10),p=n+1,f=n+1+h;f>p;p++){var a=r[p],d=a.split(/\s+/);this.compoundRules.push(d[1])}n+=h}else if("REP"===o){var d=a.split(/\s+/);3===d.length&&this.replacementTable.push([d[1],d[2]])}else this.flags[o]=s[1]}return t},_removeAffixComments:function(e){return e=e.replace(/#.*$/gm,""),e=e.replace(/^\s\s*/m,"").replace(/\s\s*$/m,""),e=e.replace(/\n{2,}/g,"\n"),e=e.replace(/^\s\s*/,"").replace(/\s\s*$/,"")},_parseDIC:function(e){function t(e,t){e in n&&"object"==typeof n[e]||(n[e]=[]),n[e].push(t)}e=this._removeDicComments(e);for(var r=e.split("\n"),n={},i=1,a=r.length;a>i;i++){var s=r[i],o=s.split("/",2),l=o[0];if(o.length>1){var u=this.parseRuleCodes(o[1]);"NEEDAFFIX"in this.flags&&-1!=u.indexOf(this.flags.NEEDAFFIX)||t(l,u);for(var h=0,c=u.length;c>h;h++){var p=u[h],f=this.rules[p];if(f)for(var d=this._applyRule(l,f),v=0,g=d.length;g>v;v++){var m=d[v];if(t(m,[]),f.combineable)for(var y=h+1;c>y;y++){var _=u[y],C=this.rules[_];if(C&&C.combineable&&f.type!=C.type)for(var R=this._applyRule(m,C),b=0,F=R.length;F>b;b++){var x=R[b];t(x,[])}}}p in this.compoundRuleCodes&&this.compoundRuleCodes[p].push(l)}}else t(l.trim(),[])}return n},_removeDicComments:function(e){return e=e.replace(/^\t.*$/gm,"")},parseRuleCodes:function(e){if(!e)return[];if(!("FLAG"in this.flags))return e.split("");if("long"===this.flags.FLAG){for(var t=[],r=0,n=e.length;n>r;r+=2)t.push(e.substr(r,2));return t}return"num"===this.flags.FLAG?textCode.split(","):void 0},_applyRule:function(e,t){for(var r=t.entries,n=[],i=0,a=r.length;a>i;i++){var s=r[i];if(!s.match||e.match(s.match)){var o=e;if(s.remove&&(o=o.replace(s.remove,"")),"SFX"===t.type?o+=s.add:o=s.add+o,n.push(o),"continuationClasses"in s)for(var l=0,u=s.continuationClasses.length;u>l;l++){var h=this.rules[s.continuationClasses[l]];h&&(n=n.concat(this._applyRule(o,h)))}}}return n},check:function(e){var t=e.replace(/^\s\s*/,"").replace(/\s\s*$/,"");if(this.checkExact(t))return!0;if(t.toUpperCase()===t){var r=t[0]+t.substring(1).toLowerCase();if(this.hasFlag(r,"KEEPCASE"))return!1;if(this.checkExact(r))return!0}var n=t.toLowerCase();if(n!==t){if(this.hasFlag(n,"KEEPCASE"))return!1;if(this.checkExact(n))return!0}return!1},checkExact:function(e){var t=this.dictionaryTable[e];if(void 0===t){if("COMPOUNDMIN"in this.flags&&e.length>=this.flags.COMPOUNDMIN)for(var r=0,n=this.compoundRules.length;n>r;r++)if(e.match(this.compoundRules[r]))return!0;return!1}for(var r=0,n=t.length;n>r;r++)if(!this.hasFlag(e,"ONLYINCOMPOUND",t[r]))return!0;return!1},hasFlag:function(e,t,r){if(t in this.flags){if(void 0===r)var r=Array.prototype.concat.apply([],this.dictionaryTable[e]);if(r&&-1!==r.indexOf(this.flags[t]))return!0}return!1},alphabet:"",suggest:function(e,t){function r(e){for(var t=[],r=0,n=e.length;n>r;r++){for(var i=e[r],a=[],s=0,o=i.length+1;o>s;s++)a.push([i.substring(0,s),i.substring(s,i.length)]);for(var l=[],s=0,o=a.length;o>s;s++){var h=a[s];h[1]&&l.push(h[0]+h[1].substring(1))}for(var c=[],s=0,o=a.length;o>s;s++){var h=a[s];h[1].length>1&&c.push(h[0]+h[1][1]+h[1][0]+h[1].substring(2))}for(var p=[],s=0,o=a.length;o>s;s++){var h=a[s];if(h[1])for(var f=0,d=u.alphabet.length;d>f;f++)p.push(h[0]+u.alphabet[f]+h[1].substring(1))}for(var v=[],s=0,o=a.length;o>s;s++){var h=a[s];if(h[1])for(var f=0,d=u.alphabet.length;d>f;f++)p.push(h[0]+u.alphabet[f]+h[1])}t=t.concat(l),t=t.concat(c),t=t.concat(p),t=t.concat(v)}return t}function n(e){for(var t=[],r=0;r<e.length;r++)u.check(e[r])&&t.push(e[r]);return t}function i(e){function i(e,t){return e[1]<t[1]?-1:1}for(var a=r([e]),s=r(a),o=n(a).concat(n(s)),l={},h=0,c=o.length;c>h;h++)o[h]in l?l[o[h]]+=1:l[o[h]]=1;var p=[];for(var h in l)p.push([h,l[h]]);p.sort(i).reverse();for(var f=[],h=0,c=Math.min(t,p.length);c>h;h++)u.hasFlag(p[h][0],"NOSUGGEST")||f.push(p[h][0]);return f}if(t||(t=5),this.check(e))return[];for(var a=0,s=this.replacementTable.length;s>a;a++){var o=this.replacementTable[a];if(-1!==e.indexOf(o[0])){var l=e.replace(o[0],o[1]);if(this.check(l))return[l]}}var u=this;return u.alphabet="abcdefghijklmnopqrstuvwxyz",i(e)}};window.num_loaded=0;var aff_loading=!1,dic_loading=!1,aff_data="",dic_data="",typo;CodeMirror.defineMode("spell-checker",function(e){if(!aff_loading){aff_loading=!0;var t=new XMLHttpRequest;t.open("GET",serverurl+"/vendor/codemirror-spell-checker/en_US.aff",!0),t.onload=function(){4===t.readyState&&200===t.status&&(aff_data=t.responseText,num_loaded++,2==num_loaded&&(typo=new Typo("en_US",aff_data,dic_data,{platform:"any"})))},t.send(null)}if(!dic_loading){dic_loading=!0;var r=new XMLHttpRequest;r.open("GET",serverurl+"/vendor/codemirror-spell-checker/en_US.dic",!0),r.onload=function(){4===r.readyState&&200===r.status&&(dic_data=r.responseText,num_loaded++,2==num_loaded&&(typo=new Typo("en_US",aff_data,dic_data,{platform:"any"})))},r.send(null)}var n="!\"#$%&()*+,-./:;<=>?@[\\]^_`{|}~ ",i=/^[A-Za-z][A-Za-z0-9']+$/,a={token:function(e){var t=e.peek(),r="";if(n.includes(t))return e.next(),null;for(;null!=(t=e.peek())&&!n.includes(t);)r+=t,e.next();return i.test(r)&&typo&&!typo.check(r)?"spell-error":null}},s=CodeMirror.getMode(e,e.backdrop||"text/plain");return CodeMirror.overlayMode(s,a,!0)}),String.prototype.includes||(String.prototype.includes=function(){return-1!==String.prototype.indexOf.apply(this,arguments)});
<|endoftext|>


<commit_before>"use strict"

const {remote} = require('electron')
const EventEmitter = require('events')
const i18n = require('../node_modules/i18n-nodejs')

const ToolUI = require('./toolui')
const ToolSettings = require('../lib/settings')
const TwitchTv = require('./twitchtv')
const TwitchHelix = require('./twitchhelix')
const TTVLogin = require('../lib/auth')
const Chat = require('../lib/chat')

const Channel = require('../var/channel')
const Follows = require('../var/follows')
const Subscriptions = require('../var/subscriptions')

const Addons = require('../lib/addons')
//const EAU = remote.require('electron-asar-updater')
const {app, autoUpdater} = remote.require('electron')
const spawn = require('child_process').spawn;

/**
 * This module initializes pretty much everything and other modules have access to other modules over here.
 *
 * @class TTVTool
 * @fires TTVTool#load
 * @fires TTVTool#exit
 * @extends {EventEmitter}
 */
class TTVTool extends EventEmitter {

	constructor() {
		super()
		const self = this

		this.setMaxListeners(50)

		this._settings = new ToolSettings(this)
		this._i18n = new i18n(this._settings.language, './../../language.json')
		this._twitchapi = new TwitchTv({
			clientid: '11vhuxdssb9pc3s2uqpa7s3s0252hyk',
			redirecturi: 'http://localhost:8086/',
			scope: [
				'user_read',
				'channel_check_subscription',
				'channel_editor',
				'channel_read',
				'channel_stream',
				'channel_subscriptions',
				'chat_login'
			]
		})
		this._twitchhelix = new TwitchHelix({
			clientid: '11vhuxdssb9pc3s2uqpa7s3s0252hyk',
			redirecturi: 'http://localhost:8086/',
			scope: []
		})
		this._auth = new TTVLogin(this)
		this._chat = new Chat(this)

		this._ui = new ToolUI(this)
		this._ui.addPage(this._settings)

		this._channel = new Channel(this)
		this._follows = new Follows(this)
		// All subscriptions are coming via chat now
		//this._subscriptions = new Subscriptions(this)

		this._addons = new Addons(this)

		this.on('load', () => {
			if(self._settings.lightDesignMode) {
				document.querySelector('body').classList.add('invert')
			}

			/*EAU.check((e) => {
				if(e != null && e.length > 0) {
					if(e === 'no_update_available') return
					self.ui.showErrorMessage(new Error(e))
				} else {
					let errormsg_download = self.ui.showErrorMessage(new Error(self.i18n.__('There is a new update. Downloading now...')))
					EAU.download((er) => {
						if(e != null && e.length > 0) {
							self.ui.showErrorMessage(new Error(e))
							return
						}
						try { errormsg_download.parentElement.removeChild(errormsg_download) } catch(e) {}

						let errormsg_restart = self.ui.showErrorMessage(new Error(self.i18n.__('Update ready. Program will restart automatically!')))
						errormsg_restart.onclick = () => {}
						setTimeout(() => {
							let exPa = process.execPath
							if(exPa.startsWith('\\')) exPa = exPa.substr(1)
							if(exPa.indexOf(' ') > 0) exPa = '"' + exPa + '"'
							spawn('cmd', ['/Q', '/C', 'copy resources\\update.asar resources\\app.asar /Y & del resources\\update.asar & start ' + exPa], {'detached': true})
							app.quit()
						}, 5000);
					})
				}
			})*/
		})

		window.onload = (e) => {
			//Riot.compile(function() {
				/**
				 * Fires after the document was loaded. Basically window.onload. Use this instead
				 * of window.onload to not overwrite the onload function and breaking the entire
				 * application. Thank you. :)
				 *
				 * @event TTVTool#load
				 */
				self.emit('load')
			//})
		}
		window.onbeforeunload = (e) => {
			/**
			 * Fires before the application is exited. Once again just window.onbeforeunload.
			 * Don't overwrite window.onbeforeunload please.
			 *
			 * @event TTVTool#exit
			 */
			self.emit('exit')
		}

	}

	/**
	 * Gives you the UI modules
	 *
	 * @type {ToolUI}
	 * @readonly
	 */
	get ui() {
		return this._ui
	}

	/**
	 * Gives you the {@link https://www.npmjs.com/package/i18n-nodejs|i18n-nodejs} module.
	 *
	 * @type {i18n-nodejs}
	 * @see {@link https://www.npmjs.com/package/i18n-nodejs}
	 * @readonly
	 */
	get i18n() {
		return this._i18n
	}

	/**
	 * Gives you the settings module.
	 *
	 * @type {ToolSettings}
	 * @readonly
	 */
	get settings() {
		return this._settings
	}

	/**
	 * Gives you the Twitch-API module.
	 *
	 * @type {TwitchTv}
	 * @readonly
	 */
	get twitchapi() {
		return this._twitchapi
	}

	/**
	 * Gives you the new Twitch API module
	 *
	 * @type {TwitchHelix}
	 * @readonly
	 */
	get twitchhelix() {
		return this._twitchhelix
	}

	/**
	 * Gives you the auth module.
	 *
	 * @type {TTVLogin}
	 * @readonly
	 */
	get auth() {
		return this._auth
	}

	/**
	 * Gives you the chat module.
	 *
	 * @type {Chat}
	 * @readonly
	 */
	get chat() {
		return this._chat
	}

	/**
	 * Gives you the cockpit module.
	 *
	 * @type {Cockpit}
	 * @readonly
	 */
	get cockpit() {
		return this._ui.findPage('Cockpit')
	}

	/**
	 * Gives you the overlay module.
	 *
	 * @type {TTVLogin}
	 * @readonly
	 */
	get overlays() {
		return this._ui.findPage('Overlays')
	}

	/**
	 * Gives you the channel data module.
	 *
	 * @type {Channel}
	 * @readonly
	 */
	get channel() {
		return this._channel
	}

	/**
	 * Gives you the follow data module.
	 *
	 * @type {Follows}
	 * @readonly
	 */
	get follows() {
		return this._follows
	}

	/**
	 * Gives you a subscription module.
	 *
	 * @type {undefined}
	 * @readonly
	 * @deprecated Subscription are now shared with everyone via chat.
	 */
	get subscriptions() {
		return this._subscriptions
	}

	/**
	 * Gives you the addons module.
	 *
	 * @type {Addons}
	 * @readonly
	 */
	get addons() {
		return this._addons
	}

}

const tool = new TTVTool()
module.exports = tool<commit_msg>Fix listener build up for F11 (fullscreen) hotkey<commit_after>"use strict"

const {remote} = require('electron')
const EventEmitter = require('events')
const i18n = require('../node_modules/i18n-nodejs')

const ToolUI = require('./toolui')
const ToolSettings = require('../lib/settings')
const TwitchTv = require('./twitchtv')
const TwitchHelix = require('./twitchhelix')
const TTVLogin = require('../lib/auth')
const Chat = require('../lib/chat')

const Channel = require('../var/channel')
const Follows = require('../var/follows')
const Subscriptions = require('../var/subscriptions')

const Addons = require('../lib/addons')
//const EAU = remote.require('electron-asar-updater')
const {app, autoUpdater} = remote.require('electron')
const spawn = require('child_process').spawn;

/**
 * This module initializes pretty much everything and other modules have access to other modules over here.
 *
 * @class TTVTool
 * @fires TTVTool#load
 * @fires TTVTool#exit
 * @extends {EventEmitter}
 */
class TTVTool extends EventEmitter {

	constructor() {
		super()
		const self = this

		this.setMaxListeners(50)

		remote.BrowserWindow.getAllWindows()[0].removeAllListeners();

		this._settings = new ToolSettings(this)
		this._i18n = new i18n(this._settings.language, './../../language.json')
		this._twitchapi = new TwitchTv({
			clientid: '11vhuxdssb9pc3s2uqpa7s3s0252hyk',
			redirecturi: 'http://localhost:8086/',
			scope: [
				'user_read',
				'channel_check_subscription',
				'channel_editor',
				'channel_read',
				'channel_stream',
				'channel_subscriptions',
				'chat_login'
			]
		})
		this._twitchhelix = new TwitchHelix({
			clientid: '11vhuxdssb9pc3s2uqpa7s3s0252hyk',
			redirecturi: 'http://localhost:8086/',
			scope: []
		})
		this._auth = new TTVLogin(this)
		this._chat = new Chat(this)

		this._ui = new ToolUI(this)
		this._ui.addPage(this._settings)

		this._channel = new Channel(this)
		this._follows = new Follows(this)
		// All subscriptions are coming via chat now
		//this._subscriptions = new Subscriptions(this)

		this._addons = new Addons(this)

		this.on('load', () => {
			if(self._settings.lightDesignMode) {
				document.querySelector('body').classList.add('invert')
			}

			/*EAU.check((e) => {
				if(e != null && e.length > 0) {
					if(e === 'no_update_available') return
					self.ui.showErrorMessage(new Error(e))
				} else {
					let errormsg_download = self.ui.showErrorMessage(new Error(self.i18n.__('There is a new update. Downloading now...')))
					EAU.download((er) => {
						if(e != null && e.length > 0) {
							self.ui.showErrorMessage(new Error(e))
							return
						}
						try { errormsg_download.parentElement.removeChild(errormsg_download) } catch(e) {}

						let errormsg_restart = self.ui.showErrorMessage(new Error(self.i18n.__('Update ready. Program will restart automatically!')))
						errormsg_restart.onclick = () => {}
						setTimeout(() => {
							let exPa = process.execPath
							if(exPa.startsWith('\\')) exPa = exPa.substr(1)
							if(exPa.indexOf(' ') > 0) exPa = '"' + exPa + '"'
							spawn('cmd', ['/Q', '/C', 'copy resources\\update.asar resources\\app.asar /Y & del resources\\update.asar & start ' + exPa], {'detached': true})
							app.quit()
						}, 5000);
					})
				}
			})*/
		})

		window.onload = (e) => {
			//Riot.compile(function() {
				/**
				 * Fires after the document was loaded. Basically window.onload. Use this instead
				 * of window.onload to not overwrite the onload function and breaking the entire
				 * application. Thank you. :)
				 *
				 * @event TTVTool#load
				 */
				self.emit('load')
			//})
		}
		window.onbeforeunload = (e) => {
			/**
			 * Fires before the application is exited. Once again just window.onbeforeunload.
			 * Don't overwrite window.onbeforeunload please.
			 *
			 * @event TTVTool#exit
			 */
			self.emit('exit')
		}

	}

	/**
	 * Gives you the UI modules
	 *
	 * @type {ToolUI}
	 * @readonly
	 */
	get ui() {
		return this._ui
	}

	/**
	 * Gives you the {@link https://www.npmjs.com/package/i18n-nodejs|i18n-nodejs} module.
	 *
	 * @type {i18n-nodejs}
	 * @see {@link https://www.npmjs.com/package/i18n-nodejs}
	 * @readonly
	 */
	get i18n() {
		return this._i18n
	}

	/**
	 * Gives you the settings module.
	 *
	 * @type {ToolSettings}
	 * @readonly
	 */
	get settings() {
		return this._settings
	}

	/**
	 * Gives you the Twitch-API module.
	 *
	 * @type {TwitchTv}
	 * @readonly
	 */
	get twitchapi() {
		return this._twitchapi
	}

	/**
	 * Gives you the new Twitch API module
	 *
	 * @type {TwitchHelix}
	 * @readonly
	 */
	get twitchhelix() {
		return this._twitchhelix
	}

	/**
	 * Gives you the auth module.
	 *
	 * @type {TTVLogin}
	 * @readonly
	 */
	get auth() {
		return this._auth
	}

	/**
	 * Gives you the chat module.
	 *
	 * @type {Chat}
	 * @readonly
	 */
	get chat() {
		return this._chat
	}

	/**
	 * Gives you the cockpit module.
	 *
	 * @type {Cockpit}
	 * @readonly
	 */
	get cockpit() {
		return this._ui.findPage('Cockpit')
	}

	/**
	 * Gives you the overlay module.
	 *
	 * @type {TTVLogin}
	 * @readonly
	 */
	get overlays() {
		return this._ui.findPage('Overlays')
	}

	/**
	 * Gives you the channel data module.
	 *
	 * @type {Channel}
	 * @readonly
	 */
	get channel() {
		return this._channel
	}

	/**
	 * Gives you the follow data module.
	 *
	 * @type {Follows}
	 * @readonly
	 */
	get follows() {
		return this._follows
	}

	/**
	 * Gives you a subscription module.
	 *
	 * @type {undefined}
	 * @readonly
	 * @deprecated Subscription are now shared with everyone via chat.
	 */
	get subscriptions() {
		return this._subscriptions
	}

	/**
	 * Gives you the addons module.
	 *
	 * @type {Addons}
	 * @readonly
	 */
	get addons() {
		return this._addons
	}

}

const tool = new TTVTool()
module.exports = tool<|endoftext|>