<commit_before>'use strict';

(function (angular) {

  angular
      .module('flickrPOC')
      .directive('imagesList', imagesList);

  imagesList.$inject = ['$log', '$compile'];

  function imagesList($log, $compile) {
    return {
      scope: {},
      restrict: 'EA',
      template: '

',
      controller: ImagesListController,
      controllerAs: 'ImagesList',
      link: linkFunction,
      bindToController: {
        images: '='
      }
    };

    function linkFunction(scope, iElem, iAttrs, controller) {

      if (!controller.images) {
        $log.error('Images List Failed! No images provided.');

      } else if (!angular.isArray(controller.images)) {
        $log.error('Images List Failed! Please provide an array.');

      } else {

        for (var i = 0; i < controller.images.length; i++) {

          if (!angular.isString(controller.images[i])) {
            $log.error('Images List Failed! Invalid image URL.');
            return;
          } else {
            iElem.find('ul').append('

');
          }
        }

      }

    }
  }

  ImagesListController.$inject = [];

  function ImagesListController() {
  }

})(angular);

/*
 Accept an array of images ===

 If no array, throw error asking for array.
 Output a list of images, with lightbox attributes/classes
 Each image, when clicked, opens in lightbox
 */

/*
 View Controller
 Retrieve the images via Service
 Store images array in VM property
 VM property passed to directive. <-- ARRAY
 */<commit_msg>returning directives tu original state<commit_after>'use strict';

(function (angular) {

  angular
      .module('flickrPOC')
      .directive('imagesList', imagesList);

  imagesList.$inject = ['$log', '$compile'];

  function imagesList($log, $compile) {
    return {
      scope: {},
      restrict: 'EA',
      template: '

',
      controller: ImagesListController,
      controllerAs: 'ImagesList',
      link: linkFunction,
      bindToController: {
        images: '='
      }
    };

    function linkFunction(scope, iElem, iAttrs, controller) {

      if (!controller.images) {
        $log.error('Images List Failed! No images provided.');

      } else if (!angular.isArray(controller.images)) {
        $log.error('Images List Failed! Please provide an array.');

      } else {

        for (var i = 0; i < controller.images.length; i++) {

          if (!angular.isString(controller.images[i])) {
            $log.error('Images List Failed! Invalid image URL.');
            return;
          } else {
            iElem.find('ul').append('

');
          }
        }

      }

    }
  }

  ImagesListController.$inject = [];

  function ImagesListController() {
  }

})(angular);

/*
 Accept an array of images ===

 If no array, throw error asking for array.
 Output a list of images, with lightbox attributes/classes
 Each image, when clicked, opens in lightbox

 */

/*
 View Controller
 Retrieve the images via Service
 Store images array in VM property
 VM property passed to directive. <-- ARRAY

 */<|endoftext|>


<commit_before>
/*
version 2014-06-26
*/
(function (factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD. Register as an anonymous module.
        define(['jquery'], factory);
    } else {
        // Browser globals
        factory(jQuery);
    }
}(function ($) {

	'use strict';

	var pluginName = 'writeDate';

	var months = {
		fr:['janvier', 'février', 'mars', 'avril', 'mai', 'juin', 'juillet', 'août', 'septembre', 'octobre', 'novembre', 'décembre'],
		en: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
	};
	var monthsShort = {
		fr:['jan', 'fév', 'mar', 'avr', 'mai', 'jun', 'jul', 'aoû', 'sep', 'oct', 'nov', 'déc'],
		en: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
	};
	var days = {
		fr:['dimanche', 'lundi', 'mardi', 'mercredi', 'jeudi', 'vendredi', 'samedi'],
		en: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
	};

	/*
	formats:
	%A day name (Sunday, Monday...)
	%e Day of the month (1 to 31)
	%d Day of the month (01 to 31)
	%Y Four digit representation for the year
	%b	Abbreviated month name, based on the locale (Jan, Feb...)
	%B  Full month name, based on the locale
	*/

	var defaults = {
		format : {
			fr : '%A %e %B %Y',
			en : '%A %B %e, %Y'
		},
		lang : 'fr'
	};
	var plugin = function(el, settings) {

		settings = $.extend({}, defaults, settings);
		var lang = settings.lang;

		var _self = $(el);
		var date = _self.text();
		var month = Number(date.substr(5,2))-1;
		var year = date.substr(0, 4);
		var dayStr = date.substr(8, 2);
		var day = Number(dayStr);/**/
		if(isNaN(day) || isNaN(month) || isNaN(year)) return;
		var dObj = new Date(year, month, day);
		var desc = {
			A : days[lang][dObj.getDay()],
			e : day,
			d : dayStr,
			Y : year,
			b: monthsShort[lang][month],
			B: months[lang][month]
		};

		var textDate = typeof settings.format == 'string' ? settings.format : settings.format[lang] ;
		$.each(desc, function(key, val){
			textDate = textDate.replace('%'+key, val);
		});

		/*console.log(day, month, year, date);
		console.log(parsedStr);/**/

		_self.html(textDate);

	};

	$.fn[pluginName] = function(options) {
		var input = arguments;
		if ( this.length ) {
			return this.each(function () {

				plugin(this, options);

			});
		}
	}

}));<commit_msg>added month format to datestr<commit_after>
/*
version 2014-06-26
*/
(function (factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD. Register as an anonymous module.
        define(['jquery'], factory);
    } else {
        // Browser globals
        factory(jQuery);
    }
}(function ($) {

	'use strict';

	var pluginName = 'writeDate';

	var months = {
		fr:['janvier', 'février', 'mars', 'avril', 'mai', 'juin', 'juillet', 'août', 'septembre', 'octobre', 'novembre', 'décembre'],
		en: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
	};
	var monthsShort = {
		fr:['jan', 'fév', 'mar', 'avr', 'mai', 'jun', 'jul', 'aoû', 'sep', 'oct', 'nov', 'déc'],
		en: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
	};
	var days = {
		fr:['dimanche', 'lundi', 'mardi', 'mercredi', 'jeudi', 'vendredi', 'samedi'],
		en: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
	};

	/*
	formats:
	%A day name (Sunday, Monday...)
	%e Day of the month (1 to 31)
	%d Day of the month (01 to 31)
	%Y Four digit representation for the year
	%b	Abbreviated month name, based on the locale (Jan, Feb...)
	%B  Full month name, based on the locale
	%m Month (01 to 12)
	*/

	var defaults = {
		format : {
			fr : '%A %e %B %Y',
			en : '%A %B %e, %Y'
		},
		lang : 'fr'
	};
	var plugin = function(el, settings) {

		settings = $.extend({}, defaults, settings);
		var lang = settings.lang;

		var _self = $(el);
		var date = _self.text();
		var monthStr = date.substr(5,2);
		var month = Number(monthStr)-1;
		var year = date.substr(0, 4);
		var dayStr = date.substr(8, 2);
		var day = Number(dayStr);/**/
		if(isNaN(day) || isNaN(month) || isNaN(year)) return;
		var dObj = new Date(year, month, day);
		var desc = {
			A : days[lang][dObj.getDay()],
			e : day,
			d : dayStr,
			Y : year,
			b: monthsShort[lang][month],
			B: months[lang][month],
			m: monthStr
		};

		var textDate = typeof settings.format == 'string' ? settings.format : settings.format[lang] ;
		$.each(desc, function(key, val){
			textDate = textDate.replace('%'+key, val);
		});

		/*console.log(day, month, year, date);
		console.log(parsedStr);/**/

		_self.html(textDate);

	};

	$.fn[pluginName] = function(options) {
		var input = arguments;
		if ( this.length ) {
			return this.each(function () {

				plugin(this, options);

			});
		}
	}

}));<|endoftext|>


<commit_before>'use strict';
// Operations on equation nodes

const clone = require('./clone');
const Equation = require('./Equation');
const EquationStatus = require('./EquationStatus');
const MathChangeTypes = require('./MathChangeTypes');
const Negative = require('./Negative');
const NodeCreator = require('./NodeCreator');
const NodeType = require('./NodeType');
const PolynomialTermNode = require('./PolynomialTermNode');
const Symbols = require('./Symbols');

const COMPARATOR_TO_INVERSE = {
  '>': '<',
  '>=': '<=',
  '<': '>',
  '<=': '>=',
  '=': '='
};

const EquationOperations = {};

// Ensures that the given equation has the given symbolName on the left side,
// by swapping the right and left sides if it is only in the right side.
// So 3 = x would become x = 3.
EquationOperations.ensureSymbolInLeftNode = function(equation, symbolName) {
  const leftSideSymbolTerm = Symbols.getLastSymbolTerm(
    equation.leftNode, symbolName);
  const rightSideSymbolTerm = Symbols.getLastSymbolTerm(
    equation.rightNode, symbolName);

  if (!leftSideSymbolTerm) {
    if (rightSideSymbolTerm) {
      const oldEquation = equation;
      const newEquation = new Equation(
        equation.rightNode, equation.leftNode, equation.comparator);
      // no change groups are set for this step because everything changes, so
      // they wouldn't be pedagogically helpful.
      return new EquationStatus(
        MathChangeTypes.SWAP_SIDES, oldEquation, newEquation);
    }
    else {
      throw Error('No term with symbol: ' + symbolName);
    }
  }
  return EquationStatus.noChange(equation);
};

// TODO: Ensures that a symbol is not in the denominator by multiplying
// both sides by the whatever order of the symbol necessary.
// This is blocked on the simplifying functionality of canceling symbols in
// fractions (needs factoring for full canceling support)
EquationOperations.removeSymbolFromDenominator = function(equation) {
  // pass for now
  return EquationStatus.noChange(equation);
};

// Removes the given symbolName from the right side by adding or subtracting
// it from both sides as appropriate.
// e.g. 2x = 3x + 5 --> 2x - 3x = 5
// There are actually no cases where we'd remove symbols from the right side
// by multiplying or dividing by a symbol term.
// TODO: support inverting functions e.g. sqrt, ^, log etc.
EquationOperations.removeSymbolFromRightSide = function(equation, symbolName) {
  const rightNode = equation.rightNode;
  let symbolTerm = Symbols.getLastSymbolTerm(rightNode, symbolName);

  let inverseOp, inverseTerm, changeType;
  if (!symbolTerm){
    return EquationStatus.noChange(equation);
  }

  // Clone it so that any operations on it don't affect the node already
  // in the equation
  symbolTerm = clone(symbolTerm);

  if (PolynomialTermNode.isPolynomialTerm(rightNode)) {
    if (Negative.isNegative(symbolTerm)) {
      inverseOp = '+';
      changeType = MathChangeTypes.ADD_TO_BOTH_SIDES;
      inverseTerm = Negative.negate(symbolTerm);
    }
    else {
      inverseOp = '-';
      changeType = MathChangeTypes.SUBTRACT_FROM_BOTH_SIDES;
      inverseTerm = symbolTerm;
    }
  }
  else if (NodeType.isOperator(rightNode)) {
    if (rightNode.op === '+') {
      if (Negative.isNegative(symbolTerm)) {
        inverseOp = '+';
        changeType = MathChangeTypes.ADD_TO_BOTH_SIDES;
        inverseTerm = Negative.negate(symbolTerm);
      }
      else {
        inverseOp = '-';
        changeType = MathChangeTypes.SUBTRACT_FROM_BOTH_SIDES;
        inverseTerm = symbolTerm;
      }
    }
    else {
      // Note that operator '-' won't show up here because subtraction is
      // flattened into adding the negative. See 'TRICKY catch' in the README
      // for more details.
      throw Error('Unsupported operation: ' + symbolTerm.op);
    }
  }
  else if (NodeType.isUnaryMinus(rightNode)) {
    inverseOp = '+';
    changeType = MathChangeTypes.ADD_TO_BOTH_SIDES;
    inverseTerm = symbolTerm.args[0];
  }
  else {
    throw Error('Unsupported node type: ' + rightNode.type);
  }
  return performTermOperationOnEquation(
      equation, inverseOp, inverseTerm, changeType);
};

// Isolates the given symbolName to the left side by adding, multiplying, subtracting
// or dividing all other symbols and constants from both sides appropriately
// TODO: support inverting functions e.g. sqrt, ^, log etc.
EquationOperations.isolateSymbolOnLeftSide = function(equation, symbolName) {
  const leftNode = equation.leftNode;
  let nonSymbolTerm = Symbols.getLastNonSymbolTerm(leftNode, symbolName);

  let inverseOp, inverseTerm, changeType;
  if (!nonSymbolTerm) {
    return EquationStatus.noChange(equation);
  }

  // Clone it so that any operations on it don't affect the node already
  // in the equation
  nonSymbolTerm = clone(nonSymbolTerm);

  if (NodeType.isOperator(leftNode)) {
    if (leftNode.op === '+') {
      if (Negative.isNegative(nonSymbolTerm)) {
        inverseOp = '+';
        changeType = MathChangeTypes.ADD_TO_BOTH_SIDES;
        inverseTerm = Negative.negate(nonSymbolTerm);
      }
      else {
        inverseOp = '-';
        changeType = MathChangeTypes.SUBTRACT_FROM_BOTH_SIDES;
        inverseTerm = nonSymbolTerm;
      }
    }
    else if (leftNode.op === '*') {
      if (NodeType.isConstantFraction(nonSymbolTerm)) {
        inverseOp = '*';
        changeType = MathChangeTypes.MULTIPLY_BOTH_SIDES_BY_INVERSE_FRACTION;
        inverseTerm = NodeCreator.operator(
          '/', [nonSymbolTerm.args[1], nonSymbolTerm.args[0]]);
      }
      else {
        inverseOp = '/';
        changeType = MathChangeTypes.DIVIDE_FROM_BOTH_SIDES;
        inverseTerm = nonSymbolTerm;
      }
    }
    else if (leftNode.op === '/') {
      // The non symbol term is always a fraction because it's the
      // coefficient of our symbol term.
      // If the numerator is 1, we multiply both sides by the denominator,
      // otherwise we multiply by the inverse
      if (['1', '-1'].indexOf(nonSymbolTerm.args[0].value) !== -1) {
        inverseOp = '*';
        changeType = MathChangeTypes.MULTIPLY_TO_BOTH_SIDES;
        inverseTerm = nonSymbolTerm.args[1];
      }
      else {
        inverseOp = '*';
        changeType = MathChangeTypes.MULTIPLY_BOTH_SIDES_BY_INVERSE_FRACTION;
        inverseTerm = NodeCreator.operator(
          '/', [nonSymbolTerm.args[1], nonSymbolTerm.args[0]]);
      }
    }
    else if (leftNode.op === '^') {
      // TODO: support roots
      return EquationStatus.noChange(equation);
    }
    else {
      throw Error('Unsupported operation: ' + leftNode.op);
    }
  }
  else if (NodeType.isUnaryMinus(leftNode)) {
    inverseOp = '*';
    changeType = MathChangeTypes.MULTIPLY_BOTH_SIDES_BY_NEGATIVE_ONE;
    inverseTerm =  NodeCreator.constant(-1);
  }
  else {
    throw Error('Unsupported node type: ' + leftNode.type);
  }

  return performTermOperationOnEquation(
      equation, inverseOp, inverseTerm, changeType);
};

// Modifies the left and right sides of an equation by `op`-ing `term`
// to both sides. Returns an EquationStatus object.
function performTermOperationOnEquation(equation, op, term, changeType) {
  const oldEquation = equation.clone();

  const leftTerm = clone(term);
  const rightTerm = clone(term);
  let leftNode = performTermOperationOnExpression(
    equation.leftNode, op, leftTerm);
  let rightNode = performTermOperationOnExpression(
    equation.rightNode, op, rightTerm);

  let comparator = equation.comparator;
  if (Negative.isNegative(term) && (op === '*' || op === '/')) {
    comparator = COMPARATOR_TO_INVERSE[comparator];
  }

  const newEquation = new Equation(leftNode, rightNode, comparator);
  return new EquationStatus(changeType, oldEquation, newEquation);
}

// Performs an operation of a term on an entire given expression
function performTermOperationOnExpression(expression, op, term) {
  let node = (NodeType.isOperator(expression) ?
    NodeCreator.parenthesis(expression) : expression);

  term.changeGroup = 1;
  const newNode = NodeCreator.operator(op, [node, term]);

  return newNode;
}

module.exports = EquationOperations;
<commit_msg>flipping the comparator when swapping sides<commit_after>'use strict';
// Operations on equation nodes

const clone = require('./clone');
const Equation = require('./Equation');
const EquationStatus = require('./EquationStatus');
const MathChangeTypes = require('./MathChangeTypes');
const Negative = require('./Negative');
const NodeCreator = require('./NodeCreator');
const NodeType = require('./NodeType');
const PolynomialTermNode = require('./PolynomialTermNode');
const Symbols = require('./Symbols');

const COMPARATOR_TO_INVERSE = {
  '>': '<',
  '>=': '<=',
  '<': '>',
  '<=': '>=',
  '=': '='
};

const EquationOperations = {};

// Ensures that the given equation has the given symbolName on the left side,
// by swapping the right and left sides if it is only in the right side.
// So 3 = x would become x = 3.
EquationOperations.ensureSymbolInLeftNode = function(equation, symbolName) {
  const leftSideSymbolTerm = Symbols.getLastSymbolTerm(
    equation.leftNode, symbolName);
  const rightSideSymbolTerm = Symbols.getLastSymbolTerm(
    equation.rightNode, symbolName);

  if (!leftSideSymbolTerm) {
    if (rightSideSymbolTerm) {
      const comparator = COMPARATOR_TO_INVERSE[equation.comparator];
      const oldEquation = equation;
      const newEquation = new Equation(
        equation.rightNode, equation.leftNode, comparator);
      // no change groups are set for this step because everything changes, so
      // they wouldn't be pedagogically helpful.
      return new EquationStatus(
        MathChangeTypes.SWAP_SIDES, oldEquation, newEquation);
    }
    else {
      throw Error('No term with symbol: ' + symbolName);
    }
  }
  return EquationStatus.noChange(equation);
};

// TODO: Ensures that a symbol is not in the denominator by multiplying
// both sides by the whatever order of the symbol necessary.
// This is blocked on the simplifying functionality of canceling symbols in
// fractions (needs factoring for full canceling support)
EquationOperations.removeSymbolFromDenominator = function(equation) {
  // pass for now
  return EquationStatus.noChange(equation);
};

// Removes the given symbolName from the right side by adding or subtracting
// it from both sides as appropriate.
// e.g. 2x = 3x + 5 --> 2x - 3x = 5
// There are actually no cases where we'd remove symbols from the right side
// by multiplying or dividing by a symbol term.
// TODO: support inverting functions e.g. sqrt, ^, log etc.
EquationOperations.removeSymbolFromRightSide = function(equation, symbolName) {
  const rightNode = equation.rightNode;
  let symbolTerm = Symbols.getLastSymbolTerm(rightNode, symbolName);

  let inverseOp, inverseTerm, changeType;
  if (!symbolTerm){
    return EquationStatus.noChange(equation);
  }

  // Clone it so that any operations on it don't affect the node already
  // in the equation
  symbolTerm = clone(symbolTerm);

  if (PolynomialTermNode.isPolynomialTerm(rightNode)) {
    if (Negative.isNegative(symbolTerm)) {
      inverseOp = '+';
      changeType = MathChangeTypes.ADD_TO_BOTH_SIDES;
      inverseTerm = Negative.negate(symbolTerm);
    }
    else {
      inverseOp = '-';
      changeType = MathChangeTypes.SUBTRACT_FROM_BOTH_SIDES;
      inverseTerm = symbolTerm;
    }
  }
  else if (NodeType.isOperator(rightNode)) {
    if (rightNode.op === '+') {
      if (Negative.isNegative(symbolTerm)) {
        inverseOp = '+';
        changeType = MathChangeTypes.ADD_TO_BOTH_SIDES;
        inverseTerm = Negative.negate(symbolTerm);
      }
      else {
        inverseOp = '-';
        changeType = MathChangeTypes.SUBTRACT_FROM_BOTH_SIDES;
        inverseTerm = symbolTerm;
      }
    }
    else {
      // Note that operator '-' won't show up here because subtraction is
      // flattened into adding the negative. See 'TRICKY catch' in the README
      // for more details.
      throw Error('Unsupported operation: ' + symbolTerm.op);
    }
  }
  else if (NodeType.isUnaryMinus(rightNode)) {
    inverseOp = '+';
    changeType = MathChangeTypes.ADD_TO_BOTH_SIDES;
    inverseTerm = symbolTerm.args[0];
  }
  else {
    throw Error('Unsupported node type: ' + rightNode.type);
  }
  return performTermOperationOnEquation(
      equation, inverseOp, inverseTerm, changeType);
};

// Isolates the given symbolName to the left side by adding, multiplying, subtracting
// or dividing all other symbols and constants from both sides appropriately
// TODO: support inverting functions e.g. sqrt, ^, log etc.
EquationOperations.isolateSymbolOnLeftSide = function(equation, symbolName) {
  const leftNode = equation.leftNode;
  let nonSymbolTerm = Symbols.getLastNonSymbolTerm(leftNode, symbolName);

  let inverseOp, inverseTerm, changeType;
  if (!nonSymbolTerm) {
    return EquationStatus.noChange(equation);
  }

  // Clone it so that any operations on it don't affect the node already
  // in the equation
  nonSymbolTerm = clone(nonSymbolTerm);

  if (NodeType.isOperator(leftNode)) {
    if (leftNode.op === '+') {
      if (Negative.isNegative(nonSymbolTerm)) {
        inverseOp = '+';
        changeType = MathChangeTypes.ADD_TO_BOTH_SIDES;
        inverseTerm = Negative.negate(nonSymbolTerm);
      }
      else {
        inverseOp = '-';
        changeType = MathChangeTypes.SUBTRACT_FROM_BOTH_SIDES;
        inverseTerm = nonSymbolTerm;
      }
    }
    else if (leftNode.op === '*') {
      if (NodeType.isConstantFraction(nonSymbolTerm)) {
        inverseOp = '*';
        changeType = MathChangeTypes.MULTIPLY_BOTH_SIDES_BY_INVERSE_FRACTION;
        inverseTerm = NodeCreator.operator(
          '/', [nonSymbolTerm.args[1], nonSymbolTerm.args[0]]);
      }
      else {
        inverseOp = '/';
        changeType = MathChangeTypes.DIVIDE_FROM_BOTH_SIDES;
        inverseTerm = nonSymbolTerm;
      }
    }
    else if (leftNode.op === '/') {
      // The non symbol term is always a fraction because it's the
      // coefficient of our symbol term.
      // If the numerator is 1, we multiply both sides by the denominator,
      // otherwise we multiply by the inverse
      if (['1', '-1'].indexOf(nonSymbolTerm.args[0].value) !== -1) {
        inverseOp = '*';
        changeType = MathChangeTypes.MULTIPLY_TO_BOTH_SIDES;
        inverseTerm = nonSymbolTerm.args[1];
      }
      else {
        inverseOp = '*';
        changeType = MathChangeTypes.MULTIPLY_BOTH_SIDES_BY_INVERSE_FRACTION;
        inverseTerm = NodeCreator.operator(
          '/', [nonSymbolTerm.args[1], nonSymbolTerm.args[0]]);
      }
    }
    else if (leftNode.op === '^') {
      // TODO: support roots
      return EquationStatus.noChange(equation);
    }
    else {
      throw Error('Unsupported operation: ' + leftNode.op);
    }
  }
  else if (NodeType.isUnaryMinus(leftNode)) {
    inverseOp = '*';
    changeType = MathChangeTypes.MULTIPLY_BOTH_SIDES_BY_NEGATIVE_ONE;
    inverseTerm =  NodeCreator.constant(-1);
  }
  else {
    throw Error('Unsupported node type: ' + leftNode.type);
  }

  return performTermOperationOnEquation(
      equation, inverseOp, inverseTerm, changeType);
};

// Modifies the left and right sides of an equation by `op`-ing `term`
// to both sides. Returns an EquationStatus object.
function performTermOperationOnEquation(equation, op, term, changeType) {
  const oldEquation = equation.clone();

  const leftTerm = clone(term);
  const rightTerm = clone(term);
  let leftNode = performTermOperationOnExpression(
    equation.leftNode, op, leftTerm);
  let rightNode = performTermOperationOnExpression(
    equation.rightNode, op, rightTerm);

  let comparator = equation.comparator;
  if (Negative.isNegative(term) && (op === '*' || op === '/')) {
    comparator = COMPARATOR_TO_INVERSE[comparator];
  }

  const newEquation = new Equation(leftNode, rightNode, comparator);
  return new EquationStatus(changeType, oldEquation, newEquation);
}

// Performs an operation of a term on an entire given expression
function performTermOperationOnExpression(expression, op, term) {
  let node = (NodeType.isOperator(expression) ?
    NodeCreator.parenthesis(expression) : expression);

  term.changeGroup = 1;
  const newNode = NodeCreator.operator(op, [node, term]);

  return newNode;
}

module.exports = EquationOperations;
<|endoftext|>


<commit_before>/**
 * @class
 */
OpenLayers.Feature = Class.create();
OpenLayers.Feature.prototype= {

    /** @type OpenLayers.Events */
    events:null,

    /** @type OpenLayers.Layer */
    layer: null,

    /** @type String */
    id: null,

    /** @type OpenLayers.LonLat */
    lonlat:null,

    /** @type Object */
    data:null,

    /** @type OpenLayers.Marker */
    marker: null,

    /** @type OpenLayers.Popup */
    popup: null,

    /**
     * @constructor
     *
     * @param {OpenLayers.Layer} layer
     * @param {String} id
     * @param {OpenLayers.LonLat} lonlat
     * @param {Object} data
     */
    initialize: function(layer, lonlat, data, id) {
        this.layer = layer;
        this.lonlat = lonlat;
        this.data = (data != null) ? data : new Object();
        this.id = (id ? id : 'f' + Math.random());
    },

    /**
     *
     */
    destroy: function() {
        this.events = null;
        this.layer = null;
        this.id = null;
        this.lonlat = null;
        this.data = null;
        if (this.marker != null) {
            this.marker.destroy();
            this.marker = null,
        }
        if (this.popup != null) {
            this.popup.destroy();
            this.popup = null;
        }
    },

    /**
     * @returns A Marker Object created from the 'lonlat' and 'icon' properties
     *          set in this.data. If no 'lonlat' is set, returns null. If no
     *          'icon' is set, OpenLayers.Marker() will load the default image
     * @type OpenLayers.Marker
     */
    createMarker: function() {

        var marker = null;

        if (this.lonlat != null) {
            this.marker = new OpenLayers.Marker(this.lonlat, this.data.icon);
        }
        return this.marker;
    },

    /**
     *
     */
    createPopup: function() {

        if (this.lonlat != null) {

            var id = this.id + "_popup";
            var anchor = (this.marker) ? this.marker.icon : null;

            this.popup = new OpenLayers.Popup.AnchoredBubble(id,
                                                    this.lonlat,
                                                    this.data.popupSize,
                                                    this.data.popupContentHTML,
                                                    anchor);
        }
        return this.popup;
    },

    CLASS_NAME: "OpenLayers.Feature"
};
<commit_msg>change , for ; from r502, fixes problems in FF after file is turned into single file version.<commit_after>/**
 * @class
 */
OpenLayers.Feature = Class.create();
OpenLayers.Feature.prototype= {

    /** @type OpenLayers.Events */
    events:null,

    /** @type OpenLayers.Layer */
    layer: null,

    /** @type String */
    id: null,

    /** @type OpenLayers.LonLat */
    lonlat:null,

    /** @type Object */
    data:null,

    /** @type OpenLayers.Marker */
    marker: null,

    /** @type OpenLayers.Popup */
    popup: null,

    /**
     * @constructor
     *
     * @param {OpenLayers.Layer} layer
     * @param {String} id
     * @param {OpenLayers.LonLat} lonlat
     * @param {Object} data
     */
    initialize: function(layer, lonlat, data, id) {
        this.layer = layer;
        this.lonlat = lonlat;
        this.data = (data != null) ? data : new Object();
        this.id = (id ? id : 'f' + Math.random());
    },

    /**
     *
     */
    destroy: function() {
        this.events = null;
        this.layer = null;
        this.id = null;
        this.lonlat = null;
        this.data = null;
        if (this.marker != null) {
            this.marker.destroy();
            this.marker = null;
        }
        if (this.popup != null) {
            this.popup.destroy();
            this.popup = null;
        }
    },

    /**
     * @returns A Marker Object created from the 'lonlat' and 'icon' properties
     *          set in this.data. If no 'lonlat' is set, returns null. If no
     *          'icon' is set, OpenLayers.Marker() will load the default image
     * @type OpenLayers.Marker
     */
    createMarker: function() {

        var marker = null;

        if (this.lonlat != null) {
            this.marker = new OpenLayers.Marker(this.lonlat, this.data.icon);
        }
        return this.marker;
    },

    /**
     *
     */
    createPopup: function() {

        if (this.lonlat != null) {

            var id = this.id + "_popup";
            var anchor = (this.marker) ? this.marker.icon : null;

            this.popup = new OpenLayers.Popup.AnchoredBubble(id,
                                                    this.lonlat,
                                                    this.data.popupSize,
                                                    this.data.popupContentHTML,
                                                    anchor);
        }
        return this.popup;
    },

    CLASS_NAME: "OpenLayers.Feature"
};
<|endoftext|>


<commit_before>/* Copyright (c) 2006-2008 MetaCarta, Inc., published under the Clear BSD
 * license.  See http://svn.openlayers.org/trunk/openlayers/license.txt for the
 * full text of the license. */

/**
 * @requires OpenLayers/Lang/en.js
 */

/**
 * Namespace: OpenLayers.Lang["de"]
 * Dictionary for German.  Keys for entries are used in calls to
 *     <OpenLayers.Lang.translate>.  Entry bodies are normal strings or
 *     strings formatted for use with <OpenLayers.String.format> calls.
 */
OpenLayers.Lang.de = OpenLayers.Util.applyDefaults({

    'unhandledRequest': "Unbehandelte Anfragerckmeldung ${statusText}",

    'permalink': "Permalink",

    'overlays': "Overlays",

    'baseLayer': "Grundkarte",

    'sameProjection':
        "Die bersichtskarte funktioniert nur, wenn sie dieselbe Projektion wie die Hauptkarte verwendet",

    'readNotImplemented': "Lesen nicht implementiert.",

    'writeNotImplemented': "Schreiben nicht implementiert.",

    'noFID': "Ein Feature, fr das keine FID existiert, kann nicht aktualisiert werden.",

    'errorLoadingGML': "Fehler beim Laden der GML-Datei ${url}",

    'browserNotSupported':
        "Ihr Browser untersttzt keine Vektordarstellung. Aktuell untersttzte Renderer:\n${renderers}",

    'componentShouldBe': "addFeatures : Komponente sollte vom Typ ${geomType} sein",

    'commitSuccess': "WFS-Transaktion: ERFOLGREICH ${response}",

    'commitFailed': "WFS-Transaktion: FEHLGESCHLAGEN ${response}",

    'googleWarning':
        "Der Google-Layer konnte nicht korrekt geladen werden.

" +
        "Um diese Meldung nicht mehr zu erhalten, whlen Sie einen anderen " +
        "Hintergrundlayer aus dem LayerSwitcher in der rechten oberen Ecke.

" +
        "Sehr wahrscheinlich tritt dieser Fehler auf, weil das Skript der " +
        "Google-Maps-Bibliothek nicht eingebunden wurde oder keinen gltigen " +
        "API-Schlssel fr Ihre URL enthlt.

" +
        "Entwickler: Fr Hilfe zum korrekten Einbinden des Google-Layers " +
        "hier klicken",

    'getLayerWarning':
        "Der ${layerType}-Layer konnte nicht korrekt geladen werden.

" +
        "Um diese Meldung nicht mehr zu erhalten, whlen Sie einen anderen " +
        "Hintergrundlayer aus dem LayerSwitcher in der rechten oberen Ecke.

" +
        "Sehr wahrscheinlich tritt dieser Fehler auf, weil das Skript der " +
        '"${layerLib}"-Bibliothek nicht eingebunden wurde.

' +
        "Entwickler: Fr Hilfe zum korrekten Einbinden von Layern " +
        "hier klicken",

    'scale': "Mastab = 1 : ${scaleDenom}",

    'end': ''
}, OpenLayers.Lang["en"]);
<commit_msg>converting encoding to UTF-8<commit_after>/* Copyright (c) 2006-2008 MetaCarta, Inc., published under the Clear BSD
 * license.  See http://svn.openlayers.org/trunk/openlayers/license.txt for the
 * full text of the license. */

/**
 * @requires OpenLayers/Lang/en.js
 */

/**
 * Namespace: OpenLayers.Lang["de"]
 * Dictionary for German.  Keys for entries are used in calls to
 *     <OpenLayers.Lang.translate>.  Entry bodies are normal strings or
 *     strings formatted for use with <OpenLayers.String.format> calls.
 */
OpenLayers.Lang.de = OpenLayers.Util.applyDefaults({

    'unhandledRequest': "Unbehandelte Anfragerückmeldung ${statusText}",

    'permalink': "Permalink",

    'overlays': "Overlays",

    'baseLayer': "Grundkarte",

    'sameProjection':
        "Die Übersichtskarte funktioniert nur, wenn sie dieselbe Projektion wie die Hauptkarte verwendet",

    'readNotImplemented': "Lesen nicht implementiert.",

    'writeNotImplemented': "Schreiben nicht implementiert.",

    'noFID': "Ein Feature, für das keine FID existiert, kann nicht aktualisiert werden.",

    'errorLoadingGML': "Fehler beim Laden der GML-Datei ${url}",

    'browserNotSupported':
        "Ihr Browser unterstützt keine Vektordarstellung. Aktuell unterstützte Renderer:\n${renderers}",

    'componentShouldBe': "addFeatures : Komponente sollte vom Typ ${geomType} sein",

    'commitSuccess': "WFS-Transaktion: ERFOLGREICH ${response}",

    'commitFailed': "WFS-Transaktion: FEHLGESCHLAGEN ${response}",

    'googleWarning':
        "Der Google-Layer konnte nicht korrekt geladen werden.

" +
        "Um diese Meldung nicht mehr zu erhalten, wählen Sie einen anderen " +
        "Hintergrundlayer aus dem LayerSwitcher in der rechten oberen Ecke.

" +
        "Sehr wahrscheinlich tritt dieser Fehler auf, weil das Skript der " +
        "Google-Maps-Bibliothek nicht eingebunden wurde oder keinen gültigen " +
        "API-Schlüssel für Ihre URL enthält.

" +
        "Entwickler: Für Hilfe zum korrekten Einbinden des Google-Layers " +
        "hier klicken",

    'getLayerWarning':
        "Der ${layerType}-Layer konnte nicht korrekt geladen werden.

" +
        "Um diese Meldung nicht mehr zu erhalten, wählen Sie einen anderen " +
        "Hintergrundlayer aus dem LayerSwitcher in der rechten oberen Ecke.

" +
        "Sehr wahrscheinlich tritt dieser Fehler auf, weil das Skript der " +
        '"${layerLib}"-Bibliothek nicht eingebunden wurde.

' +
        "Entwickler: Für Hilfe zum korrekten Einbinden von Layern " +
        "hier klicken",

    'scale': "Maßstab = 1 : ${scaleDenom}",

    'end': ''
}, OpenLayers.Lang["en"]);
<|endoftext|>


<commit_before>/* @flow */
export default function composeEventHandlers(...handlers: Array<any>) {
  const fns = handlers.filter((fn) => Boolean(fn));

  if (fns.length === 0) {
    return undefined;
  } else if (fns.length === 1) {
    return fns[0];
  } else {
    return (event: Object, ...args: Array<any>) => {
      return fns.some((fn) => {
        fn(event, ...args);
        return event.nativeEvent.preventMineralDefault;
      });
    };
  }
}
<commit_msg>refactor(utils): Update composeEventHandlers<commit_after>/* @flow */
export default function composeEventHandlers(...handlers: Array<any>) {
  const fns = handlers.filter((fn) => Boolean(fn));

  if (fns.length === 0) {
    return undefined;
  } else if (fns.length === 1) {
    return fns[0];
  } else {
    return (event: Object, ...args: Array<any>) => {
      let prevented = false;
      return fns.forEach((fn) => {
        if (!prevented) {
          fn(event, ...args);
          prevented = event.nativeEvent.preventMineralDefault;
        }
      });
    };
  }
}
<|endoftext|>


<commit_before>var map;
var service;
var actualPosition;
var markers = [];
var defaultMarkerColor = "FE7569";
var somePlaceIsSelected = false;

function initMap() {
    var myLatLng = {lat: 52.54063980000001, lng: -1.8916148000000703};
    var mapDiv = document.getElementById('map');
    map = new google.maps.Map(mapDiv, {
        center: myLatLng,
        zoom: 16
    });

    var infoWindow = new google.maps.InfoWindow({map: map});

    // Try HTML5 geolocation.
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function(position) {
            actualPosition = {
                lat: position.coords.latitude,
                lng: position.coords.longitude
            };
            createMarkerOnMap(actualPosition, "Vaše poloha", "FFFFFF")

            map.setCenter(actualPosition);
            console.log("map initialized");

            document.getElementById('radius-input').addEventListener('change', getNearbyLocations);
            getNearbyLocations();
        }, function() {
            handleLocationError(true, infoWindow, map.getCenter());
        });
    } else {
        // Browser doesn't support Geolocation
        handleLocationError(false, infoWindow, map.getCenter());
    }
}

function handleLocationError(browserHasGeolocation, infoWindow, pos) {
    infoWindow.setPosition(pos);
    infoWindow.setContent(browserHasGeolocation ?
        'Error: The Geolocation service failed.' :
        'Error: Your browser doesn\'t support geolocation.');
}

function getNearbyLocations() {
    for( var i = 0; i < markers.length; i++ ) {
        markers[i].setMap(null);
    }
    markers = [];
    var request = {
        location: actualPosition,
        radius: document.getElementById('radius-input').value,
        types: ['restaurant', 'food'],
    };
    service = new google.maps.places.PlacesService(map);
    service.nearbySearch(request, markNearbyPlaces);
}

function markNearbyPlaces(results, status) {
    if (status == google.maps.places.PlacesServiceStatus.OK) {
        var userId = localStorage.getItem("id");
        var userPlaces;
        if(userId != null && userId != undefined){
            makeCorsRequest("GET", "https://ivebeenthereapi-matyapav.rhcloud.com/userPlaces/"+userId, null, function (responseText) {
                if(responseText){
                    userPlaces = JSON.parse(responseText);
                }
                results.forEach(function (v,i) {
                    var place = results[i];
                    var marker = null;
                    var color = null;
                    var clickedColor = null;
                    userPlaces.forEach(function (userPlace) {
                        if(userPlace != null) {
                            if (encodeURIComponent(userPlace.name) == encodeURIComponent(place.name)) {
                                color = "00ff00";
                                clickedColor = "006400";
                            }else{
                                color = defaultMarkerColor;
                                clickedColor = "7f3a34";
                            }
                            marker = createMarkerOnMap(place.geometry.location, place.name, color);
                        }
                    });
                    if(marker != null && color != null && clickedColor != null){
                        markers.push({placeName: place.name, marker: marker, color: color});
                        marker.addListener('click', function(){
                            markers.forEach(function (v,i) {
                                setMarkerColor(markers[i].marker, markers[i].color);
                            });
                            setMarkerColor(marker, clickedColor)
                            showInfoAboutPlace(place);
                        });
                    }
                });
            });
        }else{
            results.forEach(function (v,i) {
                var place = results[i];
                var marker = createMarkerOnMap(place.geometry.location, place.name, defaultMarkerColor );
                markers.push({placeName: place.name, marker: marker});
                marker.addListener('click', function(){
                    markers.forEach(function (v,i) {
                        setMarkerColor(markers[i].marker, defaultMarkerColor)
                    });
                    setMarkerColor(marker, "7f3a34")
                    showInfoAboutPlace(place);
                });
            });
        }
    }
}

function createMarkerOnMap(position, title, pinColor) {
    var pinImage = new google.maps.MarkerImage("https://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|" + pinColor,
        new google.maps.Size(21, 34),
        new google.maps.Point(0, 0),
        new google.maps.Point(10, 34));
    var pinShadow = new google.maps.MarkerImage("https://chart.apis.google.com/chart?chst=d_map_pin_shadow",
        new google.maps.Size(40, 37),
        new google.maps.Point(0, 0),
        new google.maps.Point(12, 35));

    var marker = new google.maps.Marker({
        position: position,
        map: map,
        icon: pinImage,
        shadow: pinShadow,
        title: title
    });
    return marker;
}

function showInfoAboutPlace(place){

    document.getElementById('place-name').innerText = place.name;
    document.getElementById('place-address').innerText = place.vicinity;
    if(place.opening_hours != null){
        document.getElementById('place-open').innerText = place.opening_hours.open_now? 'Ano':'Ne';
    }else{
        document.getElementById('place-open').innerText = "-";
    }

    document.getElementById('actions').style = "visibility: visible";

    somePlaceIsSelected = true;
    console.log(place)
    document.getElementById('iwasthere').addEventListener('click', function () {
        var placeObj = {name: place.name, address: place.vicinity};
        userId = localStorage.getItem("id");
        markPlaceForUser(placeObj, userId);
    })
}

function setMarkerColor(marker, color) {
    marker.setIcon(new google.maps.MarkerImage("https://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|"+color ,
        new google.maps.Size(21, 34),
        new google.maps.Point(0, 0),
        new google.maps.Point(10, 34)));
}<commit_msg>Implementing "I was there" action #18<commit_after>var map;
var service;
var actualPosition;
var markers = [];
var defaultMarkerColor = "FE7569";
var somePlaceIsSelected = false;

function initMap() {
    var myLatLng = {lat: 52.54063980000001, lng: -1.8916148000000703};
    var mapDiv = document.getElementById('map');
    map = new google.maps.Map(mapDiv, {
        center: myLatLng,
        zoom: 16
    });

    var infoWindow = new google.maps.InfoWindow({map: map});

    // Try HTML5 geolocation.
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function(position) {
            actualPosition = {
                lat: position.coords.latitude,
                lng: position.coords.longitude
            };
            createMarkerOnMap(actualPosition, "Vaše poloha", "FFFFFF")

            map.setCenter(actualPosition);
            console.log("map initialized");

            document.getElementById('radius-input').addEventListener('change', getNearbyLocations);
            getNearbyLocations();
        }, function() {
            handleLocationError(true, infoWindow, map.getCenter());
        });
    } else {
        // Browser doesn't support Geolocation
        handleLocationError(false, infoWindow, map.getCenter());
    }
}

function handleLocationError(browserHasGeolocation, infoWindow, pos) {
    infoWindow.setPosition(pos);
    infoWindow.setContent(browserHasGeolocation ?
        'Error: The Geolocation service failed.' :
        'Error: Your browser doesn\'t support geolocation.');
}

function getNearbyLocations() {
    for( var i = 0; i < markers.length; i++ ) {
        markers[i].marker.setMap(null);
    }
    markers = [];
    var request = {
        location: actualPosition,
        radius: document.getElementById('radius-input').value,
        types: ['restaurant'],
    };
    service = new google.maps.places.PlacesService(map);
    service.nearbySearch(request, markNearbyPlaces);
}

function markNearbyPlaces(results, status) {
    if (status == google.maps.places.PlacesServiceStatus.OK) {
        var userId = localStorage.getItem("id");
        var userPlaces;
        if(userId != null && userId != undefined){
            makeCorsRequest("GET", "https://ivebeenthereapi-matyapav.rhcloud.com/userPlaces/"+userId, null, function (responseText) {
                if(responseText){
                    userPlaces = JSON.parse(responseText);
                }
                results.forEach(function (v,i) {
                    var place = results[i];
                    var marker = null;
                    var color = null;
                    var clickedColor = null;
                    userPlaces.forEach(function (userPlace) {
                        if(userPlace != null) {
                            if (encodeURIComponent(userPlace.name) == encodeURIComponent(place.name)) {
                                color = "00ff00";
                                clickedColor = "006400";
                            }else{
                                color = defaultMarkerColor;
                                clickedColor = "7f3a34";
                            }
                            marker = createMarkerOnMap(place.geometry.location, place.name, color);
                        }
                    });
                    if(marker != null && color != null && clickedColor != null){
                        markers.push({placeName: place.name, marker: marker, color: color});
                        marker.addListener('click', function(){
                            markers.forEach(function (v,i) {
                                setMarkerColor(markers[i].marker, markers[i].color);
                            });
                            setMarkerColor(marker, clickedColor)
                            showInfoAboutPlace(place);
                        });
                    }
                });
            });
        }else{
            results.forEach(function (v,i) {
                var place = results[i];
                var marker = createMarkerOnMap(place.geometry.location, place.name, defaultMarkerColor );
                markers.push({placeName: place.name, marker: marker});
                marker.addListener('click', function(){
                    markers.forEach(function (v,i) {
                        setMarkerColor(markers[i].marker, defaultMarkerColor)
                    });
                    setMarkerColor(marker, "7f3a34")
                    showInfoAboutPlace(place);
                });
            });
        }
    }
}

function createMarkerOnMap(position, title, pinColor) {
    var pinImage = new google.maps.MarkerImage("https://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|" + pinColor,
        new google.maps.Size(21, 34),
        new google.maps.Point(0, 0),
        new google.maps.Point(10, 34));
    var pinShadow = new google.maps.MarkerImage("https://chart.apis.google.com/chart?chst=d_map_pin_shadow",
        new google.maps.Size(40, 37),
        new google.maps.Point(0, 0),
        new google.maps.Point(12, 35));

    var marker = new google.maps.Marker({
        position: position,
        map: map,
        icon: pinImage,
        shadow: pinShadow,
        title: title
    });
    return marker;
}

function showInfoAboutPlace(place){

    document.getElementById('place-name').innerText = place.name;
    document.getElementById('place-address').innerText = place.vicinity;
    if(place.opening_hours != null){
        document.getElementById('place-open').innerText = place.opening_hours.open_now? 'Ano':'Ne';
    }else{
        document.getElementById('place-open').innerText = "-";
    }

    document.getElementById('actions').style = "visibility: visible";

    somePlaceIsSelected = true;
    console.log(place)
    document.getElementById('iwasthere').addEventListener('click', function () {
        var placeObj = {name: place.name, address: place.vicinity};
        userId = localStorage.getItem("id");
        markPlaceForUser(placeObj, userId);
    })
}

function setMarkerColor(marker, color) {
    marker.setIcon(new google.maps.MarkerImage("https://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|"+color ,
        new google.maps.Size(21, 34),
        new google.maps.Point(0, 0),
        new google.maps.Point(10, 34)));
}<|endoftext|>


<commit_before>GameBoyAdvanceMMU = function() {
	this.REGION_BIOS = 0x0;
	this.REGION_WORKING_RAM = 0x2;
	this.REGION_WORKING_IRAM = 0x3;
	this.REGION_IO = 0x4;
	this.REGION_PALETTE_RAM = 0x5;
	this.REGION_VRAM = 0x6;
	this.REGION_OAM = 0x7;
	this.REGION_CART0 = 0x8;
	this.REGION_CART1 = 0xA;
	this.REGION_CART2 = 0xC;
	this.REGION_CART_SRAM = 0xE;

	this.BASE_BIOS = 0x00000000;
	this.BASE_WORKING_RAM = 0x02000000;
	this.BASE_WORKING_IRAM = 0x03000000;
	this.BASE_IO = 0x04000000;
	this.BASE_PALETTE_RAM = 0x05000000;
	this.BASE_VRAM = 0x06000000;
	this.BASE_OAM = 0x07000000;
	this.BASE_CART0 = 0x08000000;
	this.BASE_CART1 = 0x0A000000;
	this.BASE_CART2 = 0x0C000000;
	this.BASE_CART_SRAM = 0x0E000000;

	this.BASE_MASK = 0x0F000000;
	this.BASE_OFFSET = 24;

	this.SIZE_BIOS = 0x00004000;
	this.SIZE_WORKING_RAM = 0x00040000;
	this.SIZE_WORKING_IRAM = 0x00008000;
	this.SIZE_IO = 0x00000400;
	this.SIZE_PALETTE_RAM = 0x00000400;
	this.SIZE_VRAM = 0x00018000;
	this.SIZE_OAM = 0x00000400;
	this.SIZE_CART0 = 0x02000000;
	this.SIZE_CART1 = 0x02000000;
	this.SIZE_CART2 = 0x02000000;
	this.SIZE_CART_SRAM = 0x00010000;

	this.TIMINGS_8 = [
		1,
		0,
		1,
		3,
		1,
		1,
		1,
		1,
		5,
		0,
		5,
		0,
		5,
		0
	];

	this.TIMINGS_16 = [
		1,
		0,
		1,
		3,
		1,
		1,
		1,
		1,
		5,
		0,
		5,
		0,
		5,
		0
	];

	this.TIMINGS_32 = [
		1,
		0,
		1,
		6,
		1,
		2,
		2,
		1,
		8,
		0,
		8,
		0,
		8,
		0
	];
};

GameBoyAdvanceMMU.prototype.setCPU = function(cpu) {
	this.cpu = cpu;
}

GameBoyAdvanceMMU.prototype.setIO = function(io) {
	this.io = io;
	io.setMMU(this);
}

GameBoyAdvanceMMU.prototype.clear = function() {
	this.memory = [
		null,
		null, // Unused
		new ArrayBuffer(this.SIZE_WORKING_RAM),
		new ArrayBuffer(this.SIZE_WORKING_IRAM),
		null, // This is owned by GameBoyAdvanceIO
		new ArrayBuffer(this.SIZE_PALETTE_RAM),
		new ArrayBuffer(this.SIZE_VRAM),
		new ArrayBuffer(this.SIZE_OAM),
		null,
		null, // Unused
		null,
		null, // Unused
		null,
		null, // Unused
		null,
		null // Unused
	];

	this.memoryView = [
		null,
		null, // Unused
		new DataView(this.memory[2]),
		new DataView(this.memory[3]),
		null,
		new DataView(this.memory[5]),
		new DataView(this.memory[6]),
		new DataView(this.memory[7]),
		null,
		null, // Unused
		null,
		null, // Unused
		null,
		null, // Unused
		null,
		null // Unused
	];

	this.memoryView[2].cachedInstructions = 0;
	this.memoryView[3].cachedInstructions = 0;
	this.memoryView[5].cachedInstructions = 0;
	this.memoryView[6].cachedInstructions = 0;
	this.memoryView[7].cachedInstructions = 0;

	this.icache = [
		null,
		null, // Unused
		new Array(this.SIZE_WORKING_RAM >> 1),
		new Array(this.SIZE_WORKING_IRAM >> 1),
		null,
		null,
		null,
		null,
		null,
		null, // Unusued
		null,
		null, // Unusued
		null,
		null // Unused
	];
};

GameBoyAdvanceMMU.prototype.loadRom = function(rom) {
	this.memory[this.REGION_CART0] = rom;
	this.memory[this.REGION_CART1] = rom;
	this.memory[this.REGION_CART2] = rom;
	var view = new DataView(rom);
	this.memoryView[this.REGION_CART0] = view;
	this.memoryView[this.REGION_CART1] = view;
	this.memoryView[this.REGION_CART2] = view;

	var icache = new Array(rom.byteLength >> 1);
	this.icache[this.REGION_CART0] = icache;
	this.icache[this.REGION_CART1] = icache;
	this.icache[this.REGION_CART2] = icache;
};

GameBoyAdvanceMMU.prototype.maskOffset = function(offset) {
	if (offset < this.BASE_CART0) {
		return offset & 0x00FFFFFF;
	} else {
		return offset & 0x01FFFFFF;
	}
};

GameBoyAdvanceMMU.prototype.load8 = function(offset) {
	var memoryRegion = this.getMemoryRegion(offset);
	this.cpu.cycles += this.TIMINGS_8[memoryRegion];
	if (memoryRegion == this.REGION_IO) {
		return this.io.load8(offset & 0x00FFFFFF);
	}
	return this.memoryView[memoryRegion].getInt8(this.maskOffset(offset));
};

GameBoyAdvanceMMU.prototype.load16 = function(offset) {
	var memoryRegion = this.getMemoryRegion(offset);
	this.cpu.cycles += this.TIMINGS_16[memoryRegion];
	if (memoryRegion == this.REGION_IO) {
		return this.io.load16(offset & 0x00FFFFFE);
	}
	return this.memoryView[memoryRegion].getInt16(this.maskOffset(offset), true);
};

GameBoyAdvanceMMU.prototype.load32 = function(offset) {
	var memoryRegion = this.getMemoryRegion(offset);
	this.cpu.cycles += this.TIMINGS_32[memoryRegion];
	if (memoryRegion == this.REGION_IO) {
		return this.io.load32(offset & 0x00FFFFFC);
	}
	return this.memoryView[memoryRegion].getInt32(this.maskOffset(offset), true);
};

GameBoyAdvanceMMU.prototype.loadU8 = function(offset) {
	var memoryRegion = this.getMemoryRegion(offset);
	this.cpu.cycles += this.TIMINGS_8[memoryRegion];
	if (memoryRegion == this.REGION_IO) {
		return this.io.loadU8(offset & 0x00FFFFFF);
	}
	return this.memoryView[memoryRegion].getUint8(this.maskOffset(offset));
};

GameBoyAdvanceMMU.prototype.loadU16 = function(offset) {
	var memoryRegion = this.getMemoryRegion(offset);
	this.cpu.cycles += this.TIMINGS_32[memoryRegion];
	if (memoryRegion == this.REGION_IO) {
		return this.io.loadU16(offset & 0x00FFFFFE);
	}
	return this.memoryView[memoryRegion].getUint16(this.maskOffset(offset), true);
};

// Instruction loads -- don't affect timings
GameBoyAdvanceMMU.prototype.iload16 = function(offset) {
	var memoryRegion = this.getMemoryRegion(offset);
	return this.memoryView[memoryRegion].getUint16(this.maskOffset(offset), true);
};

GameBoyAdvanceMMU.prototype.iload32 = function(offset) {
	var memoryRegion = this.getMemoryRegion(offset);
	return this.memoryView[memoryRegion].getInt32(this.maskOffset(offset), true);
};

GameBoyAdvanceMMU.prototype.store8 = function(offset, value) {
	var memoryRegion = this.getMemoryRegion(offset);
	if (memoryRegion >= this.REGION_ROM0) {
		throw "Bad access";
	}
	this.cpu.cycles += this.TIMINGS_8[memoryRegion];
	var maskedOffset = offset & 0x00FFFFFF;
	if (memoryRegion == this.REGION_IO) {
		this.io.store8(maskedOffset, value);
		return;
	}
	var memory = this.memoryView[memoryRegion];
	memory.setInt8(maskedOffset, value);
	if (memory.cachedInstructions) {
		delete this.icache[maskedOffset >> 1];
	}
};

GameBoyAdvanceMMU.prototype.store16 = function(offset, value) {
	var memoryRegion = this.getMemoryRegion(offset);
	if (memoryRegion >= this.REGION_ROM0) {
		throw "Bad access";
	}
	this.cpu.cycles += this.TIMINGS_16[memoryRegion];
	var maskedOffset = offset & 0x00FFFFFE;
	if (memoryRegion == this.REGION_IO) {
		this.io.store16(maskedOffset, value);
		return;
	}
	var memory = this.memoryView[memoryRegion];
	memory.setInt16(maskedOffset, value, true);
	if (memory.cachedInstructions) {
		delete this.icache[maskedOffset >> 1];
	}
};

GameBoyAdvanceMMU.prototype.store32 = function(offset, value) {
	var memoryRegion = this.getMemoryRegion(offset);
	if (memoryRegion >= this.REGION_ROM0) {
		throw "Bad access";
	}
	this.cpu.cycles += this.TIMINGS_32[memoryRegion];
	var maskedOffset = offset & 0x00FFFFFC;
	if (memoryRegion == this.REGION_IO) {
		this.io.store32(maskedOffset, value);
		return;
	}
	var memory = this.memoryView[memoryRegion];
	memory.setInt32(maskedOffset, value, true);
	if (memory.cachedInstructions) {
		delete this.icache[maskedOffset >> 1];
	}
};

GameBoyAdvanceMMU.prototype.getMemoryRegion = function(offset) {
	var memoryRegion = offset >> this.BASE_OFFSET;
	if (memoryRegion > this.REGION_CART0) {
		return memoryRegion & 0xE;
	}
	return memoryRegion;
};
<commit_msg>Fix CART0 being called ROM0<commit_after>GameBoyAdvanceMMU = function() {
	this.REGION_BIOS = 0x0;
	this.REGION_WORKING_RAM = 0x2;
	this.REGION_WORKING_IRAM = 0x3;
	this.REGION_IO = 0x4;
	this.REGION_PALETTE_RAM = 0x5;
	this.REGION_VRAM = 0x6;
	this.REGION_OAM = 0x7;
	this.REGION_CART0 = 0x8;
	this.REGION_CART1 = 0xA;
	this.REGION_CART2 = 0xC;
	this.REGION_CART_SRAM = 0xE;

	this.BASE_BIOS = 0x00000000;
	this.BASE_WORKING_RAM = 0x02000000;
	this.BASE_WORKING_IRAM = 0x03000000;
	this.BASE_IO = 0x04000000;
	this.BASE_PALETTE_RAM = 0x05000000;
	this.BASE_VRAM = 0x06000000;
	this.BASE_OAM = 0x07000000;
	this.BASE_CART0 = 0x08000000;
	this.BASE_CART1 = 0x0A000000;
	this.BASE_CART2 = 0x0C000000;
	this.BASE_CART_SRAM = 0x0E000000;

	this.BASE_MASK = 0x0F000000;
	this.BASE_OFFSET = 24;

	this.SIZE_BIOS = 0x00004000;
	this.SIZE_WORKING_RAM = 0x00040000;
	this.SIZE_WORKING_IRAM = 0x00008000;
	this.SIZE_IO = 0x00000400;
	this.SIZE_PALETTE_RAM = 0x00000400;
	this.SIZE_VRAM = 0x00018000;
	this.SIZE_OAM = 0x00000400;
	this.SIZE_CART0 = 0x02000000;
	this.SIZE_CART1 = 0x02000000;
	this.SIZE_CART2 = 0x02000000;
	this.SIZE_CART_SRAM = 0x00010000;

	this.TIMINGS_8 = [
		1,
		0,
		1,
		3,
		1,
		1,
		1,
		1,
		5,
		0,
		5,
		0,
		5,
		0
	];

	this.TIMINGS_16 = [
		1,
		0,
		1,
		3,
		1,
		1,
		1,
		1,
		5,
		0,
		5,
		0,
		5,
		0
	];

	this.TIMINGS_32 = [
		1,
		0,
		1,
		6,
		1,
		2,
		2,
		1,
		8,
		0,
		8,
		0,
		8,
		0
	];
};

GameBoyAdvanceMMU.prototype.setCPU = function(cpu) {
	this.cpu = cpu;
}

GameBoyAdvanceMMU.prototype.setIO = function(io) {
	this.io = io;
	io.setMMU(this);
}

GameBoyAdvanceMMU.prototype.clear = function() {
	this.memory = [
		null,
		null, // Unused
		new ArrayBuffer(this.SIZE_WORKING_RAM),
		new ArrayBuffer(this.SIZE_WORKING_IRAM),
		null, // This is owned by GameBoyAdvanceIO
		new ArrayBuffer(this.SIZE_PALETTE_RAM),
		new ArrayBuffer(this.SIZE_VRAM),
		new ArrayBuffer(this.SIZE_OAM),
		null,
		null, // Unused
		null,
		null, // Unused
		null,
		null, // Unused
		null,
		null // Unused
	];

	this.memoryView = [
		null,
		null, // Unused
		new DataView(this.memory[2]),
		new DataView(this.memory[3]),
		null,
		new DataView(this.memory[5]),
		new DataView(this.memory[6]),
		new DataView(this.memory[7]),
		null,
		null, // Unused
		null,
		null, // Unused
		null,
		null, // Unused
		null,
		null // Unused
	];

	this.memoryView[2].cachedInstructions = 0;
	this.memoryView[3].cachedInstructions = 0;
	this.memoryView[5].cachedInstructions = 0;
	this.memoryView[6].cachedInstructions = 0;
	this.memoryView[7].cachedInstructions = 0;

	this.icache = [
		null,
		null, // Unused
		new Array(this.SIZE_WORKING_RAM >> 1),
		new Array(this.SIZE_WORKING_IRAM >> 1),
		null,
		null,
		null,
		null,
		null,
		null, // Unusued
		null,
		null, // Unusued
		null,
		null // Unused
	];
};

GameBoyAdvanceMMU.prototype.loadRom = function(rom) {
	this.memory[this.REGION_CART0] = rom;
	this.memory[this.REGION_CART1] = rom;
	this.memory[this.REGION_CART2] = rom;
	var view = new DataView(rom);
	this.memoryView[this.REGION_CART0] = view;
	this.memoryView[this.REGION_CART1] = view;
	this.memoryView[this.REGION_CART2] = view;

	var icache = new Array(rom.byteLength >> 1);
	this.icache[this.REGION_CART0] = icache;
	this.icache[this.REGION_CART1] = icache;
	this.icache[this.REGION_CART2] = icache;
};

GameBoyAdvanceMMU.prototype.maskOffset = function(offset) {
	if (offset < this.BASE_CART0) {
		return offset & 0x00FFFFFF;
	} else {
		return offset & 0x01FFFFFF;
	}
};

GameBoyAdvanceMMU.prototype.load8 = function(offset) {
	var memoryRegion = this.getMemoryRegion(offset);
	this.cpu.cycles += this.TIMINGS_8[memoryRegion];
	if (memoryRegion == this.REGION_IO) {
		return this.io.load8(offset & 0x00FFFFFF);
	}
	return this.memoryView[memoryRegion].getInt8(this.maskOffset(offset));
};

GameBoyAdvanceMMU.prototype.load16 = function(offset) {
	var memoryRegion = this.getMemoryRegion(offset);
	this.cpu.cycles += this.TIMINGS_16[memoryRegion];
	if (memoryRegion == this.REGION_IO) {
		return this.io.load16(offset & 0x00FFFFFE);
	}
	return this.memoryView[memoryRegion].getInt16(this.maskOffset(offset), true);
};

GameBoyAdvanceMMU.prototype.load32 = function(offset) {
	var memoryRegion = this.getMemoryRegion(offset);
	this.cpu.cycles += this.TIMINGS_32[memoryRegion];
	if (memoryRegion == this.REGION_IO) {
		return this.io.load32(offset & 0x00FFFFFC);
	}
	return this.memoryView[memoryRegion].getInt32(this.maskOffset(offset), true);
};

GameBoyAdvanceMMU.prototype.loadU8 = function(offset) {
	var memoryRegion = this.getMemoryRegion(offset);
	this.cpu.cycles += this.TIMINGS_8[memoryRegion];
	if (memoryRegion == this.REGION_IO) {
		return this.io.loadU8(offset & 0x00FFFFFF);
	}
	return this.memoryView[memoryRegion].getUint8(this.maskOffset(offset));
};

GameBoyAdvanceMMU.prototype.loadU16 = function(offset) {
	var memoryRegion = this.getMemoryRegion(offset);
	this.cpu.cycles += this.TIMINGS_32[memoryRegion];
	if (memoryRegion == this.REGION_IO) {
		return this.io.loadU16(offset & 0x00FFFFFE);
	}
	return this.memoryView[memoryRegion].getUint16(this.maskOffset(offset), true);
};

// Instruction loads -- don't affect timings
GameBoyAdvanceMMU.prototype.iload16 = function(offset) {
	var memoryRegion = this.getMemoryRegion(offset);
	return this.memoryView[memoryRegion].getUint16(this.maskOffset(offset), true);
};

GameBoyAdvanceMMU.prototype.iload32 = function(offset) {
	var memoryRegion = this.getMemoryRegion(offset);
	return this.memoryView[memoryRegion].getInt32(this.maskOffset(offset), true);
};

GameBoyAdvanceMMU.prototype.store8 = function(offset, value) {
	var memoryRegion = this.getMemoryRegion(offset);
	if (memoryRegion >= this.REGION_CART0) {
		throw "Bad access";
	}
	this.cpu.cycles += this.TIMINGS_8[memoryRegion];
	var maskedOffset = offset & 0x00FFFFFF;
	if (memoryRegion == this.REGION_IO) {
		this.io.store8(maskedOffset, value);
		return;
	}
	var memory = this.memoryView[memoryRegion];
	memory.setInt8(maskedOffset, value);
	if (memory.cachedInstructions) {
		delete this.icache[maskedOffset >> 1];
	}
};

GameBoyAdvanceMMU.prototype.store16 = function(offset, value) {
	var memoryRegion = this.getMemoryRegion(offset);
	if (memoryRegion >= this.REGION_CART0) {
		throw "Bad access";
	}
	this.cpu.cycles += this.TIMINGS_16[memoryRegion];
	var maskedOffset = offset & 0x00FFFFFE;
	if (memoryRegion == this.REGION_IO) {
		this.io.store16(maskedOffset, value);
		return;
	}
	var memory = this.memoryView[memoryRegion];
	memory.setInt16(maskedOffset, value, true);
	if (memory.cachedInstructions) {
		delete this.icache[maskedOffset >> 1];
	}
};

GameBoyAdvanceMMU.prototype.store32 = function(offset, value) {
	var memoryRegion = this.getMemoryRegion(offset);
	if (memoryRegion >= this.REGION_CART0) {
		throw "Bad access";
	}
	this.cpu.cycles += this.TIMINGS_32[memoryRegion];
	var maskedOffset = offset & 0x00FFFFFC;
	if (memoryRegion == this.REGION_IO) {
		this.io.store32(maskedOffset, value);
		return;
	}
	var memory = this.memoryView[memoryRegion];
	memory.setInt32(maskedOffset, value, true);
	if (memory.cachedInstructions) {
		delete this.icache[maskedOffset >> 1];
	}
};

GameBoyAdvanceMMU.prototype.getMemoryRegion = function(offset) {
	var memoryRegion = offset >> this.BASE_OFFSET;
	if (memoryRegion > this.REGION_CART0) {
		return memoryRegion & 0xE;
	}
	return memoryRegion;
};
<|endoftext|>


<commit_before>$(function() {
    var $document = $(document),
        $nameShameForm = $("#name-shame-form"),
        $domainnameInput = $("[name=domainname]", $nameShameForm),

        domainLookupFail = function(jqXHR, textStatus, errorThrown) {
            // TODO: show error to the user
            console.error("domainLookupFail", jqXHR, textStatus, errorThrown);

            $nameShameForm.trigger("dnas.lookup.fail");
        },

        domainLookupDone = function(data, textStatus, jqXHR) {
            console.log("domainLookupDone", data, textStatus, jqXHR);

            $nameShameForm.trigger("dnas.lookup.done", data);

            if (data.isSecure === true) {
                $nameShameForm.trigger("dnas.lookup.is-secure", data);
            } else {
                $nameShameForm.trigger("dnas.lookup.is-insecure", data);
            }
        },

        checkDomain = function(domainname) {
            var promise = $.getJSON("/name-shame/", {
                domainname: domainname
            });

            return promise;
        },

        checkDomainAndUpdateUi = function(domainname) {
            var promise = checkDomain(domainname)
                .fail(domainLookupFail)
                .done(domainLookupDone);

            return promise;
        },

        checkDomainInUiForm = function(domainname) {
            $domainnameInput.val(domainname);

            var promise = checkDomainAndUpdateUi(domainname);

            return promise;
        };

    (function() {
        var onSubmit = function(event) {
            event.preventDefault();

            var domainname = $domainnameInput.val();

            checkDomainAndUpdateUi(domainname);

            return false;
        };

        $nameShameForm.on("submit", onSubmit);
    }());

    (function() {
        var getDomainFromUrl = function(url) {
                var domain = url.split("://")[1].split("/")[0];

                return domain;
            },
            doAjaxOnLinkClick = function(event) {
                event.preventDefault();

                var $target = $(event.target),
                    $link = $target
                    .filter("[href]")
                    .add($(event.target).parents("[href]"))
                    .first(),
                    url = $link.attr("href"),
                    domain = getDomainFromUrl(url),
                    highlightClickedItemWithResult = function(data, textStatus, jqXHR) {
                        var successClass = "success",
                            failClass = "fail",
                            bothClasses = successClass + " " + failClass,
                            resultClass;

                        if (data.isSecure === true) {
                            resultClass = successClass;
                        } else {
                            resultClass = failClass;
                        }

                        $link.parents("li")
                            .first()
                            .removeClass(bothClasses)
                            .addClass(resultClass);
                    };

                checkDomainInUiForm(domain)
                    .done(highlightClickedItemWithResult);

                return false;
            };

        $document.on("click", ".has-domains-to-check a", doAjaxOnLinkClick);
    }());

    (function() {
        $nameShameForm.on("dnas.lookup.done", function(evt, data) {
            // Happy/angry, success/failure images
            var successOrFailImage,
                angryOrHappyImage;

            if (data.isSecure === true) {
                successOrFailImage = "success";
                angryOrHappyImage = "happy";
            } else {
                successOrFailImage = "failure";
                angryOrHappyImage = "angry";
            }

            $("#results-container")
                .find(".results-image")
                .hide()
                .end()
                .find(".results-image." + angryOrHappyImage)
                .show()
                .end()
                .removeClass("none-yet");

            $("#results-blocks")
                .find(".results-image")
                .hide()
                .end()
                .find(".results-image." + successOrFailImage)
                .show()
                .end()
                .removeClass("none-yet");

            // Results text
            $("#results-domain-name").text(data.domain);
            $("#results-success-or-fail").text(data.isSecure === true ? "Yes!" : "No!");
        });
    }());

    (function() {
        $nameShameForm.on("dnas.lookup.done", function(evt, data) {
            var tweetResultsText;

            if (data.isSecure === true) {
                tweetResultsText = "#win " + data.domain + " has successfully implemented #DNSSEC!";
            } else {
                tweetResultsText = "#shame " + data.domain + " has NOT implemented #DNSSEC!";
            }

            // Tweet button
            var tweetSiteUrl = "http://dnssec-name-and-shame.com/";

            $("#results-tweet-link")
                .attr("href", "https://twitter.com/intent/tweet?text=" + encodeURIComponent(tweetResultsText) + "&url=" + encodeURIComponent(tweetSiteUrl) + "&hashtags=internet,dns,security")
                .text("Tweet results for " + data.domain);

        });
    }());

    (function() {
        var
            playSound = function(name) {
                var instance = createjs.Sound.play(name);
            };

        (function() {
            createjs.Sound.registerSound("resources/audio/164089_2975503-lq.mp3", "fail");
            createjs.Sound.registerSound("resources/audio/109662_945474-lq.mp3", "done");
        }());

        $nameShameForm.on("dnas.lookup.done", function(evt, data) {
            if (data.isSecure === true) {
                playSound("done");
            } else {
                playSound("fail");
            }
        });
    }());

    (function() {
        $nameShameForm.on("dnas.lookup.fail", function(evt, data) {
            // HACK: Server error, resubmit the form
            $nameShameForm.submit();
        });
    }());
});<commit_msg>Sleep if the server failed to respond, then retry<commit_after>$(function() {
    var $document = $(document),
        $nameShameForm = $("#name-shame-form"),
        $domainnameInput = $("[name=domainname]", $nameShameForm),

        domainLookupFail = function(jqXHR, textStatus, errorThrown) {
            // TODO: show error to the user
            console.error("domainLookupFail", jqXHR, textStatus, errorThrown);

            $nameShameForm.trigger("dnas.lookup.fail");
        },

        domainLookupDone = function(data, textStatus, jqXHR) {
            console.log("domainLookupDone", data, textStatus, jqXHR);

            $nameShameForm.trigger("dnas.lookup.done", data);

            if (data.isSecure === true) {
                $nameShameForm.trigger("dnas.lookup.is-secure", data);
            } else {
                $nameShameForm.trigger("dnas.lookup.is-insecure", data);
            }
        },

        checkDomain = function(domainname) {
            var promise = $.getJSON("/name-shame/", {
                domainname: domainname
            });

            return promise;
        },

        checkDomainAndUpdateUi = function(domainname) {
            var promise = checkDomain(domainname)
                .fail(domainLookupFail)
                .done(domainLookupDone);

            return promise;
        },

        checkDomainInUiForm = function(domainname) {
            $domainnameInput.val(domainname);

            var promise = checkDomainAndUpdateUi(domainname);

            return promise;
        };

    (function() {
        var onSubmit = function(event) {
            event.preventDefault();

            var domainname = $domainnameInput.val();

            checkDomainAndUpdateUi(domainname);

            return false;
        };

        $nameShameForm.on("submit", onSubmit);
    }());

    (function() {
        var getDomainFromUrl = function(url) {
                var domain = url.split("://")[1].split("/")[0];

                return domain;
            },
            doAjaxOnLinkClick = function(event) {
                event.preventDefault();

                var $target = $(event.target),
                    $link = $target
                    .filter("[href]")
                    .add($(event.target).parents("[href]"))
                    .first(),
                    url = $link.attr("href"),
                    domain = getDomainFromUrl(url),
                    highlightClickedItemWithResult = function(data, textStatus, jqXHR) {
                        var successClass = "success",
                            failClass = "fail",
                            bothClasses = successClass + " " + failClass,
                            resultClass;

                        if (data.isSecure === true) {
                            resultClass = successClass;
                        } else {
                            resultClass = failClass;
                        }

                        $link.parents("li")
                            .first()
                            .removeClass(bothClasses)
                            .addClass(resultClass);
                    };

                checkDomainInUiForm(domain)
                    .done(highlightClickedItemWithResult);

                return false;
            };

        $document.on("click", ".has-domains-to-check a", doAjaxOnLinkClick);
    }());

    (function() {
        $nameShameForm.on("dnas.lookup.done", function(evt, data) {
            // Happy/angry, success/failure images
            var successOrFailImage,
                angryOrHappyImage;

            if (data.isSecure === true) {
                successOrFailImage = "success";
                angryOrHappyImage = "happy";
            } else {
                successOrFailImage = "failure";
                angryOrHappyImage = "angry";
            }

            $("#results-container")
                .find(".results-image")
                .hide()
                .end()
                .find(".results-image." + angryOrHappyImage)
                .show()
                .end()
                .removeClass("none-yet");

            $("#results-blocks")
                .find(".results-image")
                .hide()
                .end()
                .find(".results-image." + successOrFailImage)
                .show()
                .end()
                .removeClass("none-yet");

            // Results text
            $("#results-domain-name").text(data.domain);
            $("#results-success-or-fail").text(data.isSecure === true ? "Yes!" : "No!");
        });
    }());

    (function() {
        $nameShameForm.on("dnas.lookup.done", function(evt, data) {
            var tweetResultsText;

            if (data.isSecure === true) {
                tweetResultsText = "#win " + data.domain + " has successfully implemented #DNSSEC!";
            } else {
                tweetResultsText = "#shame " + data.domain + " has NOT implemented #DNSSEC!";
            }

            // Tweet button
            var tweetSiteUrl = "http://dnssec-name-and-shame.com/";

            $("#results-tweet-link")
                .attr("href", "https://twitter.com/intent/tweet?text=" + encodeURIComponent(tweetResultsText) + "&url=" + encodeURIComponent(tweetSiteUrl) + "&hashtags=internet,dns,security")
                .text("Tweet results for " + data.domain);

        });
    }());

    (function() {
        var
            playSound = function(name) {
                var instance = createjs.Sound.play(name);
            };

        (function() {
            createjs.Sound.registerSound("resources/audio/164089_2975503-lq.mp3", "fail");
            createjs.Sound.registerSound("resources/audio/109662_945474-lq.mp3", "done");
        }());

        $nameShameForm.on("dnas.lookup.done", function(evt, data) {
            if (data.isSecure === true) {
                playSound("done");
            } else {
                playSound("fail");
            }
        });
    }());

    (function() {
        // HACK: Server error! Sleep and then resubmit the form.
        // TODO: check if the user changed the domain in the input box?
        var errorsInARow = 0,
            sleepDefault = 1000;

        $nameShameForm.on("dnas.lookup.fail", function(evt, data) {
            var sleepThisTime = Math.pow(2, errorsInARow++) * sleepDefault;

            console.error("Server failure, waiting to resubmit form.", "errorsInARow", errorsInARow, "sleepThisTime", sleepThisTime);

            setTimeout(function() {
                $nameShameForm.submit();
            }, sleepThisTime);
        });

        $nameShameForm.on("dnas.lookup.done", function(evt, data) {
            errorsInARow = 0;
        });
    }());
});<|endoftext|>