<commit_before>/**
 * mechanics.js
 * http://github.com/abhiagarwal/phys.js
 *
 * Copyright 2013 Abhi Agarwal
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
var constant = require('./constants/constants'),
    units = require('./constants/units'),
    multiplier = require('./constants/multiplier'),
    basic = require('./basic'),
    mechanics = exports;
/*
* Momentum
@param {Number} Mass (m)
@param {Number} Velocity (v)
@return {Number} Momentum = Mass * Velocity
*/

mechanics.momentum = function (m, v, callback) {
    var ans = m * v;
    if (typeof (callback) === 'function') {
        callback(ans);
        return (ans);
    }
    return (ans);
};

/*
* Force
@param {Number} Mass (m)
@return {Number} Force = Mass * Acceleration
*/

mechanics.force = function (m, callback) {
    var ans = (m * constant.gAcceleration);
    if (typeof (callback) === 'function') {
        callback(ans);
        return (ans);
    }
    return (ans);
};

/*
* Calculated Force (Own Acceleration Input)
@param {Number} Mass (m)
@param {Number} Acceleration (g)
@return {Number} Force = Mass * Acceleration
*/

mechanics.cForce = function (m, g, callback) {
    var ans = (m * g);
    if (typeof (callback) === 'function') {
        callback(ans);
        return (ans);
    }
    return (ans);
};

/*
* Force (Momentum over Time)
@param {Number} Change in Momentum (p1, p2)
@param {Number} Change in Time (t1, t2)
@return {Number} Force = Change in Momentum / Change in Time
*/

mechanics.forceMomentum = function (p1, p2, t1, t2, callback) {
    var ans = ((basic.changein(p1, p2)) / (basic.changein(t1, t2)));
    if (typeof (callback) === 'function') {
        callback(ans);
        return (ans);
    }
    return (ans);
};

/*
* Calculated Force (Momentum over Time)
@param {Number} Change in Momentum (m1, v1, m2, v2)
@param {Number} Change in Time (t1, t2)
@return {Number} Force = ((m2 * v2) - (m1 * v1)) / (t2 - t1)
*/

mechanics.cForceMomentum = function (m1, v1, m2, v2, t1, t2, callback) {
    var ans = ((basic.changein((mechanics.momentum(m1, v1)), mechanics.momentum(m2, v2))) / (basic.changein(t1, t2)));
    if (typeof (callback) === 'function') {
        callback(ans);
        return (ans);
    }
    return (ans);
};

/*
* SUVAT Displacement (Using u, t, a)
@param {Number} Initial Velocity (u)
@param {Number} Time (t)
@param {Number} Acceleration (a)
@return {Number} s = u * t + 1/2 * a * t^2
*/

mechanics.SUVATuta = function (u, t, a, callback) {
    var ans = ((u * t) + ((1 / 2) * a * (Math.pow(t, 2))));
    if (typeof (callback) === 'function') {
        callback(ans);
        return (ans);
    }
    return (ans);
};

/*
* SUVAT Displacement (using u, v, t)
@param {Number} Initial Velocity (u)
@param {Number} Final Velocity (v)
@param {Number} Time (t)
@return {Number}  s = 1 / 2 * (u + v) * t
*/

mechanics.SUVATuvt = function (u, v, t, callback) {
    var ans = ((1 / 2) * ((u + v) * t));
    if (typeof (callback) === 'function') {
        callback(ans);
        return (ans);
    }
    return (ans);
};

/*
* SUVAT Displacement (using a, v, t)
@param {Number} Acceleration (a)
@param {Number} Final Velocity (v)
@param {Number} Time (t)
@return {Number}  s = v * t - 1/2 * a * t^2
*/

mechanics.SUVATvta = function (v, t, a, callback) {
    var ans = ((v * t) - ((1 / 2) * a * (Math.pow(t, 2))));
    if (typeof (callback) === 'function') {
        callback(ans);
        return (ans);
    }
    return (ans);
};

/*
* SUVAT Displacement (using u, a, t)
@param {Number} Initial Velocity (u)
@param {Number} Acceleration (a)
@param {Number} Time (t)
@return {Number}  v = u + a * t
*/

mechanics.SUVATuat = function (u, a, t, callback) {
    var ans = (u + (a * t));
    if (typeof (callback) === 'function') {
        callback(ans);
        return (ans);
    }
    return (ans);
};

/*
* SUVAT Displacement (using u, a, s)
@param {Number} Initial Velocity (u)
@param {Number} Acceleration (a)
@param {Number} Dispalcement (s)
@return {Number}  v^2 = u^2 + 2 * a * s (Returns v^2 not v)
*/

mechanics.SUVATuas = function (u, a, s, callback) {
    var ans = (Math.pow(u, 2) + (2 * a * s));
    if (typeof (callback) === 'function') {
        callback(ans);
        return (ans);
    }
    return (ans);
};

/*
* Calculated SUVAT Displacement (using u, a, s)
@param {Number} Initial Velocity (u)
@param {Number} Acceleration (a)
@param {Number} Dispalcement (s)
@return {Number}  v = SquareRoot(u^2 + 2 * a * s) (Returns v)
*/

mechanics.cSUVATuas = function (u, a, s, callback) {
    var ans = Math.sqrt(mechanics.SUVATuas(u, a, s));
    if (typeof (callback) === 'function') {
        callback(ans);
        return (ans);
    }
    return (ans);
};

/*
* Impulse w/ Mass & Velocity
@param {Number} Mass (m)
@param {Number} Initial Velocity (v1)
@param {Number} Finaly Velocity (v2)
@return {Number} Impulse = Mass * Change in Velocity
*/

mechanics.impulseMass = function (m, v1, v2, callback) {
    var ans = (m * (basic.changein(v1, v2)));
    if (typeof (callback) === 'function') {
        callback(ans);
        return (ans);
    }
    return (ans);
};

/*
* Impulse w/ Force & Times
@param {Number} Force (f)
@param {Number} Initial Time (t1)
@param {Number} Final Time (t2)
@return {Number} Impulse = Force * Change im time
*/

mechanics.impulseForce = function (f, t1, t2, callback) {
    var ans = (f * (basic.changein(t1, t2)));
    if (typeof (callback) === 'function') {
        callback(ans);
        return (ans);
    }
    return (ans);
};

/*
* Work
@param {Number} Force (f)
@param {Number} Displacement (s)
@param {Number} Cos(Thetha) (angle - Cosine of an angle theta)
@return {Number} Work = Force * Distance * Cos(Thetha)
*/

mechanics.workDone = function (f, s, angle, callback) {
    var ans = (f * s * Math.cos(angle));
    if (typeof (callback) === 'function') {
        callback(ans);
        return (ans);
    }
    return (ans);
};

/*
* Kinetic Energy w/ Velocity
@param {Number} Velocity (v)
@param {Number} Mass (m)
@return {Number} Kinetic Energy = 1/2 * m * v^2
*/

mechanics.kineticVelocity = function (v, m, callback) {
    var ans = ((1 / 2) * (m) * (Math.pow(v, 2)));
    if (typeof (callback) === 'function') {
        callback(ans);
        return (ans);
    }
    return (ans);
};

/*
* Kinetic Energy w/ Momentum
@param {Number} Momentum (p)
@param {Number} Mass (m)
@return {Number} Kinetic Energy = (p^2) / (2 * m)
*/

mechanics.kineticMomentum = function (p, m, callback) {
    var ans = ((Math.pow(p, 2)) / (2 * m));
    if (typeof (callback) === 'function') {
        callback(ans);
        return (ans);
    }
    return (ans);
};

/*
* Calculated Kinetic Energy Momentum
@param {Number} Velocity (v)
@param {Number} Mass (m)
@return {Number} Kinetic Energy = ((m * v)^2) / (2 * m)
*/

mechanics.cKineticMomentum = function (v, m, callback) {
    var ans = ((Math.pow((mechanics.momentum(m, v)), 2)) / (2 * m));
    if (typeof (callback) === 'function') {
        callback(ans);
        return (ans);
    }
    return (ans);
};

/*
* Potential Energy
@param {Number} Mass (m)
@param {Number} Initial Height (h1)
@param {Number} Final Height (h2)
@return {Number} Potential Energy = Mass * Gravitational Field Strength * Change in Height
*/

mechanics.potential = function (m, h1, h2, callback) {
    var ans = ((m) * (constant.gAcceleration) * (basic.changein(h1, h2)));
    if (typeof (callback) === 'function') {
        callback(ans);
        return (ans);
    }
    return (ans);
};

/*
* Calculated Potential Energy (Entering own g)
@param {Number} Mass (m)
@param {Number} Gravitational Field Strength (g)
@param {Number} Initial Height (h1)
@param {Number} Final Height (h2)
@return {Number} Potential Energy = Mass * Gravitational Field Strength * Change in Height
*/

mechanics.cPotential = function (m, g, h1, h2, callback) {
    var ans = ((m) * (g) * (basic.changein(h1, h2)));
    if (typeof (callback) === 'function') {
        callback(ans);
        return (ans);
    }
    return (ans);
};

/*
* Power
@param {Number} Force (f)
@param {Number} Velocity (v)
@return {Number} Power = Force * Velocity
*/

mechanics.power = function (f, v, callback) {
    var ans = (f * v);
    if (typeof (callback) === 'function') {
        callback(ans);
        return (ans);
    }
    return (ans);
};

/*
* Centripetal Acceleration w/ Velocity
@param {Number} Velocity (v)
@param {Number} r (radius)
@return {Number} Acceleration = Velocity^2 / Radius
*/

mechanics.centripetalVelocity = function (v, r, callback) {
    var ans = ((Math.pow(v, 2)) / (r));
    if (typeof (callback) === 'function') {
        callback(ans);
        return (ans);
    }
    return (ans);
};

/*
* Centripetal Acceleration w/ Velocity (Entering v^2)
@param {Number} Velocity (v)
@param {Number} r (radius)
@return {Number} Acceleration = Velocity^2 / Radius
*/

mechanics.cCentripetalVelocity = function (v, r, callback) {
    var ans = (v / r);
    if (typeof (callback) === 'function') {
        callback(ans);
        return (ans);
    }
    return (ans);
};

/*
* Centripetal Acceleration w/ Time
@param {Number} Radius (r)
@param {Number} Time (t)
@return {Number} Acceleration = 4 * Pi^2 * r / (t^2)
*/

mechanics.centripetalTime = function (r, t, callback) {
    var ans = ((4 * (Math.pow(Math.PI, 2)) * r) / (Math.pow(t, 2)));
    if (typeof (callback) === 'function') {
        callback(ans);
        return (ans);
    }
    return (ans);
};

/*
* Calculated Centripetal Acceleration w/ Time (Self calculating t^2)
@param {Number} Radius (r)
@param {Number} Time (t)
@return {Number} Acceleration = 4 * Pi^2 * r / (t^2)
*/

mechanics.cCentripetalTime = function (r, t, callback) {
    var ans = ((4 * (Math.pow(Math.PI, 2)) * r) / (t));
    if (typeof (callback) === 'function') {
        callback(ans);
        return (ans);
    }
    return (ans);
};<commit_msg>Correcting Syntax<commit_after>/**
 * mechanics.js
 * http://github.com/abhiagarwal/phys.js
 *
 * Copyright 2013 Abhi Agarwal
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
var constant = require('./constants/constants'),
  units = require('./constants/units'),
  multiplier = require('./constants/multiplier'),
  basic = require('./basic'),
  mechanics = exports;
/*
* Momentum
@param {Number} Mass (m)
@param {Number} Velocity (v)
@return {Number} Momentum = Mass * Velocity
*/

mechanics.momentum = function (m, v, callback) {
  var ans = m * v;
  if (typeof (callback) === 'function') {
    callback(ans);
    return (ans);
  }
  return (ans);
};

/*
* Force
@param {Number} Mass (m)
@return {Number} Force = Mass * Acceleration
*/

mechanics.force = function (m, callback) {
  var ans = (m * constant.gAcceleration);
  if (typeof (callback) === 'function') {
    callback(ans);
    return (ans);
  }
  return (ans);
};

/*
* Calculated Force (Own Acceleration Input)
@param {Number} Mass (m)
@param {Number} Acceleration (g)
@return {Number} Force = Mass * Acceleration
*/

mechanics.cForce = function (m, g, callback) {
  var ans = (m * g);
  if (typeof (callback) === 'function') {
    callback(ans);
    return (ans);
  }
  return (ans);
};

/*
* Force (Momentum over Time)
@param {Number} Change in Momentum (p1, p2)
@param {Number} Change in Time (t1, t2)
@return {Number} Force = Change in Momentum / Change in Time
*/

mechanics.forceMomentum = function (p1, p2, t1, t2, callback) {
  var ans = ((basic.changein(p1, p2)) / (basic.changein(t1, t2)));
  if (typeof (callback) === 'function') {
    callback(ans);
    return (ans);
  }
  return (ans);
};

/*
* Calculated Force (Momentum over Time)
@param {Number} Change in Momentum (m1, v1, m2, v2)
@param {Number} Change in Time (t1, t2)
@return {Number} Force = ((m2 * v2) - (m1 * v1)) / (t2 - t1)
*/

mechanics.cForceMomentum = function (m1, v1, m2, v2, t1, t2, callback) {
  var ans = ((basic.changein((mechanics.momentum(m1, v1)),
    mechanics.momentum(m2, v2))) / (basic.changein(t1, t2)));
  if (typeof (callback) === 'function') {
    callback(ans);
    return (ans);
  }
  return (ans);
};

/*
* SUVAT Displacement (Using u, t, a)
@param {Number} Initial Velocity (u)
@param {Number} Time (t)
@param {Number} Acceleration (a)
@return {Number} s = u * t + 1/2 * a * t^2
*/

mechanics.SUVATuta = function (u, t, a, callback) {
  var ans = ((u * t) + ((1 / 2) * a * (Math.pow(t, 2))));
  if (typeof (callback) === 'function') {
    callback(ans);
    return (ans);
  }
  return (ans);
};

/*
* SUVAT Displacement (using u, v, t)
@param {Number} Initial Velocity (u)
@param {Number} Final Velocity (v)
@param {Number} Time (t)
@return {Number}  s = 1 / 2 * (u + v) * t
*/

mechanics.SUVATuvt = function (u, v, t, callback) {
  var ans = ((1 / 2) * ((u + v) * t));
  if (typeof (callback) === 'function') {
    callback(ans);
    return (ans);
  }
  return (ans);
};

/*
* SUVAT Displacement (using a, v, t)
@param {Number} Acceleration (a)
@param {Number} Final Velocity (v)
@param {Number} Time (t)
@return {Number}  s = v * t - 1/2 * a * t^2
*/

mechanics.SUVATvta = function (v, t, a, callback) {
  var ans = ((v * t) - ((1 / 2) * a * (Math.pow(t, 2))));
  if (typeof (callback) === 'function') {
    callback(ans);
    return (ans);
  }
  return (ans);
};

/*
* SUVAT Displacement (using u, a, t)
@param {Number} Initial Velocity (u)
@param {Number} Acceleration (a)
@param {Number} Time (t)
@return {Number}  v = u + a * t
*/

mechanics.SUVATuat = function (u, a, t, callback) {
  var ans = (u + (a * t));
  if (typeof (callback) === 'function') {
    callback(ans);
    return (ans);
  }
  return (ans);
};

/*
* SUVAT Displacement (using u, a, s)
@param {Number} Initial Velocity (u)
@param {Number} Acceleration (a)
@param {Number} Dispalcement (s)
@return {Number}  v^2 = u^2 + 2 * a * s (Returns v^2 not v)
*/

mechanics.SUVATuas = function (u, a, s, callback) {
  var ans = (Math.pow(u, 2) + (2 * a * s));
  if (typeof (callback) === 'function') {
    callback(ans);
    return (ans);
  }
  return (ans);
};

/*
* Calculated SUVAT Displacement (using u, a, s)
@param {Number} Initial Velocity (u)
@param {Number} Acceleration (a)
@param {Number} Dispalcement (s)
@return {Number}  v = SquareRoot(u^2 + 2 * a * s) (Returns v)
*/

mechanics.cSUVATuas = function (u, a, s, callback) {
  var ans = Math.sqrt(mechanics.SUVATuas(u, a, s));
  if (typeof (callback) === 'function') {
    callback(ans);
    return (ans);
  }
  return (ans);
};

/*
* Impulse w/ Mass & Velocity
@param {Number} Mass (m)
@param {Number} Initial Velocity (v1)
@param {Number} Finaly Velocity (v2)
@return {Number} Impulse = Mass * Change in Velocity
*/

mechanics.impulseMass = function (m, v1, v2, callback) {
  var ans = (m * (basic.changein(v1, v2)));
  if (typeof (callback) === 'function') {
    callback(ans);
    return (ans);
  }
  return (ans);
};

/*
* Impulse w/ Force & Times
@param {Number} Force (f)
@param {Number} Initial Time (t1)
@param {Number} Final Time (t2)
@return {Number} Impulse = Force * Change im time
*/

mechanics.impulseForce = function (f, t1, t2, callback) {
  var ans = (f * (basic.changein(t1, t2)));
  if (typeof (callback) === 'function') {
    callback(ans);
    return (ans);
  }
  return (ans);
};

/*
* Work
@param {Number} Force (f)
@param {Number} Displacement (s)
@param {Number} Cos(Thetha) (angle - Cosine of an angle theta)
@return {Number} Work = Force * Distance * Cos(Thetha)
*/

mechanics.workDone = function (f, s, angle, callback) {
  var ans = (f * s * Math.cos(angle));
  if (typeof (callback) === 'function') {
    callback(ans);
    return (ans);
  }
  return (ans);
};

/*
* Kinetic Energy w/ Velocity
@param {Number} Velocity (v)
@param {Number} Mass (m)
@return {Number} Kinetic Energy = 1/2 * m * v^2
*/

mechanics.kineticVelocity = function (v, m, callback) {
  var ans = ((1 / 2) * (m) * (Math.pow(v, 2)));
  if (typeof (callback) === 'function') {
    callback(ans);
    return (ans);
  }
  return (ans);
};

/*
* Kinetic Energy w/ Momentum
@param {Number} Momentum (p)
@param {Number} Mass (m)
@return {Number} Kinetic Energy = (p^2) / (2 * m)
*/

mechanics.kineticMomentum = function (p, m, callback) {
  var ans = ((Math.pow(p, 2)) / (2 * m));
  if (typeof (callback) === 'function') {
    callback(ans);
    return (ans);
  }
  return (ans);
};

/*
* Calculated Kinetic Energy Momentum
@param {Number} Velocity (v)
@param {Number} Mass (m)
@return {Number} Kinetic Energy = ((m * v)^2) / (2 * m)
*/

mechanics.cKineticMomentum = function (v, m, callback) {
  var ans = ((Math.pow((mechanics.momentum(m, v)), 2)) / (2 * m));
  if (typeof (callback) === 'function') {
    callback(ans);
    return (ans);
  }
  return (ans);
};

/*
* Potential Energy
@param {Number} Mass (m)
@param {Number} Initial Height (h1)
@param {Number} Final Height (h2)
@return {Number} Potential Energy = Mass * Gravitational Field Strength * Change in Height
*/

mechanics.potential = function (m, h1, h2, callback) {
  var ans = ((m) * (constant.gAcceleration) * (basic.changein(h1,
    h2)));
  if (typeof (callback) === 'function') {
    callback(ans);
    return (ans);
  }
  return (ans);
};

/*
* Calculated Potential Energy (Entering own g)
@param {Number} Mass (m)
@param {Number} Gravitational Field Strength (g)
@param {Number} Initial Height (h1)
@param {Number} Final Height (h2)
@return {Number} Potential Energy = Mass * Gravitational Field Strength * Change in Height
*/

mechanics.cPotential = function (m, g, h1, h2, callback) {
  var ans = ((m) * (g) * (basic.changein(h1, h2)));
  if (typeof (callback) === 'function') {
    callback(ans);
    return (ans);
  }
  return (ans);
};

/*
* Power
@param {Number} Force (f)
@param {Number} Velocity (v)
@return {Number} Power = Force * Velocity
*/

mechanics.power = function (f, v, callback) {
  var ans = (f * v);
  if (typeof (callback) === 'function') {
    callback(ans);
    return (ans);
  }
  return (ans);
};

/*
* Centripetal Acceleration w/ Velocity
@param {Number} Velocity (v)
@param {Number} r (radius)
@return {Number} Acceleration = Velocity^2 / Radius
*/

mechanics.centripetalVelocity = function (v, r, callback) {
  var ans = ((Math.pow(v, 2)) / (r));
  if (typeof (callback) === 'function') {
    callback(ans);
    return (ans);
  }
  return (ans);
};

/*
* Centripetal Acceleration w/ Velocity (Entering v^2)
@param {Number} Velocity (v)
@param {Number} r (radius)
@return {Number} Acceleration = Velocity^2 / Radius
*/

mechanics.cCentripetalVelocity = function (v, r, callback) {
  var ans = (v / r);
  if (typeof (callback) === 'function') {
    callback(ans);
    return (ans);
  }
  return (ans);
};

/*
* Centripetal Acceleration w/ Time
@param {Number} Radius (r)
@param {Number} Time (t)
@return {Number} Acceleration = 4 * Pi^2 * r / (t^2)
*/

mechanics.centripetalTime = function (r, t, callback) {
  var ans = ((4 * (Math.pow(Math.PI, 2)) * r) / (Math.pow(t, 2)));
  if (typeof (callback) === 'function') {
    callback(ans);
    return (ans);
  }
  return (ans);
};

/*
* Calculated Centripetal Acceleration w/ Time (Self calculating t^2)
@param {Number} Radius (r)
@param {Number} Time (t)
@return {Number} Acceleration = 4 * Pi^2 * r / (t^2)
*/

mechanics.cCentripetalTime = function (r, t, callback) {
  var ans = ((4 * (Math.pow(Math.PI, 2)) * r) / (t));
  if (typeof (callback) === 'function') {
    callback(ans);
    return (ans);
  }
  return (ans);
};<|endoftext|>


<commit_before>/*
* maskMoney plugin for jQuery
* http://plentz.github.com/jquery-maskmoney/
* version: 2.5.0
* Licensed under the MIT license
*/
;(function($) {
	if (!$.browser) {
		$.browser = {};
		$.browser.mozilla = /mozilla/.test(navigator.userAgent.toLowerCase()) && !/webkit/.test(navigator.userAgent.toLowerCase());
		$.browser.webkit = /webkit/.test(navigator.userAgent.toLowerCase());
		$.browser.opera = /opera/.test(navigator.userAgent.toLowerCase());
		$.browser.msie = /msie/.test(navigator.userAgent.toLowerCase());
	}

	var methods = {
		destroy : function() {
			var input = $(this);
			input.unbind('.maskMoney');

			if ($.browser.msie) {
				this.onpaste = null;
			}
			return this;
		},

		mask : function(value) {
			return this.each(function() {
				var $this = $(this);
				if (typeof(value) == 'number') {
					$this.trigger('mask');
					var decimalSize = $($this.val().split(/\D/)).last()[0].length;
					value = value.toFixed(decimalSize)
					$this.val(value);
				}
				return $this.trigger('mask');
			});
		},

		unmasked : function() {
			return this.map(function() {
				var input = $(this);
				var unmaskedStr = (input.val() || '0');
				var isNegative = unmaskedStr.indexOf("-") != -1;
				var decimalPart = $(unmaskedStr.split(/\D/)).last()[0];
				unmaskedStr = unmaskedStr.replace(/\D/g, '');
				unmaskedStr = unmaskedStr.replace(new RegExp(decimalPart + '$'), '.' + decimalPart);
				if (isNegative) {
					unmaskedStr = "-" + unmaskedStr;
				}
				return parseFloat(unmaskedStr);
			})
		},

		init : function(settings) {
			settings = $.extend({
				symbol: '',
				symbolStay: false,
				thousands: ',',
				decimal: '.',
				precision: 2,
				allowZero: false,
				allowNegative: false
			}, settings);
			if (settings.defaultZero != null && window.console) {
				console.log("settings.defaultZero is deprecated - more info here https://github.com/plentz/jquery-maskmoney/issues/55");
			}
			return this.each(function() {
				var input = $(this);
				var dirty = false;

				function markAsDirty() {
					dirty = true;
				}

				function clearDirt() {
					dirty = false;
				}

				function keypressEvent(e) {
					e = e || window.event;
					var key = e.which || e.charCode || e.keyCode;
					//needed to handle an IE "special" event
					if (key == undefined) {
						return false;
					}
					// any key except the numbers 0-9
					if (key < 48 || key > 57) {
						// -(minus) key
						if (key == 45) {
							markAsDirty();
							input.val(changeSign());
							return false;
						// +(plus) key
						} else if (key == 43) {
							markAsDirty();
							input.val(input.val().replace('-',''));
							return false;
						// enter key or tab key
						} else if (key == 13 || key == 9) {
							if (dirty) {
								clearDirt();
								$(this).change();
							}
							return true;
						} else if ($.browser.mozilla && (key == 37 || key == 39) && e.charCode == 0) {
							// needed for left arrow key or right arrow key with firefox
							// the charCode part is to avoid allowing '%'(e.charCode 0, e.keyCode 37)
							return true;
						} else { // any other key with keycode less than 48 and greater than 57
							preventDefault(e);
							return true;
						}
					} else if (canInputMoreNumbers(input)) {
						return false;
					} else {
						preventDefault(e);

						var keyPressedChar = String.fromCharCode(key);
						var x = input.get(0);
						var selection = getInputSelection(x);
						var startPos = selection.start;
						var endPos = selection.end;
						x.value = x.value.substring(0, startPos) + keyPressedChar + x.value.substring(endPos, x.value.length);
						maskAndPosition(x, startPos + 1);
						markAsDirty();
						return false;
					}
				}

				function canInputMoreNumbers(element) {
					var reachedMaxLength = (element.val().length >= element.attr('maxlength') && element.attr('maxlength') >= 0);
					var selection = getInputSelection(element.get(0));
					var start = selection.start;
					var end = selection.end;
					var hasNumberSelected = (selection.start != selection.end && element.val().substring(start,end).match(/\d/))? true : false;
					return reachedMaxLength && !hasNumberSelected;
				}

				function keydownEvent(e) {
					e = e || window.event;
					var key = e.which || e.charCode || e.keyCode;
					//needed to handle an IE "special" event
					if (key == undefined) {
						return false;
					}

					var x = input.get(0);
					var selection = getInputSelection(x);
					var startPos = selection.start;
					var endPos = selection.end;

					if (key == 8) { // backspace key
						preventDefault(e);

						if (startPos == endPos) {
							// Remove single character
							x.value = x.value.substring(0, startPos - 1) + x.value.substring(endPos, x.value.length);
							startPos = startPos - 1;
						} else {
							// Remove multiple characters
							x.value = x.value.substring(0, startPos) + x.value.substring(endPos, x.value.length);
						}
						maskAndPosition(x, startPos);
						markAsDirty();
						return false;
					} else if (key == 9) { // tab key
						if (dirty) {
							$(this).change();
							clearDirt();
						}
						return true;
					} else if (key == 46 || key == 63272) { // delete key (with special case for safari)
						preventDefault(e);
						if (x.selectionStart == x.selectionEnd) {
							// Remove single character
							x.value = x.value.substring(0, startPos) + x.value.substring(endPos + 1, x.value.length);
						} else {
							//Remove multiple characters
							x.value = x.value.substring(0, startPos) + x.value.substring(endPos, x.value.length);
						}
						maskAndPosition(x, startPos);
						markAsDirty();
						return false;
					} else { // any other key
						return true;
					}
				}

				function focusEvent(e) {
					mask();
					if (this.createTextRange) {
						var textRange = this.createTextRange();
						textRange.collapse(false); // set the cursor at the end of the input
						textRange.select();
					}
				}

				function blurEvent(e) {
					if ($.browser.msie) {
						keypressEvent(e);
					}

					if (input.val() == '' || input.val() == setSymbol(getDefaultMask()) || input.val() == settings.symbol) {
						if (!settings.allowZero) {
							input.val('');
						} else if (!settings.symbolStay) {
							input.val(getDefaultMask());
						} else {
							input.val(setSymbol(getDefaultMask()));
						}
					} else {
						if (!settings.symbolStay) {
							input.val(input.val().replace(settings.symbol,''));
						} else if (settings.symbolStay && input.val() == settings.symbol) {
							input.val(setSymbol(getDefaultMask()));
						}
					}
				}

				function preventDefault(e) {
					if (e.preventDefault) { //standard browsers
						e.preventDefault();
					} else { // old internet explorer
						e.returnValue = false;
					}
				}

				function maskAndPosition(x, startPos) {
					var originalLen = input.val().length;
					input.val(maskValue(x.value));
					var newLen = input.val().length;
					startPos = startPos - (originalLen - newLen);
					setCursorPosition(startPos);
				}

				function mask() {
					var value = input.val();
					input.val(maskValue(value));
				}

				function maskValue(value) {
					value = value.replace(settings.symbol, '');

					var strCheck = '0123456789';
					var len = value.length;
					var a = '', t = '';
					var negative = '';

					if (len != 0 && value.charAt(0)=='-') {
						value = value.replace('-','');
						if (settings.allowNegative) {
							negative = '-';
						}
					}

					if (len == 0) {
						t = '0.00';
					}

					for (var i = 0; i < len; i++) {
						if (value.charAt(i) != '0' && value.charAt(i) != settings.decimal) {
							break;
						}
					}

					for (; i < len; i++) {
						if (strCheck.indexOf(value.charAt(i)) != -1) {
							a += value.charAt(i);
						}
					}
					var n = parseFloat(a);

					n = isNaN(n) ? 0 : n / Math.pow(10, settings.precision);
					t = n.toFixed(settings.precision);

					i = settings.precision == 0 ? 0 : 1;
					var p, d = (t = t.split('.'))[i].substr(0, settings.precision);
					for (p = (t = t[0]).length; (p -= 3) >= 1;) {
						t = t.substr(0, p) + settings.thousands + t.substr(p);
					}

					return (settings.precision > 0)
						? setSymbol(negative + t + settings.decimal + d + Array((settings.precision + 1) - d.length).join(0))
						: setSymbol(negative + t);
				}

				function getDefaultMask() {
					var n = parseFloat('0') / Math.pow(10, settings.precision);
					return (n.toFixed(settings.precision)).replace(new RegExp('\\.','g'),settings.decimal);
				}

				function setSymbol(value) {
					if (settings.symbol != '') {
						var operator = '';
						if (value.length != 0 && value.charAt(0) == '-') {
							value = value.replace('-', '');
							operator = '-';
						}

						if (value.substr(0, settings.symbol.length) != settings.symbol) {
							value = operator + settings.symbol + value;
						}
					}
					return value;
				}

				function changeSign() {
					var inputValue = input.val();
					if (settings.allowNegative) {
						if (inputValue != '' && inputValue.charAt(0) == '-') {
							return inputValue.replace('-','');
						} else {
							return '-' + inputValue;
						}
					} else {
						return inputValue;
					}
				}

				function setCursorPosition(pos) {
					input.each(function(index, elem) {
						if (elem.setSelectionRange) {
							elem.focus();
							elem.setSelectionRange(pos, pos);
						} else if (elem.createTextRange) {
							var range = elem.createTextRange();
							range.collapse(true);
							range.moveEnd('character', pos);
							range.moveStart('character', pos);
							range.select();
						}
					});
					return this;
				};

				function getInputSelection(el) {
					var start = 0, end = 0, normalizedValue, range, textInputRange, len, endRange;

					if (typeof el.selectionStart == "number" && typeof el.selectionEnd == "number") {
						start = el.selectionStart;
						end = el.selectionEnd;
					} else {
						range = document.selection.createRange();

						if (range && range.parentElement() == el) {
							len = el.value.length;
							normalizedValue = el.value.replace(/\r\n/g, "\n");

							// Create a working TextRange that lives only in the input
							textInputRange = el.createTextRange();
							textInputRange.moveToBookmark(range.getBookmark());

							// Check if the start and end of the selection are at the very end
							// of the input, since moveStart/moveEnd doesn't return what we want
							// in those cases
							endRange = el.createTextRange();
							endRange.collapse(false);

							if (textInputRange.compareEndPoints("StartToEnd", endRange) > -1) {
								start = end = len;
							} else {
								start = -textInputRange.moveStart("character", - len);
								start += normalizedValue.slice(0, start).split("\n").length - 1;

								if (textInputRange.compareEndPoints("EndToEnd", endRange) > -1) {
									end = len;
								} else {
									end = -textInputRange.moveEnd("character", - len);
									end += normalizedValue.slice(0, end).split("\n").length - 1;
								}
							}
						}
					}

					return {
						start: start,
						end: end
					};
				} // getInputSelection

				input.unbind('.maskMoney');
				input.bind('keypress.maskMoney', keypressEvent);
				input.bind('keydown.maskMoney', keydownEvent);
				input.bind('blur.maskMoney', blurEvent);
				input.bind('focus.maskMoney', focusEvent);
				input.bind('mask.maskMoney', mask);
			})
		}
	}

	$.fn.maskMoney = function(method) {
		if (methods[method]) {
			return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
		} else if (typeof method === 'object' || ! method) {
			return methods.init.apply(this, arguments);
		} else {
			$.error('Method ' +  method + ' does not exist on jQuery.maskMoney');
		}
	};
})(window.jQuery || window.Zepto);
<commit_msg>code cleanup<commit_after>/*
* maskMoney plugin for jQuery
* http://plentz.github.com/jquery-maskmoney/
* version: 2.5.0
* Licensed under the MIT license
*/
;(function($) {
	if (!$.browser) {
		$.browser = {};
		$.browser.mozilla = /mozilla/.test(navigator.userAgent.toLowerCase()) && !/webkit/.test(navigator.userAgent.toLowerCase());
		$.browser.webkit = /webkit/.test(navigator.userAgent.toLowerCase());
		$.browser.opera = /opera/.test(navigator.userAgent.toLowerCase());
		$.browser.msie = /msie/.test(navigator.userAgent.toLowerCase());
	}

	var methods = {
		destroy : function() {
			$(this).unbind('.maskMoney');

			if ($.browser.msie) {
				this.onpaste = null;
			}
			return this;
		},

		mask : function(value) {
			return this.each(function() {
				var $this = $(this);
				if (typeof(value) == 'number') {
					$this.trigger('mask');
					var decimalSize = $($this.val().split(/\D/)).last()[0].length;
					value = value.toFixed(decimalSize)
					$this.val(value);
				}
				return $this.trigger('mask');
			});
		},

		unmasked : function() {
			return this.map(function() {
				var input = $(this);
				var unmaskedStr = (input.val() || '0');
				var isNegative = unmaskedStr.indexOf("-") != -1;
				var decimalPart = $(unmaskedStr.split(/\D/)).last()[0];
				unmaskedStr = unmaskedStr.replace(/\D/g, '');
				unmaskedStr = unmaskedStr.replace(new RegExp(decimalPart + '$'), '.' + decimalPart);
				if (isNegative) {
					unmaskedStr = "-" + unmaskedStr;
				}
				return parseFloat(unmaskedStr);
			})
		},

		init : function(settings) {
			settings = $.extend({
				symbol: '',
				symbolStay: false,
				thousands: ',',
				decimal: '.',
				precision: 2,
				allowZero: false,
				allowNegative: false
			}, settings);
			if (settings.defaultZero != null && window.console) {
				console.log("settings.defaultZero is deprecated - more info here https://github.com/plentz/jquery-maskmoney/issues/55");
			}
			return this.each(function() {
				var input = $(this);
				var dirty = false;

				function markAsDirty() {
					dirty = true;
				}

				function clearDirt() {
					dirty = false;
				}

				function keypressEvent(e) {
					e = e || window.event;
					var key = e.which || e.charCode || e.keyCode;
					//needed to handle an IE "special" event
					if (key == undefined) {
						return false;
					}
					// any key except the numbers 0-9
					if (key < 48 || key > 57) {
						// -(minus) key
						if (key == 45) {
							markAsDirty();
							input.val(changeSign());
							return false;
						// +(plus) key
						} else if (key == 43) {
							markAsDirty();
							input.val(input.val().replace('-',''));
							return false;
						// enter key or tab key
						} else if (key == 13 || key == 9) {
							if (dirty) {
								clearDirt();
								$(this).change();
							}
							return true;
						} else if ($.browser.mozilla && (key == 37 || key == 39) && e.charCode == 0) {
							// needed for left arrow key or right arrow key with firefox
							// the charCode part is to avoid allowing '%'(e.charCode 0, e.keyCode 37)
							return true;
						} else { // any other key with keycode less than 48 and greater than 57
							preventDefault(e);
							return true;
						}
					} else if (canInputMoreNumbers(input)) {
						return false;
					} else {
						preventDefault(e);

						var keyPressedChar = String.fromCharCode(key);
						var x = input.get(0);
						var selection = getInputSelection(x);
						var startPos = selection.start;
						var endPos = selection.end;
						x.value = x.value.substring(0, startPos) + keyPressedChar + x.value.substring(endPos, x.value.length);
						maskAndPosition(x, startPos + 1);
						markAsDirty();
						return false;
					}
				}

				function canInputMoreNumbers(element) {
					var reachedMaxLength = (element.val().length >= element.attr('maxlength') && element.attr('maxlength') >= 0);
					var selection = getInputSelection(element.get(0));
					var start = selection.start;
					var end = selection.end;
					var hasNumberSelected = (selection.start != selection.end && element.val().substring(start,end).match(/\d/))? true : false;
					return reachedMaxLength && !hasNumberSelected;
				}

				function keydownEvent(e) {
					e = e || window.event;
					var key = e.which || e.charCode || e.keyCode;
					//needed to handle an IE "special" event
					if (key == undefined) {
						return false;
					}

					var x = input.get(0);
					var selection = getInputSelection(x);
					var startPos = selection.start;
					var endPos = selection.end;

					if (key == 8) { // backspace key
						preventDefault(e);

						if (startPos == endPos) {
							// Remove single character
							x.value = x.value.substring(0, startPos - 1) + x.value.substring(endPos, x.value.length);
							startPos = startPos - 1;
						} else {
							// Remove multiple characters
							x.value = x.value.substring(0, startPos) + x.value.substring(endPos, x.value.length);
						}
						maskAndPosition(x, startPos);
						markAsDirty();
						return false;
					} else if (key == 9) { // tab key
						if (dirty) {
							$(this).change();
							clearDirt();
						}
						return true;
					} else if (key == 46 || key == 63272) { // delete key (with special case for safari)
						preventDefault(e);
						if (x.selectionStart == x.selectionEnd) {
							// Remove single character
							x.value = x.value.substring(0, startPos) + x.value.substring(endPos + 1, x.value.length);
						} else {
							//Remove multiple characters
							x.value = x.value.substring(0, startPos) + x.value.substring(endPos, x.value.length);
						}
						maskAndPosition(x, startPos);
						markAsDirty();
						return false;
					} else { // any other key
						return true;
					}
				}

				function focusEvent(e) {
					mask();
					if (this.createTextRange) {
						var textRange = this.createTextRange();
						textRange.collapse(false); // set the cursor at the end of the input
						textRange.select();
					}
				}

				function blurEvent(e) {
					if ($.browser.msie) {
						keypressEvent(e);
					}

					if (input.val() == '' || input.val() == setSymbol(getDefaultMask()) || input.val() == settings.symbol) {
						if (!settings.allowZero) {
							input.val('');
						} else if (!settings.symbolStay) {
							input.val(getDefaultMask());
						} else {
							input.val(setSymbol(getDefaultMask()));
						}
					} else {
						if (!settings.symbolStay) {
							input.val(input.val().replace(settings.symbol,''));
						} else if (settings.symbolStay && input.val() == settings.symbol) {
							input.val(setSymbol(getDefaultMask()));
						}
					}
				}

				function preventDefault(e) {
					if (e.preventDefault) { //standard browsers
						e.preventDefault();
					} else { // old internet explorer
						e.returnValue = false;
					}
				}

				function maskAndPosition(x, startPos) {
					var originalLen = input.val().length;
					input.val(maskValue(x.value));
					var newLen = input.val().length;
					startPos = startPos - (originalLen - newLen);
					setCursorPosition(startPos);
				}

				function mask() {
					var value = input.val();
					input.val(maskValue(value));
				}

				function maskValue(value) {
					value = value.replace(settings.symbol, '');

					var strCheck = '0123456789';
					var len = value.length;
					var a = '', t = '';
					var negative = '';

					if (len != 0 && value.charAt(0)=='-') {
						value = value.replace('-','');
						if (settings.allowNegative) {
							negative = '-';
						}
					}

					if (len == 0) {
						t = '0.00';
					}

					for (var i = 0; i < len; i++) {
						if (value.charAt(i) != '0' && value.charAt(i) != settings.decimal) {
							break;
						}
					}

					for (; i < len; i++) {
						if (strCheck.indexOf(value.charAt(i)) != -1) {
							a += value.charAt(i);
						}
					}
					var n = parseFloat(a);

					n = isNaN(n) ? 0 : n / Math.pow(10, settings.precision);
					t = n.toFixed(settings.precision);

					i = settings.precision == 0 ? 0 : 1;
					var p, d = (t = t.split('.'))[i].substr(0, settings.precision);
					for (p = (t = t[0]).length; (p -= 3) >= 1;) {
						t = t.substr(0, p) + settings.thousands + t.substr(p);
					}

					return (settings.precision > 0)
						? setSymbol(negative + t + settings.decimal + d + Array((settings.precision + 1) - d.length).join(0))
						: setSymbol(negative + t);
				}

				function getDefaultMask() {
					var n = parseFloat('0') / Math.pow(10, settings.precision);
					return (n.toFixed(settings.precision)).replace(new RegExp('\\.','g'),settings.decimal);
				}

				function setSymbol(value) {
					if (settings.symbol != '') {
						var operator = '';
						if (value.length != 0 && value.charAt(0) == '-') {
							value = value.replace('-', '');
							operator = '-';
						}

						if (value.substr(0, settings.symbol.length) != settings.symbol) {
							value = operator + settings.symbol + value;
						}
					}
					return value;
				}

				function changeSign() {
					var inputValue = input.val();
					if (settings.allowNegative) {
						if (inputValue != '' && inputValue.charAt(0) == '-') {
							return inputValue.replace('-','');
						} else {
							return '-' + inputValue;
						}
					} else {
						return inputValue;
					}
				}

				function setCursorPosition(pos) {
					input.each(function(index, elem) {
						if (elem.setSelectionRange) {
							elem.focus();
							elem.setSelectionRange(pos, pos);
						} else if (elem.createTextRange) {
							var range = elem.createTextRange();
							range.collapse(true);
							range.moveEnd('character', pos);
							range.moveStart('character', pos);
							range.select();
						}
					});
					return this;
				};

				function getInputSelection(el) {
					var start = 0, end = 0, normalizedValue, range, textInputRange, len, endRange;

					if (typeof el.selectionStart == "number" && typeof el.selectionEnd == "number") {
						start = el.selectionStart;
						end = el.selectionEnd;
					} else {
						range = document.selection.createRange();

						if (range && range.parentElement() == el) {
							len = el.value.length;
							normalizedValue = el.value.replace(/\r\n/g, "\n");

							// Create a working TextRange that lives only in the input
							textInputRange = el.createTextRange();
							textInputRange.moveToBookmark(range.getBookmark());

							// Check if the start and end of the selection are at the very end
							// of the input, since moveStart/moveEnd doesn't return what we want
							// in those cases
							endRange = el.createTextRange();
							endRange.collapse(false);

							if (textInputRange.compareEndPoints("StartToEnd", endRange) > -1) {
								start = end = len;
							} else {
								start = -textInputRange.moveStart("character", - len);
								start += normalizedValue.slice(0, start).split("\n").length - 1;

								if (textInputRange.compareEndPoints("EndToEnd", endRange) > -1) {
									end = len;
								} else {
									end = -textInputRange.moveEnd("character", - len);
									end += normalizedValue.slice(0, end).split("\n").length - 1;
								}
							}
						}
					}

					return {
						start: start,
						end: end
					};
				} // getInputSelection

				input.unbind('.maskMoney');
				input.bind('keypress.maskMoney', keypressEvent);
				input.bind('keydown.maskMoney', keydownEvent);
				input.bind('blur.maskMoney', blurEvent);
				input.bind('focus.maskMoney', focusEvent);
				input.bind('mask.maskMoney', mask);
			})
		}
	}

	$.fn.maskMoney = function(method) {
		if (methods[method]) {
			return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
		} else if (typeof method === 'object' || ! method) {
			return methods.init.apply(this, arguments);
		} else {
			$.error('Method ' +  method + ' does not exist on jQuery.maskMoney');
		}
	};
})(window.jQuery || window.Zepto);
<|endoftext|>


<commit_before>/*global config:true, task:true, underscore: true */

function createFactlinkConcatObject(filesObj) {
  return underscore.flatten(["<banner>", underscore(filesObj).map(function(fileGroup) {
    return fileGroup.map(function(file) {
      return "<file_strip_banner:" + file + ">";
    });
  })], true);
}

var files = {
  0: [
    'libs/jquery-1.6.1.js',
    'libs/easyXDM.js',
    'libs/underscore.js'
  ],
  1: [
    'libs/jquery.scrollTo-1.4.2.js',
    'libs/jquery.hoverintent.js'
  ],
  2: [
    'src/js/core.js'
  ],
  3: [
    'src/js/models/fact.js',
    'src/js/views/ballooney_thingy.js',
    'src/js/views/balloon.js',
    'src/js/views/prepare.js'
  ],
  4: [
    'src/js/replace.js',
    'src/js/annotate.js',
    'src/js/highlight.js',
    'src/js/scrollto.js',
    'src/js/search.js',
    'src/js/create.js',
    'src/js/modal.js',
    'src/js/lib/indicator.js'
  ],
  5: [
    'src/js/xdm.js'
  ],
  6: [
    'src/js/last.js'
  ]
};

config.init({
  pkg: '<json:package.json>',
  meta: {
    banner: '/*! \n' +
    ' * <%= pkg.title || pkg.name %> - v<%= pkg.version %> - \n' +
    '<%= pkg.homepage ? " * " + pkg.homepage + "\n" : "" %>' +
    ' *\n' +
    ' * Date: <%= template.today("m/d/yyyy") %>\n' +
    ' *\n' +
    ' * Copyright (c) <%= template.today("yyyy") %> <%= pkg.author %>;\n' +
    ' */'
  },
  concat: {
    'dist/factlink.js': createFactlinkConcatObject(files),
    'dist/factlink.start_annotating.js': '<file_strip_banner:src/js/chrome/start_annotating.js>',
    'dist/factlink.stop_annotating.js': '<file_strip_banner:src/js/chrome/stop_annotating.js>',
    'dist/factlink.start_highlighting.js': '<file_strip_banner:src/js/chrome/start_highlighting.js>',
    'dist/factlink.stop_highlighting.js': '<file_strip_banner:src/js/chrome/stop_highlighting.js>',
    'dist/easyXDM/easyXDM.js': '<file_strip_banner:libs/easyXDM.js>',
    // WARNING: fucking ugly
    'dist/server/css/basic.css': 'src/css/basic.css',
    'dist/css/basic.css': 'src/css/basic.css',

    'dist/server/images/arrow.png': 'src/images/arrow.png',
    'dist/server/images/arrow-bottom.png': 'src/images/arrow-bottom.png',
    'dist/server/images/arrow-top.png': 'src/images/arrow-top.png',
    'dist/server/images/bookmark.gif': 'src/images/bookmark.gif',
    'dist/server/images/logo-small.png': 'src/images/logo-small.png',

    'dist/images/arrow.png': 'src/images/arrow.png',
    'dist/images/arrow-bottom.png': 'src/images/arrow-bottom.png',
    'dist/images/arrow-top.png': 'src/images/arrow-top.png',
    'dist/images/bookmark.gif': 'src/images/bookmark.gif',
    'dist/images/logo-small.png': 'src/images/logo-small.png'
  },
  min: {
    'dist/server/factlink.min.js': ['<banner>', 'dist/factlink.js'],
    'dist/server/factlink.start_annotating.min.js': ['<banner>', 'dist/factlink.start_annotating.js'],
    'dist/server/factlink.stop_annotating.min.js': ['<banner>', 'dist/factlink.stop_annotating.js'],
    'dist/server/factlink.start_highlighting.min.js': ['<banner>', 'dist/factlink.start_highlighting.js'],
    'dist/server/factlink.stop_highlighting.min.js': ['<banner>', 'dist/factlink.stop_highlighting.js'],
    'dist/server/easyXDM/easyXDM.min.js': ['<banner>', 'dist/easyXDM/easyXDM.js'], // for the server
    'dist/easyXDM/easyXDM.min.js': ['<banner>', 'dist/easyXDM/easyXDM.js']         // for local
  },
  qunit: {
    files: ['test/*.html']
  },
  lint: {
    files: ['grunt.js', 'src/js/**/*.js', 'test/**/*.js']
  },
  watch: {
    files: '<config:lint.files>',
    tasks: 'lint qunit concat'
  },
  jshint: {
    options: {
      // Settings
      "passfail"      : false,  // Stop on first error.
      "maxerr"        : 100,    // Maximum error before stopping.

      // Predefined globals whom JSHint will ignore.
      "browser"       : true,   // Standard browser globals e.g. `window`, `document`.

      "node"          : false,
      "rhino"         : false,
      "couch"         : false,
      "wsh"           : false,   // Windows Scripting Host.

      "jquery"        : true,
      "prototypejs"   : false,
      "mootools"      : false,
      "dojo"          : false,

      "predef"        : [  // Custom globals.
        "Factlink", "FactlinkConfig", "escape"
      ],

      // Development.
      "debug"         : false,  // Allow debugger statements e.g. browser breakpoints.
      "devel"         : true,   // Allow developments statements e.g. `console.log();`.

      // ECMAScript 5.
      "es5"           : true,   // Allow ECMAScript 5 syntax.
      "strict"        : false,  // Require `use strict` pragma  in every file.
      "globalstrict"  : false,  // Allow global "use strict" (also enables 'strict').

      // The Good Parts.
      "asi"           : false,  // Tolerate Automatic Semicolon Insertion (no semicolons).
      "laxbreak"      : true,   // Tolerate unsafe line breaks e.g. `return [\n] x` without semicolons.
      "bitwise"       : true,   // Prohibit bitwise operators (&, |, ^, etc.).
      "boss"          : true,   // Tolerate assignments inside if, for & while. Usually conditions & loops are for comparison, not assignments.
      "curly"         : true,   // Require {} for every new block or scope.
      "eqeqeq"        : true,   // Require triple equals i.e. `===`.
      "eqnull"        : false,  // Tolerate use of `== null`.
      "evil"          : false,  // Tolerate use of `eval`.
      "expr"          : false,  // Tolerate `ExpressionStatement` as Programs.
      "forin"         : false,  // Tolerate `for in` loops without `hasOwnPrototype`.
      "immed"         : false,  // Require immediate invocations to be wrapped in parens e.g. `( function(){}() );`
      "latedef"       : true,   // Prohipit variable use before definition.
      "loopfunc"      : true,   // Allow functions to be defined within loops.
      "noarg"         : true,   // Prohibit use of `arguments.caller` and `arguments.callee`.
      "regexp"        : false,  // Prohibit `.` and `[^...]` in regular expressions.
      "regexdash"     : false,  // Tolerate unescaped last dash i.e. `[-...]`.
      "scripturl"     : true,   // Tolerate script-targeted URLs.
      "shadow"        : false,  // Allows re-define variables later in code e.g. `var x=1; x=2;`.
      "supernew"      : false,  // Tolerate `new function () { ... };` and `new Object;`.
      "undef"         : true,   // Require all non-global variables be declared before they are used.

      // Personal styling preferences.
      "newcap"        : true,   // Require capitalization of all constructor functions e.g. `new F()`.
      "noempty"       : true,   // Prohibit use of empty blocks.
      "nonew"         : true,   // Prohibit use of constructors for side-effects.
      "nomen"         : false,  // Prohibit use of initial or trailing underbars in names.
      "onevar"        : false,  // Allow only one `var` statement per function.
      "plusplus"      : false,  // Prohibit use of `++` & `--`.
      "sub"           : false,  // Tolerate all forms of subscript notation besides dot notation e.g. `dict['key']` instead of `dict.key`.
      "trailing"      : true,   // Prohibit trailing whitespaces.
      "white"         : false,  // Check against strict whitespace and indentation rules.
      "indent"        : 2       // Specify indentation spacing
    }
  },
  uglify: {}
});

// Default task.
task.registerTask('default', 'lint qunit concat min');<commit_msg>Created copy-task!<commit_after>/*global config:true, file:true, task:true, underscore: true */

function createFactlinkConcatObject(filesObj) {
  return underscore.flatten(["<banner>", underscore(filesObj).map(function(fileGroup) {
    return fileGroup.map(function(file) {
      return "<file_strip_banner:" + file + ">";
    });
  })], true);
}

var files = {
  0: [
    'libs/jquery-1.6.1.js',
    'libs/easyXDM.js',
    'libs/underscore.js'
  ],
  1: [
    'libs/jquery.scrollTo-1.4.2.js',
    'libs/jquery.hoverintent.js'
  ],
  2: [
    'src/js/core.js'
  ],
  3: [
    'src/js/models/fact.js',
    'src/js/views/ballooney_thingy.js',
    'src/js/views/balloon.js',
    'src/js/views/prepare.js'
  ],
  4: [
    'src/js/replace.js',
    'src/js/annotate.js',
    'src/js/highlight.js',
    'src/js/scrollto.js',
    'src/js/search.js',
    'src/js/create.js',
    'src/js/modal.js',
    'src/js/lib/indicator.js'
  ],
  5: [
    'src/js/xdm.js'
  ],
  6: [
    'src/js/last.js'
  ]
};

config.init({
  pkg: '<json:package.json>',
  meta: {
    banner: '/*! \n' +
    ' * <%= pkg.title || pkg.name %> - v<%= pkg.version %> - \n' +
    '<%= pkg.homepage ? " * " + pkg.homepage + "\n" : "" %>' +
    ' *\n' +
    ' * Date: <%= template.today("m/d/yyyy") %>\n' +
    ' *\n' +
    ' * Copyright (c) <%= template.today("yyyy") %> <%= pkg.author %>;\n' +
    ' */'
  },
  concat: {
    'dist/factlink.js': createFactlinkConcatObject(files),
    'dist/factlink.start_annotating.js': '<file_strip_banner:src/js/chrome/start_annotating.js>',
    'dist/factlink.stop_annotating.js': '<file_strip_banner:src/js/chrome/stop_annotating.js>',
    'dist/factlink.start_highlighting.js': '<file_strip_banner:src/js/chrome/start_highlighting.js>',
    'dist/factlink.stop_highlighting.js': '<file_strip_banner:src/js/chrome/stop_highlighting.js>',
    'dist/easyXDM/easyXDM.js': '<file_strip_banner:libs/easyXDM.js>',
  },
  copy: {
    'dist/server/css/basic.css': 'src/css/basic.css',
    'dist/css/basic.css': 'src/css/basic.css',

    'dist/server/images/arrow.png': 'src/images/arrow.png',
    'dist/server/images/arrows-bottom.png': 'src/images/arrows-bottom.png',
    'dist/server/images/arrows-top.png': 'src/images/arrows-top.png',
    'dist/server/images/bookmark.gif': 'src/images/bookmark.gif',
    'dist/server/images/logo-small.png': 'src/images/logo-small.png',

    'dist/images/arrow.png': 'src/images/arrow.png',
    'dist/images/arrows-bottom.png': 'src/images/arrows-bottom.png',
    'dist/images/arrows-top.png': 'src/images/arrows-top.png',
    'dist/images/bookmark.gif': 'src/images/bookmark.gif',
    'dist/images/logo-small.png': 'src/images/logo-small.png'
  },
  min: {
    'dist/server/factlink.min.js': ['<banner>', 'dist/factlink.js'],
    'dist/server/factlink.start_annotating.min.js': ['<banner>', 'dist/factlink.start_annotating.js'],
    'dist/server/factlink.stop_annotating.min.js': ['<banner>', 'dist/factlink.stop_annotating.js'],
    'dist/server/factlink.start_highlighting.min.js': ['<banner>', 'dist/factlink.start_highlighting.js'],
    'dist/server/factlink.stop_highlighting.min.js': ['<banner>', 'dist/factlink.stop_highlighting.js'],
    'dist/server/easyXDM/easyXDM.min.js': ['<banner>', 'dist/easyXDM/easyXDM.js'], // for the server
    'dist/easyXDM/easyXDM.min.js': ['<banner>', 'dist/easyXDM/easyXDM.js']         // for local
  },
  qunit: {
    files: ['test/*.html']
  },
  lint: {
    files: ['grunt.js', 'src/js/**/*.js', 'test/**/*.js']
  },
  watch: {
    files: '<config:lint.files>',
    tasks: 'lint qunit concat'
  },
  jshint: {
    options: {
      // Settings
      "passfail"      : false,  // Stop on first error.
      "maxerr"        : 100,    // Maximum error before stopping.

      // Predefined globals whom JSHint will ignore.
      "browser"       : true,   // Standard browser globals e.g. `window`, `document`.

      "node"          : false,
      "rhino"         : false,
      "couch"         : false,
      "wsh"           : false,   // Windows Scripting Host.

      "jquery"        : true,
      "prototypejs"   : false,
      "mootools"      : false,
      "dojo"          : false,

      "predef"        : [  // Custom globals.
        "Factlink", "FactlinkConfig", "escape"
      ],

      // Development.
      "debug"         : false,  // Allow debugger statements e.g. browser breakpoints.
      "devel"         : true,   // Allow developments statements e.g. `console.log();`.

      // ECMAScript 5.
      "es5"           : true,   // Allow ECMAScript 5 syntax.
      "strict"        : false,  // Require `use strict` pragma  in every file.
      "globalstrict"  : false,  // Allow global "use strict" (also enables 'strict').

      // The Good Parts.
      "asi"           : false,  // Tolerate Automatic Semicolon Insertion (no semicolons).
      "laxbreak"      : true,   // Tolerate unsafe line breaks e.g. `return [\n] x` without semicolons.
      "bitwise"       : true,   // Prohibit bitwise operators (&, |, ^, etc.).
      "boss"          : true,   // Tolerate assignments inside if, for & while. Usually conditions & loops are for comparison, not assignments.
      "curly"         : true,   // Require {} for every new block or scope.
      "eqeqeq"        : true,   // Require triple equals i.e. `===`.
      "eqnull"        : false,  // Tolerate use of `== null`.
      "evil"          : false,  // Tolerate use of `eval`.
      "expr"          : false,  // Tolerate `ExpressionStatement` as Programs.
      "forin"         : false,  // Tolerate `for in` loops without `hasOwnPrototype`.
      "immed"         : false,  // Require immediate invocations to be wrapped in parens e.g. `( function(){}() );`
      "latedef"       : true,   // Prohipit variable use before definition.
      "loopfunc"      : true,   // Allow functions to be defined within loops.
      "noarg"         : true,   // Prohibit use of `arguments.caller` and `arguments.callee`.
      "regexp"        : false,  // Prohibit `.` and `[^...]` in regular expressions.
      "regexdash"     : false,  // Tolerate unescaped last dash i.e. `[-...]`.
      "scripturl"     : true,   // Tolerate script-targeted URLs.
      "shadow"        : false,  // Allows re-define variables later in code e.g. `var x=1; x=2;`.
      "supernew"      : false,  // Tolerate `new function () { ... };` and `new Object;`.
      "undef"         : true,   // Require all non-global variables be declared before they are used.

      // Personal styling preferences.
      "newcap"        : true,   // Require capitalization of all constructor functions e.g. `new F()`.
      "noempty"       : true,   // Prohibit use of empty blocks.
      "nonew"         : true,   // Prohibit use of constructors for side-effects.
      "nomen"         : false,  // Prohibit use of initial or trailing underbars in names.
      "onevar"        : false,  // Allow only one `var` statement per function.
      "plusplus"      : false,  // Prohibit use of `++` & `--`.
      "sub"           : false,  // Tolerate all forms of subscript notation besides dot notation e.g. `dict['key']` instead of `dict.key`.
      "trailing"      : true,   // Prohibit trailing whitespaces.
      "white"         : false,  // Check against strict whitespace and indentation rules.
      "indent"        : 2       // Specify indentation spacing
    }
  },
  uglify: {}
});

// Default task.
task.registerTask('default', 'lint qunit concat min copy');
task.registerTask('server', 'concat min copy');

task.registerBasicTask('copy', 'copy files', function (data, name) {
  file.copy(data,name);
});<|endoftext|>


<commit_before>'usr strict';

var child_process = reuqire('child_process');

var Embryo = function() {
	var self = this;
};

Embryo.prototype.constructor = function(callback) {
	var self = this;

	process.nextTick(callback);
};

Embryo.prototype.launch = function(appPath, opts, callback) {
	var self = this;

	var app = child_process.fork(appPath);

	process.nextTick(callback);
};

// Metadata
module.exports = {
	name: 'Embryo',
	prototype: Embryo
};
<commit_msg>scanning application directory then launch all automatically<commit_after>'usr strict';

var child_process = reuqire('child_process');
var fs = require('fs');
var path = require('path');
var async = require('async');

var Embryo = function() {
	var self = this;

	self.appDir = path.join('/', 'app');
};

Embryo.prototype.constructor = function(callback) {
	var self = this;

	// Check application directory
	fs.exists(self.appDir, function(exists) {
		if (!exists) {
			fs.mkdir(self.appDir, function(err) {
				callback();
			});
			return;
		}

		// Launch all applications automatically
		fs.readdir(self.appDir, function(err, files) {

			async.eachSeries(files, function(appFile, next) {

				// Launch
				self.launch(path.join(self.appDir, appFile), {}, function() {
					next();
				});

			}, function() {
				callback();
			});
		});
	});
};

Embryo.prototype.launch = function(appPath, opts, callback) {
	var self = this;

	var app = child_process.fork(appPath);

	process.nextTick(callback);
};

// Metadata
module.exports = {
	name: 'Embryo',
	prototype: Embryo
};
<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react';
import { Link } from 'react-router';
import ImmutablePropTypes from 'react-immutable-proptypes';
import Immutable from 'immutable';
import AceEditor from 'react-ace';
import brace from 'brace';
import styles from './Configuration.css';

require('brace/mode/sql');
require('brace/theme/tomorrow');

export default class Configuration extends Component {
    constructor(props) {
        super(props);
        this.state = {query: ''};
    }

  render() {
    console.warn('this.props: ', this.props);
    const configuration = this.props.configuration.toJS();

    const onChangeQuery = query => {
        this.setState({query});
    }

    const onPressConnect = (event) => {
      this.props.ipcActions.connect(this.state.connect);
    }

    const onSendQuery = (event) => {
        this.props.ipcActions.query(this.state.query);
    }

    return (

Getting staarted

          <AceEditor
                    value={this.state.query}
                    onChange={onChangeQuery}
          			mode="sql"
          			theme="tomorrow"
                height='100'
          />

            <button  className={styles.btn} onClick={onPressConnect}>
              connect
            </button>
            <button  className={styles.btn} onClick={onSendQuery}>
              query
            </button>

            {JSON.stringify(this.props.ipc.toJS().rows, null, 2)}

            {JSON.stringify(this.props.ipc.toJS().log, null, 2)}

            {JSON.stringify(this.props.ipc.toJS().metadata, null, 2)}

            {JSON.stringify(this.props.ipc.toJS().error, null, 2)}

    );
  }
}

Configuration.PropTypes = {
    configuration: ImmutablePropTypes.map.isRequired,
    setValue: PropTypes.func.isRequired
}
<commit_msg>Resolve eslint errors for component Configuration<commit_after>import React, { Component, PropTypes } from 'react';
import ImmutablePropTypes from 'react-immutable-proptypes';
import AceEditor from 'react-ace';
import styles from './Configuration.css';

require('brace/mode/sql');
require('brace/theme/tomorrow');

export default class Configuration extends Component {
    constructor(props) {
        super(props);
        this.state = {query: ''};
    }

  render() {
    const onChangeQuery = query => {
        this.setState({query});
    };

    const onPressConnect = () => {
      this.props.ipcActions.connect(this.state.connect);
    };

    const onSendQuery = () => {
        this.props.ipcActions.query(this.state.query);
    };

    return (

Getting staarted

          <AceEditor
            value={this.state.query}
            onChange={onChangeQuery}
            mode="sql"
            theme="tomorrow"
            height="100"
          />

            <button className={styles.btn} onClick={onPressConnect}>
              connect
            </button>
            <button className={styles.btn} onClick={onSendQuery}>
              query
            </button>

            {JSON.stringify(this.props.ipc.toJS().rows, null, 2)}

            {JSON.stringify(this.props.ipc.toJS().log, null, 2)}

            {JSON.stringify(this.props.ipc.toJS().metadata, null, 2)}

            {JSON.stringify(this.props.ipc.toJS().error, null, 2)}

    );
  }
}

Configuration.propTypes = {
    configuration: ImmutablePropTypes.map.isRequired,
    setValue: PropTypes.func.isRequired,
    ipc: ImmutablePropTypes.map.isRequired,
    ipcActions: PropTypes.Object
};
<|endoftext|>


<commit_before><commit_msg>Documentation, see https://github.com/phetsims/tandem/issues/212<commit_after><|endoftext|>


<commit_before>var fs     = require('fs');
var spawn  = require('child_process').spawn;
var join   = require('path').join;
var http   = require('http');
var shell  = require('shelljs');
var      _ = require('lodash');

module.exports = function($){
  return new NodeJS($);
};

function NodeJS($){
  this.$ = $;
  this.log = require('../log')($, 'electrify:plugins:nodejs');
  this.name = 'nodejs';
  this.app_node_path = join(this.$.env.app.bin, 'node');

  if(this.$.env.sys.is_windows)
    this.app_node_path += '.exe';

  this.config = {
    ROOT_URL: 'http://localhost:3000' // find meteor's port in run time?
  };
}

NodeJS.prototype.acquire = function(done){
  this.log.info('acquiring nodejs');

  if(!fs.existsSync(this.app_node_path))
    shell.cp(this.$.env.meteor.node, this.$.env.app.bin);

  done();
};

NodeJS.prototype.start = function(done) {

  // abort if app is not packaged (though meteor is up for development)
  if(!this.$.env.app.is_packaged) return done(null); //<-- never called anynore

  this.log.info('starting meteor...');

  this.mongo_port  = this.$.plugins.get('mongodb').port;
  this.meteor_main = join(this.$.env.app.electrify, 'app', 'main.js');

  var self = this;

  this.$.freeport(null, function(meteor_port){
    self.meteor_port = meteor_port;

    // mimics the process' env data and sets meteor vars on it
    self.config = _.extend({
      MONGO_URL       : 'mongodb://localhost:'+ self.mongo_port +'/meteor',
      PORT            : self.meteor_port,
      ROOT_URL        : 'http://localhost:' + self.meteor_port,
      METEOR_SETTINGS : JSON.stringify(self.$.env.app.settings)
    }, process.env);

    self.process = spawn(self.app_node_path, [self.meteor_main], {
      env: self.config
      // , stdio: 'inherit'
      // when setting stdio to 'inherit', the node/meteor process CANNOT be
      // spawned. also, no error is risen. it was discovered with try'n'error
      // so we listen for stdout and stderr instead, and things appear to be
      // working again
    });

    self.process.stdout.on('data', function(d){
      // mimics inherit
      self.log.info('meteor:stdout', d.toString());
    });

    self.process.stderr.on('data', function(d){
      // mimics inherit
      self.log.error('meteor:stderr', d.toString());
    });

    self.log.debug('waiting for meteor ready');

    function meteor_ready(url){
      http.get(url, function(/* res */) {
        self.log.info('meteor ready');
        done();
      }).on('error', function(/* err */) {
        new setTimeout(function(){
          meteor_ready(url);
        }, 30);
      });
    }

    meteor_ready(self.config.ROOT_URL);
  });
};

NodeJS.prototype.stop = function() {
  if(this.process)
    this.process.kill();
};<commit_msg>cleaning up, reducing verbosity and improving comments<commit_after>var fs     = require('fs');
var spawn  = require('child_process').spawn;
var join   = require('path').join;
var http   = require('http');
var shell  = require('shelljs');
var      _ = require('lodash');

module.exports = function($){
  return new NodeJS($);
};

function NodeJS($){
  this.$ = $;
  this.log = require('../log')($, 'electrify:plugins:nodejs');
  this.name = 'nodejs';
  this.app_node_path = join(this.$.env.app.bin, 'node');

  if(this.$.env.sys.is_windows)
    this.app_node_path += '.exe';

  this.config = {
    ROOT_URL: 'http://localhost:3000' // find meteor's port in run time?
  };
}

NodeJS.prototype.acquire = function(done){
  this.log.info('acquiring nodejs');

  if(!fs.existsSync(this.app_node_path))
    shell.cp(this.$.env.meteor.node, this.$.env.app.bin);

  done();
};

NodeJS.prototype.start = function(done) {

  // abort if app is not packaged (though meteor is up for development)
  if(!this.$.env.app.is_packaged) return done(null); //<-- never called anynore

  this.log.info('starting meteor...');

  this.mongo_port  = this.$.plugins.get('mongodb').port;
  this.meteor_main = join(this.$.env.app.electrify, 'app', 'main.js');

  var self = this;

  this.$.freeport(null, function(meteor_port){
    self.meteor_port = meteor_port;

    // mimics the process' env data and sets meteor vars on it
    self.config = _.extend({
      MONGO_URL       : 'mongodb://localhost:'+ self.mongo_port +'/meteor',
      PORT            : self.meteor_port,
      ROOT_URL        : 'http://localhost:' + self.meteor_port,
      METEOR_SETTINGS : JSON.stringify(self.$.env.app.settings)
    }, process.env);

    self.process = spawn(self.app_node_path, [self.meteor_main], {
      env: self.config
      // , stdio: 'inherit'
      // when setting stdio to 'inherit', the node/meteor process CANNOT be
      // spawned and also, no error is shown. it was discovered with try'n'error
      // so now we just listen for stdout and stderr instead, and things appear
      // to be working again
    });

    // mimics inherit without prefixing
    self.process.stdout.pipe(process.stderr);
    self.process.stderr.pipe(process.stderr);

    self.log.debug('waiting for meteor ready');

    function meteor_ready(url){
      http.get(url, function(/* res */) {
        self.log.info('meteor ready');
        done();
      }).on('error', function(/* err */) {
        new setTimeout(function(){
          meteor_ready(url);
        }, 30);
      });
    }

    meteor_ready(self.config.ROOT_URL);
  });
};

NodeJS.prototype.stop = function() {
  if(this.process)
    this.process.kill();
};<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import { List } from 'immutable';

import { pushPath, selectEnvironment, unsetEnvironment } from '../actions/ui';
import Select from './Select';

import styles from './EnvironmentSelector.module.scss';

const MANAGE_SELECT_ID = '__manage__';
const NO_ENVIRONMENT_ID = '__no_environment__';

const DEFAULT_OPTIONS = new List([
  {value: MANAGE_SELECT_ID, label: 'Manage...'},
  {value: NO_ENVIRONMENT_ID, label: 'No environment'}
]);

export default class EnvironmentSelector extends Component {
  onChange(e) {
    switch (e.target.value) {
      case MANAGE_SELECT_ID:
        this.props.dispatch(pushPath('/environments'));
        break;
      case NO_ENVIRONMENT_ID:
        this.props.dispatch(unsetEnvironment());
        break;
      default:
        const environmentId = e.target.value;
        this.props.dispatch(selectEnvironment(environmentId));
    }
  }

  render() {
    const selected = this.props.activeEnvironment;
    const options = DEFAULT_OPTIONS.concat(this.props.environments.map((e) => {
      return {value: e.id, label: e.name}
    })).toJS();

    return (

        <Select className={styles.select} name="environment"
                onChange={ this.onChange.bind(this)}
                selected={selected.toString()}
                options={options}/>

    );
  }
}

function mapStateToProps(state) {
  return {
    environments: state.environments,
    activeEnvironment: state.ui.get('activeEnvironment') || NO_ENVIRONMENT_ID
  }
}

export default connect(mapStateToProps)(EnvironmentSelector);
<commit_msg>Select previously selected environment after selecting 'manage' item<commit_after>import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import { List } from 'immutable';

import { pushPath, selectEnvironment, unsetEnvironment } from '../actions/ui';
import Select from './Select';

import styles from './EnvironmentSelector.module.scss';

const MANAGE_SELECT_ID = '__manage__';
const NO_ENVIRONMENT_ID = '__no_environment__';

const DEFAULT_OPTIONS = new List([
  {value: MANAGE_SELECT_ID, label: 'Manage...'},
  {value: NO_ENVIRONMENT_ID, label: 'No environment'}
]);

export default class EnvironmentSelector extends Component {
  onChange(e) {
    switch (e.target.value) {
      case MANAGE_SELECT_ID:
        this.props.dispatch(pushPath('/environments'));
        this.forceUpdate(); //ensure we rerender to select previously selected option again
        break;
      case NO_ENVIRONMENT_ID:
        this.props.dispatch(unsetEnvironment());
        break;
      default:
        const environmentId = e.target.value;
        this.props.dispatch(selectEnvironment(environmentId));
    }
  }

  render() {
    const selected = this.props.activeEnvironment;
    const options = DEFAULT_OPTIONS.concat(this.props.environments.map((e) => {
      return {value: e.id, label: e.name}
    })).toJS();

    return (

        <Select className={styles.select} name="environment"
                onChange={ this.onChange.bind(this)}
                selected={selected.toString()}
                options={options}/>

    );
  }
}

function mapStateToProps(state) {
  return {
    environments: state.environments,
    activeEnvironment: state.ui.get('activeEnvironment') || NO_ENVIRONMENT_ID
  }
}

export default connect(mapStateToProps)(EnvironmentSelector);
<|endoftext|>


<commit_before>var _ = require('underscore'),
    fu = require('../fileUtil'),
    inlineStyles = require('./inline-styles'),
    nib = require('nib'),
    path = require('path'),
    stylus = require('stylus'),
    stylusImages = require('stylus-images');

function compile(files, context, callback) {
  var styleConfig = context.config.attributes.styles || {},
      includes = styleConfig.includes || [],
      pixelDensity = context.fileConfig.pixelDensity;

  includes = includes.concat(files);

  var options = { _imports: [] };

  var compiler = stylus(includes.map(function(include) { return '@import ("' + include + '")\n'; }).join(''), options)
    .set('filename', files.join(';'))
    .set('compress', context.options.minimize)
    .include(nib.path)
    .include(fu.lookupPath())
    .use(nib)
    .use(stylusImages({
      outdir: path.dirname(context.fileName),
      res: pixelDensity,
      limit: styleConfig.urlSizeLimit,
      copyFiles: styleConfig.copyFiles
    }));

  if (styleConfig.styleRoot) {
    compiler.include(fu.resolvePath(styleConfig.styleRoot));
  }

  context.config.platformList().forEach(function(platform) {
    compiler.define('$' + platform, platform === context.platform ? stylus.nodes.true : stylus.nodes.false);
  });

  fu.ensureDirs(context.fileName, function(err) {
    if (err) {
      return callback(err);
    }

    try {
      compiler.render(function(err, data) {
        var lookupPath = fu.lookupPath(),
            inputs = compiler.options._imports
                .map(function(file) { return file.path; })
                .filter(function(file) { return file.indexOf(lookupPath) === 0; });
        callback(err, {
          data: data,
          inputs: inputs,
          noSeparator: true
        });
      });
    } catch (err) {
      callback(err);
    }
  });
};

module.exports = {
  generatedFiles: function(context, next, complete) {
    if (!inlineStyles.isInline(context) && context.mode !== 'styles') {
      return next(complete);
    }

    next(function(err, files) {
      if (err) {
        return complete(err);
      }

      var ret = [],
          styleConfig = context.config.attributes.styles || {},
          pixelDensity = styleConfig.pixelDensity || {};
      if (context.platform) {
        pixelDensity = pixelDensity[context.platform] || pixelDensity;
      }
      if (!_.isArray(pixelDensity)) {
        pixelDensity = [ 1 ];
      }

      // Permutation of other configs and ours
      files.forEach(function(fileConfig) {
        pixelDensity.forEach(function(density) {
          var config = _.clone(fileConfig);
          config.pixelDensity = density;
          ret.push(config);
        });
      });
      complete(undefined, ret);
    });
  },
  fileName: function(context, next, complete) {
    if (!inlineStyles.isInline(context) && context.mode !== 'styles') {
      return next(complete);
    }

    next(function(err, ret) {
      if (ret && context.fileConfig.pixelDensity !== 1) {
        ret.path += '@' + context.fileConfig.pixelDensity + 'x';
      }
      complete(err, ret);
    });
  },

  module: function(context, next, complete) {
    next(function(err) {
      if (err) {
        return callback(err);
      }

      function mergeResources(start) {
        var files = resources.splice(start, rangeEnd-start+1).map(function(resource) { return resource.src; });

        var generator = function(callback) {
          compile(files, context, callback);
        };
        generator.style = true;

        resources.splice(start, 0, generator);
        rangeEnd = undefined;
      }

      // Merge all consequtive stylus files together
      var resources = context.moduleResources,
          len = resources.length,
          rangeEnd;
      while (len--) {
        var resource = resources[len];

        if (/\.styl$/.test(resource.src)) {
          if (!rangeEnd) {
            rangeEnd = len;
          }
        } else {
          rangeEnd && mergeResources(len+1);
        }
      }
      rangeEnd != null && mergeResources(0);
      complete();
    });
  }
};
<commit_msg>Fix typo<commit_after>var _ = require('underscore'),
    fu = require('../fileUtil'),
    inlineStyles = require('./inline-styles'),
    nib = require('nib'),
    path = require('path'),
    stylus = require('stylus'),
    stylusImages = require('stylus-images');

function compile(files, context, callback) {
  var styleConfig = context.config.attributes.styles || {},
      includes = styleConfig.includes || [],
      pixelDensity = context.fileConfig.pixelDensity;

  includes = includes.concat(files);

  var options = { _imports: [] };

  var compiler = stylus(includes.map(function(include) { return '@import ("' + include + '")\n'; }).join(''), options)
    .set('filename', files.join(';'))
    .set('compress', context.options.minimize)
    .include(nib.path)
    .include(fu.lookupPath())
    .use(nib)
    .use(stylusImages({
      outdir: path.dirname(context.fileName),
      res: pixelDensity,
      limit: styleConfig.urlSizeLimit,
      copyFiles: styleConfig.copyFiles
    }));

  if (styleConfig.styleRoot) {
    compiler.include(fu.resolvePath(styleConfig.styleRoot));
  }

  context.config.platformList().forEach(function(platform) {
    compiler.define('$' + platform, platform === context.platform ? stylus.nodes.true : stylus.nodes.false);
  });

  fu.ensureDirs(context.fileName, function(err) {
    if (err) {
      return callback(err);
    }

    try {
      compiler.render(function(err, data) {
        var lookupPath = fu.lookupPath(),
            inputs = compiler.options._imports
                .map(function(file) { return file.path; })
                .filter(function(file) { return file.indexOf(lookupPath) === 0; });
        callback(err, {
          data: data,
          inputs: inputs,
          noSeparator: true
        });
      });
    } catch (err) {
      callback(err);
    }
  });
};

module.exports = {
  generatedFiles: function(context, next, complete) {
    if (!inlineStyles.isInline(context) && context.mode !== 'styles') {
      return next(complete);
    }

    next(function(err, files) {
      if (err) {
        return complete(err);
      }

      var ret = [],
          styleConfig = context.config.attributes.styles || {},
          pixelDensity = styleConfig.pixelDensity || {};
      if (context.platform) {
        pixelDensity = pixelDensity[context.platform] || pixelDensity;
      }
      if (!_.isArray(pixelDensity)) {
        pixelDensity = [ 1 ];
      }

      // Permutation of other configs and ours
      files.forEach(function(fileConfig) {
        pixelDensity.forEach(function(density) {
          var config = _.clone(fileConfig);
          config.pixelDensity = density;
          ret.push(config);
        });
      });
      complete(undefined, ret);
    });
  },
  fileName: function(context, next, complete) {
    if (!inlineStyles.isInline(context) && context.mode !== 'styles') {
      return next(complete);
    }

    next(function(err, ret) {
      if (ret && context.fileConfig.pixelDensity !== 1) {
        ret.path += '@' + context.fileConfig.pixelDensity + 'x';
      }
      complete(err, ret);
    });
  },

  module: function(context, next, complete) {
    next(function(err) {
      if (err) {
        return complete(err);
      }

      function mergeResources(start) {
        var files = resources.splice(start, rangeEnd-start+1).map(function(resource) { return resource.src; });

        var generator = function(callback) {
          compile(files, context, callback);
        };
        generator.style = true;

        resources.splice(start, 0, generator);
        rangeEnd = undefined;
      }

      // Merge all consequtive stylus files together
      var resources = context.moduleResources,
          len = resources.length,
          rangeEnd;
      while (len--) {
        var resource = resources[len];

        if (/\.styl$/.test(resource.src)) {
          if (!rangeEnd) {
            rangeEnd = len;
          }
        } else {
          rangeEnd && mergeResources(len+1);
        }
      }
      rangeEnd != null && mergeResources(0);
      complete();
    });
  }
};
<|endoftext|>


<commit_before>// @flow

import { useCallback, useEffect, useRef, useState } from 'react';
import { get } from 'lodash';
import cx from 'classnames';
import SearchPage from 'app/components/Search/SearchPage';
import type { SearchResult } from 'app/reducers/search';
import styles from './Validator.css';

// $FlowFixMe
import goodSound from 'app/assets/good-sound.mp3';
import Button from 'app/components/Button';
import Modal from 'app/components/Modal';
import { QrReader } from 'react-qr-reader';
import Icon from 'app/components/Icon';
type Props = {
  clearSearch: () => void,
  handleSelect: (string) => Promise<void>,
  location: Object,
  onQueryChanged: (string) => void,
  results: Array<SearchResult>,
  searching: boolean,
};

const Validator = (props: Props) => {
  const input = useRef<?HTMLInputElement>(null);
  const [completed, setCompleted] = useState(false);
  const [showScanner, setShowScanner] = useState(false);
  const [scannerResult, setScannerResult] = useState('');

  const showCompleted = () => {
    setCompleted(true);
    setTimeout(() => setCompleted(false), 2000);
  };

  const handleSelect = useCallback(
    (result: string) => {
      props.clearSearch();
      return props
        .handleSelect(result)
        .then(
          () => {
            const sound = new window.Audio(goodSound);
            sound.play();
            showCompleted();
          },
          (err) => {
            const payload = get(err, 'payload.response.jsonData');
            if (payload && payload.errorCode === 'not_registered') {
              alert('Bruker er ikke påmeldt på eventet!');
            } else if (payload && payload.errorCode === 'already_present') {
              alert(payload.error);
            } else {
              alert(
                `Det oppsto en uventet feil: ${JSON.stringify(payload || err)}`
              );
            }
          }
        )
        .then(() => {
          if (input?.current) {
            input.current.focus();
          }
        });
    },
    [props]
  );

  useEffect(() => {
    if (scannerResult.length > 0 && !completed) {
      handleSelect(scannerResult);
    }
  }, [handleSelect, completed, scannerResult]);

  return (
    <>

          Tusen takk! Kos deg{' '}

            😀

      <Modal
        contentClassName={styles.scannerModal}
        show={showScanner}
        onHide={() => setShowScanner(false)}
      >

Scan ABA-ID

        <QrReader
          onResult={(res, error) => {
            if (res) {
              setScannerResult(res.getText());
            }

            if (error) {
              console.info(error);
            }

            setScannerResult('');
          }}
          constraints={{ facingMode: 'environment' }}
        />
      </Modal>
      <Button
        className={styles.scannerButton}
        onClick={() => setShowScanner(true)}
      >
        <Icon className={styles.qrIcon} name="qr-code" size={18} />
        Vis scanner
      </Button>
      <SearchPage
        {...props}
        placeholder="Skriv inn brukernavn eller navn"
        handleSelect={handleSelect}
        inputRef={input}
      />
    </>
  );
};

export default Validator;
<commit_msg>refactor(UserValidator): destructure props to optimize dep array<commit_after>// @flow

import { useCallback, useEffect, useRef, useState } from 'react';
import { get } from 'lodash';
import cx from 'classnames';
import SearchPage from 'app/components/Search/SearchPage';
import type { SearchResult } from 'app/reducers/search';
import styles from './Validator.css';

// $FlowFixMe
import goodSound from 'app/assets/good-sound.mp3';
import Button from 'app/components/Button';
import Modal from 'app/components/Modal';
import { QrReader } from 'react-qr-reader';
import Icon from 'app/components/Icon';
type Props = {
  clearSearch: () => void,
  handleSelect: (string) => Promise<void>,
  location: Object,
  onQueryChanged: (string) => void,
  results: Array<SearchResult>,
  searching: boolean,
};

const Validator = (props: Props) => {
  const { clearSearch, handleSelect } = props;

  const input = useRef<?HTMLInputElement>(null);
  const [completed, setCompleted] = useState(false);
  const [showScanner, setShowScanner] = useState(false);
  const [scannerResult, setScannerResult] = useState('');

  const showCompleted = () => {
    setCompleted(true);
    setTimeout(() => setCompleted(false), 2000);
  };

  const onSelect = useCallback(
    (result: string) => {
      clearSearch();
      return handleSelect(result)
        .then(
          () => {
            const sound = new window.Audio(goodSound);
            sound.play();
            showCompleted();
          },
          (err) => {
            const payload = get(err, 'payload.response.jsonData');
            if (payload && payload.errorCode === 'not_registered') {
              alert('Bruker er ikke påmeldt på eventet!');
            } else if (payload && payload.errorCode === 'already_present') {
              alert(payload.error);
            } else {
              alert(
                `Det oppsto en uventet feil: ${JSON.stringify(payload || err)}`
              );
            }
          }
        )
        .then(() => {
          if (input?.current) {
            input.current.focus();
          }
        });
    },
    [clearSearch, handleSelect]
  );

  useEffect(() => {
    if (scannerResult.length > 0 && !completed) {
      onSelect(scannerResult);
    }
  }, [completed, onSelect, scannerResult]);

  return (
    <>

          Tusen takk! Kos deg{' '}

            😀

      <Modal
        contentClassName={styles.scannerModal}
        show={showScanner}
        onHide={() => setShowScanner(false)}
      >

Scan ABA-ID

        <QrReader
          onResult={(res, error) => {
            if (res) {
              setScannerResult(res.getText());
            }

            if (error) {
              console.info(error);
            }

            setScannerResult('');
          }}
          constraints={{ facingMode: 'environment' }}
        />
      </Modal>
      <Button
        className={styles.scannerButton}
        onClick={() => setShowScanner(true)}
      >
        <Icon className={styles.qrIcon} name="qr-code" size={18} />
        Vis scanner
      </Button>
      <SearchPage
        {...props}
        placeholder="Skriv inn brukernavn eller navn"
        handleSelect={onSelect}
        inputRef={input}
      />
    </>
  );
};

export default Validator;
<|endoftext|>


<commit_before>var $        = require('jquery'),
    _        = require('underscore'),
    Facility = require('cloud/models/facility');

var location = function() {
  var lat, lon;

  if ( navigator.geolocation ) {
    navigator.geolocation.getCurrentPosition(function(position) {
      lat = position.coords.latitude;
      lon = position.coords.longitude;
    }, function(error) {
      console.log(error);
    });
  } else {
    // for local development
    lat = 37.782355;
    lon = -122.409825;
  }

  return {lat: lat, lon: lon};
};

var queryFunction = function(runWhere) {
  if ( true || runWhere === 'cloud' ) {
    return _.partial(Parse.Cloud.run, "browse");
  } else {
    return require('cloud/lib/browse');
  }
};

var submit = function(params) {
  // to keep track of when it finishes
  var deferred = $.Deferred();

  // choose where to run the query
  var query = queryFunction(params.runwhere);

  // add location if proximity sorting
  if ( params.sort === 'near' ) {
    $.extend(params, location());
  }

  query(params, {
    success: function(result) {
      deferred.resolve(result);
      // dumpToDOM(result);
    },

    error: function(err) {
      deferred.reject(err);
    }
  });

  return deferred.promise();
};

// TODO -- hoist this up a layer into "browse" -- or wherever we keep the direct parse communication lib.
var getByID = function(id) {
  var deferred = $.Deferred();

  var q = new Parse.Query(Facility);
  q.include("services");
  q.get(id, {
    success: function(result) {
      deferred.resolve(result);
    },
    error: function(err) {
      deferred.reject(err);
    }
  });

  return deferred.promise();
};

module.exports = { submit: submit, getByID: getByID };
<commit_msg>Revert "run in cloud by default"<commit_after>var $        = require('jquery'),
    _        = require('underscore'),
    Facility = require('cloud/models/facility');

var location = function() {
  var lat, lon;

  if ( navigator.geolocation ) {
    navigator.geolocation.getCurrentPosition(function(position) {
      lat = position.coords.latitude;
      lon = position.coords.longitude;
    }, function(error) {
      console.log(error);
    });
  } else {
    // for local development
    lat = 37.782355;
    lon = -122.409825;
  }

  return {lat: lat, lon: lon};
};

var queryFunction = function(runWhere) {
  if ( runWhere === 'cloud' ) {
    return _.partial(Parse.Cloud.run, "browse");
  } else {
    return require('cloud/lib/browse');
  }
};

var submit = function(params) {
  // to keep track of when it finishes
  var deferred = $.Deferred();

  // choose where to run the query
  var query = queryFunction(params.runwhere);

  // add location if proximity sorting
  if ( params.sort === 'near' ) {
    $.extend(params, location());
  }

  query(params, {
    success: function(result) {
      deferred.resolve(result);
      // dumpToDOM(result);
    },

    error: function(err) {
      deferred.reject(err);
    }
  });

  return deferred.promise();
};

// TODO -- hoist this up a layer into "browse" -- or wherever we keep the direct parse communication lib.
var getByID = function(id) {
  var deferred = $.Deferred();

  var q = new Parse.Query(Facility);
  q.include("services");
  q.get(id, {
    success: function(result) {
      deferred.resolve(result);
    },
    error: function(err) {
      deferred.reject(err);
    }
  });

  return deferred.promise();
};

module.exports = { submit: submit, getByID: getByID };
<|endoftext|>


<commit_before>/* Application namespace */

define(['app/utils/store', 'jquery', 'thorax', 'backbone'],
  function(Store, $, Thorax) {

    // Create the Application object, Application.setView() will
    // place a view inside the {{layout-element}}
    var Application = window.Application = new Thorax.LayoutView({
      name: 'application'
    });

    // Alias the special hashes for naming consistency
    Application.templates = Thorax.templates;
    Application.Views = Thorax.Views;
    Application.Models = Thorax.Models;
    Application.Collections = Thorax.Collections;
    Application.Store = Store;

    // Initialize main application store
    Application.store = new Store('application');

    // Encapsulate libs
    Application.libs = {
      '$': $,
      'jQuery': $,
      'Backbone': Backbone
    };

    return Application;
});
<commit_msg>Added underscore to Application.libs<commit_after>/* Application namespace */

define(['app/utils/store', 'jquery', 'thorax', 'underscore', 'backbone'],
  function(Store, $, Thorax, _) {

    // Create the Application object, Application.setView() will
    // place a view inside the {{layout-element}}
    var Application = window.Application = new Thorax.LayoutView({
      name: 'application'
    });

    // Alias the special hashes for naming consistency
    Application.templates = Thorax.templates;
    Application.Views = Thorax.Views;
    Application.Models = Thorax.Models;
    Application.Collections = Thorax.Collections;
    Application.Store = Store;

    // Initialize main application store
    Application.store = new Store('application');

    // Encapsulate libs
    Application.libs = {
      '$': $,
      'jQuery': $,
      '_', _,

      'Backbone': Backbone
    };

    return Application;
});
<|endoftext|>