jquery.inputmask.min.js 40 KB

1
  1. (function($){if($.fn.inputmask===undefined){$.inputmask={defaults:{placeholder:"_",optionalmarker:{start:"[",end:"]"},quantifiermarker:{start:"{",end:"}"},groupmarker:{start:"(",end:")"},escapeChar:"\\",mask:null,oncomplete:$.noop,onincomplete:$.noop,oncleared:$.noop,repeat:0,greedy:true,autoUnmask:false,clearMaskOnLostFocus:true,insertMode:true,clearIncomplete:false,aliases:{},onKeyUp:$.noop,onKeyDown:$.noop,showMaskOnFocus:true,showMaskOnHover:true,onKeyValidation:$.noop,skipOptionalPartCharacter:" ",showTooltip:false,numericInput:false,isNumeric:false,radixPoint:"",skipRadixDance:false,rightAlignNumerics:true,definitions:{9:{validator:"[0-9]",cardinality:1},"a":{validator:"[A-Za-z\u0410-\u044f\u0401\u0451]",cardinality:1},"*":{validator:"[A-Za-z\u0410-\u044f\u0401\u04510-9]",cardinality:1}},keyCode:{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,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},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],getMaskLength:function(buffer,greedy,repeat,currentBuffer,opts){var calculatedLength=buffer.length;if(!greedy)if(repeat=="*")calculatedLength=currentBuffer.length+1;else if(repeat>1)calculatedLength+=buffer.length*(repeat-1);return calculatedLength}},escapeRegex:function(str){var specials=["/",".","*","+","?","|","(",")","[","]","{","}","\\"];return str.replace(new RegExp("(\\"+specials.join("|\\")+")","gim"),"\\$1")}};$.fn.inputmask=function(fn,options){var opts=$.extend(true,{},$.inputmask.defaults,options),msie10=false,iphone=navigator.userAgent.match(new RegExp("iphone","i"))!==null,android=navigator.userAgent.match(new RegExp("android.*safari.*","i"))!==null,pasteEvent=isInputEventSupported("paste")&&!msie10?"paste":isInputEventSupported("input")?"input":"propertychange",android53x,masksets,activeMasksetIndex=0;if(android){var browser=navigator.userAgent.match(/safari.*/i),version=parseInt((new RegExp(/[0-9]+/)).exec(browser));android53x=version<=537}if(typeof fn==="string")switch(fn){case"mask":resolveAlias(opts.alias,options);masksets=generateMaskSets();return this.each(function(){maskScope($.extend(true,{},masksets),0).mask(this)});case"unmaskedvalue":var $input=$(this),input=this;if($input.data("_inputmask")){masksets=$input.data("_inputmask")["masksets"];activeMasksetIndex=$input.data("_inputmask")["activeMasksetIndex"];opts=$input.data("_inputmask")["opts"];return maskScope(masksets,activeMasksetIndex).unmaskedvalue($input)}else return $input.val();case"remove":return this.each(function(){var $input=$(this),input=this;if($input.data("_inputmask")){masksets=$input.data("_inputmask")["masksets"];activeMasksetIndex=$input.data("_inputmask")["activeMasksetIndex"];opts=$input.data("_inputmask")["opts"];input._valueSet(maskScope(masksets,activeMasksetIndex).unmaskedvalue($input,true));$input.removeData("_inputmask");$input.unbind(".inputmask");$input.removeClass("focus.inputmask");var valueProperty;if(Object.getOwnPropertyDescriptor)valueProperty=Object.getOwnPropertyDescriptor(input,"value");if(valueProperty&&valueProperty.get){if(input._valueGet)Object.defineProperty(input,"value",{get:input._valueGet,set:input._valueSet})}else if(document.__lookupGetter__&&input.__lookupGetter__("value"))if(input._valueGet){input.__defineGetter__("value",input._valueGet);input.__defineSetter__("value",input._valueSet)}try{delete input._valueGet;delete input._valueSet}catch(e){input._valueGet=undefined;input._valueSet=undefined}}});break;case"getemptymask":if(this.data("_inputmask")){masksets=this.data("_inputmask")["masksets"];activeMasksetIndex=this.data("_inputmask")["activeMasksetIndex"];return masksets[activeMasksetIndex]["_buffer"].join("")}else return"";case"hasMaskedValue":return this.data("_inputmask")?!this.data("_inputmask")["opts"].autoUnmask:false;case"isComplete":masksets=this.data("_inputmask")["masksets"];activeMasksetIndex=this.data("_inputmask")["activeMasksetIndex"];opts=this.data("_inputmask")["opts"];return maskScope(masksets,activeMasksetIndex).isComplete(this[0]._valueGet().split(""));case"getmetadata":if(this.data("_inputmask")){masksets=this.data("_inputmask")["masksets"];activeMasksetIndex=this.data("_inputmask")["activeMasksetIndex"];return masksets[activeMasksetIndex]["metadata"]}else return undefined;default:if(!resolveAlias(fn,options))opts.mask=fn;masksets=generateMaskSets();return this.each(function(){maskScope($.extend(true,{},masksets),activeMasksetIndex).mask(this)});break}else if(typeof fn=="object"){opts=$.extend(true,{},$.inputmask.defaults,fn);resolveAlias(opts.alias,fn);masksets=generateMaskSets();return this.each(function(){maskScope($.extend(true,{},masksets),activeMasksetIndex).mask(this)})}else if(fn==undefined)return this.each(function(){var attrOptions=$(this).attr("data-inputmask");if(attrOptions&&attrOptions!="")try{attrOptions=attrOptions.replace(new RegExp("'","g"),'"');var dataoptions=$.parseJSON("{"+attrOptions+"}");$.extend(true,dataoptions,options);opts=$.extend(true,{},$.inputmask.defaults,dataoptions);resolveAlias(opts.alias,dataoptions);opts.alias=undefined;$(this).inputmask(opts)}catch(ex){}});function isInputEventSupported(eventName){var el=document.createElement("input"),eventName="on"+eventName,isSupported=eventName in el;if(!isSupported){el.setAttribute(eventName,"return;");isSupported=typeof el[eventName]=="function"}el=null;return isSupported}function resolveAlias(aliasStr,options){var aliasDefinition=opts.aliases[aliasStr];if(aliasDefinition){if(aliasDefinition.alias)resolveAlias(aliasDefinition.alias);$.extend(true,opts,aliasDefinition);$.extend(true,opts,options);return true}return false}function getMaskTemplate(mask){if(opts.numericInput)mask=mask.split("").reverse().join("");var escaped=false,outCount=0,greedy=opts.greedy,repeat=opts.repeat;if(repeat=="*")greedy=false;if(greedy==true&&opts.placeholder=="")opts.placeholder=" ";if(mask.length==1&&greedy==false)opts.placeholder="";var singleMask=$.map(mask.split(""),function(element,index){var outElem=[];if(element==opts.escapeChar)escaped=true;else if(element!=opts.optionalmarker.start&&element!=opts.optionalmarker.end||escaped){var maskdef=opts.definitions[element];if(maskdef&&!escaped)for(var i=0;i<maskdef.cardinality;i++)outElem.push(getPlaceHolder(outCount+i));else{outElem.push(element);escaped=false}outCount+=outElem.length;return outElem}});var repeatedMask=singleMask.slice();for(var i=1;i<repeat&&greedy;i++)repeatedMask=repeatedMask.concat(singleMask.slice());return{"mask":repeatedMask,"repeat":repeat,"greedy":greedy}}function getTestingChain(mask){if(opts.numericInput)mask=mask.split("").reverse().join("");var isOptional=false,escaped=false;var newBlockMarker=false;return $.map(mask.split(""),function(element,index){var outElem=[];if(element==opts.escapeChar)escaped=true;else if(element==opts.optionalmarker.start&&!escaped){isOptional=true;newBlockMarker=true}else if(element==opts.optionalmarker.end&&!escaped){isOptional=false;newBlockMarker=true}else{var maskdef=opts.definitions[element];if(maskdef&&!escaped){var prevalidators=maskdef["prevalidator"],prevalidatorsL=prevalidators?prevalidators.length:0;for(var i=1;i<maskdef.cardinality;i++){var prevalidator=prevalidatorsL>=i?prevalidators[i-1]:[],validator=prevalidator["validator"],cardinality=prevalidator["cardinality"];outElem.push({fn:validator?typeof validator=="string"?new RegExp(validator):new function(){this.test=validator}:new RegExp("."),cardinality:cardinality?cardinality:1,optionality:isOptional,newBlockMarker:isOptional==true?newBlockMarker:false,offset:0,casing:maskdef["casing"],def:maskdef["definitionSymbol"]||element});if(isOptional==true)newBlockMarker=false}outElem.push({fn:maskdef.validator?typeof maskdef.validator=="string"?new RegExp(maskdef.validator):new function(){this.test=maskdef.validator}:new RegExp("."),cardinality:maskdef.cardinality,optionality:isOptional,newBlockMarker:newBlockMarker,offset:0,casing:maskdef["casing"],def:maskdef["definitionSymbol"]||element})}else{outElem.push({fn:null,cardinality:0,optionality:isOptional,newBlockMarker:newBlockMarker,offset:0,casing:null,def:element});escaped=false}newBlockMarker=false;return outElem}})}function generateMaskSets(){var ms=[];var genmasks=[];var maskTokens=[];function analyseMask(mask){var tokenizer=/(?:[?*+]|\{[0-9]+(?:,[0-9]*)?\})\??|[^.?*+^${[]()|\\]+|./g;function maskToken(){this.matches=[];this.isGroup=false;this.isOptional=false;this.isQuantifier=false}var currentToken=new maskToken,match,m,openenings=[];maskTokens=[];while(match=tokenizer.exec(mask)){m=match[0];switch(m.charAt(0)){case opts.optionalmarker.end:case opts.groupmarker.end:var openingToken=openenings.pop();if(openenings.length>0)openenings[openenings.length-1]["matches"].push(openingToken);else{maskTokens.push(openingToken);currentToken=new maskToken}break;case opts.optionalmarker.start:if(!currentToken.isGroup&&currentToken.matches.length>0)maskTokens.push(currentToken);currentToken=new maskToken;currentToken.isOptional=true;openenings.push(currentToken);break;case opts.groupmarker.start:if(!currentToken.isGroup&&currentToken.matches.length>0)maskTokens.push(currentToken);currentToken=new maskToken;currentToken.isGroup=true;openenings.push(currentToken);break;case opts.quantifiermarker.start:var quantifier=new maskToken;quantifier.isQuantifier=true;quantifier.matches.push(m);if(openenings.length>0)openenings[openenings.length-1]["matches"].push(quantifier);else currentToken.matches.push(quantifier);break;default:if(openenings.length>0)openenings[openenings.length-1]["matches"].push(m);else currentToken.matches.push(m)}}if(currentToken.matches.length>0)maskTokens.push(currentToken);return maskTokens}function markOptional(maskPart){return opts.optionalmarker.start+maskPart+opts.optionalmarker.end}function splitFirstOptionalEndPart(maskPart){var optionalStartMarkers=0,optionalEndMarkers=0,mpl=maskPart.length;for(i=0;i<mpl;i++){if(maskPart.charAt(i)==opts.optionalmarker.start)optionalStartMarkers++;if(maskPart.charAt(i)==opts.optionalmarker.end)optionalEndMarkers++;if(optionalStartMarkers>0&&optionalStartMarkers==optionalEndMarkers)break}var maskParts=[maskPart.substring(0,i)];if(i<mpl)maskParts.push(maskPart.substring(i+1,mpl));return maskParts}function splitFirstOptionalStartPart(maskPart){var mpl=maskPart.length;for(i=0;i<mpl;i++)if(maskPart.charAt(i)==opts.optionalmarker.start)break;var maskParts=[maskPart.substring(0,i)];if(i<mpl)maskParts.push(maskPart.substring(i+1,mpl));return maskParts}function generateMask(maskPrefix,maskPart,metadata){var maskParts=splitFirstOptionalEndPart(maskPart);var newMask,maskTemplate;var masks=splitFirstOptionalStartPart(maskParts[0]);if(masks.length>1){newMask=maskPrefix+masks[0]+markOptional(masks[1])+(maskParts.length>1?maskParts[1]:"");if($.inArray(newMask,genmasks)==-1){genmasks.push(newMask);maskTemplate=getMaskTemplate(newMask);ms.push({"mask":newMask,"_buffer":maskTemplate["mask"],"buffer":maskTemplate["mask"].slice(),"tests":getTestingChain(newMask),"lastValidPosition":-1,"greedy":maskTemplate["greedy"],"repeat":maskTemplate["repeat"],"metadata":metadata})}newMask=maskPrefix+masks[0]+(maskParts.length>1?maskParts[1]:"");if($.inArray(newMask,genmasks)==-1){genmasks.push(newMask);maskTemplate=getMaskTemplate(newMask);ms.push({"mask":newMask,"_buffer":maskTemplate["mask"],"buffer":maskTemplate["mask"].slice(),"tests":getTestingChain(newMask),"lastValidPosition":-1,"greedy":maskTemplate["greedy"],"repeat":maskTemplate["repeat"],"metadata":metadata})}if(splitFirstOptionalStartPart(masks[1]).length>1)generateMask(maskPrefix+masks[0],masks[1]+maskParts[1],metadata);if(maskParts.length>1&&splitFirstOptionalStartPart(maskParts[1]).length>1){generateMask(maskPrefix+masks[0]+markOptional(masks[1]),maskParts[1],metadata);generateMask(maskPrefix+masks[0],maskParts[1],metadata)}}else{newMask=maskPrefix+maskParts;if($.inArray(newMask,genmasks)==-1){genmasks.push(newMask);maskTemplate=getMaskTemplate(newMask);ms.push({"mask":newMask,"_buffer":maskTemplate["mask"],"buffer":maskTemplate["mask"].slice(),"tests":getTestingChain(newMask),"lastValidPosition":-1,"greedy":maskTemplate["greedy"],"repeat":maskTemplate["repeat"],"metadata":metadata})}}}if($.isFunction(opts.mask))opts.mask=opts.mask.call(this,opts);if($.isArray(opts.mask))$.each(opts.mask,function(ndx,msk){if(msk["mask"]!=undefined)generateMask("",msk["mask"].toString(),msk);else generateMask("",msk.toString())});else generateMask("",opts.mask.toString());return opts.greedy?ms:ms.sort(function(a,b){return a["mask"].length-b["mask"].length})}function getPlaceHolder(pos){return opts.placeholder.charAt(pos%opts.placeholder.length)}function maskScope(masksets,activeMasksetIndex){var isRTL=false,valueOnFocus=getActiveBuffer().join("");function getActiveMaskSet(){return masksets[activeMasksetIndex]}function getActiveTests(){return getActiveMaskSet()["tests"]}function getActiveBufferTemplate(){return getActiveMaskSet()["_buffer"]}function getActiveBuffer(){return getActiveMaskSet()["buffer"]}function isValid(pos,c,strict){strict=strict===true;function _isValid(position,activeMaskset,c,strict){var testPos=determineTestPosition(position),loopend=c?1:0,chrs="",buffer=activeMaskset["buffer"];for(var i=activeMaskset["tests"][testPos].cardinality;i>loopend;i--)chrs+=getBufferElement(buffer,testPos-(i-1));if(c)chrs+=c;return activeMaskset["tests"][testPos].fn!=null?activeMaskset["tests"][testPos].fn.test(chrs,buffer,position,strict,opts):c==getBufferElement(getActiveBufferTemplate(),position,true)||c==opts.skipOptionalPartCharacter?{"refresh":true,c:getBufferElement(getActiveBufferTemplate(),position,true),pos:position}:false}function PostProcessResults(maskForwards,results){var hasValidActual=false;$.each(results,function(ndx,rslt){hasValidActual=$.inArray(rslt["activeMasksetIndex"],maskForwards)==-1&&rslt["result"]!==false;if(hasValidActual)return false});if(hasValidActual)results=$.map(results,function(rslt,ndx){if($.inArray(rslt["activeMasksetIndex"],maskForwards)==-1)return rslt;else masksets[rslt["activeMasksetIndex"]]["lastValidPosition"]=actualLVP});else{var lowestPos=-1;$.each(results,function(ndx,rslt){if($.inArray(rslt["activeMasksetIndex"],maskForwards)!=-1&&(lowestPos==-1||lowestPos>rslt["result"]["pos"]))lowestPos=rslt["result"]["pos"]});results=$.map(results,function(rslt,ndx){if($.inArray(rslt["activeMasksetIndex"],maskForwards)==-1||rslt["result"]["pos"]==lowestPos)return rslt;else masksets[rslt["activeMasksetIndex"]]["lastValidPosition"]=actualLVP})}return results}if(strict){var result=_isValid(pos,getActiveMaskSet(),c,strict);if(result===true)result={"pos":pos};return result}var results=[],result=false,currentActiveMasksetIndex=activeMasksetIndex,actualBuffer=getActiveBuffer().slice(),actualLVP=getActiveMaskSet()["lastValidPosition"],actualPrevious=seekPrevious(pos),maskForwards=[];$.each(masksets,function(index,value){if(typeof value=="object"){activeMasksetIndex=index;var maskPos=pos;var lvp=getActiveMaskSet()["lastValidPosition"],rsltValid;if(lvp==actualLVP&&maskPos-actualLVP>1)for(var i=lvp==-1?0:lvp;i<maskPos;i++){rsltValid=_isValid(i,getActiveMaskSet(),actualBuffer[i],true);if(rsltValid===false)break;else{setBufferElement(getActiveBuffer(),i,actualBuffer[i],true);if(rsltValid===true)rsltValid={"pos":i};var newValidPosition=rsltValid.pos||i;if(getActiveMaskSet()["lastValidPosition"]<newValidPosition)getActiveMaskSet()["lastValidPosition"]=newValidPosition}}if(!isMask(maskPos)&&!_isValid(maskPos,getActiveMaskSet(),c,strict)){maskPos=seekNext(pos);maskForwards.push(activeMasksetIndex)}if(getActiveMaskSet()["lastValidPosition"]>=actualLVP)if(maskPos>=0&&maskPos<getMaskLength()){result=_isValid(maskPos,getActiveMaskSet(),c,strict);if(result!==false){if(result===true)result={"pos":maskPos};var newValidPosition=result.pos||maskPos;if(getActiveMaskSet()["lastValidPosition"]<newValidPosition)getActiveMaskSet()["lastValidPosition"]=newValidPosition}results.push({"activeMasksetIndex":index,"result":result})}}});activeMasksetIndex=currentActiveMasksetIndex;return PostProcessResults(maskForwards,results)}function determineActiveMasksetIndex(){var currentMasksetIndex=activeMasksetIndex,highestValid={"activeMasksetIndex":0,"lastValidPosition":-1,"next":-1};$.each(masksets,function(index,value){if(typeof value=="object"){activeMasksetIndex=index;if(getActiveMaskSet()["lastValidPosition"]>highestValid["lastValidPosition"]){highestValid["activeMasksetIndex"]=index;highestValid["lastValidPosition"]=getActiveMaskSet()["lastValidPosition"];highestValid["next"]=seekNext(getActiveMaskSet()["lastValidPosition"])}else if(getActiveMaskSet()["lastValidPosition"]==highestValid["lastValidPosition"]&&(highestValid["next"]==-1||highestValid["next"]>seekNext(getActiveMaskSet()["lastValidPosition"]))){highestValid["activeMasksetIndex"]=index;highestValid["lastValidPosition"]=getActiveMaskSet()["lastValidPosition"];highestValid["next"]=seekNext(getActiveMaskSet()["lastValidPosition"])}}});activeMasksetIndex=highestValid["lastValidPosition"]!=-1&&masksets[currentMasksetIndex]["lastValidPosition"]==highestValid["lastValidPosition"]?currentMasksetIndex:highestValid["activeMasksetIndex"];if(currentMasksetIndex!=activeMasksetIndex){clearBuffer(getActiveBuffer(),seekNext(highestValid["lastValidPosition"]),getMaskLength());getActiveMaskSet()["writeOutBuffer"]=true}}function isMask(pos){var testPos=determineTestPosition(pos);var test=getActiveTests()[testPos];return test!=undefined?test.fn:false}function determineTestPosition(pos){return pos%getActiveTests().length}function getMaskLength(){return opts.getMaskLength(getActiveBufferTemplate(),getActiveMaskSet()["greedy"],getActiveMaskSet()["repeat"],getActiveBuffer(),opts)}function seekNext(pos){var maskL=getMaskLength();if(pos>=maskL)return maskL;var position=pos;while(++position<maskL&&!isMask(position));return position}function seekPrevious(pos){var position=pos;if(position<=0)return 0;while(--position>0&&!isMask(position));return position}function setBufferElement(buffer,position,element,autoPrepare){if(autoPrepare)position=prepareBuffer(buffer,position);var test=getActiveTests()[determineTestPosition(position)];var elem=element;if(elem!=undefined)switch(test.casing){case"upper":elem=element.toUpperCase();break;case"lower":elem=element.toLowerCase();break}buffer[position]=elem}function getBufferElement(buffer,position,autoPrepare){if(autoPrepare)position=prepareBuffer(buffer,position);return buffer[position]}function prepareBuffer(buffer,position){var j;while(buffer[position]==undefined&&buffer.length<getMaskLength()){j=0;while(getActiveBufferTemplate()[j]!==undefined)buffer.push(getActiveBufferTemplate()[j++])}return position}function writeBuffer(input,buffer,caretPos){input._valueSet(buffer.join(""));if(caretPos!=undefined)caret(input,caretPos)}function clearBuffer(buffer,start,end){for(var i=start,maskL=getMaskLength();i<end&&i<maskL;i++)setBufferElement(buffer,i,getBufferElement(getActiveBufferTemplate().slice(),i,true))}function setReTargetPlaceHolder(buffer,pos){var testPos=determineTestPosition(pos);setBufferElement(buffer,pos,getBufferElement(getActiveBufferTemplate(),testPos))}function checkVal(input,writeOut,strict,nptvl){var inputValue=nptvl!=undefined?nptvl.slice():truncateInput(input._valueGet()).split("");$.each(masksets,function(ndx,ms){if(typeof ms=="object"){ms["buffer"]=ms["_buffer"].slice();ms["lastValidPosition"]=-1;ms["p"]=0}});if(strict!==true)activeMasksetIndex=0;if(writeOut)input._valueSet("");var ml=getMaskLength();$.each(inputValue,function(ndx,charCode){var index=ndx,lvp=getActiveMaskSet()["lastValidPosition"],pos=getActiveMaskSet()["p"];pos=lvp==-1?index:pos;if(strict&&isMask(index)||(charCode!=getBufferElement(getActiveBufferTemplate().slice(),index,true)||isMask(index))&&$.inArray(charCode,getActiveBufferTemplate().slice(lvp+1,pos))==-1)$(input).trigger("_keypress",[true,charCode.charCodeAt(0),writeOut,strict,index])});if(strict===true)getActiveMaskSet()["lastValidPosition"]=seekPrevious(getActiveMaskSet()["p"])}function escapeRegex(str){return $.inputmask.escapeRegex.call(this,str)}function truncateInput(inputValue){return inputValue.replace(new RegExp("("+escapeRegex(getActiveBufferTemplate().join(""))+")*$"),"")}function clearOptionalTail(input){var buffer=getActiveBuffer(),tmpBuffer=buffer.slice(),testPos,pos;for(var pos=tmpBuffer.length-1;pos>=0;pos--){var testPos=determineTestPosition(pos);if(getActiveTests()[testPos].optionality)if(!isMask(pos)||!isValid(pos,buffer[pos],true))tmpBuffer.pop();else break;else break}writeBuffer(input,tmpBuffer)}this.unmaskedvalue=function($input,skipDatepickerCheck){isRTL=$input.data("_inputmask")["isRTL"];return unmaskedvalue($input,skipDatepickerCheck)};function unmaskedvalue($input,skipDatepickerCheck){if(getActiveTests()&&(skipDatepickerCheck===true||!$input.hasClass("hasDatepicker"))){var umValue=$.map(getActiveBuffer(),function(element,index){return isMask(index)&&isValid(index,element,true)?element:null});return(isRTL?umValue.reverse():umValue).join("")}else return $input[0]._valueGet()}function TranslatePosition(pos){if(isRTL&&typeof pos=="number"){var bffrLght=getActiveBuffer().length;pos=bffrLght-pos}return pos}function caret(input,begin,end){var npt=input.jquery&&input.length>0?input[0]:input,range;if(typeof begin=="number"){begin=TranslatePosition(begin);end=TranslatePosition(end);if(!$(input).is(":visible"))return;end=typeof end=="number"?end:begin;if(opts.insertMode==false&&begin==end)end++;if(npt.setSelectionRange){npt.selectionStart=begin;npt.selectionEnd=android?begin:end}else if(npt.createTextRange){range=npt.createTextRange();range.collapse(true);range.moveEnd("character",end);range.moveStart("character",begin);range.select()}}else{if(!$(input).is(":visible"))return{"begin":0,"end":0};if(npt.setSelectionRange){begin=npt.selectionStart;end=npt.selectionEnd}else if(document.selection&&document.selection.createRange){range=document.selection.createRange();begin=0-range.duplicate().moveStart("character",-1E5);end=begin+range.text.length}begin=TranslatePosition(begin);end=TranslatePosition(end);return{"begin":begin,"end":end}}}this.isComplete=function(buffer){return isComplete(buffer)};function isComplete(buffer){var complete=false,highestValidPosition=0,currentActiveMasksetIndex=activeMasksetIndex;$.each(masksets,function(ndx,ms){if(typeof ms=="object"){activeMasksetIndex=ndx;var aml=seekPrevious(getMaskLength());if(ms["lastValidPosition"]>=highestValidPosition&&ms["lastValidPosition"]==aml){var msComplete=true;for(var i=0;i<=aml;i++){var mask=isMask(i),testPos=determineTestPosition(i);if(mask&&(buffer[i]==undefined||buffer[i]==getPlaceHolder(i))||!mask&&buffer[i]!=getActiveBufferTemplate()[testPos]){msComplete=false;break}}complete=complete||msComplete;if(complete)return false}highestValidPosition=ms["lastValidPosition"]}});activeMasksetIndex=currentActiveMasksetIndex;return complete}function isSelection(begin,end){return isRTL?begin-end>1||begin-end==1&&opts.insertMode:end-begin>1||end-begin==1&&opts.insertMode}this.mask=function(el){var $input=$(el);if(!$input.is(":input"))return;$input.data("_inputmask",{"masksets":masksets,"activeMasksetIndex":activeMasksetIndex,"opts":opts,"isRTL":false});if(opts.showTooltip)$input.prop("title",getActiveMaskSet()["mask"]);getActiveMaskSet()["greedy"]=getActiveMaskSet()["greedy"]?getActiveMaskSet()["greedy"]:getActiveMaskSet()["repeat"]==0;if($input.attr("maxLength")!=null){var maxLength=$input.prop("maxLength");if(maxLength>-1)$.each(masksets,function(ndx,ms){if(typeof ms=="object")if(ms["repeat"]=="*")ms["repeat"]=maxLength});if(getMaskLength()>maxLength&&maxLength>-1){if(maxLength<getActiveBufferTemplate().length)getActiveBufferTemplate().length=maxLength;if(getActiveMaskSet()["greedy"]==false)getActiveMaskSet()["repeat"]=Math.round(maxLength/getActiveBufferTemplate().length);$input.prop("maxLength",getMaskLength()*2)}}patchValueProperty(el);var skipKeyPressEvent=false,ignorable=false;if(opts.numericInput)opts.isNumeric=opts.numericInput;if(el.dir=="rtl"||(opts.numericInput&&opts.rightAlignNumerics||opts.isNumeric&&opts.rightAlignNumerics))$input.css("text-align","right");if(el.dir=="rtl"||opts.numericInput){el.dir="ltr";$input.removeAttr("dir");var inputData=$input.data("_inputmask");inputData["isRTL"]=true;$input.data("_inputmask",inputData);isRTL=true}$input.unbind(".inputmask");$input.removeClass("focus.inputmask");$input.closest("form").bind("submit",function(){if(valueOnFocus!=getActiveBuffer().join(""))$input.change()}).bind("reset",function(){$.each(masksets,function(ndx,ms){if(typeof ms=="object"){ms["buffer"]=ms["_buffer"].slice();ms["lastValidPosition"]=-1;ms["p"]=-1}})});$input.bind("mouseenter.inputmask",function(){var $input=$(this),input=this;if(!$input.hasClass("focus.inputmask")&&opts.showMaskOnHover)if(input._valueGet()!=getActiveBuffer().join(""))writeBuffer(input,getActiveBuffer())}).bind("blur.inputmask",function(){var $input=$(this),input=this,nptValue=input._valueGet(),buffer=getActiveBuffer();$input.removeClass("focus.inputmask");if(valueOnFocus!=getActiveBuffer().join(""))$input.change();if(opts.clearMaskOnLostFocus&&nptValue!="")if(nptValue==getActiveBufferTemplate().join(""))input._valueSet("");else clearOptionalTail(input);if(!isComplete(buffer)){$input.trigger("incomplete");if(opts.clearIncomplete){$.each(masksets,function(ndx,ms){if(typeof ms=="object"){ms["buffer"]=ms["_buffer"].slice();ms["lastValidPosition"]=-1;ms["p"]=0}});activeMasksetIndex=0;if(opts.clearMaskOnLostFocus)input._valueSet("");else{buffer=getActiveBufferTemplate().slice();writeBuffer(input,buffer)}}}}).bind("focus.inputmask",function(){var $input=$(this),input=this,nptValue=input._valueGet();if(opts.showMaskOnFocus&&(!$input.hasClass("focus.inputmask")&&(!opts.showMaskOnHover||opts.showMaskOnHover&&nptValue=="")))if(input._valueGet()!=getActiveBuffer().join(""))writeBuffer(input,getActiveBuffer(),getActiveMaskSet()["p"]);$input.addClass("focus.inputmask");valueOnFocus=getActiveBuffer().join("")}).bind("mouseleave.inputmask",function(){var $input=$(this),input=this;if(opts.clearMaskOnLostFocus)if(!$input.hasClass("focus.inputmask"))if(input._valueGet()==getActiveBufferTemplate().join("")||input._valueGet()=="")input._valueSet("");else clearOptionalTail(input)}).bind("click.inputmask",function(){var input=this;setTimeout(function(){var selectedCaret=caret(input),buffer=getActiveBuffer();if(selectedCaret.begin==selectedCaret.end){var clickPosition=opts.isRTL?TranslatePosition(selectedCaret.begin):selectedCaret.begin,lvp=getActiveMaskSet()["lastValidPosition"],lastPosition;if(opts.isNumeric)lastPosition=opts.skipRadixDance===false&&(opts.radixPoint!=""&&$.inArray(opts.radixPoint,buffer)!=-1)?opts.numericInput?seekNext($.inArray(opts.radixPoint,buffer)):$.inArray(opts.radixPoint,buffer):seekNext(lvp);else lastPosition=seekNext(lvp);if(clickPosition<lastPosition)if(isMask(clickPosition))caret(input,clickPosition);else caret(input,seekNext(clickPosition));else caret(input,lastPosition)}},0)}).bind("dblclick.inputmask",function(){var input=this;setTimeout(function(){caret(input,0,seekNext(getActiveMaskSet()["lastValidPosition"]))},0)}).bind("keydown.inputmask",keydownEvent).bind("keypress.inputmask",keypressEvent).bind("keyup.inputmask",keyupEvent).bind(pasteEvent+".inputmask dragdrop.inputmask drop.inputmask",function(e){var input=this,$input=$(input);if(e.type=="propertychange"&&input._valueGet().length<=getMaskLength())return true;setTimeout(function(){checkVal(input,true,false);if(isComplete(getActiveBuffer()))$input.trigger("complete");$input.click()},0)}).bind("setvalue.inputmask",function(){var input=this;checkVal(input,true);valueOnFocus=getActiveBuffer().join("");if(input._valueGet()==getActiveBufferTemplate().join(""))input._valueSet("")}).bind("_keypress.inputmask",keypressEvent).bind("complete.inputmask",opts.oncomplete).bind("incomplete.inputmask",opts.onincomplete).bind("cleared.inputmask",opts.oncleared);checkVal(el,true,false);valueOnFocus=getActiveBuffer().join("");var activeElement;try{activeElement=document.activeElement}catch(e){}if(activeElement===el){$input.addClass("focus.inputmask");caret(el,getActiveMaskSet()["p"])}else if(opts.clearMaskOnLostFocus)if(getActiveBuffer().join("")==getActiveBufferTemplate().join(""))el._valueSet("");else clearOptionalTail(el);else writeBuffer(el,getActiveBuffer());installEventRuler(el);function installEventRuler(npt){var events=$._data(npt).events;$.each(events,function(eventType,eventHandlers){$.each(eventHandlers,function(ndx,eventHandler){if(eventHandler.namespace=="inputmask")if(eventHandler.type!="setvalue"&&eventHandler.type!="_keypress"){var handler=eventHandler.handler;eventHandler.handler=function(e){if(this.readOnly||this.disabled)e.preventDefault;else return handler.apply(this,arguments)}}})})}function patchValueProperty(npt){var valueProperty;if(Object.getOwnPropertyDescriptor)valueProperty=Object.getOwnPropertyDescriptor(npt,"value");if(valueProperty&&valueProperty.get){if(!npt._valueGet){var valueGet=valueProperty.get;var valueSet=valueProperty.set;npt._valueGet=function(){return isRTL?valueGet.call(this).split("").reverse().join(""):valueGet.call(this)};npt._valueSet=function(value){valueSet.call(this,isRTL?value.split("").reverse().join(""):value)};Object.defineProperty(npt,"value",{get:function(){var $self=$(this),inputData=$(this).data("_inputmask"),masksets=inputData["masksets"],activeMasksetIndex=inputData["activeMasksetIndex"];return inputData&&inputData["opts"].autoUnmask?$self.inputmask("unmaskedvalue"):valueGet.call(this)!=masksets[activeMasksetIndex]["_buffer"].join("")?valueGet.call(this):""},set:function(value){valueSet.call(this,value);$(this).triggerHandler("setvalue.inputmask")}})}}else if(document.__lookupGetter__&&npt.__lookupGetter__("value")){if(!npt._valueGet){var valueGet=npt.__lookupGetter__("value");var valueSet=npt.__lookupSetter__("value");npt._valueGet=function(){return isRTL?valueGet.call(this).split("").reverse().join(""):valueGet.call(this)};npt._valueSet=function(value){valueSet.call(this,isRTL?value.split("").reverse().join(""):value)};npt.__defineGetter__("value",function(){var $self=$(this),inputData=$(this).data("_inputmask"),masksets=inputData["masksets"],activeMasksetIndex=inputData["activeMasksetIndex"];return inputData&&inputData["opts"].autoUnmask?$self.inputmask("unmaskedvalue"):valueGet.call(this)!=masksets[activeMasksetIndex]["_buffer"].join("")?valueGet.call(this):""});npt.__defineSetter__("value",function(value){valueSet.call(this,value);$(this).triggerHandler("setvalue.inputmask")})}}else{if(!npt._valueGet){npt._valueGet=function(){return isRTL?this.value.split("").reverse().join(""):this.value};npt._valueSet=function(value){this.value=isRTL?value.split("").reverse().join(""):value}}if($.valHooks.text==undefined||$.valHooks.text.inputmaskpatch!=true){var valueGet=$.valHooks.text&&$.valHooks.text.get?$.valHooks.text.get:function(){return this.value};var valueSet=$.valHooks.text&&$.valHooks.text.set?$.valHooks.text.set:function(value){return this.value=value};jQuery.extend($.valHooks,{text:{get:function(elem){var $elem=$(elem);if($elem.data("_inputmask"))if($elem.data("_inputmask")["opts"].autoUnmask)return $elem.inputmask("unmaskedvalue");else{var result=valueGet.call(elem),inputData=$elem.data("_inputmask"),masksets=inputData["masksets"],activeMasksetIndex=inputData["activeMasksetIndex"];return result!=masksets[activeMasksetIndex]["_buffer"].join("")?result:""}else return valueGet.call(elem)},set:function(elem,value){var $elem=$(elem);var result=valueSet.call(elem,value);if($elem.data("_inputmask"))$elem.triggerHandler("setvalue.inputmask");return result},inputmaskpatch:true}})}}}function shiftL(start,end,c){var buffer=getActiveBuffer();while(!isMask(start)&&start-1>=0)start--;for(var i=start;i<end&&i<getMaskLength();i++)if(isMask(i)){setReTargetPlaceHolder(buffer,i);var j=seekNext(i);var p=getBufferElement(buffer,j);if(p!=getPlaceHolder(j))if(j<getMaskLength()&&(isValid(i,p,true)!==false&&getActiveTests()[determineTestPosition(i)].def==getActiveTests()[determineTestPosition(j)].def)){setBufferElement(buffer,i,getBufferElement(buffer,j),true);if(j<end)setReTargetPlaceHolder(buffer,j)}else if(isMask(i))break}else setReTargetPlaceHolder(buffer,i);if(c!=undefined)setBufferElement(buffer,seekPrevious(end),c);if(getActiveMaskSet()["greedy"]==false){var trbuffer=truncateInput(buffer.join("")).split("");buffer.length=trbuffer.length;for(var i=0,bl=buffer.length;i<bl;i++)buffer[i]=trbuffer[i];if(buffer.length==0)getActiveMaskSet()["buffer"]=getActiveBufferTemplate().slice()}return start}function shiftR(start,end,c,full){var buffer=getActiveBuffer();for(var i=start;i<=end&&i<getMaskLength();i++)if(isMask(i)){var t=getBufferElement(buffer,i,true);setBufferElement(buffer,i,c,true);if(t!=getPlaceHolder(i)){var j=seekNext(i);if(j<getMaskLength())if(isValid(j,t,true)!==false&&getActiveTests()[determineTestPosition(i)].def==getActiveTests()[determineTestPosition(j)].def)c=t;else if(isMask(j))break;else c=t;else break}else{c=t;if(full!==true)break}}else setReTargetPlaceHolder(buffer,i);var lengthBefore=buffer.length;if(getActiveMaskSet()["greedy"]==false){var trbuffer=truncateInput(buffer.join("")).split("");buffer.length=trbuffer.length;for(var i=0,bl=buffer.length;i<bl;i++)buffer[i]=trbuffer[i];if(buffer.length==0)getActiveMaskSet()["buffer"]=getActiveBufferTemplate().slice()}return end-(lengthBefore-buffer.length)}function keydownEvent(e){skipKeyPressEvent=false;var input=this,k=e.keyCode,pos=caret(input);if(k==opts.keyCode.BACKSPACE||(k==opts.keyCode.DELETE||(iphone&&k==127||e.ctrlKey&&k==88))){e.preventDefault();if(opts.numericInput||isRTL)switch(k){case opts.keyCode.BACKSPACE:k=opts.keyCode.DELETE;break;case opts.keyCode.DELETE:k=opts.keyCode.BACKSPACE;break}if(isSelection(pos.begin,pos.end)){if(isRTL){var pend=pos.end;pos.end=pos.begin;pos.begin=pend}clearBuffer(getActiveBuffer(),pos.begin,pos.end);if(pos.begin==0&&pos.end==getMaskLength())$.each(masksets,function(ndx,ms){if(typeof ms=="object"){ms["buffer"]=ms["_buffer"].slice();ms["lastValidPosition"]=-1;ms["p"]=0}});else{var ml=getMaskLength();if(opts.greedy==false)shiftL(pos.begin,ml);else for(var i=pos.begin;i<pos.end;i++)if(isMask(i))shiftL(pos.begin,ml);checkVal(input,false,true,getActiveBuffer())}}else $.each(masksets,function(ndx,ms){if(typeof ms=="object"){activeMasksetIndex=ndx;var beginPos=android53x?pos.end:pos.begin;var buffer=getActiveBuffer(),firstMaskPos=seekNext(-1),maskL=getMaskLength();if(k==opts.keyCode.BACKSPACE)beginPos--;if(beginPos<firstMaskPos)beginPos=firstMaskPos;if(beginPos<maskL){if(opts.isNumeric&&(opts.radixPoint!=""&&buffer[beginPos]==opts.radixPoint)){beginPos=buffer.length-1==beginPos?beginPos:seekNext(beginPos);beginPos=shiftL(beginPos,maskL)}else beginPos=shiftL(beginPos,maskL);if(getActiveMaskSet()["lastValidPosition"]!=-1&&getActiveBuffer()[getActiveMaskSet()["lastValidPosition"]]==getActiveBufferTemplate()[getActiveMaskSet()["lastValidPosition"]])getActiveMaskSet()["lastValidPosition"]=getActiveMaskSet()["lastValidPosition"]==0?-1:seekPrevious(getActiveMaskSet()["lastValidPosition"]);if(getActiveMaskSet()["lastValidPosition"]<firstMaskPos){getActiveMaskSet()["lastValidPosition"]=-1;getActiveMaskSet()["p"]=firstMaskPos}else{getActiveMaskSet()["writeOutBuffer"]=true;getActiveMaskSet()["p"]=beginPos}}}});determineActiveMasksetIndex();writeBuffer(input,getActiveBuffer(),getActiveMaskSet()["p"]);if(input._valueGet()==getActiveBufferTemplate().join(""))$(input).trigger("cleared");if(opts.showTooltip)$input.prop("title",getActiveMaskSet()["mask"])}else if(k==opts.keyCode.END||k==opts.keyCode.PAGE_DOWN)setTimeout(function(){var caretPos=seekNext(getActiveMaskSet()["lastValidPosition"]);if(!opts.insertMode&&(caretPos==getMaskLength()&&!e.shiftKey))caretPos--;caret(input,e.shiftKey?pos.begin:caretPos,caretPos)},0);else if(k==opts.keyCode.HOME&&!e.shiftKey||k==opts.keyCode.PAGE_UP)caret(input,0,e.shiftKey?pos.begin:0);else if(k==opts.keyCode.ESCAPE)checkVal(input,true,true,valueOnFocus);else if(k==opts.keyCode.INSERT&&!(e.shiftKey||e.ctrlKey)){opts.insertMode=!opts.insertMode;caret(input,!opts.insertMode&&pos.begin==getMaskLength()?pos.begin-1:pos.begin)}else if(opts.insertMode==false&&!e.shiftKey)if(k==opts.keyCode.RIGHT)setTimeout(function(){var caretPos=caret(input);caret(input,caretPos.begin)},0);else if(k==opts.keyCode.LEFT)setTimeout(function(){var caretPos=caret(input);caret(input,caretPos.begin-1)},0);var caretPos=caret(input);opts.onKeyDown.call(this,e,getActiveBuffer(),opts);caret(input,caretPos.begin,caretPos.end);ignorable=$.inArray(k,opts.ignorables)!=-1}function keypressEvent(e,checkval,k,writeOut,strict,ndx){if(k==undefined&&skipKeyPressEvent)return false;skipKeyPressEvent=true;var input=this,$input=$(input);e=e||window.event;var k=k||(e.which||(e.charCode||e.keyCode));if(!(e.ctrlKey&&e.altKey)&&(e.ctrlKey||(e.metaKey||ignorable))&&checkval!==true)return true;else if(k){if(checkval!==true&&(k==46&&(e.shiftKey==false&&opts.radixPoint==",")))k=44;var pos,results,result,c=String.fromCharCode(k);if(checkval){var pcaret=strict?ndx:getActiveMaskSet()["lastValidPosition"]+1;pos={begin:pcaret,end:pcaret}}else pos=caret(input);var isSlctn=isSelection(pos.begin,pos.end),redetermineLVP=false,initialIndex=activeMasksetIndex;if(isSlctn){if(isRTL){var pend=pos.end;pos.end=pos.begin;pos.begin=pend}$.each(masksets,function(ndx,lmnt){if(typeof lmnt=="object"){activeMasksetIndex=ndx;getActiveMaskSet()["undoBuffer"]=getActiveBuffer().join("");var posend=pos.end<getMaskLength()?pos.end:getMaskLength();if(getActiveMaskSet()["lastValidPosition"]>pos.begin&&getActiveMaskSet()["lastValidPosition"]<posend)getActiveMaskSet()["lastValidPosition"]=seekPrevious(pos.begin);else redetermineLVP=true;clearBuffer(getActiveBuffer(),pos.begin,posend);var ml=getMaskLength();if(opts.greedy==false)shiftL(pos.begin,ml);else for(var i=pos.begin;i<posend;i++)if(isMask(i))shiftL(pos.begin,ml)}});if(redetermineLVP===true){activeMasksetIndex=initialIndex;checkVal(input,false,true,getActiveBuffer());if(!opts.insertMode)$.each(masksets,function(ndx,lmnt){if(typeof lmnt=="object"){activeMasksetIndex=ndx;shiftR(pos.begin,getMaskLength(),getPlaceHolder(pos.begin),true);getActiveMaskSet()["lastValidPosition"]=seekNext(getActiveMaskSet()["lastValidPosition"])}})}activeMasksetIndex=initialIndex}if(opts.isNumeric&&(c==opts.radixPoint&&checkval!==true)){var nptStr=getActiveBuffer().join("");var radixPosition=nptStr.indexOf(opts.radixPoint);if(radixPosition!=-1){pos.begin=pos.begin==radixPosition?seekNext(radixPosition):radixPosition;pos.end=pos.begin;caret(input,pos.begin)}}var p=pos.begin;results=isValid(p,c,strict);if(strict===true)results=[{"activeMasksetIndex":activeMasksetIndex,"result":results}];$.each(results,function(index,result){activeMasksetIndex=result["activeMasksetIndex"];getActiveMaskSet()["writeOutBuffer"]=true;var np=result["result"];if(np!==false){var refresh=false,buffer=getActiveBuffer();if(np!==true){refresh=np["refresh"];p=np.pos!=undefined?np.pos:p;c=np.c!=undefined?np.c:c}if(refresh!==true)if(opts.insertMode==true){var lastUnmaskedPosition=getMaskLength();var bfrClone=buffer.slice();while(getBufferElement(bfrClone,lastUnmaskedPosition,true)!=getPlaceHolder(lastUnmaskedPosition)&&lastUnmaskedPosition>=p)lastUnmaskedPosition=lastUnmaskedPosition==0?-1:seekPrevious(lastUnmaskedPosition);if(lastUnmaskedPosition>=p){shiftR(p,buffer.length,c);var lvp=getActiveMaskSet()["lastValidPosition"],nlvp=seekNext(lvp);if(nlvp!=getMaskLength()&&(lvp>=p&&getBufferElement(getActiveBuffer(),nlvp,true)!=getPlaceHolder(nlvp)))getActiveMaskSet()["lastValidPosition"]=nlvp}else getActiveMaskSet()["writeOutBuffer"]=false}else setBufferElement(buffer,p,c,true);getActiveMaskSet()["p"]=seekNext(p)}});if(strict!==true){activeMasksetIndex=initialIndex;determineActiveMasksetIndex()}if(writeOut!==false){$.each(results,function(ndx,rslt){if(rslt["activeMasksetIndex"]==activeMasksetIndex){result=rslt;return false}});if(result!=undefined){var self=this;setTimeout(function(){opts.onKeyValidation.call(self,result["result"],opts)},0);if(getActiveMaskSet()["writeOutBuffer"]&&result["result"]!==false){var buffer=getActiveBuffer();writeBuffer(input,buffer,checkval?undefined:opts.numericInput?seekPrevious(getActiveMaskSet()["p"]):getActiveMaskSet()["p"]);if(checkval!==true)setTimeout(function(){if(isComplete(buffer))$input.trigger("complete")},0)}else if(isSlctn)getActiveMaskSet()["buffer"]=getActiveMaskSet()["undoBuffer"].split("")}}if(opts.showTooltip)$input.prop("title",getActiveMaskSet()["mask"]);e.preventDefault()}}function keyupEvent(e){var $input=$(this),input=this,k=e.keyCode,buffer=getActiveBuffer();var caretPos=caret(input);opts.onKeyUp.call(this,e,buffer,opts);caret(input,caretPos.begin,caretPos.end);if(k==opts.keyCode.TAB&&($input.hasClass("focus.inputmask")&&(input._valueGet().length==0&&opts.showMaskOnFocus))){buffer=getActiveBufferTemplate().slice();writeBuffer(input,buffer);caret(input,0);valueOnFocus=getActiveBuffer().join("")}}};return this}return this}}})(jQuery);