PageSourceSearch

https://care.ditp.go.th/frontend/assets/input-mask/inputmask.js

js ditp.go.th collected 2026-10-02 04:02:20 UTC 97,568 bytes, 1,791 lines download raw bytes

1/**
2 * @license Input Mask plugin for jquery
3 * http://github.com/RobinHerbots/jquery.inputmask
4 * Copyright (c) 2010 - 2014 Robin Herbots
5 * Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php)
6 * Version: 0.0.0
7 */
8
9(function ($) {
10    if ($.fn.inputmask === undefined) {
11
12        //helper functions
13        function isInputEventSupported(eventName) {
14            var el = document.createElement('input'),
15                eventName = 'on' + eventName,
16                isSupported = (eventName in el);
17            if (!isSupported) {
18                el.setAttribute(eventName, 'return;');
19                isSupported = typeof el[eventName] == 'function';
20            }
21            el = null;
22            return isSupported;
23        }
24
25        function resolveAlias(aliasStr, options, opts) {
26            var aliasDefinition = opts.aliases[aliasStr];
27            if (aliasDefinition) {
28                if (aliasDefinition.alias) resolveAlias(aliasDefinition.alias, undefined, opts); //alias is another alias
29                $.extend(true, opts, aliasDefinition); //merge alias definition in the options
30                $.extend(true, opts, options); //reapply extra given options
31                return true;
32            }
33            return false;
34        }
35
36        function generateMaskSet(opts, multi) {
37            var ms = [];
38
39            function analyseMask(mask) {
40                var tokenizer = /(?:[?*+]|\{[0-9\+\*]+(?:,[0-9\+\*]*)?\})\??|[^.?*+^${[]()|\\]+|./g,
41                    escaped = false;
42
43                function maskToken(isGroup, isOptional, isQuantifier, isAlternator) {
44                    this.matches = [];
45                    this.isGroup = isGroup || false;
46                    this.isOptional = isOptional || false;
47                    this.isQuantifier = isQuantifier || false;
48                    this.isAlternator = isAlternator || false;
49                    this.quantifier = { min: 1, max: 1 };
50                };
51
52                //test definition => {fn: RegExp/function, cardinality: int, optionality: bool, newBlockMarker: bool, casing: null/upper/lower, def: definitionSymbol, placeholder: placeholder, mask: real maskDefinition}
53                function insertTestDefinition(mtoken, element, position) {
54                    var maskdef = opts.definitions[element];
55                    var newBlockMarker = mtoken.matches.length == 0;
56                    position = position != undefined ? position : mtoken.matches.length;
57                    if (maskdef && !escaped) {
58                        var prevalidators = maskdef["prevalidator"], prevalidatorsL = prevalidators ? prevalidators.length : 0;
59                        for (var i = 1; i < maskdef.cardinality; i++) {
60                            var prevalidator = prevalidatorsL >= i ? prevalidators[i - 1] : [], validator = prevalidator["validator"], cardinality = prevalidator["cardinality"];
61                            mtoken.matches.splice(position++, 0, { fn: validator ? typeof validator == 'string' ? new RegExp(validator) : new function () { this.test = validator; } : new RegExp("."), cardinality: cardinality ? cardinality : 1, optionality: mtoken.isOptional, newBlockMarker: newBlockMarker, casing: maskdef["casing"], def: maskdef["definitionSymbol"] || element, placeholder: maskdef["placeholder"], mask: element });
62                        }
63                        mtoken.matches.splice(position++, 0, { fn: maskdef.validator ? typeof maskdef.validator == 'string' ? new RegExp(maskdef.validator) : new function () { this.test = maskdef.validator; } : new RegExp("."), cardinality: maskdef.cardinality, optionality: mtoken.isOptional, newBlockMarker: newBlockMarker, casing: maskdef["casing"], def: maskdef["definitionSymbol"] || element, placeholder: maskdef["placeholder"], mask: element });
64                    } else {
65                        mtoken.matches.splice(position++, 0, { fn: null, cardinality: 0, optionality: mtoken.isOptional, newBlockMarker: newBlockMarker, casing: null, def: element, placeholder: undefined, mask: element });
66                        escaped = false;
67                    }
68                }
69
70                var currentToken = new maskToken(),
71                    match,
72                    m,
73                    openenings = [],
74                    maskTokens = [],
75                    openingToken;
76
77                while (match = tokenizer.exec(mask)) {
78                    m = match[0];
79                    switch (m.charAt(0)) {
80                        case opts.optionalmarker.end:
81                        // optional closing
82                        case opts.groupmarker.end:
83                            // Group closing
84                            openingToken = openenings.pop();
85                            if (openenings.length > 0) {
86                                openenings[openenings.length - 1]["matches"].push(openingToken);
87                            } else {
88                                currentToken.matches.push(openingToken);
89                            }
90                            break;
91                        case opts.optionalmarker.start:
92                            // optional opening
93                            openenings.push(new maskToken(false, true));
94                            break;
95                        case opts.groupmarker.start:
96                            // Group opening
97                            openenings.push(new maskToken(true));
98                            break;
99                        case opts.quantifiermarker.start:
100                            //Quantifier
101                            var quantifier = new maskToken(false, false, true);
102
103                            m = m.replace(/[{}]/g, "");
104                            var mq = m.split(","),
105                                mq0 = isNaN(mq[0]) ? mq[0] : parseInt(mq[0]),
106                                mq1 = mq.length == 1 ? mq0 : (isNaN(mq[1]) ? mq[1] : parseInt(mq[1]));
107                            if (mq1 == "*" || mq1 == "+") {
108                                mq0 = mq1 == "*" ? 0 : 1;
109                            }
110                            quantifier.quantifier = { min: mq0, max: mq1 };
111                            if (openenings.length > 0) {
112                                var matches = openenings[openenings.length - 1]["matches"];
113                                match = matches.pop();
114                                if (!match["isGroup"]) {
115                                    var groupToken = new maskToken(true);
116                                    groupToken.matches.push(match);
117                                    match = groupToken;
118                                }
119                                matches.push(match);
120                                matches.push(quantifier);
121                            } else {
122                                match = currentToken.matches.pop();
123                                if (!match["isGroup"]) {
124                                    var groupToken = new maskToken(true);
125                                    groupToken.matches.push(match);
126                                    match = groupToken;
127                                }
128                                currentToken.matches.push(match);
129                                currentToken.matches.push(quantifier);
130                            }
131                            break;
132                        case opts.escapeChar:
133                            escaped = true;
134                            break;
135                        case opts.alternatormarker:
136                            var alternator = new maskToken(false, false, false, true);
137                            if (openenings.length > 0) {
138                                var matches = openenings[openenings.length - 1]["matches"];
139                                match = matches.pop();
140                                alternator.matches.push(match);
141                                openenings.push(alternator);
142                            } else {
143                                match = currentToken.matches.pop();
144                                alternator.matches.push(match);
145                                openenings.push(alternator);
146                            }
147                            break;
148                        default:
149                            if (openenings.length > 0) {
150                                insertTestDefinition(openenings[openenings.length - 1], m);
151                                var lastToken = openenings[openenings.length - 1];
152                                if (lastToken["isAlternator"]) {
153                                    openingToken = openenings.pop();
154                                    for (var mndx = 0; mndx < openingToken.matches.length; mndx++) {
155                                        openingToken.matches[mndx].isGroup = false; //don't mark alternate groups as group
156                                    }
157                                    if (openenings.length > 0) {
158                                        openenings[openenings.length - 1]["matches"].push(openingToken);
159                                    } else {
160                                        currentToken.matches.push(openingToken);
161                                    }
162                                }
163                            } else {
164                                if (currentToken.matches.length > 0) {
165                                    var lastMatch = currentToken.matches[currentToken.matches.length - 1];
166                                    if (lastMatch["isGroup"]) { //this is not a group but a normal mask => convert
167                                        lastMatch.isGroup = false;
168                                        insertTestDefinition(lastMatch, opts.groupmarker.start, 0);
169                                        insertTestDefinition(lastMatch, opts.groupmarker.end);
170                                    }
171                                }
172                                insertTestDefinition(currentToken, m);
173                            }
174                    }
175                }
176
177                if (openenings.length > 0) {
178                    var lastToken = openenings[openenings.length - 1];
179                    if (lastToken["isAlternator"]) {
180                        for (var mndx = 0; mndx < lastToken.matches.length; mndx++) {
181                            lastToken.matches[mndx].isGroup = false; //don't mark alternate groups as group
182                        }
183                    }
184                    currentToken.matches = currentToken.matches.concat(openenings);
185                }
186                if (currentToken.matches.length > 0) {
187                    var lastMatch = currentToken.matches[currentToken.matches.length - 1];
188                    if (lastMatch["isGroup"]) { //this is not a group but a normal mask => convert
189                        lastMatch.isGroup = false;
190                        insertTestDefinition(lastMatch, opts.groupmarker.start, 0);
191                        insertTestDefinition(lastMatch, opts.groupmarker.end);
192                    }
193                    maskTokens.push(currentToken);
194                }
195
196                //console.log(JSON.stringify(maskTokens));
197                return maskTokens;
198            }
199
200            function generateMask(mask, metadata) {
201                if (opts.numericInput && opts.multi !== true) { //TODO FIX FOR DYNAMIC MASKS WITH QUANTIFIERS
202                    mask = mask.split('').reverse();
203                    for (var ndx = 0; ndx < mask.length; ndx++) {
204                        if (mask[ndx] == opts.optionalmarker.start)
205                            mask[ndx] = opts.optionalmarker.end;
206                        else if (mask[ndx] == opts.optionalmarker.end)
207                            mask[ndx] = opts.optionalmarker.start;
208                        else if (mask[ndx] == opts.groupmarker.start)
209                            mask[ndx] = opts.groupmarker.end;
210                        else if (mask[ndx] == opts.groupmarker.end)
211                            mask[ndx] = opts.groupmarker.start;
212                    }
213                    mask = mask.join('');
214                }
215                if (mask == undefined || mask == "")
216                    return undefined;
217                else {
218                    if (opts.repeat > 0 || opts.repeat == "*" || opts.repeat == "+") {
219                        var repeatStart = opts.repeat == "*" ? 0 : (opts.repeat == "+" ? 1 : opts.repeat);
220                        mask = opts.groupmarker.start + mask + opts.groupmarker.end + opts.quantifiermarker.start + repeatStart + "," + opts.repeat + opts.quantifiermarker.end;
221                    }
222                    if ($.inputmask.masksCache[mask] == undefined) {
223                        $.inputmask.masksCache[mask] = {
224                            "mask": mask,
225                            "maskToken": analyseMask(mask),
226                            "validPositions": {},
227                            "_buffer": undefined,
228                            "buffer": undefined,
229                            "tests": {},
230                            "metadata": metadata
231                        };
232                    }
233
234                    return $.extend(true, {}, $.inputmask.masksCache[mask]);
235                }
236            }
237
238            if ($.isFunction(opts.mask)) { //allow mask to be a preprocessing fn - should return a valid mask
239                opts.mask = opts.mask.call(this, opts);
240            }
241            if ($.isArray(opts.mask)) {
242                if (multi) {
243                    $.each(opts.mask, function (ndx, msk) {
244                        if (msk["mask"] != undefined) {
245                            ms.push(generateMask(msk["mask"].toString(), msk));
246                        } else {
247                            ms.push(generateMask(msk.toString()));
248                        }
249                    });
250                } else {
251                    var altMask = "(" + opts.mask.join(")|(") + ")";
252                    ms = generateMask(altMask);
253                }
254            } else {
255                if (opts.mask.length == 1 && opts.greedy == false && opts.repeat != 0) {
256                    opts.placeholder = "";
257                } //hide placeholder with single non-greedy mask
258                if (opts.mask["mask"] != undefined) {
259                    ms = generateMask(opts.mask["mask"].toString(), opts.mask);
260                } else {
261                    ms = generateMask(opts.mask.toString());
262                }
263            }
264            return ms;
265        }
266
267        var msie1x = typeof ScriptEngineMajorVersion === "function"
268                ? ScriptEngineMajorVersion() //IE11 detection
269                : new Function("/*@cc_on return @_jscript_version; @*/")() >= 10, //conditional compilation from mickeysoft trick
270            ua = navigator.userAgent,
271            iphone = ua.match(new RegExp("iphone", "i")) !== null,
272            android = ua.match(new RegExp("android.*safari.*", "i")) !== null,
273            androidchrome = ua.match(new RegExp("android.*chrome.*", "i")) !== null,
274            androidfirefox = ua.match(new RegExp("android.*firefox.*", "i")) !== null,
275            kindle = /Kindle/i.test(ua) || /Silk/i.test(ua) || /KFTT/i.test(ua) || /KFOT/i.test(ua) || /KFJWA/i.test(ua) || /KFJWI/i.test(ua) || /KFSOWI/i.test(ua) || /KFTHWA/i.test(ua) || /KFTHWI/i.test(ua) || /KFAPWA/i.test(ua) || /KFAPWI/i.test(ua),
276            PasteEventType = isInputEventSupported('paste') ? 'paste' : isInputEventSupported('input') ? 'input' : "propertychange";
277
278        //if (androidchrome) {
279        //    var browser = navigator.userAgent.match(new RegExp("chrome.*", "i")),
280        //        version = parseInt(new RegExp(/[0-9]+/).exec(browser));
281        //    androidchrome32 = (version == 32);
282        //}
283
284        //masking scope
285        //actionObj definition see below
286        function maskScope(actionObj, maskset, opts) {
287            var isRTL = false,
288                valueOnFocus,
289                $el,
290                skipKeyPressEvent = false, //Safari 5.1.x - modal dialog fires keypress twice workaround
291                skipInputEvent = false, //skip when triggered from within inputmask
292                ignorable = false,
293                maxLength;
294
295            //maskset helperfunctions
296
297
298            function getMaskTemplate(baseOnInput, minimalPos, includeInput) {
299                minimalPos = minimalPos || 0;
300                var maskTemplate = [], ndxIntlzr, pos = 0, test, testPos;
301                do {
302                    if (baseOnInput === true && getMaskSet()['validPositions'][pos]) {
303                        var validPos = getMaskSet()['validPositions'][pos];
304                        test = validPos["match"];
305                        ndxIntlzr = validPos["locator"].slice();
306                        maskTemplate.push(test["fn"] == null ? test["def"] : (includeInput === true ? validPos["input"] : test["placeholder"] || opts.placeholder.charAt(pos % opts.placeholder.length)));
307                    } else {
308                        if (minimalPos > pos) {
309                            var testPositions = getTests(pos, ndxIntlzr, pos - 1);
310                            testPos = testPositions[0];
311                        } else {
312                            testPos = getTestTemplate(pos, ndxIntlzr, pos - 1);
313                        }
314                        test = testPos["match"];
315                        ndxIntlzr = testPos["locator"].slice();
316                        maskTemplate.push(test["fn"] == null ? test["def"] : test["placeholder"] || opts.placeholder.charAt(pos % opts.placeholder.length));
317                    }
318                    pos++;
319                } while ((maxLength == undefined || pos - 1 < maxLength) && test["fn"] != null || (test["fn"] == null && test["def"] != "") || minimalPos >= pos);
320                maskTemplate.pop(); //drop the last one which is empty
321                return maskTemplate;
322            }
323
324            function getMaskSet() {
325                return maskset;
326            }
327
328            function resetMaskSet(soft) {
329                var maskset = getMaskSet();
330                maskset["buffer"] = undefined;
331                maskset["tests"] = {};
332                if (soft !== true) {
333                    maskset["_buffer"] = undefined;
334                    maskset["validPositions"] = {};
335                    maskset["p"] = -1;
336                }
337            }
338
339            function getLastValidPosition(closestTo) {
340                var maskset = getMaskSet(), lastValidPosition = -1, valids = maskset["validPositions"];
341                if (closestTo == undefined) closestTo = -1;
342                var before = lastValidPosition, after = lastValidPosition;
343                for (var posNdx in valids) {
344                    var psNdx = parseInt(posNdx);
345                    if (closestTo == -1 || valids[psNdx]["match"].fn != null) {
346                        if (psNdx < closestTo) before = psNdx;
347                        if (psNdx >= closestTo) after = psNdx;
348                    }
349                }
350                lastValidPosition = (closestTo - before) > 1 || after < closestTo ? before : after;
351                return lastValidPosition;
352            }
353
354            function setValidPosition(pos, validTest, fromSetValid) {
355                if (opts.insertMode && getMaskSet()["validPositions"][pos] != undefined && fromSetValid == undefined) {
356                    //reposition & revalidate others
357                    var positionsClone = $.extend(true, {}, getMaskSet()["validPositions"]), lvp = getLastValidPosition(), i;
358                    for (i = pos; i <= lvp; i++) { //clear selection
359                        delete getMaskSet()["validPositions"][i];
360                    }
361                    getMaskSet()["validPositions"][pos] = validTest;
362                    var valid = true;
363                    for (i = pos; i <= lvp ; i++) {
364                        var t = positionsClone[i];
365                        if (t != undefined) {
366                            var j = t["match"].fn == null ? i + 1 : seekNext(i);
367                            if (positionCanMatchDefinition(j, t["match"].def)) {
368                                valid = valid && isValid(j, t["input"], true, true) !== false;
369                            } else valid = false;
370                        }
371                        if (!valid) break;
372                    }
373
374                    if (!valid) {
375                        getMaskSet()["validPositions"] = $.extend(true, {}, positionsClone);
376                        return false;
377                    }
378                } else
379                    getMaskSet()["validPositions"][pos] = validTest;
380
381                return true;
382            }
383
384            function stripValidPositions(start, end) {
385                var i, startPos = start, lvp;
386                for (i = start; i < end; i++) { //clear selection
387                    //TODO FIXME BETTER CHECK
388                    delete getMaskSet()["validPositions"][i];
389                }
390
391                for (i = end ; i <= getLastValidPosition() ;) {
392                    var t = getMaskSet()["validPositions"][i];
393                    var s = getMaskSet()["validPositions"][startPos];
394                    if (t != undefined && s == undefined) {
395                        if (positionCanMatchDefinition(startPos, t.match.def) && isValid(startPos, t["input"], true) !== false) {
396                            delete getMaskSet()["validPositions"][i];
397                            i++;
398                        }
399                        startPos++;
400                    } else i++;
401                }
402                lvp = getLastValidPosition();
403                //catchup
404                while (lvp > 0 && (getMaskSet()["validPositions"][lvp] == undefined || getMaskSet()["validPositions"][lvp].match.fn == null)) {
405                    delete getMaskSet()["validPositions"][lvp];
406                    lvp--;
407                }
408                resetMaskSet(true);
409            }
410
411            function getTestTemplate(pos, ndxIntlzr, tstPs) {
412                var testPositions = getTests(pos, ndxIntlzr, tstPs), testPos;
413                for (var ndx = 0; ndx < testPositions.length; ndx++) {
414                    testPos = testPositions[ndx];
415                    if (opts.greedy || (testPos["match"] && (testPos["match"].optionality === false || testPos["match"].newBlockMarker === false) && testPos["match"].optionalQuantifier !== true)) {
416                        break;
417                    }
418                }
419
420                return testPos;
421            }
422            function getTest(pos) {
423                if (getMaskSet()['validPositions'][pos]) {
424                    return getMaskSet()['validPositions'][pos]["match"];
425                }
426                return getTests(pos)[0]["match"];
427            }
428            function positionCanMatchDefinition(pos, def) {
429                var valid = false, tests = getTests(pos);
430                for (var tndx = 0; tndx < tests.length; tndx++) {
431                    if (tests[tndx]["match"] && tests[tndx]["match"].def == def) {
432                        valid = true;
433                        break;
434                    }
435                }
436                return valid;
437            };
438            function getTests(pos, ndxIntlzr, tstPs) {
439                var maskTokens = getMaskSet()["maskToken"], testPos = ndxIntlzr ? tstPs : 0, ndxInitializer = ndxIntlzr || [0], matches = [], insertStop = false;
440                function ResolveTestFromToken(maskToken, ndxInitializer, loopNdx, quantifierRecurse) { //ndxInitilizer contains a set of indexes to speedup searches in the mtokens
441
442                    function handleMatch(match, loopNdx, quantifierRecurse) {
443                        if (testPos == pos && match.matches == undefined) {
444                            matches.push({ "match": match, "locator": loopNdx.reverse() });
445                            return true;
446                        } else if (match.matches != undefined) {
447                            if (match.isGroup && quantifierRecurse !== true) { //when a group pass along to the quantifier
448                                match = handleMatch(maskToken.matches[tndx + 1], loopNdx);
449                                if (match) return true;
450                            } else if (match.isOptional) {
451                                var optionalToken = match;
452                                match = ResolveTestFromToken(match, ndxInitializer, loopNdx, quantifierRecurse);
453                                if (match) {
454                                    var latestMatch = matches[matches.length - 1]["match"];
455                                    var isFirstMatch = $.inArray(latestMatch, optionalToken.matches) == 0;
456                                    if (isFirstMatch) {
457                                        insertStop = true; //insert a stop for non greedy
458                                    }
459                                    testPos = pos; //match the position after the group
460                                }
461                            } else if (match.isAlternator) {
462                                var alternateToken = match;
463                                var currentMatches = matches.slice(), malternate1, malternate2, loopNdxCnt = loopNdx.length;
464                                var altIndex = ndxInitializer.length > 0 ? ndxInitializer.shift() : -1;
465                                if (altIndex == -1) {
466                                    var currentPos = testPos;
467                                    matches = [];
468                                    match = ResolveTestFromToken(alternateToken.matches[0], ndxInitializer.slice(), [0].concat(loopNdx), quantifierRecurse);
469                                    malternate1 = matches.slice();
470                                    testPos = currentPos;
471                                    matches = [];
472                                    match = ResolveTestFromToken(alternateToken.matches[1], ndxInitializer, [1].concat(loopNdx), quantifierRecurse);
473                                    malternate2 = matches.slice();
474                                    //fuzzy merge matches
475                                    matches = [];
476                                    for (var ndx1 = 0; ndx1 < malternate1.length; ndx1++) {
477                                        var altMatch = malternate1[ndx1]; currentMatches.push(altMatch);
478                                        for (var ndx2 = 0; ndx2 < malternate2.length; ndx2++) {
479                                            var altMatch2 = malternate2[ndx2];
480                                            //verify equality
481                                            if (altMatch.match.mask == altMatch2.match.mask) {
482                                                malternate2.splice(ndx2, 1);
483                                                altMatch.locator[loopNdxCnt] = -1;
484                                                break;
485                                            }
486                                        }
487                                    }
488                                    matches = currentMatches.concat(malternate2);
489
490                                } else {
491                                    match = handleMatch(alternateToken.matches[altIndex], [altIndex].concat(loopNdx), quantifierRecurse);
492                                }
493                                if (match) return true;
494                            } else if (match.isQuantifier && quantifierRecurse !== true) {
495                                var qt = match;
496                                opts.greedy = opts.greedy && isFinite(qt.quantifier.max); //greedy must be off when * or + is used (always!!)
497                                for (var qndx = (ndxInitializer.length > 0 && quantifierRecurse !== true) ? ndxInitializer.shift() : 0; (qndx < (isNaN(qt.quantifier.max) ? qndx + 1 : qt.quantifier.max)) && testPos <= pos; qndx++) {
498                                    var tokenGroup = maskToken.matches[$.inArray(qt, maskToken.matches) - 1];
499                                    match = handleMatch(tokenGroup, [qndx].concat(loopNdx), true);
500                                    if (match) {
501                                        //get latest match
502                                        var latestMatch = matches[matches.length - 1]["match"];
503                                        latestMatch.optionalQuantifier = qndx > qt.quantifier.min - 1;
504                                        var isFirstMatch = $.inArray(latestMatch, tokenGroup.matches) == 0;
505
506                                        if (isFirstMatch) { //search for next possible match
507                                            if (qndx > qt.quantifier.min - 1) {
508                                                insertStop = true;
509                                                testPos = pos; //match the position after the group
510                                                break; //stop quantifierloop
511                                            } else return true;
512                                        } else {
513                                            return true;
514                                        }
515                                    }
516                                }
517                            } else {
518                                match = ResolveTestFromToken(match, ndxInitializer, loopNdx, quantifierRecurse);
519                                if (match)
520                                    return true;
521                            }
522                        } else testPos++;
523                    }
524
525                    for (var tndx = (ndxInitializer.length > 0 ? ndxInitializer.shift() : 0) ; tndx < maskToken.matches.length; tndx++) {
526                        if (maskToken.matches[tndx]["isQuantifier"] !== true) {
527                            var match = handleMatch(maskToken.matches[tndx], [tndx].concat(loopNdx), quantifierRecurse);
528                            if (match && testPos == pos) {
529                                return match;
530                            } else if (testPos > pos) {
531                                break;
532                            }
533                        }
534                    }
535                }
536
537                //if (disableCache !== true && getMaskSet()['tests'][pos] && !getMaskSet()['validPositions'][pos]) {
538                //    return getMaskSet()['tests'][pos];
539                //}
540                if (ndxIntlzr == undefined) {
541                    var previousPos = pos - 1, test;
542                    while ((test = getMaskSet()['validPositions'][previousPos]) == undefined && previousPos > -1) {
543                        previousPos--;
544                    }
545                    if (test != undefined && previousPos > -1) {
546                        testPos = previousPos;
547                        ndxInitializer = test["locator"].slice();
548                    } else {
549                        previousPos = pos - 1;
550                        while ((test = getMaskSet()['tests'][previousPos]) == undefined && previousPos > -1) {
551                            previousPos--;
552                        }
553                        if (test != undefined && previousPos > -1) {
554                            testPos = previousPos;
555                            ndxInitializer = test[0]["locator"].slice();
556                        }
557                    }
558                }
559                for (var mtndx = ndxInitializer.shift() ; mtndx < maskTokens.length; mtndx++) {
560                    var match = ResolveTestFromToken(maskTokens[mtndx], ndxInitializer, [mtndx]);
561                    if ((match && testPos == pos) || testPos > pos) {
562                        break;
563                    }
564                }
565                if (matches.length == 0 || insertStop)
566                    matches.push({ "match": { fn: null, cardinality: 0, optionality: true, casing: null, def: "" }, "locator": [] });
567
568                getMaskSet()['tests'][pos] = matches;
569                //console.log(pos + " - " + JSON.stringify(matches));
570                return matches;
571            }
572
573            function getBufferTemplate() {
574                if (getMaskSet()['_buffer'] == undefined) {
575                    //generate template
576                    getMaskSet()["_buffer"] = getMaskTemplate(false, 1);
577                }
578                return getMaskSet()['_buffer'];
579            }
580
581            function getBuffer() {
582                if (getMaskSet()['buffer'] == undefined) {
583                    getMaskSet()['buffer'] = getMaskTemplate(true, getLastValidPosition(), true);
584                }
585                return getMaskSet()['buffer'];
586            }
587
588            function refreshFromBuffer(start, end) {
589                var buffer = getBuffer().slice(); //work on clone
590                if (start === true) {
591                    resetMaskSet();
592                    start = 0;
593                    end = buffer.length;
594                } else {
595                    for (var i = start; i < end; i++) {
596                        delete getMaskSet()["validPositions"][i];
597                        delete getMaskSet()["tests"][i];
598                    }
599                }
600
601                for (var i = start; i < end; i++) {
602                    if (buffer[i] != opts.skipOptionalPartCharacter) {
603                        isValid(i, buffer[i], true, true);
604                    }
605                }
606            }
607
608            function casing(elem, test) {
609                switch (test.casing) {
610                    case "upper":
611                        elem = elem.toUpperCase();
612                        break;
613                    case "lower":
614                        elem = elem.toLowerCase();
615                        break;
616                }
617
618                return elem;
619            }
620
621            function isValid(pos, c, strict, fromSetValid) { //strict true ~ no correction or autofill
622                strict = strict === true; //always set a value to strict to prevent possible strange behavior in the extensions 
623
624                function _isValid(position, c, strict, fromSetValid) {
625                    var rslt = false;
626                    $.each(getTests(position), function (ndx, tst) {
627                        var test = tst["match"];
628                        var loopend = c ? 1 : 0, chrs = '', buffer = getBuffer();
629                        for (var i = test.cardinality; i > loopend; i--) {
630                            chrs += getBufferElement(position - (i - 1));
631                        }
632                        if (c) {
633                            chrs += c;
634                        }
635
636                        //return is false or a json object => { pos: ??, c: ??} or true
637                        rslt = test.fn != null ?
638                            test.fn.test(chrs, getMaskSet(), position, strict, opts)
639                            : (c == test["def"] || c == opts.skipOptionalPartCharacter) && test["def"] != "" ? //non mask
640                        { c: test["def"], pos: position }
641                            : false;
642
643                        if (rslt !== false) {
644                            var elem = rslt.c != undefined ? rslt.c : c;
645                            elem = (elem == opts.skipOptionalPartCharacter && test["fn"] === null) ? test["def"] : elem;
646
647                            var validatedPos = position;
648                            if (rslt["remove"] != undefined) { //remove position
649                                stripValidPositions(rslt["remove"], rslt["remove"] + 1);
650                            }
651
652                            if (rslt["refreshFromBuffer"]) {
653                                var refresh = rslt["refreshFromBuffer"];
654                                strict = true;
655                                refreshFromBuffer(refresh === true ? refresh : refresh["start"], refresh["end"]);
656                                if (rslt.pos == undefined && rslt.c == undefined) {
657                                    rslt.pos = getLastValidPosition();
658                                    return false;//breakout if refreshFromBuffer && nothing to insert
659                                }
660                                validatedPos = rslt.pos != undefined ? rslt.pos : position;
661                                if (validatedPos != position) {
662                                    rslt = $.extend(rslt, isValid(validatedPos, elem, true)); //revalidate new position strict
663                                    return false;
664                                }
665
666                            } else if (rslt !== true && rslt.pos != undefined && rslt["pos"] != position) { //their is a position offset
667                                validatedPos = rslt["pos"];
668                                refreshFromBuffer(position, validatedPos);
669                                if (validatedPos != position) {
670                                    rslt = $.extend(rslt, isValid(validatedPos, elem, true)); //revalidate new position strict
671                                    return false;
672                                }
673                            }
674
675                            if (rslt != true && rslt.pos == undefined && rslt.c == undefined) {
676                                return false; //breakout if nothing to insert
677                            }
678
679                            if (ndx > 0) {
680                                resetMaskSet(true);
681                            }
682
683                            if (!setValidPosition(validatedPos, $.extend({}, tst, { "input": casing(elem, test) }), fromSetValid))
684                                rslt = false;
685                            return false; //break from $.each
686                        }
687                    });
688
689                    return rslt;
690                }
691
692                //Check for a nonmask before the pos
693                var buffer = getBuffer();
694                for (var pndx = pos - 1; pndx > -1; pndx--) {
695                    if (getMaskSet()["validPositions"][pndx] && getMaskSet()["validPositions"][pndx].fn == null)
696                        break;
697                    else if ((!isMask(pndx) || buffer[pndx] != getPlaceholder(pndx)) && getTests(pndx).length > 1) {
698                        _isValid(pndx, buffer[pndx], true);
699                        break;
700                    }
701                }
702
703                var maskPos = pos;
704                if (maskPos >= getMaskLength()) {
705                    // console.log("try alternate match");
706                    return false;
707                }
708                var result = _isValid(maskPos, c, strict, fromSetValid);
709                if (!strict && result === false) {
710                    var currentPosValid = getMaskSet()["validPositions"][maskPos];
711                    if (currentPosValid && currentPosValid["match"].fn == null && (currentPosValid["match"].def == c || c == opts.skipOptionalPartCharacter)) {
712                        result = { "caret": seekNext(maskPos) };
713                    } else if ((opts.insertMode || getMaskSet()["validPositions"][seekNext(maskPos)] == undefined) && !isMask(maskPos)) { //does the input match on a further position?
714                        for (var nPos = maskPos + 1, snPos = seekNext(maskPos) ; nPos <= snPos; nPos++) {
715                            result = _isValid(nPos, c, strict, fromSetValid);
716                            if (result !== false) {
717                                maskPos = nPos;
718                                break;
719                            }
720                        }
721                    }
722                }
723
724                if (result === true) result = { "pos": maskPos };
725                return result;
726            }
727
728            function isMask(pos) {
729                var test = getTest(pos);
730                return test.fn != null ? test.fn : false;
731            }
732
733            function getMaskLength() {
734                var maskLength;
735                maxLength = $el.prop('maxLength');
736                if (maxLength == -1) maxLength = undefined; /* FF sets no defined max length to -1 */
737                if (opts.greedy == false) {
738                    var pos, lvp = getLastValidPosition(), testPos = getMaskSet()["validPositions"][lvp],
739                        ndxIntlzr = testPos != undefined ? testPos["locator"].slice() : undefined;
740                    for (pos = lvp + 1; testPos == undefined || (testPos["match"]["fn"] != null || (testPos["match"]["fn"] == null && testPos["match"]["def"] != "")) ; pos++) {
741                        testPos = getTestTemplate(pos, ndxIntlzr, pos - 1);
742                        ndxIntlzr = testPos["locator"].slice();
743                    }
744                    maskLength = pos;
745                } else
746                    maskLength = getBuffer().length;
747
748                return (maxLength == undefined || maskLength < maxLength) ? maskLength : maxLength;
749            }
750
751            function seekNext(pos) {
752                var maskL = getMaskLength();
753                if (pos >= maskL) return maskL;
754                var position = pos;
755                while (++position < maskL && !isMask(position) && (opts.nojumps !== true || opts.nojumpsThreshold > position)) {
756                }
757                return position;
758            }
759
760            function seekPrevious(pos) {
761                var position = pos;
762                if (position <= 0) return 0;
763
764                while (--position > 0 && !isMask(position)) {
765                };
766                return position;
767            }
768
769            function getBufferElement(position) {
770                return getMaskSet()["validPositions"][position] == undefined ? getPlaceholder(position) : getMaskSet()["validPositions"][position]["input"];
771            }
772
773            function writeBuffer(input, buffer, caretPos) {
774                input._valueSet(buffer.join(''));
775                if (caretPos != undefined) {
776                    caret(input, caretPos);
777                }
778            }
779
780            function getPlaceholder(pos, test) {
781                test = test || getTest(pos);
782                return test["placeholder"] || (test["fn"] == null ? test["def"] : opts.placeholder.charAt(pos % opts.placeholder.length));
783            }
784
785            function checkVal(input, writeOut, strict, nptvl, intelliCheck) {
786                var inputValue = nptvl != undefined ? nptvl.slice() : truncateInput(input._valueGet()).split('');
787                resetMaskSet();
788                if (writeOut) input._valueSet(""); //initial clear
789                $.each(inputValue, function (ndx, charCode) {
790                    if (intelliCheck === true) {
791                        var p = getMaskSet()["p"],
792                            lvp = p == -1 ? p : seekPrevious(p),
793                            pos = lvp == -1 ? ndx : seekNext(lvp);
794                        if ($.inArray(charCode, getBufferTemplate().slice(lvp + 1, pos)) == -1) {
795                            keypressEvent.call(input, undefined, true, charCode.charCodeAt(0), false, strict, ndx);
796                        }
797                    } else {
798                        keypressEvent.call(input, undefined, true, charCode.charCodeAt(0), false, strict, ndx);
799                        strict = strict || (ndx > 0 && ndx > getMaskSet()["p"]);
800                    }
801                });
802                if (writeOut) {
803                    var keypressResult = opts.onKeyPress.call(this, undefined, getBuffer(), 0, opts);
804                    handleOnKeyResult(input, keypressResult);
805                    writeBuffer(input, getBuffer(), $(input).is(":focus") ? seekNext(getLastValidPosition(0)) : undefined);
806                }
807            }
808
809            function escapeRegex(str) {
810                return $.inputmask.escapeRegex.call(this, str);
811            }
812
813            function truncateInput(inputValue) {
814                return inputValue.replace(new RegExp("(" + escapeRegex(getBufferTemplate().join('')) + ")*$"), "");
815            }
816            function unmaskedvalue($input) {
817                if ($input.data('_inputmask') && !$input.hasClass('hasDatepicker')) {
818                    var umValue = [], vps = getMaskSet()["validPositions"];
819                    for (var pndx in vps) {
820                        if (vps[pndx]["match"] && vps[pndx]["match"].fn != null) {
821                            umValue.push(vps[pndx]["input"]);
822                        }
823                    }
824                    var unmaskedValue = (isRTL ? umValue.reverse() : umValue).join('');
825                    var bufferValue = (isRTL ? getBuffer().reverse() : getBuffer()).join('');
826                    if ($.isFunction(opts.onUnMask)) {
827                        unmaskedValue = opts.onUnMask.call($input, bufferValue, unmaskedValue, opts);
828                    }
829                    return unmaskedValue;
830                } else {
831                    return $input[0]._valueGet();
832                }
833            }
834            function TranslatePosition(pos) {
835                if (isRTL && typeof pos == 'number' && (!opts.greedy || opts.placeholder != "")) {
836                    var bffrLght = getBuffer().length;
837                    pos = bffrLght - pos;
838                }
839                return pos;
840            }
841            function caret(input, begin, end) {
842                var npt = input.jquery && input.length > 0 ? input[0] : input, range;
843                if (typeof begin == 'number') {
844                    begin = TranslatePosition(begin);
845                    end = TranslatePosition(end);
846                    end = (typeof end == 'number') ? end : begin;
847
848                    //store caret for multi scope
849                    var data = $(npt).data('_inputmask') || {};
850                    data["caret"] = { "begin": begin, "end": end };
851                    $(npt).data('_inputmask', data);
852
853                    if (!$(npt).is(":visible")) {
854                        return;
855                    }
856
857                    npt.scrollLeft = npt.scrollWidth;
858                    if (opts.insertMode == false && begin == end) end++; //set visualization for insert/overwrite mode
859                    if (npt.setSelectionRange) {
860                        npt.selectionStart = begin;
861                        npt.selectionEnd = end;
862
863                    } else if (npt.createTextRange) {
864                        range = npt.createTextRange();
865                        range.collapse(true);
866                        range.moveEnd('character', end);
867                        range.moveStart('character', begin);
868                        range.select();
869                    }
870                } else {
871                    var data = $(npt).data('_inputmask');
872                    if (!$(npt).is(":visible") && data && data["caret"] != undefined) {
873                        begin = data["caret"]["begin"];
874                        end = data["caret"]["end"];
875                    } else if (npt.setSelectionRange) {
876                        begin = npt.selectionStart;
877                        end = npt.selectionEnd;
878                    } else if (document.selection && document.selection.createRange) {
879                        range = document.selection.createRange();
880                        begin = 0 - range.duplicate().moveStart('character', -100000);
881                        end = begin + range.text.length;
882                    }
883                    begin = TranslatePosition(begin);
884                    end = TranslatePosition(end);
885                    return { "begin": begin, "end": end };
886                }
887            }
888            function determineLastRequiredPosition(returnDefinition) {
889                var buffer = getBuffer(), bl = buffer.length,
890                    pos, lvp = getLastValidPosition(), positions = {},
891                    ndxIntlzr = getMaskSet()["validPositions"][lvp] != undefined ? getMaskSet()["validPositions"][lvp]["locator"].slice() : undefined, testPos;
892                for (pos = lvp + 1; pos < buffer.length; pos++) {
893                    testPos = getTestTemplate(pos, ndxIntlzr, pos - 1);
894                    ndxIntlzr = testPos["locator"].slice();
895                    positions[pos] = $.extend(true, {}, testPos);
896                }
897
898                for (pos = bl - 1; pos > lvp; pos--) {
899                    testPos = positions[pos]["match"];
900                    if ((testPos.optionality || testPos.optionalQuantifier) && buffer[pos] == getPlaceholder(pos, testPos)) {
901                        bl--;
902                    } else break;
903                }
904                return returnDefinition ? { "l": bl, "def": positions[bl] ? positions[bl]["match"] : undefined } : bl;
905            }
906            function clearOptionalTail(input) {
907                var buffer = getBuffer(), tmpBuffer = buffer.slice();
908                var rl = determineLastRequiredPosition();
909                tmpBuffer.length = rl;
910                writeBuffer(input, tmpBuffer);
911            }
912            function isComplete(buffer) { //return true / false / undefined (repeat *)
913                if ($.isFunction(opts.isComplete)) return opts.isComplete.call($el, buffer, opts);
914                if (opts.repeat == "*") return undefined;
915                var complete = false, lrp = determineLastRequiredPosition(true), aml = seekPrevious(lrp["l"]), lvp = getLastValidPosition();
916
917                if (lvp == aml) {
918                    if (lrp["def"] == undefined || lrp["def"].newBlockMarker || lrp["def"].optionalQuantifier) {
919                        complete = true;
920                        for (var i = 0; i <= aml; i++) {
921                            var mask = isMask(i);
922                            if ((mask && (buffer[i] == undefined || buffer[i] == getPlaceholder(i))) || (!mask && buffer[i] != getPlaceholder(i))) {
923                                complete = false;
924                                break;
925                            }
926                        }
927                    }
928                }
929                return complete;
930            }
931
932            function isSelection(begin, end) {
933                return isRTL ? (begin - end) > 1 || ((begin - end) == 1 && opts.insertMode) :
934                (end - begin) > 1 || ((end - begin) == 1 && opts.insertMode);
935            }
936
937            function installEventRuler(npt) {
938                var events = $._data(npt).events;
939
940                $.each(events, function (eventType, eventHandlers) {
941                    $.each(eventHandlers, function (ndx, eventHandler) {
942                        if (eventHandler.namespace == "inputmask") {
943                            if (eventHandler.type != "setvalue") {
944                                var handler = eventHandler.handler;
945                                eventHandler.handler = function (e) {
946                                    if (this.readOnly || this.disabled)
947                                        e.preventDefault;
948                                    else
949                                        return handler.apply(this, arguments);
950                                };
951                            }
952                        }
953                    });
954                });
955            }
956
957            function patchValueProperty(npt) {
958
959                function PatchValhook(type) {
960                    if ($.valHooks[type] == undefined || $.valHooks[type].inputmaskpatch != true) {
961                        var valueGet = $.valHooks[type] && $.valHooks[type].get ? $.valHooks[type].get : function (elem) { return elem.value; };
962                        var valueSet = $.valHooks[type] && $.valHooks[type].set ? $.valHooks[type].set : function (elem, value) {
963                            elem.value = value;
964                            return elem;
965                        };
966
967                        $.valHooks[type] = {
968                            get: function (elem) {
969                                var $elem = $(elem);
970                                if ($elem.data('_inputmask')) {
971                                    if ($elem.data('_inputmask')['opts'].autoUnmask)
972                                        return $elem.inputmask('unmaskedvalue');
973                                    else {
974                                        var result = valueGet(elem),
975                                            inputData = $elem.data('_inputmask'),
976                                            maskset = inputData['maskset'],
977                                            bufferTemplate = maskset['_buffer'];
978                                        bufferTemplate = bufferTemplate ? bufferTemplate.join('') : '';
979                                        return result != bufferTemplate ? result : '';
980                                    }
981                                } else return valueGet(elem);
982                            },
983                            set: function (elem, value) {
984                                var $elem = $(elem), inputData = $elem.data('_inputmask'), result;
985                                if (inputData) {
986                                    result = valueSet(elem, $.isFunction(inputData['opts'].onBeforeMask) ? inputData['opts'].onBeforeMask.call(el, value, inputData['opts']) : value);
987                                    $elem.triggerHandler('setvalue.inputmask');
988                                } else {
989                                    result = valueSet(elem, value);
990                                }
991                                return result;
992                            },
993                            inputmaskpatch: true
994                        };
995                    }
996                }
997
998                var valueProperty;
999                if (Object.getOwnPropertyDescriptor)
1000                    valueProperty = Object.getOwnPropertyDescriptor(npt, "value");
1001                if (valueProperty && valueProperty.get) {
1002                    if (!npt._valueGet) {
1003                        var valueGet = valueProperty.get;
1004                        var valueSet = valueProperty.set;
1005                        npt._valueGet = function () {
1006                            return isRTL ? valueGet.call(this).split('').reverse().join('') : valueGet.call(this);
1007                        };
1008                        npt._valueSet = function (value) {
1009                            valueSet.call(this, isRTL ? value.split('').reverse().join('') : value);
1010                        };
1011
1012                        Object.defineProperty(npt, "value", {
1013                            get: function () {
1014                                var $self = $(this), inputData = $(this).data('_inputmask');
1015                                if (inputData) {
1016                                    return inputData['opts'].autoUnmask ? $self.inputmask('unmaskedvalue') : (valueGet.call(this) != getBufferTemplate().join('') ? valueGet.call(this) : '');
1017                                } else return valueGet.call(this);
1018                            },
1019                            set: function (value) {
1020                                var inputData = $(this).data('_inputmask');
1021                                if (inputData) {
1022                                    valueSet.call(this, $.isFunction(inputData['opts'].onBeforeMask) ? inputData['opts'].onBeforeMask.call(el, value, inputData['opts']) : value);
1023                                    $(this).triggerHandler('setvalue.inputmask');
1024                                } else {
1025                                    valueSet.call(this, value);
1026                                }
1027                            }
1028                        });
1029                    }
1030                } else if (document.__lookupGetter__ && npt.__lookupGetter__("value")) {
1031                    if (!npt._valueGet) {
1032                        var valueGet = npt.__lookupGetter__("value");
1033                        var valueSet = npt.__lookupSetter__("value");
1034                        npt._valueGet = function () {
1035                            return isRTL ? valueGet.call(this).split('').reverse().join('') : valueGet.call(this);
1036                        };
1037                        npt._valueSet = function (value) {
1038                            valueSet.call(this, isRTL ? value.split('').reverse().join('') : value);
1039                        };
1040
1041                        npt.__defineGetter__("value", function () {
1042                            var $self = $(this), inputData = $(this).data('_inputmask');
1043                            if (inputData) {
1044                                return inputData['opts'].autoUnmask ? $self.inputmask('unmaskedvalue') : (valueGet.call(this) != getBufferTemplate().join('') ? valueGet.call(this) : '');
1045                            } else return valueGet.call(this);
1046                        });
1047                        npt.__defineSetter__("value", function (value) {
1048                            var inputData = $(this).data('_inputmask');
1049                            if (inputData) {
1050                                valueSet.call(this, $.isFunction(inputData['opts'].onBeforeMask) ? inputData['opts'].onBeforeMask.call(el, value, inputData['opts']) : value);
1051                                $(this).triggerHandler('setvalue.inputmask');
1052                            } else {
1053                                valueSet.call(this, value);
1054                            }
1055                        });
1056                    }
1057                } else {
1058                    if (!npt._valueGet) {
1059                        npt._valueGet = function () { return isRTL ? this.value.split('').reverse().join('') : this.value; };
1060                        npt._valueSet = function (value) { this.value = isRTL ? value.split('').reverse().join('') : value; };
1061                    }
1062                    PatchValhook(npt.type);
1063                }
1064            }
1065
1066            function handleRemove(input, k, pos) {
1067                if (opts.numericInput || isRTL) {
1068                    if (k == opts.keyCode.BACKSPACE)
1069                        k = opts.keyCode.DELETE;
1070                    else if (k == opts.keyCode.DELETE)
1071                        k = opts.keyCode.BACKSPACE;
1072
1073                    if (isRTL) {
1074                        var pend = pos.end;
1075                        pos.end = pos.begin;
1076                        pos.begin = pend;
1077                    }
1078                }
1079
1080                if (k == opts.keyCode.BACKSPACE && pos.end - pos.begin <= 1)
1081                    pos.begin = seekPrevious(pos.begin);
1082                else if (k == opts.keyCode.DELETE && pos.begin == pos.end)
1083                    pos.end++;
1084
1085                stripValidPositions(pos.begin, pos.end);
1086                var firstMaskedPos = getLastValidPosition(pos.begin);
1087                if (firstMaskedPos < pos.begin) {
1088                    getMaskSet()["p"] = seekNext(firstMaskedPos);
1089                } else {
1090                    getMaskSet()["p"] = pos.begin;
1091                }
1092            }
1093
1094            function handleOnKeyResult(input, keyResult, caretPos) {
1095                if (keyResult && keyResult["refreshFromBuffer"]) {
1096                    var refresh = keyResult["refreshFromBuffer"];
1097                    refreshFromBuffer(refresh === true ? refresh : refresh["start"], refresh["end"]);
1098
1099                    resetMaskSet(true);
1100                    if (caretPos != undefined) {
1101                        writeBuffer(input, getBuffer());
1102                        caret(input, keyResult.caret || caretPos.begin, keyResult.caret || caretPos.end);
1103                    }
1104                }
1105            }
1106
1107            function keydownEvent(e) {
1108                //Safari 5.1.x - modal dialog fires keypress twice workaround
1109                skipKeyPressEvent = false;
1110                var input = this, $input = $(input), k = e.keyCode, pos = caret(input);
1111
1112                //backspace, delete, and escape get special treatment
1113                if (k == opts.keyCode.BACKSPACE || k == opts.keyCode.DELETE || (iphone && k == 127) || e.ctrlKey && k == 88) { //backspace/delete
1114                    e.preventDefault(); //stop default action but allow propagation
1115                    if (k == 88) valueOnFocus = getBuffer().join('');
1116                    handleRemove(input, k, pos);
1117                    writeBuffer(input, getBuffer(), getMaskSet()["p"]);
1118                    if (input._valueGet() == getBufferTemplate().join(''))
1119                        $input.trigger('cleared');
1120
1121                    if (opts.showTooltip) { //update tooltip
1122                        $input.prop("title", getMaskSet()["mask"]);
1123                    }
1124                } else if (k == opts.keyCode.END || k == opts.keyCode.PAGE_DOWN) { //when END or PAGE_DOWN pressed set position at lastmatch
1125                    setTimeout(function () {
1126                        var caretPos = seekNext(getLastValidPosition());
1127                        if (!opts.insertMode && caretPos == getMaskLength() && !e.shiftKey) caretPos--;
1128                        caret(input, e.shiftKey ? pos.begin : caretPos, caretPos);
1129                    }, 0);
1130                } else if ((k == opts.keyCode.HOME && !e.shiftKey) || k == opts.keyCode.PAGE_UP) { //Home or page_up
1131                    caret(input, 0, e.shiftKey ? pos.begin : 0);
1132                } else if (k == opts.keyCode.ESCAPE || (k == 90 && e.ctrlKey)) { //escape && undo
1133                    checkVal(input, true, false, valueOnFocus.split(''));
1134                    $input.click();
1135                } else if (k == opts.keyCode.INSERT && !(e.shiftKey || e.ctrlKey)) { //insert
1136                    opts.insertMode = !opts.insertMode;
1137                    caret(input, !opts.insertMode && pos.begin == getMaskLength() ? pos.begin - 1 : pos.begin);
1138                } else if (opts.insertMode == false && !e.shiftKey) {
1139                    if (k == opts.keyCode.RIGHT) {
1140                        setTimeout(function () {
1141                            var caretPos = caret(input);
1142                            caret(input, caretPos.begin);
1143                        }, 0);
1144                    } else if (k == opts.keyCode.LEFT) {
1145                        setTimeout(function () {
1146                            var caretPos = caret(input);
1147                            caret(input, isRTL ? caretPos.begin + 1 : caretPos.begin - 1);
1148                        }, 0);
1149                    }
1150                }
1151
1152                var currentCaretPos = caret(input);
1153                var keydownResult = opts.onKeyDown.call(this, e, getBuffer(), currentCaretPos.begin, opts);
1154                handleOnKeyResult(input, keydownResult, currentCaretPos);
1155                ignorable = $.inArray(k, opts.ignorables) != -1;
1156            }
1157
1158            function keypressEvent(e, checkval, k, writeOut, strict, ndx) {
1159                //Safari 5.1.x - modal dialog fires keypress twice workaround
1160                if (k == undefined && skipKeyPressEvent) return false;
1161                skipKeyPressEvent = true;
1162
1163                var input = this, $input = $(input);
1164
1165                e = e || window.event;
1166                var k = checkval ? k : (e.which || e.charCode || e.keyCode);
1167
1168                if (checkval !== true && (!(e.ctrlKey && e.altKey) && (e.ctrlKey || e.metaKey || ignorable))) {
1169                    return true;
1170                } else {
1171                    if (k) {
1172                        //special treat the decimal separator
1173                        if (checkval !== true && k == 46 && e.shiftKey == false && opts.radixPoint == ",") k = 44;
1174
1175                        var pos, forwardPosition, c = String.fromCharCode(k);
1176                        if (checkval) {
1177                            var pcaret = strict ? ndx : getLastValidPosition() + 1;
1178                            pos = { begin: pcaret, end: pcaret };
1179                        } else {
1180                            pos = caret(input);
1181                        }
1182
1183                        //should we clear a possible selection??
1184                        var isSlctn = isSelection(pos.begin, pos.end);
1185                        if (isSlctn) {
1186                            getMaskSet()["undoPositions"] = $.extend(true, {}, getMaskSet()["validPositions"]); //init undobuffer for recovery when not valid
1187                            handleRemove(input, opts.keyCode.DELETE, pos);
1188                            if (!opts.insertMode) { //preserve some space
1189                                opts.insertMode = !opts.insertMode;
1190                                setValidPosition(pos.begin, strict);
1191                                opts.insertMode = !opts.insertMode;
1192                            }
1193                            isSlctn = !opts.multi;
1194                        }
1195
1196                        getMaskSet()["writeOutBuffer"] = true;
1197                        var p = isRTL && !isSlctn ? pos.end : pos.begin;
1198                        var valResult = isValid(p, c, strict);
1199                        if (valResult !== false) {
1200                            if (valResult !== true) {
1201                                p = valResult.pos != undefined ? valResult.pos : p; //set new position from isValid
1202                                c = valResult.c != undefined ? valResult.c : c; //set new char from isValid
1203                            }
1204                            resetMaskSet(true);
1205                            if (valResult.caret != undefined)
1206                                forwardPosition = valResult.caret;
1207                            else {
1208                                var vps = getMaskSet()["validPositions"];
1209                                if (vps[p + 1] != undefined && getTests(p + 1, vps[p].locator.slice(), p).length > 1)
1210                                    forwardPosition = p + 1;
1211                                else
1212                                    forwardPosition = seekNext(p);
1213                            }
1214                            getMaskSet()["p"] = forwardPosition; //needed for checkval
1215                        }
1216
1217                        if (writeOut !== false) {
1218                            var self = this;
1219                            setTimeout(function () { opts.onKeyValidation.call(self, valResult, opts); }, 0);
1220                            if (getMaskSet()["writeOutBuffer"] && valResult !== false) {
1221                                var buffer = getBuffer();
1222                                writeBuffer(input, buffer, checkval ? undefined : opts.numericInput ? seekPrevious(forwardPosition) : forwardPosition);
1223                                if (checkval !== true) {
1224                                    setTimeout(function () { //timeout needed for IE
1225                                        if (isComplete(buffer) === true)
1226                                            $input.trigger("complete");
1227                                        skipInputEvent = true;
1228                                        $input.trigger("input");
1229                                    }, 0);
1230                                }
1231                            } else if (isSlctn) {
1232                                getMaskSet()["buffer"] = undefined;
1233                                getMaskSet()["validPositions"] = getMaskSet()["undoPositions"];
1234                            }
1235                        } else if (isSlctn) {
1236                            getMaskSet()["buffer"] = undefined;
1237                            getMaskSet()["validPositions"] = getMaskSet()["undoPositions"];
1238                        }
1239
1240
1241                        if (opts.showTooltip) { //update tooltip
1242                            $input.prop("title", getMaskSet()["mask"]);
1243                        }
1244
1245                        //needed for IE8 and below
1246                        if (e && checkval != true) {
1247                            e.preventDefault ? e.preventDefault() : e.returnValue = false;
1248
1249                            var currentCaretPos = caret(input);
1250                            var keypressResult = opts.onKeyPress.call(this, e, getBuffer(), currentCaretPos.begin, opts);
1251                            handleOnKeyResult(input, keypressResult, currentCaretPos);
1252                        }
1253                        var temp;
1254                        for (var i in getMaskSet().validPositions) {
1255                            temp += " " + i;
1256                        }
1257                    }
1258                }
1259            }
1260            function keyupEvent(e) {
1261                var $input = $(this), input = this, k = e.keyCode, buffer = getBuffer();
1262
1263                var currentCaretPos = caret(input);
1264                var keyupResult = opts.onKeyUp.call(this, e, buffer, currentCaretPos.begin, opts);
1265                handleOnKeyResult(input, keyupResult, currentCaretPos);
1266                if (k == opts.keyCode.TAB && opts.showMaskOnFocus) {
1267                    if ($input.hasClass('focus-inputmask') && input._valueGet().length == 0) {
1268                        resetMaskSet();
1269                        buffer = getBuffer();
1270                        writeBuffer(input, buffer);
1271                        caret(input, 0);
1272                        valueOnFocus = getBuffer().join('');
1273                    } else {
1274                        writeBuffer(input, buffer);
1275                        caret(input, TranslatePosition(0), TranslatePosition(getMaskLength()));
1276                    }
1277                }
1278            }
1279            function pasteEvent(e) {
1280                if (skipInputEvent === true && e.type == "input") {
1281                    skipInputEvent = false;
1282                    return true;
1283                }
1284
1285                var input = this, $input = $(input), inputValue = input._valueGet();
1286                //paste event for IE8 and lower I guess ;-)
1287                if (e.type == "propertychange" && input._valueGet().length <= getMaskLength()) {
1288                    return true;
1289                } else if (e.type == "paste") {
1290                    if (window.clipboardData && window.clipboardData.getData) { // IE
1291                        inputValue = window.clipboardData.getData('Text');
1292                    } else if (e.originalEvent && e.originalEvent.clipboardData && e.originalEvent.clipboardData.getData) {
1293                        inputValue = e.originalEvent.clipboardData.getData('text/plain');
1294                    }
1295                }
1296
1297                var pasteValue = $.isFunction(opts.onBeforePaste) ? opts.onBeforePaste.call(input, inputValue, opts) : inputValue;
1298                checkVal(input, true, false, pasteValue.split(''), true);
1299                $input.click();
1300                if (isComplete(getBuffer()) === true)
1301                    $input.trigger("complete");
1302
1303                return false;
1304            }
1305            function mobileInputEvent(e) {
1306                if (skipInputEvent === true && e.type == "input") {
1307                    skipInputEvent = false;
1308                    return true;
1309                }
1310                var input = this;
1311
1312                //backspace in chrome32 only fires input event - detect & treat
1313                var caretPos = caret(input),
1314                    currentValue = input._valueGet();
1315
1316                currentValue = currentValue.replace(new RegExp("(" + escapeRegex(getBufferTemplate().join('')) + ")*"), "");
1317                //correct caretposition for chrome
1318                if (caretPos.begin > currentValue.length) {
1319                    caret(input, currentValue.length);
1320                    caretPos = caret(input);
1321                }
1322                if ((getBuffer().length - currentValue.length) == 1 && currentValue.charAt(caretPos.begin) != getBuffer()[caretPos.begin]
1323                    && currentValue.charAt(caretPos.begin + 1) != getBuffer()[caretPos.begin]
1324                    && !isMask(caretPos.begin)) {
1325                    e.keyCode = opts.keyCode.BACKSPACE;
1326                    keydownEvent.call(input, e);
1327                }
1328                e.preventDefault();
1329            }
1330
1331            function mask(el) {
1332                $el = $(el);
1333                if ($el.is(":input") && $el.attr("type") != "number") {
1334                    //store tests & original buffer in the input element - used to get the unmasked value
1335                    $el.data('_inputmask', {
1336                        'maskset': maskset,
1337                        'opts': opts,
1338                        'isRTL': false
1339                    });
1340
1341                    //show tooltip
1342                    if (opts.showTooltip) {
1343                        $el.prop("title", getMaskSet()["mask"]);
1344                    }
1345
1346                    patchValueProperty(el);
1347
1348                    if (el.dir == "rtl" || opts.rightAlign)
1349                        $el.css("text-align", "right");
1350
1351                    if (el.dir == "rtl" || opts.numericInput) {
1352                        el.dir = "ltr";
1353                        $el.removeAttr("dir");
1354                        var inputData = $el.data('_inputmask');
1355                        inputData['isRTL'] = true;
1356                        $el.data('_inputmask', inputData);
1357                        isRTL = true;
1358                    }
1359
1360                    //unbind all events - to make sure that no other mask will interfere when re-masking
1361                    $el.unbind(".inputmask");
1362                    $el.removeClass('focus-inputmask');
1363                    //bind events
1364                    $el.closest('form').bind("submit", function () { //trigger change on submit if any
1365                        if (valueOnFocus != getBuffer().join('')) {
1366                            $el.change();
1367                        }
1368                        if (opts.autoUnmask && opts.removeMaskOnSubmit) {
1369                            $el.inputmask("remove");
1370                        }
1371                    }).bind('reset', function () {
1372                        setTimeout(function () {
1373                            $el.trigger("setvalue");
1374                        }, 0);
1375                    });
1376                    $el.bind("mouseenter.inputmask", function () {
1377                        var $input = $(this), input = this;
1378                        if (!$input.hasClass('focus-inputmask') && opts.showMaskOnHover) {
1379                            if (input._valueGet() != getBuffer().join('')) {
1380                                writeBuffer(input, getBuffer());
1381                            }
1382                        }
1383                    }).bind("blur.inputmask", function () {
1384                        var $input = $(this), input = this;
1385                        if ($input.data('_inputmask')) {
1386                            var nptValue = input._valueGet(), buffer = getBuffer();
1387                            $input.removeClass('focus-inputmask');
1388                            if (valueOnFocus != getBuffer().join('')) {
1389                                $input.change();
1390                            }
1391                            if (opts.clearMaskOnLostFocus && nptValue != '') {
1392                                if (nptValue == getBufferTemplate().join(''))
1393                                    input._valueSet('');
1394                                else { //clearout optional tail of the mask
1395                                    clearOptionalTail(input);
1396                                }
1397                            }
1398                            if (isComplete(buffer) === false) {
1399                                $input.trigger("incomplete");
1400                                if (opts.clearIncomplete) {
1401                                    resetMaskSet();
1402                                    if (opts.clearMaskOnLostFocus)
1403                                        input._valueSet('');
1404                                    else {
1405                                        buffer = getBufferTemplate().slice();
1406                                        writeBuffer(input, buffer);
1407                                    }
1408                                }
1409                            }
1410                        }
1411                    }).bind("focus.inputmask", function () {
1412                        var $input = $(this), input = this, nptValue = input._valueGet();
1413                        if (opts.showMaskOnFocus && !$input.hasClass('focus-inputmask') && (!opts.showMaskOnHover || (opts.showMaskOnHover && nptValue == ''))) {
1414                            if (input._valueGet() != getBuffer().join('')) {
1415                                writeBuffer(input, getBuffer(), seekNext(getLastValidPosition()));
1416                            }
1417                        }
1418                        $input.addClass('focus-inputmask');
1419                        valueOnFocus = getBuffer().join('');
1420                    }).bind("mouseleave.inputmask", function () {
1421                        var $input = $(this), input = this;
1422                        if (opts.clearMaskOnLostFocus) {
1423                            if (!$input.hasClass('focus-inputmask') && input._valueGet() != $input.attr("placeholder")) {
1424                                if (input._valueGet() == getBufferTemplate().join('') || input._valueGet() == '')
1425                                    input._valueSet('');
1426                                else { //clearout optional tail of the mask
1427                                    clearOptionalTail(input);
1428                                }
1429                            }
1430                        }
1431                    }).bind("click.inputmask", function () {
1432                        var input = this;
1433                        if ($(input).is(":focus")) {
1434                            setTimeout(function () {
1435                                var selectedCaret = caret(input);
1436                                if (selectedCaret.begin == selectedCaret.end) {
1437                                    var clickPosition = isRTL ? TranslatePosition(selectedCaret.begin) : selectedCaret.begin,
1438                                        lvp = getLastValidPosition(clickPosition),
1439                                        lastPosition = seekNext(lvp);
1440                                    if (clickPosition < lastPosition) {
1441                                        if (isMask(clickPosition))
1442                                            caret(input, clickPosition);
1443                                        else caret(input, seekNext(clickPosition));
1444                                    } else
1445                                        caret(input, lastPosition);
1446                                }
1447                            }, 0);
1448                        }
1449                    }).bind('dblclick.inputmask', function () {
1450                        var input = this;
1451                        setTimeout(function () {
1452                            caret(input, 0, seekNext(getLastValidPosition()));
1453                        }, 0);
1454                    }).bind(PasteEventType + ".inputmask dragdrop.inputmask drop.inputmask", pasteEvent
1455                    ).bind('setvalue.inputmask', function () {
1456                            var input = this;
1457                            checkVal(input, true);
1458                            valueOnFocus = getBuffer().join('');
1459                        }).bind('complete.inputmask', opts.oncomplete
1460                    ).bind('incomplete.inputmask', opts.onincomplete
1461                    ).bind('cleared.inputmask', opts.oncleared);
1462
1463                    $el.bind("keydown.inputmask", keydownEvent
1464                    ).bind("keypress.inputmask", keypressEvent
1465                    ).bind("keyup.inputmask", keyupEvent);
1466
1467                    if (android || androidfirefox || androidchrome || kindle) {
1468                        if (PasteEventType == "input") {
1469                            $el.unbind(PasteEventType + ".inputmask");
1470                        }
1471                        $el.bind("input.inputmask", mobileInputEvent);
1472                    }
1473
1474                    if (msie1x)
1475                        $el.bind("input.inputmask", pasteEvent);
1476
1477                    //apply mask
1478                    var initialValue = $.isFunction(opts.onBeforeMask) ? opts.onBeforeMask.call(el, el._valueGet(), opts) : el._valueGet();
1479                    checkVal(el, true, false, initialValue.split(''), true);
1480                    valueOnFocus = getBuffer().join('');
1481                    // Wrap document.activeElement in a try/catch block since IE9 throw "Unspecified error" if document.activeElement is undefined when we are in an IFrame.
1482                    var activeElement;
1483                    try {
1484                        activeElement = document.activeElement;
1485                    } catch (e) {
1486                    }
1487                    if (isComplete(getBuffer()) === false) {
1488                        if (opts.clearIncomplete)
1489                            resetMaskSet();
1490                    }
1491                    if (opts.clearMaskOnLostFocus) {
1492                        if (getBuffer().join('') == getBufferTemplate().join('')) {
1493                            el._valueSet('');
1494                        } else {
1495                            clearOptionalTail(el);
1496                        }
1497                    } else {
1498                        writeBuffer(el, getBuffer());
1499                    }
1500                    if (activeElement === el) { //position the caret when in focus
1501                        $el.addClass('focus-inputmask');
1502                        caret(el, seekNext(getLastValidPosition()));
1503                    }
1504
1505                    installEventRuler(el);
1506                }
1507            }
1508
1509            //action object
1510            if (actionObj != undefined) {
1511                switch (actionObj["action"]) {
1512                    case "isComplete":
1513                        $el = $(actionObj["el"]);
1514                        maskset = $el.data('_inputmask')['maskset'];
1515                        opts = $el.data('_inputmask')['opts'];
1516                        return isComplete(actionObj["buffer"]);
1517                    case "unmaskedvalue":
1518                        $el = actionObj["$input"];
1519                        maskset = $el.data('_inputmask')['maskset'];
1520                        opts = $el.data('_inputmask')['opts'];
1521                        isRTL = actionObj["$input"].data('_inputmask')['isRTL'];
1522                        return unmaskedvalue(actionObj["$input"]);
1523                    case "mask":
1524                        valueOnFocus = getBuffer().join('');
1525                        mask(actionObj["el"]);
1526                        break;
1527                    case "format":
1528                        $el = $({});
1529                        $el.data('_inputmask', {
1530                            'maskset': maskset,
1531                            'opts': opts,
1532                            'isRTL': opts.numericInput
1533                        });
1534                        if (opts.numericInput) {
1535                            isRTL = true;
1536                        }
1537                        var valueBuffer = actionObj["value"].split('');
1538                        checkVal($el, false, false, isRTL ? valueBuffer.reverse() : valueBuffer, true);
1539                        return isRTL ? getBuffer().reverse().join('') : getBuffer().join('');
1540                    case "isValid":
1541                        $el = $({});
1542                        $el.data('_inputmask', {
1543                            'maskset': maskset,
1544                            'opts': opts,
1545                            'isRTL': opts.numericInput
1546                        });
1547                        if (opts.numericInput) {
1548                            isRTL = true;
1549                        }
1550                        var valueBuffer = actionObj["value"].split('');
1551                        checkVal($el, false, true, isRTL ? valueBuffer.reverse() : valueBuffer);
1552                        var buffer = getBuffer();
1553                        var rl = determineLastRequiredPosition();
1554                        buffer.length = rl;
1555
1556                        return isComplete(buffer) && actionObj["value"] == buffer.join('');
1557                    case "getemptymask":
1558                        $el = $(actionObj["el"]);
1559                        maskset = $el.data('_inputmask')['maskset'];
1560                        opts = $el.data('_inputmask')['opts'];
1561                        return getBufferTemplate();
1562                    case "remove":
1563                        var el = actionObj["el"];
1564                        $el = $(el);
1565                        maskset = $el.data('_inputmask')['maskset'];
1566                        opts = $el.data('_inputmask')['opts'];
1567                        //writeout the unmaskedvalue
1568                        el._valueSet(unmaskedvalue($el));
1569                        //unbind all events
1570                        $el.unbind(".inputmask");
1571                        $el.removeClass('focus-inputmask');
1572                        //clear data
1573                        $el.removeData('_inputmask');
1574                        //restore the value property
1575                        var valueProperty;
1576                        if (Object.getOwnPropertyDescriptor)
1577                            valueProperty = Object.getOwnPropertyDescriptor(el, "value");
1578                        if (valueProperty && valueProperty.get) {
1579                            if (el._valueGet) {
1580                                Object.defineProperty(el, "value", {
1581                                    get: el._valueGet,
1582                                    set: el._valueSet
1583                                });
1584                            }
1585                        } else if (document.__lookupGetter__ && el.__lookupGetter__("value")) {
1586                            if (el._valueGet) {
1587                                el.__defineGetter__("value", el._valueGet);
1588                                el.__defineSetter__("value", el._valueSet);
1589                            }
1590                        }
1591                        try { //try catch needed for IE7 as it does not supports deleting fns
1592                            delete el._valueGet;
1593                            delete el._valueSet;
1594                        } catch (e) {
1595                            el._valueGet = undefined;
1596                            el._valueSet = undefined;
1597
1598                        }
1599                        break;
1600                }
1601            }
1602        };
1603
1604        $.inputmask = {
1605            //options default
1606            defaults: {
1607                placeholder: "_",
1608                optionalmarker: { start: "[", end: "]" },
1609                quantifiermarker: { start: "{", end: "}" },
1610                groupmarker: { start: "(", end: ")" },
1611                alternatormarker: "|",
1612                escapeChar: "\\",
1613                mask: null,
1614                oncomplete: $.noop, //executes when the mask is complete
1615                onincomplete: $.noop, //executes when the mask is incomplete and focus is lost
1616                oncleared: $.noop, //executes when the mask is cleared
1617                repeat: 0, //repetitions of the mask: * ~ forever, otherwise specify an integer
1618                greedy: true, //true: allocated buffer for the mask and repetitions - false: allocate only if needed
1619                autoUnmask: false, //automatically unmask when retrieving the value with $.fn.val or value if the browser supports __lookupGetter__ or getOwnPropertyDescriptor
1620                removeMaskOnSubmit: true, //remove the mask before submitting the form.  Use in combination with autoUnmask: true
1621                clearMaskOnLostFocus: true,
1622                insertMode: true, //insert the input or overwrite the input
1623                clearIncomplete: false, //clear the incomplete input on blur
1624                aliases: {}, //aliases definitions => see jquery.inputmask.extensions.js
1625                alias: null,
1626                onKeyUp: $.noop, //callback to implement autocomplete on certain keys for example
1627                onKeyPress: $.noop, //callback to implement autocomplete on certain keys for example
1628                onKeyDown: $.noop, //callback to implement autocomplete on certain keys for example
1629                onBeforeMask: undefined, //executes before masking the initial value to allow preprocessing of the initial value.  args => initialValue, opts => return processedValue
1630                onBeforePaste: undefined, //executes before masking the pasted value to allow preprocessing of the pasted value.  args => pastedValue, opts => return processedValue
1631                onUnMask: undefined, //executes after unmasking to allow postprocessing of the unmaskedvalue.  args => maskedValue, unmaskedValue, opts
1632                showMaskOnFocus: true, //show the mask-placeholder when the input has focus
1633                showMaskOnHover: true, //show the mask-placeholder when hovering the empty input
1634                onKeyValidation: $.noop, //executes on every key-press with the result of isValid. Params: result, opts
1635                skipOptionalPartCharacter: " ", //a character which can be used to skip an optional part of a mask
1636                showTooltip: false, //show the activemask as tooltip
1637                numericInput: false, //numericInput input direction style (input shifts to the left while holding the caret position)
1638                rightAlign: false, //align to the right
1639                //numeric basic properties
1640                radixPoint: "", //".", // | ","
1641                //numeric basic properties
1642                nojumps: false, //do not jump over fixed parts in the mask
1643                nojumpsThreshold: 0, //start nojumps as of
1644                definitions: {
1645                    '9': {
1646                        validator: "[0-9]",
1647                        cardinality: 1,
1648                        definitionSymbol: "*"
1649                    },
1650                    'a': {
1651                        validator: "[A-Za-z\u0410-\u044F\u0401\u0451]",
1652                        cardinality: 1,
1653                        definitionSymbol: "*"
1654                    },
1655                    '*': {
1656                        validator: "[A-Za-z\u0410-\u044F\u0401\u04510-9]",
1657                        cardinality: 1
1658                    }
1659                },
1660                keyCode: {
1661                    ALT: 18, BACKSPACE: 8, CAPS_LOCK: 20, COMMA: 188, COMMAND: 91, COMMAND_LEFT: 91, COMMAND_RIGHT: 93, CONTROL: 17, DELETE: 46, DOWN: 40, END: 35, ENTER: 13, ESCAPE: 27, HOME: 36, INSERT: 45, LEFT: 37, MENU: 93, NUMPAD_ADD: 107, NUMPAD_DECIMAL: 110, NUMPAD_DIVIDE: 111, NUMPAD_ENTER: 108,
1662                    NUMPAD_MULTIPLY: 106, NUMPAD_SUBTRACT: 109, PAGE_DOWN: 34, PAGE_UP: 33, PERIOD: 190, RIGHT: 39, SHIFT: 16, SPACE: 32, TAB: 9, UP: 38, WINDOWS: 91
1663                },
1664                //specify keycodes which should not be considered in the keypress event, otherwise the preventDefault will stop their default behavior especially in FF
1665                ignorables: [8, 9, 13, 19, 27, 33, 34, 35, 36, 37, 38, 39, 40, 45, 46, 93, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123],
1666                isComplete: undefined //override for isComplete - args => buffer, opts - return true || false
1667            },
1668            masksCache: {},
1669            escapeRegex: function (str) {
1670                var specials = ['/', '.', '*', '+', '?', '|', '(', ')', '[', ']', '{', '}', '\\'];
1671                return str.replace(new RegExp('(\\' + specials.join('|\\') + ')', 'gim'), '\\$1');
1672            },
1673            format: function (value, options) {
1674                var opts = $.extend(true, {}, $.inputmask.defaults, options);
1675                resolveAlias(opts.alias, options, opts);
1676                return maskScope({ "action": "format", "value": value }, generateMaskSet(opts), opts);
1677            },
1678            isValid: function (value, options) {
1679                var opts = $.extend(true, {}, $.inputmask.defaults, options);
1680                resolveAlias(opts.alias, options, opts);
1681                return maskScope({ "action": "isValid", "value": value }, generateMaskSet(opts), opts);
1682            }
1683        };
1684
1685        $.fn.inputmask = function (fn, options, targetScope, targetData, msk) {
1686            targetScope = targetScope || maskScope;
1687            targetData = targetData || "_inputmask";
1688            function importAttributeOptions(npt, opts) {
1689                var $npt = $(npt);
1690                for (var option in opts) {
1691                    var optionData = $npt.data("inputmask-" + option.toLowerCase());
1692                    if (optionData != undefined)
1693                        opts[option] = optionData;
1694                }
1695                return opts;
1696            }
1697            var opts = $.extend(true, {}, $.inputmask.defaults, options),
1698                maskset;
1699
1700            if (typeof fn === "string") {
1701                switch (fn) {
1702                    case "mask":
1703                        //resolve possible aliases given by options
1704                        resolveAlias(opts.alias, options, opts);
1705                        maskset = generateMaskSet(opts, targetScope !== maskScope);
1706                        if (maskset.length == 0) { return this; }
1707
1708                        return this.each(function () {
1709                            targetScope({ "action": "mask", "el": this }, $.extend(true, {}, maskset), importAttributeOptions(this, opts));
1710                        });
1711                    case "unmaskedvalue":
1712                        var $input = $(this);
1713                        if ($input.data(targetData)) {
1714                            return targetScope({ "action": "unmaskedvalue", "$input": $input });
1715                        } else return $input.val();
1716                    case "remove":
1717                        return this.each(function () {
1718                            var $input = $(this);
1719                            if ($input.data(targetData)) {
1720                                targetScope({ "action": "remove", "el": this });
1721                            }
1722                        });
1723                    case "getemptymask": //return the default (empty) mask value, usefull for setting the default value in validation
1724                        if (this.data(targetData)) {
1725                            return targetScope({ "action": "getemptymask", "el": this });
1726                        }
1727                        else return "";
1728                    case "hasMaskedValue": //check wheter the returned value is masked or not;
1728 currently only works reliable when using jquery.val fn to retrieve the value 
1729                        return this.data(targetData) ? !this.data(targetData)['opts'].autoUnmask : false;
1730                    case "isComplete":
1731                        if (this.data(targetData)) {
1732                            return targetScope({ "action": "isComplete", "buffer": this[0]._valueGet().split(''), "el": this });
1733                        } else return true;
1734                    case "getmetadata": //return mask metadata if exists
1735                        if (this.data(targetData)) {
1736                            maskset = this.data(targetData)['maskset'];
1737                            return maskset['metadata'];
1738                        }
1739                        else return undefined;
1740                    case "_detectScope":
1741                        resolveAlias(opts.alias, options, opts);
1742                        if (msk != undefined && !resolveAlias(msk, options, opts) && $.inArray(msk, ["mask", "unmaskedvalue", "remove", "getemptymask", "hasMaskedValue", "isComplete", "getmetadata", "_detectScope"]) == -1) {
1743                            opts.mask = msk;
1744                        }
1745                        if ($.isFunction(opts.mask)) {
1746                            opts.mask = opts.mask.call(this, opts);
1747                        }
1748                        return $.isArray(opts.mask);
1749                    default:
1750                        resolveAlias(opts.alias, options, opts);
1751                        //check if the fn is an alias
1752                        if (!resolveAlias(fn, options, opts)) {
1753                            //maybe fn is a mask so we try
1754                            //set mask
1755                            opts.mask = fn;
1756                        }
1757                        maskset = generateMaskSet(opts, targetScope !== maskScope);
1758                        if (maskset == undefined) { return this; }
1759                        return this.each(function () {
1760                            targetScope({ "action": "mask", "el": this }, $.extend(true, {}, maskset), importAttributeOptions(this, opts));
1761                        });
1762                }
1763            } else if (typeof fn == "object") {
1764                opts = $.extend(true, {}, $.inputmask.defaults, fn);
1765
1766                resolveAlias(opts.alias, fn, opts); //resolve aliases
1767                maskset = generateMaskSet(opts, targetScope !== maskScope);
1768                if (maskset == undefined) { return this; }
1769                return this.each(function () {
1770                    targetScope({ "action": "mask", "el": this }, $.extend(true, {}, maskset), importAttributeOptions(this, opts));
1771                });
1772            } else if (fn == undefined) {
1773                //look for data-inputmask atribute - the attribute should only contain optipns
1774                return this.each(function () {
1775                    var attrOptions = $(this).attr("data-inputmask");
1776                    if (attrOptions && attrOptions != "") {
1777                        try {
1778                            attrOptions = attrOptions.replace(new RegExp("'", "g"), '"');
1779                            var dataoptions = $.parseJSON("{" + attrOptions + "}");
1780                            $.extend(true, dataoptions, options);
1781                            opts = $.extend(true, {}, $.inputmask.defaults, dataoptions);
1782                            resolveAlias(opts.alias, dataoptions, opts);
1783                            opts.alias = undefined;
1784                            $(this).inputmask("mask", opts, targetScope);
1785                        } catch (ex) { } //need a more relax parseJSON
1786                    }
1787                });
1788            }
1789        };
1790    }
1791})(jQuery);

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.