<commit_before>var Game = Game || {};

Game.Snake = function(width, height, options) {
  'use strict';
  this.width = width;
  this.height = height;
  this.blockWidth = options.blockWidth || 20;
  this.blockHeight = options.blockHeight || 20;
  this.columns = Math.round(this.width / this.blockWidth);
  this.rows = Math.round(this.height / this.blockHeight);
  var midCol = Math.floor(this.columns / 2);
  var midRow = Math.floor(this.rows / 2);
  this.snake = [[midCol, midRow], [midCol - 1, midRow], [midCol - 2, midRow]];
  this.direction = 'right';
  this.pause = false;
  this.gameOver = false;
  this.food = [];
  this.foodCount = 0;
};

Game.Snake.prototype.DIRECTIONS = {
  UP: 'up',
  RIGHT: 'right',
  DOWN: 'down',
  LEFT: 'left'
};

Game.Snake.prototype.blockPosition = function(col, row) {
  'use strict';
  return {
    x: col * this.blockWidth,
    y: row * this.blockHeight
  };
};

Game.Snake.prototype.moveSnake = function() {
  'use strict';
  var headX = this.snake[0][0];
  var headY = this.snake[0][1];
  var tail;

  if (this.direction === this.DIRECTIONS.UP) {
    headY -= 1;
  } else if (this.direction === this.DIRECTIONS.RIGHT) {
    headX += 1;
  } else if (this.direction === this.DIRECTIONS.DOWN) {
    headY += 1;
  } else if (this.direction === this.DIRECTIONS.LEFT) {
    headX -= 1;
  }

  if (this.food[0] !== headX || this.food[1] !== headY) {
    tail = this.snake.pop();
  }
  else {
    this.food = [];
    this.foodCount += 1;
  }
  tail = [headX, headY];
  this.snake.unshift(tail);
};

Game.Snake.prototype.isIntersecting = function(element, arr) {
  'use strict';
  return arr.some(function(a) {
    return a[0] === element[0] && a[1] === element[1];
  });
};

Game.Snake.prototype.isGameOver = function() {
  'use strict';
  var head = this.snake[0];
  if (head[0] < 0 || head[0] >= this.columns ||
     head[1] < 0 || head[1] >= this.rows ||
     this.isIntersecting(head, this.snake.slice(1))) {
    return true;
  }
  return false;
};

Game.Snake.prototype.getRandomInt = function(min, max) {
  'use strict';
  return Math.floor(Math.random() * (max - min)) + min;
};

Game.Snake.prototype.update = function(inputHandler) {
  'use strict';

  this.gameOver = this.isGameOver();
  if (!this.gameOver) {

    if (inputHandler.pressed && inputHandler.isDown('ESC')) {
      this.pause = !this.pause;
    }
    if (!this.pause) {

      if (this.food.length === 0) {
        this.food = [this.getRandomInt(0, this.columns),
                     this.getRandomInt(0, this.rows)];
      }

      if (this.direction !== this.DIRECTIONS.DOWN &&
          (inputHandler.isDown('UP') || inputHandler.isDown('W'))) {
        this.direction = this.DIRECTIONS.UP;
      } else if (this.direction !== this.DIRECTIONS.LEFT &&
                 (inputHandler.isDown('RIGHT') || inputHandler.isDown('D'))) {
        this.direction = this.DIRECTIONS.RIGHT;
      } else if (this.direction !== this.DIRECTIONS.UP &&
                 (inputHandler.isDown('DOWN') || inputHandler.isDown('S'))) {
        this.direction = this.DIRECTIONS.DOWN;
      } else if (this.direction !== this.DIRECTIONS.RIGHT &&
                 (inputHandler.isDown('LEFT') || inputHandler.isDown('A'))) {
        this.direction = this.DIRECTIONS.LEFT;
      }
      this.moveSnake();
    }
  }
};

Game.Snake.prototype.render = function(context) {
  'use strict';
  var coordinates, textMeasure, foodCoordinates;
  var self = this;

  context.beginPath();
  context.fillStyle = '#000000';
  context.fillRect(0, 0, this.width, this.height);
  context.closePath();

  context.beginPath();
  this.snake.forEach(function(s) {
    coordinates = self.blockPosition(s[0], s[1]);
    context.fillStyle = '#FFFFFF';
    context.rect(coordinates.x, coordinates.y, self.blockWidth,
                 self.blockHeight);
    context.lineWidth = "1";
    context.strokeStyle = '#000000';
    context.rect(coordinates.x, coordinates.y, self.blockWidth,
                      self.blockHeight);
  });
  context.closePath();
  context.fill();
  context.stroke();

  context.beginPath();
  foodCoordinates = this.blockPosition(this.food[0], this.food[1]);
  context.fillStyle = '#FF5566';
  context.rect(foodCoordinates.x, foodCoordinates.y, this.blockWidth,
               this.blockHeight);
  context.closePath();
  context.fill();

  if (this.pause) {
    context.beginPath();
    context.font = 'bold 120px Helvetica, Verdana, san-serif';
    context.fillStyle = '#FFDD88';
    textMeasure = context.measureText('Paused').width;
    context.fillText('Paused', (this.width / 2) - (textMeasure / 2), this.height / 2);
    context.closePath();
  }

  if (this.gameOver) {
    context.beginPath();
    context.font = 'bold 120px Helvetica, Verdana, san-serif';
    context.fillStyle = '#FFDD88';
    textMeasure = context.measureText('Game Over').width;
    context.fillText('Game Over', (this.width / 2) - (textMeasure / 2), this.height / 2);
    context.closePath();
  }
};
<commit_msg>Add option to try again after game over<commit_after>var Game = Game || {};

Game.Snake = function(width, height, options) {
  'use strict';
  this.width = width;
  this.height = height;
  this.blockWidth = options.blockWidth || 20;
  this.blockHeight = options.blockHeight || 20;
  this.columns = Math.round(this.width / this.blockWidth);
  this.rows = Math.round(this.height / this.blockHeight);
  this.midCol = Math.floor(this.columns / 2);
  this.midRow = Math.floor(this.rows / 2);
  this.snake = [[this.midCol, this.midRow], [this.midCol - 1, this.midRow],
                [this.midCol - 2, this.midRow]];
  this.direction = 'right';
  this.pause = false;
  this.gameOver = false;
  this.food = [];
  this.foodCount = 0;
};

Game.Snake.prototype.DIRECTIONS = {
  UP: 'up',
  RIGHT: 'right',
  DOWN: 'down',
  LEFT: 'left'
};

Game.Snake.prototype.blockPosition = function(col, row) {
  'use strict';
  return {
    x: col * this.blockWidth,
    y: row * this.blockHeight
  };
};

Game.Snake.prototype.moveSnake = function() {
  'use strict';
  var headX = this.snake[0][0];
  var headY = this.snake[0][1];
  var tail;

  if (this.direction === this.DIRECTIONS.UP) {
    headY -= 1;
  } else if (this.direction === this.DIRECTIONS.RIGHT) {
    headX += 1;
  } else if (this.direction === this.DIRECTIONS.DOWN) {
    headY += 1;
  } else if (this.direction === this.DIRECTIONS.LEFT) {
    headX -= 1;
  }

  if (this.food[0] !== headX || this.food[1] !== headY) {
    tail = this.snake.pop();
  }
  else {
    this.food = [];
    this.foodCount += 1;
  }
  tail = [headX, headY];
  this.snake.unshift(tail);
};

Game.Snake.prototype.isIntersecting = function(element, arr) {
  'use strict';
  return arr.some(function(a) {
    return a[0] === element[0] && a[1] === element[1];
  });
};

Game.Snake.prototype.isGameOver = function() {
  'use strict';
  var head = this.snake[0];
  if (head[0] < 0 || head[0] >= this.columns ||
     head[1] < 0 || head[1] >= this.rows ||
     this.isIntersecting(head, this.snake.slice(1))) {
    return true;
  }
  return false;
};

Game.Snake.prototype.getRandomInt = function(min, max) {
  'use strict';
  return Math.floor(Math.random() * (max - min)) + min;
};

Game.Snake.prototype.reset = function() {
  this.snake = [[this.midCol, this.midRow], [this.midCol - 1, this.midRow],
                [this.midCol - 2, this.midRow]];
  this.food = [];
  this.foodCount = 0;
  this.direction = 'right';
  this.gameOver = false;
}

Game.Snake.prototype.update = function(inputHandler) {
  'use strict';

  this.gameOver = this.isGameOver();
  if (!this.gameOver) {

    if (inputHandler.pressed && inputHandler.isDown('ESC')) {
      this.pause = !this.pause;
    }
    if (!this.pause) {

      if (this.food.length === 0) {
        this.food = [this.getRandomInt(0, this.columns),
                     this.getRandomInt(0, this.rows)];
      }

      if (this.direction !== this.DIRECTIONS.DOWN &&
          (inputHandler.isDown('UP') || inputHandler.isDown('W'))) {
        this.direction = this.DIRECTIONS.UP;
      } else if (this.direction !== this.DIRECTIONS.LEFT &&
                 (inputHandler.isDown('RIGHT') || inputHandler.isDown('D'))) {
        this.direction = this.DIRECTIONS.RIGHT;
      } else if (this.direction !== this.DIRECTIONS.UP &&
                 (inputHandler.isDown('DOWN') || inputHandler.isDown('S'))) {
        this.direction = this.DIRECTIONS.DOWN;
      } else if (this.direction !== this.DIRECTIONS.RIGHT &&
                 (inputHandler.isDown('LEFT') || inputHandler.isDown('A'))) {
        this.direction = this.DIRECTIONS.LEFT;
      }
      this.moveSnake();
    }
  } else {
    if (inputHandler.pressed && inputHandler.isDown('RTN')) {
      this.reset();
    }
  }
};

Game.Snake.prototype.render = function(context) {
  'use strict';
  var coordinates, textMeasure, foodCoordinates;
  var self = this;

  context.beginPath();
  context.fillStyle = '#000000';
  context.fillRect(0, 0, this.width, this.height);
  context.closePath();

  context.beginPath();
  this.snake.forEach(function(s) {
    coordinates = self.blockPosition(s[0], s[1]);
    context.fillStyle = '#FFFFFF';
    context.rect(coordinates.x, coordinates.y, self.blockWidth,
                 self.blockHeight);
    context.lineWidth = "1";
    context.strokeStyle = '#000000';
    context.rect(coordinates.x, coordinates.y, self.blockWidth,
                      self.blockHeight);
  });
  context.closePath();
  context.fill();
  context.stroke();

  context.beginPath();
  foodCoordinates = this.blockPosition(this.food[0], this.food[1]);
  context.fillStyle = '#FF5566';
  context.rect(foodCoordinates.x, foodCoordinates.y, this.blockWidth,
               this.blockHeight);
  context.closePath();
  context.fill();

  if (this.pause) {
    context.beginPath();
    context.font = 'bold 120px Helvetica, Verdana, san-serif';
    context.fillStyle = '#FFDD88';
    textMeasure = context.measureText('Paused').width;
    context.fillText('Paused', (this.width / 2) - (textMeasure / 2), this.height / 2);
    context.closePath();
  }

  if (this.gameOver) {
    context.beginPath();
    context.font = 'bold 120px Helvetica, Verdana, san-serif';
    context.fillStyle = '#FFDD88';
    textMeasure = context.measureText('Game Over').width;
    context.fillText('Game Over', (this.width / 2) - (textMeasure / 2), this.height / 2);
    context.closePath();

    context.beginPath();
    context.font = '80pt Helvetica, Verdana, sans-serif';
    context.fillStyle = '#FFFFFF';
    textMeasure = context.measureText('Try Again?').width;
    context.fillText('Try Again?', (this.width / 2) - (textMeasure / 2), (this.height / 2) + 120);
    context.closePath();
  }
};
<|endoftext|>


<commit_before>// OS Monitoring for Node.js

// Copyright (c) 2012-2013 Laurent Fortin
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

var util     = require('util'),
    os       = require('os'),
    events   = require('events'),
    stream   = require('stream'),
    _        = require('underscore'),
    critical = os.cpus().length,
    defaults = {
      delay     : 3000,
      critical1 : critical,
      critical5 : critical,
      critical15: critical,
      freemem   : 0,
      uptime    : 0,
      silent    : false,
      stream    : false
    };

// constructor
var Monitor = function() {
  if(stream.Readable) {
    stream.Readable.call(this, {highWaterMark: 102400});
  } else {
    events.EventEmitter.call(this);
  }

  this._monitorState = {
    running: false,
    streamBuffering: true,
    interval: undefined,
    config: _.clone(defaults)
  };
};

if(stream.Readable) {
  util.inherits(Monitor, stream.Readable);
} else {
  util.inherits(Monitor, events.EventEmitter);
}

Monitor.prototype.version = '0.1.4';

// readable stream implementation requirement
Monitor.prototype._read = function() {
  this._monitorState.streamBuffering = true;
};

Monitor.prototype.sendEvent = function(event, data) {
  // for EventEmitter
  this.emit(event, data);
  // for readable Stream
  if(this._monitorState.config.stream && this._monitorState.streamBuffering) {
    var prettyJSON = os.EOL + JSON.stringify(data, null, 2);
    if( !this.push(new Buffer(prettyJSON)) ) {
      this._monitorState.streamBuffering = false;
    }
  }
};

Monitor.prototype.start = function(options) {

  var self = this;

  self.stop()
      .config(options);

  this._monitorState.interval  = setInterval(function() {
    var info = {
      loadavg  : os.loadavg(),
      uptime   : os.uptime(),
      freemem  : os.freemem(),
      totalmem : os.totalmem()
    },
    config = self._monitorState.config,
    freemem  = (config.freemem < 1) ? config.freemem * info.totalmem : config.freemem;

    if(!config.silent) {
      self.sendEvent('monitor', _.extend({type: 'monitor'}, info));
    }
    if(info.loadavg[0] > config.critical1) {
      self.sendEvent('loadavg1', _.extend({type: 'loadavg1'}, info));
    }
    if(info.loadavg[1] > config.critical5) {
      self.sendEvent('loadavg5', _.extend({type: 'loadavg5'}, info));
    }
    if(info.loadavg[2] > config.critical15) {
      self.sendEvent('loadavg15', _.extend({type: 'loadavg15'}, info));
    }
    if(info.freemem < freemem) {
      self.sendEvent('freemem', _.extend({type: 'freemem'}, info));
    }
    if(Number(config.uptime) && info.uptime > Number(config.uptime)) {
      self.sendEvent('uptime', _.extend({type: 'uptime'}, info));
    }
  }, this._monitorState.config.delay);

  if(!self.isRunning()) {
    this._monitorState.running = true;
    self.sendEvent('start', {type: 'start'});
  }

  return self;
};

Monitor.prototype.stop = function() {

  clearInterval(this._monitorState.interval);

  if(this.isRunning()) {
    this._monitorState.running = false;
    this.sendEvent('stop', {type: 'stop'});
  }

  return this;
};

Monitor.prototype.config = function(options) {

  if(_.isObject(options)) {
    _.extend(this._monitorState.config, options);
    this.sendEvent('config', {type: 'config', options: _.clone(options)});
  }

  return this._monitorState.config;
};

Monitor.prototype.isRunning = function() {
  return !!this._monitorState.running;
};

Monitor.prototype.throttle = function(event, handler, wait) {
  var self     = this,
      _handler = _.wrap(handler, function(fn) {
                   if(self.isRunning()) {
                     fn.apply(this, _.toArray(arguments).slice(1));
                   }
                 });
  return self.on.call(self, event, _.throttle(_handler, wait || this._monitorState.config.throttle));
};

/*
 * convenience methods
 */

Monitor.prototype._sanitizeNumber = function(n) {
  if(!_.isNumber(n)) {
    throw new Error("Number expected");
  }
  if(!n || n < 0) {
    throw new Error("Number must be greater than 0");
  }
  // Math.pow(2, 31);
  if(n >= 2147483648) {
    throw new Error("Number must be smaller than 2147483648");
  }
};

Monitor.prototype.seconds = function(n) {
  this._sanitizeNumber(n);
  return n * 1000;
};

Monitor.prototype.minutes = function(n) {
  this._sanitizeNumber(n);
  return n * this.seconds(60);
};

Monitor.prototype.hours = function(n) {
  this._sanitizeNumber(n);
  return n * this.minutes(60);
};

Monitor.prototype.days = function(n) {
  this._sanitizeNumber(n);
  return n * this.hours(24);
};

// deprecated stuff
Monitor.prototype.setConfig = util.deprecate(Monitor.prototype.config);

// expose OS module
Monitor.prototype.os = os;

// expose Underscore
Monitor.prototype._ = _;

// create object
var Osm = new Monitor();

// expose main class
Osm.Monitor = Monitor;

module.exports = Osm;

<commit_msg>better sanitize number<commit_after>// OS Monitoring for Node.js

// Copyright (c) 2012-2013 Laurent Fortin
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

var util     = require('util'),
    os       = require('os'),
    events   = require('events'),
    stream   = require('stream'),
    _        = require('underscore'),
    critical = os.cpus().length,
    defaults = {
      delay     : 3000,
      critical1 : critical,
      critical5 : critical,
      critical15: critical,
      freemem   : 0,
      uptime    : 0,
      silent    : false,
      stream    : false
    };

// constructor
var Monitor = function() {
  if(stream.Readable) {
    stream.Readable.call(this, {highWaterMark: 102400});
  } else {
    events.EventEmitter.call(this);
  }

  this._monitorState = {
    running: false,
    streamBuffering: true,
    interval: undefined,
    config: _.clone(defaults)
  };
};

if(stream.Readable) {
  util.inherits(Monitor, stream.Readable);
} else {
  util.inherits(Monitor, events.EventEmitter);
}

Monitor.prototype.version = '0.1.4';

// readable stream implementation requirement
Monitor.prototype._read = function() {
  this._monitorState.streamBuffering = true;
};

Monitor.prototype.sendEvent = function(event, data) {
  // for EventEmitter
  this.emit(event, data);
  // for readable Stream
  if(this._monitorState.config.stream && this._monitorState.streamBuffering) {
    var prettyJSON = os.EOL + JSON.stringify(data, null, 2);
    if( !this.push(new Buffer(prettyJSON)) ) {
      this._monitorState.streamBuffering = false;
    }
  }
};

Monitor.prototype.start = function(options) {

  var self = this;

  self.stop()
      .config(options);

  this._monitorState.interval  = setInterval(function() {
    var info = {
      loadavg  : os.loadavg(),
      uptime   : os.uptime(),
      freemem  : os.freemem(),
      totalmem : os.totalmem()
    },
    config = self._monitorState.config,
    freemem  = (config.freemem < 1) ? config.freemem * info.totalmem : config.freemem;

    if(!config.silent) {
      self.sendEvent('monitor', _.extend({type: 'monitor'}, info));
    }
    if(info.loadavg[0] > config.critical1) {
      self.sendEvent('loadavg1', _.extend({type: 'loadavg1'}, info));
    }
    if(info.loadavg[1] > config.critical5) {
      self.sendEvent('loadavg5', _.extend({type: 'loadavg5'}, info));
    }
    if(info.loadavg[2] > config.critical15) {
      self.sendEvent('loadavg15', _.extend({type: 'loadavg15'}, info));
    }
    if(info.freemem < freemem) {
      self.sendEvent('freemem', _.extend({type: 'freemem'}, info));
    }
    if(Number(config.uptime) && info.uptime > Number(config.uptime)) {
      self.sendEvent('uptime', _.extend({type: 'uptime'}, info));
    }
  }, this._monitorState.config.delay);

  if(!self.isRunning()) {
    this._monitorState.running = true;
    self.sendEvent('start', {type: 'start'});
  }

  return self;
};

Monitor.prototype.stop = function() {

  clearInterval(this._monitorState.interval);

  if(this.isRunning()) {
    this._monitorState.running = false;
    this.sendEvent('stop', {type: 'stop'});
  }

  return this;
};

Monitor.prototype.config = function(options) {

  if(_.isObject(options)) {
    _.extend(this._monitorState.config, options);
    this.sendEvent('config', {type: 'config', options: _.clone(options)});
  }

  return this._monitorState.config;
};

Monitor.prototype.isRunning = function() {
  return !!this._monitorState.running;
};

Monitor.prototype.throttle = function(event, handler, wait) {
  var self     = this,
      _handler = _.wrap(handler, function(fn) {
                   if(self.isRunning()) {
                     fn.apply(this, _.toArray(arguments).slice(1));
                   }
                 });
  return self.on.call(self, event, _.throttle(_handler, wait || this._monitorState.config.throttle));
};

/*
 * convenience methods
 */

Monitor.prototype._sanitizeNumber = function(n) {
  if(!_.isNumber(n)) {
    throw new Error("Number expected");
  }
  if(!n || n < 0) {
    throw new Error("Number must be greater than 0");
  }
  // Math.pow(2, 31);
  if(n >= 2147483648) {
    throw new Error("Number must be smaller than 2147483648");
  }
  return n;
};

Monitor.prototype.seconds = function(n) {
  return this._sanitizeNumber(n * 1000);
};

Monitor.prototype.minutes = function(n) {
  return this._sanitizeNumber(n * this.seconds(60));
};

Monitor.prototype.hours = function(n) {
  return this._sanitizeNumber(n * this.minutes(60));
};

Monitor.prototype.days = function(n) {
  return this._sanitizeNumber(n * this.hours(24));
};

// deprecated stuff
Monitor.prototype.setConfig = util.deprecate(Monitor.prototype.config);

// expose OS module
Monitor.prototype.os = os;

// expose Underscore
Monitor.prototype._ = _;

// create object
var Osm = new Monitor();

// expose main class
Osm.Monitor = Monitor;

module.exports = Osm;

<|endoftext|>


<commit_before>/*

 jquery.remoteLoad.js -- Remotely load content referenced in data attribute
 https://github.com/aegixx/jquery-remoteLoad - Bryan Stone - Copyright 2015
 Dual licensed under the MIT and GPL licenses.

 */
jQuery.fn.extend({
	remoteLoad: function(options) {
		var targets = $(this);
		var options = $.extend({
			srcAttr: 'src',                         // Data attribute for remote src
			loadedAttr: 'loaded',                   // Data attribute to use once loaded
			loadingImgClass: 'loading-img',         // Class for loading image (empty span)
			errorImgClass: 'loading-error-img',     // Class for error image (empty span)
			loadingClass: 'loading',                // Class for loading content
			errorClass: 'loading-error',            // Class for error content
			errorContent: '',                       // HTML content to display while loading
			loadingContent: '',                     // HTML content to display when an error occurs
			beforeSend: null,                       // ajax:beforeSend Callback function
			success: null,                          // ajax:success Callback function
			error: null,                            // ajax:error Callback function
			complete: null,                         // ajax:complete Callback function
			force: false                            // Forces reload of data, even if it is already loaded
		}, options);

		this.each(function() {
			var target = $(this);
			var src = target.data(options.srcAttr);
			// Skip if already loaded (unless force is enabled)
			if (target.data(options.loadedAttr) && !options.force)
				return true;

			$.ajax({
				url: src,
				dataType: 'html',
				beforeSend: function (xhr, settings) {
					target.addClass(options.loadingClass).html('Loading...' + options.loadingContent)
					if (typeof options.beforeSend == 'function')
						options.beforeSend.call(target, xhr, settings);
					target.trigger('ajax:beforeSend');
				},
				success: function (data, status, xhr) {
					target.html(data);
					if (typeof options.success == 'function')
						options.success.call(target, data, status, xhr);
					target.trigger('ajax:success');
					target.data(options.loadedAttr, true);
				},
				error: function (xhr, status, error) {
					target.addClass(options.errorClass).html('Error!' + options.errorContent)
					if (typeof options.error == 'function')
						options.error.call(target, xhr, status, error);
					target.trigger('ajax:error');
				},
				complete: function(xhr, status) {
					target.removeClass(options.loadingClass);
					if (typeof options.complete == 'function')
						options.complete.call(target, xhr, status);
					target.trigger('ajax:complete');
				}
			});
		});

		return targets; // Allow for chaining
	},
	remoteSubmit: function(options) {
		var targets = $(this);
		var options = $.extend({
			target: null,                           // Forced element to use as a target for the response
																							//   (takes precedence over targetAttr)
			targetAttr: 'target',                   // Data attribute to examine for elements to update with form response
			loadingImgClass: 'loading-img',         // Class for loading image (empty span)
			errorImgClass: 'loading-error-img',     // Class for error image (empty span)
			loadingClass: 'loading',                // Class for loading content
			errorClass: 'loading-error',            // Class for error content
			errorContent: '',                       // HTML content to display while loading
			loadingContent: '',                     // HTML content to display when an error occurs
			beforeSend: null,                       // ajax:beforeSend Callback function
			success: null,                          // ajax:success Callback function
			error: null,                            // ajax:error Callback function
			complete: null                          // ajax:complete Callback function
		}, options);

		this.filter('form').each(function() {
			var form = $(this);
			var target = options.target ? $(options.target) : $($(this).data(options.targetAttr));
			var src = form.attr('action') || window.location.pathname;
			var type = form.attr('method') || 'POST';

			form.submit(function (e) {
				e.preventDefault();

				$.ajax({
					url: src,
					dataType: 'html',
					type: type,
					data: form.serialize(),
					beforeSend: function (xhr, settings) {
						target.addClass(options.loadingClass).html('Loading...' + options.loadingContent)
						if (typeof options.beforeSend == 'function')
							options.beforeSend.call(form, xhr, settings);
						form.trigger('ajax:beforeSend');
					},
					success: function (data, status, xhr) {
						target.html(data);
						if (typeof options.success == 'function')
							options.success.call(form, data, status, xhr);
						form.trigger('ajax:success');
					},
					error: function (xhr, status, error) {
						target.addClass(options.errorClass).html('Error!' + options.errorContent)
						if (typeof options.error == 'function')
							options.error.call(form, xhr, status, error);
						form.trigger('ajax:error');
					},
					complete: function(xhr, status) {
						target.removeClass(options.loadingClass);
						if (typeof options.complete == 'function')
							options.complete.call(form, xhr, status);
						form.trigger('ajax:complete');
					}
				});
			});

		});

		return targets; // Allow for chaining
	}
});<commit_msg>Update HTML prior to callback<commit_after>/*

 jquery.remoteLoad.js -- Remotely load content referenced in data attribute
 https://github.com/aegixx/jquery-remoteLoad - Bryan Stone - Copyright 2015
 Dual licensed under the MIT and GPL licenses.

 */
jQuery.fn.extend({
	remoteLoad: function(options) {
		var targets = $(this);
		var options = $.extend({
			srcAttr: 'src',                         // Data attribute for remote src
			loadedAttr: 'loaded',                   // Data attribute to use once loaded
			loadingImgClass: 'loading-img',         // Class for loading image (empty span)
			errorImgClass: 'loading-error-img',     // Class for error image (empty span)
			loadingClass: 'loading',                // Class for loading content
			errorClass: 'loading-error',            // Class for error content
			errorContent: '',                       // HTML content to display while loading
			loadingContent: '',                     // HTML content to display when an error occurs
			beforeSend: null,                       // ajax:beforeSend Callback function
			success: null,                          // ajax:success Callback function
			error: null,                            // ajax:error Callback function
			complete: null,                         // ajax:complete Callback function
			force: false                            // Forces reload of data, even if it is already loaded
		}, options);

		this.each(function() {
			var target = $(this);
			var src = target.data(options.srcAttr);
			// Skip if already loaded (unless force is enabled)
			if (target.data(options.loadedAttr) && !options.force)
				return true;

			$.ajax({
				url: src,
				dataType: 'html',
				beforeSend: function (xhr, settings) {
					target.addClass(options.loadingClass).html('Loading...' + options.loadingContent)
					if (typeof options.beforeSend == 'function')
						options.beforeSend.call(target, xhr, settings);
					target.trigger('ajax:beforeSend');
				},
				success: function (data, status, xhr) {
					target.html(data);
					if (typeof options.success == 'function')
						options.success.call(target, data, status, xhr);
					target.trigger('ajax:success');
					target.data(options.loadedAttr, true);
				},
				error: function (xhr, status, error) {
					target.addClass(options.errorClass).html('Error!' + options.errorContent)
					if (typeof options.error == 'function')
						options.error.call(target, xhr, status, error);
					target.trigger('ajax:error');
				},
				complete: function(xhr, status) {
					target.removeClass(options.loadingClass);
					if (typeof options.complete == 'function')
						options.complete.call(target, xhr, status);
					target.trigger('ajax:complete');
				}
			});
		});

		return targets; // Allow for chaining
	},
	remoteSubmit: function(options) {
		var targets = $(this);
		var options = $.extend({
			target: null,                           // Forced element to use as a target for the response
																							//   (takes precedence over targetAttr)
			targetAttr: 'target',                   // Data attribute to examine for elements to update with form response
			loadingImgClass: 'loading-img',         // Class for loading image (empty span)
			errorImgClass: 'loading-error-img',     // Class for error image (empty span)
			loadingClass: 'loading',                // Class for loading content
			errorClass: 'loading-error',            // Class for error content
			errorContent: '',                       // HTML content to display while loading
			loadingContent: '',                     // HTML content to display when an error occurs
			beforeSend: null,                       // ajax:beforeSend Callback function
			success: null,                          // ajax:success Callback function
			error: null,                            // ajax:error Callback function
			complete: null                          // ajax:complete Callback function
		}, options);

		this.filter('form').each(function() {
			var form = $(this);
			var target = options.target ? $(options.target) : $($(this).data(options.targetAttr));
			var src = form.attr('action') || window.location.pathname;
			var type = form.attr('method') || 'POST';

			form.submit(function (e) {
				e.preventDefault();

				$.ajax({
					url: src,
					dataType: 'html',
					type: type,
					data: form.serialize(),
					beforeSend: function (xhr, settings) {
						target.addClass(options.loadingClass).html('Loading...' + options.loadingContent)
						if (typeof options.beforeSend == 'function') {
							if (!options.beforeSend.call(form, xhr, settings))
								return false;
						}
						if (!form.trigger('ajax:beforeSend'))
							return false;
					},
					success: function (data, status, xhr) {
						target.html(data);
						if (typeof options.success == 'function')
							options.success.call(target, data, status, xhr);
						form.trigger('ajax:success');
					},
					error: function (xhr, status, error) {
						target.addClass(options.errorClass).html('Error!' + options.errorContent)
						if (typeof options.error == 'function')
							options.error.call(target, xhr, status, error);
						form.trigger('ajax:error');
					},
					complete: function(xhr, status) {
						target.removeClass(options.loadingClass);
						if (typeof options.complete == 'function')
							options.complete.call(target, xhr, status);
						form.trigger('ajax:complete');
					}
				});
			});

		});

		return targets; // Allow for chaining
	}
});<|endoftext|>


<commit_before>/*
* jquery.collection.js v0.0.42
*
* Copyright (c) 2015 alain tiemblo <alain at fuz dot org>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the
* following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

;(function($) {

   $.fn.collection = function(options) {

      var defaults = {
         container: 'body',
         allow_up: true,
         up: '▲',
         before_up: function(collection, element) { return true; },
         after_up: function(collection, element) { return true; },
         allow_down: true,
         down: '▼',
         before_down: function(collection, element) { return true; },
         after_down: function(collection, element) { return true; },
         allow_add: true,
         add: '[ + ]',
         before_add: function(collection, element) { return true; },
         after_add: function(collection, element) { return true; },
         allow_delete: true,
         delete: '[ - ]',
         before_delete: function(collection, element) { return true; },
         after_delete: function(collection, element) { return true; },
         min: 0,
         max: 100,
         add_at_the_end: false,
         prefix: 'collection',
         prototype_name: '__name__',
         name_prefix: null,
         elements_selector: '> div',
         children: null
      };

      var randomNumber = function() {
         var rand = '' + Math.random() * 1000 * new Date().getTime();
         return rand.replace('.', '').split('').sort(function () {
            return 0.5 - Math.random();
         }).join('');
      };

      var getOrCreateId = function(obj) {
         if (!obj.attr('id')) {
            var generated_id;
            do {
               generated_id = 'i' + randomNumber();
            } while ($('#' + generated_id).length > 0);
            obj.attr('id', generated_id);
         }
         return obj.attr('id');
      };

      var getFieldValue = function (selector) {
         try {
            var jqElem = $(selector);
         } catch (e) {
            return null;
         }
         if (jqElem.length === 0) {
            return null;
         } else if (jqElem.is('input[type="checkbox"]')) {
            return (jqElem.prop('checked') === true ? true : false);
         } else if (jqElem.is('input[type="radio"]') && jqElem.attr('name') !== undefined) {
            return $('input[name="' + jqElem.attr('name') + '"]:checked').val();
         } else if (jqElem.prop('value') !== undefined) {
            return jqElem.val();
         } else {
            return jqElem.html();
         }
      };

      var putFieldValue = function (selector, value) {
         try {
            var jqElem = $(selector);
         } catch (e) {
            return;
         }
         if (jqElem.length === 0) {
            return null;
         } else if (jqElem.is('input[type="checkbox"]') && value) {
            jqElem.attr('checked', true);
         } else if (jqElem.prop('value') !== undefined) {
            jqElem.val(value);
         } else {
            jqElem.html(value);
         }
      };

      var trueOrUndefined = function(value) {
          return undefined === value || value;
      };

      var pregQuote = function(string) {
         return (string + '').replace(/[.?*+^$[\]\\(){}|-]/g, "\\$&");
      };

      var resetCollectionActions = function(collection, settings) {
         collection.find('.' + settings.prefix + '-tmp').remove();
         collection.find('.' + settings.prefix + '-rescue-add').remove();
         collection.find('.' + settings.prefix + '-actions').remove();
      };

      var dumpCollectionActions = function(collection, settings) {

         var init = collection.find('.' + settings.prefix + '-tmp').length === 0;
         var elements = collection.find(settings.elements_selector);

          if (settings.allow_add) {
            if (init) {
                collection.append('');
                if (settings.add) {
                    collection.append(
                            $(settings.add)
                                .addClass(settings.prefix + '-action ' + settings.prefix + '-rescue-add')
                                .data('collection', collection.attr('id'))
                    );
                }
            }
         }

         elements.each(function() {
            var element = $(this);

            if (element.find('> .' + settings.prefix + '-actions').length === 0) {
                var actions = $('

');
                element.append(actions);
            }

            var buttons = [
               {'enabled': 'allow_delete', 'class': settings.prefix + '-delete', 'html': settings.delete, 'condition': elements.length > settings.min},
               {'enabled': 'allow_up', 'class': settings.prefix + '-up', 'html': settings.up, 'condition': elements.index(element) !== 0},
               {'enabled': 'allow_down', 'class': settings.prefix + '-down', 'html': settings.down, 'condition': elements.index(element) !== elements.length - 1},
               {'enabled': 'allow_add', 'class': settings.prefix + '-add', 'html': settings.add, 'condition': !settings.add_at_the_end && elements.length < settings.max},
            ];

            $.each(buttons, function(index, button) {
               if (settings[button.enabled]) {
                   var action = element.find('.' + button.class);
                   if (action.length === 0 && button.html) {
                       action = $(button.html)
                           .appendTo(actions)
                           .addClass(button.class);
                   }
                   if (button.condition) {
                      action.css('display', 'initial');
                   } else {
                      action.css('display', 'none');
                   }
                   action
                     .addClass(settings.prefix + '-action')
                     .data('collection', collection.attr('id'))
                     .data(settings.prefix + '-element', getOrCreateId(element));
               } else {
                  element.find('.' + button.class).css('display', 'none');
               }
            });
         });

         if (settings.allow_add) {
            var rescueAdd = collection.find('.' + settings.prefix + '-rescue-add').css('display', 'initial');
            var adds = collection.find('.' + settings.prefix + '-add:visible');
            if (adds.length > 0) {
                rescueAdd.css('display', 'none');
            }
            if (elements.length >= settings.max) {
                collection.find('.' + settings.prefix + '-add, .' + settings.prefix + '-rescue-add').css('display', 'none');
            }
         }

      };

      var swapElements = function(collection, elements, oldIndex, newIndex) {
         var settings = collection.data('collection-settings');
         var oldField= elements.eq(oldIndex);
         var newField = elements.eq(newIndex);
         $.each(collection.data(settings.prefix + '-skeletons'), function(index, name) {
            var regexp = new RegExp(pregQuote(settings.prototype_name), 'g');
            var oldName = name.replace(regexp, oldIndex);
            var newName = name.replace(regexp, newIndex);
            var swap = getFieldValue(oldField.find("[name='" + oldName + "']"));
            putFieldValue(oldField.find("[name='" + oldName + "']"), getFieldValue(newField.find("[name='" + newName + "']")));
            putFieldValue(newField.find("[name='" + newName + "']"), swap);
         });
      };

      var shiftElementsUp = function(collection, elements, index) {
         for (var i = index + 1; i < elements.length; i++) {
            swapElements(collection, elements, i - 1, i);
         }
      };

      var shiftElementsDown = function(collection, elements, index) {
         for (var i = elements.length - 2; i > index; i--) {
            swapElements(collection, elements, i + 1, i);
         }
      };

      var enableChildrenCollections = function(collection, elements, settings) {
         if (settings.children) {
            $.each(settings.children, function(index, childrenSettings) {
               if (!childrenSettings.selector) {
                 console.log("jquery.collection.js: given collection " + collection.attr('id') + " has children collections, but children's root selector is undefined.");
                 return true;
               }
               if (elements !== null) {
                  elements.find(childrenSettings.selector).collection(childrenSettings);
               } else {
                  collection.find(childrenSettings.selector).collection(childrenSettings);
               }
            });
         }
      };

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

      if ($(settings.container).length === 0) {
         console.log("jquery.collection.js: a container should exist to handle events (basically, a  tag).");
         return false;
      }

      var elems = $(this);

      if (elems.length === 0) {
         console.log("jquery.collection.js: given collection selector does not exist.");
         return false;
      }

      elems.each(function() {

         var elem = $(this);
         if (elem.data('collection') !== undefined) {
            var collection = $('#' + elem.data('collection'));
            if (collection.length === 0) {
               console.log("jquery.collection.js: given collection id does not exist.");
               return true;
            }
         } else {
             collection = elem;
         }

         if (collection.data('prototype') === null) {
            console.log("jquery.collection.js: given collection field has no prototype, check that your field has the prototype option set to true.");
            return true;
         }

        if (collection.data('prototype-name') !== undefined) {
            settings.prototype_name = collection.data('prototype-name');
        }
        if (collection.data('allow-add') !== undefined) {
            settings.allow_add = collection.data('allow-add');
        }
        if (collection.data('allow-delete') !== undefined) {
            settings.allow_delete = collection.data('allow-delete');
        }
        if (collection.data('name-prefix') !== undefined) {
            settings.name_prefix = collection.data('name-prefix');
        }

        if (!settings.name_prefix) {
            console.log("jquery.collection.js: the prefix used in descendant field names is mandatory, you can set it using 2 ways:");
            console.log("jquery.collection.js: - use the form theme given with this plugin source");
            console.log("jquery.collection.js: - set name_prefix option to  '{{ formView.myCollectionField.vars.full_name }}'");
            return true;
        }

         collection.addClass('collection-managed');
         collection.data('collection-settings', settings);

         var skeletons = [];
         $(collection.data('prototype')).find('[name]').each(function() {
            var that = $(this);
            skeletons.push(that.attr('name'));
         });
         collection.data(settings.prefix + '-skeletons', skeletons);

         resetCollectionActions(collection, settings);
         dumpCollectionActions(collection, settings);
         enableChildrenCollections(collection, null, settings);

         var container = $(settings.container);

         container
            .off('click', '.' + settings.prefix + '-action')
            .on('click', '.' + settings.prefix + '-action', function(e) {

               var that = $(this);
               var collection = $('#' + that.data('collection'));
               var settings = collection.data('collection-settings');
               var elements = collection.find(settings.elements_selector);

               var element = that.data(settings.prefix + '-element') ? $('#' + that.data(settings.prefix + '-element')) : undefined;
               if ((that.is('.' + settings.prefix + '-add') || that.is('.' + settings.prefix + '-rescue-add')) && settings.allow_add &&
                       elements.length < settings.max && trueOrUndefined(settings.before_add(collection, element))) {
                  var prototype = collection.data('prototype');
                  for (var index = 0; (index < settings.max); index++) {
                     var regexp = new RegExp(pregQuote(settings.prototype_name), 'g');
                     var code = $(prototype.replace(regexp, index));
                     var tmp = collection.find('> .' + settings.prefix + '-tmp');
                     var id = tmp.html(code).find('[id]').first().attr('id');
                     tmp.empty();
                     if (container.find('#' + id).length === 0) {
                        tmp.before(code);
                        elements = collection.find(settings.elements_selector);
                        var action = code.find('.' + settings.prefix + '-add');
                        if (action.length > 0) {
                           action.addClass(settings.prefix + '-action').data('collection', collection.attr('id'));
                        }

                        if (that.data(settings.prefix + '-element') !== undefined) {
                           var index = elements.index($('#' + that.data(settings.prefix + '-element')));
                           if (index !== -1) {
                              shiftElementsDown(collection, elements, index);
                           }
                        }

                        enableChildrenCollections(collection, code, settings);

                        if (!trueOrUndefined(settings.after_add(collection, code))) {
                            if (index !== -1) {
                                shiftElementsUp(collection, elements, index + 1);
                            }
                            code.remove();
                        }
                        break;
                     }
                  }
               }

               var element = $('#' + that.data(settings.prefix + '-element'));
               var index = elements.index(element);

               if (that.is('.' + settings.prefix + '-delete') && settings.allow_delete &&
                       elements.length > settings.min && trueOrUndefined(settings.before_delete(collection, element))) {
                    shiftElementsUp(collection, elements, index);
                    var toDelete = elements.last();
                    var backup = toDelete.clone({withDataAndEvents: true});
                    toDelete.remove();
                    if (!trueOrUndefined(settings.after_delete(collection, backup))) {
                       collection.find('> .' + settings.prefix + '-tmp').before(backup);
                       elements = collection.find(settings.elements_selector);
                       shiftElementsDown(collection, elements, index - 1);
                    }
               }

               if (that.is('.' + settings.prefix + '-up') && settings.allow_up) {
                  if (index !== 0 && trueOrUndefined(settings.before_up(collection, element))) {
                     swapElements(collection, elements, index, index - 1);
                     if (!trueOrUndefined(settings.after_up(collection, element))) {
                         swapElements(collection, elements, index - 1, index);
                     }
                  }
               }

               if (that.is('.' + settings.prefix + '-down') && settings.allow_down) {
                  if (index !== (elements.length - 1) && trueOrUndefined(settings.before_down(collection, element))) {
                     swapElements(collection, elements, index, index + 1);
                     if (!trueOrUndefined(settings.after_down(collection, elements))) {
                         swapElements(collection, elements, index + 1, index);
                     }
                  }
               }

               dumpCollectionActions(collection, settings);
               e.preventDefault();
            })
         ;

      });

      return true;
   };

})(jQuery);
<commit_msg>now works on collections of form collections<commit_after>/*
* jquery.collection.js v0.0.42
*
* Copyright (c) 2015 alain tiemblo <alain at fuz dot org>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the
* following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

;(function($) {

   $.fn.collection = function(options) {

      var defaults = {
         container: 'body',
         allow_up: true,
         up: '▲',
         before_up: function(collection, element) { return true; },
         after_up: function(collection, element) { return true; },
         allow_down: true,
         down: '▼',
         before_down: function(collection, element) { return true; },
         after_down: function(collection, element) { return true; },
         allow_add: true,
         add: '[ + ]',
         before_add: function(collection, element) { return true; },
         after_add: function(collection, element) { return true; },
         allow_delete: true,
         delete: '[ - ]',
         before_delete: function(collection, element) { return true; },
         after_delete: function(collection, element) { return true; },
         min: 0,
         max: 100,
         add_at_the_end: false,
         prefix: 'collection',
         prototype_name: '__name__',
         name_prefix: null,
         elements_selector: '> div',
         children: null
      };

      var randomNumber = function() {
         var rand = '' + Math.random() * 1000 * new Date().getTime();
         return rand.replace('.', '').split('').sort(function () {
            return 0.5 - Math.random();
         }).join('');
      };

      var getOrCreateId = function(obj) {
         if (!obj.attr('id')) {
            var generated_id;
            do {
               generated_id = 'i' + randomNumber();
            } while ($('#' + generated_id).length > 0);
            obj.attr('id', generated_id);
         }
         return obj.attr('id');
      };

      var getFieldValue = function (selector) {
         try {
            var jqElem = $(selector);
         } catch (e) {
            return null;
         }
         if (jqElem.length === 0) {
            return null;
         } else if (jqElem.is('input[type="checkbox"]')) {
            return (jqElem.prop('checked') === true ? true : false);
         } else if (jqElem.is('input[type="radio"]') && jqElem.attr('name') !== undefined) {
            return $('input[name="' + jqElem.attr('name') + '"]:checked').val();
         } else if (jqElem.prop('value') !== undefined) {
            return jqElem.val();
         } else {
            return jqElem.html();
         }
      };

      var putFieldValue = function (selector, value) {
         try {
            var jqElem = $(selector);
         } catch (e) {
            return;
         }
         if (jqElem.length === 0) {
            return null;
         } else if (jqElem.is('input[type="checkbox"]') && value) {
            jqElem.attr('checked', true);
         } else if (jqElem.prop('value') !== undefined) {
            jqElem.val(value);
         } else {
            jqElem.html(value);
         }
      };

      var trueOrUndefined = function(value) {
          return undefined === value || value;
      };

      var pregQuote = function(string) {
         return (string + '').replace(/[.?*+^$[\]\\(){}|-]/g, "\\$&");
      };

      var resetCollectionActions = function(collection, settings) {
         collection.find('.' + settings.prefix + '-tmp').remove();
         collection.find('.' + settings.prefix + '-rescue-add').remove();
         collection.find('.' + settings.prefix + '-actions').remove();
      };

      var dumpCollectionActions = function(collection, settings) {

         var init = collection.find('.' + settings.prefix + '-tmp').length === 0;
         var elements = collection.find(settings.elements_selector);

          if (settings.allow_add) {
            if (init) {
                collection.append('');
                if (settings.add) {
                    collection.append(
                            $(settings.add)
                                .addClass(settings.prefix + '-action ' + settings.prefix + '-rescue-add')
                                .data('collection', collection.attr('id'))
                    );
                }
            }
         }

         elements.each(function() {
            var element = $(this);

            if (element.find('> .' + settings.prefix + '-actions').length === 0) {
                var actions = $('

');
                element.append(actions);
            }

            var buttons = [
               {'enabled': 'allow_delete', 'class': settings.prefix + '-delete', 'html': settings.delete, 'condition': elements.length > settings.min},
               {'enabled': 'allow_up', 'class': settings.prefix + '-up', 'html': settings.up, 'condition': elements.index(element) !== 0},
               {'enabled': 'allow_down', 'class': settings.prefix + '-down', 'html': settings.down, 'condition': elements.index(element) !== elements.length - 1},
               {'enabled': 'allow_add', 'class': settings.prefix + '-add', 'html': settings.add, 'condition': !settings.add_at_the_end && elements.length < settings.max},
            ];

            $.each(buttons, function(index, button) {
               if (settings[button.enabled]) {
                   var action = element.find('.' + button.class);
                   if (action.length === 0 && button.html) {
                       action = $(button.html)
                           .appendTo(actions)
                           .addClass(button.class);
                   }
                   if (button.condition) {
                      action.css('display', 'initial');
                   } else {
                      action.css('display', 'none');
                   }
                   action
                     .addClass(settings.prefix + '-action')
                     .data('collection', collection.attr('id'))
                     .data(settings.prefix + '-element', getOrCreateId(element));
               } else {
                  element.find('.' + button.class).css('display', 'none');
               }
            });
         });

         if (settings.allow_add) {
            var rescueAdd = collection.find('.' + settings.prefix + '-rescue-add').css('display', 'initial');
            var adds = collection.find('.' + settings.prefix + '-add:visible');
            if (adds.length > 0) {
                rescueAdd.css('display', 'none');
            }
            if (elements.length >= settings.max) {
                collection.find('.' + settings.prefix + '-add, .' + settings.prefix + '-rescue-add').css('display', 'none');
            }
         }

      };

      var swapElements = function(collection, elements, oldIndex, newIndex) {

         var settings = collection.data('collection-settings');

         var replaceAttrData = function(index, toReplace, replaceWith) {
            elements.eq(index).find('*').each(function() {
                var node = $(this);
                $.each(this.attributes, function(i, attrib) {
                    if ($.type(attrib.value) === 'string') {
                        node.attr(attrib.name.replace(toReplace, replaceWith), attrib.value.replace(toReplace, replaceWith));
                    }
                });
                $.each(node.data(), function(name, value) {
                    if ($.type(value) === 'string') {
                        node.data(name.replace(toReplace, replaceWith), value.replace(toReplace, replaceWith));
                    }
                });
            });
         };

         var doSwap = function(index, oldIndex, newIndex) {
            var toReplace = new RegExp(pregQuote(settings.name_prefix + '[' + oldIndex + ']'), 'g');
            var replaceWith = settings.name_prefix + '[' + newIndex + ']';
            replaceAttrData(index, toReplace, replaceWith);

            var toReplace = new RegExp(pregQuote(collection.attr('id') + '_' + oldIndex), 'g');
            var replaceWith = collection.attr('id') + '_' + newIndex;
            replaceAttrData(index, toReplace, replaceWith);
         };

         doSwap(oldIndex, oldIndex, '__swap__');
         doSwap(newIndex, newIndex, oldIndex);
         doSwap(oldIndex, '__swap__', newIndex);

         elements.eq(oldIndex).insertBefore(elements.eq(newIndex));
         if (newIndex > oldIndex) {
            elements.eq(newIndex).insertBefore(elements.eq(oldIndex));
         } else {
            elements.eq(newIndex).insertAfter(elements.eq(oldIndex));
         }

         return collection.find(settings.elements_selector);
     };

      var shiftElementsUp = function(collection, elements, settings, index) {
         for (var i = index + 1; i < elements.length; i++) {
            elements = swapElements(collection, elements, i - 1, i);
         }
         return collection.find(settings.elements_selector);
      };

      var shiftElementsDown = function(collection, elements, settings, index) {
         for (var i = elements.length - 2; i > index; i--) {
            elements = swapElements(collection, elements, i + 1, i);
         }
         return collection.find(settings.elements_selector);
      };

      var enableChildrenCollections = function(collection, elements, settings) {
         if (settings.children) {
            $.each(settings.children, function(index, childrenSettings) {
               if (!childrenSettings.selector) {
                 console.log("jquery.collection.js: given collection " + collection.attr('id') + " has children collections, but children's root selector is undefined.");
                 return true;
               }
               if (elements !== null) {
                  elements.find(childrenSettings.selector).collection(childrenSettings);
               } else {
                  collection.find(childrenSettings.selector).collection(childrenSettings);
               }
            });
         }
      };

      var elems = $(this);

      if (elems.length === 0) {
         console.log("jquery.collection.js: given collection selector does not exist.");
         return false;
      }

      elems.each(function() {

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

         if ($(settings.container).length === 0) {
            console.log("jquery.collection.js: a container should exist to handle events (basically, a  tag).");
            return false;
         }

         var elem = $(this);
         if (elem.data('collection') !== undefined) {
            var collection = $('#' + elem.data('collection'));
            if (collection.length === 0) {
               console.log("jquery.collection.js: given collection id does not exist.");
               return true;
            }
         } else {
             collection = elem;
         }

         if (collection.data('prototype') === null) {
            console.log("jquery.collection.js: given collection field has no prototype, check that your field has the prototype option set to true.");
            return true;
         }

        if (collection.data('prototype-name') !== undefined) {
            settings.prototype_name = collection.data('prototype-name');
        }
        if (collection.data('allow-add') !== undefined) {
            settings.allow_add = collection.data('allow-add');
        }
        if (collection.data('allow-delete') !== undefined) {
            settings.allow_delete = collection.data('allow-delete');
        }
        if (collection.data('name-prefix') !== undefined) {
            settings.name_prefix = collection.data('name-prefix');
        }

        if (!settings.name_prefix) {
            console.log("jquery.collection.js: the prefix used in descendant field names is mandatory, you can set it using 2 ways:");
            console.log("jquery.collection.js: - use the form theme given with this plugin source");
            console.log("jquery.collection.js: - set name_prefix option to  '{{ formView.myCollectionField.vars.full_name }}'");
            return true;
        }

         collection.addClass('collection-managed');
         collection.data('collection-settings', settings);

         resetCollectionActions(collection, settings);
         dumpCollectionActions(collection, settings);
         enableChildrenCollections(collection, null, settings);

         var container = $(settings.container);

         container
            .off('click', '.' + settings.prefix + '-action')
            .on('click', '.' + settings.prefix + '-action', function(e) {

               var that = $(this);

               var collection = $('#' + that.data('collection'));
               var settings = collection.data('collection-settings');

               var elements = collection.find(settings.elements_selector);

               var element = that.data(settings.prefix + '-element') ? $('#' + that.data(settings.prefix + '-element')) : undefined;
               if ((that.is('.' + settings.prefix + '-add') || that.is('.' + settings.prefix + '-rescue-add')) && settings.allow_add &&
                       elements.length < settings.max && trueOrUndefined(settings.before_add(collection, element))) {
                  var prototype = collection.data('prototype');
                  for (var index = 0; (index < settings.max); index++) {
                     var regexp = new RegExp(pregQuote(settings.prototype_name), 'g');
                     var code = $(prototype.replace(regexp, index));
                     var tmp = collection.find('> .' + settings.prefix + '-tmp');
                     var id = tmp.html(code).find('[id]').first().attr('id');
                     tmp.empty();
                     if (container.find('#' + id).length === 0) {
                        tmp.before(code);
                        elements = collection.find(settings.elements_selector);
                        var action = code.find('.' + settings.prefix + '-add');
                        if (action.length > 0) {
                           action.addClass(settings.prefix + '-action').data('collection', collection.attr('id'));
                        }

                        if (that.data(settings.prefix + '-element') !== undefined) {
                           var index = elements.index($('#' + that.data(settings.prefix + '-element')));
                           if (index !== -1) {
                              elements = shiftElementsDown(collection, elements, settings, index);
                           }
                        }

                        enableChildrenCollections(collection, code, settings);

                        if (!trueOrUndefined(settings.after_add(collection, code))) {
                            if (index !== -1) {
                                elements = shiftElementsUp(collection, elements, settings, index + 1);
                            }
                            code.remove();
                        }
                        break;
                     }
                  }
               }

               var element = $('#' + that.data(settings.prefix + '-element'));
               var index = elements.index(element);

               if (that.is('.' + settings.prefix + '-delete') && settings.allow_delete &&
                       elements.length > settings.min && trueOrUndefined(settings.before_delete(collection, element))) {
                    element = shiftElementsUp(collection, elements, settings, index);
                    var toDelete = elements.last();
                    var backup = toDelete.clone({withDataAndEvents: true});
                    toDelete.remove();
                    if (!trueOrUndefined(settings.after_delete(collection, backup))) {
                       collection.find('> .' + settings.prefix + '-tmp').before(backup);
                       elements = collection.find(settings.elements_selector);
                       element = shiftElementsDown(collection, elements, settings, index - 1);
                    }
               }

               if (that.is('.' + settings.prefix + '-up') && settings.allow_up) {
                  if (index !== 0 && trueOrUndefined(settings.before_up(collection, element))) {
                     elements = swapElements(collection, elements, index, index - 1);
                     if (!trueOrUndefined(settings.after_up(collection, element))) {
                         elements = swapElements(collection, elements, index - 1, index);
                     }
                  }
               }

               if (that.is('.' + settings.prefix + '-down') && settings.allow_down) {
                  if (index !== (elements.length - 1) && trueOrUndefined(settings.before_down(collection, element))) {
                     elements = swapElements(collection, elements, index, index + 1);
                     if (!trueOrUndefined(settings.after_down(collection, elements))) {
                         elements = swapElements(collection, elements, index + 1, index);
                     }
                  }
               }

               dumpCollectionActions(collection, settings);
               e.preventDefault();
            })
         ;

      });

      return true;
   };

})(jQuery);
<|endoftext|>


<commit_before>//  elmoSlider v0.0.4 by Michal Dolny
//  dependencies: jQuery

(function($){

    $.fn.elmoSlider = function(options){
        var defaults = {
            speed: 500,
            pause: 2500,
            anim: 'slide',
            autoPlay: false
        };
        options = $.extend(defaults, options);

        var slider = $(this);
        var state = [0];
        var i = 0;
        var j = 0;

        slider.find('.slide').each(function(){
            state[j]=-(j * $(this).width());
            j++;
        });

        // setup css
        if (options.anim === 'slide'){
            slider.find('.slider-content').css({
                width: (state.length * 100 + '%')
            });
            slider.find('.slide').css({
                width: (100 / state.length + '%'),
                'float': 'left',
            });
        } else if (options.anim === 'fade'){
            slider.find('.slider-content').css({
                width: (100 + '%')
            });
            slider.find('.slide').css({
                width: (100 + '%'),
                'float': 'none',
                position: 'absolute',
                opacity: 0
            });
        }
        $(slider).find('.slide').first().addClass('active-slide').css('opacity', '1');

        if (options.pause <= options.speed){
            options.pause = options.speed + 100;
        }

        if (options.autoPlay === false){
            $(slider).on('click', '.slide-left', function(){
                i--;
                if ( i < 0 ){ i = 2 };
                if (options.anim === 'fade'){
                    $('.active-slide').removeClass('active-slide').animate({'opacity': 0}, options.speed);
                    $('.slide'+(i+1)).addClass('active-slide').animate({'opacity': 1}, options.speed);
                } else {
                    $(slider).find('.slider-content').animate({'margin-left': state[i]}, options.speed);
                };
            });
            $(slider).on('click', '.slide-right', function(){
                slideForward();
            });
        }

        if (options.autoPlay === true){
            setInterval(function(){
                slideForward();
            }, options.pause);
        }

        function slideForward(){
            i++;
            if ( i > 2 ){ i = 0 };
            if (options.anim === 'fade'){
                $('.active-slide').removeClass('active-slide').animate({'opacity': 0}, options.speed);
                $('.slide'+(i+1)).addClass('active-slide').animate({'opacity': 1}, options.speed);
            } else {
                $(slider).find('.slider-content').animate({'margin-left': state[i]}, options.speed);
            };
        }

    };

})(jQuery);
<commit_msg>change anim option name<commit_after>//  elmoSlider v0.0.4 by Michal Dolny
//  dependencies: jQuery

(function($){

    $.fn.elmoSlider = function(options){
        var defaults = {
            speed: 500,
            pause: 2500,
            transition: 'slide',
            autoPlay: false
        };
        options = $.extend(defaults, options);

        var slider = $(this);
        var state = [0];
        var i = 0;
        var j = 0;

        slider.find('.slide').each(function(){
            state[j]=-(j * $(this).width());
            j++;
        });

        // setup css
        if (options.transition === 'slide'){
            slider.find('.slider-content').css({
                width: (state.length * 100 + '%')
            });
            slider.find('.slide').css({
                width: (100 / state.length + '%'),
                'float': 'left',
            });
        } else if (options.transition === 'fade'){
            slider.find('.slider-content').css({
                width: (100 + '%')
            });
            slider.find('.slide').css({
                width: (100 + '%'),
                'float': 'none',
                position: 'absolute',
                opacity: 0
            });
        }
        $(slider).find('.slide').first().addClass('active-slide').css('opacity', '1');

        if (options.pause <= options.speed){
            options.pause = options.speed + 100;
        }

        if (options.autoPlay === false){
            $(slider).on('click', '.slide-left', function(){
                i--;
                if ( i < 0 ){ i = 2 };
                if (options.transition === 'fade'){
                    $('.active-slide').removeClass('active-slide').animate({'opacity': 0}, options.speed);
                    $('.slide'+(i+1)).addClass('active-slide').animate({'opacity': 1}, options.speed);
                } else {
                    $(slider).find('.slider-content').animate({'margin-left': state[i]}, options.speed);
                };
            });
            $(slider).on('click', '.slide-right', function(){
                slideForward();
            });
        }

        if (options.autoPlay === true){
            setInterval(function(){
                slideForward();
            }, options.pause);
        }

        function slideForward(){
            i++;
            if ( i > 2 ){ i = 0 };
            if (options.transition === 'fade'){
                $('.active-slide').removeClass('active-slide').animate({'opacity': 0}, options.speed);
                $('.slide'+(i+1)).addClass('active-slide').animate({'opacity': 1}, options.speed);
            } else {
                $(slider).find('.slider-content').animate({'margin-left': state[i]}, options.speed);
            };
        }

    };

})(jQuery);
<|endoftext|>