<commit_before>(function($) {
  $.fn.qubit = function(options) {
    return this.each(function() {
      var qubit = new Qubit(this, options);
    });
  };
  var Qubit = function(el) {
    var self = this;
    this.scope = $(el);
    this.scope.on('change', 'input[type=checkbox]', function(e) {
      if (!self.suspendListeners) {
        self.process(e.target);
      }
    });
    this.scope.find('input[type=checkbox]:checked').each(function() {
      self.process(this);
    });
  };
  Qubit.prototype = {
    itemSelector: 'li',
    process: function(checkbox) {
      var checkbox = $(checkbox),
          parentItems = checkbox.parentsUntil(this.scope, this.itemSelector);
      try {
        this.suspendListeners = true;
        // all children inherit my state
        parentItems.eq(0).find('input[type=checkbox]')
          .filter(checkbox.prop('checked') ? ':not(:checked)' : ':checked')
          .each(function() {
            if (!$(this).parent().hasClass('hidden')) {
              $(this).prop('checked', checkbox.prop('checked'));
            }
          })
          .trigger('change');
        this.processParents(checkbox);
      } finally {
        this.suspendListeners = false;
      }
    },
    processParents: function() {
      var self = this, changed = false;
      this.scope.find('input[type=checkbox]').each(function() {
        var $this = $(this),
            parent = $this.closest(self.itemSelector),
            children = parent.find('input[type=checkbox]').not($this),
            numChecked = children.filter(function() {
              return $(this).prop('checked') || $(this).prop('indeterminate');
            }).length;

        if (children.length) {
          if (numChecked == 0) {
            if (self.setChecked($this, false)) changed = true;
          } else if (numChecked == children.length) {
            if (self.setChecked($this, true)) changed = true;
          } else {
            if (self.setIndeterminate($this, true)) changed = true;
          }
        }
        else {
          if (self.setIndeterminate($this, false)) changed = true;
        }
      });
      if (changed) this.processParents();
    },
    setChecked: function(checkbox, value, event) {
      var changed = false;
      if (checkbox.prop('indeterminate')) {
        checkbox.prop('indeterminate', false);
        changed = true;
      }
      if (checkbox.prop('checked') != value) {
        checkbox.prop('checked', value).trigger('change');
        changed = true;
      }
      return changed;
    },
    setIndeterminate: function(checkbox, value) {
      if (value) {
        checkbox.prop('checked', false);
      }
      if (checkbox.prop('indeterminate') != value) {
        checkbox.prop('indeterminate', value);
        return true;
      }
    }
  };
}(jQuery));
<commit_msg>Performance improvements<commit_after>(function($) {
  $.fn.qubit = function(options) {
    return this.each(function() {
      new Qubit(this, options);
    });
  };
  var Qubit = function(el) {
    var self = this;
    this.scope = $(el);
    this.scope.on('change', 'input[type=checkbox]', function(e) {
      if (!self.suspendListeners) {
        self.process(e.target);
      }
    });
    this.processParents();
  };
  Qubit.prototype = {
    itemSelector: 'li',
    process: function(checkbox) {
      checkbox = $(checkbox);
      var parentItems = checkbox.parentsUntil(this.scope, this.itemSelector);
      var self = this;
      try {
        this.suspendListeners = true;
        // all children inherit my state
        parentItems.eq(0).find('input[type=checkbox]')
          .filter(checkbox.prop('checked') ? ':not(:checked)' : ':checked')
          .each(function() {
            if (!$(this).parent().hasClass('hidden')) {
              self.setChecked($(this), checkbox.prop('checked'));
            }
          })
          .trigger('change');
        this.processParents();
      } finally {
        this.suspendListeners = false;
      }
    },
    processParents: function() {
      var self = this, changed = false;
      this.scope.find('input[type=checkbox]').each(function() {
        var $this = $(this);
        var parent = $this.closest(self.itemSelector);
        var children = parent.find('input[type=checkbox]').not($this);
        var numChecked = children.filter(function() {
          return $(this).prop('checked') || $(this).prop('indeterminate');
        }).length;

        if (children.length) {
          if (numChecked === 0) {
            self.setChecked($this, false) && (changed = true);
          }
          else if (numChecked == children.length) {
            self.setChecked($this, true) && (changed = true);
          }
          else {
            self.setIndeterminate($this, true) && (changed = true);
          }
        }
        else {
          self.setIndeterminate($this, false) && (changed = true);
        }
      });
      if (changed) this.processParents();
    },
    setChecked: function(checkbox, value, event) {
      var changed = false;
      if (checkbox.prop('indeterminate')) {
        checkbox.prop('indeterminate', false);
        changed = true;
      }
      if (checkbox.prop('checked') != value) {
        checkbox.prop('checked', value).trigger('change');
        changed = true;
      }
      return changed;
    },
    setIndeterminate: function(checkbox, value) {
      if (value) {
        checkbox.prop('checked', false);
      }
      if (checkbox.prop('indeterminate') != value) {
        checkbox.prop('indeterminate', value);
        return true;
      }
    }
  };
}(jQuery));
<|endoftext|>


<commit_before>/**
 * Author: Michał Gołębiowski <michal.golebiowski@laboratorium.ee>
 * Author: Brandon Aaron (http://brandonaaron.net)
 * Copyright (c) 2011 Brandon Aaron (http://brandonaaron.net)
 * Copyright (c) 2013 Laboratorium EE (http://laboratorium.ee)
 */

(function ($) {
    'use strict';

    // Modern browsers support 'wheel', other - 'mousewheel'.
    var nativeEvent = 'onwheel' in document.createElement('div') ? 'wheel' : 'mousewheel';

    // Normalizing event properties for the 'wheel' event (like event.which etc.).
    if (nativeEvent === 'wheel') {
        $.event.fixHooks.wheel = $.event.mouseHooks;
    } else {
        // We can't attach hooks to 'wheel' only since we need a type matching to originalEvent.type
        // and this field is non-mutable.
        $.event.fixHooks.mousewheel = $.event.mouseHooks;
    }

    function handler(orgEvent) {
        /* jshint validthis:true */ // event handler
        // Handler for the 'mousewheel' event (Chrome, Opera, Safari).

        var multiplier = -1 / 120,
            event = $.event.fix(orgEvent);

        if (nativeEvent === 'wheel') {
            event.deltaMode = orgEvent.deltaMode;
            event.deltaX = orgEvent.deltaX;
            event.deltaY = orgEvent.deltaY;
            event.deltaZ = orgEvent.deltaZ;
        } else {
            event.type = 'wheel';
            event.deltaMode = 1; // delta === 1 => scrolled one line
            event.deltaX = event.deltaZ = 0; // defaults

            event.deltaY = multiplier * orgEvent.wheelDelta;
            // Webkit supports wheelDeltaX as well.
            if (orgEvent.wheelDeltaX != null) {
                event.deltaX = multiplier * orgEvent.wheelDeltaX;
            }
        }

        // Exchange original event for the modified one in arguments list.
        var args = [].slice.call(arguments, 0);
        args[0] = event;

        return $.event.dispatch.apply(this, args);
    }

    // Implementing 'wheel' using non-standard 'mousewheel' event.
    $.event.special.wheel = {
        setup: function () {
            this.addEventListener(nativeEvent, handler, false);
        },

        teardown: function () {
            this.removeEventListener(nativeEvent, handler, false);
        }
    };
})(jQuery);
<commit_msg>micro-changes: code style, typo<commit_after>/**
 * Author: Michał Gołębiowski <michal.golebiowski@laboratorium.ee>
 * Author: Brandon Aaron (http://brandonaaron.net)
 * Copyright (c) 2011 Brandon Aaron (http://brandonaaron.net)
 * Copyright (c) 2013 Laboratorium EE (http://laboratorium.ee)
 */

(function ($) {
    'use strict';

    // Modern browsers support 'wheel', others - 'mousewheel'.
    var nativeEvent = 'onwheel' in document.createElement('div') ? 'wheel' : 'mousewheel';

    // Normalizing event properties for the 'wheel' event (like event.which etc.).
    if (nativeEvent === 'wheel') {
        $.event.fixHooks.wheel = $.event.mouseHooks;
    } else {
        // We can't attach hooks to 'wheel' only since we need a type matching to originalEvent.type
        // and this field is non-mutable.
        $.event.fixHooks.mousewheel = $.event.mouseHooks;
    }

    function handler(orgEvent) {
        /* jshint validthis: true */ // event handler
        // Handler for the 'mousewheel' event (Chrome, Opera, Safari).

        var multiplier = -1 / 120,
            event = $.event.fix(orgEvent);

        if (nativeEvent === 'wheel') {
            event.deltaMode = orgEvent.deltaMode;
            event.deltaX = orgEvent.deltaX;
            event.deltaY = orgEvent.deltaY;
            event.deltaZ = orgEvent.deltaZ;
        } else {
            event.type = 'wheel';
            event.deltaMode = 1; // delta === 1 => scrolled one line
            event.deltaX = event.deltaZ = 0; // defaults

            event.deltaY = multiplier * orgEvent.wheelDelta;
            // Webkit supports wheelDeltaX as well.
            if (orgEvent.wheelDeltaX != null) {
                event.deltaX = multiplier * orgEvent.wheelDeltaX;
            }
        }

        // Exchange original event for the modified one in arguments list.
        var args = [].slice.call(arguments, 0);
        args[0] = event;

        return $.event.dispatch.apply(this, args);
    }

    // Implementing 'wheel' using non-standard 'mousewheel' event.
    $.event.special.wheel = {
        setup: function () {
            this.addEventListener(nativeEvent, handler, false);
        },

        teardown: function () {
            this.removeEventListener(nativeEvent, handler, false);
        }
    };
})(jQuery);
<|endoftext|>


<commit_before>THREE.py.CANNONize = function (obj, world) {
    "use strict";
    obj.updateMatrixWorld();
    obj.traverse(function(node) {
        if (node.userData && node.userData.cannonData) {
            var body = makeCANNON(node, node.userData.cannonData);
            if (world) {
                if (body instanceof CANNON.Body) {
                    world.addBody(body);
                } else {
                    // assumed to be array
                    body.forEach(function (b) { world.addBody(b); });
                }
            }
        }
    });

    function makeCANNON(node, cannonData) {
        var body;
        if (node.body) {
            return node.body;
        }
        if (node instanceof THREE.Mesh) {
            var params = {mass: cannonData.mass,
                          position: node.getWorldPosition(),
                          quaternion: node.getWorldQuaternion()};
            if (cannonData.linearDamping !== undefined) {
                params.linearDamping = cannonData.linearDamping;
            }
            if (cannonData.angularDamping !== undefined) {
                params.angularDamping = cannonData.angularDamping;
            }
            body = new CANNON.Body(params);
            body.mesh = node;
            cannonData.shapes.forEach(function(e) {
                var shape,
                    quaternion,
                    position,
                    array;
                switch (e) {
                    case 'Plane':
                        shape = new CANNON.Plane();
                        break;
                    case 'Box':
                        var halfExtents = new CANNON.Vec3();
                        node.geometry.computeBoundingBox();
                        halfExtents.x = node.scale.x * (node.geometry.boundingBox.max.x - node.geometry.boundingBox.min.x) / 2;
                        halfExtents.y = node.scale.y * (node.geometry.boundingBox.max.y - node.geometry.boundingBox.min.y) / 2;
                        halfExtents.z = node.scale.z * (node.geometry.boundingBox.max.z - node.geometry.boundingBox.min.z) / 2;
                        shape = new CANNON.Box(halfExtents);
                        break;
                    case 'Sphere':
                        node.geometry.computeBoundingSphere();
                        shape = new CANNON.Sphere(node.geometry.boundingSphere.radius);
                        break;
                    case 'ConvexPolyhedron':
                        var points = [];
                        var faces = [];
                        if (node.geometry instanceof THREE.BufferGeometry) {
                            array = node.geometry.getAttribute('position').array;
                            for (var i = 0; i < array.length; i += 3) {
                                points.push(new CANNON.Vec3(array[i], array[i+1], array[i+2]));
                            }
                            array = node.geometry.index.array;
                            for (i = 0; i < array.length; i += 3) {
                                var face = [array[i], array[i+1], array[i+2]];
                                faces.push(face);
                            }
                        } else if (node.geometry instanceof THREE.Geometry) {
                            // TODO
                        }
                        shape = new CANNON.ConvexPolyhedron(points, faces);
                        break;
                    case 'Cylinder':
                        shape = new CANNON.Cylinder(node.geometry.parameters.radiusTop,
                            node.geometry.parameters.radiusBottom,
                            node.geometry.parameters.height,
                            node.geometry.parameters.radialSegments);
                        var quaternion = new CANNON.Quaternion();
                        quaternion.setFromEuler(-Math.PI/2, 0, 0, 'XYZ');
                        break;
                    case 'Heightfield':
                        array = node.geometry.getAttribute('position').array;
                        if (node.geometry.type !== 'PlaneBufferGeometry') {
                            alert('uh oh!');
                        }
                        var gridX1 = node.geometry.parameters.widthSegments + 1;
                        var gridY1 = node.geometry.parameters.heightSegments + 1;
                        var dx = node.geometry.parameters.width / node.geometry.parameters.widthSegments;
                        var data = [];
                        for (var ix = 0; ix < gridX1; ++ix) {
                            data.push(new Float32Array(gridY1));
                            for (var iy = 0; iy < gridY1; ++iy) {
                                data[ix][iy] = array[3 * (gridX1 * (gridY1 - iy - 1) + ix) + 2];
                            }
                        }
                        shape = new CANNON.Heightfield(data, {
                            elementSize: dx
                        });
                        // center to match THREE.PlaneBufferGeometry:
                        position = new CANNON.Vec3();
                        position.x = -node.geometry.parameters.width / 2;
                        position.y = -node.geometry.parameters.height / 2;
                        break;
                    case 'Trimesh':
                        var vertices;
                        var indices;
                        if (node.geometry instanceof THREE.BufferGeometry) {
                            vertices = node.geometry.getAttribute('position').array;
                            indices = node.geometry.index.array;
                        } else {
                            vertices = [];
                            for (var iv = 0; iv < node.geometry.vertices.length; iv++) {
                                var vert = node.geometry.vertices[iv];
                                vertices.push(vert.x, vert.y, vert.z);
                            }
                            indices = [];
                            for (var iface = 0; iface < node.geometry.faces.length; iface++) {
                                var face = node.geometry.faces[iface];
                                indices.push(face.a, face.b, face.c);
                            }
                        }
                        shape = new CANNON.Trimesh(vertices, indices);
                        break;
                    case 'Ellipsoid':
                        // TODO
                        console.warn('TODO');
                        break;
                    default:
                        console.error("unknown shape type: " + e);
                        break;
                }
                body.addShape(shape, position, quaternion);
            });
            node.body = body;
            return body;
        } else if (node instanceof THREE.Object3D) {
            var bodies = [];
            node.children.forEach(function (c) { bodies.push(makeCANNON(c, cannonData)); });
            return bodies;
        } else {
            console.error("makeCANNON error");
        }
    }
};
<commit_msg>fix jshint errs<commit_after>THREE.py.CANNONize = function (obj, world) {
    "use strict";
    obj.updateMatrixWorld();
    obj.traverse(function(node) {
        if (node.userData && node.userData.cannonData) {
            var body = makeCANNON(node, node.userData.cannonData);
            if (world) {
                if (body instanceof CANNON.Body) {
                    world.addBody(body);
                } else {
                    // assumed to be array
                    body.forEach(function (b) { world.addBody(b); });
                }
            }
        }
    });

    function makeCANNON(node, cannonData) {
        var body;
        if (node.body) {
            return node.body;
        }
        if (node instanceof THREE.Mesh) {
            var params = {mass: cannonData.mass,
                          position: node.getWorldPosition(),
                          quaternion: node.getWorldQuaternion()};
            if (cannonData.linearDamping !== undefined) {
                params.linearDamping = cannonData.linearDamping;
            }
            if (cannonData.angularDamping !== undefined) {
                params.angularDamping = cannonData.angularDamping;
            }
            body = new CANNON.Body(params);
            body.mesh = node;
            cannonData.shapes.forEach(function(e) {
                var shape,
                    quaternion,
                    position,
                    array;
                switch (e) {
                    case 'Plane':
                        shape = new CANNON.Plane();
                        break;
                    case 'Box':
                        var halfExtents = new CANNON.Vec3();
                        node.geometry.computeBoundingBox();
                        halfExtents.x = node.scale.x * (node.geometry.boundingBox.max.x - node.geometry.boundingBox.min.x) / 2;
                        halfExtents.y = node.scale.y * (node.geometry.boundingBox.max.y - node.geometry.boundingBox.min.y) / 2;
                        halfExtents.z = node.scale.z * (node.geometry.boundingBox.max.z - node.geometry.boundingBox.min.z) / 2;
                        shape = new CANNON.Box(halfExtents);
                        break;
                    case 'Sphere':
                        node.geometry.computeBoundingSphere();
                        shape = new CANNON.Sphere(node.geometry.boundingSphere.radius);
                        break;
                    case 'ConvexPolyhedron':
                        var points = [];
                        var faces = [];
                        if (node.geometry instanceof THREE.BufferGeometry) {
                            array = node.geometry.getAttribute('position').array;
                            for (var i = 0; i < array.length; i += 3) {
                                points.push(new CANNON.Vec3(array[i], array[i+1], array[i+2]));
                            }
                            array = node.geometry.index.array;
                            for (i = 0; i < array.length; i += 3) {
                                var face = [array[i], array[i+1], array[i+2]];
                                faces.push(face);
                            }
                        } else if (node.geometry instanceof THREE.Geometry) {
                            // TODO
                        }
                        shape = new CANNON.ConvexPolyhedron(points, faces);
                        break;
                    case 'Cylinder':
                        shape = new CANNON.Cylinder(node.geometry.parameters.radiusTop,
                            node.geometry.parameters.radiusBottom,
                            node.geometry.parameters.height,
                            node.geometry.parameters.radialSegments);
                        quaternion = new CANNON.Quaternion();
                        quaternion.setFromEuler(-Math.PI/2, 0, 0, 'XYZ');
                        break;
                    case 'Heightfield':
                        array = node.geometry.getAttribute('position').array;
                        if (node.geometry.type !== 'PlaneBufferGeometry') {
                            alert('uh oh!');
                        }
                        var gridX1 = node.geometry.parameters.widthSegments + 1;
                        var gridY1 = node.geometry.parameters.heightSegments + 1;
                        var dx = node.geometry.parameters.width / node.geometry.parameters.widthSegments;
                        var data = [];
                        for (var ix = 0; ix < gridX1; ++ix) {
                            data.push(new Float32Array(gridY1));
                            for (var iy = 0; iy < gridY1; ++iy) {
                                data[ix][iy] = array[3 * (gridX1 * (gridY1 - iy - 1) + ix) + 2];
                            }
                        }
                        shape = new CANNON.Heightfield(data, {
                            elementSize: dx
                        });
                        // center to match THREE.PlaneBufferGeometry:
                        position = new CANNON.Vec3();
                        position.x = -node.geometry.parameters.width / 2;
                        position.y = -node.geometry.parameters.height / 2;
                        break;
                    case 'Trimesh':
                        var vertices;
                        var indices;
                        if (node.geometry instanceof THREE.BufferGeometry) {
                            vertices = node.geometry.getAttribute('position').array;
                            indices = node.geometry.index.array;
                        } else {
                            vertices = [];
                            for (var iv = 0; iv < node.geometry.vertices.length; iv++) {
                                var vert = node.geometry.vertices[iv];
                                vertices.push(vert.x, vert.y, vert.z);
                            }
                            indices = [];
                            for (i = 0; i < node.geometry.faces.length; i++) {
                                face = node.geometry.faces[i];
                                indices.push(face.a, face.b, face.c);
                            }
                        }
                        shape = new CANNON.Trimesh(vertices, indices);
                        break;
                    case 'Ellipsoid':
                        // TODO
                        console.warn('TODO');
                        break;
                    default:
                        console.error("unknown shape type: " + e);
                        break;
                }
                body.addShape(shape, position, quaternion);
            });
            node.body = body;
            return body;
        } else if (node instanceof THREE.Object3D) {
            var bodies = [];
            node.children.forEach(function (c) { bodies.push(makeCANNON(c, cannonData)); });
            return bodies;
        } else {
            console.error("makeCANNON error");
        }
    }
};
<|endoftext|>


<commit_before>var lastInputBox;
$.widget("ui.resizable", $.ui.resizable, {
resizeBy: function(newSize) {
		this._mouseStart($.Event("mousedown", { pageX: 0, pageY: 0 }));
		this.axis = 'se';
		var end = $.Event("mouseup", {
				pageX: newSize.width,
				pageY: newSize.height
		});
		this._mouseDrag(end);
		this._mouseStop(end);
}
});

$(document).ready(function() {

		setInterval(update_animations, 100);

		 // Controls menu hide/show
		$('#hotdog').click(function(){
                        $('#controls').toggleClass("active");
    });

		// Reset view
    $('.reset-container').click(function(){ reset_view();});
		$('#submitfindbyname').click(function() {
		      var selected = $('#findbyselect option:selected').text();
					var object = findObjectInfo(selected);
					zoomfocus(selected);
					// Populate information area about target
					//console.log(object)
					var objdata = "Name: " + object.name;
					objdata += "
Classification: " + object.type;
					objdata += "
Owning Faction:" + object.parent.name;
					objdata += "
Location (Galactic Ref.)
X: " + object.x + "
Y: " + object.y + "
Z: " + object.z;
					$('#findbydata').html(objdata)
		});
		$('#route_output').change(function() {
			 var stop=$('#route_output :selected').parent().attr('label');
			 zoomfocus(stop);
		});
		$('#fbc_output').change(function() {
			 var beacon=$('#fbc_output :selected').val();
			 zoomfocus("FBC_" + beacon);
		});
		$('#swapab').click(function() {
			var swap=$('#pointa').val();
			$("#pointa").val($("#pointb").val());
			$("#pointb").val(swap);
		});
		$('#calctnd').click(function() {
			removeEntity('arrow');
			lastInputBox = null;
			$('#route_output').html("No route calculated");
			var speed = {'speed': $('#speed').val(), 'unit':$('#speedunit option:selected').val() };
			populateRoutePlan( $('#pointa  option:selected').text() , $('#pointb  option:selected').text(),speed );
		});
		$('#submitfindcoord').click(function() {
			 cleanupFBC();
			 execFBC( $('#fbc-x').val(), $('#fbc-y').val(), $('#fbc-z').val(), $('#fbc_frame option:selected').val() );
		});
		$('#submitfbcclear').click(function() {
					cleanupFBC();
		});
		$('#cbs').click(function() {populateFBSelect(); });
		$('#cbp').click(function() {populateFBSelect(); });
		$("#pointa").focus(function() {
			lastInputBox = "pointa";
		//	console.log('Updating last touched box to : ' + lastInputBox)
		});
		$("#pointb").focus(function() {
			lastInputBox = "pointb";
		//	console.log('Updating last touched box to : ' + lastInputBox)
		});
		String.prototype.capitalize = function(lower) {
    return (lower ? this.toLowerCase() : this).replace(/(?:^|\s)\S/g, function(a) { return a.toUpperCase(); });
		};
		$('.rpcoord').blur(function() {
			 if(!$(this).val()) { $(this).val( $(this).attr("id") ) }

		});
		$('.rpcoord').focus(function() {
			if($(this).val() == $(this).attr("id")) { $(this).val("") }
		});
		$('#calcpredict').click(function() {
				$('#intel_predicted').html("");
				var predicted = predictDestination(new THREE.Vector3(Number($('#x').val()),Number($('#y').val()),Number($('#z').val())),new THREE.Vector2(Number($('#azmuth').val()),Number($('#inclination').val())),$('#intel_frame option:selected').val());
				$('#intel_predicted').html(predicted);
		});
		$('#client-bar-control').click(function() {
			$('#client-term-container').toggleClass("hidden");
			$('#client-ico-down').toggleClass("hidden");
			$('#client-ico-up').toggleClass("hidden");
		});
		$('#client-login').click(function() { reconnect();})
		$(".vertical-resize").resizable({
        handles: {
            'n': '.handle'
        },
				alsoResize: "#client-term-output",
				minWidth: "100%",
				maxWidth: "100%",
				maxHeight: ($(window).height() * 0.95),
				stop: function(event, ui) {
        $(this).css("width", '');
				$('#client-term-output').css("width",'');
				}
		});
		$(".client-term-container").resize(function() { width = $(this).width(); $("#client").css({'width' : '100%'});   $("#client-term-output").css({'margin-right' : '0px !important', 'padding-right' : '0 !important'})  })
		$.ajax({
			url: 'CHANGELOG.md',
			type: 'get',
			async: 'true',
			success: function(text) {
				var converter = new showdown.Converter(),
				html = converter.makeHtml(text);

				$("#changelog_container").html(html);
			}
		});

		$(window).resize(function() {
				$('.vertical-resize').resizable( "option", "maxHeight", ($('.vertical-resize').parent().parent().height() * 0.95) );
				if($('.vertical-resize').height() > ($('.vertical-resize').parent().parent().height() * 0.95) )  	{
						$('.vertical-resize').resizable("resizeBy", {height: '95%', width:'100%'});
				}
		});
		// Websocket client startup
		startup();

});

function populateUserFields() {
	// Populate findby box
	populateFBSelect();
  // Populate pointa and pointb dropdowns
	var types = ['planets','stations'];
	option = "";
	for (var type in types){
			var keys = Object.keys(listobjects(types[type]));
			var captype = types[type];
			captype = captype.capitalize()
			option += '<optgroup label="'+ captype + '">';
			keys.sort().forEach(function(element, index, array){
				 option += '<option value="'+ escapeHTML(element) + '">' + escapeHTML(element) + '</option>';
			 });
			 option += '</optgroup>';

 	}

 	$('#pointa').html(option);
	$('#pointb').html(option);

	// Populate list of borders for intel frame selection
	option = $('#intel_frame').html();
	var borderlist = listobjects("borders");

	for (var border in borderlist) {
		if(borderlist[border].radius > 10) {
			option += '<option value="'+ escapeHTML(border) + '">' + escapeHTML(border) + '</option>';
		}
	}
		$('#intel_frame').html(option);

		// Poulate the frame list for find by coordinate
		option = $('#fbc_frame').html();
		var borderlist = listobjects("borders");

		for (var border in borderlist) {
			if(borderlist[border].radius > 10) {
				option += '<option value="'+ escapeHTML(border) + '">' + escapeHTML(border) + '</option>';
			}
		}
			$('#fbc_frame').html(option);

}
function populateFBSelect() {
	//Populate find by select dropdown
	 var types = [];
	 var checkboxes = document.getElementsByName("objtype");
	 for (var type in checkboxes) {
	 if(checkboxes[type].checked) {
			types[type] = checkboxes[type].value;
		}

	 }
	 var option = '';
	 for (var type in types) {
		 				var captype = types[type];
		 				captype = captype.capitalize()
		 				option += '<optgroup label="'+ captype + '">';
						var keys = Object.keys(listobjects(types[type]));
						keys.sort().forEach(function(element, index, array){
							 option += '<option value="'+ escapeHTML(element) + '">' + escapeHTML(element) + '</option>';
						 });
						  option += '</optgroup>';

	}

	$('#findbyselect').html(option);

}

function openTab(evt,tabName) {
    var i, x, tablinks;
    x = document.getElementsByClassName("wvg-tools");
    for (i = 0; i < x.length; i++) {
        x[i].style.display = "none";
    }
    tablinks = document.getElementsByClassName("wvg-tablink");
    for (i = 0; i < x.length; i++) {
        tablinks[i].className = tablinks[i].className.replace(" wvg-tab-active", "");
    }
    document.getElementById(tabName).style.display = "block";
    evt.currentTarget.className += " wvg-tab-active";
}

function escapeHTML(text) {
       var chr = { '"': '"', '&': '&', '<': '[', '>': ']' };
       function abc(a)
       {
          return chr[a];
       }
       return text.replace(/[\"&<>]/g, abc);
}

function timeformat(secs) {
	  var s = new Decimal(secs);
    var hours = new Decimal(secs / 3600);
		var h = hours.floor(); //Get whole hours
		s = s - (h * 3600);
		var m = new Decimal(s / 60); //Get remaining minutes
		m = m.floor();
    s = s - (m * 60 );
		s = Math.round(s,0)
	//	console.log("Hours :"+ h);
	//	console.log("Minutes :"+ m);
	//	console.log("Seconds :"+ s);
	//	console.log("Input :"+ secs);
		return h+":"+(m < 10 ? '0'+m : m)+":"+(s < 10 ? '0'+s : s); //zero padding on minutes and seconds
}

function populateRoutePlan(pointa,pointb,speed) {
		if ( pointa != pointb ) {
			// Populate legacy (trip total) fields with route info
			$('#cal_start').html( pointa );
			$('#cal_end').html( pointb );
			$('#cal_speed').html( speed.speed + " " + speed.unit );
			var route = calcBestRoute(pointa,pointb);
			var dist = route.distance;
			var eta = calcETA(speed,dist);
			$('#cal_eta').html( timeformat(eta) );
			$('#cal_dist').html( dist.toFixed(2) + " PC");

			// Populate the route plan select area
			lastWaypoint = {'name': pointa, gate:false};
			var routeplan;
			route.stops.forEach(function(waypoint,index,self) {
				routeplan += '<optgroup label="' + waypoint.name + '">';
				if(typeof self[index+1] != 'undefined' ) {
					if(waypoint.gate && self[index+1].gate) {routeplan += '<option>^---- Gate From</option>'; }
				}
				if(waypoint.gate && lastWaypoint.gate) {routeplan += '<option>^---- Gate Exit</option>'; }

				if(!waypoint.gate || (!lastWaypoint.gate && waypoint.gate)) {
					routeplan += '<option>Distance:' + waypoint.distance.toFixed(2) + '</option>'
					routeplan += '<option>ETA: ' + timeformat(calcETA(speed,waypoint.distance)) + '</option>';
					drawline(grabPositionByName(lastWaypoint.name.split('@')[lastWaypoint.name.split('@').length-1] ),grabPositionByName(waypoint.name.split('@')[waypoint.name.split('@').length-1]    ));
				}
				lastWaypoint = waypoint;
			});
				$('#route_output').html(routeplan);
			//drawline(grabPositionByName($('#pointa  option:selected').text()),grabPositionByName($('#pointb  option:selected').text()));
	}
}

function execFBC(x,y,z,frame) {
			var optionoutput = "";
			var zoomto = "";
			var borderlist = listobjects("borders");

			if(frame === "Unknown") {
				// The stupid bumblefuck located at the chair/computer interface
				// doesn't know where it is so we gotta draw all the places!

				// Galactic frame. The easiest so we do it first on account that i'm stupid
				drawcircleindicator(new THREE.Vector3(x,y,z), "FBC_Galactic");
				optionoutput += '<option> Galactic </option>';

				// Now chooch each border/frame
				for (var border in borderlist) {
					if(borderlist[border].radius > 10) {
						var inputvector = new THREE.Vector3(x,y,z);
						var framevector = new THREE.Vector3(borderlist[border].x, borderlist[border].y, borderlist[border].z);
						var outputvector = framevector.sub(inputvector);
						drawcircleindicator(outputvector,"FBC_" + borderlist[border].name);
						optionoutput += '<option>' + borderlist[border].name + '</option>';
					}
				}
			}  // Borders done got chooched. End bumblefuckery
			else if (frame === "Galactic") {
							drawcircleindicator(new THREE.Vector3(x,y,z), "FBC_Galactic");
							optionoutput += '<option> Galactic </option>';
			}
			else {
				border = borderlist[frame];
				var inputvector = new THREE.Vector3(x,y,z);
				var framevector = new THREE.Vector3(border.x, border.y, border.z);
				var outputvector = framevector.sub(inputvector);
				drawcircleindicator(outputvector,"FBC_" + frame);
				optionoutput += '<option>' + frame + '</option>';
			}

			$('#fbc_output').html(optionoutput);
}

function cleanupFBC() {
	var borderlist = listobjects("borders");
	for (var border in borderlist) {
		if(borderlist[border].radius > 10) {
				removeEntity("FBC_" + borderlist[border].name);
				removeEntity("FBC_" + borderlist[border].name + "_label");
				removeEntity("FBC_" + borderlist[border].name + "_light");
				var index = misc_followers.indexOf("FBC_" + borderlist[border].name + "_label")
				if (index > -1 ) { misc_followers.splice(index, 1);}
		}
		removeEntity("FBC_Galactic");
		removeEntity("FBC_Galactic_light");
		removeEntity("FBC_Galactic_label");
		var index = misc_followers.indexOf("FBC_Galactic_label")
		if (index > -1 ) { misc_followers.splice(index, 1);}

	}
	$('#fbc_output').html("");
}
<commit_msg>Fix inaccurate find by coord due to javascript math<commit_after>var lastInputBox;
$.widget("ui.resizable", $.ui.resizable, {
resizeBy: function(newSize) {
		this._mouseStart($.Event("mousedown", { pageX: 0, pageY: 0 }));
		this.axis = 'se';
		var end = $.Event("mouseup", {
				pageX: newSize.width,
				pageY: newSize.height
		});
		this._mouseDrag(end);
		this._mouseStop(end);
}
});

$(document).ready(function() {

		setInterval(update_animations, 100);

		 // Controls menu hide/show
		$('#hotdog').click(function(){
                        $('#controls').toggleClass("active");
    });

		// Reset view
    $('.reset-container').click(function(){ reset_view();});
		$('#submitfindbyname').click(function() {
		      var selected = $('#findbyselect option:selected').text();
					var object = findObjectInfo(selected);
					zoomfocus(selected);
					// Populate information area about target
					//console.log(object)
					var objdata = "Name: " + object.name;
					objdata += "
Classification: " + object.type;
					objdata += "
Owning Faction:" + object.parent.name;
					objdata += "
Location (Galactic Ref.)
X: " + object.x + "
Y: " + object.y + "
Z: " + object.z;
					$('#findbydata').html(objdata)
		});
		$('#route_output').change(function() {
			 var stop=$('#route_output :selected').parent().attr('label');
			 zoomfocus(stop);
		});
		$('#fbc_output').change(function() {
			 var beacon=$('#fbc_output :selected').val();
			 zoomfocus("FBC_" + beacon);
		});
		$('#swapab').click(function() {
			var swap=$('#pointa').val();
			$("#pointa").val($("#pointb").val());
			$("#pointb").val(swap);
		});
		$('#calctnd').click(function() {
			removeEntity('arrow');
			lastInputBox = null;
			$('#route_output').html("No route calculated");
			var speed = {'speed': $('#speed').val(), 'unit':$('#speedunit option:selected').val() };
			populateRoutePlan( $('#pointa  option:selected').text() , $('#pointb  option:selected').text(),speed );
		});
		$('#submitfindcoord').click(function() {
			 cleanupFBC();
			 execFBC( $('#fbc-x').val(), $('#fbc-y').val(), $('#fbc-z').val(), $('#fbc_frame option:selected').val() );
		});
		$('#submitfbcclear').click(function() {
					cleanupFBC();
		});
		$('#cbs').click(function() {populateFBSelect(); });
		$('#cbp').click(function() {populateFBSelect(); });
		$("#pointa").focus(function() {
			lastInputBox = "pointa";
		//	console.log('Updating last touched box to : ' + lastInputBox)
		});
		$("#pointb").focus(function() {
			lastInputBox = "pointb";
		//	console.log('Updating last touched box to : ' + lastInputBox)
		});
		String.prototype.capitalize = function(lower) {
    return (lower ? this.toLowerCase() : this).replace(/(?:^|\s)\S/g, function(a) { return a.toUpperCase(); });
		};
		$('.rpcoord').blur(function() {
			 if(!$(this).val()) { $(this).val( $(this).attr("id") ) }

		});
		$('.rpcoord').focus(function() {
			if($(this).val() == $(this).attr("id")) { $(this).val("") }
		});
		$('#calcpredict').click(function() {
				$('#intel_predicted').html("");
				var predicted = predictDestination(new THREE.Vector3(Number($('#x').val()),Number($('#y').val()),Number($('#z').val())),new THREE.Vector2(Number($('#azmuth').val()),Number($('#inclination').val())),$('#intel_frame option:selected').val());
				$('#intel_predicted').html(predicted);
		});
		$('#client-bar-control').click(function() {
			$('#client-term-container').toggleClass("hidden");
			$('#client-ico-down').toggleClass("hidden");
			$('#client-ico-up').toggleClass("hidden");
		});
		$('#client-login').click(function() { reconnect();})
		$(".vertical-resize").resizable({
        handles: {
            'n': '.handle'
        },
				alsoResize: "#client-term-output",
				minWidth: "100%",
				maxWidth: "100%",
				maxHeight: ($(window).height() * 0.95),
				stop: function(event, ui) {
        $(this).css("width", '');
				$('#client-term-output').css("width",'');
				}
		});
		$(".client-term-container").resize(function() { width = $(this).width(); $("#client").css({'width' : '100%'});   $("#client-term-output").css({'margin-right' : '0px !important', 'padding-right' : '0 !important'})  })
		$.ajax({
			url: 'CHANGELOG.md',
			type: 'get',
			async: 'true',
			success: function(text) {
				var converter = new showdown.Converter(),
				html = converter.makeHtml(text);

				$("#changelog_container").html(html);
			}
		});

		$(window).resize(function() {
				$('.vertical-resize').resizable( "option", "maxHeight", ($('.vertical-resize').parent().parent().height() * 0.95) );
				if($('.vertical-resize').height() > ($('.vertical-resize').parent().parent().height() * 0.95) )  	{
						$('.vertical-resize').resizable("resizeBy", {height: '95%', width:'100%'});
				}
		});
		// Websocket client startup
		startup();

});

function populateUserFields() {
	// Populate findby box
	populateFBSelect();
  // Populate pointa and pointb dropdowns
	var types = ['planets','stations'];
	option = "";
	for (var type in types){
			var keys = Object.keys(listobjects(types[type]));
			var captype = types[type];
			captype = captype.capitalize()
			option += '<optgroup label="'+ captype + '">';
			keys.sort().forEach(function(element, index, array){
				 option += '<option value="'+ escapeHTML(element) + '">' + escapeHTML(element) + '</option>';
			 });
			 option += '</optgroup>';

 	}

 	$('#pointa').html(option);
	$('#pointb').html(option);

	// Populate list of borders for intel frame selection
	option = $('#intel_frame').html();
	var borderlist = listobjects("borders");

	for (var border in borderlist) {
		if(borderlist[border].radius > 10) {
			option += '<option value="'+ escapeHTML(border) + '">' + escapeHTML(border) + '</option>';
		}
	}
		$('#intel_frame').html(option);

		// Poulate the frame list for find by coordinate
		option = $('#fbc_frame').html();
		var borderlist = listobjects("borders");

		for (var border in borderlist) {
			if(borderlist[border].radius > 10) {
				option += '<option value="'+ escapeHTML(border) + '">' + escapeHTML(border) + '</option>';
			}
		}
			$('#fbc_frame').html(option);

}
function populateFBSelect() {
	//Populate find by select dropdown
	 var types = [];
	 var checkboxes = document.getElementsByName("objtype");
	 for (var type in checkboxes) {
	 if(checkboxes[type].checked) {
			types[type] = checkboxes[type].value;
		}

	 }
	 var option = '';
	 for (var type in types) {
		 				var captype = types[type];
		 				captype = captype.capitalize()
		 				option += '<optgroup label="'+ captype + '">';
						var keys = Object.keys(listobjects(types[type]));
						keys.sort().forEach(function(element, index, array){
							 option += '<option value="'+ escapeHTML(element) + '">' + escapeHTML(element) + '</option>';
						 });
						  option += '</optgroup>';

	}

	$('#findbyselect').html(option);

}

function openTab(evt,tabName) {
    var i, x, tablinks;
    x = document.getElementsByClassName("wvg-tools");
    for (i = 0; i < x.length; i++) {
        x[i].style.display = "none";
    }
    tablinks = document.getElementsByClassName("wvg-tablink");
    for (i = 0; i < x.length; i++) {
        tablinks[i].className = tablinks[i].className.replace(" wvg-tab-active", "");
    }
    document.getElementById(tabName).style.display = "block";
    evt.currentTarget.className += " wvg-tab-active";
}

function escapeHTML(text) {
       var chr = { '"': '"', '&': '&', '<': '[', '>': ']' };
       function abc(a)
       {
          return chr[a];
       }
       return text.replace(/[\"&<>]/g, abc);
}

function timeformat(secs) {
	  var s = new Decimal(secs);
    var hours = new Decimal(secs / 3600);
		var h = hours.floor(); //Get whole hours
		s = s - (h * 3600);
		var m = new Decimal(s / 60); //Get remaining minutes
		m = m.floor();
    s = s - (m * 60 );
		s = Math.round(s,0)
	//	console.log("Hours :"+ h);
	//	console.log("Minutes :"+ m);
	//	console.log("Seconds :"+ s);
	//	console.log("Input :"+ secs);
		return h+":"+(m < 10 ? '0'+m : m)+":"+(s < 10 ? '0'+s : s); //zero padding on minutes and seconds
}

function populateRoutePlan(pointa,pointb,speed) {
		if ( pointa != pointb ) {
			// Populate legacy (trip total) fields with route info
			$('#cal_start').html( pointa );
			$('#cal_end').html( pointb );
			$('#cal_speed').html( speed.speed + " " + speed.unit );
			var route = calcBestRoute(pointa,pointb);
			var dist = route.distance;
			var eta = calcETA(speed,dist);
			$('#cal_eta').html( timeformat(eta) );
			$('#cal_dist').html( dist.toFixed(2) + " PC");

			// Populate the route plan select area
			lastWaypoint = {'name': pointa, gate:false};
			var routeplan;
			route.stops.forEach(function(waypoint,index,self) {
				routeplan += '<optgroup label="' + waypoint.name + '">';
				if(typeof self[index+1] != 'undefined' ) {
					if(waypoint.gate && self[index+1].gate) {routeplan += '<option>^---- Gate From</option>'; }
				}
				if(waypoint.gate && lastWaypoint.gate) {routeplan += '<option>^---- Gate Exit</option>'; }

				if(!waypoint.gate || (!lastWaypoint.gate && waypoint.gate)) {
					routeplan += '<option>Distance:' + waypoint.distance.toFixed(2) + '</option>'
					routeplan += '<option>ETA: ' + timeformat(calcETA(speed,waypoint.distance)) + '</option>';
					drawline(grabPositionByName(lastWaypoint.name.split('@')[lastWaypoint.name.split('@').length-1] ),grabPositionByName(waypoint.name.split('@')[waypoint.name.split('@').length-1]    ));
				}
				lastWaypoint = waypoint;
			});
				$('#route_output').html(routeplan);
			//drawline(grabPositionByName($('#pointa  option:selected').text()),grabPositionByName($('#pointb  option:selected').text()));
	}
}

function execFBC(x,y,z,frame) {
			var optionoutput = "";
			var zoomto = "";
			var borderlist = listobjects("borders");

			if(frame === "Unknown") {
				// The stupid bumblefuck located at the chair/computer interface
				// doesn't know where it is so we gotta draw all the places!

				// Galactic frame. The easiest so we do it first on account that i'm stupid
				drawcircleindicator(new THREE.Vector3(x,y,z), "FBC_Galactic");
				optionoutput += '<option> Galactic </option>';

				// Now chooch each border/frame
				for (var border in borderlist) {
					if(borderlist[border].radius > 10) {
						var inputvector = new THREE.Vector3(parseFloat( x ),parseFloat( y ),parseFloat( z ));
						var framevector = new THREE.Vector3(parseFloat( borderlist[border].x ), parseFloat( borderlist[border].y ), parseFloat( borderlist[border].z ));
						var outputvector = framevector.add(inputvector);
						drawcircleindicator(outputvector,"FBC_" + borderlist[border].name);
						optionoutput += '<option>' + borderlist[border].name + '</option>';
					}
				}
			}  // Borders done got chooched. End bumblefuckery
			else if (frame === "Galactic") {
							drawcircleindicator(new THREE.Vector3(x,y,z), "FBC_Galactic");
							optionoutput += '<option> Galactic </option>';
			}
			else {
				border = borderlist[frame];
				var inputvector = new THREE.Vector3(parseFloat( x ),parseFloat( y ),parseFloat( z ));
				var framevector = new THREE.Vector3(parseFloat( border.x ), parseFloat( border.y ), parseFloat( border.z ));
				var outputvector = framevector.add(inputvector);
				console.log( outputvector );
				drawcircleindicator(outputvector,"FBC_" + frame);
				optionoutput += '<option>' + frame + '</option>';
			}

			$('#fbc_output').html(optionoutput);
}

function cleanupFBC() {
	var borderlist = listobjects("borders");
	for (var border in borderlist) {
		if(borderlist[border].radius > 10) {
				removeEntity("FBC_" + borderlist[border].name);
				removeEntity("FBC_" + borderlist[border].name + "_label");
				removeEntity("FBC_" + borderlist[border].name + "_light");
				var index = misc_followers.indexOf("FBC_" + borderlist[border].name + "_label")
				if (index > -1 ) { misc_followers.splice(index, 1);}
		}
		removeEntity("FBC_Galactic");
		removeEntity("FBC_Galactic_light");
		removeEntity("FBC_Galactic_label");
		var index = misc_followers.indexOf("FBC_Galactic_label")
		if (index > -1 ) { misc_followers.splice(index, 1);}

	}
	$('#fbc_output').html("");
}
<|endoftext|>


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

 MO5.js - JavaScript Library For Building Modern DOM And Canvas Applications

 Copyright (c) 2013 Jonathan Steinbeck
 All rights reserved.

 Redistribution and use in source and binary forms, with or without
 modification, are permitted provided that the following conditions are met:

 * Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.

 * Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.

 * Neither the name MO5.js nor the names of its contributors
   may be used to endorse or promote products derived from this software
   without specific prior written permission.

 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY
 DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

/////////////////////////////////////////////////////////////////////////////////*/

/* global MO5, window, module, require */

(function MO5TimerBootstrap () {

    if (typeof MO5 === "function") {
        MO5("MO5.Exception", "MO5.CoreObject", "MO5.fail", "MO5.Promise").
        define("MO5.Timer", MO5TimerModule);
    }
    else if (typeof window !== "undefined") {
        window.MO5.Timer = MO5TimerModule(MO5.Exception, MO5.CoreObject, MO5.fail, MO5.Promise);
    }
    else {
        module.exports = MO5TimerModule(
            require("./MO5.Exception.js"),
            require("./MO5.CoreObject.js"),
            require("./MO5.fail.js"),
            require("./MO5.Promise.js")
        );
    }

    function MO5TimerModule (Exception, CoreObject, fail, Promise) {

        function TimerError (msg) {
            Exception.call(this);

            this.message = msg;
            this.name = "MO5.TimerError";
        }

        TimerError.prototype = new Exception();

        /**
         * A Timer object is returned by the transform() function.
         * It can be used to control the transformation during its
         * execution and it can also be used to obtain information
         * about the state of a transformation, e.g. whether it's
         * still ongoing.
         */
        function Timer () {
            CoreObject.call(this);

            this.running = false;
            this.paused = false;
            this.canceled = false;
            this.startTime = +(new Date());
            this.timeElapsed = 0;
            this.pauseTimeElapsed = 0;
            this.pauseStartTime = this.startTime;
        }

        Timer.prototype = new CoreObject();
        Timer.prototype.constructor = Timer;

        Timer.prototype.start = function () {
            this.startTime = +(new Date());
            this.running = true;

            this.trigger("started", null, false);

            return this;
        };

        Timer.prototype.stop = function () {
            this.running = false;
            this.paused = false;

            this.trigger("stopped", null, false);

            return this;
        };

        Timer.prototype.cancel = function () {
            if (!this.running) {
                fail(new TimerError("Trying to cancel a Timer that isn't running."));
            }

            this.elapsed();
            this.canceled = true;
            this.running = false;
            this.paused = false;

            this.trigger("canceled", null, false);

            return this;
        };

        Timer.prototype.isRunning = function () {
            return this.running;
        };

        Timer.prototype.isCanceled = function () {
            return this.canceled;
        };

        Timer.prototype.isPaused = function () {
            return this.paused;
        };

        Timer.prototype.pause = function () {
            this.paused = true;
            this.pauseStartTime = +(new Date());
            this.trigger("paused", null, false);
        };

        Timer.prototype.resume = function () {
            if (!this.paused) {
                fail(new TimerError("Trying to resume a timer that isn't paused."));
            }

            this.paused = false;
            this.pauseTimeElapsed += +(new Date()) - this.pauseStartTime;
            this.trigger("resumed", null, false);
        };

        /**
         * Returns the number of milliseconds since the call of start(). If the
         * Timer's already been stopped, then the number of milliseconds between
         * start() and stop() is returned. The number of milliseconds does not
         * include the times between pause() and resume()!
         */
        Timer.prototype.elapsed = function () {
            if (this.running && !this.paused) {
                this.timeElapsed = ((+(new Date()) - this.startTime) - this.pauseTimeElapsed);
            }

            return this.timeElapsed;
        };

        /**
         * Returns a capability object that can be given to other objects
         * by those owning a reference to the Timer. It is read only so that
         * the receiver of the capability object can only obtain information
         * about the Timer's state, but not modify it.
         */
        Timer.prototype.getReadOnlyCapability = function () {
            var self = this;

            return {
                isRunning: function () { return self.running; },
                isCanceled: function () { return self.canceled; },
                isPaused: function () { return self.paused; },
                elapsed: function () { return self.elapsed(); }
            };
        };

        Timer.prototype.promise = function () {

            var promise = new Promise(), self = this;

            this.once(
                function () {
                    if (!promise.destroyed && promise.isPending()) {
                        promise.resolve(self);
                    }
                },
                "stopped"
            );

            this.once(
                function () {
                    if (!promise.destroyed && promise.isPending()) {
                        promise.reject(self);
                    }
                },
                "canceled"
            );

            this.once(
                function () {
                    if (!promise.destroyed && promise.isPending()) {
                        promise.reject(self);
                    }
                },
                "destroyed"
            );

            return promise;
        };

        return Timer;

    }
}());
<commit_msg>Changed .promise() method on Timer to work with the new Promise class.<commit_after>/*/////////////////////////////////////////////////////////////////////////////////

 MO5.js - JavaScript Library For Building Modern DOM And Canvas Applications

 Copyright (c) 2013 Jonathan Steinbeck
 All rights reserved.

 Redistribution and use in source and binary forms, with or without
 modification, are permitted provided that the following conditions are met:

 * Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.

 * Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.

 * Neither the name MO5.js nor the names of its contributors
   may be used to endorse or promote products derived from this software
   without specific prior written permission.

 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY
 DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

/////////////////////////////////////////////////////////////////////////////////*/

/* global MO5, window, module, require */

(function MO5TimerBootstrap () {

    if (typeof MO5 === "function") {
        MO5("MO5.Exception", "MO5.CoreObject", "MO5.fail", "MO5.Promise").
        define("MO5.Timer", MO5TimerModule);
    }
    else if (typeof window !== "undefined") {
        window.MO5.Timer = MO5TimerModule(MO5.Exception, MO5.CoreObject, MO5.fail, MO5.Promise);
    }
    else {
        module.exports = MO5TimerModule(
            require("./MO5.Exception.js"),
            require("./MO5.CoreObject.js"),
            require("./MO5.fail.js"),
            require("./MO5.Promise.js")
        );
    }

    function MO5TimerModule (Exception, CoreObject, fail, Promise) {

        function TimerError (msg) {
            Exception.call(this);

            this.message = msg;
            this.name = "MO5.TimerError";
        }

        TimerError.prototype = new Exception();

        /**
         * A Timer object is returned by the transform() function.
         * It can be used to control the transformation during its
         * execution and it can also be used to obtain information
         * about the state of a transformation, e.g. whether it's
         * still ongoing.
         */
        function Timer () {
            CoreObject.call(this);

            this.running = false;
            this.paused = false;
            this.canceled = false;
            this.startTime = +(new Date());
            this.timeElapsed = 0;
            this.pauseTimeElapsed = 0;
            this.pauseStartTime = this.startTime;
        }

        Timer.prototype = new CoreObject();
        Timer.prototype.constructor = Timer;

        Timer.prototype.start = function () {
            this.startTime = +(new Date());
            this.running = true;

            this.trigger("started", null, false);

            return this;
        };

        Timer.prototype.stop = function () {
            this.running = false;
            this.paused = false;

            this.trigger("stopped", null, false);

            return this;
        };

        Timer.prototype.cancel = function () {
            if (!this.running) {
                fail(new TimerError("Trying to cancel a Timer that isn't running."));
            }

            this.elapsed();
            this.canceled = true;
            this.running = false;
            this.paused = false;

            this.trigger("canceled", null, false);

            return this;
        };

        Timer.prototype.isRunning = function () {
            return this.running;
        };

        Timer.prototype.isCanceled = function () {
            return this.canceled;
        };

        Timer.prototype.isPaused = function () {
            return this.paused;
        };

        Timer.prototype.pause = function () {
            this.paused = true;
            this.pauseStartTime = +(new Date());
            this.trigger("paused", null, false);
        };

        Timer.prototype.resume = function () {
            if (!this.paused) {
                fail(new TimerError("Trying to resume a timer that isn't paused."));
            }

            this.paused = false;
            this.pauseTimeElapsed += +(new Date()) - this.pauseStartTime;
            this.trigger("resumed", null, false);
        };

        /**
         * Returns the number of milliseconds since the call of start(). If the
         * Timer's already been stopped, then the number of milliseconds between
         * start() and stop() is returned. The number of milliseconds does not
         * include the times between pause() and resume()!
         */
        Timer.prototype.elapsed = function () {
            if (this.running && !this.paused) {
                this.timeElapsed = ((+(new Date()) - this.startTime) - this.pauseTimeElapsed);
            }

            return this.timeElapsed;
        };

        /**
         * Returns a capability object that can be given to other objects
         * by those owning a reference to the Timer. It is read only so that
         * the receiver of the capability object can only obtain information
         * about the Timer's state, but not modify it.
         */
        Timer.prototype.getReadOnlyCapability = function () {
            var self = this;

            return {
                isRunning: function () { return self.running; },
                isCanceled: function () { return self.canceled; },
                isPaused: function () { return self.paused; },
                elapsed: function () { return self.elapsed(); }
            };
        };

        Timer.prototype.promise = function () {

            var promise = new Promise(), self = this;

            this.once(
                function () {
                    promise.resolve(self);
                },
                "stopped"
            );

            this.once(
                function () {
                    promise.reject(self);
                },
                "canceled"
            );

            this.once(
                function () {
                    promise.reject(self);
                },
                "destroyed"
            );

            return promise;
        };

        return Timer;

    }
}());
<|endoftext|>


<commit_before>/*jslint browser: true, white: true, vars: true */
/*globals GameManager, proxy_makeMove */

(function (global) {
    "use strict";
    var emptyFunc = function () { return undefined; };
    function fakeInputManager() {
        this.on = emptyFunc;
    }

    function fakeActuator() {
        this.actuate = emptyFunc;
    }

    function makeMove(model, move) {
        var gameManager = new GameManager(model.grid.size, fakeInputManager, fakeActuator,
            function fakeStorageManager() {
                this.getGameState = function () {
                    return model;
                };
                this.getBestScore = emptyFunc;
                this.setGameState = emptyFunc;
            });
        gameManager.actuate = emptyFunc;
        gameManager.move(move);
        return {
            score: gameManager.score,
            model: JSON.parse(JSON.stringify(gameManager.serialize())),
            wasMoved: JSON.stringify(gameManager.serialize().grid) !== JSON.stringify(model.grid),
            move: move
        };
    }

    global.proxy_makeMove = makeMove;
}(window));

(function (global) {
    "use strict";

    var keydown = function (k) {
        var oEvent = document.createEvent('KeyboardEvent');

        Object.defineProperty(oEvent, 'keyCode', {
            get : function() {
                return this.keyCodeVal;
            }
        });
        Object.defineProperty(oEvent, 'metaKey', {
            get : function() {
                return false;
            }
        });
        Object.defineProperty(oEvent, 'shiftKey', {
            get : function() {
                return false;
            }
        });
        Object.defineProperty(oEvent, 'which', {
            get : function() {
                return this.keyCodeVal;
            }
        });

        Object.defineProperty(oEvent, 'target', {
            get : function() {
                return {tagName: ""};
            }
        });

        if (oEvent.initKeyboardEvent) {
            oEvent.initKeyboardEvent("keydown", true, true, document.defaultView, false, false, false, false, k, k);
        } else {
            oEvent.initKeyEvent("keydown", true, true, document.defaultView, false, false, false, false, k, 0);
        }

        oEvent.keyCodeVal = k;

        if (oEvent.keyCode !== k) {
            throw "keyCode mismatch " + oEvent.keyCode + "(" + oEvent.which + ")";
        }

        document.dispatchEvent(oEvent);
    };

    function runAI() {
        var MOVE = {
            LEFT: 37,
            UP: 38,
            RIGHT: 39,
            DOWN: 40
        };

        /*var makeAIMove = function () {
            var moves = [MOVE.LEFT, MOVE.UP, MOVE.RIGHT, MOVE.DOWN];
            var randomIndex = Math.floor(Math.random()*4);
            var randomMove = moves[randomIndex];
            return randomMove;
        };*/

        var oneLevelAI = function (model) {
            var possibleMoves = [0, 1, 2, 3].map(function (internalMove) {
                var copyOfModel = JSON.parse(JSON.stringify(model));
                return proxy_makeMove(copyOfModel, internalMove);
            });

            var bestMove = possibleMoves.sort(function (a, b) {
                var d = a.score - b.score;
                if (d === 0 ) {
                    d = (a.wasMoved ? 1 : 0) - (b.wasMoved ? 1 : 0);
                }
                return -d;
            })[0];

            var moves = [MOVE.UP, MOVE.RIGHT, MOVE.DOWN, MOVE.LEFT];
            return moves[bestMove.move];
        };

        function aiLoop(aiAlgorithm) {
            setTimeout(function () {
                var model = JSON.parse(localStorage.getItem("gameState"));
                if(model !== null) {
                    var aiMove = aiAlgorithm(model);
                    keydown(aiMove);
                    aiLoop(aiAlgorithm);
                }
            }, 100);
        }

        aiLoop(oneLevelAI);
    }

    global.runAI = runAI;
}(window));
<commit_msg>Implement AI that based on tree of moves<commit_after>/*jslint browser: true, white: true, vars: true */
/*globals GameManager, proxy_makeMove */

(function (global) {
    "use strict";
    var emptyFunc = function () { return undefined; };
    function fakeInputManager() {
        this.on = emptyFunc;
    }

    function fakeActuator() {
        this.actuate = emptyFunc;
    }

    function makeMove(model, move) {
        var gameManager = new GameManager(model.grid.size, fakeInputManager, fakeActuator,
            function fakeStorageManager() {
                this.getGameState = function () {
                    return model;
                };
                this.clearGameState = emptyFunc;
                this.getBestScore = emptyFunc;
                this.setGameState = emptyFunc;
            });
        gameManager.actuate = emptyFunc;
        gameManager.move(move);
        return {
            score: gameManager.score,
            model: JSON.parse(JSON.stringify(gameManager.serialize())),
            wasMoved: JSON.stringify(gameManager.serialize().grid) !== JSON.stringify(model.grid),
            move: move
        };
    }

    global.proxy_makeMove = makeMove;
}(window));

(function (global) {
    "use strict";

    var keydown = function (k) {
        var oEvent = document.createEvent('KeyboardEvent');

        Object.defineProperty(oEvent, 'keyCode', {
            get : function() {
                return this.keyCodeVal;
            }
        });
        Object.defineProperty(oEvent, 'metaKey', {
            get : function() {
                return false;
            }
        });
        Object.defineProperty(oEvent, 'shiftKey', {
            get : function() {
                return false;
            }
        });
        Object.defineProperty(oEvent, 'which', {
            get : function() {
                return this.keyCodeVal;
            }
        });

        Object.defineProperty(oEvent, 'target', {
            get : function() {
                return {tagName: ""};
            }
        });

        if (oEvent.initKeyboardEvent) {
            oEvent.initKeyboardEvent("keydown", true, true, document.defaultView, false, false, false, false, k, k);
        } else {
            oEvent.initKeyEvent("keydown", true, true, document.defaultView, false, false, false, false, k, 0);
        }

        oEvent.keyCodeVal = k;

        if (oEvent.keyCode !== k) {
            throw "keyCode mismatch " + oEvent.keyCode + "(" + oEvent.which + ")";
        }

        document.dispatchEvent(oEvent);
    };

    function runAI() {
        var MOVE = {
            LEFT: 37,
            UP: 38,
            RIGHT: 39,
            DOWN: 40
        };

        /*var makeAIMove = function () {
            var moves = [MOVE.LEFT, MOVE.UP, MOVE.RIGHT, MOVE.DOWN];
            var randomIndex = Math.floor(Math.random()*4);
            var randomMove = moves[randomIndex];
            return randomMove;
        };*/

        /*var oneLevelAI = function (model) {
            var possibleMoves = [0, 1, 2, 3].map(function (internalMove) {
                var copyOfModel = JSON.parse(JSON.stringify(model));
                return proxy_makeMove(copyOfModel, internalMove);
            });

            var bestMove = possibleMoves.sort(function (a, b) {
                var d = a.score - b.score;
                if (d === 0 ) {
                    d = (a.wasMoved ? 1 : 0) - (b.wasMoved ? 1 : 0);
                }
                return -d;
            })[0];

            var moves = [MOVE.UP, MOVE.RIGHT, MOVE.DOWN, MOVE.LEFT];
            return moves[bestMove.move];
        };*/

        var treeAI = function (model, maxLevel) {
            var leaves = [];

            var expandTree = function (node, level) {
                if (level == maxLevel) {
                    leaves.push(node);
                    return;
                }

                var possibleMoves = [0, 1, 2, 3].map(function (internalMove) {
                    var copyOfModel = JSON.parse(JSON.stringify(node.value));
                    var newNode = {
                        value: proxy_makeMove(copyOfModel.model, internalMove),
                        children: [],
                        move: internalMove,
                        parent: node
                    };

                    if(newNode.value.wasMoved) {
                        node.children.push(newNode);
                    }
                });

                node.children.forEach(function (childNode) {
                    expandTree(childNode, level + 1);
                });

                if(node.children.length == 0) {
                    leaves.push(node);
                }
            };

            var rootNode = {value: {model: model}, children: []};
            expandTree(rootNode, 0);

            var bestNode = leaves.sort(function (a, b) {
                return b.value.score - a.value.score;
            })[0];

            var bestMove;
            while (bestNode.parent !== undefined) {
                bestMove = bestNode.move;
                bestNode = bestNode.parent;
            }

            var moves = [MOVE.UP, MOVE.RIGHT, MOVE.DOWN, MOVE.LEFT];
            return moves[bestMove];
        };

        function aiLoop(aiAlgorithm) {
            setTimeout(function () {
                var model = JSON.parse(localStorage.getItem("gameState"));
                if(model !== null) {
                    var aiMove = aiAlgorithm(model);
                    keydown(aiMove);
                    aiLoop(aiAlgorithm);
                }
            }, 100);
        }

        aiLoop(function (model) { return treeAI(model, 3);});
    }

    global.runAI = runAI;
}(window));
<|endoftext|>


<commit_before>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
	(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new
		Date();a=s.createElement(o),
	m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');

ga('create', 'UA-42531432-1', 'auto');
ga('send', 'pageview');
<commit_msg>Added enhanced link attribution for analytics<commit_after>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
	(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new
		Date();a=s.createElement(o),
	m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');

ga('create', 'UA-42531432-1', 'auto');
ga('require', 'linkid', 'linkid.js');
ga('send', 'pageview');
<|endoftext|>


<commit_before>$(document).ready(function(){
	app.c.init();
	app.v.init();
	app.c.listeners();
})
/////////////////////////////////////////////////////////////////////////////////

var app={m:{},v:{},c:{}};

/////////////////////////////////////////////////////////////////////////////////

app.m.inspiration=false;
app.m.lexicon=false;
app.m.colors={};
app.m.colors.primary="#f37";
app.m.colors.secondary="#f67";
app.m.colors.grey="#555";

/////////////////////////////////////////////////////////////////////////////////

app.c.init=function(){
	app.m.metadata={"name":"Lingua Esoterica","version":"0.0.2"};
};

app.c.listeners=function(){

$("input#count").click(function(){
	var input=$("#input").val();
	var inspiration=$("input[type=text]#inspiration").val();
	var count=$("input[name=count]:checked").val();
	var division=$("input[name=division]:checked").val();
	if (parseInt(division)==1){
		division=true;
	}else{
		division=false;
	}
	//console.log(division);
	input=app.c.ziph(input,parseInt(count,10),division);

	var sortable=[];
	for (var key in input){sortable.push([key,input[key].count],input[key].translation);}
	sortable.sort(function(a,b){return b[1]-a[1];});

	var s=[];
	for (var i=0;i<sortable.length;i++){
		if (sortable[i]!==undefined){s.push(sortable[i]);}
	}
	sortable=s;

	app.m.lexicon=app.c.translate(input,app.c.phonemify(inspiration));
	app.v.glossary(sortable);

});

};

app.c.ziph=function(sample,n,spaces){
	var spaces=spaces||false;
	var n=n||1;
	var lex={};
	var sample=sample.toLowerCase();
	if (spaces==true){
		sample=sample.split(" ");
	}
	else{
		sample=sample.split("");
	}

	app.m.sampleLength=sample.length;

	for (var i=0;i<=(sample.length-n);i++){
		//then populate the lexicon
			var compilation=[];
			for (var j=0;j<n;j++){
				compilation.push(sample[i+j])
			}
			if (spaces==true){
				compilation=compilation.join(" ");
			}
			else{
				compilation=compilation.join("");
			}

		if (!lex[compilation]){
			lex[compilation]={};
			lex[compilation].count=1;
		}
		else{
			lex[compilation].count++;
		}
	}
	return lex;
};

app.c.translate=function(lexicon,phonemes){
	var s=[];

	console.log("lexicon");

	var i=0;
	for (var key in lexicon){i++;}
	console.log(i);

	var ps=[];
	while (ps.length-1){
			nt+=davis.pick(phonemes);
		}

		ps.push(nt);
		console.log(nt);
		ps=_.uniq(ps);
	};

	var i=0;
	for (var key in lexicon){
		var t=ps[i];
		s.push({source:key,count:lexicon[key],translation:t});
		i++;
	};

	return s;
};

app.c.phonemify = function (inspiration) {
	var soft = [
		'c', 'f', 'h', 'l', 'm', 'n', 'r', 's', 'v', 'w', 'z', 'y'
	];
	var hard = [
		'b', 'c', 'd', 'g', 'j', 'k', 'p', 'q', 't', 'x', 'y'
	];
	var vowels = [
		'a', 'e', 'i', 'o', 'u', 'y'
	];
	var softp = inspiration.match(new RegExp('([' + vowels.join('|') + "]+["+ soft.join('|') + ']+)', 'gi')) || [];
	var hardp = inspiration.match(new RegExp('([' + vowels.join('|') + "]+["+ hard.join('|') + ']+)', 'gi')) || [];
	var softsoft = inspiration.match(new RegExp('([' + soft.join('|') + ']+[' + vowels.join('|') + "]+["+ soft.join('|') + ']+)', 'gi')) || [];
	var softhard = inspiration.match(new RegExp('([' + soft.join('|') + ']+[' + vowels.join('|') + "]+["+ hard.join('|') + ']+)', 'gi')) || [];
	var hardsoft = inspiration.match(new RegExp('([' + hard.join('|') + ']+[' + vowels.join('|') + "]+["+ soft.join('|') + ']+)', 'gi')) || [];
	var hardhard = inspiration.match(new RegExp('([' + hard.join('|') + ']+[' + vowels.join('|') + "]+["+ hard.join('|') + ']+)', 'gi')) || [];
	var default_ret = [
		'sa','so','si','da','do','di'
	];

	var ret = _.uniq([].concat(softp, hardp, softsoft, softhard, hardsoft, hardhard));

	if (ret.length < 1) {
		return default_ret;
	}

	return ret || default_ret;
};

app.c.phonemify_0 = function (inspiration) {
	var soft = [
		'c', 'f', 'h', 'l', 'm', 'n', 'r', 's', 'v', 'w', 'z', 'y'
	];
	var hard = [
		'b', 'c', 'd', 'g', 'j', 'k', 'p', 'q', 't', 'x', 'y'
	];
	var vowels = [
		'a', 'e', 'i', 'o', 'u', 'y'
	];
	var softp = inspiration.match(new RegExp('([' + vowels.join('|') + "]+["+ soft.join('|') + ']+)', 'gi')) || [];
	var hardp = inspiration.match(new RegExp('([' + vowels.join('|') + "]+["+ hard.join('|') + ']+)', 'gi')) || [];
	var softsoft = inspiration.match(new RegExp('([' + soft.join('|') + ']+[' + vowels.join('|') + "]+["+ soft.join('|') + ']+)', 'gi')) || [];
	var softhard = inspiration.match(new RegExp('([' + soft.join('|') + ']+[' + vowels.join('|') + "]+["+ hard.join('|') + ']+)', 'gi')) || [];
	var hardsoft = inspiration.match(new RegExp('([' + hard.join('|') + ']+[' + vowels.join('|') + "]+["+ soft.join('|') + ']+)', 'gi')) || [];
	var hardhard = inspiration.match(new RegExp('([' + hard.join('|') + ']+[' + vowels.join('|') + "]+["+ hard.join('|') + ']+)', 'gi')) || [];
	var default_ret = [
		'sa','so','si','da','do','di'
	];

	var ret = _.uniq([].concat(softp, hardp, softsoft, softhard, hardsoft, hardhard));

	if (ret.length < 1) {
		return default_ret;
	}

	return ret || default_ret;
};

///////////////////////////////////////////

app.v.init=function(){
	app.v.style();
	app.v.LAYOUT();
};

app.v.LAYOUT=function(){
var d="";
	d+="
";
		d+="
"+app.m.metadata.name+"
";
		d+=app.v.exposition();
		d+="
";
		d+="<input type='radio' value='1' name='count' checked>count by singletons
";
		d+="<input type='radio' value='2' name='count'>count by doubles
";
		d+="<input type='radio' value='3' name='count'>count by triples
";
		d+="<input type='radio' value='4' name='count'>count by quadruples
";
		d+="
";
		d+="<input type='radio' value='1' name='division' checked>count by words
";
		d+="<input type='radio' value='0' name='division'>count by characters
";
		d+="
";
		d+="
inspirational seed
";
		d+="
";
			d+="<input type='text' id='inspiration'></input>";
		d+="
";
		d+="
text to translate
";
		d+="<textarea rows='10' cols='5' id='input' autofocus></textarea>";
		d+="<input type='button' value='translate' id='count'></input>";
	d+="
";
	d+="
";
	d+="
";
	$("body").html(d);
};

app.v.exposition=function(){
	var d="
";
	d+="a quick way to create a fantasy language: ";
	d+="just give esoterica a little inspiration, and some text to translate, ";
	d+="and you'll get a quick english to fantasy-language dictionary.";
	d+="
";
	return d;
};

app.v.glossary=function(sortable){
	var lex=app.m.lexicon;
	var d="";
	d+="
Translating Dictionary
";
	d+="
";
	//d+="
sample length: "+app.m.sampleLength+"
";
	d+="
source	translation
";
	for (var i=0;i<lex.length;i++){
		var rowClass="odd";
		if (i%2==0){rowClass="even";}
		d+="
"+lex[i].source+"	"+lex[i].translation+"
";
	}
	d+="
";
	$("#output").html(d);
};

//////////////////////////////////////////
//////////////////////////////////////////

app.v.style=function(){
	davis.style("body",{
		"width":"100%",
		"margin":"0px",
		"padding":"0px",
		"color":"#555",
		"font-size":"1em",
		"font-family":"sans-serif"
	});
	davis.style("div",{
		"padding":"0",
		"font-size":"1.5em",
		"margin":"30px"
	});
	davis.style("h1",{
		"text-align":"left",
		"font-size":"2em",
		"margin-bottom":"30px",
		"color":app.m.colors.primary
	});
	davis.style("input[type=button]",{
		"width":"100%",
		"font-size":"2em",
		"background":app.m.colors.primary,
		"border":"2px solid "+app.m.colors.grey,
		"cursor":"pointer",
		"color":"#fff"
	});
	davis.style("textarea",{
		"width":"100%",
		"font-size":"0.8em",
		"font-family":"arial sans-serif",
		"border":"1px solid "+app.m.colors.grey,
		"margin":"0",
		"margin-top":"10px"
	});
	davis.style("table",{
		"width":"100%"
	});
	davis.style("table#layout",{
		"height":"100%",
		"table-layout":"fixed"
	});
	davis.style("td",{
		"padding":"30px",
		"margin":"0px",
		"vertical-align":"top",
		"text-align":"left"
	});
	davis.style("div#output",{
		"text-align":"left",
		"padding":"0"
	});
	davis.style("div#output td",{
		"background":app.m.colors.primary,
		"color":"#fff",
		"padding":"3px",
		"margin":"0",
	});
	davis.style("tr.odd td",{
		"background":app.m.colors.secondary
	});
	davis.style("td#output td:hover",{
		"background":"#555"
	});
	davis.style("div.wrapper",{
		"padding":"0",
		"margin":"0",
		"border":"0"
	});
	davis.style("div#options",{
		"display":"none"
	});
	davis.style("p#exposition",{
		"font-size":"0.8em"
	});
	davis.style("input[type=text]",{
		"width":"100%"
	});
	davis.style("th",{
		"background":"transparent",
		"border":"0",
		"font-size":"2em",
		"text-align":"center"
	});
};<commit_msg>expanded the phonemify method to include naked vowels<commit_after>$(document).ready(function(){
	app.c.init();
	app.v.init();
	app.c.listeners();
})
/////////////////////////////////////////////////////////////////////////////////

var app={m:{},v:{},c:{}};

/////////////////////////////////////////////////////////////////////////////////

app.m.inspiration=false;
app.m.lexicon=false;
app.m.colors={};
app.m.colors.primary="#f37";
app.m.colors.secondary="#f67";
app.m.colors.grey="#555";

/////////////////////////////////////////////////////////////////////////////////

app.c.init=function(){
	app.m.metadata={"name":"Lingua Esoterica","version":"0.0.2"};
};

app.c.listeners=function(){

$("input#count").click(function(){
	var input=$("#input").val();
	var inspiration=$("input[type=text]#inspiration").val();
	var count=$("input[name=count]:checked").val();
	var division=$("input[name=division]:checked").val();
	if (parseInt(division)==1){
		division=true;
	}else{
		division=false;
	}
	//console.log(division);
	if (input.length>1000){input.length=1000;}
	input=app.c.ziph(input,parseInt(count,10),division);

	var sortable=[];
	for (var key in input){sortable.push([key,input[key].count],input[key].translation);}
	sortable.sort(function(a,b){return b[1]-a[1];});

	var s=[];
	for (var i=0;i<sortable.length;i++){
		if (sortable[i]!==undefined){s.push(sortable[i]);}
	}
	sortable=s;

	app.m.lexicon=app.c.translate(input,app.c.phonemify(inspiration));
	app.v.glossary(sortable);

});

};

app.c.ziph=function(sample,n,spaces){
	var spaces=spaces||false;
	var n=n||1;
	var lex={};
	var sample=sample.toLowerCase();
	if (spaces==true){
		sample=sample.split(" ");
	}
	else{
		sample=sample.split("");
	}

	app.m.sampleLength=sample.length;

	for (var i=0;i<=(sample.length-n);i++){
		//then populate the lexicon
			var compilation=[];
			for (var j=0;j<n;j++){
				compilation.push(sample[i+j])
			}
			if (spaces==true){
				compilation=compilation.join(" ");
			}
			else{
				compilation=compilation.join("");
			}

		if (!lex[compilation]){
			lex[compilation]={};
			lex[compilation].count=1;
		}
		else{
			lex[compilation].count++;
		}
	}
	return lex;
};

app.c.translate=function(lexicon,phonemes){
	var s=[];

	console.log("lexicon");

	var i=0;
	for (var key in lexicon){i++;}
	console.log(i);

	var ps=[];
	while (ps.length-1){
			nt+=davis.pick(phonemes);
		}

		ps.push(nt);
		console.log(nt);
		ps=_.uniq(ps);
	};

	var i=0;
	for (var key in lexicon){
		var t=ps[i];
		s.push({source:key,count:lexicon[key],translation:t});
		i++;
	};

	return s;
};

app.c.phonemify = function (inspiration) {
	var soft = [
		'c', 'f', 'h', 'l', 'm', 'n', 'r', 's', 'v', 'w', 'z', 'y'
	];
	var hard = [
		'b', 'c', 'd', 'g', 'j', 'k', 'p', 'q', 't', 'x', 'y'
	];
	var vowels = [
		'a', 'e', 'i', 'o', 'u', 'y'
	];
	var default_ret = [
		'sa','so','si','da','do','di'
	];

	var v = inspiration.match(new RegExp('(['+ vowels.join('|') + ']+)', 'gi')) || [];

	var psoft = inspiration.match(new RegExp('([' + soft.join('|') + "]+["+ vowels.join('|') + ']+)', 'gi')) || [];
	var phard = inspiration.match(new RegExp('([' + hard.join('|') + "]+["+ vowels.join('|') + ']+)', 'gi')) || [];
	var softp = inspiration.match(new RegExp('([' + vowels.join('|') + "]+["+ soft.join('|') + ']+)', 'gi')) || [];
	var hardp = inspiration.match(new RegExp('([' + vowels.join('|') + "]+["+ hard.join('|') + ']+)', 'gi')) || [];
	var softsoft = inspiration.match(new RegExp('([' + soft.join('|') + ']+[' + vowels.join('|') + "]+["+ soft.join('|') + ']+)', 'gi')) || [];
	var softhard = inspiration.match(new RegExp('([' + soft.join('|') + ']+[' + vowels.join('|') + "]+["+ hard.join('|') + ']+)', 'gi')) || [];
	var hardsoft = inspiration.match(new RegExp('([' + hard.join('|') + ']+[' + vowels.join('|') + "]+["+ soft.join('|') + ']+)', 'gi')) || [];
	var hardhard = inspiration.match(new RegExp('([' + hard.join('|') + ']+[' + vowels.join('|') + "]+["+ hard.join('|') + ']+)', 'gi')) || [];

	var ret = _.uniq([].concat(v,psoft,phard,softp, hardp, softsoft, softhard, hardsoft, hardhard));

	if (ret.length < 1) {
		ret= default_ret;
	}

	ret=_.sortBy(ret,function(n){return n.length});
	console.log(ret);
	return ret;
};

app.c.phonemify_0 = function (inspiration) {
	var soft = [
		'c', 'f', 'h', 'l', 'm', 'n', 'r', 's', 'v', 'w', 'z', 'y'
	];
	var hard = [
		'b', 'c', 'd', 'g', 'j', 'k', 'p', 'q', 't', 'x', 'y'
	];
	var vowels = [
		'a', 'e', 'i', 'o', 'u', 'y'
	];
	var softp = inspiration.match(new RegExp('([' + vowels.join('|') + "]+["+ soft.join('|') + ']+)', 'gi')) || [];
	var hardp = inspiration.match(new RegExp('([' + vowels.join('|') + "]+["+ hard.join('|') + ']+)', 'gi')) || [];
	var softsoft = inspiration.match(new RegExp('([' + soft.join('|') + ']+[' + vowels.join('|') + "]+["+ soft.join('|') + ']+)', 'gi')) || [];
	var softhard = inspiration.match(new RegExp('([' + soft.join('|') + ']+[' + vowels.join('|') + "]+["+ hard.join('|') + ']+)', 'gi')) || [];
	var hardsoft = inspiration.match(new RegExp('([' + hard.join('|') + ']+[' + vowels.join('|') + "]+["+ soft.join('|') + ']+)', 'gi')) || [];
	var hardhard = inspiration.match(new RegExp('([' + hard.join('|') + ']+[' + vowels.join('|') + "]+["+ hard.join('|') + ']+)', 'gi')) || [];
	var default_ret = [
		'sa','so','si','da','do','di'
	];

	var ret = _.uniq([].concat(softp, hardp, softsoft, softhard, hardsoft, hardhard));

	if (ret.length < 1) {
		return default_ret;
	}

	return ret || default_ret;
};

///////////////////////////////////////////

app.v.init=function(){
	app.v.style();
	app.v.LAYOUT();
};

app.v.LAYOUT=function(){
var d="";
	d+="
";
		d+="
"+app.m.metadata.name+"
";
		d+=app.v.exposition();
		d+="
";
		d+="<input type='radio' value='1' name='count' checked>count by singletons
";
		d+="<input type='radio' value='2' name='count'>count by doubles
";
		d+="<input type='radio' value='3' name='count'>count by triples
";
		d+="<input type='radio' value='4' name='count'>count by quadruples
";
		d+="
";
		d+="<input type='radio' value='1' name='division' checked>count by words
";
		d+="<input type='radio' value='0' name='division'>count by characters
";
		d+="
";
		d+="
inspirational seed
";
		d+="
";
			d+="<input type='text' id='inspiration'></input>";
		d+="
";
		d+="
text to translate
";
		d+="<textarea rows='10' cols='5' id='input' autofocus></textarea>";
		d+="<input type='button' value='translate' id='count'></input>";
	d+="
";
	d+="
";
	d+="
";
	$("body").html(d);
};

app.v.exposition=function(){
	var d="
";
	d+="a quick way to create a fantasy language: ";
	d+="just give esoterica a little inspiration, and some text to translate, ";
	d+="and you'll get a quick english to fantasy-language dictionary.";
	d+="
";
	return d;
};

app.v.glossary=function(sortable){
	var lex=app.m.lexicon;
	var d="";
	d+="
Translating Dictionary
";
	d+="
";
	//d+="
sample length: "+app.m.sampleLength+"
";
	d+="
source	translation
";
	for (var i=0;i<lex.length;i++){
		var rowClass="odd";
		if (i%2==0){rowClass="even";}
		d+="
"+lex[i].source+"	"+lex[i].translation+"
";
	}
	d+="
";
	$("#output").html(d);
};

//////////////////////////////////////////
//////////////////////////////////////////

app.v.style=function(){
	davis.style("body",{
		"width":"100%",
		"margin":"0px",
		"padding":"0px",
		"color":"#555",
		"font-size":"1em",
		"font-family":"sans-serif"
	});
	davis.style("div",{
		"padding":"0",
		"font-size":"1.5em",
		"margin":"30px"
	});
	davis.style("h1",{
		"text-align":"left",
		"font-size":"2em",
		"margin-bottom":"30px",
		"color":app.m.colors.primary
	});
	davis.style("input[type=button]",{
		"width":"100%",
		"font-size":"2em",
		"background":app.m.colors.primary,
		"border":"2px solid "+app.m.colors.grey,
		"cursor":"pointer",
		"color":"#fff"
	});
	davis.style("textarea",{
		"width":"100%",
		"font-size":"0.8em",
		"font-family":"arial sans-serif",
		"border":"1px solid "+app.m.colors.grey,
		"margin":"0",
		"margin-top":"10px"
	});
	davis.style("table",{
		"width":"100%"
	});
	davis.style("table#layout",{
		"height":"100%",
		"table-layout":"fixed"
	});
	davis.style("td",{
		"padding":"30px",
		"margin":"0px",
		"vertical-align":"top",
		"text-align":"left"
	});
	davis.style("div#output",{
		"text-align":"left",
		"padding":"0"
	});
	davis.style("div#output td",{
		"background":app.m.colors.primary,
		"color":"#fff",
		"padding":"3px",
		"margin":"0",
	});
	davis.style("tr.odd td",{
		"background":app.m.colors.secondary
	});
	davis.style("td#output td:hover",{
		"background":"#555"
	});
	davis.style("div.wrapper",{
		"padding":"0",
		"margin":"0",
		"border":"0"
	});
	davis.style("div#options",{
		"display":"none"
	});
	davis.style("p#exposition",{
		"font-size":"0.8em"
	});
	davis.style("input[type=text]",{
		"width":"100%"
	});
	davis.style("th",{
		"background":"transparent",
		"border":"0",
		"font-size":"2em",
		"text-align":"center"
	});
};<|endoftext|>


<commit_before>'use strict';
define(
    [
        'app/config',
        'three',
        'stats',
        'app/controls',
        'app/inputHandler',
        'app/classes/GameObjectManager',
        'app/classes/Planet',
        'app/classes/Star',
        'app/classes/SpaceShip',
        'app/classes/Grid'
    ],
    function(config, THREE, Stats, controls, inputHandler, GameObjectManager, Planet, Star, SpaceShip, Grid) {
        let stats = new Stats();
        stats.showPanel(0);
        document.body.appendChild(stats.dom);

        let scene = new THREE.Scene();

        let renderer = new THREE.WebGLRenderer({ antialias: true });
        renderer.setSize(config.canvasWidth, config.canvasHeight);
        document.getElementById('game').appendChild( renderer.domElement );

        let camera = new THREE.PerspectiveCamera(config.camera.fov, config.canvasWidth / config.canvasHeight, 0.1, 1000);
        camera.rotation.x = 0.75;
        camera.position.y = -40;
        camera.position.z = 50;

        let ambientLight = new THREE.AmbientLight( 0x101010 ); // soft white light
        scene.add( ambientLight );

        // Create plane that is being displayed at origin and moves with the camera
        let cameraPlaneWidth  = 20;
        let cameraPlaneHeight = 20;

        // scene, name, camera, position, width, height
        GameObjectManager.add([
            new Grid(scene, 'grid', new THREE.Vector3(0, 0, 0), 40, 40, 10, camera),

            new Planet(scene, 'home',   1234,   100, new THREE.Vector3(-10, 5, 0), true, 0x33ff33),
            new Planet(scene, 'second', 6000,   50,  new THREE.Vector3(  7, 3, 0), true, 0xff3333),

            new Star(scene, 'sol', 400000, 300, new THREE.Vector3(0, 0, 0), 0xffff00),

            new SpaceShip(scene, 'player', 40.0, new THREE.Vector3(0, 5, 0))
        ]);

        GameObjectManager.get('home').velocity.setX(.01);
        GameObjectManager.get('home').velocity.setY(.02);

        GameObjectManager.get('second').velocity.setX(.01);
        GameObjectManager.get('second').velocity.setY(-.02);

        GameObjectManager.get('player').velocity.setX(.03);

        let lastFrameTime = 0;

        function update(currentFrameTime) {
            stats.begin();

            let deltaT = currentFrameTime - lastFrameTime;
            lastFrameTime = currentFrameTime;

            // Ugly hack to prevent "jumps" when the tab lost focus
            if(deltaT > 32) deltaT = 1000/60;

            // Handle user input
            inputHandler.checkInput(camera);

            // Update all the objects' positions
            GameObjectManager.updatePositions(deltaT);

            // Update all the objects
            GameObjectManager.update(deltaT);

            // Render the scene
            renderer.render(scene, camera);

            stats.end();
            requestAnimationFrame(update);
        }

        requestAnimationFrame(update);
    }
);<commit_msg>Reduced number of grid segments<commit_after>'use strict';
define(
    [
        'app/config',
        'three',
        'stats',
        'app/controls',
        'app/inputHandler',
        'app/classes/GameObjectManager',
        'app/classes/Planet',
        'app/classes/Star',
        'app/classes/SpaceShip',
        'app/classes/Grid'
    ],
    function(config, THREE, Stats, controls, inputHandler, GameObjectManager, Planet, Star, SpaceShip, Grid) {
        let stats = new Stats();
        stats.showPanel(0);
        document.body.appendChild(stats.dom);

        let scene = new THREE.Scene();

        let renderer = new THREE.WebGLRenderer({ antialias: true });
        renderer.setSize(config.canvasWidth, config.canvasHeight);
        document.getElementById('game').appendChild( renderer.domElement );

        let camera = new THREE.PerspectiveCamera(config.camera.fov, config.canvasWidth / config.canvasHeight, 0.1, 1000);
        camera.rotation.x = 0.75;
        camera.position.y = -40;
        camera.position.z = 50;

        let ambientLight = new THREE.AmbientLight( 0x101010 ); // soft white light
        scene.add( ambientLight );

        // Create plane that is being displayed at origin and moves with the camera
        let cameraPlaneWidth  = 20;
        let cameraPlaneHeight = 20;

        // scene, name, camera, position, width, height
        GameObjectManager.add([
            new Grid(scene, 'grid', new THREE.Vector3(0, 0, 0), 40, 40, 6, camera),

            new Planet(scene, 'home',   1234,   100, new THREE.Vector3(-10, 5, 0), true, 0x33ff33),
            new Planet(scene, 'second', 6000,   50,  new THREE.Vector3(  7, 3, 0), true, 0xff3333),

            new Star(scene, 'sol', 400000, 300, new THREE.Vector3(0, 0, 0), 0xffff00),

            new SpaceShip(scene, 'player', 40.0, new THREE.Vector3(0, 5, 0))
        ]);

        GameObjectManager.get('home').velocity.setX(.01);
        GameObjectManager.get('home').velocity.setY(.02);

        GameObjectManager.get('second').velocity.setX(.01);
        GameObjectManager.get('second').velocity.setY(-.02);

        GameObjectManager.get('player').velocity.setX(.03);

        let lastFrameTime = 0;

        function update(currentFrameTime) {
            stats.begin();

            let deltaT = currentFrameTime - lastFrameTime;
            lastFrameTime = currentFrameTime;

            // Ugly hack to prevent "jumps" when the tab lost focus
            if(deltaT > 32) deltaT = 1000/60;

            // Handle user input
            inputHandler.checkInput(camera);

            // Update all the objects' positions
            GameObjectManager.updatePositions(deltaT);

            // Update all the objects
            GameObjectManager.update(deltaT);

            // Render the scene
            renderer.render(scene, camera);

            stats.end();
            requestAnimationFrame(update);
        }

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