<commit_before>AUI.add('rating', function(A) {

var L = A.Lang,
	isBoolean = L.isBoolean,
	isNumber = L.isNumber,
	isString = L.isString,

	isNodeList = function(v) {
		return (v instanceof A.NodeList);
	},

	isNode = function(v) {
		return (v instanceof A.Node);
	},

	BLANK = '',
	BOUNDING_BOX = 'boundingBox',
	CAN_RESET = 'canReset',
	CLEARFIX = 'clearfix',
	CONTENT_BOX = 'contentBox',
	DEFAULT_SELECTED = 'defaultSelected',
	DESTROY = 'destroy',
	DISABLED = 'disabled',
	DOT = '.',
	ELEMENT = 'element',
	ELEMENTS = 'elements',
	EMPTY_STR = '',
	HELPER = 'helper',
	HOVER = 'hover',
	ID = 'id',
	INNER_HTML = 'innerHTML',
	INPUT = 'input',
	INPUT_NAME = 'inputName',
	LABEL = 'label',
	LABEL_ELEMENT = 'labelElement',
	NAME = 'name',
	NODE_NAME = 'nodeName',
	OFF = 'off',
	ON = 'on',
	RATING = 'rating',
	SELECTED_INDEX = 'selectedIndex',
	SHOW_TITLE = 'showTitle',
	SIZE = 'size',
	TITLE = 'title',
	VALUE = 'value',

	EV_RATING_ITEM_CLICK = 'itemClick',
	EV_RATING_ITEM_SELECT = 'itemSelect',
	EV_RATING_ITEM_OUT = 'itemOut',
	EV_RATING_ITEM_OVER = 'itemOver',

	getCN = A.ClassNameManager.getClassName,

	CSS_CLEAR_FIX = getCN(HELPER, CLEARFIX),
	CSS_RATING_LABEL_EL = getCN(RATING, LABEL, ELEMENT),
	CSS_RATING_EL = getCN(RATING, ELEMENT),
	CSS_RATING_EL_HOVER  = getCN(RATING, ELEMENT, HOVER),
	CSS_RATING_EL_OFF = getCN(RATING, ELEMENT, OFF),
	CSS_RATING_EL_ON = getCN(RATING, ELEMENT, ON);

function Rating() {
	Rating.superclass.constructor.apply(this, arguments);
}

A.mix(Rating, {
	NAME: 'rating',

	ATTRS: {
		canReset: {
			value: true,
			validator: isBoolean
		},

		defaultSelected: {
			value: 0,
			writeOnce: true,
			validator: isNumber
		},

		elements: {
			writeOnce: true,
			readOnly: true,
			validator: isNodeList
		},

		hiddenInput: {
			validator: isNode
		},

		labelElement: {
			validator: isNode
		},

		inputName: {
			value: BLANK,
			validator: isString
		},

		label: {
			value: BLANK,
			validator: isString
		},

		render: {
			value: true
		},

		selectedIndex: {
			value: -1,
			validator: isNumber
		},

		showTitle: {
			value: true,
			validator: isBoolean
		},

		size: {
			value: 5,
			validator: function(v) {
				return isNumber(v) && (v > 0);
			}
		},

		title: null,

		value: null
	}
});

A.extend(Rating, A.Component, {
	/*
	* Lifecycle
	*/
	initializer: function(){
		var instance = this;

		instance.inputElementsData = {};

		instance.after('labelChange', this._afterSetLabel);
	},

	renderUI: function () {
		var instance = this;

		instance._parseInputElements();
		instance._renderElements();
	},

	bindUI: function () {
		var instance = this;

		instance._createEvents();

		instance.on('click', instance._handleClickEvent);
		instance.on('mouseover', instance._handleMouseOverEvent);
		instance.on('mouseout', instance._handleMouseOutEvent);
	},

	syncUI: function(){
		var instance = this;

		instance._syncElements();
	},

	destructor: function(){
		var instance = this;
		var	boundingBox = instance.get(BOUNDING_BOX);

		boundingBox.detachAll();
		boundingBox.remove();
	},

	/*
	* Methods
	*/
	clearSelection: function() {
		var instance = this;

		instance.get(ELEMENTS).each(function(node) {
			node.removeClass(CSS_RATING_EL_ON);
			node.removeClass(CSS_RATING_EL_HOVER);
		});
	},

	select: function(index) {
		var instance = this;
		var oldIndex = instance.get(SELECTED_INDEX);
		var canReset = instance.get(CAN_RESET);

		// clear selection when the selected element is clicked
		if (canReset && (oldIndex == index)) {
			index = -1;
		}

		instance.set(SELECTED_INDEX, index);

		var selectedIndex = instance.get(SELECTED_INDEX);
		var	data = instance._getInputData(selectedIndex);

		var title = (TITLE in data) ? data.title : BLANK;
		var value = (VALUE in data) ? data.value : selectedIndex;

		instance.fillTo(selectedIndex);

		instance.set(TITLE, title);
		instance.set(VALUE, value);

		var hiddenInput = instance.get('hiddenInput');

		hiddenInput.setAttribute(TITLE, title);
		hiddenInput.setAttribute(VALUE, value);
	},

	fillTo: function(index, className) {
		var instance = this;

		instance.clearSelection();

		if (index >= 0) {
			instance.get(ELEMENTS).some(function(node, i) {
				node.addClass(className || CSS_RATING_EL_ON);

				// stop loop when return true
				return (i == index);
			});
		}
	},

	indexOf: function(elem) {
		var instance = this;

		return instance.get(ELEMENTS).indexOf(elem);
	},

	_canFireCustomEvent: function(event) {
		var instance = this;
		var domTarget = event.domEvent.target;

		// checks if the widget is not disabled and if the dom event is firing with a item as target
		// do not fire custom events for other elements into the boundingBox
		return !instance.get(DISABLED) && domTarget.hasClass(CSS_RATING_EL);
	},

	_createEvents: function() {
		var instance = this;

		// create publish function for kweight optimization
		var publish = function(name, fn) {
			instance.publish(name, {
	            defaultFn: fn,
	            queuable: false,
	            emitFacade: true,
	            bubbles: true
	        });
		};

		// publishing events
		publish(
			EV_RATING_ITEM_CLICK,
			this._defRatingItemClickFn
		);

		publish(
			EV_RATING_ITEM_SELECT,
			this._defRatingItemSelectFn
		);

		publish(
			EV_RATING_ITEM_OVER,
			this._defRatingItemOverFn
		);

		publish(
			EV_RATING_ITEM_OUT,
			this._defRatingItemOutFn
		);
	},

	_defRatingItemClickFn: function(event) {
		var instance = this;
		var domEvent = event.domEvent;

		instance.fire(EV_RATING_ITEM_SELECT, {
			delegateEvent: event,
			domEvent: domEvent,
			ratingItem: domEvent.target
		});
	},

	_defRatingItemSelectFn: function(event) {
		var instance = this;
		var domTarget = event.domEvent.target;

		instance.select(
			instance.indexOf(domTarget)
		);
	},

	_defRatingItemOutFn: function(event) {
		var instance = this;

		instance.fillTo(
			instance.get(SELECTED_INDEX)
		);
	},

	_defRatingItemOverFn: function(event) {
		var instance = this;
		var index = instance.indexOf(event.domEvent.target);

		instance.fillTo(index, CSS_RATING_EL_HOVER);
	},

	_parseInputElements: function() {
		var instance = this;
		var boundingBox = instance.get(BOUNDING_BOX);
		var inputs = boundingBox.queryAll(INPUT);
		var size = inputs.size();
		var inputName = instance.get(INPUT_NAME);
		var hiddenInput = A.Node.create('<input type="hidden" />');

		if (size > 0) {
			inputName = inputName || inputs.item(0).getAttribute(NAME);

			instance.set(SIZE, size);

			var labels = boundingBox.all('label');

			inputs.each(function(node, index) {
				var id = node.get(ID);
				var label = EMPTY_STR;

				if (id) {
					// for a11y parse the  elments information
					// checking if the node has a
					var labelEl = labels.filter('[for="'+id+'"]');

					if (labelEl.size()) {
						// if there is, extract the content of the label to use as content of the anchors...
						label = labelEl.item(0).html();
					}
				}

				instance.inputElementsData[index] = {
					content: label,
					value: node.getAttribute(VALUE) || index,
					title: node.getAttribute(TITLE)
				};
			});

			labels.remove();
			inputs.remove();
		}

		hiddenInput.setAttribute(NAME, inputName);

		boundingBox.appendChild(hiddenInput);

		instance.set('hiddenInput', hiddenInput);
	},

	_renderElements: function() {
		var instance = this;
		var contentBox = instance.get(CONTENT_BOX);
		var ratingElement = A.Node.create('');
		var labelElement = A.Node.create('

');

		contentBox.addClass(CSS_CLEAR_FIX);
		ratingElement.addClass(CSS_RATING_EL);
		labelElement.addClass(CSS_RATING_LABEL_EL);

		contentBox.append(labelElement);

		// creating rating elements
		for (var i = 0, size = this.get(SIZE); i < size; i++) {
			var	data = instance._getInputData(i);
			var element = ratingElement.cloneNode();

			var content = data.content;

			// try to use the pulled title data from the dom, otherwise use the TITLE attr, in the last case use the content
			var title = data.title || instance.get(TITLE) || content;

			// setting the content
			if (content || title) {
				// if there is no content use the title as content
				element.html(content || title);
			}

			// setting the title
			if (title && instance.get(SHOW_TITLE)) {
				element.setAttribute(TITLE, title);
			}

			contentBox.appendChild(element);
		}

		instance.set(LABEL_ELEMENT, labelElement);
		instance.set(ELEMENTS, contentBox.queryAll(DOT+CSS_RATING_EL));
	},

	_syncElements: function(){
		var instance = this;
		var labelText = instance.get(LABEL);
		var selectedIndex = instance.get(DEFAULT_SELECTED) - 1;

		instance.set(SELECTED_INDEX, selectedIndex);

		instance.get(LABEL_ELEMENT).html(labelText);

		instance.select();
	},

	_getInputData: function(index) {
		var instance = this;

		return instance.inputElementsData[index] || {};
	},

	/*
	* Delegated events
	*/
	_handleClickEvent: function(event) {
		var instance = this;
		var domTarget = event.domEvent.target;

		if (instance._canFireCustomEvent(event)) {
			instance.fire(EV_RATING_ITEM_CLICK, {
				delegateEvent: event,
				domEvent: event.domEvent
			});
		}
	},

	_handleMouseOutEvent: function(event) {
		var instance = this;

		if (instance._canFireCustomEvent(event)) {
			instance.fire(EV_RATING_ITEM_OUT, {
				delegateEvent: event,
				domEvent: event.domEvent
			});
		}
	},

	_handleMouseOverEvent: function(event) {
		var instance = this;

		if (instance._canFireCustomEvent(event)) {
			instance.fire(EV_RATING_ITEM_OVER, {
				delegateEvent: event,
				domEvent: event.domEvent
			});
		}
	},

	/*
	* Attribute Listeners
	*/
	_afterSetLabel: function(event) {
		this.syncUI();
	}
});

/*
* ThumbRating
*/
var DOWN = 'down',
	THUMB = 'thumb',
	THUMB_RATING = 'ThumbRating',
	UP = 'up',

	CSS_RATING_THUMB_DOWN = getCN(RATING, THUMB, DOWN),
	CSS_RATING_THUMB_UP = getCN(RATING, THUMB, UP);

function ThumbRating(config) {
	ThumbRating.superclass.constructor.apply(this, arguments);
}

A.mix(ThumbRating, {
	NAME: THUMB_RATING,

	ATTRS: {
		size: {
			value: 2,
			readOnly: true
		}
	}
});

A.extend(ThumbRating, Rating, {
	renderUI: function() {
		var instance = this;

		ThumbRating.superclass.renderUI.apply(this, arguments);

		var elements = instance.get(ELEMENTS);

		elements.addClass(CSS_RATING_EL_OFF);
		elements.item(0).addClass(CSS_RATING_THUMB_UP);
		elements.item(1).addClass(CSS_RATING_THUMB_DOWN);
	},

	fillTo: function(index, className) {
		this.clearSelection();

		if (index >= 0) {
			this.get(ELEMENTS).item(index).addClass(className || CSS_RATING_EL_ON);
		}
	},

	_syncElements: function(){
		var instance = this;
		var labelText = instance.get(LABEL);

		instance.get(LABEL_ELEMENT).html(labelText);
	}
});

A.Rating = Rating;
A.StarRating = Rating;
A.ThumbRating = ThumbRating;

}, '@VERSION' , { requires: [ 'aui-base', 'rating-css' ] });<commit_msg>Changing the anchors for spans in ratings when they are disabled<commit_after>AUI.add('rating', function(A) {

var L = A.Lang,
	isBoolean = L.isBoolean,
	isNumber = L.isNumber,
	isString = L.isString,

	isNodeList = function(v) {
		return (v instanceof A.NodeList);
	},

	isNode = function(v) {
		return (v instanceof A.Node);
	},

	BLANK = '',
	BOUNDING_BOX = 'boundingBox',
	CAN_RESET = 'canReset',
	CLEARFIX = 'clearfix',
	CONTENT_BOX = 'contentBox',
	DEFAULT_SELECTED = 'defaultSelected',
	DESTROY = 'destroy',
	DISABLED = 'disabled',
	DOT = '.',
	ELEMENT = 'element',
	ELEMENTS = 'elements',
	EMPTY_STR = '',
	HELPER = 'helper',
	HOVER = 'hover',
	ID = 'id',
	INNER_HTML = 'innerHTML',
	INPUT = 'input',
	INPUT_NAME = 'inputName',
	LABEL = 'label',
	LABEL_ELEMENT = 'labelElement',
	NAME = 'name',
	NODE_NAME = 'nodeName',
	OFF = 'off',
	ON = 'on',
	RATING = 'rating',
	SELECTED_INDEX = 'selectedIndex',
	SHOW_TITLE = 'showTitle',
	SIZE = 'size',
	TITLE = 'title',
	VALUE = 'value',

	EV_RATING_ITEM_CLICK = 'itemClick',
	EV_RATING_ITEM_SELECT = 'itemSelect',
	EV_RATING_ITEM_OUT = 'itemOut',
	EV_RATING_ITEM_OVER = 'itemOver',

	getCN = A.ClassNameManager.getClassName,

	CSS_CLEAR_FIX = getCN(HELPER, CLEARFIX),
	CSS_RATING_LABEL_EL = getCN(RATING, LABEL, ELEMENT),
	CSS_RATING_EL = getCN(RATING, ELEMENT),
	CSS_RATING_EL_HOVER  = getCN(RATING, ELEMENT, HOVER),
	CSS_RATING_EL_OFF = getCN(RATING, ELEMENT, OFF),
	CSS_RATING_EL_ON = getCN(RATING, ELEMENT, ON);

function Rating() {
	Rating.superclass.constructor.apply(this, arguments);
}

A.mix(Rating, {
	NAME: 'rating',

	ATTRS: {
		disabled: {
			value: false,
			validator: isBoolean
		},
		canReset: {
			value: true,
			validator: isBoolean
		},

		defaultSelected: {
			value: 0,
			writeOnce: true,
			validator: isNumber
		},

		elements: {
			writeOnce: true,
			readOnly: true,
			validator: isNodeList
		},

		hiddenInput: {
			validator: isNode
		},

		labelElement: {
			validator: isNode
		},

		inputName: {
			value: BLANK,
			validator: isString
		},

		label: {
			value: BLANK,
			validator: isString
		},

		render: {
			value: true
		},

		selectedIndex: {
			value: -1,
			validator: isNumber
		},

		showTitle: {
			value: true,
			validator: isBoolean
		},

		size: {
			value: 5,
			validator: function(v) {
				return isNumber(v) && (v > 0);
			}
		},

		title: null,

		value: null
	}
});

A.extend(Rating, A.Component, {
	/*
	* Lifecycle
	*/
	initializer: function(){
		var instance = this;

		instance.inputElementsData = {};

		instance.after('labelChange', this._afterSetLabel);
	},

	renderUI: function () {
		var instance = this;

		instance._parseInputElements();
		instance._renderElements();
	},

	bindUI: function () {
		var instance = this;

		instance._createEvents();

		instance.on('click', instance._handleClickEvent);
		instance.on('mouseover', instance._handleMouseOverEvent);
		instance.on('mouseout', instance._handleMouseOutEvent);
	},

	syncUI: function(){
		var instance = this;

		instance._syncElements();
	},

	destructor: function(){
		var instance = this;
		var	boundingBox = instance.get(BOUNDING_BOX);

		boundingBox.detachAll();
		boundingBox.remove();
	},

	/*
	* Methods
	*/
	clearSelection: function() {
		var instance = this;

		instance.get(ELEMENTS).each(function(node) {
			node.removeClass(CSS_RATING_EL_ON);
			node.removeClass(CSS_RATING_EL_HOVER);
		});
	},

	select: function(index) {
		var instance = this;
		var oldIndex = instance.get(SELECTED_INDEX);
		var canReset = instance.get(CAN_RESET);

		// clear selection when the selected element is clicked
		if (canReset && (oldIndex == index)) {
			index = -1;
		}

		instance.set(SELECTED_INDEX, index);

		var selectedIndex = instance.get(SELECTED_INDEX);
		var	data = instance._getInputData(selectedIndex);

		var title = (TITLE in data) ? data.title : BLANK;
		var value = (VALUE in data) ? data.value : selectedIndex;

		instance.fillTo(selectedIndex);

		instance.set(TITLE, title);
		instance.set(VALUE, value);

		var hiddenInput = instance.get('hiddenInput');

		hiddenInput.setAttribute(TITLE, title);
		hiddenInput.setAttribute(VALUE, value);
	},

	fillTo: function(index, className) {
		var instance = this;

		instance.clearSelection();

		if (index >= 0) {
			instance.get(ELEMENTS).some(function(node, i) {
				node.addClass(className || CSS_RATING_EL_ON);

				// stop loop when return true
				return (i == index);
			});
		}
	},

	indexOf: function(elem) {
		var instance = this;

		return instance.get(ELEMENTS).indexOf(elem);
	},

	_canFireCustomEvent: function(event) {
		var instance = this;
		var domTarget = event.domEvent.target;

		// checks if the widget is not disabled and if the dom event is firing with a item as target
		// do not fire custom events for other elements into the boundingBox
		return !instance.get(DISABLED) && domTarget.hasClass(CSS_RATING_EL);
	},

	_createEvents: function() {
		var instance = this;

		// create publish function for kweight optimization
		var publish = function(name, fn) {
			instance.publish(name, {
	            defaultFn: fn,
	            queuable: false,
	            emitFacade: true,
	            bubbles: true
	        });
		};

		// publishing events
		publish(
			EV_RATING_ITEM_CLICK,
			this._defRatingItemClickFn
		);

		publish(
			EV_RATING_ITEM_SELECT,
			this._defRatingItemSelectFn
		);

		publish(
			EV_RATING_ITEM_OVER,
			this._defRatingItemOverFn
		);

		publish(
			EV_RATING_ITEM_OUT,
			this._defRatingItemOutFn
		);
	},

	_defRatingItemClickFn: function(event) {
		var instance = this;
		var domEvent = event.domEvent;

		instance.fire(EV_RATING_ITEM_SELECT, {
			delegateEvent: event,
			domEvent: domEvent,
			ratingItem: domEvent.target
		});
	},

	_defRatingItemSelectFn: function(event) {
		var instance = this;
		var domTarget = event.domEvent.target;

		instance.select(
			instance.indexOf(domTarget)
		);
	},

	_defRatingItemOutFn: function(event) {
		var instance = this;

		instance.fillTo(
			instance.get(SELECTED_INDEX)
		);
	},

	_defRatingItemOverFn: function(event) {
		var instance = this;
		var index = instance.indexOf(event.domEvent.target);

		instance.fillTo(index, CSS_RATING_EL_HOVER);
	},

	_parseInputElements: function() {
		var instance = this;
		var boundingBox = instance.get(BOUNDING_BOX);
		var inputs = boundingBox.queryAll(INPUT);
		var size = inputs.size();
		var inputName = instance.get(INPUT_NAME);
		var hiddenInput = A.Node.create('<input type="hidden" />');

		if (size > 0) {
			inputName = inputName || inputs.item(0).getAttribute(NAME);

			instance.set(SIZE, size);

			var labels = boundingBox.all('label');

			inputs.each(function(node, index) {
				var id = node.get(ID);
				var label = EMPTY_STR;

				if (id) {
					// for a11y parse the  elments information
					// checking if the node has a
					var labelEl = labels.filter('[for="'+id+'"]');

					if (labelEl.size()) {
						// if there is, extract the content of the label to use as content of the anchors...
						label = labelEl.item(0).html();
					}
				}

				instance.inputElementsData[index] = {
					content: label,
					value: node.getAttribute(VALUE) || index,
					title: node.getAttribute(TITLE)
				};
			});

			labels.remove();
			inputs.remove();
		}

		hiddenInput.setAttribute(NAME, inputName);

		boundingBox.appendChild(hiddenInput);

		instance.set('hiddenInput', hiddenInput);
	},

	_renderElements: function() {
		var instance = this;
		var contentBox = instance.get(CONTENT_BOX);
		var disabled = instance.get(DISABLED);

		var ratingElement = null;
		if (disabled){
			ratingElement = A.Node.create('');
		}
		else {
			ratingElement = A.Node.create('');

		}

		var labelElement = A.Node.create('

');

		contentBox.addClass(CSS_CLEAR_FIX);
		ratingElement.addClass(CSS_RATING_EL);
		labelElement.addClass(CSS_RATING_LABEL_EL);

		contentBox.append(labelElement);

		// creating rating elements
		for (var i = 0, size = this.get(SIZE); i < size; i++) {
			var	data = instance._getInputData(i);
			var element = ratingElement.cloneNode();

			var content = data.content;

			// try to use the pulled title data from the dom, otherwise use the TITLE attr, in the last case use the content
			var title = data.title || instance.get(TITLE) || content;

			// setting the content
			if (content || title) {
				// if there is no content use the title as content
				element.html(content || title);
			}

			// setting the title
			if (title && instance.get(SHOW_TITLE)) {
				element.setAttribute(TITLE, title);
			}

			contentBox.appendChild(element);
		}

		instance.set(LABEL_ELEMENT, labelElement);
		instance.set(ELEMENTS, contentBox.queryAll(DOT+CSS_RATING_EL));
	},

	_syncElements: function(){
		var instance = this;
		var labelText = instance.get(LABEL);
		var selectedIndex = instance.get(DEFAULT_SELECTED) - 1;

		instance.set(SELECTED_INDEX, selectedIndex);

		instance.get(LABEL_ELEMENT).html(labelText);

		instance.select();
	},

	_getInputData: function(index) {
		var instance = this;

		return instance.inputElementsData[index] || {};
	},

	/*
	* Delegated events
	*/
	_handleClickEvent: function(event) {
		var instance = this;
		var domTarget = event.domEvent.target;

		if (instance._canFireCustomEvent(event)) {
			instance.fire(EV_RATING_ITEM_CLICK, {
				delegateEvent: event,
				domEvent: event.domEvent
			});
		}
	},

	_handleMouseOutEvent: function(event) {
		var instance = this;

		if (instance._canFireCustomEvent(event)) {
			instance.fire(EV_RATING_ITEM_OUT, {
				delegateEvent: event,
				domEvent: event.domEvent
			});
		}
	},

	_handleMouseOverEvent: function(event) {
		var instance = this;

		if (instance._canFireCustomEvent(event)) {
			instance.fire(EV_RATING_ITEM_OVER, {
				delegateEvent: event,
				domEvent: event.domEvent
			});
		}
	},

	/*
	* Attribute Listeners
	*/
	_afterSetLabel: function(event) {
		this.syncUI();
	}
});

/*
* ThumbRating
*/
var DOWN = 'down',
	THUMB = 'thumb',
	THUMB_RATING = 'ThumbRating',
	UP = 'up',

	CSS_RATING_THUMB_DOWN = getCN(RATING, THUMB, DOWN),
	CSS_RATING_THUMB_UP = getCN(RATING, THUMB, UP);

function ThumbRating(config) {
	ThumbRating.superclass.constructor.apply(this, arguments);
}

A.mix(ThumbRating, {
	NAME: THUMB_RATING,

	ATTRS: {
		size: {
			value: 2,
			readOnly: true
		}
	}
});

A.extend(ThumbRating, Rating, {
	renderUI: function() {
		var instance = this;

		ThumbRating.superclass.renderUI.apply(this, arguments);

		var elements = instance.get(ELEMENTS);

		elements.addClass(CSS_RATING_EL_OFF);
		elements.item(0).addClass(CSS_RATING_THUMB_UP);
		elements.item(1).addClass(CSS_RATING_THUMB_DOWN);
	},

	fillTo: function(index, className) {
		this.clearSelection();

		if (index >= 0) {
			this.get(ELEMENTS).item(index).addClass(className || CSS_RATING_EL_ON);
		}
	},

	_syncElements: function(){
		var instance = this;
		var labelText = instance.get(LABEL);

		instance.get(LABEL_ELEMENT).html(labelText);
	}
});

A.Rating = Rating;
A.StarRating = Rating;
A.ThumbRating = ThumbRating;

}, '@VERSION' , { requires: [ 'aui-base', 'rating-css' ] });<|endoftext|>


<commit_before>const get = (keys) => new Promise((resolve, reject) => {
  return chrome
    .storage
    .sync
    .get(keys, (items) => {
      resolve(items);
      const err = chrome.runtime.lastError;
      return (err) ? reject(err) : resolve(items);
    });
});

const set = (items) => new Promise((resolve, reject) => {
  return chrome
    .storage
    .sync
    .set(items, () => {
      const err = chrome.runtime.lastError;
      return (err) ? reject(err) : resolve(items);
    });
});

export default { get, set };
<commit_msg>Satisfy ESlint<commit_after>const get = (keys) => {
  const promise = new Promise((resolve, reject) => {
    chrome
      .storage
      .sync
      .get(keys, (items) => {
        resolve(items);
        const err = chrome.runtime.lastError;
        return (err) ? reject(err) : resolve(items);
      });
  });
  return promise;
};

const set = (items) => {
  const promise = new Promise((resolve, reject) => {
    chrome
      .storage
      .sync
      .set(items, () => {
        const err = chrome.runtime.lastError;
        return (err) ? reject(err) : resolve(items);
      });
  });
  return promise;
};

export { get, set };
<|endoftext|>


<commit_before>//

function Browse()
{
	this.conf = config('global').Browse;
	this.onBrowsePage = window.location.pathname === "/browse.php";
}

Browse.prototype.run = function()
{
	this.torrentTablePlus();
	this.expandableTorrents();
	this.massAddSearchButton();
};

Browse.prototype.expandableTorrents = function expandableTorrents()
{
	if(!this.onBrowsePage || !this.conf.Show.expandableTorrents)
		return;

	//cache object
	window.__expandableTorrentsCache = window.__expandableTorrentsCache || {};

	//Expand button
	$('<input>',{type:'button',value:'+','class':'expandableTorrents'}).appendTo(this.$trPlus.not(':eq(0)'));

	//on expand button is clicked
	$(document.body).on('click','#torrentTablePlus .torrentTablePlusTr .expandableTorrents', function()
	{
		var
			$button = $(this)
			, $parent = $button.parent()
			, $tr = $parent.data('$tr')
			, torrentId = $parent.data('torrentId')
		;

		if($tr.next().is('.expanded'))
		{
			$button.val('+');
			$tr.next().remove();
		} else {
			var
				link = '/details.php?id='+torrentId
				, __cache = window.__expandableTorrentsCache
				, $trExpanded = $('
',{'class':'expanded'}).insertAfter($tr)
			;

			if(!__cache[link])
			{
				__cache[link] = torrentId ? '<pic src="/pic/loading2.gif" />' : 'Error[no_ID]';

				if(!torrentId)
				{
					return _done();
				}

				var $_ = $('
').load(link+' .pageContainer > table[width="880"][border="1"][cellspacing="0"][cellpadding="5"]', function()
				{
					__cache[link] = $_.html();
					_done();
				});
			}

			_done();
			function _done()
			{
				$trExpanded.html(''+__cache[link]+'	')
					.find('>td>table').css('width','867px')
					.find('tbody>tr>td:first-child').css({'background-color': 'rgb(216, 211, 180)', cursor: 'pointer'}).click(function()
					{
						$button.click();
					});

				$button.val('-');
			}
		}
	});

	//thanks button
	$(document.body).on('click', '.expanded form input[name="thank"]', function(e)
	{
		e.preventDefault();
		e.stopPropagation();

		$(this).hide();

		var tid = $(this).siblings('[name="id"]').val();
		$.post('./details.php', {id:tid, thank:1, async:1});

		$(this).closest('tr')
			.find('#thanks_count').each(function(){this.innerHTML = parseInt(this.innerHTML,10)+1;}).end()
			.find('div.sp-body').each(function()
			{
				var
					$last_a = $(this).find('a:last')
					, a = '' + tmd.user.name + ''
				;

				if ($last_a.length == 0)
				{
					$(this).html(a);
				} else {
					$last_a.after($(', '+a));
				}

				$('div.sp-head:first',$(this).parent()).not('.unfolded').click();
			})
		;
	});
};

Browse.prototype.massAddSearchButton = function massAddSearchButton()
{
	if(!this.onBrowsePage || !this.conf.Show.massAddSearchButton)
		return;

	var
		$massAddSearchButton = $('

',{'class':'massAddSearchButton'})
	;

	$('<input>',{type: 'button', value: 'S'}).appendTo($massAddSearchButton);
	$('<input>',{type: 'checkbox'}).appendTo($massAddSearchButton);

	$massAddSearchButton.appendTo(this.$trPlus.not(':eq(0)'));

	$(document.body).on('click', '#torrentTablePlus .massAddSearchButton [type="button"]', function()
	{
		var
			$parent = $(this).closest('.torrentTablePlusTr').data('$tr')
			, $td = $parent.find('td[align="left"]:eq(0)')
			, text = getSelectionText() || $td.find('a').text()
			, win = window.open(window.location.origin + '/search.php?search_str='+encodeURIComponent(text), '_blank');

		win.focus();
	});

	$(document.body).on('change', '#torrentTablePlus .massAddSearchButton [type="checkbox"]', function()
	{
		var
			$parent = $(this).closest('.torrentTablePlusTr').data('$tr')
			, $td = $parent.find('td[align="left"]:eq(0)')
			, $link = $td.find('a')
			, $titleSpan = $td.find('span.titleSpan').length ? $td.find('span.titleSpan') : $('',{'class':'titleSpan'}).text($link.text()).insertAfter($link).hide()
		;

		$link.toggle();
		$titleSpan.toggle();
	});

	function getSelectionText()
	{
		return window.getSelection().toString();
	}

};

/**
 * Create a fixed table on left side of `torrents table`
 * ---
 * this.$tablePlus - reference for created table
 * this.$trPlus - reference for its rows, each row has .data('$tr') = reference for real $tr from `torrents table`
 */
Browse.prototype.torrentTablePlus = function torrentTablePlus()
{
	if(!this.onBrowsePage || !(this.conf.Show.massAddSearchButton || this.conf.Show.expandableTorrents))
		return;

	var
		$torrentTable = $$('table.tableTorrents').length ? $$('table.tableTorrents') : $('.pageContainer > table td img[src*="arrowdown.gif"]').closest('table')
		, $tablePlus = $('

',{id:'torrentTablePlus'}).hide()
		, $trPlus = $('

',{'class':'torrentTablePlusTr'})
		, _$trPlus = $()
		, tablePlusCss = {
			top: 0
			, right: $torrentTable.offset().left + $torrentTable.width()
		}
	;

	//fill _$trPlus array
	$torrentTable.find('tr').each(function()
	{
		var
			$a = $(this).find('a[href*="details.php?id="]').eq(0)
			, id = $a.length ? parseInt($a.attr('href').replace(/.+php\?id=(\d+).*/,'$1'),10) : 0
		;

		_$trPlus = _$trPlus.add($trPlus.clone().data({'$tr': $(this), torrentId:id}) );
	});

	//fill $tablePlus, apply styles and append it to DOM
	$tablePlus.append(_$trPlus).css(tablePlusCss).appendTo(document.body).show(200);

	//update before showing
	updateTrPlusPosition();

	//cache
	this.$tablePlus = $tablePlus;
	this.$trPlus = _$trPlus;

	//update $trPlus positions on $torrentTable DOMSubtreeModified
	$torrentTable.on('DOMSubtreeModified', function()
	{
		[10, 200, 400].forEach(function(time)
		{
			$.wait(time).then(updateTrPlusPosition);
		});
	});

	/**
	 * update $trPlus positions
	 */
	var lastTimeUpdated = 0;
	function updateTrPlusPosition()
	{
		if(new Date() - lastTimeUpdated < 400 )
			return;

		_$trPlus.each(function()
		{
			var $tr = $(this).data('$tr');
			$(this).css({'height':$tr.height()-6, 'top':$tr.offset().top})
		});

		lastTimeUpdated = new Date();
	}
};

<commit_msg>return to previous view location on Expand torrent<commit_after>//

function Browse()
{
	this.conf = config('global').Browse;
	this.onBrowsePage = window.location.pathname === "/browse.php";
}

Browse.prototype.run = function()
{
	this.torrentTablePlus();
	this.expandableTorrents();
	this.massAddSearchButton();
};

Browse.prototype.expandableTorrents = function expandableTorrents()
{
	if(!this.onBrowsePage || !this.conf.Show.expandableTorrents)
		return;

	//cache object
	window.__expandableTorrentsCache = window.__expandableTorrentsCache || {};

	//Expand button
	$('<input>',{type:'button',value:'+','class':'expandableTorrents'}).appendTo(this.$trPlus.not(':eq(0)'));

	//on expand button is clicked
	$(document.body).on('click','#torrentTablePlus .torrentTablePlusTr .expandableTorrents', function()
	{
		var
			$button = $(this)
			, $parent = $button.parent()
			, $tr = $parent.data('$tr')
			, torrentId = $parent.data('torrentId')
		;

		if($tr.next().is('.expanded'))
		{
			$button.val('+');
			$tr.next().remove();

			//update view location with previous one
			$(window).scrollTop($tr.data('scrollTop'));
		} else {
			var
				link = '/details.php?id='+torrentId
				, __cache = window.__expandableTorrentsCache
				, $trExpanded = $('
',{'class':'expanded'}).insertAfter($tr)
			;

			//save current view location
			$tr.data('scrollTop', $(window).scrollTop());

			if(!__cache[link])
			{
				__cache[link] = torrentId ? '<pic src="/pic/loading2.gif" />' : 'Error[no_ID]';

				if(!torrentId)
				{
					return _done();
				}

				var $_ = $('
').load(link+' .pageContainer > table[width="880"][border="1"][cellspacing="0"][cellpadding="5"]', function()
				{
					__cache[link] = $_.html();
					_done();
				});
			}

			_done();
			function _done()
			{
				$trExpanded.html(''+__cache[link]+'	')
					.find('>td>table').css('width','867px')
					.find('tbody>tr>td:first-child').css({'background-color': 'rgb(216, 211, 180)', cursor: 'pointer'}).click(function()
					{
						$button.click();
					});

				$button.val('-');
			}
		}
	});

	//thanks button
	$(document.body).on('click', '.expanded form input[name="thank"]', function(e)
	{
		e.preventDefault();
		e.stopPropagation();

		$(this).hide();

		var tid = $(this).siblings('[name="id"]').val();
		$.post('./details.php', {id:tid, thank:1, async:1});

		$(this).closest('tr')
			.find('#thanks_count').each(function(){this.innerHTML = parseInt(this.innerHTML,10)+1;}).end()
			.find('div.sp-body').each(function()
			{
				var
					$last_a = $(this).find('a:last')
					, a = '' + tmd.user.name + ''
				;

				if ($last_a.length == 0)
				{
					$(this).html(a);
				} else {
					$last_a.after($(', '+a));
				}

				$('div.sp-head:first',$(this).parent()).not('.unfolded').click();
			})
		;
	});
};

Browse.prototype.massAddSearchButton = function massAddSearchButton()
{
	if(!this.onBrowsePage || !this.conf.Show.massAddSearchButton)
		return;

	var
		$massAddSearchButton = $('

',{'class':'massAddSearchButton'})
	;

	$('<input>',{type: 'button', value: 'S'}).appendTo($massAddSearchButton);
	$('<input>',{type: 'checkbox'}).appendTo($massAddSearchButton);

	$massAddSearchButton.appendTo(this.$trPlus.not(':eq(0)'));

	$(document.body).on('click', '#torrentTablePlus .massAddSearchButton [type="button"]', function()
	{
		var
			$parent = $(this).closest('.torrentTablePlusTr').data('$tr')
			, $td = $parent.find('td[align="left"]:eq(0)')
			, text = getSelectionText() || $td.find('a').text()
			, win = window.open(window.location.origin + '/search.php?search_str='+encodeURIComponent(text), '_blank');

		win.focus();
	});

	$(document.body).on('change', '#torrentTablePlus .massAddSearchButton [type="checkbox"]', function()
	{
		var
			$parent = $(this).closest('.torrentTablePlusTr').data('$tr')
			, $td = $parent.find('td[align="left"]:eq(0)')
			, $link = $td.find('a')
			, $titleSpan = $td.find('span.titleSpan').length ? $td.find('span.titleSpan') : $('',{'class':'titleSpan'}).text($link.text()).insertAfter($link).hide()
		;

		$link.toggle();
		$titleSpan.toggle();
	});

	function getSelectionText()
	{
		return window.getSelection().toString();
	}

};

/**
 * Create a fixed table on left side of `torrents table`
 * ---
 * this.$tablePlus - reference for created table
 * this.$trPlus - reference for its rows, each row has .data('$tr') = reference for real $tr from `torrents table`
 */
Browse.prototype.torrentTablePlus = function torrentTablePlus()
{
	if(!this.onBrowsePage || !(this.conf.Show.massAddSearchButton || this.conf.Show.expandableTorrents))
		return;

	var
		$torrentTable = $$('table.tableTorrents').length ? $$('table.tableTorrents') : $('.pageContainer > table td img[src*="arrowdown.gif"]').closest('table')
		, $tablePlus = $('

',{id:'torrentTablePlus'}).hide()
		, $trPlus = $('

',{'class':'torrentTablePlusTr'})
		, _$trPlus = $()
		, tablePlusCss = {
			top: 0
			, right: $torrentTable.offset().left + $torrentTable.width()
		}
	;

	//fill _$trPlus array
	$torrentTable.find('tr').each(function()
	{
		var
			$a = $(this).find('a[href*="details.php?id="]').eq(0)
			, id = $a.length ? parseInt($a.attr('href').replace(/.+php\?id=(\d+).*/,'$1'),10) : 0
		;

		_$trPlus = _$trPlus.add($trPlus.clone().data({'$tr': $(this), torrentId:id}) );
	});

	//fill $tablePlus, apply styles and append it to DOM
	$tablePlus.append(_$trPlus).css(tablePlusCss).appendTo(document.body).show(200);

	//update before showing
	updateTrPlusPosition();

	//cache
	this.$tablePlus = $tablePlus;
	this.$trPlus = _$trPlus;

	//update $trPlus positions on $torrentTable DOMSubtreeModified
	$torrentTable.on('DOMSubtreeModified', function()
	{
		[10, 200, 400].forEach(function(time)
		{
			$.wait(time).then(updateTrPlusPosition);
		});
	});

	/**
	 * update $trPlus positions
	 */
	var lastTimeUpdated = 0;
	function updateTrPlusPosition()
	{
		if(new Date() - lastTimeUpdated < 400 )
			return;

		_$trPlus.each(function()
		{
			var $tr = $(this).data('$tr');
			$(this).css({'height':$tr.height()-6, 'top':$tr.offset().top})
		});

		lastTimeUpdated = new Date();
	}
};

<|endoftext|>


<commit_before>
import { Vector3 }  from '../../../../three.js/src/math/Vector3';

export const VERSION = '1.6.1';

export const MATERIAL_LINE       = 1;
export const MATERIAL_SURFACE    = 2;

export const CAMERA_ORTHOGRAPHIC = 1;
export const CAMERA_PERSPECTIVE  = 2;
export const CAMERA_OFFSET       = 600;

// preset camera views

export const VIEW_NONE           = 0;
export const VIEW_PLAN           = 1;
export const VIEW_ELEVATION_N    = 2;
export const VIEW_ELEVATION_S    = 3;
export const VIEW_ELEVATION_E    = 4;
export const VIEW_ELEVATION_W    = 5;

// mouse selection operation mode

export const MOUSE_MODE_NORMAL     = 0;
export const MOUSE_MODE_ROUTE_EDIT = 1;
// shading types

export const SHADING_HEIGHT       = 1;
export const SHADING_LENGTH       = 2;
export const SHADING_INCLINATION  = 3;
export const SHADING_CURSOR       = 4;
export const SHADING_SINGLE       = 5;
export const SHADING_SURVEY       = 6;
export const SHADING_OVERLAY      = 7;
export const SHADING_SHADED       = 8;
export const SHADING_DEPTH        = 9;
export const SHADING_PATH         = 10;
export const SHADING_DEPTH_CURSOR = 11;
export const SHADING_AXIS         = 12;

// layer tags for scene objects

export const LEG_CAVE              = 1;
export const LEG_SPLAY             = 2;
export const LEG_SURFACE           = 3;
export const FEATURE_BOX           = 4;
export const FEATURE_SELECTED_BOX  = 5;
export const FEATURE_ENTRANCES     = 6;
export const FEATURE_TERRAIN       = 7;
export const FEATURE_STATIONS      = 8;
export const FEATURE_TRACES        = 9;

export const FACE_WALLS            = 10;
export const FACE_SCRAPS           = 11;

export const WALL_OVAL             = 1; // based on Therion .lox types
export const WALL_SQUARE           = 2;
export const WALL_DIAMOND          = 3;

export const LABEL_STATION         = 12;

// flags in legs exported by Cave models

export const NORMAL  = 0;
export const SURFACE = 1;
export const SPLAY   = 2;
export const DIVING  = 3;

export const STATION_NORMAL = 0;
export const STATION_ENTRANCE = 1;

export const upAxis = new Vector3( 0, 0, 1 );

// EOF<commit_msg>up version number<commit_after>
import { Vector3 }  from '../../../../three.js/src/math/Vector3';

export const VERSION = '1.6.2';

export const MATERIAL_LINE       = 1;
export const MATERIAL_SURFACE    = 2;

export const CAMERA_ORTHOGRAPHIC = 1;
export const CAMERA_PERSPECTIVE  = 2;
export const CAMERA_OFFSET       = 600;

// preset camera views

export const VIEW_NONE           = 0;
export const VIEW_PLAN           = 1;
export const VIEW_ELEVATION_N    = 2;
export const VIEW_ELEVATION_S    = 3;
export const VIEW_ELEVATION_E    = 4;
export const VIEW_ELEVATION_W    = 5;

// mouse selection operation mode

export const MOUSE_MODE_NORMAL     = 0;
export const MOUSE_MODE_ROUTE_EDIT = 1;
// shading types

export const SHADING_HEIGHT       = 1;
export const SHADING_LENGTH       = 2;
export const SHADING_INCLINATION  = 3;
export const SHADING_CURSOR       = 4;
export const SHADING_SINGLE       = 5;
export const SHADING_SURVEY       = 6;
export const SHADING_OVERLAY      = 7;
export const SHADING_SHADED       = 8;
export const SHADING_DEPTH        = 9;
export const SHADING_PATH         = 10;
export const SHADING_DEPTH_CURSOR = 11;
export const SHADING_AXIS         = 12;

// layer tags for scene objects

export const LEG_CAVE              = 1;
export const LEG_SPLAY             = 2;
export const LEG_SURFACE           = 3;
export const FEATURE_BOX           = 4;
export const FEATURE_SELECTED_BOX  = 5;
export const FEATURE_ENTRANCES     = 6;
export const FEATURE_TERRAIN       = 7;
export const FEATURE_STATIONS      = 8;
export const FEATURE_TRACES        = 9;

export const FACE_WALLS            = 10;
export const FACE_SCRAPS           = 11;

export const WALL_OVAL             = 1; // based on Therion .lox types
export const WALL_SQUARE           = 2;
export const WALL_DIAMOND          = 3;

export const LABEL_STATION         = 12;

// flags in legs exported by Cave models

export const NORMAL  = 0;
export const SURFACE = 1;
export const SPLAY   = 2;
export const DIVING  = 3;

export const STATION_NORMAL = 0;
export const STATION_ENTRANCE = 1;

export const upAxis = new Vector3( 0, 0, 1 );

// EOF<|endoftext|>


<commit_before>'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
	errorHandler = require('./errors.server.controller'),
	Criterium = mongoose.model('Criterium'),
	_ = require('lodash');

/**
 * Create a Criterium
 */
exports.create = function(req, res) {
	var criterium = new Criterium(req.body);
	criterium.user = req.user;

	criterium.save(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(criterium);
		}
	});
};

/**
 * Show the current Criterium
 */
exports.read = function(req, res) {
	res.jsonp(req.criterium);
};

/**
 * Update a Criterium
 */
exports.update = function(req, res) {
	var criterium = req.criterium ;

	criterium = _.extend(criterium , req.body);

	criterium.save(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(criterium);
		}
	});
};

/**
 * Delete an Criterium
 */
exports.delete = function(req, res) {
	var criterium = req.criterium ;

	criterium.remove(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(criterium);
		}
	});
};

/**
 * List of Criteria
 */
exports.list = function(req, res) {
	Criterium.find().sort('-created').populate('user', 'displayName').exec(function(err, criteria) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(criteria);
		}
	});
};

/**
 * Criterium middleware
 */
exports.criteriumByID = function(req, res, next, id) {
	Criterium.findById(id).populate('user', 'displayName').exec(function(err, criterium) {
		if (err) return next(err);
		if (! criterium) return next(new Error('Failed to load Criterium ' + id));
		req.criterium = criterium ;
		next();
	});
};

/**
 * Criterium authorization middleware
 */
exports.hasAuthorization = function(req, res, next) {
	if (req.criterium.user.id !== req.user.id) {
		return res.status(403).send('User is not authorized');
	}
	next();
};
<commit_msg>Change order of criteria<commit_after>'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
	errorHandler = require('./errors.server.controller'),
	Criterium = mongoose.model('Criterium'),
	_ = require('lodash');

/**
 * Create a Criterium
 */
exports.create = function(req, res) {
	var criterium = new Criterium(req.body);
	criterium.user = req.user;

	criterium.save(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(criterium);
		}
	});
};

/**
 * Show the current Criterium
 */
exports.read = function(req, res) {
	res.jsonp(req.criterium);
};

/**
 * Update a Criterium
 */
exports.update = function(req, res) {
	var criterium = req.criterium ;

	criterium = _.extend(criterium , req.body);

	criterium.save(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(criterium);
		}
	});
};

/**
 * Delete an Criterium
 */
exports.delete = function(req, res) {
	var criterium = req.criterium ;

	criterium.remove(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(criterium);
		}
	});
};

/**
 * List of Criteria
 */
exports.list = function(req, res) {
	Criterium.find().sort('created').populate('user', 'displayName').exec(function(err, criteria) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(criteria);
		}
	});
};

/**
 * Criterium middleware
 */
exports.criteriumByID = function(req, res, next, id) {
	Criterium.findById(id).populate('user', 'displayName').exec(function(err, criterium) {
		if (err) return next(err);
		if (! criterium) return next(new Error('Failed to load Criterium ' + id));
		req.criterium = criterium ;
		next();
	});
};

/**
 * Criterium authorization middleware
 */
exports.hasAuthorization = function(req, res, next) {
	if (req.criterium.user.id !== req.user.id) {
		return res.status(403).send('User is not authorized');
	}
	next();
};
<|endoftext|>


<commit_before>(function() { //IIFE

    var DJANGO_SERVER_URL = "https://cryptic-citadel-5628.herokuapp.com/api";
    var FIREBASE_SERVER_URL = "https://tanks-for-waiting.firebaseio.com";

    angular.module('tanks-for-waiting').controller('GameController', GameController);
    GameController.$inject = ['$scope', '$http', '$firebaseObject'];

    function GameController($scope, $http, $firebaseObject) {

        var firebaseref = null;
        var playerID = null; //player_id stored here
        var gameID = null; //game_id stored here
        $scope.gameRunning = false;
        $scope.score = 0;
        /*
        *This begins the process of game selection.
        POST to /players/ for player_id
        Returns player_id
        Stores player_id
        POST to games/player_id
        Returns game_id
        Stores game_id
        Starts game
        */
        $scope.startGame = function() {
            $http.post(DJANGO_SERVER_URL + "/players/")
                .then(function(response) {
                    playerID = response.data;
                    //this is where I would display the tutorial
                    $http.post(DJANGO_SERVER_URL + "/game/" + playerID)
                        .then(function(response) {
                                gameID = response.data;
                                firebaseref = new Firebase (FIREBASE_SERVER_URL + "/games/" + gameID); //websocket to firebase api
                                $scope.game = $firsebaseObject (firebaseref); //websocket to firebase api
                                // $scope.gameRunning = true;
                                // new Game("screen");
                            },
                            function(errobj) {
                                alert("Game request failed: " + JSON.stringify(errobj));
                            });
                }, function(errobj) {
                  $scope.gameRunning = true;
                  new Game("screen");
                    // alert("Player request failed: " + JSON.stringify(errobj));
                });
            console.log("click");
        };

        var Game = function(canvasId) { //holds all the main game code
            var canvas = document.getElementById(canvasId); //get the canvas into my game
            var screen = canvas.getContext('2d'); //var screen will allow me to draw to the canvas. "2d" leads to the creation of a CanvasRenderingContext2D object representing a two-dimensional rendering context.
            var gameSize = {
                x: canvas.width,
                y: canvas.height
            }; // stores the width and height of the canvas for later use for placing entities on the canvas

            this.tanks = [new Player(this, gameSize)]; //will hold all of the tanks in the game
            this.targets = [new Target(this, gameSize),
                new Target(this, gameSize),
                new Target(this, gameSize),
                new Target(this, gameSize),
                new Target(this, gameSize)
            ];
            var self = this;
            var framesPerSecond = function() { // framesPerSecond is going to get run about 60 times a second and it's responsible for running all the main game logic
                self.update(); //updates the screen
                self.draw(screen, gameSize); //based upon what's happening in the game
                requestAnimationFrame(framesPerSecond); // and then asks to run framesPerSecond again
                // console.log("hello"); // uncomment the console log to see this 60fps in action
            };

            framesPerSecond();

        };

        Game.prototype = { //gives Game a prototype
            update: function() { //updates the movement of all the on screen entities
                for (var i = 0; i < this.tanks.length; i++) {
                    this.tanks[i].update();
                }
                var thisPlayer = this.tanks[0];
                for (i = 0; i < this.targets.length; i++) {
                  if (colliding(thisPlayer, this.targets[i])) {
                    console.log("HIT!");
                    $scope.score += 1;
                  }
                }
            },

            draw: function(screen, gameSize) {
                screen.clearRect(0, 0, gameSize.x, gameSize.y);
                for (var i = 0; i < this.tanks.length; i++) {
                    drawTank(screen, this.tanks[i]);
                    // drawTarget(screen, this.tanks[i]);
                    if (i === 0) {
                        if (this.tanks[i].keyboarder.isDown(this.tanks[i].keyboarder.KEYS.LEFT)) {
                            drawDrillHeadLeft(screen, this.tanks[i]);
                        } else if (this.tanks[i].keyboarder.isDown(this.tanks[i].keyboarder.KEYS.RIGHT)) {
                            drawDrillHeadRight(screen, this.tanks[i]);
                        } else if (this.tanks[i].keyboarder.isDown(this.tanks[i].keyboarder.KEYS.UP)) {
                            drawDrillHeadUp(screen, this.tanks[i]);
                        } else if (this.tanks[i].keyboarder.isDown(this.tanks[i].keyboarder.KEYS.DOWN)) {
                            drawDrillHeadDown(screen, this.tanks[i]);
                        }
                    }
                }
                for (i = 0; i < this.targets.length; i++) {
                    drawTarget(screen, this.targets[i]);
                    // drawTarget(screen, this.tanks[i]);

                }
            },

            addBody: function(body) { //takes a body and pushes it to the tanks array
                this.tanks.push(body); // example; this.game.addBody(varNameOfBody);
            }
        };
        var Player = function(game, gameSize) {
            this.game = game;
            this.size = {
                x: 16,
                y: 16
            }; //player size
            this.center = {
                x: gameSize.x / 2,
                y: gameSize.y - this.size.x
            }; //tells the game where the player is at the moment, starting at half way through the screen and just above the bottom
            this.keyboarder = new Keyboarder();
        };

        Player.prototype = {
            update: function() {
                if (this.keyboarder.isDown(this.keyboarder.KEYS.LEFT)) {
                    if (this.center.x <= 10) {
                        this.center.x = 8;
                    } else {
                        this.center.x -= 2;
                    }
                }
                if (this.keyboarder.isDown(this.keyboarder.KEYS.RIGHT)) {
                    if (this.center.x >= 490) {
                        this.center.x = 492;
                    } else {
                        this.center.x += 2;
                    }
                }
                if (this.keyboarder.isDown(this.keyboarder.KEYS.UP)) {
                    if (this.center.y <= 10) {
                        this.center.y = 8;
                    } else {
                        this.center.y -= 2;
                    }
                }
                if (this.keyboarder.isDown(this.keyboarder.KEYS.DOWN)) {
                    if (this.center.y >= 490) {
                        this.center.y = 492;
                    } else {
                        this.center.y += 2;
                    }
                }
            }
        };

        var Target = function(game, gameSize) {
            this.game = game;
            this.size = {
                x: 10,
                y: 10
            }; //player size
            this.center = {
                x: Math.random() * gameSize.x,
                y: Math.random() * gameSize.y
            }; //tells the game where the player is at the moment, starting at half way through the screen and just above the bottom
        };

        Target.prototype = {
            update: function() {
                console.log("helllo");
            }
        };

        var drawTank = function(screen, body) {
            //tank body
            screen.fillRect(body.center.x - body.size.x / 2, //x coordinate
                body.center.y - body.size.y / 2, // y coordinate
                body.size.x, body.size.y); //width and hieght
        };

        var drawDrillHeadLeft = function(screen, body) {
            screen.fillRect(body.center.x - body.size.x / 2 - 4, body.center.y - 2, 4, 4);
        };

        var drawDrillHeadRight = function(screen, body) {
            screen.fillRect(body.center.x + body.size.x / 2, body.center.y - 2, 4, 4);
        };

        var drawDrillHeadUp = function(screen, body) {
            screen.fillRect(body.center.x - 2, body.center.y - body.size.y / 2 - 4, 4, 4);
        };

        var drawDrillHeadDown = function(screen, body) {
            screen.fillRect(body.center.x - 2, body.center.y + body.size.y / 2, 4, 4);
        };

        var drawTarget = function(screen, target) {
            screen.fillRect(target.center.x - target.size.x / 2, //x coordinate
                target.center.y - target.size.y / 2, // y coordinate
                target.size.x, target.size.y);
        };

        var Keyboarder = function() { //handles keyboard input
            var keyState = {}; //records if any key that's been pressed is pressed or released

            window.onkeydown = function(e) {
                keyState[e.keyCode] = true;
            };

            window.onkeyup = function(e) {
                keyState[e.keyCode] = false;
            };

            this.isDown = function(keyCode) {
                return keyState[keyCode] === true;
            };

            this.KEYS = {
                LEFT: 37,
                UP: 38,
                RIGHT: 39,
                DOWN: 40,
                SPACE: 32
            };
        };

        var colliding = function(b1, b2) {
          return !(b1 === b2 ||
                   b1.center.x + b1.size.x /2 < b2.center.x - b2.size.x / 2 ||
                   b1.center.y + b1.size.y /2 < b2.center.y - b2.size.y / 2 ||
                   b1.center.x - b1.size.x /2 > b2.center.x + b2.size.x / 2 ||
                   b1.center.y - b1.size.y /2 > b2.center.y + b2.size.y / 2);
        };
    }
})(); // End of IIFE
<commit_msg>score increases when tank hits target<commit_after>(function() { //IIFE

    var DJANGO_SERVER_URL = "https://cryptic-citadel-5628.herokuapp.com/api";
    var FIREBASE_SERVER_URL = "https://tanks-for-waiting.firebaseio.com";

    angular.module('tanks-for-waiting').controller('GameController', GameController);
    GameController.$inject = ['$scope', '$http', '$firebaseObject', '$interval'];

    function GameController($scope, $http, $firebaseObject, $interval) {

        var firebaseref = null;
        var playerID = null; //player_id stored here
        var gameID = null; //game_id stored here
        $scope.gameRunning = false;
        $scope.score = 0;
        /*
        *This begins the process of game selection.
        POST to /players/ for player_id
        Returns player_id
        Stores player_id
        POST to games/player_id
        Returns game_id
        Stores game_id
        Starts game
        */
        $scope.startGame = function() {
            $http.post(DJANGO_SERVER_URL + "/players/")
                .then(function(response) {
                    playerID = response.data;
                    //this is where I would display the tutorial
                    $http.post(DJANGO_SERVER_URL + "/game/" + playerID)
                        .then(function(response) {
                                gameID = response.data;
                                firebaseref = new Firebase (FIREBASE_SERVER_URL + "/games/" + gameID); //websocket to firebase api
                                $scope.game = $firsebaseObject (firebaseref); //websocket to firebase api
                                // $scope.gameRunning = true;
                                // new Game("screen");
                            },
                            function(errobj) {
                                alert("Game request failed: " + JSON.stringify(errobj));
                            });
                }, function(errobj) {
                  $scope.gameRunning = true;
                  new Game("screen");
                    // alert("Player request failed: " + JSON.stringify(errobj));
                });
            console.log("click");
        };

        var Game = function(canvasId) { //holds all the main game code
            var canvas = document.getElementById(canvasId); //get the canvas into my game
            var screen = canvas.getContext('2d'); //var screen will allow me to draw to the canvas. "2d" leads to the creation of a CanvasRenderingContext2D object representing a two-dimensional rendering context.
            var gameSize = {
                x: canvas.width,
                y: canvas.height
            }; // stores the width and height of the canvas for later use for placing entities on the canvas

            this.tanks = [new Player(this, gameSize)]; //will hold all of the tanks in the game
            this.targets = [new Target(this, gameSize),
                new Target(this, gameSize),
                new Target(this, gameSize),
                new Target(this, gameSize),
                new Target(this, gameSize)
            ];
            var self = this;
            // var framesPerSecond = function() { // framesPerSecond is going to get run about 60 times a second and it's responsible for running all the main game logic
            //     self.update(); //updates the screen
            //     self.draw(screen, gameSize); //based upon what's happening in the game
            //     requestAnimationFrame(framesPerSecond); // and then asks to run framesPerSecond again
            //     // console.log("hello"); // uncomment the console log to see this 60fps in action
            // };
            //
            // framesPerSecond();
            $interval(function() {
              self.update(); //updates the screen
              self.draw(screen, gameSize); //based upon what's happening in the game
            }, 16.7);
        };

        Game.prototype = { //gives Game a prototype
            update: function() { //updates the movement of all the on screen entities
                for (var i = 0; i < this.tanks.length; i++) {
                    this.tanks[i].update();
                }
                var thisPlayer = this.tanks[0];
                for (i = 0; i < this.targets.length; i++) {
                  if (colliding(thisPlayer, this.targets[i])) {
                    console.log("HIT!");
                    $scope.score += 1;
                  }
                }
            },

            draw: function(screen, gameSize) {
                screen.clearRect(0, 0, gameSize.x, gameSize.y);
                for (var i = 0; i < this.tanks.length; i++) {
                    drawTank(screen, this.tanks[i]);
                    // drawTarget(screen, this.tanks[i]);
                    if (i === 0) {
                        if (this.tanks[i].keyboarder.isDown(this.tanks[i].keyboarder.KEYS.LEFT)) {
                            drawDrillHeadLeft(screen, this.tanks[i]);
                        } else if (this.tanks[i].keyboarder.isDown(this.tanks[i].keyboarder.KEYS.RIGHT)) {
                            drawDrillHeadRight(screen, this.tanks[i]);
                        } else if (this.tanks[i].keyboarder.isDown(this.tanks[i].keyboarder.KEYS.UP)) {
                            drawDrillHeadUp(screen, this.tanks[i]);
                        } else if (this.tanks[i].keyboarder.isDown(this.tanks[i].keyboarder.KEYS.DOWN)) {
                            drawDrillHeadDown(screen, this.tanks[i]);
                        }
                    }
                }
                for (i = 0; i < this.targets.length; i++) {
                    drawTarget(screen, this.targets[i]);
                    // drawTarget(screen, this.tanks[i]);

                }
            },

            addBody: function(body) { //takes a body and pushes it to the tanks array
                this.tanks.push(body); // example; this.game.addBody(varNameOfBody);
            }
        };
        var Player = function(game, gameSize) {
            this.game = game;
            this.size = {
                x: 16,
                y: 16
            }; //player size
            this.center = {
                x: gameSize.x / 2,
                y: gameSize.y - this.size.x
            }; //tells the game where the player is at the moment, starting at half way through the screen and just above the bottom
            this.keyboarder = new Keyboarder();
        };

        Player.prototype = {
            update: function() {
                if (this.keyboarder.isDown(this.keyboarder.KEYS.LEFT)) {
                    if (this.center.x <= 10) {
                        this.center.x = 8;
                    } else {
                        this.center.x -= 2;
                    }
                }
                if (this.keyboarder.isDown(this.keyboarder.KEYS.RIGHT)) {
                    if (this.center.x >= 490) {
                        this.center.x = 492;
                    } else {
                        this.center.x += 2;
                    }
                }
                if (this.keyboarder.isDown(this.keyboarder.KEYS.UP)) {
                    if (this.center.y <= 10) {
                        this.center.y = 8;
                    } else {
                        this.center.y -= 2;
                    }
                }
                if (this.keyboarder.isDown(this.keyboarder.KEYS.DOWN)) {
                    if (this.center.y >= 490) {
                        this.center.y = 492;
                    } else {
                        this.center.y += 2;
                    }
                }
            }
        };

        var Target = function(game, gameSize) {
            this.game = game;
            this.size = {
                x: 10,
                y: 10
            }; //player size
            this.center = {
                x: Math.random() * gameSize.x,
                y: Math.random() * gameSize.y
            }; //tells the game where the player is at the moment, starting at half way through the screen and just above the bottom
        };

        Target.prototype = {
            update: function() {
                console.log("helllo");
            }
        };

        var drawTank = function(screen, body) {
            //tank body
            screen.fillRect(body.center.x - body.size.x / 2, //x coordinate
                body.center.y - body.size.y / 2, // y coordinate
                body.size.x, body.size.y); //width and hieght
        };

        var drawDrillHeadLeft = function(screen, body) {
            screen.fillRect(body.center.x - body.size.x / 2 - 4, body.center.y - 2, 4, 4);
        };

        var drawDrillHeadRight = function(screen, body) {
            screen.fillRect(body.center.x + body.size.x / 2, body.center.y - 2, 4, 4);
        };

        var drawDrillHeadUp = function(screen, body) {
            screen.fillRect(body.center.x - 2, body.center.y - body.size.y / 2 - 4, 4, 4);
        };

        var drawDrillHeadDown = function(screen, body) {
            screen.fillRect(body.center.x - 2, body.center.y + body.size.y / 2, 4, 4);
        };

        var drawTarget = function(screen, target) {
            screen.fillRect(target.center.x - target.size.x / 2, //x coordinate
                target.center.y - target.size.y / 2, // y coordinate
                target.size.x, target.size.y);
        };

        var Keyboarder = function() { //handles keyboard input
            var keyState = {}; //records if any key that's been pressed is pressed or released

            window.onkeydown = function(e) {
                keyState[e.keyCode] = true;
            };

            window.onkeyup = function(e) {
                keyState[e.keyCode] = false;
            };

            this.isDown = function(keyCode) {
                return keyState[keyCode] === true;
            };

            this.KEYS = {
                LEFT: 37,
                UP: 38,
                RIGHT: 39,
                DOWN: 40,
                SPACE: 32
            };
        };

        var colliding = function(b1, b2) {
          return !(b1 === b2 ||
                   b1.center.x + b1.size.x /2 < b2.center.x - b2.size.x / 2 ||
                   b1.center.y + b1.size.y /2 < b2.center.y - b2.size.y / 2 ||
                   b1.center.x - b1.size.x /2 > b2.center.x + b2.size.x / 2 ||
                   b1.center.y - b1.size.y /2 > b2.center.y + b2.size.y / 2);
        };
    }
})(); // End of IIFE
<|endoftext|>


<commit_before>quail.lib.EarlAssert = (function () {

	var resultPrioMap = [
		'untested', 'inapplicable', 'passed',
		'cantTell', 'failed'
	];

	function Assert(base) {
		var earlAssert = $.extend({}, base, Assert.defaultAssert);

		earlAssert.outcome = $.extend({}, earlAssert.outcome);

		return earlAssert;
	}

	Assert.defaultAssert = {
		// type: 'assert',
		// subject: '',
		// assertedBy: '',
		// mode: 'automated'
	};

	/**
	 * Return the priorty index of the result
	 * @param  {result|assert|outcome} val
	 * @return {integer}     Result index in order of prioerty
	 */
	Assert.getResultPrio = function (val) {
		if (typeof val === 'object') {
			if (val.outcome) {
				val = val.outcome.result;
			} else {
				val = val.result;
			}
		}
		return resultPrioMap.indexOf(val);
	};

	return Assert;

}());<commit_msg>Adjusted spacing<commit_after>quail.lib.EarlAssert = (function () {

  var resultPrioMap = [
    'untested', 'inapplicable', 'passed',
    'cantTell', 'failed'
  ];

  /**
   * Create a new earl assert object
   * @param {object} base An object on which the values of Assert are based
   */
  function Assert(base) {
    var earlAssert = $.extend({}, base, Assert.defaultAssert);

    earlAssert.outcome = $.extend({}, earlAssert.outcome);

    return earlAssert;
  }

  Assert.defaultAssert = {
    // type: 'assert',
    // subject: '',
    // assertedBy: '',
    // mode: 'automated'
  };

  /**
   * Return the priorty index of the result
   * @param  {result|assert|outcome} val
   * @return {integer}     Result index in order of prioerty
   */
  Assert.getResultPrio = function (val) {
    if (typeof val === 'object') {
      if (val.outcome) {
        val = val.outcome.result;
      } else {
        val = val.result;
      }
    }
    return resultPrioMap.indexOf(val);
  };

  return Assert;

}());<|endoftext|>


<commit_before>AnnotationsEventsController.MEASURING_TOOL = 'measuring_tool';

AnnotationsEventsController.prototype.initializeMeasuringTool = function(polyline_config) {
    // by default, initialize dummy tool
    this.initializeDummyTool();

    if (!(AnnotationsEventsController.MEASURING_TOOL  in this.initialized_tools)) {

        this.annotation_controller.ruler = undefined;
        this.annotation_controller.ruler_id = 'ruler';
        this.annotation_controller.ruler_config =
            (typeof polyline_config === 'undefined') ? {} : polyline_config;
        // VERY IMPORTANT!!! set polyline_config fill_alpha to 0!
        this.annotation_controller.ruler_config.fill_alpha = 0;

        this.annotation_controller.ruler_out_id = undefined;

        this.annotation_controller._pointToRuler = function(x, y) {
            if (this.ruler) {
                this.ruler.addPoint(x, y);
            } else {
                this.drawPolyline(this.ruler_id, [], undefined,
                    this.ruler_config, false);
                this.selectShape(this.ruler_id);
                this.ruler = this.getShape(this.ruler_id);
                this.ruler.addPoint(x,y);
                $("#" + this.ruler_out_id).trigger('ruler_created');
            }
            this.refreshView();
        };

        this.annotation_controller.addPointToRuler = function(event) {
            this._pointToRuler(event.point.x, event.point.y);
        };

        this.annotation_controller.replaceLastRulerPoint = function(event) {
            this.ruler.removePoint();
            this.addPointToRuler(event);
        };

        this.annotation_controller.removeLastRulerPoint = function() {
            try {
                this.ruler.removePoint();
                this.refreshView();
            } catch (err) {
                this.clearRuler();
            }
        };

        this.annotation_controller.clearRuler = function(ruler_saved) {
            if (typeof this.ruler !== 'undefined') {
                this.deleteShape(this.ruler_id);
                this.ruler = undefined;
            }
            $('#' + this.ruler_out_id).trigger('ruler_cleared', [ruler_saved]);
        };

        this.annotation_controller.getRulerMeasure = function() {
            if (typeof this.ruler !== 'undefined') {
                return this.ruler.getPerimeter(this.image_mpp);
            }
        };

        this.annotation_controller.serializeRuler = function() {
            var $ruler_out = $("#" + this.ruler_out_id);
            var ruler_json = this.getShapeJSON(this.ruler_id);
            var ac = this;
            ruler_json.points = $.map(ruler_json.points, function(point) {
                return {
                    'x': point.x + ac.x_offset,
                    'y': point.y + ac.y_offset
                }
            });
            ruler_json.shape_id = this._getShapeId('ruler');
            $ruler_out.data('ruler_json', ruler_json);
        };

        this.annotation_controller.updateOutputField = function() {
            var measure = this.getRulerMeasure();
            if (typeof this.ruler_out_id === 'undefined') {
                console.log('Current ruler measure is: ' + measure + ' microns');
            } else {
                var $ruler_out = $("#" + this.ruler_out_id);
                if ($ruler_out.is('input')) {
                    $ruler_out.val(measure);
                } else if ($ruler_out.is('div') || $ruler_out.is('p')){
                    $ruler_out.text(measure);
                } else {
                    console.warn('output field with ID ' + this.ruler_out_id + ' is not handled');
                }
            }
        };

        var aec = this;
        this.annotation_controller.bindToRuler = function(switch_on_id, switch_off_id, output_field_id) {
            // first of all, bind tool activation
            aec._bind_switch(switch_on_id, AnnotationsEventsController.MEASURING_TOOL);
            // then bind extra behaviour for click
            $('#' + switch_on_id).bind(
                'click',
                {'annotation_controller': this},
                function(event) {
                    event.data.annotation_controller.ruler_out_id = output_field_id;
                    $('#' + output_field_id).trigger('start_new_ruler');
                }
            );
            $('#' + switch_off_id).bind(
                'click',
                {'annotation_controller': this},
                function(event) {
                    var ac = event.data.annotation_controller;
                    console.log('clicked on the SWITCH OFF button');
                    ac.serializeRuler();
                    ac.clearRuler(true);
                }
            );
        };

        var ruler_tool = new paper.Tool();

        ruler_tool.annotations_controller = this.annotation_controller;

        ruler_tool.onMouseDown = function(event) {
            this.annotations_controller.addPointToRuler(event);
        };

        ruler_tool.onMouseDrag = function(event) {
            this.annotations_controller.replaceLastRulerPoint(event);
        };

        ruler_tool.onMouseUp = function(event) {
            this.annotations_controller.updateOutputField();
        };

        this.initialized_tools[AnnotationsEventsController.MEASURING_TOOL] = ruler_tool;

    } else {
        console.warn('Tool"' + AnnotationsEventsController.MEASURING_TOOL + '" already initialized');
    }
};<commit_msg>choose the number of decimal digits for ruler measure<commit_after>AnnotationsEventsController.MEASURING_TOOL = 'measuring_tool';

AnnotationsEventsController.prototype.initializeMeasuringTool = function(polyline_config) {
    // by default, initialize dummy tool
    this.initializeDummyTool();

    if (!(AnnotationsEventsController.MEASURING_TOOL  in this.initialized_tools)) {

        this.annotation_controller.ruler = undefined;
        this.annotation_controller.ruler_id = 'ruler';
        this.annotation_controller.ruler_config =
            (typeof polyline_config === 'undefined') ? {} : polyline_config;
        // VERY IMPORTANT!!! set polyline_config fill_alpha to 0!
        this.annotation_controller.ruler_config.fill_alpha = 0;

        this.annotation_controller.ruler_out_id = undefined;

        this.annotation_controller._pointToRuler = function(x, y) {
            if (this.ruler) {
                this.ruler.addPoint(x, y);
            } else {
                this.drawPolyline(this.ruler_id, [], undefined,
                    this.ruler_config, false);
                this.selectShape(this.ruler_id);
                this.ruler = this.getShape(this.ruler_id);
                this.ruler.addPoint(x,y);
                $("#" + this.ruler_out_id).trigger('ruler_created');
            }
            this.refreshView();
        };

        this.annotation_controller.addPointToRuler = function(event) {
            this._pointToRuler(event.point.x, event.point.y);
        };

        this.annotation_controller.replaceLastRulerPoint = function(event) {
            this.ruler.removePoint();
            this.addPointToRuler(event);
        };

        this.annotation_controller.removeLastRulerPoint = function() {
            try {
                this.ruler.removePoint();
                this.refreshView();
            } catch (err) {
                this.clearRuler();
            }
        };

        this.annotation_controller.clearRuler = function(ruler_saved) {
            if (typeof this.ruler !== 'undefined') {
                this.deleteShape(this.ruler_id);
                this.ruler = undefined;
            }
            $('#' + this.ruler_out_id).trigger('ruler_cleared', [ruler_saved]);
        };

        this.annotation_controller.getRulerMeasure = function(decimal_digits) {
            if (typeof this.ruler !== 'undefined') {
                return this.ruler.getPerimeter(this.image_mpp, decimal_digits);
            }
        };

        this.annotation_controller.serializeRuler = function() {
            var $ruler_out = $("#" + this.ruler_out_id);
            var ruler_json = this.getShapeJSON(this.ruler_id);
            var ac = this;
            ruler_json.points = $.map(ruler_json.points, function(point) {
                return {
                    'x': point.x + ac.x_offset,
                    'y': point.y + ac.y_offset
                }
            });
            ruler_json.shape_id = this._getShapeId('ruler');
            $ruler_out.data('ruler_json', ruler_json);
        };

        this.annotation_controller.updateOutputField = function() {
            var measure = this.getRulerMeasure();
            if (typeof this.ruler_out_id === 'undefined') {
                console.log('Current ruler measure is: ' + measure + ' microns');
            } else {
                var $ruler_out = $("#" + this.ruler_out_id);
                if ($ruler_out.is('input')) {
                    $ruler_out.val(measure);
                } else if ($ruler_out.is('div') || $ruler_out.is('p')){
                    $ruler_out.text(measure);
                } else {
                    console.warn('output field with ID ' + this.ruler_out_id + ' is not handled');
                }
            }
        };

        var aec = this;
        this.annotation_controller.bindToRuler = function(switch_on_id, switch_off_id, output_field_id) {
            // first of all, bind tool activation
            aec._bind_switch(switch_on_id, AnnotationsEventsController.MEASURING_TOOL);
            // then bind extra behaviour for click
            $('#' + switch_on_id).bind(
                'click',
                {'annotation_controller': this},
                function(event) {
                    event.data.annotation_controller.ruler_out_id = output_field_id;
                    $('#' + output_field_id).trigger('start_new_ruler');
                }
            );
            $('#' + switch_off_id).bind(
                'click',
                {'annotation_controller': this},
                function(event) {
                    var ac = event.data.annotation_controller;
                    console.log('clicked on the SWITCH OFF button');
                    ac.serializeRuler();
                    ac.clearRuler(true);
                }
            );
        };

        var ruler_tool = new paper.Tool();

        ruler_tool.annotations_controller = this.annotation_controller;

        ruler_tool.onMouseDown = function(event) {
            this.annotations_controller.addPointToRuler(event);
        };

        ruler_tool.onMouseDrag = function(event) {
            this.annotations_controller.replaceLastRulerPoint(event);
        };

        ruler_tool.onMouseUp = function(event) {
            this.annotations_controller.updateOutputField();
        };

        this.initialized_tools[AnnotationsEventsController.MEASURING_TOOL] = ruler_tool;

    } else {
        console.warn('Tool"' + AnnotationsEventsController.MEASURING_TOOL + '" already initialized');
    }
};<|endoftext|>


<commit_before>var config = function () {

  return {
    extensionName: 'Uncanny Cookie Clicker',
    cookieClickerUrls: [
      'http://orteil.dashnet.org/cookieclicker/',
      'http://orteil.dashnet.org/cookieclicker/beta/'
    ],
    defaultSettings: {
      autoClickCookie: false,
      autoClickCookieInterval: 1,
      autoPopWrinklers: false,
      autoClickGoldenCookie: false,
      autoClickSeasonPopup: false,
      avoidRedCookie: true,
      notifyGoldenCookie: false,
      notifySeasonPopup: false,
      autoBuyUpgrades: false,
      bypassDialogForUpgrades: false,
      buyRepeatableUpgrades: false,
      notifyUpgrades: false,
      speedUpGame: false,
      speedUpGameFactor: 1,
      autoBuyBuildings: false
    },
    notificationDuration: 5000
  };

}();
<commit_msg>Update config.js<commit_after>var config = function () {

  return {
    extensionName: 'Uncanny Cookie Clicker',
    cookieClickerUrls: [
      'http://orteil.dashnet.org/cookieclicker/',
      'http://orteil.dashnet.org/cookieclicker/beta/'
      'https://orteil.dashnet.org/cookieclicker/',
      'https://orteil.dashnet.org/cookieclicker/beta/'
    ],
    defaultSettings: {
      autoClickCookie: false,
      autoClickCookieInterval: 1,
      autoPopWrinklers: false,
      autoClickGoldenCookie: false,
      autoClickSeasonPopup: false,
      avoidRedCookie: true,
      notifyGoldenCookie: false,
      notifySeasonPopup: false,
      autoBuyUpgrades: false,
      bypassDialogForUpgrades: false,
      buyRepeatableUpgrades: false,
      notifyUpgrades: false,
      speedUpGame: false,
      speedUpGameFactor: 1,
      autoBuyBuildings: false
    },
    notificationDuration: 5000
  };

}();
<|endoftext|>