<commit_before>(function(name, definition) {

    if (typeof define === 'function') { // RequireJS
        define(function() { return definition; });
    } else if (typeof module !== 'undefined' && module.exports) { // CommonJS
        module.exports = definition;
    } else { // Browser
        this[name] = definition;
    }

})('signal', function(root, undefined) {

		/**
		 * Quick reference to Array.prototype.splice
		 * for duplicating arrays (while removing the
		 * first parameter)
		 * @type {Function}
		 */
	var _ripFirstArg = (function(splice) {
			return function(arr) {
				return splice.call(arr, 0, 1)[0];
			};
		}([].splice)),

		/**
		 * Object merger
		 * @param {Objects}
		 * @return {Object}
		 */
		_extend = function(base) {
			var args = arguments,
				idx = 1, length = args.length,
				key, merger;
			for (; idx < length; idx += 1) {
				merger = args[idx];

				for (key in merger) {
					base[key] = merger[key];
				}
			}

			return base;
		},

		/**
		 * Holds cached, parsed event keys by string
		 * @type {Object}
		 */
		_cache = {},

		/**
		 * Unique Id
		 * @type {Number}
		 */
		_id = 0,
		_uniqueId = function() {
			return _id++;
		},

		/**
		 * Cached regex used to parse event string
		 * @type {RegExp}
		 */
		_NAME_REGEX = /(?:([\w-]+):)?([\w-]*)(?:.([\w-]+))?/,
		_parseConfig = function(eventname) {
			var match = _NAME_REGEX.exec(eventname);
			return {
				// [0] : the entire match, don't care!
				// [1] : handle
				h:  (match[1] === undefined) ? '' : match[1],
				// [2] : event
				e:  (match[2] === undefined) ? '' : match[2],
				// [3] : namespace
				ns: (match[3] === undefined) ? '' : match[3]
			};
		},

		_reassignEvents = function(handle, active, inactive) {
			inactive[handle] = inactive[handle] || {};
			inactive[handle] = _extend({}, active[handle]);
			delete active[handle];
		},

		_callEvents = function(events, args) {
			args = args || [];

			var idx = 0, length = events.length,
				evt;
			for (; idx < length; idx += 1) {
				evt = events[idx];
				if (!evt) { continue; }
				if (evt.apply(null, args) === false) { return; }
			}
		},

		_eventLookup = function(eventConfig, location) {
			var handle    = location[eventConfig.h] || (location[eventConfig.h] = {}),
				evt       = handle[eventConfig.e]   || (handle[eventConfig.e]   = {}),
				namespace = evt[eventConfig.ns]     || (evt[eventConfig.ns]     = []);

			return namespace;
		};

	var Signal = function() {
		/**
		 * Holds active events by handle + event + namespace
		 * @type {Object}
		 */
		this._active = {};

		/**
		 * Holds inactive events by handle - lazy creation
		 * @type {Object}
		 */
		// this._inactive;

		/**
		 * Holds subscriptions - lazy creation
		 * @type {Object}
		 */
		// this._subs;
	};

	_extend(Signal, {

		/**
		 * Returns a new Signal instance
		 * @return {Signal}
		 */
		construct: function() {
			return new Signal();
		},

		/**
		 * Klass extend method
		 * @param  {Function} constructor
		 * @param  {Object} extension   prototype extension
		 * @return {Function} constructor
		 */
		extend: function(constructor, extension) {
			var hasConstructor = (typeof constructor === 'function');
			if (!hasConstructor) { extension = constructor; }

			var self = this,
				fn = function() {
					var ret = self.apply(this, arguments);
					if (hasConstructor) {
						ret = constructor.apply(this, arguments);
					}
					return ret;
				};

			// Add properties to the object
			_extend(fn, this);

			// Duplicate the prototype
			var NoOp = function() {};
			NoOp.prototype = this.prototype;
			fn.prototype = new NoOp();

			// Merge the prototypes
			_extend(fn.prototype, this.prototype, extension);
			fn.prototype.constructor = constructor || fn;

			return fn;
		}
	});

	Signal.prototype = {

		constructor: Signal,

		subscribe: function(name, func) {
			var subscriptions = this._subs || (this._subs = {});

			var id = _uniqueId(),
				location = subscriptions[name] || (subscriptions[name] = []);

			func.__subid__ = id;
			location.push(func);

			return id;
		},

		unsubscribe: function(name, id) {
			var subscriptions = this._subs || (this._subs = {});

			var location = subscriptions[name];
			if (!location) { return; }

			var idx = 0, length = location.length;
			for (; idx < length; idx += 1) {
				if (location[idx].__subid__ === id) {
					location.splice(idx, 1);
					return true;
				}
			}

			return false;
		},

		dispatch: function() {
			var subscriptions = this._subs || (this._subs = {});

			var args = arguments,
				name = _ripFirstArg(args),
				location = subscriptions[name] || (subscriptions[name] = []),
				idx = 0, length = location.length,
				func;
			for (; idx < length; idx++) {
				func = location[idx];
				if (func) { func.apply(null, args); }
			}
		},

		// Disable | Enable *************************************
		disable: function(handle) {
			var active = this._active,
				inactive = this._inactive || (this._inactive = {});

			_reassignEvents(handle, active, inactive);

			return this;
		},

		enable: function(handle) {
			var active = this._active,
				inactive = this._inactive || (this._inactive = {});

			_reassignEvents(handle, inactive, active);

			return this;
		},

		// On | Off ************************************************
		on: function(eventname, callback) {
			var eventConfig = _cache[eventname] || (_cache[eventname] = _parseConfig(eventname));

			_eventLookup(eventConfig, this._active).push(callback);

			return this;
		},
		bind: function() { this.on.apply(this, arguments); },

		off: function(eventname) {
			var active = this._active,
				eventConfig = _cache[eventname] || (_cache[eventname] = _parseConfig(eventname));

			if (eventConfig.e === '') { // Removing a namespace

				var events = active[eventConfig.h],
					eventName,
					namespaceName;
				for (eventName in events) {
					for (namespaceName in events[eventName]) {
						if (namespaceName === eventConfig.ns) {
							active[eventConfig.h][eventName][namespaceName].length = 0;
						}
					}
				}

			} else if (eventConfig.ns !== '') { // Has a namespace

				if (active[eventConfig.h] &&
					active[eventConfig.h][eventConfig.e] &&
						active[eventConfig.h][eventConfig.e][eventConfig.ns]) {

					active[eventConfig.h][eventConfig.e][eventConfig.ns].length = 0;

				}

			} else { // Does not have a namespace

				if (active[eventConfig.h]) {
					active[eventConfig.h][eventConfig.e] = { '': [] };
				}

			}

			return this;
		},
		unbind: function() { this.off.apply(this, arguments); },

		// Based on underscore's once implementation
		once: function(eventname, callback) {
			var hasRan = false,
				memo;
			return this.on(eventname, function() {
				if (hasRan) { return memo; }
				hasRan = true;

				memo = callback.apply(this, arguments);
				callback = null;

				return memo;
			});
		},

		// Trigger ************************************************
		trigger: function() {
			var args = arguments,
				active = this._active,
				eventname = _ripFirstArg(args),
				eventConfig = _cache[eventname] || (_cache[eventname] = _parseConfig(eventname)),
				// Always do an event lookup. This ensures that the location
				// of the event has been created so that calls to trigger
				// for events that haven't been registered don't throw exceptions
				location = _eventLookup(eventConfig, active);

			if (eventConfig.ns !== '') { // If there's a namespace, trigger only that array

				_callEvents(location, args);

			} else { // Else, trigger everything registered to the event

				var subSignal = active[eventConfig.h][eventConfig.e],
					key;
				for (key in subSignal) {
					_callEvents(subSignal[key], args);
				}

			}

			return this;
		},

		// ListenTo | StopListening ********************************
		listenTo: function(obj, eventname, callback) {
			obj.on(eventname, callback);
			return this;
		},
		stopListening: function(obj, eventname) {
			obj.off(eventname);
			return this;
		}
	};

	// Create a pub/sub to expose Signal as
	// e.g. Signal.on(), Signal.trigger()
	var pubSub = new Signal();

	// Attach the Signal object as a property
	// of the exposed object so that new instances
	// can be constructed/extended
	// e.g. Signal.core.construct(), Signal.core.extend({})
	pubSub.core = Signal;

	// Expose
	root.Signal = pubSub;

}(this));
<commit_msg>Fix event reassignment<commit_after>(function(name, definition) {

    if (typeof define === 'function') { // RequireJS
        define(function() { return definition; });
    } else if (typeof module !== 'undefined' && module.exports) { // CommonJS
        module.exports = definition;
    } else { // Browser
        this[name] = definition;
    }

})('signal', function(root, undefined) {

		/**
		 * Quick reference to Array.prototype.splice
		 * for duplicating arrays (while removing the
		 * first parameter)
		 * @type {Function}
		 */
	var _ripFirstArg = (function(splice) {
			return function(arr) {
				return splice.call(arr, 0, 1)[0];
			};
		}([].splice)),

		/**
		 * Object merger
		 * @param {Objects}
		 * @return {Object}
		 */
		_extend = function(base) {
			var args = arguments,
				idx = 1, length = args.length,
				key, merger;
			for (; idx < length; idx += 1) {
				merger = args[idx];

				for (key in merger) {
					base[key] = merger[key];
				}
			}

			return base;
		},

		/**
		 * Holds cached, parsed event keys by string
		 * @type {Object}
		 */
		_cache = {},

		/**
		 * Unique Id
		 * @type {Number}
		 */
		_id = 0,
		_uniqueId = function() {
			return _id++;
		},

		/**
		 * Cached regex used to parse event string
		 * @type {RegExp}
		 */
		_NAME_REGEX = /(?:([\w-]+):)?([\w-]*)(?:.([\w-]+))?/,
		_parseConfig = function(eventname) {
			var match = _NAME_REGEX.exec(eventname);
			return {
				// [0] : the entire match, don't care!
				// [1] : handle
				h:  (match[1] === undefined) ? '' : match[1],
				// [2] : event
				e:  (match[2] === undefined) ? '' : match[2],
				// [3] : namespace
				ns: (match[3] === undefined) ? '' : match[3]
			};
		},

		_reassignEvents = function(handle, first, second) {
			second[handle] = second[handle] || {};
			_extend(second[handle], first[handle]);
			delete first[handle];
		},

		_callEvents = function(events, args) {
			args = args || [];

			var idx = 0, length = events.length,
				evt;
			for (; idx < length; idx += 1) {
				evt = events[idx];
				if (!evt) { continue; }
				if (evt.apply(null, args) === false) { return; }
			}
		},

		_eventLookup = function(eventConfig, location) {
			var handle    = location[eventConfig.h] || (location[eventConfig.h] = {}),
				evt       = handle[eventConfig.e]   || (handle[eventConfig.e]   = {}),
				namespace = evt[eventConfig.ns]     || (evt[eventConfig.ns]     = []);

			return namespace;
		};

	var Signal = function() {
		/**
		 * Holds active events by handle + event + namespace
		 * @type {Object}
		 */
		this._active = {};

		/**
		 * Holds inactive events by handle - lazy creation
		 * @type {Object}
		 */
		// this._inactive;

		/**
		 * Holds subscriptions - lazy creation
		 * @type {Object}
		 */
		// this._subs;
	};

	_extend(Signal, {

		/**
		 * Returns a new Signal instance
		 * @return {Signal}
		 */
		construct: function() {
			return new Signal();
		},

		/**
		 * Klass extend method
		 * @param  {Function} constructor
		 * @param  {Object} extension   prototype extension
		 * @return {Function} constructor
		 */
		extend: function(constructor, extension) {
			var hasConstructor = (typeof constructor === 'function');
			if (!hasConstructor) { extension = constructor; }

			var self = this,
				fn = function() {
					var ret = self.apply(this, arguments);
					if (hasConstructor) {
						ret = constructor.apply(this, arguments);
					}
					return ret;
				};

			// Add properties to the object
			_extend(fn, this);

			// Duplicate the prototype
			var NoOp = function() {};
			NoOp.prototype = this.prototype;
			fn.prototype = new NoOp();

			// Merge the prototypes
			_extend(fn.prototype, this.prototype, extension);
			fn.prototype.constructor = constructor || fn;

			return fn;
		}
	});

	Signal.prototype = {

		constructor: Signal,

		subscribe: function(name, func) {
			var subscriptions = this._subs || (this._subs = {});

			var id = _uniqueId(),
				location = subscriptions[name] || (subscriptions[name] = []);

			func.__subid__ = id;
			location.push(func);

			return id;
		},

		unsubscribe: function(name, id) {
			var subscriptions = this._subs || (this._subs = {});

			var location = subscriptions[name];
			if (!location) { return; }

			var idx = 0, length = location.length;
			for (; idx < length; idx += 1) {
				if (location[idx].__subid__ === id) {
					location.splice(idx, 1);
					return true;
				}
			}

			return false;
		},

		dispatch: function() {
			var subscriptions = this._subs || (this._subs = {});

			var args = arguments,
				name = _ripFirstArg(args),
				location = subscriptions[name] || (subscriptions[name] = []),
				idx = 0, length = location.length,
				func;
			for (; idx < length; idx++) {
				func = location[idx];
				if (func) { func.apply(null, args); }
			}
		},

		// Disable | Enable *************************************
		disable: function(handle) {
			var active = this._active,
				inactive = this._inactive || (this._inactive = {});

			_reassignEvents(handle, active, inactive);

			return this;
		},

		enable: function(handle) {
			var active = this._active,
				inactive = this._inactive || (this._inactive = {});

			_reassignEvents(handle, inactive, active);

			return this;
		},

		// On | Off ************************************************
		on: function(eventname, callback) {
			var eventConfig = _cache[eventname] || (_cache[eventname] = _parseConfig(eventname));

			_eventLookup(eventConfig, this._active).push(callback);

			return this;
		},
		bind: function() { this.on.apply(this, arguments); },

		off: function(eventname) {
			var active = this._active,
				eventConfig = _cache[eventname] || (_cache[eventname] = _parseConfig(eventname));

			if (eventConfig.e === '') { // Removing a namespace

				var events = active[eventConfig.h],
					eventName,
					namespaceName;
				for (eventName in events) {
					for (namespaceName in events[eventName]) {
						if (namespaceName === eventConfig.ns) {
							active[eventConfig.h][eventName][namespaceName].length = 0;
						}
					}
				}

			} else if (eventConfig.ns !== '') { // Has a namespace

				if (active[eventConfig.h] &&
					active[eventConfig.h][eventConfig.e] &&
						active[eventConfig.h][eventConfig.e][eventConfig.ns]) {

					active[eventConfig.h][eventConfig.e][eventConfig.ns].length = 0;

				}

			} else { // Does not have a namespace

				if (active[eventConfig.h]) {
					active[eventConfig.h][eventConfig.e] = { '': [] };
				}

			}

			return this;
		},
		unbind: function() { this.off.apply(this, arguments); },

		// Based on underscore's once implementation
		once: function(eventname, callback) {
			var hasRan = false,
				memo;
			return this.on(eventname, function() {
				if (hasRan) { return memo; }
				hasRan = true;

				memo = callback.apply(this, arguments);
				callback = null;

				return memo;
			});
		},

		// Trigger ************************************************
		trigger: function() {
			var args = arguments,
				active = this._active,
				eventname = _ripFirstArg(args),
				eventConfig = _cache[eventname] || (_cache[eventname] = _parseConfig(eventname)),
				// Always do an event lookup. This ensures that the location
				// of the event has been created so that calls to trigger
				// for events that haven't been registered don't throw exceptions
				location = _eventLookup(eventConfig, active);

			if (eventConfig.ns !== '') { // If there's a namespace, trigger only that array

				_callEvents(location, args);

			} else { // Else, trigger everything registered to the event

				var subSignal = active[eventConfig.h][eventConfig.e],
					key;
				for (key in subSignal) {
					_callEvents(subSignal[key], args);
				}

			}

			return this;
		},

		// ListenTo | StopListening ********************************
		listenTo: function(obj, eventname, callback) {
			obj.on(eventname, callback);
			return this;
		},
		stopListening: function(obj, eventname) {
			obj.off(eventname);
			return this;
		}
	};

	// Create a pub/sub to expose Signal as
	// e.g. Signal.on(), Signal.trigger()
	var pubSub = new Signal();

	// Attach the Signal object as a property
	// of the exposed object so that new instances
	// can be constructed/extended
	// e.g. Signal.core.construct(), Signal.core.extend({})
	pubSub.core = Signal;

	// Expose
	root.Signal = pubSub;

}(this));
<|endoftext|>


<commit_before>/*\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

	LANGENIUM CLIENT

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/

/*\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
	Globals
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/

// This object
var client = function() {

	this.camera;
	this.instance_id;
	this.isFiring = false;
	this.winW = 1024;
	this.winH = 768;

	if (window.location.href.indexOf("editor") > 0) { this.is_editor = true; } else { this.is_editor = false; }

	return this;
}

/*\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
	Function Definitions
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/

client.prototype.initialize = function () {
/*
	Initializes the client... :P
*/
	engine.renderer = new THREE.WebGLRenderer({
		antialias : true
	});

	engine.renderer.setSize( client.winW, client.winH);

	events.socket.emit("login", { username: "Droopy", editor: client.is_editor });
	$("#game").append(engine.renderer.domElement);

	window.addEventListener( 'resize', client.onWindowResize, false );
}

client.prototype.onWindowResize = function () {
/*
	Resizes the engine.renderer
*/
	client.updateWinSizeVariables();
	client.camera.aspect = client.winW / client.winH;
	client.camera.updateProjectionMatrix();

	engine.renderer.setSize( client.winW, client.winH );
}

client.prototype.updateWinSizeVariables = function (){
/*
	Update the global window variables
*/
	if (document.body && document.body.offsetWidth) {
		client.winW = document.body.offsetWidth;
		client.winH = document.body.offsetHeight;
	}
	if (document.compatMode=='CSS1Compat' &&
		document.documentElement &&
		document.documentElement.offsetWidth ) {
		client.winW = document.documentElement.offsetWidth;
		client.winH = document.documentElement.offsetHeight;
	}
	if (window.innerWidth && window.innerHeight) {
		client.winW = window.innerWidth;
		client.winH = window.innerHeight;
	}
}

<commit_msg>Made play and editor default to different scenes<commit_after>/*\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

	LANGENIUM CLIENT

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/

/*\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
	Globals
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/

// This object
var client = function() {

	this.camera;
	this.instance_id;
	this.isFiring = false;
	this.winW = 1024;
	this.winH = 768;

	if (window.location.href.indexOf("editor") > 0) { this.is_editor = true; } else { this.is_editor = false; }

	return this;
}

/*\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
	Function Definitions
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/

client.prototype.initialize = function () {
/*
	Initializes the client... :P
*/
	engine.renderer = new THREE.WebGLRenderer({
		antialias : true
	});

	engine.renderer.setSize( client.winW, client.winH);
	var username;

	if (client.is_editor == true) {
		username = "Droopy";
	}
	else {
		username = "Saggy";
	}

	events.socket.emit("login", { username: username, editor: client.is_editor });
	$("#game").append(engine.renderer.domElement);

	window.addEventListener( 'resize', client.onWindowResize, false );
}

client.prototype.onWindowResize = function () {
/*
	Resizes the engine.renderer
*/
	client.updateWinSizeVariables();
	client.camera.aspect = client.winW / client.winH;
	client.camera.updateProjectionMatrix();

	engine.renderer.setSize( client.winW, client.winH );
}

client.prototype.updateWinSizeVariables = function (){
/*
	Update the global window variables
*/
	if (document.body && document.body.offsetWidth) {
		client.winW = document.body.offsetWidth;
		client.winH = document.body.offsetHeight;
	}
	if (document.compatMode=='CSS1Compat' &&
		document.documentElement &&
		document.documentElement.offsetWidth ) {
		client.winW = document.documentElement.offsetWidth;
		client.winH = document.documentElement.offsetHeight;
	}
	if (window.innerWidth && window.innerHeight) {
		client.winW = window.innerWidth;
		client.winH = window.innerHeight;
	}
}

<|endoftext|>


<commit_before>'use strict';

import Base from './base.js';

export default class extends Base {
  /**
   * index action
   * @return {Promise} []
   */
  async getAction(){
    let data = await this.session('userInfo');
    this.success(data);
  }
  async setAction(){
    let data = {
      name: 'wwww'
    }
    await this.session('userInfo', data);
    this.success();
  }
}<commit_msg>update file session<commit_after>'use strict';

import Base from './base.js';

export default class extends Base {
  /**
   * index action
   * @return {Promise} []
   */
  async getAction(){
    let data = await this.session('userInfo');
    this.success(data);
  }
  async setAction(){
    let data = {
      name: this.get('name') || 'wwww'
    }
    await this.session('userInfo', data);
    return this.redirect('/session/get');
  }
  async deleteAction(){
    await this.session();
    return this.redirect('/session/get');
  }
}<|endoftext|>


<commit_before>var CloudCmd, Util, DOM, CloudFunc, ace, DiffProto, diff_match_patch, Zip, MenuIO, Format;
(function(CloudCmd, Util, DOM, CloudFunc) {
    'use strict';

    CloudCmd.Edit = EditProto;

    function EditProto(callback) {
        var Name        = 'Edit',
            Loading     = true,
            DIR         = CloudCmd.LIBDIRCLIENT + 'edit/',
            LIBDIR      = CloudCmd.LIBDIR,
            Info        = DOM.CurrentInfo,
            Files       = DOM.Files,
            Storage     = DOM.Storage,
            type        = Util.type,
            exec        = Util.exec,
            join        = CloudCmd.join,

            Menu,
            Value,
            Edit        = this,
            Diff,
            Emmet,
            Ace,
            Session,
            Modelist,
            Events      = DOM.Events,
            RESTful     = DOM.RESTful,
            Dialog      = DOM.Dialog,
            Images      = DOM.Images,
            Element, JSHintConfig,
            ConfigView  = {
                beforeClose: function() {
                    isChanged();
                    exec.ifExist(Menu, 'hide');
                },
                afterShow: function() {
                    Ace.clearSelection();
                    Ace.moveCursorTo(0, 0);
                    Ace.focus();
                }
            };

       function init(callback) {
            exec.series([
                CloudCmd.View,
                load,
                Edit.show.bind(null, callback)
            ]);
        }

        this.show                       = function(callback) {
            var func    = exec.ret(callback);

            if (!Loading) {
                Images.showLoad();

                if (!Element) {
                    Element         = DOM.load({
                        name        : 'div',
                        style   :
                            'width      : 100%;'    +
                            'height     : 100%;'    +
                            'font       : 16px "Droid Sans Mono";' +
                            'position   : absolute;',
                        notAppend : true
                    });

                    initAce();

                    Events.add(Element, {
                            contextmenu :   setMenu,
                            drop        :   onDrop,
                            dragover    :   Events.preventDefault
                        });
                }

                getData(function(error, data) {
                    Edit.setValue(data);

                    ConfigView.beforeShow = func;

                    CloudCmd.View.show(Element, ConfigView);
                });
            }
        };

        this.setValue                   = function(value) {
            var UndoManager = ace.require('ace/undomanager').UndoManager;

            Value           = value;

            Ace.setValue(value);
            Session.setUndoManager(new UndoManager());
        };

        this.hide                       = function() {
            CloudCmd.View.hide();
        };

        this.goToLine                   = function() {
            var msg     = 'Enter line number:',
                cursor  = Ace.selection.getCursor(),
                number  = cursor.row + 1,
                line    = Dialog.prompt(msg, number);

            number      = line - 0;

            if (number)
                Ace.gotoLine(number);
        };

        function getData(callback) {
            var name        = Info.name,
                isDir       = Info.isDir;

            Util.checkArgs(arguments, ['callback']);

            if (isDir)
                Edit.setMode('json');
            else
                Edit.setModeForPath(name);

            Info.getData(callback);
        }

        this.setModeForPath             = function(name) {
            var modesByName = Modelist.modesByName,
                mode        = Modelist.getModeForPath(name).mode,

                htmlMode    = modesByName.html.mode,
                jsMode      = modesByName.javascript.mode,

                isHTML      = mode === htmlMode,
                isJS        = mode === jsMode;

            Session.setMode(mode, function() {
                setUseOfWorker(mode);

                if (isHTML)
                    setEmmet();

                if (isJS && Session.getUseWorker())
                    setJsHintConfig();
            });
        };

        this.setMode                    = function(mode) {
            var ext,
                modesByName = Modelist.modesByName;

            if (modesByName[mode]) {
                ext = modesByName[mode].extensions.split('|')[0];
                Edit.setModeForPath('.' + ext);
            }
        };

        function isChanged() {
            var is,
                value   = Ace.getValue(),
                isEqual = value === Value,
                msg     = 'Do you want to save changes to ' + name + '?';

            if (!isEqual) {
                is = Dialog.confirm(msg);

                if (is)
                    save();
            }
        }

        function setEmmet() {
            Files.get('edit', function(error, config) {
                var extensions  = config.extensions,
                    isEmmet     = extensions.emmet;

                if (isEmmet)
                    exec.if(Emmet, function() {
                        Ace.setOption('enableEmmet', true);
                    }, function(callback) {
                        var url;

                        url = join([
                            DIR + 'emmet.js',
                            DIR + 'ext-emmet.js'
                        ]);

                        DOM.load.js(url, function() {
                            Emmet = ace.require('ace/ext/emmet');
                            Emmet.setCore(window.emmet);

                            callback();
                        });
                    });
                });
        }

        function setUseOfWorker(mode) {
            var isMatch,
                isStr   = type.string(mode),
                regStr  = 'coffee|css|html|javascript|json|lua|php|xquery',
                regExp  = new RegExp(regStr);

            if (isStr)
                isMatch = regExp.test(mode);

            Session.setUseWorker(isMatch);
        }

        function initAce() {
            Ace     = ace.edit(Element);
            Session = Ace.getSession();

            Ace.commands.addCommand({
                name    : 'hide',
                bindKey : { win: 'Esc',  mac: 'Esc' },
                exec    : function () {
                    Edit.hide();
                }
            });

            Ace.commands.addCommand({
                name    : 'goToLine',
                bindKey : { win: 'Ctrl-G',  mac: 'Command-G' },
                exec    : function () {
                    Edit.goToLine();
                }
            });

            Ace.commands.addCommand({
                name    : 'save',
                bindKey : { win: 'Ctrl-S',  mac: 'Command-S' },
                exec    : save
            });

            Ace.commands.addCommand({
                name    : 'saveMC',
                bindKey : { win: 'F2',  mac: 'F2' },
                exec    : save
            });

            Ace.commands.addCommand({
                name    : 'beautify',
                bindKey : { win: 'Ctrl-B',  mac: 'Command-B' },
                exec    : function() {
                    Edit.beautify();
                }
            });

            Ace.commands.addCommand({
                name    : 'minify',
                bindKey : { win: 'Ctrl-M',  mac: 'Command-M' },
                exec    : function() {
                    Edit.minify();
                }
            });

            ace.require('ace/ext/language_tools');
            Modelist = ace.require('ace/ext/modelist');

            Files.get('edit', function(error, config) {
                var options      = config.options;

                Ace.setOptions(options);
            });
        }

        function save () {
            var path    = Info.path,
                value   = Ace.getValue();

            Files.get('config', function(error, config) {
                var isDiff      = config.diff,
                    isZip       = config.zip;

                exec.if(!isDiff, function(patch) {
                    var query           = '',
                        MAX_SIZE        = CloudFunc.MAX_FILE_SIZE,
                        patchLength     = patch.length,
                        length          = Value.length,
                        isLessMaxLength = length < MAX_SIZE,
                        isLessLength    = isLessMaxLength && patchLength < length,
                        isStr           = type.string(patch),
                        isPatch         = patch && isStr && isLessLength;

                    Value               = value;

                    exec.if(!isZip || isPatch, function(equal, data) {
                        var result  = data || Value;

                        if (isPatch)
                            RESTful.patch(path, patch, onSave);
                        else
                            RESTful.write(path + query, result, onSave);
                    }, function(func) {
                        zip(value, function(error, data) {
                            if (error)
                                Util.log(error);

                            query = '?unzip';
                            func(null, data);
                        });
                    });

                }, exec.with(doDiff, path));
            });
        }

        function doDiff(path, callback) {
            var value = Ace.getValue();

            diff(value, function(patch) {
                var isAllowed = Storage.isAllowed();

                exec.if(!isAllowed, callback, function(func) {
                        DOM.checkStorageHash(path, function(error, equal) {
                            if (!equal)
                                patch = '';

                            func(patch);
                        });
                });
            });
        }

        function diff(newValue, callback) {
            var url = join([
                    LIBDIR + 'diff/diff-match-patch.js',
                    LIBDIR + 'diff.js'
                ]);

            DOM.load.js(url, function(error) {
                var patch,
                    isAllowed   = Storage.isAllowed();

                if (error) {
                    Dialog.alert(error);
                } else {
                    if (!Diff)
                        Diff        = new DiffProto(diff_match_patch);

                    exec.if(!isAllowed, function() {
                        patch       = Diff.createPatch(Value, newValue);
                        exec(callback, patch);
                    }, function(func) {
                        var path = Info.path;

                        DOM.getDataFromStorage(path, function(error, data) {
                            if (data)
                                Value   = data;

                            func();
                        });
                    });
                }
            });
        }

        function zip(value, callback) {
            var dir             = CloudCmd.LIBDIRCLIENT,
                url             = join([
                    dir + 'zip/dist/pako.js',
                    dir + 'zip.js'
                ]);

            DOM.load.js(url, function() {
                Zip.pack(value, callback);
            });
        }

        function sha(callback) {
            var dir             = CloudCmd.LIBDIR,
                url             = dir + 'sha/jsSHA.js';

            DOM.load.js(url, function() {
                var shaObj, hash, error,
                    value   = Ace.getValue();

                error = Util.exec.try(function() {
                    shaObj  = new window.jsSHA(value, 'TEXT');
                    hash    = shaObj.getHash('SHA-1', 'HEX');
                });

                callback(error, hash);
            });
        }

        function setJsHintConfig(callback) {
            var JSHINT_PATH = CloudCmd.PREFIX + '/.jshintrc',
                func        = function() {
                    var worker  = Session.$worker;

                    if (worker)
                        worker.send('changeOptions', [JSHintConfig]);

                    exec(callback);
                };

            exec.if(JSHintConfig, func, function() {
                DOM.load.ajax({
                    url     :  JSHINT_PATH,
                    success : function(data) {
                        JSHintConfig = Util.json.parse(data);
                        func();
                    }
                });
            });
        }

        function setMenu() {
            if (!Menu) {
                DOM.loadMenu(function(error) {
                    var position    = CloudCmd.MousePosition,
                        options     = {
                            beforeShow: function(params) {
                                params.x -= 18;
                                params.y -= 27;
                            },
                            afterClick: function() {
                                Ace.focus();
                            }
                    },
                    menuData    = {
                        'Save           Ctrl+S' : save,
                        'Go To Line     Ctrl+G' : function() {
                            Edit.goToLine();
                        },
                        'Select All     Ctrl+A' : function() {
                            Ace.selectAll();
                        },
                        'Delete         Del'    : function() {
                            Ace.remove('right');
                        },
                        'Beautify       Ctrl+B' : function() {
                            Edit.beautify();
                        },
                        'Minify         Ctrl+M' : function() {
                            Edit.minify();
                        },
                        'Close          Esc'    : Edit.hide
                    };

                    if (error) {
                        Dialog.alert(error);
                    } else if (!Menu) {
                        Menu        = new MenuIO(Element, options, menuData);
                        Menu.show(position.x, position.y);

                        Events.remove('contextMenu', Element, setMenu);
                    }
                });
            }
        }

        function load(callback) {
            var url     = join([
                    'theme-tomorrow_night_blue',
                    'ext-language_tools',
                    'ext-searchbox',
                    'ext-modelist'
                ].map(function(name) {
                    return DIR + name + '.js';
                }));

            Util.time(Name + ' load');

            DOM.loadRemote('ace', function() {
                DOM.load.js(url, function() {
                    Loading = false;

                    Util.timeEnd(Name + ' load');
                    exec(callback);
                });

                DOM.load.style({
                    id      : 'msg-css',
                    inner   : '#js-view .msg {'     +
                                'z-index'           + ': 1;'                    +
                                'background-color'  + ': #7285B7;'              +
                                'color'             + ': #D1F1A9;'              +
                                'position'          + ': fixed;'                +
                                'left'              + ': 40%;'                  +
                                'top'               + ': 25px;'                 +
                                'padding'           + ': 5px;'                  +
                                'opacity'           + ': 0.9;'                  +
                                'transition'        + ': ease 0.5s;'            +
                            '}'
                });
            });
        }

        function onSave(text) {
            var ret,
                size    = Format.size(Value.length),
                isError = Util.isContainStrAtBegin(text, 'error'),
                path    = Info.path,
                msg     = '\nShould I save file anyway?';

            if (!isError) {
                Edit.showMessage(text);

                sha(function(error, hash) {
                    if (error)
                        Util.log(error);

                    DOM.saveDataToStorage(path, Value, hash);
                });

                DOM.setCurrentSize(size);
            } else {
                ret     = Dialog.confirm(text + msg);

                if (ret)
                    RESTful.write(path, Value, onSave);
            }
        }

        Edit.beautify = function() {
           readWithFlag('beautify');
        };

        Edit.minify = function() {
            readWithFlag('minify');
        };

        function readWithFlag(flag) {
            var path = Info.path;

            Util.checkArgs(arguments, ['flag']);

            RESTful.read(path + '?' + flag, function(data) {
                Ace.setValue(data);
                Ace.clearSelection();
                Ace.moveCursorTo(0, 0);
            });
        }

        function onDrop(event) {
            var reader, files,
                onLoad   =  function(event) {
                    var data    = event.target.result;

                    Ace.setValue(data);
                };

            event.preventDefault();

            files   = event.dataTransfer.files;

            Util.forEach(files, function(file) {
                reader  = new FileReader();
                Events.addLoad(reader, onLoad);
                reader.readAsBinaryString(file);
            });
        }

        this.showMessage    = function(text) {
            var msg, HIDE_TIME = 2000;

            /*
             * Msg should be created and removed
             * if it's not and just inner text
             * is changing, and hide and show of DOM
             * is called - bug occures: empty box
             * with no text inside.
             */
            msg = DOM.load({
                name        : 'div',
                className   : 'msg',
                parent      : Element,
                inner       : text,
                func        : alert
            });

            setTimeout(function() {
                DOM.remove(msg, Element);
            }, HIDE_TIME);
        };

        init(callback);
    }

})(CloudCmd, Util, DOM, CloudFunc);
<commit_msg>refactor(edit) onSave isContainStrAtBegin(text, error) -> /^error/.test(text)<commit_after>var CloudCmd, Util, DOM, CloudFunc, ace, DiffProto, diff_match_patch, Zip, MenuIO, Format;
(function(CloudCmd, Util, DOM, CloudFunc) {
    'use strict';

    CloudCmd.Edit = EditProto;

    function EditProto(callback) {
        var Name        = 'Edit',
            Loading     = true,
            DIR         = CloudCmd.LIBDIRCLIENT + 'edit/',
            LIBDIR      = CloudCmd.LIBDIR,
            Info        = DOM.CurrentInfo,
            Files       = DOM.Files,
            Storage     = DOM.Storage,
            type        = Util.type,
            exec        = Util.exec,
            join        = CloudCmd.join,

            Menu,
            Value,
            Edit        = this,
            Diff,
            Emmet,
            Ace,
            Session,
            Modelist,
            Events      = DOM.Events,
            RESTful     = DOM.RESTful,
            Dialog      = DOM.Dialog,
            Images      = DOM.Images,
            Element, JSHintConfig,
            ConfigView  = {
                beforeClose: function() {
                    isChanged();
                    exec.ifExist(Menu, 'hide');
                },
                afterShow: function() {
                    Ace.clearSelection();
                    Ace.moveCursorTo(0, 0);
                    Ace.focus();
                }
            };

       function init(callback) {
            exec.series([
                CloudCmd.View,
                load,
                Edit.show.bind(null, callback)
            ]);
        }

        this.show                       = function(callback) {
            var func    = exec.ret(callback);

            if (!Loading) {
                Images.showLoad();

                if (!Element) {
                    Element         = DOM.load({
                        name        : 'div',
                        style   :
                            'width      : 100%;'    +
                            'height     : 100%;'    +
                            'font       : 16px "Droid Sans Mono";' +
                            'position   : absolute;',
                        notAppend : true
                    });

                    initAce();

                    Events.add(Element, {
                            contextmenu :   setMenu,
                            drop        :   onDrop,
                            dragover    :   Events.preventDefault
                        });
                }

                getData(function(error, data) {
                    Edit.setValue(data);

                    ConfigView.beforeShow = func;

                    CloudCmd.View.show(Element, ConfigView);
                });
            }
        };

        this.setValue                   = function(value) {
            var UndoManager = ace.require('ace/undomanager').UndoManager;

            Value           = value;

            Ace.setValue(value);
            Session.setUndoManager(new UndoManager());
        };

        this.hide                       = function() {
            CloudCmd.View.hide();
        };

        this.goToLine                   = function() {
            var msg     = 'Enter line number:',
                cursor  = Ace.selection.getCursor(),
                number  = cursor.row + 1,
                line    = Dialog.prompt(msg, number);

            number      = line - 0;

            if (number)
                Ace.gotoLine(number);
        };

        function getData(callback) {
            var name        = Info.name,
                isDir       = Info.isDir;

            Util.checkArgs(arguments, ['callback']);

            if (isDir)
                Edit.setMode('json');
            else
                Edit.setModeForPath(name);

            Info.getData(callback);
        }

        this.setModeForPath             = function(name) {
            var modesByName = Modelist.modesByName,
                mode        = Modelist.getModeForPath(name).mode,

                htmlMode    = modesByName.html.mode,
                jsMode      = modesByName.javascript.mode,

                isHTML      = mode === htmlMode,
                isJS        = mode === jsMode;

            Session.setMode(mode, function() {
                setUseOfWorker(mode);

                if (isHTML)
                    setEmmet();

                if (isJS && Session.getUseWorker())
                    setJsHintConfig();
            });
        };

        this.setMode                    = function(mode) {
            var ext,
                modesByName = Modelist.modesByName;

            if (modesByName[mode]) {
                ext = modesByName[mode].extensions.split('|')[0];
                Edit.setModeForPath('.' + ext);
            }
        };

        function isChanged() {
            var is,
                value   = Ace.getValue(),
                isEqual = value === Value,
                msg     = 'Do you want to save changes to ' + name + '?';

            if (!isEqual) {
                is = Dialog.confirm(msg);

                if (is)
                    save();
            }
        }

        function setEmmet() {
            Files.get('edit', function(error, config) {
                var extensions  = config.extensions,
                    isEmmet     = extensions.emmet;

                if (isEmmet)
                    exec.if(Emmet, function() {
                        Ace.setOption('enableEmmet', true);
                    }, function(callback) {
                        var url;

                        url = join([
                            DIR + 'emmet.js',
                            DIR + 'ext-emmet.js'
                        ]);

                        DOM.load.js(url, function() {
                            Emmet = ace.require('ace/ext/emmet');
                            Emmet.setCore(window.emmet);

                            callback();
                        });
                    });
                });
        }

        function setUseOfWorker(mode) {
            var isMatch,
                isStr   = type.string(mode),
                regStr  = 'coffee|css|html|javascript|json|lua|php|xquery',
                regExp  = new RegExp(regStr);

            if (isStr)
                isMatch = regExp.test(mode);

            Session.setUseWorker(isMatch);
        }

        function initAce() {
            Ace     = ace.edit(Element);
            Session = Ace.getSession();

            Ace.commands.addCommand({
                name    : 'hide',
                bindKey : { win: 'Esc',  mac: 'Esc' },
                exec    : function () {
                    Edit.hide();
                }
            });

            Ace.commands.addCommand({
                name    : 'goToLine',
                bindKey : { win: 'Ctrl-G',  mac: 'Command-G' },
                exec    : function () {
                    Edit.goToLine();
                }
            });

            Ace.commands.addCommand({
                name    : 'save',
                bindKey : { win: 'Ctrl-S',  mac: 'Command-S' },
                exec    : save
            });

            Ace.commands.addCommand({
                name    : 'saveMC',
                bindKey : { win: 'F2',  mac: 'F2' },
                exec    : save
            });

            Ace.commands.addCommand({
                name    : 'beautify',
                bindKey : { win: 'Ctrl-B',  mac: 'Command-B' },
                exec    : function() {
                    Edit.beautify();
                }
            });

            Ace.commands.addCommand({
                name    : 'minify',
                bindKey : { win: 'Ctrl-M',  mac: 'Command-M' },
                exec    : function() {
                    Edit.minify();
                }
            });

            ace.require('ace/ext/language_tools');
            Modelist = ace.require('ace/ext/modelist');

            Files.get('edit', function(error, config) {
                var options      = config.options;

                Ace.setOptions(options);
            });
        }

        function save () {
            var path    = Info.path,
                value   = Ace.getValue();

            Files.get('config', function(error, config) {
                var isDiff      = config.diff,
                    isZip       = config.zip;

                exec.if(!isDiff, function(patch) {
                    var query           = '',
                        MAX_SIZE        = CloudFunc.MAX_FILE_SIZE,
                        patchLength     = patch.length,
                        length          = Value.length,
                        isLessMaxLength = length < MAX_SIZE,
                        isLessLength    = isLessMaxLength && patchLength < length,
                        isStr           = type.string(patch),
                        isPatch         = patch && isStr && isLessLength;

                    Value               = value;

                    exec.if(!isZip || isPatch, function(equal, data) {
                        var result  = data || Value;

                        if (isPatch)
                            RESTful.patch(path, patch, onSave);
                        else
                            RESTful.write(path + query, result, onSave);
                    }, function(func) {
                        zip(value, function(error, data) {
                            if (error)
                                Util.log(error);

                            query = '?unzip';
                            func(null, data);
                        });
                    });

                }, exec.with(doDiff, path));
            });
        }

        function doDiff(path, callback) {
            var value = Ace.getValue();

            diff(value, function(patch) {
                var isAllowed = Storage.isAllowed();

                exec.if(!isAllowed, callback, function(func) {
                        DOM.checkStorageHash(path, function(error, equal) {
                            if (!equal)
                                patch = '';

                            func(patch);
                        });
                });
            });
        }

        function diff(newValue, callback) {
            var url = join([
                    LIBDIR + 'diff/diff-match-patch.js',
                    LIBDIR + 'diff.js'
                ]);

            DOM.load.js(url, function(error) {
                var patch,
                    isAllowed   = Storage.isAllowed();

                if (error) {
                    Dialog.alert(error);
                } else {
                    if (!Diff)
                        Diff        = new DiffProto(diff_match_patch);

                    exec.if(!isAllowed, function() {
                        patch       = Diff.createPatch(Value, newValue);
                        exec(callback, patch);
                    }, function(func) {
                        var path = Info.path;

                        DOM.getDataFromStorage(path, function(error, data) {
                            if (data)
                                Value   = data;

                            func();
                        });
                    });
                }
            });
        }

        function zip(value, callback) {
            var dir             = CloudCmd.LIBDIRCLIENT,
                url             = join([
                    dir + 'zip/dist/pako.js',
                    dir + 'zip.js'
                ]);

            DOM.load.js(url, function() {
                Zip.pack(value, callback);
            });
        }

        function sha(callback) {
            var dir             = CloudCmd.LIBDIR,
                url             = dir + 'sha/jsSHA.js';

            DOM.load.js(url, function() {
                var shaObj, hash, error,
                    value   = Ace.getValue();

                error = Util.exec.try(function() {
                    shaObj  = new window.jsSHA(value, 'TEXT');
                    hash    = shaObj.getHash('SHA-1', 'HEX');
                });

                callback(error, hash);
            });
        }

        function setJsHintConfig(callback) {
            var JSHINT_PATH = CloudCmd.PREFIX + '/.jshintrc',
                func        = function() {
                    var worker  = Session.$worker;

                    if (worker)
                        worker.send('changeOptions', [JSHintConfig]);

                    exec(callback);
                };

            exec.if(JSHintConfig, func, function() {
                DOM.load.ajax({
                    url     :  JSHINT_PATH,
                    success : function(data) {
                        JSHintConfig = Util.json.parse(data);
                        func();
                    }
                });
            });
        }

        function setMenu() {
            if (!Menu) {
                DOM.loadMenu(function(error) {
                    var position    = CloudCmd.MousePosition,
                        options     = {
                            beforeShow: function(params) {
                                params.x -= 18;
                                params.y -= 27;
                            },
                            afterClick: function() {
                                Ace.focus();
                            }
                    },
                    menuData    = {
                        'Save           Ctrl+S' : save,
                        'Go To Line     Ctrl+G' : function() {
                            Edit.goToLine();
                        },
                        'Select All     Ctrl+A' : function() {
                            Ace.selectAll();
                        },
                        'Delete         Del'    : function() {
                            Ace.remove('right');
                        },
                        'Beautify       Ctrl+B' : function() {
                            Edit.beautify();
                        },
                        'Minify         Ctrl+M' : function() {
                            Edit.minify();
                        },
                        'Close          Esc'    : Edit.hide
                    };

                    if (error) {
                        Dialog.alert(error);
                    } else if (!Menu) {
                        Menu        = new MenuIO(Element, options, menuData);
                        Menu.show(position.x, position.y);

                        Events.remove('contextMenu', Element, setMenu);
                    }
                });
            }
        }

        function load(callback) {
            var url     = join([
                    'theme-tomorrow_night_blue',
                    'ext-language_tools',
                    'ext-searchbox',
                    'ext-modelist'
                ].map(function(name) {
                    return DIR + name + '.js';
                }));

            Util.time(Name + ' load');

            DOM.loadRemote('ace', function() {
                DOM.load.js(url, function() {
                    Loading = false;

                    Util.timeEnd(Name + ' load');
                    exec(callback);
                });

                DOM.load.style({
                    id      : 'msg-css',
                    inner   : '#js-view .msg {'     +
                                'z-index'           + ': 1;'                    +
                                'background-color'  + ': #7285B7;'              +
                                'color'             + ': #D1F1A9;'              +
                                'position'          + ': fixed;'                +
                                'left'              + ': 40%;'                  +
                                'top'               + ': 25px;'                 +
                                'padding'           + ': 5px;'                  +
                                'opacity'           + ': 0.9;'                  +
                                'transition'        + ': ease 0.5s;'            +
                            '}'
                });
            });
        }

        function onSave(text) {
            var ret,
                size    = Format.size(Value.length),
                isError = /^error/.test(text),
                path    = Info.path,
                msg     = '\nShould I save file anyway?';

            if (!isError) {
                Edit.showMessage(text);

                sha(function(error, hash) {
                    if (error)
                        Util.log(error);

                    DOM.saveDataToStorage(path, Value, hash);
                });

                DOM.setCurrentSize(size);
            } else {
                ret     = Dialog.confirm(text + msg);

                if (ret)
                    RESTful.write(path, Value, onSave);
            }
        }

        Edit.beautify = function() {
           readWithFlag('beautify');
        };

        Edit.minify = function() {
            readWithFlag('minify');
        };

        function readWithFlag(flag) {
            var path = Info.path;

            Util.checkArgs(arguments, ['flag']);

            RESTful.read(path + '?' + flag, function(data) {
                Ace.setValue(data);
                Ace.clearSelection();
                Ace.moveCursorTo(0, 0);
            });
        }

        function onDrop(event) {
            var reader, files,
                onLoad   =  function(event) {
                    var data    = event.target.result;

                    Ace.setValue(data);
                };

            event.preventDefault();

            files   = event.dataTransfer.files;

            Util.forEach(files, function(file) {
                reader  = new FileReader();
                Events.addLoad(reader, onLoad);
                reader.readAsBinaryString(file);
            });
        }

        this.showMessage    = function(text) {
            var msg, HIDE_TIME = 2000;

            /*
             * Msg should be created and removed
             * if it's not and just inner text
             * is changing, and hide and show of DOM
             * is called - bug occures: empty box
             * with no text inside.
             */
            msg = DOM.load({
                name        : 'div',
                className   : 'msg',
                parent      : Element,
                inner       : text,
                func        : alert
            });

            setTimeout(function() {
                DOM.remove(msg, Element);
            }, HIDE_TIME);
        };

        init(callback);
    }

})(CloudCmd, Util, DOM, CloudFunc);
<|endoftext|>


<commit_before>var mainTable;

var current_columns = {
  'legislator[name]': 1,
  'legislator[state]': 1,
  'legislator[district]': 1
};

function init() {

  prepare_table();

    // Add source data links
  $('a.source_form_link').click(function() {
    var source_id = this.id.replace('_form_link', '');
    jQuery.facebox({ajax: '/' + source_id + '/form'});
    return false;
  });

  // filter fields
  $('input#filter_field').keyup(function() {
    filter_table(this.value);
  }).focus(function() {
    if (!$(this).hasClass('activated')) {
      $(this).addClass('activated');
      $(this).val('');
    }
  });;

  // download links
  update_links();

  // table functions
  $('tr.titles th a').click(function() {
    var values = this.className.split('_');
    remove_column(values[0], values[1]);
  });

  $(document).bind('reveal.facebox', function() {
    $("div#facebox table").show();
  });
}

function init_source_form(source) {
  // for popups with a search field - the search form
  var popup_elem = 'div#' + source;
  $(popup_elem + ' form.search_name_form').submit(function() {
    return search_table(source, $('#search_name_field_' + source).val(), 1);
  });
  $(popup_elem + ' div.search_field input.search').focus(function() {this.value = '';})

  // For all popups - collecting the checked columns
  $(popup_elem + ' button.add_button').click(function() {
    popup_spinner_on();
    $(popup_elem + ' input:checked').each(function(i, box) {
      add_column(source, $(this).siblings('input:hidden').val());
    });
    popup_spinner_off();
    $(document).trigger('close.facebox');
  });

}

function search_table(source, q, page) {
  var popup_elem = 'div#' + source;
  var search_url = '/' + source + '/search?q=' + q + '&page=' + page;
  popup_spinner_on();
  $.ajax({
    success: function(data) {
      $(popup_elem + ' .search_table_inner').html(data);
      $(popup_elem + ' tr.search_result td:not(td.' + source + '_box)').click(function() {
        $(this).parent('tr').find('input:checkbox').click();
      });
      $(popup_elem + ' tr.search_result td.' + source + '_box input').click(function() {
        $(this).parent('td').parent('tr').toggleClass('selected');
      });
      $(popup_elem + ' div.page_button a').click(function() {
        return search_table(source, $('#roll_call_query').val(), $(this).siblings('input:hidden').val());
      });
      popup_spinner_off();
    },
    url: search_url
  });
  return false;
}

function add_column(source, column) {
  spinner_on();
  $.getJSON('/column.json', {source: source, column: column}, function(data) {
    var id = column_id(source, column);
    for (var bioguide_id in data) {
      if (bioguide_id != 'title' && bioguide_id != 'header') {
        if (data[bioguide_id] == null)
          data[bioguide_id] = '';
        if (data['title'] == null)
          data['title'] = '';
        var row = $('tr#' + bioguide_id);
        if (row)
          $('tr#' + bioguide_id).append('' + data[bioguide_id] + '
');
      }
    }
    $('#main_table tr.titles').append("" + data['header'] + "	");

    $('th.' + id + ' a.remove').click(function() {
      remove_column(source, column);
    });

    $('#main_table a.filter').click(function() {
      var filter = $('input#filter_field');
      filter.focus();
      filter.val(unencode($(this).html()));
      filter.keyup();
    });

    spinner_off();
    prepare_table();

    current_columns[source + "[" + column + "]"] = 1;
    update_links();
  });
}

function remove_column(source, column) {
  spinner_on();
  $('.' + column_id(source, column)).remove();
  spinner_off();

  delete current_columns[source + "[" + column + "]"];
  update_links();
}

function table_url(format) {
  if (format) format = "." + format;
  var query_string = query_string_for(current_columns);
  return "/table" + format + "?" + query_string;
}

function update_links() {
  $('div.download a').each(function(i, a) {
    a.href = table_url(a.id);
  });
}

function query_string_for(options) {
  var string = [];
  for (var key in options)
    string.push(key + "=" + options[key]);
  return string.join("&");
}

function spinner_on() {$('#spinner').show();}
function spinner_off() {$('#spinner').hide();}

function popup_spinner_on() {$('.popup_spinner').show();}
function popup_spinner_off() {$('.popup_spinner').hide();}

function column_id(source, column) {
  return source + '_' + column;
}

function escape_single_quotes(string) {
  return string.replace(/\'/g, '\\\'');
}

function unencode(string) {
  return string.replace('&', '&');
}

/** Functions that deal with the raw table plugins **/

function prepare_table() {
  $('#main_table').tablesorter({
    widgets: ['zebra']
  });
}

function filter_table(q, column) {
  // uiTableFilter expects the column argument to be a class name on the TH tag of that column
  $.uiTableFilter($('#main_table'), q, column);
}<commit_msg>Fix to allow for quotes to be used in searches, but made useless<commit_after>var mainTable;

var current_columns = {
  'legislator[name]': 1,
  'legislator[state]': 1,
  'legislator[district]': 1
};

function init() {

  prepare_table();

    // Add source data links
  $('a.source_form_link').click(function() {
    var source_id = this.id.replace('_form_link', '');
    jQuery.facebox({ajax: '/' + source_id + '/form'});
    return false;
  });

  // filter fields
  $('input#filter_field').keyup(function() {
    filter_table(strip_search(this.value));
  }).focus(function() {
    if (!$(this).hasClass('activated')) {
      $(this).addClass('activated');
      $(this).val('');
    }
  });;

  // download links
  update_links();

  // table functions
  $('tr.titles th a').click(function() {
    var values = this.className.split('_');
    remove_column(values[0], values[1]);
  });

  $(document).bind('reveal.facebox', function() {
    $("div#facebox table").show();
  });
}

function init_source_form(source) {
  // for popups with a search field - the search form
  var popup_elem = 'div#' + source;
  $(popup_elem + ' form.search_name_form').submit(function() {
    return search_table(source, $('#search_name_field_' + source).val(), 1);
  });
  $(popup_elem + ' div.search_field input.search').focus(function() {this.value = '';})

  // For all popups - collecting the checked columns
  $(popup_elem + ' button.add_button').click(function() {
    popup_spinner_on();
    $(popup_elem + ' input:checked').each(function(i, box) {
      add_column(source, $(this).siblings('input:hidden').val());
    });
    popup_spinner_off();
    $(document).trigger('close.facebox');
  });

}

function search_table(source, q, page) {
  var popup_elem = 'div#' + source;
  var search_url = '/' + source + '/search?q=' + q + '&page=' + page;
  popup_spinner_on();
  $.ajax({
    success: function(data) {
      $(popup_elem + ' .search_table_inner').html(data);
      $(popup_elem + ' tr.search_result td:not(td.' + source + '_box)').click(function() {
        $(this).parent('tr').find('input:checkbox').click();
      });
      $(popup_elem + ' tr.search_result td.' + source + '_box input').click(function() {
        $(this).parent('td').parent('tr').toggleClass('selected');
      });
      $(popup_elem + ' div.page_button a').click(function() {
        return search_table(source, $('#roll_call_query').val(), $(this).siblings('input:hidden').val());
      });
      popup_spinner_off();
    },
    url: search_url
  });
  return false;
}

function add_column(source, column) {
  spinner_on();
  $.getJSON('/column.json', {source: source, column: column}, function(data) {
    var id = column_id(source, column);
    for (var bioguide_id in data) {
      if (bioguide_id != 'title' && bioguide_id != 'header') {
        if (data[bioguide_id] == null)
          data[bioguide_id] = '';
        if (data['title'] == null)
          data['title'] = '';
        var row = $('tr#' + bioguide_id);
        if (row)
          $('tr#' + bioguide_id).append('' + data[bioguide_id] + '
');
      }
    }
    $('#main_table tr.titles').append("" + data['header'] + "	");

    $('th.' + id + ' a.remove').click(function() {
      remove_column(source, column);
    });

    $('#main_table a.filter').click(function() {
      var filter = $('input#filter_field');
      filter.focus();
      filter.val(unencode($(this).html()));
      filter.keyup();
    });

    spinner_off();
    prepare_table();

    current_columns[source + "[" + column + "]"] = 1;
    update_links();
  });
}

function remove_column(source, column) {
  spinner_on();
  $('.' + column_id(source, column)).remove();
  spinner_off();

  delete current_columns[source + "[" + column + "]"];
  update_links();
}

function table_url(format) {
  if (format) format = "." + format;
  var query_string = query_string_for(current_columns);
  return "/table" + format + "?" + query_string;
}

function update_links() {
  $('div.download a').each(function(i, a) {
    a.href = table_url(a.id);
  });
}

function query_string_for(options) {
  var string = [];
  for (var key in options)
    string.push(key + "=" + options[key]);
  return string.join("&");
}

function spinner_on() {$('#spinner').show();}
function spinner_off() {$('#spinner').hide();}

function popup_spinner_on() {$('.popup_spinner').show();}
function popup_spinner_off() {$('.popup_spinner').hide();}

function column_id(source, column) {
  return source + '_' + column;
}

function escape_single_quotes(string) {
  return string.replace(/\'/g, '\\\'');
}

function unencode(string) {
  return string.replace('&', '&');
}

function strip_search(string) {
  return string.replace(/[\"]/g, '');
}

/** Functions that deal with the raw table plugins **/

function prepare_table() {
  $('#main_table').tablesorter({
    widgets: ['zebra']
  });
}

function filter_table(q, column) {
  // uiTableFilter expects the column argument to be a class name on the TH tag of that column
  $.uiTableFilter($('#main_table'), q, column);
}<|endoftext|>


<commit_before>'use strict';

import '../../node_modules/bootstrap-sass/assets/javascripts/bootstrap';

const DynamicCSS = require('./DynamicCSS');
const NotificationController = require('./NotificationController');
const notificationController = new NotificationController();

const dynamic = new DynamicCSS();
dynamic.watch();
<commit_msg>Use es6 imports<commit_after>'use strict';

import '../../node_modules/bootstrap-sass/assets/javascripts/bootstrap';

import DynamicCSS from './DynamicCSS';
import NotificationController from './NotificationController';
const notificationController = new NotificationController();

const dynamic = new DynamicCSS();
dynamic.watch();
<|endoftext|>


<commit_before>var geocoder = new google.maps.Geocoder();

$(document).ready(function(){
    socket.on('geocoder', function(data){
    var address = data.location
    if (address === "")
    {
      console.log("Blank string")
    }
    else {
    setTimeout(geocoding(address), 500);
    };
  });

  var geocoding = function(address) {
    geocoder.geocode({"address": address}, function(results, status){
      if (status == google.maps.GeocoderStatus.OK){
        var location = results[0].geometry.location
        var lat = location.G
        var lng = location.K
        makeMarker([lat, lng], map);
      }
      else {
        console.log("Geocode was not successful for the following reason: "+ status)
      }
    })
  };
});
<commit_msg>Comment out debugging code<commit_after>var geocoder = new google.maps.Geocoder();

$(document).ready(function(){
    socket.on('geocoder', function(data){
    var address = data.location
    if (address === "")
    {
      // console.log("Blank string")
    }
    else {
    setTimeout(geocoding(address), 500);
    };
  });

  var geocoding = function(address) {
    geocoder.geocode({"address": address}, function(results, status){
      if (status == google.maps.GeocoderStatus.OK){
        var location = results[0].geometry.location
        var lat = location.G
        var lng = location.K
        makeMarker([lat, lng], map);
      }
      // else {
      //   console.log("Geocode was not successful for the following reason: "+ status)
      // }
    })
  };
});
<|endoftext|>


<commit_before>var CloudCmd, Util, DOM, CloudFunc, $;

(function(CloudCmd, Util, DOM, CloudFunc){
    'use strict';

    CloudCmd.View = new ViewProto(CloudCmd, Util, DOM, CloudFunc);

    function ViewProto(CloudCmd, Util, DOM, CloudFunc){
        var Key     = CloudCmd.Key,
            Images  = DOM.Images,
            View    = this,
            Element,

            Config      = {
                beforeShow      : function(){
                    Images.hideLoad();
                    Key.unsetBind();
                },
                afterShow       : function(){
                    Element.focus();
                },

                beforeClose     : Key.setBind,

                openEffect      : 'none',
                closeEffect     : 'none',
                autoSize        : false,
                height          : window.innerHeight,
                helpers : {
                    overlay : {
                        css : {
                            'background'  : 'rgba(255, 255, 255, 0.1)'
                        }
                    }
                },
                padding : 0
            };

        this.init                = function(pCallBack){
            Util.loadOnLoad([
                pCallBack || Util.retExec(View.show, null),
                load,
                DOM.jqueryLoad
            ]);

            DOM.Events.addKey(listener);
            DOM.setButtonKey('f3', view);

            delete View.init;
        };

        /**
         * function shows FancyBox
         */
        this.show                       = function(pData, pCallBack){
            var lPath, lElement,
                lAfterFunc, lFunc;

            Element         = $('
');
            if(pData) {
                lElement    = $(Element).append(pData);
                lAfterFunc  = Config.afterShow,
                lFunc       = function(){
                        Util.exec(lAfterFunc);
                        Util.exec(pCallBack);
                };

                Config.afterShow = lFunc;

                $.fancybox(lElement, Config);

            } else {
                lPath = CloudFunc.FS + DOM.getCurrentPath();
                if( Util.checkExtension(lPath, ['png','jpg', 'gif','ico']) ) {
                    $.fancybox.open({ href : lPath }, Config);
                }
                else
                    DOM.getCurrentData(function(pParams){
                        $.fancybox( Element.append(pParams.data), Config );
                    });
            }
        };

        this.hide                       =  function(){
            $.fancybox.close();
        };

        /**
         * function loads css and js of FancyBox
         * @pParent     - this
         * @pCallBack   -  executes, when everything loaded
         */
        function load(pCallBack){
            Util.time('fancybox load');
            var lDir    = CloudCmd.LIBDIRCLIENT + 'view/fancyBox/source/',
                lFiles  = [ lDir + 'jquery.fancybox.css',
                            lDir + 'jquery.fancybox.js' ];

            DOM.anyLoadOnLoad([lFiles], function(){
                Util.timeEnd('fancybox load');
                Util.exec( pCallBack );
                Images.hideLoad();
            })
            .cssSet({id:'view-css',
                inner : '#view{'                         +
                            'font-size: 16px;'                  +
                            'white-space :pre'                  +
                        '}'                                     +
                        '#view::selection{'              +
                            /*
                                'background: #fe57a1;'
                                'color: #fff;'
                            */
                            'background: #b3d4fc;'              +
                            'text-shadow: none;'                +
                        '}'
            });

        }

        function view(){
            Images.showLoad();
            View.show();
        }

        function listener(pEvent){
            var lF3         = Key.F3,
                lIsBind     = Key.isBind(),
                lKey        = pEvent.keyCode;

            /* если клавиши можно обрабатывать */
            if (lIsBind && lKey === lF3) {
                view();
                DOM.preventDefault(pEvent);
            }
        }
    }

})(CloudCmd, Util, DOM, CloudFunc);<commit_msg>chore(view) show<commit_after>var CloudCmd, Util, DOM, CloudFunc, $;

(function(CloudCmd, Util, DOM, CloudFunc){
    'use strict';

    CloudCmd.View = new ViewProto(CloudCmd, Util, DOM, CloudFunc);

    function ViewProto(CloudCmd, Util, DOM, CloudFunc){
        var Key     = CloudCmd.Key,
            Images  = DOM.Images,
            View    = this,
            Element,

            Config      = {
                beforeShow      : function(){
                    Images.hideLoad();
                    Key.unsetBind();
                },
                afterShow       : function(){
                    Element.focus();
                },

                beforeClose     : Key.setBind,

                openEffect      : 'none',
                closeEffect     : 'none',
                autoSize        : false,
                height          : window.innerHeight,
                helpers : {
                    overlay : {
                        css : {
                            'background'  : 'rgba(255, 255, 255, 0.1)'
                        }
                    }
                },
                padding : 0
            };

        this.init                = function(pCallBack){
            Util.loadOnLoad([
                pCallBack || Util.retExec(View.show, null),
                load,
                DOM.jqueryLoad
            ]);

            DOM.Events.addKey(listener);
            DOM.setButtonKey('f3', view);

            delete View.init;
        };

        /**
         * function shows FancyBox
         */
        this.show                       = function(pData, pCallBack){
            var lPath, lElement,
                lAfterFunc, lFunc;

            Element         = $('
');
            if(pData) {
                lElement    = $(Element).append(pData);
                lAfterFunc  = Config.afterShow,
                lFunc       = function(){
                    Util.exec(lAfterFunc);
                    Util.exec(pCallBack);
                };

                Config.afterShow = lFunc;

                $.fancybox(lElement, Config);

            } else {
                lPath = CloudFunc.FS + DOM.getCurrentPath();
                if( Util.checkExtension(lPath, ['png','jpg', 'gif','ico']) ) {
                    $.fancybox.open({ href : lPath }, Config);
                }
                else
                    DOM.getCurrentData(function(pParams){
                        $.fancybox( Element.append(pParams.data), Config );
                    });
            }
        };

        this.hide                       =  function(){
            $.fancybox.close();
        };

        /**
         * function loads css and js of FancyBox
         * @pParent     - this
         * @pCallBack   -  executes, when everything loaded
         */
        function load(pCallBack){
            Util.time('fancybox load');
            var lDir    = CloudCmd.LIBDIRCLIENT + 'view/fancyBox/source/',
                lFiles  = [ lDir + 'jquery.fancybox.css',
                            lDir + 'jquery.fancybox.js' ];

            DOM.anyLoadOnLoad([lFiles], function(){
                Util.timeEnd('fancybox load');
                Util.exec( pCallBack );
                Images.hideLoad();
            })
            .cssSet({id:'view-css',
                inner : '#view{'                         +
                            'font-size: 16px;'                  +
                            'white-space :pre'                  +
                        '}'                                     +
                        '#view::selection{'              +
                            /*
                                'background: #fe57a1;'
                                'color: #fff;'
                            */
                            'background: #b3d4fc;'              +
                            'text-shadow: none;'                +
                        '}'
            });

        }

        function view(){
            Images.showLoad();
            View.show();
        }

        function listener(pEvent){
            var lF3         = Key.F3,
                lIsBind     = Key.isBind(),
                lKey        = pEvent.keyCode;

            /* если клавиши можно обрабатывать */
            if (lIsBind && lKey === lF3) {
                view();
                DOM.preventDefault(pEvent);
            }
        }
    }

})(CloudCmd, Util, DOM, CloudFunc);<|endoftext|>


<commit_before>'use strict'

const Fetch = require('node-fetch')
const Qs = require('qs')

class Jira {
  constructor (config) {
    this.config = config
    this.defaults = {
      method: 'GET',
      mode: 'cors',
      headers: {
        'Authorization': 'Basic ' + new Buffer(`${config.username}:${config.password}`).toString('base64'),
        'Content-Type': 'application/json',
        Accept: 'application/json'
      }
    }
  }
  fetchWithDefaults (url, options = {}) {
    const opts = Object.assign({}, this.defaults, options)
    return Fetch(url, opts).then((response) => {
      if (!response.ok) {
        const error = new Error(response.statusText)
        error.response = response
        throw error
      }
      if (response.status === 204) {
        return Promise.resolve({})
      }
      return response.json()
    })
  }
  search (jql) {
    const startAt = 0
    const maxResults = 1000
    const qs = Qs.stringify({
      jql,
      startAt,
      maxResults
    })
    return this.fetchWithDefaults(`${this.config.server}rest/api/2/search?${qs}`)
  }
  getIssue (id) {
    return Promise.resolve({})
  }
}

exports = module.exports = Jira
<commit_msg>split out handling for search and by id<commit_after>'use strict'

const Fetch = require('node-fetch')
const Qs = require('qs')

class Jira {
  constructor (config) {
    this.config = config
    this.defaults = {
      method: 'GET',
      mode: 'cors',
      headers: {
        'Authorization': 'Basic ' + new Buffer(`${config.username}:${config.password}`).toString('base64'),
        'Content-Type': 'application/json',
        Accept: 'application/json'
      }
    }
  }

  /**
   * Pass a search query to Jira
   * [Jira Doc](https://docs.atlassian.com/jira/REST/cloud/#api/2/search-search)
   * @name search
   * @function
   * @param {string} jql - jira query string in JQL
   */
  search (jql) {
    const startAt = 0
    const maxResults = 1000
    const qs = Qs.stringify({
      jql,
      startAt,
      maxResults,
      fields: this.config.issueFields.join(',')
    })
    console.log(qs)
    const url = `${this.config.server}rest/api/2/search?${qs}`
    const opts = Object.assign({}, this.defaults, {})
    return Fetch(url, opts).then((response) => {
      if (!response.ok) {
        const error = new Error(response.statusText)
        error.response = response
        throw error
      }
      return response.json()
    })
  }

  /**
   * Gets an issue in jira, or returns undefine
   * @name getIssue
   * @function
   * [Jira Doc](https://docs.atlassian.com/jira/REST/cloud/#api/2/issue-getIssue)
   * @param {string} key - The issue key (including the project key prefix)
   */
  getIssue (key) {
    const qs = Qs.stringify({
      fields: this.config.issueFields.join(',')
    })
    const url = `${this.config.server}rest/api/2/issue/${key}?${qs}`
    const opts = Object.assign({}, this.defaults, {})
    return Fetch(url, opts).then((response) => {
      if (response.status === 404) {
        return Promise.resolve(undefined)
      }
      if (!response.ok) {
        const error = new Error(response.statusText)
        error.response = response
        throw error
      }
      return response.json()
    })
  }
}

exports = module.exports = Jira
<|endoftext|>


<commit_before>function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min)) + min;
}

function areResourcesLoaded(resourceKey) {
  var allLoaded = false;
  var resources = flashApp.resources;

  // set resource loaded to true
  resources[resourceKey] = true;

  // Loop through all resources
  for (var key in resources) {
    // console.log("resources." + key + " :" + resources[key]);
    // if the current resource is still loading, stop the loop and return false
    if (resources[key] == false) {
      console.log(key + " is still loading...");
      return false;
    }
    console.log('All resources loaded!!');
    flashApp.els.resourcesLoaded.dispatchEvent(flashApp.misc.allLoadedEvent);
    // if it gets through the loop, then something all resources are loaded
    return true;
  }
}

function startGame() {
  console.log('startGame()');
  // Hide Loading Gif
  flashApp.els.loadingGif.style.display = "none";

  flashApp.els.statusMsg.innerHTML = 'Let\'s rock!';

  // Wait for user to click to start game
  flashApp.els.statusMsg.innerHTML += "
Click here to start playing!";
  flashApp.els.statusMsg.addEventListener('click', startGameClick );
};

function startGameClick() {
  // User Clicked
  console.log('click');
  flashApp.els.flashCard.style.display = "block";
  // create a new deck of cards
  flashApp.game.flashCards = allCards;
  console.log('Current Deck: ' + flashApp.game.flashCards);

  // initialize results object
  flashApp.game.results = {};
  for (var index in flashApp.game.flashCards) {
    flashApp.game.results[flashApp.game.flashCards[index]] = 0;
  }
  console.log('Results: ', flashApp.game.results);

  // Remove event listener
  flashApp.els.flashCard.removeEventListener('click', startGameClick);

  flashApp.els.statusMsg.innerHTML = "Play the notes, dood!";

  // Allow user input from MIDI device and set game into play mode
  flashApp.game.inProgress = true;

  // Display note
  flashApp.els.flashCardNote.style.display = 'block';

  // Choose a card from the deck and display
  getRandomCardAndDisplay();
};

function getRandomCardAndDisplay() {
  flashApp.game.currentCardIndex = getRandomInt(0, flashApp.game.flashCards.length);
  console.log('index: ' + flashApp.game.currentCardIndex + ' card: ' + flashApp.game.flashCards[flashApp.game.currentCardIndex]);
  flashApp.els.flashCardNote.style.top = noteNameToPosition[flashApp.game.flashCards[flashApp.game.currentCardIndex]];
}

// This checks if the answer is correct or not.
// update results for each card.
// discards and choose new card.
// when deck completed sends data to server to store
function checkIfCorrectAnswer(noteName) {
  // does it match the flash card?
  if (noteName == flashApp.game.flashCards[flashApp.game.currentCardIndex]) {
    console.log('correct!');
    flashApp.els.statusMsg.innerHTML = noteName + " CORRECT!";

    // Let transition finish and continue processing correctAnswer logic
    flashApp.els.userNote.classList.add('correctAnswer');
    setTimeout(function() {
      console.log('got timeout');

      // Visual Feedback.  Do something cool!
      flashApp.els.userNote.classList.remove('correctAnswer');
      flashApp.els.userNote.style.display = "none";

      // Remove card from Deck
      flashApp.game.flashCards.splice(flashApp.game.currentCardIndex ,1);
      console.log('current cards: ' + flashApp.game.flashCards);
      if (flashApp.game.flashCards.length == 0)
      {
        // stop accepting MIDI input and evaluating answers
        flashApp.game.inProgress = false;

        // Display the results of the game
        // TODO Make pretty
        flashApp.els.statusMsg.innerHTML += "GREAT JOB!!! Deck completed!
Results: ";
        for (var key in flashApp.game.results) {
          flashApp.els.statusMsg.innerHTML += key;
          flashApp.els.statusMsg.innerHTML += ': ';
          flashApp.els.statusMsg.innerHTML += flashApp.game.results[key];
          flashApp.els.statusMsg.innerHTML += '  ';
        }
        // flashApp.els.statusMsg.innerHTML += "
results: " + flashApp.game.results;
        console.log(flashApp.game.results);
        // Send results to server if there logged in
        var username = document.getElementById('studentUsername').innerHTML;
        console.log('username from DOM: ', username);
        if( username != "") {
          console.log('someone signed in.  calling sendResults()');
          sendResults();
        }
      }
      // still more cards. Choose new card
      else{
        getRandomCardAndDisplay();
      }
    },1000);
  } // end correct answer

  // Wrong answer
  else {
    console.log('wrong!');

    // Tell user he/she is wrong
    flashApp.els.statusMsg.innerHTML = "OOOPS! " + noteName + " is not the right note!
Try again!";

    // Animate
    flashApp.els.userNote.classList.add('incorrectAnswer');
    setTimeout(function() {
      console.log('got timeout');
      flashApp.els.userNote.classList.remove('incorrectAnswer');
      flashApp.els.userNote.style.display = "none";
    } ,1000);

    var currentCard = flashApp.game.flashCards[flashApp.game.currentCardIndex];

    // increase number of wrong attempts in results
    flashApp.game.results[currentCard] = flashApp.game.results[currentCard] + 1;
  }

  console.log('results: ', flashApp.game.results);
}

function sendResults() {
  var studentData = {};
  studentData.studentUsername = document.getElementById('studentUsername').innerHTML;
  studentData.cards = flashApp.game.results;
  console.log('studentData: ');
  console.log(studentData);
  console.log('JSON.stringify(studentData)');
  console.log(JSON.stringify(studentData));
  var url = "http://" + window.location.host + "/results/store"
  console.log('url: ' + url);
  // $('.spinner').show(); //
...
  $.ajax({
    url: url,
    type: 'post',
    dataType: 'text',
    data: JSON.stringify(studentData),
    success: function(data) {
      console.log('resultSaved and got response from server! ',data);
    },
    error: function(err) {
      console.log('error: ', err);
    }
  });
}

function resultSaved(data) { console.log('resultSaved():', data); }
<commit_msg>fixed ajax to match protocol (http/https)<commit_after>function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min)) + min;
}

function areResourcesLoaded(resourceKey) {
  var allLoaded = false;
  var resources = flashApp.resources;

  // set resource loaded to true
  resources[resourceKey] = true;

  // Loop through all resources
  for (var key in resources) {
    // console.log("resources." + key + " :" + resources[key]);
    // if the current resource is still loading, stop the loop and return false
    if (resources[key] == false) {
      console.log(key + " is still loading...");
      return false;
    }
    console.log('All resources loaded!!');
    flashApp.els.resourcesLoaded.dispatchEvent(flashApp.misc.allLoadedEvent);
    // if it gets through the loop, then something all resources are loaded
    return true;
  }
}

function startGame() {
  console.log('startGame()');
  // Hide Loading Gif
  flashApp.els.loadingGif.style.display = "none";

  flashApp.els.statusMsg.innerHTML = 'Let\'s rock!';

  // Wait for user to click to start game
  flashApp.els.statusMsg.innerHTML += "
Click here to start playing!";
  flashApp.els.statusMsg.addEventListener('click', startGameClick );
};

function startGameClick() {
  // User Clicked
  console.log('click');
  flashApp.els.flashCard.style.display = "block";
  // create a new deck of cards
  flashApp.game.flashCards = allCards;
  console.log('Current Deck: ' + flashApp.game.flashCards);

  // initialize results object
  flashApp.game.results = {};
  for (var index in flashApp.game.flashCards) {
    flashApp.game.results[flashApp.game.flashCards[index]] = 0;
  }
  console.log('Results: ', flashApp.game.results);

  // Remove event listener
  flashApp.els.flashCard.removeEventListener('click', startGameClick);

  flashApp.els.statusMsg.innerHTML = "Play the notes, dood!";

  // Allow user input from MIDI device and set game into play mode
  flashApp.game.inProgress = true;

  // Display note
  flashApp.els.flashCardNote.style.display = 'block';

  // Choose a card from the deck and display
  getRandomCardAndDisplay();
};

function getRandomCardAndDisplay() {
  flashApp.game.currentCardIndex = getRandomInt(0, flashApp.game.flashCards.length);
  console.log('index: ' + flashApp.game.currentCardIndex + ' card: ' + flashApp.game.flashCards[flashApp.game.currentCardIndex]);
  flashApp.els.flashCardNote.style.top = noteNameToPosition[flashApp.game.flashCards[flashApp.game.currentCardIndex]];
}

// This checks if the answer is correct or not.
// update results for each card.
// discards and choose new card.
// when deck completed sends data to server to store
function checkIfCorrectAnswer(noteName) {
  // does it match the flash card?
  if (noteName == flashApp.game.flashCards[flashApp.game.currentCardIndex]) {
    console.log('correct!');
    flashApp.els.statusMsg.innerHTML = noteName + " CORRECT!";

    // Let transition finish and continue processing correctAnswer logic
    flashApp.els.userNote.classList.add('correctAnswer');
    setTimeout(function() {
      console.log('got timeout');

      // Visual Feedback.  Do something cool!
      flashApp.els.userNote.classList.remove('correctAnswer');
      flashApp.els.userNote.style.display = "none";

      // Remove card from Deck
      flashApp.game.flashCards.splice(flashApp.game.currentCardIndex ,1);
      console.log('current cards: ' + flashApp.game.flashCards);
      if (flashApp.game.flashCards.length == 0)
      {
        // stop accepting MIDI input and evaluating answers
        flashApp.game.inProgress = false;

        // Display the results of the game
        // TODO Make pretty
        flashApp.els.statusMsg.innerHTML += "GREAT JOB!!! Deck completed!
Results: ";
        for (var key in flashApp.game.results) {
          flashApp.els.statusMsg.innerHTML += key;
          flashApp.els.statusMsg.innerHTML += ': ';
          flashApp.els.statusMsg.innerHTML += flashApp.game.results[key];
          flashApp.els.statusMsg.innerHTML += '  ';
        }
        // flashApp.els.statusMsg.innerHTML += "
results: " + flashApp.game.results;
        console.log(flashApp.game.results);
        // Send results to server if there logged in
        var username = document.getElementById('studentUsername').innerHTML;
        console.log('username from DOM: ', username);
        if( username != "") {
          console.log('someone signed in.  calling sendResults()');
          sendResults();
        }
      }
      // still more cards. Choose new card
      else{
        getRandomCardAndDisplay();
      }
    },1000);
  } // end correct answer

  // Wrong answer
  else {
    console.log('wrong!');

    // Tell user he/she is wrong
    flashApp.els.statusMsg.innerHTML = "OOOPS! " + noteName + " is not the right note!
Try again!";

    // Animate
    flashApp.els.userNote.classList.add('incorrectAnswer');
    setTimeout(function() {
      console.log('got timeout');
      flashApp.els.userNote.classList.remove('incorrectAnswer');
      flashApp.els.userNote.style.display = "none";
    } ,1000);

    var currentCard = flashApp.game.flashCards[flashApp.game.currentCardIndex];

    // increase number of wrong attempts in results
    flashApp.game.results[currentCard] = flashApp.game.results[currentCard] + 1;
  }

  console.log('results: ', flashApp.game.results);
}

function sendResults() {
  var studentData = {};
  studentData.studentUsername = document.getElementById('studentUsername').innerHTML;
  studentData.cards = flashApp.game.results;
  console.log('studentData: ');
  console.log(studentData);
  console.log('JSON.stringify(studentData)');
  console.log(JSON.stringify(studentData));

  // setup url for http or https to match server side
  var url = window.location.protocol + "//" + window.location.host + "/results/store"
  console.log('url: ' + url);
  // $('.spinner').show(); //
...
  $.ajax({
    url: url,
    type: 'post',
    dataType: 'text',
    data: JSON.stringify(studentData),
    success: function(data) {
      console.log('resultSaved and got response from server! ',data);
    },
    error: function(err) {
      console.log('error: ', err);
    }
  });
}

function resultSaved(data) { console.log('resultSaved():', data); }
<|endoftext|>