autonumeric-rails 0.1.9.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,18 @@
1
+ *.gem
2
+ *.rbc
3
+ .bundle
4
+ .config
5
+ .yardoc
6
+ Gemfile.lock
7
+ InstalledFiles
8
+ _yardoc
9
+ coverage
10
+ doc/
11
+ lib/bundler/man
12
+ pkg
13
+ rdoc
14
+ spec/reports
15
+ test/tmp
16
+ test/version_tmp
17
+ tmp
18
+ .idea
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in autonumeric-rails.gemspec
4
+ gemspec
@@ -0,0 +1,22 @@
1
+ Copyright (c) 2013 randoum
2
+
3
+ MIT License
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining
6
+ a copy of this software and associated documentation files (the
7
+ "Software"), to deal in the Software without restriction, including
8
+ without limitation the rights to use, copy, modify, merge, publish,
9
+ distribute, sublicense, and/or sell copies of the Software, and to
10
+ permit persons to whom the Software is furnished to do so, subject to
11
+ the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be
14
+ included in all copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
20
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
21
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
22
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,29 @@
1
+ # Autonumeric::Rails
2
+
3
+ TODO: Write a gem description
4
+
5
+ ## Installation
6
+
7
+ Add this line to your application's Gemfile:
8
+
9
+ gem 'autonumeric-rails'
10
+
11
+ And then execute:
12
+
13
+ $ bundle
14
+
15
+ Or install it yourself as:
16
+
17
+ $ gem install autonumeric-rails
18
+
19
+ ## Usage
20
+
21
+ TODO: Write usage instructions here
22
+
23
+ ## Contributing
24
+
25
+ 1. Fork it
26
+ 2. Create your feature branch (`git checkout -b my-new-feature`)
27
+ 3. Commit your changes (`git commit -am 'Add some feature'`)
28
+ 4. Push to the branch (`git push origin my-new-feature`)
29
+ 5. Create new Pull Request
@@ -0,0 +1 @@
1
+ require "bundler/gem_tasks"
@@ -0,0 +1,23 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path('../lib', __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require 'autonumeric/rails/version'
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = 'autonumeric-rails'
8
+ spec.version = Autonumeric::Rails::VERSION
9
+ spec.authors = ['randoum']
10
+ spec.email = ['randoum@gmail.com']
11
+ spec.summary = %q{Wrap autoNumeric.js library ready-to-use for rails}
12
+ spec.description = %q{Rails ready-to-use autoNumeric.js library that automatically formats currency and numbers. All credits goes to the library creator BobKnothe}
13
+ spec.homepage = 'https://github.com/randoum/autonumeric-rails'
14
+ spec.license = 'MIT'
15
+
16
+ spec.files = `git ls-files`.split($/)
17
+ spec.require_paths = ['lib']
18
+
19
+ spec.add_dependency 'jquery-rails', '>= 2.0.2'
20
+
21
+ spec.add_development_dependency 'bundler', '~> 1.3'
22
+ spec.add_development_dependency 'rake'
23
+ end
@@ -0,0 +1 @@
1
+ require 'autonumeric/rails'
@@ -0,0 +1,2 @@
1
+ require 'autonumeric/rails/engine' if ::Rails.version >= '3.1'
2
+ require 'autonumeric/rails/version'
@@ -0,0 +1,6 @@
1
+ module Autonumeric
2
+ module Rails
3
+ class Engine < ::Rails::Engine
4
+ end
5
+ end
6
+ end
@@ -0,0 +1,5 @@
1
+ module Autonumeric
2
+ module Rails
3
+ VERSION = '0.1.9.15'
4
+ end
5
+ end
@@ -0,0 +1,1251 @@
1
+ /**
2
+ * autoNumeric.js
3
+ * @author: Bob Knothe
4
+ * @author: Sokolov Yura aka funny_falcon
5
+ * @version: 1.9.15 - 2013-08-05 GMT 6:30 PM
6
+ *
7
+ * Created by Robert J. Knothe on 2010-10-25. Please report any bugs to https://github.com/BobKnothe/autoNumeric
8
+ * Created by Sokolov Yura on 2010-11-07
9
+ *
10
+ * Copyright (c) 2011 Robert J. Knothe http://www.decorplanit.com/plugin/
11
+ *
12
+ * The MIT License (http://www.opensource.org/licenses/mit-license.php)
13
+ *
14
+ * Permission is hereby granted, free of charge, to any person
15
+ * obtaining a copy of this software and associated documentation
16
+ * files (the "Software"), to deal in the Software without
17
+ * restriction, including without limitation the rights to use,
18
+ * copy, modify, merge, publish, distribute, sublicense, and/or sell
19
+ * copies of the Software, and to permit persons to whom the
20
+ * Software is furnished to do so, subject to the following
21
+ * conditions:
22
+ *
23
+ * The above copyright notice and this permission notice shall be
24
+ * included in all copies or substantial portions of the Software.
25
+ *
26
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
27
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
28
+ * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
29
+ * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
30
+ * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
31
+ * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
32
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
33
+ * OTHER DEALINGS IN THE SOFTWARE.
34
+ */
35
+ (function ($) {
36
+ "use strict";
37
+ /*jslint browser: true*/
38
+ /*global jQuery: false*/
39
+ /* Cross browser routine for getting selected range/cursor position
40
+ */
41
+ function getElementSelection(that) {
42
+ var position = {};
43
+ if (that.selectionStart === undefined) {
44
+ that.focus();
45
+ var select = document.selection.createRange();
46
+ position.length = select.text.length;
47
+ select.moveStart('character', -that.value.length);
48
+ position.end = select.text.length;
49
+ position.start = position.end - position.length;
50
+ } else {
51
+ position.start = that.selectionStart;
52
+ position.end = that.selectionEnd;
53
+ position.length = position.end - position.start;
54
+ }
55
+ return position;
56
+ }
57
+ /**
58
+ * Cross browser routine for setting selected range/cursor position
59
+ */
60
+ function setElementSelection(that, start, end) {
61
+ if (that.selectionStart === undefined) {
62
+ that.focus();
63
+ var r = that.createTextRange();
64
+ r.collapse(true);
65
+ r.moveEnd('character', end);
66
+ r.moveStart('character', start);
67
+ r.select();
68
+ } else {
69
+ that.selectionStart = start;
70
+ that.selectionEnd = end;
71
+ }
72
+ }
73
+ /**
74
+ * run callbacks in parameters if any
75
+ * any parameter could be a callback:
76
+ * - a function, which invoked with jQuery element, parameters and this parameter name and returns parameter value
77
+ * - a name of function, attached to $(selector).autoNumeric.functionName(){} - which was called previously
78
+ */
79
+ function runCallbacks($this, settings) {
80
+ /**
81
+ * loops through the settings object (option array) to find the following
82
+ * k = option name example k=aNum
83
+ * val = option value example val=0123456789
84
+ */
85
+ $.each(settings, function (k, val) {
86
+ if (typeof val === 'function') {
87
+ settings[k] = val($this, settings, k);
88
+ } else if (typeof $this.autoNumeric[val] === 'function') {
89
+ /**
90
+ * calls the attached function from the html5 data example: data-a-sign="functionName"
91
+ */
92
+ settings[k] = $this.autoNumeric[val]($this, settings, k);
93
+ }
94
+ });
95
+ }
96
+
97
+ function convertKeyToNumber(settings, key) {
98
+ if (typeof (settings[key]) === 'string') {
99
+ settings[key] *= 1;
100
+ }
101
+ }
102
+ /**
103
+ * Preparing user defined options for further usage
104
+ * merge them with defaults appropriatly
105
+ */
106
+ function autoCode($this, settings) {
107
+ runCallbacks($this, settings);
108
+ settings.oEvent = null;
109
+ settings.tagList = ['B', 'CAPTION', 'CITE', 'CODE', 'DD', 'DEL', 'DIV', 'DFN', 'DT', 'EM', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6', 'INS', 'KDB', 'LABEL', 'LI', 'OUTPUT', 'P', 'Q', 'S', 'SAMPLE', 'SPAN', 'STRONG', 'TD', 'TH', 'U', 'VAR'];
110
+ var vmax = settings.vMax.toString().split('.'),
111
+ vmin = (!settings.vMin && settings.vMin !== 0) ? [] : settings.vMin.toString().split('.');
112
+ convertKeyToNumber(settings, 'vMax');
113
+ convertKeyToNumber(settings, 'vMin');
114
+ convertKeyToNumber(settings, 'mDec'); /** set mDec if not defained by user */
115
+ settings.allowLeading = true;
116
+ settings.aNeg = settings.vMin < 0 ? '-' : '';
117
+ vmax[0] = vmax[0].replace('-', '');
118
+ vmin[0] = vmin[0].replace('-', '');
119
+ settings.mInt = Math.max(vmax[0].length, vmin[0].length, 1);
120
+ if (settings.mDec === null) {
121
+ var vmaxLength = 0,
122
+ vminLength = 0;
123
+ if (vmax[1]) {
124
+ vmaxLength = vmax[1].length;
125
+ }
126
+ if (vmin[1]) {
127
+ vminLength = vmin[1].length;
128
+ }
129
+ settings.mDec = Math.max(vmaxLength, vminLength);
130
+ } /** set alternative decimal separator key */
131
+ if (settings.altDec === null && settings.mDec > 0) {
132
+ if (settings.aDec === '.' && settings.aSep !== ',') {
133
+ settings.altDec = ',';
134
+ } else if (settings.aDec === ',' && settings.aSep !== '.') {
135
+ settings.altDec = '.';
136
+ }
137
+ }
138
+ /** cache regexps for autoStrip */
139
+ var aNegReg = settings.aNeg ? '([-\\' + settings.aNeg + ']?)' : '(-?)';
140
+ settings.aNegRegAutoStrip = aNegReg;
141
+ settings.skipFirstAutoStrip = new RegExp(aNegReg + '[^-' + (settings.aNeg ? '\\' + settings.aNeg : '') + '\\' + settings.aDec + '\\d]' + '.*?(\\d|\\' + settings.aDec + '\\d)');
142
+ settings.skipLastAutoStrip = new RegExp('(\\d\\' + settings.aDec + '?)[^\\' + settings.aDec + '\\d]\\D*$');
143
+ var allowed = '-' + settings.aNum + '\\' + settings.aDec;
144
+ settings.allowedAutoStrip = new RegExp('[^' + allowed + ']', 'gi');
145
+ settings.numRegAutoStrip = new RegExp(aNegReg + '(?:\\' + settings.aDec + '?(\\d+\\' + settings.aDec + '\\d+)|(\\d*(?:\\' + settings.aDec + '\\d*)?))');
146
+ return settings;
147
+ }
148
+ /**
149
+ * strip all unwanted characters and leave only a number alert
150
+ */
151
+ function autoStrip(s, settings, strip_zero) {
152
+ if (settings.aSign) { /** remove currency sign */
153
+ while (s.indexOf(settings.aSign) > -1) {
154
+ s = s.replace(settings.aSign, '');
155
+ }
156
+ }
157
+ s = s.replace(settings.skipFirstAutoStrip, '$1$2'); /** first replace anything before digits */
158
+ s = s.replace(settings.skipLastAutoStrip, '$1'); /** then replace anything after digits */
159
+ s = s.replace(settings.allowedAutoStrip, ''); /** then remove any uninterested characters */
160
+ if (settings.altDec) {
161
+ s = s.replace(settings.altDec, settings.aDec);
162
+ } /** get only number string */
163
+ var m = s.match(settings.numRegAutoStrip);
164
+ s = m ? [m[1], m[2], m[3]].join('') : '';
165
+ if ((settings.lZero === 'allow' || settings.lZero === 'keep') && strip_zero !== 'strip') {
166
+ var parts = [],
167
+ nSign = '';
168
+ parts = s.split(settings.aDec);
169
+ if (parts[0].indexOf('-') !== -1) {
170
+ nSign = '-';
171
+ parts[0] = parts[0].replace('-', '');
172
+ }
173
+ if (parts[0].length > settings.mInt && parts[0].charAt(0) === '0') { /** strip leading zero if need */
174
+ parts[0] = parts[0].slice(1);
175
+ }
176
+ s = nSign + parts.join(settings.aDec);
177
+ }
178
+ if ((strip_zero && settings.lZero === 'deny') || (strip_zero && settings.lZero === 'allow' && settings.allowLeading === false)) {
179
+ var strip_reg = '^' + settings.aNegRegAutoStrip + '0*(\\d' + (strip_zero === 'leading' ? ')' : '|$)');
180
+ strip_reg = new RegExp(strip_reg);
181
+ s = s.replace(strip_reg, '$1$2');
182
+ }
183
+ return s;
184
+ }
185
+ /**
186
+ * places or removes brackets on negative values
187
+ */
188
+ function negativeBracket(s, nBracket, oEvent) { /** oEvent = settings.oEvent */
189
+ nBracket = nBracket.split(',');
190
+ if (oEvent === 'set' || oEvent === 'focusout') {
191
+ s = s.replace('-', '');
192
+ s = nBracket[0] + s + nBracket[1];
193
+ } else if ((oEvent === 'get' || oEvent === 'focusin' || oEvent === 'pageLoad') && s.charAt(0) === nBracket[0]) {
194
+ s = s.replace(nBracket[0], '-');
195
+ s = s.replace(nBracket[1], '');
196
+ }
197
+ return s;
198
+ }
199
+ /**
200
+ * truncate decimal part of a number
201
+ */
202
+ function truncateDecimal(s, aDec, mDec) {
203
+ if (aDec && mDec) {
204
+ var parts = s.split(aDec);
205
+ /** truncate decimal part to satisfying length
206
+ * cause we would round it anyway */
207
+ if (parts[1] && parts[1].length > mDec) {
208
+ if (mDec > 0) {
209
+ parts[1] = parts[1].substring(0, mDec);
210
+ s = parts.join(aDec);
211
+ } else {
212
+ s = parts[0];
213
+ }
214
+ }
215
+ }
216
+ return s;
217
+ }
218
+ /**
219
+ * prepare number string to be converted to real number
220
+ */
221
+ function fixNumber(s, aDec, aNeg) {
222
+ if (aDec && aDec !== '.') {
223
+ s = s.replace(aDec, '.');
224
+ }
225
+ if (aNeg && aNeg !== '-') {
226
+ s = s.replace(aNeg, '-');
227
+ }
228
+ if (!s.match(/\d/)) {
229
+ s += '0';
230
+ }
231
+ return s;
232
+ }
233
+ /**
234
+ * function to handle numbers less than 0 that are stored in Exponential notaion ex: .0000001 stored as 1e-7
235
+ */
236
+ function checkValue(value) {
237
+ var decimal = value.indexOf('.');
238
+ if (decimal !== -1) {
239
+ if (decimal === 1 && value.charAt(0) === '0') {
240
+ value = +value;
241
+ if (value < 0.000001 && value > 0) {
242
+ value = (value + 1).toString();
243
+ value = value.substring(1);
244
+ }
245
+ if (value < 0 && value > -1) {
246
+ value = (value - 1).toString();
247
+ value = '-' + value.substring(2);
248
+ }
249
+ value = value.toString();
250
+ } else {
251
+ var parts = value.split('.');
252
+ if (parts[1] !== undefined) {
253
+ if (+parts[1] === 0) {
254
+ value = parts[0];
255
+ } else {
256
+ parts[1] = parts[1].replace(/0*$/, '');
257
+ value = parts.join('.');
258
+ }
259
+ }
260
+ }
261
+ }
262
+ return value.replace(/^0*(\d)/, '$1');
263
+ }
264
+ /**
265
+ * prepare real number to be converted to our format
266
+ */
267
+ function presentNumber(s, aDec, aNeg) {
268
+ if (aNeg && aNeg !== '-') {
269
+ s = s.replace('-', aNeg);
270
+ }
271
+ if (aDec && aDec !== '.') {
272
+ s = s.replace('.', aDec);
273
+ }
274
+ return s;
275
+ }
276
+ /**
277
+ * checking that number satisfy format conditions
278
+ * and lays between settings.vMin and settings.vMax
279
+ * and the string length does not exceed the digits in settings.vMin and settings.vMax
280
+ */
281
+ function autoCheck(s, settings) {
282
+ s = autoStrip(s, settings);
283
+ s = truncateDecimal(s, settings.aDec, settings.mDec);
284
+ s = fixNumber(s, settings.aDec, settings.aNeg);
285
+ var value = +s;
286
+ if (settings.oEvent === 'set' && (value < settings.vMin || value > settings.vMax)) {
287
+ $.error("The value (" + value + ") from the 'set' method falls outside of the vMin / vMax range");
288
+ }
289
+ return value >= settings.vMin && value <= settings.vMax;
290
+ }
291
+ /**
292
+ * private function to check for empty value
293
+ */
294
+ function checkEmpty(iv, settings, signOnEmpty) {
295
+ if (iv === '' || iv === settings.aNeg) {
296
+ if (settings.wEmpty === 'zero') {
297
+ return iv + '0';
298
+ }
299
+ if (settings.wEmpty === 'sign' || signOnEmpty) {
300
+ return iv + settings.aSign;
301
+ }
302
+ return iv;
303
+ }
304
+ return null;
305
+ }
306
+ /**
307
+ * private function that formats our number
308
+ */
309
+ function autoGroup(iv, settings) {
310
+ iv = autoStrip(iv, settings);
311
+ var testNeg = iv.replace(',', '.'),
312
+ empty = checkEmpty(iv, settings, true);
313
+ if (empty !== null) {
314
+ return empty;
315
+ }
316
+ var digitalGroup = '';
317
+ if (settings.dGroup === 2) {
318
+ digitalGroup = /(\d)((\d)(\d{2}?)+)$/;
319
+ } else if (settings.dGroup === 4) {
320
+ digitalGroup = /(\d)((\d{4}?)+)$/;
321
+ } else {
322
+ digitalGroup = /(\d)((\d{3}?)+)$/;
323
+ } /** splits the string at the decimal string */
324
+ var ivSplit = iv.split(settings.aDec);
325
+ if (settings.altDec && ivSplit.length === 1) {
326
+ ivSplit = iv.split(settings.altDec);
327
+ } /** assigns the whole number to the a varibale (s) */
328
+ var s = ivSplit[0];
329
+ if (settings.aSep) {
330
+ while (digitalGroup.test(s)) { /** re-inserts the thousand sepparator via a regualer expression */
331
+ s = s.replace(digitalGroup, '$1' + settings.aSep + '$2');
332
+ }
333
+ }
334
+ if (settings.mDec !== 0 && ivSplit.length > 1) {
335
+ if (ivSplit[1].length > settings.mDec) {
336
+ ivSplit[1] = ivSplit[1].substring(0, settings.mDec);
337
+ } /** joins the whole number with the deciaml value */
338
+ iv = s + settings.aDec + ivSplit[1];
339
+ } else { /** if whole numers only */
340
+ iv = s;
341
+ }
342
+ if (settings.aSign) {
343
+ var has_aNeg = iv.indexOf(settings.aNeg) !== -1;
344
+ iv = iv.replace(settings.aNeg, '');
345
+ iv = settings.pSign === 'p' ? settings.aSign + iv : iv + settings.aSign;
346
+ if (has_aNeg) {
347
+ iv = settings.aNeg + iv;
348
+ }
349
+ }
350
+ if (settings.oEvent === 'set' && testNeg < 0 && settings.nBracket !== null) { /** removes the negative sign and places brackets */
351
+ iv = negativeBracket(iv, settings.nBracket, settings.oEvent);
352
+ }
353
+ return iv;
354
+ }
355
+ /**
356
+ * round number after setting by pasting or $().autoNumericSet()
357
+ * private function for round the number
358
+ * please note this handled as text - Javascript math function can return inaccurate values
359
+ * also this offers multiple rounding metods that are not easily accomplished in javascript
360
+ */
361
+ function autoRound(iv, settings) { /** value to string */
362
+ iv = (iv === '') ? '0' : iv.toString();
363
+ convertKeyToNumber(settings, 'mDec'); /** set mDec to number needed when mDec set by 'update method */
364
+ var ivRounded = '',
365
+ i = 0,
366
+ nSign = '',
367
+ rDec = (typeof (settings.aPad) === 'boolean' || settings.aPad === null) ? (settings.aPad ? settings.mDec : 0) : +settings.aPad;
368
+ var truncateZeros = function (ivRounded) { /** truncate not needed zeros */
369
+ var regex = rDec === 0 ? (/(\.[1-9]*)0*$/) : rDec === 1 ? (/(\.\d[1-9]*)0*$/) : new RegExp('(\\.\\d{' + rDec + '}[1-9]*)0*$');
370
+ ivRounded = ivRounded.replace(regex, '$1'); /** If there are no decimal places, we don't need a decimal point at the end */
371
+ if (rDec === 0) {
372
+ ivRounded = ivRounded.replace(/\.$/, '');
373
+ }
374
+ return ivRounded;
375
+ };
376
+ if (iv.charAt(0) === '-') { /** Checks if the iv (input Value)is a negative value */
377
+ nSign = '-'; /** removes the negative sign will be added back later if required */
378
+ iv = iv.replace('-', '');
379
+ } /** prepend a zero if first character is not a digit (then it is likely to be a dot)*/
380
+ if (!iv.match(/^\d/)) {
381
+ iv = '0' + iv;
382
+ } /** determines if the value is zero - if zero no negative sign */
383
+ if (nSign === '-' && +iv === 0) {
384
+ nSign = '';
385
+ }
386
+ if ((+iv > 0 && settings.lZero !== 'keep') || (iv.length > 0 && settings.lZero === 'allow')) { /** trims leading zero's if needed */
387
+ iv = iv.replace(/^0*(\d)/, '$1');
388
+ }
389
+ var dPos = iv.lastIndexOf('.'), /** virtual decimal position */
390
+ vdPos = dPos === -1 ? iv.length - 1 : dPos, /** checks decimal places to determine if rounding is required */
391
+ cDec = (iv.length - 1) - vdPos; /** check if no rounding is required */
392
+ if (cDec <= settings.mDec) {
393
+ ivRounded = iv; /** check if we need to pad with zeros */
394
+ if (cDec < rDec) {
395
+ if (dPos === -1) {
396
+ ivRounded += '.';
397
+ }
398
+ while (cDec < rDec) {
399
+ var zeros = '000000'.substring(0, rDec - cDec);
400
+ ivRounded += zeros;
401
+ cDec += zeros.length;
402
+ }
403
+ } else if (cDec > rDec) {
404
+ ivRounded = truncateZeros(ivRounded);
405
+ } else if (cDec === 0 && rDec === 0) {
406
+ ivRounded = ivRounded.replace(/\.$/, '');
407
+ }
408
+ return nSign + ivRounded;
409
+ } /** rounded length of the string after rounding */
410
+ var rLength = dPos + settings.mDec, /** test round */
411
+ tRound = +iv.charAt(rLength + 1),
412
+ ivArray = iv.substring(0, rLength + 1).split(''),
413
+ odd = (iv.charAt(rLength) === '.') ? (iv.charAt(rLength - 1) % 2) : (iv.charAt(rLength) % 2);
414
+ if ((tRound > 4 && settings.mRound === 'S') || (tRound > 4 && settings.mRound === 'A' && nSign === '') || (tRound > 5 && settings.mRound === 'A' && nSign === '-') || (tRound > 5 && settings.mRound === 's') || (tRound > 5 && settings.mRound === 'a' && nSign === '') || (tRound > 4 && settings.mRound === 'a' && nSign === '-') || (tRound > 5 && settings.mRound === 'B') || (tRound === 5 && settings.mRound === 'B' && odd === 1) || (tRound > 0 && settings.mRound === 'C' && nSign === '') || (tRound > 0 && settings.mRound === 'F' && nSign === '-') || (tRound > 0 && settings.mRound === 'U')) {
415
+ /** Round up the last digit if required, and continue until no more 9's are found */
416
+ for (i = (ivArray.length - 1); i >= 0; i -= 1) {
417
+ if (ivArray[i] !== '.') {
418
+ ivArray[i] = +ivArray[i] + 1;
419
+ if (ivArray[i] < 10) {
420
+ break;
421
+ }
422
+ if (i > 0) {
423
+ ivArray[i] = '0';
424
+ }
425
+ }
426
+ }
427
+ } /** Reconstruct the string, converting any 10's to 0's */
428
+ ivArray = ivArray.slice(0, rLength + 1);
429
+ ivRounded = truncateZeros(ivArray.join('')); /** return rounded value */
430
+ return nSign + ivRounded;
431
+ }
432
+ /**
433
+ * Holder object for field properties
434
+ */
435
+ function AutoNumericHolder(that, settings) {
436
+ this.settings = settings;
437
+ this.that = that;
438
+ this.$that = $(that);
439
+ this.formatted = false;
440
+ this.settingsClone = autoCode(this.$that, this.settings);
441
+ this.value = that.value;
442
+ }
443
+ AutoNumericHolder.prototype = {
444
+ init: function (e) {
445
+ this.value = this.that.value;
446
+ this.settingsClone = autoCode(this.$that, this.settings);
447
+ this.ctrlKey = e.ctrlKey;
448
+ this.cmdKey = e.metaKey;
449
+ this.shiftKey = e.shiftKey;
450
+ this.selection = getElementSelection(this.that); /** keypress event overwrites meaningfull value of e.keyCode */
451
+ if (e.type === 'keydown' || e.type === 'keyup') {
452
+ this.kdCode = e.keyCode;
453
+ }
454
+ this.which = e.which;
455
+ this.processed = false;
456
+ this.formatted = false;
457
+ },
458
+ setSelection: function (start, end, setReal) {
459
+ start = Math.max(start, 0);
460
+ end = Math.min(end, this.that.value.length);
461
+ this.selection = {
462
+ start: start,
463
+ end: end,
464
+ length: end - start
465
+ };
466
+ if (setReal === undefined || setReal) {
467
+ setElementSelection(this.that, start, end);
468
+ }
469
+ },
470
+ setPosition: function (pos, setReal) {
471
+ this.setSelection(pos, pos, setReal);
472
+ },
473
+ getBeforeAfter: function () {
474
+ var value = this.value,
475
+ left = value.substring(0, this.selection.start),
476
+ right = value.substring(this.selection.end, value.length);
477
+ return [left, right];
478
+ },
479
+ getBeforeAfterStriped: function () {
480
+ var parts = this.getBeforeAfter();
481
+ parts[0] = autoStrip(parts[0], this.settingsClone);
482
+ parts[1] = autoStrip(parts[1], this.settingsClone);
483
+ return parts;
484
+ },
485
+ /**
486
+ * strip parts from excess characters and leading zeroes
487
+ */
488
+ normalizeParts: function (left, right) {
489
+ var settingsClone = this.settingsClone;
490
+ right = autoStrip(right, settingsClone); /** if right is not empty and first character is not aDec, */
491
+ /** we could strip all zeros, otherwise only leading */
492
+ var strip = right.match(/^\d/) ? true : 'leading';
493
+ left = autoStrip(left, settingsClone, strip); /** prevents multiple leading zeros from being entered */
494
+ if ((left === '' || left === settingsClone.aNeg) && settingsClone.lZero === 'deny') {
495
+ if (right > '') {
496
+ right = right.replace(/^0*(\d)/, '$1');
497
+ }
498
+ }
499
+ var new_value = left + right; /** insert zero if has leading dot */
500
+ if (settingsClone.aDec) {
501
+ var m = new_value.match(new RegExp('^' + settingsClone.aNegRegAutoStrip + '\\' + settingsClone.aDec));
502
+ if (m) {
503
+ left = left.replace(m[1], m[1] + '0');
504
+ new_value = left + right;
505
+ }
506
+ } /** insert zero if number is empty and io.wEmpty == 'zero' */
507
+ if (settingsClone.wEmpty === 'zero' && (new_value === settingsClone.aNeg || new_value === '')) {
508
+ left += '0';
509
+ }
510
+ return [left, right];
511
+ },
512
+ /**
513
+ * set part of number to value keeping position of cursor
514
+ */
515
+ setValueParts: function (left, right) {
516
+ var settingsClone = this.settingsClone,
517
+ parts = this.normalizeParts(left, right),
518
+ new_value = parts.join(''),
519
+ position = parts[0].length;
520
+ if (autoCheck(new_value, settingsClone)) {
521
+ new_value = truncateDecimal(new_value, settingsClone.aDec, settingsClone.mDec);
522
+ if (position > new_value.length) {
523
+ position = new_value.length;
524
+ }
525
+ this.value = new_value;
526
+ this.setPosition(position, false);
527
+ return true;
528
+ }
529
+ return false;
530
+ },
531
+ /**
532
+ * helper function for expandSelectionOnSign
533
+ * returns sign position of a formatted value
534
+ */
535
+ signPosition: function () {
536
+ var settingsClone = this.settingsClone,
537
+ aSign = settingsClone.aSign,
538
+ that = this.that;
539
+ if (aSign) {
540
+ var aSignLen = aSign.length;
541
+ if (settingsClone.pSign === 'p') {
542
+ var hasNeg = settingsClone.aNeg && that.value && that.value.charAt(0) === settingsClone.aNeg;
543
+ return hasNeg ? [1, aSignLen + 1] : [0, aSignLen];
544
+ }
545
+ var valueLen = that.value.length;
546
+ return [valueLen - aSignLen, valueLen];
547
+ }
548
+ return [1000, -1];
549
+ },
550
+ /**
551
+ * expands selection to cover whole sign
552
+ * prevents partial deletion/copying/overwritting of a sign
553
+ */
554
+ expandSelectionOnSign: function (setReal) {
555
+ var sign_position = this.signPosition(),
556
+ selection = this.selection;
557
+ if (selection.start < sign_position[1] && selection.end > sign_position[0]) { /** if selection catches something except sign and catches only space from sign */
558
+ if ((selection.start < sign_position[0] || selection.end > sign_position[1]) && this.value.substring(Math.max(selection.start, sign_position[0]), Math.min(selection.end, sign_position[1])).match(/^\s*$/)) { /** then select without empty space */
559
+ if (selection.start < sign_position[0]) {
560
+ this.setSelection(selection.start, sign_position[0], setReal);
561
+ } else {
562
+ this.setSelection(sign_position[1], selection.end, setReal);
563
+ }
564
+ } else { /** else select with whole sign */
565
+ this.setSelection(Math.min(selection.start, sign_position[0]), Math.max(selection.end, sign_position[1]), setReal);
566
+ }
567
+ }
568
+ },
569
+ /**
570
+ * try to strip pasted value to digits
571
+ */
572
+ checkPaste: function () {
573
+ if (this.valuePartsBeforePaste !== undefined) {
574
+ var parts = this.getBeforeAfter(),
575
+ oldParts = this.valuePartsBeforePaste;
576
+ delete this.valuePartsBeforePaste; /** try to strip pasted value first */
577
+ parts[0] = parts[0].substr(0, oldParts[0].length) + autoStrip(parts[0].substr(oldParts[0].length), this.settingsClone);
578
+ if (!this.setValueParts(parts[0], parts[1])) {
579
+ this.value = oldParts.join('');
580
+ this.setPosition(oldParts[0].length, false);
581
+ }
582
+ }
583
+ },
584
+ /**
585
+ * process pasting, cursor moving and skipping of not interesting keys
586
+ * if returns true, futher processing is not performed
587
+ */
588
+ skipAllways: function (e) {
589
+ var kdCode = this.kdCode,
590
+ which = this.which,
591
+ ctrlKey = this.ctrlKey,
592
+ cmdKey = this.cmdKey,
593
+ shiftKey = this.shiftKey; /** catch the ctrl up on ctrl-v */
594
+ if (((ctrlKey || cmdKey) && e.type === 'keyup' && this.valuePartsBeforePaste !== undefined) || (shiftKey && kdCode === 45)) {
595
+ this.checkPaste();
596
+ return false;
597
+ }
598
+ /** codes are taken from http://www.cambiaresearch.com/c4/702b8cd1-e5b0-42e6-83ac-25f0306e3e25/Javascript-Char-Codes-Key-Codes.aspx
599
+ * skip Fx keys, windows keys, other special keys
600
+ */
601
+ if ((kdCode >= 112 && kdCode <= 123) || (kdCode >= 91 && kdCode <= 93) || (kdCode >= 9 && kdCode <= 31) || (kdCode < 8 && (which === 0 || which === kdCode)) || kdCode === 144 || kdCode === 145 || kdCode === 45) {
602
+ return true;
603
+ }
604
+ if ((ctrlKey || cmdKey) && kdCode === 65) { /** if select all (a=65)*/
605
+ return true;
606
+ }
607
+ if ((ctrlKey || cmdKey) && (kdCode === 67 || kdCode === 86 || kdCode === 88)) { /** if copy (c=67) paste (v=86) or cut (x=88) */
608
+ if (e.type === 'keydown') {
609
+ this.expandSelectionOnSign();
610
+ }
611
+ if (kdCode === 86 || kdCode === 45) { /** try to prevent wrong paste */
612
+ if (e.type === 'keydown' || e.type === 'keypress') {
613
+ if (this.valuePartsBeforePaste === undefined) {
614
+ this.valuePartsBeforePaste = this.getBeforeAfter();
615
+ }
616
+ } else {
617
+ this.checkPaste();
618
+ }
619
+ }
620
+ return e.type === 'keydown' || e.type === 'keypress' || kdCode === 67;
621
+ }
622
+ if (ctrlKey || cmdKey) {
623
+ return true;
624
+ }
625
+ if (kdCode === 37 || kdCode === 39) { /** jump over thousand separator */
626
+ var aSep = this.settingsClone.aSep,
627
+ start = this.selection.start,
628
+ value = this.that.value;
629
+ if (e.type === 'keydown' && aSep && !this.shiftKey) {
630
+ if (kdCode === 37 && value.charAt(start - 2) === aSep) {
631
+ this.setPosition(start - 1);
632
+ } else if (kdCode === 39 && value.charAt(start + 1) === aSep) {
633
+ this.setPosition(start + 1);
634
+ }
635
+ }
636
+ return true;
637
+ }
638
+ if (kdCode >= 34 && kdCode <= 40) {
639
+ return true;
640
+ }
641
+ return false;
642
+ },
643
+ /**
644
+ * process deletion of characters
645
+ * returns true if processing performed
646
+ */
647
+ processAllways: function () {
648
+ var parts; /** process backspace or delete */
649
+ if (this.kdCode === 8 || this.kdCode === 46) {
650
+ if (!this.selection.length) {
651
+ parts = this.getBeforeAfterStriped();
652
+ if (this.kdCode === 8) {
653
+ parts[0] = parts[0].substring(0, parts[0].length - 1);
654
+ } else {
655
+ parts[1] = parts[1].substring(1, parts[1].length);
656
+ }
657
+ this.setValueParts(parts[0], parts[1]);
658
+ } else {
659
+ this.expandSelectionOnSign(false);
660
+ parts = this.getBeforeAfterStriped();
661
+ this.setValueParts(parts[0], parts[1]);
662
+ }
663
+ return true;
664
+ }
665
+ return false;
666
+ },
667
+ /**
668
+ * process insertion of characters
669
+ * returns true if processing performed
670
+ */
671
+ processKeypress: function () {
672
+ var settingsClone = this.settingsClone,
673
+ cCode = String.fromCharCode(this.which),
674
+ parts = this.getBeforeAfterStriped(),
675
+ left = parts[0],
676
+ right = parts[1]; /** start rules when the decimal charactor key is pressed */
677
+ /** always use numeric pad dot to insert decimal separator */
678
+ if (cCode === settingsClone.aDec || (settingsClone.altDec && cCode === settingsClone.altDec) || ((cCode === '.' || cCode === ',') && this.kdCode === 110)) { /** do not allow decimal character if no decimal part allowed */
679
+ if (!settingsClone.mDec || !settingsClone.aDec) {
680
+ return true;
681
+ } /** do not allow decimal character before aNeg character */
682
+ if (settingsClone.aNeg && right.indexOf(settingsClone.aNeg) > -1) {
683
+ return true;
684
+ } /** do not allow decimal character if other decimal character present */
685
+ if (left.indexOf(settingsClone.aDec) > -1) {
686
+ return true;
687
+ }
688
+ if (right.indexOf(settingsClone.aDec) > 0) {
689
+ return true;
690
+ }
691
+ if (right.indexOf(settingsClone.aDec) === 0) {
692
+ right = right.substr(1);
693
+ }
694
+ this.setValueParts(left + settingsClone.aDec, right);
695
+ return true;
696
+ } /** start rule on negative sign */
697
+
698
+ if (cCode === '-' || cCode === '+') { /** prevent minus if not allowed */
699
+ if (!settingsClone.aNeg) {
700
+ return true;
701
+ } /** carret is always after minus */
702
+ if (left === '' && right.indexOf(settingsClone.aNeg) > -1) {
703
+ left = settingsClone.aNeg;
704
+ right = right.substring(1, right.length);
705
+ } /** change sign of number, remove part if should */
706
+ if (left.charAt(0) === settingsClone.aNeg) {
707
+ left = left.substring(1, left.length);
708
+ } else {
709
+ left = (cCode === '-') ? settingsClone.aNeg + left : left;
710
+ }
711
+ this.setValueParts(left, right);
712
+ return true;
713
+ } /** digits */
714
+ if (cCode >= '0' && cCode <= '9') { /** if try to insert digit before minus */
715
+ if (settingsClone.aNeg && left === '' && right.indexOf(settingsClone.aNeg) > -1) {
716
+ left = settingsClone.aNeg;
717
+ right = right.substring(1, right.length);
718
+ }
719
+ if (settingsClone.vMax <= 0 && settingsClone.vMin < settingsClone.vMax && this.value.indexOf(settingsClone.aNeg) === -1 && cCode !== '0') {
720
+ left = settingsClone.aNeg + left;
721
+ }
722
+ this.setValueParts(left + cCode, right);
723
+ return true;
724
+ } /** prevent any other character */
725
+ return true;
726
+ },
727
+ /**
728
+ * formatting of just processed value with keeping of cursor position
729
+ */
730
+ formatQuick: function () {
731
+ var settingsClone = this.settingsClone,
732
+ parts = this.getBeforeAfterStriped(),
733
+ leftLength = this.value;
734
+ if ((settingsClone.aSep === '' || (settingsClone.aSep !== '' && leftLength.indexOf(settingsClone.aSep) === -1)) && (settingsClone.aSign === '' || (settingsClone.aSign !== '' && leftLength.indexOf(settingsClone.aSign) === -1))) {
735
+ var subParts = [],
736
+ nSign = '';
737
+ subParts = leftLength.split(settingsClone.aDec);
738
+ if (subParts[0].indexOf('-') > -1) {
739
+ nSign = '-';
740
+ subParts[0] = subParts[0].replace('-', '');
741
+ parts[0] = parts[0].replace('-', '');
742
+ }
743
+ if (subParts[0].length > settingsClone.mInt && parts[0].charAt(0) === '0') { /** strip leading zero if need */
744
+ parts[0] = parts[0].slice(1);
745
+ }
746
+ parts[0] = nSign + parts[0];
747
+ }
748
+ var value = autoGroup(this.value, this.settingsClone),
749
+ position = value.length;
750
+ if (value) {
751
+ /** prepare regexp which searches for cursor position from unformatted left part */
752
+ var left_ar = parts[0].split(''),
753
+ i = 0;
754
+ for (i; i < left_ar.length; i += 1) { /** thanks Peter Kovari */
755
+ if (!left_ar[i].match('\\d')) {
756
+ left_ar[i] = '\\' + left_ar[i];
757
+ }
758
+ }
759
+ var leftReg = new RegExp('^.*?' + left_ar.join('.*?'));
760
+ /** search cursor position in formatted value */
761
+ var newLeft = value.match(leftReg);
762
+ if (newLeft) {
763
+ position = newLeft[0].length;
764
+ /** if we are just before sign which is in prefix position */
765
+ if (((position === 0 && value.charAt(0) !== settingsClone.aNeg) || (position === 1 && value.charAt(0) === settingsClone.aNeg)) && settingsClone.aSign && settingsClone.pSign === 'p') {
766
+ /** place carret after prefix sign */
767
+ position = this.settingsClone.aSign.length + (value.charAt(0) === '-' ? 1 : 0);
768
+ }
769
+ } else if (settingsClone.aSign && settingsClone.pSign === 's') {
770
+ /** if we could not find a place for cursor and have a sign as a suffix */
771
+ /** place carret before suffix currency sign */
772
+ position -= settingsClone.aSign.length;
773
+ }
774
+ }
775
+ this.that.value = value;
776
+ this.setPosition(position);
777
+ this.formatted = true;
778
+ }
779
+ };
780
+ /** thanks to Anthony & Evan C */
781
+ function autoGet(obj) {
782
+ if (typeof obj === 'string') {
783
+ obj = obj.replace(/\[/g, "\\[").replace(/\]/g, "\\]");
784
+ obj = '#' + obj.replace(/(:|\.)/g, '\\$1');
785
+ /** obj = '#' + obj.replace(/([;&,\.\+\*\~':"\!\^#$%@\[\]\(\)=>\|])/g, '\\$1'); */
786
+ /** possible modification to replace the above 2 lines */
787
+ }
788
+ return $(obj);
789
+ }
790
+
791
+ function getHolder($that, settings, update) {
792
+ var data = $that.data('autoNumeric');
793
+ if (!data) {
794
+ data = {};
795
+ $that.data('autoNumeric', data);
796
+ }
797
+ var holder = data.holder;
798
+ if ((holder === undefined && settings) || update) {
799
+ holder = new AutoNumericHolder($that.get(0), settings);
800
+ data.holder = holder;
801
+ }
802
+ return holder;
803
+ }
804
+ var methods = {
805
+ init: function (options) {
806
+ return this.each(function () {
807
+ var $this = $(this),
808
+ settings = $this.data('autoNumeric'), /** attempt to grab 'autoNumeric' settings, if they don't exist returns "undefined". */
809
+ tagData = $this.data(); /** attempt to grab HTML5 data, if they don't exist we'll get "undefined".*/
810
+ if (typeof settings !== 'object') { /** If we could't grab settings, create them from defaults and passed options. */
811
+ var defaults = {
812
+ /** allowed numeric values
813
+ * please do not modify
814
+ */
815
+ aNum: '0123456789',
816
+ /** allowed thousand separator characters
817
+ * comma = ','
818
+ * period "full stop" = '.'
819
+ * apostrophe is escaped = '\''
820
+ * space = ' '
821
+ * none = ''
822
+ * NOTE: do not use numeric characters
823
+ */
824
+ aSep: ',',
825
+ /** digital grouping for the thousand separator used in Format
826
+ * dGroup: '2', results in 99,99,99,999 common in India for values less than 1 billion and greater than -1 billion
827
+ * dGroup: '3', results in 999,999,999 default
828
+ * dGroup: '4', results in 9999,9999,9999 used in some Asian countries
829
+ */
830
+ dGroup: '3',
831
+ /** allowed decimal separator characters
832
+ * period "full stop" = '.'
833
+ * comma = ','
834
+ */
835
+ aDec: '.',
836
+ /** allow to declare alternative decimal separator which is automatically replaced by aDec
837
+ * developed for countries the use a comma ',' as the decimal character
838
+ * and have keyboards\numeric pads that have a period 'full stop' as the decimal characters (Spain is an example)
839
+ */
840
+ altDec: null,
841
+ /** allowed currency symbol
842
+ * Must be in quotes aSign: '$', a space is allowed aSign: '$ '
843
+ */
844
+ aSign: '',
845
+ /** placement of currency sign
846
+ * for prefix pSign: 'p',
847
+ * for suffix pSign: 's',
848
+ */
849
+ pSign: 'p',
850
+ /** maximum possible value
851
+ * value must be enclosed in quotes and use the period for the decimal point
852
+ * value must be larger than vMin
853
+ */
854
+ vMax: '999999999.99',
855
+ /** minimum possible value
856
+ * value must be enclosed in quotes and use the period for the decimal point
857
+ * value must be smaller than vMax
858
+ */
859
+ vMin: '0.00',
860
+ /** max number of decimal places = used to overide deciaml places set by the vMin & vMax values
861
+ * value must be enclosed in quotes example mDec: '3',
862
+ * This can also set the value via a call back function mDec: 'css:#
863
+ */
864
+ mDec: null,
865
+ /** method used for rounding
866
+ * mRound: 'S', Round-Half-Up Symmetric (default)
867
+ * mRound: 'A', Round-Half-Up Asymmetric
868
+ * mRound: 's', Round-Half-Down Symmetric (lower case s)
869
+ * mRound: 'a', Round-Half-Down Asymmetric (lower case a)
870
+ * mRound: 'B', Round-Half-Even "Bankers Rounding"
871
+ * mRound: 'U', Round Up "Round-Away-From-Zero"
872
+ * mRound: 'D', Round Down "Round-Toward-Zero" - same as trancate
873
+ * mRound: 'C', Round to Ceiling "Toward Positive Infinity"
874
+ * mRound: 'F', Round to Floor "Toward Negative Infinity"
875
+ */
876
+ mRound: 'S',
877
+ /** controls decimal padding
878
+ * aPad: true - always Pad decimals with zeros
879
+ * aPad: false - does not pad with zeros.
880
+ * aPad: `some number` - pad decimals with zero to number different from mDec
881
+ * thanks to Jonas Johansson for the suggestion
882
+ */
883
+ aPad: true,
884
+ /** places brackets on negative value -$ 999.99 to (999.99)
885
+ * visible only when the field does NOT have focus the left and right symbols should be enclosed in quotes and seperated by a comma
886
+ * nBracket: null, nBracket: '(,)', nBracket: '[,]', nBracket: '<,>' or nBracket: '{,}'
887
+ */
888
+ nBracket: null,
889
+ /** Displayed on empty string
890
+ * wEmpty: 'empty', - input can be blank
891
+ * wEmpty: 'zero', - displays zero
892
+ * wEmpty: 'sign', - displays the currency sign
893
+ */
894
+ wEmpty: 'empty',
895
+ /** controls leading zero behavior
896
+ * lZero: 'allow', - allows leading zeros to be entered. Zeros will be truncated when entering additional digits. On focusout zeros will be deleted.
897
+ * lZero: 'deny', - allows only one leading zero on values less than one
898
+ * lZero: 'keep', - allows leading zeros to be entered. on fousout zeros will be retained.
899
+ */
900
+ lZero: 'allow',
901
+ /** determine if the default value will be formatted on page ready.
902
+ * true = atomatically formats the default value on page ready
903
+ * false = will not format the default value
904
+ */
905
+ aForm: true,
906
+ /** future use */
907
+ onSomeEvent: function () {}
908
+ };
909
+ settings = $.extend({}, defaults, tagData, options); /** Merge defaults, tagData and options */
910
+ if (settings.aDec === settings.aSep) {
911
+ $.error("autoNumeric will not function properly when the decimal character aDec: '" + settings.aDec + "' and thousand seperater aSep: '" + settings.aSep + "' are the same character");
912
+ return this;
913
+ }
914
+ $this.data('autoNumeric', settings); /** Save our new settings */
915
+ } else {
916
+ return this;
917
+ }
918
+ settings.lastSetValue = '';
919
+ settings.runOnce = false;
920
+ var holder = getHolder($this, settings);
921
+ if ($.inArray($this.prop('tagName'), settings.tagList) === -1 && $this.prop('tagName') !== 'INPUT') {
922
+ $.error("The <" + $this.prop('tagName') + "> is not supported by autoNumeric()");
923
+ return this;
924
+ }
925
+ if (settings.runOnce === false && settings.aForm) {/** routine to format default value on page load */
926
+ if ($this.is('input[type=text], input[type=hidden], input:not([type])')) {
927
+ var setValue = true;
928
+ if ($this[0].value === '' && settings.wEmpty === 'empty') {
929
+ $this[0].value = '';
930
+ setValue = false;
931
+ }
932
+ if ($this[0].value === '' && settings.wEmpty === 'sign') {
933
+ $this[0].value = settings.aSign;
934
+ setValue = false;
935
+ }
936
+ if (setValue) {
937
+ $this.autoNumeric('set', $this.val());
938
+ }
939
+ }
940
+ if ($.inArray($this.prop('tagName'), settings.tagList) !== -1 && $this.text() !== '') {
941
+ $this.autoNumeric('set', $this.text());
942
+ }
943
+ }
944
+ settings.runOnce = true;
945
+ if ($this.is('input[type=text], input[type=hidden], input:not([type])')) { /**added hidden type */
946
+ $this.on('keydown.autoNumeric', function (e) {
947
+ holder = getHolder($this);
948
+ if (holder.settings.aDec === holder.settings.aSep) {
949
+ $.error("autoNumeric will not function properly when the decimal character aDec: '" + holder.settings.aDec + "' and thousand seperater aSep: '" + holder.settings.aSep + "' are the same character");
950
+ return this;
951
+ }
952
+ if (holder.that.readOnly) {
953
+ holder.processed = true;
954
+ return true;
955
+ }
956
+ /** The below streamed code / comment allows the "enter" keydown to throw a change() event */
957
+ /** if (e.keyCode === 13 && holder.inVal !== $this.val()){
958
+ $this.change();
959
+ holder.inVal = $this.val();
960
+ }*/
961
+ holder.init(e);
962
+ holder.settings.oEvent = 'keydown';
963
+ if (holder.skipAllways(e)) {
964
+ holder.processed = true;
965
+ return true;
966
+ }
967
+ if (holder.processAllways()) {
968
+ holder.processed = true;
969
+ holder.formatQuick();
970
+ e.preventDefault();
971
+ return false;
972
+ }
973
+ holder.formatted = false;
974
+ return true;
975
+ });
976
+ $this.on('keypress.autoNumeric', function (e) {
977
+ var holder = getHolder($this),
978
+ processed = holder.processed;
979
+ holder.init(e);
980
+ holder.settings.oEvent = 'keypress';
981
+ if (holder.skipAllways(e)) {
982
+ return true;
983
+ }
984
+ if (processed) {
985
+ e.preventDefault();
986
+ return false;
987
+ }
988
+ if (holder.processAllways() || holder.processKeypress()) {
989
+ holder.formatQuick();
990
+ e.preventDefault();
991
+ return false;
992
+ }
993
+ holder.formatted = false;
994
+
995
+ });
996
+ $this.on('keyup.autoNumeric', function (e) {
997
+ var holder = getHolder($this);
998
+ holder.init(e);
999
+ holder.settings.oEvent = 'keyup';
1000
+ var skip = holder.skipAllways(e);
1001
+ holder.kdCode = 0;
1002
+ delete holder.valuePartsBeforePaste;
1003
+ if ($this[0].value === holder.settings.aSign) { /** added to properly place the caret when only the currency is present */
1004
+ if (holder.settings.pSign === 's') {
1005
+ setElementSelection(this, 0, 0);
1006
+ } else {
1007
+ setElementSelection(this, holder.settings.aSign.length, holder.settings.aSign.length);
1008
+ }
1009
+ }
1010
+ if (skip) {
1011
+ return true;
1012
+ }
1013
+ if (this.value === '') {
1014
+ return true;
1015
+ }
1016
+ if (!holder.formatted) {
1017
+ holder.formatQuick();
1018
+ }
1019
+ });
1020
+ $this.on('focusin.autoNumeric', function () {
1021
+ var holder = getHolder($this);
1022
+ holder.settingsClone.oEvent = 'focusin';
1023
+ if (holder.settingsClone.nBracket !== null) {
1024
+ var checkVal = $this.val();
1025
+ $this.val(negativeBracket(checkVal, holder.settingsClone.nBracket, holder.settingsClone.oEvent));
1026
+ }
1027
+ holder.inVal = $this.val();
1028
+ var onempty = checkEmpty(holder.inVal, holder.settingsClone, true);
1029
+ if (onempty !== null) {
1030
+ $this.val(onempty);
1031
+ if (holder.settings.pSign === 's') {
1032
+ setElementSelection(this, 0, 0);
1033
+ } else {
1034
+ setElementSelection(this, holder.settings.aSign.length, holder.settings.aSign.length);
1035
+ }
1036
+ }
1037
+ });
1038
+ $this.on('focusout.autoNumeric', function () {
1039
+ var holder = getHolder($this),
1040
+ settingsClone = holder.settingsClone,
1041
+ value = $this.val(),
1042
+ origValue = value;
1043
+ holder.settingsClone.oEvent = 'focusout';
1044
+ var strip_zero = ''; /** added to control leading zero */
1045
+ if (settingsClone.lZero === 'allow') { /** added to control leading zero */
1046
+ settingsClone.allowLeading = false;
1047
+ strip_zero = 'leading';
1048
+ }
1049
+ if (value !== '') {
1050
+ value = autoStrip(value, settingsClone, strip_zero);
1051
+ if (checkEmpty(value, settingsClone) === null && autoCheck(value, settingsClone, $this[0])) {
1052
+ value = fixNumber(value, settingsClone.aDec, settingsClone.aNeg);
1053
+ value = autoRound(value, settingsClone);
1054
+ value = presentNumber(value, settingsClone.aDec, settingsClone.aNeg);
1055
+ } else {
1056
+ value = '';
1057
+ }
1058
+ }
1059
+ var groupedValue = checkEmpty(value, settingsClone, false);
1060
+ if (groupedValue === null) {
1061
+ groupedValue = autoGroup(value, settingsClone);
1062
+ }
1063
+ if (groupedValue !== origValue) {
1064
+ $this.val(groupedValue);
1065
+ }
1066
+ if (groupedValue !== holder.inVal) {
1067
+ $this.change();
1068
+ delete holder.inVal;
1069
+ }
1070
+ if (settingsClone.nBracket !== null && $this.autoNumeric('get') < 0) {
1071
+ holder.settingsClone.oEvent = 'focusout';
1072
+ $this.val(negativeBracket($this.val(), settingsClone.nBracket, settingsClone.oEvent));
1073
+ }
1074
+ });
1075
+ }
1076
+ });
1077
+ },
1078
+ /** method to remove settings and stop autoNumeric() */
1079
+ destroy: function () {
1080
+ return $(this).each(function () {
1081
+ var $this = $(this);
1082
+ $this.off('.autoNumeric');
1083
+ $this.removeData('autoNumeric');
1084
+ });
1085
+ },
1086
+ /** method to update settings - can call as many times */
1087
+ update: function (options) {
1088
+ return $(this).each(function () {
1089
+ var $this = autoGet($(this)),
1090
+ settings = $this.data('autoNumeric');
1091
+ if (typeof settings !== 'object') {
1092
+ $.error("You must initialize autoNumeric('init', {options}) prior to calling the 'update' method");
1093
+ return this;
1094
+ }
1095
+ var strip = $this.autoNumeric('get');
1096
+ settings = $.extend(settings, options);
1097
+ getHolder($this, settings, true);
1098
+ if (settings.aDec === settings.aSep) {
1099
+ $.error("autoNumeric will not function properly when the decimal character aDec: '" + settings.aDec + "' and thousand seperater aSep: '" + settings.aSep + "' are the same character");
1100
+ return this;
1101
+ }
1102
+ $this.data('autoNumeric', settings);
1103
+ if ($this.val() !== '' || $this.text() !== '') {
1104
+ return $this.autoNumeric('set', strip);
1105
+ }
1106
+ return;
1107
+ });
1108
+ },
1109
+ /** returns a formated strings for "input:text" fields Uses jQuery's .val() method*/
1110
+ set: function (valueIn) {
1111
+ return $(this).each(function () {
1112
+ var $this = autoGet($(this)),
1113
+ settings = $this.data('autoNumeric'),
1114
+ value = valueIn.toString(),
1115
+ testValue = valueIn.toString();
1116
+ if (typeof settings !== 'object') {
1117
+ $.error("You must initialize autoNumeric('init', {options}) prior to calling the 'set' method");
1118
+ return this;
1119
+ }
1120
+ /** allows locale decimal seperator to be a comma */
1121
+ if (testValue === $this.attr('value')) {
1122
+ value = value.replace(',', '.');
1123
+ }
1124
+ /** routine to handle page re-load from back button */
1125
+ if (testValue !== $this.attr('value') && settings.runOnce === false) {
1126
+ value = autoStrip(value, settings);
1127
+ }
1128
+ /** returns a empty string if the value being 'set' contains non-numeric characters and or more than decimal point (full stop) and will not be formatted */
1129
+ if (!$.isNumeric(+value)) {
1130
+ return '';
1131
+ }
1132
+ value = checkValue(value);
1133
+ settings.oEvent = 'set';
1134
+ settings.lastSetValue = value; /** saves the unrounded value from the set method - $('selector').data('autoNumeric').lastSetValue; - helpful when you need to change the rounding accuracy*/
1135
+ value.toString();
1136
+ if (value !== '') {
1137
+ value = autoRound(value, settings);
1138
+ }
1139
+ value = presentNumber(value, settings.aDec, settings.aNeg);
1140
+ if (!autoCheck(value, settings)) {
1141
+ value = autoRound('', settings);
1142
+ }
1143
+ value = autoGroup(value, settings);
1144
+ if ($this.is('input[type=text], input[type=hidden], input:not([type])')) { /**added hidden type */
1145
+ return $this.val(value);
1146
+ }
1147
+ if ($.inArray($this.prop('tagName'), settings.tagList) !== -1) {
1148
+ return $this.text(value);
1149
+ }
1150
+ $.error("The <" + $this.prop('tagName') + "> is not supported by autoNumeric()");
1151
+ return false;
1152
+ });
1153
+ },
1154
+ /** method to get the unformated value from a specific input field, returns a numeric value */
1155
+ get: function () {
1156
+ var $this = autoGet($(this)),
1157
+ settings = $this.data('autoNumeric');
1158
+ if (typeof settings !== 'object') {
1159
+ $.error("You must initialize autoNumeric('init', {options}) prior to calling the 'get' method");
1160
+ return this;
1161
+ }
1162
+ settings.oEvent = 'get';
1163
+ var getValue = '';
1164
+ /** determine the element type then use .eq(0) selector to grab the value of the first element in selector */
1165
+ if ($this.is('input[type=text], input[type=hidden], input:not([type])')) { /**added hidden type */
1166
+ getValue = $this.eq(0).val();
1167
+ } else if ($.inArray($this.prop('tagName'), settings.tagList) !== -1) {
1168
+ getValue = $this.eq(0).text();
1169
+ } else {
1170
+ $.error("The <" + $this.prop('tagName') + "> is not supported by autoNumeric()");
1171
+ return false;
1172
+ }
1173
+ if ((getValue === '' && settings.wEmpty === 'empty') || (getValue === settings.aSign && (settings.wEmpty === 'sign' || settings.wEmpty === 'empty'))) {
1174
+ return '';
1175
+ }
1176
+ if (settings.nBracket !== null && getValue !== '') {
1177
+ getValue = negativeBracket(getValue, settings.nBracket, settings.oEvent);
1178
+ }
1179
+ if (settings.runOnce || settings.aForm === false) {
1180
+ getValue = autoStrip(getValue, settings);
1181
+ }
1182
+ getValue = fixNumber(getValue, settings.aDec, settings.aNeg);
1183
+ if (+getValue === 0 && settings.lZero !== 'keep') {
1184
+ getValue = '0';
1185
+ }
1186
+ if (settings.lZero === 'keep') {
1187
+ return getValue;
1188
+ }
1189
+ getValue = checkValue(getValue);
1190
+ return getValue; /** returned Numeric String */
1191
+ },
1192
+ /** method to get the unformated value from multiple fields */
1193
+ getString: function () {
1194
+ var isAutoNumeric = false,
1195
+ $this = autoGet($(this)),
1196
+ str = $this.serialize(),
1197
+ parts = str.split('&'),
1198
+ i = 0;
1199
+ for (i; i < parts.length; i += 1) {
1200
+ var miniParts = parts[i].split('=');
1201
+ var settings = $('*[name="' + decodeURIComponent(miniParts[0]) + '"]').data('autoNumeric');
1202
+ if (typeof settings === 'object') {
1203
+ if (miniParts[1] !== null && $('*[name="' + decodeURIComponent(miniParts[0]) + '"]').data('autoNumeric') !== undefined) {
1204
+ miniParts[1] = $('input[name="' + decodeURIComponent(miniParts[0]) + '"]').autoNumeric('get');
1205
+ parts[i] = miniParts.join('=');
1206
+ isAutoNumeric = true;
1207
+ }
1208
+ }
1209
+ }
1210
+ if (isAutoNumeric === true) {
1211
+ return parts.join('&');
1212
+ }
1213
+ $.error("You must initialize autoNumeric('init', {options}) prior to calling the 'getString' method");
1214
+ return this;
1215
+ },
1216
+ /** method to get the unformated value from multiple fields */
1217
+ getArray: function () {
1218
+ var isAutoNumeric = false,
1219
+ $this = autoGet($(this)),
1220
+ formFields = $this.serializeArray();
1221
+ $.each(formFields, function (i, field) {
1222
+ var settings = $('*[name="' + decodeURIComponent(field.name) + '"]').data('autoNumeric');
1223
+ if (typeof settings === 'object') {
1224
+ if (field.value !== '' && $('*[name="' + decodeURIComponent(field.name) + '"]').data('autoNumeric') !== undefined) {
1225
+ field.value = $('input[name="' + decodeURIComponent(field.name) + '"]').autoNumeric('get').toString();
1226
+ }
1227
+ isAutoNumeric = true;
1228
+ }
1229
+ });
1230
+ if (isAutoNumeric === true) {
1231
+ return formFields;
1232
+ }
1233
+ $.error("You must initialize autoNumeric('init', {options}) prior to calling the 'getArray' method");
1234
+ return this;
1235
+ },
1236
+ /** returns the settings object for those who need to look under the hood */
1237
+ getSettings: function () {
1238
+ var $this = autoGet($(this));
1239
+ return $this.eq(0).data('autoNumeric');
1240
+ }
1241
+ };
1242
+ $.fn.autoNumeric = function (method) {
1243
+ if (methods[method]) {
1244
+ return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
1245
+ }
1246
+ if (typeof method === 'object' || !method) {
1247
+ return methods.init.apply(this, arguments);
1248
+ }
1249
+ $.error('Method "' + method + '" is not supported by autoNumeric()');
1250
+ };
1251
+ }(jQuery));