<commit_before>'use strict'
/*eslint no-unused-vars: 0*/

/**
 * {@link chat-service.ChatService} hooks.
 *
 * @namespace hooks
 * @memberof chat-service
 *
 * @see chat-service.hooks.HooksInterface
 * @see chat-service.hooks.CommandsHooks
 */

/**
 * Before hooks are available for all {@link rpc.clientRequests} and
 * are executed after a command arguments validation, but before
 * Chat Service standard handler.
 *
 * @callback beforeHook
 *
 * @param {chat-service.ExecInfo} execInfo Command execution details.
 * @param {callback} [cb] Optional callback.
 *
 * @return {Promise<Array|undefined>} Resolves without a data to
 * continue a command execution. Rejections or a resolved array will
 * stop further execution, and return results to the command issuer.
 *
 * @static
 */

/**
 * After hooks are available for all {@link rpc.clientRequests} and
 * are executed after Chat Service standard handlers, but before
 * returning results to the command issuer.
 *
 * @callback afterHook
 *
 * @param {chat-service.ExecInfo} execInfo Command execution details.
 * @param {callback} [cb] Optional callback.
 *
 * @return {Promise<Array|undefined>} Resolves without a data to
 * return unchanged command results to the command issuer. Rejections
 * or a resolved array will override command results.
 *
 * @static
 */

/**
 * Commands hooks full list, they are available for all {@link
 * rpc.clientRequests}. There are just two types of command hooks, for
 * a concise description see {@link beforeHook} and {@link afterHook}.
 *
 * @interface
 * @borrows beforeHook as CommandsHooks#directAddToListBefore
 * @borrows afterHook as CommandsHooks#directAddToListAfter
 * @borrows beforeHook as CommandsHooks#directGetAccessListBefore
 * @borrows afterHook as CommandsHooks#directGetAccessListAfter
 * @borrows beforeHook as CommandsHooks#directGetWhitelistModeBefore
 * @borrows afterHook as CommandsHooks#directGetWhitelistModeAfter
 * @borrows beforeHook as CommandsHooks#directMessageBefore
 * @borrows afterHook as CommandsHooks#directMessageAfter
 * @borrows beforeHook as CommandsHooks#directRemoveFromListBefore
 * @borrows afterHook as CommandsHooks#directRemoveFromListAfter
 * @borrows beforeHook as CommandsHooks#directSetWhitelistModeBefore
 * @borrows afterHook as CommandsHooks#directSetWhitelistModeAfter
 * @borrows beforeHook as CommandsHooks#listOwnSocketsBefore
 * @borrows afterHook as CommandsHooks#listOwnSocketsAfter
 * @borrows beforeHook as CommandsHooks#roomAddToListBefore
 * @borrows afterHook as CommandsHooks#roomAddToListAfter
 * @borrows beforeHook as CommandsHooks#roomCreateBefore
 * @borrows afterHook as CommandsHooks#roomCreateAfter
 * @borrows beforeHook as CommandsHooks#roomDeleteBefore
 * @borrows afterHook as CommandsHooks#roomDeleteAfter
 * @borrows beforeHook as CommandsHooks#roomGetAccessListBefore
 * @borrows afterHook as CommandsHooks#roomGetAccessListAfter
 * @borrows beforeHook as CommandsHooks#roomGetOwnerBefore
 * @borrows afterHook as CommandsHooks#roomGetOwnerAfter
 * @borrows beforeHook as CommandsHooks#roomGetWhitelistModeBefore
 * @borrows afterHook as CommandsHooks#roomGetWhitelistModeAfter
 * @borrows beforeHook as CommandsHooks#roomHistoryGetBefore
 * @borrows afterHook as CommandsHooks#roomHistoryGetAfter
 * @borrows beforeHook as CommandsHooks#roomHistoryInfoBefore
 * @borrows afterHook as CommandsHooks#roomHistoryInfoAfter
 * @borrows beforeHook as CommandsHooks#roomJoinBefore
 * @borrows afterHook as CommandsHooks#roomJoinAfter
 * @borrows beforeHook as CommandsHooks#roomLeaveBefore
 * @borrows afterHook as CommandsHooks#roomLeaveAfter
 * @borrows beforeHook as CommandsHooks#roomMessageBefore
 * @borrows afterHook as CommandsHooks#roomMessageAfter
 * @borrows beforeHook as CommandsHooks#roomRecentHistoryBefore
 * @borrows afterHook as CommandsHooks#roomRecentHistoryAfter
 * @borrows beforeHook as CommandsHooks#roomRemoveFromListBefore
 * @borrows afterHook as CommandsHooks#roomRemoveFromListAfter
 * @borrows beforeHook as CommandsHooks#roomSetWhitelistModeBefore
 * @borrows afterHook as CommandsHooks#roomSetWhitelistModeAfter
 * @borrows beforeHook as CommandsHooks#roomUserSeenBefore
 * @borrows afterHook as CommandsHooks#roomUserSeenAfter
 * @borrows beforeHook as CommandsHooks#systemMessageBefore
 * @borrows afterHook as CommandsHooks#systemMessageAfter
 * @memberof chat-service.hooks
 *
 * @see rpc.clientRequests
 * @see chat-service.hooks.HooksInterface
 */
class CommandsHooks {}

/**
 * {@link chat-service.ChatService} hooks interface.
 * @interface
 * @extends chat-service.hooks.CommandsHooks
 * @memberof chat-service.hooks
 */
class HooksInterface extends CommandsHooks {

  /**
   * Client connection hook. Client can send requests or receive
   * notifications only after this hook is resolved.
   *
   * @param {chat-service.ChatService} server Service instance.
   * @param {string} id Socket id.
   * @param {callback} [cb] Optional callback.
   *
   * @return {Promise<Array|string>} Resolves either a login string
   * (user name) or an array with a login string and an optional auth
   * data object. User name and auth data are send back with a {@link
   * rpc.serverNotifications.loginConfirmed} message. Error is sent as
   * a {@link rpc.serverNotifications.loginRejected} message.
   *
   * @static
   */
  onConnect (server, id, cb) {}

  /**
   * Client disconnection hook.
   *
   * @param {chat-service.ChatService} server Service instance.
   * @param {string} id Socket id.
   * @param {callback} [cb] Optional callback.
   *
   * @return {Promise<undefined>} Promise that resolves without any data.
   *
   * @static
   */
  onDisconnect (server, id, cb) {}

  /**
   * Executes when server is started (after a state and a transport are
   * up, but before requests processing is started).
   *
   * @param {chat-service.ChatService} server Service instance.
   * @param {callback} [cb] Optional callback.
   *
   * @return {Promise<undefined>} Promise that resolves without any data.
   *
   * @static
   */
  onStart (server, cb) {}

  /**
   * Executes when server is closed (after a transport is closed and
   * all clients are disconnected, but a state is still up).
   *
   * @param {chat-service.ChatService} server Service instance.
   * @param {Error} [error] An error occurred during closing.
   * @param {callback} [cb] Optional callback.
   *
   * @return {Promise<undefined>} Promise that resolves without any data.
   *
   * @static
   */
  onClose (server, error, cb) {}

  /**
   * Validator for `directMessage` message objects. When is set, a
   * custom format in direct messages is enabled. When hooks resolves,
   * than a message format is considered valid, and the other way
   * around for the rejection case.
   *
   * @param {Object} message Message object.
   * @param {callback} [cb] Optional callback.
   *
   * @return {Promise<undefined>} Promise that resolves without any data.
   *
   * @see rpc.clientRequests.directMessage
   *
   * @static
   */
  directMessagesChecker (message, cb) {}

  /**
   * Validator for `roomMessage` message objects. When is set, a
   * custom format in room messages is enabled. When hooks resolves,
   * than a message format is considered valid, and the other way
   * around for the rejection case.
   *
   * @param {Object} message Message object.
   * @param {callback} [cb] Optional callback.
   *
   * @return {Promise<undefined>} Promise that resolves without any data.
   *
   * @see rpc.clientRequests.roomMessage
   *
   * @static
   */
  roomMessagesChecker (message, cb) {}

}
<commit_msg>docs: add missing hooks in the list<commit_after>'use strict'
/*eslint no-unused-vars: 0*/

/**
 * {@link chat-service.ChatService} hooks.
 *
 * @namespace hooks
 * @memberof chat-service
 *
 * @see chat-service.hooks.HooksInterface
 * @see chat-service.hooks.CommandsHooks
 */

/**
 * Before hooks are available for all {@link rpc.clientRequests} and
 * are executed after a command arguments validation, but before
 * Chat Service standard handler.
 *
 * @callback beforeHook
 *
 * @param {chat-service.ExecInfo} execInfo Command execution details.
 * @param {callback} [cb] Optional callback.
 *
 * @return {Promise<Array|undefined>} Resolves without a data to
 * continue a command execution. Rejections or a resolved array will
 * stop further execution, and return results to the command issuer.
 *
 * @static
 */

/**
 * After hooks are available for all {@link rpc.clientRequests} and
 * are executed after Chat Service standard handlers, but before
 * returning results to the command issuer.
 *
 * @callback afterHook
 *
 * @param {chat-service.ExecInfo} execInfo Command execution details.
 * @param {callback} [cb] Optional callback.
 *
 * @return {Promise<Array|undefined>} Resolves without a data to
 * return unchanged command results to the command issuer. Rejections
 * or a resolved array will override command results.
 *
 * @static
 */

/**
 * Commands hooks full list, they are available for all {@link
 * rpc.clientRequests}. There are just two types of command hooks, for
 * a concise description see {@link beforeHook} and {@link afterHook}.
 *
 * @interface
 * @borrows beforeHook as CommandsHooks#directAddToListBefore
 * @borrows afterHook as CommandsHooks#directAddToListAfter
 * @borrows beforeHook as CommandsHooks#directGetAccessListBefore
 * @borrows afterHook as CommandsHooks#directGetAccessListAfter
 * @borrows beforeHook as CommandsHooks#directGetWhitelistModeBefore
 * @borrows afterHook as CommandsHooks#directGetWhitelistModeAfter
 * @borrows beforeHook as CommandsHooks#directMessageBefore
 * @borrows afterHook as CommandsHooks#directMessageAfter
 * @borrows beforeHook as CommandsHooks#directRemoveFromListBefore
 * @borrows afterHook as CommandsHooks#directRemoveFromListAfter
 * @borrows beforeHook as CommandsHooks#directSetWhitelistModeBefore
 * @borrows afterHook as CommandsHooks#directSetWhitelistModeAfter
 * @borrows beforeHook as CommandsHooks#listOwnSocketsBefore
 * @borrows afterHook as CommandsHooks#listOwnSocketsAfter
 * @borrows beforeHook as CommandsHooks#roomAddToListBefore
 * @borrows afterHook as CommandsHooks#roomAddToListAfter
 * @borrows beforeHook as CommandsHooks#roomCreateBefore
 * @borrows afterHook as CommandsHooks#roomCreateAfter
 * @borrows beforeHook as CommandsHooks#roomDeleteBefore
 * @borrows afterHook as CommandsHooks#roomDeleteAfter
 * @borrows beforeHook as CommandsHooks#roomGetAccessListBefore
 * @borrows afterHook as CommandsHooks#roomGetAccessListAfter
 * @borrows beforeHook as CommandsHooks#roomGetOwnerBefore
 * @borrows afterHook as CommandsHooks#roomGetOwnerAfter
 * @borrows beforeHook as CommandsHooks#roomGetWhitelistModeBefore
 * @borrows afterHook as CommandsHooks#roomGetWhitelistModeAfter
 * @borrows beforeHook as CommandsHooks#roomHistoryGetBefore
 * @borrows afterHook as CommandsHooks#roomHistoryGetAfter
 * @borrows beforeHook as CommandsHooks#roomHistoryInfoBefore
 * @borrows afterHook as CommandsHooks#roomHistoryInfoAfter
 * @borrows beforeHook as CommandsHooks#roomJoinBefore
 * @borrows afterHook as CommandsHooks#roomJoinAfter
 * @borrows beforeHook as CommandsHooks#roomLeaveBefore
 * @borrows afterHook as CommandsHooks#roomLeaveAfter
 * @borrows beforeHook as CommandsHooks#roomMessageBefore
 * @borrows afterHook as CommandsHooks#roomMessageAfter
 * @borrows beforeHook as CommandsHooks#roomNotificationsInfoBefore
 * @borrows afterHook as CommandsHooks#roomNotificationsInfoAfter
 * @borrows beforeHook as CommandsHooks#roomRecentHistoryBefore
 * @borrows afterHook as CommandsHooks#roomRecentHistoryAfter
 * @borrows beforeHook as CommandsHooks#roomRemoveFromListBefore
 * @borrows afterHook as CommandsHooks#roomRemoveFromListAfter
 * @borrows beforeHook as CommandsHooks#roomSetWhitelistModeBefore
 * @borrows afterHook as CommandsHooks#roomSetWhitelistModeAfter
 * @borrows beforeHook as CommandsHooks#roomUserSeenBefore
 * @borrows afterHook as CommandsHooks#roomUserSeenAfter
 * @borrows beforeHook as CommandsHooks#systemMessageBefore
 * @borrows afterHook as CommandsHooks#systemMessageAfter
 * @memberof chat-service.hooks
 *
 * @see rpc.clientRequests
 * @see chat-service.hooks.HooksInterface
 */
class CommandsHooks {}

/**
 * {@link chat-service.ChatService} hooks interface.
 * @interface
 * @extends chat-service.hooks.CommandsHooks
 * @memberof chat-service.hooks
 */
class HooksInterface extends CommandsHooks {

  /**
   * Client connection hook. Client can send requests or receive
   * notifications only after this hook is resolved.
   *
   * @param {chat-service.ChatService} server Service instance.
   * @param {string} id Socket id.
   * @param {callback} [cb] Optional callback.
   *
   * @return {Promise<Array|string>} Resolves either a login string
   * (user name) or an array with a login string and an optional auth
   * data object. User name and auth data are send back with a {@link
   * rpc.serverNotifications.loginConfirmed} message. Error is sent as
   * a {@link rpc.serverNotifications.loginRejected} message.
   *
   * @static
   */
  onConnect (server, id, cb) {}

  /**
   * Client disconnection hook.
   *
   * @param {chat-service.ChatService} server Service instance.
   * @param {string} id Socket id.
   * @param {callback} [cb] Optional callback.
   *
   * @return {Promise<undefined>} Promise that resolves without any data.
   *
   * @static
   */
  onDisconnect (server, id, cb) {}

  /**
   * Executes when server is started (after a state and a transport are
   * up, but before requests processing is started).
   *
   * @param {chat-service.ChatService} server Service instance.
   * @param {callback} [cb] Optional callback.
   *
   * @return {Promise<undefined>} Promise that resolves without any data.
   *
   * @static
   */
  onStart (server, cb) {}

  /**
   * Executes when server is closed (after a transport is closed and
   * all clients are disconnected, but a state is still up).
   *
   * @param {chat-service.ChatService} server Service instance.
   * @param {Error} [error] An error occurred during closing.
   * @param {callback} [cb] Optional callback.
   *
   * @return {Promise<undefined>} Promise that resolves without any data.
   *
   * @static
   */
  onClose (server, error, cb) {}

  /**
   * Validator for `directMessage` message objects. When is set, a
   * custom format in direct messages is enabled. When hooks resolves,
   * than a message format is considered valid, and the other way
   * around for the rejection case.
   *
   * @param {Object} message Message object.
   * @param {callback} [cb] Optional callback.
   *
   * @return {Promise<undefined>} Promise that resolves without any data.
   *
   * @see rpc.clientRequests.directMessage
   *
   * @static
   */
  directMessagesChecker (message, cb) {}

  /**
   * Validator for `roomMessage` message objects. When is set, a
   * custom format in room messages is enabled. When hooks resolves,
   * than a message format is considered valid, and the other way
   * around for the rejection case.
   *
   * @param {Object} message Message object.
   * @param {callback} [cb] Optional callback.
   *
   * @return {Promise<undefined>} Promise that resolves without any data.
   *
   * @see rpc.clientRequests.roomMessage
   *
   * @static
   */
  roomMessagesChecker (message, cb) {}

}
<|endoftext|>


<commit_before>/*
	Key Masher plugin for jQuery (https://github.com/digitalBush/jquery.keymasher)
	Copyright (c) 2010 Josh Bush (digitalbush.com)
	Licensed under the MIT license
	Version: 0.1
*/

(function($,undefined){
		//numberPad={'0':96,'1':97,'2':98,'3':99,'4':100,'5':101,'6':102,'7':103,'8':104,'9':105,'*':106,'+':107,'-':109,'.':110,'/':111},

	var keys=(function(){
		var	defs={},
			keys    = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890`-=[]\\;',./ \t\n",
			shifted = "abcdefghijklmnopqrstuvwxyz!@#$%^&*()~_+{}|:\"<>?",
			noprint={shift:16,ctrl:17,meta:91,alt:18,f1:112,f2:113,f3:114,f4:115,f5:116,f6:117,f7:118,f8:119,f9:120,f10:121,f11:122,f12:123,
					capslock:20,numlock:144,scrolllock:145,pageup:33,pagedown:34,end:35,home:36,backspace:8,
					insert:45,delete:46,pause:19,esc:27,left:37,up:38,right:39,down:40,printscreen:44};

		$.each(keys,function(index,value){
			var keyCode=value.charCodeAt(0),shift=shifted[index];
			defs[value]={keyCode:keyCode,charCode:keyCode,shift:shift};
			if(shift)
				defs[shift]={keyCode:keyCode,charCode:shift.charCodeAt(0),shift:value,requiresShift:index>=26};
		});
		$.each(noprint,function(key,value){defs[key]={keyCode:value};});
		return defs;
	})();

	var KeyMasher=function(elm){
		var	modifierState={alt: false, ctrl: false,	meta: false, shift: false},
			forced={};

		var queueModifierEvent=function(direction,modifier,isForced){
			forced[modifier]=isForced;
			modifierState[modifier]=(direction=='down');
			var event=$.extend($.Event(), modifierState, {type:'key'+direction, keyCode: keys[modifier].keyCode, charCode: 0});
			elm.trigger(event);
		};

		var queueStroke=function(key){
			if($.type(key)==='string')
				key=keys[key];
			if(key.requiresShift && !modifierState.shift)
				queueModifierEvent('down','shift',true);
			else if(modifierState.shift && key.shift)
				key=keys[key.shift];

			var ignore = !key.charCode || modifierState.alt || modifierState.ctrl || modifierState.meta,
				down = $.extend($.Event('keydown'), modifierState, {keyCode: key.keyCode, charCode: 0}),
				press = $.extend($.Event('keypress'), modifierState, {keyCode: key.charCode, charCode: key.charCode}),
				up = $.extend($.Event('keyup'), modifierState, {keyCode: key.keyCode, charCode: 0});

			elm.trigger(down);
			if(!down.isPropagationStopped() && !ignore){
				elm.trigger(press);
				if(!press.isPropagationStopped()){
					//need to do caret positioning
					elm.val(elm.val()+String.fromCharCode(key.charCode));
				}
			}
			elm.trigger(up);

			if(forced.shift)
				queueModifierEvent('up','shift');
		};

		var public={
			hold:function(holding,typing){
				var toks=holding.split(',');
				$.each(toks,function(index,value){queueModifierEvent('down',value);});
				public.type(typing);
				$.each(toks,function(index,value){queueModifierEvent('up',value);});
				return public;
			},
			type:function(){
				$.each(arguments,function(index,typing){
					if($.type(typing)==='string')
						$.each(typing,function(index,value){queueStroke(value);});
					else
						queueStroke(typing);
				});
				return public;
			}
		};
		return $.extend(public,keys);
	};

	$.fn.mashKeys=function(fn){
		if($.type(fn)==='string'){
			var typing=fn;
			fn=function(keys){keys.type(typing)};
		}
		return this.each(function(){
			fn(KeyMasher($(this)));
		});
	};
})(jQuery);<commit_msg>including the 'which' property on the keypress event<commit_after>/*
	Key Masher plugin for jQuery (https://github.com/digitalBush/jquery.keymasher)
	Copyright (c) 2010 Josh Bush (digitalbush.com)
	Licensed under the MIT license
	Version: 0.1
*/

(function($,undefined){
		//numberPad={'0':96,'1':97,'2':98,'3':99,'4':100,'5':101,'6':102,'7':103,'8':104,'9':105,'*':106,'+':107,'-':109,'.':110,'/':111},

	var keys=(function(){
		var	defs={},
			keys    = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890`-=[]\\;',./ \t\n",
			shifted = "abcdefghijklmnopqrstuvwxyz!@#$%^&*()~_+{}|:\"<>?",
			noprint={shift:16,ctrl:17,meta:91,alt:18,f1:112,f2:113,f3:114,f4:115,f5:116,f6:117,f7:118,f8:119,f9:120,f10:121,f11:122,f12:123,
					capslock:20,numlock:144,scrolllock:145,pageup:33,pagedown:34,end:35,home:36,backspace:8,
					insert:45,delete:46,pause:19,esc:27,left:37,up:38,right:39,down:40,printscreen:44};

		$.each(keys,function(index,value){
			var keyCode=value.charCodeAt(0),shift=shifted[index];
			defs[value]={keyCode:keyCode,charCode:keyCode,shift:shift};
			if(shift)
				defs[shift]={keyCode:keyCode,charCode:shift.charCodeAt(0),shift:value,requiresShift:index>=26};
		});
		$.each(noprint,function(key,value){defs[key]={keyCode:value};});
		return defs;
	})();

	var KeyMasher=function(elm){
		var	modifierState={alt: false, ctrl: false,	meta: false, shift: false},
			forced={};

		var queueModifierEvent=function(direction,modifier,isForced){
			forced[modifier]=isForced;
			modifierState[modifier]=(direction=='down');
			var event=$.extend($.Event(), modifierState, {type:'key'+direction, keyCode: keys[modifier].keyCode, charCode: 0});
			elm.trigger(event);
		};

		var queueStroke=function(key){
			if($.type(key)==='string')
				key=keys[key];
			if(key.requiresShift && !modifierState.shift)
				queueModifierEvent('down','shift',true);
			else if(modifierState.shift && key.shift)
				key=keys[key.shift];

			var ignore = !key.charCode || modifierState.alt || modifierState.ctrl || modifierState.meta,
				down = $.extend($.Event('keydown'), modifierState, {keyCode: key.keyCode, charCode: 0}),
				press = $.extend($.Event('keypress'), modifierState, {keyCode: key.charCode, charCode: key.charCode, which: key.charCode}),
				up = $.extend($.Event('keyup'), modifierState, {keyCode: key.keyCode, charCode: 0});

			elm.trigger(down);
			if(!down.isPropagationStopped() && !ignore){
				elm.trigger(press);
				if(!press.isPropagationStopped()){
					//need to do caret positioning
					elm.val(elm.val()+String.fromCharCode(key.charCode));
				}
			}
			elm.trigger(up);

			if(forced.shift)
				queueModifierEvent('up','shift');
		};

		var public={
			hold:function(holding,typing){
				var toks=holding.split(',');
				$.each(toks,function(index,value){queueModifierEvent('down',value);});
				public.type(typing);
				$.each(toks,function(index,value){queueModifierEvent('up',value);});
				return public;
			},
			type:function(){
				$.each(arguments,function(index,typing){
					if($.type(typing)==='string')
						$.each(typing,function(index,value){queueStroke(value);});
					else
						queueStroke(typing);
				});
				return public;
			}
		};
		return $.extend(public,keys);
	};

	$.fn.mashKeys=function(fn){
		if($.type(fn)==='string'){
			var typing=fn;
			fn=function(keys){keys.type(typing)};
		}
		return this.each(function(){
			fn(KeyMasher($(this)));
		});
	};
})(jQuery);<|endoftext|>


<commit_before>(function ($) {
    "use strict";
    if (!$.browser) {
        $.browser = {};
        $.browser.mozilla = /mozilla/.test(navigator.userAgent.toLowerCase()) && !/webkit/.test(navigator.userAgent.toLowerCase());
        $.browser.webkit = /webkit/.test(navigator.userAgent.toLowerCase());
        $.browser.opera = /opera/.test(navigator.userAgent.toLowerCase());
        $.browser.msie = /msie/.test(navigator.userAgent.toLowerCase());
    }

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

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

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

        unmasked : function () {
            return this.map(function () {
                var value = ($(this).val() || "0"),
                    isNegative = value.indexOf("-") !== -1,
                    decimalPart;
                // get the last position of the array that is a number(coercion makes "" to be evaluated as false)
                $(value.split(/\D/).reverse()).each(function (index, element) {
                    if(element) {
                        decimalPart = element;
                        return false;
                   }
                });
                value = value.replace(/\D/g, "");
                value = value.replace(new RegExp(decimalPart + "$"), "." + decimalPart);
                if (isNegative) {
                    value = "-" + value;
                }
                return parseFloat(value);
            });
        },

        init : function (settings) {
            settings = $.extend({
                prefix: "",
                suffix: "",
                affixesStay: true,
                thousands: ",",
                decimal: ".",
                precision: 2,
                allowZero: false,
                allowNegative: false,
                thousandsStay: true
            }, settings);

            return this.each(function () {
                var $input = $(this),
                    onFocusValue;

                // data-* api
                settings = $.extend(settings, $input.data());

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

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

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

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

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

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

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

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

                function canInputMoreNumbers() {
                    var haventReachedMaxLength = !($input.val().length >= $input.attr("maxlength") && $input.attr("maxlength") >= 0),
                        selection = getInputSelection(),
                        start = selection.start,
                        end = selection.end,
                        haveNumberSelected = (selection.start !== selection.end && $input.val().substring(start, end).match(/\d/)) ? true : false,
                        startWithZero = ($input.val().substring(0, 1) === "0");
                    return haventReachedMaxLength || haveNumberSelected || startWithZero;
                }

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

                function setSymbol(value) {
                    var operator = "";
                    if (value.indexOf("-") > -1) {
                        value = value.replace("-", "");
                        operator = "-";
                    }
                    return operator + settings.prefix + value + settings.suffix;
                }

                function maskValue(value) {
                    var negative = (value.indexOf("-") > -1 && settings.allowNegative) ? "-" : "",
                        onlyNumbers = value.replace(/[^0-9]/g, ""),
                        integerPart = onlyNumbers.slice(0, onlyNumbers.length - settings.precision),
                        newValue,
                        decimalPart,
                        leadingZeros;

                    // remove initial zeros
                    integerPart = integerPart.replace(/^0*/g, "");
                    // put settings.thousands every 3 chars
                    integerPart = integerPart.replace(/\B(?=(\d{3})+(?!\d))/g, settings.thousands);
                    if (integerPart === "") {
                        integerPart = "0";
                    }
                    newValue = negative + integerPart;

                    if (settings.precision > 0) {
                        decimalPart = onlyNumbers.slice(onlyNumbers.length - settings.precision);
                        leadingZeros = new Array((settings.precision + 1) - decimalPart.length).join(0);
                        newValue += settings.decimal + leadingZeros + decimalPart;
                    }
                    return setSymbol(newValue);
                }

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

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

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

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

                function keypressEvent(e) {
                    e = e || window.event;
                    var key = e.which || e.charCode || e.keyCode,
                        keyPressedChar,
                        selection,
                        startPos,
                        endPos,
                        value;
                    //added to handle an IE "special" event
                    if (key === undefined) {
                        return false;
                    }

                    // any key except the numbers 0-9
                    if (key < 48 || key > 57) {
                        // -(minus) key
                        if (key === 45) {
                            $input.val(changeSign());
                            return false;
                        // +(plus) key
                        } else if (key === 43) {
                            $input.val($input.val().replace("-", ""));
                            return false;
                        // enter key or tab key
                        } else if (key === 13 || key === 9) {
                            return true;
                        } else if ($.browser.mozilla && (key === 37 || key === 39) && e.charCode === 0) {
                            // needed for left arrow key or right arrow key with firefox
                            // the charCode part is to avoid allowing "%"(e.charCode 0, e.keyCode 37)
                            return true;
                        } else { // any other key with keycode less than 48 and greater than 57
                            preventDefault(e);
                            return true;
                        }
                    } else if (!canInputMoreNumbers()) {
                        return false;
                    } else {
                        preventDefault(e);

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

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

                    selection = getInputSelection();
                    startPos = selection.start;
                    endPos = selection.end;

                    if (key === 8 || key === 46 || key === 63272) { // backspace or delete key (with special case for safari)
                        preventDefault(e);

                        value = $input.val();
                        // not a selection
                        if (startPos === endPos) {
                            // backspace
                            if (key === 8) {
                                if (settings.suffix === "") {
                                    startPos -= 1;
                                } else {
                                    // needed to find the position of the last number to be erased
                                    lastNumber = value.split("").reverse().join("").search(/\d/);
                                    startPos = value.length - lastNumber - 1;
                                    endPos = startPos + 1;
                                }
                            //delete
                            } else {
                                endPos += 1;
                            }
                        }

                        $input.val(value.substring(0, startPos) + value.substring(endPos, value.length));

                        maskAndPosition(startPos);
                        return false;
                    } else if (key === 9) { // tab key
                        return true;
                    } else { // any other key
                        return true;
                    }
                }

                function focusEvent() {
                    onFocusValue = $input.val();
                    mask();
                    var input = $input.get(0),
                        textRange;
                    if (input.createTextRange) {
                        textRange = input.createTextRange();
                        textRange.collapse(false); // set the cursor at the end of the input
                        textRange.select();
                    }
                }

                function cutPasteEvent() {
                    setTimeout(function() {
                        mask();
                    }, 0);
                }

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

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

                    if ($input.val() === "" || $input.val() === setSymbol(getDefaultMask())) {
                        if (!settings.allowZero) {
                            $input.val("");
                        } else if (!settings.affixesStay) {
                            $input.val(getDefaultMask());
                        } else {
                            $input.val(setSymbol(getDefaultMask()));
                        }
                    } else {
                    	var newValue = $input.val();
                        if (!settings.affixesStay) {
                            newValue = newValue.replace(settings.prefix, "").replace(settings.suffix, "");
                        }
                        if (!settings.thousandsStay) {
                            newValue = newValue.replace(new RegExp(settings.thousands,"g"), "");
                        }
                        $input.val(newValue);
                    }
                    if ($input.val() !== onFocusValue) {
                        $input.change();
                    }
                }

                function clickEvent() {
                    var input = $input.get(0),
                        length;
                    if (input.setSelectionRange) {
                        length = $input.val().length;
                        input.setSelectionRange(length, length);
                    } else {
                        $input.val($input.val());
                    }
                }

                $input.unbind(".maskMoney");
                $input.bind("keypress.maskMoney", keypressEvent);
                $input.bind("keydown.maskMoney", keydownEvent);
                $input.bind("blur.maskMoney", blurEvent);
                $input.bind("focus.maskMoney", focusEvent);
                $input.bind("click.maskMoney", clickEvent);
                $input.bind("cut.maskMoney", cutPasteEvent);
                $input.bind("paste.maskMoney", cutPasteEvent);
                $input.bind("mask.maskMoney", mask);
            });
        }
    };

    $.fn.maskMoney = function (method) {
        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === "object" || ! method) {
            return methods.init.apply(this, arguments);
        } else {
            $.error("Method " +  method + " does not exist on jQuery.maskMoney");
        }
    };
})(window.jQuery || window.Zepto);
<commit_msg>fix unmasked with precision 0<commit_after>(function ($) {
    "use strict";
    if (!$.browser) {
        $.browser = {};
        $.browser.mozilla = /mozilla/.test(navigator.userAgent.toLowerCase()) && !/webkit/.test(navigator.userAgent.toLowerCase());
        $.browser.webkit = /webkit/.test(navigator.userAgent.toLowerCase());
        $.browser.opera = /opera/.test(navigator.userAgent.toLowerCase());
        $.browser.msie = /msie/.test(navigator.userAgent.toLowerCase());
    }

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

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

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

        unmasked: function () {
            return this.map(function () {
                var value = ($(this).val() || "0"),
                    settings = $.extend(settings, $(this).data()),
                    re = new RegExp("\\"+settings.prefix+"|\\"+settings.thousands,"g");
                value = value.replace(re, "");
                return parseFloat(value);
            });
        },

        init : function (settings) {
            settings = $.extend({
                prefix: "",
                suffix: "",
                affixesStay: true,
                thousands: ",",
                decimal: ".",
                precision: 2,
                allowZero: false,
                allowNegative: false,
                thousandsStay: true
            }, settings);

            return this.each(function () {
                var $input = $(this),
                    onFocusValue;

                // data-* api
                settings = $.extend(settings, $input.data());

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

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

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

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

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

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

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

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

                function canInputMoreNumbers() {
                    var haventReachedMaxLength = !($input.val().length >= $input.attr("maxlength") && $input.attr("maxlength") >= 0),
                        selection = getInputSelection(),
                        start = selection.start,
                        end = selection.end,
                        haveNumberSelected = (selection.start !== selection.end && $input.val().substring(start, end).match(/\d/)) ? true : false,
                        startWithZero = ($input.val().substring(0, 1) === "0");
                    return haventReachedMaxLength || haveNumberSelected || startWithZero;
                }

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

                function setSymbol(value) {
                    var operator = "";
                    if (value.indexOf("-") > -1) {
                        value = value.replace("-", "");
                        operator = "-";
                    }
                    return operator + settings.prefix + value + settings.suffix;
                }

                function maskValue(value) {
                    var negative = (value.indexOf("-") > -1 && settings.allowNegative) ? "-" : "",
                        onlyNumbers = value.replace(/[^0-9]/g, ""),
                        integerPart = onlyNumbers.slice(0, onlyNumbers.length - settings.precision),
                        newValue,
                        decimalPart,
                        leadingZeros;

                    // remove initial zeros
                    integerPart = integerPart.replace(/^0*/g, "");
                    // put settings.thousands every 3 chars
                    integerPart = integerPart.replace(/\B(?=(\d{3})+(?!\d))/g, settings.thousands);
                    if (integerPart === "") {
                        integerPart = "0";
                    }
                    newValue = negative + integerPart;

                    if (settings.precision > 0) {
                        decimalPart = onlyNumbers.slice(onlyNumbers.length - settings.precision);
                        leadingZeros = new Array((settings.precision + 1) - decimalPart.length).join(0);
                        newValue += settings.decimal + leadingZeros + decimalPart;
                    }
                    return setSymbol(newValue);
                }

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

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

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

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

                function keypressEvent(e) {
                    e = e || window.event;
                    var key = e.which || e.charCode || e.keyCode,
                        keyPressedChar,
                        selection,
                        startPos,
                        endPos,
                        value;
                    //added to handle an IE "special" event
                    if (key === undefined) {
                        return false;
                    }

                    // any key except the numbers 0-9
                    if (key < 48 || key > 57) {
                        // -(minus) key
                        if (key === 45) {
                            $input.val(changeSign());
                            return false;
                        // +(plus) key
                        } else if (key === 43) {
                            $input.val($input.val().replace("-", ""));
                            return false;
                        // enter key or tab key
                        } else if (key === 13 || key === 9) {
                            return true;
                        } else if ($.browser.mozilla && (key === 37 || key === 39) && e.charCode === 0) {
                            // needed for left arrow key or right arrow key with firefox
                            // the charCode part is to avoid allowing "%"(e.charCode 0, e.keyCode 37)
                            return true;
                        } else { // any other key with keycode less than 48 and greater than 57
                            preventDefault(e);
                            return true;
                        }
                    } else if (!canInputMoreNumbers()) {
                        return false;
                    } else {
                        preventDefault(e);

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

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

                    selection = getInputSelection();
                    startPos = selection.start;
                    endPos = selection.end;

                    if (key === 8 || key === 46 || key === 63272) { // backspace or delete key (with special case for safari)
                        preventDefault(e);

                        value = $input.val();
                        // not a selection
                        if (startPos === endPos) {
                            // backspace
                            if (key === 8) {
                                if (settings.suffix === "") {
                                    startPos -= 1;
                                } else {
                                    // needed to find the position of the last number to be erased
                                    lastNumber = value.split("").reverse().join("").search(/\d/);
                                    startPos = value.length - lastNumber - 1;
                                    endPos = startPos + 1;
                                }
                            //delete
                            } else {
                                endPos += 1;
                            }
                        }

                        $input.val(value.substring(0, startPos) + value.substring(endPos, value.length));

                        maskAndPosition(startPos);
                        return false;
                    } else if (key === 9) { // tab key
                        return true;
                    } else { // any other key
                        return true;
                    }
                }

                function focusEvent() {
                    onFocusValue = $input.val();
                    mask();
                    var input = $input.get(0),
                        textRange;
                    if (input.createTextRange) {
                        textRange = input.createTextRange();
                        textRange.collapse(false); // set the cursor at the end of the input
                        textRange.select();
                    }
                }

                function cutPasteEvent() {
                    setTimeout(function() {
                        mask();
                    }, 0);
                }

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

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

                    if ($input.val() === "" || $input.val() === setSymbol(getDefaultMask())) {
                        if (!settings.allowZero) {
                            $input.val("");
                        } else if (!settings.affixesStay) {
                            $input.val(getDefaultMask());
                        } else {
                            $input.val(setSymbol(getDefaultMask()));
                        }
                    } else {
                    	var newValue = $input.val();
                        if (!settings.affixesStay) {
                            newValue = newValue.replace(settings.prefix, "").replace(settings.suffix, "");
                        }
                        if (!settings.thousandsStay) {
                            newValue = newValue.replace(new RegExp(settings.thousands,"g"), "");
                        }
                        $input.val(newValue);
                    }
                    if ($input.val() !== onFocusValue) {
                        $input.change();
                    }
                }

                function clickEvent() {
                    var input = $input.get(0),
                        length;
                    if (input.setSelectionRange) {
                        length = $input.val().length;
                        input.setSelectionRange(length, length);
                    } else {
                        $input.val($input.val());
                    }
                }

                $input.unbind(".maskMoney");
                $input.bind("keypress.maskMoney", keypressEvent);
                $input.bind("keydown.maskMoney", keydownEvent);
                $input.bind("blur.maskMoney", blurEvent);
                $input.bind("focus.maskMoney", focusEvent);
                $input.bind("click.maskMoney", clickEvent);
                $input.bind("cut.maskMoney", cutPasteEvent);
                $input.bind("paste.maskMoney", cutPasteEvent);
                $input.bind("mask.maskMoney", mask);
            });
        }
    };

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


<commit_before>(function ($) {
    "use strict";
    if (!$.browser) {
        $.browser = {};
        $.browser.mozilla = /mozilla/.test(navigator.userAgent.toLowerCase()) && !/webkit/.test(navigator.userAgent.toLowerCase());
        $.browser.webkit = /webkit/.test(navigator.userAgent.toLowerCase());
        $.browser.opera = /opera/.test(navigator.userAgent.toLowerCase());
        $.browser.msie = /msie/.test(navigator.userAgent.toLowerCase());
    }

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

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

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

        unmasked : function () {
            return this.map(function () {
                var value = ($(this).val() || "0"),
                    isNegative = value.indexOf("-") !== -1,
                    decimalPart;
                // get the last position of the array that is a number(coercion makes "" to be evaluated as false)
                $(value.split(/\D/).reverse()).each(function (index, element) {
                    if(element) {
                        decimalPart = element;
                        return false;
                    }
                });
                value = value.replace(/\D/g, "");
                value = value.replace(new RegExp(decimalPart + "$"), "." + decimalPart);
                if (isNegative) {
                    value = "-" + value;
                }
                return parseFloat(value);
            });
        },

        init : function (settings) {
            settings = $.extend({
                prefix: "",
                suffix: "",
                affixesStay: true,
                thousands: ",",
                decimal: ".",
                precision: 2,
                allowZero: false,
                allowNegative: false,
                thousandsStay: true
            }, settings);

            return this.each(function () {
                var $input = $(this),
                    onFocusValue;

                // data-* api
                settings = $.extend(settings, $input.data());

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

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

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

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

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

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

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

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

                function canInputMoreNumbers() {
                    var haventReachedMaxLength = !($input.val().length >= $input.attr("maxlength") && $input.attr("maxlength") >= 0),
                        selection = getInputSelection(),
                        start = selection.start,
                        end = selection.end,
                        haveNumberSelected = (selection.start !== selection.end && $input.val().substring(start, end).match(/\d/)) ? true : false,
                        startWithZero = ($input.val().substring(0, 1) === "0");
                    return haventReachedMaxLength || haveNumberSelected || startWithZero;
                }

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

                function setSymbol(value) {
                    var operator = "";
                    if (value.indexOf("-") > -1) {
                        value = value.replace("-", "");
                        operator = "-";
                    }
                    return operator + settings.prefix + value + settings.suffix;
                }

                function maskValue(value) {
                    var negative = (value.indexOf("-") > -1 && settings.allowNegative) ? "-" : "",
                        onlyNumbers = value.replace(/[^0-9]/g, ""),
                        integerPart = onlyNumbers.slice(0, onlyNumbers.length - settings.precision),
                        newValue,
                        decimalPart,
                        leadingZeros;

                    // remove initial zeros
                    integerPart = integerPart.replace(/^0*/g, "");
                    // put settings.thousands every 3 chars
                    integerPart = integerPart.replace(/\B(?=(\d{3})+(?!\d))/g, settings.thousands);
                    if (integerPart === "") {
                        integerPart = "0";
                    }
                    newValue = negative + integerPart;

                    if (settings.precision > 0) {
                        decimalPart = onlyNumbers.slice(onlyNumbers.length - settings.precision);
                        leadingZeros = new Array((settings.precision + 1) - decimalPart.length).join(0);
                        newValue += settings.decimal + leadingZeros + decimalPart;
                    }
                    return setSymbol(newValue);
                }

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

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

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

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

                function keypressEvent(e) {
                    e = e || window.event;
                    var key = e.which || e.charCode || e.keyCode,
                        keyPressedChar,
                        selection,
                        startPos,
                        endPos,
                        value;
                    //added to handle an IE "special" event
                    if (key === undefined) {
                        return false;
                    }

                    // any key except the numbers 0-9
                    if (key < 48 || key > 57) {
                        // -(minus) key
                        if (key === 45) {
                            $input.val(changeSign());
                            return false;
                            // +(plus) key
                        } else if (key === 43) {
                            $input.val($input.val().replace("-", ""));
                            return false;
                            // enter key or tab key
                        } else if (key === 13 || key === 9) {
                            return true;
                        } else if ($.browser.mozilla && (key === 37 || key === 39) && e.charCode === 0) {
                            // needed for left arrow key or right arrow key with firefox
                            // the charCode part is to avoid allowing "%"(e.charCode 0, e.keyCode 37)
                            return true;
                        } else { // any other key with keycode less than 48 and greater than 57
                            preventDefault(e);
                            return true;
                        }
                    } else if (!canInputMoreNumbers()) {
                        return false;
                    } else {
                        preventDefault(e);

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

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

                    selection = getInputSelection();
                    startPos = selection.start;
                    endPos = selection.end;

                    if (key === 8 || key === 46 || key === 63272) { // backspace or delete key (with special case for safari)
                        preventDefault(e);

                        value = $input.val();
                        // not a selection
                        if (startPos === endPos) {
                            // backspace
                            if (key === 8) {
                                if (settings.suffix === "") {
                                    startPos -= 1;
                                } else {
                                    // needed to find the position of the last number to be erased
                                    lastNumber = value.split("").reverse().join("").search(/\d/);
                                    startPos = value.length - lastNumber - 1;
                                    endPos = startPos + 1;
                                }
                                //delete
                            } else {
                                endPos += 1;
                            }
                        }

                        $input.val(value.substring(0, startPos) + value.substring(endPos, value.length));

                        maskAndPosition(startPos);
                        return false;
                    } else if (key === 9) { // tab key
                        return true;
                    } else { // any other key
                        return true;
                    }
                }

                function focusEvent() {
                    onFocusValue = $input.val();
                    mask();
                    var input = $input.get(0),
                        textRange;
                    if (input.createTextRange) {
                        textRange = input.createTextRange();
                        textRange.collapse(false); // set the cursor at the end of the input
                        textRange.select();
                    }
                }

                function cutPasteEvent() {
                    setTimeout(function() {
                        mask();
                    }, 0);
                }

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

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

                    if ($input.val() === "" || $input.val() === setSymbol(getDefaultMask())) {
                        if (!settings.allowZero) {
                            $input.val("");
                        } else if (!settings.affixesStay) {
                            $input.val(getDefaultMask());
                        } else {
                            $input.val(setSymbol(getDefaultMask()));
                        }
                    } else {
                        var newValue = $input.val();
                        if (!settings.affixesStay) {
                            newValue = newValue.replace(settings.prefix, "").replace(settings.suffix, "");
                        }
                        if (!settings.thousandsStay) {
                            var thTest = new RegExp(settings.thousands,'g');
                            newValue = newValue.replace(thTest, "");
                        }
                        $input.val(newValue);
                    }
                    if ($input.val() !== onFocusValue) {
                        $input.change();
                    }
                }

                function clickEvent() {
                    var input = $input.get(0),
                        length;
                    if (input.setSelectionRange) {
                        length = $input.val().length;
                        input.setSelectionRange(length, length);
                    } else {
                        $input.val($input.val());
                    }
                }

                $input.unbind(".maskMoney");
                $input.bind("keypress.maskMoney", keypressEvent);
                $input.bind("keydown.maskMoney", keydownEvent);
                $input.bind("blur.maskMoney", blurEvent);
                $input.bind("focus.maskMoney", focusEvent);
                $input.bind("click.maskMoney", clickEvent);
                $input.bind("cut.maskMoney", cutPasteEvent);
                $input.bind("paste.maskMoney", cutPasteEvent);
                $input.bind("mask.maskMoney", mask);
            });
        }
    };

    $.fn.maskMoney = function (method) {
        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === "object" || ! method) {
            return methods.init.apply(this, arguments);
        } else {
            $.error("Method " +  method + " does not exist on jQuery.maskMoney");
        }
    };
})(window.jQuery || window.Zepto);
<commit_msg>changed single to double quotes<commit_after>(function ($) {
    "use strict";
    if (!$.browser) {
        $.browser = {};
        $.browser.mozilla = /mozilla/.test(navigator.userAgent.toLowerCase()) && !/webkit/.test(navigator.userAgent.toLowerCase());
        $.browser.webkit = /webkit/.test(navigator.userAgent.toLowerCase());
        $.browser.opera = /opera/.test(navigator.userAgent.toLowerCase());
        $.browser.msie = /msie/.test(navigator.userAgent.toLowerCase());
    }

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

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

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

        unmasked : function () {
            return this.map(function () {
                var value = ($(this).val() || "0"),
                    isNegative = value.indexOf("-") !== -1,
                    decimalPart;
                // get the last position of the array that is a number(coercion makes "" to be evaluated as false)
                $(value.split(/\D/).reverse()).each(function (index, element) {
                    if(element) {
                        decimalPart = element;
                        return false;
                    }
                });
                value = value.replace(/\D/g, "");
                value = value.replace(new RegExp(decimalPart + "$"), "." + decimalPart);
                if (isNegative) {
                    value = "-" + value;
                }
                return parseFloat(value);
            });
        },

        init : function (settings) {
            settings = $.extend({
                prefix: "",
                suffix: "",
                affixesStay: true,
                thousands: ",",
                decimal: ".",
                precision: 2,
                allowZero: false,
                allowNegative: false,
                thousandsStay: true
            }, settings);

            return this.each(function () {
                var $input = $(this),
                    onFocusValue;

                // data-* api
                settings = $.extend(settings, $input.data());

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

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

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

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

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

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

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

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

                function canInputMoreNumbers() {
                    var haventReachedMaxLength = !($input.val().length >= $input.attr("maxlength") && $input.attr("maxlength") >= 0),
                        selection = getInputSelection(),
                        start = selection.start,
                        end = selection.end,
                        haveNumberSelected = (selection.start !== selection.end && $input.val().substring(start, end).match(/\d/)) ? true : false,
                        startWithZero = ($input.val().substring(0, 1) === "0");
                    return haventReachedMaxLength || haveNumberSelected || startWithZero;
                }

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

                function setSymbol(value) {
                    var operator = "";
                    if (value.indexOf("-") > -1) {
                        value = value.replace("-", "");
                        operator = "-";
                    }
                    return operator + settings.prefix + value + settings.suffix;
                }

                function maskValue(value) {
                    var negative = (value.indexOf("-") > -1 && settings.allowNegative) ? "-" : "",
                        onlyNumbers = value.replace(/[^0-9]/g, ""),
                        integerPart = onlyNumbers.slice(0, onlyNumbers.length - settings.precision),
                        newValue,
                        decimalPart,
                        leadingZeros;

                    // remove initial zeros
                    integerPart = integerPart.replace(/^0*/g, "");
                    // put settings.thousands every 3 chars
                    integerPart = integerPart.replace(/\B(?=(\d{3})+(?!\d))/g, settings.thousands);
                    if (integerPart === "") {
                        integerPart = "0";
                    }
                    newValue = negative + integerPart;

                    if (settings.precision > 0) {
                        decimalPart = onlyNumbers.slice(onlyNumbers.length - settings.precision);
                        leadingZeros = new Array((settings.precision + 1) - decimalPart.length).join(0);
                        newValue += settings.decimal + leadingZeros + decimalPart;
                    }
                    return setSymbol(newValue);
                }

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

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

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

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

                function keypressEvent(e) {
                    e = e || window.event;
                    var key = e.which || e.charCode || e.keyCode,
                        keyPressedChar,
                        selection,
                        startPos,
                        endPos,
                        value;
                    //added to handle an IE "special" event
                    if (key === undefined) {
                        return false;
                    }

                    // any key except the numbers 0-9
                    if (key < 48 || key > 57) {
                        // -(minus) key
                        if (key === 45) {
                            $input.val(changeSign());
                            return false;
                            // +(plus) key
                        } else if (key === 43) {
                            $input.val($input.val().replace("-", ""));
                            return false;
                            // enter key or tab key
                        } else if (key === 13 || key === 9) {
                            return true;
                        } else if ($.browser.mozilla && (key === 37 || key === 39) && e.charCode === 0) {
                            // needed for left arrow key or right arrow key with firefox
                            // the charCode part is to avoid allowing "%"(e.charCode 0, e.keyCode 37)
                            return true;
                        } else { // any other key with keycode less than 48 and greater than 57
                            preventDefault(e);
                            return true;
                        }
                    } else if (!canInputMoreNumbers()) {
                        return false;
                    } else {
                        preventDefault(e);

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

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

                    selection = getInputSelection();
                    startPos = selection.start;
                    endPos = selection.end;

                    if (key === 8 || key === 46 || key === 63272) { // backspace or delete key (with special case for safari)
                        preventDefault(e);

                        value = $input.val();
                        // not a selection
                        if (startPos === endPos) {
                            // backspace
                            if (key === 8) {
                                if (settings.suffix === "") {
                                    startPos -= 1;
                                } else {
                                    // needed to find the position of the last number to be erased
                                    lastNumber = value.split("").reverse().join("").search(/\d/);
                                    startPos = value.length - lastNumber - 1;
                                    endPos = startPos + 1;
                                }
                                //delete
                            } else {
                                endPos += 1;
                            }
                        }

                        $input.val(value.substring(0, startPos) + value.substring(endPos, value.length));

                        maskAndPosition(startPos);
                        return false;
                    } else if (key === 9) { // tab key
                        return true;
                    } else { // any other key
                        return true;
                    }
                }

                function focusEvent() {
                    onFocusValue = $input.val();
                    mask();
                    var input = $input.get(0),
                        textRange;
                    if (input.createTextRange) {
                        textRange = input.createTextRange();
                        textRange.collapse(false); // set the cursor at the end of the input
                        textRange.select();
                    }
                }

                function cutPasteEvent() {
                    setTimeout(function() {
                        mask();
                    }, 0);
                }

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

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

                    if ($input.val() === "" || $input.val() === setSymbol(getDefaultMask())) {
                        if (!settings.allowZero) {
                            $input.val("");
                        } else if (!settings.affixesStay) {
                            $input.val(getDefaultMask());
                        } else {
                            $input.val(setSymbol(getDefaultMask()));
                        }
                    } else {
                        var newValue = $input.val();
                        if (!settings.affixesStay) {
                            newValue = newValue.replace(settings.prefix, "").replace(settings.suffix, "");
                        }
                        if (!settings.thousandsStay) {
                            var thTest = new RegExp(settings.thousands,"g");
                            newValue = newValue.replace(thTest, "");
                        }
                        $input.val(newValue);
                    }
                    if ($input.val() !== onFocusValue) {
                        $input.change();
                    }
                }

                function clickEvent() {
                    var input = $input.get(0),
                        length;
                    if (input.setSelectionRange) {
                        length = $input.val().length;
                        input.setSelectionRange(length, length);
                    } else {
                        $input.val($input.val());
                    }
                }

                $input.unbind(".maskMoney");
                $input.bind("keypress.maskMoney", keypressEvent);
                $input.bind("keydown.maskMoney", keydownEvent);
                $input.bind("blur.maskMoney", blurEvent);
                $input.bind("focus.maskMoney", focusEvent);
                $input.bind("click.maskMoney", clickEvent);
                $input.bind("cut.maskMoney", cutPasteEvent);
                $input.bind("paste.maskMoney", cutPasteEvent);
                $input.bind("mask.maskMoney", mask);
            });
        }
    };

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


<commit_before>/* eslint-disable promise/always-return */
import { runAuthenticatedQuery } from "test/utils"

describe("FollowShow", () => {
  it("follows a show", () => {
    const mutation = `
      mutation {
        followShow(input: { partner_show_id: "pop-art-show" }) {
          show {
            id
            name
          }
        }
      }
    `

    const rootValue = {
      followShowLoader: () =>
        Promise.resolve({
          show: {
            id: "pop-art-show",
            name: "Pop Art Show",
          },
        }),
      showLoader: () =>
        Promise.resolve({
          id: "pop-art-show",
          name: "Pop Art Show",
        }),
    }

    const expectedShowData = {
      show: {
        id: "pop-art-show",
        name: "Pop Art Show",
      },
    }

    expect.assertions(1)
    return runAuthenticatedQuery(mutation, rootValue).then(({ followShow }) => {
      expect(followShow).toEqual(expectedShowData)
    })
  })
})
<commit_msg>fixed test (show -> partner_show)<commit_after>/* eslint-disable promise/always-return */
import { runAuthenticatedQuery } from "test/utils"

describe("FollowShow", () => {
  it("follows a show", () => {
    const mutation = `
      mutation {
        followShow(input: { partner_show_id: "pop-art-show" }) {
          show {
            id
            name
          }
        }
      }
    `

    const rootValue = {
      followShowLoader: () =>
        Promise.resolve({
          partner_show: {
            id: "pop-art-show",
            name: "Pop Art Show",
          },
        }),
      showLoader: () =>
        Promise.resolve({
          id: "pop-art-show",
          name: "Pop Art Show",
        }),
    }

    const expectedShowData = {
      show: {
        id: "pop-art-show",
        name: "Pop Art Show",
      },
    }

    expect.assertions(1)
    return runAuthenticatedQuery(mutation, rootValue).then(({ followShow }) => {
      expect(followShow).toEqual(expectedShowData)
    })
  })
})
<|endoftext|>


<commit_before>import React from 'react/addons';

import Board       from '../../models/board';
import BoardAction from '../../actions/board';

import Dialog           from '../../components/dialog';
import BackgroundSelect from '../../components/background-select';
import Minimap          from '../../components/minimap'
/**
 *
 */
export default React.createClass({
	mixins: [ React.addons.PureRenderMixin, React.addons.LinkedStateMixin ],

	propTypes: {
		board: (props) => {
			if(!props.board instanceof Board) throw new Error();
		},
		onDismiss: React.PropTypes.func.isRequired
	},

	getInitialState() {
		return {
			name:             this.props.board.name,
			background:       this.props.board.background,
			customBackground: this.props.board.customBackground,
			width:            this.props.board.size.width,
			height:           this.props.board.size.height
		}
	},

	submit(event) {
		event.preventDefault();

		let size = {
			width: this.state.width,
			height: this.state.height
		};

		if (!isNaN(size.width) && !isNaN(size.height)) {
			if (size.width < 1 || size.height < 1) {
				size.width = this.props.board.size.width;
				size.height = this.props.board.size.height;
			}

			BoardAction.update({
				id: this.props.board.id,
				name: this.state.name,
				background: this.state.background,
				customBackground: this.state.customBackground,
				size: size
			});
		}
		return this.props.onDismiss();
	},

	render() {
		let board = this.props.board.set('size',
			new Board.Size({ width: this.state.width, height: this.state.height }));

		if(this.linkState('background')) {
			board = board.set('background', this.linkState('background').value);
		}

		return (
			<Dialog className="dialog-edit-board"
					onDismiss={this.props.onDismiss}>

					Edit Board

					Board Name
					<input name="board-name" placeholder="Board Name"
						valueLink={this.linkState('name')} autoFocus={true} />

						<Minimap
							board={board}
							isTicketSized={true} />

					<BackgroundSelect background={this.linkState('background')}
						customBackground={this.linkState('customBackground')} />

					Board size (measured in tickets)

								Width
								<input name="board-width"
                                       placeholder="Board Width"
                                       valueLink={this.linkState('width')}
                                       type="number" min="1" />

							Height
								<input name="board-height"
                                       placeholder="Board Height"
                                       valueLink={this.linkState('height')}
                                       type="number" min="1"/>

					<button className="btn-primary" onClick={this.submit}>
						Done
					</button>

			</Dialog>
		);
	}
});
<commit_msg>Number validation on input<commit_after>import React from 'react/addons';

import Board       from '../../models/board';
import BoardAction from '../../actions/board';

import Dialog           from '../../components/dialog';
import BackgroundSelect from '../../components/background-select';
import Minimap          from '../../components/minimap'
/**
 *
 */
export default React.createClass({
	mixins: [ React.addons.PureRenderMixin, React.addons.LinkedStateMixin ],

	propTypes: {
		board: (props) => {
			if(!props.board instanceof Board) throw new Error();
		},
		onDismiss: React.PropTypes.func.isRequired
	},

	getInitialState() {
		return {
			name:             this.props.board.name,
			background:       this.props.board.background,
			customBackground: this.props.board.customBackground,
			width:            this.props.board.size.width,
			height:           this.props.board.size.height
		}
	},

	submit(event) {
		event.preventDefault();

		let size = {
			width: this.state.width,
			height: this.state.height
		};

		let updatePayload = {
			id: this.props.board.id,
			name: this.state.name,
			background: this.state.background,
			customBackground: this.state.customBackground,
		}

		if (!isNaN(size.width) && !isNaN(size.height)) {
			if (size.width < 1 || size.height < 1) {
				size.width = this.props.board.size.width;
				size.height = this.props.board.size.height;
			}
			updatePayload.size = size;
		}

		BoardAction.update(updatePayload);
		return this.props.onDismiss();
	},

	render() {
		let board = this.props.board.set('size',
			new Board.Size({ width: this.state.width, height: this.state.height }));

		if(this.linkState('background')) {
			board = board.set('background', this.linkState('background').value);
		}

		let widthValueLink = {
			value: this.state.width,
			requestChange: (val) => {

				let reg = new RegExp('^[0-9]+$');

				if(reg.test(val)) {
					this.setState({width: val});
				}
			}
		}

		let heightValueLink = {
			value: this.state.height,
			requestChange: (val) => {

				let reg = new RegExp('^[0-9]+$');

				if (reg.test(val)) {
					this.setState({height: val});
				}
			}
		}

		return (
			<Dialog className="dialog-edit-board"
					onDismiss={this.props.onDismiss}>

					Edit Board

					Board Name
					<input name="board-name" placeholder="Board Name"
						valueLink={this.linkState('name')} autoFocus={true} />

						<Minimap
							board={board}
							isTicketSized={true} />

					<BackgroundSelect background={this.linkState('background')}
						customBackground={this.linkState('customBackground')} />

					Board size (measured in tickets)

								Width
								<input name="board-width"
                                       placeholder="Board Width"
                                       valueLink={widthValueLink}
                                       type="number" min="1" />

							Height
								<input name="board-height"
                                       placeholder="Board Height"
                                       valueLink={heightValueLink}
                                       type="number" min="1"/>

					<button className="btn-primary" onClick={this.submit}>
						Done
					</button>

			</Dialog>
		);
	}
});
<|endoftext|>