-
Notifications
You must be signed in to change notification settings - Fork 19
/
tmp-recaptcha-bundle.js
7672 lines (7082 loc) · 230 KB
/
tmp-recaptcha-bundle.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(function (jQuery) { (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
module.exports={
"api": "http://api.testing.ringcaptcha.com",
"cdn": "http://localhost:4001",
"recaptchaSiteKey": "6LcGnDcUAAAAAIA4fmiHFmflAQvHBHvh8qg09-XS",
"locale": {
"default": "en",
"available": ["bg", "en", "es", "gr", "fr", "ar", "pt", "ru", "it", "de", "nl", "sr", "sv", "tr", "fi", "ja", "zh"]
}
}
},{}],2:[function(require,module,exports){
'use strict';
var $ = require('./src/zepto');
var Widget = require('./src/widget');
var config = require('./config.json');
var cssify = require('cssify');
var cssPath = config.cdn + '/resources/css/widget.css';
cssify.byUrl(cssPath);
$('[data-widget]').each(function () {
var settings = $(this).data();
settings.recaptchaSiteKey = config.recaptchaSiteKey;
new Widget(this, settings.app, settings).setup();
});
module.exports = { Widget: Widget };
},{"./config.json":1,"./src/widget":33,"./src/zepto":34,"cssify":3}],3:[function(require,module,exports){
module.exports = function (css) {
var head = document.getElementsByTagName('head')[0],
style = document.createElement('style');
style.type = 'text/css';
if (style.styleSheet) {
style.styleSheet.cssText = css;
} else {
style.appendChild(document.createTextNode(css));
}
head.appendChild(style);
};
module.exports.byUrl = function(url) {
var head = document.getElementsByTagName('head')[0],
link = document.createElement('link');
link.rel = 'stylesheet';
link.href = url;
head.appendChild(link);
};
},{}],4:[function(require,module,exports){
/*
* fingerprintJS 0.5.3 - Fast browser fingerprint library
* https://github.com/Valve/fingerprintjs
* Copyright (c) 2013 Valentin Vasilyev ([email protected])
* Licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) license.
*/
;(function (name, context, definition) {
if (typeof module !== 'undefined' && module.exports) { module.exports = definition(); }
else if (typeof define === 'function' && define.amd) { define(definition); }
else { context[name] = definition(); }
})('Fingerprint', this, function () {
'use strict';
var Fingerprint = function (options) {
var nativeForEach, nativeMap;
nativeForEach = Array.prototype.forEach;
nativeMap = Array.prototype.map;
this.each = function (obj, iterator, context) {
if (obj === null) {
return;
}
if (nativeForEach && obj.forEach === nativeForEach) {
obj.forEach(iterator, context);
} else if (obj.length === +obj.length) {
for (var i = 0, l = obj.length; i < l; i++) {
if (iterator.call(context, obj[i], i, obj) === {}) return;
}
} else {
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
if (iterator.call(context, obj[key], key, obj) === {}) return;
}
}
}
};
this.map = function(obj, iterator, context) {
var results = [];
// Not using strict equality so that this acts as a
// shortcut to checking for `null` and `undefined`.
if (obj == null) return results;
if (nativeMap && obj.map === nativeMap) return obj.map(iterator, context);
this.each(obj, function(value, index, list) {
results[results.length] = iterator.call(context, value, index, list);
});
return results;
};
if (typeof options == 'object'){
this.hasher = options.hasher;
this.screen_resolution = options.screen_resolution;
this.canvas = options.canvas;
this.ie_activex = options.ie_activex;
} else if(typeof options == 'function'){
this.hasher = options;
}
};
Fingerprint.prototype = {
get: function(){
var keys = [];
keys.push(navigator.userAgent);
keys.push(navigator.language);
keys.push(screen.colorDepth);
if (this.screen_resolution) {
var resolution = this.getScreenResolution();
if (typeof resolution !== 'undefined'){ // headless browsers, such as phantomjs
keys.push(this.getScreenResolution().join('x'));
}
}
keys.push(new Date().getTimezoneOffset());
keys.push(this.hasSessionStorage());
keys.push(this.hasLocalStorage());
keys.push(!!window.indexedDB);
//body might not be defined at this point or removed programmatically
if(document.body){
keys.push(typeof(document.body.addBehavior));
} else {
keys.push(typeof undefined);
}
keys.push(typeof(window.openDatabase));
keys.push(navigator.cpuClass);
keys.push(navigator.platform);
keys.push(navigator.doNotTrack);
keys.push(this.getPluginsString());
if(this.canvas && this.isCanvasSupported()){
keys.push(this.getCanvasFingerprint());
}
if(this.hasher){
return this.hasher(keys.join('###'), 31);
} else {
return this.murmurhash3_32_gc(keys.join('###'), 31);
}
},
/**
* JS Implementation of MurmurHash3 (r136) (as of May 20, 2011)
*
* @author <a href="mailto:[email protected]">Gary Court</a>
* @see http://github.com/garycourt/murmurhash-js
* @author <a href="mailto:[email protected]">Austin Appleby</a>
* @see http://sites.google.com/site/murmurhash/
*
* @param {string} key ASCII only
* @param {number} seed Positive integer only
* @return {number} 32-bit positive integer hash
*/
murmurhash3_32_gc: function(key, seed) {
var remainder, bytes, h1, h1b, c1, c2, k1, i;
remainder = key.length & 3; // key.length % 4
bytes = key.length - remainder;
h1 = seed;
c1 = 0xcc9e2d51;
c2 = 0x1b873593;
i = 0;
while (i < bytes) {
k1 =
((key.charCodeAt(i) & 0xff)) |
((key.charCodeAt(++i) & 0xff) << 8) |
((key.charCodeAt(++i) & 0xff) << 16) |
((key.charCodeAt(++i) & 0xff) << 24);
++i;
k1 = ((((k1 & 0xffff) * c1) + ((((k1 >>> 16) * c1) & 0xffff) << 16))) & 0xffffffff;
k1 = (k1 << 15) | (k1 >>> 17);
k1 = ((((k1 & 0xffff) * c2) + ((((k1 >>> 16) * c2) & 0xffff) << 16))) & 0xffffffff;
h1 ^= k1;
h1 = (h1 << 13) | (h1 >>> 19);
h1b = ((((h1 & 0xffff) * 5) + ((((h1 >>> 16) * 5) & 0xffff) << 16))) & 0xffffffff;
h1 = (((h1b & 0xffff) + 0x6b64) + ((((h1b >>> 16) + 0xe654) & 0xffff) << 16));
}
k1 = 0;
switch (remainder) {
case 3: k1 ^= (key.charCodeAt(i + 2) & 0xff) << 16;
case 2: k1 ^= (key.charCodeAt(i + 1) & 0xff) << 8;
case 1: k1 ^= (key.charCodeAt(i) & 0xff);
k1 = (((k1 & 0xffff) * c1) + ((((k1 >>> 16) * c1) & 0xffff) << 16)) & 0xffffffff;
k1 = (k1 << 15) | (k1 >>> 17);
k1 = (((k1 & 0xffff) * c2) + ((((k1 >>> 16) * c2) & 0xffff) << 16)) & 0xffffffff;
h1 ^= k1;
}
h1 ^= key.length;
h1 ^= h1 >>> 16;
h1 = (((h1 & 0xffff) * 0x85ebca6b) + ((((h1 >>> 16) * 0x85ebca6b) & 0xffff) << 16)) & 0xffffffff;
h1 ^= h1 >>> 13;
h1 = ((((h1 & 0xffff) * 0xc2b2ae35) + ((((h1 >>> 16) * 0xc2b2ae35) & 0xffff) << 16))) & 0xffffffff;
h1 ^= h1 >>> 16;
return h1 >>> 0;
},
// https://bugzilla.mozilla.org/show_bug.cgi?id=781447
hasLocalStorage: function () {
try{
return !!window.localStorage;
} catch(e) {
return true; // SecurityError when referencing it means it exists
}
},
hasSessionStorage: function () {
try{
return !!window.sessionStorage;
} catch(e) {
return true; // SecurityError when referencing it means it exists
}
},
isCanvasSupported: function () {
var elem = document.createElement('canvas');
return !!(elem.getContext && elem.getContext('2d'));
},
isIE: function () {
if(navigator.appName === 'Microsoft Internet Explorer') {
return true;
} else if(navigator.appName === 'Netscape' && /Trident/.test(navigator.userAgent)){// IE 11
return true;
}
return false;
},
getPluginsString: function () {
if(this.isIE() && this.ie_activex){
return this.getIEPluginsString();
} else {
return this.getRegularPluginsString();
}
},
getRegularPluginsString: function () {
return this.map(navigator.plugins, function (p) {
var mimeTypes = this.map(p, function(mt){
return [mt.type, mt.suffixes].join('~');
}).join(',');
return [p.name, p.description, mimeTypes].join('::');
}, this).join(';');
},
getIEPluginsString: function () {
if(window.ActiveXObject){
var names = ['ShockwaveFlash.ShockwaveFlash',//flash plugin
'AcroPDF.PDF', // Adobe PDF reader 7+
'PDF.PdfCtrl', // Adobe PDF reader 6 and earlier, brrr
'QuickTime.QuickTime', // QuickTime
// 5 versions of real players
'rmocx.RealPlayer G2 Control',
'rmocx.RealPlayer G2 Control.1',
'RealPlayer.RealPlayer(tm) ActiveX Control (32-bit)',
'RealVideo.RealVideo(tm) ActiveX Control (32-bit)',
'RealPlayer',
'SWCtl.SWCtl', // ShockWave player
'WMPlayer.OCX', // Windows media player
'AgControl.AgControl', // Silverlight
'Skype.Detection'];
// starting to detect plugins in IE
return this.map(names, function(name){
try{
new ActiveXObject(name);
return name;
} catch(e){
return null;
}
}).join(';');
} else {
return ""; // behavior prior version 0.5.0, not breaking backwards compat.
}
},
getScreenResolution: function () {
return [screen.height, screen.width];
},
getCanvasFingerprint: function () {
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
// https://www.browserleaks.com/canvas#how-does-it-work
var txt = 'http://valve.github.io';
ctx.textBaseline = "top";
ctx.font = "14px 'Arial'";
ctx.textBaseline = "alphabetic";
ctx.fillStyle = "#f60";
ctx.fillRect(125,1,62,20);
ctx.fillStyle = "#069";
ctx.fillText(txt, 2, 15);
ctx.fillStyle = "rgba(102, 204, 0, 0.7)";
ctx.fillText(txt, 4, 17);
return canvas.toDataURL();
}
};
return Fingerprint;
});
},{}],5:[function(require,module,exports){
/*!
* v0.1.5
* Copyright (c) 2014 First Opinion
* formatter.js is open sourced under the MIT license.
*
* thanks to digitalBush/jquery.maskedinput for some of the trickier
* keycode handling
*/
//
// Uses Node, AMD or browser globals to create a module. This example creates
// a global even when AMD is used. This is useful if you have some scripts
// that are loaded by an AMD loader, but they still want access to globals.
// If you do not need to export a global for the AMD case,
// see returnExports.js.
//
// If you want something that will work in other stricter CommonJS environments,
// or if you need to create a circular dependency, see commonJsStrictGlobal.js
//
// Defines a module "returnExportsGlobal" that depends another module called
// "b". Note that the name of the module is implied by the file name. It is
// best if the file name and the exported global have matching names.
//
// If the 'b' module also uses this type of boilerplate, then
// in the browser, it will create a global .b that is used below.
//
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define([], function () {
return (root.returnExportsGlobal = factory());
});
} else if (typeof exports === 'object') {
// Node. Does not work with strict CommonJS, but
// only CommonJS-like enviroments that support module.exports,
// like Node.
module.exports = factory();
} else {
root['Formatter'] = factory();
}
}(this, function () {
/*
* pattern.js
*
* Utilities to parse str pattern and return info
*
*/
var pattern = function () {
// Define module
var pattern = {};
// Match information
var DELIM_SIZE = 4;
// Our regex used to parse
var regexp = new RegExp('{{([^}]+)}}', 'g');
//
// Helper method to parse pattern str
//
var getMatches = function (pattern) {
// Populate array of matches
var matches = [], match;
while (match = regexp.exec(pattern)) {
matches.push(match);
}
return matches;
};
//
// Create an object holding all formatted characters
// with corresponding positions
//
pattern.parse = function (pattern) {
// Our obj to populate
var info = {
inpts: {},
chars: {}
};
// Pattern information
var matches = getMatches(pattern), pLength = pattern.length;
// Counters
var mCount = 0, iCount = 0, i = 0;
// Add inpts, move to end of match, and process
var processMatch = function (val) {
var valLength = val.length;
for (var j = 0; j < valLength; j++) {
info.inpts[iCount] = val.charAt(j);
iCount++;
}
mCount++;
i += val.length + DELIM_SIZE - 1;
};
// Process match or add chars
for (i; i < pLength; i++) {
if (mCount < matches.length && i === matches[mCount].index) {
processMatch(matches[mCount][1]);
} else {
info.chars[i - mCount * DELIM_SIZE] = pattern.charAt(i);
}
}
// Set mLength and return
info.mLength = i - mCount * DELIM_SIZE;
return info;
};
// Expose
return pattern;
}();
/*
* utils.js
*
* Independent helper methods (cross browser, etc..)
*
*/
var utils = function () {
// Define module
var utils = {};
// Useragent info for keycode handling
var uAgent = typeof navigator !== 'undefined' ? navigator.userAgent : null;
//
// Shallow copy properties from n objects to destObj
//
utils.extend = function (destObj) {
for (var i = 1; i < arguments.length; i++) {
for (var key in arguments[i]) {
destObj[key] = arguments[i][key];
}
}
return destObj;
};
//
// Add a given character to a string at a defined pos
//
utils.addChars = function (str, chars, pos) {
return str.substr(0, pos) + chars + str.substr(pos, str.length);
};
//
// Remove a span of characters
//
utils.removeChars = function (str, start, end) {
return str.substr(0, start) + str.substr(end, str.length);
};
//
// Return true/false is num false between bounds
//
utils.isBetween = function (num, bounds) {
bounds.sort(function (a, b) {
return a - b;
});
return num > bounds[0] && num < bounds[1];
};
//
// Helper method for cross browser event listeners
//
utils.addListener = function (el, evt, handler) {
return typeof el.addEventListener !== 'undefined' ? el.addEventListener(evt, handler, false) : el.attachEvent('on' + evt, handler);
};
//
// Helper method for cross browser event listeners
//
utils.removeListener = function (el, evt, handler) {
return typeof el.removeEventListener !== 'undefined' ? el.removeEventListener(evt, handler, false) : el.detachEvent('on' + evt, handler);
};
//
// Helper method for cross browser implementation of preventDefault
//
utils.preventDefault = function (evt) {
return evt.preventDefault ? evt.preventDefault() : evt.returnValue = false;
};
//
// Helper method for cross browser implementation for grabbing
// clipboard data
//
utils.getClip = function (evt) {
if (evt.clipboardData) {
return evt.clipboardData.getData('Text');
}
if (window.clipboardData) {
return window.clipboardData.getData('Text');
}
};
//
// Loop over object and checking for matching properties
//
utils.getMatchingKey = function (which, keyCode, keys) {
// Loop over and return if matched.
for (var k in keys) {
var key = keys[k];
if (which === key.which && keyCode === key.keyCode) {
return k;
}
}
};
//
// Returns true/false if k is a del keyDown
//
utils.isDelKeyDown = function (which, keyCode) {
var keys = {
'backspace': {
'which': 8,
'keyCode': 8
},
'delete': {
'which': 46,
'keyCode': 46
}
};
return utils.getMatchingKey(which, keyCode, keys);
};
//
// Returns true/false if k is a del keyPress
//
utils.isDelKeyPress = function (which, keyCode) {
var keys = {
'backspace': {
'which': 8,
'keyCode': 8,
'shiftKey': false
},
'delete': {
'which': 0,
'keyCode': 46
}
};
return utils.getMatchingKey(which, keyCode, keys);
};
// //
// // Determine if keydown relates to specialKey
// //
// utils.isSpecialKeyDown = function (which, keyCode) {
// var keys = {
// 'tab': { 'which': 9, 'keyCode': 9 },
// 'enter': { 'which': 13, 'keyCode': 13 },
// 'end': { 'which': 35, 'keyCode': 35 },
// 'home': { 'which': 36, 'keyCode': 36 },
// 'leftarrow': { 'which': 37, 'keyCode': 37 },
// 'uparrow': { 'which': 38, 'keyCode': 38 },
// 'rightarrow': { 'which': 39, 'keyCode': 39 },
// 'downarrow': { 'which': 40, 'keyCode': 40 },
// 'F5': { 'which': 116, 'keyCode': 116 }
// };
// return utils.getMatchingKey(which, keyCode, keys);
// };
//
// Determine if keypress relates to specialKey
//
utils.isSpecialKeyPress = function (which, keyCode) {
var keys = {
'tab': {
'which': 0,
'keyCode': 9
},
'enter': {
'which': 13,
'keyCode': 13
},
'end': {
'which': 0,
'keyCode': 35
},
'home': {
'which': 0,
'keyCode': 36
},
'leftarrow': {
'which': 0,
'keyCode': 37
},
'uparrow': {
'which': 0,
'keyCode': 38
},
'rightarrow': {
'which': 0,
'keyCode': 39
},
'downarrow': {
'which': 0,
'keyCode': 40
},
'F5': {
'which': 116,
'keyCode': 116
}
};
return utils.getMatchingKey(which, keyCode, keys);
};
//
// Returns true/false if modifier key is held down
//
utils.isModifier = function (evt) {
return evt.ctrlKey || evt.altKey || evt.metaKey;
};
//
// Iterates over each property of object or array.
//
utils.forEach = function (collection, callback, thisArg) {
if (collection.hasOwnProperty('length')) {
for (var index = 0, len = collection.length; index < len; index++) {
if (callback.call(thisArg, collection[index], index, collection) === false) {
break;
}
}
} else {
for (var key in collection) {
if (collection.hasOwnProperty(key)) {
if (callback.call(thisArg, collection[key], key, collection) === false) {
break;
}
}
}
}
};
// Expose
return utils;
}();
/*
* pattern-matcher.js
*
* Parses a pattern specification and determines appropriate pattern for an
* input string
*
*/
var patternMatcher = function (pattern, utils) {
//
// Parse a matcher string into a RegExp. Accepts valid regular
// expressions and the catchall '*'.
// @private
//
var parseMatcher = function (matcher) {
if (matcher === '*') {
return /.*/;
}
return new RegExp(matcher);
};
//
// Parse a pattern spec and return a function that returns a pattern
// based on user input. The first matching pattern will be chosen.
// Pattern spec format:
// Array [
// Object: { Matcher(RegExp String) : Pattern(Pattern String) },
// ...
// ]
function patternMatcher(patternSpec) {
var matchers = [], patterns = [];
// Iterate over each pattern in order.
utils.forEach(patternSpec, function (patternMatcher) {
// Process single property object to obtain pattern and matcher.
utils.forEach(patternMatcher, function (patternStr, matcherStr) {
var parsedPattern = pattern.parse(patternStr), regExpMatcher = parseMatcher(matcherStr);
matchers.push(regExpMatcher);
patterns.push(parsedPattern);
// Stop after one iteration.
return false;
});
});
var getPattern = function (input) {
var matchedIndex;
utils.forEach(matchers, function (matcher, index) {
if (matcher.test(input)) {
matchedIndex = index;
return false;
}
});
return matchedIndex === undefined ? null : patterns[matchedIndex];
};
return {
getPattern: getPattern,
patterns: patterns,
matchers: matchers
};
}
// Expose
return patternMatcher;
}(pattern, utils);
/*
* inpt-sel.js
*
* Cross browser implementation to get and set input selections
*
*/
var inptSel = function () {
// Define module
var inptSel = {};
//
// Get begin and end positions of selected input. Return 0's
// if there is no selectiion data
//
inptSel.get = function (el) {
// If normal browser return with result
if (typeof el.selectionStart === 'number') {
return {
begin: el.selectionStart,
end: el.selectionEnd
};
}
// Uh-Oh. We must be IE. Fun with TextRange!!
var range = document.selection.createRange();
// Determine if there is a selection
if (range && range.parentElement() === el) {
var inputRange = el.createTextRange(), endRange = el.createTextRange(), length = el.value.length;
// Create a working TextRange for the input selection
inputRange.moveToBookmark(range.getBookmark());
// Move endRange begin pos to end pos (hence endRange)
endRange.collapse(false);
// If we are at the very end of the input, begin and end
// must both be the length of the el.value
if (inputRange.compareEndPoints('StartToEnd', endRange) > -1) {
return {
begin: length,
end: length
};
}
// Note: moveStart usually returns the units moved, which
// one may think is -length, however, it will stop when it
// gets to the begin of the range, thus giving us the
// negative value of the pos.
return {
begin: -inputRange.moveStart('character', -length),
end: -inputRange.moveEnd('character', -length)
};
}
//Return 0's on no selection data
return {
begin: 0,
end: 0
};
};
//
// Set the caret position at a specified location
//
inptSel.set = function (el, pos) {
// Normalize pos
if (typeof pos !== 'object') {
pos = {
begin: pos,
end: pos
};
}
// If normal browser
if (el.setSelectionRange) {
el.setSelectionRange(pos.begin, pos.end);
} else if (el.createTextRange) {
var range = el.createTextRange();
range.collapse(true);
range.moveEnd('character', pos.end);
range.moveStart('character', pos.begin);
range.select();
}
};
// Expose
return inptSel;
}();
/*
* formatter.js
*
* Class used to format input based on passed pattern
*
*/
var formatter = function (patternMatcher, inptSel, utils) {
// Defaults
var defaults = {
persistent: false,
repeat: false,
placeholder: ' '
};
// Regexs for input validation
var inptRegs = {
'9': /[0-9]/,
'a': /[A-Za-z]/,
'*': /[A-Za-z0-9]/
};
//
// Class Constructor - Called with new Formatter(el, opts)
// Responsible for setting up required instance variables, and
// enabling the formatter.
//
function Formatter(el, opts) {
// Cache this
var self = this;
// Make sure we have an element. Make accesible to instance
self.el = el;
if (!self.el) {
throw new TypeError('Must provide an existing element');
}
// Merge opts with defaults
self.opts = utils.extend({}, defaults, opts);
// 1 pattern is special case
if (typeof self.opts.pattern !== 'undefined') {
self.opts.patterns = self._specFromSinglePattern(self.opts.pattern);
delete self.opts.pattern;
}
// Make sure we have valid opts
if (typeof self.opts.patterns === 'undefined') {
throw new TypeError('Must provide a pattern or array of patterns');
}
self.patternMatcher = patternMatcher(self.opts.patterns);
// Init values
self.hldrs = {};
self.focus = 0;
self.enabled = false;
self.listeners = {
keydown: function (evt) {
self._keyDown(evt);
},
keypress: function (evt) {
self._keyPress(evt);
},
paste: function (evt) {
self._paste(evt);
},
focus: function (evt) {
self._focus(evt);
},
click: function (evt) {
self._focus(evt);
},
touchstart: function (evt) {
self._focus(evt);
}
};
// Enable formatter
self.enable();
}
//
// @public
// Add new char
//
Formatter.addInptType = function (chr, reg) {
inptRegs[chr] = reg;
};
//
// @public
// Enable the formatter
//
Formatter.prototype.enable = function () {
// Do not register listeners more than once
if (this.enabled) {
return;
}
// Upate pattern with initial value
this._updatePattern();
// Format on start
this._processKey('', false);
this.el.blur();
// Add listeners
utils.addListener(this.el, 'keydown', this.listeners.keydown);
utils.addListener(this.el, 'keypress', this.listeners.keypress);
utils.addListener(this.el, 'paste', this.listeners.paste);
if (this.opts.persistent) {
// Add Listeners
utils.addListener(this.el, 'focus', this.listeners.focus);
utils.addListener(this.el, 'click', this.listeners.click);
utils.addListener(this.el, 'touchstart', this.listeners.touchstart);
}
this.enabled = true;
};
//
// @public
// Disable the formatter
//
Formatter.prototype.disable = function () {
// Do not try to remove listeners already removed
if (!this.enabled) {
return;
}
// Get current state
this.sel = inptSel.get(this.el);
this.val = this.el.value;
// Init values
this.delta = 0;
// Remove all formatted chars from val
this._removeChars();
// Set value and adhere to maxLength
this.el.value = this.val.substr(0, this.mLength);
// Remove listeners
utils.removeListener(this.el, 'keydown', this.listeners.keydown);
utils.removeListener(this.el, 'keypress', this.listeners.keypress);
utils.removeListener(this.el, 'paste', this.listeners.paste);
if (this.opts.persistent) {
// Remove Listeners
utils.removeListener(this.el, 'focus', this.listeners.focus);
utils.removeListener(this.el, 'click', this.listeners.click);
utils.removeListener(this.el, 'touchstart', this.listeners.touchstart);
}
this.enabled = false;
};
//
// @public
// Apply the given pattern to the current input without moving caret.
//
Formatter.prototype.resetPattern = function (str) {
// Skip if the formatter is not enabled
if (!this.enabled) {
return;
}
// Update opts to hold new pattern
this.opts.patterns = str ? this._specFromSinglePattern(str) : this.opts.patterns;
// Get current state
this.sel = inptSel.get(this.el);
this.val = this.el.value;
// Init values
this.delta = 0;
// Remove all formatted chars from val
this._removeChars();
this.patternMatcher = patternMatcher(this.opts.patterns);
// Update pattern
var newPattern = this.patternMatcher.getPattern(this.val);
this.mLength = newPattern.mLength;
this.chars = newPattern.chars;
this.inpts = newPattern.inpts;
// Format on start
this._processKey('', false, true);
};
//
// @private
// Determine correct format pattern based on input val
//
Formatter.prototype._updatePattern = function () {
// Determine appropriate pattern
var newPattern = this.patternMatcher.getPattern(this.val);
// Only update the pattern if there is an appropriate pattern for the value.
// Otherwise, leave the current pattern (and likely delete the latest character.)
if (newPattern) {
// Get info about the given pattern
this.mLength = newPattern.mLength;
this.chars = newPattern.chars;
this.inpts = newPattern.inpts;
}
};
//
// @private
// Handler called on all keyDown strokes. All keys trigger
// this handler. Only process delete keys.
//
Formatter.prototype._keyDown = function (evt) {
// The first thing we need is the character code
var k = evt.which || evt.keyCode;
// If delete key
if (k && utils.isDelKeyDown(evt.which, evt.keyCode)) {
// Process the keyCode and prevent default
this._processKey(null, k);
return utils.preventDefault(evt);
}
};
//
// @private
// Handler called on all keyPress strokes. Only processes
// character keys (as long as no modifier key is in use).
//
Formatter.prototype._keyPress = function (evt) {
// The first thing we need is the character code
var k, isSpecial;
// Mozilla will trigger on special keys and assign the the value 0
// We want to use that 0 rather than the keyCode it assigns.
k = evt.which || evt.keyCode;
isSpecial = utils.isSpecialKeyPress(evt.which, evt.keyCode);
// Process the keyCode and prevent default
if (!utils.isDelKeyPress(evt.which, evt.keyCode) && !isSpecial && !utils.isModifier(evt)) {
this._processKey(String.fromCharCode(k), false);
return utils.preventDefault(evt);
}
};
//
// @private
// Handler called on paste event.
//
Formatter.prototype._paste = function (evt) {
// Process the clipboard paste and prevent default
this._processKey(utils.getClip(evt), false);
return utils.preventDefault(evt);
};
//
// @private
// Handle called on focus event.
//
Formatter.prototype._focus = function () {